hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
f407717572ec56488a9fe6da0a094d858395b36c
6,733
package cc.zip.charon.features.modules.combat; import cc.zip.charon.Charon; import cc.zip.charon.features.command.Command; import cc.zip.charon.features.modules.Module; import cc.zip.charon.features.setting.Setting; import cc.zip.charon.util.BlockUtil; import cc.zip.charon.util.EntityUtil; import cc.zip.charon.util.InventoryUtil; import cc.zip.charon.util.MathUtil; import cc.zip.charon.util.Timer; import com.mojang.realmsclient.gui.ChatFormatting; import java.util.ArrayList; import java.util.Comparator; import java.util.Iterator; import java.util.List; import net.minecraft.block.BlockWeb; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; public class AutoWeb extends Module { public static boolean isPlacing = false; private final Setting<Integer> delay = this.register(new Setting("Delay", 50, 0, 250)); private final Setting<Integer> blocksPerPlace = this.register(new Setting("BlocksPerTick", 8, 1, 30)); private final Setting<Boolean> packet = this.register(new Setting("PacketPlace", false)); private final Setting<Boolean> disable = this.register(new Setting("AutoDisable", false)); private final Setting<Boolean> rotate = this.register(new Setting("Rotate", true)); private final Setting<Boolean> raytrace = this.register(new Setting("Raytrace", false)); private final Setting<Boolean> lowerbody = this.register(new Setting("Feet", true)); private final Setting<Boolean> upperBody = this.register(new Setting("Face", false)); private final Timer timer = new Timer(); public EntityPlayer target; private boolean didPlace = false; private boolean switchedItem; private boolean isSneaking; private int lastHotbarSlot; private int placements = 0; private boolean smartRotate = false; private BlockPos startPos = null; public AutoWeb() { super("AutoWeb", "Traps other players in webs", Module.Category.COMBAT, true, false, false); } public void onEnable() { if (!fullNullCheck()) { this.startPos = EntityUtil.getRoundedBlockPos(mc.player); this.lastHotbarSlot = mc.player.inventory.currentItem; } } public void onTick() { this.smartRotate = false; this.doTrap(); } public String getDisplayInfo() { return this.target != null ? this.target.getName() : null; } public void onDisable() { isPlacing = false; this.isSneaking = EntityUtil.stopSneaking(this.isSneaking); this.switchItem(true); } private void doTrap() { if (!this.check()) { this.doWebTrap(); if (this.didPlace) { this.timer.reset(); } } } private void doWebTrap() { List<Vec3d> placeTargets = this.getPlacements(); this.placeList(placeTargets); } private List<Vec3d> getPlacements() { ArrayList<Vec3d> list = new ArrayList(); Vec3d baseVec = this.target.getPositionVector(); if ((Boolean)this.lowerbody.getValue()) { list.add(baseVec); } if ((Boolean)this.upperBody.getValue()) { list.add(baseVec.add(0.0D, 1.0D, 0.0D)); } return list; } private void placeList(List<Vec3d> list) { list.sort((vec3d, vec3d2) -> { return Double.compare(mc.player.getDistanceSq(vec3d2.x, vec3d2.y, vec3d2.z), mc.player.getDistanceSq(vec3d.x, vec3d.y, vec3d.z)); }); list.sort(Comparator.comparingDouble((vec3d) -> { return vec3d.y; })); Iterator var2 = list.iterator(); while(true) { BlockPos position; int placeability; do { if (!var2.hasNext()) { return; } Vec3d vec3d3 = (Vec3d)var2.next(); position = new BlockPos(vec3d3); placeability = BlockUtil.isPositionPlaceable(position, (Boolean)this.raytrace.getValue()); } while(placeability != 3 && placeability != 1); this.placeBlock(position); } } private boolean check() { isPlacing = false; this.didPlace = false; this.placements = 0; int obbySlot = InventoryUtil.findHotbarBlock(BlockWeb.class); if (this.isOff()) { return true; } else if ((Boolean)this.disable.getValue() && !this.startPos.equals(EntityUtil.getRoundedBlockPos(mc.player))) { this.disable(); return true; } else if (obbySlot == -1) { Command.sendMessage("<" + this.getDisplayName() + "> " + ChatFormatting.RED + "No Webs in hotbar disabling..."); this.toggle(); return true; } else { if (mc.player.inventory.currentItem != this.lastHotbarSlot && mc.player.inventory.currentItem != obbySlot) { this.lastHotbarSlot = mc.player.inventory.currentItem; } this.switchItem(true); this.isSneaking = EntityUtil.stopSneaking(this.isSneaking); this.target = this.getTarget(10.0D); return this.target == null || !this.timer.passedMs((long)(Integer)this.delay.getValue()); } } private EntityPlayer getTarget(double range) { EntityPlayer target = null; double distance = Math.pow(range, 2.0D) + 1.0D; Iterator var6 = mc.world.playerEntities.iterator(); while(var6.hasNext()) { EntityPlayer player = (EntityPlayer)var6.next(); if (!EntityUtil.isntValid(player, range) && !player.isInWeb && !(Charon.speedManager.getPlayerSpeed(player) > 30.0D)) { if (target == null) { target = player; distance = mc.player.getDistanceSq(player); } else if (mc.player.getDistanceSq(player) < distance) { target = player; distance = mc.player.getDistanceSq(player); } } } return target; } private void placeBlock(BlockPos pos) { if (this.placements < (Integer)this.blocksPerPlace.getValue() && mc.player.getDistanceSq(pos) <= MathUtil.square(6.0D) && this.switchItem(false)) { isPlacing = true; this.isSneaking = this.smartRotate ? BlockUtil.placeBlockSmartRotate(pos, EnumHand.MAIN_HAND, true, (Boolean)this.packet.getValue(), this.isSneaking) : BlockUtil.placeBlock(pos, EnumHand.MAIN_HAND, (Boolean)this.rotate.getValue(), (Boolean)this.packet.getValue(), this.isSneaking); this.didPlace = true; ++this.placements; } } private boolean switchItem(boolean back) { boolean[] value = InventoryUtil.switchItem(back, this.lastHotbarSlot, this.switchedItem, InventoryUtil.Switch.NORMAL, BlockWeb.class); this.switchedItem = value[0]; return value[1]; } }
36.005348
290
0.65231
06c5c61c90d7d441a70caa9580cbc8c9af157fcd
859
import java.util.Collections; import java.util.List; import java.util.function.Supplier; class Test { public static void bar(boolean f) { foo(() -> { if (f) <error descr="Missing return value">return;</error> if (false) <error descr="Missing return value">return;</error> if (!f) return <error descr="Bad return type in lambda expression: int cannot be converted to String">1</error>; return null; }); } public static void foo(Supplier<String> consumer) {} private void foo(List<String> descriptions) { Collections.sort(descriptions, (o1, o2) -> { final int elementsDiff = o1.length() - o2.length(); if (elementsDiff == 0) { return <error descr="Bad return type in lambda expression: boolean cannot be converted to int">o1.equals(o2)</error>; } return -elementsDiff; }); } }
33.038462
125
0.654249
7f32b163f7fe25ec7cd1bf74a6d63d1c1a86a9cd
1,225
package fr.uiytt.magiclauncher; import java.io.File; import java.io.IOException; import fr.theshark34.openlauncherlib.minecraft.GameInfos; import fr.theshark34.openlauncherlib.minecraft.GameType; import fr.theshark34.openlauncherlib.minecraft.GameVersion; import fr.theshark34.openlauncherlib.minecraft.util.GameDirGenerator; public class Main { public static final GameVersion KM_VERSION = new GameVersion("1.12.2", GameType.V1_8_HIGHER); public static GameInfos KM_INFOS; public static File KM_DIR; private static LauncherFrame frame; public static GuiRunnable staticrunnable; public static void main(String[] args) { KM_DIR = GameDirGenerator.createGameDir(Config.name); try { if(Config.debug) { Config.updateConfig(new File("/home/uiytt/Dev/Serveurs/modpack")); } else { Config.updateConfig(KM_DIR); } } catch (IOException e1) { e1.printStackTrace(); } GuiRunnable runnable = new GuiRunnable(); Thread a = new Thread(runnable); a.start(); staticrunnable = runnable; } public static LauncherFrame getFrame() { return frame; } public static void setFrame(LauncherFrame frame2) { frame = frame2; } }
24.019608
95
0.718367
5dec67323b12e2f13ef6fde6e8af89f9794ab634
1,369
package cn.sexycode.myjpa.binding; import cn.sexycode.myjpa.mapping.PersistentClass; import cn.sexycode.sql.dialect.function.SQLFunction; import cn.sexycode.sql.model.Database; import cn.sexycode.sql.type.TypeResolver; import javax.persistence.MappedSuperclass; import java.io.Serializable; import java.util.Collection; import java.util.Map; import java.util.UUID; /** * Container for configuration data collected during binding the metamodel. * * */ public class MetadataImpl implements Metadata, Serializable { private final UUID uuid; private final Map<String, PersistentClass> entityBindingMap; private final Map<Class, MappedSuperclass> mappedSuperclassMap; public MetadataImpl(UUID uuid, MetadataBuildingOptions options, TypeResolver typeResolver, Map<String, PersistentClass> entityBindingMap, Map<Class, MappedSuperclass> mappedSuperclassMap, Map<String, SQLFunction> sqlFunctionMap, Database database ) { this.uuid = uuid; this.entityBindingMap = entityBindingMap; this.mappedSuperclassMap = mappedSuperclassMap; } @Override public Collection<PersistentClass> getEntityBindings() { return entityBindingMap.values(); } @Override public PersistentClass getEntityBinding(String entityName) { return entityBindingMap.get(entityName); } }
29.12766
108
0.753104
e10ee0c52a3f107532227ebccb4de91e6b28786b
409
package at.petrak.hexcasting.mixin.accessor; import net.minecraft.world.entity.ai.village.poi.PoiType; import net.minecraft.world.level.block.state.BlockState; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Accessor; import java.util.Set; @Mixin(PoiType.class) public interface AccessorPoiType { @Accessor("matchingStates") Set<BlockState> hex$matchingStates(); }
27.266667
57
0.797066
f9b3c418eb2d25fa70e090452d06d522e0ea8525
1,351
package algorithms; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import graph.Vertex; /** * This class implements the Bron-Kerbosh algorithm for finding all Maximal Cliques * in a graph. (https://en.wikipedia.org/wiki/Bron%E2%80%93Kerbosch_algorithm) * * @author Sudharaka Palamakumbura * */ public class BronKerbosch { public static List<Set<Vertex>> maximalCliques(graph.Graph graph){ List<Set<Vertex>> cliques = new ArrayList<Set<Vertex>>(); Set<Vertex> R = new HashSet<Vertex>(); Set<Vertex> X = new HashSet<Vertex>(); Set<Vertex> P = new HashSet<Vertex>(graph.exportGraph().keySet()); bronKerbosch(cliques, R, P, X); return cliques; } private static void bronKerbosch(List<Set<Vertex>> cliques, Set<Vertex> R, Set<Vertex> P, Set<Vertex> X){ if (P.isEmpty() && X.isEmpty()) cliques.add(R); Set<Vertex> PCopy = new HashSet<Vertex>(P); for (Vertex v: PCopy){ Set<Vertex> N = v.getAdjVertices(); Set<Vertex> RModified = new HashSet<Vertex>(R); Set<Vertex> PModified = new HashSet<Vertex>(P); Set<Vertex> XModified = new HashSet<Vertex>(X); RModified.add(v); PModified.retainAll(N); XModified.retainAll(N); bronKerbosch(cliques, RModified, PModified, XModified); P.remove(v); X.add(v); } } }
23.701754
106
0.678016
d636cce42b0e992269e31c45e1596b8d3c17e1d0
2,489
/* * Copyright 2013-2015 Alex Lin. * * 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.opoopress.maven.plugins.plugin; import org.apache.commons.lang.StringUtils; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.opoo.press.impl.SiteConfigImpl; import java.io.File; import java.util.HashMap; import java.util.Map; /** * @author Alex Lin * //requiresDependencyResolution */ abstract class AbstractOpooPressMojo extends AbstractMojo{ /** * Base directory of the project. * @parameter expression="${basedir}" * @readonly * @required */ private File baseDirectory; /** * Site configuration files string, separated by ','. * @parameter expression="${op.config}" */ private String config; /** * @parameter expression="${debug}" default-value="false" */ private boolean debug = false; @Override public final void execute() throws MojoExecutionException, MojoFailureException { try { SiteConfigImpl configImpl = new SiteConfigImpl(baseDirectory, getOverrideConfiguration()); if(configImpl.getConfigFiles().length == 0){ getLog().info("No OpooPress site to generate."); return; } executeInternal(configImpl); }catch(RuntimeException e){ throw new MojoFailureException(e.getMessage(), e); } } protected Map<String,Object> getOverrideConfiguration(){ Map<String,Object> override = new HashMap<String,Object>(); if(StringUtils.isNotBlank(config)){ override.put("config", config); } if(debug){ override.put("debug", true); } return override; } protected abstract void executeInternal(SiteConfigImpl config) throws MojoExecutionException, MojoFailureException; }
29.987952
119
0.675372
8ec43c3beebe4dd11b8095f7724bf1899e9d6866
1,674
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot.commands; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj2.command.CommandBase; import frc.robot.subsystems.Shooting; import frc.robot.subsystems.Chassis; public class ShootTest extends CommandBase { private Shooting shooting; private Chassis chassis; public ShootTest(Shooting shooting, Chassis chassis) { this.shooting = shooting; this.chassis = chassis; } @Override public void initialize() { SmartDashboard.setDefaultNumber("SVelocity", 4500); SmartDashboard.setDefaultNumber("SAngle", 5); SmartDashboard.setDefaultBoolean("Shoot", false); SmartDashboard.setDefaultBoolean("Save", false); } @Override public void execute() { if (SmartDashboard.getBoolean("Shoot", false)) { shoot(); SmartDashboard.putBoolean("Shoot", false); } else if (SmartDashboard.getBoolean("NextPos", false)) { nextPos(); SmartDashboard.putBoolean("NextPos", false); } } @Override public void end(boolean interrupted) { } @Override public boolean isFinished() { return false; } private double getVelocity(){ return SmartDashboard.getNumber("SVelocity", 4500); } private double getAngle(){ return SmartDashboard.getNumber("SAngle", 5); } private void shoot() { new Shoot(shooting, this::getVelocity, this::getAngle).withTimeout(15).schedule(); } private void nextPos() { new GoTo(chassis, -0.5); } }
25.753846
86
0.710872
ac5eb8cbb328ac8182ce04d415d1c4b0997212b8
2,794
/* * Copyright 2009 Andrew Pietsch * * 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.dragome.forms.bindings.client.bean; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; /** * Created by IntelliJ IDEA. * User: andrew * Date: Aug 6, 2009 * Time: 5:19:48 PM * To change this template use File | Settings | File Templates. */ public class CollectionConverters { public static final CollectionConverter<Collection> COLLECTION_CONVERTER= new CollectionConverter<Collection>() { public Collection<?> fromBean(Collection source) { return source; } public Collection toBean(List<?> source) { return new ArrayList<Object>(source); } }; public static final CollectionConverter<List> LIST_CONVERTER= new CollectionConverter<List>() { public Collection<?> fromBean(List source) { return source; } public List toBean(List<?> source) { return new ArrayList<Object>(source); } }; public static final CollectionConverter<Set> SET_CONVERTER= new CollectionConverter<Set>() { public Collection<?> fromBean(Set source) { return source; } public Set toBean(List<?> source) { return new HashSet<Object>(source); } }; public static final CollectionConverter<SortedSet> SORTED_SET_CONVERTER= new CollectionConverter<SortedSet>() { public Collection<?> fromBean(SortedSet source) { return source; } public SortedSet toBean(List<?> source) { return new TreeSet<Object>(source); } }; private HashMap<Class<?>, CollectionConverter<?>> converters= new HashMap<Class<?>, CollectionConverter<?>>(); public CollectionConverters() { register(List.class, LIST_CONVERTER); register(Set.class, SET_CONVERTER); register(SortedSet.class, SORTED_SET_CONVERTER); register(Collection.class, COLLECTION_CONVERTER); } public <T> void register(Class<T> collectionClass, CollectionConverter<T> converter) { converters.put(collectionClass, converter); } @SuppressWarnings("unchecked") public <T> CollectionConverter<T> getConverter(Class<T> aClass) { return (CollectionConverter<T>) converters.get(aClass); } }
25.4
112
0.72942
1a7e152475ba5174c055e37681c04905843f7425
1,532
package examples.sharedui; import java.net.URL; import java.util.ResourceBundle; import ilusr.core.ioc.ServiceManager; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.control.ContextMenu; import javafx.scene.control.Label; import javafx.scene.control.MenuItem; public class ThemeItem extends Label implements Initializable, IThemeListener{ private final String CURRENT_THEME = "Current Theme: "; private final ThemeService _themeService; private ContextMenu _selectionMenu; public ThemeItem() { _themeService = ServiceManager.getInstance().<ThemeService>get("ThemeService"); FXMLLoader themeLoader = new FXMLLoader(getClass().getResource("ThemeItem.fxml")); themeLoader.setRoot(this); themeLoader.setController(this); try { themeLoader.load(); } catch (Exception exception) { exception.printStackTrace(); } } @Override public void initialize(URL arg0, ResourceBundle arg1) { _themeService.addListener(this); _selectionMenu = new ContextMenu(); buildContextMenu(); super.contextMenuProperty().set(_selectionMenu); super.textProperty().set(CURRENT_THEME); } private void buildContextMenu() { for(String style : _themeService.getRegisteredStyles()) { MenuItem temp = new MenuItem(style); temp.setOnAction((e) -> { _themeService.changeStyle(temp.getText()); }); _selectionMenu.getItems().add(temp); } } @Override public void themeChanged(String theme) { super.textProperty().set(CURRENT_THEME + theme); } }
25.533333
84
0.751305
88277d6ab45a109f26a56b9fef936d48bd22b5c2
3,112
package mskubilov; import mskubilov.board.*; import mskubilov.exceptions.*; import mskubilov.moves.*; import mskubilov.figures.*; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; /** * TestKingLikeRook. * @author Maksim Skubilov [email protected] * @since 30.03.2017 * @version 1.0 */ public class TestKingLikeRook { /** * Test of moving King like Rook. * @throws ImpossibleMoveException - исключение невозможного хода. * @throws OccupiedWayException - исключение хода, путь к которому закрыт другой фигурой. * @throws FigureNotFoundException - исключение хода, когда нет фигуры на source. */ @Test public void testKing() throws ImpossibleMoveException, OccupiedWayException, FigureNotFoundException { Board board = new Board(); board.fillBoard(); board.setFigure(new King(new Cell('d', 4))); boolean move = false; Cell source = new Cell('d', 4); Cell dest = new Cell('e', 4); move = board.move(source, dest); assertThat(move, is(true)); assertThat(board.getFigure(0).getPosition(), is(dest)); } /** * Test of FigureNotFoundException. * @throws ImpossibleMoveException - исключение невозможного хода. * @throws OccupiedWayException - исключение хода, путь к которому закрыт другой фигурой. * @throws FigureNotFoundException - исключение хода, когда нет фигуры на source. */ @Test (expected = FigureNotFoundException.class) public void whenWrongSourceCellThenThereIsFigureNotFoundException() throws ImpossibleMoveException, OccupiedWayException, FigureNotFoundException { Board board = new Board(); board.fillBoard(); board.setFigure(new King(new Cell('d', 4))); boolean move = false; move = board.move(new Cell('d', 1), new Cell('d', 2)); } /** * Test of ImpossibleMoveException. * @throws ImpossibleMoveException - исключение невозможного хода. * @throws OccupiedWayException - исключение хода, путь к которому закрыт другой фигурой. * @throws FigureNotFoundException - исключение хода, когда нет фигуры на source. */ @Test (expected = ImpossibleMoveException.class) public void whenWrongDestCellThenThereIsImpossibleMoveException() throws ImpossibleMoveException, OccupiedWayException, FigureNotFoundException { Board board = new Board(); board.fillBoard(); board.setFigure(new King(new Cell('d', 4))); boolean move = false; move = board.move(new Cell('d', 4), new Cell('b', 4)); } /** * Test of OccupiedWayException. * @throws ImpossibleMoveException - исключение невозможного хода. * @throws OccupiedWayException - исключение хода, путь к которому закрыт другой фигурой. * @throws FigureNotFoundException - исключение хода, когда нет фигуры на source. */ @Test (expected = OccupiedWayException.class) public void whenThereIsAFigureOnTheWayThenThereIsOccupiedWayException() throws ImpossibleMoveException, OccupiedWayException, FigureNotFoundException { Board board = new Board(); board.fillBoard(); board.setFigure(new King(new Cell('f', 7))); boolean move = false; move = board.move(new Cell('f', 7), new Cell('g', 7)); } }
37.493976
103
0.742609
7b1f7dbbcae991fa5a0c4112bb180960838ae348
15,904
/* * This file is generated by jOOQ. */ package io.cattle.platform.core.model.tables.records; import io.cattle.platform.core.model.Network; import io.cattle.platform.core.model.tables.NetworkTable; import io.cattle.platform.db.jooq.utils.TableRecordJaxb; import java.util.Date; import java.util.Map; import javax.annotation.Generated; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import org.jooq.Field; import org.jooq.Record1; import org.jooq.Record14; import org.jooq.Row14; import org.jooq.impl.UpdatableRecordImpl; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.9.3" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) @Entity @Table(name = "network", schema = "cattle") public class NetworkRecord extends UpdatableRecordImpl<NetworkRecord> implements TableRecordJaxb, Record14<Long, String, Long, String, String, String, String, Date, Date, Date, Map<String,Object>, Boolean, String, Long>, Network { private static final long serialVersionUID = -161879277; /** * Setter for <code>cattle.network.id</code>. */ @Override public void setId(Long value) { set(0, value); } /** * Getter for <code>cattle.network.id</code>. */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", unique = true, nullable = false, precision = 19) @Override public Long getId() { return (Long) get(0); } /** * Setter for <code>cattle.network.name</code>. */ @Override public void setName(String value) { set(1, value); } /** * Getter for <code>cattle.network.name</code>. */ @Column(name = "name", length = 255) @Override public String getName() { return (String) get(1); } /** * Setter for <code>cattle.network.account_id</code>. */ @Override public void setAccountId(Long value) { set(2, value); } /** * Getter for <code>cattle.network.account_id</code>. */ @Column(name = "account_id", precision = 19) @Override public Long getAccountId() { return (Long) get(2); } /** * Setter for <code>cattle.network.kind</code>. */ @Override public void setKind(String value) { set(3, value); } /** * Getter for <code>cattle.network.kind</code>. */ @Column(name = "kind", nullable = false, length = 255) @Override public String getKind() { return (String) get(3); } /** * Setter for <code>cattle.network.uuid</code>. */ @Override public void setUuid(String value) { set(4, value); } /** * Getter for <code>cattle.network.uuid</code>. */ @Column(name = "uuid", unique = true, nullable = false, length = 128) @Override public String getUuid() { return (String) get(4); } /** * Setter for <code>cattle.network.description</code>. */ @Override public void setDescription(String value) { set(5, value); } /** * Getter for <code>cattle.network.description</code>. */ @Column(name = "description", length = 1024) @Override public String getDescription() { return (String) get(5); } /** * Setter for <code>cattle.network.state</code>. */ @Override public void setState(String value) { set(6, value); } /** * Getter for <code>cattle.network.state</code>. */ @Column(name = "state", nullable = false, length = 128) @Override public String getState() { return (String) get(6); } /** * Setter for <code>cattle.network.created</code>. */ @Override public void setCreated(Date value) { set(7, value); } /** * Getter for <code>cattle.network.created</code>. */ @Column(name = "created") @Override public Date getCreated() { return (Date) get(7); } /** * Setter for <code>cattle.network.removed</code>. */ @Override public void setRemoved(Date value) { set(8, value); } /** * Getter for <code>cattle.network.removed</code>. */ @Column(name = "removed") @Override public Date getRemoved() { return (Date) get(8); } /** * Setter for <code>cattle.network.remove_time</code>. */ @Override public void setRemoveTime(Date value) { set(9, value); } /** * Getter for <code>cattle.network.remove_time</code>. */ @Column(name = "remove_time") @Override public Date getRemoveTime() { return (Date) get(9); } /** * Setter for <code>cattle.network.data</code>. */ @Override public void setData(Map<String,Object> value) { set(10, value); } /** * Getter for <code>cattle.network.data</code>. */ @Column(name = "data", length = 16777215) @Override public Map<String,Object> getData() { return (Map<String,Object>) get(10); } /** * Setter for <code>cattle.network.is_public</code>. */ @Override public void setIsPublic(Boolean value) { set(11, value); } /** * Getter for <code>cattle.network.is_public</code>. */ @Column(name = "is_public", nullable = false, precision = 1) @Override public Boolean getIsPublic() { return (Boolean) get(11); } /** * Setter for <code>cattle.network.domain</code>. */ @Override public void setDomain(String value) { set(12, value); } /** * Getter for <code>cattle.network.domain</code>. */ @Column(name = "domain", length = 128) @Override public String getDomain() { return (String) get(12); } /** * Setter for <code>cattle.network.network_driver_id</code>. */ @Override public void setNetworkDriverId(Long value) { set(13, value); } /** * Getter for <code>cattle.network.network_driver_id</code>. */ @Column(name = "network_driver_id", precision = 19) @Override public Long getNetworkDriverId() { return (Long) get(13); } // ------------------------------------------------------------------------- // Primary key information // ------------------------------------------------------------------------- /** * {@inheritDoc} */ @Override public Record1<Long> key() { return (Record1) super.key(); } // ------------------------------------------------------------------------- // Record14 type implementation // ------------------------------------------------------------------------- /** * {@inheritDoc} */ @Override public Row14<Long, String, Long, String, String, String, String, Date, Date, Date, Map<String,Object>, Boolean, String, Long> fieldsRow() { return (Row14) super.fieldsRow(); } /** * {@inheritDoc} */ @Override public Row14<Long, String, Long, String, String, String, String, Date, Date, Date, Map<String,Object>, Boolean, String, Long> valuesRow() { return (Row14) super.valuesRow(); } /** * {@inheritDoc} */ @Override public Field<Long> field1() { return NetworkTable.NETWORK.ID; } /** * {@inheritDoc} */ @Override public Field<String> field2() { return NetworkTable.NETWORK.NAME; } /** * {@inheritDoc} */ @Override public Field<Long> field3() { return NetworkTable.NETWORK.ACCOUNT_ID; } /** * {@inheritDoc} */ @Override public Field<String> field4() { return NetworkTable.NETWORK.KIND; } /** * {@inheritDoc} */ @Override public Field<String> field5() { return NetworkTable.NETWORK.UUID; } /** * {@inheritDoc} */ @Override public Field<String> field6() { return NetworkTable.NETWORK.DESCRIPTION; } /** * {@inheritDoc} */ @Override public Field<String> field7() { return NetworkTable.NETWORK.STATE; } /** * {@inheritDoc} */ @Override public Field<Date> field8() { return NetworkTable.NETWORK.CREATED; } /** * {@inheritDoc} */ @Override public Field<Date> field9() { return NetworkTable.NETWORK.REMOVED; } /** * {@inheritDoc} */ @Override public Field<Date> field10() { return NetworkTable.NETWORK.REMOVE_TIME; } /** * {@inheritDoc} */ @Override public Field<Map<String,Object>> field11() { return NetworkTable.NETWORK.DATA; } /** * {@inheritDoc} */ @Override public Field<Boolean> field12() { return NetworkTable.NETWORK.IS_PUBLIC; } /** * {@inheritDoc} */ @Override public Field<String> field13() { return NetworkTable.NETWORK.DOMAIN; } /** * {@inheritDoc} */ @Override public Field<Long> field14() { return NetworkTable.NETWORK.NETWORK_DRIVER_ID; } /** * {@inheritDoc} */ @Override public Long value1() { return getId(); } /** * {@inheritDoc} */ @Override public String value2() { return getName(); } /** * {@inheritDoc} */ @Override public Long value3() { return getAccountId(); } /** * {@inheritDoc} */ @Override public String value4() { return getKind(); } /** * {@inheritDoc} */ @Override public String value5() { return getUuid(); } /** * {@inheritDoc} */ @Override public String value6() { return getDescription(); } /** * {@inheritDoc} */ @Override public String value7() { return getState(); } /** * {@inheritDoc} */ @Override public Date value8() { return getCreated(); } /** * {@inheritDoc} */ @Override public Date value9() { return getRemoved(); } /** * {@inheritDoc} */ @Override public Date value10() { return getRemoveTime(); } /** * {@inheritDoc} */ @Override public Map<String,Object> value11() { return getData(); } /** * {@inheritDoc} */ @Override public Boolean value12() { return getIsPublic(); } /** * {@inheritDoc} */ @Override public String value13() { return getDomain(); } /** * {@inheritDoc} */ @Override public Long value14() { return getNetworkDriverId(); } /** * {@inheritDoc} */ @Override public NetworkRecord value1(Long value) { setId(value); return this; } /** * {@inheritDoc} */ @Override public NetworkRecord value2(String value) { setName(value); return this; } /** * {@inheritDoc} */ @Override public NetworkRecord value3(Long value) { setAccountId(value); return this; } /** * {@inheritDoc} */ @Override public NetworkRecord value4(String value) { setKind(value); return this; } /** * {@inheritDoc} */ @Override public NetworkRecord value5(String value) { setUuid(value); return this; } /** * {@inheritDoc} */ @Override public NetworkRecord value6(String value) { setDescription(value); return this; } /** * {@inheritDoc} */ @Override public NetworkRecord value7(String value) { setState(value); return this; } /** * {@inheritDoc} */ @Override public NetworkRecord value8(Date value) { setCreated(value); return this; } /** * {@inheritDoc} */ @Override public NetworkRecord value9(Date value) { setRemoved(value); return this; } /** * {@inheritDoc} */ @Override public NetworkRecord value10(Date value) { setRemoveTime(value); return this; } /** * {@inheritDoc} */ @Override public NetworkRecord value11(Map<String,Object> value) { setData(value); return this; } /** * {@inheritDoc} */ @Override public NetworkRecord value12(Boolean value) { setIsPublic(value); return this; } /** * {@inheritDoc} */ @Override public NetworkRecord value13(String value) { setDomain(value); return this; } /** * {@inheritDoc} */ @Override public NetworkRecord value14(Long value) { setNetworkDriverId(value); return this; } /** * {@inheritDoc} */ @Override public NetworkRecord values(Long value1, String value2, Long value3, String value4, String value5, String value6, String value7, Date value8, Date value9, Date value10, Map<String,Object> value11, Boolean value12, String value13, Long value14) { value1(value1); value2(value2); value3(value3); value4(value4); value5(value5); value6(value6); value7(value7); value8(value8); value9(value9); value10(value10); value11(value11); value12(value12); value13(value13); value14(value14); return this; } // ------------------------------------------------------------------------- // FROM and INTO // ------------------------------------------------------------------------- /** * {@inheritDoc} */ @Override public void from(Network from) { setId(from.getId()); setName(from.getName()); setAccountId(from.getAccountId()); setKind(from.getKind()); setUuid(from.getUuid()); setDescription(from.getDescription()); setState(from.getState()); setCreated(from.getCreated()); setRemoved(from.getRemoved()); setRemoveTime(from.getRemoveTime()); setData(from.getData()); setIsPublic(from.getIsPublic()); setDomain(from.getDomain()); setNetworkDriverId(from.getNetworkDriverId()); } /** * {@inheritDoc} */ @Override public <E extends Network> E into(E into) { into.from(this); return into; } // ------------------------------------------------------------------------- // Constructors // ------------------------------------------------------------------------- /** * Create a detached NetworkRecord */ public NetworkRecord() { super(NetworkTable.NETWORK); } /** * Create a detached, initialised NetworkRecord */ public NetworkRecord(Long id, String name, Long accountId, String kind, String uuid, String description, String state, Date created, Date removed, Date removeTime, Map<String,Object> data, Boolean isPublic, String domain, Long networkDriverId) { super(NetworkTable.NETWORK); set(0, id); set(1, name); set(2, accountId); set(3, kind); set(4, uuid); set(5, description); set(6, state); set(7, created); set(8, removed); set(9, removeTime); set(10, data); set(11, isPublic); set(12, domain); set(13, networkDriverId); } }
21.009247
249
0.529678
6240466dc914b536ab46e07e08e9438336caa35a
1,321
// In-Place Quick Sort, a little bit dump way, but maybe easier to understand. public class Main { static void swap(int x[], int a, int b) { int t = x[a]; x[a] = x[b]; x[b] = t; } static int partition(int[] x, int l, int r) { int p = r; // Choosing last element as pivot. boolean flag = false; // Used to avoid unnecessary iterations, can be omitted. for (int i = l; i < r; i++) { while (x[i] > x[p] && p > i) { swap(x, p, p - 1); if (i != p - 1) swap(x, i, p); else flag = true; p--; } if(flag) break; } // Debugging System.out.println("Array after partitioning with pivot = " + x[p]); for (int i : x) System.out.print(i + " "); System.out.println(""); return p; } static void qsort(int[] x, int l, int r) { if (l >= r) return; int p = partition(x, l, r); qsort(x, l, p - 1); qsort(x, p + 1, r); } public static void main(String[] args) { int[] x = {5, 9, 1, 0, -561, 69, 98, -20, 6}; // We can random shuffle the array here to avoid worst case. qsort(x, 0, x.length - 1); for (int i : x) System.out.print(i + " "); } }
28.106383
86
0.4595
bfe5b468f6400ed2dfc6d565864888f47ad9dc12
230
package com.github.xfslove.shiro.uaa.service; import com.github.xfslove.shiro.uaa.model.Role; /** * Created by hanwen on 2017/6/12. */ public interface RoleService { Role getById(Long id); Role getByName(String name); }
16.428571
47
0.726087
74ca9d3b3996c60f2accadf05755c9f8b703ce3b
1,707
package Day5; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.stream.Stream; public class Day5 { static final int INPUT = 1; static final int OPT_ADD = 1; static final int OPT_MUL = 2; static final int OPT_IN = 3; static final int OPT_OUT = 4; static final int OPT_END = 99; public static void main(String[] args) { String fileName = "inputDay5.txt"; Integer[] optcodes = null; try (Stream<String> stream = Files.lines(Paths.get(fileName))) { String[] temp = stream.toArray(String[]::new)[0].split(","); optcodes = new Integer[temp.length]; for(int i = 0; i < temp.length; ++i) { optcodes[i] = Integer.parseInt(temp[i]); } } catch (IOException e) { e.printStackTrace(); } int stepSize = 4; int output = -1; boolean done = false; for(int i = 0; i < optcodes.length; i += stepSize) { OptContainer opt = new OptContainer(optcodes[i]); switch(opt.optCode) { case OPT_ADD: optcodes[optcodes[i + 3]] = opt.get(optcodes, optcodes[i + 1], 1) + opt.get(optcodes, optcodes[i + 2], 2); stepSize = 4; break; case OPT_MUL: optcodes[optcodes[i + 3]] = opt.get(optcodes, optcodes[i + 1], 1) * opt.get(optcodes, optcodes[i + 2], 2); stepSize = 4; break; case OPT_IN: optcodes[optcodes[i + 1]] = INPUT; stepSize = 2; break; case OPT_OUT: output = opt.get(optcodes, optcodes[i + 1], 1); stepSize = 2; break; default: if(opt.optCode != OPT_END) { System.out.println("Unknown optcode: " + opt.optCode); } done = true; break; } if(done) { break; } } System.out.println("Output was: " + output); } }
23.708333
110
0.617458
2b366bcab922be6f3948722dc553eadfe1648617
516
package org.enricogiurin.codingchallenges.codeforces.old.c1140; public class GoodStringB { public static void main(String[] args) { /*Scanner sc = new Scanner(System.in); int n = sc.nextInt(); for (int i = 0; i <n; i++) { int length = sc.nextInt(); String s = sc.next(); System.out.println(s, length)); }*/ solve(">>>><<>>".toCharArray(), 8); } static int solve(char[] arrayChars, int lenght) { return 0; } }
21.5
63
0.531008
107728a50889b8c25f05950853135c7de4d59129
2,992
package io.sealights.plugins.sealightsjenkins.buildsteps.cli.utils; import io.sealights.plugins.sealightsjenkins.buildsteps.cli.CommandMode; import io.sealights.plugins.sealightsjenkins.buildsteps.cli.entities.*; import io.sealights.plugins.sealightsjenkins.utils.PropertiesUtils; /** * Created by shahar on 2/12/2017. */ public class ModeToArgumentsConverter { public AbstractCommandArgument convert(CommandMode mode){ if (mode == null){ return null; } if (CommandModes.Start.equals(mode.getCurrentMode())) { return toStartCommandArguments((CommandMode.StartView) mode); } else if (CommandModes.End.equals(mode.getCurrentMode())) { return toEndCommandArguments(); } else if (CommandModes.UploadReports.equals(mode.getCurrentMode())) { return toUploadReportCommandArguments((CommandMode.UploadReportsView) mode); } else if (CommandModes.ExternalReport.equals(mode.getCurrentMode())) { return toExternalReportArguments((CommandMode.ExternalReportView) mode); } else if (CommandModes.Config.equals(mode.getCurrentMode())) { return toConfigCommandArguments((CommandMode.ConfigView) mode); } else if (CommandModes.PrConfig.equals(mode.getCurrentMode())) { return toPrConfigCommandArguments((CommandMode.PrConfigView) mode); } throw new IllegalStateException("toCommandArgument() - The provided CommandMode is not one of the expected types"); } private StartCommandArguments toStartCommandArguments(CommandMode.StartView startView){ return new StartCommandArguments(startView.getTestStage()); } private EndCommandArguments toEndCommandArguments(){ return new EndCommandArguments(); } private UploadReportsCommandArguments toUploadReportCommandArguments(CommandMode.UploadReportsView uploadReportsView){ String source = PropertiesUtils.toProperties(uploadReportsView.getAdditionalArguments()).getProperty("source"); return new UploadReportsCommandArguments( uploadReportsView.getReportFiles(), uploadReportsView.getReportsFolders(), uploadReportsView.getHasMoreRequests(), source); } private ExternalReportCommandArguments toExternalReportArguments(CommandMode.ExternalReportView externalReportView){ return new ExternalReportCommandArguments(externalReportView.getReport()); } private ConfigCommandArguments toConfigCommandArguments(CommandMode.ConfigView configView){ return new ConfigCommandArguments(configView.getTechOptions()); } private PrConfigCommandArguments toPrConfigCommandArguments(CommandMode.PrConfigView prConfigView){ return new PrConfigCommandArguments(prConfigView.getTechOptions(), prConfigView.getLatestCommit(), prConfigView.getPullRequestNumber(), prConfigView.getRepoUrl(), prConfigView.getTargetBranch()); } }
46.75
123
0.741979
dee73e9c1676e4bc905bb1a0da64b296f1415a04
3,323
/* * MIT License * * Copyright (c) 2016 Eric * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.EricSun.EricWidget.Widget; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.widget.RadioGroup; public class CustomRadioGroup extends RadioGroup { public CustomRadioGroup(Context context) { super(context); } public CustomRadioGroup(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int maxWidth = MeasureSpec.getSize(widthMeasureSpec); int childCount = getChildCount(); int x = 0; int y = 0; int row = 0; for (int index = 0; index < childCount; index++) { final View child = getChildAt(index); if (child.getVisibility() != View.GONE) { child.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED); // 此处增加onlayout中的换行判断,用于计算所需的高度 int width = child.getMeasuredWidth(); int height = child.getMeasuredHeight(); x += width; y = row * height + height; if (x > maxWidth) { x = width; row++; y = row * height + height; } } } // 设置容器所需的宽度和高度 setMeasuredDimension(maxWidth, y); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { final int childCount = getChildCount(); int maxWidth = r - l; int x = 0; int y = 0; int row = 0; for (int i = 0; i < childCount; i++) { final View child = this.getChildAt(i); if (child.getVisibility() != View.GONE) { int width = child.getMeasuredWidth(); int height = child.getMeasuredHeight(); x += width; y = row * height + height; if (x > maxWidth) { x = width; row++; y = row * height + height; } child.layout(x - width, y - height, x, y); } } } }
35.351064
81
0.597051
dc2c4e231f2d1427d81818d7b4ab34b1fbf0387a
3,629
/* * 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.cassandra.transport; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import org.junit.Test; import io.netty.buffer.ByteBuf; import org.apache.cassandra.db.TypeSizes; import org.apache.cassandra.db.marshal.AbstractType; import org.apache.cassandra.db.marshal.AsciiType; import org.apache.cassandra.db.marshal.LongType; import static org.junit.Assert.assertEquals; public class DataTypeTest { @Test public void TestSimpleDataTypeSerialization() { for (DataType type : DataType.values()) { if (isComplexType(type)) continue; Map<DataType, Object> options = Collections.singletonMap(type, (Object)type.toString()); for (int version = 1; version < 5; version++) testEncodeDecode(type, options, version); } } @Test public void TestListDataTypeSerialization() { DataType type = DataType.LIST; Map<DataType, Object> options = Collections.singletonMap(type, (Object)LongType.instance); for (int version = 1; version < 5; version++) testEncodeDecode(type, options, version); } @Test public void TestMapDataTypeSerialization() { DataType type = DataType.MAP; List<AbstractType> value = new ArrayList<>(); value.add(LongType.instance); value.add(AsciiType.instance); Map<DataType, Object> options = Collections.singletonMap(type, (Object)value); for (int version = 1; version < 5; version++) testEncodeDecode(type, options, version); } private void testEncodeDecode(DataType type, Map<DataType, Object> options, int version) { ByteBuf dest = type.codec.encode(options, version); Map<DataType, Object> results = type.codec.decode(dest, version); for (DataType key : results.keySet()) { int ssize = type.serializedValueSize(results.get(key), version); int esize = version < type.getProtocolVersion() ? 2 + TypeSizes.encodedUTF8Length(results.get(key).toString()) : 0; switch (type) { case LIST: case SET: esize += 2; break; case MAP: esize += 4; break; case CUSTOM: esize = 8; break; } assertEquals(esize, ssize); DataType expected = version < type.getProtocolVersion() ? DataType.CUSTOM : type; assertEquals(expected, key); } } private boolean isComplexType(DataType type) { return type.getId(Server.CURRENT_VERSION) >= 32; } }
33.293578
127
0.630201
dd72433e9a8272014f8414343c594038ad8be3c2
6,123
package core.menu; import static core.Frame.SCREEN_SIZE; import gui.FontManager.FontType; import gui.GameGUI; import gui.PowerSelectionGUI; import gui.ui.ButtonElement; import gui.ui.HudElement.InteractionType; import gui.ui.HudOverlay; import gui.ui.TextElement; import java.awt.Color; import java.util.List; import java.util.Set; import java.util.TreeSet; import mission.powers.Power; import monitor.PowerShop; import org.lwjgl.input.Mouse; import org.lwjgl.opengl.Display; import phys.Point2D; import phys.Shape; import core.Frame; import core.controller.MouseController; import core.controller.ShipController; public class PowerSelectionScreen extends SetupScreen { /* GUI */ HudOverlay menuOverlay; PowerSelectionGUI gui; Point2D[] cursorPosition = new Point2D[] { new Point2D(Frame.SCREEN_SIZE[0]/3f,Frame.SCREEN_SIZE[1]/2f), new Point2D(Frame.SCREEN_SIZE[0]*2/3f,Frame.SCREEN_SIZE[1]/2f) }; ShipController[] controllers; boolean hotDown[] = {false, false}; boolean play = true; Set<Integer> powers0; Set<Integer> powers1; public PowerSelectionScreen(Frame frame, ShipController[] controllers) { super(frame); this.gui = new PowerSelectionGUI(); this.controllers = controllers; powers0 = new TreeSet<Integer>(); powers1 = new TreeSet<Integer>(); makeOverlay(); } private void makeOverlay() { // create menu UI menuOverlay = new HudOverlay(); float hs = SCREEN_SIZE[1]/10; Shape bs = new Shape(new Point2D[] { new Point2D(-hs*2,-hs/2), new Point2D( hs*2,-hs/2), new Point2D( hs*2, hs/2), new Point2D(-hs*2, hs/2) }); ButtonElement playButton = new ButtonElement("play_button", bs, new Point2D(SCREEN_SIZE[0]/2 + 2*hs, SCREEN_SIZE[1]-hs), Color.BLACK, GameGUI.wreckage, Color.WHITE); playButton.addCommand(InteractionType.MOUSE_DOWN, "play"); playButton.addElement(new TextElement("pbt", bs,new Point2D(), "PLAY", FontType.FONT_32)); ButtonElement backButton = new ButtonElement("quit_button", bs, new Point2D(SCREEN_SIZE[0]/2 - 2*hs, SCREEN_SIZE[1]-hs), Color.BLACK, GameGUI.wreckage, Color.WHITE); backButton.addCommand(InteractionType.MOUSE_DOWN, "quit"); backButton.addElement(new TextElement("bbt", bs,new Point2D(), "BACK", FontType.FONT_32)); menuOverlay.addElement(playButton); menuOverlay.addElement(backButton); } public void setupPowers() { Mouse.setGrabbed(true); // load saved power builds frame.getFileManager().readPowers(); for(int p: frame.getFileManager().getPlayerPowers(0)) if(p>=0 && PowerShop.isPowerUnlocked(p)) powers0.add(p); for(int p: frame.getFileManager().getPlayerPowers(1)) if(p>=0 && PowerShop.isPowerUnlocked(p)) powers1.add(p); finished = false; while(!finished) { pollInput(); // draw view gui.draw(this); menuOverlay.draw(); gui.drawCursors(this); // opengl update Display.update(); Display.sync(60); if (Display.wasResized()) { frame.setDisplayMode( Display.getWidth(), Display.getHeight(), Frame.FULLSCREEN); makeOverlay(); } if(Display.isCloseRequested()) finished = true; } // save new builds frame.getFileManager().savePowers(powers0,powers1); Mouse.setGrabbed(false); } private void pollInput() { // HUD commands with mouse List<String> commands = menuOverlay.pollInput(); for(String com: commands) { switch(com) { case "play": finish(); return; case "quit": cancel(); return; } } // select powers for(int i=0;i<2;i++) { if(controllers[i]==null) continue; // move cursors if(controllers[i] instanceof MouseController) { cursorPosition[i].x = Mouse.getX(); cursorPosition[i].y = Frame.SCREEN_SIZE[1] - Mouse.getY(); } else { controllers[i].pollInput(); cursorPosition[i].x += controllers[i].getDirection().x*Frame.SCREEN_SIZE[0]/160f; cursorPosition[i].y += controllers[i].getDirection().y*Frame.SCREEN_SIZE[0]/160f; cursorPosition[i].x = clamp(cursorPosition[i].x,0,Frame.SCREEN_SIZE[0]-10); cursorPosition[i].y = clamp(cursorPosition[i].y,0,Frame.SCREEN_SIZE[1]-10); } // HUD interaction with non-mouse controllers if(controllers[i].isSelecting() && !(controllers[i] instanceof MouseController)) { // HUD commands commands = menuOverlay.interact(cursorPosition[i], InteractionType.MOUSE_DOWN); for(String com: commands) { switch(com) { case "play": finish(); return; case "quit": cancel(); return; } } } // power buttons if(controllers[i].isSelecting()) { if(hotDown[i]) { hotDown[i] = false; selectPower(i); } } else { hotDown[i] = true; } } } private void selectPower(int player) { int slot = gui.getSlot(player, cursorPosition[player]); if(slot==-1) return; if(!PowerShop.isPowerUnlocked(slot)) return; Set<Integer> powers = powers0; if(player==1) powers = powers1; if(!powers.contains(slot) && powers.size()<6 && (!Power.values()[slot].active || getNoActivePowers(player)<4)) powers.add(slot); else if(powers.contains(slot)) powers.remove(slot); } public int getNoActivePowers(int player) { int amnt = 0; Set<Integer> list = getPowers(player); for(Integer i: list) { if(Power.values()[i].active) amnt++; } return amnt; } public Set<Integer> getPowers(int player) { if(player==1) return powers1; return powers0; } private float clamp(float value, float min, float max) { if(value>max) return max; if(value<min) return min; return value; } public boolean toPlay() { return play; } public ShipController[] getControllers() { return controllers; } public Point2D[] getCursorPosition() { return cursorPosition; } @Override public void cancel() { play = false; finished = true; } }
26.27897
168
0.649518
c4406f89056c42ac1a040846f5df1cc872926523
2,071
package com.thalesgroup.rtti._2012_01_13.ldb.types; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * A list of messages applicable to a station departure board, warning of general disruptions or important information. * * <p>Java class for ArrayOfNRCCMessages complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="ArrayOfNRCCMessages"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="message" type="{http://thalesgroup.com/RTTI/2012-01-13/ldb/types}NRCCMessage" maxOccurs="unbounded" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ArrayOfNRCCMessages", propOrder = { "message" }) public class ArrayOfNRCCMessages { @XmlElement(nillable = true) protected List<NRCCMessage> message; /** * Gets the value of the message property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the message property. * * <p> * For example, to add a new item, do as follows: * <pre> * getMessage().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link NRCCMessage } * * */ public List<NRCCMessage> getMessage() { if (message == null) { message = new ArrayList<NRCCMessage>(); } return this.message; } }
28.763889
147
0.654273
ed42c9aa07b16e1768148d2fb1b71cd69db7f5ef
997
/* * Copyright (c) 2001-2002, Stewart Allen <[email protected]> * * This program is free software; you can redistribute it and/or * modify it under the terms of the Artistic License. */ package javax.comm; // ---( imports )--- import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.FilenameFilter; import java.util.StringTokenizer; import java.util.TooManyListenersException; public class DriverMac_OS_X extends DriverLinux { private final static String IGNORE_KEY = "javax.ignore.modem"; public static void setIgnoreModems(boolean tf) { if (tf) { System.getProperties().put(IGNORE_KEY, "true"); } else { System.getProperties().remove(IGNORE_KEY); } } protected String[][] getSerial() { return new String[][] { {"/dev", "cu."}, }; } protected boolean skipPort(File file) { return (System.getProperty(IGNORE_KEY) != null && file.toString().toLowerCase().indexOf("modem") >= 0); } }
20.770833
105
0.703109
aca0eb07835db0d43e0546a961a81e8965dc8e45
124
package org.apache.age.jdbc.base.type; public interface UnrecognizedObject { void setAnnotation(String annotation); }
17.714286
42
0.782258
186b386c7ae7390ce6760dd9b1e98e71bde0c576
1,496
package net.devaction.kafka.transferswebsocketsservice.server.sender; import javax.websocket.Session; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import net.devaction.entity.TransferEntity; import net.devaction.kafka.transferswebsocketsservice.message.MessageType; import net.devaction.kafka.transferswebsocketsservice.message.MessageWrapper; /** * @author Víctor Gil * * since August 2019 */ public class TransferDataResponseSender implements TransferSender { private static final Logger log = LoggerFactory.getLogger(TransferDataResponseSender.class); private final ObjectMapper mapper = new ObjectMapper(); private final MessageSender messageSender; public TransferDataResponseSender(MessageSender messageSender) { this.messageSender = messageSender; } @Override public void send(TransferEntity transfer, Session session) { String json; try { json = mapper.writeValueAsString(transfer); } catch (JsonProcessingException ex) { log.error("Unable to serialize {} to JSON: {}", TransferEntity.class.getSimpleName(), transfer, ex); return; } MessageWrapper message = new MessageWrapper(MessageType.TRANSFER_DATA_RESPONSE.name(), json); messageSender.send(message, session); } }
29.92
96
0.719251
4101a3ee61af0e17848357a317da9cbf5d31d1da
270
package space.harbour.l71.structural.decorator; /** * Created by tully. * <p> * CoreFunctionality in the Decorator pattern. */ public class PrinterImpl implements Printer { @Override public void print(String str) { System.out.println(str); } }
18
47
0.681481
89857d01487118de8284e7c965aa88ac035652f2
2,185
/* * 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.sysml.runtime.matrix.sort; import java.io.IOException; import java.util.Iterator; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Writable; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.MapReduceBase; import org.apache.hadoop.mapred.OutputCollector; import org.apache.hadoop.mapred.Reducer; import org.apache.hadoop.mapred.Reporter; import org.apache.sysml.runtime.matrix.SortMR; import org.apache.sysml.runtime.util.MapReduceTool; @SuppressWarnings("rawtypes") public class ValueSortReducer<K extends WritableComparable, V extends Writable> extends MapReduceBase implements Reducer<K, V, K, V> { private String taskID=null; private boolean valueIsWeight=false; private long count=0; @Override public void configure(JobConf job) { taskID=MapReduceTool.getUniqueKeyPerTask(job, false); valueIsWeight=job.getBoolean(SortMR.VALUE_IS_WEIGHT, false); } @Override public void reduce(K key, Iterator<V> values, OutputCollector<K, V> out, Reporter report) throws IOException { int sum=0; while(values.hasNext()) { V value=values.next(); out.collect(key, value); if(valueIsWeight) sum+=((IntWritable)value).get(); else sum++; } count+=sum; report.incrCounter(SortMR.NUM_VALUES_PREFIX, taskID, sum); } }
31.666667
102
0.759268
9cff7047efefad9ded093b59088d6114cdfe98f5
8,116
/* * Copyright © 2020 Cask Data, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package io.cdap.cdap.etl.spark; import io.cdap.cdap.api.Admin; import io.cdap.cdap.api.Transactional; import io.cdap.cdap.api.data.DatasetContext; import io.cdap.cdap.api.macro.MacroEvaluator; import io.cdap.cdap.api.metrics.Metrics; import io.cdap.cdap.api.plugin.PluginContext; import io.cdap.cdap.etl.api.SplitterTransform; import io.cdap.cdap.etl.api.Transform; import io.cdap.cdap.etl.api.batch.BatchAggregator; import io.cdap.cdap.etl.api.batch.BatchConfigurable; import io.cdap.cdap.etl.api.batch.BatchJoiner; import io.cdap.cdap.etl.api.batch.BatchSinkContext; import io.cdap.cdap.etl.api.batch.SparkCompute; import io.cdap.cdap.etl.api.batch.SparkPluginContext; import io.cdap.cdap.etl.api.batch.SparkSink; import io.cdap.cdap.etl.api.streaming.StreamingSource; import io.cdap.cdap.etl.batch.DefaultAggregatorContext; import io.cdap.cdap.etl.batch.DefaultJoinerContext; import io.cdap.cdap.etl.batch.PipelinePluginInstantiator; import io.cdap.cdap.etl.common.PhaseSpec; import io.cdap.cdap.etl.common.PipelineRuntime; import io.cdap.cdap.etl.common.submit.AggregatorContextProvider; import io.cdap.cdap.etl.common.submit.ContextProvider; import io.cdap.cdap.etl.common.submit.Finisher; import io.cdap.cdap.etl.common.submit.JoinerContextProvider; import io.cdap.cdap.etl.common.submit.PipelinePhasePreparer; import io.cdap.cdap.etl.common.submit.SubmitterPlugin; import io.cdap.cdap.etl.proto.v2.spec.StageSpec; import io.cdap.cdap.etl.spark.batch.BasicSparkPluginContext; import io.cdap.cdap.etl.spark.batch.SparkBatchSinkContext; import io.cdap.cdap.etl.spark.batch.SparkBatchSinkFactory; import io.cdap.cdap.etl.spark.batch.SparkBatchSourceFactory; import org.apache.tephra.TransactionFailureException; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Nullable; /** * Abstract preparer for spark related pipelines */ public abstract class AbstractSparkPreparer extends PipelinePhasePreparer { protected Map<String, Integer> stagePartitions; protected SparkBatchSourceFactory sourceFactory; protected SparkBatchSinkFactory sinkFactory; private final Admin admin; private final Transactional transactional; public AbstractSparkPreparer(PluginContext pluginContext, Metrics metrics, MacroEvaluator macroEvaluator, PipelineRuntime pipelineRuntime, Admin admin, Transactional transactional) { super(pluginContext, metrics, macroEvaluator, pipelineRuntime); this.admin = admin; this.transactional = transactional; } @Override public List<Finisher> prepare(PhaseSpec phaseSpec) throws TransactionFailureException, InstantiationException, IOException { stageOperations = new HashMap<>(); stagePartitions = new HashMap<>(); sourceFactory = new SparkBatchSourceFactory(); sinkFactory = new SparkBatchSinkFactory(); return super.prepare(phaseSpec); } @Nullable @Override protected SubmitterPlugin create(PipelinePluginInstantiator pluginInstantiator, StageSpec stageSpec) throws InstantiationException { String stageName = stageSpec.getName(); if (SparkSink.PLUGIN_TYPE.equals(stageSpec.getPluginType())) { BatchConfigurable<SparkPluginContext> sparkSink = pluginInstantiator.newPluginInstance(stageName, macroEvaluator); ContextProvider<BasicSparkPluginContext> contextProvider = dsContext -> getSparkPluginContext(dsContext, stageSpec); return new SubmitterPlugin<>(stageName, transactional, sparkSink, contextProvider, ctx -> stageOperations.put(stageName, ctx.getFieldOperations())); } if (SparkCompute.PLUGIN_TYPE.equals(stageSpec.getPluginType())) { SparkCompute<?, ?> compute = pluginInstantiator.newPluginInstance(stageName, macroEvaluator); ContextProvider<BasicSparkPluginContext> contextProvider = dsContext -> getSparkPluginContext(dsContext, stageSpec); return new SubmitterPlugin<>(stageName, transactional, compute, contextProvider, ctx -> stageOperations.put(stageName, ctx.getFieldOperations())); } if (StreamingSource.PLUGIN_TYPE.equals(stageSpec.getPluginType())) { return createStreamingSource(pluginInstantiator, stageSpec); } return null; } @Override protected SubmitterPlugin createTransform(Transform<?, ?> transform, StageSpec stageSpec) { String stageName = stageSpec.getName(); ContextProvider<SparkSubmitterContext> contextProvider = dsContext -> getSparkSubmitterContext(dsContext, stageSpec); return new SubmitterPlugin<>(stageName, transactional, transform, contextProvider, ctx -> stageOperations.put(stageName, ctx.getFieldOperations())); } @Override protected SubmitterPlugin createSplitterTransform(SplitterTransform<?, ?> splitterTransform, StageSpec stageSpec) { String stageName = stageSpec.getName(); ContextProvider<SparkSubmitterContext> contextProvider = dsContext -> getSparkSubmitterContext(dsContext, stageSpec); return new SubmitterPlugin<>(stageName, transactional, splitterTransform, contextProvider, ctx -> stageOperations.put(stageName, ctx.getFieldOperations())); } @Override protected SubmitterPlugin createSink(BatchConfigurable<BatchSinkContext> batchSink, StageSpec stageSpec) { String stageName = stageSpec.getName(); ContextProvider<SparkBatchSinkContext> contextProvider = dsContext -> getSparkBatchSinkContext(dsContext, stageSpec); return new SubmitterPlugin<>(stageName, transactional, batchSink, contextProvider, ctx -> stageOperations.put(stageName, ctx.getFieldOperations())); } @Override protected SubmitterPlugin createAggregator(BatchAggregator<?, ?, ?> aggregator, StageSpec stageSpec) { String stageName = stageSpec.getName(); ContextProvider<DefaultAggregatorContext> contextProvider = new AggregatorContextProvider(pipelineRuntime, stageSpec, admin); return new SubmitterPlugin<>(stageName, transactional, aggregator, contextProvider, ctx -> stageOperations.put(stageName, ctx.getFieldOperations())); } @Override protected SubmitterPlugin createJoiner(BatchJoiner<?, ?, ?> batchJoiner, StageSpec stageSpec) { String stageName = stageSpec.getName(); ContextProvider<DefaultJoinerContext> contextProvider = new JoinerContextProvider(pipelineRuntime, stageSpec, admin); return new SubmitterPlugin<>(stageName, transactional, batchJoiner, contextProvider, sparkJoinerContext -> { stagePartitions.put(stageName, sparkJoinerContext.getNumPartitions()); stageOperations.put(stageName, sparkJoinerContext.getFieldOperations()); }); } protected abstract SparkBatchSinkContext getSparkBatchSinkContext(DatasetContext dsContext, StageSpec stageSpec); protected abstract BasicSparkPluginContext getSparkPluginContext(DatasetContext dsContext, StageSpec stageSpec); protected abstract SparkSubmitterContext getSparkSubmitterContext(DatasetContext dsContext, StageSpec stageSpec); // only streaming pipeline can create streaming source @Nullable protected SubmitterPlugin createStreamingSource(PipelinePluginInstantiator pluginInstantiator, StageSpec stageSpec) throws InstantiationException { return null; } }
46.913295
120
0.759364
f6b785c23f0bad8d8fcfcd63e566320018f03e5a
643
package org.cmdb.dto; import java.io.Serializable; import lombok.Getter; import lombok.Setter; /** * DTO to customize the returned message * * @author lishen */ @Getter @Setter public class RestResult<T> implements Serializable { public static final int OK = 0; public static final String M_OK = "成功"; public static <T> RestResult OK(T data) { RestResult restResult = new RestResult(); restResult.setErrorMessage(M_OK); restResult.setErrorCode(OK); restResult.setData(data); return restResult; } private int errorCode; private String errorMessage; private T data; }
20.741935
52
0.681182
f69256fc98d225bcad87ddd27ffd4060580c315e
218
package com.gitee.sop.adminserver.service; import org.springframework.stereotype.Service; /** * @author tanghc */ @Service public class ConfigRouteBaseService { public void updateConfigRouteBase() { } }
13.625
46
0.733945
35ebaaa038ef80a93efd8a66c9d5517d43231f9d
615
package reflectDemo; import commondata.People; import java.lang.reflect.Constructor; /** * @author bin.yu * @create 2018-08-24 15:23 **/ public class ReflectDemo { public static void main(String[] args) { try { Class<?> clz = Class.forName("commondata.People"); Constructor<?> constructor = clz.getConstructor(String.class, int.class); People people = (People) constructor.newInstance("张三", 34); System.out.println(people.getName()+": "+people.getAge()); } catch (Exception e) { throw new RuntimeException(e); } } }
25.625
85
0.609756
5ad0412b9c8d062dcbef3ddfd3fe85229d22df15
6,291
/* * 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. */ /* $Id: PDFArray.java 1661887 2015-02-24 11:23:44Z ssteiner $ */ package org.apache.fop.pdf; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.apache.commons.io.output.CountingOutputStream; /** * Class representing an array object. */ public class PDFArray extends PDFObject { /** * List holding the values of this array */ protected List<Object> values = new java.util.ArrayList<Object>(); /** * Create a new, empty array object * @param parent the array's parent if any */ public PDFArray(PDFObject parent) { /* generic creation of PDF object */ super(parent); } /** * Create a new, empty array object with no parent. */ public PDFArray() { this((PDFObject) null); } /** * Create an array object. * @param parent the array's parent if any * @param values the actual array wrapped by this object */ public PDFArray(PDFObject parent, int[] values) { /* generic creation of PDF object */ super(parent); for (int i = 0, c = values.length; i < c; i++) { this.values.add(Integer.valueOf(values[i])); } } /** * Create an array object. * @param parent the array's parent if any * @param values the actual array wrapped by this object */ public PDFArray(PDFObject parent, double[] values) { /* generic creation of PDF object */ super(parent); for (int i = 0, c = values.length; i < c; i++) { this.values.add(new Double(values[i])); } } /** * Create an array object. * @param parent the array's parent if any * @param values the actual values wrapped by this object */ public PDFArray(PDFObject parent, List<?> values) { /* generic creation of PDF object */ super(parent); this.values.addAll(values); } /** * Creates an array object made of the given elements. * * @param elements the array content */ public PDFArray(Object... elements) { this(null, elements); } /** * Creates an array object made of the given elements. * * @param elements the array content */ public PDFArray(List<?> elements) { this(null, elements); } /** * Create the array object * @param parent the array's parent if any * @param values the actual array wrapped by this object */ public PDFArray(PDFObject parent, Object[] values) { /* generic creation of PDF object */ super(parent); for (int i = 0, c = values.length; i < c; i++) { this.values.add(values[i]); } } /** * Indicates whether the given object exists in the array. * @param obj the object to look for * @return true if obj is contained */ public boolean contains(Object obj) { return this.values.contains(obj); } /** * Returns the length of the array * @return the length of the array */ public int length() { return this.values.size(); } /** * Sets an entry at a given location. * @param index the index of the value to set * @param obj the new value */ public void set(int index, Object obj) { this.values.set(index, obj); } /** * Sets an entry at a given location. * @param index the index of the value to set * @param value the new value */ public void set(int index, double value) { this.values.set(index, new Double(value)); } /** * Gets an entry at a given location. * @param index the index of the value to set * @return the requested value */ public Object get(int index) { return this.values.get(index); } /** * Adds a new value to the array. * @param obj the value */ public void add(Object obj) { if (obj instanceof PDFObject) { PDFObject pdfObj = (PDFObject)obj; if (!pdfObj.hasObjectNumber()) { pdfObj.setParent(this); } } this.values.add(obj); } /** * Adds a new value to the array. * @param value the value */ public void add(double value) { this.values.add(new Double(value)); } /** * Clears the PDF array. */ public void clear() { this.values.clear(); } /** {@inheritDoc} */ @Override public int output(OutputStream stream) throws IOException { CountingOutputStream cout = new CountingOutputStream(stream); StringBuilder textBuffer = new StringBuilder(64); textBuffer.append('['); for (int i = 0; i < values.size(); i++) { if (i > 0) { textBuffer.append(' '); } Object obj = this.values.get(i); formatObject(obj, cout, textBuffer); } textBuffer.append(']'); PDFDocument.flushTextBuffer(textBuffer, cout); return cout.getCount(); } @Override public void getChildren(Set<PDFObject> children) { List<Object> contents = new ArrayList<Object>(); for (Object c : values) { if (!(c instanceof PDFReference)) { contents.add(c); } } PDFDictionary.getChildren(contents, children); } }
27.471616
75
0.593228
2903968c8f9fce9bb74013097d0aade5d65f7be8
658
package com.netease.nim.demo.login; import com.netease.nim.demo.DemoCache; import com.netease.nim.demo.chatroom.helper.ChatRoomHelper; import com.netease.nim.uikit.LoginSyncDataStatusObserver; import com.netease.nim.uikit.NimUIKit; import com.netease.nim.uikit.common.ui.drop.DropManager; /** * 注销帮助类 * Created by huangjun on 2015/10/8. */ public class LogoutHelper { public static void logout() { // 清理缓存&注销监听&清除状态 NimUIKit.clearCache(); ChatRoomHelper.logout(); DemoCache.clear(); LoginSyncDataStatusObserver.getInstance().reset(); DropManager.getInstance().destroy(); } }
28.608696
60
0.68997
3b1f4b2df578f73a14ec97443c1d885ea4939664
9,682
package org.contentmine.ami.lookups; import java.util.List; import nu.xom.Element; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; import org.eclipse.jetty.util.log.Log; import org.contentmine.eucl.xml.XMLUtil; /** * analyzes the XML returned by a Genbank search. * * @author pm286 * */ public class GenbankResultAnalyzer { private static final Logger LOG = LogManager.getLogger(GenbankResultAnalyzer.class); public final static String GBSEQ_TAXON_XPATH = "//GBSet/GBSeq/GBSeq_feature-table/GBFeature/GBFeature_quals/GBQualifier/GBQualifier_value[starts-with(.,'taxon:')]"; public final static String GBSEQ_ORGANISM_XPATH = "//GBSet/GBSeq/GBSeq_organism"; public final static String ESEARCH_ID_XPATH = "//eSearchResult/IdList/Id"; private Element gbseqElement; private Element taxonomyElement; public GenbankResultAnalyzer() { } /** GBSet> <GBSeq> <GBSeq_locus>EU379932</GBSeq_locus> <GBSeq_length>5066</GBSeq_length> <GBSeq_strandedness>double</GBSeq_strandedness> <GBSeq_moltype>DNA</GBSeq_moltype> <GBSeq_topology>linear</GBSeq_topology> <GBSeq_division>BCT</GBSeq_division> <GBSeq_update-date>05-MAY-2009</GBSeq_update-date> <GBSeq_create-date>24-FEB-2008</GBSeq_create-date> <GBSeq_definition>Synergistes sp. W5455 16S ribosomal RNA gene, 16S-23S ribosomal RNA intergenic spacer, 23S ribosomal RNA gene, 23S-5S ribosomal RNA intergenic spacer, and 5S ribosomal RNA gene, complete sequence</GBSeq_definition> <GBSeq_primary-accession>EU379932</GBSeq_primary-accession> <GBSeq_accession-version>EU379932.1</GBSeq_accession-version> <GBSeq_other-seqids> <GBSeqid>gb|EU379932.1|</GBSeqid> <GBSeqid>gi|167996909</GBSeqid> </GBSeq_other-seqids> <GBSeq_source>Pyramidobacter piscolens W5455</GBSeq_source> <GBSeq_organism>Pyramidobacter piscolens W5455</GBSeq_organism> <GBSeq_taxonomy>Bacteria; Synergistetes; Synergistia; Synergistales; Synergistaceae; Pyramidobacter</GBSeq_taxonomy> <GBSeq_references> <GBReference> <GBReference_reference>1</GBReference_reference> <GBReference_position>1..5066</GBReference_position> <GBReference_authors> <GBAuthor>Downes,J.</GBAuthor> <GBAuthor>Vartoukian,S.R.</GBAuthor> <GBAuthor>Dewhirst,F.E.</GBAuthor> <GBAuthor>Izard,J.</GBAuthor> <GBAuthor>Chen,T.</GBAuthor> <GBAuthor>Yu,W.H.</GBAuthor> <GBAuthor>Sutcliffe,I.C.</GBAuthor> <GBAuthor>Wade,W.G.</GBAuthor> </GBReference_authors> <GBReference_title>Pyramidobacter piscolens gen. nov., sp. nov., a member of the phylum 'Synergistetes' isolated from the human oral cavity</GBReference_title> <GBReference_journal>Int. J. Syst. Evol. Microbiol. 59 (PT 5), 972-980 (2009)</GBReference_journal> <GBReference_xref> <GBXref> <GBXref_dbname>doi</GBXref_dbname> <GBXref_id>10.1099/ijs.0.000364-0</GBXref_id> </GBXref> </GBReference_xref> <GBReference_pubmed>19406777</GBReference_pubmed> </GBReference> <GBReference> <GBReference_reference>2</GBReference_reference> <GBReference_position>1..5066</GBReference_position> <GBReference_authors> <GBAuthor>Dewhirst,F.E.</GBAuthor> </GBReference_authors> <GBReference_title>Direct Submission</GBReference_title> <GBReference_journal>Submitted (09-JAN-2008) Molecular Genetics, The Forsyth Institute, 140 The Fenway, Boston, MA 02115, USA</GBReference_journal> </GBReference> </GBSeq_references> <GBSeq_feature-table> <GBFeature> <GBFeature_key>source</GBFeature_key> <GBFeature_location>1..5066</GBFeature_location> <GBFeature_intervals> <GBInterval> <GBInterval_from>1</GBInterval_from> <GBInterval_to>5066</GBInterval_to> <GBInterval_accession>EU379932.1</GBInterval_accession> </GBInterval> </GBFeature_intervals> <GBFeature_quals> <GBQualifier> <GBQualifier_name>organism</GBQualifier_name> <GBQualifier_value>Pyramidobacter piscolens W5455</GBQualifier_value> </GBQualifier> <GBQualifier> <GBQualifier_name>mol_type</GBQualifier_name> <GBQualifier_value>genomic DNA</GBQualifier_value> </GBQualifier> <GBQualifier> <GBQualifier_name>isolate</GBQualifier_name> <GBQualifier_value>W5455</GBQualifier_value> </GBQualifier> <GBQualifier> <GBQualifier_name>db_xref</GBQualifier_name> <GBQualifier_value>taxon:352165</GBQualifier_value> </GBQualifier> </GBFeature_quals> </GBFeature> <GBFeature> <GBFeature_key>rRNA</GBFeature_key> <GBFeature_location>75..1596</GBFeature_location> <GBFeature_intervals> <GBInterval> <GBInterval_from>75</GBInterval_from> <GBInterval_to>1596</GBInterval_to> <GBInterval_accession>EU379932.1</GBInterval_accession> </GBInterval> </GBFeature_intervals> <GBFeature_quals> <GBQualifier> <GBQualifier_name>product</GBQualifier_name> <GBQualifier_value>16S ribosomal RNA</GBQualifier_value> </GBQualifier> </GBFeature_quals> </GBFeature> <GBFeature> <GBFeature_key>misc_RNA</GBFeature_key> <GBFeature_location>1597..1844</GBFeature_location> <GBFeature_intervals> <GBInterval> <GBInterval_from>1597</GBInterval_from> <GBInterval_to>1844</GBInterval_to> <GBInterval_accession>EU379932.1</GBInterval_accession> </GBInterval> </GBFeature_intervals> <GBFeature_quals> <GBQualifier> <GBQualifier_name>product</GBQualifier_name> <GBQualifier_value>16S-23S ribosomal RNA intergenic spacer</GBQualifier_value> </GBQualifier> </GBFeature_quals> </GBFeature> <GBFeature> <GBFeature_key>rRNA</GBFeature_key> <GBFeature_location>1845..4818</GBFeature_location> <GBFeature_intervals> <GBInterval> <GBInterval_from>1845</GBInterval_from> <GBInterval_to>4818</GBInterval_to> <GBInterval_accession>EU379932.1</GBInterval_accession> </GBInterval> </GBFeature_intervals> <GBFeature_quals> <GBQualifier> <GBQualifier_name>product</GBQualifier_name> <GBQualifier_value>23S ribosomal RNA</GBQualifier_value> </GBQualifier> </GBFeature_quals> </GBFeature> <GBFeature> <GBFeature_key>misc_RNA</GBFeature_key> <GBFeature_location>4819..4991</GBFeature_location> <GBFeature_intervals> <GBInterval> <GBInterval_from>4819</GBInterval_from> <GBInterval_to>4991</GBInterval_to> <GBInterval_accession>EU379932.1</GBInterval_accession> </GBInterval> </GBFeature_intervals> <GBFeature_quals> <GBQualifier> <GBQualifier_name>product</GBQualifier_name> <GBQualifier_value>23S-5S ribosomal RNA intergenic spacer</GBQualifier_value> </GBQualifier> </GBFeature_quals> </GBFeature> <GBFeature> <GBFeature_key>rRNA</GBFeature_key> <GBFeature_location>4992..5066</GBFeature_location> <GBFeature_intervals> <GBInterval> <GBInterval_from>4992</GBInterval_from> <GBInterval_to>5066</GBInterval_to> <GBInterval_accession>EU379932.1</GBInterval_accession> </GBInterval> </GBFeature_intervals> <GBFeature_quals> <GBQualifier> <GBQualifier_name>product</GBQualifier_name> <GBQualifier_value>5S ribosomal RNA</GBQualifier_value> </GBQualifier> </GBFeature_quals> </GBFeature> </GBSeq_feature-table> <GBSeq_sequence>taccttgacaagag...cacgcgccgatggt</GBSeq_sequence> </GBSeq> </GBSet> * @param gbseqXML */ public void readGBSeq(String gbseqXML) { gbseqElement = XMLUtil.stripDTDAndParse(gbseqXML); } public String getTaxonFromGBSeq() { String taxon = null; if (gbseqElement != null) { List<Element> taxonElements = XMLUtil.getQueryElements(gbseqElement, GBSEQ_TAXON_XPATH); taxon = taxonElements.size() != 1 ? null : taxonElements.get(0).getValue(); } return taxon; } public String getOrganismFromGBSeq() { String organism = null; if (gbseqElement != null) { List<Element> organismElements = XMLUtil.getQueryElements(gbseqElement, GBSEQ_ORGANISM_XPATH); String org = organismElements.size() != 1 ? null : organismElements.get(0).getValue(); // only take first two words if (org != null) { String[] parts = org.split("\\s+"); organism = parts.length == 1 ? parts[0] : parts[0]+" "+parts[1]; } } return organism; } /** taxon search by name in taxonomy db <eSearchResult> <Count>1</Count> <RetMax>1</RetMax> <RetStart>0</RetStart> <IdList> <Id>638849</Id> </IdList> <TranslationSet /> <TranslationStack> <TermSet> <Term>Pyramidobacter piscolens[All Names]</Term> <Field>All Names</Field> <Count>1</Count> <Explode>N</Explode> </TermSet> <OP>GROUP</OP> </TranslationStack> <QueryTranslation>Pyramidobacter piscolens[All Names]</QueryTranslation> </eSearchResult> * @param taxonomyXML */ public void readEsearch(String taxonomyXML) { taxonomyElement = XMLUtil.stripDTDAndParse(taxonomyXML); } public String getIdFromEsearch() { String id = null; if (taxonomyElement != null) { List<Element> idElements = XMLUtil.getQueryElements(taxonomyElement, ESEARCH_ID_XPATH); id = idElements.size() != 1 ? null : idElements.get(0).getValue(); } return id; } }
35.335766
234
0.697377
03e5a2967f690128c2d5b19b92b6590ef82d9fba
2,038
//package com.hitesh_sahu.retailapp.domain.mock; // //import android.content.Context; // //import com.android.volley.AuthFailureError; //import com.android.volley.Cache; //import com.android.volley.Request; //import com.android.volley.RequestQueue; //import com.android.volley.toolbox.BasicNetwork; //import com.android.volley.toolbox.NoCache; // ////To use FakeHttpStack, you just have to pass it to your RequestQueue. I override RequestQueue too. // //public class FakeRequestQueue extends RequestQueue { // public FakeRequestQueue(Context context) { // super(new NoCache(), new BasicNetwork(new FakeHttpStack(context))); // start(); // } // // @Override // public void start() { // System.out.println("request start"); // super.start(); // } // // @Override // public void stop() { // System.out.println("request stop"); // super.stop(); // } // // @Override // public Cache getCache() { // System.out.println("request start"); // return super.getCache(); // } // // @Override // public void cancelAll(RequestFilter filter) { // System.out.println("Request cancel with filter " + filter); // super.cancelAll(filter); // } // // @Override // public void cancelAll(Object tag) { // System.out.println("Request cancel with tag " + tag); // super.cancelAll(tag); // } // // @Override // public Request add(Request request) { // System.out.println("Note: FakeRequestQueue is used"); // System.out.println("New request " + request.getUrl() // + " is added with priority " + request.getPriority()); // try { // if (request.getBody() == null) { // System.out.println("body is null"); // } else { // System.out.println("Body:" + new String(request.getBody())); // } // } catch (AuthFailureError e) { // // cannot do anything // } // return super.add(request); // } //}
30.41791
101
0.587831
16063ce062dc8176f5f1c49547d21dc53d34a003
5,922
/* * Copyright ConsenSys AG. * * 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. * * SPDX-License-Identifier: Apache-2.0 */ package org.enterchain.enter.controller; import org.enterchain.enter.config.CliqueConfigOptions; import org.enterchain.enter.consensus.clique.CliqueBlockInterface; import org.enterchain.enter.consensus.clique.CliqueContext; import org.enterchain.enter.consensus.clique.CliqueMiningTracker; import org.enterchain.enter.consensus.clique.CliqueProtocolSchedule; import org.enterchain.enter.consensus.clique.blockcreation.CliqueBlockScheduler; import org.enterchain.enter.consensus.clique.blockcreation.CliqueMinerExecutor; import org.enterchain.enter.consensus.clique.blockcreation.CliqueMiningCoordinator; import org.enterchain.enter.consensus.clique.jsonrpc.CliqueJsonRpcMethods; import org.enterchain.enter.consensus.common.BlockInterface; import org.enterchain.enter.consensus.common.EpochManager; import org.enterchain.enter.consensus.common.VoteProposer; import org.enterchain.enter.consensus.common.VoteTallyCache; import org.enterchain.enter.consensus.common.VoteTallyUpdater; import org.enterchain.enter.ethereum.ProtocolContext; import org.enterchain.enter.ethereum.api.jsonrpc.methods.JsonRpcMethods; import org.enterchain.enter.ethereum.blockcreation.MiningCoordinator; import org.enterchain.enter.ethereum.chain.Blockchain; import org.enterchain.enter.ethereum.core.Address; import org.enterchain.enter.ethereum.core.BlockHeader; import org.enterchain.enter.ethereum.core.MiningParameters; import org.enterchain.enter.ethereum.core.Util; import org.enterchain.enter.ethereum.eth.manager.EthProtocolManager; import org.enterchain.enter.ethereum.eth.sync.state.SyncState; import org.enterchain.enter.ethereum.eth.transactions.TransactionPool; import org.enterchain.enter.ethereum.mainnet.ProtocolSchedule; import org.enterchain.enter.ethereum.worldstate.WorldStateArchive; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class CliqueBesuControllerBuilder extends BesuControllerBuilder { private static final Logger LOG = LogManager.getLogger(); private Address localAddress; private EpochManager epochManager; private long secondsBetweenBlocks; private final BlockInterface blockInterface = new CliqueBlockInterface(); @Override protected void prepForBuild() { localAddress = Util.publicKeyToAddress(nodeKey.getPublicKey()); final CliqueConfigOptions cliqueConfig = genesisConfig.getConfigOptions(genesisConfigOverrides).getCliqueConfigOptions(); final long blocksPerEpoch = cliqueConfig.getEpochLength(); secondsBetweenBlocks = cliqueConfig.getBlockPeriodSeconds(); epochManager = new EpochManager(blocksPerEpoch); } @Override protected JsonRpcMethods createAdditionalJsonRpcMethodFactory( final ProtocolContext protocolContext) { return new CliqueJsonRpcMethods(protocolContext); } @Override protected MiningCoordinator createMiningCoordinator( final ProtocolSchedule protocolSchedule, final ProtocolContext protocolContext, final TransactionPool transactionPool, final MiningParameters miningParameters, final SyncState syncState, final EthProtocolManager ethProtocolManager) { final CliqueMinerExecutor miningExecutor = new CliqueMinerExecutor( protocolContext, protocolSchedule, transactionPool.getPendingTransactions(), nodeKey, miningParameters, new CliqueBlockScheduler( clock, protocolContext.getConsensusState(CliqueContext.class).getVoteTallyCache(), localAddress, secondsBetweenBlocks), epochManager, gasLimitCalculator); final CliqueMiningCoordinator miningCoordinator = new CliqueMiningCoordinator( protocolContext.getBlockchain(), miningExecutor, syncState, new CliqueMiningTracker(localAddress, protocolContext)); miningCoordinator.addMinedBlockObserver(ethProtocolManager); // Clique mining is implicitly enabled. miningCoordinator.enable(); return miningCoordinator; } @Override protected ProtocolSchedule createProtocolSchedule() { return CliqueProtocolSchedule.create( genesisConfig.getConfigOptions(genesisConfigOverrides), nodeKey, privacyParameters, isRevertReasonEnabled); } @Override protected void validateContext(final ProtocolContext context) { final BlockHeader genesisBlockHeader = context.getBlockchain().getGenesisBlock().getHeader(); if (blockInterface.validatorsInBlock(genesisBlockHeader).isEmpty()) { LOG.warn("Genesis block contains no signers - chain will not progress."); } } @Override protected PluginServiceFactory createAdditionalPluginServices(final Blockchain blockchain) { return new CliqueQueryPluginServiceFactory(blockchain, nodeKey); } @Override protected CliqueContext createConsensusContext( final Blockchain blockchain, final WorldStateArchive worldStateArchive) { return new CliqueContext( new VoteTallyCache( blockchain, new VoteTallyUpdater(epochManager, blockInterface), epochManager, blockInterface), new VoteProposer(), epochManager, blockInterface); } }
40.561644
118
0.772712
d771c8244014e2b42512fed64e346d1d718e797a
3,789
package org.ddouglascarr.integration.query.repositories; import org.ddouglascarr.LiquidcanonApplication; import org.ddouglascarr.exceptions.ItemNotFoundException; import org.ddouglascarr.query.models.Area; import org.ddouglascarr.query.repositories.AreaRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.jdbc.Sql; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; import java.util.List; import static org.junit.Assert.*; import static org.ddouglascarr.testutils.IntegrationTestConsts.*; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(LiquidcanonApplication.class) @TestPropertySource(locations = "classpath:test.properties") @Transactional @Sql( executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD, scripts = { "classpath:sql/test-world.sql" } ) public class AreaRepositoryTests { @Autowired private AreaRepository areaRepository; @Test(expected = ItemNotFoundException.class) public void findOneShouldThrowIfDoesNotExist() throws Exception { areaRepository.findOne(NON_EXISTANT_AREA_ID); } @Test public void findOneShouldReturnArea() throws Exception { Area area = areaRepository.findOne(MARS_STATUTES_AREA_ID); assertEquals(MARS_STATUTES_AREA_ID, area.getId()); } @Test public void findByUnitIdShouldReturnListOfAreasForEarth() throws Exception { List<Area> areas = areaRepository.findByUnitId(EARTH_MOON_FEDERATION_UNIT_ID); assertEquals(3, areas.size()); Area statutesArea = areas.stream() .filter(a -> EARTH_MOON_FEDERATION_STATUTES_AREA_ID.equals(a.getId())) .findFirst().get(); assertNotNull(statutesArea); assertEquals(EARTH_MOON_FEDERATION_STATUTES_AREA_ID, statutesArea.getId()); Area spaceVehiclesArea = areas.stream() .filter(a -> EARTH_SPACE_VEHICLES_AREA_ID.equals(a.getId())) .findFirst().get(); assertNotNull(spaceVehiclesArea); } @Test public void findByUnitIdShouldReturnListOfAreasForMars() throws Exception { List<Area> areas = areaRepository.findByUnitId(MARS_UNIT_ID); assertEquals(4, areas.size()); Area mineralResourcesArea = areas.stream() .filter(a -> MARS_MINERAL_RESOURCES_AREA_ID.equals(a.getId())) .findFirst().get(); assertNotNull(mineralResourcesArea); Area statutesArea = areas.stream() .filter(a -> MARS_STATUTES_AREA_ID.equals(a.getId())) .findFirst().get(); assertNotNull(statutesArea); } @Test(expected = ItemNotFoundException.class) public void findOneByUnitIdAndIdShouldThrowIfNotPartOfUnit() throws Exception { areaRepository.findOneByUnitIdAndId(EARTH_MOON_FEDERATION_UNIT_ID, MARS_STATUTES_AREA_ID); } @Test(expected = ItemNotFoundException.class) public void findOneByUnitIdAndIDSHouldThrowIfDoesNotExist() throws Exception { areaRepository.findOneByUnitIdAndId(EARTH_MOON_FEDERATION_UNIT_ID, NON_EXISTANT_AREA_ID); } @Test public void findOneByUnitIdAndIDShouldReturnArea() throws Exception { Area area = areaRepository.findOneByUnitIdAndId(EARTH_MOON_FEDERATION_UNIT_ID, EARTH_MOON_FEDERATION_STATUTES_AREA_ID); assertNotNull(area); assertEquals(EARTH_MOON_FEDERATION_STATUTES_AREA_ID, area.getId()); } }
35.083333
127
0.73555
2a4fed1f886fd7482d8ed3d3a1149d7f3fd36c22
319
package slack.android.api.webapi.response; import slack.android.api.models.Channel; public class ChannelResponse extends BaseResponse { private Channel channel; public Channel getChannel() { return channel; } public void setChannel(Channel channel) { this.channel = channel; } }
19.9375
51
0.702194
841998996a52b7938a3e09dc21d0a0c64bb01e73
482
package com.brandon.apps.groupstudio.models; /** * Created by Brandon on 11/27/2015. */ public class CalculationModel { public int CalculationId; public int CalculationTarget; public int CalculationStat; public String CalculationName; public CalculationModel(int id, int target, int stat, String name) { CalculationId = id; CalculationTarget = target; CalculationStat = stat; CalculationName = name; } }
25.368421
73
0.661826
7eb8947b4ab906c09765d493036f267bbdda1879
10,422
package com.example.rohanupponi.scribeapp; import android.content.Intent; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.firestore.FirebaseFirestore; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; public class PatientRegistration extends AppCompatActivity { public static final String TAG = "PatientRegistration"; private EditText nameField, emailField, addressField, cityField, zipField, passwordField, passwordConfirmField; private Spinner stateDropDown; private String name, email, address, city, sZip, password, passwordConfirm; private Map<String, Object> newPatient; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_patient_registration); Button patientRegisterButton = (Button) findViewById(R.id.new_patient_button); //====== SET UP DROPDOWN FOR STATE CHOICES ===========================================================================// stateDropDown = findViewById(R.id.new_patient_state_spinner); ArrayAdapter adapter = ArrayAdapter.createFromResource(PatientRegistration.this, R.array.states_array, R.layout.dropdown_layout ); adapter.setDropDownViewResource(R.layout.dropdown_layout); stateDropDown.setAdapter(adapter); patientRegisterButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { //============== SET EDIT FIELDS TO VIEWS TO COLLECT DATA ============================================================// nameField = findViewById(R.id.new_patient_name_field); emailField = findViewById(R.id.new_patient_email_field); addressField = findViewById(R.id.new_patient_address_field); cityField = findViewById(R.id.new_patient_city_field); zipField = findViewById(R.id.new_patient_zip_field); passwordField = findViewById(R.id.new_patient_password); passwordConfirmField = findViewById(R.id.new_patient_password_confirm); //====================================================================================================================// //============== COLLECT DATA FROM TEXT FIELDS =======================================================================// name = nameField.getText().toString().trim(); email = emailField.getText().toString().trim(); address = addressField.getText().toString().trim(); city = cityField.getText().toString().trim(); List<String> stateChoices = Arrays.asList(getResources().getStringArray(R.array.states_array)); State state = Utils.getState(stateChoices.indexOf(stateDropDown.getSelectedItem().toString())); sZip = zipField.getText().toString().trim(); password = passwordField.getText().toString().trim(); passwordConfirm = passwordConfirmField.getText().toString().trim(); //====================================================================================================================// //============== IF A FIELD IS EMPTY, YOU SHALL NOT PASS =============================================================// if (name.matches("") ||email.matches("") || address.matches("") || city.matches("") || sZip.matches("") || password.matches("") || passwordConfirm.matches("")) { Toast incompleteInfo = Toast.makeText(getApplicationContext(), "We are currently missing some information. Please be sure to fill in all fields.", Toast.LENGTH_LONG ); incompleteInfo.show(); return; } //====================================================================================================================// //============== IF PASSWORD ISN'T CONFIRMED PROPERLY, YOU SHALL NOT PASS ============================================// if (!password.equals(passwordConfirm)) { Toast test = Toast.makeText(getApplicationContext(), "Error: Passwords don't match. Please make sure to confirm correct password.", Toast.LENGTH_LONG ); test.show(); return; } //====================================================================================================================// //============== GENERATE NEW PATIENT FROM INPUT FIELD DATA ==========================================================// newPatient = new HashMap<>(); newPatient.put("name", name); newPatient.put("address-street", address); newPatient.put("address-city", city); newPatient.put("address-state", state); newPatient.put("address-zip", Integer.parseInt(sZip)); newPatient.put("primary-phone", ""); newPatient.put("gender", Gender.NONE); newPatient.put("date-of-birth", ""); newPatient.put("marital-status", MaritalStatus.NONE); newPatient.put("ethnicity", Ethnicity.NONE); newPatient.put("primary-insurance",""); newPatient.put("primary-policy",""); newPatient.put("primary-group", ""); newPatient.put("secondary-insurance",""); newPatient.put("secondary-policy",""); newPatient.put("secondary-group", ""); newPatient.put("employer", ""); newPatient.put("employer-address-street", ""); newPatient.put("employer-address-city", ""); newPatient.put("employer-address-state", State.NONE); newPatient.put("employer-address-zip",""); newPatient.put("primary-emergency-name", ""); newPatient.put("primary-emergency-phone", ""); newPatient.put("secondary-emergency-name", ""); newPatient.put("secondary-emergency-phone",""); newPatient.put("blood-type", BloodType.NONE); newPatient.put("prescriptions", ""); newPatient.put("vaccinations", ""); newPatient.put("lifestyle", ""); newPatient.put("allergies", ""); newPatient.put("family-history", ""); newPatient.put("surgical-history", ""); newPatient.put("conditions", ""); //====================================================================================================================// //============== REGISTER PATIENT CREDENTIALS ========================================================================// FirebaseAuth patientRegisterAuth = FirebaseAuth.getInstance(); patientRegisterAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(PatientRegistration.this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> register) { if (register.isSuccessful()) { FirebaseFirestore db = FirebaseFirestore.getInstance(); db.collection("patients").document(email).set(newPatient).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Log.d(PatientRegistration.TAG, "Successful registration of patient."); Toast successfulRegistration = Toast.makeText(getApplicationContext(), "Congratulations! You have now been registered.", Toast.LENGTH_LONG); successfulRegistration.show(); Intent redirectToPatientLogin = new Intent(getApplicationContext(), LoginPage.class); startActivity(redirectToPatientLogin); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.w(PatientRegistration.TAG, "Unsuccessful registration of patient."); Toast failedRegistration = Toast.makeText(getApplicationContext(), "Oops! Looks like we had some issues in setting up your account!", Toast.LENGTH_LONG); failedRegistration.show(); Intent redirectToPatientLogin = new Intent(getApplicationContext(), LoginPage.class); startActivity(redirectToPatientLogin); } }); } else { Toast test = Toast.makeText(getApplicationContext(), "Sorry! We experienced some issues in connectivity. Please check your connection and try again.", Toast.LENGTH_LONG); test.show(); } } }); //====================================================================================================================// } }); } }
54.565445
199
0.504606
e4856311db4f9619b949bcc48cc56d481a03a29b
383
package io.github.parj.getExternalIP; import java.util.Optional; /** * Main class for entry point */ public class App { public static void main(String[] args) { String port = Optional.ofNullable(System.getenv("port")).orElse("9998"); MainServer.getInstance() .startServer() .startReverseProxy(Integer.valueOf(port)); } }
21.277778
80
0.629243
69da0dfae6e52eb8cff40b3d731a13274bf8b086
2,066
package org.liballeg.android; import android.app.Activity; import android.content.Context; import android.content.ClipData; import android.content.ClipboardManager; import android.util.Log; class Clipboard { private static final String TAG = "Clipboard"; private Activity activity; private boolean clip_thread_done = false; private String clipdata; Clipboard(Activity activity) { this.activity = activity; } public boolean setText(String text) { final String ss = text; Runnable runnable = new Runnable() { public void run() { ClipboardManager clipboard = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText("allegro", ss); clipboard.setPrimaryClip(clip); clip_thread_done = true; }; }; activity.runOnUiThread(runnable); while (!clip_thread_done) ; clip_thread_done = false; return true; } public String getText() { Runnable runnable = new Runnable() { public void run() { ClipboardManager clipboard = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = clipboard.getPrimaryClip(); if (clip == null) { clipdata = null; } else { ClipData.Item item = clip.getItemAt(0); if (item == null) { clipdata = null; } else { String text = item.coerceToText(activity.getApplicationContext()).toString(); clipdata = text; } } clip_thread_done = true; } }; activity.runOnUiThread(runnable); while (!clip_thread_done); clip_thread_done = false; return clipdata; } boolean hasText() { /* Lazy implementation... */ return this.getText() != null; } } /* vim: set sts=3 sw=3 et: */
23.213483
95
0.57696
db7508cf2e361a0af6a6ae4f85dffdd28af0fc0c
1,407
package com.fo0.robot.utils; import java.text.SimpleDateFormat; import java.util.Date; /** * TODO: Add java.utils.logging or log4j as logger * * @author max * */ public class Logger { private static final String DATE_PATTERN = "yyyy-mm-dd HH:mm:ss.SSS"; public static FileLog log = null; public static void info(String message) { print("INFO", message); addToLog("INFO", message); } public static void error(String message) { print("ERROR", message); addToLog("ERROR", message); } public static void debug(String message) { if (CONSTANTS.DEBUG) { print("DEBUG", message); } addToLog("DEBUG", message); } private static void print(String prefix, String message) { //@formatter:off String msg = ""; if(CONSTANTS.DEBUG) { msg = String.format("%s %s [%s] - %s", new SimpleDateFormat(DATE_PATTERN).format(new Date()), prefix, StackTraceUtils.methodCaller(2), message); } else { msg = String.format("%s [%s] %s", new SimpleDateFormat(DATE_PATTERN).format(new Date()), prefix, message); } if (prefix.equals("ERROR")) { System.err.println(msg); } else { System.out.println(msg); } //@formatter:on } private static void addToLog(String level, String message) { if (log != null) { log.add(level, message); } } public static void activateFileLogging() { log = new FileLog(); info("Activated File-Logging to: 'robot.log'"); } }
22.333333
147
0.665956
7e0daf542aac3472dd6558c6c332d9a942da5c3f
5,025
package org.opensha.gem.GEM1.calc.gemHazardMaps; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import org.opensha.commons.data.function.ArbitrarilyDiscretizedFunc; import org.opensha.commons.param.AbstractParameter; import org.opensha.commons.param.impl.WarningDoubleParameter; import org.opensha.gem.GEM1.calc.gemHazardCalculator.GemComputeHazardLogicTree; import org.opensha.gem.GEM1.calc.gemLogicTree.gemLogicTreeImpl.gmpe.GemGmpe; import org.opensha.gem.GEM1.calc.gemLogicTree.gemLogicTreeImpl.gmpe.GemGmpe2; import org.opensha.gem.GEM1.commons.CalculationSettings; import org.opensha.sha.imr.ScalarIMR; import org.opensha.sha.imr.param.EqkRuptureParams.MagParam; import org.opensha.sha.imr.param.IntensityMeasureParams.PGA_Param; import org.opensha.sha.imr.param.PropagationEffectParams.AbstractDoublePropEffectParam; import org.opensha.sha.imr.param.PropagationEffectParams.PropagationEffectParameter; import org.opensha.sha.imr.param.PropagationEffectParams.WarningDoublePropagationEffectParameter; import org.opensha.sha.imr.param.SiteParams.Vs30_Param; import org.opensha.sha.util.TectonicRegionType; public class GemCalcSetup { private String inputDir; private String outputDir; private CalculationSettings calcSettings; private GemGmpe gemGmpeLT; /** * * @param inputDir relative path * @param outputDir */ public GemCalcSetup (String inputDir, String outputDir) { this.inputDir = inputDir; this.outputDir = outputDir; this.calcSettings = new CalculationSettings(); this.gemGmpeLT = new GemGmpe(); } /** * * @param fileName * @return */ public BufferedReader getInputBufferedReader(String fileName) { String myClass = '/'+getClass().getName().replace('.', '/')+".class"; URL myClassURL = getClass().getResource(myClass); String inputfile = this.inputDir+fileName; System.out.println(inputfile); if ("jar" == myClassURL.getProtocol()) { inputfile = inputfile.substring(inputfile.lastIndexOf("./")+1); } BufferedReader reader = new BufferedReader(new InputStreamReader(GemComputeHazardLogicTree.class.getResourceAsStream(inputfile))); return reader; } /** * * @param fileName * @return */ public String getOutputPath(String fileName) { String outPath = ""; // String myClass = '/'+getClass().getName().replace('.', '/')+".class"; URL myClassURL = getClass().getResource(myClass); if ("jar" == myClassURL.getProtocol()) { outPath = "./Out/"; } else { URL outURL = GemComputeHazardLogicTree.class.getResource(fileName); String path = outURL.getPath(); System.out.println(path); outPath = path.replaceAll("/GEM1/bin/","/GEM1/"); } return outPath; } /** * * @return */ public ArrayList<Double[]> setUpMDFilter() { ArrayList<Double[]> lst = new ArrayList<Double[]>(); double mmin = 5.0; double mmax = 7.0; double step = 0.2; HashMap<String, HashMap<TectonicRegionType, ScalarIMR>> map = gemGmpeLT.getGemLogicTree().getEBMap(); // ArbitrarilyDiscretizedFunc fun = new ArbitrarilyDiscretizedFunc(); Double[] dst = {1.0,10.0,25.0,45.0,70.0,100.0,140.0,190.0,240.0}; for (int i=0; i<dst.length; i++){ fun.set(dst[i],0.0); } for (String str: map.keySet()){ // Get Hash Map HashMap<TectonicRegionType, ScalarIMR> mapImr = map.get(str); // ScalarIMR imr = mapImr.get(TectonicRegionType.ACTIVE_SHALLOW); System.out.println(imr.getName()); // Set parameters ((WarningDoubleParameter)imr.getParameter(Vs30_Param.NAME)).setValueIgnoreWarning(760.0); imr.setIntensityMeasure(PGA_Param.NAME); // Iterator<AbstractParameter> iter = imr.getMeanIndependentParamsIterator(); String dstStr = ""; while (iter.hasNext()) { String strTmp = iter.next().getName(); if (strTmp.matches("Distance.*")) { System.out.println("-----"+strTmp); dstStr = strTmp; } } // double gmThres = 0.005; // double mTmp = mmin; while (mTmp <= mmax){ for (int i=0; i<dst.length; i++){ // Set magnitude ((WarningDoubleParameter)imr.getParameter(MagParam.NAME)).setValueIgnoreWarning(new Double(mTmp)); // Set distance ((AbstractDoublePropEffectParam)imr.getParameter(dstStr)). setValueIgnoreWarning(new Double(dst[i])); double val = Math.exp(imr.getMean() + 2.0*imr.getStdDev()); fun.set(dst[i],val); } double dstThres = 0.0; if (gmThres<fun.getMinY()){ dstThres = fun.getMaxX(); } else { dstThres = fun.getFirstInterpolatedX(gmThres); } System.out.printf("mag %6.2f dst %6.2f\n",mTmp,dstThres); mTmp += step; } } return lst; } /** * * @return */ public GemGmpe getGmpeLT(){ return this.gemGmpeLT; } /** * * @return */ public GemGmpe2 getGmpeLT111(){ return new GemGmpe2(); } /** * * @return */ public CalculationSettings getcalcSett(){ return this.calcSettings; } }
28.389831
132
0.702488
1d30f48fffa449b825ffabdb70d9e25a56658ebd
2,571
/* * 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.nutch.keymatch; import java.util.HashMap; import org.apache.hadoop.conf.Configuration; import org.apache.nutch.searcher.Query; import org.apache.nutch.util.NutchConfiguration; import junit.framework.TestCase; public class TestViewCountSorter extends TestCase { SimpleKeyMatcher km; Configuration conf; /* (non-Javadoc) * @see junit.framework.TestCase#setUp() */ protected void setUp() throws Exception { super.setUp(); conf=NutchConfiguration.create(); km=new SimpleKeyMatcher(conf); km.clear(); KeyMatch m=new KeyMatch("kw1","u1","t1",KeyMatch.TYPE_KEYWORD); km.addKeyMatch(m); m=new KeyMatch("kw1","u2","t2",KeyMatch.TYPE_KEYWORD); km.addKeyMatch(m); m=new KeyMatch("kw1","u3","t3",KeyMatch.TYPE_KEYWORD); km.addKeyMatch(m); ViewCountSorter vcs=new ViewCountSorter(); vcs.setNext(new CountFilter()); km.setFilter(vcs); } /* * Test method for 'org.apache.nutch.keymatch.ViewCountSorter.filter(List, Map)' */ public void testFilter() { KeyMatch m1,m2,m3; KeyMatch[] matches=getKeyMatchesForString("kw1"); m1=matches[0]; assertNotNull(m1); matches=getKeyMatchesForString("kw1"); m2=matches[0]; assertNotNull(m2); matches=getKeyMatchesForString("kw1"); m3=matches[0]; assertNotNull(m3); assertFalse(m1.equals(m2)); assertFalse(m2.equals(m3)); assertFalse(m1.equals(m3)); } private KeyMatch[] getKeyMatchesForString(String string) { Query q; HashMap context=new HashMap(); context.put(CountFilter.KEY_COUNT,"1"); try { q = Query.parse(string, conf); return km.getMatches(q,context); } catch (Exception e){ } return new KeyMatch[0]; } }
28.88764
82
0.697783
e983229c76c5948d8600a2b4685c919514b54d45
1,019
package io.hawt.jmx; public interface QuartzFacadeMBean { /** * Updates an existing simple trigger by changing the repeat counter and interval values. * * @param misfireInstruction the misfire instruction * @param repeatCount the repeat count (use 0 for forever) * @param repeatInterval the repeat interval in millis */ void updateSimpleTrigger(String schedulerObjectName, String triggerName, String groupName, int misfireInstruction, int repeatCount, long repeatInterval) throws Exception; /** * Updates an existing cron trigger by changing the cron expression * * @param misfireInstruction the misfire instruction * @param cronExpression the cron expressions * @param timeZone optional time zone */ void updateCronTrigger(String schedulerObjectName, String triggerName, String groupName, int misfireInstruction, String cronExpression, String timeZone) throws Exception; }
40.76
118
0.700687
f622f39137dc10de0a83000a1892b971ce1ad720
7,798
package com.lightclockcontrol.gss; import android.content.Intent; import android.os.Bundle; import android.os.Parcelable; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v4.app.NavUtils; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.Spinner; import android.widget.TimePicker; import android.widget.Toast; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; public class ScheduleItemEditor extends AppCompatActivity { Spinner spinVisualEffect; TimePicker timePicker; ScheduleViewAdapter.ScheduleItem editingItem; CheckBox chkRnd; EditText edtSong; Spinner spinFolder; EditText edtLightLength; EditText edtSoundLength; CheckBox[] chkWeekdays = new CheckBox[7]; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_schedule_item_editor); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); // Getting GUI objects spinVisualEffect = (Spinner) findViewById(R.id.spinVisualEffect); timePicker = (TimePicker) findViewById(R.id.timePicker); spinFolder = (Spinner) findViewById(R.id.spinAudioFolder); chkRnd = (CheckBox) findViewById(R.id.chkRnd); edtSong = (EditText) findViewById(R.id.txtSong); edtLightLength = (EditText) findViewById(R.id.txtLightLength); edtSoundLength = (EditText) findViewById(R.id.txtSoundLength); chkWeekdays[0] = (CheckBox) findViewById(R.id.chkSun); chkWeekdays[1] = (CheckBox) findViewById(R.id.chkMon); chkWeekdays[2] = (CheckBox) findViewById(R.id.chkTue); chkWeekdays[3] = (CheckBox) findViewById(R.id.chkWed); chkWeekdays[4] = (CheckBox) findViewById(R.id.chkThu); chkWeekdays[5] = (CheckBox) findViewById(R.id.chkFri); chkWeekdays[6] = (CheckBox) findViewById(R.id.chkSat); // Filling in spinner values ArrayAdapter<String> spinnerAdapterEffects= new ArrayAdapter<String>(App.getContext(), android.R.layout.simple_spinner_dropdown_item); for (EffectType t: EffectType.values()){ spinnerAdapterEffects.add(t.toString()); } spinVisualEffect.setAdapter(spinnerAdapterEffects); ArrayAdapter<String> spinnerAdapterFolders= new ArrayAdapter<String>(App.getContext(), android.R.layout.simple_spinner_dropdown_item); for (AudioFolder t: AudioFolder.values()){ spinnerAdapterFolders.add(t.toString()); } spinFolder.setAdapter(spinnerAdapterFolders); // Configuring TimePicker timePicker.setIs24HourView(true); // Loading initial data Parcelable parcel = this.getIntent().getExtras().getParcelable("EditingItem"); if(parcel!=null) { editingItem = (ScheduleViewAdapter.ScheduleItem) parcel; if(editingItem.folderID>=spinnerAdapterFolders.getCount()) { editingItem.folderID=0; } if(editingItem.effectType.getValue()>=spinnerAdapterEffects.getCount()) { editingItem.effectType=EffectType.None; } spinVisualEffect.setSelection(editingItem.effectType.getValue()); Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); cal.setTime(editingItem.execTime); timePicker.setCurrentHour(cal.get(Calendar.HOUR_OF_DAY)); timePicker.setCurrentMinute(cal.get(Calendar.MINUTE)); spinFolder.setSelection(editingItem.folderID); if(editingItem.folderID!=-1) { chkRnd.setChecked(false); edtSong.setText(Integer.toString(editingItem.songID)); } else { chkRnd.setChecked(true); edtSong.setText("0"); } edtLightLength.setText(Integer.toString(editingItem.lightEnabledTime)); edtSoundLength.setText(Integer.toString(editingItem.soundEnabledTime)); for(int i=0;i<7;i++) { chkWeekdays[i].setChecked((editingItem.dayOfWeekMask&(1<<i))!=0); } } // Adding event handlers chkRnd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { edtSong.setEnabled(!isChecked); } }); // FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); // fab.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) // .setAction("Action", null).show(); // } // }); } @Override public void onBackPressed() { setResult(-1,null); super.onBackPressed(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.schedule_item_editor_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case R.id.action_cancel: setResult(-1,null); finish(); break; case R.id.action_save: if(SaveDataToClock()) { setResult(0,null); finish(); onBackPressed(); } else{ Toast.makeText(this,R.string.toast_cannot_save,Toast.LENGTH_LONG).show(); } break; } return super.onOptionsItemSelected(item); } private boolean SaveDataToClock() { editingItem.effectType = EffectType.fromValue((int)spinVisualEffect.getSelectedItemId()); editingItem.execTime.setTime(((long)timePicker.getCurrentHour())*3600l+((long)timePicker.getCurrentMinute())*60l); if(chkRnd.isChecked()) { editingItem.folderID=-1; } else { editingItem.folderID = (byte) (spinFolder.getSelectedItemId()); } editingItem.songID = (byte)Integer.parseInt(edtSong.getText().toString()); try { editingItem.lightEnabledTime = Integer.parseInt(edtLightLength.getText().toString()); } catch (Exception e) { editingItem.lightEnabledTime = 600; } try { editingItem.soundEnabledTime = Integer.parseInt(edtSoundLength.getText().toString()); } catch (Exception e) { editingItem.soundEnabledTime = 600; } editingItem.dayOfWeekMask=0; for(int i=0;i<7;i++) { editingItem.dayOfWeekMask|=(chkWeekdays[i].isChecked() ? 1<<i : 0); } return BTInterface.GetInstance().SendScheduleItemUpdate(editingItem); /* editingItem.effectType = EffectType.fromValue((int)spinVisualEffect.getSelectedItemId()); editingItem.execTime.setTime(((long)timePicker.getCurrentHour())*3600000l+((long)timePicker.getCurrentMinute())*60000l); Intent intent = new Intent(); intent.putExtra("ResultItem",editingItem); setResult(1,intent);*/ } }
36.610329
142
0.639266
f7a925ff4cdde47be473667416af2f8d53c55ee3
9,532
package com.alrosyid.notula.activities.notulas; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import android.Manifest; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.speech.RecognizerIntent; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; import com.alrosyid.notula.R; import com.alrosyid.notula.activities.attendances.EditAttendancesActivity; import com.alrosyid.notula.activities.meetings.EditMeetingsActivity; import com.alrosyid.notula.api.Constant; import com.alrosyid.notula.fragments.attendances.AttendancesListFragments; import com.alrosyid.notula.fragments.meetings.MeetingsFragment; import com.alrosyid.notula.fragments.notulas.NotulasListFragment; import com.alrosyid.notula.models.Attendances; import com.alrosyid.notula.models.Meetings; import com.alrosyid.notula.models.Notula; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.google.android.material.textfield.TextInputEditText; import com.google.android.material.textfield.TextInputLayout; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Map; public class EditNotulaActivity extends AppCompatActivity { private Button btnSave; private TextInputLayout lytTitle, lytSummary; private TextInputEditText txtTitle, txtSummary; private ProgressDialog dialog; private int notulasId = 0, position = 0; public static final Integer RecordAudioRequestCode = 1; public static final int RECOGNIZER_RESULT = 1; private ImageView speechButton; private SharedPreferences sharedPreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit_notula); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setTitle(R.string.edit_notula); if(ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED){ checkPermission(); } init(); } private void init() { dialog = new ProgressDialog(this); dialog.setCancelable(false); sharedPreferences = getApplicationContext().getSharedPreferences("user", Context.MODE_PRIVATE); btnSave = findViewById(R.id.btnSave); lytTitle = findViewById(R.id.tilTitle); txtTitle = findViewById(R.id.tieTitle); lytSummary = findViewById(R.id.tilSummary); txtSummary = findViewById(R.id.tieSummary); position = getIntent().getIntExtra("position", 0); notulasId = getIntent().getIntExtra("notulasId", 0); btnSave.setOnClickListener(v -> { //validate fields first if (validate()) { update(); } }); getNotulas(); speechButton = findViewById(R.id.btnRecord); speechButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent speechIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); speechIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "id-ID"); speechIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); speechIntent.putExtra(RecognizerIntent.EXTRA_PROMPT,"Speech to text"); startActivityForResult(speechIntent,RECOGNIZER_RESULT); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { if (requestCode==RECOGNIZER_RESULT && resultCode == RESULT_OK){ ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); txtSummary.setText(txtSummary.getText().toString()+ " " + matches.get(0).toString()); } super.onActivityResult(requestCode, resultCode, data); } private void checkPermission() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.RECORD_AUDIO},RecordAudioRequestCode); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == RecordAudioRequestCode && grantResults.length > 0 ){ if(grantResults[0] == PackageManager.PERMISSION_GRANTED) Toast.makeText(this,R.string.permission_grandated,Toast.LENGTH_SHORT).show(); } } private boolean validate() { if (txtTitle.getText().toString().isEmpty()) { lytTitle.setErrorEnabled(true); lytTitle.setError(getString(R.string.required)); return false; } if (txtSummary.getText().toString().isEmpty()) { lytSummary.setErrorEnabled(true); lytSummary.setError(getString(R.string.required)); return false; } return true; } private void getNotulas() { Integer id_notula = getIntent().getIntExtra("notulasId", 0); StringRequest request = new StringRequest(Request.Method.GET, Constant.DETAIL_NOTULA + (id_notula), response -> { try { JSONObject object = new JSONObject(response); if (object.getBoolean("success")) { JSONArray array = new JSONArray(object.getString("notulas")); for (int i = 0; i < array.length(); i++) { JSONObject notula = array.getJSONObject(i); txtTitle.setText(notula.getString("title")); txtSummary.setText(notula.getString("summary")); } } } catch (JSONException e) { e.printStackTrace(); } }, error -> { error.printStackTrace(); }) { @Override public Map<String, String> getHeaders() throws AuthFailureError { String token = sharedPreferences.getString("token", ""); HashMap<String, String> map = new HashMap<>(); map.put("Authorization", "Bearer " + token); return map; } }; RequestQueue queue = Volley.newRequestQueue(EditNotulaActivity.this); queue.add(request); } private void update() { dialog.setMessage(getString(R.string.update)); dialog.show(); StringRequest request = new StringRequest(Request.Method.POST, Constant.UPDATE_NOTULA, response -> { try { JSONObject object = new JSONObject(response); if (object.getBoolean("success")) { Notula notula = NotulasListFragment.arrayList.get(position); notula.setSummary(txtSummary.getText().toString()); notula.setTitle(txtTitle.getText().toString()); NotulasListFragment.arrayList.set(position, notula); NotulasListFragment.recyclerView.getAdapter().notifyItemChanged(position); NotulasListFragment.recyclerView.getAdapter().notifyDataSetChanged(); Toast.makeText(this, R.string.update_successfully, Toast.LENGTH_SHORT).show(); finish(); } } catch (JSONException e) { e.printStackTrace(); } }, error -> { error.printStackTrace(); }) { //add token to header @Override public Map<String, String> getHeaders() throws AuthFailureError { String token = sharedPreferences.getString("token", ""); HashMap<String, String> map = new HashMap<>(); map.put("Authorization", "Bearer " + token); return map; } @Override protected Map<String, String> getParams() throws AuthFailureError { HashMap<String, String> map = new HashMap<>(); map.put("id", notulasId + ""); map.put("summary", txtSummary.getText().toString()); map.put("title", txtTitle.getText().toString()); return map; } }; RequestQueue queue = Volley.newRequestQueue(EditNotulaActivity.this); queue.add(request); } @Override public boolean onSupportNavigateUp() { onBackPressed(); return true; } @Override public void onBackPressed() { super.onBackPressed(); } }
38.591093
123
0.650126
10e51ff8ea0b8ec1cbdfe88c00b553508ed5d895
1,441
package GUI_SingleFiles; // Пример использования окна без рамки JWindow import javax.swing.*; import java.awt.*; // http://java-online.ru/swing-windows.xhtml // Класс прорисовки изображения class ImageDraw extends JComponent { private static final long serialVersionUID = 1L; private Image capture; ImageDraw (Image capture) { this.capture = capture; } public void paintComponent(Graphics g) { // Прорисовка изображения g.drawImage(capture, 0, 0, this); } } public class Utf8_JWindowTest extends JWindow { private static final long serialVersionUID = 1L; // изображение "рабочего стола" private Image capture; // Размер окна private int window_w = 300, window_h = 300; public Utf8_JWindowTest() { super(); // Определение положение окна на экране setLocation(200, 100); // Определение размера окна setSize (window_w, window_h); try { // "Вырезаем" часть изображения "рабочего стола" Robot robot = new Robot(); capture = robot.createScreenCapture( new Rectangle(5, 5, window_w, window_h)); } catch (Exception ex) { ex.printStackTrace(); } // Добавляем в интерфейс изображение getContentPane().add(new ImageDraw(capture)); // Открываем окно setVisible(true); try { // Заканчиваем работу через 10 сек Thread.currentThread(); Thread.sleep(10000); } catch (Exception e) { } System.exit(0); } public static void main(String[] args) { new Utf8_JWindowTest(); } }
24.844828
51
0.712006
719db194feb15e9def3f06c6152c06d5a86ffd52
1,641
/** * Copyright (C) 2011 Inqwell Ltd * * You may distribute under the terms of the Artistic License, as specified in * the README file. */ /* * $Archive: /src/com/inqwell/any/GetUniqueKey.java $ * $Author: sanderst $ * $Revision: 1.2 $ * $Date: 2011-04-07 22:18:20 $ */ package com.inqwell.any; /** * Returns the unique key of the * single <code>Map</code> operand. * <p> * Returns the given root node. * @author $Author: sanderst $ * @version $Revision: 1.2 $ */ public class GetUniqueKey extends AbstractFunc implements Cloneable { private Any node_; /** * */ public GetUniqueKey(Any node) { node_ = node; } public Any exec(Any a) throws AnyException { Transaction t = getTransaction(); Map node = (Map)EvalExpr.evalFunc(t, a, node_, Map.class); if (node == null) nullOperand(node_); // When map is in the transaction get the public copy. Only this has // the unique key (is that right or should it have been copied across?) if (t.getResolving() == Transaction.R_MAP) node = t.getLastTMap(); Any ret = node.getUniqueKey(); if (ret == null) throw new AnyException("Unique key is not initialised"); return ret; } public Iter createIterator () { Array a = AbstractComposite.array(); a.add(node_); return a.createIterator(); } public Object clone () throws CloneNotSupportedException { GetUniqueKey g = (GetUniqueKey)super.clone(); g.node_ = node_.cloneAny(); return g; } }
21.038462
78
0.594759
565af287cfb909466235e8cf0dc09d0225ecee90
3,517
package com.example.cityweather.data.local; import androidx.lifecycle.LiveData; import com.example.cityweather.data.api.RequestCallback; import com.example.cityweather.data.api.ResponseCode; import com.example.cityweather.data.local.dao.CityDao; import com.example.cityweather.data.local.dao.ForecastDao; import com.example.cityweather.data.local.model.City; import com.example.cityweather.data.local.model.Forecast; import com.example.cityweather.utils.AppExecutors; import java.util.List; public class LocalDataSource implements LocalDataSourceContract { private static final Object LOCK = new Object(); private static LocalDataSource localDataSource; private final CityDao cityDao; private final ForecastDao forecastDao; private final AppExecutors executors; public LocalDataSource(CityDao cityDao, ForecastDao forecastDao, AppExecutors executors) { this.cityDao = cityDao; this.forecastDao = forecastDao; this.executors = executors; } public static LocalDataSource getInstance(CityDao cityDao, ForecastDao forecastDao, AppExecutors executors) { if (localDataSource == null) { synchronized (LOCK) { localDataSource = new LocalDataSource(cityDao, forecastDao, executors); } } return localDataSource; } @Override public LiveData<City> getCityByCoordinates(double latitude, double longitude) { return cityDao.getCityByCoordinates(latitude, longitude); } @Override public LiveData<List<City>> getCities() { return cityDao.getCities(); } @Override public LiveData<List<City>> searchCityByName(String query) { return cityDao.searchCityByName(query); } @Override public long createCity(City city) { return cityDao.insert(city); } @Override public void updateCity(City city) { executors.getDiskIO().execute(() -> cityDao.update(new City[]{city})); } @Override public void deleteForecastByCityId(int cityId) { executors.getDiskIO().execute(() -> forecastDao.deleteForecastByCityId(cityId)); } @Override public void insertForecast(List<Forecast> forecastList) { executors.getDiskIO().execute(() -> forecastDao.insertObjects(forecastList)); } @Override public int getCityForecastCount(int cityId) { return forecastDao.getCityForecastCount(cityId); } @Override public LiveData<List<Forecast>> getCityForecast(int cityId) { return forecastDao.getCityForecast(cityId); } @Override public List<City> getCitiesList() { return cityDao.getCitiesList(); } @Override public int getCityCount(double latitude, double longitude) { return cityDao.getCityCountByCoordinates(latitude, longitude); } @Override public void deleteCities(List<City> cities) { executors.getDiskIO().execute(() -> cityDao.deleteObjects(cities)); } @Override public void getForecastByCityIdAsynchronous(int cityId, RequestCallback<Forecast> callback) { executors.getDiskIO().execute(() -> { final Forecast forecast = forecastDao.getCityForecastSynchronous(cityId); executors.getMainThread().execute(() -> { if (forecast != null) { callback.onSuccess(forecast); } else { callback.onError(ResponseCode.NO_DATA, null); } }); }); } }
31.972727
113
0.681547
e97444fd2ea7e7f9f2a7f6b515b44a4971c47fa0
406
package com.dev.crm.core.repository.jpa; import java.math.BigDecimal; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.dev.crm.core.model.entity.Usuario; @Repository("usuarioJpaRepository") public interface UsuarioJpaRepository extends JpaRepository<Usuario, BigDecimal> { Usuario findByNombreUsuario(String nombreUsuario); }
27.066667
82
0.834975
c8fc2f8d3cd3736dd16ff4ff082e48fbaf6b29b9
1,973
package uk.gov.hmcts.probate.services.submit.controllers.v2; import au.com.dius.pact.provider.junitsupport.IgnoreNoPactsToVerify; import au.com.dius.pact.provider.junitsupport.loader.PactBroker; import com.fasterxml.jackson.databind.ObjectMapper; import org.json.JSONException; import org.json.JSONObject; import org.junit.Before; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.util.ResourceUtils; import uk.gov.hmcts.reform.probate.model.cases.ProbateCaseDetails; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.file.Files; @PactBroker(scheme = "${pact.broker.scheme}", host = "${pact.broker.baseUrl}", port = "${pact.broker.port}", tags = { "${pact.broker.consumer.tag}"}) @IgnoreNoPactsToVerify public abstract class ControllerProviderTest { @Autowired ObjectMapper objectMapper; @Value("${pact.provider.version}") private String providerVersion; @Before public void setUpTest() { System.getProperties().setProperty("pact.verifier.publishResults", "true"); System.getProperties().setProperty("pact.provider.version", providerVersion); } protected JSONObject createJsonObject(String fileName) throws JSONException, IOException { File file = getFile(fileName); String jsonString = new String(Files.readAllBytes(file.toPath())); return new JSONObject(jsonString); } protected ProbateCaseDetails getProbateCaseDetails(String fileName) throws JSONException, IOException { File file = getFile(fileName); ProbateCaseDetails probateCaseDetails = objectMapper.readValue(file, ProbateCaseDetails.class); return probateCaseDetails; } private File getFile(String fileName) throws FileNotFoundException { return ResourceUtils.getFile(this.getClass().getResource("/json/" + fileName)); } }
37.942308
117
0.758236
11106ac55471418318c7a2bac04778682d7822bb
3,241
/* * Copyright (c) 2017 Mattias Eklöf <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package com.github.jomnipod; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import com.github.jomnipod.datatypes.SignedBEInteger; import com.github.jomnipod.datatypes.SignedLEInteger; import com.github.jomnipod.datatypes.SignedLEShort; import com.github.jomnipod.datatypes.UnsignedBEShort; import com.github.jomnipod.datatypes.UnsignedLEInteger; import com.github.jomnipod.datatypes.UnsignedLEShort; import com.github.jomnipod.datatypes.ZeroTerminatedString; public class IBFRecord { public class Iterator { private ByteBuffer buffer; public Iterator(ByteBuffer buffer) { this.buffer = buffer; } public void skipBytes(int nrOfBytes) { buffer.get(new byte[nrOfBytes]); } public String nextString(int maxLength) { return new ZeroTerminatedString(buffer, maxLength).value(); } public Byte nextByte() { return buffer.get(); } public Integer nextSignedBEInteger() { return new SignedBEInteger(buffer).value(); } public Integer nextSignedLEInteger() { return new SignedLEInteger(buffer).value(); } public Short nextSignedLEShort() { return new SignedLEShort(buffer).value(); } public Integer nextUnsignedBEShort() { return new UnsignedBEShort(buffer).value(); } public Long nextUnsignedLEInteger() { return new UnsignedLEInteger(buffer).value(); } public Integer nextUnsignedLEShort() { return new UnsignedLEShort(buffer).value(); } } private byte[] buffer; public IBFRecord(InputStream dataStream) throws IOException { int recordSize = new UnsignedBEShort(dataStream).value(); buffer = new byte[recordSize - 2]; dataStream.read(buffer); int checksum = 0; for (int i = 0; i < buffer.length; i++) { checksum += buffer[i] & 0xff; } int expectedChecksum = new UnsignedBEShort(dataStream).value(); if (checksum != expectedChecksum) { throw new IBFIntegrityException("Checksum error", String.valueOf(expectedChecksum), String.valueOf(checksum)); } } public Iterator iterator() { return new Iterator(ByteBuffer.wrap(buffer)); } }
29.463636
86
0.746066
4815bba18e846af41d71dee7f8f5a473a51ff7c1
4,735
package keytouch; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.TreeSet; import extractors.data.Answer; import extractors.data.DataNode; import extractors.data.ExtractionModule; import extractors.data.Feature; import extractors.data.TestVectorShutdownModule; import keystroke.KeyStroke; /** * This class implements a specific version of ngram fusion. It takes a * unigraph key hold and digraph key interval * @author Adam Goodkind * */ public class KeyTouchFusionUniHoldDiInt implements ExtractionModule, TestVectorShutdownModule { /** * For intermediate TestVector file processing<p><p> * < User : < LinkedList<HashMap < Feature : Value > > > > */ private static LinkedHashMap<Integer,LinkedList<LinkedHashMap<String,String>>> vectorFileMap = new LinkedHashMap<Integer,LinkedList<LinkedHashMap<String,String>>>();; public static final String vectorMapFileName = "vectorFile.map"; private static boolean preliminaryScan = false; // private static final RevisionStatus[] revStatusList = KeystrokeRevision.RevisionStatus.values(); private HashMap<String, LinkedList<Double>> featureMap = new HashMap<String, LinkedList<Double>>(10000); // private static final int NGRAM_SIZE = 1; public KeyTouchFusionUniHoldDiInt() { featureMap.clear(); } @Override public Collection<Feature> extract(DataNode data) { // createSearchSpace(); featureMap.clear(); int userID = data.getUserID(); //create user's hashmap if (!vectorFileMap.containsKey(userID)) { vectorFileMap.put(userID, new LinkedList<LinkedHashMap<String,String>>()); } //create HashMap to be placed in LinkedList, only if this is not a //pre-processing scan LinkedHashMap<String,String> sliceMap = null; if (!preliminaryScan) { sliceMap = new LinkedHashMap<String,String>(); } for (Answer a : data) { //add Cognitive Load as a feature // featureMap.put("CogLoad", // new LinkedList<Double>(Arrays.asList((double) a.getCogLoad()))); LinkedList<KeyTouch> ktList = KeyTouch.parseSessionToKeyTouches(a.getKeyStrokes()); for (int i=0; i < ktList.size()-1; i++) { KeyTouch k1 = ktList.get(i); KeyTouch k2 = ktList.get(i+1); String uniStr = "H__"+KeyStroke.vkCodetoString(k1.getKeyCode()); String diStr = "I__"+KeyStroke.vkCodetoString(k1.getKeyCode())+"_"+ KeyStroke.vkCodetoString(k2.getKeyCode()); double uniHoldTime = k1.getHoldTime(); double diIntervalTime = k2.getPrecedingPause(); if (featureMap.containsKey(uniStr)) { featureMap.get(uniStr).add(uniHoldTime); } else { featureMap.put(uniStr, new LinkedList<Double>(Arrays.asList(uniHoldTime))); } if (featureMap.containsKey(diStr)) { featureMap.get(diStr).add(diIntervalTime); } else { featureMap.put(diStr, new LinkedList<Double>(Arrays.asList(diIntervalTime))); } } // end loop through keystroke list } //end answer loop //add this slice's HashMap to the LinkedList, if this is not a //pre-processing scan if (sliceMap != null) { //add features from featureMap to sliceMap for (String feature : featureMap.keySet()) { //ignore subjanswid because it is already added to slicemap //needed to add it to featuremap for Template creation, and //subsequent availability pruning, where it is necessary to //have all features if (!feature.equals("SubjAnswID")) sliceMap.put(feature, featureMap.get(feature).toString()); } vectorFileMap.get(userID).add(sliceMap); } LinkedList<Feature> output = new LinkedList<Feature>(); for (String featureName : featureMap.keySet()) { output.add(new Feature(featureName,featureMap.get(featureName))); } // for (Feature f : output) System.out.println(f.toTemplate()); //changed to false after initial, pre-user, Scan preliminaryScan=false; return output; } /** * Write vector map file */ @Override public void shutdown() { try { File f = new File(vectorMapFileName); ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(f,false)); out.writeObject(vectorFileMap); out.close(); vectorFileMap.clear(); } catch (IOException e) { e.printStackTrace(); } } @Override public String getName() { return "Ngram 1KH 2KI"; } }
31.993243
107
0.685322
140af5810ebec22a192dda918e07aa4ec69ff6a2
415
package com.fernandocejas.android10.sample.data.cache; import com.fernandocejas.android10.sample.data.entity.UserEntity; import io.reactivex.Observable; /** * Created by Leeprohacker on 3/21/18. */ public interface HomeCache { Observable<UserEntity> get(final int userId); void put(UserEntity userEntity); boolean isCached(final int userId); boolean isExpired(); void evictAll(); }
16.6
65
0.73253
9e08084bd335b0daf871167cb5af964512348ce6
207
package jdk_dynamic_proxy; /** * Author: markliu * Time : 16-9-2 下午4:31 */ public class Logger { public void log(String userId) { System.out.println("Logger ==> user (" + userId + ") logged"); } }
15.923077
64
0.628019
db0caddaa98ca214d24a2fc40cb879fb7b0a70fd
1,054
package pkg06rockpaperscissors; public class Check { public Check(int player1,int com){ //papier kamien nozyce switch(player1){ case 1: if(com==1) System.out.println("Remis!"); else if(com==2) System.out.println("Wygrałeś!"); else if(com==3) System.out.println("Przegrałeś!"); break; case 2: if(com==1) System.out.println("Przegrałeś!"); else if(com==2) System.out.println("Remis!"); else if(com==3) System.out.println("Wygrałeś!"); break; case 3: if(com==1) System.out.println("Wygrałeś!"); else if(com==2) System.out.println("Przegrałeś!"); else if(com==3) System.out.println("Remis!"); break; } } }
29.277778
54
0.402277
b5e8a8a24dffba7946d767b7a76e2daececb969c
2,250
package com.hzh.answer.dao.impl; import java.io.Serializable; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.List; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.Projections; import org.springframework.orm.hibernate5.support.HibernateDaoSupport; import com.hzh.answer.dao.BaseDao; import com.hzh.answer.domain.StudentPaper; /** * 通用的Dao层实现 * @author ken * * @param <T> */ public class BaseDaoImpl<T> extends HibernateDaoSupport implements BaseDao<T> { private Class clazz; // 通过建立构造器来获取class public BaseDaoImpl() { // 反射: 第一步获得Class Class clazz = this.getClass(); // 这里获取到的class是目前正在被调用的class,CustomerDaoImpl或LinkManDaoImpl // 通过查看JDK的API得知可以通过class获取父类的class(这里的Class已经传入泛型T) Type type = clazz.getGenericSuperclass(); // 参数化类型: BaseDaoImpl<Customer>,BaseDaoImpl<LinkMan> // 得到的type本身是一个参数化的类型,所以这里将type强转成参数化的类型 ParameterizedType pType = (ParameterizedType) type; // 通过参数化类型获得实际类型参数: 得到一个实际类型参数的数组?Map<String,Integer>(这里的泛型有可能是Map,所以这里获取的是数组) Type[] types = pType.getActualTypeArguments(); // 只获得第一个实际类型参数即可 this.clazz = (Class) types[0]; } @Override public void save(T t) { this.getHibernateTemplate().save(t); } @Override public void update(T t) { this.getHibernateTemplate().update(t); } @Override public void delete(T t) { this.getHibernateTemplate().delete(t); } @Override public T findById(Serializable id) { Object object = this.getHibernateTemplate().get(clazz, id); return (T) object; } @Override public Integer findCount(DetachedCriteria detachedCriteria) { detachedCriteria.setProjection(Projections.rowCount()); List<Long> list = (List<Long>) this.getHibernateTemplate().findByCriteria(detachedCriteria); if(list.size()>0) { return list.get(0).intValue(); } return null; } @Override public List<T> findByPage(DetachedCriteria detachedCriteria, Integer begin, Integer pageSize) { detachedCriteria.setProjection(null); List<T> list = (List<T>) this.getHibernateTemplate().findByCriteria(detachedCriteria, begin, pageSize); return list; } @Override public List<T> findAll() { return (List<T>) this.getHibernateTemplate().find("from " + clazz.getSimpleName()); } }
27.108434
105
0.752889
313ea7eb466ffe94ada3d7347559315cfc9a5000
1,112
package com.gosun.xone.core.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import com.gosun.xone.core.entity.Organization; import com.gosun.xone.core.entity.Person; public interface PersonRespository extends JpaRepository<Person, Long> { @Query("select t1 from Person t1,PersonRelations t2" + " where t1.personId = t2.personId and t2.organizationId = :organizationId") public List<Person> findPersonsByOrganizationId(Long organizationId); @Query("select t1 from Organization t1,PersonRelations t2" + " where t1.organizationId = t2.organizationId and t2.personId = :personId") public List<Organization> findOrganizationsByPersonId(Long personId); @Modifying @Query("delete from Person t1 where t1.personId in :personIds") public void deleteByIdList(List<Long> personIds); @Query("select t1 from Person t1 where t1.account.accountId = :accountId") public Person findByAccountId(Long accountId); }
37.066667
81
0.774281
3b20ed5d7ea482d8410f63c80803f54a2065c07a
3,531
package com.example.main; import java.util.ArrayList; import java.util.List; import android.app.Fragment; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.example.baozhang.Baozhang_detailActivity; import com.example.common.HttpUtils; import com.example.common.MyApplication; import com.example.wowodai.R; public class Fragment_baozhang extends Fragment implements OnClickListener { private HttpUtils httpUtils; private MyApplication myApplication; private Context context; private View mainView; private RelativeLayout layout_aqywms, layout_xsfktx, layout_zcflbz, layout_tzhtfb; @Override public void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); httpUtils = new HttpUtils(); myApplication = (MyApplication) getActivity().getApplication(); context = getActivity(); } private void init() { layout_aqywms = (RelativeLayout) mainView .findViewById(R.id.layout_aqywms); layout_xsfktx = (RelativeLayout) mainView .findViewById(R.id.layout_xsfktx); layout_zcflbz = (RelativeLayout) mainView .findViewById(R.id.layout_zcflbz); layout_tzhtfb = (RelativeLayout) mainView .findViewById(R.id.layout_tzhtfb); layout_aqywms.setOnClickListener(this); layout_xsfktx.setOnClickListener(this); layout_zcflbz.setOnClickListener(this); layout_tzhtfb.setOnClickListener(this); } public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mainView = inflater.inflate(R.layout.main_baozhang, null); init(); return mainView; } @Override public void onClick(View v) { // TODO Auto-generated method stub String webViewUrl = ""; String titleString = ""; Intent intent; switch (v.getId()) { case R.id.layout_aqywms: webViewUrl = "http://manage.55178.com/mobile/page/moshi.html"; titleString = "安全业务模式"; intent = new Intent(context, Baozhang_detailActivity.class); intent.putExtra("webViewUrl", webViewUrl); intent.putExtra("titleString", titleString); startActivity(intent); break; case R.id.layout_xsfktx: webViewUrl = "http://manage.55178.com/mobile/page/xinshen.html"; titleString = "信审风控体系"; intent = new Intent(context, Baozhang_detailActivity.class); intent.putExtra("webViewUrl", webViewUrl); intent.putExtra("titleString", titleString); startActivity(intent); break; case R.id.layout_zcflbz: webViewUrl = "http://manage.55178.com/mobile/page/zhengce.html"; titleString = "政策法律保障"; intent = new Intent(context, Baozhang_detailActivity.class); intent.putExtra("webViewUrl", webViewUrl); intent.putExtra("titleString", titleString); startActivity(intent); break; case R.id.layout_tzhtfb: webViewUrl = "http://manage.55178.com/mobile/page/hetong.html"; titleString = "投资合同范本"; intent = new Intent(context, Baozhang_detailActivity.class); intent.putExtra("webViewUrl", webViewUrl); intent.putExtra("titleString", titleString); startActivity(intent); break; } } }
30.179487
76
0.766072
a82bbdf388c47be04fb37a390b3eaea2b06b2961
91
@tech.jhipster.lite.BusinessContext package tech.jhipster.lite.generator.setup.codespaces;
30.333333
54
0.857143
a7ec0c677af60bf834ed92d52c646cceb50a75bb
1,740
package com.redhat.repository.validator.impl.remoterepository; import java.io.File; import java.net.URI; import org.apache.http.Header; import org.apache.http.HttpResponse; public class ChecksumProviderNginx implements ChecksumProvider { @Override public String getRemoteArtifactChecksum(URI remoteArtifact, HttpResponse httpResponse) { Header etagHeader = httpResponse.getFirstHeader("ETag"); if (etagHeader != null) { String etagValue = etagHeader.getValue(); if( etagValue.startsWith("\"") && etagValue.endsWith("\"") ) { etagValue = etagValue.substring(1, etagValue.length()-1); } return etagValue; } throw new ChecksumProviderException("Remote repository returned unknown headers, it is not possible to parse artifact hash for " + remoteArtifact); } @Override public String getLocalArtifactChecksum(URI localArtifact) { File file = new File(localArtifact); return String.format("%1$x-%2$x", file.lastModified() / 1000, file.length()); } } /* nginx etag format is combination of last modified time in seconds plus content length, both formated in hexadecimal, see http://hustoknow.blogspot.cz/2014/11/how-nginx-computes-etag-header-for-files.html SAMPLE HTTP RESPONSE ... Server: nginx Content-Type: text/xml Content-Length: 3345 Last-Modified: Thu, 17 Jul 2014 04:59:43 GMT ETag: "53c7583f-d11" Accept-Ranges: bytes Accept-Ranges: bytes Via: 1.1 varnish Accept-Ranges: bytes Date: Fri, 30 Jan 2015 07:16:20 GMT Via: 1.1 varnish Connection: keep-alive X-Served-By: cache-iad2135-IAD, cache-ams4131-AMS X-Cache: MISS, MISS X-Cache-Hits: 0, 0 X-Timer: S1422602180.757671,VS0,VE103 */
31.071429
155
0.70977
2cd3488ac7444fecb5b0c371966fdf8feae9cf0e
2,293
package com.skeqi.mes.controller.dzb.report; import com.alibaba.fastjson.JSONObject; import com.skeqi.mes.service.dzb.report.ScrewDownService; import com.skeqi.mes.util.ToolUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import java.util.Date; /** * @Created by DZB * @Date 2021/3/11 9:35 * @Description 拧紧合格率 */ @RestController @RequestMapping("report/screwDown") public class ScrewDownController { @Resource(name = "ScrewDownService") private ScrewDownService service; @RequestMapping(value = "queryScrewDown",method = RequestMethod.POST) // @OptionalLog(module="报表", module2="拧紧合格率", method="查询拧紧数据") public Object queryScrewDown(HttpServletRequest request, @RequestParam("lineId") Integer lineId, @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @RequestParam("startDate") Date startDate, @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @RequestParam(value = "endDate",required = false) Date endDate){ JSONObject out =new JSONObject(); try { out = service.countBoltGroupSt(lineId,startDate,endDate); out.put("code",200); } catch (Exception e) { out.put("code",201); e.printStackTrace(); ToolUtils.errorLog(this, e, request); } return out; } @RequestMapping(value = "listLine",method = RequestMethod.POST) // @OptionalLog(module="报表", module2="拧紧合格率", method="查询产线") public Object listLine(HttpServletRequest request){ JSONObject out =new JSONObject(); try { out = service.listLine(); out.put("code",200); } catch (Exception e) { out.put("code",201); e.printStackTrace(); ToolUtils.errorLog(this, e, request); } return out; } }
35.828125
146
0.662451
32873291ee697967b0949d77cd3c604c936ee9a8
3,397
package be.howest.twentytwo.parametergame.factory; import be.howest.twentytwo.parametergame.dataTypes.DifficultyDataI; import be.howest.twentytwo.parametergame.dataTypes.EnemyDataI; import be.howest.twentytwo.parametergame.model.ai.IAIMoveBehaviour; import be.howest.twentytwo.parametergame.model.ai.IAIShootBehaviour; import be.howest.twentytwo.parametergame.model.ai.NullAIMoveBehaviour; import be.howest.twentytwo.parametergame.model.ai.NullAIShootBehaviour; import be.howest.twentytwo.parametergame.model.component.AIComponent; import be.howest.twentytwo.parametergame.model.component.EnemyComponent; import be.howest.twentytwo.parametergame.model.physics.collision.Collision; import com.badlogic.ashley.core.Entity; import com.badlogic.ashley.core.PooledEngine; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.World; public class AIShipFactory implements ISpawnFactory { private ShipFactory shipFactory; private PooledEngine engine; private World world; private AssetManager assets; private EnemyDataI enemyData; private DifficultyDataI difficulty; private Body target; private IAIMoveBehaviour moveBehaviour; private IAIShootBehaviour shootBehaviour; public AIShipFactory(PooledEngine engine, World world, AssetManager assets, EnemyDataI shipData, DifficultyDataI difficulty, Body target, IAIMoveBehaviour moveBehaviour, IAIShootBehaviour shootBehaviour) { this.shipFactory = new ShipFactory(engine, world, assets, shipData.getShipData(), difficulty); this.engine = engine; this.world = world; this.assets = assets; this.enemyData = shipData; this.difficulty = difficulty; this.target = target; this.moveBehaviour = moveBehaviour; this.shootBehaviour = shootBehaviour; } public AIShipFactory(PooledEngine engine, World world, AssetManager assets, EnemyDataI shipData, DifficultyDataI difficulty, Body target, IAIMoveBehaviour moveBehaviour) { this(engine, world, assets, shipData, difficulty, target, moveBehaviour, new NullAIShootBehaviour()); } public AIShipFactory(PooledEngine engine, World world, AssetManager assets, EnemyDataI shipData, DifficultyDataI difficulty, Body target) { this(engine, world, assets, shipData, difficulty, target, new NullAIMoveBehaviour(), new NullAIShootBehaviour()); } @Override public Entity spawnEntity(Vector2 pos, float rotation, Vector2 initialVelocity, short physicsCategory, short physicsMask) { Entity aiShip = shipFactory.createShip(pos, rotation, Collision.BULLET_ENEMY_CATEGORY, Collision.BULLET_ENEMY_MASK); AIComponent ai = engine.createComponent(AIComponent.class); ai.setMoveBehaviour(moveBehaviour); ai.setShootBehaviour(shootBehaviour); ai.setTarget(target); aiShip.add(ai); EnemyComponent ec = engine.createComponent(EnemyComponent.class); ec.setScoreValue(enemyData.getBaseScore() * difficulty.getScoreModifier()); ec.setGeomDropRate(enemyData.getGeomDropRate()); aiShip.add(ec); engine.addEntity(aiShip); return aiShip; } @Override public Entity spawnEntity(Vector2 pos, float rotation, Vector2 initialVelocity) { return spawnEntity(pos, rotation, initialVelocity, Collision.BULLET_ENEMY_CATEGORY, Collision.BULLET_ENEMY_MASK); } @Override public String getType() { return shipFactory.getType(); } }
38.602273
97
0.806888
d0d282c1ae175a19b9e9c7d2edd2af43ff48d309
738
/* SPDX-License-Identifier: Apache-2.0 */ /* Copyright Contributors to the ODPi Egeria project. */ package org.odpi.openmetadata.governanceservers.openlineage.scheduler; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.time.LocalDateTime; public class BufferGraphJob implements Job { private static final Logger log = LoggerFactory.getLogger(BufferGraphJob.class); @Override public void execute(JobExecutionContext context) { LocalDateTime localTime = LocalDateTime.now(); System.out.println("Run QuartzJob at " + localTime); BufferGraphJobTask mytask = new BufferGraphJobTask(); mytask.perform(); } }
29.52
84
0.749322
0119c05377e9c6f078fb58002144fef43b986bb0
294
package com.billy.android.preloader.interfaces; /** * @author billy.qi */ public interface DataLoader<DATA> { /** * pre-load loaded data * Note: this method will runs in thread pool, * @return load result data (maybe null when load failed) */ DATA loadData(); }
19.6
61
0.642857
537467d894d9a2672d29d4b050cf73454f0a32a9
942
/** * */ package serendip.struts.plugins.thymeleaf.diarect; import java.util.LinkedHashSet; import java.util.Set; import org.thymeleaf.dialect.AbstractProcessorDialect; import org.thymeleaf.processor.IProcessor; import org.thymeleaf.templatemode.TemplateMode; /** * diarect:sth. * * @author A-pZ * @version 3.0.0.BETA03 * */ public class FieldDialect extends AbstractProcessorDialect { public static final String NAME = "Struts2Standard"; public static final String PREFIX = "sth"; public static final int PROCESSOR_PRECEDENCE = 1000; public FieldDialect(final TemplateMode templateMode, final String dialectPrefix) { super(NAME, PREFIX, PROCESSOR_PRECEDENCE); } @Override public Set<IProcessor> getProcessors(final String dialectPrefix) { Set<IProcessor> processors = new LinkedHashSet<IProcessor>(); processors.add(new FieldErrorAttributeProcessor(dialectPrefix)); return processors; } }
24.789474
83
0.759023
5913bc1d33324f198a730544013be632b6922625
740
package de.adesso.gitstalker.core.objects; import lombok.Data; import java.util.ArrayList; @Data public class Team { private String name; private String description; private String avatarURL; private String githubURL; private ArrayList<Member> teamMembers; private ArrayList<Repository> teamRepositories; public Team(String name, String description, String avatarURL, String githubURL, ArrayList<Member> teamMembers, ArrayList<Repository> teamRepositories) { this.setName(name); this.setDescription(description); this.setAvatarURL(avatarURL); this.setGithubURL(githubURL); this.setTeamMembers(teamMembers); this.setTeamRepositories(teamRepositories); } }
28.461538
157
0.735135
b0c1fca88bf0cdae569b6323a53afb05c4dc31a5
524
package cn.houtaroy.springboot.koala.starter.log.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author Houtaroy */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface KoalaLog { /** * 功能模块 * * @return 功能模块 */ String type() default ""; /** * 业务描述 * * @return 业务描述 */ String content() default ""; }
17.466667
61
0.660305
811d37f537e4da8af3e72acdd76ec969a4a8d719
726
import org.paddy.generics.GenericTypes; import org.paddy.http.HTTP_Header; import org.paddy.streams.CollectionManipulation; import org.paddy.streams.Transactions; import java.util.Arrays; public class Main { public static void main(String[] args) { new CollectionManipulation(); HTTP_Header.parseHTTPheader(); new Transactions(); System.out.println("== Generics =="); GenericTypes<Integer, String> gtNS = new GenericTypes<>(); gtNS.setT("Teststring"); System.out.println(gtNS.getT()); gtNS.setN(Arrays.asList(1, 2 , 3, 4, 5, 6, 7, 8, 9, 10)); int sum = gtNS.getN().stream().mapToInt(Integer::intValue).sum(); System.out.println(sum); } }
36.3
73
0.655647
f2e558f06a240a5de1bd4a06503806f8b1436b6a
5,207
package at.tuwien.rocreateprofil.model.entity.rocrate.meta.util; import at.tuwien.rocreateprofil.output.rocrate.RoCrateSchema; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import java.util.ListIterator; public class RoCrateMetaUtil { public static JSONArray getRoCrateMetadataGraphArray(JSONObject roCrateMetadata) { guardRoCrateInitialized(roCrateMetadata); return (JSONArray) roCrateMetadata.get(RoCrateSchema.GRAPH); } public static JSONObject getRootDataEntity(JSONObject roCrateMetadata) { guardRoCrateInitialized(roCrateMetadata); return retrieveEntityByIdAndType(getRoCrateMetadataGraphArray(roCrateMetadata), RoCrateSchema.ROOT_DATA_ENTITY_ID, RoCrateSchema.TYPE_DATASET); } // Might not be necessary thanks to passing by reference, TODO: @marwin remove once dataset integration is done // public static JSONObject updateEntity(JSONObject roCrateMetadata, JSONObject updatedEntity) { // JSONArray entityGraph = getRoCrateMetadataGraphArray(roCrateMetadata); // // TODO: @marwin this might have issues if the type is an array - make sure to add unit tests checking the functionality // JSONObject entityToUpdate = retrieveEntityByIdAndType(entityGraph, updatedEntity.get(RoCrateSchema.ID).toString(), updatedEntity.get(RoCrateSchema.TYPE).toString()); // return roCrateMetadata; // } public static JSONObject retrieveEntityByIdAndType(JSONArray objectArray, String id, String type) { ListIterator iterator = objectArray.listIterator(); while (iterator.hasNext()) { JSONObject object = (JSONObject) iterator.next(); JSONArray typeArray = getTypeArray(object); String objectId = (String) object.get(RoCrateSchema.ID); if (typeArray.contains(type) && objectId.equals(id)) { return object; } } throw new IllegalStateException("Object not found for id and type"); // TODO: @marwin change this to a defined error } /* * Retrieves type as array regardless even if there is only a single type */ private static JSONArray getTypeArray(JSONObject object) { JSONArray typeArray; try { typeArray = (JSONArray) object.get(RoCrateSchema.TYPE); } catch (ClassCastException e) { typeArray = new JSONArray(); typeArray.add(object.get(RoCrateSchema.TYPE)); } return typeArray; } public static JSONObject retrieveEntityById(JSONArray objectArray, String id) { ListIterator iterator = objectArray.listIterator(); while (iterator.hasNext()) { JSONObject object = (JSONObject) iterator.next(); String objectId = (String) object.get(RoCrateSchema.ID); if (objectId != null && objectId.equals(id)) { return object; } } throw new IllegalStateException("Object not found for id"); // TODO: @marwin change this to a defined error } private static void guardRoCrateInitialized(JSONObject roCrateMetadata) { if (roCrateMetadata == null) { throw new IllegalStateException(); // TODO: @marwin change this to a defined error } } private static String JSON = "{\n" + " \"@graph\": [\n" + " {\n" + " \"@type\": \"CreativeWork\",\n" + " \"about\": {\n" + " \"@id\": \".\\/\"\n" + " },\n" + " \"@id\": \"ro-crate-metadata.json\",\n" + " \"conformsTo\": {\n" + " \"@id\": \"https:\\/\\/w3id.org\\/ro\\/crate\\/1.1\"\n" + " }\n" + " },\n" + " {\n" + " \"@id\": \".\\/\",\n" + " \"datePublished\": \"2021-06-18T01:04:32Z\",\n" + " \"license\": \"\",\n" + " \"application\": {\n" + " \"@id\": \"72ce19e6-d248-4961-a7ed-cdb40d127534\"\n" + " },\n" + " \"@type\": \"Dataset\",\n" + " \"name\": null,\n" + " \"description\": \"\",\n" + " \"hasPart\": [\n" + " {\n" + " \"@id\": \"input.xlsx\"\n" + " }\n" + " ],\n" + " \"@id\": \".\\/\"\n" + " },\n" + " {\n" + " \"@type\": \"file\",\n" + " \"name\": \"input.xlsx\",\n" + " \"encodingFormat\": \"application\\/json\",\n" + " \"@id\": \"input.xlsx\"\n" + " },\n" + " {\n" + " \"@type\": \"SoftwareApplication\",\n" + " \"name\": \"Microsoft Excel\",\n" + " \"@id\": \"72ce19e6-d248-4961-a7ed-cdb40d127534\",\n" + " \"version\": \"16.0300\"\n" + " }\n" + " ],\n" + " \"@context\": \"https:\\/\\/w3id.org\\/ro\\/crate\\/1.1\\/context\"\n" + "}\n" + "\n" + "\n" + "\n"; }
42.333333
175
0.525639
a4189df31d1150b0be218a784d3e73df4f35fc78
243
package com.baeldung.concurrent.interrupt; public class CustomInterruptedException extends Exception { private static final long serialVersionUID = 1L; CustomInterruptedException(String message) { super(message); } }
22.090909
59
0.744856
f896d38f2cdd03025c546997599d265dcadae459
4,769
package cellsociety.configuration; import cellsociety.model.Cells.Cell; import com.opencsv.CSVReader; import com.opencsv.exceptions.CsvException; import java.io.FileReader; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.nio.file.Path; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Random; /** * This class is designed to develop a Grid of Cells based on the size of the grid stored in the csv * file and random probability for each cell. * <p> * Exceptions can be thrown if the file passed into the constructor has faulty information, the data * in the csv file doesn't match the proper format, or if the simulation requested isn't supported. * <p> * This class relies on its parent class, Grid, as well as the PropertyReader class to pass in * proper data. * <p> * Grid grid = new ProbabilityGrid(Path.of("test/test_data/na.csv"), "NA", optionalKeyMap); * * @author Hayden Lau */ public class ProbabilityGrid extends Grid { private static final Random random = new Random(1); /** * this constructor serves to call the Grid constructor and generates a CsvGrid of the simulation * requested with the data passed in through the parameters * * @param cellFile path of the csv file containing the data * @param simulationName name of the type of the simulation to be created * @param optional map containing the optional keys and values necessary to generate the * simulation * @throws ConfigurationException */ public ProbabilityGrid(Path cellFile, String simulationName, Map optional) throws ConfigurationException { super(cellFile, simulationName, optional); } /** * builds out a list of list of cells that represent the graph based on the csv file's header row * and a probability passed in through the optional key map stored in the parent's instance * variable * * @param cellFile the path of csv file to create the simulation from * @return list of list of cells that represent the grid * @throws ConfigurationException if there is an error while building the grid */ @Override List<List<Cell>> build2DArray(Path cellFile) throws ConfigurationException { List<List<Cell>> ret = new ArrayList<>(); List<String[]> csvData; int rows; int cols; try { FileReader inputFile = new FileReader(String.valueOf(cellFile)); CSVReader csvReader = new CSVReader(inputFile); csvData = csvReader.readAll(); } catch (CsvException | IOException e) { throw new ConfigurationException( String.format(resourceBundle.getString("otherSimulationCreationErrors"), e.getMessage())); } Iterator<String[]> iterator = csvData.iterator(); if (iterator.hasNext()) { String[] headerRow = iterator.next(); rows = (int) removeHiddenChars(headerRow[0]); cols = (int) removeHiddenChars(headerRow[1]); } else { throw new ConfigurationException(String .format(resourceBundle.getString("otherSimulationCreationErrors"), "no header row")); } for (int i = 0; i < rows; i++) { ret.add(i, new ArrayList<>()); for (int j = 0; j < cols; j++) { ret.get(i).add(createNewCell()); } } return ret; } private Cell createNewCell() throws ConfigurationException { Cell ret; try { String modelPackagePath = MODEL_PATH + simulationName + "."; // get state from cell value and simulation name Class<?> modelStates = Class.forName(modelPackagePath + simulationName + "States"); Method method = modelStates.getMethod("values"); Enum<?>[] states = ((Enum<?>[]) method.invoke(null)); Enum<?> state = states[0]; // randomization of state and defaults to the 0th state for (int i = states.length - 1; i > 0; i--) { if (random.nextDouble() <= Double.parseDouble((String) optional.get("probability"))) { state = states[i]; break; } } // create a new cell from simulation name with defined state Class<?> simulation = Class.forName(modelPackagePath + simulationName + "Cell"); Constructor<?> simConstructor = simulation.getConstructor(Enum.class, Map.class); ret = (Cell) simConstructor.newInstance(state, optional); } catch (ClassNotFoundException e) { throw new ConfigurationException( String.format(resourceBundle.getString("simulationNotSupported"), simulationName)); } catch (Exception e) { throw new ConfigurationException( String.format(resourceBundle.getString("otherSimulationCreationErrors"), e.getMessage())); } return ret; } }
38.459677
100
0.689453
1055b78d2310b24a1903989de6dc343237711605
1,544
package com.lazydev.stksongbook.webapp.config; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; @Configuration @ComponentScan(basePackages = "com.lazydev.stksongbook.webapp") @EnableConfigurationProperties({StorageProperties.class, ApplicationProperties.class, SecurityProperties.class, FlywayProperties.class}) @EnableTransactionManagement public class ApplicationConfiguration { private final SecurityProperties securityProperties; public ApplicationConfiguration(SecurityProperties securityProperties) { this.securityProperties = securityProperties; } @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = securityProperties.getCors(); if(config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) { source.registerCorsConfiguration("/api/**", config); source.registerCorsConfiguration("/management/**", config); source.registerCorsConfiguration("/v2/api-docs", config); } return new CorsFilter(source); } }
41.72973
111
0.816062
85dde1cc03b20fdb2394b576d8db9b56052d0cb6
2,457
/********************************************************************************************** Copyright 2019 Pivotal Software Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *********************************************************************************************/ package io.pivotal.rtsmadlib.batch.mlmodel.meta; import java.util.HashMap; import java.util.Map; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; /** * @author sridhar paladugu * */ @Component @ConfigurationProperties(prefix = "ml-batch") public class ApplicationProperties { private String name; private String schema; private String batchFunction; private boolean hydrateCache; private int loadBatchSize; private Map<String, String> cacheSourceTables; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSchema() { return schema; } public void setSchema(String schema) { this.schema = schema; } public String getBatchFunction() { return batchFunction; } public void setBatchFunction(String batchFunction) { this.batchFunction = batchFunction; } public boolean getHydrateCache() { return hydrateCache; } public void setHydrateCache(boolean hydrateCache) { this.hydrateCache = hydrateCache; } public int getLoadBatchSize() { return loadBatchSize; } public void setLoadBatchSize(int loadBatchSize) { this.loadBatchSize = loadBatchSize; } public Map<String, String> getCacheSourceTables() { return cacheSourceTables; } public void setCacheSourceTables(Map<String, String> cacheSourceTables) { this.cacheSourceTables = cacheSourceTables; } public void addCacheSourceTable(String table, String idColumn) { if (null == this.cacheSourceTables) { cacheSourceTables = new HashMap<String, String>(); } cacheSourceTables.put(table, idColumn); } }
22.135135
95
0.693122
e55429e9d6aab3ece01bd56de64d179db6be38cd
1,853
package no.kjelli.generic.tweens; import no.kjelli.generic.gameobjects.GameObject; import aurelienribon.tweenengine.TweenAccessor; public class GameObjectAccessor implements TweenAccessor<GameObject> { public static final int POSITION_X = 1; public static final int POSITION_Y = 2; public static final int POSITION_XY = 3; public static final int SCALE_W = 4; public static final int SCALE_H = 5; public static final int SCALE_WH = 6; public static final int ROTATION = 7; @Override public int getValues(GameObject go, int type, float[] returnValues) { switch (type) { case POSITION_X: returnValues[0] = go.getX(); return 1; case POSITION_Y: returnValues[0] = go.getY(); return 1; case POSITION_XY: returnValues[0] = go.getX(); returnValues[1] = go.getY(); return 2; /* * */ case SCALE_W: returnValues[0] = go.getXScale(); return 1; case SCALE_H: returnValues[0] = go.getYScale(); return 1; case SCALE_WH: returnValues[0] = go.getXScale(); returnValues[1] = go.getYScale(); return 2; /* * */ case ROTATION: returnValues[0] = go.getRotation(); return 1; default: assert false; return -1; } } @Override public void setValues(GameObject go, int type, float[] newValues) { switch (type) { case POSITION_X: go.setX(newValues[0]); break; case POSITION_Y: go.setY(newValues[0]); break; case POSITION_XY: go.setX(newValues[0]); go.setY(newValues[1]); break; /* * * */ case SCALE_W: go.setXScale(newValues[0]); break; case SCALE_H: go.setYScale(newValues[0]); break; case SCALE_WH: go.setXScale(newValues[0]); go.setYScale(newValues[1]); break; /* * */ case ROTATION: go.setRotation(newValues[0]); break; default: assert false; break; } } }
17.481132
70
0.649757
f9d27d3a2b67fee47e37db7c7bbe99575cc283fc
1,911
package com.db.prisma.droolspoc.generation; import com.db.prisma.droolspoc.pain001.Document; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.xml.sax.SAXException; import javax.xml.XMLConstants; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.util.Random; class Pain00100108GeneratorTest { Pain00100108Generator generator; private Schema schema; @BeforeEach void setup() throws Exception { generator = new Pain00100108Generator(); generator.random = new Random(42); generator.batchMax = 1; generator.maxInBatch = 1; schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI) .newSchema(new StreamSource(new File("xsd/pain.001.001.08.xsd"))); } @Test void generate() throws IOException, org.xml.sax.SAXException, JAXBException { Document result = generator.generate(); System.out.println("Generation - ok!"); StringWriter xml = new StringWriter(); JAXBContext jc = JAXBContext.newInstance("com.db.prisma.droolspoc.pain001"); Marshaller marshaller = jc.createMarshaller(); marshaller.marshal(result, xml); System.out.println("Marshall - ok!"); validate(new StreamSource(new StringReader(xml.toString()))); System.out.println("Validate - ok!"); } private void validate(Source source) throws IOException, SAXException { Validator validator = schema.newValidator(); validator.validate(source); } }
34.745455
84
0.723182
1dda0b772323dc9602a82c763fa97322d3ed6dc4
3,689
package wannabit.io.cosmostaion.widget; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.widget.CardView; import android.view.View; import android.widget.RelativeLayout; import android.widget.TextView; import org.jetbrains.annotations.NotNull; import java.math.BigDecimal; import wannabit.io.cosmostaion.R; import wannabit.io.cosmostaion.activities.MainActivity; import wannabit.io.cosmostaion.activities.ValidatorListActivity; import wannabit.io.cosmostaion.activities.VoteListActivity; import wannabit.io.cosmostaion.utils.WDp; import static wannabit.io.cosmostaion.base.BaseConstant.TOKEN_ATOM; import static wannabit.io.cosmostaion.base.BaseConstant.TOKEN_IRIS; import static wannabit.io.cosmostaion.base.BaseConstant.TOKEN_IRIS_ATTO; public class WalletIrisHolder extends WalletHolder { public TextView mTvIrisTotal, mTvIrisValue, mTvIrisAvailable, mTvIrisDelegated, mTvIrisUnBonding, mTvIrisRewards; public RelativeLayout mBtnStake, mBtnVote; public WalletIrisHolder(@NonNull View itemView) { super(itemView); mTvIrisTotal = itemView.findViewById(R.id.iris_amount); mTvIrisValue = itemView.findViewById(R.id.iris_value); mTvIrisAvailable = itemView.findViewById(R.id.iris_available); mTvIrisDelegated = itemView.findViewById(R.id.iris_delegate); mTvIrisUnBonding = itemView.findViewById(R.id.iris_unbonding); mTvIrisRewards = itemView.findViewById(R.id.iris_reward); mBtnStake = itemView.findViewById(R.id.btn_iris_reward); mBtnVote = itemView.findViewById(R.id.btn_iris_vote); } public void onBindHolder(@NotNull MainActivity mainActivity) { final BigDecimal availableAmount = WDp.getAvailableCoin(mainActivity.mBalances, TOKEN_IRIS_ATTO); final BigDecimal delegateAmount = WDp.getAllDelegatedAmount(mainActivity.mBondings, mainActivity.mAllValidators, mainActivity.mBaseChain); final BigDecimal unbondingAmount = WDp.getUnbondingAmount(mainActivity.mUnbondings); final BigDecimal rewardAmount = mainActivity.mIrisReward == null ? BigDecimal.ZERO : mainActivity.mIrisReward.getSimpleIrisReward(); final BigDecimal totalAmount = availableAmount.add(delegateAmount).add(unbondingAmount).add(rewardAmount); mTvIrisTotal.setText(WDp.getDpAmount2(mainActivity, totalAmount, 18, 6)); mTvIrisAvailable.setText(WDp.getDpAmount2(mainActivity, availableAmount, 18, 6)); mTvIrisDelegated.setText(WDp.getDpAmount2(mainActivity, delegateAmount, 18, 6)); mTvIrisUnBonding.setText(WDp.getDpAmount2(mainActivity, unbondingAmount, 18, 6)); mTvIrisRewards.setText(WDp.getDpAmount2(mainActivity, rewardAmount, 18, 6)); mTvIrisValue.setText(WDp.getValueOfIris(mainActivity, mainActivity.getBaseDao(), totalAmount)); mainActivity.getBaseDao().onUpdateLastTotalAccount(mainActivity.mAccount, totalAmount.toPlainString()); mBtnStake.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent validators = new Intent(mainActivity, ValidatorListActivity.class); validators.putExtra("irisreward", mainActivity.mIrisReward); mainActivity.startActivity(validators); } }); mBtnVote.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent proposals = new Intent(mainActivity, VoteListActivity.class); mainActivity.startActivity(proposals); } }); } }
50.534247
146
0.740851
88cd12dce462b3d086f7ed84fc5acb29dcf53ce9
2,435
/* */ package org.apache.xpath.compiler; /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public class OpMapVector /* */ { /* */ protected int m_blocksize; /* */ protected int[] m_map; /* 38 */ protected int m_lengthPos = 0; /* */ /* */ /* */ /* */ /* */ /* */ protected int m_mapSize; /* */ /* */ /* */ /* */ /* */ /* */ public OpMapVector(int blocksize, int increaseSize, int lengthPos) { /* 51 */ this.m_blocksize = increaseSize; /* 52 */ this.m_mapSize = blocksize; /* 53 */ this.m_lengthPos = lengthPos; /* 54 */ this.m_map = new int[blocksize]; /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public final int elementAt(int i) { /* 66 */ return this.m_map[i]; /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public final void setElementAt(int value, int index) { /* 81 */ if (index >= this.m_mapSize) { /* */ /* 83 */ int oldSize = this.m_mapSize; /* */ /* 85 */ this.m_mapSize += this.m_blocksize; /* */ /* 87 */ int[] newMap = new int[this.m_mapSize]; /* */ /* 89 */ System.arraycopy(this.m_map, 0, newMap, 0, oldSize); /* */ /* 91 */ this.m_map = newMap; /* */ } /* */ /* 94 */ this.m_map[index] = value; /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public final void setToSize(int size) { /* 105 */ int[] newMap = new int[size]; /* */ /* 107 */ System.arraycopy(this.m_map, 0, newMap, 0, this.m_map[this.m_lengthPos]); /* */ /* 109 */ this.m_mapSize = size; /* 110 */ this.m_map = newMap; /* */ } /* */ } /* Location: /mnt/r/ConTenDoViewer.jar!/org/apache/xpath/compiler/OpMapVector.class * Java compiler version: 1 (45.3) * JD-Core Version: 1.1.3 */
20.635593
96
0.340452
6cc966c9e2424efc0f087a1662f731e4b099b8a6
5,510
package library.rays; import library.collision.Arbiter; import library.dynamics.Body; import library.geometry.Circle; import library.geometry.Polygon; import library.math.Matrix2D; import library.math.Vectors2D; import testbed.Camera; import testbed.ColourSettings; import java.awt.*; import java.awt.geom.Path2D; import java.util.ArrayList; /** * A class for generating polygons that can mimic line of sight around objects and cast shadows. */ public class ShadowCasting { private final int distance; private Vectors2D startPoint; /** * Setter for start point. * * @param startPoint Returns start point. */ public void setStartPoint(Vectors2D startPoint) { this.startPoint = startPoint; } /** * Constructor * * @param startPoint Origin of projecting rays. * @param distance The desired distance to project the rays. */ public ShadowCasting(Vectors2D startPoint, int distance) { this.startPoint = startPoint; this.distance = distance; } private final ArrayList<RayAngleInformation> rayData = new ArrayList<>(); /** * Updates the all projections in world space and acquires information about all intersecting rays. * * @param bodiesToEvaluate Arraylist of bodies to check if they intersect with the ray projection. */ public void updateProjections(ArrayList<Body> bodiesToEvaluate) { rayData.clear(); for (Body B : bodiesToEvaluate) { if (Arbiter.isPointInside(B, startPoint)) { rayData.clear(); break; } if (B.shape instanceof Polygon) { Polygon poly1 = (Polygon) B.shape; for (Vectors2D v : poly1.vertices) { Vectors2D direction = poly1.orient.mul(v, new Vectors2D()).addi(B.position).subtract(startPoint); projectRays(direction, bodiesToEvaluate); } } else { Circle circle = (Circle) B.shape; Vectors2D d = B.position.subtract(startPoint); double angle = Math.asin(circle.radius / d.length()); Matrix2D u = new Matrix2D(angle); projectRays(u.mul(d.normalize(), new Vectors2D()), bodiesToEvaluate); Matrix2D u2 = new Matrix2D(-angle); projectRays(u2.mul(d.normalize(), new Vectors2D()), bodiesToEvaluate); } } rayData.sort((lhs, rhs) -> Double.compare(rhs.getANGLE(), lhs.getANGLE())); } /** * Projects a ray and evaluates it against all objects supplied in world space. * * @param direction Direction of ray to project. * @param bodiesToEvaluate Arraylist of bodies to check if they intersect with the ray projection. */ private void projectRays(Vectors2D direction, ArrayList<Body> bodiesToEvaluate) { Matrix2D m = new Matrix2D(0.001); m.transpose().mul(direction); for (int i = 0; i < 3; i++) { Ray ray = new Ray(startPoint, direction, distance); ray.updateProjection(bodiesToEvaluate); rayData.add(new RayAngleInformation(ray, Math.atan2(direction.y, direction.x))); m.mul(direction); } } /** * Debug draw method for all polygons generated and rays. * * @param g Graphics2D object to draw to * @param paintSettings Colour settings to draw the objects to screen with * @param camera Camera class used to convert points from world space to view space */ public void draw(Graphics2D g, ColourSettings paintSettings, Camera camera) { for (int i = 0; i < rayData.size(); i++) { Ray ray1 = rayData.get(i).getRAY(); Ray ray2 = rayData.get(i + 1 == rayData.size() ? 0 : i + 1).getRAY(); g.setColor(paintSettings.shadow); Path2D.Double s = new Path2D.Double(); Vectors2D worldStartPoint = camera.convertToScreen(startPoint); s.moveTo(worldStartPoint.x, worldStartPoint.y); if (ray1.getRayInformation() != null) { Vectors2D point1 = camera.convertToScreen(ray1.getRayInformation().getCoord()); s.lineTo(point1.x, point1.y); } if (ray2.getRayInformation() != null) { Vectors2D point2 = camera.convertToScreen(ray2.getRayInformation().getCoord()); s.lineTo(point2.x, point2.y); } s.closePath(); g.fill(s); } } /** * Getter for number of rays projected. * * @return Returns size of raydata. */ public int getNoOfRays() { return rayData.size(); } } /** * Ray information class to store relevant data about rays and any intersection found specific to shadow casting. */ class RayAngleInformation { private final Ray RAY; private final double ANGLE; /** * Constructor to store ray information. * * @param ray Ray of intersection. * @param angle Angle the ray is set to. */ public RayAngleInformation(Ray ray, double angle) { this.RAY = ray; this.ANGLE = angle; } /** * Getter for RAY. * * @return returns RAY. */ public Ray getRAY() { return RAY; } /** * Getter for ANGLE. * * @return returns ANGLE. */ public double getANGLE() { return ANGLE; } }
32.994012
117
0.601996
0b7575b8e08e1f9e34db61978a1035fcd35ae40e
1,877
/*- * #%L * Slice - Core API * %% * Copyright (C) 2012 Wunderman Thompson Technology * %% * 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% */ package com.cognifide.slice.api.scope; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.cognifide.slice.mapper.annotation.SliceResource; import com.google.inject.ScopeAnnotation; /** * Indicates that an object is cached within context scope (see {@link ContextScoped}) for a current resource * path. This means that Slice will create only one instance of the class for a given path within single * request processing. Subsequent injections of the class will result with reusing of already created object. * This is especially useful for heavy {@link SliceResource} classes which map complex repository structures and which * don't change within single request invocation. <br> * <br> * It should be noted that if a resource which is mapped to a {@link SliceResource} class can change during request or * OSGi service invocation (ContextScope) then such a class cannot be annotated by the Cacheable annotation * as it may result in hard-to-track runtime errors. */ @Target({ ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) @ScopeAnnotation public @interface Cacheable { }
40.804348
118
0.765051
93913dc9f2a78a44e277e2a3a5d4eb59db02f36e
9,118
package io.github.yedaxia.musicnote.activity; import android.content.Intent; import android.media.AudioTrack; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.os.Looper; import android.os.Message; import android.view.View; import android.widget.Button; import android.widget.SeekBar; import android.widget.TextView; import androidx.annotation.Nullable; import java.io.IOException; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import io.github.yedaxia.musicnote.R; import io.github.yedaxia.musicnote.app.util.AppUtils; import io.github.yedaxia.musicnote.app.util.BundleKeys; import io.github.yedaxia.musicnote.media.AudioConfig; import io.github.yedaxia.musicnote.media.AudioUtils; import io.github.yedaxia.musicnote.media.PCMAnalyser; import io.github.yedaxia.musicnote.ui.dialog.MListDialog; import io.github.yedaxia.musicnote.util.StringUtils; import io.github.yedaxia.musicnote.view.TabButton; /** * @author Darcy https://yedaxia.github.io/ * @version 2018/2/27. */ public class BeatSettingActivity extends BaseActivity{ private static final String TAG = "BeatSettingActivity"; private static final int STATUS_PLAY_PREPARE = 1; private static final int STATUS_PLAYING =2; private static final short MIN_SPEED = 30; private static final short MAX_SPEED = 240; @BindView(R.id.tv_beat) TextView tvBeat; @BindView(R.id.btn_speed_down) TabButton btnSpeedDown; @BindView(R.id.tv_speed) TextView tvSpeed; @BindView(R.id.btn_speed_up) TabButton btnSpeedUp; @BindView(R.id.sb_speed) SeekBar sbSpeed; @BindView(R.id.btn_play_beat) TabButton btnPlayBeat; @BindView(R.id.tv_tune) TextView tvTune; @BindView(R.id.btn_save) Button btnSave; private AudioTrack audioTrack; private byte[] beatStrongBytes; private byte[] beetWeakBytes; private byte[] playBeatBytes; private int playStatus; private boolean stopPlay; private short currentSpeed; private String currentBeat; private String currentTone; private List<String> toneList = new ArrayList<>(); private Intent beatResult = new Intent(); private PCMAnalyser pcmAudioFile; private BeatPlayHandler beatPlayHandler; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_beat_setting); ButterKnife.bind(this); currentSpeed = getIntent().getShortExtra(BundleKeys.RESULT_SPEED, (short)120); currentBeat = getIntent().getStringExtra(BundleKeys.RESULT_BEAT); currentTone = getIntent().getStringExtra(BundleKeys.RESULT_TUNE); currentBeat = StringUtils.isEmpty(currentBeat)? "4/4" : currentBeat; currentTone = StringUtils.isEmpty(currentTone)? "C" : currentTone; tvTune.setText(String.format("1=%s", currentTone)); tvSpeed.setText(String.valueOf(currentSpeed)); tvBeat.setText(currentBeat); setTitle(R.string.beat_setting); enableBack(); initToneList(); audioTrack = AudioUtils.createTrack(AudioConfig.BEAT_CHANNEL_COUNT); pcmAudioFile = PCMAnalyser.createPCMAnalyser(AudioConfig.BEAT_CHANNEL_COUNT); sbSpeed.setProgress((int)((double)(currentSpeed - MIN_SPEED) / (MAX_SPEED - MIN_SPEED) * 100)); sbSpeed.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { currentSpeed = (short) (MIN_SPEED + (MAX_SPEED - MIN_SPEED) * (progress / 100.0)); refreshSpeed(); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); HandlerThread playBeatHandlerThread = new HandlerThread("PlayBeatHandlerThread"); playBeatHandlerThread.start(); beatPlayHandler = new BeatPlayHandler(playBeatHandlerThread.getLooper()); loadBeatData(); } @OnClick(R.id.btn_play_beat) void onPlayClick(View v){ if(playStatus == STATUS_PLAY_PREPARE){ stopPlay = false; audioTrack.play(); //预写一些填缓冲区 beatPlayHandler.removeMessages(R.integer.PLAY_BEAT); beatPlayHandler.sendEmptyMessage(R.integer.PLAY_BEAT); playStatus= STATUS_PLAYING; }else if(playStatus == STATUS_PLAYING){ stopPlay = true; beatPlayHandler.removeMessages(R.integer.PLAY_BEAT); audioTrack.stop(); playStatus = STATUS_PLAY_PREPARE; } } @OnClick(R.id.tv_beat) void onBeatClick(View v){ new MListDialog.Builder(this) .title(R.string.select_beat) .items(R.array.beats_array) .onItemClick(new MListDialog.OnItemClickListener() { @Override public void onItemClick(MListDialog dialog, int position, CharSequence text) { dialog.dismiss(); refreshBeat(text.toString()); } }) .build() .show(); } @OnClick(R.id.tv_tune) void onTuneClick(View v){ new MListDialog.Builder(this) .title(R.string.select_tone) .items(toneList) .onItemClick(new MListDialog.OnItemClickListener() { @Override public void onItemClick(MListDialog dialog, int position, CharSequence text) { dialog.dismiss(); refreshTune(text.toString()); } }) .build() .show(); } @OnClick(R.id.btn_speed_up) void onSpeedUpClick(View v){ if(currentSpeed != MAX_SPEED){ currentSpeed++; refreshSpeed(); } } @OnClick(R.id.btn_speed_down) void onSpeedDownClick(View v){ if(currentSpeed != MIN_SPEED){ currentSpeed--; refreshSpeed(); } } @OnClick(R.id.btn_save) void onSaveClick(View v){ beatResult.putExtra(BundleKeys.RESULT_SPEED, currentSpeed); beatResult.putExtra(BundleKeys.RESULT_BEAT, currentBeat); beatResult.putExtra(BundleKeys.RESULT_TUNE, currentTone); setResult(RESULT_OK, beatResult); finish(); } @Override protected void onDestroy() { super.onDestroy(); stopPlay = true; audioTrack.release(); audioTrack = null; beatPlayHandler.removeCallbacksAndMessages(null); beatPlayHandler = null; } private synchronized void generatePlayBeatBytes(){ this.playBeatBytes = pcmAudioFile.generateBeatBytes(beatStrongBytes, beetWeakBytes, currentBeat, currentSpeed); audioTrack.flush(); } private void initToneList(){ for(char c = 'A'; c != 'H'; c++){ toneList.add(String.format("%sb",c)); toneList.add(String.valueOf(c)); toneList.add(String.format("%s#",c)); } } private void refreshSpeed(){ tvSpeed.setText(String.valueOf(currentSpeed)); beatPlayHandler.removeMessages(R.integer.REFRESH_BEAT_DATA); beatPlayHandler.sendEmptyMessage(R.integer.REFRESH_BEAT_DATA); } private void refreshBeat(String beatText){ currentBeat = beatText; tvBeat.setText(beatText); beatPlayHandler.removeMessages(R.integer.REFRESH_BEAT_DATA); beatPlayHandler.sendEmptyMessage(R.integer.REFRESH_BEAT_DATA); } private void refreshTune(String tune){ currentTone = tune; tvTune.setText(String.format("1=%s",tune)); } private void loadBeatData(){ new Thread(){ @Override public void run() { try{ byte[][] beatsData = AppUtils.loadBeatSoundData(); beatStrongBytes = beatsData[0]; beetWeakBytes = beatsData[1]; generatePlayBeatBytes(); }catch (IOException ex){ ex.printStackTrace(); } playStatus = STATUS_PLAY_PREPARE; } }.start(); } private class BeatPlayHandler extends Handler { public BeatPlayHandler(Looper looper) { super(looper); } @Override public void handleMessage(Message msg) { if(msg.what == R.integer.REFRESH_BEAT_DATA){ generatePlayBeatBytes(); }else{ if(stopPlay){ return; } audioTrack.write(playBeatBytes, 0, playBeatBytes.length); super.sendEmptyMessage(R.integer.PLAY_BEAT); } } } }
32.798561
119
0.629963
43f44dec27d72c7d369b54770a1a50aed4a5da69
319
package com.nicjansma.tisktasks.test; public abstract class TestConstants { // // test constants // public static final String DEFAULT_USER_EMAIL = "[email protected]"; public static final String DEFAULT_USER_API_KEY = "xyz"; public static final String DEFAULT_USER_PASSWORD = "test"; }
26.583333
69
0.69906
9e3078afa1556209c00f9b8c85fb3e9ba9c88412
3,351
/* * Copyright (c) 2014-2018 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * 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. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.graphql.ui; import com.kumuluz.ee.common.Extension; import com.kumuluz.ee.common.config.EeConfig; import com.kumuluz.ee.common.dependencies.EeExtensionDef; import com.kumuluz.ee.common.wrapper.KumuluzServerWrapper; import com.kumuluz.ee.configuration.utils.ConfigurationUtil; import com.kumuluz.ee.graphql.ui.servlets.GraphQLUIServlet; import com.kumuluz.ee.jetty.JettyServletServer; import java.util.logging.Logger; /** * GraphQLUIExtension class - extension class for hosting GraphiQL * * @author Domen Kajdic * @since 1.0.0 */ @EeExtensionDef(name = "GraphQLUI", group = "GRAPHQL_UI") public class GraphQLUIExtension implements Extension { private static final Logger LOG = Logger.getLogger(GraphQLUIExtension.class.getName()); @Override public void load() { } @Override public void init(KumuluzServerWrapper kumuluzServerWrapper, EeConfig eeConfig) { if (kumuluzServerWrapper.getServer() instanceof JettyServletServer) { LOG.info("Initializing GraphQL UI extension."); ConfigurationUtil configurationUtil = ConfigurationUtil.getInstance(); try { Class.forName("com.kumuluz.ee.graphql.GraphQLExtension"); } catch (ClassNotFoundException e) { LOG.severe("Unable to find GraphQL extension, GraphQL UI will not be initialized: " + e.getMessage()); return; } boolean production = configurationUtil.get("kumuluzee.env.name").orElse("dev").equals("production"); if(configurationUtil.getBoolean("kumuluzee.graphql.ui.enabled").orElse(!production)) { String mapping = configurationUtil.get("kumuluzee.graphql.ui.mapping").orElse("/graphiql"); if(mapping.charAt(0) != '/') { mapping = '/' + mapping; } LOG.info("GraphQL UI registered on " + mapping + " (servlet context is implied)."); JettyServletServer server = (JettyServletServer) kumuluzServerWrapper.getServer(); server.registerServlet(GraphQLUIServlet.class, mapping); LOG.info("GraphQL UI extension initialized."); } else { LOG.info("GraphQL UI disabled. You can enable it explicitly by setting field kumuluzee.graphql.ui.enabled to true."); } } } }
41.37037
133
0.68875
6627e61401aa44cf1d66fd8e2ea7286284b0565b
5,109
package eclipse.tests.exams.matriculation.cs.y2009; import eclipse.utilities.adt.*; import eclipse.utilities.adt.mine.Utilities; import eclipse.utilities.adt.moe.Node; /** * @author GrizzlyMcBear * * @implNote This class contains the solution for question #1. * @implSpec * <ul> * <li>The exam questions could be found <a href="http://blog.csit.org.il/UpLoad/FilesUpload/t205_09.pdf">here</a>.</li> * <li>The MOE topic id is 899205</li> * </ul> * */ public class Question1 { public static boolean isTrinityList(Node<Integer> list) { boolean result = false; if (list != null) {// Only if list isn't empty - continue checking. int length = getListLengthRecursive(list); if (length % 3 == 0) {// Only if list's length divides by 3 without remainder - continue checking. // Check that nodes in the 1st and 2nd thirds are equal Node<Integer> firstThirdNode = list; Node<Integer> secondThirdNode = getListNodeByIndex(list, (length / 3) + 1); if (checkNodesEqual(firstThirdNode, secondThirdNode, length / 3)) { // Check that nodes in the 1st and 3rd thirds are equal. Node<Integer> thirdThirdNode = getListNodeByIndex(list, (length / 3) * 2 + 1); if (checkNodesEqual(firstThirdNode, thirdThirdNode, length / 3)) result = true; } } } return result; } // Find the length of a list using a loop. public static int getListLengthLoop(Node<Integer> list) { int length = 0; Node<Integer> currNode = list; while (currNode != null) { currNode = currNode.getNext(); length++; } return length; } // Find the length of a list using a recursive method. public static int getListLengthRecursive(Node<Integer> list) { int length = 0; if (list != null) length += 1 + getListLengthRecursive(list.getNext()); return length; } // Return a node in the list at the given index. public static Node<Integer> getListNodeByIndex(Node<Integer> list, int index) { Node<Integer> result = null; int currIndex = 0; if (list != null && index >= 0) {// If the list isn't empty and the index is positive result = list; // Advance along the list's nodes: for (currIndex = 1; result != null && currIndex < index; currIndex++) { result = result.getNext(); } } return result; } public static Node<Integer> getListNodeByIndexWhileLoop(Node<Integer> list, int index) { Node<Integer> result = null; int currIndex = 0; if (list != null && index >= 0) {// If the list isn't empty and the index is positive // Reset values result = list; currIndex = 1; // Advance along the list's nodes: while (result != null && currIndex < index) {// While not at the end of the list and haven't reached the desired index yet // Advance to the next node and increment the current index (counter) result = result.getNext(); currIndex++; } } return result; } // Same as method above, only `for` loop is more compact, also we could've used a `while` loop public static Node<Integer> getListNodeByIndexCompactForLoop(Node<Integer> list, int index) { Node<Integer> result = null; int currIndex = 0; if (list != null && index >= 0) {// If the list isn't empty and the index is positive // Advance along the list's nodes: for (result = list, currIndex = 1; // Reset values result != null && currIndex < index; // While not at the end of the list and haven't reached the desired index yet result = result.getNext(), currIndex++); // Advance to the next node and increment the current index (counter) } return result; } /* Checks if `amount` nodes are equal, comparing between 2 node lists: * `first` and `second`. */ public static boolean checkNodesEqual(Node<Integer> first, Node<Integer> second, int amount) { boolean nodesEqual = true; Node<Integer> currFirst; Node<Integer> currSecond; int checkedNodes; for (currFirst = first, currSecond = second, checkedNodes = 0;// Initialize variables currFirst != null && currSecond != null && checkedNodes < amount && nodesEqual; currFirst = currFirst.getNext(), currSecond = currSecond.getNext(), checkedNodes++) { nodesEqual = currFirst.getValue().equals(currSecond.getValue()); } return nodesEqual; } // Runs tests to make sure that the solution is correct public static void checkSolution() { // Empty list Node<Integer> newList = Utilities.createIntegerNodes(null); System.out.println(String.format("The following list is%s a trinity list:\n%s", isTrinityList(newList) ? "" : "n't", "-|")); // List with 1 item newList = Utilities.createIntegerNodes("13"); System.out.println(String.format("The following list is%s a trinity list:\n%s", isTrinityList(newList) ? "" : "n't", newList.toString())); // List in question newList = Utilities.createIntegerNodes("2, 5, 3, 7, 2, 5, 3, 7, 2, 5, 3, 7"); System.out.println(String.format("The following list is%s a trinity list:\n%s", isTrinityList(newList) ? "" : "n't", newList.toString())); } }
31.93125
125
0.667058
504857850163751b9628a55e40fd910339c2e475
485
package wooteco.prolog.report.application.dto.ability; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import wooteco.prolog.report.domain.ablity.Ability; @Getter @NoArgsConstructor @AllArgsConstructor public class AbilityUpdateRequest { private Long id; private String name; private String description; private String color; public Ability toEntity() { return new Ability(id, name, description, color); } }
22.045455
57
0.764948
69e101bef1188f1a106b943f9e69c5b9698dfe57
6,465
package org.clarksnut.report.jasper; import net.sf.jasperreports.engine.JRDataSource; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.data.JRMapCollectionDataSource; import net.sf.jasperreports.engine.export.HtmlExporter; import net.sf.jasperreports.engine.export.JRPdfExporter; import net.sf.jasperreports.export.Exporter; import net.sf.jasperreports.export.SimpleExporterInput; import net.sf.jasperreports.export.SimpleHtmlExporterOutput; import net.sf.jasperreports.export.SimpleOutputStreamExporterOutput; import org.clarksnut.datasource.DatasourceFactory; import org.clarksnut.datasource.DatasourceProvider; import org.clarksnut.files.*; import org.clarksnut.models.DocumentModel; import org.clarksnut.models.exceptions.ImpossibleToUnmarshallException; import org.clarksnut.report.*; import org.clarksnut.report.exceptions.ReportException; import org.jboss.logging.Logger; import javax.ejb.Stateless; import javax.inject.Inject; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.lang.reflect.Field; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; @Stateless public class JasperReportProvider implements ReportTemplateProvider { private static final Logger logger = Logger.getLogger(JasperReportProvider.class); @Inject private JasperReportUtil jasperReportUtil; @Inject @ReportProviderType(type = ReportProviderType.Type.EXTENDING) private ReportThemeProvider themeProvider; @Override public ReportTheme getTheme(String name, String type) { try { return themeProvider.getTheme(name, type); } catch (IOException e) { return null; } } @Override public byte[] getReport(ReportTemplateConfiguration config, DocumentModel document, ExportFormat exportFormat) throws ReportException { try { String themeName = config.getThemeName() != null ? config.getThemeName().toLowerCase() : null; String themeType = document.getType().toLowerCase(); ReportTheme theme = themeProvider.getTheme(themeName, themeType); XmlUBLFileModel ublFile = new FlyWeightXmlUBLFileModel( new BasicXmlUBLFileModel( new FlyWeightXmlFileModel( new BasicXmlFileModel( new FlyWeightFileModel(document.getCurrentVersion().getImportedDocument().getFile()) ) ) ) ); DatasourceProvider datasourceProvider = DatasourceFactory.getInstance().getDatasourceProvider(theme.getDatasource()); Object bean = datasourceProvider.getDatasource(ublFile); Map<String, Object> beanMap = toMap(bean, "bean"); Map<String, Object> modelMap = toMap(toModelBean(document), "model"); beanMap.putAll(modelMap); JRDataSource dataSource = new JRMapCollectionDataSource(Collections.singletonList(beanMap)); JasperPrint jasperPrint = jasperReportUtil.processReport(theme, theme.getName(), config.getAttributes(), dataSource, config.getLocale()); return export(jasperPrint, exportFormat); } catch (IOException e) { throw new ReportException("Could not read a resource on template", e); } catch (JRException e) { throw new ReportException("Failed to process jasper report", e); } catch (IllegalAccessException e) { throw new ReportException("Failed to map fields jasper report", e); } catch (ImpossibleToUnmarshallException e) { throw new ReportException(e.getMessage(), e); } } protected byte[] export(final JasperPrint print, ExportFormat format) throws JRException { final Exporter exporter; final ByteArrayOutputStream out = new ByteArrayOutputStream(); boolean html = false; switch (format) { case HTML: exporter = new HtmlExporter(); exporter.setExporterOutput(new SimpleHtmlExporterOutput(out)); html = true; break; case PDF: exporter = new JRPdfExporter(); break; default: throw new JRException("Unknown report format: " + format.toString()); } if (!html) { exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(out)); } exporter.setExporterInput(new SimpleExporterInput(print)); exporter.exportReport(); return out.toByteArray(); } public ModelBean toModelBean(DocumentModel document) { ModelBean bean = new ModelBean(); bean.setType(document.getType()); bean.setAssignedId(document.getAssignedId()); bean.setSupplierAssignedId(document.getSupplierAssignedId()); bean.setCustomerAssignedId(document.getCustomerAssignedId()); bean.setAmount(document.getAmount()); bean.setTax(document.getTax()); bean.setCurrency(document.getCurrency()); bean.setIssueDate(document.getIssueDate()); bean.setSupplierName(document.getSupplierName()); bean.setCustomerName(document.getCustomerName()); bean.setSupplierStreetAddress(document.getSupplierStreetAddress()); bean.setSupplierCity(document.getSupplierCity()); bean.setSupplierCountry(document.getSupplierCountry()); bean.setCustomerStreetAddress(document.getCustomerStreetAddress()); bean.setCustomerCity(document.getCustomerCity()); bean.setCustomerCountry(document.getCustomerCountry()); bean.setLocation("www.clakrsnut.com"); return bean; } public Map<String, Object> toMap(Object obj, String... prefixes) throws IllegalAccessException { String prefix = Stream.of(prefixes).collect(Collectors.joining("_")); prefix = prefix.isEmpty() ? "" : prefix + "_"; Map<String, Object> map = new HashMap<>(); Field[] fields = obj.getClass().getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); map.put(prefix + field.getName(), field.get(obj)); } return map; } }
39.662577
149
0.676566
cc22f92fd56fa9dd5594438f774da1404dab9e6a
1,994
package com.acmebank.accountmanager.exception; public class BusinessException extends Exception { public static final ErrorCode BAD_REQUEST = new ErrorCode(400001, 400, "Bad request"); public static final ErrorCode INVALID_METHOD_ARGUMENT = new ErrorCode(400002, 400, "Invalid method argument"); public static final ErrorCode TYPE_MISMATCH = new ErrorCode(400003, 400, "Type mismatch"); public static final ErrorCode METHOD_ARGUMENT_TYPE_MISMATCH = new ErrorCode(400004, 400, "Method argument type mismatch"); public static final ErrorCode CONSTRAINT_VIOLATION = new ErrorCode(400005, 400, "Constraint violation"); public static final ErrorCode NOT_FOUND = new ErrorCode(404001, 400, "Not found"); public static final ErrorCode ACCOUNT_NOT_EXISTS = new ErrorCode(404002, 400, "Account not exists"); public static final ErrorCode METHOD_NOT_ALLOWED = new ErrorCode(405001, 400, "Method not allowed"); public static final ErrorCode UNKNOWN_ERROR = new ErrorCode(500001, 500, "Unknown error"); public static final ErrorCode INTERNAL_ERROR = new ErrorCode(500002, 500, "Internal error"); private ErrorCode errorCode; private String customeMessage = null; public BusinessException() { super(UNKNOWN_ERROR.getMsg()); this.errorCode = UNKNOWN_ERROR; } public BusinessException(ErrorCode errorCode) { super(errorCode.getMsg()); this.errorCode = errorCode; } public BusinessException(ErrorCode errorCode, String customeMessage) { super(errorCode.getMsg()); this.errorCode = errorCode; this.customeMessage = customeMessage; } public int getCode() { return errorCode.getCode(); } public int getHttpCode() { return errorCode.getHttpCode(); } @Override public String getMessage() { if (customeMessage == null) { return errorCode.getMsg(); } else { return customeMessage; } } }
37.622642
126
0.703109
b0d5fe50655891e83a10d1e75ca05e3dcab2ffaf
7,033
/* * 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.accumulo.test.continuous; import static com.google.common.base.Charsets.UTF_8; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map.Entry; import java.util.Random; import java.util.zip.CRC32; import org.apache.accumulo.core.Constants; import org.apache.accumulo.core.client.Connector; import org.apache.accumulo.core.client.Scanner; import org.apache.accumulo.core.data.Key; import org.apache.accumulo.core.data.Range; import org.apache.accumulo.core.data.Value; import org.apache.accumulo.core.security.Authorizations; import org.apache.accumulo.trace.instrument.Span; import org.apache.accumulo.trace.instrument.Trace; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.Text; import com.beust.jcommander.IStringConverter; import com.beust.jcommander.Parameter; public class ContinuousWalk { static public class Opts extends ContinuousQuery.Opts { class RandomAuthsConverter implements IStringConverter<RandomAuths> { @Override public RandomAuths convert(String value) { try { return new RandomAuths(value); } catch (IOException e) { throw new RuntimeException(e); } } } @Parameter(names = "--authsFile", description = "read the authorities to use from a file") RandomAuths randomAuths = new RandomAuths(); } static class BadChecksumException extends RuntimeException { private static final long serialVersionUID = 1L; public BadChecksumException(String msg) { super(msg); } } static class RandomAuths { private List<Authorizations> auths; RandomAuths() { auths = Collections.singletonList(Constants.NO_AUTHS); } RandomAuths(String file) throws IOException { if (file == null) { auths = Collections.singletonList(Constants.NO_AUTHS); return; } auths = new ArrayList<Authorizations>(); FileSystem fs = FileSystem.get(new Configuration()); BufferedReader in = new BufferedReader(new InputStreamReader(fs.open(new Path(file)), UTF_8)); try { String line; while ((line = in.readLine()) != null) { auths.add(new Authorizations(line.split(","))); } } finally { in.close(); } } Authorizations getAuths(Random r) { return auths.get(r.nextInt(auths.size())); } } public static void main(String[] args) throws Exception { Opts opts = new Opts(); opts.parseArgs(ContinuousWalk.class.getName(), args); Connector conn = opts.getConnector(); Random r = new Random(); ArrayList<Value> values = new ArrayList<Value>(); while (true) { Scanner scanner = ContinuousUtil.createScanner(conn, opts.getTableName(), opts.randomAuths.getAuths(r)); String row = findAStartRow(opts.min, opts.max, scanner, r); while (row != null) { values.clear(); long t1 = System.currentTimeMillis(); Span span = Trace.on("walk"); try { scanner.setRange(new Range(new Text(row))); for (Entry<Key,Value> entry : scanner) { validate(entry.getKey(), entry.getValue()); values.add(entry.getValue()); } } finally { span.stop(); } long t2 = System.currentTimeMillis(); System.out.printf("SRQ %d %s %d %d%n", t1, row, (t2 - t1), values.size()); if (values.size() > 0) { row = getPrevRow(values.get(r.nextInt(values.size()))); } else { System.out.printf("MIS %d %s%n", t1, row); System.err.printf("MIS %d %s%n", t1, row); row = null; } if (opts.sleepTime > 0) Thread.sleep(opts.sleepTime); } if (opts.sleepTime > 0) Thread.sleep(opts.sleepTime); } } private static String findAStartRow(long min, long max, Scanner scanner, Random r) { byte[] scanStart = ContinuousIngest.genRow(min, max, r); scanner.setRange(new Range(new Text(scanStart), null)); scanner.setBatchSize(100); int count = 0; String pr = null; long t1 = System.currentTimeMillis(); for (Entry<Key,Value> entry : scanner) { validate(entry.getKey(), entry.getValue()); pr = getPrevRow(entry.getValue()); count++; if (pr != null) break; } long t2 = System.currentTimeMillis(); System.out.printf("FSR %d %s %d %d%n", t1, new String(scanStart, UTF_8), (t2 - t1), count); return pr; } static int getPrevRowOffset(byte val[]) { if (val.length == 0) throw new IllegalArgumentException(); if (val[53] != ':') throw new IllegalArgumentException(new String(val, UTF_8)); // prev row starts at 54 if (val[54] != ':') { if (val[54 + 16] != ':') throw new IllegalArgumentException(new String(val, UTF_8)); return 54; } return -1; } static String getPrevRow(Value value) { byte[] val = value.get(); int offset = getPrevRowOffset(val); if (offset > 0) { return new String(val, offset, 16, UTF_8); } return null; } static int getChecksumOffset(byte val[]) { if (val[val.length - 1] != ':') { if (val[val.length - 9] != ':') throw new IllegalArgumentException(new String(val, UTF_8)); return val.length - 8; } return -1; } static void validate(Key key, Value value) throws BadChecksumException { int ckOff = getChecksumOffset(value.get()); if (ckOff < 0) return; long storedCksum = Long.parseLong(new String(value.get(), ckOff, 8, UTF_8), 16); CRC32 cksum = new CRC32(); cksum.update(key.getRowData().toArray()); cksum.update(key.getColumnFamilyData().toArray()); cksum.update(key.getColumnQualifierData().toArray()); cksum.update(key.getColumnVisibilityData().toArray()); cksum.update(value.get(), 0, ckOff); if (cksum.getValue() != storedCksum) { throw new BadChecksumException("Checksum invalid " + key + " " + value); } } }
29.304167
110
0.652069
85515b217e8517808c601ec5a82c23352ac10aa5
1,089
package br.com.hmv.dtos.responses.administrativo; import br.com.hmv.models.entities.ConvenioAdministrativo; import br.com.hmv.models.enums.StatusConvenioEnum; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; import lombok.NoArgsConstructor; import java.time.LocalDateTime; @Data @NoArgsConstructor public class ConvenioDefaultResponseDTO { private static final long serialVersionUID = 1L; private Long id; private String descricao; @JsonProperty("status") private StatusConvenioEnum statusConvenio; @JsonProperty("data_criacao") private LocalDateTime dataCriacao; @JsonProperty("data_atualizacao") private LocalDateTime dataAtualizacao; //Construtor diferenciado public ConvenioDefaultResponseDTO(ConvenioAdministrativo entity) { id = entity.getId(); descricao = entity.getDescricao(); statusConvenio = StatusConvenioEnum.obterStatusConvenio(entity.getCodigoStatusConvenio()); dataCriacao = entity.getDataCriacao(); dataAtualizacao = entity.getDataAtualizacao(); } }
28.657895
98
0.76584
4702ee9bcb96b91f011a9d5b8dce24997898fa2b
960
// 2021.05.21 // Leetcode 第 213 题 // https://leetcode-cn.com/problems/house-robber-ii/ package DynamicProgramming; public class T213 { public static void main(String[] args) { T213 solution = new T213(); int[] nums = { 2, 3, 2 }; int[] nums2 = { 1, 2, 3, 1 }; System.out.println(solution.rob(nums)); System.out.println(solution.rob(nums2)); } public int rob(int[] nums) { if (nums == null || nums.length == 0) { return 0; } int n = nums.length; if (n == 1) { return nums[0]; } return Math.max(rob(nums, 0, n - 2), rob(nums, 1, n - 1)); } private int rob(int[] nums, int start, int end) { int pre2 = 0; int pre1 = 0; for (int i = start; i <= end; i++) { int cur = Math.max(pre2 + nums[i], pre1); pre2 = pre1; pre1 = cur; } return pre1; } }
22.325581
66
0.480208
0de5d5e4fa02fd16ef13f5fec84a0fa5821ad8b1
1,470
/* * Copyright 2019 Dhiego Cassiano Fogaça Barbosa * * 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 app; import app.database.Connections; import app.ui.MainWindow; import com.modscleo4.ui.ExceptionDialog; import javax.swing.*; import java.io.File; import java.io.FileNotFoundException; /** * Main class of project. * * @author Dhiego Cassiano Fogaça Barbosa <[email protected]> */ public class Main { public static void main(String[] args) { try { Thread.setDefaultUncaughtExceptionHandler((t, e) -> ExceptionDialog.show(e)); Connections.envdir = "./"; UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); if (!new File(".env").exists()) { throw new FileNotFoundException(".env not found."); } new MainWindow().setVisible(true); } catch (Exception e) { ExceptionDialog.show(e); } } }
28.823529
89
0.67551
be04104a6b88ba3cd7c006fc97e31746af4a1f36
250
package com.test.privat.currency.models.utils; import java.math.BigDecimal; public class StringUtils { public static String getPercentage(BigDecimal digit) { return digit.multiply(BigDecimal.valueOf(100)).toPlainString() + "%"; } }
25
77
0.732
e95b5e4d01ec1789905e6927329a5788496688de
3,974
/* * Landscape omnikeeper REST API * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: v1 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package org.openapitools.client.api; import org.openapitools.client.ApiException; import org.openapitools.client.model.AddContextRequest; import org.openapitools.client.model.ChangeDataRequest; import org.openapitools.client.model.EditContextRequest; import org.openapitools.client.model.ProblemDetails; import org.junit.Test; import org.junit.Ignore; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * API tests for GridViewApi */ @Ignore public class GridViewApiTest { private final GridViewApi api = new GridViewApi(); /** * Adds new context * * * * @throws ApiException * if the Api call fails */ @Test public void addContextTest() throws ApiException { String version = null; AddContextRequest addContextRequest = null; api.addContext(version, addContextRequest); // TODO: test validations } /** * Saves grid view row changes and returns change results * * * * @throws ApiException * if the Api call fails */ @Test public void changeDataTest() throws ApiException { String context = null; String version = null; ChangeDataRequest changeDataRequest = null; api.changeData(context, version, changeDataRequest); // TODO: test validations } /** * Deletes specific context * * * * @throws ApiException * if the Api call fails */ @Test public void deleteContextTest() throws ApiException { String name = null; String version = null; api.deleteContext(name, version); // TODO: test validations } /** * Edits specific context * * * * @throws ApiException * if the Api call fails */ @Test public void editContextTest() throws ApiException { String name = null; String version = null; EditContextRequest editContextRequest = null; api.editContext(name, version, editContextRequest); // TODO: test validations } /** * Returns a single context in full * * * * @throws ApiException * if the Api call fails */ @Test public void getContextTest() throws ApiException { String name = null; String version = null; api.getContext(name, version); // TODO: test validations } /** * Returns a list of contexts for grid view. * * * * @throws ApiException * if the Api call fails */ @Test public void getContextsTest() throws ApiException { String version = null; api.getContexts(version); // TODO: test validations } /** * Returns grid view data for specific context * * * * @throws ApiException * if the Api call fails */ @Test public void getDataTest() throws ApiException { String context = null; String version = null; api.getData(context, version); // TODO: test validations } /** * Returns grid view schema for specific context * * * * @throws ApiException * if the Api call fails */ @Test public void getSchemaTest() throws ApiException { String context = null; String version = null; api.getSchema(context, version); // TODO: test validations } }
22.579545
109
0.597383
86f5a7298c79a0427be410289f9ace1ca1b47bfe
672
package me.bytebeats.mns.tool; import com.github.promeg.pinyinhelper.Pinyin; /** * @author <a href="https://github.com/bytebeats">bytebeats</a> * @email <[email protected]> * @since 2020/8/19 16:48 */ public class PinyinUtils { public static String toPinyin(String input) { StringBuilder pinyins = new StringBuilder(); for (char ch : input.toCharArray()) { char[] pys = Pinyin.toPinyin(ch).toLowerCase().toCharArray(); if (pys.length > 0) { pys[0] = Character.toUpperCase(pys[0]); pinyins.append(String.valueOf(pys)); } } return pinyins.toString(); } }
29.217391
73
0.60119
9e6523fe942eef8db6673af955d476a3922a0ebb
1,479
package eu.rcauth.delegserver.storage.sql.table; import edu.uiuc.ncsa.myproxy.oa4mp.oauth2.storage.OA2TransactionKeys; import edu.uiuc.ncsa.myproxy.oa4mp.oauth2.storage.OA2TransactionTable; import edu.uiuc.ncsa.security.storage.sql.internals.ColumnDescriptorEntry; import java.sql.Types; import eu.rcauth.delegserver.storage.DSOA2TransactionKeys; public class DSOA2TransactionTable extends OA2TransactionTable { public DSOA2TransactionTable(OA2TransactionKeys keys, String schema, String tablenamePrefix, String tablename) { super(keys, schema, tablenamePrefix, tablename); } @Override public void createColumnDescriptors() { super.createColumnDescriptors(); getColumnDescriptor().add(new ColumnDescriptorEntry( ((DSOA2TransactionKeys)getOA2Keys()).claims(), Types.LONGVARCHAR)); getColumnDescriptor().add(new ColumnDescriptorEntry( ((DSOA2TransactionKeys)getOA2Keys()).user_attributes(), Types.LONGVARCHAR)); getColumnDescriptor().add(new ColumnDescriptorEntry( ((DSOA2TransactionKeys)getOA2Keys()).cn_hash() , Types.LONGVARCHAR)); getColumnDescriptor().add(new ColumnDescriptorEntry( ((DSOA2TransactionKeys)getOA2Keys()).sequence_nr() , Types.SMALLINT)); } }
49.3
116
0.651792
5af03e8887e467ce067ae5c11c2e76b4bfd6c670
571
package kvj.taskw.data; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import org.kvj.bravo7.log.Logger; import kvj.taskw.App; /** * Created by kvorobyev on 11/25/15. */ public class BootReceiver extends BroadcastReceiver { Controller controller = App.controller(); Logger logger = Logger.forInstance(this); @Override public void onReceive(Context context, Intent intent) { logger.i("Application started"); controller.messageShort("Auto-sync timers have started"); } }
22.84
65
0.730298
f60dcfba90189d92fc3257f5bf87b4fcb2f8de7e
3,655
package com.zxj.resolver; import com.zxj.model.Table; import com.zxj.util.GenerateConfig; import com.zxj.util.JdbcConnectionFactory; import com.zxj.util.PathUtil; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.Properties; /** * Created by zxj on 2017/5/2. */ public class CodeGenerateResolver { GenerateConfig generateConfig = GenerateConfig.getInstance(); private Properties p; private JdbcConnectionFactory jdbcConnectionFactory; private File baseDir; public CodeGenerateResolver(Properties p, File baseDir) { this.p = p; this.jdbcConnectionFactory = new JdbcConnectionFactory(p); this.baseDir = baseDir; } public void generate() { try { MysqlDaoResolver mysqlDaoResolver = new MysqlDaoResolver(jdbcConnectionFactory); for (String tableName : generateConfig.tableName.split(",")) { Table table = mysqlDaoResolver.getTable(tableName); if (table.getPrimaryKeyName() == null || table.getPrimaryKeyName().equals("")) { throw new RuntimeException(String.format("表【%s】必须要有主键", tableName)); } ObjectResolver resolver = new ObjectResolver(); if (generateConfig.genModel) { resolver.gen(p, table, PathUtil.getModelPath(baseDir.getAbsolutePath(), tableName), "javaModel.ftl", false); } if (generateConfig.genDao) { resolver.gen(p, table, PathUtil.getDaoPath(baseDir.getAbsolutePath(), tableName), "javaDao.ftl", false); } if (generateConfig.genMapper) { resolver.gen(p, table, PathUtil.getMapperPath(baseDir.getAbsolutePath(), tableName), "xmlMapper.ftl", false); } if (generateConfig.genService) { resolver.gen(p, table, PathUtil.getServicePath(baseDir.getAbsolutePath(), tableName), "javaService.ftl", false); } if (generateConfig.genProvider) { resolver.gen(p, table, PathUtil.getServiceImplPath(baseDir.getAbsolutePath(), tableName), "javaServiceImpl.ftl", false); } if (generateConfig.genTest) { resolver.gen(p, table, PathUtil.getTestPath(baseDir.getAbsolutePath(), tableName), "test.ftl", false); } } } catch (Exception e) { System.out.println(e.getMessage()); throw new RuntimeException(e); } } public static void main(String[] args) throws Exception { Properties p = new Properties(); try { String path = "E:\\56top\\code\\archetype-2017\\src\\main\\resources\\code-generate.properties"; p.load(new InputStreamReader(new FileInputStream(path), "UTF-8")); } catch (IOException e) { throw new RuntimeException("加载配置文件出错", e); } JdbcConnectionFactory jdbcConnectionFactory = new JdbcConnectionFactory(); MysqlDaoResolver mysqlDaoResolver = new MysqlDaoResolver(jdbcConnectionFactory); Table table = mysqlDaoResolver.getTable("share_company_website"); ObjectResolver resolver = new ObjectResolver(); resolver.gen(p, table, "D:/aaa/ShareCompanyWebsite.java", "javaModel.ftl", true); // resolver.gen(p, table, "D:/aaa/FinancePayReceiveDao.java", "javaDao.ftl", false); // resolver.gen(p, table, "D:/aaa/t_finance_pay_receive.xml", "xmlMapper.ftl", false); System.out.println(table); } }
42.011494
140
0.630369
bfc69fc6d43ff7c4d24e4de9953ee8c73ecccccb
14,182
/* * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.bigtable.hbase.adapters.admin; import com.google.bigtable.admin.v2.ColumnFamily; import com.google.bigtable.admin.v2.GcRule; import com.google.bigtable.admin.v2.GcRule.Intersection; import com.google.bigtable.admin.v2.GcRule.RuleCase; import com.google.bigtable.admin.v2.GcRule.Union; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.protobuf.Duration; import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.HConstants; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; /** * Adapt a single instance of an HBase {@link org.apache.hadoop.hbase.HColumnDescriptor} to * an instance of {@link com.google.bigtable.admin.v2.ColumnFamily} * * @author sduskis * @version $Id: $Id */ public class ColumnDescriptorAdapter { public static final ColumnDescriptorAdapter INSTANCE = new ColumnDescriptorAdapter(); /** * Configuration keys that we can support unconditionally and we provide * a mapped version of the column descriptor to Bigtable. */ public static final Set<String> SUPPORTED_OPTION_KEYS = ImmutableSet.of( HColumnDescriptor.MIN_VERSIONS, HColumnDescriptor.TTL, HConstants.VERSIONS); /** * Configuration keys that we ignore unconditionally */ public static final Set<String> IGNORED_OPTION_KEYS = ImmutableSet.of( HColumnDescriptor.COMPRESSION, HColumnDescriptor.COMPRESSION_COMPACT, HColumnDescriptor.DATA_BLOCK_ENCODING, HColumnDescriptor.BLOCKCACHE, HColumnDescriptor.CACHE_DATA_ON_WRITE, HColumnDescriptor.CACHE_INDEX_ON_WRITE, HColumnDescriptor.CACHE_BLOOMS_ON_WRITE, HColumnDescriptor.EVICT_BLOCKS_ON_CLOSE, HColumnDescriptor.CACHE_DATA_IN_L1, HColumnDescriptor.PREFETCH_BLOCKS_ON_OPEN, HColumnDescriptor.BLOCKSIZE, HColumnDescriptor.BLOOMFILTER, HColumnDescriptor.REPLICATION_SCOPE, HConstants.IN_MEMORY); /** * Configuration option values that we ignore as long as the value is the one specified below. * Any other value results in an exception. */ public static final Map<String, String> SUPPORTED_OPTION_VALUES = ImmutableMap.of( HColumnDescriptor.KEEP_DELETED_CELLS, Boolean.toString(false), HColumnDescriptor.COMPRESS_TAGS, Boolean.toString(false)); /** * Build a list of configuration keys that we don't know how to handle * * @param columnDescriptor a {@link org.apache.hadoop.hbase.HColumnDescriptor} object. * @return a {@link java.util.List} object. */ public static List<String> getUnknownFeatures(HColumnDescriptor columnDescriptor) { List<String> unknownFeatures = new ArrayList<String>(); for (Map.Entry<String, String> entry : columnDescriptor.getConfiguration().entrySet()) { String key = entry.getKey(); if (!SUPPORTED_OPTION_KEYS.contains(key) && !IGNORED_OPTION_KEYS.contains(key) && !SUPPORTED_OPTION_VALUES.containsKey(key)) { unknownFeatures.add(key); } } return unknownFeatures; } /** * Build a Map of configuration keys and values describing configuration values we don't support. * * @param columnDescriptor a {@link org.apache.hadoop.hbase.HColumnDescriptor} object. * @return a {@link java.util.Map} object. */ public static Map<String, String> getUnsupportedFeatures(HColumnDescriptor columnDescriptor) { Map<String, String> unsupportedConfiguration = new HashMap<String, String>(); Map<String, String> configuration = columnDescriptor.getConfiguration(); for (Map.Entry<String, String> entry : SUPPORTED_OPTION_VALUES.entrySet()) { if (configuration.containsKey(entry.getKey()) && configuration.get(entry.getKey()) != null && !entry.getValue().equals(configuration.get(entry.getKey()))) { unsupportedConfiguration.put(entry.getKey(), configuration.get(entry.getKey())); } } return unsupportedConfiguration; } /** * Throw an {@link java.lang.UnsupportedOperationException} if the column descriptor cannot be adapted due * to it having unknown configuration keys. * * @param columnDescriptor a {@link org.apache.hadoop.hbase.HColumnDescriptor} object. */ public static void throwIfRequestingUnknownFeatures(HColumnDescriptor columnDescriptor) { List<String> unknownFeatures = getUnknownFeatures(columnDescriptor); if (!unknownFeatures.isEmpty()) { String featureString = String.format( "Unknown configuration options: [%s]", Joiner.on(", ").join(unknownFeatures)); throw new UnsupportedOperationException(featureString); } } /** * Throw an {@link java.lang.UnsupportedOperationException} if the column descriptor cannot be adapted due * to it having configuration values that are not supported. * * @param columnDescriptor a {@link org.apache.hadoop.hbase.HColumnDescriptor} object. */ public static void throwIfRequestingUnsupportedFeatures(HColumnDescriptor columnDescriptor) { Map<String, String> unsupportedConfiguration = getUnsupportedFeatures(columnDescriptor); if (!unsupportedConfiguration.isEmpty()) { List<String> configurationStrings = new ArrayList<String>(unsupportedConfiguration.size()); for (Map.Entry<String, String> entry : unsupportedConfiguration.entrySet()) { configurationStrings.add(String.format("(%s: %s)", entry.getKey(), entry.getValue())); } String exceptionMessage = String.format( "Unsupported configuration options: %s", Joiner.on(",").join(configurationStrings)); throw new UnsupportedOperationException(exceptionMessage); } } /** * Construct an Bigtable {@link com.google.bigtable.admin.v2.GcRule} from the given column descriptor. * * @param columnDescriptor a {@link org.apache.hadoop.hbase.HColumnDescriptor} object. * @return a {@link com.google.bigtable.admin.v2.GcRule} object. */ public static GcRule buildGarbageCollectionRule(HColumnDescriptor columnDescriptor) { int maxVersions = columnDescriptor.getMaxVersions(); int minVersions = columnDescriptor.getMinVersions(); int ttlSeconds = columnDescriptor.getTimeToLive(); Preconditions.checkState(minVersions < maxVersions, "HColumnDescriptor min versions must be less than max versions."); if (ttlSeconds == HColumnDescriptor.DEFAULT_TTL) { if (maxVersions == Integer.MAX_VALUE) { return null; } else { return maxVersions(maxVersions); } } // minVersions only comes into play with a TTL: GcRule ageRule = maxAge(ttlSeconds); if (minVersions != HColumnDescriptor.DEFAULT_MIN_VERSIONS) { // The logic here is: only delete a cell if: // 1) the age is older than :ttlSeconds AND // 2) the cell's relative version number is greater than :minVersions // // Bigtable's nomenclature for this is: // Intersection (AND) // - maxAge = :HBase_ttlSeconds // - maxVersions = :HBase_minVersion ageRule = intersection(ageRule, maxVersions(minVersions)); } if (maxVersions == Integer.MAX_VALUE) { return ageRule; } else { return union(ageRule, maxVersions(maxVersions)); } } @VisibleForTesting static GcRule intersection(GcRule... rules) { return GcRule.newBuilder() .setIntersection(Intersection.newBuilder().addAllRules(Arrays.asList(rules)).build()) .build(); } @VisibleForTesting static GcRule union(GcRule... rules) { return GcRule.newBuilder() .setUnion(Union.newBuilder().addAllRules(Arrays.asList(rules)).build()) .build(); } private static Duration duration(int ttlSeconds) { return Duration.newBuilder().setSeconds(ttlSeconds).build(); } @VisibleForTesting static GcRule maxAge(int ttlSeconds) { return GcRule.newBuilder().setMaxAge(duration(ttlSeconds)).build(); } @VisibleForTesting static GcRule maxVersions(int maxVersions) { return GcRule.newBuilder().setMaxNumVersions(maxVersions).build(); } /** * <p> * Parse a Bigtable {@link GcRule} that is in line with * {@link #buildGarbageCollectionRule(HColumnDescriptor)} into the provided * {@link HColumnDescriptor}. * </p> * <p> * This method will likely throw IllegalStateException or IllegalArgumentException if the GC Rule * isn't similar to {@link #buildGarbageCollectionRule(HColumnDescriptor)}'s rule. * </p> */ private static void convertGarbageCollectionRule(GcRule gcRule, HColumnDescriptor columnDescriptor) { // The Bigtable default is to have infinite versions. columnDescriptor.setMaxVersions(Integer.MAX_VALUE); if (gcRule == null || gcRule.equals(GcRule.getDefaultInstance())) { return; } switch(gcRule.getRuleCase()) { case MAX_AGE: columnDescriptor.setTimeToLive((int) gcRule.getMaxAge().getSeconds()); return; case MAX_NUM_VERSIONS: columnDescriptor.setMaxVersions(gcRule.getMaxNumVersions()); return; case INTERSECTION: { // minVersions and maxAge are set. processIntersection(gcRule, columnDescriptor); return; } case UNION: { // (minVersion && maxAge) || maxVersions List<GcRule> unionRules = gcRule.getUnion().getRulesList(); Preconditions.checkArgument(unionRules.size() == 2, "Cannot process rule " + gcRule); if (hasRule(unionRules, RuleCase.INTERSECTION)) { processIntersection(getRule(unionRules, RuleCase.INTERSECTION), columnDescriptor); } else { columnDescriptor .setTimeToLive((int) getRule(unionRules, RuleCase.MAX_AGE).getMaxAge().getSeconds()); } columnDescriptor.setMaxVersions(getVersionCount(unionRules)); return; } default: throw new IllegalArgumentException("Could not proess gc rules: " + gcRule); } } /** * <p>processIntersection.</p> * * @param gcRule a {@link com.google.bigtable.admin.v2.GcRule} object. * @param columnDescriptor a {@link org.apache.hadoop.hbase.HColumnDescriptor} object. */ protected static void processIntersection(GcRule gcRule, HColumnDescriptor columnDescriptor) { // minVersions and maxAge are set. List<GcRule> intersectionRules = gcRule.getIntersection().getRulesList(); Preconditions.checkArgument(intersectionRules.size() == 2, "Cannot process rule " + gcRule); columnDescriptor.setMinVersions(getVersionCount(intersectionRules)); columnDescriptor.setTimeToLive(getTtl(intersectionRules)); } private static int getVersionCount(List<GcRule> intersectionRules) { return getRule(intersectionRules, RuleCase.MAX_NUM_VERSIONS).getMaxNumVersions(); } private static int getTtl(List<GcRule> intersectionRules) { return (int) getRule(intersectionRules, RuleCase.MAX_AGE).getMaxAge().getSeconds(); } private static GcRule getRule(List<GcRule> intersectionRules, RuleCase ruleCase) { for (GcRule gcRule : intersectionRules) { if (gcRule.getRuleCase() == ruleCase) { return gcRule; } } throw new IllegalStateException("Could not get process: " + intersectionRules); } private static boolean hasRule(List<GcRule> intersectionRules, RuleCase ruleCase) { for (GcRule gcRule : intersectionRules) { if (gcRule.getRuleCase() == ruleCase) { return true; } } return false; } /** * <p>Adapt a single instance of an HBase {@link org.apache.hadoop.hbase.HColumnDescriptor} to * an instance of {@link com.google.bigtable.admin.v2.ColumnFamily.Builder}.</p> * * <p>NOTE: This method does not set the name of the ColumnFamily.Builder. The assumption is * that the CreateTableRequest or CreateColumFamilyRequest takes care of the naming. As of now * (3/11/2015), the server insists on having a blank name.</p> * * @param columnDescriptor a {@link org.apache.hadoop.hbase.HColumnDescriptor} object. * @return a {@link com.google.bigtable.admin.v2.ColumnFamily.Builder} object. */ public ColumnFamily adapt(HColumnDescriptor columnDescriptor) { throwIfRequestingUnknownFeatures(columnDescriptor); throwIfRequestingUnsupportedFeatures(columnDescriptor); ColumnFamily.Builder resultBuilder = ColumnFamily.newBuilder(); GcRule gcRule = buildGarbageCollectionRule(columnDescriptor); if (gcRule != null) { resultBuilder.setGcRule(gcRule); } return resultBuilder.build(); } /** * Convert a Bigtable {@link com.google.bigtable.admin.v2.ColumnFamily} to an HBase {@link org.apache.hadoop.hbase.HColumnDescriptor}. * See {@link #convertGarbageCollectionRule(GcRule, HColumnDescriptor)} for more info. * * @param familyName a {@link java.lang.String} object. * @param columnFamily a {@link com.google.bigtable.admin.v2.ColumnFamily} object. * @return a {@link org.apache.hadoop.hbase.HColumnDescriptor} object. */ public HColumnDescriptor adapt(String familyName, ColumnFamily columnFamily) { HColumnDescriptor hColumnDescriptor = new HColumnDescriptor(familyName); convertGarbageCollectionRule(columnFamily.getGcRule(), hColumnDescriptor); return hColumnDescriptor; } }
39.176796
136
0.717388
cdd1d1ed67acc410514fea66712ef2dd132561b1
4,571
package com.github.loki.afro.metallum.entity; import com.github.loki.afro.metallum.enums.Country; import java.awt.image.BufferedImage; import java.util.*; public class Member extends AbstractEntity { // good Example: http://www.metal-archives.com/artists/Kerry_King/267 private Country country; private String realName; private List<Band> uncategorizedBands = new ArrayList<>(); private int age = 0; private String province = ""; private String gender = ""; private BufferedImage photo = null; private String alternativeName = ""; private Map<Band, Map<Disc, String>> guestSessionBands = new LinkedHashMap<>(); private Map<Band, Map<Disc, String>> activeInBands = new LinkedHashMap<>(); private Map<Band, Map<Disc, String>> pastBands = new LinkedHashMap<>(); private Map<Band, Map<Disc, String>> miscBands = new LinkedHashMap<>(); private final List<Link> linkList = new ArrayList<>(); private String details = ""; private String photoUrl = ""; public Member(final long id) { super(id); } public Member() { super(0); } public void setCountry(final Country country) { this.country = country; } public void setRealName(final String realName) { this.realName = realName; } /** * If we just search for the Member it is not possible to know if these are past Bands. * * @return uncategorizedBands */ public final List<Band> getUncategorizedBands() { return this.uncategorizedBands; } public String getRealName() { return this.realName; } public Country getCountry() { return this.country; } public final void setUncategorizedBands(final List<Band> memberBands) { this.uncategorizedBands = memberBands; } public void setAge(final int age) { this.age = age; } public void setProvince(final String province) { this.province = province; } public void setGender(final String gender) { this.gender = gender; } public void setPhoto(final BufferedImage parseMemberImage) { this.photo = parseMemberImage; } @Deprecated public void setGuestIn(final Map<Band, Map<Disc, String>> map) { this.guestSessionBands = map; } public void setAlternativeName(final String alternativeName) { this.alternativeName = alternativeName; } @Deprecated public void setMiscActivities(final Map<Band, Map<Disc, String>> parseMiscBands) { this.miscBands = parseMiscBands; } @Deprecated public void setPastBands(final Map<Band, Map<Disc, String>> parsePastBands) { this.pastBands = parsePastBands; } @Deprecated public void setActiveIn(final Map<Band, Map<Disc, String>> parseActiveBands) { this.activeInBands = parseActiveBands; } public void setDetails(final String details) { this.details = details; } /** * @return the age */ public int getAge() { return this.age; } /** * @return the province */ public String getProvince() { return this.province; } /** * @return the gender */ public String getGender() { return this.gender; } /** * @return the photo */ public BufferedImage getPhoto() { return this.photo; } /** * @return the alternativeName */ public String getAlternativeName() { return this.alternativeName; } /** * @return the guestSessionBands */ @Deprecated public Map<Band, Map<Disc, String>> getGuestSessionBands() { return this.guestSessionBands; } @Deprecated public Map<Band, Map<Disc, String>> getActiveInBands() { return this.activeInBands; } @Deprecated public Map<Band, Map<Disc, String>> getPastBands() { return this.pastBands; } @Deprecated public Map<Band, Map<Disc, String>> getMiscBands() { return this.miscBands; } public String getDetails() { return this.details; } public void addLinks(final Link... links) { Collections.addAll(this.linkList, links); } public List<Link> getLinks() { return this.linkList; } public boolean hasPhoto() { return this.photo != null; } public final void setPhotoUrl(final String photoUrl) { this.photoUrl = photoUrl; } public final String getPhotoUrl() { return this.photoUrl; } }
24.057895
91
0.62809