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 |
|---|---|---|---|---|---|
796508e9c6629d0f19a900c732765863c16d9b79 | 7,409 | /*
* Copyright 2007 skynamics 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.
*/
package org.openbp.common.generic.msgcontainer;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import org.openbp.common.ExceptionUtil;
import org.openbp.common.MsgFormat;
import org.openbp.common.generic.PrintNameProvider;
import org.openbp.common.generic.description.DescriptionObject;
import org.openbp.common.logger.LogLevel;
import org.openbp.common.logger.LogUtil;
/**
* Description object of a message.
* The message will be formatted according to the rules specified in the
* {@link MsgFormat} class.<br>
* The message source references the object that caused the message.
*
* @author Heiko Erhardt
*/
public class MsgItem
implements Serializable
{
//////////////////////////////////////////////////
// @@ Properties
//////////////////////////////////////////////////
/** Source of the message (may be null) */
private transient Object source;
/**
* Message type.
* See the constants of {@link LogLevel} interface.
*/
private String msgType;
/** The message */
private String msg;
/** Message arguments (may be null) */
private Object [] msgArgs;
//////////////////////////////////////////////////
// @@ Construction
//////////////////////////////////////////////////
/**
* Default constructor.
*/
public MsgItem()
{
}
/**
* Value constructor.
*
* @param msgType Message type
* See the constants of {@link LogLevel} interface.
* @param source Source of the message (may be null)
* @param msg The message
* @param msgArgs Message arguments (may be null)
*/
public MsgItem(String msgType, Object source, String msg, Object [] msgArgs)
{
this.msgType = msgType;
this.source = source;
this.msg = msg;
this.msgArgs = msgArgs;
}
/**
* Gets a string representation of this object.
*
* @return Same as {@link #getFormattedMsgWithSource}
*/
public String toString()
{
return getFormattedMsgWithSource();
}
/**
* Gets the name of the source of the message.
* @return The print name in case of a {@link PrintNameProvider} object, the name for a {@link DescriptionObject}
* or otherwise the result of toString(). Can be null if there is no source object for this description.
*/
public String getSourceString()
{
String ret = null;
if (source != null)
{
if (source instanceof PrintNameProvider)
ret = ((PrintNameProvider) source).getPrintName();
if (ret == null && (source instanceof DescriptionObject))
ret = ((DescriptionObject) source).getName();
if (ret == null)
ret = source.toString();
}
return ret;
}
/**
* Gets the formatted message including message source specification.
* @return The formatted message or null if neither message source nor
* message was provided.
*/
public String getFormattedMsgWithSource()
{
String ret = getSourceString();
String msg = getFormattedMsg();
if (msg != null)
{
if (ret != null)
ret += ": " + msg;
else
ret = msg;
}
return ret;
}
/**
* Gets the formatted message.
* @return The formatted message or null if no message was provided
*/
public String getFormattedMsg()
{
// TOLOCALIZE
String s;
if (!msgType.equals(LogLevel.ERROR))
s = msgType + ": " + msg;
else
s = msg;
if (s != null && msgArgs != null)
{
// Format the message
try
{
// Perform null argument and throwable argument checks
int l = msgArgs.length;
for (int i = 0; i < l; i++)
{
if (msgArgs [i] == null)
msgArgs [i] = "(null)";
}
if (msgArgs != null)
s = MsgFormat.format(s, msgArgs);
Object o = msgArgs [l - 1];
if (o instanceof Throwable)
{
// We have an excpetion object as last argument
// Iterate down any nested exceptions and append the excption message
Throwable throwable = (Throwable) o;
String exceptionMsg = ExceptionUtil.getNestedMessage(throwable);
if (exceptionMsg != null)
{
s += ": ";
s += exceptionMsg;
}
}
}
catch (Exception e)
{
// Error in message format, probably wrong number of args
LogUtil.error(getClass(), "Logging error: Can't format message $0 with {1} arguments.", s, Integer.valueOf(msgArgs.length), e);
}
}
return s;
}
//////////////////////////////////////////////////
// @@ Serialization support
//////////////////////////////////////////////////
/**
* This method is implemented here to support serialization of the source object.
* See {@link java.io.Serializable} for more information on this method.
*
* @param out The current object output stream
* @throws IOException if an I/O problem occured.
*/
private void writeObject(ObjectOutputStream out)
throws IOException
{
// All non-transient members
out.defaultWriteObject();
// Write the source string instead of the source object
out.writeObject(getSourceString());
}
/**
* This method is implemented here to support serialization of the source object.
* See {@link java.io.Serializable} for more information on this method.
*
* @param in The current object input stream<br>
* @throws IOException if an I/O problem occured.
* @throws ClassNotFoundException if a class could not be found
*/
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
// All non-transient members
in.defaultReadObject();
// Assign the source string as source object
source = in.readObject();
}
//////////////////////////////////////////////////
// @@ Property access
//////////////////////////////////////////////////
/**
* Sets the source of the message.
* @nowarn
*/
public void setSource(Object source)
{
this.source = source;
}
/**
* Gets the message type.
* See the constants of {@link LogLevel} interface.
* @nowarn
*/
public String getMsgType()
{
return msgType;
}
/**
* Sets the message type.
* See the constants of {@link LogLevel} interface.
* @nowarn
*/
public void setMsgType(String msgType)
{
this.msgType = msgType;
}
/**
* Gets the message.
* @nowarn
*/
public String getMsg()
{
return msg;
}
/**
* Sets the message.
* @nowarn
*/
public void setMsg(String msg)
{
this.msg = msg;
}
/**
* Gets the message arguments.
* @nowarn
*/
public Object [] getMsgArgs()
{
return msgArgs;
}
/**
* Sets the message arguments.
* @nowarn
*/
public void setMsgArgs(Object [] msgArgs)
{
this.msgArgs = msgArgs;
}
}
| 24.862416 | 132 | 0.608314 |
1333c43fbcc11bef7e018b243f5fda3f614d2f18 | 838 | package com.microsoft.azure.cosmosdb.kafka.connect;
import org.apache.kafka.common.config.ConfigDef;
import org.junit.Test;
import java.util.HashMap;
import static org.junit.Assert.assertEquals;
public class SettingsTest {
@Test
public void verifyMasterKeyIsPasswordType() {
HashMap<String, String> common = new HashMap<>();
common.put(Settings.PREFIX + ".master.key", "foobar");
Settings settings = new Settings();
settings.populate(common);
assertEquals("foobar", settings.getKey());
assertEquals(ConfigDef.Type.PASSWORD, settings.getAllSettings()
.stream()
.filter(s -> s.getName().equals(Settings.PREFIX + ".master.key"))
.map(Setting::getKafkaConfigType)
.findAny()
.orElse(null));
}
}
| 28.896552 | 81 | 0.634845 |
3d02b70f3ea24b8d68c2e607dcf248ff79af74ab | 810 | /** A class that represents a path via pursuit curves. */
public class Path {
// TODO
private Point curr;
private Point next;
public Path(double x, double y) {
this.curr = new Point(x, y);
this.next = new Point(x, y);
}
public double getCurrX() {
return this.curr.getX();
}
public double getCurrY() {
return this.curr.getY();
}
public double getNextX() {
return this.next.getX();
}
public double getNextY() {
return this.next.getY();
}
public Point getCurrentPoint() {
return this.curr;
}
public void setCurrentPoint(Point point) {
this.curr = point;
}
public void iterate(double dx, double dy) {
this.curr.setX(this.next.getX());
this.curr.setY(this.next.getY());
this.next.setX(this.next.getX() + dx);
this.next.setY(this.next.getY() + dy);
}
}
| 18.409091 | 57 | 0.648148 |
c94000ad9863dfc68a455ad1192eed0b32e7cf11 | 7,559 | package world;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
import combat.Player;
/**
* Simple world class containing an array of Tiles making up the world. Used for representing a game world as an array.
*/
public class World {
private final int width;
private final int height;
private final Tile[][] world;
private int goalX;
private int goalY;
private int startX;
private int startY;
/**
* Due to restrictions in world creation (see world.World.createWorld()), the world should always be of odd width and height.
* Creates a new World, with given parameters and generates start and goal Tiles, also spawns monsters to Tiles based on world.World.spawnMonsters() (frequency can be adjusted).
* Last creates some opening to the maze to make the world feel less cramped.
* @param width World width
* @param height World height
*/
public World(int width, int height) {
this.width = width;
this.height = height;
this.world = new Tile[height][width];
/*
* for filling the array with tiles, should maybe move this to its own method
*/
for (int i = 0; i < this.world.length; i++) {
for (int j = 0; j < this.world.length; j++) {
this.world[i][j] = new Tile();
}
}
this.createWorld();
this.generateStart();
this.generateGoal();
this.generateOpenings();
this.spawnMonsters();
}
public int getWidth() {
return this.width;
}
public int getHeight() {
return this.height;
}
public Tile getTile(int a, int b) {
return world[a][b];
}
/**
* Creates a world array by calling world.World.recursiveCreateWorld
*/
private void createWorld() {
final Random r = new Random();
int row = r.nextInt(this.height);
while (row % 2 == 0) {
row = r.nextInt(this.height);
}
int column = r.nextInt(this.width);
while (column % 2 == 0) {
column = r.nextInt(this.width);
}
this.world[row][column].setPassable(true);
recursiveCreateWorld(row, column);
}
/**
* Uses a simple recursion to create a mathematically sound maze (the generated maze is always solvable).
*
*
* @param r = row Starting row
* @param c = column Starting column
*/
private void recursiveCreateWorld(int r, int c) {
final Integer[] rand = randDirections();
for (int i = 0; i < rand.length; i++) {
switch (rand[i].intValue()) {
case 1:
if (r - 2 <= 0) {
continue;
}
if (!this.world[r - 2][c].getPassable()) {
this.world[r - 2][c].setPassable(true);
this.world[r - 1][c].setPassable(true);
recursiveCreateWorld(r - 2, c);
}
break;
case 2:
if (c + 2 >= this.height - 1) {
continue;
}
if (!this.world[r][c + 2].getPassable()) {
this.world[r][c + 2].setPassable(true);
this.world[r][c + 1].setPassable(true);
recursiveCreateWorld(r, c + 2);
}
break;
case 3:
if (r + 2 >= this.width - 1) {
continue;
}
if (!this.world[r + 2][c].getPassable()) {
this.world[r + 2][c].setPassable(true);
this.world[r + 1][c].setPassable(true);
recursiveCreateWorld(r + 2, c);
}
break;
case 4:
if (c - 2 <= 0) {
continue;
}
if (!this.world[r][c - 2].getPassable()) {
this.world[r][c - 2].setPassable(true);
this.world[r][c - 1].setPassable(true);
recursiveCreateWorld(r, c - 2);
}
break;
}
}
}
/**
* Random direction generator for recursiveCreateWorld
* @return list of random directions (1-4), used by recursivePopulateWorld
*/
private Integer[] randDirections() {
final ArrayList<Integer> directions = new ArrayList<Integer>();
for (int i = 0; i < 4; i++) {
directions.add(i + 1);
}
Collections.shuffle(directions);
return directions.toArray(new Integer[4]);
}
/**
* ASCII render method for playing the game in command line environment.
*
* @param p Player object for referencing relative position.
*/
public void render(Player p) {
int left = 0;
int right = 0;
int up = 0;
int down = 0;
if (p.getY() - 10 < 0) {
up= 0;
} else {
up = p.getY() - 10;
}
if (p.getY() + 10 > this.height) {
down = this.height;
} else {
down = p.getY() + 10;
}
if (p.getX() - 10 < 0) {
left = 0;
} else {
left = p.getX() - 10;
}
if (p.getX() + 10 > this.width) {
right = this.width;
} else {
right = p.getX() + 10;
}
for (int y = up; y < down; y++) {
for (int x = left; x < right; x++) {
if (y == p.getY() && x == p.getX()) {
System.out.print("P" + " ");
} else {
if (y == this.goalY && x == this.goalX) {
System.out.print("G" + " ");
} else if (y == this.startY && x == this.startX) {
System.out.print("S" + " ");
} else {
if (this.world[y][x].getPassable()) {
System.out.print(" " + " ");
} else {
System.out.print("#" + " ");
}
}
}
}
System.out.println();
}
}
/**
* Prints the whole World array. For testing purposes only.
*/
public void printWorld() {
for (int i = 0; i < this.height; i++) {
for (int j = 0; j < this.width; j++) {
if (this.world[i][j].getPassable()) {
System.out.print(" " + " ");
} else {
System.out.print("#" + " ");
}
}
System.out.println();
}
}
/**
* Generates a sane starting position, so the player won't spawn inside a wall or outside the array.
*/
public void generateStart () {
final Random r = new Random();
this.startY = r.nextInt(this.height);
this.startX = r.nextInt(this.width);
while (!this.getTile(this.startY, this.startX).getPassable()) {
this.startY = r.nextInt(this.height);
this.startX = r.nextInt(this.width);
}
}
public int[] getStart () {
final int[] start = new int[2];
start[0] = this.startY;
start[1] = this.startX;
return start;
}
/**
* Generates a goal to a random corner of {@code world}.
*/
public void generateGoal () {
final Random r = new Random();
final int n = r.nextInt(4);
if (n == 0) {
this.goalX = 1;
this.goalY = 1;
} else if (n == 1) {
this.goalX = this.width - 1;
this.goalY = this.height - 1;
} else if (n == 2) {
this.goalX = 1;
this.goalY = this.height -1;
} else {
this.goalX = this.width - 1;
this.goalY = 1;
}
}
public int[] getGoal () {
final int[] goal = new int[2];
goal[0] = this.goalY;
goal[1] = this.goalX;
return goal;
}
/**
* Sets world.Tile.monster to true randomly.
*/
private void spawnMonsters() {
final Random r = new Random();
for (int i = 0; i < this.height; i++) {
for (int j = 0; j < this.width; j++) {
if ((r.nextDouble()) > 0.92 && this.world[i][j].getPassable()) {
this.world[i][j].setMonster(true);
}
}
}
}
/**
* A messy way for creating opening to the maze
*/
private void generateOpenings() {
final Random r = new Random();
for (int i = 1; i < this.height - 1; i++) {
for (int j = 1; j < this.width - 1; j++) {
final double rand = r.nextDouble();
if (rand > 0.96) {
final int n = r.nextInt(5);
if (n + i < this.height - 1 && n + j < this.width - 1) {
for (int k = i; k < i + n; k++) {
for (int l = j; l < j + n; l++) {
this.world[k][l].setPassable(true);
}
}
}
}
}
}
}
}
| 25.112957 | 179 | 0.556026 |
63a8834c7bfa8d0c64c3c77590719de2095eaef9 | 400 | package com.sms.server.stream;
import com.sms.server.messaging.IProvider;
/**
* Provider that is seekable
*/
public interface ISeekableProvider extends IProvider {
public static final String KEY = ISeekableProvider.class.getName();
/**
* Seek the provider to timestamp ts (in milliseconds).
* @param ts Timestamp to seek to
* @return Actual timestamp seeked to
*/
int seek(int ts);
}
| 22.222222 | 68 | 0.7325 |
5f810c6dada5549a49e61f3a4cd8bcb4271900b1 | 1,673 | package io.ebeaninternal.server.query;
import io.ebean.config.dbplatform.DbHistorySupport;
import java.util.Map;
/**
* Helper to support history functions.
*/
class CQueryHistorySupport {
/**
* The DB specific support.
*/
private final DbHistorySupport dbHistorySupport;
/**
* The mapping of base tables to their matching 'with history' views.
*/
private final Map<String, String> asOfTableMap;
/**
* The sys period column.
*/
private final String sysPeriod;
CQueryHistorySupport(DbHistorySupport dbHistorySupport, Map<String, String> asOfTableMap, String sysPeriod) {
this.dbHistorySupport = dbHistorySupport;
this.asOfTableMap = asOfTableMap;
this.sysPeriod = sysPeriod;
}
/**
* Return true if the underlying history support is standards based.
*/
boolean isStandardsBased() {
return dbHistorySupport.isStandardsBased();
}
/**
* Return the 'as of' history view for the given base table.
*/
String getAsOfView(String table) {
return asOfTableMap.get(table);
}
/**
* Return the lower bound column.
*/
String getSysPeriodLower(String tableAlias) {
return dbHistorySupport.getSysPeriodLower(tableAlias, sysPeriod);
}
/**
* Return the upper bound column.
*/
String getSysPeriodUpper(String tableAlias) {
return dbHistorySupport.getSysPeriodUpper(tableAlias, sysPeriod);
}
/**
* Return the predicate appended to the end of the query.
* <p>
* Note used for Oracle total recall etc with the more standard approach.
*/
String getAsOfPredicate(String tableAlias) {
return dbHistorySupport.getAsOfPredicate(tableAlias, sysPeriod);
}
}
| 23.56338 | 111 | 0.710102 |
b0cc6dec2faa166ccb3cd1d9263114b8c2c64ac7 | 2,200 | package no.nav.foreldrepenger.behandlingslager.behandling.resultat.beregningsgrunnlag;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import no.nav.foreldrepenger.behandlingslager.kodeverk.Kodeliste;
@Entity(name = "FaktaOmBeregningTilfelle")
@DiscriminatorValue(FaktaOmBeregningTilfelle.DISCRIMINATOR)
public class FaktaOmBeregningTilfelle extends Kodeliste {
public static final String DISCRIMINATOR = "FAKTA_OM_BEREGNING_TILFELLE";
public static final FaktaOmBeregningTilfelle VURDER_TIDSBEGRENSET_ARBEIDSFORHOLD = new FaktaOmBeregningTilfelle("VURDER_TIDSBEGRENSET_ARBEIDSFORHOLD"); //$NON-NLS-1$
public static final FaktaOmBeregningTilfelle VURDER_SN_NY_I_ARBEIDSLIVET = new FaktaOmBeregningTilfelle("VURDER_SN_NY_I_ARBEIDSLIVET"); //$NON-NLS-1$
public static final FaktaOmBeregningTilfelle VURDER_NYOPPSTARTET_FL = new FaktaOmBeregningTilfelle("VURDER_NYOPPSTARTET_FL"); //$NON-NLS-1$
public static final FaktaOmBeregningTilfelle FASTSETT_MAANEDSINNTEKT_FL = new FaktaOmBeregningTilfelle("FASTSETT_MAANEDSINNTEKT_FL"); //$NON-NLS-1$
public static final FaktaOmBeregningTilfelle FASTSETT_ENDRET_BEREGNINGSGRUNNLAG = new FaktaOmBeregningTilfelle("FASTSETT_ENDRET_BEREGNINGSGRUNNLAG"); //$NON-NLS-1$
public static final FaktaOmBeregningTilfelle VURDER_LØNNSENDRING = new FaktaOmBeregningTilfelle("VURDER_LØNNSENDRING"); //$NON-NLS-1$
public static final FaktaOmBeregningTilfelle FASTSETT_MÅNEDSLØNN_ARBEIDSTAKER_UTEN_INNTEKTSMELDING = new FaktaOmBeregningTilfelle("FASTSETT_MÅNEDSLØNN_ARBEIDSTAKER_UTEN_INNTEKTSMELDING"); //$NON-NLS-1$
public static final FaktaOmBeregningTilfelle VURDER_AT_OG_FL_I_SAMME_ORGANISASJON = new FaktaOmBeregningTilfelle("VURDER_AT_OG_FL_I_SAMME_ORGANISASJON"); //$NON-NLS-1$
public static final FaktaOmBeregningTilfelle TILSTØTENDE_YTELSE = new FaktaOmBeregningTilfelle("TILSTØTENDE_YTELSE"); //$NON-NLS-1$
public static final FaktaOmBeregningTilfelle UDEFINERT = new FaktaOmBeregningTilfelle("-"); //$NON-NLS-1$
FaktaOmBeregningTilfelle() {
// Hibernate trenger en
}
private FaktaOmBeregningTilfelle(String kode) {
super(kode, DISCRIMINATOR);
}
}
| 62.857143 | 205 | 0.823182 |
ab8ccac8d19db6035c605476c694ede02ec648f0 | 6,467 | /**
* Copyright 2016 OpenSemantics.IO
*
* 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.opensemantics.semiotics.model.assessment;
import org.eclipse.emf.common.util.EList;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Node</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link io.opensemantics.semiotics.model.assessment.Node#getChildren <em>Children</em>}</li>
* <li>{@link io.opensemantics.semiotics.model.assessment.Node#getParent <em>Parent</em>}</li>
* <li>{@link io.opensemantics.semiotics.model.assessment.Node#getRefersTo <em>Refers To</em>}</li>
* <li>{@link io.opensemantics.semiotics.model.assessment.Node#getReferredBy <em>Referred By</em>}</li>
* <li>{@link io.opensemantics.semiotics.model.assessment.Node#getTasks <em>Tasks</em>}</li>
* <li>{@link io.opensemantics.semiotics.model.assessment.Node#getFindings <em>Findings</em>}</li>
* </ul>
*
* @see io.opensemantics.semiotics.model.assessment.AssessmentPackage#getNode()
* @model abstract="true"
* @generated
*/
public interface Node extends Label, Notes {
/**
* Returns the value of the '<em><b>Children</b></em>' containment reference list.
* The list contents are of type {@link io.opensemantics.semiotics.model.assessment.GraphNode}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Children</em>' containment reference list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Children</em>' containment reference list.
* @see io.opensemantics.semiotics.model.assessment.AssessmentPackage#getNode_Children()
* @model containment="true"
* @generated
*/
EList<GraphNode> getChildren();
/**
* Returns the value of the '<em><b>Parent</b></em>' reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Parent</em>' container reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Parent</em>' reference.
* @see #setParent(Node)
* @see io.opensemantics.semiotics.model.assessment.AssessmentPackage#getNode_Parent()
* @model
* @generated
*/
Node getParent();
/**
* Sets the value of the '{@link io.opensemantics.semiotics.model.assessment.Node#getParent <em>Parent</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Parent</em>' reference.
* @see #getParent()
* @generated
*/
void setParent(Node value);
/**
* Returns the value of the '<em><b>Refers To</b></em>' reference list.
* The list contents are of type {@link io.opensemantics.semiotics.model.assessment.Node}.
* It is bidirectional and its opposite is '{@link io.opensemantics.semiotics.model.assessment.Node#getReferredBy <em>Referred By</em>}'.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Refers To</em>' reference list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Refers To</em>' reference list.
* @see io.opensemantics.semiotics.model.assessment.AssessmentPackage#getNode_RefersTo()
* @see io.opensemantics.semiotics.model.assessment.Node#getReferredBy
* @model opposite="referredBy"
* @generated
*/
EList<Node> getRefersTo();
/**
* Returns the value of the '<em><b>Referred By</b></em>' reference list.
* The list contents are of type {@link io.opensemantics.semiotics.model.assessment.Node}.
* It is bidirectional and its opposite is '{@link io.opensemantics.semiotics.model.assessment.Node#getRefersTo <em>Refers To</em>}'.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Referred By</em>' reference list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Referred By</em>' reference list.
* @see io.opensemantics.semiotics.model.assessment.AssessmentPackage#getNode_ReferredBy()
* @see io.opensemantics.semiotics.model.assessment.Node#getRefersTo
* @model opposite="refersTo"
* @generated
*/
EList<Node> getReferredBy();
/**
* Returns the value of the '<em><b>Tasks</b></em>' reference list.
* The list contents are of type {@link io.opensemantics.semiotics.model.assessment.Task}.
* It is bidirectional and its opposite is '{@link io.opensemantics.semiotics.model.assessment.Task#getAffects <em>Affects</em>}'.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Tasks</em>' reference list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Tasks</em>' reference list.
* @see io.opensemantics.semiotics.model.assessment.AssessmentPackage#getNode_Tasks()
* @see io.opensemantics.semiotics.model.assessment.Task#getAffects
* @model opposite="affects"
* @generated
*/
EList<Task> getTasks();
/**
* Returns the value of the '<em><b>Findings</b></em>' reference list.
* The list contents are of type {@link io.opensemantics.semiotics.model.assessment.Finding}.
* It is bidirectional and its opposite is '{@link io.opensemantics.semiotics.model.assessment.Finding#getAffects <em>Affects</em>}'.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Findings</em>' reference list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Findings</em>' reference list.
* @see io.opensemantics.semiotics.model.assessment.AssessmentPackage#getNode_Findings()
* @see io.opensemantics.semiotics.model.assessment.Finding#getAffects
* @model opposite="affects"
* @generated
*/
EList<Finding> getFindings();
} // Node
| 41.191083 | 139 | 0.682697 |
4ea4b8a570e4ebda4665e71e6933ab48078f5af4 | 185 | package abstractfactory;
/**
* @author tonyc
*/
public class Square implements Shape{
@Override
public void draw() {
System.out.println("we draw a square.");
}
}
| 15.416667 | 48 | 0.627027 |
b1ea251b45eeadefcbca712e40b77b854dd5a7a4 | 1,408 | /*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.performance.fixture;
public class PerformanceTestSpec {
String testId;
String testClassName;
Integer runs;
Integer warmUpRuns;
public String getTestId() {
return testId;
}
public void setTestId(String testId) {
this.testId = testId;
}
public String getTestClassName() {
return testClassName;
}
public void setTestClassName(String testClassName) {
this.testClassName = testClassName;
}
public Integer getRuns() {
return runs;
}
public void setRuns(Integer runs) {
this.runs = runs;
}
public Integer getWarmUpRuns() {
return warmUpRuns;
}
public void setWarmUpRuns(Integer warmUpRuns) {
this.warmUpRuns = warmUpRuns;
}
}
| 24.701754 | 75 | 0.678977 |
78ea22c697d397ca42bde554950120b4e310adfb | 9,207 | /*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.cloud.tenantdeletion.deleter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.cloud.tenantdeletion.DeletionManager;
import org.wso2.carbon.cloud.tenantdeletion.constants.DeletionConstants;
import org.wso2.carbon.cloud.tenantdeletion.constants.UMQueries;
import org.wso2.carbon.cloud.tenantdeletion.internal.ServiceHolder;
import org.wso2.carbon.cloud.tenantdeletion.utils.DataAccessManager;
import org.wso2.carbon.cloud.tenantdeletion.utils.TenantDeletionMap;
import org.wso2.carbon.user.api.RealmConfiguration;
import org.wso2.carbon.user.core.util.DatabaseUtil;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;
import javax.sql.DataSource;
/**
* User Management Data deleter class for tenants
*/
public class UMDataDeleter {
private static final Log LOG = LogFactory.getLog(UMDataDeleter.class);
private static DataSource realmDataSource;
public UMDataDeleter() {
setRealmDataSource();
}
public static void setRealmDataSource() {
RealmConfiguration realmConfig = ServiceHolder.getInstance().getRealmService().
getBootstrapRealmConfiguration();
realmDataSource = DatabaseUtil.getRealmDataSource(realmConfig);
}
/**
* Delete all tenant information related to tenant stored in UM tables
*
* @param tenantId id of tenant whose data should be deleted
* @param conn database connection object
*/
public static void deleteTenantUMData(int tenantId, Connection conn) {
try {
conn.setAutoCommit(false);
String deleteUserPermissionSql = UMQueries.QUERY_DELETE_USER_PERMISSION;
DataAccessManager.getInstance().executeDeleteQuery(conn, deleteUserPermissionSql, tenantId);
String deleteRolePermissionSql = UMQueries.QUERY_DELETE_ROLE_PERMISSION;
DataAccessManager.getInstance().executeDeleteQuery(conn, deleteRolePermissionSql, tenantId);
String deletePermissionSql = UMQueries.QUERY_DELETE_PERMISSION;
DataAccessManager.getInstance().executeDeleteQuery(conn, deletePermissionSql, tenantId);
String deleteProfileConfigSql = UMQueries.QUERY_DELETE_PROFILE_CONFIG;
DataAccessManager.getInstance().executeDeleteQuery(conn, deleteProfileConfigSql, tenantId);
String deleteClaimSql = UMQueries.QUERY_DELETE_CLAIM;
DataAccessManager.getInstance().executeDeleteQuery(conn, deleteClaimSql, tenantId);
String deleteDialectSql = UMQueries.QUERY_DELETE_DIALECT;
DataAccessManager.getInstance().executeDeleteQuery(conn, deleteDialectSql, tenantId);
String deleteUserAttributeSql = UMQueries.QUERY_DELETE_DELETE_USER_ATTRIBUTE;
DataAccessManager.getInstance().executeDeleteQuery(conn, deleteUserAttributeSql, tenantId);
String deleteHybridUserRoleSql = UMQueries.QUERY_DELETE_HYBRID_USER_ROLE;
DataAccessManager.getInstance().executeDeleteQuery(conn, deleteHybridUserRoleSql, tenantId);
String deleteHybridRoleSql = UMQueries.QUERY_DELETE_HYBRID_ROLE;
DataAccessManager.getInstance().executeDeleteQuery(conn, deleteHybridRoleSql, tenantId);
String deleteHybridRememberMeSql = UMQueries.QUERY_DELETE_HYBRID_REMEMBER_ME;
DataAccessManager.getInstance().executeDeleteQuery(conn, deleteHybridRememberMeSql, tenantId);
String deleteUserRoleSql = UMQueries.QUERY_DELETE_USER_ROLE;
DataAccessManager.getInstance().executeDeleteQuery(conn, deleteUserRoleSql, tenantId);
String deleteRoleSql = UMQueries.QUERY_DELETE_ROLE;
DataAccessManager.getInstance().executeDeleteQuery(conn, deleteRoleSql, tenantId);
String deleteUserSql = UMQueries.QUERY_DELETE_USER;
DataAccessManager.getInstance().executeDeleteQuery(conn, deleteUserSql, tenantId);
String deleteDomainSql = UMQueries.QUERY_DELETE_DOMAIN;
DataAccessManager.getInstance().executeDeleteQuery(conn, deleteDomainSql, tenantId);
String deleteSystemUserRoleSql = UMQueries.QUERY_DELETE_SYSTEM_USER_ROLE;
DataAccessManager.getInstance().executeDeleteQuery(conn, deleteSystemUserRoleSql, tenantId);
String deleteSystemRoleSql = UMQueries.QUERY_DELETE_SYSTEM_ROLE;
DataAccessManager.getInstance().executeDeleteQuery(conn, deleteSystemRoleSql, tenantId);
String deleteSystemUserSql = UMQueries.QUERY_DELETE_SYSTEM_USER;
DataAccessManager.getInstance().executeDeleteQuery(conn, deleteSystemUserSql, tenantId);
String deleteTenantSql = UMQueries.QUERY_DELETE_TENANT;
DataAccessManager.getInstance().executeDeleteQuery(conn, deleteTenantSql, tenantId);
conn.commit();
} catch (SQLException e) {
try {
conn.rollback();
} catch (SQLException e1) {
LOG.error("SQL Exception occurred due to rollback", e1);
}
String errorMsg = "An error occurred while deleting registry data for tenant: " + tenantId;
LOG.error(errorMsg, e);
} finally {
try {
conn.close();
} catch (SQLException e) {
LOG.error("SQL Exception occurred while Closing connection ", e);
}
}
}
/**
* Method to startDeletion User Manager Data for given tenants.
*
* @param deletionLimit Number of tenants to be cleaned up in a single round
*/
public void delete(int deletionLimit) {
Map<String, Integer> tenantMap = null;
boolean deletionCompleted = TenantDeletionMap.getInstance().checkDeletionCompleted(DeletionConstants.USER_MGT);
//If deletion has been limited to specific number of tenants
if (!deletionCompleted) {
if (deletionLimit != 0) {
tenantMap =
TenantDeletionMap.getInstance().getInactiveTenantMap(DeletionConstants.USER_MGT, deletionLimit);
} else {
tenantMap = TenantDeletionMap.getInstance().getInactiveTenantMap(DeletionConstants.USER_MGT);
}
if (tenantMap != null && !tenantMap.isEmpty()) {
triggerDelete(tenantMap);
LOG.info("User Management data deletion completed for all the " + tenantMap.size() + " tenants.");
} else {
LOG.info("User Management data to be deleted");
}
} else {
LOG.info("User Management Data already Deleted");
}
//After completion UserMgt data deletion, Database flag updated to notify that UserMgt data deletion is over
DataAccessManager.getInstance().raiseDeletionFlag(DeletionConstants.USER_MGT);
//At last, UserMgt data will be deleted. Then this server will finish tenant deletion round
if (tenantMap != null && !tenantMap.isEmpty()) {
DeletionManager.getInstance().finishDeletionProcess(tenantMap);
} else {
DeletionManager.getInstance().finishDeletionWithoutEmail();
}
}
/**
* Deletion start method for the class.
* Runs the deletion queries on User Manager by calling deleteTenantUMData()
*
* @param tenantMap Map of tenant Domain, tenant Id to be delete APIs
*/
public void triggerDelete(Map<String, Integer> tenantMap) {
for (Map.Entry<String, Integer> entry : tenantMap.entrySet()) {
String tenantDomain = entry.getKey();
try {
deleteTenantUMData(tenantMap.get(tenantDomain), realmDataSource.getConnection());
//Sets deletion flag to 1 for the tenant domain
DataAccessManager.getInstance().raiseDeletionFlag(DeletionConstants.USER_MGT, tenantDomain,
DeletionConstants.DELETION_SUCCESS_STATUS);
} catch (SQLException e) {
String msg = "Error while deleting user management data of tenant : " + tenantMap.get(tenantDomain);
LOG.error(msg, e);
//Sets deletion flag to 2 for the tenant domain
DataAccessManager.getInstance().raiseDeletionFlag(DeletionConstants.USER_MGT, tenantDomain,
DeletionConstants.DELETION_ERROR_STATUS);
}
}
}
}
| 47.215385 | 120 | 0.68752 |
7e408f82eb8d51b2d55215dd11d7e176d2df0029 | 1,948 | package com.lazydash.audio.visualizer.spectrum.plugin;
import com.lazydash.audio.visualizer.spectrum.core.audio.TarsosAudioEngine;
import com.lazydash.audio.visualizer.spectrum.core.service.FrequencyBarsFFTService;
import com.lazydash.audio.visualizer.spectrum.ui.fxml.spectrum.SettingsController;
import javafx.scene.Parent;
import org.pf4j.DefaultPluginManager;
import org.pf4j.PluginManager;
import java.util.List;
public class PluginSystem {
private PluginManager pluginManager = new DefaultPluginManager();
private static PluginSystem pluginSystem = new PluginSystem();
private PluginSystem(){}
public static PluginSystem getInstance(){
return pluginSystem;
}
public void startAllPlugins() {
pluginManager.loadPlugins();
pluginManager.startPlugins();
}
public void stopAllPlugins() {
pluginManager.stopPlugins();
}
public void registerAllFffPlugins(TarsosAudioEngine tarsosAudioEngine){
List<SpectralExtensionPoint> fftRegisters = pluginManager.getExtensions(SpectralExtensionPoint.class);
for (SpectralExtensionPoint fftRegister : fftRegisters) {
FrequencyBarsFFTService frequencyBarsFFTService = new FrequencyBarsFFTService();
tarsosAudioEngine.getFttListenerList().add(frequencyBarsFFTService);
fftRegister.register(frequencyBarsFFTService);
}
}
public void extendUiPlugin(SettingsController settingsController){
List<UiSettingsExtensionPoint> uiSettingsExtensionPoints = pluginManager.getExtensions(UiSettingsExtensionPoint.class);
for (UiSettingsExtensionPoint uiSettingsExtensionPoint : uiSettingsExtensionPoints) {
String pluginTitle = uiSettingsExtensionPoint.getPluginTitle();
Parent pluginParent = uiSettingsExtensionPoint.getPluginParent();
settingsController.addTitleToPluginsFMXL(pluginTitle, pluginParent);
}
}
}
| 37.461538 | 127 | 0.760267 |
9eda3a64de27f021075014daac154b2f869fc45d | 3,097 | /*
* Copyright 2006-2021 The JGUIraffe Team.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.jguiraffe.gui.builder.enablers;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import net.sf.jguiraffe.gui.builder.components.ComponentBuilderData;
import net.sf.jguiraffe.gui.builder.components.FormBuilderException;
import net.sf.jguiraffe.gui.forms.ComponentHandlerImpl;
import net.sf.jguiraffe.gui.forms.TransformerContextImpl;
import net.sf.jguiraffe.gui.forms.bind.BeanBindingStrategy;
import org.junit.Test;
/**
* Test class for {@link ComponentEnabler}.
*
* @author Oliver Heger
* @version $Id: TestComponentEnabler.java 205 2012-01-29 18:29:57Z oheger $
*/
public class TestComponentEnabler
{
/** Constant for the name of a component. */
private static final String COMP_NAME = "TestComponent";
/**
* Creates and initializes a {@code ComponentBuilderData} object.
*
* @return the initialized object
*/
private ComponentBuilderData setUpCompData()
{
ComponentBuilderData compData = new ComponentBuilderData();
compData.initializeForm(new TransformerContextImpl(),
new BeanBindingStrategy());
return compData;
}
/**
* Tests creating an instance without a component name. This should cause an
* exception.
*/
@Test(expected = IllegalArgumentException.class)
public void testInitNoCompName()
{
new ComponentEnabler(null);
}
/**
* Tests setting the enabled state of a component.
*/
@Test
public void testSetEnabledState() throws FormBuilderException
{
ComponentBuilderData compData = setUpCompData();
ComponentHandlerImpl ch = new ComponentHandlerImpl();
compData.storeComponentHandler(COMP_NAME, ch);
ComponentEnabler enabler = new ComponentEnabler(COMP_NAME);
enabler.setEnabledState(compData, true);
assertTrue("Not enabled", ch.isEnabled());
enabler.setEnabledState(compData, false);
assertFalse("Not disabled", ch.isEnabled());
}
/**
* Tests setting the enabled state when the component cannot be resolved.
* This should cause an exception.
*/
@Test(expected = FormBuilderException.class)
public void testSetEnabledStateUnknownComponent()
throws FormBuilderException
{
ComponentBuilderData compData = setUpCompData();
ComponentEnabler enabler = new ComponentEnabler(COMP_NAME);
enabler.setEnabledState(compData, true);
}
}
| 34.032967 | 80 | 0.711011 |
c53889ccf552c25c2185d07a51577b78fce6ef3f | 280 | package com.alibaba.test.steed.constant;
/**
* Created by liyang on 2019/8/30.
*/
public interface RuleEndPoint {
String EXECUTE = "/testruleengine/smoke";
String REFRESH = "/rules/refreshRuleSet";
String GET_RULE_SET = "/rules/getRuleSetByTags?type=&tags=";
}
| 18.666667 | 64 | 0.7 |
ba7cbbc72a82e7e895fca034acfe6279436e5c14 | 19,313 | /*
* SPDX-License-Identifier: Apache-2.0
*
* Copyright 2015-2021 Andres Almiray
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kordamp.ikonli.dashicons;
import org.kordamp.ikonli.Ikon;
/**
* @author Andres Almiray
*/
public enum Dashicons implements Ikon {
ADMIN_APPEARANCE("dashicons-admin-appearance", '\uf100'),
ADMIN_COLLAPSE("dashicons-admin-collapse", '\uf148'),
ADMIN_COMMENTS("dashicons-admin-comments", '\uf101'),
ADMIN_CUSTOMIZER("dashicons-admin-customizer", '\uf540'),
ADMIN_GENERIC("dashicons-admin-generic", '\uf111'),
ADMIN_HOME("dashicons-admin-home", '\uf102'),
ADMIN_LINKS("dashicons-admin-links", '\uf103'),
ADMIN_MEDIA("dashicons-admin-media", '\uf104'),
ADMIN_MULTISITE("dashicons-admin-multisite", '\uf541'),
ADMIN_NETWORK("dashicons-admin-network", '\uf112'),
ADMIN_PAGE("dashicons-admin-page", '\uf105'),
ADMIN_PLUGINS("dashicons-admin-plugins", '\uf106'),
ADMIN_POST("dashicons-admin-post", '\uf109'),
ADMIN_SETTINGS("dashicons-admin-settings", '\uf108'),
ADMIN_SITE("dashicons-admin-site", '\uf319'),
ADMIN_SITE_ALT("dashicons-admin-site-alt", '\uf11d'),
ADMIN_SITE_ALT2("dashicons-admin-site-alt2", '\uf11e'),
ADMIN_SITE_ALT3("dashicons-admin-site-alt3", '\uf11f'),
ADMIN_TOOLS("dashicons-admin-tools", '\uf107'),
ADMIN_USERS("dashicons-admin-users", '\uf110'),
AIRPLANE("dashicons-airplane", '\uf15f'),
ALBUM("dashicons-album", '\uf514'),
ALIGN_CENTER("dashicons-align-center", '\uf134'),
ALIGN_FULL_WIDTH("dashicons-align-full-width", '\uf114'),
ALIGN_LEFT("dashicons-align-left", '\uf135'),
ALIGN_NONE("dashicons-align-none", '\uf138'),
ALIGN_PULL_LEFT("dashicons-align-pull-left", '\uf10a'),
ALIGN_PULL_RIGHT("dashicons-align-pull-right", '\uf10b'),
ALIGN_RIGHT("dashicons-align-right", '\uf136'),
ALIGN_WIDE("dashicons-align-wide", '\uf11b'),
AMAZON("dashicons-amazon", '\uf162'),
ANALYTICS("dashicons-analytics", '\uf183'),
ARCHIVE("dashicons-archive", '\uf480'),
ARROW_DOWN("dashicons-arrow-down", '\uf140'),
ARROW_DOWN_ALT("dashicons-arrow-down-alt", '\uf346'),
ARROW_DOWN_ALT2("dashicons-arrow-down-alt2", '\uf347'),
ARROW_LEFT("dashicons-arrow-left", '\uf141'),
ARROW_LEFT_ALT("dashicons-arrow-left-alt", '\uf340'),
ARROW_LEFT_ALT2("dashicons-arrow-left-alt2", '\uf341'),
ARROW_RIGHT("dashicons-arrow-right", '\uf139'),
ARROW_RIGHT_ALT("dashicons-arrow-right-alt", '\uf344'),
ARROW_RIGHT_ALT2("dashicons-arrow-right-alt2", '\uf345'),
ARROW_UP("dashicons-arrow-up", '\uf142'),
ARROW_UP_ALT("dashicons-arrow-up-alt", '\uf342'),
ARROW_UP_ALT2("dashicons-arrow-up-alt2", '\uf343'),
ARROW_UP_DUPLICATE("dashicons-arrow-up-duplicate", '\uf143'),
ART("dashicons-art", '\uf309'),
AWARDS("dashicons-awards", '\uf313'),
BACKUP("dashicons-backup", '\uf321'),
BANK("dashicons-bank", '\uf16a'),
BEER("dashicons-beer", '\uf16c'),
BELL("dashicons-bell", '\uf16d'),
BLOCK_DEFAULT("dashicons-block-default", '\uf12b'),
BOOK("dashicons-book", '\uf330'),
BOOK_ALT("dashicons-book-alt", '\uf331'),
BUDDICONS_ACTIVITY("dashicons-buddicons-activity", '\uf452'),
BUDDICONS_BBPRESS_LOGO("dashicons-buddicons-bbpress-logo", '\uf477'),
BUDDICONS_BUDDYPRESS_LOGO("dashicons-buddicons-buddypress-logo", '\uf448'),
BUDDICONS_COMMUNITY("dashicons-buddicons-community", '\uf453'),
BUDDICONS_FORUMS("dashicons-buddicons-forums", '\uf449'),
BUDDICONS_FRIENDS("dashicons-buddicons-friends", '\uf454'),
BUDDICONS_GROUPS("dashicons-buddicons-groups", '\uf456'),
BUDDICONS_PM("dashicons-buddicons-pm", '\uf457'),
BUDDICONS_REPLIES("dashicons-buddicons-replies", '\uf451'),
BUDDICONS_TOPICS("dashicons-buddicons-topics", '\uf450'),
BUDDICONS_TRACKING("dashicons-buddicons-tracking", '\uf455'),
BUILDING("dashicons-building", '\uf512'),
BUSINESSMAN("dashicons-businessman", '\uf338'),
BUSINESSPERSON("dashicons-businessperson", '\uf12e'),
BUSINESSWOMAN("dashicons-businesswoman", '\uf12f'),
BUTTON("dashicons-button", '\uf11a'),
CALCULATOR("dashicons-calculator", '\uf16e'),
CALENDAR("dashicons-calendar", '\uf145'),
CALENDAR_ALT("dashicons-calendar-alt", '\uf508'),
CAMERA("dashicons-camera", '\uf306'),
CAMERA_ALT("dashicons-camera-alt", '\uf129'),
CAR("dashicons-car", '\uf16b'),
CARROT("dashicons-carrot", '\uf511'),
CART("dashicons-cart", '\uf174'),
CATEGORY("dashicons-category", '\uf318'),
CHART_AREA("dashicons-chart-area", '\uf239'),
CHART_BAR("dashicons-chart-bar", '\uf185'),
CHART_LINE("dashicons-chart-line", '\uf238'),
CHART_PIE("dashicons-chart-pie", '\uf184'),
CLIPBOARD("dashicons-clipboard", '\uf481'),
CLOCK("dashicons-clock", '\uf469'),
CLOUD("dashicons-cloud", '\uf176'),
CLOUD_SAVED("dashicons-cloud-saved", '\uf137'),
CLOUD_UPLOAD("dashicons-cloud-upload", '\uf13b'),
CODE_STANDARDS("dashicons-code-standards", '\uf13a'),
COFFEE("dashicons-coffee", '\uf16f'),
COLOR_PICKER("dashicons-color-picker", '\uf131'),
COLUMNS("dashicons-columns", '\uf13c'),
CONTROLS_BACK("dashicons-controls-back", '\uf518'),
CONTROLS_FORWARD("dashicons-controls-forward", '\uf519'),
CONTROLS_PAUSE("dashicons-controls-pause", '\uf523'),
CONTROLS_PLAY("dashicons-controls-play", '\uf522'),
CONTROLS_REPEAT("dashicons-controls-repeat", '\uf515'),
CONTROLS_SKIPBACK("dashicons-controls-skipback", '\uf516'),
CONTROLS_SKIPFORWARD("dashicons-controls-skipforward", '\uf517'),
CONTROLS_VOLUMEOFF("dashicons-controls-volumeoff", '\uf520'),
CONTROLS_VOLUMEON("dashicons-controls-volumeon", '\uf521'),
COVER_IMAGE("dashicons-cover-image", '\uf13d'),
DASHBOARD("dashicons-dashboard", '\uf226'),
DATABASE("dashicons-database", '\uf17e'),
DATABASE_ADD("dashicons-database-add", '\uf170'),
DATABASE_EXPORT("dashicons-database-export", '\uf17a'),
DATABASE_IMPORT("dashicons-database-import", '\uf17b'),
DATABASE_REMOVE("dashicons-database-remove", '\uf17c'),
DATABASE_VIEW("dashicons-database-view", '\uf17d'),
DESKTOP("dashicons-desktop", '\uf472'),
DISMISS("dashicons-dismiss", '\uf153'),
DOWNLOAD("dashicons-download", '\uf316'),
DRUMSTICK("dashicons-drumstick", '\uf17f'),
EDIT("dashicons-edit", '\uf464'),
EDITOR_ALIGNCENTER("dashicons-editor-aligncenter", '\uf207'),
EDITOR_ALIGNLEFT("dashicons-editor-alignleft", '\uf206'),
EDITOR_ALIGNRIGHT("dashicons-editor-alignright", '\uf208'),
EDITOR_BOLD("dashicons-editor-bold", '\uf200'),
EDITOR_BREAK("dashicons-editor-break", '\uf474'),
EDITOR_CODE("dashicons-editor-code", '\uf475'),
EDITOR_CODE_DUPLICATE("dashicons-editor-code-duplicate", '\uf494'),
EDITOR_CONTRACT("dashicons-editor-contract", '\uf506'),
EDITOR_CUSTOMCHAR("dashicons-editor-customchar", '\uf220'),
EDITOR_DISTRACTIONFREE("dashicons-editor-distractionfree", '\uf211'),
EDITOR_EXPAND("dashicons-editor-expand", '\uf211'),
EDITOR_HELP("dashicons-editor-help", '\uf223'),
EDITOR_INDENT("dashicons-editor-indent", '\uf222'),
EDITOR_INSERTMORE("dashicons-editor-insertmore", '\uf209'),
EDITOR_ITALIC("dashicons-editor-italic", '\uf201'),
EDITOR_JUSTIFY("dashicons-editor-justify", '\uf214'),
EDITOR_KITCHENSINK("dashicons-editor-kitchensink", '\uf212'),
EDITOR_LTR("dashicons-editor-ltr", '\uf10c'),
EDITOR_OL("dashicons-editor-ol", '\uf204'),
EDITOR_OL_RTL("dashicons-editor-ol-rtl", '\uf12c'),
EDITOR_OUTDENT("dashicons-editor-outdent", '\uf221'),
EDITOR_PARAGRAPH("dashicons-editor-paragraph", '\uf476'),
EDITOR_PASTE_TEXT("dashicons-editor-paste-text", '\uf217'),
EDITOR_PASTE_WORD("dashicons-editor-paste-word", '\uf216'),
EDITOR_QUOTE("dashicons-editor-quote", '\uf205'),
EDITOR_REMOVEFORMATTING("dashicons-editor-removeformatting", '\uf218'),
EDITOR_RTL("dashicons-editor-rtl", '\uf320'),
EDITOR_SPELLCHECK("dashicons-editor-spellcheck", '\uf210'),
EDITOR_STRIKETHROUGH("dashicons-editor-strikethrough", '\uf224'),
EDITOR_TABLE("dashicons-editor-table", '\uf535'),
EDITOR_TEXTCOLOR("dashicons-editor-textcolor", '\uf215'),
EDITOR_UL("dashicons-editor-ul", '\uf203'),
EDITOR_UNDERLINE("dashicons-editor-underline", '\uf213'),
EDITOR_UNLINK("dashicons-editor-unlink", '\uf225'),
EDITOR_VIDEO("dashicons-editor-video", '\uf219'),
EDIT_LARGE("dashicons-edit-large", '\uf327'),
EDIT_PAGE("dashicons-edit-page", '\uf186'),
ELLIPSIS("dashicons-ellipsis", '\uf11c'),
EMAIL("dashicons-email", '\uf465'),
EMAIL_ALT("dashicons-email-alt", '\uf466'),
EMAIL_ALT2("dashicons-email-alt2", '\uf467'),
EMBED_AUDIO("dashicons-embed-audio", '\uf13e'),
EMBED_GENERIC("dashicons-embed-generic", '\uf13f'),
EMBED_PHOTO("dashicons-embed-photo", '\uf144'),
EMBED_POST("dashicons-embed-post", '\uf146'),
EMBED_VIDEO("dashicons-embed-video", '\uf149'),
EXCERPT_VIEW("dashicons-excerpt-view", '\uf164'),
EXERPT_VIEW("dashicons-exerpt-view", '\uf164'),
EXIT("dashicons-exit", '\uf14a'),
EXTERNAL("dashicons-external", '\uf504'),
FACEBOOK("dashicons-facebook", '\uf304'),
FACEBOOK_ALT("dashicons-facebook-alt", '\uf305'),
FEEDBACK("dashicons-feedback", '\uf175'),
FILTER("dashicons-filter", '\uf536'),
FLAG("dashicons-flag", '\uf227'),
FOOD("dashicons-food", '\uf187'),
FORMAT_ASIDE("dashicons-format-aside", '\uf123'),
FORMAT_AUDIO("dashicons-format-audio", '\uf127'),
FORMAT_CHAT("dashicons-format-chat", '\uf125'),
FORMAT_GALLERY("dashicons-format-gallery", '\uf161'),
FORMAT_IMAGE("dashicons-format-image", '\uf128'),
FORMAT_LINKS("dashicons-format-links", '\uf103'),
FORMAT_QUOTE("dashicons-format-quote", '\uf122'),
FORMAT_STANDARD("dashicons-format-standard", '\uf109'),
FORMAT_STATUS("dashicons-format-status", '\uf130'),
FORMAT_VIDEO("dashicons-format-video", '\uf126'),
FORMS("dashicons-forms", '\uf314'),
FULLSCREEN_ALT("dashicons-fullscreen-alt", '\uf188'),
FULLSCREEN_EXIT_ALT("dashicons-fullscreen-exit-alt", '\uf189'),
GAMES("dashicons-games", '\uf18a'),
GOOGLE("dashicons-google", '\uf18b'),
GOOGLEPLUS("dashicons-googleplus", '\uf462'),
GRID_VIEW("dashicons-grid-view", '\uf509'),
GROUPS("dashicons-groups", '\uf307'),
HAMMER("dashicons-hammer", '\uf308'),
HEADING("dashicons-heading", '\uf10e'),
HEART("dashicons-heart", '\uf487'),
HIDDEN("dashicons-hidden", '\uf530'),
HOURGLASS("dashicons-hourglass", '\uf18c'),
HTML("dashicons-html", '\uf14b'),
ID("dashicons-id", '\uf336'),
ID_ALT("dashicons-id-alt", '\uf337'),
IMAGES_ALT("dashicons-images-alt", '\uf232'),
IMAGES_ALT2("dashicons-images-alt2", '\uf233'),
IMAGE_CROP("dashicons-image-crop", '\uf165'),
IMAGE_FILTER("dashicons-image-filter", '\uf533'),
IMAGE_FLIP_HORIZONTAL("dashicons-image-flip-horizontal", '\uf169'),
IMAGE_FLIP_VERTICAL("dashicons-image-flip-vertical", '\uf168'),
IMAGE_ROTATE("dashicons-image-rotate", '\uf531'),
IMAGE_ROTATE_LEFT("dashicons-image-rotate-left", '\uf166'),
IMAGE_ROTATE_RIGHT("dashicons-image-rotate-right", '\uf167'),
INDEX_CARD("dashicons-index-card", '\uf510'),
INFO("dashicons-info", '\uf348'),
INFO_OUTLINE("dashicons-info-outline", '\uf14c'),
INSERT("dashicons-insert", '\uf10f'),
INSERT_AFTER("dashicons-insert-after", '\uf14d'),
INSERT_BEFORE("dashicons-insert-before", '\uf14e'),
INSTAGRAM("dashicons-instagram", '\uf12d'),
LAPTOP("dashicons-laptop", '\uf547'),
LAYOUT("dashicons-layout", '\uf538'),
LEFTRIGHT("dashicons-leftright", '\uf229'),
LIGHTBULB("dashicons-lightbulb", '\uf339'),
LINKEDIN("dashicons-linkedin", '\uf18d'),
LIST_VIEW("dashicons-list-view", '\uf163'),
LOCATION("dashicons-location", '\uf230'),
LOCATION_ALT("dashicons-location-alt", '\uf231'),
LOCK("dashicons-lock", '\uf160'),
LOCK_DUPLICATE("dashicons-lock-duplicate", '\uf315'),
MARKER("dashicons-marker", '\uf159'),
MEDIA_ARCHIVE("dashicons-media-archive", '\uf501'),
MEDIA_AUDIO("dashicons-media-audio", '\uf500'),
MEDIA_CODE("dashicons-media-code", '\uf499'),
MEDIA_DEFAULT("dashicons-media-default", '\uf498'),
MEDIA_DOCUMENT("dashicons-media-document", '\uf497'),
MEDIA_INTERACTIVE("dashicons-media-interactive", '\uf496'),
MEDIA_SPREADSHEET("dashicons-media-spreadsheet", '\uf495'),
MEDIA_TEXT("dashicons-media-text", '\uf491'),
MEDIA_VIDEO("dashicons-media-video", '\uf490'),
MEGAPHONE("dashicons-megaphone", '\uf488'),
MENU("dashicons-menu", '\uf333'),
MENU_ALT("dashicons-menu-alt", '\uf228'),
MENU_ALT2("dashicons-menu-alt2", '\uf329'),
MENU_ALT3("dashicons-menu-alt3", '\uf349'),
MICROPHONE("dashicons-microphone", '\uf482'),
MIGRATE("dashicons-migrate", '\uf310'),
MINUS("dashicons-minus", '\uf460'),
MONEY("dashicons-money", '\uf526'),
MONEY_ALT("dashicons-money-alt", '\uf18e'),
MOVE("dashicons-move", '\uf545'),
NAMETAG("dashicons-nametag", '\uf484'),
NETWORKING("dashicons-networking", '\uf325'),
NO("dashicons-no", '\uf158'),
NO_ALT("dashicons-no-alt", '\uf335'),
OPEN_FOLDER("dashicons-open-folder", '\uf18f'),
PALMTREE("dashicons-palmtree", '\uf527'),
PAPERCLIP("dashicons-paperclip", '\uf546'),
PDF("dashicons-pdf", '\uf190'),
PERFORMANCE("dashicons-performance", '\uf311'),
PETS("dashicons-pets", '\uf191'),
PHONE("dashicons-phone", '\uf525'),
PINTEREST("dashicons-pinterest", '\uf192'),
PLAYLIST_AUDIO("dashicons-playlist-audio", '\uf492'),
PLAYLIST_VIDEO("dashicons-playlist-video", '\uf493'),
PLUGINS_CHECKED("dashicons-plugins-checked", '\uf485'),
PLUS("dashicons-plus", '\uf132'),
PLUS_ALT("dashicons-plus-alt", '\uf502'),
PLUS_ALT2("dashicons-plus-alt2", '\uf543'),
PODIO("dashicons-podio", '\uf19c'),
PORTFOLIO("dashicons-portfolio", '\uf322'),
POST_STATUS("dashicons-post-status", '\uf173'),
POST_TRASH("dashicons-post-trash", '\uf182'),
PRESSTHIS("dashicons-pressthis", '\uf157'),
PRINTER("dashicons-printer", '\uf193'),
PRIVACY("dashicons-privacy", '\uf194'),
PRODUCTS("dashicons-products", '\uf312'),
RANDOMIZE("dashicons-randomize", '\uf503'),
REDDIT("dashicons-reddit", '\uf195'),
REDO("dashicons-redo", '\uf172'),
REMOVE("dashicons-remove", '\uf14f'),
REST_API("dashicons-rest-api", '\uf124'),
RSS("dashicons-rss", '\uf303'),
SAVED("dashicons-saved", '\uf15e'),
SCHEDULE("dashicons-schedule", '\uf489'),
SCREENOPTIONS("dashicons-screenoptions", '\uf180'),
SEARCH("dashicons-search", '\uf179'),
SHARE("dashicons-share", '\uf237'),
SHARE1("dashicons-share1", '\uf237'),
SHARE_ALT("dashicons-share-alt", '\uf240'),
SHARE_ALT2("dashicons-share-alt2", '\uf242'),
SHIELD("dashicons-shield", '\uf332'),
SHIELD_ALT("dashicons-shield-alt", '\uf334'),
SHORTCODE("dashicons-shortcode", '\uf150'),
SLIDES("dashicons-slides", '\uf181'),
SMARTPHONE("dashicons-smartphone", '\uf470'),
SMILEY("dashicons-smiley", '\uf328'),
SORT("dashicons-sort", '\uf156'),
SOS("dashicons-sos", '\uf468'),
SPOTIFY("dashicons-spotify", '\uf196'),
STAR_EMPTY("dashicons-star-empty", '\uf154'),
STAR_FILLED("dashicons-star-filled", '\uf155'),
STAR_HALF("dashicons-star-half", '\uf459'),
STICKY("dashicons-sticky", '\uf537'),
STORE("dashicons-store", '\uf513'),
SUPERHERO("dashicons-superhero", '\uf198'),
SUPERHERO_ALT("dashicons-superhero-alt", '\uf197'),
TABLET("dashicons-tablet", '\uf471'),
TABLE_COL_AFTER("dashicons-table-col-after", '\uf151'),
TABLE_COL_BEFORE("dashicons-table-col-before", '\uf152'),
TABLE_COL_DELETE("dashicons-table-col-delete", '\uf15a'),
TABLE_ROW_AFTER("dashicons-table-row-after", '\uf15b'),
TABLE_ROW_BEFORE("dashicons-table-row-before", '\uf15c'),
TABLE_ROW_DELETE("dashicons-table-row-delete", '\uf15d'),
TAG("dashicons-tag", '\uf323'),
TAGCLOUD("dashicons-tagcloud", '\uf479'),
TESTIMONIAL("dashicons-testimonial", '\uf473'),
TEXT("dashicons-text", '\uf478'),
TEXT_PAGE("dashicons-text-page", '\uf121'),
THUMBS_DOWN("dashicons-thumbs-down", '\uf542'),
THUMBS_UP("dashicons-thumbs-up", '\uf529'),
TICKETS("dashicons-tickets", '\uf486'),
TICKETS_ALT("dashicons-tickets-alt", '\uf524'),
TIDE("dashicons-tide", '\uf10d'),
TRANSLATION("dashicons-translation", '\uf326'),
TRASH("dashicons-trash", '\uf182'),
TWITCH("dashicons-twitch", '\uf199'),
TWITTER("dashicons-twitter", '\uf301'),
TWITTER_ALT("dashicons-twitter-alt", '\uf302'),
UNDO("dashicons-undo", '\uf171'),
UNIVERSAL_ACCESS("dashicons-universal-access", '\uf483'),
UNIVERSAL_ACCESS_ALT("dashicons-universal-access-alt", '\uf507'),
UNLOCK("dashicons-unlock", '\uf528'),
UPDATE("dashicons-update", '\uf463'),
UPDATE_ALT("dashicons-update-alt", '\uf113'),
UPLOAD("dashicons-upload", '\uf317'),
VAULT("dashicons-vault", '\uf178'),
VIDEO_ALT("dashicons-video-alt", '\uf234'),
VIDEO_ALT2("dashicons-video-alt2", '\uf235'),
VIDEO_ALT3("dashicons-video-alt3", '\uf236'),
VISIBILITY("dashicons-visibility", '\uf177'),
WARNING("dashicons-warning", '\uf534'),
WELCOME_ADD_PAGE("dashicons-welcome-add-page", '\uf133'),
WELCOME_COMMENTS("dashicons-welcome-comments", '\uf117'),
WELCOME_EDIT_PAGE("dashicons-welcome-edit-page", '\uf119'),
WELCOME_LEARN_MORE("dashicons-welcome-learn-more", '\uf118'),
WELCOME_VIEW_SITE("dashicons-welcome-view-site", '\uf115'),
WELCOME_WIDGETS_MENUS("dashicons-welcome-widgets-menus", '\uf116'),
WELCOME_WRITE_BLOG("dashicons-welcome-write-blog", '\uf119'),
WHATSAPP("dashicons-whatsapp", '\uf19a'),
WORDPRESS("dashicons-wordpress", '\uf120'),
WORDPRESS_ALT("dashicons-wordpress-alt", '\uf324'),
XING("dashicons-xing", '\uf19d'),
YES("dashicons-yes", '\uf147'),
YES_ALT("dashicons-yes-alt", '\uf12a'),
YOUTUBE("dashicons-youtube", '\uf19b');
public static Dashicons findByDescription(String description) {
for (Dashicons font : values()) {
if (font.getDescription().equals(description)) {
return font;
}
}
throw new IllegalArgumentException("Icon description '" + description + "' is invalid!");
}
private String description;
private int code;
Dashicons(String description, int code) {
this.description = description;
this.code = code;
}
@Override
public String getDescription() {
return description;
}
@Override
public int getCode() {
return code;
}
}
| 47.923077 | 97 | 0.672966 |
882352d70b0c7c13df32f9c288b0c6a7b7ced92b | 13,215 | // Copyright (C) 2013 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.change;
import static com.google.common.base.Preconditions.checkState;
import static com.google.gerrit.server.notedb.ReviewerStateInternal.CC;
import static com.google.gerrit.server.notedb.ReviewerStateInternal.REVIEWER;
import static com.google.gerrit.server.project.ProjectCache.illegalState;
import static java.util.Objects.requireNonNull;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.entities.Change;
import com.google.gerrit.entities.ChangeMessage;
import com.google.gerrit.entities.PatchSet;
import com.google.gerrit.entities.PatchSetInfo;
import com.google.gerrit.extensions.api.changes.NotifyHandling;
import com.google.gerrit.extensions.restapi.AuthException;
import com.google.gerrit.extensions.restapi.BadRequestException;
import com.google.gerrit.extensions.restapi.ResourceConflictException;
import com.google.gerrit.server.ApprovalsUtil;
import com.google.gerrit.server.ChangeMessagesUtil;
import com.google.gerrit.server.ChangeUtil;
import com.google.gerrit.server.PatchSetUtil;
import com.google.gerrit.server.ReviewerSet;
import com.google.gerrit.server.events.CommitReceivedEvent;
import com.google.gerrit.server.extensions.events.RevisionCreated;
import com.google.gerrit.server.extensions.events.WorkInProgressStateChanged;
import com.google.gerrit.server.git.validators.CommitValidationException;
import com.google.gerrit.server.git.validators.CommitValidators;
import com.google.gerrit.server.mail.send.MessageIdGenerator;
import com.google.gerrit.server.mail.send.ReplacePatchSetSender;
import com.google.gerrit.server.notedb.ChangeNotes;
import com.google.gerrit.server.notedb.ChangeUpdate;
import com.google.gerrit.server.patch.PatchSetInfoFactory;
import com.google.gerrit.server.permissions.ChangePermission;
import com.google.gerrit.server.permissions.PermissionBackend;
import com.google.gerrit.server.permissions.PermissionBackendException;
import com.google.gerrit.server.project.ProjectCache;
import com.google.gerrit.server.ssh.NoSshInfo;
import com.google.gerrit.server.update.BatchUpdateOp;
import com.google.gerrit.server.update.ChangeContext;
import com.google.gerrit.server.update.Context;
import com.google.gerrit.server.update.RepoContext;
import com.google.gerrit.server.validators.ValidationException;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.transport.ReceiveCommand;
public class PatchSetInserter implements BatchUpdateOp {
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
public interface Factory {
PatchSetInserter create(ChangeNotes notes, PatchSet.Id psId, ObjectId commitId);
}
// Injected fields.
private final PermissionBackend permissionBackend;
private final PatchSetInfoFactory patchSetInfoFactory;
private final CommitValidators.Factory commitValidatorsFactory;
private final ReplacePatchSetSender.Factory replacePatchSetFactory;
private final ProjectCache projectCache;
private final RevisionCreated revisionCreated;
private final ApprovalsUtil approvalsUtil;
private final ChangeMessagesUtil cmUtil;
private final PatchSetUtil psUtil;
private final WorkInProgressStateChanged wipStateChanged;
private final MessageIdGenerator messageIdGenerator;
// Assisted-injected fields.
private final PatchSet.Id psId;
private final ObjectId commitId;
// Read prior to running the batch update, so must only be used during
// updateRepo; updateChange and later must use the notes from the
// ChangeContext.
private final ChangeNotes origNotes;
// Fields exposed as setters.
private String message;
private String description;
private Boolean workInProgress;
private boolean validate = true;
private boolean checkAddPatchSetPermission = true;
private List<String> groups = Collections.emptyList();
private boolean fireRevisionCreated = true;
private boolean allowClosed;
private boolean sendEmail = true;
private String topic;
// Fields set during some phase of BatchUpdate.Op.
private Change change;
private PatchSet patchSet;
private PatchSetInfo patchSetInfo;
private ChangeMessage changeMessage;
private ReviewerSet oldReviewers;
private boolean oldWorkInProgressState;
@Inject
public PatchSetInserter(
PermissionBackend permissionBackend,
ApprovalsUtil approvalsUtil,
ChangeMessagesUtil cmUtil,
PatchSetInfoFactory patchSetInfoFactory,
CommitValidators.Factory commitValidatorsFactory,
ReplacePatchSetSender.Factory replacePatchSetFactory,
PatchSetUtil psUtil,
RevisionCreated revisionCreated,
ProjectCache projectCache,
WorkInProgressStateChanged wipStateChanged,
MessageIdGenerator messageIdGenerator,
@Assisted ChangeNotes notes,
@Assisted PatchSet.Id psId,
@Assisted ObjectId commitId) {
this.permissionBackend = permissionBackend;
this.approvalsUtil = approvalsUtil;
this.cmUtil = cmUtil;
this.patchSetInfoFactory = patchSetInfoFactory;
this.commitValidatorsFactory = commitValidatorsFactory;
this.replacePatchSetFactory = replacePatchSetFactory;
this.psUtil = psUtil;
this.revisionCreated = revisionCreated;
this.projectCache = projectCache;
this.wipStateChanged = wipStateChanged;
this.messageIdGenerator = messageIdGenerator;
this.origNotes = notes;
this.psId = psId;
this.commitId = commitId.copy();
}
public PatchSet.Id getPatchSetId() {
return psId;
}
public PatchSetInserter setMessage(String message) {
this.message = message;
return this;
}
public PatchSetInserter setDescription(String description) {
this.description = description;
return this;
}
public PatchSetInserter setWorkInProgress(boolean workInProgress) {
this.workInProgress = workInProgress;
return this;
}
public PatchSetInserter setValidate(boolean validate) {
this.validate = validate;
return this;
}
public PatchSetInserter setCheckAddPatchSetPermission(boolean checkAddPatchSetPermission) {
this.checkAddPatchSetPermission = checkAddPatchSetPermission;
return this;
}
public PatchSetInserter setGroups(List<String> groups) {
requireNonNull(groups, "groups may not be null");
this.groups = groups;
return this;
}
public PatchSetInserter setFireRevisionCreated(boolean fireRevisionCreated) {
this.fireRevisionCreated = fireRevisionCreated;
return this;
}
public PatchSetInserter setAllowClosed(boolean allowClosed) {
this.allowClosed = allowClosed;
return this;
}
public PatchSetInserter setSendEmail(boolean sendEmail) {
this.sendEmail = sendEmail;
return this;
}
public PatchSetInserter setTopic(String topic) {
this.topic = topic;
return this;
}
public Change getChange() {
checkState(change != null, "getChange() only valid after executing update");
return change;
}
public PatchSet getPatchSet() {
checkState(patchSet != null, "getPatchSet() only valid after executing update");
return patchSet;
}
@Override
public void updateRepo(RepoContext ctx)
throws AuthException, ResourceConflictException, IOException, PermissionBackendException {
validate(ctx);
ctx.addRefUpdate(ObjectId.zeroId(), commitId, getPatchSetId().toRefName());
}
@Override
public boolean updateChange(ChangeContext ctx)
throws ResourceConflictException, IOException, BadRequestException {
change = ctx.getChange();
ChangeUpdate update = ctx.getUpdate(psId);
update.setSubjectForCommit("Create patch set " + psId.get());
if (!change.isNew() && !allowClosed) {
throw new ResourceConflictException(
String.format(
"Cannot create new patch set of change %s because it is %s",
change.getId(), ChangeUtil.status(change)));
}
List<String> newGroups = groups;
if (newGroups.isEmpty()) {
PatchSet prevPs = psUtil.current(ctx.getNotes());
if (prevPs != null) {
newGroups = prevPs.groups();
}
}
patchSet =
psUtil.insert(
ctx.getRevWalk(), ctx.getUpdate(psId), psId, commitId, newGroups, null, description);
if (ctx.getNotify(change.getId()).handling() != NotifyHandling.NONE) {
oldReviewers = approvalsUtil.getReviewers(ctx.getNotes());
}
if (message != null) {
changeMessage =
ChangeMessagesUtil.newMessage(
patchSet.id(),
ctx.getUser(),
ctx.getWhen(),
message,
ChangeMessagesUtil.uploadedPatchSetTag(change.isWorkInProgress()));
changeMessage.setMessage(message);
}
oldWorkInProgressState = change.isWorkInProgress();
if (workInProgress != null) {
change.setWorkInProgress(workInProgress);
change.setReviewStarted(!workInProgress);
update.setWorkInProgress(workInProgress);
}
patchSetInfo =
patchSetInfoFactory.get(ctx.getRevWalk(), ctx.getRevWalk().parseCommit(commitId), psId);
if (!allowClosed) {
change.setStatus(Change.Status.NEW);
}
change.setCurrentPatchSet(patchSetInfo);
if (changeMessage != null) {
cmUtil.addChangeMessage(update, changeMessage);
}
if (topic != null) {
change.setTopic(topic);
try {
update.setTopic(topic);
} catch (ValidationException ex) {
throw new BadRequestException(ex.getMessage());
}
}
return true;
}
@Override
public void postUpdate(Context ctx) {
NotifyResolver.Result notify = ctx.getNotify(change.getId());
if (notify.shouldNotify() && sendEmail) {
requireNonNull(changeMessage);
try {
ReplacePatchSetSender emailSender =
replacePatchSetFactory.create(ctx.getProject(), change.getId());
emailSender.setFrom(ctx.getAccountId());
emailSender.setPatchSet(patchSet, patchSetInfo);
emailSender.setChangeMessage(changeMessage.getMessage(), ctx.getWhen());
emailSender.addReviewers(oldReviewers.byState(REVIEWER));
emailSender.addExtraCC(oldReviewers.byState(CC));
emailSender.setNotify(notify);
emailSender.setMessageId(
messageIdGenerator.fromChangeUpdate(ctx.getRepoView(), patchSet.id()));
emailSender.send();
} catch (Exception err) {
logger.atSevere().withCause(err).log(
"Cannot send email for new patch set on change %s", change.getId());
}
}
if (fireRevisionCreated) {
revisionCreated.fire(change, patchSet, ctx.getAccount(), ctx.getWhen(), notify);
}
if (workInProgress != null && oldWorkInProgressState != workInProgress) {
wipStateChanged.fire(change, patchSet, ctx.getAccount(), ctx.getWhen());
}
}
private void validate(RepoContext ctx)
throws AuthException, ResourceConflictException, IOException, PermissionBackendException {
// Not allowed to create a new patch set if the current patch set is locked.
psUtil.checkPatchSetNotLocked(origNotes);
if (checkAddPatchSetPermission) {
permissionBackend.user(ctx.getUser()).change(origNotes).check(ChangePermission.ADD_PATCH_SET);
}
projectCache
.get(ctx.getProject())
.orElseThrow(illegalState(ctx.getProject()))
.checkStatePermitsWrite();
if (!validate) {
return;
}
String refName = getPatchSetId().toRefName();
try (CommitReceivedEvent event =
new CommitReceivedEvent(
new ReceiveCommand(
ObjectId.zeroId(),
commitId,
refName.substring(0, refName.lastIndexOf('/') + 1) + "new"),
projectCache
.get(origNotes.getProjectName())
.orElseThrow(illegalState(origNotes.getProjectName()))
.getProject(),
origNotes.getChange().getDest().branch(),
ctx.getRevWalk().getObjectReader(),
commitId,
ctx.getIdentifiedUser())) {
commitValidatorsFactory
.forGerritCommits(
permissionBackend.user(ctx.getUser()).project(ctx.getProject()),
origNotes.getChange().getDest(),
ctx.getIdentifiedUser(),
new NoSshInfo(),
ctx.getRevWalk(),
origNotes.getChange())
.validate(event);
} catch (CommitValidationException e) {
throw new ResourceConflictException(e.getFullMessage());
}
}
}
| 36.505525 | 100 | 0.730685 |
d10944b5858e53ed8d6f0e3f0934dc0ad5adf527 | 8,674 | package issco.eval.ts;
import issco.eval.util.SegmentedText;
import issco.util.mgDebug;
/*
* <p> Implementation of the evaluation metric proposed by (Georgescul et al., 2006) for topic segmentation algorithms. </p> <br>
* The evaluation metric called "Pr_error" is defined as:
* <br> Pr_error = C_Miss * Pr_Miss + C_FalseAlarm * Pr_FalseAlarm
* <br> For a detailed description see: <br>
*inproceedings{Georgescul_eval:2006, <br>
* Author = "Georgescul, Maria and Clark, A. and Armstrong, S.", <br>
* Title = "{An Analysis of Quantitative Aspects in the Evaluation of Thematic Segmentation Algorithms}", <br>
* BookTitle = "SIGDIAL", <br>
* Address = "Sydney, Australia", <br>
* Year = "2006" }<br> <br>
* <br>
* <br>
* In this implementation, the Pr_error is estimated for the given reference and hypothetised files.
* Thus the first parameter of the main method should be a String specifying the full path name of
* the file containing the reference segmentation.
* The second parameter of the main method should be the full path name of the
* file containing the hypothetised segmentation.
* <br> Each ref/hyp file should be in a text format, where each topic segment is marked by "==========" string.
* <br> Please also note that any input (ref / hyp) file should contain the string '=========='
* as marking the start/end of the document
* (also when the entire document contains only one thematic episode).
*<br>
*
* Copyright (C) 2006 Maria Georgescul, ISSCO/TIM, ETI, UNIVERSITY OF GENEVA
* <br/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*<br/>
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* <br>
*
*@author Maria GEORGESCUL
*@version 1.0
*/
public class Pr_error extends MetricComputation{
public Pr_error(SegmentedText ref, SegmentedText hyp, int K) {
super(ref, hyp, K);
}
/**
* Computes Pr_error by taking a window of a fixed number of words (denoted by K).<br/>
* K is usually set as half segment length.<br/>
*
* Given the reference and the hypothesised segmentation map, compute Pr_error components
* (i.e. Pr_miss and Pr_false_alarm ) as follows: <br/>
* Pr_miss = [ sum (1-delta_ref)* teta_hyp ] / [ sum (1 - delta_ref )] </br>
* Pr_false_alarm = [ sum [ tau_hyp) ] ] / [N - k] </br>
* delta_ref = 0 when r(i, i+k) > 0; </br>
* = 0, when r(i, i+k) = 0 </br>
* teta_hyp = 1 when h(i, i+k) < r(i, i+k) </br>
* = 0, otherwise </br>
* tau_hyp = 1 when h(i, i+k) > r(i, i+k) </br>
* = 0 otherwise </br>
*
* @author Maria Georgescul
* @returns TopicSegEvalStats
* @param refB int[] -- for each segment i, refB[i] = word index before the thematic segment, in the reference file
* @param hypB int[] -- for each segment i, hypB[i] = word index before the thematic segment, in the hyp file
* @param K int
*/
protected EvalStats computeStats4Error(int[] refB, int[] hypB, int K){
EvalStats stat = new EvalStats();
int ie = refB[refB.length-1] - K ;
stat.noWords = ie ;
int noLoops = 0;
for (int i=0; i<ie; i++) {
try{
// verify if there is a boundary in the interval (i, i+K)
// loop all the boundaries in the
int noBoundRef = 0;
for (int tb = 0; tb < refB.length; tb++){
// check if the current boundary is in the interval (i, i+k)
if ((refB[tb] >= i) && (refB[tb] < i+K)){
noBoundRef++; // count here how many boundaries are in our interval
}
}
int noBoundHyp = 0;
for (int tb = 0; tb < hypB.length; tb++){
// check if the current boundary is in the interval (i, i+k)
if ((hypB[tb] >= i) && (hypB[tb] < i+K)){
noBoundHyp++; // count here how many boundaries are in our interval
}
}
int delta_ref = 0;
int teta_hyp = 0;
int tau_hyp = 0;
if (noBoundRef == 0) {
delta_ref = 1;
}
else { // there are > 0 boundaries in that interval for "ref" file
delta_ref = 0;
}
if (noBoundHyp < noBoundRef ) {
teta_hyp = 1;
tau_hyp = 0;
}
else {
if (noBoundHyp > noBoundRef ){
teta_hyp = 0;
tau_hyp = 1;
}
else{
teta_hyp = 0;
tau_hyp = 0;
}
}
stat.p_miss_numerator += ( teta_hyp * (1-delta_ref));
stat.p_miss_denominator += (1-delta_ref) ;
stat.p_fa_numerator += tau_hyp;
noLoops++;
}
catch(Exception e){
System.out.println("ERR when compute stats at i = " + i + " ik = " + i+ K );
}
} // end for
stat.p_fa_denominator = ie;
if ((stat.p_miss_denominator !=0 ) && (stat.p_fa_denominator !=0 )){
stat.p_miss = ((float) stat.p_miss_numerator / ((float) stat.p_miss_denominator));
stat.p_fa = (float)stat.p_fa_numerator / (float)stat.p_fa_denominator;
// stat.error = stat.p_miss + stat.p_fa ;
}
else {
stat.error = -1;
}
return stat;
}
/**
* Not implemented.
protected EvalStats computeStats4RefMap(int[] refMap, int[] hypMap, int K) {
return new EvalStats();
}
*/
/**
* Compute Pr_error for two annotation files.
* @param arg
*/
public static void main(String args[]) {
mgDebug.header("Implementation of the Pr_error evaluation metric proposed by (Georgescul et al., 2006).");
String refFile, hypFile;
int K = 2;
float C_miss = (float) 0.5;
// refFile = "C:/Documents and Settings/GEORGESC/Desktop/eval/ref/test.ref";
// hypFile = "C:/Documents and Settings/GEORGESC/Desktop/eval/hyp/test.out";
if(args.length == 4){
refFile = args[0];
hypFile = args[1];
try{
K = new Integer(args[2]).intValue();
}
catch(Error er){
System.out.println("Please provide as the third argument, an integer value specifying k, i.e. the window dimmension.");
System.exit(0);
}
try{
C_miss = new Float (args[3]).floatValue();
}
catch(Error er){
System.out.println("The fourth argument should be a double value ( in the interval [0, 1] ) specifying C_miss for your reference data.");
System.exit(0);
}
SegmentedText hyp = new SegmentedText();
if (hyp.initSegmentedText(hypFile) == false){
System.out.println("Err when loading hypothesised segmentation file ");
return;
};
SegmentedText ref = new SegmentedText();
if (ref.initSegmentedText(refFile) == false ){
System.out.println("Err when loading reference segmentation file ");
return;
};
Pr_error eval = new Pr_error(ref, hyp, K);
/* Print results */
// System.out.println(eval.stats.toString());
eval.stats.error = C_miss * eval.stats.p_miss + (1 - C_miss ) * eval.stats.p_fa;
System.out.println("For k = " + K + " and C_miss = " + C_miss +
" : \n Pr_error = " + eval.stats.error );
System.out.println(" Pr_miss = " + eval.stats.p_miss );
System.out.println(" Pr_fa = " + eval.stats.p_fa );
}
else{
System.out.println("The following arguments should be provided : ");
System.out.println("1) the name of the file containing the reference topic segmentation;");
System.out.println("2) the name of the file containing the hypothetised topic segmentation;");
System.out.println("3) an integer value specifying k, i.e. the window dimmension;");
System.out.println("4) a double value ( in the interval [0, 1] ), specifying the constant C_miss.");
System.exit(-1);
}
}
}
| 38.723214 | 141 | 0.571247 |
4dfeefbc168d105a76c6e42589143e4734f1f7dd | 2,554 |
package net.ninjaenterprises.dialer;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.net.Uri;
import android.content.ActivityNotFoundException;
import android.util.Log;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
/**
* Sample PhoneGap plugin to call Dialer app
* @author chale
*
*/
public class DialerPlugin extends CordovaPlugin{
public static final String ACTION_DIAL_NUMBER = "dialNumber";
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
try {
if (ACTION_DIAL_NUMBER.equals(action)) {
JSONObject arg_object = args.getJSONObject(0);
String phonenumber= arg_object.getString("phone_number");
// String phonenumber = "19195740046,,123456#,,,,,1"; // , = pauses
String encodedPhonenumber="";
encodedPhonenumber = URLEncoder.encode(phonenumber, "UTF-8");
Intent calIntent= new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + encodedPhonenumber));
this.cordova.getActivity().startActivity(calIntent);
callbackContext.success();
return true;
}
callbackContext.error("Invalid action");
return false;
} catch(Exception e) {
System.err.println("Exception: " + e.getMessage());
callbackContext.error(e.getMessage());
return false;
}
}
/*
*
* try {
Intent callIntent = new Intent(Intent.ACTION_CALL);
// callIntent.setData(Uri.parse("tel:+19195740046,,123456#,,,,,1"));
String phonenumber = "19195740046,,123456#,,,,,1"; // , = pauses
String encodedPhonenumber="";
try {
encodedPhonenumber = URLEncoder.encode(phonenumber, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + encodedPhonenumber)));
startActivity(callIntent);
} catch (ActivityNotFoundException e) {
Log.e("helloandroid dialing example", "Call failed", e);
}
*
* */
} // end class
| 29.356322 | 109 | 0.667972 |
f9955814e87e62f55bbd3ddc2d9e32cd76f77a2a | 296 | package org.flyants.book.utils;
import android.util.Log;
public class LogUtils {
public static final String TAG = "LOG_UTILS";
public static void d(String tag,String log){
Log.d(tag,log);
}
public static void d(Object log){
d(TAG,String.valueOf(log));
}
}
| 18.5 | 49 | 0.64527 |
902a352bc43f1d475e561963f332286270c06433 | 6,958 | package com.ksa.model.logistics;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.ksa.util.StringUtils;
public class ArrivalNote extends BaseLogisticsModel {
private static final long serialVersionUID = 2741955471843294574L;
private static DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
protected BookingNote bookingNote;
protected String date;
protected String code;
protected String consignee;
protected String shipper;
protected String vessel;
protected String voyage;
protected String mawb;
protected String hawb;
protected String container;
protected String seal;
protected String eta;
protected String cy;
protected String loadingPort;
protected String dischargePort;
protected String deliverPlace;
protected String cargoMark;
protected String cargoWeight;
protected String cargoVolumn;
protected String cargoDescription;
protected String cargo;
protected String pkg;
protected String count;
protected String freight;
protected String charge;
protected String rate;
@Override
public void initialModel( BookingNote bookingNote ) {
this.bookingNote = bookingNote;
this.date = format.format( new Date() );
this.consignee = bookingNote.getConsignee().getAlias();
this.shipper = bookingNote.getShipper().getAlias();
this.vessel = bookingNote.getRouteName();
this.voyage = bookingNote.getRouteCode();
this.mawb = bookingNote.getMawb();
this.hawb = bookingNote.getHawb();
if( StringUtils.hasText( this.mawb ) ) {
this.code = this.mawb;
int length = this.code.length();
if( length > 4 ) {
this.code = code.substring( length - 4, length );
}
}
if( bookingNote.getDestinationDate() != null ) {
this.eta = format.format( bookingNote.getDestinationDate() );
}
// 装货港
this.loadingPort = bookingNote.getLoadingPort();
if( this.loadingPort == null ) {
this.loadingPort = bookingNote.getDeparturePort();
}
this.dischargePort = bookingNote.getDischargePort();
if( this.dischargePort == null ) {
this.dischargePort = bookingNote.getDestinationPort();
}
this.cargoMark = bookingNote.getShippingMark();
if( bookingNote.getVolumn() != null ) {
this.cargoVolumn = bookingNote.getVolumn().toString();
}
if( bookingNote.getWeight() != null ) {
this.cargoWeight = bookingNote.getWeight().toString();
}
}
public String getDate() {
return date;
}
public void setDate( String date ) {
this.date = date;
}
public String getCode() {
return code;
}
public void setCode( String code ) {
this.code = code;
}
public String getConsignee() {
return consignee;
}
public void setConsignee( String consignee ) {
this.consignee = consignee;
}
public String getShipper() {
return shipper;
}
public void setShipper( String shipper ) {
this.shipper = shipper;
}
public String getVessel() {
return vessel;
}
public void setVessel( String vessel ) {
this.vessel = vessel;
}
public String getVoyage() {
return voyage;
}
public void setVoyage( String voyage ) {
this.voyage = voyage;
}
public String getMawb() {
return mawb;
}
public void setMawb( String mawb ) {
this.mawb = mawb;
}
public String getHawb() {
return hawb;
}
public void setHawb( String hawb ) {
this.hawb = hawb;
}
public String getContainer() {
return container;
}
public void setContainer( String container ) {
this.container = container;
}
public String getSeal() {
return seal;
}
public void setSeal( String seal ) {
this.seal = seal;
}
public String getEta() {
return eta;
}
public void setEta( String eta ) {
this.eta = eta;
}
public String getCy() {
return cy;
}
public void setCy( String cy ) {
this.cy = cy;
}
public String getLoadingPort() {
return loadingPort;
}
public void setLoadingPort( String loadingPort ) {
this.loadingPort = loadingPort;
}
public String getDischargePort() {
return dischargePort;
}
public void setDischargePort( String dischargePort ) {
this.dischargePort = dischargePort;
}
public String getDeliverPlace() {
return deliverPlace;
}
public void setDeliverPlace( String deliverPlace ) {
this.deliverPlace = deliverPlace;
}
public String getCargoMark() {
return cargoMark;
}
public void setCargoMark( String cargoMark ) {
this.cargoMark = cargoMark;
}
public String getCargoWeight() {
return cargoWeight;
}
public void setCargoWeight( String cargoWeight ) {
this.cargoWeight = cargoWeight;
}
public String getCargoVolumn() {
return cargoVolumn;
}
public void setCargoVolumn( String cargoVolumn ) {
this.cargoVolumn = cargoVolumn;
}
public String getCargoDescription() {
return cargoDescription;
}
public void setCargoDescription( String cargoDescription ) {
this.cargoDescription = cargoDescription;
}
public String getCargo() {
return cargo;
}
public void setCargo( String cargo ) {
this.cargo = cargo;
}
public String getPkg() {
return pkg;
}
public void setPkg( String pkg ) {
this.pkg = pkg;
}
public String getCount() {
return count;
}
public void setCount( String count ) {
this.count = count;
}
public BookingNote getBookingNote() {
return bookingNote;
}
public void setBookingNote( BookingNote bookingNote ) {
this.bookingNote = bookingNote;
}
public String getFreight() {
return freight;
}
public void setFreight( String freight ) {
this.freight = freight;
}
public String getCharge() {
return charge;
}
public void setCharge( String charge ) {
this.charge = charge;
}
public String getRate() {
return rate;
}
public void setRate( String rate ) {
this.rate = rate;
}
}
| 22.301282 | 74 | 0.579764 |
a3ebe134eebf0e4bdfdb0eb87016dc9182f7ce4f | 6,867 | /*
* Copyright 2014 Mahiar Mody.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mybatis.generator.hierarchical.plugins.jaxbAnnotations;
import hierarchical.fieldType.noLobs.modelDto.*; //these are our mbg generated compiled model classes that we want to test.
import org.mybatis.generator.JaxbAnnotationsTestUtils;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlAccessOrder;
import javax.xml.bind.annotation.XmlAccessorOrder;
import javax.xml.bind.annotation.XmlTransient;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
This class is used to test the MyBatis Generator generated model classes for
the presence of Jaxb annotations when the Xml access type specified is FIELD
and LOBs fields are not marshaled.
@author Mahiar Mody
*/
@RunWith(JUnit4.class)
public class FieldTypePresenceNoLobsTest
{
@Test
public void testXmlRootElementPresence()
{
JaxbAnnotationsTestUtils.checkXmlRootElementAnnotation(UsersKey.class, "usERs", null);
JaxbAnnotationsTestUtils.checkXmlRootElementAnnotation(Users.class, "usERs", null);
JaxbAnnotationsTestUtils.checkXmlRootElementAnnotation(UserSkillsKey.class, "userSkillsKey", null);
JaxbAnnotationsTestUtils.checkXmlRootElementAnnotation(UserSkills.class, "userSkills", null);
JaxbAnnotationsTestUtils.checkXmlRootElementAnnotation(UsersToSkillsKey.class, "usersToSkillsKey", null);
JaxbAnnotationsTestUtils.checkXmlRootElementAnnotation(UserPhotos.class, "Photos", "http://mybatis.generator.org/plugins/jaxb/test");
JaxbAnnotationsTestUtils.checkXmlRootElementAnnotation(UserBlog.class, "userBlog", null);
JaxbAnnotationsTestUtils.checkXmlRootElementAnnotation(UserTutorialKey.class, "Tutorial", null);
JaxbAnnotationsTestUtils.checkXmlRootElementAnnotation(UserTutorial.class, "Tutorial", null);
JaxbAnnotationsTestUtils.checkAccessTypeFieldClassAnnotation(UsersKey.class);
JaxbAnnotationsTestUtils.checkAccessTypeFieldClassAnnotation(Users.class);
JaxbAnnotationsTestUtils.checkAccessTypeFieldClassAnnotation(UserSkillsKey.class);
JaxbAnnotationsTestUtils.checkAccessTypeFieldClassAnnotation(UserSkills.class);
JaxbAnnotationsTestUtils.checkAccessTypeFieldClassAnnotation(UsersToSkillsKey.class);
JaxbAnnotationsTestUtils.checkAccessTypeFieldClassAnnotation(UserPhotos.class);
JaxbAnnotationsTestUtils.checkAccessTypeFieldClassAnnotation(UserBlog.class);
JaxbAnnotationsTestUtils.checkAccessTypeFieldClassAnnotation(UserTutorialKey.class);
JaxbAnnotationsTestUtils.checkAccessTypeFieldClassAnnotation(UserTutorial.class);
}
@Test
public void testXmlAccessorOrderPresence()
{
Class<?> cls = Users.class;
Annotation annt = cls.getAnnotation(XmlAccessorOrder.class);
Assert.assertNotNull("@XmlAccessorOrder annotation missing from Users class", annt);
XmlAccessOrder value = ((XmlAccessorOrder) annt).value();
Assert.assertTrue("XmlAccessOrder attribute of @XmlaccessorOrder element is wrong in User class",
XmlAccessOrder.ALPHABETICAL.equals(value));
cls = UsersKey.class;
annt = cls.getAnnotation(XmlAccessorOrder.class);
Assert.assertNotNull("@XmlAccessorOrder annotation missing from UsersKey class", annt);
value = ((XmlAccessorOrder) annt).value();
Assert.assertTrue("XmlAccessOrder attribute of @XmlaccessorOrder element is wrong in UsersKey classs",
XmlAccessOrder.ALPHABETICAL.equals(value));
}
@Test
public void testFieldLevelExplicitXmlAttributeAnnotations()
{
Field fldUserId = null, fldFirstName=null;
try
{
fldUserId = UsersKey.class.getDeclaredField("userId");
fldFirstName = Users.class.getDeclaredField("firstName");
}
catch(NoSuchFieldException e)
{
Assert.fail("NoSuchFieldException thrown. Check MyBatisGeneratorConfig.xml: " + e.getMessage());
}
fldUserId.setAccessible(true);
fldFirstName.setAccessible(true);
Annotation annt = fldUserId.getAnnotation(XmlAttribute.class);
Assert.assertNotNull("@XmlAttribute annotation missing from UsersKey.userId java class field", annt);
annt = fldFirstName.getAnnotation(XmlAttribute.class);
Assert.assertNotNull("@XmlAttribute annotation missing from Users.firstName java class field", annt);
String name = ((XmlAttribute) annt).name();
boolean required = ((XmlAttribute) annt).required();
Assert.assertEquals("name attribute of the @XmlAttribute annotation is wrong or missing in Users.firstName java class field",
"first_name", name);
Assert.assertTrue("required attribute of @XmlAttribute annotation is wrong or missing in Users.firstName java class field",
required);
}
@Test
public void testBlobFieldsNotAnnotatedWithXmlTransientInWithBlobsClass()
{
Field fldPhoto = null, fldBlogTxt=null;
try
{
fldPhoto = UserPhotosWithBLOBs.class.getDeclaredField("photo");
fldBlogTxt = UserBlogWithBLOBs.class.getDeclaredField("blogText");
}
catch(NoSuchFieldException e)
{
Assert.fail("NoSuchFieldException thrown. Check SetupDbTestScripts.sql file: " + e.getMessage());
}
fldPhoto.setAccessible(true);
fldBlogTxt.setAccessible(true);
Annotation annt = fldPhoto.getAnnotation(XmlTransient.class);
Assert.assertNull("@XmlTransient annotation present in UserPhotosWithBLOBs.photo java class field. It shouldn't be as class itself not annotated.", annt);
annt = fldBlogTxt.getAnnotation(XmlTransient.class);
Assert.assertNull("@XmlTransient annotation present in UserBlogWithBLOBs.blogText java class field. It shouldn't be as class itself not annotated.", annt);
}
@Test
public void testClassWithBlobsNotAnnotated()
{
Annotation[] arrAnnts = UserTutorialWithBLOBs.class.getDeclaredAnnotations();
Assert.assertTrue("UserTutorialWithBLOBs class should NOT be annotated at all, but it is.", arrAnnts.length == 0);
arrAnnts = UserPhotosWithBLOBs.class.getDeclaredAnnotations();
Assert.assertTrue("UserPhotosWithBLOBs class should NOT be annotated at all, but it is.", arrAnnts.length == 0);
arrAnnts = UserBlogWithBLOBs.class.getDeclaredAnnotations();
Assert.assertTrue("UserBlogWithBLOBs class should NOT be annotated at all, but it is.", arrAnnts.length == 0);
}
}
| 36.526596 | 157 | 0.793796 |
bd073935004bcb0cd2513cf405f3b2b592336444 | 1,243 | package daos;
import java.util.List;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.sql.ResultSet;
import models.TipoEstrato;
import java.sql.Connection;
import javax.inject.Inject;
import play.db.*;
public class TipoEstratoDAO{
private Database db;
@Inject
private TipoEstratoDAO(Database db) {
this.db = db;
}
public List<TipoEstrato> getTipoEstrato(){
List<TipoEstrato> _dataList = new ArrayList<TipoEstrato>();
PreparedStatement stmt;
Connection conn = db.getConnection();
try {
String sql;
sql = "SELECT t.ID_ESTRATO, t.DESCRIPCION FROM \"gen$estrato\" t";
stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
//Extract data from result set
if (rs != null){
while(rs.next()){
TipoEstrato tp = new TipoEstrato();
tp.set_id(rs.getInt("ID_ESTRATO"));
tp.set_descripcion(rs.getString("DESCRIPCION"));
_dataList.add(tp);
}
}
} catch ( Exception e){
e.printStackTrace();
}
return _dataList;
}
} | 26.446809 | 78 | 0.572808 |
14a2068a7aca9fa7c152bbe8afb8208b8aa0e1fd | 4,700 | package org.openmrs.module.mentalhealth.activator;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.api.FormService;
import org.openmrs.api.context.Context;
import org.openmrs.module.mentalhealth.MentalHealthConstants;
import org.openmrs.module.mentalhealth.utils.MentalHealthExtensionFormUtil;
import org.openmrs.module.formentryapp.FormEntryAppService;
import org.openmrs.module.formentryapp.FormManager;
import org.openmrs.module.formentryapp.page.controller.forms.ExtensionForm;
import org.openmrs.module.htmlformentry.HtmlForm;
import org.openmrs.module.htmlformentry.HtmlFormEntryService;
import org.openmrs.module.htmlformentryui.HtmlFormUtil;
import org.openmrs.ui.framework.resource.ResourceFactory;
import org.openmrs.ui.framework.resource.ResourceProvider;
/**
* Sets up the HFE forms
* 1) Scans the webapp/resources/htmlforms folder
* 2) Attempts to create an HFE form from each of the files
* 3) Adds the forms as in Configure MentalHealthMetadata \ Manage Forms
*/
public class MentalHealthHtmlFormsInitializer implements MentalHealthInitializer {
protected static final Log log = LogFactory.getLog(MentalHealthHtmlFormsInitializer.class);
protected static final String providerName = "mentalhealth";
protected static final String formsPath = "htmlforms/";
/**
* @see MentalHealthInitializer#started()
*/
public synchronized void started() {
log.info("Setting HFE forms for " + MentalHealthConstants.MODULE_ID);
final ResourceFactory resourceFactory = ResourceFactory.getInstance();
final ResourceProvider resourceProvider = resourceFactory.getResourceProviders().get(providerName);
// Scanning the forms resources folder
final List<String> formPaths = new ArrayList<String>();
final File formsDir = resourceProvider.getResource(formsPath); // The ResourceFactory can't return File instances, hence the ResourceProvider need
if (formsDir == null || formsDir.isDirectory() == false) {
log.error("No HTML forms could be retrieved from the provided folder: " + providerName + ":" + formsPath);
return;
}
for (File file : formsDir.listFiles())
formPaths.add(formsPath + file.getName()); // Adding each file's path to the list
// Save form + add its meta data
final FormManager formManager = Context.getRegisteredComponent("formManager", FormManager.class);
final FormEntryAppService hfeAppService = Context.getRegisteredComponent("formEntryAppService", FormEntryAppService.class);
final FormService formService = Context.getFormService();
final HtmlFormEntryService hfeService = Context.getService(HtmlFormEntryService.class);
for (String formPath : formPaths) {
// Save form
HtmlForm htmlForm = null;
try {
htmlForm = HtmlFormUtil.getHtmlFormFromUiResource(resourceFactory, formService, hfeService, providerName, formPath);
try {
// Adds meta data
System.out.println("The form is found here :::"+htmlForm.getName());
ExtensionForm extensionForm = MentalHealthExtensionFormUtil.getExtensionFormFromUiResourceAndForm(resourceFactory, providerName, formPath, hfeAppService, formManager, htmlForm.getForm());
log.info("The form at " + formPath + " has been successfully loaded with its metadata");
} catch (Exception e) {
log.error("The form was created but its extension point could not be created in Manage Forms \\ Configure MentalHealthMetadata: " + formPath, e);
throw new RuntimeException("The form was created but its extension point could not be created in Manage Forms \\ Configure MentalHealthMetadata: " + formPath, e);
}
} catch (IOException e) {
log.error("Could not generate HTML form from the following resource file: " + formPath, e);
throw new RuntimeException("Could not generate HTML form from the following resource file: " + formPath, e);
} catch (IllegalArgumentException e) {
log.error("Error while parsing the form's XML: " + formPath, e);
throw new IllegalArgumentException("Error while parsing the form's XML: " + formPath, e);
}
}
}
/**
* @see MentalHealthInitializer#stopped()
*/
public void stopped() {
//TODO: Perhaps disable the forms?
}
}
| 51.086957 | 207 | 0.703617 |
cda14a4c85f21fbf79a0464cf858cfb9592a341c | 215 | package io.github.stereo.items;
import io.github.stereo.Main;
import net.minecraft.item.Item;
public class Items extends Item {
public Items() {
super(new Item.Properties().group(Main.TAB));
}
}
| 16.538462 | 53 | 0.688372 |
b1fd16db061dc8063e3058b7a239daf06fa11f19 | 690 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.py.hib.mytest.generator;
//import org.hibernate.*;
/**
*
* @author Administrator
*/
@SuppressWarnings("serial")
public class GeneratorTest implements java.io.Serializable
{
private Integer id;
private String name;
public GeneratorTest()
{
}
public Integer getId()
{
return this.id;
}
public void setId(Integer id)
{
this.id = id;
}
public String getName()
{
return this.name;
}
public void setName(String name)
{
this.name = name;
}
}
| 15.681818 | 60 | 0.573913 |
f5c65a5b7dc21d7e900601145ada0040d62d000a | 2,242 | package org.smartregister.cbhc.fragment;
import android.os.Bundle;
import android.support.v4.view.GestureDetectorCompat;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import org.smartregister.cbhc.activity.BaseProfileActivity;
import org.smartregister.view.fragment.SecuredFragment;
/**
* Created by ndegwamartin on 12/07/2018.
*/
public abstract class BaseProfileFragment extends SecuredFragment implements View.OnTouchListener {
private GestureDetectorCompat gestureDetector;
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gestureDetector = new GestureDetectorCompat(this.getActivity(), new ProfileFragmentsSwipeListener());
view.setOnTouchListener(this);
}
@Override
public boolean onTouch(View view, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
class ProfileFragmentsSwipeListener extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onDown(MotionEvent event) {
return true;
}
@Override
public boolean onFling(MotionEvent event1, MotionEvent event2, float velocityX, float velocityY) {
final int SWIPE_MIN_DISTANCE = 120;
final int SWIPE_MAX_OFF_PATH = 300;
final int SWIPE_THRESHOLD_VELOCITY = 200;
try {
if (Math.abs(event1.getX() - event2.getX()) > SWIPE_MAX_OFF_PATH) {
return false;
}
if (event1.getY() - event2.getY() > SWIPE_MIN_DISTANCE && Math.abs(velocityY) > SWIPE_THRESHOLD_VELOCITY) {
((BaseProfileActivity) getActivity()).getProfileAppBarLayout().setExpanded(false, true);
} else if (event2.getY() - event1.getY() > SWIPE_MIN_DISTANCE && Math.abs(velocityY) > SWIPE_THRESHOLD_VELOCITY) {
((BaseProfileActivity) getActivity()).getProfileAppBarLayout().setExpanded(true, true);
}
} catch (Exception e) {
// nothing
}
return super.onFling(event1, event2, velocityX, velocityY);
}
}
} | 35.03125 | 130 | 0.668153 |
4096738a4c7a7167b06eef46a34c3b37ab9e58c0 | 2,456 | package org.kuali.kpme.edo.item.web;
import java.util.LinkedList;
import java.util.List;
import org.apache.struts.upload.FormFile;
import org.kuali.kpme.edo.api.checklist.EdoChecklistItem;
import org.kuali.kpme.edo.api.item.EdoItem;
import org.kuali.kpme.edo.base.web.EdoForm;
import org.kuali.kpme.edo.service.EdoServiceLocator;
/**
* $HeadURL$
* $Revision$
* Created with IntelliJ IDEA.
* User: bradleyt
* Date: 6/24/13
* Time: 10:03 AM
*/
public class EdoSectionSummaryForm extends EdoForm {
private List<EdoChecklistItem> checklistItems = EdoServiceLocator.getChecklistItemService().getChecklistItems("IU-IN", "ALL", "ALL");
private FormFile uploadFile;
private int checklistItemID;
private int itemID;
private String outputJson;
private String nidFwd;
private String formData;
List<EdoItem> itemList = new LinkedList<EdoItem>();
/* KPME-3705 This has been changed to int count from EdoItemService
List<EdoItemCountV> itemCount = new LinkedList<EdoItemCou ntV>(); */
private int itemCount;
public void setItemCount(int itemCount) {
this.itemCount = itemCount;
}
public String getFormData() {
return formData;
}
public void setFormData(String formData) {
this.formData = formData;
}
public FormFile getUploadFile() {
return uploadFile;
}
public void setUploadFile(FormFile file) {
this.uploadFile = file;
}
public List<EdoChecklistItem> getChecklistItems() {
return checklistItems;
}
public void setChecklistItems(List<EdoChecklistItem> checklistItems) {
this.checklistItems = checklistItems;
}
public int getChecklistItemID() {
return checklistItemID;
}
public void setChecklistItemID(int checklistItemID) {
this.checklistItemID = checklistItemID;
}
public int getItemID() {
return itemID;
}
public void setItemID(int itemID) {
this.itemID = itemID;
}
public String getOutputJson() {
return outputJson;
}
public void setOutputJson(String outputJson) {
this.outputJson = outputJson;
}
public List<EdoItem> getItemList() {
return itemList;
}
public void setItemList(List<EdoItem> itemList) {
this.itemList = itemList;
}
public String getNidFwd() {
return nidFwd;
}
public void setNidFwd(String nidFwd) {
this.nidFwd = nidFwd;
}
}
| 24.078431 | 137 | 0.681596 |
934add342354c9fba38714c1a66f40acea4726bd | 5,109 | package com.example.starsucks;
import androidx.appcompat.app.AppCompatActivity;
import android.app.DatePickerDialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.Calendar;
public class OrderDetailsActivity extends AppCompatActivity {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference starSucksRef = database.getReference("orders");
private EditText etCustomerName;
private EditText etCustomerCell;
private TextView placedOrder;
private String orderValue;
private ImageView imgOrderdBeverage;
private FloatingActionButton fab_order;
private FloatingActionButton fab_calender;
private FloatingActionButton fab_cloud;
private Order order;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_details);
order = new Order();
fab_order = findViewById(R.id.fab_order);
fab_calender = findViewById(R.id.fab_calender);
fab_cloud = findViewById(R.id.fab_cloud);
placedOrder = findViewById(R.id.tv_placedOrder);
etCustomerName = findViewById(R.id.et_customerName);
etCustomerCell = findViewById(R.id.et_customerCell);
imgOrderdBeverage = findViewById(R.id.img_orderedBeverage);
orderValue = getIntent().getStringExtra("order");
placedOrder.setText(orderValue);
switch (orderValue) {
case "Soy Latte":
imgOrderdBeverage.setImageResource(R.drawable.sb1);
break;
case "Chocco Frappe":
imgOrderdBeverage.setImageResource(R.drawable.sb2);
break;
case "Bottled Americano":
imgOrderdBeverage.setImageResource(R.drawable.sb3);
break;
case "Rainbow Frapp":
imgOrderdBeverage.setImageResource(R.drawable.sb4);
break;
case "Caramel Frapp":
imgOrderdBeverage.setImageResource(R.drawable.sb5);
break;
case "Black Forest Frapp":
imgOrderdBeverage.setImageResource(R.drawable.sb6);
break;
}
fab_order.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
intentHelper.shareIntent(OrderDetailsActivity.this, orderValue);
}
});
fab_calender.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// create a calender to get today's date
Calendar datePickerCalender = Calendar.getInstance();
int year = datePickerCalender.get(Calendar.YEAR);
int month = datePickerCalender.get(Calendar.MONTH);
int day = datePickerCalender.get(Calendar.DAY_OF_MONTH);
//show a datepicker, starting from today's date
DatePickerDialog ordersDatePicker = new DatePickerDialog(
OrderDetailsActivity.this,
android.R.style.Theme_Light_Panel,
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
//set the date of the order once it is picked
order.setOrderDate(year + "-" + month + "-" + dayOfMonth);
}
}, year, month, day);
ordersDatePicker.show();
}
});
fab_cloud.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String customerCell = etCustomerCell.getText().toString();
String customerName = etCustomerName.getText().toString();
// validate data
if(
!TextUtils.isEmpty(customerName) &&
!TextUtils.isEmpty(customerCell) &&
!TextUtils.isEmpty(order.getOrderDate()) &&
!TextUtils.isEmpty(orderValue)
) {
order.setProductName(orderValue);
order.setCustomerName(customerName);
order.setCustomerCell(customerCell);
starSucksRef.push().setValue(order);
} else {
Toast.makeText(OrderDetailsActivity.this, "Please complete all fields", Toast.LENGTH_SHORT).show();
}
}
});
}
} | 39.604651 | 119 | 0.607947 |
04502698a1b6db926d642947bf26e82d2021f1e2 | 1,661 | package uk.gov.hmcts.reform.hmc.helper.hmi;
import org.springframework.stereotype.Component;
import uk.gov.hmcts.reform.hmc.model.PartyDetails;
import uk.gov.hmcts.reform.hmc.model.hmi.EntityCommunication;
import java.util.ArrayList;
import java.util.List;
import static uk.gov.hmcts.reform.hmc.constants.Constants.EMAIL_TYPE;
import static uk.gov.hmcts.reform.hmc.constants.Constants.PHONE_TYPE;
@Component
public class CommunicationsMapper {
public List<EntityCommunication> getCommunications(PartyDetails partyDetails) {
List<EntityCommunication> entityCommunications = new ArrayList<>();
if (partyDetails.getIndividualDetails().getHearingChannelEmail() != null) {
for (String email : partyDetails.getIndividualDetails().getHearingChannelEmail()) {
EntityCommunication entityCommunication = EntityCommunication.builder()
.entityCommunicationDetails(email)
.entityCommunicationType(EMAIL_TYPE)
.build();
entityCommunications.add(entityCommunication);
}
}
if (partyDetails.getIndividualDetails().getHearingChannelPhone() != null) {
for (String phoneNumber : partyDetails.getIndividualDetails().getHearingChannelPhone()) {
EntityCommunication entityCommunication = EntityCommunication.builder()
.entityCommunicationDetails(phoneNumber)
.entityCommunicationType(PHONE_TYPE)
.build();
entityCommunications.add(entityCommunication);
}
}
return entityCommunications;
}
}
| 41.525 | 101 | 0.686334 |
921d7a21534271fa0d50820c4d48b7140dca3033 | 332 | package io.github.reflekt;
import java.util.Set;
public interface ReflektSubClasses {
/**
* Returns all classes that are sub types of the parameter class
* @param clazz scanning subclasses for
* @return all classes that are sub types of the parameter class
*/
Set<Class> getSubClasses(Class clazz);
}
| 23.714286 | 68 | 0.704819 |
424d1cf320871d902058e579e088f6b1c4f40143 | 1,569 | package com.virjar.vscrawler.core.processor;
import com.google.common.collect.Lists;
import com.virjar.vscrawler.core.seed.Seed;
import java.util.Collection;
import java.util.List;
/**
* Created by virjar on 17/4/16.
* 请使用GrabResult
*
* @author virjar
* @see GrabResult
* @since 0.0.1
* @deprecated
*/
public class CrawlResult {
/**
* 一个种子可能产生多个结果
*/
//private List<String> results = Lists.newLinkedList();
private List<Seed> newSeeds = Lists.newLinkedList();
public void addResult(String result) {
throw new UnsupportedOperationException("add result for CrawlResult is not allowed now");
// results.add(result);
}
public void addResults(Collection<?> resultsIn) {
throw new UnsupportedOperationException("add result for CrawlResult is not allowed now");
//results.addAll(resultsIn);
}
public List<String> allResult() {
throw new UnsupportedOperationException("allResult for CrawlResult is not allowed now");
//return Lists.newArrayList(results);
}
public void addSeed(Seed seed) {
newSeeds.add(seed);
}
public void addStrSeeds(Collection<String> seeds) {
for (String str : seeds) {
addSeed(str);
}
}
public void addSeeds(Collection<Seed> seeds) {
for (Seed seed : seeds) {
addSeed(seed);
}
}
public void addSeed(String seed) {
newSeeds.add(new Seed(seed));
}
public List<Seed> allSeed() {
return Lists.newArrayList(newSeeds);
}
}
| 24.138462 | 98 | 0.641173 |
017fcf424cea74a19805bc11a1333e5f22485494 | 6,673 | package cn.com.sciencsys.sciencsys.UImaker;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.RecyclerView;
import cn.com.sciencsys.sciencsys.PopActivity;
import cn.com.sciencsys.sciencsys.R;
import cn.com.sciencsys.sciencsys.initsystem.Constants;
import cn.com.sciencsys.sciencsys.initsystem.Sensor;
public class SensorAdapter extends RecyclerView.Adapter<SensorAdapter.ViewHolder> {
private UploadCommandListener uploadCommandListener;
private Context context;
private List<Sensor> mSensorList;
private Sensor sensor;
private int whichDw = 0; //档位
private int whichPl = 0; //频率
static class ViewHolder extends RecyclerView.ViewHolder{
TextView sensorId;
TextView sensorDate;
TextView sensorPort;
TextView sensorName;
View sensorView;
public ViewHolder(View view){
super(view);
sensorView = view;
sensorId = (TextView) view.findViewById(R.id.idText);
sensorDate = (TextView) view.findViewById(R.id.dataText);
sensorPort = (TextView) view.findViewById(R.id.portText);
sensorName = (TextView) view.findViewById(R.id.nameText);
}
}
public SensorAdapter(Context context,List<Sensor> sensorList){
this.mSensorList = sensorList;
this.context = context;
}
public void setUploadCommandListener(UploadCommandListener uploadCommandListener) {
this.uploadCommandListener = uploadCommandListener;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.sensor,parent,false);
final ViewHolder holder =new ViewHolder(view);
return holder;
}
/**
* 该回调可以实现Item的部分数据的更新而不更新所以数据
* @param holder
* @param position
* @param payloads
*/
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position, @NonNull List<Object> payloads) {
if (payloads.isEmpty()){
onBindViewHolder(holder,position);
}else {
holder.sensorDate.setText(String.valueOf(mSensorList.get(position).getData()));
}
}
//对recycleview子项赋值
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {
sensor = mSensorList.get(position);
holder.sensorId.setText("ID:"+String.valueOf(sensor.getId())); //setText传入其他类型数据会出错
holder.sensorDate.setText(String.valueOf(sensor.getData()));
holder.sensorPort.setText("Port:"+String.valueOf(sensor.getPort()));
holder.sensorName.setText(sensor.IdToName(sensor.getId()));
/**
* 长按选择
*/
holder.sensorView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return false;
}
});
/**
* 之前的按键监听放在onCreateViewHolder中,无法获取position
* 先选择档位:档位根据传感器Id来选择
* 确定后再选择频率,频率固定
* 此dialog可以取消,只有确定后才会上传数据
* 此dialog只有在通用软件处使用,所以不在activity上应用,集成在adapter中,方便之后有rec时候调用
*/
holder.sensorView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("选择档位:");
//设置按键监听
alertDialog.setSingleChoiceItems(sensor.IdToGear(mSensorList.get(position).getId()), position, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
whichDw = which;
}
});
alertDialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
/**
* 频率选择
* @param dialog
* @param which
*/
String[] mString = new String[]{"1Hz","10Hz","50Hz","100Hz","1KHz"};
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("选择频率:");
//设置按键监听
alertDialog.setSingleChoiceItems(mString, 0, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
whichPl = which;
}
});
alertDialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
//确定后开线程上传档位数据
//用回调到PopActivity中处理
@Override
public void onClick(DialogInterface dialog, int which) {
uploadCommandListener.onUploadCommand(whichDw,whichPl,sensor.getPort());
}
});
alertDialog.create();
alertDialog.show();
}
});
alertDialog.create();
alertDialog.show();
}
});
}
@Override
public int getItemCount() {
return mSensorList.size();
}
public void addItem(int position,Sensor sensor){
if (sensor != null) {
mSensorList.add(position, sensor);
notifyItemChanged(position);
}
}
public void removeItem(int position){
if (getItemCount() > 0) {
mSensorList.remove(position);
notifyItemRemoved(position);
}
}
public void removeAllItem(){
if (getItemCount() > 0) {
for (int i =0 ;i<getItemCount();i++) {
mSensorList.remove(i);
}
notifyItemRangeRemoved(0,getItemCount());
}
}
public void updataItemDataText(int position, float data){
}
}
| 35.306878 | 150 | 0.580698 |
571401b96162d3aeca5a231d676db2fcbf6f8fff | 311 | package fun.lovexy.reverseproxy.service;
import fun.lovexy.reverseproxy.entity.Mapping;
import com.baomidou.mybatisplus.extension.service.IService;
import java.util.List;
public interface MappingService extends IService<Mapping> {
List<Mapping> enabledList();
boolean removeByIdCascade(int id);
}
| 20.733333 | 59 | 0.794212 |
a20c6b2f44dc6c43e213842199201dbda535bdaa | 141 | package mappers;
import java.util.List;
public interface ICityMapper {
public List<String> queryCityInfo(String str)throws Exception;
}
| 14.1 | 63 | 0.787234 |
14c8343c1eea34d9d87bee322be9b0aa2c9ac149 | 11,028 | package com.github.steveice10.mc.protocol;
import com.github.steveice10.mc.auth.data.GameProfile;
import com.github.steveice10.mc.auth.exception.request.RequestException;
import com.github.steveice10.mc.auth.service.SessionService;
import com.github.steveice10.mc.protocol.data.SubProtocol;
import com.github.steveice10.mc.protocol.data.status.PlayerInfo;
import com.github.steveice10.mc.protocol.data.status.ServerStatusInfo;
import com.github.steveice10.mc.protocol.data.status.VersionInfo;
import com.github.steveice10.mc.protocol.data.status.handler.ServerInfoBuilder;
import com.github.steveice10.mc.protocol.packet.handshake.client.HandshakePacket;
import com.github.steveice10.mc.protocol.packet.ingame.client.ClientKeepAlivePacket;
import com.github.steveice10.mc.protocol.packet.ingame.server.ServerDisconnectPacket;
import com.github.steveice10.mc.protocol.packet.ingame.server.ServerKeepAlivePacket;
import com.github.steveice10.mc.protocol.packet.login.client.EncryptionResponsePacket;
import com.github.steveice10.mc.protocol.packet.login.client.LoginStartPacket;
import com.github.steveice10.mc.protocol.packet.login.server.EncryptionRequestPacket;
import com.github.steveice10.mc.protocol.packet.login.server.LoginDisconnectPacket;
import com.github.steveice10.mc.protocol.packet.login.server.LoginSetCompressionPacket;
import com.github.steveice10.mc.protocol.packet.login.server.LoginSuccessPacket;
import com.github.steveice10.mc.protocol.packet.status.client.StatusPingPacket;
import com.github.steveice10.mc.protocol.packet.status.client.StatusQueryPacket;
import com.github.steveice10.mc.protocol.packet.status.server.StatusPongPacket;
import com.github.steveice10.mc.protocol.packet.status.server.StatusResponsePacket;
import com.github.steveice10.packetlib.Session;
import com.github.steveice10.packetlib.event.session.ConnectedEvent;
import com.github.steveice10.packetlib.event.session.DisconnectingEvent;
import com.github.steveice10.packetlib.event.session.PacketReceivedEvent;
import com.github.steveice10.packetlib.event.session.PacketSentEvent;
import com.github.steveice10.packetlib.event.session.SessionAdapter;
import net.kyori.adventure.text.Component;
import javax.crypto.SecretKey;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.util.Arrays;
import java.util.Random;
import java.util.UUID;
/**
* Handles initial login and status requests for servers.
*/
public class ServerListener extends SessionAdapter {
private static final int DEFAULT_COMPRESSION_THRESHOLD = 256;
// Always empty post-1.7
private static final String SERVER_ID = "";
private static final KeyPair KEY_PAIR;
static {
try {
KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
gen.initialize(1024);
KEY_PAIR = gen.generateKeyPair();
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("Failed to generate server key pair.", e);
}
}
private byte[] verifyToken = new byte[4];
private String username = "";
private long lastPingTime = 0;
private int lastPingId = 0;
public ServerListener() {
new Random().nextBytes(this.verifyToken);
}
@Override
public void connected(ConnectedEvent event) {
event.getSession().setFlag(MinecraftConstants.PING_KEY, 0);
}
@Override
public void packetReceived(PacketReceivedEvent event) {
MinecraftProtocol protocol = (MinecraftProtocol) event.getSession().getPacketProtocol();
if (protocol.getSubProtocol() == SubProtocol.HANDSHAKE) {
if (event.getPacket() instanceof HandshakePacket) {
HandshakePacket packet = event.getPacket();
switch (packet.getIntent()) {
case STATUS:
protocol.setSubProtocol(SubProtocol.STATUS, false, event.getSession());
break;
case LOGIN:
protocol.setSubProtocol(SubProtocol.LOGIN, false, event.getSession());
if (packet.getProtocolVersion() > MinecraftConstants.PROTOCOL_VERSION) {
event.getSession().disconnect("Outdated server! I'm still on " + MinecraftConstants.GAME_VERSION + ".");
} else if (packet.getProtocolVersion() < MinecraftConstants.PROTOCOL_VERSION) {
event.getSession().disconnect("Outdated client! Please use " + MinecraftConstants.GAME_VERSION + ".");
}
break;
default:
throw new UnsupportedOperationException("Invalid client intent: " + packet.getIntent());
}
}
}
if (protocol.getSubProtocol() == SubProtocol.LOGIN) {
if (event.getPacket() instanceof LoginStartPacket) {
this.username = event.<LoginStartPacket>getPacket().getUsername();
if (event.getSession().getFlag(MinecraftConstants.VERIFY_USERS_KEY, true)) {
event.getSession().send(new EncryptionRequestPacket(SERVER_ID, KEY_PAIR.getPublic(), this.verifyToken));
} else {
new Thread(new UserAuthTask(event.getSession(), null)).start();
}
} else if (event.getPacket() instanceof EncryptionResponsePacket) {
EncryptionResponsePacket packet = event.getPacket();
PrivateKey privateKey = KEY_PAIR.getPrivate();
if (!Arrays.equals(this.verifyToken, packet.getVerifyToken(privateKey))) {
event.getSession().disconnect("Invalid nonce!");
return;
}
SecretKey key = packet.getSecretKey(privateKey);
protocol.enableEncryption(key);
new Thread(new UserAuthTask(event.getSession(), key)).start();
}
}
if (protocol.getSubProtocol() == SubProtocol.STATUS) {
if (event.getPacket() instanceof StatusQueryPacket) {
ServerInfoBuilder builder = event.getSession().getFlag(MinecraftConstants.SERVER_INFO_BUILDER_KEY);
if (builder == null) {
builder = session -> new ServerStatusInfo(
VersionInfo.CURRENT,
new PlayerInfo(0, 20, new GameProfile[0]),
Component.text("A Minecraft Server"),
null
);
}
ServerStatusInfo info = builder.buildInfo(event.getSession());
event.getSession().send(new StatusResponsePacket(info));
} else if (event.getPacket() instanceof StatusPingPacket) {
event.getSession().send(new StatusPongPacket(event.<StatusPingPacket>getPacket().getPingTime()));
}
}
if (protocol.getSubProtocol() == SubProtocol.GAME) {
if (event.getPacket() instanceof ClientKeepAlivePacket) {
ClientKeepAlivePacket packet = event.getPacket();
if (packet.getPingId() == this.lastPingId) {
long time = System.currentTimeMillis() - this.lastPingTime;
event.getSession().setFlag(MinecraftConstants.PING_KEY, time);
}
}
}
}
@Override
public void packetSent(PacketSentEvent event) {
Session session = event.getSession();
if (event.getPacket() instanceof LoginSetCompressionPacket) {
session.setCompressionThreshold(event.<LoginSetCompressionPacket>getPacket().getThreshold());
session.send(new LoginSuccessPacket(session.getFlag(MinecraftConstants.PROFILE_KEY)));
} else if (event.getPacket() instanceof LoginSuccessPacket) {
((MinecraftProtocol) session.getPacketProtocol()).setSubProtocol(SubProtocol.GAME, false, session);
ServerLoginHandler handler = session.getFlag(MinecraftConstants.SERVER_LOGIN_HANDLER_KEY);
if (handler != null) {
handler.loggedIn(session);
}
if (event.getSession().getFlag(MinecraftConstants.AUTOMATIC_KEEP_ALIVE_MANAGEMENT, true)) {
new Thread(new KeepAliveTask(session)).start();
}
}
}
@Override
public void disconnecting(DisconnectingEvent event) {
MinecraftProtocol protocol = (MinecraftProtocol) event.getSession().getPacketProtocol();
if (protocol.getSubProtocol() == SubProtocol.LOGIN) {
event.getSession().send(new LoginDisconnectPacket(event.getReason()));
} else if (protocol.getSubProtocol() == SubProtocol.GAME) {
event.getSession().send(new ServerDisconnectPacket(event.getReason()));
}
}
private class UserAuthTask implements Runnable {
private Session session;
private SecretKey key;
public UserAuthTask(Session session, SecretKey key) {
this.key = key;
this.session = session;
}
@Override
public void run() {
GameProfile profile = null;
if (this.key != null) {
SessionService sessionService = this.session.getFlag(MinecraftConstants.SESSION_SERVICE_KEY, new SessionService());
try {
profile = sessionService.getProfileByServer(username, sessionService.getServerId(SERVER_ID, KEY_PAIR.getPublic(), this.key));
} catch (RequestException e) {
this.session.disconnect("Failed to make session service request.", e);
return;
}
if (profile == null) {
this.session.disconnect("Failed to verify username.");
}
} else {
profile = new GameProfile(UUID.nameUUIDFromBytes(("OfflinePlayer:" + username).getBytes()), username);
}
this.session.setFlag(MinecraftConstants.PROFILE_KEY, profile);
int threshold = session.getFlag(MinecraftConstants.SERVER_COMPRESSION_THRESHOLD, DEFAULT_COMPRESSION_THRESHOLD);
this.session.send(new LoginSetCompressionPacket(threshold));
}
}
private class KeepAliveTask implements Runnable {
private Session session;
public KeepAliveTask(Session session) {
this.session = session;
}
@Override
public void run() {
while (this.session.isConnected()) {
lastPingTime = System.currentTimeMillis();
lastPingId = (int) lastPingTime;
this.session.send(new ServerKeepAlivePacket(lastPingId));
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
break;
}
}
}
}
}
| 45.570248 | 145 | 0.647624 |
a568607494343e6a272722ba74329038cc1ca143 | 350 | package com.example.adapterdemo.model;
public class Product {
public String name;
public int price;
public int image;
public boolean checked;
public Product(String _describe, int _price, int _image, boolean _checked) {
name = _describe;
price = _price;
image = _image;
checked = _checked;
}
} | 23.333333 | 80 | 0.645714 |
41e85b2bd5b9b1fd0e17a143a45196638b7ed97e | 4,233 | /*
* Copyright 2016 Yan Zhenjie
*
* 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.yanzhenjie.alertdialog.sample;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.yanzhenjie.alertdialog.AlertDialog;
/**
* Created by Yan Zhenjie on 2016/12/28.
*/
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
findViewById(R.id.btn_show_common).setOnClickListener(mOnClickListener);
findViewById(R.id.btn_show_special).setOnClickListener(mOnClickListener);
}
// 这里注意包别导错了。
// X 不是:android.support.v7.app.AlertDialog
// X 不是:android.app.AlertDialog
// √ 是:com.yanzhenjie.alertdialog.AlertDialog
/**
* 显示正常用法的按钮。
*/
private void onCommonClick() {
AlertDialog.build(this)
.setTitle("标题")
.setMessage("提示信息")
.setNeutralButton("忽略", (dialog, which) -> {
Toast.makeText(MainActivity.this, "点击了忽略", Toast.LENGTH_SHORT).show();
})
.setNegativeButton("取消", (dialog, which) -> {
Toast.makeText(MainActivity.this, "点击了取消", Toast.LENGTH_SHORT).show();
})
.setPositiveButton("好的", (dialog, which) -> {
Toast.makeText(MainActivity.this, "点击了确定", Toast.LENGTH_SHORT).show();
})
.show();
// Button被点击后,不调用dialog.dismiss(),因为AlertDialog会自动调用。
}
/**
* 特殊用法被点击。
*/
private void onSpecialClick() {
AlertDialog alertDialog = AlertDialog.build(this)
.setTitle("标题")
.setMessage("提示信息")
// Listener 写null,Button被点击时,Alertdialog就不会自动dismiss了。
.setNeutralButton("忽略", null)
.setNegativeButton("取消", null)
.setPositiveButton("好的", null)
.show(); // 这里是直接show(),不是create(),否则不能getButton()。
// 获取中性按钮。
Button btnNeutral = alertDialog.getButton(DialogInterface.BUTTON_NEUTRAL);
btnNeutral.setOnClickListener(v -> {
Toast.makeText(MainActivity.this, "我们拦截了忽略点击关闭dialog操作",
Toast.LENGTH_SHORT).show();
});
// 获取取消按钮。
Button btnNegative = alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE);
btnNegative.setOnClickListener(v -> {
alertDialog.dismiss(); // 拦截了btn的默认操作,需要调用dialog.dismiss()。
Toast.makeText(MainActivity.this, "点击了取消",
Toast.LENGTH_SHORT).show();
});
// 获取确定按钮。
Button btnPositive = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
btnPositive.setOnClickListener(v -> {
alertDialog.dismiss(); // 拦截了btn的默认操作,需要调用dialog.dismiss()。
Toast.makeText(MainActivity.this, "点击了确定",
Toast.LENGTH_SHORT).show();
});
}
/**
* Show dialog btn click.
*/
private View.OnClickListener mOnClickListener = v -> {
int id = v.getId();
switch (id) {
case R.id.btn_show_common: {
onCommonClick();
break;
}
case R.id.btn_show_special: {
onSpecialClick();
break;
}
}
};
}
| 34.414634 | 90 | 0.609261 |
729e94cb9f01868bd0e58850d6f4308ae78bc840 | 2,353 | package com.ubergeek42.WeechatAndroid.utils;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import androidx.viewpager.widget.ViewPager;
// this code by Nikhil Kumar has been found here:
// https://medium.com/winkl-insights/how-to-have-a-height-wrapping-viewpager-when-images-have-variable-heights-on-android-60b18e55e72e
// see also https://stackoverflow.com/a/48029387/1449683
// this code has been modified to exclude extra padding (parentWithWithoutPadding) and also
// to not grow beyond allotted height
public class HeightWrappingViewPager extends ViewPager {
public HeightWrappingViewPager(Context context) {
super(context);
}
public HeightWrappingViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int mode = MeasureSpec.getMode(heightMeasureSpec);
// Unspecified means that the ViewPager is in a ScrollView WRAP_CONTENT.
// At Most means that the ViewPager is not in a ScrollView WRAP_CONTENT.
if (mode == MeasureSpec.UNSPECIFIED || mode == MeasureSpec.AT_MOST) {
// super has to be called in the beginning so the child views can be initialized.
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int parentWithWithoutPadding = getMeasuredWidth() - getPaddingLeft() - getPaddingRight();
int height = 0;
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
child.measure(MeasureSpec.makeMeasureSpec(parentWithWithoutPadding, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int h = child.getMeasuredHeight();
if (h > height) height = h;
}
// make sure we don't “shrink” ourselves beyond the allotted space
int allottedHeight = getMeasuredHeight();
if (allottedHeight < height) height = allottedHeight;
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
}
// super has to be called again so the new specs are treated as exact measurements
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
} | 47.06 | 134 | 0.688483 |
223554b32249f0405b7692906c35737c592a085a | 2,260 | package org.inaetics.pubsub.examples.pubsub.common;
import java.io.Serializable;
public class Location implements Serializable {
public static final String MSG_POI_NAME = "poi1"; //Has to match the message name in the msg descriptor in the C bundle!
public static final double MIN_LAT = -90.0F;
public static final double MAX_LAT = 90.0F;
public static final double MIN_LON = -180.0F;
public static final double MAX_LON = 180.0F;
private String name;
private String description;
private String extra;
private String data;
private Poi position;
public Location() {
this.name = "";
this.description = "";
this.extra = "";
this.data = "";
this.position = new Poi();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getExtra() {
return extra;
}
public void setExtra(String extra) {
this.extra = extra;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public void setPositionLat(double lat){
this.position.setLat(lat);
}
public void setPositionLong(double lon){
this.position.setLong(lon);
}
public Poi getPosition() {
return this.position;
}
public class Poi {
double lat;
double lon;
public double getLat() {
return lat;
}
public void setLat(double lat) {
this.lat = lat;
}
public double getLong() {
return lon;
}
public void setLong(double lon) {
this.lon = lon;
}
}
@Override
public String toString() {
return String.format("[%f, %f] (%s, %s) data len = %d",
this.getPosition().getLat(),
this.getPosition().getLong(),
this.getName(),
this.getDescription(),
this.getData().length());
}
}
| 21.730769 | 124 | 0.565929 |
8dc265abfd56fa8e2efa6bf3cf84f124068ef46d | 344 | //,temp,sample_3875.java,2,9,temp,sample_3873.java,2,9
//,2
public class xxx {
public boolean removeAllLoadBalanacersForIp(long ipId, Account caller, long callerUserId) {
List<FirewallRuleVO> rules = _firewallDao.listByIpAndPurposeAndNotRevoked(ipId, Purpose.LoadBalancing);
if (rules != null) {
log.info("found lb rules to cleanup");
}
}
}; | 26.461538 | 103 | 0.767442 |
aacad11d60de242e912f05ef69faa64a481b9fb8 | 1,725 | /*
* Copyright 2021 DataCanvas
*
* 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.dingodb.expr.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.SOURCE)
public @interface Evaluators {
/**
* Specify the EvaluatorKey class.
*
* @return the EvaluatorKey class
*/
Class<?> evaluatorKey();
/**
* Specify the base class/interface of the generated Evaluators.
*
* @return the base class/interface
*/
Class<?> evaluatorBase();
/**
* Specify the base class of the generated EvaluatorFactory.
*
* @return the EvaluatorFactory base class
*/
Class<?> evaluatorFactory();
/**
* Specify the class of universal evaluator.
*
* @return the class of universal evaluator
*/
Class<?> universalEvaluator();
/**
* Specify the sequence of the type when inducing evaluators by type.
*
* @return an array of class
*/
Class<?>[] induceSequence();
@interface Base {
Class<?> value();
}
}
| 26.136364 | 75 | 0.674203 |
f0b7f1d8d2a39d7a346c724a26e972caa62ea549 | 564 | package site.zido.coffee.extra.limiter;
import org.springframework.context.annotation.AdviceMode;
import org.springframework.context.annotation.AdviceModeImportSelector;
import org.springframework.context.annotation.AutoProxyRegistrar;
public class LimiterConfigurationSelector extends AdviceModeImportSelector<EnableLimiter> {
@Override
protected String[] selectImports(AdviceMode adviceMode) {
return new String[]{
AutoProxyRegistrar.class.getName(),
ProxyLimiterConfiguration.class.getName()
};
}
}
| 35.25 | 91 | 0.760638 |
705bf7821203d7e44442853a92ca151e7855aafc | 1,366 | package uk.co.idv.method.adapter.json.otp.policy.delivery;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.Module;
import com.fasterxml.jackson.databind.module.SimpleModule;
import uk.co.idv.method.adapter.json.otp.policy.delivery.email.EmailDeliveryMethodConfigModule;
import uk.co.idv.method.adapter.json.otp.policy.delivery.phone.PhoneDeliveryMethodConfigModule;
import uk.co.idv.method.entities.otp.policy.delivery.DeliveryMethodConfig;
import uk.co.idv.method.entities.otp.policy.delivery.DeliveryMethodConfigs;
import java.util.Arrays;
public class DeliveryMethodConfigModule extends SimpleModule {
public DeliveryMethodConfigModule() {
super("delivery-method-config-module", Version.unknownVersion());
setMixInAnnotation(DeliveryMethodConfig.class, DeliveryMethodConfigMixin.class);
setMixInAnnotation(DeliveryMethodConfigs.class, DeliveryMethodConfigsMixin.class);
addDeserializer(DeliveryMethodConfig.class, new DeliveryMethodConfigDeserializer());
addDeserializer(DeliveryMethodConfigs.class, new DeliveryMethodConfigsDeserializer());
}
@Override
public Iterable<? extends Module> getDependencies() {
return Arrays.asList(
new EmailDeliveryMethodConfigModule(),
new PhoneDeliveryMethodConfigModule()
);
}
}
| 40.176471 | 95 | 0.779649 |
263d3a795c68cfeeb2633532c9e8ba5416c528f1 | 2,738 | package io.github.armani.server.handler;
import io.github.armani.common.protocol.packet.request.LoginRequestPacket;
import io.github.armani.common.protocol.packet.response.LoginResponsePacket;
import io.github.armani.common.utils.AttributeKeyConst;
import io.github.armani.common.utils.SessionMember;
import io.github.armani.common.utils.SessionUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.atomic.AtomicLong;
/**
* SimpleChannelInboundHandler 不用再去各种if(是不是本次要处理的包) else(传递给下一个处理器)判断。<br>
* 并且会自动传递给下一个对应的处理器以及自动释放内存
*/
@ChannelHandler.Sharable
public class LoginRequestHandler extends SimpleChannelInboundHandler<LoginRequestPacket> {
private static final Logger LOGGER = LoggerFactory.getLogger(LoginRequestHandler.class);
public static final LoginRequestHandler INSTANCE = new LoginRequestHandler();
private AtomicLong online = new AtomicLong();
@Override
protected void channelRead0(ChannelHandlerContext ctx, LoginRequestPacket login) throws Exception {
LOGGER.info("处理登录请求。入参:{}", login.toJSON());
final Channel channel = ctx.channel();
LoginResponsePacket loginResponsePacket = new LoginResponsePacket();
String userId = login.getUserId();
String username = login.getUsername();
if (SessionUtil.isLogin(userId)) {
String reason = userId + "已经登录过了,请勿重复登录!";
LOGGER.info("登录失败,原因:{}", reason);
loginResponsePacket.setSuccess(false);
loginResponsePacket.setReason(reason);
ctx.writeAndFlush(loginResponsePacket);
return;
}
LOGGER.info("[{}]登录验证通过,当前登录用户数:{}", username, online.incrementAndGet());
SessionMember member = SessionMember.builder().userId(userId).username(username).build();
channel.attr(AttributeKeyConst.SESSION_MEMBER).set(member);
SessionUtil.bindSessionMember(member, channel);
loginResponsePacket.setReason("登录成功,欢迎帅气的[" + userId + "]");
loginResponsePacket.setSuccess(true);
ctx.writeAndFlush(loginResponsePacket);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
SessionMember member = ctx.channel().attr(AttributeKeyConst.SESSION_MEMBER).get();
if (member.isNotNull()) {
SessionUtil.unbindSessionMember(member, ctx.channel());
LOGGER.info("[{}]下线了,当前登录用户数:{}", member.getUsername(), online.decrementAndGet());
} else {
LOGGER.info("未登陆用户连接断开");
}
}
}
| 37 | 103 | 0.719869 |
a9d81550e5fc90e095132ef5d2a2e7f92b14d715 | 1,432 | package jp.gr.java_conf.ya.yumura.Network; // Copyright (c) 2013-2017 YA <ya.androidapp@gmail.com> All rights reserved. --><!-- This software includes the work that is distributed in the Apache License 2.0
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class ConnectionReceiver extends BroadcastReceiver {
private Observer mObserver;
public ConnectionReceiver(Observer observer) {
mObserver = observer;
}
@Override
public void onReceive(final Context context, final Intent intent) {
final ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo activeNetwork = manager.getActiveNetworkInfo();
if (activeNetwork != null) {
if ((activeNetwork.isConnectedOrConnecting()) || (activeNetwork.isConnected())) {
try {
if (mObserver != null)
mObserver.onConnect();
} catch (Exception e) {
}
return;
}
}
try {
if (mObserver != null)
mObserver.onDisconnect();
} catch (Exception e) {
}
}
public interface Observer {
void onConnect();
void onDisconnect();
}
} | 34.095238 | 205 | 0.631983 |
2843bcc2320780e673a82f0f3a3447758ccb3985 | 428 | package com.emajliramokade.api.model.Sigurnost.repositories;
import com.dslplatform.patterns.*;
import com.dslplatform.client.*;
public class KorisnikRepository
extends
ClientPersistableRepository<com.emajliramokade.api.model.Sigurnost.Korisnik> {
public KorisnikRepository(
final ServiceLocator locator) {
super(com.emajliramokade.api.model.Sigurnost.Korisnik.class, locator);
}
}
| 30.571429 | 86 | 0.75 |
75ff1cf8bcb1c0c733b57c62aedf5c22b1dd5ed6 | 327 | public class ParameterScopeExercise4 {
// what does the following program print out?
public static void main(String[] args) {
int x = 7;
int y = 10;
myMethod(x, y);
x -= 2;
y -= 3;
myMethod(x, y);
}
public static void myMethod(int x, int y) {
for (int i = x; i <= y; i++) {
System.out.println(i);
}
}
} | 19.235294 | 46 | 0.593272 |
8c9ec37e7c9cc2183aa3c55bd69592ee2c25fe95 | 1,357 | import java.util.Scanner;
import java.util.stream.IntStream;
public class EnterNumbers {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(true) {
try {
printNumbers(sc);
break;
} catch (NumberFormatException e) {
System.out.println(e.getMessage());
}
}
}
private static void printNumbers(Scanner sc) {
String str1 = sc.nextLine();
String str2 = sc.nextLine();
if (isInvalid(str1, str2)) {
throw new NumberFormatException("Invalid numbers! Try again");
}
int start = Integer.parseInt(str1);
int end = Integer.parseInt(str2);
IntStream.rangeClosed(start,end).forEach(System.out::println);
}
private static boolean isInvalid(String str1, String str2) {
if (checkInput(str1) || checkInput(str2)) {
return true;
}
int start = Integer.parseInt(str1);
int end = Integer.parseInt(str2);
return start <= 1 || end >= 100 || start >= end;
}
private static boolean checkInput(String input) {
for (char symbol : input.toCharArray()) {
if (!Character.isDigit(symbol)) {
return true;
}
}
return false;
}
}
| 27.693878 | 74 | 0.551216 |
aad25fba235e62cec77f7d6796da62b62d76b701 | 5,259 | package com.example.medical.fragment;
import android.content.Intent;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.medical.MainActivity44;
import com.example.medical.MainActivity45;
import com.example.medical.MainActivity46;
import com.example.medical.MainActivity47;
import com.example.medical.MainActivity48;
import com.example.medical.MainActivity49;
import com.example.medical.MainActivity50;
import com.example.medical.MainActivity51;
import com.example.medical.MainActivity52;
import com.example.medical.MainActivity53;
import com.example.medical.R;
import com.example.medical.adapter.ayadapter;
import com.example.medical.classes.recycler;
import com.example.medical.model.ay;
import com.example.medical.model.person;
import java.util.ArrayList;
public class ayfragment extends Fragment {
RecyclerView rec;
ArrayList <ay> aer;
public ayfragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate ( savedInstanceState );
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate ( R.layout.fragment_ayfragment, container, false );
rec=view.findViewById ( R.id.rec);
aer=new ArrayList <> ( );
aer.add ( new ay ( R.drawable.raf,"Smw'S Iron Tonic Heamzo Fill Natural Multi Vitamins MRP 165" ) );
aer.add ( new ay ( R.drawable.as,"Calcimax Forte Plus Strip of 30 Tablets MRP 208" ) );
aer.add ( new ay ( R.drawable.at,"Himalya Sepilin Tablets -60's MRP 123" ) );
aer.add ( new ay ( R.drawable.afo,"Himalya Liv.52Ds Tablets MRP 119" ) );
aer.add ( new ay ( R.drawable.afi,"Himalya Liv.52 Tablets=100's MRP 95" ) );
aer.add ( new ay ( R.drawable.asi,"Himalya Gasx Tablets-100's MRP 105" ) );
aer.add ( new ay ( R.drawable.rase," Everhub Karela Jamun Juice MRP 195" ) );
aer.add ( new ay ( R.drawable.ae,"Volin Pain Relif Spray Bottle MRP 55" ) );
aer.add ( new ay ( R.drawable.an,"Himalya Septlin Syrup -200ml MRP 100" ) );
aer.add ( new ay ( R.drawable.ate,"Volin Pain Rlif Gel-30gm MRP 90" ) );
ayadapter ayadapter=new ayadapter ( aer,getContext () );
LinearLayoutManager layoutManager=new LinearLayoutManager ( getContext (),LinearLayoutManager.VERTICAL,false );
rec.setLayoutManager ( layoutManager );
rec.setNestedScrollingEnabled ( false );
rec.setAdapter ( ayadapter );
rec.addOnItemTouchListener ( new recycler ( getContext ( ), rec, new recycler.OnItemClickListener ( ) {
@Override
public void onItemClick(View view, int position) {
switch (position){
case 0:
Intent intent=new Intent ( getActivity (), MainActivity44.class );
startActivity ( intent );
break;
case 1:
Intent intent1=new Intent ( getActivity (), MainActivity45.class );
startActivity ( intent1 );
break;
case 2:
Intent intent2=new Intent ( getActivity (), MainActivity46.class );
startActivity ( intent2 );
break;
case 3:
Intent intent3=new Intent ( getActivity (), MainActivity47.class );
startActivity ( intent3 );
break;
case 4:
Intent intent4=new Intent ( getActivity (), MainActivity48.class );
startActivity ( intent4 );
break;
case 5:
Intent intent5=new Intent ( getActivity (), MainActivity49.class );
startActivity ( intent5 );
break;
case 6:
Intent intent6=new Intent ( getActivity (), MainActivity50.class );
startActivity ( intent6 );
break;
case 7:
Intent intent7=new Intent ( getActivity (), MainActivity51.class );
startActivity ( intent7);
break;
case 8:
Intent intent8=new Intent ( getActivity (), MainActivity52.class );
startActivity ( intent8 );
break;
case 9:
Intent intent9=new Intent ( getActivity (), MainActivity53.class );
startActivity ( intent9 );
break;
}
}
@Override
public void onItemLongClick(View view, int position) {
}
} ) );
return view;
}
} | 38.669118 | 119 | 0.574634 |
f906990859dfb2df97cf7f0909023962248ed1a4 | 2,571 | /*
* The MIT License
*
* Copyright (c) 2009 The Broad Institute
*
* 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 picard.cmdline;
/**
* A set of String constants in which the name of the constant (minus the _SHORT_NAME suffix)
* is the standard long Option name, and the value of the constant is the standard shortName.
*/
public class StandardOptionDefinitions {
public static final String INPUT_SHORT_NAME = "I";
public static final String OUTPUT_SHORT_NAME = "O";
public static final String REFERENCE_SHORT_NAME = "R";
public static final String SAMPLE_ALIAS_SHORT_NAME = "ALIAS";
public static final String LIBRARY_NAME_SHORT_NAME = "LIB";
public static final String EXPECTED_INSERT_SIZE_SHORT_NAME = "INSERT";
public static final String LANE_SHORT_NAME = "L";
public static final String SEQUENCE_DICTIONARY_SHORT_NAME = "SD";
public static final String METRICS_FILE_SHORT_NAME = "M";
public static final String ASSUME_SORTED_SHORT_NAME = "AS";
public static final String ASSUME_SORT_ORDER_SHORT_NAME = "ASO";
public static final String PF_READS_ONLY_SHORT_NAME = "PF";
public static final String MINIMUM_MAPPING_QUALITY_SHORT_NAME = "MQ";
public static final String READ_GROUP_ID_SHORT_NAME = "RG";
public static final String PROGRAM_RECORD_ID_SHORT_NAME = "PG";
public static final String MINIMUM_LOD_SHORT_NAME = "LOD";
public static final String SORT_ORDER_SHORT_NAME = "SO";
public static final String USE_ORIGINAL_QUALITIES_SHORT_NAME = "OQ";
}
| 51.42 | 93 | 0.763516 |
dee1ad6cc5aac245f175fdd336eac3eeab23380a | 6,702 | package com.xialan.beautymall.utils;
/**
* Created by liunian on 2017/12/13.
*/
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.DrawableRes;
import android.support.annotation.Nullable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.support.v7.widget.AppCompatImageView;
import android.util.AttributeSet;
import android.view.View;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.DrawableRes;
import android.support.annotation.Nullable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.support.v7.widget.AppCompatImageView;
import android.util.AttributeSet;
import android.view.View;
import com.xialan.beautymall.R;
public class BGAImageView extends AppCompatImageView {
private int mDefaultImageId;
private int mCornerRadius = 0;
private boolean mIsCircle = false;
private boolean mIsSquare = false;
private int mBorderWidth = 0;
private int mBorderColor = Color.WHITE;
private Paint mBorderPaint;
private Delegate mDelegate;
public BGAImageView(Context context) {
this(context, null);
}
public BGAImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public BGAImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initCustomAttrs(context, attrs);
initBorderPaint();
setDefaultImage();
}
private void initBorderPaint() {
mBorderPaint = new Paint();
mBorderPaint.setAntiAlias(true);
mBorderPaint.setStyle(Paint.Style.STROKE);
mBorderPaint.setColor(mBorderColor);
mBorderPaint.setStrokeWidth(mBorderWidth);
}
private void initCustomAttrs(Context context, AttributeSet attrs) {
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.BGAImageView);
final int N = typedArray.getIndexCount();
for (int i = 0; i < N; i++) {
initCustomAttr(typedArray.getIndex(i), typedArray);
}
typedArray.recycle();
}
private void initCustomAttr(int attr, TypedArray typedArray) {
if (attr == R.styleable.BGAImageView_android_src) {
mDefaultImageId = typedArray.getResourceId(attr, 0);
} else if (attr == R.styleable.BGAImageView_bga_iv_circle) {
mIsCircle = typedArray.getBoolean(attr, mIsCircle);
} else if (attr == R.styleable.BGAImageView_bga_iv_cornerRadius) {
mCornerRadius = typedArray.getDimensionPixelSize(attr, mCornerRadius);
} else if (attr == R.styleable.BGAImageView_bga_iv_square) {
mIsSquare = typedArray.getBoolean(attr, mIsSquare);
} else if (attr == R.styleable.BGAImageView_bga_iv_borderWidth) {
mBorderWidth = typedArray.getDimensionPixelSize(attr, mBorderWidth);
} else if (attr == R.styleable.BGAImageView_bga_iv_borderColor) {
mBorderColor = typedArray.getColor(attr, mBorderColor);
}
}
private void setDefaultImage() {
if (mDefaultImageId != 0) {
setImageResource(mDefaultImageId);
}
}
@Override
public void setImageResource(@DrawableRes int resId) {
setImageDrawable(getResources().getDrawable(resId));
}
@Override
public void setImageDrawable(@Nullable Drawable drawable) {
if (drawable instanceof BitmapDrawable && mCornerRadius > 0) {
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
if (bitmap != null) {
super.setImageDrawable(getRoundedDrawable(getContext(), bitmap, mCornerRadius));
} else {
super.setImageDrawable(drawable);
}
} else if (drawable instanceof BitmapDrawable && mIsCircle) {
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
if (bitmap != null) {
super.setImageDrawable(getCircleDrawable(getContext(), bitmap));
} else {
super.setImageDrawable(drawable);
}
} else {
super.setImageDrawable(drawable);
}
notifyDrawableChanged(drawable);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (mIsCircle || mIsSquare) {
setMeasuredDimension(getDefaultSize(0, widthMeasureSpec), getDefaultSize(0, heightMeasureSpec));
int childWidthSize = getMeasuredWidth();
heightMeasureSpec = widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(childWidthSize, View.MeasureSpec.EXACTLY);
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mIsCircle && mBorderWidth > 0) {
canvas.drawCircle(getWidth() / 2, getHeight() / 2, getWidth() / 2 - 1.0f * mBorderWidth / 2, mBorderPaint);
}
}
private void notifyDrawableChanged(Drawable drawable) {
if (mDelegate != null) {
mDelegate.onDrawableChanged(drawable);
}
}
public void setDelegate(Delegate delegate) {
mDelegate = delegate;
}
public interface Delegate {
void onDrawableChanged(Drawable drawable);
}
public static RoundedBitmapDrawable getCircleDrawable(Context context, Bitmap bitmap) {
RoundedBitmapDrawable circleDrawable = RoundedBitmapDrawableFactory.create(context.getResources(), bitmap);
circleDrawable.setAntiAlias(true);
circleDrawable.setCircular(true);
return circleDrawable;
}
public static RoundedBitmapDrawable getRoundedDrawable(Context context, Bitmap bitmap, float cornerRadius) {
RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(context.getResources(), bitmap);
roundedBitmapDrawable.setAntiAlias(true);
roundedBitmapDrawable.setCornerRadius(cornerRadius);
return roundedBitmapDrawable;
}
}
| 36.622951 | 126 | 0.699493 |
4bf2e573a6e65dc104eab2b1eea1d1163c05f21a | 4,554 | package parser.json;
import java.time.LocalDate;
import java.time.YearMonth;
import java.util.List;
import java.util.stream.Collectors;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;
import data.Entry;
import data.TimeSpan;
import parser.IMonthParser;
import parser.ParseException;
/**
* A JsonMonthParser provides the functionality to parse the
* elements specified by {@link IMonthParser} from a json string.
*/
public class JsonMonthParser implements IMonthParser {
private final String json;
private MonthJson monthJson; // caching
/**
* Constructs a new {@link JsonMonthParser} instance.
* @param json - to parse the data from.
*/
public JsonMonthParser(String json) {
this.json = json;
}
private MonthJson parse() throws JsonProcessingException {
if (monthJson == null) {
ObjectMapper mapper = JsonMapper.builder()
.addModule(new ParameterNamesModule())
.addModule(new Jdk8Module())
.addModule(new JavaTimeModule())
.build();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
monthJson = mapper.readValue(json, MonthJson.class);
}
return monthJson;
}
@Override
public YearMonth getYearMonth() throws ParseException {
try {
return parse().getYearMonth();
} catch (JsonProcessingException e) {
throw new ParseException(e.getMessage());
}
}
@Override
public Entry[] getEntries() throws ParseException {
List<Entry> entries;
try {
MonthJson month = parse();
// catching the ParseException is necessary, because Java complains about a unhandled exception otherwise
// declaring the exception is not possible in a lambda function
// a workaround is to encapsulate the exception in a RuntimeException, which doesn't have to be declared
// since we expect the RuntimeException caught outside the lambda function to include the actual exception as the cause,
// we need to encapsulate RuntimeExceptions thrown in parseEntry(..) as well
// (note that IllegalArgumentException is a RuntimeException as well)
entries = month.getEntries().stream().map(entry -> {
try {
return parseEntry(entry);
} catch (ParseException | RuntimeException e) {
throw new RuntimeException(e);
}
}).collect(Collectors.toList());
} catch(RuntimeException e) {
throw new ParseException(e.getCause().getMessage());
} catch (JsonProcessingException e) {
throw new ParseException(e.getMessage());
}
return entries.toArray(new Entry[entries.size()]);
}
@Override
public TimeSpan getSuccTransfer() throws ParseException {
try {
return parse().getSuccTransfer();
} catch (JsonProcessingException e) {
throw new ParseException(e.getMessage());
}
}
@Override
public TimeSpan getPredTransfer() throws ParseException {
try {
return parse().getPredTransfer();
} catch (JsonProcessingException e) {
throw new ParseException(e.getMessage());
}
}
/**
* Parses an {@link Entry} from an {@link MonthEntryJson}.
* @param json - to parse {@link Entry} from
* @return The entry parsed from the {@link MonthEntryJson}.
* @throws ParseException if an error occurs while fetching the {@link YearMonth}.
*/
private Entry parseEntry(MonthEntryJson entry) throws ParseException {
// LocalDate construction
YearMonth yearMonth = getYearMonth();
LocalDate date = LocalDate.of(yearMonth.getYear(), yearMonth.getMonth(), entry.getDay());
return new Entry(
entry.getAction(),
date,
entry.getStart(),
entry.getEnd(),
entry.getPause(),
entry.getVacation()
);
}
}
| 35.030769 | 132 | 0.635485 |
6aeca4c64292c9e4ad95b65e10ce3f5b60011cf6 | 3,404 | /*
* Copyright 2019 Grabtaxi Holdings PTE LTE (GRAB), All rights reserved.
*
* Use of this source code is governed by an MIT-style license that can be found in the LICENSE file.
*
*/
package org.openstreetmap.josm.plugins.improveosm.gui.details;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import org.openstreetmap.josm.data.coor.EastNorth;
import org.openstreetmap.josm.data.coor.LatLon;
import org.openstreetmap.josm.gui.MainApplication;
import org.openstreetmap.josm.gui.widgets.DisableShortcutsOnFocusGainedTextField;
import org.openstreetmap.josm.plugins.improveosm.util.cnf.GuiConfig;
/**
* Builds a text field for searching a location.
*
* @author nicoletav
*/
class SearchBox extends DisableShortcutsOnFocusGainedTextField implements ActionListener {
private static final long serialVersionUID = 1L;
private static final int ELEMENTS_NR = 2;
private static final int LAT_INDEX = 0;
private static final int LON_INDEX = 1;
private static final double MAX_LAT_VALUE = 85.05;
private static final double MIN_LAT_VALUE = -85.05;
SearchBox() {
super(GuiConfig.getInstance().getInitialTxt());
this.addActionListener(this);
}
@Override
public void actionPerformed(final ActionEvent e) {
final String latLonValue = this.getText();
if (latLonValue.split(",").length == ELEMENTS_NR) {
try {
final double lat = Double.parseDouble(latLonValue.split(",")[LAT_INDEX]);
final double lon = Double.parseDouble(latLonValue.split(",")[LON_INDEX]);
LatLon searchedLocation = new LatLon(lat, lon);
if (searchedLocation.isValid()) {
if (!isLocationSearchable(searchedLocation.getY())) {
searchedLocation = getExtremityPoint(searchedLocation);
}
final EastNorth demoZoomLocation =
searchedLocation.getEastNorth(MainApplication.getMap().mapView.getProjection());
MainApplication.getMap().mapView.zoomTo(demoZoomLocation, 1);
} else {
this.setText(GuiConfig.getInstance().getIncorrectValuesTxt());
}
} catch (final NumberFormatException e1) {
this.setText(GuiConfig.getInstance().getIncorrectFormatTxt());
}
} else {
this.setText(GuiConfig.getInstance().getIncorrectElementsNr());
}
MainApplication.getMap().mapView.requestFocus();
}
/*
Checks if the latitude value can be displayed.
Display of the geographical point is possible for a latitude value within [-85.05, 85,05] due to the map space.
*/
private boolean isLocationSearchable(final double latitude) {
boolean isSearchable = false;
if (MIN_LAT_VALUE <= latitude && latitude <= MAX_LAT_VALUE) {
isSearchable = true;
}
return isSearchable;
}
private LatLon getExtremityPoint(final LatLon point) {
LatLon extremityPoint = null;
if (point.getY() > MAX_LAT_VALUE) {
extremityPoint = new LatLon(MAX_LAT_VALUE, point.getX());
}
if (point.getY() < MIN_LAT_VALUE) {
extremityPoint = new LatLon(MIN_LAT_VALUE, point.getX());
}
return extremityPoint;
}
} | 37.822222 | 119 | 0.650411 |
a89bb3d957260efc542d8933c55d63620a1cbe78 | 2,288 | /**
* Leetcode - remove_max_number_of_edges_to_keep_graph_fully_traversable
*/
package com.leetcode.remove_max_number_of_edges_to_keep_graph_fully_traversable;
import java.util.*;
import com.ciaoshen.leetcode.util.*;
/**
* log instance is defined in Solution interface
* this is how slf4j will work in this class:
* =============================================
* if (log.isDebugEnabled()) {
* log.debug("a + b = {}", sum);
* }
* =============================================
*/
class Solution1 implements Solution {
int find(int[] f, int i) {
if(f[i] == i) {
return i;
} else {
f[i] = find(f, f[i]);
return f[i];
}
}
public int maxNumEdgesToRemove(int n, int[][] edges) {
int[] f0 = new int[n + 1], f1 = new int[n + 1], f2 = new int[n + 1];
int m = edges.length;
int s = 0, s1 = 0, s2 = 0;
for(int i = 1; i <= n; i++) {
f0[i] = i;
f1[i] = i;
f2[i] = i;
}
for(int i = 0; i < m; i++) {
int c = edges[i][0], a = edges[i][1], b = edges[i][2];
if(c == 3) {
int aa = find(f0, a), bb = find(f0, b);
if(aa != bb) {
f0[aa] = bb;
s++;
aa = find(f1, a);
bb = find(f1, b);
f1[aa] = bb;
s1++;
aa = find(f2, a);
bb = find(f2, b);
f2[aa] = bb;
s2++;
}
}
}
for(int i = 0; i < m; i++) {
int c = edges[i][0], a = edges[i][1], b = edges[i][2];
if(c == 1) {
int aa = find(f1, a), bb = find(f1, b);
if(aa != bb) {
f1[aa] = bb;
s++;
s1++;
}
} else if(c == 2) {
int aa = find(f2, a), bb = find(f2, b);
if(aa != bb) {
f2[aa] = bb;
s++;
s2++;
}
}
}
if(s1 != n - 1 || s2 != n - 1) {
return -1;
}
return m - s;
}
}
| 28.6 | 80 | 0.33479 |
2f28780e977148b911ce38671bc8df6eb6b26014 | 1,945 | package org.meridor.perspective.rest.data.listeners;
import org.meridor.perspective.beans.Project;
import org.meridor.perspective.backend.storage.ProjectsAware;
import org.meridor.perspective.backend.storage.StorageEvent;
import org.meridor.perspective.rest.data.converters.ProjectConverters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import static org.meridor.perspective.rest.data.TableName.*;
@Component
public class ProjectsListener extends BaseEntityListener<Project> {
@Autowired
private ProjectsAware projectsAware;
@PostConstruct
public void init() {
projectsAware.addProjectListener(this);
}
@Override
public void onEvent(Project project, Project oldProject, StorageEvent event) {
updateEntity(event, PROJECTS.getTableName(), project, oldProject);
updateDerivedEntities(event, PROJECT_METADATA.getTableName(), project, oldProject, ProjectConverters::projectToMetadata);
updateDerivedEntities(event, PROJECT_QUOTA.getTableName(), project, oldProject, ProjectConverters::projectToQuota);
updateDerivedEntities(event, AVAILABILITY_ZONES.getTableName(), project, oldProject, ProjectConverters::projectToAvailabilityZones);
updateDerivedEntities(event, CLOUDS.getTableName(), project, oldProject, ProjectConverters::projectToCloud);
updateDerivedEntities(event, FLAVORS.getTableName(), project, oldProject, ProjectConverters::projectToFlavors);
updateDerivedEntities(event, KEYPAIRS.getTableName(), project, oldProject, ProjectConverters::projectToKeypairs);
updateDerivedEntities(event, NETWORKS.getTableName(), project, oldProject, ProjectConverters::projectToNetworks);
updateDerivedEntities(event, NETWORK_SUBNETS.getTableName(), project, oldProject, ProjectConverters::projectToNetworkSubnets);
}
}
| 49.871795 | 140 | 0.794344 |
76b3b6c0d0d4270aa23acb2a9dd878bcbb748e1d | 14,152 | package com.lilithsthrone.game.sex.sexActions.baseActionsSelfPartner;
import com.lilithsthrone.game.character.attributes.CorruptionLevel;
import com.lilithsthrone.game.dialogue.utils.UtilText;
import com.lilithsthrone.game.sex.ArousalIncrease;
import com.lilithsthrone.game.sex.Sex;
import com.lilithsthrone.game.sex.SexAreaOrifice;
import com.lilithsthrone.game.sex.SexAreaPenetration;
import com.lilithsthrone.game.sex.SexPace;
import com.lilithsthrone.game.sex.SexParticipantType;
import com.lilithsthrone.game.sex.positions.SexPositionBipeds;
import com.lilithsthrone.game.sex.positions.SexSlotBipeds;
import com.lilithsthrone.game.sex.sexActions.SexAction;
import com.lilithsthrone.game.sex.sexActions.SexActionLimitation;
import com.lilithsthrone.game.sex.sexActions.SexActionType;
import com.lilithsthrone.utils.Util;
import com.lilithsthrone.utils.Util.Value;
/**
* @since 0.1.79
* @version 0.1.97
* @author Innoxia
*/
public class PartnerSelfFingerAnus {
public static final SexAction PARTNER_SELF_FINGER_ANUS_SPREAD_ASS = new SexAction(
SexActionType.REQUIRES_NO_PENETRATION_AND_EXPOSED,
ArousalIncrease.TWO_LOW,
ArousalIncrease.TWO_LOW,
CorruptionLevel.ONE_VANILLA,
Util.newHashMapOfValues(new Value<>(SexAreaPenetration.FINGER, SexAreaOrifice.ANUS)),
SexParticipantType.SELF) {
@Override
public SexActionLimitation getLimitation() {
return SexActionLimitation.NPC_ONLY;
}
@Override
public boolean isBaseRequirementsMet() {
return Sex.getSexPace(Sex.getCharacterPerformingAction())!=SexPace.SUB_RESISTING;
}
@Override
public String getActionTitle() {
return "Spread ass";
}
@Override
public String getActionDescription() {
return "Use your [npc.hands] to spread your ass.";
}
@Override
public String getDescription() {
if(Sex.getPosition()==SexPositionBipeds.DOGGY_STYLE && Sex.getSexPositionSlot(Sex.getCharacterPerformingAction())==SexSlotBipeds.DOGGY_ON_ALL_FOURS) {
return (UtilText.returnStringAtRandom(
"Reaching back with one [npc.hand], [npc.name] grabs [npc.her] [npc.ass+] and pulls to one side, letting out [npc.a_moan+] as [npc.she] presents [npc.her] [npc.asshole+] to you.",
"[npc.Name] reaches back with one [npc.hand], moaning softly as [npc.she] grabs hold of [npc.her] [npc.ass+], before invitingly pulling to one side and presenting [npc.her] [npc.asshole+] to you.",
"Sliding [npc.her] fingertips over [npc.her] [npc.asshole+],"
+ " [npc.name] lets out [npc.a_moan+] as [npc.she] grabs one of [npc.her] [npc.assSize] ass cheeks and pulls to one one side in order to present [npc.her] [npc.asshole+] to you.",
"[npc.Name] eagerly slides [npc.her] [npc.fingers] over [npc.her] needy [npc.asshole],"
+ " [npc.moaning+] as [npc.she] uses [npc.her] [npc.hand] to pull [npc.her] ass cheek to one side and present [npc.herself] for anal penetration."));
} else {
return (UtilText.returnStringAtRandom(
"Reaching back with both [npc.hands], [npc.name] grabs [npc.her] [npc.assSize] ass cheeks and pulls them apart, letting out [npc.a_moan+] as [npc.she] presents [npc.her] [npc.asshole+] to you.",
"[npc.Name] reaches back with both [npc.hands], moaning softly as [npc.she] invitingly pulls [npc.her] [npc.assSize] ass cheeks apart and presents [npc.her] [npc.asshole+] to you.",
"Sliding [npc.her] fingertips over [npc.her] [npc.asshole+],"
+ " [npc.name] lets out [npc.a_moan+] as [npc.she] grabs [npc.her] [npc.assSize] ass cheeks and pulls them apart in order to present [npc.her] [npc.asshole+] to you.",
"[npc.Name] eagerly slides [npc.her] [npc.fingers] over [npc.her] needy [npc.asshole], [npc.moaning+] as [npc.she] uses [npc.her] [npc.hands] to pull [npc.her] ass cheeks aside and present [npc.herself] for anal penetration."));
}
}
};
public static final SexAction PARTNER_SELF_FINGER_ANUS_PENETRATION = new SexAction(
SexActionType.START_ONGOING,
ArousalIncrease.THREE_NORMAL,
ArousalIncrease.ONE_MINIMUM,
CorruptionLevel.TWO_HORNY,
Util.newHashMapOfValues(new Value<>(SexAreaPenetration.FINGER, SexAreaOrifice.ANUS)),
SexParticipantType.SELF) {
@Override
public SexActionLimitation getLimitation() {
return SexActionLimitation.NPC_ONLY;
}
@Override
public String getActionTitle() {
return "Anal fingering (self)";
}
@Override
public String getActionDescription() {
return "Start fingering [npc.her] ass.";
}
@Override
public String getDescription() {
return UtilText.returnStringAtRandom(
"Reaching around to [npc.her] [npc.ass], [npc.name] teases [npc.her] fingers over the entrance to [npc.her] [npc.asshole+], before pushing them inside and letting out [npc.a_moan+].",
"[npc.Name] probes [npc.her] fingers down over [npc.her] [npc.ass], [npc.moaning+] as [npc.she] pushes two of [npc.her] digits into [npc.her] inviting [npc.asshole].",
"Sliding [npc.her] fingertips over [npc.her] neglected [npc.asshole], [npc.name] lets out a [npc.groan+] as [npc.she] pushes [npc.her] digits inside.",
"[npc.Name] eagerly pushes [npc.her] fingers into [npc.her] needy [npc.asshole], [npc.moaning+] as [npc.she] starts pumping [npc.her] digits in and out of [npc.her] [npc.ass].");
}
};
public static final SexAction DOM_PARTNER_SELF_FINGER_ANUS_GENTLE = new SexAction(
SexActionType.ONGOING,
ArousalIncrease.THREE_NORMAL,
ArousalIncrease.ONE_MINIMUM,
CorruptionLevel.TWO_HORNY,
Util.newHashMapOfValues(new Value<>(SexAreaPenetration.FINGER, SexAreaOrifice.ANUS)),
SexParticipantType.SELF,
SexPace.DOM_GENTLE) {
@Override
public SexActionLimitation getLimitation() {
return SexActionLimitation.NPC_ONLY;
}
@Override
public String getActionTitle() {
return "Gentle anal fingering (self)";
}
@Override
public String getActionDescription() {
return "Gently finger [npc.her] [npc.asshole].";
}
@Override
public String getDescription() {
return UtilText.returnStringAtRandom(
"[npc.A_moan+] escapes from between [npc.namePos] [npc.lips+] as [npc.she] slowly pushes [npc.her] [npc.fingers] deep inside [npc.her] [npc.asshole+].",
"Gently pumping [npc.her] [npc.fingers] in and out of [npc.her] [npc.asshole+], [npc.name] starts letting out a series of delighted [npc.moans] as [npc.she] rhythmically fingers [npc.her] [npc.ass].",
"Curling [npc.her] [npc.fingers] up inside [npc.her] [npc.asshole], [npc.name] lets out a little whimper as [npc.she] starts "
+(Sex.getCharacterPerformingAction().hasPenis()?"gently stroking [npc.her] prostate.":"gently fingering [npc.her] [npc.ass+]."),
"Focusing on pleasuring [npc.her] [npc.ass+], [npc.name] starts gently pumping [npc.her] [npc.fingers] in and out of [npc.her] [npc.asshole+].");
}
};
public static final SexAction DOM_PARTNER_SELF_FINGER_ANUS_NORMAL = new SexAction(
SexActionType.ONGOING,
ArousalIncrease.THREE_NORMAL,
ArousalIncrease.ONE_MINIMUM,
CorruptionLevel.TWO_HORNY,
Util.newHashMapOfValues(new Value<>(SexAreaPenetration.FINGER, SexAreaOrifice.ANUS)),
SexParticipantType.SELF,
SexPace.DOM_NORMAL) {
@Override
public SexActionLimitation getLimitation() {
return SexActionLimitation.NPC_ONLY;
}
@Override
public String getActionTitle() {
return "Anal fingering (self)";
}
@Override
public String getActionDescription() {
return "Concentrate on fingering [npc.her] [npc.ass].";
}
@Override
public String getDescription() {
return UtilText.returnStringAtRandom(
"[npc.A_moan+] escapes from between [npc.namePos] [npc.lips+] as [npc.she] greedily pushes [npc.her] [npc.fingers] deep inside [npc.her] [npc.asshole+].",
"Pumping [npc.her] [npc.fingers] in and out of [npc.her] [npc.asshole+], [npc.name] starts letting out a series of delighted [npc.moans] as [npc.she] rhythmically fingers [npc.her] [npc.ass].",
"Curling [npc.her] [npc.fingers] up inside [npc.her] [npc.asshole], [npc.name] lets out [npc.a_moan] as [npc.she] starts "
+(Sex.getCharacterPerformingAction().hasPenis()?"stroking [npc.her] prostate.":"fingering [npc.her] [npc.ass+]."),
"Focusing on pleasuring [npc.her] [npc.ass+], [npc.name] starts pumping [npc.her] [npc.fingers] in and out of [npc.her] [npc.asshole+].");
}
};
public static final SexAction DOM_PARTNER_SELF_FINGER_ANUS_ROUGH = new SexAction(
SexActionType.ONGOING,
ArousalIncrease.THREE_NORMAL,
ArousalIncrease.ONE_MINIMUM,
CorruptionLevel.THREE_DIRTY,
Util.newHashMapOfValues(new Value<>(SexAreaPenetration.FINGER, SexAreaOrifice.ANUS)),
SexParticipantType.SELF,
SexPace.DOM_ROUGH) {
@Override
public SexActionLimitation getLimitation() {
return SexActionLimitation.NPC_ONLY;
}
@Override
public String getActionTitle() {
return "Rough anal fingering (self)";
}
@Override
public String getActionDescription() {
return "Roughly finger [npc.her] [npc.ass].";
}
@Override
public String getDescription() {
return UtilText.returnStringAtRandom(
"[npc.A_moan+] escapes from between [npc.namePos] [npc.lips+] as [npc.she] roughly slams [npc.her] [npc.fingers] deep inside [npc.her] [npc.asshole+], before starting to roughly finger [npc.her] [npc.ass].",
"Roughly pumping [npc.her] [npc.fingers] in and out of [npc.her] [npc.asshole+], [npc.name] [npc.verb(start)] letting out a series of delighted [npc.moans] as [npc.she] ruthlessly fingers [npc.her] own [npc.ass].",
"Forcefully curling [npc.her] [npc.fingers] up inside [npc.her] [npc.asshole], [npc.name] lets out [npc.a_moan] as [npc.she] [npc.verb(start)] "
+(Sex.getCharacterPerformingAction().hasPenis()
?"roughly grinding [npc.her] fingertips up against [npc.her] prostate."
:"roughly grinding [npc.her] digits in and out of [npc.her] [npc.ass+]."),
"Focusing on pleasuring [npc.her] [npc.ass+], [npc.name] [npc.verb(start)] roughly slamming [npc.her] [npc.fingers] in and out of [npc.her] [npc.asshole+].");
}
};
public static final SexAction SUB_PARTNER_SELF_FINGER_ANUS_NORMAL = new SexAction(
SexActionType.ONGOING,
ArousalIncrease.THREE_NORMAL,
ArousalIncrease.ONE_MINIMUM,
CorruptionLevel.TWO_HORNY,
Util.newHashMapOfValues(new Value<>(SexAreaPenetration.FINGER, SexAreaOrifice.ANUS)),
SexParticipantType.SELF,
SexPace.SUB_NORMAL) {
@Override
public SexActionLimitation getLimitation() {
return SexActionLimitation.NPC_ONLY;
}
@Override
public String getActionTitle() {
return "Anal fingering (self)";
}
@Override
public String getActionDescription() {
return "Concentrate on fingering [npc.her] [npc.ass].";
}
@Override
public String getDescription() {
return UtilText.returnStringAtRandom(
"[npc.A_moan+] escapes from between [npc.namePos] [npc.lips+] as [npc.she] greedily pushes [npc.her] [npc.fingers] deep inside [npc.her] [npc.asshole+].",
"Pumping [npc.her] [npc.fingers] in and out of [npc.her] [npc.asshole+], [npc.name] starts letting out a series of delighted [npc.moans] as [npc.she] rhythmically fingers [npc.her] [npc.ass].",
"Curling [npc.her] [npc.fingers] up inside [npc.her] [npc.asshole], [npc.name] lets out [npc.a_moan] as [npc.she] starts "
+(Sex.getCharacterPerformingAction().hasPenis()?"stroking [npc.her] prostate.":"fingering [npc.her] [npc.ass+]."),
"Focusing on pleasuring [npc.her] [npc.ass+], [npc.name] starts pumping [npc.her] [npc.fingers] in and out of [npc.her] [npc.asshole+].");
}
};
public static final SexAction SUB_PARTNER_SELF_FINGER_ANUS_EAGER = new SexAction(
SexActionType.ONGOING,
ArousalIncrease.THREE_NORMAL,
ArousalIncrease.ONE_MINIMUM,
CorruptionLevel.THREE_DIRTY,
Util.newHashMapOfValues(new Value<>(SexAreaPenetration.FINGER, SexAreaOrifice.ANUS)),
SexParticipantType.SELF,
SexPace.SUB_EAGER) {
@Override
public SexActionLimitation getLimitation() {
return SexActionLimitation.NPC_ONLY;
}
@Override
public String getActionTitle() {
return "Eager anal fingering (self)";
}
@Override
public String getActionDescription() {
return "Eagerly finger [npc.her] [npc.ass].";
}
@Override
public String getDescription() {
return UtilText.returnStringAtRandom(
"[npc.A_moan+] escapes from between [npc.namePos] [npc.lips+] as [npc.she] eagerly slams [npc.her] [npc.fingers] deep inside [npc.her] [npc.asshole+], before starting to desperately finger [npc.her] [npc.ass].",
"Enthusiastically pumping [npc.her] [npc.fingers] in and out of [npc.her] [npc.asshole+], [npc.name] starts letting out a series of delighted [npc.moans] as [npc.she] frantically fingers [npc.her] own [npc.ass].",
"Desperately curling [npc.her] [npc.fingers] up inside [npc.her] [npc.asshole], [npc.name] lets out [npc.a_moan] as [npc.she] starts "
+(Sex.getCharacterPerformingAction().hasPenis()
?"eagerly grinding [npc.her] fingertips up against [npc.her] prostate."
:"eagerly grinding [npc.her] digits in and out of [npc.her] [npc.ass+]."),
"Focusing on pleasuring [npc.her] [npc.ass+], [npc.name] eagerly starts slamming [npc.her] [npc.fingers] in and out of [npc.her] [npc.asshole+].");
}
};
public static final SexAction PARTNER_SELF_FINGER_ANUS_STOP_PENETRATION = new SexAction(
SexActionType.STOP_ONGOING,
ArousalIncrease.ONE_MINIMUM,
ArousalIncrease.ONE_MINIMUM,
CorruptionLevel.ZERO_PURE,
Util.newHashMapOfValues(new Value<>(SexAreaPenetration.FINGER, SexAreaOrifice.ANUS)),
SexParticipantType.SELF) {
@Override
public SexActionLimitation getLimitation() {
return SexActionLimitation.NPC_ONLY;
}
@Override
public String getActionTitle() {
return "Stop anal fingering (self)";
}
@Override
public String getActionDescription() {
return "Stop fingering [npc.her] ass.";
}
@Override
public String getDescription() {
return "With [npc.a_groan+], [npc.name] slides [npc.her] fingers out of [npc.her] [npc.asshole+].";
}
};
}
| 42.626506 | 234 | 0.712761 |
cef23de93739d7f835e678ae32e067dd7c7d3a14 | 5,077 | /*
* Copyright 2020-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.mongodb.core.aggregation;
import static org.assertj.core.api.Assertions.*;
import java.util.Arrays;
import java.util.List;
import org.bson.Document;
import org.junit.jupiter.api.Test;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.convert.NoOpDbRefResolver;
import org.springframework.data.mongodb.core.convert.QueryMapper;
import org.springframework.data.mongodb.core.mapping.Field;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
import org.springframework.lang.Nullable;
/**
* Unit tests for {@link UnionWithOperation}.
*
* @author Christoph Strobl
*/
class UnionWithOperationUnitTests {
@Test // DATAMONGO-2622
void throwsErrorWhenNoCollectionPresent() {
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> UnionWithOperation.unionWith(null));
}
@Test // DATAMONGO-2622
void rendersJustCollectionCorrectly() {
assertThat(UnionWithOperation.unionWith("coll-1").toPipelineStages(contextFor(Warehouse.class)))
.containsExactly(new Document("$unionWith", new Document("coll", "coll-1")));
}
@Test // DATAMONGO-2622
void rendersPipelineCorrectly() {
assertThat(UnionWithOperation.unionWith("coll-1").mapFieldsTo(Warehouse.class)
.pipeline(Aggregation.project().and("location").as("region")).toPipelineStages(contextFor(Warehouse.class)))
.containsExactly(new Document("$unionWith", new Document("coll", "coll-1").append("pipeline",
Arrays.asList(new Document("$project", new Document("region", 1))))));
}
@Test // DATAMONGO-2622
void rendersPipelineCorrectlyForDifferentDomainType() {
assertThat(UnionWithOperation.unionWith("coll-1").pipeline(Aggregation.project().and("name").as("name"))
.mapFieldsTo(Supplier.class).toPipelineStages(contextFor(Warehouse.class)))
.containsExactly(new Document("$unionWith", new Document("coll", "coll-1").append("pipeline",
Arrays.asList(new Document("$project", new Document("name", "$supplier"))))));
}
@Test // DATAMONGO-2622
void rendersPipelineCorrectlyForUntypedContext() {
assertThat(UnionWithOperation.unionWith("coll-1").pipeline(Aggregation.project("region"))
.toPipelineStages(contextFor(null)))
.containsExactly(new Document("$unionWith", new Document("coll", "coll-1").append("pipeline",
Arrays.asList(new Document("$project", new Document("region", 1))))));
}
@Test // DATAMONGO-2622
void doesNotMapAgainstFieldsFromAPreviousStage() {
TypedAggregation<Supplier> agg = TypedAggregation.newAggregation(Supplier.class,
Aggregation.project().and("name").as("supplier"),
UnionWithOperation.unionWith("coll-1").pipeline(Aggregation.project().and("name").as("name")));
List<Document> pipeline = agg.toPipeline(contextFor(Supplier.class));
assertThat(pipeline).containsExactly(new Document("$project", new Document("supplier", 1)), //
new Document("$unionWith", new Document("coll", "coll-1").append("pipeline",
Arrays.asList(new Document("$project", new Document("name", 1))))));
}
@Test // DATAMONGO-2622
void mapAgainstUnionWithDomainTypeEvenWhenInsideTypedAggregation() {
TypedAggregation<Supplier> agg = TypedAggregation.newAggregation(Supplier.class,
Aggregation.project().and("name").as("supplier"), UnionWithOperation.unionWith("coll-1")
.mapFieldsTo(Warehouse.class).pipeline(Aggregation.project().and("location").as("location")));
List<Document> pipeline = agg.toPipeline(contextFor(Supplier.class));
assertThat(pipeline).containsExactly(new Document("$project", new Document("supplier", 1)), //
new Document("$unionWith", new Document("coll", "coll-1").append("pipeline",
Arrays.asList(new Document("$project", new Document("location", "$region"))))));
}
private static AggregationOperationContext contextFor(@Nullable Class<?> type) {
if (type == null) {
return Aggregation.DEFAULT_CONTEXT;
}
MappingMongoConverter mongoConverter = new MappingMongoConverter(NoOpDbRefResolver.INSTANCE,
new MongoMappingContext());
mongoConverter.afterPropertiesSet();
return new TypeBasedAggregationOperationContext(type, mongoConverter.getMappingContext(),
new QueryMapper(mongoConverter));
}
static class Warehouse {
String name;
@Field("region") String location;
String state;
}
static class Supplier {
@Field("supplier") String name;
String state;
}
}
| 38.755725 | 113 | 0.747686 |
7c3a4da9bc87d135246e7a2f46b863e07272b99c | 139 | /**
* this package is for domain models in regionizer project
* @author Min Zheng
*
*/
package org.wallerlab.yoink.regionizer.domain;
| 19.857143 | 58 | 0.726619 |
7e78301aab5ff1a0470885e8935ff7d8fe637028 | 127 | package models;
/**
* Created by arkady on 16/02/16.
*/
public enum VenueRequestStatus {
APPROVED,
REQUESTED,
PREVIOUS
}
| 11.545455 | 33 | 0.700787 |
b0ecaf52af3ea0fe799b88eb842990ce88a6fdbd | 1,800 | package com.holmes.hoo.blackwatch.model.entity;
import com.holmes.hoo.blackwatch.common.Code;
import org.apache.http.HttpStatus;
import java.io.Serializable;
/**
* @author A20019
* @since 2022/1/8 10:39
*/
public class Result<T> implements Serializable {
private static final long serialVersionUID = -9120721239942303550L;
private T data;
private Integer code;
private String message;
public static <T> Result<T> ofFailed(Code code) {
Result<T> result = new Result<>();
result.code = code.getCode();
result.message = code.getMessage();
return result;
}
public static <T> Result<T> ofFailed(Code code, String message) {
Result<T> result = new Result<>();
result.code = code.getCode();
result.message = message;
return result;
}
public static <T> Result<T> ofSucceed() {
Result<T> result = new Result<>();
result.code = HttpStatus.SC_OK;
result.message = "successful";
return result;
}
public static <T> Result<T> ofSucceed(T data) {
Result<T> result = new Result<>();
result.data = data;
result.code = HttpStatus.SC_OK;
result.message = "successful";
return result;
}
public Result() {
}
public T getData() {
return this.data;
}
public Integer getCode() {
return this.code;
}
public String getMessage() {
return this.message;
}
public void setData(final T data) {
this.data = data;
}
public void setCode(final Integer code) {
this.code = code;
}
public void setMessage(final String message) {
this.message = message;
}
}
| 24 | 72 | 0.578889 |
36d3f6e0dbb806cbcfc456a0fd89f60579b2419a | 1,419 | /*
* (C) Copyright 2015-2017 Nuxeo (http://nuxeo.com/) and others.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Contributors:
* Florent Guillaume
*/
package org.nuxeo.ecm.core.blob;
import org.nuxeo.ecm.core.api.Blob;
/**
* Class describing information from a {@link Blob}, suitable for serialization and storage.
*
* @since 7.2
*/
public class BlobInfo {
public String key;
public String mimeType;
public String encoding;
public String filename;
public Long length;
public String digest;
/** Empty constructor. */
public BlobInfo() {
}
/**
* Copy constructor.
*
* @since 7.10
*/
public BlobInfo(BlobInfo other) {
key = other.key;
mimeType = other.mimeType;
encoding = other.encoding;
filename = other.filename;
length = other.length;
digest = other.digest;
}
}
| 23.262295 | 92 | 0.661029 |
317fcb64f3d0fda83faa5d8b4fbca58237876cc3 | 1,078 | package com.sda.practicalproject.phonebook.database.contact;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
@Entity
@Table(name = "contact")
@Getter
@Setter
@NoArgsConstructor
@EntityListeners(ContactListener.class)
public class Contact {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long contactId;
@Column
private String personName;
@Column
private String address;
@Column
private String email;
@Column
private Long phoneNumber;
@Column
private Long creatorId;
public Contact(String name, String address, String email, long phoneNumber) {
this.personName = name;
this.address = address;
this.email = email;
this.phoneNumber = phoneNumber;
}
public void setCreatorId(Long id) {
this.creatorId = id;
}
@Override
public String toString() {
return personName + " " +
address + " " +
email + " " +
+phoneNumber;
}
}
| 19.6 | 81 | 0.641002 |
72818e87091fca3452378d4a48b73e44398d1ffa | 2,082 | package com.jinjunhang.contract.controller;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;
import com.jinjunhang.contract.BuildConfig;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by lzn on 16/4/3.
*/
public class Utils {
private final static String TAG = "Utils";
public final static int PAGESIZE_APPROVAL = 25;
public final static int PAGESIZE_ORDER = 25;
public final static int PAGESIZE_PRICEREPORT = 25;
public final static long UPDATE_TIME_DELTA = 1000 * 60 * 5;
public static void showMessage(Context context, String message) {
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(context);
dlgAlert.setMessage(message);
dlgAlert.setPositiveButton("确定", null);
dlgAlert.create().show();
}
public static void showMessage(Context context, String message, DialogInterface.OnClickListener listener) {
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(context);
dlgAlert.setMessage(message);
dlgAlert.setPositiveButton("确定", listener);
dlgAlert.create().show();
}
public static void showConfirmMessage(Context context, String message, DialogInterface.OnClickListener listener) {
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(context);
dlgAlert.setMessage(message);
dlgAlert.setPositiveButton("确定", listener);
dlgAlert.setNegativeButton("取消", null);
dlgAlert.create().show();
}
public static void showServerErrorDialog(Context context){
showMessage(context, "服务器返回出错!");
}
public static int compareDate(String dateStr1, String dateStr2) {
SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date1 = dt.parse(dateStr1);
Date date2 = dt.parse(dateStr2);
return date1.compareTo(date2);
}
catch (Exception ex){
Log.e(TAG, ex.toString());
}
return 0;
}
}
| 30.173913 | 118 | 0.682037 |
e3542b5f2349906c9e207d409beb5e8bbf12671a | 6,510 | package com.infoclinika.mssharing.services.billing.persistence.helper;
import com.infoclinika.mssharing.model.internal.repository.LabPaymentAccountRepository;
import com.infoclinika.mssharing.model.read.BillingInfoReader;
import com.infoclinika.mssharing.model.write.billing.BillingManagement;
import com.infoclinika.mssharing.propertiesprovider.BillingPropertiesProvider;
import com.infoclinika.mssharing.services.billing.persistence.enity.ArchiveStorageVolumeUsage;
import com.infoclinika.mssharing.services.billing.persistence.enity.StorageVolumeUsage;
import com.infoclinika.mssharing.services.billing.persistence.read.ChargeableItemUsageReader;
import com.infoclinika.mssharing.services.billing.persistence.repository.ArchiveStorageVolumeUsageRepository;
import com.infoclinika.mssharing.services.billing.persistence.repository.StorageVolumeUsageRepository;
import com.infoclinika.mssharing.services.billing.persistence.write.PaymentManagement;
import com.infoclinika.mssharing.services.billing.rest.api.model.BillingFeature;
import com.infoclinika.mssharing.services.billing.rest.api.model.LabAccountFeatureInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.Optional;
import java.util.Set;
import java.util.TimeZone;
/**
* @author : Alexander Serebriyan
*/
@Component
public class StorageAndProcessingFeaturesUsageAnalyser {
private static final Logger LOGGER = LoggerFactory.getLogger(StorageAndProcessingFeaturesUsageAnalyser.class);
private TimeZone timeZone;
@Inject
private PaymentManagement paymentManagement;
@Inject
private LabPaymentAccountRepository labPaymentAccountRepository;
@Inject
private StorageVolumeUsageRepository storageVolumeUsageRepository;
@Inject
private ArchiveStorageVolumeUsageRepository archiveStorageVolumeUsageRepository;
@Inject
private ChargeableItemUsageReader chargeableItemUsageReader;
@Inject
private BillingManagement billingManagement;
@Inject
private PaymentCalculationsHelper paymentCalculationsHelper;
@Inject
private BillingInfoReader billingInfoReader;
@Inject
private BillingPropertiesProvider billingPropertiesProvider;
@PostConstruct
private void init() {
timeZone = TimeZone.getTimeZone(ZoneId.of(billingPropertiesProvider.getTimeZoneId()));
}
public void analyseStorageVolumeUsage(long currentTime) {
LOGGER.info("analyseStorageVolumeUsage");
labPaymentAccountRepository.findAll().forEach(account -> {
final Long labId = account.getLab().getId();
final StorageVolumeUsage lastUsage = storageVolumeUsageRepository.findLast(labId);
if (lastUsage != null) {
final ZonedDateTime now =
ZonedDateTime.ofInstant(Instant.ofEpochMilli(currentTime), timeZone.toZoneId());
final ZonedDateTime lastUsageTime =
ZonedDateTime.ofInstant(Instant.ofEpochMilli(lastUsage.getTimestamp()), timeZone.toZoneId());
if (oneMonthPassed(lastUsageTime, now)) {
final ZonedDateTime lastUsageTimePlusMonth = lastUsageTime.plusMonths(1);
final long maximumStorageUsage = paymentCalculationsHelper.calculateMaximumStorageUsage(
labId,
new Date(lastUsageTime.toInstant().toEpochMilli()),
new Date(lastUsageTimePlusMonth.toInstant().toEpochMilli())
);
final int storageVolumes = paymentCalculationsHelper.calculateStorageVolumes(maximumStorageUsage);
paymentManagement.logStorageVolumeUsage(
lastUsage.getUser(),
lastUsage.getLab(),
storageVolumes,
lastUsageTimePlusMonth.toInstant().toEpochMilli()
);
}
}
});
}
public void analyseArchiveStorageVolumeUsage(long currentTime) {
LOGGER.info("archiveStorageVolumeUsage");
labPaymentAccountRepository.findAll().forEach(account -> {
final Long labId = account.getLab().getId();
final ArchiveStorageVolumeUsage lastUsage = archiveStorageVolumeUsageRepository.findLast(labId);
if (lastUsage != null) {
final ZonedDateTime now =
ZonedDateTime.ofInstant(Instant.ofEpochMilli(currentTime), timeZone.toZoneId());
final ZonedDateTime lastUsageTime =
ZonedDateTime.ofInstant(Instant.ofEpochMilli(lastUsage.getTimestamp()), timeZone.toZoneId());
if (oneMonthPassed(lastUsageTime, now)) {
final ZonedDateTime lastUsageTimePlusMonth = lastUsageTime.plusMonths(1);
final long maximumStorageUsage = paymentCalculationsHelper.calculateMaximumArchiveStorageUsage(
labId,
new Date(lastUsageTime.toInstant().toEpochMilli()),
new Date(lastUsageTimePlusMonth.toInstant().toEpochMilli())
);
final int storageVolumes =
paymentCalculationsHelper.calculateArchiveStorageVolumes(maximumStorageUsage);
paymentManagement.logArchiveStorageVolumeUsage(
lastUsage.getUser(),
lastUsage.getLab(),
storageVolumes,
lastUsageTimePlusMonth.toInstant().toEpochMilli()
);
}
}
});
}
private boolean oneMonthPassed(ZonedDateTime from, ZonedDateTime to) {
return !from.plusMonths(1).isAfter(to);
}
private boolean autoprolongateFeature(long lab, BillingFeature billingFeature) {
final Set<LabAccountFeatureInfo> labAccountFeatureInfos = billingInfoReader.readLabAccountFeatures(lab);
final Optional<LabAccountFeatureInfo> storageVolumesFeature = labAccountFeatureInfos
.stream()
.filter(feature -> feature.name.equals(billingFeature.name()))
.findFirst();
return storageVolumesFeature.isPresent() && storageVolumesFeature.get().autoProlongate;
}
}
| 42.272727 | 118 | 0.696313 |
9523f9e60481e06f2379502f32735c9dcc3958a9 | 634 | package com.vzome.core.editor;
import static org.junit.Assert.*;
import org.junit.Test;
public class VersionComparisonTest {
@Test
public void testVersionComparison()
{
Application app = new Application( false, null, null )
{
@Override
public String getCoreVersion()
{
return "0.8.10";
}
};
DocumentModel doc = app .createDocument( "golden" );
assertTrue( doc .fileIsTooNew( "100.100.100" ) );
assertFalse( doc .fileIsTooNew( "0.8.9" ) );
assertTrue( doc .fileIsTooNew( "0.8.19" ) );
assertFalse( doc .fileIsTooNew( "fred.joe" ) );
assertFalse( doc .fileIsTooNew( null ) );
}
}
| 18.647059 | 56 | 0.654574 |
879a727c102dd1dd6a640f7a73426b30a6060683 | 226 | package com.twitter.hraven.mapreduce;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.NonNull;
@Data
@NoArgsConstructor
public class ReplaceRule {
@NonNull
String regex;
@NonNull
String with;
}
| 14.125 | 37 | 0.769912 |
3526ce2141e8e192658b9fdc5f9ba9e983f931ff | 2,950 | package com.shejiaomao.weibo.service.listener;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.Display;
import android.view.MotionEvent;
import android.view.WindowManager;
import android.view.GestureDetector.OnGestureListener;
import com.shejiaomao.common.CompatibilityUtil;
import com.shejiaomao.maobo.R;
import com.shejiaomao.weibo.activity.AccountsActivity;
import com.shejiaomao.weibo.common.Constants;
public class HomePageOnGestureListener implements OnGestureListener {
//mdpi下的比例计算;
private static final float FACTOR_PORTRAIT;
private static final float FACTOR_LANDSCAPE;
//水平滑动的参数
private static int SLIDE_MIN_DISTANCE_X;
private static int SLIDE_MAX_DISTANCE_Y;
private static int DISPLAY_WINDOW_WIDTH;
private static int DISPLAY_WINDOW_HEIGHT;
static {
FACTOR_PORTRAIT = 120f / 320;
FACTOR_LANDSCAPE = FACTOR_PORTRAIT;
}
private Context context;
//private int orientation;
public HomePageOnGestureListener(Context context) {
this.context = context;
initEnv(context);
}
private void initEnv(Context context) {
// 获得屏幕大小
WindowManager windowManager = ((Activity)context).getWindowManager();
Display display = windowManager.getDefaultDisplay();
DISPLAY_WINDOW_WIDTH = display.getWidth();
DISPLAY_WINDOW_HEIGHT = display.getHeight();
SLIDE_MIN_DISTANCE_X = (int)(DISPLAY_WINDOW_WIDTH * FACTOR_PORTRAIT);
SLIDE_MAX_DISTANCE_Y = (int)(DISPLAY_WINDOW_HEIGHT * FACTOR_LANDSCAPE);
SLIDE_MAX_DISTANCE_Y = 120;
//orientation = context.getResources().getConfiguration().orientation;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
float x1 = (e1 != null ? e1.getX() : 0);
float x2 = (e2 != null ? e2.getX() : 0);
float y1 = (e1 != null ? e1.getY() : 0);
float y2 = (e2 != null ? e2.getY() : 0);
float distanceX = x1 - x2;
float distanceY = y1 - y2;
//切换帐号,符合条件
if (
distanceX < 0 && //slide to right
Math.abs(distanceX) > SLIDE_MIN_DISTANCE_X &&
Math.abs(distanceY) < SLIDE_MAX_DISTANCE_Y
) {
Intent intent = new Intent();
intent.setClass(context, AccountsActivity.class);
((Activity)context).startActivityForResult(intent, Constants.REQUEST_CODE_ACCOUNTS);
CompatibilityUtil.overridePendingTransition(
(Activity)context, R.anim.slide_in_left, android.R.anim.fade_out
);
return true;
}
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
float distanceY) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
}
| 27.830189 | 88 | 0.721356 |
98f40d9ed6c68bd968d95f4ed212336031921cf1 | 4,101 | /*
* Copyright (c) 2008-2020, Hazelcast, 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.hazelcast.sql.impl;
import com.hazelcast.sql.impl.exec.io.flowcontrol.FlowControl;
import com.hazelcast.sql.impl.operation.QueryOperationHandler;
import java.util.UUID;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
public final class LoggingFlowControl implements FlowControl {
private final QueryId queryId;
private final int edgeId;
private final UUID localMemberId;
private final QueryOperationHandler operationHandler;
private boolean setupInvoked;
private boolean fragmentCallbackInvoked;
private BatchAddDescriptor addDescriptor;
private BatchRemoveDescriptor removeDescriptor;
public LoggingFlowControl(QueryId queryId, int edgeId, UUID localMemberId, QueryOperationHandler operationHandler) {
this.queryId = queryId;
this.edgeId = edgeId;
this.localMemberId = localMemberId;
this.operationHandler = operationHandler;
}
@Override
public void setup(QueryId queryId, int edgeId, UUID localMemberId, QueryOperationHandler operationHandler) {
assertEquals(this.queryId, queryId);
assertEquals(this.edgeId, edgeId);
assertEquals(this.localMemberId, localMemberId);
assertSame(this.operationHandler, operationHandler);
setupInvoked = true;
}
@Override
public void onBatchAdded(UUID memberId, long size, boolean last, long remoteMemory) {
addDescriptor = new BatchAddDescriptor(memberId, size, last, remoteMemory);
}
@Override
public void onBatchRemoved(UUID memberId, long size, boolean last) {
removeDescriptor = new BatchRemoveDescriptor(memberId, size, last);
}
@Override
public void onFragmentExecutionCompleted() {
fragmentCallbackInvoked = true;
}
public boolean isSetupInvoked() {
return setupInvoked;
}
public boolean isFragmentCallbackInvoked() {
return fragmentCallbackInvoked;
}
public BatchAddDescriptor getAddDescriptor() {
return addDescriptor;
}
public BatchRemoveDescriptor getRemoveDescriptor() {
return removeDescriptor;
}
public static class BatchAddDescriptor {
private final UUID memberId;
private final long size;
private final boolean last;
private final long remoteMemory;
private BatchAddDescriptor(UUID memberId, long size, boolean last, long remoteMemory) {
this.memberId = memberId;
this.size = size;
this.last = last;
this.remoteMemory = remoteMemory;
}
public UUID getMemberId() {
return memberId;
}
public long getSize() {
return size;
}
public boolean isLast() {
return last;
}
public long getRemoteMemory() {
return remoteMemory;
}
}
public static class BatchRemoveDescriptor {
private final UUID memberId;
private final long size;
private final boolean last;
private BatchRemoveDescriptor(UUID memberId, long size, boolean last) {
this.memberId = memberId;
this.size = size;
this.last = last;
}
public UUID getMemberId() {
return memberId;
}
public long getSize() {
return size;
}
public boolean isLast() {
return last;
}
}
}
| 29.085106 | 120 | 0.671544 |
16ba8c224a2bac751c8d3ad435842a06c7921a58 | 832 | package com.linln.modules.system.repository;
import com.linln.modules.system.domain.Interview;
import com.linln.modules.system.domain.Scale;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;
/**
* @author 小懒虫
* @date 2018/8/14extends JpaRepository<Scale, Integer>
*/
public interface InterviewRepository extends JpaRepository<Interview,String> {
@Query(value = "SELECT * FROM sys_interview WHERE report_id=?1",nativeQuery = true)
List<Interview> findByReportId(String reportId);
}
| 26 | 87 | 0.800481 |
8cda2c336b29172d3d62ae2ef87b551f9cc5dc07 | 902 | package org.example.dto;
import javax.validation.constraints.NotEmpty;
/**
* @author <a href="mailto:itfuyun@gmail.com">Tanxh</a>
* @since 1.0
*/
public class UserDTO {
/**
* 登录名
*/
@NotEmpty(message = "登录名不能为空")
private String loginName;
/**
* 登录密码
*/
@NotEmpty(message = "登录密码不能为空")
private String password;
/**
* 手机号码
*/
@NotEmpty(message = "手机号码不能为空")
private String phone;
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
| 17.686275 | 55 | 0.584257 |
ee18ef1d8b199621a228bc74c3ccfb471148a7c0 | 4,591 | package github.nisrulz.sample.usingfirebasejobdispatcher;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.firebase.jobdispatcher.Constraint;
import com.firebase.jobdispatcher.FirebaseJobDispatcher;
import com.firebase.jobdispatcher.GooglePlayDriver;
import com.firebase.jobdispatcher.Job;
import com.firebase.jobdispatcher.Lifetime;
import com.firebase.jobdispatcher.RetryStrategy;
import com.firebase.jobdispatcher.Trigger;
import java.util.ArrayList;
/**
* The type Main activity.
*/
public class MainActivity extends AppCompatActivity {
/**
* The Dispatcher.
*/
FirebaseJobDispatcher dispatcher;
ListView listView;
ArrayList<String> actions;
ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create a new dispatcher using the Google Play driver.
dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));
listView = (ListView) findViewById(R.id.listview);
actions = new ArrayList<>();
actions.add("Schedule a Simple Job");
actions.add("Cancel the Simple Job");
actions.add("Schedule a Complex Job");
actions.add("Cancel the Complex Job");
actions.add("Cancel all Jobs");
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, actions);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
switch (position) {
case 0:
scheduleASimpleJob("simple-job");
Toast.makeText(MainActivity.this, "Scheduled the Simple Job", Toast.LENGTH_SHORT)
.show();
break;
case 1:
cancelAJob("simple-job");
Toast.makeText(MainActivity.this, "Cancelling the Simple Job", Toast.LENGTH_SHORT)
.show();
break;
case 2:
Bundle extraBundle = new Bundle();
extraBundle.putString("some-key", "some-value");
scheduleAComplexJob("complex-job", extraBundle);
Toast.makeText(MainActivity.this, "Scheduled the Complex Job", Toast.LENGTH_SHORT)
.show();
break;
case 3:
cancelAJob("complex-job");
Toast.makeText(MainActivity.this, "Cancelling the Complex Job", Toast.LENGTH_SHORT)
.show();
break;
case 4:
cancelAllJobs();
Toast.makeText(MainActivity.this, "Cancelling all Jobs", Toast.LENGTH_SHORT).show();
break;
}
}
});
}
private void scheduleASimpleJob(String uniqueTag) {
Job myJob = dispatcher.newJobBuilder()
.setService(MyJobService.class) // the JobService that will be called
.setTag(uniqueTag) // uniquely identifies the job
.build();
dispatcher.mustSchedule(myJob);
}
private void scheduleAComplexJob(String uniqueTag, Bundle myExtrasBundle) {
Job myJob = dispatcher.newJobBuilder()
// the JobService that will be called
.setService(MyJobService.class)
// uniquely identifies the job
.setTag(uniqueTag)
// one-off job
.setRecurring(false)
// don't persist past a device reboot
.setLifetime(Lifetime.UNTIL_NEXT_BOOT)
// start between 0 and 60 seconds from now
.setTrigger(Trigger.executionWindow(0, 60))
// don't overwrite an existing job with the same tag
.setReplaceCurrent(false)
// retry with exponential backoff
.setRetryStrategy(RetryStrategy.DEFAULT_EXPONENTIAL)
// constraints that need to be satisfied for the job to run
.setConstraints(
// only run on an unmetered network
Constraint.ON_UNMETERED_NETWORK,
// only run when the device is charging
Constraint.DEVICE_CHARGING).setExtras(myExtrasBundle).build();
dispatcher.mustSchedule(myJob);
}
private void cancelAJob(String uniqueTag) {
dispatcher.cancel(uniqueTag);
}
private void cancelAllJobs() {
dispatcher.cancelAll();
}
}
| 34.518797 | 96 | 0.675234 |
270337585db04ac2c4099d89010f6adc349750b2 | 90 | /**
* Contains various utility classes
*/
package com.github.ruediste.salta.jsr330.util; | 22.5 | 46 | 0.755556 |
90832a60a548154fb25adde0c01e3c871a302513 | 1,205 | import java.util.Scanner;
class Main {
public static void main(String[] args) {
int i, j;
int sum_row, sum_col, sum_diagonal = 0, sum = 0;
boolean magic=true;
int[][] square = new int[3][3];
Scanner input = new Scanner(System.in);
System.out.print("enter numbers");
for (i=0; i<3; i++)
for (j=0; j<3; j++)
square[i][j] = input.nextInt();
System.out.println("Square");
for (i=0; i<3; i++) {
for (j=0; j<3; j++)
System.out.print(square[i][j] + " ");
System.out.println();
}
for (j=0; j<3; j++)
sum += square[0][j];
for (i=1; i<3; i++) {
sum_row =0;
for (j=0; j<3; j++)
sum_row += square[i][j];
if (sum_row != sum) {
magic = false;
break;
}
}
if (magic) {
for (j=0; j<3; j++) {
sum_col = 0;
for (i=0; i<3; i++)
sum_col += square[i][j];
if (sum_col != sum) {
magic = false;
break;
}
}
}
if (magic) {
for (i=0; i<3; i++)
for (j=0; j<3; j++)
if (i==j)
sum_diagonal += square[i][j];
if (sum_diagonal != sum) {
magic = false;
}
}
if (magic) {
sum_diagonal = 0;
for (i=0; i<3; i++)
for (j=0; j<3; j++)
if ((i+j) == 2)
sum_diagonal += square[i][j];
if (sum_diagonal != sum) {
magic = false;
}
}
if (magic)
System.out.println("It is a magic square");
else
System.out.println("It is not a magic square");
}
} | 16.283784 | 48 | 0.579253 |
b9cc5e7c59c2443dd708ea319afed64a654cecae | 6,859 | package com.cuong.cdroid.util;
import android.app.Activity;
import android.content.Context;
import android.widget.TextView;
import android.widget.Toast;
/**
* Created by Clover on 5/10/2016.
* Open Source: This source has been wrote by CuongNguyen
* Contact: vcuong11s@gmail.com or unme.rf@gmail.com
*/
public final class ToastUtils {
public static Toast toast;
public static boolean IsDisableMessage = false;
public static void disable() {
IsDisableMessage = true;
}
public static void enable() {
IsDisableMessage = false;
}
/**
* Show a Toast message (LENGTH_SHORT), sure that it will show without delay
*
* @param context Context
* @param message Message
*/
public static void show(final Activity context, final String message) {
if (IsDisableMessage) {
return;
}
try {
context.runOnUiThread(new Runnable() {
@Override
public void run() {
if (toast != null) {
toast.cancel();
}
toast = Toast.makeText(context, message, Toast.LENGTH_SHORT);
toast.show();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Show a Toast message (LENGTH_SHORT), sure that it will show without delay
*
* @param context Context
* @param message Message
*/
public static void show(final Context context, final String message) {
Activity activity = (Activity) context;
show(activity, message);
}
/**
* Show a Toast message (LENGTH_SHORT), sure that it will show without delay
*
* @param context Context
* @param resource String ResourceId
*/
public static void show(final Context context, int resource) {
Activity activity = (Activity) context;
show(activity, context.getResources().getString(resource));
}
/**
* Show a Toast message (LENGTH_LONG), sure that it will show without delay
*
* @param context Activity
* @param message Message
*/
public static void showLong(final Activity context, final String message) {
if (IsDisableMessage) {
return;
}
try {
context.runOnUiThread(new Runnable() {
@Override
public void run() {
if (toast != null) {
toast.cancel();
}
toast = Toast.makeText(context, message, Toast.LENGTH_LONG);
toast.show();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Show a Toast message (LENGTH_LONG), sure that it will show without delay
*
* @param context Context
* @param message Message
*/
public static void showLong(final Context context, final String message) {
Activity activity = (Activity) context;
showLong(activity, message);
}
/**
* Show a Toast message (LENGTH_LONG), sure that it will show without delay
*
* @param context Context
* @param resource String ResourceId
*/
public static void showLong(final Context context, int resource) {
Activity activity = (Activity) context;
showLong(activity, context.getResources().getString(resource));
}
/**
* Show Toast with Gravity, LENGTH_SORT
*
* @param context Context
* @param message Message
* @param gravity Gravity
*/
public static void show(final Activity context, final String message, final int gravity) {
if (IsDisableMessage) {
return;
}
try {
context.runOnUiThread(new Runnable() {
@Override
public void run() {
if (toast != null) {
toast.cancel();
}
toast = Toast.makeText(context, message, Toast.LENGTH_SHORT);
TextView v = (TextView) toast.getView().findViewById(android.R.id.message);
if (v != null) v.setGravity(gravity);
toast.show();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Show Toast with Gravity, LENGTH_SORT
*
* @param context Context
* @param message Message
* @param gravity Gravity
*/
public static void show(final Context context, final String message, final int gravity) {
Activity activity = (Activity) context;
show(activity, message, gravity);
}
/**
* Show Toast with Gravity, LENGTH_SORT
*
* @param context Context
* @param resource String ResourceId
* @param gravity Gravity
*/
public static void show(final Context context, int resource, final int gravity) {
Activity activity = (Activity) context;
show(activity, context.getResources().getString(resource), gravity);
}
/**
* Show Toast with Gravity, LENGTH_LONG
*
* @param context Context
* @param message Message
* @param gravity Gravity
*/
public static void showLong(final Activity context, final String message, final int gravity) {
if (IsDisableMessage) {
return;
}
try {
context.runOnUiThread(new Runnable() {
@Override
public void run() {
if (toast != null) {
toast.cancel();
}
toast = Toast.makeText(context, message, Toast.LENGTH_LONG);
TextView v = (TextView) toast.getView().findViewById(android.R.id.message);
if (v != null) v.setGravity(gravity);
toast.show();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Show Toast with Gravity, LENGTH_LONG
*
* @param context Context
* @param message Message
* @param gravity Gravity
*/
public static void showLong(final Context context, final String message, final int gravity) {
Activity activity = (Activity) context;
showLong(activity, message, gravity);
}
/**
* Show Toast with Gravity, LENGTH_LONG
*
* @param context Context
* @param resource String ResourceId
* @param gravity Gravity
*/
public static void showLong(final Context context, int resource, final int gravity) {
Activity activity = (Activity) context;
showLong(activity, context.getResources().getString(resource), gravity);
}
}
| 30.083333 | 98 | 0.556349 |
7022363d038646209a79adbaeb2237d7afe8cadd | 2,757 | /*
* 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.apisix.plugin.runner.handler;
import com.google.common.cache.Cache;
import io.github.api7.A6.PrepareConf.Req;
import io.github.api7.A6.TextEntry;
import lombok.RequiredArgsConstructor;
import org.apache.apisix.plugin.runner.A6Conf;
import org.apache.apisix.plugin.runner.A6ConfigRequest;
import org.apache.apisix.plugin.runner.A6ConfigResponse;
import org.apache.apisix.plugin.runner.A6Request;
import org.apache.apisix.plugin.runner.A6Response;
import org.apache.apisix.plugin.runner.filter.PluginFilter;
import org.apache.apisix.plugin.runner.filter.PluginFilterChain;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* Handle APISIX configuration request.
*/
@RequiredArgsConstructor
public class A6ConfigHandler implements Handler {
private final Logger logger = LoggerFactory.getLogger(A6ConfigHandler.class);
private final Cache<Long, A6Conf> cache;
private final Map<String, PluginFilter> filters;
@Override
public void handle(A6Request request, A6Response response) {
Req req = ((A6ConfigRequest) request).getReq();
long token = ((A6ConfigResponse) response).getConfToken();
PluginFilterChain chain = createFilterChain(req);
A6Conf config = new A6Conf(req, chain);
cache.put(token, config);
}
private PluginFilterChain createFilterChain(Req req) {
List<PluginFilter> chainFilters = new ArrayList<>();
for (int i = 0; i < req.confLength(); i++) {
TextEntry conf = req.conf(i);
PluginFilter filter = filters.get(conf.name());
if (Objects.isNull(filter)) {
logger.error("receive undefined filter: {}, skip it", conf.name());
continue;
}
chainFilters.add(filter);
}
return new PluginFilterChain(chainFilters);
}
}
| 37.256757 | 83 | 0.723975 |
e451b4359c0c3c85a5c54452c85fd1493fb142ab | 3,207 | package controllers;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import play.mvc.Controller;
import play.mvc.Result;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
public class DatasourceTestConn extends Controller {
private enum TYPE{
MYSQL, POSTGRES
}
private static Map<TYPE, String> testConnSQLMap = new HashMap<>();
static {
testConnSQLMap.put(TYPE.MYSQL, "select 1+1");
testConnSQLMap.put(TYPE.POSTGRES, "select 1+1");
}
public Result testConn() throws IOException {
if(request().hasBody()){
JsonNode json = request().body().asJson();
String type = json.get("type").textValue();
String driver = json.get("driver").textValue();
String url = json.get("url").textValue();
String username = json.get("username").textValue();
String password = json.get("password").textValue();
if("mysql".equalsIgnoreCase(type)){
return test(TYPE.MYSQL, driver, url, username, password);
} else if("postgresql".equalsIgnoreCase(type)) {
return test(TYPE.POSTGRES, driver, url, username, password);
}else {
ObjectMapper mapper = new ObjectMapper();
JsonNode j = mapper.readTree("{\"result\":400,\"message\":\""+type+" not support yet.\"}");
return status(400, j);
}
} else {
ObjectMapper mapper = new ObjectMapper();
JsonNode json = mapper.readTree("{\"result\":400,\"message\":\"not a valid params.\"}");
return status(400, json);
}
}
private Result test(TYPE type, String driver, String url, String username, String password) throws IOException {
try {
Class.forName(driver);
} catch (ClassNotFoundException e){
ObjectMapper mapper = new ObjectMapper();
JsonNode j = mapper.readTree("{\"result\":400,\"message\":\"driver class not found.\"}");
return status(400, j);
}
try (Connection conn = DriverManager.getConnection(url, username, password);
PreparedStatement prstat =conn.prepareStatement(testConnSQLMap.get(type));
ResultSet rs = prstat.executeQuery()){
if(rs.next() && rs.getInt(1) == 2){
ObjectMapper mapper = new ObjectMapper();
JsonNode j = mapper.readTree("{\"result\":200,\"message\":\"success.\"}");
return ok(j);
} else {
ObjectMapper mapper = new ObjectMapper();
JsonNode j = mapper.readTree("{\"result\":500,\"message\":\"failed.\"}");
return status(500, j);
}
} catch (SQLException e){
ObjectMapper mapper = new ObjectMapper();
JsonNode j = mapper.readTree("{\"result\":500,\"message\":\""+e.getMessage()+"\"}");
return status(500, j);
}
}
}
| 36.443182 | 116 | 0.587153 |
1a854a63f37e70d3ae207b65ad2de0e722729a4e | 12,937 | /*
* 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.geode.connectors.jdbc.internal.cli;
import static org.apache.geode.cache.Region.SEPARATOR;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;
import org.apache.geode.cache.configuration.CacheConfig;
import org.apache.geode.cache.configuration.CacheConfig.AsyncEventQueue;
import org.apache.geode.cache.configuration.CacheElement;
import org.apache.geode.cache.configuration.DeclarableType;
import org.apache.geode.cache.configuration.RegionAttributesDataPolicy;
import org.apache.geode.cache.configuration.RegionAttributesType;
import org.apache.geode.cache.configuration.RegionConfig;
import org.apache.geode.connectors.jdbc.JdbcWriter;
import org.apache.geode.connectors.jdbc.internal.configuration.RegionMapping;
import org.apache.geode.distributed.ConfigurationPersistenceService;
import org.apache.geode.distributed.internal.membership.InternalDistributedMember;
import org.apache.geode.internal.cache.InternalCache;
import org.apache.geode.management.cli.Result;
import org.apache.geode.management.internal.cli.result.model.ResultModel;
import org.apache.geode.management.internal.functions.CliFunctionResult;
public class DestroyMappingCommandTest {
private InternalCache cache;
private DestroyMappingCommand destroyRegionMappingCommand;
private String regionName;
private Set<InternalDistributedMember> members;
private List<CliFunctionResult> results;
private CliFunctionResult successFunctionResult;
private CacheConfig cacheConfig;
RegionConfig matchingRegion;
RegionAttributesType matchingRegionAttributes;
@Before
public void setup() {
regionName = "regionName";
cache = mock(InternalCache.class);
members = new HashSet<>();
members.add(mock(InternalDistributedMember.class));
destroyRegionMappingCommand = spy(DestroyMappingCommand.class);
destroyRegionMappingCommand.setCache(cache);
results = new ArrayList<>();
successFunctionResult = mock(CliFunctionResult.class);
when(successFunctionResult.isSuccessful()).thenReturn(true);
doReturn(results).when(destroyRegionMappingCommand).executeAndGetFunctionResult(any(), any(),
any());
doReturn(members).when(destroyRegionMappingCommand).findMembers(null, null);
cacheConfig = mock(CacheConfig.class);
matchingRegion = mock(RegionConfig.class);
when(matchingRegion.getName()).thenReturn(regionName);
matchingRegionAttributes = mock(RegionAttributesType.class);
when(matchingRegionAttributes.getDataPolicy()).thenReturn(RegionAttributesDataPolicy.REPLICATE);
when(matchingRegion.getRegionAttributes()).thenReturn(matchingRegionAttributes);
}
@Test
public void destroyMappingGivenARegionNameForServerGroup() throws PreconditionException {
ConfigurationPersistenceService service = mock(ConfigurationPersistenceService.class);
doReturn(service).when(destroyRegionMappingCommand).checkForClusterConfiguration();
when(service.getCacheConfig("testGroup1")).thenReturn(cacheConfig);
List<RegionConfig> list = new ArrayList<>();
RegionConfig region = mock(RegionConfig.class);
List<CacheElement> listCacheElements = new ArrayList<>();
RegionMapping mapping = mock(RegionMapping.class);
listCacheElements.add(mapping);
when(region.getCustomRegionElements()).thenReturn(listCacheElements);
list.add(region);
when(cacheConfig.getRegions()).thenReturn(list);
doReturn(members).when(destroyRegionMappingCommand).findMembers(new String[] {"testGroup1"},
null);
results.add(successFunctionResult);
ResultModel result =
destroyRegionMappingCommand.destroyMapping(regionName, new String[] {"testGroup1"});
assertThat(result.getStatus()).isSameAs(Result.Status.OK);
assertThat(result.getConfigObject()).isEqualTo(regionName);
}
@Test
public void destroyMappingGivenARegionNameReturnsTheNameAsTheConfigObject()
throws PreconditionException {
ConfigurationPersistenceService service = mock(ConfigurationPersistenceService.class);
doReturn(service).when(destroyRegionMappingCommand).checkForClusterConfiguration();
when(service.getCacheConfig("cluster")).thenReturn(cacheConfig);
List<RegionConfig> list = new ArrayList<>();
RegionConfig region = mock(RegionConfig.class);
List<CacheElement> listCacheElements = new ArrayList<>();
RegionMapping mapping = mock(RegionMapping.class);
listCacheElements.add(mapping);
when(region.getCustomRegionElements()).thenReturn(listCacheElements);
list.add(region);
when(cacheConfig.getRegions()).thenReturn(list);
results.add(successFunctionResult);
ResultModel result = destroyRegionMappingCommand.destroyMapping(regionName, null);
assertThat(result.getStatus()).isSameAs(Result.Status.OK);
assertThat(result.getConfigObject()).isEqualTo(regionName);
}
@Test
public void destroyMappingGivenARegionPathReturnsTheNoSlashRegionNameAsTheConfigObject()
throws PreconditionException {
ConfigurationPersistenceService service = mock(ConfigurationPersistenceService.class);
doReturn(service).when(destroyRegionMappingCommand).checkForClusterConfiguration();
when(service.getCacheConfig("cluster")).thenReturn(cacheConfig);
List<RegionConfig> list = new ArrayList<>();
RegionConfig region = mock(RegionConfig.class);
List<CacheElement> listCacheElements = new ArrayList<>();
RegionMapping mapping = mock(RegionMapping.class);
listCacheElements.add(mapping);
when(region.getCustomRegionElements()).thenReturn(listCacheElements);
list.add(region);
when(cacheConfig.getRegions()).thenReturn(list);
results.add(successFunctionResult);
ResultModel result = destroyRegionMappingCommand.destroyMapping(SEPARATOR + regionName, null);
verify(destroyRegionMappingCommand, times(1)).executeAndGetFunctionResult(any(), eq(regionName),
any());
assertThat(result.getStatus()).isSameAs(Result.Status.OK);
assertThat(result.getConfigObject()).isEqualTo(regionName);
}
@Test
public void updateClusterConfigWithNoRegionsDoesNotThrowException() {
when(cacheConfig.getRegions()).thenReturn(Collections.emptyList());
boolean modified =
destroyRegionMappingCommand.updateConfigForGroup(null, cacheConfig, regionName);
assertThat(modified).isFalse();
}
@Test
public void updateClusterConfigWithOneNonMatchingRegionDoesNotRemoveMapping() {
List<RegionConfig> list = new ArrayList<>();
RegionConfig nonMatchingRegion = mock(RegionConfig.class);
when(nonMatchingRegion.getName()).thenReturn("nonMatchingRegion");
List<CacheElement> listCacheElements = new ArrayList<>();
RegionMapping nonMatchingMapping = mock(RegionMapping.class);
listCacheElements.add(nonMatchingMapping);
when(nonMatchingRegion.getCustomRegionElements()).thenReturn(listCacheElements);
list.add(nonMatchingRegion);
when(cacheConfig.getRegions()).thenReturn(list);
boolean modified =
destroyRegionMappingCommand.updateConfigForGroup(null, cacheConfig, regionName);
assertThat(listCacheElements).isEqualTo(Arrays.asList(nonMatchingMapping));
assertThat(modified).isFalse();
}
@Test
public void updateClusterConfigWithOneMatchingRegionDoesRemoveMapping() {
List<RegionConfig> list = new ArrayList<>();
List<CacheElement> listCacheElements = new ArrayList<>();
RegionMapping matchingMapping = mock(RegionMapping.class);
listCacheElements.add(matchingMapping);
when(matchingRegion.getCustomRegionElements()).thenReturn(listCacheElements);
list.add(matchingRegion);
when(cacheConfig.getRegions()).thenReturn(list);
boolean modified =
destroyRegionMappingCommand.updateConfigForGroup(null, cacheConfig, regionName);
assertThat(listCacheElements).isEmpty();
assertThat(modified).isTrue();
}
@Test
public void updateClusterConfigWithOneMatchingRegionAndJdbcAsyncQueueRemovesTheQueue() {
List<RegionConfig> list = new ArrayList<>();
List<CacheElement> listCacheElements = new ArrayList<>();
RegionMapping matchingMapping = mock(RegionMapping.class);
listCacheElements.add(matchingMapping);
when(matchingRegion.getCustomRegionElements()).thenReturn(listCacheElements);
list.add(matchingRegion);
when(cacheConfig.getRegions()).thenReturn(list);
AsyncEventQueue queue = mock(AsyncEventQueue.class);
String queueName = MappingCommandUtils.createAsyncEventQueueName(regionName);
when(queue.getId()).thenReturn(queueName);
List<AsyncEventQueue> queueList = new ArrayList<>();
queueList.add(queue);
when(cacheConfig.getAsyncEventQueues()).thenReturn(queueList);
boolean modified =
destroyRegionMappingCommand.updateConfigForGroup(null, cacheConfig, regionName);
assertThat(queueList).isEmpty();
assertThat(modified).isTrue();
}
@Test
public void updateClusterConfigWithOneMatchingRegionAndJdbcWriterRemovesTheWriter() {
List<RegionConfig> list = new ArrayList<>();
List<CacheElement> listCacheElements = new ArrayList<>();
RegionMapping matchingMapping = mock(RegionMapping.class);
listCacheElements.add(matchingMapping);
when(matchingRegion.getCustomRegionElements()).thenReturn(listCacheElements);
list.add(matchingRegion);
when(cacheConfig.getRegions()).thenReturn(list);
DeclarableType cacheWriter = mock(DeclarableType.class);
when(cacheWriter.getClassName()).thenReturn(JdbcWriter.class.getName());
when(matchingRegionAttributes.getCacheWriter()).thenReturn(cacheWriter);
boolean modified =
destroyRegionMappingCommand.updateConfigForGroup(null, cacheConfig, regionName);
verify(matchingRegionAttributes, times(1)).setCacheWriter(null);
assertThat(modified).isTrue();
}
@Test
public void updateClusterConfigWithOneMatchingRegionAndJdbcAsyncQueueIdRemovesTheId() {
List<RegionConfig> list = new ArrayList<>();
List<CacheElement> listCacheElements = new ArrayList<>();
RegionMapping matchingMapping = mock(RegionMapping.class);
listCacheElements.add(matchingMapping);
when(matchingRegion.getCustomRegionElements()).thenReturn(listCacheElements);
list.add(matchingRegion);
when(cacheConfig.getRegions()).thenReturn(list);
String queueName = MappingCommandUtils.createAsyncEventQueueName(regionName);
when(matchingRegionAttributes.getAsyncEventQueueIds()).thenReturn(queueName);
boolean modified =
destroyRegionMappingCommand.updateConfigForGroup(null, cacheConfig, regionName);
verify(matchingRegionAttributes, times(1)).setAsyncEventQueueIds("");
assertThat(modified).isTrue();
}
@Test
public void updateClusterConfigWithOneMatchingRegionAndJdbcAsyncQueueIdsRemovesTheId() {
List<RegionConfig> list = new ArrayList<>();
List<CacheElement> listCacheElements = new ArrayList<>();
RegionMapping matchingMapping = mock(RegionMapping.class);
listCacheElements.add(matchingMapping);
when(matchingRegion.getCustomRegionElements()).thenReturn(listCacheElements);
list.add(matchingRegion);
when(cacheConfig.getRegions()).thenReturn(list);
String queueName = MappingCommandUtils.createAsyncEventQueueName(regionName);
when(matchingRegionAttributes.getAsyncEventQueueIds())
.thenReturn(queueName + "1," + queueName + "," + queueName + "2");
boolean modified =
destroyRegionMappingCommand.updateConfigForGroup(null, cacheConfig, regionName);
verify(matchingRegionAttributes, times(1))
.setAsyncEventQueueIds(queueName + "1," + queueName + "2");
assertThat(modified).isTrue();
}
}
| 44.304795 | 100 | 0.780011 |
60d16a9813f164240197634a01988e01716a86d6 | 49,758 | /**
*
* 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.hadoop.hbase.client;
// DO NOT MAKE USE OF THESE IMPORTS! THEY ARE HERE FOR COPROCESSOR ENDPOINTS ONLY.
// Internally, we use shaded protobuf. This below are part of our public API.
//SEE ABOVE NOTE!
import com.google.protobuf.Descriptors;
import com.google.protobuf.Message;
import com.google.protobuf.Service;
import com.google.protobuf.ServiceException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.CompareOperator;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HRegionLocation;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.io.TimeRange;
import org.apache.yetus.audience.InterfaceAudience;
import org.apache.yetus.audience.InterfaceStability;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.hbase.client.coprocessor.Batch;
import org.apache.hadoop.hbase.client.coprocessor.Batch.Callback;
import org.apache.hadoop.hbase.filter.BinaryComparator;
import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;
import org.apache.hadoop.hbase.ipc.CoprocessorRpcChannel;
import org.apache.hadoop.hbase.ipc.RpcControllerFactory;
import org.apache.hbase.thirdparty.com.google.common.annotations.VisibleForTesting;
import org.apache.hbase.thirdparty.com.google.common.base.Preconditions;
import org.apache.hadoop.hbase.shaded.protobuf.ProtobufUtil;
import org.apache.hadoop.hbase.shaded.protobuf.RequestConverter;
import org.apache.hadoop.hbase.shaded.protobuf.ResponseConverter;
import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos;
import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos.MultiRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos.MutateRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos.MutateResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos.RegionAction;
import org.apache.hadoop.hbase.shaded.protobuf.generated.HBaseProtos.CompareType;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.Pair;
import org.apache.hadoop.hbase.util.ReflectionUtils;
import org.apache.hadoop.hbase.util.Threads;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import static org.apache.hadoop.hbase.client.ConnectionUtils.checkHasFamilies;
/**
* An implementation of {@link Table}. Used to communicate with a single HBase table.
* Lightweight. Get as needed and just close when done.
* Instances of this class SHOULD NOT be constructed directly.
* Obtain an instance via {@link Connection}. See {@link ConnectionFactory}
* class comment for an example of how.
*
* <p>This class is thread safe since 2.0.0 if not invoking any of the setter methods.
* All setters are moved into {@link TableBuilder} and reserved here only for keeping
* backward compatibility, and TODO will be removed soon.
*
* <p>HTable is no longer a client API. Use {@link Table} instead. It is marked
* InterfaceAudience.Private indicating that this is an HBase-internal class as defined in
* <a href="https://hadoop.apache.org/docs/current/hadoop-project-dist/hadoop-common/InterfaceClassification.html">Hadoop
* Interface Classification</a>
* There are no guarantees for backwards source / binary compatibility and methods or class can
* change or go away without deprecation.
*
* @see Table
* @see Admin
* @see Connection
* @see ConnectionFactory
*/
@InterfaceAudience.Private
@InterfaceStability.Stable
public class HTable implements Table {
private static final Logger LOG = LoggerFactory.getLogger(HTable.class);
private static final Consistency DEFAULT_CONSISTENCY = Consistency.STRONG;
private final ClusterConnection connection;
private final TableName tableName;
private final Configuration configuration;
private final ConnectionConfiguration connConfiguration;
private boolean closed = false;
private final int scannerCaching;
private final long scannerMaxResultSize;
private final ExecutorService pool; // For Multi & Scan
private int operationTimeoutMs; // global timeout for each blocking method with retrying rpc
private final int rpcTimeoutMs; // FIXME we should use this for rpc like batch and checkAndXXX
private int readRpcTimeoutMs; // timeout for each read rpc request
private int writeRpcTimeoutMs; // timeout for each write rpc request
private final boolean cleanupPoolOnClose; // shutdown the pool in close()
private final HRegionLocator locator;
/** The Async process for batch */
@VisibleForTesting
AsyncProcess multiAp;
private final RpcRetryingCallerFactory rpcCallerFactory;
private final RpcControllerFactory rpcControllerFactory;
// Marked Private @since 1.0
@InterfaceAudience.Private
public static ThreadPoolExecutor getDefaultExecutor(Configuration conf) {
int maxThreads = conf.getInt("hbase.htable.threads.max", Integer.MAX_VALUE);
if (maxThreads == 0) {
maxThreads = 1; // is there a better default?
}
int corePoolSize = conf.getInt("hbase.htable.threads.coresize", 1);
long keepAliveTime = conf.getLong("hbase.htable.threads.keepalivetime", 60);
// Using the "direct handoff" approach, new threads will only be created
// if it is necessary and will grow unbounded. This could be bad but in HCM
// we only create as many Runnables as there are region servers. It means
// it also scales when new region servers are added.
ThreadPoolExecutor pool = new ThreadPoolExecutor(corePoolSize, maxThreads, keepAliveTime,
TimeUnit.SECONDS, new SynchronousQueue<>(), Threads.newDaemonThreadFactory("htable"));
pool.allowCoreThreadTimeOut(true);
return pool;
}
/**
* Creates an object to access a HBase table.
* Used by HBase internally. DO NOT USE. See {@link ConnectionFactory} class comment for how to
* get a {@link Table} instance (use {@link Table} instead of {@link HTable}).
* @param connection Connection to be used.
* @param builder The table builder
* @param rpcCallerFactory The RPC caller factory
* @param rpcControllerFactory The RPC controller factory
* @param pool ExecutorService to be used.
*/
@InterfaceAudience.Private
protected HTable(final ConnectionImplementation connection,
final TableBuilderBase builder,
final RpcRetryingCallerFactory rpcCallerFactory,
final RpcControllerFactory rpcControllerFactory,
final ExecutorService pool) {
this.connection = Preconditions.checkNotNull(connection, "connection is null");
this.configuration = connection.getConfiguration();
this.connConfiguration = connection.getConnectionConfiguration();
if (pool == null) {
this.pool = getDefaultExecutor(this.configuration);
this.cleanupPoolOnClose = true;
} else {
this.pool = pool;
this.cleanupPoolOnClose = false;
}
if (rpcCallerFactory == null) {
this.rpcCallerFactory = connection.getNewRpcRetryingCallerFactory(configuration);
} else {
this.rpcCallerFactory = rpcCallerFactory;
}
if (rpcControllerFactory == null) {
this.rpcControllerFactory = RpcControllerFactory.instantiate(configuration);
} else {
this.rpcControllerFactory = rpcControllerFactory;
}
this.tableName = builder.tableName;
this.operationTimeoutMs = builder.operationTimeout;
this.rpcTimeoutMs = builder.rpcTimeout;
this.readRpcTimeoutMs = builder.readRpcTimeout;
this.writeRpcTimeoutMs = builder.writeRpcTimeout;
this.scannerCaching = connConfiguration.getScannerCaching();
this.scannerMaxResultSize = connConfiguration.getScannerMaxResultSize();
// puts need to track errors globally due to how the APIs currently work.
multiAp = this.connection.getAsyncProcess();
this.locator = new HRegionLocator(tableName, connection);
}
/**
* @return maxKeyValueSize from configuration.
*/
public static int getMaxKeyValueSize(Configuration conf) {
return conf.getInt(ConnectionConfiguration.MAX_KEYVALUE_SIZE_KEY, -1);
}
@Override
public Configuration getConfiguration() {
return configuration;
}
@Override
public TableName getName() {
return tableName;
}
/**
* <em>INTERNAL</em> Used by unit tests and tools to do low-level
* manipulations.
* @return A Connection instance.
*/
@VisibleForTesting
protected Connection getConnection() {
return this.connection;
}
@Override
@Deprecated
public HTableDescriptor getTableDescriptor() throws IOException {
HTableDescriptor htd = HBaseAdmin.getHTableDescriptor(tableName, connection, rpcCallerFactory,
rpcControllerFactory, operationTimeoutMs, readRpcTimeoutMs);
if (htd != null) {
return new ImmutableHTableDescriptor(htd);
}
return null;
}
@Override
public TableDescriptor getDescriptor() throws IOException {
return HBaseAdmin.getTableDescriptor(tableName, connection, rpcCallerFactory,
rpcControllerFactory, operationTimeoutMs, readRpcTimeoutMs);
}
/**
* Get the corresponding start keys and regions for an arbitrary range of
* keys.
* <p>
* @param startKey Starting row in range, inclusive
* @param endKey Ending row in range
* @param includeEndKey true if endRow is inclusive, false if exclusive
* @return A pair of list of start keys and list of HRegionLocations that
* contain the specified range
* @throws IOException if a remote or network exception occurs
*/
private Pair<List<byte[]>, List<HRegionLocation>> getKeysAndRegionsInRange(
final byte[] startKey, final byte[] endKey, final boolean includeEndKey)
throws IOException {
return getKeysAndRegionsInRange(startKey, endKey, includeEndKey, false);
}
/**
* Get the corresponding start keys and regions for an arbitrary range of
* keys.
* <p>
* @param startKey Starting row in range, inclusive
* @param endKey Ending row in range
* @param includeEndKey true if endRow is inclusive, false if exclusive
* @param reload true to reload information or false to use cached information
* @return A pair of list of start keys and list of HRegionLocations that
* contain the specified range
* @throws IOException if a remote or network exception occurs
*/
private Pair<List<byte[]>, List<HRegionLocation>> getKeysAndRegionsInRange(
final byte[] startKey, final byte[] endKey, final boolean includeEndKey,
final boolean reload) throws IOException {
final boolean endKeyIsEndOfTable = Bytes.equals(endKey,HConstants.EMPTY_END_ROW);
if ((Bytes.compareTo(startKey, endKey) > 0) && !endKeyIsEndOfTable) {
throw new IllegalArgumentException(
"Invalid range: " + Bytes.toStringBinary(startKey) +
" > " + Bytes.toStringBinary(endKey));
}
List<byte[]> keysInRange = new ArrayList<>();
List<HRegionLocation> regionsInRange = new ArrayList<>();
byte[] currentKey = startKey;
do {
HRegionLocation regionLocation = getRegionLocator().getRegionLocation(currentKey, reload);
keysInRange.add(currentKey);
regionsInRange.add(regionLocation);
currentKey = regionLocation.getRegionInfo().getEndKey();
} while (!Bytes.equals(currentKey, HConstants.EMPTY_END_ROW)
&& (endKeyIsEndOfTable || Bytes.compareTo(currentKey, endKey) < 0
|| (includeEndKey && Bytes.compareTo(currentKey, endKey) == 0)));
return new Pair<>(keysInRange, regionsInRange);
}
/**
* The underlying {@link HTable} must not be closed.
* {@link Table#getScanner(Scan)} has other usage details.
*/
@Override
public ResultScanner getScanner(Scan scan) throws IOException {
if (scan.getCaching() <= 0) {
scan.setCaching(scannerCaching);
}
if (scan.getMaxResultSize() <= 0) {
scan.setMaxResultSize(scannerMaxResultSize);
}
if (scan.getMvccReadPoint() > 0) {
// it is not supposed to be set by user, clear
scan.resetMvccReadPoint();
}
Boolean async = scan.isAsyncPrefetch();
if (async == null) {
async = connConfiguration.isClientScannerAsyncPrefetch();
}
if (scan.isReversed()) {
return new ReversedClientScanner(getConfiguration(), scan, getName(),
this.connection, this.rpcCallerFactory, this.rpcControllerFactory,
pool, connConfiguration.getReplicaCallTimeoutMicroSecondScan());
} else {
if (async) {
return new ClientAsyncPrefetchScanner(getConfiguration(), scan, getName(), this.connection,
this.rpcCallerFactory, this.rpcControllerFactory,
pool, connConfiguration.getReplicaCallTimeoutMicroSecondScan());
} else {
return new ClientSimpleScanner(getConfiguration(), scan, getName(), this.connection,
this.rpcCallerFactory, this.rpcControllerFactory,
pool, connConfiguration.getReplicaCallTimeoutMicroSecondScan());
}
}
}
/**
* The underlying {@link HTable} must not be closed.
* {@link Table#getScanner(byte[])} has other usage details.
*/
@Override
public ResultScanner getScanner(byte [] family) throws IOException {
Scan scan = new Scan();
scan.addFamily(family);
return getScanner(scan);
}
/**
* The underlying {@link HTable} must not be closed.
* {@link Table#getScanner(byte[], byte[])} has other usage details.
*/
@Override
public ResultScanner getScanner(byte [] family, byte [] qualifier)
throws IOException {
Scan scan = new Scan();
scan.addColumn(family, qualifier);
return getScanner(scan);
}
@Override
public Result get(final Get get) throws IOException {
return get(get, get.isCheckExistenceOnly());
}
private Result get(Get get, final boolean checkExistenceOnly) throws IOException {
// if we are changing settings to the get, clone it.
if (get.isCheckExistenceOnly() != checkExistenceOnly || get.getConsistency() == null) {
get = ReflectionUtils.newInstance(get.getClass(), get);
get.setCheckExistenceOnly(checkExistenceOnly);
if (get.getConsistency() == null){
get.setConsistency(DEFAULT_CONSISTENCY);
}
}
if (get.getConsistency() == Consistency.STRONG) {
final Get configuredGet = get;
ClientServiceCallable<Result> callable = new ClientServiceCallable<Result>(this.connection, getName(),
get.getRow(), this.rpcControllerFactory.newController(), get.getPriority()) {
@Override
protected Result rpcCall() throws Exception {
ClientProtos.GetRequest request = RequestConverter.buildGetRequest(
getLocation().getRegionInfo().getRegionName(), configuredGet);
ClientProtos.GetResponse response = doGet(request);
return response == null? null:
ProtobufUtil.toResult(response.getResult(), getRpcControllerCellScanner());
}
};
return rpcCallerFactory.<Result>newCaller(readRpcTimeoutMs).callWithRetries(callable,
this.operationTimeoutMs);
}
// Call that takes into account the replica
RpcRetryingCallerWithReadReplicas callable = new RpcRetryingCallerWithReadReplicas(
rpcControllerFactory, tableName, this.connection, get, pool,
connConfiguration.getRetriesNumber(), operationTimeoutMs, readRpcTimeoutMs,
connConfiguration.getPrimaryCallTimeoutMicroSecond());
return callable.call(operationTimeoutMs);
}
@Override
public Result[] get(List<Get> gets) throws IOException {
if (gets.size() == 1) {
return new Result[]{get(gets.get(0))};
}
try {
Object[] r1 = new Object[gets.size()];
batch((List<? extends Row>)gets, r1, readRpcTimeoutMs);
// Translate.
Result [] results = new Result[r1.length];
int i = 0;
for (Object obj: r1) {
// Batch ensures if there is a failure we get an exception instead
results[i++] = (Result)obj;
}
return results;
} catch (InterruptedException e) {
throw (InterruptedIOException)new InterruptedIOException().initCause(e);
}
}
@Override
public void batch(final List<? extends Row> actions, final Object[] results)
throws InterruptedException, IOException {
int rpcTimeout = writeRpcTimeoutMs;
boolean hasRead = false;
boolean hasWrite = false;
for (Row action : actions) {
if (action instanceof Mutation) {
hasWrite = true;
} else {
hasRead = true;
}
if (hasRead && hasWrite) {
break;
}
}
if (hasRead && !hasWrite) {
rpcTimeout = readRpcTimeoutMs;
}
batch(actions, results, rpcTimeout);
}
public void batch(final List<? extends Row> actions, final Object[] results, int rpcTimeout)
throws InterruptedException, IOException {
AsyncProcessTask task = AsyncProcessTask.newBuilder()
.setPool(pool)
.setTableName(tableName)
.setRowAccess(actions)
.setResults(results)
.setRpcTimeout(rpcTimeout)
.setOperationTimeout(operationTimeoutMs)
.setSubmittedRows(AsyncProcessTask.SubmittedRows.ALL)
.build();
AsyncRequestFuture ars = multiAp.submit(task);
ars.waitUntilDone();
if (ars.hasError()) {
throw ars.getErrors();
}
}
@Override
public <R> void batchCallback(
final List<? extends Row> actions, final Object[] results, final Batch.Callback<R> callback)
throws IOException, InterruptedException {
doBatchWithCallback(actions, results, callback, connection, pool, tableName);
}
public static <R> void doBatchWithCallback(List<? extends Row> actions, Object[] results,
Callback<R> callback, ClusterConnection connection, ExecutorService pool, TableName tableName)
throws InterruptedIOException, RetriesExhaustedWithDetailsException {
int operationTimeout = connection.getConnectionConfiguration().getOperationTimeout();
int writeTimeout = connection.getConfiguration().getInt(HConstants.HBASE_RPC_WRITE_TIMEOUT_KEY,
connection.getConfiguration().getInt(HConstants.HBASE_RPC_TIMEOUT_KEY,
HConstants.DEFAULT_HBASE_RPC_TIMEOUT));
AsyncProcessTask<R> task = AsyncProcessTask.newBuilder(callback)
.setPool(pool)
.setTableName(tableName)
.setRowAccess(actions)
.setResults(results)
.setOperationTimeout(operationTimeout)
.setRpcTimeout(writeTimeout)
.setSubmittedRows(AsyncProcessTask.SubmittedRows.ALL)
.build();
AsyncRequestFuture ars = connection.getAsyncProcess().submit(task);
ars.waitUntilDone();
if (ars.hasError()) {
throw ars.getErrors();
}
}
@Override
public void delete(final Delete delete) throws IOException {
ClientServiceCallable<Void> callable =
new ClientServiceCallable<Void>(this.connection, getName(), delete.getRow(),
this.rpcControllerFactory.newController(), delete.getPriority()) {
@Override
protected Void rpcCall() throws Exception {
MutateRequest request = RequestConverter
.buildMutateRequest(getLocation().getRegionInfo().getRegionName(), delete);
doMutate(request);
return null;
}
};
rpcCallerFactory.<Void>newCaller(this.writeRpcTimeoutMs)
.callWithRetries(callable, this.operationTimeoutMs);
}
@Override
public void delete(final List<Delete> deletes)
throws IOException {
Object[] results = new Object[deletes.size()];
try {
batch(deletes, results, writeRpcTimeoutMs);
} catch (InterruptedException e) {
throw (InterruptedIOException)new InterruptedIOException().initCause(e);
} finally {
// TODO: to be consistent with batch put(), do not modify input list
// mutate list so that it is empty for complete success, or contains only failed records
// results are returned in the same order as the requests in list walk the list backwards,
// so we can remove from list without impacting the indexes of earlier members
for (int i = results.length - 1; i>=0; i--) {
// if result is not null, it succeeded
if (results[i] instanceof Result) {
deletes.remove(i);
}
}
}
}
@Override
public void put(final Put put) throws IOException {
validatePut(put);
ClientServiceCallable<Void> callable =
new ClientServiceCallable<Void>(this.connection, getName(), put.getRow(),
this.rpcControllerFactory.newController(), put.getPriority()) {
@Override
protected Void rpcCall() throws Exception {
MutateRequest request =
RequestConverter.buildMutateRequest(getLocation().getRegionInfo().getRegionName(), put);
doMutate(request);
return null;
}
};
rpcCallerFactory.<Void> newCaller(this.writeRpcTimeoutMs).callWithRetries(callable,
this.operationTimeoutMs);
}
@Override
public void put(final List<Put> puts) throws IOException {
for (Put put : puts) {
validatePut(put);
}
Object[] results = new Object[puts.size()];
try {
batch(puts, results, writeRpcTimeoutMs);
} catch (InterruptedException e) {
throw (InterruptedIOException) new InterruptedIOException().initCause(e);
}
}
@Override
public void mutateRow(final RowMutations rm) throws IOException {
CancellableRegionServerCallable<MultiResponse> callable =
new CancellableRegionServerCallable<MultiResponse>(this.connection, getName(), rm.getRow(),
rpcControllerFactory.newController(), writeRpcTimeoutMs,
new RetryingTimeTracker().start(), rm.getMaxPriority()) {
@Override
protected MultiResponse rpcCall() throws Exception {
RegionAction.Builder regionMutationBuilder = RequestConverter.buildRegionAction(
getLocation().getRegionInfo().getRegionName(), rm);
regionMutationBuilder.setAtomic(true);
MultiRequest request =
MultiRequest.newBuilder().addRegionAction(regionMutationBuilder.build()).build();
ClientProtos.MultiResponse response = doMulti(request);
ClientProtos.RegionActionResult res = response.getRegionActionResultList().get(0);
if (res.hasException()) {
Throwable ex = ProtobufUtil.toException(res.getException());
if (ex instanceof IOException) {
throw (IOException) ex;
}
throw new IOException("Failed to mutate row: " + Bytes.toStringBinary(rm.getRow()), ex);
}
return ResponseConverter.getResults(request, response, getRpcControllerCellScanner());
}
};
AsyncProcessTask task = AsyncProcessTask.newBuilder()
.setPool(pool)
.setTableName(tableName)
.setRowAccess(rm.getMutations())
.setCallable(callable)
.setRpcTimeout(writeRpcTimeoutMs)
.setOperationTimeout(operationTimeoutMs)
.setSubmittedRows(AsyncProcessTask.SubmittedRows.ALL)
.build();
AsyncRequestFuture ars = multiAp.submit(task);
ars.waitUntilDone();
if (ars.hasError()) {
throw ars.getErrors();
}
}
@Override
public Result append(final Append append) throws IOException {
checkHasFamilies(append);
NoncedRegionServerCallable<Result> callable =
new NoncedRegionServerCallable<Result>(this.connection, getName(), append.getRow(),
this.rpcControllerFactory.newController(), append.getPriority()) {
@Override
protected Result rpcCall() throws Exception {
MutateRequest request = RequestConverter.buildMutateRequest(
getLocation().getRegionInfo().getRegionName(), append, getNonceGroup(), getNonce());
MutateResponse response = doMutate(request);
if (!response.hasResult()) return null;
return ProtobufUtil.toResult(response.getResult(), getRpcControllerCellScanner());
}
};
return rpcCallerFactory.<Result> newCaller(this.writeRpcTimeoutMs).
callWithRetries(callable, this.operationTimeoutMs);
}
@Override
public Result increment(final Increment increment) throws IOException {
checkHasFamilies(increment);
NoncedRegionServerCallable<Result> callable =
new NoncedRegionServerCallable<Result>(this.connection, getName(), increment.getRow(),
this.rpcControllerFactory.newController(), increment.getPriority()) {
@Override
protected Result rpcCall() throws Exception {
MutateRequest request = RequestConverter.buildMutateRequest(
getLocation().getRegionInfo().getRegionName(), increment, getNonceGroup(), getNonce());
MutateResponse response = doMutate(request);
// Should this check for null like append does?
return ProtobufUtil.toResult(response.getResult(), getRpcControllerCellScanner());
}
};
return rpcCallerFactory.<Result> newCaller(writeRpcTimeoutMs).callWithRetries(callable,
this.operationTimeoutMs);
}
@Override
public long incrementColumnValue(final byte [] row, final byte [] family,
final byte [] qualifier, final long amount)
throws IOException {
return incrementColumnValue(row, family, qualifier, amount, Durability.SYNC_WAL);
}
@Override
public long incrementColumnValue(final byte [] row, final byte [] family,
final byte [] qualifier, final long amount, final Durability durability)
throws IOException {
NullPointerException npe = null;
if (row == null) {
npe = new NullPointerException("row is null");
} else if (family == null) {
npe = new NullPointerException("family is null");
}
if (npe != null) {
throw new IOException(
"Invalid arguments to incrementColumnValue", npe);
}
NoncedRegionServerCallable<Long> callable =
new NoncedRegionServerCallable<Long>(this.connection, getName(), row,
this.rpcControllerFactory.newController(), HConstants.PRIORITY_UNSET) {
@Override
protected Long rpcCall() throws Exception {
MutateRequest request = RequestConverter.buildIncrementRequest(
getLocation().getRegionInfo().getRegionName(), row, family,
qualifier, amount, durability, getNonceGroup(), getNonce());
MutateResponse response = doMutate(request);
Result result = ProtobufUtil.toResult(response.getResult(), getRpcControllerCellScanner());
return Long.valueOf(Bytes.toLong(result.getValue(family, qualifier)));
}
};
return rpcCallerFactory.<Long> newCaller(this.writeRpcTimeoutMs).
callWithRetries(callable, this.operationTimeoutMs);
}
@Override
@Deprecated
public boolean checkAndPut(final byte [] row, final byte [] family, final byte [] qualifier,
final byte [] value, final Put put) throws IOException {
return doCheckAndPut(row, family, qualifier, CompareOperator.EQUAL.name(), value, null, put);
}
@Override
@Deprecated
public boolean checkAndPut(final byte [] row, final byte [] family, final byte [] qualifier,
final CompareOp compareOp, final byte [] value, final Put put) throws IOException {
return doCheckAndPut(row, family, qualifier, compareOp.name(), value, null, put);
}
@Override
@Deprecated
public boolean checkAndPut(final byte [] row, final byte [] family, final byte [] qualifier,
final CompareOperator op, final byte [] value, final Put put) throws IOException {
// The name of the operators in CompareOperator are intentionally those of the
// operators in the filter's CompareOp enum.
return doCheckAndPut(row, family, qualifier, op.name(), value, null, put);
}
private boolean doCheckAndPut(final byte[] row, final byte[] family, final byte[] qualifier,
final String opName, final byte[] value, final TimeRange timeRange, final Put put)
throws IOException {
ClientServiceCallable<Boolean> callable =
new ClientServiceCallable<Boolean>(this.connection, getName(), row,
this.rpcControllerFactory.newController(), put.getPriority()) {
@Override
protected Boolean rpcCall() throws Exception {
CompareType compareType = CompareType.valueOf(opName);
MutateRequest request = RequestConverter.buildMutateRequest(
getLocation().getRegionInfo().getRegionName(), row, family, qualifier,
new BinaryComparator(value), compareType, timeRange, put);
MutateResponse response = doMutate(request);
return Boolean.valueOf(response.getProcessed());
}
};
return rpcCallerFactory.<Boolean> newCaller(this.writeRpcTimeoutMs)
.callWithRetries(callable, this.operationTimeoutMs);
}
@Override
@Deprecated
public boolean checkAndDelete(final byte[] row, final byte[] family, final byte[] qualifier,
final byte[] value, final Delete delete) throws IOException {
return doCheckAndDelete(row, family, qualifier, CompareOperator.EQUAL.name(), value, null,
delete);
}
@Override
@Deprecated
public boolean checkAndDelete(final byte[] row, final byte[] family, final byte[] qualifier,
final CompareOp compareOp, final byte[] value, final Delete delete) throws IOException {
return doCheckAndDelete(row, family, qualifier, compareOp.name(), value, null, delete);
}
@Override
@Deprecated
public boolean checkAndDelete(final byte[] row, final byte[] family, final byte[] qualifier,
final CompareOperator op, final byte[] value, final Delete delete) throws IOException {
return doCheckAndDelete(row, family, qualifier, op.name(), value, null, delete);
}
private boolean doCheckAndDelete(final byte[] row, final byte[] family, final byte[] qualifier,
final String opName, final byte[] value, final TimeRange timeRange, final Delete delete)
throws IOException {
CancellableRegionServerCallable<SingleResponse> callable =
new CancellableRegionServerCallable<SingleResponse>(this.connection, getName(), row,
this.rpcControllerFactory.newController(), writeRpcTimeoutMs,
new RetryingTimeTracker().start(), delete.getPriority()) {
@Override
protected SingleResponse rpcCall() throws Exception {
CompareType compareType = CompareType.valueOf(opName);
MutateRequest request = RequestConverter
.buildMutateRequest(getLocation().getRegionInfo().getRegionName(), row, family,
qualifier, new BinaryComparator(value), compareType, timeRange, delete);
MutateResponse response = doMutate(request);
return ResponseConverter.getResult(request, response, getRpcControllerCellScanner());
}
};
List<Delete> rows = Collections.singletonList(delete);
Object[] results = new Object[1];
AsyncProcessTask task =
AsyncProcessTask.newBuilder().setPool(pool).setTableName(tableName).setRowAccess(rows)
.setCallable(callable)
// TODO any better timeout?
.setRpcTimeout(Math.max(readRpcTimeoutMs, writeRpcTimeoutMs))
.setOperationTimeout(operationTimeoutMs)
.setSubmittedRows(AsyncProcessTask.SubmittedRows.ALL).setResults(results).build();
AsyncRequestFuture ars = multiAp.submit(task);
ars.waitUntilDone();
if (ars.hasError()) {
throw ars.getErrors();
}
return ((SingleResponse.Entry) results[0]).isProcessed();
}
@Override
public CheckAndMutateBuilder checkAndMutate(byte[] row, byte[] family) {
return new CheckAndMutateBuilderImpl(row, family);
}
private boolean doCheckAndMutate(final byte[] row, final byte[] family, final byte[] qualifier,
final String opName, final byte[] value, final TimeRange timeRange, final RowMutations rm)
throws IOException {
CancellableRegionServerCallable<MultiResponse> callable =
new CancellableRegionServerCallable<MultiResponse>(connection, getName(), rm.getRow(),
rpcControllerFactory.newController(), writeRpcTimeoutMs, new RetryingTimeTracker().start(),
rm.getMaxPriority()) {
@Override
protected MultiResponse rpcCall() throws Exception {
CompareType compareType = CompareType.valueOf(opName);
MultiRequest request = RequestConverter
.buildMutateRequest(getLocation().getRegionInfo().getRegionName(), row, family, qualifier,
new BinaryComparator(value), compareType, timeRange, rm);
ClientProtos.MultiResponse response = doMulti(request);
ClientProtos.RegionActionResult res = response.getRegionActionResultList().get(0);
if (res.hasException()) {
Throwable ex = ProtobufUtil.toException(res.getException());
if (ex instanceof IOException) {
throw (IOException) ex;
}
throw new IOException(
"Failed to checkAndMutate row: " + Bytes.toStringBinary(rm.getRow()), ex);
}
return ResponseConverter.getResults(request, response, getRpcControllerCellScanner());
}
};
/**
* Currently, we use one array to store 'processed' flag which is returned by server.
* It is excessive to send such a large array, but that is required by the framework right now
* */
Object[] results = new Object[rm.getMutations().size()];
AsyncProcessTask task = AsyncProcessTask.newBuilder()
.setPool(pool)
.setTableName(tableName)
.setRowAccess(rm.getMutations())
.setResults(results)
.setCallable(callable)
// TODO any better timeout?
.setRpcTimeout(Math.max(readRpcTimeoutMs, writeRpcTimeoutMs))
.setOperationTimeout(operationTimeoutMs)
.setSubmittedRows(AsyncProcessTask.SubmittedRows.ALL)
.build();
AsyncRequestFuture ars = multiAp.submit(task);
ars.waitUntilDone();
if (ars.hasError()) {
throw ars.getErrors();
}
return ((Result)results[0]).getExists();
}
@Override
@Deprecated
public boolean checkAndMutate(final byte [] row, final byte [] family, final byte [] qualifier,
final CompareOp compareOp, final byte [] value, final RowMutations rm)
throws IOException {
return doCheckAndMutate(row, family, qualifier, compareOp.name(), value, null, rm);
}
@Override
@Deprecated
public boolean checkAndMutate(final byte [] row, final byte [] family, final byte [] qualifier,
final CompareOperator op, final byte [] value, final RowMutations rm) throws IOException {
return doCheckAndMutate(row, family, qualifier, op.name(), value, null, rm);
}
@Override
public boolean exists(final Get get) throws IOException {
Result r = get(get, true);
assert r.getExists() != null;
return r.getExists();
}
@Override
public boolean[] exists(List<Get> gets) throws IOException {
if (gets.isEmpty()) return new boolean[]{};
if (gets.size() == 1) return new boolean[]{exists(gets.get(0))};
ArrayList<Get> exists = new ArrayList<>(gets.size());
for (Get g: gets){
Get ge = new Get(g);
ge.setCheckExistenceOnly(true);
exists.add(ge);
}
Object[] r1= new Object[exists.size()];
try {
batch(exists, r1, readRpcTimeoutMs);
} catch (InterruptedException e) {
throw (InterruptedIOException)new InterruptedIOException().initCause(e);
}
// translate.
boolean[] results = new boolean[r1.length];
int i = 0;
for (Object o : r1) {
// batch ensures if there is a failure we get an exception instead
results[i++] = ((Result)o).getExists();
}
return results;
}
/**
* Process a mixed batch of Get, Put and Delete actions. All actions for a
* RegionServer are forwarded in one RPC call. Queries are executed in parallel.
*
* @param list The collection of actions.
* @param results An empty array, same size as list. If an exception is thrown,
* you can test here for partial results, and to determine which actions
* processed successfully.
* @throws IOException if there are problems talking to META. Per-item
* exceptions are stored in the results array.
*/
public <R> void processBatchCallback(
final List<? extends Row> list, final Object[] results, final Batch.Callback<R> callback)
throws IOException, InterruptedException {
this.batchCallback(list, results, callback);
}
@Override
public void close() throws IOException {
if (this.closed) {
return;
}
if (cleanupPoolOnClose) {
this.pool.shutdown();
try {
boolean terminated = false;
do {
// wait until the pool has terminated
terminated = this.pool.awaitTermination(60, TimeUnit.SECONDS);
} while (!terminated);
} catch (InterruptedException e) {
this.pool.shutdownNow();
LOG.warn("waitForTermination interrupted");
}
}
this.closed = true;
}
// validate for well-formedness
private void validatePut(final Put put) throws IllegalArgumentException {
ConnectionUtils.validatePut(put, connConfiguration.getMaxKeyValueSize());
}
/**
* The pool is used for mutli requests for this HTable
* @return the pool used for mutli
*/
ExecutorService getPool() {
return this.pool;
}
/**
* Explicitly clears the region cache to fetch the latest value from META.
* This is a power user function: avoid unless you know the ramifications.
*/
public void clearRegionCache() {
this.connection.clearRegionLocationCache();
}
@Override
public CoprocessorRpcChannel coprocessorService(byte[] row) {
return new RegionCoprocessorRpcChannel(connection, tableName, row);
}
@Override
public <T extends Service, R> Map<byte[],R> coprocessorService(final Class<T> service,
byte[] startKey, byte[] endKey, final Batch.Call<T,R> callable)
throws ServiceException, Throwable {
final Map<byte[],R> results = Collections.synchronizedMap(
new TreeMap<byte[], R>(Bytes.BYTES_COMPARATOR));
coprocessorService(service, startKey, endKey, callable, new Batch.Callback<R>() {
@Override
public void update(byte[] region, byte[] row, R value) {
if (region != null) {
results.put(region, value);
}
}
});
return results;
}
@Override
public <T extends Service, R> void coprocessorService(final Class<T> service,
byte[] startKey, byte[] endKey, final Batch.Call<T,R> callable,
final Batch.Callback<R> callback) throws ServiceException, Throwable {
// get regions covered by the row range
List<byte[]> keys = getStartKeysInRange(startKey, endKey);
Map<byte[],Future<R>> futures = new TreeMap<>(Bytes.BYTES_COMPARATOR);
for (final byte[] r : keys) {
final RegionCoprocessorRpcChannel channel =
new RegionCoprocessorRpcChannel(connection, tableName, r);
Future<R> future = pool.submit(new Callable<R>() {
@Override
public R call() throws Exception {
T instance =
org.apache.hadoop.hbase.protobuf.ProtobufUtil.newServiceStub(service, channel);
R result = callable.call(instance);
byte[] region = channel.getLastRegion();
if (callback != null) {
callback.update(region, r, result);
}
return result;
}
});
futures.put(r, future);
}
for (Map.Entry<byte[],Future<R>> e : futures.entrySet()) {
try {
e.getValue().get();
} catch (ExecutionException ee) {
LOG.warn("Error calling coprocessor service " + service.getName() + " for row "
+ Bytes.toStringBinary(e.getKey()), ee);
throw ee.getCause();
} catch (InterruptedException ie) {
throw new InterruptedIOException("Interrupted calling coprocessor service "
+ service.getName() + " for row " + Bytes.toStringBinary(e.getKey())).initCause(ie);
}
}
}
private List<byte[]> getStartKeysInRange(byte[] start, byte[] end)
throws IOException {
if (start == null) {
start = HConstants.EMPTY_START_ROW;
}
if (end == null) {
end = HConstants.EMPTY_END_ROW;
}
return getKeysAndRegionsInRange(start, end, true).getFirst();
}
@Override
public long getRpcTimeout(TimeUnit unit) {
return unit.convert(rpcTimeoutMs, TimeUnit.MILLISECONDS);
}
@Override
@Deprecated
public int getRpcTimeout() {
return rpcTimeoutMs;
}
@Override
@Deprecated
public void setRpcTimeout(int rpcTimeout) {
setReadRpcTimeout(rpcTimeout);
setWriteRpcTimeout(rpcTimeout);
}
@Override
public long getReadRpcTimeout(TimeUnit unit) {
return unit.convert(readRpcTimeoutMs, TimeUnit.MILLISECONDS);
}
@Override
@Deprecated
public int getReadRpcTimeout() {
return readRpcTimeoutMs;
}
@Override
@Deprecated
public void setReadRpcTimeout(int readRpcTimeout) {
this.readRpcTimeoutMs = readRpcTimeout;
}
@Override
public long getWriteRpcTimeout(TimeUnit unit) {
return unit.convert(writeRpcTimeoutMs, TimeUnit.MILLISECONDS);
}
@Override
@Deprecated
public int getWriteRpcTimeout() {
return writeRpcTimeoutMs;
}
@Override
@Deprecated
public void setWriteRpcTimeout(int writeRpcTimeout) {
this.writeRpcTimeoutMs = writeRpcTimeout;
}
@Override
public long getOperationTimeout(TimeUnit unit) {
return unit.convert(operationTimeoutMs, TimeUnit.MILLISECONDS);
}
@Override
@Deprecated
public int getOperationTimeout() {
return operationTimeoutMs;
}
@Override
@Deprecated
public void setOperationTimeout(int operationTimeout) {
this.operationTimeoutMs = operationTimeout;
}
@Override
public String toString() {
return tableName + ";" + connection;
}
@Override
public <R extends Message> Map<byte[], R> batchCoprocessorService(
Descriptors.MethodDescriptor methodDescriptor, Message request,
byte[] startKey, byte[] endKey, R responsePrototype) throws ServiceException, Throwable {
final Map<byte[], R> results = Collections.synchronizedMap(new TreeMap<byte[], R>(
Bytes.BYTES_COMPARATOR));
batchCoprocessorService(methodDescriptor, request, startKey, endKey, responsePrototype,
new Callback<R>() {
@Override
public void update(byte[] region, byte[] row, R result) {
if (region != null) {
results.put(region, result);
}
}
});
return results;
}
@Override
public <R extends Message> void batchCoprocessorService(
final Descriptors.MethodDescriptor methodDescriptor, final Message request,
byte[] startKey, byte[] endKey, final R responsePrototype, final Callback<R> callback)
throws ServiceException, Throwable {
if (startKey == null) {
startKey = HConstants.EMPTY_START_ROW;
}
if (endKey == null) {
endKey = HConstants.EMPTY_END_ROW;
}
// get regions covered by the row range
Pair<List<byte[]>, List<HRegionLocation>> keysAndRegions =
getKeysAndRegionsInRange(startKey, endKey, true);
List<byte[]> keys = keysAndRegions.getFirst();
List<HRegionLocation> regions = keysAndRegions.getSecond();
// check if we have any calls to make
if (keys.isEmpty()) {
LOG.info("No regions were selected by key range start=" + Bytes.toStringBinary(startKey) +
", end=" + Bytes.toStringBinary(endKey));
return;
}
List<RegionCoprocessorServiceExec> execs = new ArrayList<>(keys.size());
final Map<byte[], RegionCoprocessorServiceExec> execsByRow = new TreeMap<>(Bytes.BYTES_COMPARATOR);
for (int i = 0; i < keys.size(); i++) {
final byte[] rowKey = keys.get(i);
final byte[] region = regions.get(i).getRegionInfo().getRegionName();
RegionCoprocessorServiceExec exec =
new RegionCoprocessorServiceExec(region, rowKey, methodDescriptor, request);
execs.add(exec);
execsByRow.put(rowKey, exec);
}
// tracking for any possible deserialization errors on success callback
// TODO: it would be better to be able to reuse AsyncProcess.BatchErrors here
final List<Throwable> callbackErrorExceptions = new ArrayList<>();
final List<Row> callbackErrorActions = new ArrayList<>();
final List<String> callbackErrorServers = new ArrayList<>();
Object[] results = new Object[execs.size()];
AsyncProcess asyncProcess = new AsyncProcess(connection, configuration,
RpcRetryingCallerFactory.instantiate(configuration, connection.getStatisticsTracker()),
RpcControllerFactory.instantiate(configuration));
Callback<ClientProtos.CoprocessorServiceResult> resultsCallback
= (byte[] region, byte[] row, ClientProtos.CoprocessorServiceResult serviceResult) -> {
if (LOG.isTraceEnabled()) {
LOG.trace("Received result for endpoint " + methodDescriptor.getFullName() +
": region=" + Bytes.toStringBinary(region) +
", row=" + Bytes.toStringBinary(row) +
", value=" + serviceResult.getValue().getValue());
}
try {
Message.Builder builder = responsePrototype.newBuilderForType();
org.apache.hadoop.hbase.protobuf.ProtobufUtil.mergeFrom(builder,
serviceResult.getValue().getValue().toByteArray());
callback.update(region, row, (R) builder.build());
} catch (IOException e) {
LOG.error("Unexpected response type from endpoint " + methodDescriptor.getFullName(),
e);
callbackErrorExceptions.add(e);
callbackErrorActions.add(execsByRow.get(row));
callbackErrorServers.add("null");
}
};
AsyncProcessTask<ClientProtos.CoprocessorServiceResult> task =
AsyncProcessTask.newBuilder(resultsCallback)
.setPool(pool)
.setTableName(tableName)
.setRowAccess(execs)
.setResults(results)
.setRpcTimeout(readRpcTimeoutMs)
.setOperationTimeout(operationTimeoutMs)
.setSubmittedRows(AsyncProcessTask.SubmittedRows.ALL)
.build();
AsyncRequestFuture future = asyncProcess.submit(task);
future.waitUntilDone();
if (future.hasError()) {
throw future.getErrors();
} else if (!callbackErrorExceptions.isEmpty()) {
throw new RetriesExhaustedWithDetailsException(callbackErrorExceptions, callbackErrorActions,
callbackErrorServers);
}
}
public RegionLocator getRegionLocator() {
return this.locator;
}
private class CheckAndMutateBuilderImpl implements CheckAndMutateBuilder {
private final byte[] row;
private final byte[] family;
private byte[] qualifier;
private TimeRange timeRange;
private CompareOperator op;
private byte[] value;
CheckAndMutateBuilderImpl(byte[] row, byte[] family) {
this.row = Preconditions.checkNotNull(row, "row is null");
this.family = Preconditions.checkNotNull(family, "family is null");
}
@Override
public CheckAndMutateBuilder qualifier(byte[] qualifier) {
this.qualifier = Preconditions.checkNotNull(qualifier, "qualifier is null. Consider using" +
" an empty byte array, or just do not call this method if you want a null qualifier");
return this;
}
@Override
public CheckAndMutateBuilder timeRange(TimeRange timeRange) {
this.timeRange = timeRange;
return this;
}
@Override
public CheckAndMutateBuilder ifNotExists() {
this.op = CompareOperator.EQUAL;
this.value = null;
return this;
}
@Override
public CheckAndMutateBuilder ifMatches(CompareOperator compareOp, byte[] value) {
this.op = Preconditions.checkNotNull(compareOp, "compareOp is null");
this.value = Preconditions.checkNotNull(value, "value is null");
return this;
}
private void preCheck() {
Preconditions.checkNotNull(op, "condition is null. You need to specify the condition by" +
" calling ifNotExists/ifEquals/ifMatches before executing the request");
}
@Override
public boolean thenPut(Put put) throws IOException {
validatePut(put);
preCheck();
return doCheckAndPut(row, family, qualifier, op.name(), value, timeRange, put);
}
@Override
public boolean thenDelete(Delete delete) throws IOException {
preCheck();
return doCheckAndDelete(row, family, qualifier, op.name(), value, timeRange, delete);
}
@Override
public boolean thenMutate(RowMutations mutation) throws IOException {
preCheck();
return doCheckAndMutate(row, family, qualifier, op.name(), value, timeRange, mutation);
}
}
}
| 39.334387 | 121 | 0.702621 |
7356e5de0137f7713be42bbb0cd6b1d235b31d11 | 1,711 | package org.ethereum.beacon.ssz.access.list;
import java.lang.reflect.Array;
import java.util.List;
import org.ethereum.beacon.ssz.access.SSZField;
import org.ethereum.beacon.ssz.type.SSZType;
public class ArrayAccessor extends AbstractListAccessor {
@Override
public boolean isSupported(SSZField field) {
return field.getRawClass().isArray();
}
@Override
public int getChildrenCount(Object complexObject) {
return Array.getLength(complexObject);
}
@Override
public Object getChildValue(Object complexObject, int index) {
return Array.get(complexObject, index);
}
@Override
public SSZField getListElementType(SSZField listTypeDescriptor) {
return new SSZField(listTypeDescriptor.getRawClass().getComponentType());
}
@Override
public ListInstanceBuilder createInstanceBuilder(SSZType sszType) {
SSZField compositeDescriptor = sszType.getTypeDescriptor();
return new SimpleInstanceBuilder() {
@Override
protected Object buildImpl(List<Object> children) {
if (!getListElementType(compositeDescriptor).getRawClass().isPrimitive()) {
return children.toArray((Object[]) Array.newInstance(
getListElementType(compositeDescriptor).getRawClass(),children.size()));
} else {
if (getListElementType(compositeDescriptor).getRawClass() == byte.class) {
Object ret = Array.newInstance(byte.class);
for (int i = 0; i < children.size(); i++) {
Array.setByte(ret, i, (Byte) children.get(i));
}
return ret;
} else {
throw new UnsupportedOperationException("Not implemented yet");
}
}
}
};
}
}
| 31.109091 | 86 | 0.683226 |
9f66e18ae69b1fba4cf3796125b4ea9e08bb7b17 | 1,641 | package de.beachboys.aoc2016;
import de.beachboys.Day;
import java.util.List;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Day09 extends Day {
private Function<String, Long> getRepeatedStringLength;
public Object part1(List<String> input) {
getRepeatedStringLength = repeatedString -> (long) repeatedString.length();
return getLength(input.get(0));
}
public Object part2(List<String> input) {
getRepeatedStringLength = this::getLength;
return getLength(input.get(0));
}
private long getLength(String compressed) {
Pattern p = Pattern.compile("(\\(([0-9]+)x([0-9]+)\\)).*");
int position = 0;
while (position < compressed.length()) {
if (compressed.charAt(position) == '(') {
Matcher m = p.matcher(compressed.substring(position));
if (m.matches()) {
int markerLength = m.group(1).length();
int numCharacters = Integer.parseInt(m.group(2));
int repeat = Integer.parseInt(m.group(3));
String substringToRepeat = compressed.substring(position + markerLength, position + markerLength + numCharacters);
String followingSubstring = compressed.substring(position + markerLength + numCharacters);
return position + repeat * getRepeatedStringLength.apply(substringToRepeat) + getLength(followingSubstring);
}
} else {
position++;
}
}
return position;
}
}
| 35.673913 | 134 | 0.607556 |
2593386640d264b6bbca52420a71f8f94bc3a9d4 | 7,197 | package cz.johnyapps.jecnakvkapse.Adapters;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.util.ArrayList;
import cz.johnyapps.jecnakvkapse.Fragments.RozvrhFragment;
import cz.johnyapps.jecnakvkapse.R;
import cz.johnyapps.jecnakvkapse.Rozvrh.Den;
import cz.johnyapps.jecnakvkapse.Rozvrh.Hodina;
import cz.johnyapps.jecnakvkapse.Rozvrh.Period;
import cz.johnyapps.jecnakvkapse.Rozvrh.Predmet;
import cz.johnyapps.jecnakvkapse.Rozvrh.Rozvrh;
import cz.johnyapps.jecnakvkapse.Tools.ColorUtils;
/**
* Adapter pro rozvrh
* @see RozvrhFragment
*/
public class RozvrhAdaper {
private Context context;
private LayoutInflater inflater;
private Rozvrh rozvrh;
/**
* Inicializace
* @param context Context
* @param rozvrh Rozvrh
* @see cz.johnyapps.jecnakvkapse.Singletons.User
* @see Rozvrh
*/
public RozvrhAdaper(Context context, Rozvrh rozvrh) {
this.context = context;
inflater = LayoutInflater.from(context);
this.rozvrh = rozvrh;
}
/**
* Vytvoří rozvrh
* @param layout LinearLayout na kterém se rozvrh zobrazí
*/
public void adapt(LinearLayout layout) {
//Creating period layout
LinearLayout.LayoutParams periodLayoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
LinearLayout periodLayout = new LinearLayout(context);
periodLayout.setOrientation(LinearLayout.HORIZONTAL);
periodLayout.setLayoutParams(periodLayoutParams);
//Creating periods
for (Period period : rozvrh.getPeriods()) {
periodLayout.addView(createPeriod(period, periodLayout));
}
//Creating days
LinearLayout daysLayout = (LinearLayout) inflater.inflate(R.layout.item_rozvrh_dny, layout, false);
ArrayList<Den> dny = rozvrh.getDny();
int currentDay = rozvrh.getCurrentDay();
for (int i = 0; i < dny.size(); i++) {
boolean now = currentDay == i;
Den den = dny.get(i);
daysLayout.addView(createDen(den, now));
}
//Adding layouts
layout.removeAllViews();
layout.addView(periodLayout);
layout.addView(daysLayout);
}
/**
* Vytvoří časy hodin
* @param period Perioda
* @param parent Parent
* @return View s časem hodiny
*/
private View createPeriod(Period period, ViewGroup parent) {
View periodLayout = inflater.inflate(R.layout.item_rozvrh_period, parent, false);
TextView hodina = periodLayout.findViewById(R.id.Period_hodina);
TextView cas = periodLayout.findViewById(R.id.Period_cas);
hodina.setText(String.valueOf(period.getPoradi()));
cas.setText(period.getCas());
return periodLayout;
}
/**
* Vytvoří den
* @param den Den
* @return View se dnem
*/
private LinearLayout createDen(Den den, boolean now) {
LinearLayout.LayoutParams denLayoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);
denLayoutParams.weight = 1;
LinearLayout denLayout = new LinearLayout(context);
denLayout.setLayoutParams(denLayoutParams);
if (now) {
ArrayList<Hodina> hodiny = den.getHodiny();
int currentClass = rozvrh.getCurrentClass();
for (int i = 0; i < hodiny.size(); i++) {
now = currentClass == i;
Hodina hodina = hodiny.get(i);
denLayout.addView(createHodina(hodina, denLayout, now));
}
} else {
for (Hodina hodina : den.getHodiny()) {
denLayout.addView(createHodina(hodina, denLayout, false));
}
}
return denLayout;
}
/**
* Vytvoří hodinu
* @param hodina Hodina
* @param parent Parent
* @return View s hodinou
*/
private LinearLayout createHodina(final Hodina hodina, ViewGroup parent, boolean now) {
LinearLayout hodinaLayout = (LinearLayout) inflater.inflate(R.layout.item_rozvrh_hodina, parent, false);
int weight = 6;
if (hodina.getPredmety().size() != 0) weight /= hodina.getPredmety().size();
for (Predmet predmet : hodina.getPredmety()) {
hodinaLayout.addView(createPredmet(predmet, hodinaLayout, weight, now));
}
return hodinaLayout;
}
/**
* Vytvoří předmět
* @param predmet Předmět
* @param parent Parent
* @param weight Váha v Layoutu (Podle počtu skupin)
* @return View s předmětem
*/
private RelativeLayout createPredmet(Predmet predmet, ViewGroup parent, int weight, boolean now) {
LinearLayout.LayoutParams predmetLayoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, weight);
RelativeLayout predmetLayout = (RelativeLayout) inflater.inflate(R.layout.item_rozvrh_predmet, parent, false);
predmetLayout.setLayoutParams(predmetLayoutParams);
TextView vyucujiciTxt = predmetLayout.findViewById(R.id.Predmet_vyucujici);
TextView ucebnaTxt = predmetLayout.findViewById(R.id.Predmet_ucebna);
TextView predmetTxt = predmetLayout.findViewById(R.id.Predmet_predmet);
TextView tridaTxt = predmetLayout.findViewById(R.id.Predmet_trida);
TextView skupinaTxt = predmetLayout.findViewById(R.id.Predmet_skupina);
if (now) {
ColorUtils colorUtils = new ColorUtils();
int color = colorUtils.getColorAccent(context);
vyucujiciTxt.setTextColor(color);
ucebnaTxt.setTextColor(color);
predmetTxt.setTextColor(color);
tridaTxt.setTextColor(color);
skupinaTxt.setTextColor(color);
int clr = Color.argb(40, Color.red(color), Color.green(color), Color.blue(color));
predmetLayout.setBackgroundColor(clr);
}
if (predmet.getVyucujici() != null) {
vyucujiciTxt.setText(predmet.getVyucujici());
} else {
vyucujiciTxt.setVisibility(View.INVISIBLE);
}
if (predmet.getUcebna() != null) {
ucebnaTxt.setText(predmet.getUcebna());
} else {
ucebnaTxt.setVisibility(View.INVISIBLE);
}
if (predmet.getNazev() != null) {
predmetTxt.setText(predmet.getNazev());
} else {
predmetTxt.setVisibility(View.INVISIBLE);
}
if (predmet.getTrida() != null) {
tridaTxt.setText(predmet.getTrida());
} else {
tridaTxt.setVisibility(View.INVISIBLE);
}
if (predmet.getSkupina() != null) {
skupinaTxt.setText(predmet.getSkupina());
} else {
skupinaTxt.setVisibility(View.INVISIBLE);
}
return predmetLayout;
}
}
| 33.319444 | 159 | 0.645686 |
c7bd48b80d324dc91a63ee07ea196b4fd7b60eaa | 6,896 | /*
* Copyright 2017-2021 original authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.micronaut.email.javamail.composer;
import io.micronaut.core.annotation.NonNull;
import io.micronaut.core.util.CollectionUtils;
import io.micronaut.core.util.StringUtils;
import io.micronaut.email.Attachment;
import io.micronaut.email.Body;
import io.micronaut.email.BodyType;
import io.micronaut.email.Contact;
import io.micronaut.email.Email;
import jakarta.inject.Singleton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* {@link io.micronaut.context.annotation.DefaultImplementation} of {@link MessageComposer}.
*
* @author Sergio del Amo
* @since 1.0.0
*/
@Singleton
public class DefaultMessageComposer implements MessageComposer {
public static final String TYPE_TEXT_PLAIN_CHARSET_UTF_8 = "text/plain; charset=UTF-8";
public static final String TYPE_TEXT_HTML_CHARSET_UTF_8 = "text/html; charset=UTF-8";
private static final Logger LOG = LoggerFactory.getLogger(DefaultMessageComposer.class);
private static final String SUBTYPE_ALTERNATIVE = "alternative";
private static final EnumMap<BodyType, String> BODY_TYPES;
static {
EnumMap<BodyType, String> m = new EnumMap<>(BodyType.class);
m.put(BodyType.TEXT, TYPE_TEXT_PLAIN_CHARSET_UTF_8);
m.put(BodyType.HTML, TYPE_TEXT_HTML_CHARSET_UTF_8);
BODY_TYPES = m;
}
@Override
@NonNull
public Message compose(@NonNull Email email,
@NonNull Session session) throws MessagingException {
MimeMessage message = new MimeMessage(session);
message.setSubject(email.getSubject(), "UTF-8");
message.setFrom(contactToAddress(email.getFrom()));
if (CollectionUtils.isNotEmpty(email.getTo())) {
message.setRecipients(Message.RecipientType.TO, contactAddresses(email.getTo()));
}
if (CollectionUtils.isNotEmpty(email.getCc())) {
message.setRecipients(Message.RecipientType.CC, contactAddresses(email.getCc()));
}
if (CollectionUtils.isNotEmpty(email.getBcc())) {
message.setRecipients(Message.RecipientType.BCC, contactAddresses(email.getBcc()));
}
if (null != email.getReplyTo()) {
message.setReplyTo(contactAddresses(Stream.of(email.getReplyTo()).collect(Collectors.toList())));
}
MimeMultipart multipart = new MimeMultipart();
Body body = email.getBody();
if (body != null) {
multipart.addBodyPart(bodyPart(body));
}
for (MimeBodyPart bodyPart : attachmentBodyParts(email)) {
multipart.addBodyPart(bodyPart);
}
message.setContent(multipart);
return message;
}
@NonNull
private MimeBodyPart bodyPart(@NonNull Body body) throws MessagingException {
final MimeBodyPart mbp = new MimeBodyPart();
MimeMultipart alternativeBody = new MimeMultipart(SUBTYPE_ALTERNATIVE);
mbp.setContent(alternativeBody);
for (MimeBodyPart part : bodyParts(body)) {
alternativeBody.addBodyPart(part);
}
return mbp;
}
@NonNull
private Address[] contactAddresses(@NonNull Collection<Contact> contacts) throws AddressException {
List<Address> addressList = new ArrayList<>();
for (Contact contact : contacts) {
addressList.add(contactToAddress(contact));
}
Address[] array = new Address[addressList.size()];
addressList.toArray(array);
return array;
}
@NonNull
private static List<MimeBodyPart> bodyParts(@NonNull Body body) {
List<MimeBodyPart> result = new ArrayList<>();
for (Map.Entry<BodyType, String> entry : BODY_TYPES.entrySet()) {
body.get(entry.getKey()).ifPresent(it -> {
try {
result.add(partForContent(entry.getValue(), it));
} catch (MessagingException e) {
if (LOG.isErrorEnabled()) {
LOG.error("Messaging exception setting {} body part", entry.getValue(), e);
}
}
});
}
return result;
}
@NonNull
private static MimeBodyPart partForContent(@NonNull String type, @NonNull String content) throws MessagingException {
MimeBodyPart part = new MimeBodyPart();
part.setContent(content, type);
return part;
}
@NonNull
private List<MimeBodyPart> attachmentBodyParts(@NonNull Email email) throws MessagingException {
if (email.getAttachments() == null) {
return Collections.emptyList();
}
List<MimeBodyPart> list = new ArrayList<>();
for (Attachment attachment : email.getAttachments()) {
MimeBodyPart mimeBodyPart = attachmentBodyPart(attachment);
list.add(mimeBodyPart);
}
return list;
}
private MimeBodyPart attachmentBodyPart(@NonNull Attachment attachment) throws MessagingException {
MimeBodyPart att = new MimeBodyPart();
DataSource fds = new ByteArrayDataSource(attachment.getContent(), attachment.getContentType());
att.setDataHandler(new DataHandler(fds));
String reportName = attachment.getFilename();
att.setFileName(reportName);
return att;
}
private InternetAddress contactToAddress(Contact contact) throws AddressException {
if (StringUtils.isNotEmpty(contact.getName())) {
return InternetAddress.parse(contact.getName() + " <" + contact.getEmail() + ">")[0];
} else {
return InternetAddress.parse(contact.getEmail())[0];
}
}
}
| 38.099448 | 121 | 0.68228 |
c909b111ca864eb2d625616d34567ba06f0b948e | 1,295 |
import java.util.ArrayList;
import java.util.Scanner;
public class IndexOfSmallest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Integer>list = new ArrayList<>();
while(true){
System.out.println("Enter a number:");
int userNum = Integer.valueOf(scanner.nextLine());
if(userNum == 9999){
break;
}
list.add(userNum);
}
int smallest = list.get(0);
int index = list.size() -1;
for(int i = 0; i < list.size(); i++){
int number = list.get(i);
if(smallest > number){
smallest = number;
}
}
System.out.println("Smallest number: " + smallest);
for(int i = 0; i < list.size(); i++){
if(list.get(i) == smallest){
System.out.println("Found at index: " + i);
}
}
// implement here a program that reads user input
// until the user enters 9999
// after that, the program prints the smallest number
// and its index -- the smallest number
// might appear multiple times
}
}
| 27.553191 | 62 | 0.487259 |
60e2e2bfcaa95f37c39d143c8b05d0372d28e666 | 1,076 | // GraphicsLab01st.java
// Student starting version of the GraphicsLab01 assignment.
// Resave this program as GraphicsLab01v80 for the 80 point version.
// Repeat this process as you progress to the 90 and 100 point versions.
import java.awt.*;
import java.applet.*;
public class GraphicsLab01st extends Applet
{
public void paint(Graphics g)
{
// DRAW CUBE
g.drawRect(100, 100, 300, 300);
g.drawLine(100, 100, 200, 50);
g.drawLine(400, 100, 500, 50);
g.drawRect(200, 50, 300, 300);
g.drawLine(100, 400, 200, 350);
g.drawLine(400, 400, 500, 350);
// DRAW SPHERE
g.drawOval(150, 75, 300, 300);
g.drawOval(187, 75, 225, 300);
g.drawOval(225, 75, 150, 300);
g.drawOval(262, 75, 75, 300);
g.drawOval(150, 112, 300, 225);
g.drawOval(150, 155, 300, 150);
g.drawOval(150, 187, 300, 75);
// DRAW TRIANGLE
g.drawLine(350, 650, 950, 650);
g.drawLine(650, 650, 650, 350);
g.drawLine(350, 650, 650, 350);
g.drawLine(950, 650, 650, 350);
g.drawLine(800, 500, 350, 650);
g.drawLine(500, 500, 950, 650);
}
}
| 20.692308 | 72 | 0.643123 |
978a61330969e74e811154c88568c34e578d9533 | 2,293 | package com.bbn.akbc.evaluation.tac;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class FilterByResponseIDs {
static Set<String> responseIdInEval;
public static void main(String[] argv) throws IOException {
String strFileAllCSV = argv[0];
String strFileRespnoseIdInEval = argv[1];
String strFileCSVshrinked = argv[2];
boolean isDuplicateLinesForMultipleSourceOfError = argv[3].equals("true");
List<String> linesInAllCSV = readLinesIntoList(strFileAllCSV);
List<String> linesAllResponseIdInEval = readLinesIntoList(strFileRespnoseIdInEval);
responseIdInEval = new HashSet<String>();
for (String responseId : linesAllResponseIdInEval) {
responseIdInEval.add(responseId);
}
BufferedWriter writer = new BufferedWriter(new FileWriter(new File(strFileCSVshrinked)));
for (int i = 1; i < linesInAllCSV.size(); i++) {
// System.out.println("-> " + linesInAllCSV.get(i));
if (!linesInAllCSV.get(i).startsWith("0_")) {
continue;
}
String[] items = linesInAllCSV.get(i).split(",");
String responseID = items[0].trim();
if (responseIdInEval.contains(responseID)) {
if (!isDuplicateLinesForMultipleSourceOfError) {
writer.write(responseID + "," + items[1] + "\n");
} else {
for (int idx = 1; idx <= 4; idx++) {
if (!items[idx].trim().isEmpty()) {
writer.write(responseID + "," + items[idx] + "\n");
}
}
}
}
}
writer.close();
}
public static List<String> readLinesIntoList(String file) {
List<String> lines = new ArrayList<String>();
int nLine = 0;
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String sline;
while ((sline = reader.readLine()) != null) {
if (nLine++ % 100000 == 0) {
System.out.println("# lines read: " + nLine);
}
lines.add(sline);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
return lines;
}
}
| 27.963415 | 93 | 0.633668 |
75a64492ec8d87578273b0da6990dc35bf733204 | 264 | package ru.geekbrains.lesson8.clients;
import ru.geekbrains.lesson8.apps.ClientApp;
/**
* Java Core. Advanced level. Lesson 8
*
* @author Zurbaevi Nika
*/
public class ClientOne {
public static void main(String[] args) {
new ClientApp();
}
}
| 17.6 | 44 | 0.67803 |
c63804b5b86fab92aa5744467f8e14f495c8e983 | 2,303 | package cn.com.woong.serialdemo;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.com.woong.serialdemo.base.BaseActivity;
import cn.com.woong.serialdemo.packets.TestMsg;
import cn.com.woong.serialdemo.packets.TestPacket;
import cn.com.woong.serialdemo.utils.TestUtil;
import cn.com.woong.serialdemo.widget.TitleBarLayout;
import io.reactivex.functions.Consumer;
/**
* @author Created by wong on 2018/3/14.
*/
public class MainActivity extends BaseActivity {
@BindView(R.id.title_bar)
TitleBarLayout titleBar;
@BindView(R.id.btn_serial_open)
Button serialOpen;
@BindView(R.id.btn_serial_close)
Button serialClose;
@BindView(R.id.btn_serial_send)
Button btnSerialSend;
TestUtil mTestUtil;
@Override
protected int getLayoutId() {
return R.layout.activity_main;
}
@Override
protected void initView() {
titleBar.setTitle(getString(R.string.serial_port_debug));
mTestUtil = TestUtil.getInstance();
}
@OnClick({R.id.btn_serial_open, R.id.btn_serial_close, R.id.btn_serial_send})
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_serial_open:
mTestUtil.init();
break;
case R.id.btn_serial_close:
mTestUtil.destory();
break;
case R.id.btn_serial_send:
TestPacket testPacket = new TestPacket();
TestMsg testMsg = new TestMsg();
testPacket.serialMsg = testMsg;
mTestUtil.sendPacket(testPacket)
.compose(RxSchedulers.<TestPacket>io_main())
.subscribe(new Consumer<TestPacket>() {
@Override
public void accept(TestPacket testPacket) throws Exception {
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
}
});
default:
break;
}
}
}
| 30.302632 | 88 | 0.595745 |
c8ee1e4919df7074d3a52fb4107ceb96fac559cd | 3,004 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package nicta.com.au.patent.pac.index;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.apache.lucene.index.DocsAndPositionsEnum;
import org.apache.lucene.index.Terms;
import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.util.BytesRef;
/**
*
* @author rbouadjenek
*/
public class TermFreqVector {
private final Map<String, Integer> TermFreqVector;
public TermFreqVector(Query query) throws IOException {
TermFreqVector = new HashMap<>();
if (query instanceof BooleanQuery) {
for (BooleanClause bc : ((BooleanQuery) query).clauses()) {
TermQuery qt = (TermQuery) bc.getQuery();
TermFreqVector.put(qt.getTerm().text(), (int) qt.getBoost());
}
} else if (query instanceof TermQuery) {
TermQuery qt = (TermQuery) query;
TermFreqVector.put(qt.getTerm().text(), (int) qt.getBoost());
}
}
public TermFreqVector(Terms terms) throws IOException {
TermFreqVector = new HashMap<>();
if (terms != null && terms.size() > 0) {
TermsEnum termsEnum = terms.iterator(null); // access the terms for this field
BytesRef term;
// System.out.println("--------");
while ((term = termsEnum.next()) != null) {// explore the terms for this field
DocsAndPositionsEnum docsPosEnum = termsEnum.docsAndPositions(null, null);
docsPosEnum.nextDoc();
TermFreqVector.put(term.utf8ToString(), docsPosEnum.freq());
// System.out.print(term.utf8ToString() + " " + docsPosEnum.freq() + " positions: "); //get the term frequency in the document
for (int j = 0; j < docsPosEnum.freq(); j++) {
// System.out.print(docsPosEnum.nextPosition() + " ");
}
// System.out.println("");
// System.out.print(term.utf8ToString()+" ");
}
// System.out.println("");
// System.out.println("----------");
}
}
public int size() {
return TermFreqVector.size();
}
public Integer getFreq(String term) {
return TermFreqVector.get(term);
}
public Set<String> getTerms() {
return TermFreqVector.keySet();
}
public Collection<Integer> termFreqs() {
return TermFreqVector.values();
}
public int numberOfTerms() {
int sum = 0;
for (int i : TermFreqVector.values()) {
sum += i;
}
return sum;
}
}
| 33.377778 | 141 | 0.605526 |
9170676899e23114aae8888b61f7b5d58342c781 | 317 | package leetcode.easy;
public class LC168 {
public String convertToTitle(int columnNumber) {
String ans = "";
while(columnNumber > 0) {
columnNumber--;
ans = (char) ('A' + columnNumber % 26) + ans;
columnNumber /= 26;
}
return ans;
}
}
| 17.611111 | 57 | 0.514196 |
e8692eb05b4cdf7d4ffdd44196b93f7dbdc2e19b | 113 | package superpkg;
public class Simple {
public void moo() {
System.out.println("Simple.moo() running");
}
} | 14.125 | 45 | 0.681416 |
c158b2dcd01c3d6165cc300dc704f5eb285754e9 | 543 | package com.daycaptain.systemtest.frontend.actions;
import java.util.List;
import static com.codeborne.selenide.Condition.visible;
import static com.codeborne.selenide.Selenide.$;
public class EditBacklogItemAction extends EditInformationAction {
public EditBacklogItemAction() {
waitForLoading();
}
public List<String> getRelationNames() {
return overlay.$$("dp-relations dp-relation").texts();
}
protected void waitForLoading() {
$("dp-relations div.loading").shouldNotBe(visible);
}
}
| 23.608696 | 66 | 0.71639 |
8579563fb5adf5042cafa41e8dc69a0ad16e0751 | 977 | package io.potato.test;
import io.potato.task.PotatoTaskApplication;
import io.potato.ts.sms.SmsContent;
import io.potato.ts.sms.SmsSender;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Arrays;
/**
* author: timl
* time: 2019-4-4 10:12
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = PotatoTaskApplication.class)
public class SmsSenderTest {
@Autowired
SmsSender smsSender;
@Test
public void testSend() {
String body = "【新短信平台对接测试,共2条】今日应急专题已完成对接到资源中心新部署的短信平台,本条为测试短信1:按规格宣称,新短信平台可支持的最大短信发送并发量为2000条/秒,发送成功率99%以上。";
SmsContent smsContent = new SmsContent("13927452867", body);
smsSender.batchSendDiffSms(Arrays.asList(smsContent),
"272",
"",
null);
}
}
| 26.405405 | 118 | 0.720573 |
fb9c2401b33eb036db3af8e7e63bb02fdd1c2307 | 4,282 | /**
* Licensed to Apereo under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright ownership. Apereo
* 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 the
* following location:
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>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.apereo.portal.groups.local.searchers;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apereo.portal.EntityIdentifier;
import org.apereo.portal.IBasicEntity;
import org.apereo.portal.groups.GroupsException;
import org.apereo.portal.groups.local.ITypedEntitySearcher;
import org.apereo.portal.security.IPerson;
import org.jasig.services.persondir.IPersonAttributeDao;
import org.jasig.services.persondir.IPersonAttributes;
import org.jasig.services.persondir.support.IUsernameAttributeProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Searches the portal DB for people. Used by EntitySearcherImpl
*
* @author Alex Vigdor
*/
@Service
public class PersonDirectorySearcher implements ITypedEntitySearcher {
private static final Log log = LogFactory.getLog(PersonDirectorySearcher.class);
private final Class<? extends IBasicEntity> personEntityType = IPerson.class;
private IPersonAttributeDao personAttributeDao;
private IUsernameAttributeProvider usernameAttributeProvider;
@Autowired
public void setUsernameAttributeProvider(IUsernameAttributeProvider usernameAttributeProvider) {
this.usernameAttributeProvider = usernameAttributeProvider;
}
@Autowired
public void setPersonAttributeDao(IPersonAttributeDao personAttributeDao) {
this.personAttributeDao = personAttributeDao;
}
@Override
public EntityIdentifier[] searchForEntities(String query, int method) throws GroupsException {
switch (method) {
case IS:
{
break;
}
case STARTS_WITH:
{
query = query + IPersonAttributeDao.WILDCARD;
break;
}
case ENDS_WITH:
{
query = IPersonAttributeDao.WILDCARD + query;
break;
}
case CONTAINS:
{
query = IPersonAttributeDao.WILDCARD + query + IPersonAttributeDao.WILDCARD;
break;
}
default:
{
throw new GroupsException("Unknown search type");
}
}
log.debug("Searching for a person directory account matching query string " + query);
final String usernameAttribute = this.usernameAttributeProvider.getUsernameAttribute();
final Map<String, Object> queryMap =
Collections.<String, Object>singletonMap(usernameAttribute, query);
final Set<IPersonAttributes> results = this.personAttributeDao.getPeople(queryMap);
// create an array of EntityIdentifiers from the search results
final List<EntityIdentifier> entityIdentifiers =
new ArrayList<EntityIdentifier>(results.size());
for (final IPersonAttributes personAttributes : results) {
entityIdentifiers.add(
new EntityIdentifier(personAttributes.getName(), this.personEntityType));
}
return entityIdentifiers.toArray(new EntityIdentifier[entityIdentifiers.size()]);
}
@Override
public Class<? extends IBasicEntity> getType() {
return this.personEntityType;
}
}
| 38.927273 | 100 | 0.694302 |
f294c7d5a5b6e0525a6daf2869c4ab71939f2f7f | 1,681 | package gov.samhsa.acs.xdsb.common;
import static org.junit.Assert.*;
import gov.samhsa.acs.xdsb.common.XdsbDocumentReference;
import org.junit.BeforeClass;
import org.junit.Test;
public class XdsbDocumentReferenceTest {
private static XdsbDocumentReference xdsbDocumentReference;
private static final String DOCUMENT_UNIQUE_ID = "111";
private static final String REPOSITORY_UNIQUE_ID = "222";
@BeforeClass
public static void setUp() throws Exception {
xdsbDocumentReference = new XdsbDocumentReference(DOCUMENT_UNIQUE_ID,
REPOSITORY_UNIQUE_ID);
}
@Test
public void testToString() {
// Assert
assertEquals(REPOSITORY_UNIQUE_ID + ":" + DOCUMENT_UNIQUE_ID,
xdsbDocumentReference.toString());
}
@Test
public void testEqualsObject() {
// Arrange
XdsbDocumentReference anotherXdsbDocumentReference = new XdsbDocumentReference(
"111", "222");
XdsbDocumentReference notEqualXdsbDocumentReference = new XdsbDocumentReference(
"111", "aaa");
XdsbDocumentReference notEqualXdsbDocumentReference2 = new XdsbDocumentReference(
"aaa", "222");
// Assert
assertTrue(xdsbDocumentReference.equals(anotherXdsbDocumentReference));
assertTrue(anotherXdsbDocumentReference.equals(xdsbDocumentReference));
assertEquals(xdsbDocumentReference, anotherXdsbDocumentReference);
assertEquals(anotherXdsbDocumentReference, xdsbDocumentReference);
assertNotEquals(xdsbDocumentReference, notEqualXdsbDocumentReference);
assertNotEquals(notEqualXdsbDocumentReference, xdsbDocumentReference);
assertNotEquals(xdsbDocumentReference, notEqualXdsbDocumentReference2);
assertNotEquals(notEqualXdsbDocumentReference2, xdsbDocumentReference);
}
}
| 34.306122 | 83 | 0.813801 |
886e43e927cced5e787a6dc3fd71ca5555a9690c | 639 | package com.parkinfo.request.parkCulture;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
/**
* When I wrote this, only God and I understood what I was doing
* Now, God only knows
*
* @author cnyuchu@gmail.com
* @create 2019-09-05 17:22
**/
@Data
public class SetReadProcessRequest {
@ApiModelProperty(value = "进度id")
@NotBlank(message = "进度id不能为空")
private String id;
@ApiModelProperty(value = "阅读进度")
@NotNull(message = "阅读进度不能为空")
private BigDecimal process;
}
| 22.821429 | 64 | 0.733959 |
80d03e8408469fd2183cc8c5e30083fde4dc421c | 333 | package WebPresentationPatterns.ApplicationController;
import java.util.Map;
/**
* @author <a href="kayvanfar.sj@gmail.com">Saeed Kayvanfar</a> on 2/3/2017.
*/
public interface ApplicationController {
DomainCommand getDomainCommand (String commandString, Map params);
String getView (String commandString, Map params);
}
| 27.75 | 76 | 0.765766 |
4189c9e85261de26bc5cf6a4103bddf6dc462427 | 1,433 | package com.git.vladkudryshov.testparsejson.parser.json;
import com.git.vladkudryshov.testparsejson.parser.IUser;
import org.json.JSONObject;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
class UserJson implements IUser {
private static final String AGE = "age";
private static final String SUR_NAME = "surName";
private static final String FIRST_NAME = "firstName";
private static final String ID = "id";
private static final String LAST_SESSION = "lastSession";
private final JSONObject mUserObject;
UserJson(final JSONObject pPUserObject) {
mUserObject = pPUserObject;
}
@Override
public long getId() {
return mUserObject.optLong(ID);
}
@Override
public String getFirstName() {
return mUserObject.optString(FIRST_NAME);
}
@Override
public String getSurName() {
return mUserObject.optString(SUR_NAME);
}
@Override
public int getAge() {
return mUserObject.optInt(AGE);
}
@Override
public String getLastSession() throws ParseException {
final long dateLong = mUserObject.optLong(LAST_SESSION);
final Date date = new Date(dateLong);
final DateFormat formatter = new SimpleDateFormat("dd MMM yyyy, HH:mm:ss", Locale.ENGLISH);
return formatter.format(date);
}
}
| 26.537037 | 99 | 0.699232 |
1482ef1ded1bb16b3af0caccf2f80d3a9c96c83f | 3,555 | /*
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Distribution License v. 1.0, which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
package simple.hostedclient;
import java.net.InetAddress;
import java.net.URI;
import java.net.UnknownHostException;
import java.util.List;
import org.tempuri.*;
import xwsinterop.interoprt.*;
public class HostedClient {
private static final String PARAM_STSAddress = "STS_Endpoint_Address";
private static final String PARAM_ServiceAddress = "Service_Endpoint_Address";
private static final String PARAM_ConfigName = "Service_Endpoint_ConfigName";
private static final String featureName ="WSTRUST";
private static final String SCENARIO_1 = "Scenario_1_IssuedTokenOverTransport_UsernameOverTransport";
public static void main(String [] args) throws UnknownHostException{
String serviceUrl = System.getProperty("service.url");
String sts = System.getProperty("sts");
String stsUrl = System.getProperty("msclient."+sts+"sts.url");
if(InetAddress.getByName(URI.create(serviceUrl).getHost()).isLoopbackAddress()){
serviceUrl = serviceUrl.replaceFirst("localhost",InetAddress.getLocalHost().getHostAddress());
}
if(InetAddress.getByName(URI.create(stsUrl).getHost()).isLoopbackAddress()){
stsUrl = stsUrl.replaceFirst("localhost",InetAddress.getLocalHost().getHostAddress());
}
HostedClientSoap proxy = createProxy();
ArrayOfHostedClientParameter paramArray = new ArrayOfHostedClientParameter();
List<HostedClientParameter> list = paramArray.getHostedClientParameter();
HostedClientParameter stsParameter = readParameter(stsUrl, PARAM_STSAddress);
list.add(stsParameter);
HostedClientParameter serviceParameter = readParameter(serviceUrl, PARAM_ServiceAddress);
list.add(serviceParameter);
HostedClientParameter configParameter = readParameter(SCENARIO_1, PARAM_ConfigName);
list.add(configParameter);
runScenario(SCENARIO_1,paramArray,proxy);
}
public static HostedClientParameter readParameter(String endpoint, String parameterName) {
HostedClientParameter parameter = new HostedClientParameter();
parameter.setKey(parameterName);
parameter.setValue(endpoint);
return parameter;
}
public static HostedClientSoap createProxy() {
HostedClientSoapImpl hostclisvc = new HostedClientSoapImpl();
return hostclisvc.getBasicHttpBindingHostedClientSoap();
}
public static void runScenario(String scenarioName, ArrayOfHostedClientParameter paramArray, HostedClientSoap proxy){
System.out.println("Run Scenario: " + scenarioName);
List<HostedClientParameter> list = paramArray.getHostedClientParameter();
for(int i = 0; i<list.size();i++) {
System.out.println(list.get(i).getKey() + ":" + list.get(i).getValue());
}
System.out.println("Proxy created=================: " + proxy);
HostedClientResult result = proxy.run(featureName, scenarioName, paramArray);
System.out.println("Result: " + (result.isSuccess() ? "PASS" : "FAIL"));
System.out.println("Debuglog: " + result.getDebugLog());
}
}
| 42.321429 | 121 | 0.699859 |
70f0e3cd78da3a17ab8e855adf76d3221810c30c | 2,981 | /*
* IntPTI: integer error fixing by proper-type inference
* Copyright (c) 2017.
*
* Open-source component:
*
* CPAchecker
* Copyright (C) 2007-2014 Dirk Beyer
*
* Guava: Google Core Libraries for Java
* Copyright (C) 2010-2006 Google
*
*
*/
package org.sosy_lab.cpachecker.cfa.types.c;
import static com.google.common.base.Preconditions.checkNotNull;
import java.io.Serializable;
import java.util.Objects;
import javax.annotation.Nullable;
/**
* This represents a type which was created by using typedef.
*/
public final class CTypedefType implements CType, Serializable {
private static final long serialVersionUID = -3461236537115147688L;
private final String name; // the typedef name
private final CType realType; // the real type this typedef points to
private boolean isConst;
private boolean isVolatile;
public CTypedefType(
final boolean pConst, final boolean pVolatile,
final String pName, CType pRealType) {
isConst = pConst;
isVolatile = pVolatile;
name = pName.intern();
realType = checkNotNull(pRealType);
}
public String getName() {
return name;
}
public CType getRealType() {
return realType;
}
@Override
public String toString() {
return toASTString("");
}
@Override
public String toASTString(String pDeclarator) {
checkNotNull(pDeclarator);
return (isConst() ? "const " : "")
+ (isVolatile() ? "volatile " : "")
+ name
+ " " + pDeclarator;
}
@Override
public boolean isConst() {
return isConst;
}
@Override
public boolean isVolatile() {
return isVolatile;
}
@Override
public <R, X extends Exception> R accept(CTypeVisitor<R, X> pVisitor) throws X {
return pVisitor.visit(this);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 7;
result = prime * result + Objects.hashCode(name);
result = prime * result + Objects.hashCode(isConst);
result = prime * result + Objects.hashCode(isVolatile);
result = prime * result + Objects.hashCode(realType);
return result;
}
/**
* Be careful, this method compares the CType as it is to the given object,
* typedefs won't be resolved. If you want to compare the type without having
* typedefs in it use #getCanonicalType().equals()
*/
@Override
public boolean equals(@Nullable Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof CTypedefType)) {
return false;
}
CTypedefType other = (CTypedefType) obj;
return Objects.equals(name, other.name) && isConst == other.isConst
&& isVolatile == other.isVolatile && Objects.equals(realType, other.realType);
}
@Override
public CType getCanonicalType() {
return getCanonicalType(isConst, isVolatile);
}
@Override
public CType getCanonicalType(boolean pForceConst, boolean pForceVolatile) {
return realType.getCanonicalType(pForceConst, pForceVolatile);
}
}
| 24.040323 | 86 | 0.679973 |
a15a45514a91bf8fbbd0a772e322cc13b23afafa | 1,308 | import com.wangxt.redis.helper.config.RedisConfig;
import com.wangxt.redis.helper.helper.Cache;
import com.wangxt.redis.helper.helper.RedisHelper;
import com.wangxt.redis.helper.pojo.RedisDBIdentity;
import lombok.AllArgsConstructor;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.HashSet;
import java.util.Set;
public class RedisHelperTest {
private RedisHelper redisHelper;
@Before
public void before(){
RedisConfig redisConfig = new RedisConfig();
redisConfig.setHost("");
redisConfig.setPort(6379);
redisConfig.setPasswd("");
Set<Integer> assignedDbIndexes = new HashSet<>();
assignedDbIndexes.add(1);
redisHelper = new RedisHelper(redisConfig, assignedDbIndexes);
}
@AllArgsConstructor
public enum RedisDb implements RedisDBIdentity{
IDX1(1);
private final Integer index;
@Override
public int getIndex() {
return index;
}
}
@Test
public void test(){
Cache cache = redisHelper.get(RedisDb.IDX1);
String key = "wxt_test";
String set = cache.set(key, "good");
Assert.assertEquals(set, "ok");
String s = cache.get(key);
Assert.assertEquals(s, "good");
}
}
| 24.222222 | 70 | 0.658257 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.