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
|
---|---|---|---|---|---|
57a858f66348533ddd1dd573756c730c0999869a | 1,716 | package com.service.room.booking.service;
import com.service.room.booking.entity.BookingCalendar;
import com.service.room.booking.entity.Room;
import com.service.room.booking.entity.RoomType;
import com.service.room.booking.repository.RoomRepo;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
@SpringBootTest
@RunWith(MockitoJUnitRunner.class)
class RoomServiceTest {
@Mock
private RoomRepo roomRepoMock;
@InjectMocks
private RoomService roomService;
@Test
void getAllRooms() {
when(roomRepoMock.findAll()).thenReturn(new ArrayList<Room>());
List<Room> result = roomService.getAllRooms();
assertEquals(Collections.emptyList(), result);
}
@Test
void getRoomById() {
Room room = new Room();
room.setId(1);
when(roomRepoMock.findById(1)).thenReturn(Optional.of(room));
Room result = roomService.getRoomById(1);
assertEquals(room, result);
}
@Test
void createRoom() {
Room room = new Room();
room.setBookingCalendarList(new ArrayList<>());
room.setType(RoomType.Double);
when(roomRepoMock.save(any(Room.class))).thenReturn(room);
Room result = roomService.createRoom("Double");
assertEquals(room, result);
}
} | 30.642857 | 71 | 0.722611 |
a1d2b2b9234a2dad91629a2cf85c1a34afa969c3 | 33,809 | /*
* Copyright (c) 2011-2019, Peter Abeles. All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.org).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package boofcv.alg.geo;
import boofcv.alg.distort.LensDistortionNarrowFOV;
import boofcv.alg.distort.pinhole.PinholeNtoP_F64;
import boofcv.alg.distort.pinhole.PinholePtoN_F32;
import boofcv.alg.distort.pinhole.PinholePtoN_F64;
import boofcv.alg.geo.impl.ImplPerspectiveOps_F32;
import boofcv.alg.geo.impl.ImplPerspectiveOps_F64;
import boofcv.struct.calib.CameraModel;
import boofcv.struct.calib.CameraPinhole;
import boofcv.struct.calib.CameraPinholeBrown;
import boofcv.struct.distort.Point2Transform2_F64;
import boofcv.struct.geo.AssociatedPair;
import boofcv.struct.geo.AssociatedTriple;
import georegression.geometry.UtilVector3D_F64;
import georegression.metric.UtilAngle;
import georegression.struct.GeoTuple3D_F64;
import georegression.struct.point.*;
import georegression.struct.se.Se3_F64;
import org.ejml.data.DMatrix3;
import org.ejml.data.DMatrix3x3;
import org.ejml.data.DMatrixRMaj;
import org.ejml.data.FMatrixRMaj;
import org.ejml.dense.row.CommonOps_DDRM;
import javax.annotation.Nullable;
import java.util.List;
/**
* Functions related to perspective geometry and intrinsic camera calibration.
*
* @author Peter Abeles
*/
public class PerspectiveOps {
/**
* Approximates a pinhole camera using the distoriton model
* @param p2n Distorted pixel to undistorted normalized image coordinates
* @return
*/
public static CameraPinhole approximatePinhole( Point2Transform2_F64 p2n ,
int width , int height )
{
Point2D_F64 na = new Point2D_F64();
Point2D_F64 nb = new Point2D_F64();
// determine horizontal FOV using dot product of (na.x, na.y, 1 ) and (nb.x, nb.y, 1)
p2n.compute(0,height/2,na);
p2n.compute(width-1,height/2,nb);
double abdot = na.x*nb.x + na.y*nb.y + 1;
double normA = Math.sqrt(na.x*na.x + na.y*na.y + 1);
double normB = Math.sqrt(nb.x*nb.x + nb.y*nb.y + 1);
double hfov = Math.acos( abdot/(normA*normB));
// vertical FOV
p2n.compute(width/2,0,na);
p2n.compute(width/2,height-1,nb);
abdot = na.x*nb.x + na.y*nb.y + 1;
normA = Math.sqrt(na.x*na.x + na.y*na.y + 1);
normB = Math.sqrt(nb.x*nb.x + nb.y*nb.y + 1);
double vfov = Math.acos( abdot/(normA*normB));
return createIntrinsic(width,height, UtilAngle.degree(hfov), UtilAngle.degree(vfov));
}
/**
* Creates a set of intrinsic parameters, without distortion, for a camera with the specified characteristics
*
* @param width Image width
* @param height Image height
* @param hfov Horizontal FOV in degrees
* @param vfov Vertical FOV in degrees
* @return guess camera parameters
*/
public static CameraPinhole createIntrinsic(int width, int height, double hfov, double vfov) {
CameraPinhole intrinsic = new CameraPinhole();
intrinsic.width = width;
intrinsic.height = height;
intrinsic.cx = width / 2;
intrinsic.cy = height / 2;
intrinsic.fx = intrinsic.cx / Math.tan(UtilAngle.degreeToRadian(hfov/2.0));
intrinsic.fy = intrinsic.cy / Math.tan(UtilAngle.degreeToRadian(vfov/2.0));
return intrinsic;
}
/**
* Creates a set of intrinsic parameters, without distortion, for a camera with the specified characteristics.
* The focal length is assumed to be the same for x and y.
*
* @param width Image width
* @param height Image height
* @param hfov Horizontal FOV in degrees
* @return guess camera parameters
*/
public static CameraPinholeBrown createIntrinsic(int width, int height, double hfov) {
CameraPinholeBrown intrinsic = new CameraPinholeBrown();
intrinsic.width = width;
intrinsic.height = height;
intrinsic.cx = width / 2;
intrinsic.cy = height / 2;
intrinsic.fx = intrinsic.cx / Math.tan(UtilAngle.degreeToRadian(hfov/2.0));
intrinsic.fy = intrinsic.fx;
return intrinsic;
}
/**
* Multiplies each element of the intrinsic parameters by the provided scale factor. Useful
* if the image has been rescaled.
*
* @param param Intrinsic parameters
* @param scale Scale factor that input image is being scaled by.
*/
public static void scaleIntrinsic(CameraPinhole param , double scale ) {
param.width = (int)(param.width*scale);
param.height = (int)(param.height*scale);
param.cx *= scale;
param.cy *= scale;
param.fx *= scale;
param.fy *= scale;
param.skew *= scale;
}
/**
*
* <p>Recomputes the {@link CameraPinholeBrown} given an adjustment matrix.</p>
* K<sub>A</sub> = A*K<br>
* Where K<sub>A</sub> is the returned adjusted intrinsic matrix, A is the adjustment matrix and K is the
* original intrinsic calibration matrix.
*
* <p>
* NOTE: Distortion parameters are ignored in the provided {@link CameraPinholeBrown} class.
* </p>
*
* @param parameters (Input) Original intrinsic parameters. Not modified.
* @param adjustMatrix (Input) Adjustment matrix. Not modified.
* @param adjustedParam (Output) Optional storage for adjusted intrinsic parameters. Can be null.
* @return Adjusted intrinsic parameters.
*/
public static <C extends CameraPinhole>C adjustIntrinsic(C parameters,
DMatrixRMaj adjustMatrix,
C adjustedParam)
{
return ImplPerspectiveOps_F64.adjustIntrinsic(parameters, adjustMatrix, adjustedParam);
}
/**
*
* <p>Recomputes the {@link CameraPinholeBrown} given an adjustment matrix.</p>
* K<sub>A</sub> = A*K<br>
* Where K<sub>A</sub> is the returned adjusted intrinsic matrix, A is the adjustment matrix and K is the
* original intrinsic calibration matrix.
*
* <p>
* NOTE: Distortion parameters are ignored in the provided {@link CameraPinholeBrown} class.
* </p>
*
* @param parameters (Input) Original intrinsic parameters. Not modified.
* @param adjustMatrix (Input) Adjustment matrix. Not modified.
* @param adjustedParam (Output) Optional storage for adjusted intrinsic parameters. Can be null.
* @return Adjusted intrinsic parameters.
*/
public static <C extends CameraPinhole>C adjustIntrinsic(C parameters,
FMatrixRMaj adjustMatrix,
C adjustedParam)
{
return ImplPerspectiveOps_F32.adjustIntrinsic(parameters, adjustMatrix, adjustedParam);
}
/**
* Given the intrinsic parameters create a calibration matrix
*
* @param fx Focal length x-axis in pixels
* @param fy Focal length y-axis in pixels
* @param skew skew in pixels
* @param cx camera center x-axis in pixels
* @param cy center center y-axis in pixels
* @return Calibration matrix 3x3
*/
public static DMatrixRMaj pinholeToMatrix(double fx, double fy, double skew,
double cx, double cy) {
return ImplPerspectiveOps_F64.pinholeToMatrix(fx, fy, skew, cx, cy,null);
}
public static void pinholeToMatrix(double fx, double fy, double skew,
double cx, double cy , DMatrix3x3 K ) {
K.a11 = fx; K.a12 = skew; K.a13 = cx;
K.a22 = fy; K.a23 = cy;
K.a33 = 1;
K.a21 = K.a31 = K.a32 = 0;
}
/**
* Analytic matrix inversion to 3x3 camera calibration matrix. Input and output
* can be the same matrix. Zeros are not set.
*
* @param K (Input) Calibration matrix
* @param Kinv (Output) inverse.
*/
public static void invertPinhole( DMatrix3x3 K , DMatrix3x3 Kinv) {
double fx = K.a11;
double skew = K.a12;
double cx = K.a13;
double fy = K.a22;
double cy = K.a23;
Kinv.a11 = 1.0/fx;
Kinv.a12 = -skew/(fx*fy);
Kinv.a13 = (skew*cy - cx*fy)/(fx*fy);
Kinv.a22 = 1.0/fy;
Kinv.a23 = -cy/fy;
Kinv.a33 = 1;
}
/**
* Given the intrinsic parameters create a calibration matrix
*
* @param fx Focal length x-axis in pixels
* @param fy Focal length y-axis in pixels
* @param skew skew in pixels
* @param xc camera center x-axis in pixels
* @param yc center center y-axis in pixels
* @return Calibration matrix 3x3
*/
public static FMatrixRMaj pinholeToMatrix(float fx, float fy, float skew,
float xc, float yc) {
return ImplPerspectiveOps_F32.pinholeToMatrix(fx, fy, skew, xc, yc, null);
}
/**
* Given the intrinsic parameters create a calibration matrix
*
* @param param Intrinsic parameters structure that is to be converted into a matrix
* @param K Storage for calibration matrix, must be 3x3. If null then a new matrix is declared
* @return Calibration matrix 3x3
*/
public static DMatrixRMaj pinholeToMatrix(CameraPinhole param , DMatrixRMaj K )
{
return ImplPerspectiveOps_F64.pinholeToMatrix(param, K);
}
/**
* Given the intrinsic parameters create a calibration matrix
*
* @param param Intrinsic parameters structure that is to be converted into a matrix
* @param K Storage for calibration matrix, must be 3x3. If null then a new matrix is declared
* @return Calibration matrix 3x3
*/
public static FMatrixRMaj pinholeToMatrix(CameraPinhole param , FMatrixRMaj K )
{
return ImplPerspectiveOps_F32.pinholeToMatrix(param, K);
}
/**
* Given the intrinsic parameters create a calibration matrix
*
* @param param Intrinsic parameters structure that is to be converted into a matrix
* @param K Storage for calibration matrix, must be 3x3. If null then a new matrix is declared
* @return Calibration matrix 3x3
*/
public static DMatrix3x3 pinholeToMatrix(CameraPinhole param , DMatrix3x3 K )
{
return ImplPerspectiveOps_F64.pinholeToMatrix(param, K);
}
/**
* Converts a calibration matrix into intrinsic parameters
*
* @param K Camera calibration matrix.
* @param width Image width in pixels
* @param height Image height in pixels
* @param output (Output) Where the intrinsic parameter are written to. If null then a new instance is declared.
* @return camera parameters
*/
public static <C extends CameraPinhole>C matrixToPinhole(DMatrixRMaj K , int width , int height , C output )
{
return (C)ImplPerspectiveOps_F64.matrixToPinhole(K, width, height, output);
}
/**
* Converts a calibration matrix into intrinsic parameters
*
* @param K Camera calibration matrix.
* @param width Image width in pixels
* @param height Image height in pixels
* @param output (Output) Where the intrinsic parameter are written to. If null then a new instance is declared.
* @return camera parameters
*/
public static <C extends CameraPinhole>C matrixToPinhole(FMatrixRMaj K , int width , int height , C output )
{
return (C)ImplPerspectiveOps_F32.matrixToPinhole(K, width, height, output);
}
/**
* Given the transform from pixels to normalized image coordinates, create an approximate pinhole model
* for this camera. Assumes (cx,cy) is the image center and that there is no skew.
*
* @param pixelToNorm Pixel coordinates into normalized image coordinates
* @param width Input image's width
* @param height Input image's height
* @return Approximate pinhole camera
*/
public static CameraPinhole estimatePinhole(Point2Transform2_F64 pixelToNorm , int width , int height ) {
Point2D_F64 normA = new Point2D_F64();
Point2D_F64 normB = new Point2D_F64();
Vector3D_F64 vectorA = new Vector3D_F64();
Vector3D_F64 vectorB = new Vector3D_F64();
pixelToNorm.compute(0,height/2,normA);
pixelToNorm.compute(width,height/2,normB);
vectorA.set(normA.x,normA.y,1);
vectorB.set(normB.x,normB.y,1);
double hfov = UtilVector3D_F64.acute(vectorA,vectorB);
pixelToNorm.compute(width/2,0,normA);
pixelToNorm.compute(width/2,height,normB);
vectorA.set(normA.x,normA.y,1);
vectorB.set(normB.x,normB.y,1);
double vfov = UtilVector3D_F64.acute(vectorA,vectorB);
CameraPinhole intrinsic = new CameraPinhole();
intrinsic.width = width;
intrinsic.height = height;
intrinsic.skew = 0;
intrinsic.cx = width/2;
intrinsic.cy = height/2;
intrinsic.fx = intrinsic.cx/Math.tan(hfov/2);
intrinsic.fy = intrinsic.cy/Math.tan(vfov/2);
return intrinsic;
}
/**
* <p>
* Convenient function for converting from normalized image coordinates to the original image pixel coordinate.
* If speed is a concern then {@link PinholeNtoP_F64} should be used instead.
* </p>
*
* @param param Intrinsic camera parameters
* @param x X-coordinate of normalized.
* @param y Y-coordinate of normalized.
* @param pixel Optional storage for output. If null a new instance will be declared.
* @return pixel image coordinate
*/
public static Point2D_F64 convertNormToPixel(CameraModel param , double x , double y , Point2D_F64 pixel ) {
return ImplPerspectiveOps_F64.convertNormToPixel(param, x, y, pixel);
}
public static Point2D_F64 convertNormToPixel( CameraPinhole param , double x , double y , Point2D_F64 pixel ) {
if( pixel == null )
pixel = new Point2D_F64();
pixel.x = param.fx * x + param.skew * y + param.cx;
pixel.y = param.fy * y + param.cy;
return pixel;
}
/**
* <p>
* Convenient function for converting from normalized image coordinates to the original image pixel coordinate.
* If speed is a concern then {@link PinholeNtoP_F64} should be used instead.
* </p>
*
* @param param Intrinsic camera parameters
* @param x X-coordinate of normalized.
* @param y Y-coordinate of normalized.
* @param pixel Optional storage for output. If null a new instance will be declared.
* @return pixel image coordinate
*/
public static Point2D_F32 convertNormToPixel(CameraModel param , float x , float y , Point2D_F32 pixel ) {
return ImplPerspectiveOps_F32.convertNormToPixel(param, x, y, pixel);
}
/**
* <p>
* Convenient function for converting from normalized image coordinates to the original image pixel coordinate.
* If speed is a concern then {@link PinholeNtoP_F64} should be used instead.
* </p>
*
* NOTE: norm and pixel can be the same instance.
*
* @param param Intrinsic camera parameters
* @param norm Normalized image coordinate.
* @param pixel Optional storage for output. If null a new instance will be declared.
* @return pixel image coordinate
*/
public static Point2D_F64 convertNormToPixel(CameraModel param , Point2D_F64 norm , Point2D_F64 pixel ) {
return convertNormToPixel(param,norm.x,norm.y,pixel);
}
/**
* <p>
* Convenient function for converting from normalized image coordinates to the original image pixel coordinate.
* If speed is a concern then {@link PinholeNtoP_F64} should be used instead.
* </p>
*
* NOTE: norm and pixel can be the same instance.
*
* @param K Intrinsic camera calibration matrix
* @param norm Normalized image coordinate.
* @param pixel Optional storage for output. If null a new instance will be declared.
* @return pixel image coordinate
*/
public static Point2D_F64 convertNormToPixel( DMatrixRMaj K, Point2D_F64 norm , Point2D_F64 pixel )
{
return ImplPerspectiveOps_F64.convertNormToPixel(K, norm, pixel);
}
/**
* <p>
* Convenient function for converting from distorted image pixel coordinate to undistorted normalized
* image coordinates. If speed is a concern then {@link PinholePtoN_F64} should be used instead.
* </p>
*
* NOTE: norm and pixel can be the same instance.
*
* @param param Intrinsic camera parameters
* @param pixel Pixel coordinate
* @param norm Optional storage for output. If null a new instance will be declared.
* @return normalized image coordinate
*/
public static Point2D_F64 convertPixelToNorm(CameraModel param , Point2D_F64 pixel , Point2D_F64 norm ) {
return ImplPerspectiveOps_F64.convertPixelToNorm(param, pixel, norm);
}
/**
* <p>
* Convenient function for converting from distorted image pixel coordinate to undistorted normalized
* image coordinates. If speed is a concern then {@link PinholePtoN_F32} should be used instead.
* </p>
*
* NOTE: norm and pixel can be the same instance.
*
* @param param Intrinsic camera parameters
* @param pixel Pixel coordinate
* @param norm Optional storage for output. If null a new instance will be declared.
* @return normalized image coordinate
*/
public static Point2D_F32 convertPixelToNorm(CameraModel param , Point2D_F32 pixel , Point2D_F32 norm ) {
return ImplPerspectiveOps_F32.convertPixelToNorm(param, pixel, norm);
}
/**
* <p>
* Convenient function for converting from original image pixel coordinate to normalized< image coordinates.
* If speed is a concern then {@link PinholePtoN_F64} should be used instead.
* </p>
*
* NOTE: norm and pixel can be the same instance.
*
* @param K Intrinsic camera calibration matrix
* @param pixel Pixel coordinate.
* @param norm Optional storage for output. If null a new instance will be declared.
* @return normalized image coordinate
*/
public static Point2D_F64 convertPixelToNorm( DMatrixRMaj K , Point2D_F64 pixel , Point2D_F64 norm ) {
return ImplPerspectiveOps_F64.convertPixelToNorm(K, pixel, norm);
}
/**
* <p>
* Convenient function for converting from original image pixel coordinate to normalized< image coordinates.
* If speed is a concern then {@link PinholePtoN_F64} should be used instead.
* </p>
*
* NOTE: norm and pixel can be the same instance.
*
* @param K Intrinsic camera calibration matrix
* @param pixel Pixel coordinate.
* @param norm Optional storage for output. If null a new instance will be declared.
* @return normalized image coordinate
*/
public static Point2D_F32 convertPixelToNorm( FMatrixRMaj K , Point2D_F32 pixel , Point2D_F32 norm ) {
return ImplPerspectiveOps_F32.convertPixelToNorm(K, pixel, norm);
}
public static Point2D_F64 convertPixelToNorm( CameraPinhole intrinsic , double x , double y, Point2D_F64 norm ) {
return ImplPerspectiveOps_F64.convertPixelToNorm(intrinsic, x,y, norm);
}
/**
* Renders a point in world coordinates into the image plane in pixels or normalized image
* coordinates.
*
* @param worldToCamera Transform from world to camera frame
* @param K Optional. Intrinsic camera calibration matrix. If null then normalized image coordinates are returned.
* @param X 3D Point in world reference frame..
* @return 2D Render point on image plane or null if it's behind the camera
*/
public static Point2D_F64 renderPixel( Se3_F64 worldToCamera , DMatrixRMaj K , Point3D_F64 X ) {
return ImplPerspectiveOps_F64.renderPixel(worldToCamera,K,X);
// if( K == null )
// return renderPixel(worldToCamera,X);
// return ImplPerspectiveOps_F64.renderPixel(worldToCamera,
// K.data[0], K.data[1], K.data[2], K.data[4], K.data[5], X);
}
public static Point2D_F64 renderPixel( Se3_F64 worldToCamera , CameraPinhole K , Point3D_F64 X ) {
return ImplPerspectiveOps_F64.renderPixel(worldToCamera,
K.fy, K.skew, K.cx, K.fy, K.cy, X);
}
public static Point2D_F64 renderPixel( Se3_F64 worldToCamera , Point3D_F64 X ) {
return ImplPerspectiveOps_F64.renderPixel(worldToCamera,
1, 0, 0, 1, 0, X);
}
/**
* Renders a point in camera coordinates into the image plane in pixels.
*
* @param intrinsic Intrinsic camera parameters.
* @param X 3D Point in world reference frame..
* @return 2D Render point on image plane or null if it's behind the camera
*/
public static Point2D_F64 renderPixel(CameraPinhole intrinsic , Point3D_F64 X ) {
Point2D_F64 norm = new Point2D_F64(X.x/X.z,X.y/X.z);
return convertNormToPixel(intrinsic, norm, norm);
}
/**
* Computes the image coordinate of a point given its 3D location and the camera matrix.
*
* @param worldToCamera 3x4 camera matrix for transforming a 3D point from world to image coordinates.
* @param X 3D Point in world reference frame..
* @return 2D Render point on image plane.
*/
public static Point2D_F64 renderPixel( DMatrixRMaj worldToCamera , Point3D_F64 X ) {
return renderPixel(worldToCamera,X,(Point2D_F64)null);
}
public static Point2D_F64 renderPixel( DMatrixRMaj worldToCamera , Point3D_F64 X , @Nullable Point2D_F64 pixel ) {
if( pixel == null )
pixel = new Point2D_F64();
ImplPerspectiveOps_F64.renderPixel(worldToCamera, X, pixel);
return pixel;
}
public static Point3D_F64 renderPixel( DMatrixRMaj worldToCamera , Point3D_F64 X , @Nullable Point3D_F64 pixel ) {
if( pixel == null )
pixel = new Point3D_F64();
ImplPerspectiveOps_F64.renderPixel(worldToCamera, X, pixel);
return pixel;
}
/**
* Render a pixel in homogeneous coordinates from a 3x4 camera matrix and a 3D homogeneous point.
* @param cameraMatrix (Input) 3x4 camera matrix
* @param X (Input) 3D point in homogeneous coordinates
* @param x (Output) Rendered 2D point in homogeneous coordinates
* @return Rendered 2D point in homogeneous coordinates
*/
public static Point3D_F64 renderPixel( DMatrixRMaj cameraMatrix , Point4D_F64 X , @Nullable Point3D_F64 x) {
if( x == null )
x = new Point3D_F64();
ImplPerspectiveOps_F64.renderPixel(cameraMatrix, X, x);
return x;
}
/**
* Render a pixel in homogeneous coordinates from a 3x4 camera matrix and a 2D point.
* @param cameraMatrix (Input) 3x4 camera matrix
* @param X (Input) 3D point in homogeneous coordinates
* @param x (Output) Rendered 2D point coordinates
* @return Rendered 2D point coordinates
*/
public static Point2D_F64 renderPixel( DMatrixRMaj cameraMatrix , Point4D_F64 X , @Nullable Point2D_F64 x) {
if( x == null )
x = new Point2D_F64();
ImplPerspectiveOps_F64.renderPixel(cameraMatrix, X, x);
return x;
}
/**
* Takes a list of {@link AssociatedPair} as input and breaks it up into two lists for each view.
*
* @param pairs Input: List of associated pairs.
* @param view1 Output: List of observations from view 1
* @param view2 Output: List of observations from view 2
*/
public static void splitAssociated( List<AssociatedPair> pairs ,
List<Point2D_F64> view1 , List<Point2D_F64> view2 ) {
for( AssociatedPair p : pairs ) {
view1.add(p.p1);
view2.add(p.p2);
}
}
/**
* Takes a list of {@link AssociatedTriple} as input and breaks it up into three lists for each view.
*
* @param pairs Input: List of associated triples.
* @param view1 Output: List of observations from view 1
* @param view2 Output: List of observations from view 2
* @param view3 Output: List of observations from view 3
*/
public static void splitAssociated( List<AssociatedTriple> pairs ,
List<Point2D_F64> view1 , List<Point2D_F64> view2 , List<Point2D_F64> view3 ) {
for( AssociatedTriple p : pairs ) {
view1.add(p.p1);
view2.add(p.p2);
view3.add(p.p3);
}
}
/**
* Create a 3x4 camera matrix. For calibrated camera P = [R|T]. For uncalibrated camera it is P = K*[R|T].
*
* @param R Rotation matrix. 3x3
* @param T Translation vector.
* @param K Optional camera calibration matrix 3x3.
* @param ret Storage for camera calibration matrix. If null a new instance will be created.
* @return Camera calibration matrix.
*/
public static DMatrixRMaj createCameraMatrix( DMatrixRMaj R , Vector3D_F64 T ,
@Nullable DMatrixRMaj K ,
@Nullable DMatrixRMaj ret ) {
return ImplPerspectiveOps_F64.createCameraMatrix(R, T, K, ret);
}
/**
* Splits the projection matrix into a 3x3 matrix and 3x1 vector.
*
* @param P (Input) 3x4 projection matirx
* @param M (Output) M = P(:,0:2)
* @param T (Output) T = P(:,3)
*/
public static void projectionSplit( DMatrixRMaj P , DMatrixRMaj M , Vector3D_F64 T ) {
CommonOps_DDRM.extract(P,0,3,0,3,M,0,0);
T.x = P.get(0,3);
T.y = P.get(1,3);
T.z = P.get(2,3);
}
/**
* Splits the projection matrix into a 3x3 matrix and 3x1 vector.
*
* @param P (Input) 3x4 projection matirx
* @param M (Output) M = P(:,0:2)
* @param T (Output) T = P(:,3)
*/
public static void projectionSplit( DMatrixRMaj P , DMatrix3x3 M , DMatrix3 T ) {
M.a11 = P.data[0]; M.a12 = P.data[1]; M.a13 = P.data[2 ]; T.a1 = P.data[3 ];
M.a21 = P.data[4]; M.a22 = P.data[5]; M.a23 = P.data[6 ]; T.a2 = P.data[7 ];
M.a31 = P.data[8]; M.a32 = P.data[9]; M.a33 = P.data[10]; T.a3 = P.data[11];
}
/**
* P = [M|T]
*
* @param M (Input) 3x3 matrix
* @param T (Input) 3x1 vector
* @param P (Output) [M,T]
*/
public static void projectionCombine( DMatrixRMaj M , Vector3D_F64 T , DMatrixRMaj P ) {
CommonOps_DDRM.insert(M,P,0,0);
P.data[3] = T.x;
P.data[7] = T.y;
P.data[11] = T.z;
}
/**
* Creates a transform from world coordinates into pixel coordinates. can handle lens distortion
*/
public static WorldToCameraToPixel createWorldToPixel(CameraPinholeBrown intrinsic , Se3_F64 worldToCamera )
{
WorldToCameraToPixel alg = new WorldToCameraToPixel();
alg.configure(intrinsic,worldToCamera);
return alg;
}
/**
* Creates a transform from world coordinates into pixel coordinates. can handle lens distortion
*/
public static WorldToCameraToPixel createWorldToPixel(LensDistortionNarrowFOV distortion , Se3_F64 worldToCamera )
{
WorldToCameraToPixel alg = new WorldToCameraToPixel();
alg.configure(distortion,worldToCamera);
return alg;
}
public static double computeHFov(CameraPinhole intrinsic) {
return 2*Math.atan((intrinsic.width/2)/intrinsic.fx);
}
public static double computeVFov(CameraPinhole intrinsic) {
return 2*Math.atan((intrinsic.height/2)/intrinsic.fy);
}
/**
* Computes the cross-ratio between 4 points. This is an invariant under projective geometry.
* @param a0 Point
* @param a1 Point
* @param a2 Point
* @param a3 Point
* @return cross ratio
*/
public static double crossRatios( Point3D_F64 a0 , Point3D_F64 a1 , Point3D_F64 a2 , Point3D_F64 a3) {
double d01 = a0.distance(a1);
double d23 = a2.distance(a3);
double d02 = a0.distance(a2);
double d13 = a1.distance(a3);
return (d01*d23)/(d02*d13);
}
/**
* Computes the cross-ratio between 4 points. This is an invariant under projective geometry.
* @param a0 Point
* @param a1 Point
* @param a2 Point
* @param a3 Point
* @return cross ratio
*/
public static double crossRatios( Point2D_F64 a0 , Point2D_F64 a1 , Point2D_F64 a2 , Point2D_F64 a3) {
double d01 = a0.distance(a1);
double d23 = a2.distance(a3);
double d02 = a0.distance(a2);
double d13 = a1.distance(a3);
return (d01*d23)/(d02*d13);
}
/**
* Converts the SE3 into a 3x4 matrix. [R|T]
* @param m (Input) transform
* @param A (Output) equivalent 3x4 matrix represenation
*/
public static DMatrixRMaj convertToMatrix( Se3_F64 m , DMatrixRMaj A ) {
if( A == null )
A = new DMatrixRMaj(3,4);
else
A.reshape(3,4);
CommonOps_DDRM.insert(m.R,A,0,0);
A.data[3] = m.T.x;
A.data[7] = m.T.y;
A.data[11] = m.T.z;
return A;
}
/**
* Extracts a column from the camera matrix and puts it into the geometric 3-tuple.
*/
public static void extractColumn(DMatrixRMaj P, int col, GeoTuple3D_F64 a) {
a.x = P.unsafe_get(0,col);
a.y = P.unsafe_get(1,col);
a.z = P.unsafe_get(2,col);
}
/**
* Inserts 3-tuple into the camera matrix's columns
*/
public static void insertColumn(DMatrixRMaj P, int col, GeoTuple3D_F64 a) {
P.unsafe_set(0,col,a.x);
P.unsafe_set(1,col,a.y);
P.unsafe_set(2,col,a.z);
}
/**
* Computes: D = A<sup>T</sup>*B*C
*
* @param A (Input) 3x3 matrix
* @param B (Input) 3x3 matrix
* @param C (Input) 3x3 matrix
* @param output (Output) 3x3 matrix. Can be same instance A or B.
*/
public static void multTranA( DMatrixRMaj A , DMatrixRMaj B , DMatrixRMaj C , DMatrixRMaj output )
{
double t11 = A.data[0]*B.data[0] + A.data[3]*B.data[3] + A.data[6]*B.data[6];
double t12 = A.data[0]*B.data[1] + A.data[3]*B.data[4] + A.data[6]*B.data[7];
double t13 = A.data[0]*B.data[2] + A.data[3]*B.data[5] + A.data[6]*B.data[8];
double t21 = A.data[1]*B.data[0] + A.data[4]*B.data[3] + A.data[7]*B.data[6];
double t22 = A.data[1]*B.data[1] + A.data[4]*B.data[4] + A.data[7]*B.data[7];
double t23 = A.data[1]*B.data[2] + A.data[4]*B.data[5] + A.data[7]*B.data[8];
double t31 = A.data[2]*B.data[0] + A.data[5]*B.data[3] + A.data[8]*B.data[6];
double t32 = A.data[2]*B.data[1] + A.data[5]*B.data[4] + A.data[8]*B.data[7];
double t33 = A.data[2]*B.data[2] + A.data[5]*B.data[5] + A.data[8]*B.data[8];
output.data[0] = t11*C.data[0] + t12*C.data[3] + t13*C.data[6];
output.data[1] = t11*C.data[1] + t12*C.data[4] + t13*C.data[7];
output.data[2] = t11*C.data[2] + t12*C.data[5] + t13*C.data[8];
output.data[3] = t21*C.data[0] + t22*C.data[3] + t23*C.data[6];
output.data[4] = t21*C.data[1] + t22*C.data[4] + t23*C.data[7];
output.data[5] = t21*C.data[2] + t22*C.data[5] + t23*C.data[8];
output.data[6] = t31*C.data[0] + t32*C.data[3] + t33*C.data[6];
output.data[7] = t31*C.data[1] + t32*C.data[4] + t33*C.data[7];
output.data[8] = t31*C.data[2] + t32*C.data[5] + t33*C.data[8];
}
/**
* Computes: D = A*B*C<sup>T</sup>
*
* @param A (Input) 3x3 matrix
* @param B (Input) 3x3 matrix
* @param C (Input) 3x3 matrix
* @param output (Output) 3x3 matrix. Can be same instance A or B.
*/
public static void multTranC( DMatrixRMaj A , DMatrixRMaj B , DMatrixRMaj C , DMatrixRMaj output )
{
double t11 = A.data[0]*B.data[0] + A.data[1]*B.data[3] + A.data[2]*B.data[6];
double t12 = A.data[0]*B.data[1] + A.data[1]*B.data[4] + A.data[2]*B.data[7];
double t13 = A.data[0]*B.data[2] + A.data[1]*B.data[5] + A.data[2]*B.data[8];
double t21 = A.data[3]*B.data[0] + A.data[4]*B.data[3] + A.data[5]*B.data[6];
double t22 = A.data[3]*B.data[1] + A.data[4]*B.data[4] + A.data[5]*B.data[7];
double t23 = A.data[3]*B.data[2] + A.data[4]*B.data[5] + A.data[5]*B.data[8];
double t31 = A.data[6]*B.data[0] + A.data[7]*B.data[3] + A.data[8]*B.data[6];
double t32 = A.data[6]*B.data[1] + A.data[7]*B.data[4] + A.data[8]*B.data[7];
double t33 = A.data[6]*B.data[2] + A.data[7]*B.data[5] + A.data[8]*B.data[8];
output.data[0] = t11*C.data[0] + t12*C.data[1] + t13*C.data[2];
output.data[1] = t11*C.data[3] + t12*C.data[4] + t13*C.data[5];
output.data[2] = t11*C.data[6] + t12*C.data[7] + t13*C.data[8];
output.data[3] = t21*C.data[0] + t22*C.data[1] + t23*C.data[2];
output.data[4] = t21*C.data[3] + t22*C.data[4] + t23*C.data[5];
output.data[5] = t21*C.data[6] + t22*C.data[7] + t23*C.data[8];
output.data[6] = t31*C.data[0] + t32*C.data[1] + t33*C.data[2];
output.data[7] = t31*C.data[3] + t32*C.data[4] + t33*C.data[5];
output.data[8] = t31*C.data[6] + t32*C.data[7] + t33*C.data[8];
}
/**
* Computes: D = A<sup>T</sup>*B*C
*
* @param A (Input) 3x3 matrix
* @param B (Input) 3x3 matrix
* @param C (Input) 3x3 matrix
* @param output (Output) 3x3 matrix. Can be same instance A or B.
*/
public static void multTranA( DMatrix3x3 A , DMatrix3x3 B , DMatrix3x3 C , DMatrix3x3 output )
{
double t11 = A.a11*B.a11 + A.a21*B.a21 + A.a31*B.a31;
double t12 = A.a11*B.a12 + A.a21*B.a22 + A.a31*B.a32;
double t13 = A.a11*B.a13 + A.a21*B.a23 + A.a31*B.a33;
double t21 = A.a12*B.a11 + A.a22*B.a21 + A.a32*B.a31;
double t22 = A.a12*B.a12 + A.a22*B.a22 + A.a32*B.a32;
double t23 = A.a12*B.a13 + A.a22*B.a23 + A.a32*B.a33;
double t31 = A.a13*B.a11 + A.a23*B.a21 + A.a33*B.a31;
double t32 = A.a13*B.a12 + A.a23*B.a22 + A.a33*B.a32;
double t33 = A.a13*B.a13 + A.a23*B.a23 + A.a33*B.a33;
output.a11 = t11*C.a11 + t12*C.a21 + t13*C.a31;
output.a12 = t11*C.a12 + t12*C.a22 + t13*C.a32;
output.a13 = t11*C.a13 + t12*C.a23 + t13*C.a33;
output.a21 = t21*C.a11 + t22*C.a21 + t23*C.a31;
output.a22 = t21*C.a12 + t22*C.a22 + t23*C.a32;
output.a23 = t21*C.a13 + t22*C.a23 + t23*C.a33;
output.a31 = t31*C.a11 + t32*C.a21 + t33*C.a31;
output.a32 = t31*C.a12 + t32*C.a22 + t33*C.a32;
output.a33 = t31*C.a13 + t32*C.a23 + t33*C.a33;
}
/**
* Computes: D = A*B*C<sup>T</sup>
*
* @param A (Input) 3x3 matrix
* @param B (Input) 3x3 matrix
* @param C (Input) 3x3 matrix
* @param output (Output) 3x3 matrix. Can be same instance A or B.
*/
public static void multTranC( DMatrix3x3 A , DMatrix3x3 B , DMatrix3x3 C , DMatrix3x3 output )
{
double t11 = A.a11*B.a11 + A.a12*B.a21 + A.a13*B.a31;
double t12 = A.a11*B.a12 + A.a12*B.a22 + A.a13*B.a32;
double t13 = A.a11*B.a13 + A.a12*B.a23 + A.a13*B.a33;
double t21 = A.a21*B.a11 + A.a22*B.a21 + A.a23*B.a31;
double t22 = A.a21*B.a12 + A.a22*B.a22 + A.a23*B.a32;
double t23 = A.a21*B.a13 + A.a22*B.a23 + A.a23*B.a33;
double t31 = A.a31*B.a11 + A.a32*B.a21 + A.a33*B.a31;
double t32 = A.a31*B.a12 + A.a32*B.a22 + A.a33*B.a32;
double t33 = A.a31*B.a13 + A.a32*B.a23 + A.a33*B.a33;
output.a11 = t11*C.a11 + t12*C.a12 + t13*C.a13;
output.a12 = t11*C.a21 + t12*C.a22 + t13*C.a23;
output.a13 = t11*C.a31 + t12*C.a32 + t13*C.a33;
output.a21 = t21*C.a11 + t22*C.a12 + t23*C.a13;
output.a22 = t21*C.a21 + t22*C.a22 + t23*C.a23;
output.a23 = t21*C.a31 + t22*C.a32 + t23*C.a33;
output.a31 = t31*C.a11 + t32*C.a12 + t33*C.a13;
output.a32 = t31*C.a21 + t32*C.a22 + t33*C.a23;
output.a33 = t31*C.a31 + t32*C.a32 + t33*C.a33;
}
/**
* Multiplies A*P, where A = [sx 0 tx; 0 sy ty; 0 0 1]
*/
public static void inplaceAdjustCameraMatrix( double sx , double sy , double tx , double ty , DMatrixRMaj P ) {
// multiply each column one at a time. Because of the zeros everything is decoupled
for (int col = 0; col < 4; col++) {
int row0 = col;
int row1 = 4 + row0;
int row2 = 4 + row1;
P.data[row0] = P.data[row0]*sx + tx*P.data[row2];
P.data[row1] = P.data[row1]*sy + ty*P.data[row2];
}
}
}
| 36.120726 | 117 | 0.69307 |
8a7384cd7c07468817e7573cc9df28d495799a8c | 95 | package com.fasterxml.mama;
public enum NodeState
{
Fresh, Started, Draining, Shutdown;
}
| 13.571429 | 39 | 0.736842 |
c2377ebb1f7fea08a70d0812870416906b474ec8 | 590 | package de.peeeq.wurstscript.attributes;
import com.google.common.base.Preconditions;
import de.peeeq.wurstscript.ast.Annotation;
import de.peeeq.wurstscript.ast.Modifier;
import de.peeeq.wurstscript.ast.NameDef;
public class HasAnnotation {
public static boolean hasAnnotation(NameDef e, String annotation) {
Preconditions.checkArgument(annotation.startsWith("@"));
for (Modifier m : e.getModifiers()) {
if (m instanceof Annotation) {
Annotation a = (Annotation) m;
if (a.getAnnotationType().equals(annotation)) {
return true;
}
}
}
return false;
}
}
| 23.6 | 68 | 0.732203 |
2e58f99772562496638e3df34cdb72389d8e92e9 | 1,188 | package org.eclipse.dataspaceconnector.spi.persistence;
import org.jetbrains.annotations.NotNull;
import java.util.List;
/**
* Define a store that can be used within a state machine
*/
public interface StateEntityStore<T> {
/**
* Returns a list of entities that are in a specific state.
* <br/>
* Implementors MUST handle these requirements: <br/>
* <ul>
* <il>
* * entities should be fetched from the oldest to the newest, by a timestamp that reports the last state transition on the entity
* <br/><br/>
* </il>
* <il>
* * fetched entities should be leased for a configurable timeout, that will be released after the timeout expires or when the entity will be updated.
* This will avoid consecutive fetches in the state machine loop
* <br/><br/>
* </il>
* </ul>
*
* @param state The state that the processes of interest should be in.
* @param max The maximum amount of result items.
* @return A list of entities (at most _max_) that are in the desired state.
*/
@NotNull
List<T> nextForState(int state, int max);
}
| 33 | 162 | 0.628788 |
3eec7da6c51cdbf32eb136ca89830a3c8abf715e | 16,177 | package com.project.convertedCode.globalNamespace.namespaces.SebastianBergmann.namespaces.CodeCoverage.namespaces.Node.classes;
import com.runtimeconverter.runtime.references.ReferenceContainer;
import com.runtimeconverter.runtime.nativeFunctions.string.function_str_replace;
import com.runtimeconverter.runtime.passByReference.PassByReferenceArgs;
import com.runtimeconverter.runtime.nativeFunctions.array.function_ksort;
import com.runtimeconverter.runtime.nativeFunctions.string.function_explode;
import com.runtimeconverter.runtime.passByReference.RuntimeArgsWithReferences;
import com.runtimeconverter.runtime.ZVal;
import com.runtimeconverter.runtime.reflection.ReflectionClassData;
import com.runtimeconverter.runtime.annotations.ConvertedParameter;
import com.runtimeconverter.runtime.arrays.ZPair;
import com.runtimeconverter.runtime.exceptions.TemporaryStubFunctionException;
import java.lang.invoke.MethodHandles;
import com.runtimeconverter.runtime.nativeFunctions.array.function_count;
import com.runtimeconverter.runtime.annotations.ConvertedMethod;
import com.runtimeconverter.runtime.references.ArrayDimensionReference;
import com.project.convertedCode.globalNamespace.namespaces.SebastianBergmann.namespaces.CodeCoverage.namespaces.Node.classes.Directory;
import com.runtimeconverter.runtime.references.BasicReferenceContainer;
import com.runtimeconverter.runtime.classes.StaticBaseClass;
import com.runtimeconverter.runtime.nativeFunctions.array.function_array_shift;
import com.runtimeconverter.runtime.nativeFunctions.file.function_file_exists;
import com.runtimeconverter.runtime.classes.RuntimeClassBase;
import com.runtimeconverter.runtime.RuntimeEnv;
import com.runtimeconverter.runtime.nativeFunctions.array.function_array_keys;
import com.runtimeconverter.runtime.nativeFunctions.string.function_strpos;
import com.runtimeconverter.runtime.classes.NoConstructor;
import com.runtimeconverter.runtime.arrays.ArrayAction;
import com.project.convertedCode.globalNamespace.NamespaceGlobal;
import com.runtimeconverter.runtime.nativeFunctions.string.function_substr;
import com.runtimeconverter.runtime.nativeFunctions.file.function_dirname;
import static com.runtimeconverter.runtime.ZVal.arrayActionR;
import static com.runtimeconverter.runtime.ZVal.assignParameterRef;
import static com.runtimeconverter.runtime.ZVal.toStringR;
import static com.runtimeconverter.runtime.ZVal.assignParameter;
/*
Converted with The Runtime Converter (runtimeconverter.com)
vendor/phpunit/php-code-coverage/src/Node/Builder.php
*/
public final class Builder extends RuntimeClassBase {
public Builder(RuntimeEnv env, Object... args) {
super(env);
}
public Builder(NoConstructor n) {
super(n);
}
@ConvertedMethod
@ConvertedParameter(
index = 0,
name = "coverage",
typeHint = "SebastianBergmann\\CodeCoverage\\CodeCoverage"
)
public Object build(RuntimeEnv env, Object... args) {
Object coverage = assignParameter(args, 0, false);
Object root = null;
Object commonPath = null;
ReferenceContainer files = new BasicReferenceContainer(null);
files.setObject(env.callMethod(coverage, "getData", Builder.class));
commonPath =
env.callMethod(
this,
new RuntimeArgsWithReferences().add(0, files),
"reducePaths",
Builder.class,
files.getObject());
root = new Directory(env, commonPath, ZVal.getNull());
this.addItems(
env,
root,
this.buildDirectoryStructure(env, files.getObject()),
env.callMethod(coverage, "getTests", Builder.class),
env.callMethod(coverage, "getCacheTokens", Builder.class));
return ZVal.assign(root);
}
@ConvertedMethod
@ConvertedParameter(
index = 0,
name = "root",
typeHint = "SebastianBergmann\\CodeCoverage\\Node\\Directory"
)
@ConvertedParameter(index = 1, name = "items", typeHint = "array")
@ConvertedParameter(index = 2, name = "tests", typeHint = "array")
@ConvertedParameter(index = 3, name = "cacheTokens", typeHint = "bool")
private Object addItems(RuntimeEnv env, Object... args) {
Object root = assignParameter(args, 0, false);
Object items = assignParameter(args, 1, false);
Object tests = assignParameter(args, 2, false);
Object cacheTokens = assignParameter(args, 3, false);
Object value = null;
Object key = null;
Object child = null;
for (ZPair zpairResult1018 : ZVal.getIterable(items, env, false)) {
key = ZVal.assign(zpairResult1018.getKey());
value = ZVal.assign(zpairResult1018.getValue());
if (ZVal.equalityCheck(function_substr.f.env(env).call(key, -2).value(), "/f")) {
key = function_substr.f.env(env).call(key, 0, -2).value();
if (function_file_exists
.f
.env(env)
.call(
toStringR(env.callMethod(root, "getPath", Builder.class), env)
+ toStringR("/", env)
+ toStringR(key, env))
.getBool()) {
env.callMethod(root, "addFile", Builder.class, key, value, tests, cacheTokens);
}
} else {
child = env.callMethod(root, "addDirectory", Builder.class, key);
this.addItems(env, child, value, tests, cacheTokens);
}
}
return null;
}
@ConvertedMethod
@ConvertedParameter(index = 0, name = "files", typeHint = "array")
private Object buildDirectoryStructure(RuntimeEnv env, Object... args) {
Object files = assignParameter(args, 0, false);
ReferenceContainer result = new BasicReferenceContainer(null);
ReferenceContainer path = new BasicReferenceContainer(null);
ReferenceContainer pointer = new BasicReferenceContainer(null);
Object file = null;
Object max = null;
ReferenceContainer i = new BasicReferenceContainer(null);
Object type = null;
result.setObject(ZVal.newArray());
for (ZPair zpairResult1019 : ZVal.getIterable(files, env, false)) {
path.setObject(ZVal.assign(zpairResult1019.getKey()));
file = ZVal.assign(zpairResult1019.getValue());
path.setObject(function_explode.f.env(env).call("/", path.getObject()).value());
pointer = result;
max = function_count.f.env(env).call(path.getObject()).value();
for (i.setObject(0);
ZVal.isLessThan(i.getObject(), '<', max);
i.setObject(ZVal.increment(i.getObject()))) {
type = "";
if (ZVal.equalityCheck(i.getObject(), ZVal.subtract(max, 1))) {
type = "/f";
}
pointer =
new ArrayDimensionReference(
pointer.getObject(),
toStringR(path.arrayGet(env, i.getObject()), env)
+ toStringR(type, env));
}
pointer.setObject(ZVal.assign(file));
}
return ZVal.assign(result.getObject());
}
@ConvertedMethod
@ConvertedParameter(index = 0, name = "files", typeHint = "array")
private Object reducePaths(
RuntimeEnv env, PassByReferenceArgs runtimePassByReferenceArgs, Object... args) {
int runtimeConverterBreakCount;
ReferenceContainer files = assignParameterRef(runtimePassByReferenceArgs, args, 0, false);
ReferenceContainer original = new BasicReferenceContainer(null);
Object max = null;
ReferenceContainer paths = new BasicReferenceContainer(null);
Object commonPath = null;
ReferenceContainer i = new BasicReferenceContainer(null);
Object done = null;
if (ZVal.isEmpty(files.getObject())) {
return ".";
}
commonPath = "";
paths.setObject(function_array_keys.f.env(env).call(files.getObject()).value());
if (ZVal.strictEqualityCheck(
function_count.f.env(env).call(files.getObject()).value(), "===", 1)) {
commonPath =
toStringR(function_dirname.f.env(env).call(paths.arrayGet(env, 0)).value(), env)
+ "/";
files.arrayAccess(
env,
NamespaceGlobal.basename.env(env).call(paths.arrayGet(env, 0)).value())
.set(files.arrayGet(env, paths.arrayGet(env, 0)));
arrayActionR(ArrayAction.UNSET, files, env, paths.arrayGet(env, 0));
return ZVal.assign(commonPath);
}
max = function_count.f.env(env).call(paths.getObject()).value();
runtimeConverterBreakCount = 0;
for (i.setObject(0);
ZVal.isLessThan(i.getObject(), '<', max);
i.setObject(ZVal.increment(i.getObject()))) {
if (ZVal.strictEqualityCheck(
function_strpos
.f
.env(env)
.call(paths.arrayGet(env, i.getObject()), "phar://")
.value(),
"===",
0)) {
paths.arrayAccess(env, i.getObject())
.set(
function_substr
.f
.env(env)
.call(paths.arrayGet(env, i.getObject()), 7)
.value());
paths.arrayAccess(env, i.getObject())
.set(
function_str_replace
.f
.env(env)
.call("/", "/", paths.arrayGet(env, i.getObject()))
.value());
}
paths.arrayAccess(env, i.getObject())
.set(
function_explode
.f
.env(env)
.call("/", paths.arrayGet(env, i.getObject()))
.value());
if (arrayActionR(ArrayAction.EMPTY, paths, env, i.getObject(), 0)) {
paths.arrayAccess(env, i.getObject(), 0).set("/");
}
}
done = false;
max = function_count.f.env(env).call(paths.getObject()).value();
runtimeConverterBreakCount = 0;
while (!ZVal.isTrue(done)) {
runtimeConverterBreakCount = 0;
for (i.setObject(0);
ZVal.isLessThan(i.getObject(), '<', ZVal.subtract(max, 1));
i.setObject(ZVal.increment(i.getObject()))) {
if (ZVal.toBool(
ZVal.toBool(
!arrayActionR(
ArrayAction.ISSET,
paths,
env,
i.getObject(),
0))
|| ZVal.toBool(
!arrayActionR(
ArrayAction.ISSET,
paths,
env,
ZVal.add(i.getObject(), 1),
0)))
|| ZVal.toBool(
ZVal.notEqualityCheck(
paths.arrayGet(env, i.getObject(), 0),
paths.arrayGet(env, ZVal.add(i.getObject(), 1), 0)))) {
done = true;
break;
}
}
if (!ZVal.isTrue(done)) {
commonPath = toStringR(commonPath, env) + toStringR(paths.arrayGet(env, 0, 0), env);
if (ZVal.notEqualityCheck(paths.arrayGet(env, 0, 0), "/")) {
commonPath = toStringR(commonPath, env) + toStringR("/", env);
}
runtimeConverterBreakCount = 0;
for (i.setObject(0);
ZVal.isLessThan(i.getObject(), '<', max);
i.setObject(ZVal.increment(i.getObject()))) {
function_array_shift.f.env(env).call(paths.arrayGet(env, i.getObject()));
}
}
}
original.setObject(function_array_keys.f.env(env).call(files.getObject()).value());
max = function_count.f.env(env).call(original.getObject()).value();
runtimeConverterBreakCount = 0;
for (i.setObject(0);
ZVal.isLessThan(i.getObject(), '<', max);
i.setObject(ZVal.increment(i.getObject()))) {
files.arrayAccess(
env,
NamespaceGlobal.implode
.env(env)
.call("/", paths.arrayGet(env, i.getObject()))
.value())
.set(files.arrayGet(env, original.arrayGet(env, i.getObject())));
arrayActionR(ArrayAction.UNSET, files, env, original.arrayGet(env, i.getObject()));
}
function_ksort.f.env(env).call(files.getObject());
return ZVal.assign(function_substr.f.env(env).call(commonPath, 0, -1).value());
}
public Object reducePaths(RuntimeEnv env, Object... args) {
throw new TemporaryStubFunctionException();
}
public static final Object CONST_class = "SebastianBergmann\\CodeCoverage\\Node\\Builder";
// Runtime Converter Internals
// RuntimeStaticCompanion contains static methods
// RequestStaticProperties contains static (per-request) properties
// ReflectionClassData contains php reflection data used by the runtime library
public static class RuntimeStaticCompanion extends StaticBaseClass {
private static final MethodHandles.Lookup staticCompanionLookup = MethodHandles.lookup();
}
public static final RuntimeStaticCompanion runtimeStaticObject = new RuntimeStaticCompanion();
private static final ReflectionClassData runtimeConverterReflectionData =
ReflectionClassData.builder()
.setName("SebastianBergmann\\CodeCoverage\\Node\\Builder")
.setLookup(
Builder.class,
MethodHandles.lookup(),
RuntimeStaticCompanion.staticCompanionLookup)
.setLocalProperties()
.setFilename("vendor/phpunit/php-code-coverage/src/Node/Builder.php")
.get();
@Override
public ReflectionClassData getRuntimeConverterReflectionData() {
return runtimeConverterReflectionData;
}
@Override
public Object converterRuntimeCallExtended(
RuntimeEnv env,
String method,
Class<?> caller,
PassByReferenceArgs passByReferenceArgs,
Object... args) {
return RuntimeClassBase.converterRuntimeCallExtendedWithDataStatic(
this,
runtimeConverterReflectionData,
env,
method,
caller,
passByReferenceArgs,
args);
}
}
| 45.569014 | 136 | 0.554367 |
233f61c76b5c0729e5cc0f4ef6f087f709f41f9c | 2,248 | package com.epam.ccproject.web.controller;
import static org.junit.Assert.*;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.context.WebApplicationContext;
import com.epam.ccproject.WebappContextConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes=WebappContextConfiguration.class)
public class HomeControllerIT {
@Autowired
private HomeController homecontroller;
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void init() {
this.mockMvc = webAppContextSetup(this.wac).build();
}
@Test
public void shouldNotBeNull() {
assertNotNull(homecontroller);
}
@Test
public void shouldReturnStatusOk() throws Exception {
mockMvc.perform(get("/").accept(MediaType.TEXT_HTML)).andExpect(status().isOk());
}
@Test
public void shouldAcceptOnlyApplicationHTMLMimeType() throws Exception {
mockMvc.perform(get("/").accept(MediaType.TEXT_HTML)).andExpect(status().isOk());
mockMvc.perform(get("/").accept(MediaType.TEXT_PLAIN)).andExpect(status().isNotAcceptable());
mockMvc.perform(get("/").accept(MediaType.TEXT_XML)).andExpect(status().isNotAcceptable());
mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)).andExpect(status().isNotAcceptable());
mockMvc.perform(get("/").accept(MediaType.APPLICATION_XML)).andExpect(status().isNotAcceptable());
}
@Test
public void shouldReturnHomeTilesDefinitionValue() throws Exception {
mockMvc.perform(get("/").accept(MediaType.TEXT_HTML)).andExpect(content().contentType(MediaType.TEXT_HTML));
}
}
| 35.68254 | 110 | 0.799377 |
a54aecb77cd57198e3b1915df15d747ac571a9fd | 921 | package cyan.toolkit.rest.error.supply;
import cyan.toolkit.rest.RestError;
import cyan.toolkit.rest.RestErrorException;
import cyan.toolkit.rest.RestErrorStatus;
/**
* <p>ForbiddenException</p>
* @author Cyan ([email protected])
* @version V.0.0.1
* @group cyan.tool.kit
* @date 9:28 2019/12/20
*/
public class ForbiddenException extends RestErrorException {
public ForbiddenException() {
super(RestErrorStatus.AUTH_FORBIDDEN);
}
public ForbiddenException(String user) {
super(RestErrorStatus.AUTH_FORBIDDEN, RestError.error(null, user, RestErrorStatus.AUTH_FORBIDDEN));
}
public ForbiddenException(String resource, String user, String auth) {
super(RestErrorStatus.AUTH_FORBIDDEN, RestError.error(resource, user, auth, RestErrorStatus.AUTH_FORBIDDEN));
}
@Override
public ForbiddenException get() {
return new ForbiddenException();
}
}
| 28.78125 | 117 | 0.730727 |
7d9370183cd4fc67d14b7e83117d35889f7090ab | 998 | package frc.team832.robot.commands;
import edu.wpi.first.wpilibj2.command.InstantCommand;
import edu.wpi.first.wpilibj2.command.SequentialCommandGroup;
import edu.wpi.first.wpilibj2.command.WaitCommand;
import frc.team832.robot.subsystems.ConveyerSubsystem;
import frc.team832.robot.subsystems.ShooterSubsystem;
import frc.team832.robot.Constants.ConveyerConstants;
import frc.team832.robot.Constants.ShooterConstants;
public class QueueBallCommand extends SequentialCommandGroup {
public QueueBallCommand(ConveyerSubsystem conveyer, ShooterSubsystem shooter) {
addRequirements(conveyer, shooter);
addCommands(
new InstantCommand(() -> shooter.setPower(ShooterConstants.SHOOTER_QUEUING_POWER)),
new InstantCommand(() -> conveyer.setPower(ConveyerConstants.CONVEYER_QUEUING_POWER)),
new WaitCommand(5),
new InstantCommand (() -> conveyer.setPower(0)),
new InstantCommand (() -> shooter.setPower(0))
);
}
} | 45.363636 | 98 | 0.752505 |
380bd3ba427029c1a339ace652a6a4942cf1f086 | 12,859 | package ru.ps.vlcatv.remote.data;
import android.view.KeyEvent;
import androidx.annotation.ColorRes;
import androidx.databinding.BaseObservable;
import androidx.databinding.Observable;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableBoolean;
import androidx.databinding.ObservableField;
import androidx.databinding.ObservableInt;
import ru.ps.vlcatv.constanttag.DataTagVlcStatus;
import ru.ps.vlcatv.constanttag.DataUriApi;
import ru.ps.vlcatv.remote.AppMain;
import ru.ps.vlcatv.remote.BuildConfig;
import ru.ps.vlcatv.remote.R;
import ru.ps.vlcatv.remote.data.event.EventPlayHistoryChange;
import ru.ps.vlcatv.remote.data.event.EventPlayItemChange;
import ru.ps.vlcatv.remote.data.event.EventPlayStateChange;
import ru.ps.vlcatv.utils.json.JSONObject;
public class DataSharedControl extends BaseObservable {
private static final String TAG = DataSharedControl.class.getSimpleName();
//
public static final int BTN_LOOP = R.id.imgbtn_loop;
public static final int BTN_RANDOM = R.id.imgbtn_random;
public static final int BTN_REPEAT = R.id.imgbtn_repeat;
public static final int BTN_FULLSCREEN = R.id.imgbtn_fullscreen;
public static final int BTN_MUTE = R.id.imgbtn_vol_mute;
public static final int BTN_VOLUP = R.id.imgbtn_vol_up;
public static final int BTN_VOLDOWN = R.id.imgbtn_vol_down;
public static final int BTN_PLAY_BY_ID = R.id.imgebtn_history_play;
public static final int BTN_PLAY = R.id.imgbtn_play;
public static final int BTN_PAUSE = R.id.imgbtn_pause;
public static final int BTN_STOP = R.id.imgbtn_stop;
public static final int BTN_PREV = R.id.imgbtn_rev;
public static final int BTN_NEXT = R.id.imgbtn_next;
public static final int BTN_FWD = R.id.imgbtn_fwd;
public static final int BTN_REV = R.id.imgbtn_prev;
//
public static final int BTN_BACK = R.id.imgbtn_back;
public static final int BTN_HISTORY = R.id.imgbtn_history;
public static final int BTN_HISTORY_BACK = R.id.imgbtn_return;
public static final int BTN_UP = R.id.imgbtn_dpad_up;
public static final int BTN_DOWN = R.id.imgbtn_dpad_down;
public static final int BTN_LEFT = R.id.imgbtn_dpad_left;
public static final int BTN_RIGHT = R.id.imgbtn_dpad_right;
public static final int BTN_CENTER = R.id.imgbtn_dpad_center;
public static final int BTN_HOME = R.id.imgbtn_home;
public static final int BTN_SETUP = R.id.imgbtn_setup;
public static final int BTN_SETUPD = R.id.imgbtn_net_end;
public static final int BTN_TITLE = R.id.tv_title_close;
public static final int BTN_SEARCH = R.id.imgbtn_search;
public static final int BTN_MLIST = R.id.imgbtn_mlist;
public static final int BTN_ERROR = R.id.imgbtn_error;
public static final int BTN_ERRORD = R.id.tv_error;
public static final int BTN_ERRORE = 10001;
public static final int BTN_TOGGLE = 10002;
public static final int GET_STAT = 10003;
public static final int GET_MEDIA_ITEM = 10004;
public static final int GET_MEDIA_ITEMS = 10005;
///
public final ObservableField<String> Title = new ObservableField<>("");
public final ObservableField<String> FileName = new ObservableField<>("");
public final ObservableField<String> TimeType = new ObservableField<>("");
public final ObservableInt PlayId = new ObservableInt(-1);
public final ObservableInt AudioVolume = new ObservableInt(0);
public final ObservableInt TimeTotal = new ObservableInt(0);
public final ObservableInt TimeCurrent = new ObservableInt(0);
public final ObservableInt TimeRemain = new ObservableInt(0);
public final ObservableInt TimeTypeId = new ObservableInt(0);
public final ObservableInt PlayState = new ObservableInt(-1);
public final ObservableInt VlcApiVersion = new ObservableInt(-1);
public final ObservableBoolean PlayIsRepeat = new ObservableBoolean(false);
public final ObservableBoolean PlayIsLoop = new ObservableBoolean(false);
public final ObservableBoolean PlayIsRandom = new ObservableBoolean(false);
public final ObservableBoolean PlayIsFullscreen = new ObservableBoolean(false);
public final ObservableBoolean AppRun = new ObservableBoolean(false);
public final ObservableBoolean AppSetup = new ObservableBoolean(false);
public final ObservableBoolean AppTitle = new ObservableBoolean(false);
public final ObservableBoolean AppInfo = new ObservableBoolean(false);
public final ObservableBoolean AppHistory = new ObservableBoolean(false);
public final ObservableBoolean AppSearch = new ObservableBoolean(false);
public final ObservableBoolean AppError = new ObservableBoolean(false);
public final ObservableArrayList<String> SearchTag = new ObservableArrayList<>();
public DataMediaItem MmItem = new DataMediaItem();
public EventPlayHistoryChange eventHistory = new EventPlayHistoryChange();
public EventPlayStateChange eventState = new EventPlayStateChange();
public EventPlayItemChange eventItem = new EventPlayItemChange();
// virtual changer
public final ObservableBoolean StateChange = new ObservableBoolean();
private int colorTransparent;
private int colorActivate;
private int oldPlayId = -1;
public DataSharedControl() {
colorTransparent = AppMain.getAppResources().getColor(R.color.colorTransparent, null);
colorActivate = AppMain.getAppResources().getColor(R.color.colorAccent, null);
PlayId.addOnPropertyChangedCallback(
new OnPropertyChangedCallback() {
@Override
public void onPropertyChanged(Observable sender, int propertyId) {
eventItem.onChangeProperty(PlayId.get());
}
});
PlayState.addOnPropertyChangedCallback(
new OnPropertyChangedCallback() {
@Override
public void onPropertyChanged(Observable sender, int propertyId) {
eventState.onChangeProperty(PlayState.get());
}
});
Title.addOnPropertyChangedCallback(
new OnPropertyChangedCallback() {
@Override
public void onPropertyChanged(Observable sender, int propertyId) {
eventItem.onChangeProperty();
}
});
}
public void fromJson(JSONObject obj) {
if (obj == null)
return;
try {
Title.set(obj.optString(DataTagVlcStatus.TAG_TITLE, ""));
FileName.set(obj.optString(DataTagVlcStatus.TAG_FILE, ""));
PlayId.set(obj.optInt(DataTagVlcStatus.TAG_PLAYID, -1));
AudioVolume.set(obj.optInt(DataTagVlcStatus.TAG_VOLUME, 0));
TimeTypeId.set(obj.optInt(DataTagVlcStatus.TAG_TIME_FMT, 1));
TimeTotal.set(obj.optInt(DataTagVlcStatus.TAG_LENGTH, 0));
TimeCurrent.set(obj.optInt(DataTagVlcStatus.TAG_TIME, 0));
TimeRemain.set(TimeTotal.get() - TimeCurrent.get());
PlayState.set(obj.optInt(DataTagVlcStatus.TAG_STATE, -1));
VlcApiVersion.set(obj.optInt(DataTagVlcStatus.TAG_API, -1));
PlayIsRepeat.set(obj.optBoolean(DataTagVlcStatus.TAG_REPEAT, false));
PlayIsLoop.set(obj.optBoolean(DataTagVlcStatus.TAG_LOOP, false));
PlayIsRandom.set(obj.optBoolean(DataTagVlcStatus.TAG_RANDOM, false));
PlayIsFullscreen.set(obj.optBoolean(DataTagVlcStatus.TAG_FULLSCREEN, false));
if (TimeTypeId.get() > 0)
TimeType.set(
AppMain.getAppResources().getQuantityString(R.plurals.plurals_minutes, TimeRemain.get())
);
else
TimeType.set(
AppMain.getAppResources().getQuantityString(R.plurals.plurals_second, TimeRemain.get())
);
switch (PlayState.get())
{
case KeyEvent.KEYCODE_MEDIA_PLAY:
case KeyEvent.KEYCODE_MEDIA_PAUSE: {
if ((PlayId.get() > -1) && (oldPlayId != PlayId.get()))
AppMain.getMediaItem(PlayId.get());
}
}
} catch (Exception e) {
if (BuildConfig.DEBUG) AppMain.printError(e.getLocalizedMessage());
}
setStateChange();
oldPlayId = PlayId.get();
}
public String getCtrlCmd(int id)
{
switch (id)
{
case BTN_TOGGLE:
return DataUriApi.PLAY_TOGGLE;
case BTN_PLAY_BY_ID:
return DataUriApi.PLAY_ID;
case BTN_PLAY:
return DataUriApi.PLAY_PLAY;
case BTN_PAUSE:
return DataUriApi.PLAY_PAUSE;
case BTN_STOP:
return DataUriApi.PLAY_STOP;
case BTN_FWD:
return DataUriApi.PLAY_FORWARD;
case BTN_REV:
return DataUriApi.PLAY_REWIND;
case BTN_NEXT:
return DataUriApi.PLAY_NEXT_TRACK;
case BTN_PREV:
return DataUriApi.PLAY_PREVIOUS_TRACK;
case GET_MEDIA_ITEM:
return DataUriApi.GET_MEDIA_ITEM;
case GET_MEDIA_ITEMS:
return DataUriApi.GET_MEDIA_ITEMS;
case GET_STAT:
return DataUriApi.GET_STAT;
case BTN_VOLUP:
return DataUriApi.AUDIO_VOLUME_UP;
case BTN_VOLDOWN:
return DataUriApi.AUDIO_VOLUME_DOWN;
case BTN_MUTE:
return DataUriApi.AUDIO_VOLUME_MUTE;
case BTN_UP:
return DataUriApi.PAD_UP;
case BTN_DOWN:
return DataUriApi.PAD_DOWN;
case BTN_LEFT:
return DataUriApi.PAD_LEFT;
case BTN_RIGHT:
return DataUriApi.PAD_RIGHT;
case BTN_CENTER:
return DataUriApi.PAD_CENTER;
case BTN_BACK:
return DataUriApi.KEY_BACK;
case BTN_SEARCH:
return DataUriApi.GET_SEARCH_ACTIVITY;
case BTN_HOME: {
if (AppRun.get()) {
return DataUriApi.GET_MAIN_ACTIVITY;
} else {
return DataUriApi.KEY_BACK;
}
}
default:
return "";
}
}
public @ColorRes int getCtrlButtonBg(int id, ObservableBoolean ignoring)
{
switch (id) {
case BTN_REPEAT: {
return PlayIsRepeat.get() ? colorActivate : colorTransparent;
}
case BTN_RANDOM: {
return PlayIsRandom.get() ? colorActivate : colorTransparent;
}
case BTN_LOOP: {
return PlayIsLoop.get() ? colorActivate : colorTransparent;
}
case BTN_FULLSCREEN: {
return PlayIsFullscreen.get() ? colorActivate : colorTransparent;
}
case BTN_MUTE: {
return (AudioVolume.get() == 0) ? colorActivate : colorTransparent;
}
case BTN_VOLUP: {
return (AudioVolume.get() >= 90) ? colorActivate : colorTransparent;
}
case BTN_PLAY: {
return (PlayState.get() == KeyEvent.KEYCODE_MEDIA_PLAY) ? colorActivate : colorTransparent;
}
case BTN_PAUSE: {
return (PlayState.get() == KeyEvent.KEYCODE_MEDIA_PAUSE) ? colorActivate : colorTransparent;
}
case BTN_STOP: {
return ((PlayState.get() == KeyEvent.KEYCODE_MEDIA_STOP) || (PlayId.get() == -1)) ? colorActivate : colorTransparent;
}
case BTN_HOME: {
setStateChange();
return AppRun.get() ? colorActivate : colorTransparent;
}
case BTN_SEARCH: {
setStateChange();
return AppSearch.get() ? colorActivate : colorTransparent;
}
case BTN_SETUP: {
setStateChange();
return AppSetup.get() ? colorActivate : colorTransparent;
}
case BTN_HISTORY: {
setStateChange();
return AppHistory.get() ? colorActivate : colorTransparent;
}
default:
return colorTransparent;
}
}
private void setStateChange() {
StateChange.set(!StateChange.get());
}
public void clickStateChange() {
StateChange.set(!StateChange.get());
eventState.onChangeProperty(PlayState.get());
}
public boolean checkPlayState(int id) {
return (PlayState.get() == id);
}
}
| 42.863333 | 133 | 0.635819 |
67ee0c95cfb3249ee5cc3126847f3f8020078dd9 | 910 | package org.osmdroid.samplefragments.layouts.rec;
/**
* created on 1/13/2017.
*
* @author Alex O'Ree
*/
/**
* This class content Data
* <p>
* TypeLayout: type of layout to generate in recyclerview
*/
public class Info {
public String TypeLayout;
public String Title;
public String Content;
public Info(String typeLayout, String title, String content) {
TypeLayout = typeLayout;
Title = title;
Content = content;
}
public String getTitle() {
return Title;
}
public void setTitle(String title) {
Title = title;
}
public String getTypeLayout() {
return TypeLayout;
}
public void setTypeLayout(String typeLayout) {
TypeLayout = typeLayout;
}
public String getContent() {
return Content;
}
public void setContent(String content) {
Content = content;
}
}
| 17.169811 | 66 | 0.614286 |
2fe4bc09398baf7b02e72385b7ffcddedad914cc | 556 | import java.util.Scanner;
public class TimeConversion {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in=new Scanner(System.in);
int SecInNum=in.nextInt();
int hour=SecInNum/(60*60);
int remain=SecInNum-(hour*(3600));
int min=remain/60;
remain=remain-(min*60);
printmassege(hour,min,remain);
}
static void printmassege(int hour,int mins,int sec){
System.out.print(hour);
System.out.print(":");
System.out.print(mins);
System.out.print(":");
System.out.println(sec);
}
}
| 22.24 | 54 | 0.67446 |
cb140b83932fe309dae8200116a4aa41a3933ace | 713 | package cello.jtablet.installer.ui;
import java.io.File;
import java.net.URL;
public abstract class Download {
private final URL source;
private final File destination;
public Download(URL source, File destination) {
this.source = source;
this.destination = destination;
}
public abstract boolean hasStarted();
public abstract long getBytesDownloaded();
public abstract long getBytesTotal();
protected DownloadListener listener;
public void setListener(DownloadListener listener) {
this.listener = listener;
}
/**
* @return the source
*/
public URL getSource() {
return source;
}
/**
* @return the destination
*/
public File getDestination() {
return destination;
}
}
| 17.825 | 53 | 0.72791 |
9d1f34e21d675276cf18a00e319835df3de05f2b | 166 | package com.transwrap.transwrap.utils;
public interface SystemUtil {
boolean ISWINDOWS = System.getProperties().toString().toLowerCase().contains("windows");
}
| 23.714286 | 92 | 0.76506 |
7139a2be1d07a50a94de14b524cc383fa0c2f84e | 1,780 | package tree;
public class CollatzTree {
// prints tree diagram for tree representation of "reverse" Collatz sequences
public static void main(String[] args) {
TreeNode root;
root = collatzTree(15);
// Collatz Conjecture: for every positive integer X, there is some N such that X appears in collatzTree(N)
TreePrinter<TreeNode> printer = new TreePrinter<>(n -> ""+n.getValue(), n -> n.getLeft(), n -> n.getRight());
printer.setHspace(1);
printer.setSquareBranches(true);
printer.setLrAgnostic(true);
printer.printTree(root);
}
private static TreeNode collatzTree(int depth) {
return collatzTree(1, 1, depth);
}
private static TreeNode collatzTree(int start, int curLength, int maxLength) {
TreeNode root = new TreeNode(start);
if (curLength < maxLength) {
// Forward Collatz sequence has that an even number N is followed by N/2, which is either an even or odd number.
// So in reverse, either an even or odd number (any number) can be preceded by 2N.
root.setLeft(collatzTree(start*2, curLength+1, maxLength));
// Forward Collatz sequence has that an odd number N (i.e. a number of form 2X+1) is followed
// by 3N+1 (i.e. 3(2X+1)+1, or 6X+4).
// So in reverse, a number N of the form 6X+4 can be preceded by (N-1)/3 (N-1 is divisible by 3)
// But if N is 4, we don't want it preceded (in reverse) by 1, since in the forward direction,
// the sequence stops at 1 (or, in the reverse direction, 1 is where we started).
if (start%6==4 && start>4) root.setRight(collatzTree((start-1)/3, curLength+1, maxLength));
}
return root;
}
}
| 43.414634 | 124 | 0.626966 |
5d14c0c92d66fc164db77438b86b54691c230c0c | 2,783 | package com.example.dealball.main.course;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.example.dealball.main.course.friends.FriendsFragment;
import com.example.dealball.main.course.girl.GirlFragment;
import com.example.dealball.main.course.nearby.NearbyFragment;
import com.example.dealball.main.course.picture.PictureFragment;
import com.example.dealball.main.course.rank.RankFragment;
import com.example.dealball.main.course.recommend.RecommendFragment;
import com.example.dealball.main.course.video.VideoFragment;
public class CourseTabAdapter extends FragmentPagerAdapter {
private RecommendFragment recommendFragment;
private RankFragment rankFragment;
private FriendsFragment friendsFragment;
private GirlFragment girlFragment;
private NearbyFragment nearbyFragment;
private PictureFragment pictureFragment;
private VideoFragment videoFragment;
private String[] titles=new String[]{"推荐","排名","好友","附近","女生","图文","视频"};
public CourseTabAdapter(FragmentManager fm) {
super(fm);
recommendFragment=new RecommendFragment();
rankFragment=new RankFragment();
friendsFragment=new FriendsFragment();
girlFragment=new GirlFragment();
nearbyFragment=new NearbyFragment();
pictureFragment=new PictureFragment();
videoFragment=new VideoFragment();
}
@Override
public int getItemPosition(Object object) {
if (object instanceof RecommendFragment) {
return 0;
} else if(object instanceof RankFragment){
return 1;
}else if(object instanceof FriendsFragment){
return 2;
}else if(object instanceof GirlFragment){
return 3;
}else if(object instanceof NearbyFragment){
return 4;
}else if(object instanceof PictureFragment){
return 5;
}else{
return 6;
}
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return recommendFragment;
case 1:
return rankFragment;
case 2:
return friendsFragment;
case 3:
return girlFragment;
case 4:
return nearbyFragment;
case 5:
return pictureFragment;
case 6:
return videoFragment;
default:
return recommendFragment;
}
}
@Override
public int getCount() {
return titles.length;
}
@Override
public CharSequence getPageTitle(int position) {
return titles[position];
}
}
| 31.269663 | 77 | 0.652533 |
f76cec202421d50166f090144988fac81c3eeb9d | 18,790 | package org.basex.data.atomic;
import java.util.*;
import org.basex.data.*;
import org.basex.util.*;
import org.basex.util.hash.*;
/**
* A container/list for atomic updates. Updates are then carried out in the same order
* that they have been added. No reordering takes place. The user is responsible to add
* them in the correct order.
*
* Updates must be strictly ordered from the highest to the lowest PRE value, otherwise
* an exception is returned.
*
*
* If a collection of updates is carried out via this container there are several
* benefits:
*
* 1) Caching distance updates of the table due to structural changes and carrying them
* out in an efficient manner.
* 2) Tree-Aware Updates: identification of superfluous updates (like updating the
* descendants of a deleted node).
* 3) Merging of adjacent text nodes which are not allowed (see XDM).
*
*
* Mind that two delete atomics on a list targeting the same PRE value location result in
* two nodes A and B being deleted, due to PRE value shifts after the first delete,
* where pre(B) = pre(A) + 1. If a list of atomic updates is prepared for execution it
* should be ordered from the highest to the lowest PRE value.
*
* To avoid ambiguity it is not allowed to add:
* - more than one destructive update like {@link Delete} or {@link Replace} operating on
* the same node.
* - more than one {@link Rename} or {@link UpdateValue} operating on the same node.
*
* @author BaseX Team 2005-12, BSD License
* @author Lukas Kircher
*/
public final class AtomicUpdateList {
/** List of structural updates (nodes are inserted to / deleted from the table. */
private final List<BasicUpdate> updStructural;
/** List of value updates. */
private final List<BasicUpdate> updValue;
/** Target data reference. */
public final Data data;
/** States if update constraints have been checked. */
private boolean ok;
/** States if update haven been optimized. */
private boolean opt;
/** States if this list has been merged, hence accumulations are invalid. */
private boolean dirty;
/**
* Constructor.
* @param d target data reference
*/
public AtomicUpdateList(final Data d) {
updStructural = new ArrayList<BasicUpdate>();
updValue = new ArrayList<BasicUpdate>();
data = d;
}
/**
* Adds a delete atomic to the list.
* @param pre PRE value of the target node/update location
*/
public void addDelete(final int pre) {
final int k = data.kind(pre);
final int s = data.size(pre, k);
add(new Delete(pre, -s, pre + s), true);
}
/**
* Adds an insert atomic to the list.
* @param pre PRE value of the target node/update location
* @param par new parent of the inserted nodes
* @param clip insertion sequence data clip
* @param attr insert attribute if true or a node of any other kind if false
*/
public void addInsert(final int pre, final int par, final DataClip clip,
final boolean attr) {
add(attr ? new InsertAttr(pre, par, clip) : new Insert(pre, par, clip), true);
}
/**
* Adds a replace atomic to the list.
* @param pre PRE value of the target node/update location
* @param clip insertion sequence data clip
*/
public void addReplace(final int pre, final DataClip clip) {
final int oldsize = data.size(pre, data.kind(pre));
final int newsize = clip.size();
add(new Replace(pre, newsize - oldsize, pre + oldsize, clip), true);
}
/**
* Adds a rename atomic to the list.
* @param pre PRE value of the target node/update location
* @param k kind of the target node
* @param n new name for the target node
* @param u new uri for the target node
*/
public void addRename(final int pre, final int k, final byte[] n, final byte[] u) {
add(new Rename(pre, k, n, u), false);
}
/**
* Adds an updateValue atomic to the list.
* @param pre PRE value of the target node/update location
* @param k kind of the target node
* @param v new value for the target node
*/
public void addUpdateValue(final int pre, final int k, final byte[] v) {
add(new UpdateValue(pre, k, v), false);
}
/**
* Returns the number of structural updates.
* @return number of structural updates
*/
public int structuralUpdatesSize() {
return updStructural.size();
}
/**
* Resets the list.
*/
public void clear() {
updStructural.clear();
updValue.clear();
dirty();
}
/**
* Adds an update to the corresponding list.
* @param u atomic update
* @param s true if given update performs structural changes, false if update only
* alters values
*/
private void add(final BasicUpdate u, final boolean s) {
if(s) updStructural.add(u);
else updValue.add(u);
dirty();
}
/**
* Adds all updates in a given list B to the end of the updates in this list (A).
*
* As updates must be unambiguous and are ordered from the highest to the lowest PRE
* value, make sure that all updates in B access PRE values smaller than any update
* in A.
*
* Mainly used to resolve text node adjacency.
*
* @param toMerge given list that is appended to the end of this list
*/
private void merge(final AtomicUpdateList toMerge) {
updStructural.addAll(toMerge.updStructural);
updValue.addAll(toMerge.updValue);
dirty();
}
/**
* Marks this list dirty.
*/
private void dirty() {
ok = false;
opt = false;
dirty = true;
}
/**
* Checks the list of updates for violations. Updates must be ordered strictly from
* the highest to the lowest PRE value.
*
* A single node must not be affected by more than one {@link Rename},
* {@link UpdateValue} operation.
*
* A single node must not be affected by more than one destructive operation. These
* operations include {@link Replace}, {@link Delete}.
*/
public void check() {
if(ok || updStructural.size() < 2 && updValue.size() < 2) return;
int i = 0;
while(i + 1 < updStructural.size()) {
final BasicUpdate current = updStructural.get(i);
final BasicUpdate next = updStructural.get(++i);
// check order of location PRE
if(current.location < next.location)
Util.notexpected("Invalid order at location " + current.location);
// check multiple {@link Delete}, {@link Replace}
if(current.location == next.location &&
current.destructive() && next.destructive())
Util.notexpected("Multiple deletes/replaces on node " + current.location);
}
i = 0;
while(i + 1 < updValue.size()) {
final BasicUpdate current = updValue.get(i++);
final BasicUpdate next = updValue.get(i);
// check order of location PRE
if(current.location < next.location)
Util.notexpected("Invalid order at location " + current.location);
if(current.location == next.location) {
// check multiple {@link Rename}
if(current instanceof Rename && next instanceof Rename)
Util.notexpected("Multiple renames on node " + current.location);
// check multiple {@link UpdateValue}
if(current instanceof UpdateValue && next instanceof UpdateValue)
Util.notexpected("Multiple updates on node " + current.location);
}
}
ok = true;
}
/**
* Removes superfluous update operations. If a node T is deleted or replaced, all
* updates on the descendant axis of T can be left out as they won't affect the database
* after all.
*
* Superfluous updates can have a minimum PRE value of pre(T)+1 and a maximum PRE value
* of pre(T)+size(T).
*
* An update with location pre(T)+size(T) can only be removed if the update is an
* atomic insert and the inserted node is then part of the subtree of T.
*/
public void optimize() {
if(opt) return;
check();
// traverse from lowest to highest PRE value
int i = updStructural.size() - 1;
while(i >= 0) {
final BasicUpdate u = updStructural.get(i);
// If this update can lead to superfluous updates ...
if(u.destructive()) {
// we determine the lowest and highest PRE values of a superfluous update
final int pre = u.location;
final int fol = pre + data.size(pre, data.kind(pre));
i--;
// and have a look at the next candidate
while(i >= 0) {
final BasicUpdate desc = updStructural.get(i);
final int descpre = desc.location;
// if the candidate operates on the subtree of T and inserts a node ...
if(descpre <= fol && (desc instanceof Insert || desc instanceof InsertAttr) &&
desc.parent() >= pre && desc.parent() < fol) {
// it is removed.
updStructural.remove(i--);
// Other updates (not inserting a node) that operate on the subtree of T can
// only have a PRE value that is smaller than the following PRE of T
} else if(descpre < fol) {
// these we delete.
updStructural.remove(i--);
// Else there's nothing to delete
} else
break;
}
} else
i--;
}
opt = true;
}
/**
* Executes the updates. Resolving text node adjacency can be skipped if adjacent text
* nodes are not to be expected.
* @param mergeTexts adjacent text nodes are to be expected and must be merged
*/
public void execute(final boolean mergeTexts) {
check();
optimize();
applyValueUpdates();
data.cache = true;
applyStructuralUpdates();
updateDistances();
if(mergeTexts) resolveTextAdjacency();
data.cache = false;
}
/**
* Carries out structural updates.
*/
public void applyStructuralUpdates() {
accumulatePreValueShifts();
for(final BasicUpdate t : updStructural)
t.apply(data);
}
/**
* Carries out value updates.
*/
public void applyValueUpdates() {
for(final BasicUpdate t : updValue) t.apply(data);
}
/**
* Calculates the accumulated PRE value shifts for all updates on the list.
*/
private void accumulatePreValueShifts() {
if(!dirty) return;
int s = 0;
for(int i = updStructural.size() - 1; i >= 0; i--) {
final BasicUpdate t = updStructural.get(i);
s += t.shifts;
t.accumulatedShifts = s;
}
dirty = false;
}
/**
* Updates distances to restore parent-child relationships that have been invalidated
* by structural updates.
*
* Each structural update (insert/delete) leads to a shift of higher PRE values. This
* invalidates parent-child relationships. Distances are only updated after all
* structural updates have been carried out to make sure each node (that has to be
* updated) is only touched once.
*/
private void updateDistances() {
accumulatePreValueShifts();
final IntSet alreadyUpdatedNodes = new IntSet();
for(final BasicUpdate update : updStructural) {
int newPreOfAffectedNode = update.preOfAffectedNode + update.accumulatedShifts;
/* Update distance for the affected node and all following siblings of nodes
* on the ancestor-or-self axis. */
while(newPreOfAffectedNode < data.meta.size) {
if(alreadyUpdatedNodes.contains(newPreOfAffectedNode)) break;
data.dist(newPreOfAffectedNode, data.kind(newPreOfAffectedNode),
calculateNewDistance(newPreOfAffectedNode));
alreadyUpdatedNodes.add(newPreOfAffectedNode);
newPreOfAffectedNode +=
data.size(newPreOfAffectedNode, data.kind(newPreOfAffectedNode));
}
}
}
/**
* Calculates the new distance value for the given node.
* @param preAfter the current PRE value of the node (after structural updates have
* been applied)
* @return new distance for the given node
*/
private int calculateNewDistance(final int preAfter) {
final int kind = data.kind(preAfter);
final int distanceBefore = data.dist(preAfter, kind);
final int preBefore = calculatePreValue(preAfter, true);
final int parentBefore = preBefore - distanceBefore;
final int parentAfter = calculatePreValue(parentBefore, false);
return preAfter - parentAfter;
}
/**
* Calculates the PRE value of a given node before/after updates.
*
* Finds all updates that affect the given node N. The result is than calculated based
* on N and the accumulated PRE value shifts introduced by these updates.
*
* If a node has been inserted at position X and this method is used to calculate the
* PRE value of X before updates, X is the result. As the node at position X has not
* existed before the insertion, its PRE value is unchanged. If in contrast the PRE
* value is calculated after updates, the result is X+1, as the node with the original
* position X has been shifted by the insertion at position X.
*
* Make sure accumulated shifts have been calculated before calling this method!
*
* @param pre PRE value
* @param beforeUpdates calculate PRE value before shifts/updates have been applied
* @return index of update, or -1
*/
public int calculatePreValue(final int pre, final boolean beforeUpdates) {
int i = find(pre, beforeUpdates);
// given PRE not changed by updates
if(i == -1) return pre;
i = refine(updStructural, i, beforeUpdates);
final int acm = updStructural.get(i).accumulatedShifts;
return beforeUpdates ? pre - acm : pre + acm;
}
/**
* Finds the position of the update with the lowest index that affects the given PRE
* value P. If there are multiple updates whose affected PRE value equals P, the search
* has to be further refined as this method returns the first match.
* @param pre given PRE value
* @param beforeUpdates compare based on PRE values before/after updates
* @return index of update
*/
private int find(final int pre, final boolean beforeUpdates) {
int left = 0;
int right = updStructural.size() - 1;
while(left <= right) {
if(left == right) {
if(c(updStructural, left, beforeUpdates) <= pre) return left;
return -1;
}
if(right - left == 1) {
if(c(updStructural, left, beforeUpdates) <= pre) return left;
if(c(updStructural, right, beforeUpdates) <= pre) return right;
return -1;
}
final int middle = left + right >>> 1;
final int value = c(updStructural, middle, beforeUpdates);
if(value == pre) return middle;
else if(value > pre) left = middle + 1;
else right = middle;
}
// empty array
return -1;
}
/**
* Finds the update with the lowest index in the given list that affects the same
* PRE value as the update with the given index.
* @param l list of updates
* @param index of update
* @param beforeUpdates find update for PRE values before updates have been applied
* @return update with the lowest index that invalidates the distance of the same node
* as the given one
*/
private static int refine(final List<BasicUpdate> l, final int index,
final boolean beforeUpdates) {
int i = index;
final int value = c(l, i--, beforeUpdates);
while(i >= 0 && c(l, i, beforeUpdates) == value) i--;
return i + 1;
}
/**
* Recalculates the PRE value of the first node whose distance is affected by the
* given update.
* @param l list of updates
* @param index index of the update
* @param beforeUpdates calculate PRE value before or after updates
* @return PRE value
*/
private static int c(final List<BasicUpdate> l, final int index,
final boolean beforeUpdates) {
final BasicUpdate u = l.get(index);
return u.preOfAffectedNode + (beforeUpdates ? u.accumulatedShifts : 0);
}
/**
* Resolves unwanted text node adjacency which can result from structural changes in
* the database. Adjacent text nodes are two text nodes A and B, where
* PRE(B)=PRE(A)+1 and PARENT(A)=PARENT(B).
*/
private void resolveTextAdjacency() {
// Text node merges are also gathered on a separate list to leverage optimizations.
final AtomicUpdateList allMerges = new AtomicUpdateList(data);
// keep track of the visited locations to avoid superfluous checks
final IntSet s = new IntSet();
// Text nodes have to be merged from the highest to the lowest pre value
for(final BasicUpdate u : updStructural) {
final DataClip insseq = u.getInsertionData();
// calculate the new location of the update, here we have to check for adjacency
final int newLocation = u.location + u.accumulatedShifts - u.shifts;
final int beforeNewLocation = newLocation - 1;
// check surroundings of this location for adjacent text nodes depending on the
// kind of update, first the one with higher PRE values (due to shifts!)
// ... for insert/replace ...
if(insseq != null) {
// calculate the current following node
final int followingNode = newLocation + insseq.size();
final int beforeFollowingNode = followingNode - 1;
// check the nodes at the end of/after the insertion sequence
if(!s.contains(beforeFollowingNode)) {
final AtomicUpdateList merges = necessaryMerges(beforeFollowingNode);
merges.mergeNodes();
allMerges.merge(merges);
s.add(beforeFollowingNode);
}
}
// check nodes for delete and for insert before the updated location
if(!s.contains(beforeNewLocation)) {
final AtomicUpdateList merges = necessaryMerges(beforeNewLocation);
merges.mergeNodes();
allMerges.merge(merges);
s.add(beforeNewLocation);
}
}
allMerges.updateDistances();
allMerges.clear();
}
/**
* Applies text node merges.
*/
private void mergeNodes() {
check();
applyValueUpdates();
applyStructuralUpdates();
}
/**
* Returns atomic text node merging operations if necessary for the given node PRE and
* its right neighbor PRE+1.
* @param a node PRE value
* @return list of text merging operations
*/
private AtomicUpdateList necessaryMerges(final int a) {
final AtomicUpdateList mergeTwoNodes = new AtomicUpdateList(data);
final int s = data.meta.size;
final int b = a + 1;
// don't leave table
if(a >= s || b >= s || a < 0 || b < 0) return mergeTwoNodes;
// only merge texts
if(data.kind(a) != Data.TEXT || data.kind(b) != Data.TEXT) return mergeTwoNodes;
// only merge neighboring texts
if(data.parent(a, Data.TEXT) != data.parent(b, Data.TEXT)) return mergeTwoNodes;
mergeTwoNodes.addDelete(b);
mergeTwoNodes.addUpdateValue(a, Data.TEXT,
Token.concat(data.text(a, true), data.text(b, true)));
return mergeTwoNodes;
}
} | 35.187266 | 90 | 0.664822 |
264441312cf2920e1f7c1abcc82496c141443ed1 | 878 | package io.agora.propeller;
import android.view.SurfaceView;
public class VideoStatusData {
public static final int DEFAULT_STATUS = 0;
public static final int VIDEO_MUTED = 1;
public static final int AUDIO_MUTED = VIDEO_MUTED << 1;
public static final int DEFAULT_VOLUME = 0;
public VideoStatusData(int uid, SurfaceView view, int status, int volume) {
this.mUid = uid;
this.mView = view;
this.mStatus = status;
this.mVolume = volume;
}
public int mUid;
public SurfaceView mView;
public int mStatus;
public int mVolume;
@Override
public String toString() {
return "VideoStatusData{" +
"uid=" + (mUid & 0xFFFFFFFFL) +
", mView=" + mView +
", mStatus=" + mStatus +
", mVolume=" + mVolume +
'}';
}
}
| 23.72973 | 79 | 0.583144 |
0b9b7f2e1e8154078bb7282b63da2d3cb188c83d | 5,694 | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.autofill.keyboard_accessory;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.support.v7.content.res.AppCompatResources;
import android.support.v7.widget.RecyclerView;
import android.view.ViewGroup;
import org.chromium.base.VisibleForTesting;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.ChromeFeatureList;
import org.chromium.chrome.browser.autofill.keyboard_accessory.AccessorySheetTabModel.AccessorySheetDataPiece;
import org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryData.AccessorySheetData;
import org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryData.Provider;
import org.chromium.ui.modelutil.ListModel;
import org.chromium.ui.modelutil.RecyclerViewAdapter;
import org.chromium.ui.modelutil.SimpleRecyclerViewMcp;
/**
* This component is a tab that can be added to the {@link ManualFillingCoordinator} which shows it
* as bottom sheet below the keyboard accessory.
*/
public class PasswordAccessorySheetCoordinator extends AccessorySheetTabCoordinator {
private final AccessorySheetTabModel mModel = new AccessorySheetTabModel();
private final PasswordAccessorySheetMediator mMediator;
@VisibleForTesting
static class IconProvider {
private final static IconProvider sInstance = new IconProvider();
private Drawable mIcon;
private IconProvider() {}
public static IconProvider getInstance() {
return sInstance;
}
/**
* Loads and remembers the icon used for this class. Used to mock icons in unit tests.
* @param context The context containing the icon resources.
* @return The icon as {@link Drawable}.
*/
public Drawable getIcon(Context context) {
if (mIcon != null) return mIcon;
mIcon = AppCompatResources.getDrawable(context, R.drawable.ic_vpn_key_grey);
return mIcon;
}
@VisibleForTesting
void setIconForTesting(Drawable icon) {
mIcon = icon;
}
}
/**
* Creates the passwords tab.
* @param context The {@link Context} containing resources like icons and layouts for this tab.
* @param scrollListener An optional listener that will be bound to the inflated recycler view.
*/
public PasswordAccessorySheetCoordinator(
Context context, @Nullable RecyclerView.OnScrollListener scrollListener) {
super(IconProvider.getInstance().getIcon(context),
context.getString(R.string.password_accessory_sheet_toggle),
context.getString(R.string.password_accessory_sheet_opened),
R.layout.password_accessory_sheet, AccessoryTabType.PASSWORDS, scrollListener);
mMediator = new PasswordAccessorySheetMediator(mModel);
}
@Override
public void onTabCreated(ViewGroup view) {
super.onTabCreated(view);
if (ChromeFeatureList.isEnabled(ChromeFeatureList.AUTOFILL_KEYBOARD_ACCESSORY)) {
PasswordAccessorySheetModernViewBinder.initializeView((RecyclerView) view, mModel);
} else {
PasswordAccessorySheetViewBinder.initializeView((RecyclerView) view, mModel);
}
}
@Override
public void onTabShown() {
mMediator.onTabShown();
}
/**
* Registers the provider pushing a complete new instance of {@link AccessorySheetData} that
* should be displayed as sheet for this tab.
* @param accessorySheetDataProvider A {@link Provider<AccessorySheetData>}.
*/
void registerDataProvider(Provider<AccessorySheetData> accessorySheetDataProvider) {
accessorySheetDataProvider.addObserver(mMediator);
}
/**
* Creates an adapter to an {@link PasswordAccessorySheetViewBinder} that is wired
* up to a model change processor listening to the {@link AccessorySheetTabModel}.
* @param model the {@link AccessorySheetTabModel} the adapter gets its data from.
* @return Returns a fully initialized and wired adapter to a PasswordAccessorySheetViewBinder.
*/
static RecyclerViewAdapter<AccessorySheetTabViewBinder.ElementViewHolder, Void> createAdapter(
AccessorySheetTabModel model) {
return new RecyclerViewAdapter<>(
new SimpleRecyclerViewMcp<>(model, AccessorySheetDataPiece::getType,
AccessorySheetTabViewBinder.ElementViewHolder::bind),
PasswordAccessorySheetViewBinder::create);
}
/**
* Creates an adapter to an {@link PasswordAccessorySheetModernViewBinder} that is wired up to
* the model change processor which listens to the {@link AccessorySheetTabModel}.
* @param model the {@link AccessorySheetTabModel} the adapter gets its data from.
* @return Returns an {@link PasswordAccessorySheetModernViewBinder} wired to a MCP.
*/
static RecyclerViewAdapter<AccessorySheetTabViewBinder.ElementViewHolder, Void>
createModernAdapter(ListModel<AccessorySheetDataPiece> model) {
return new RecyclerViewAdapter<>(
new SimpleRecyclerViewMcp<>(model, AccessorySheetDataPiece::getType,
AccessorySheetTabViewBinder.ElementViewHolder::bind),
PasswordAccessorySheetModernViewBinder::create);
}
@VisibleForTesting
AccessorySheetTabModel getSheetDataPiecesForTesting() {
return mModel;
}
}
| 43.8 | 110 | 0.727081 |
018f9eecc4be7c6221e6f556e8cc3594f72d1375 | 1,590 | package com.javaweb.context;
import java.util.Map;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
//new ClassPathXmlApplicationContext(xmlFilePath).getBean(beanName)
public class ApplicationContextHelper implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ApplicationContextHelper.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext(){
return applicationContext;
}
public static Object getBean(String beanName) {
return applicationContext.getBean(beanName);
}
/**
使用示例:
@Component
public class IdGenerator implements IdentifierGenerator {
public Long nextId(Object entity) {
return SecretUtil.defaultGenPkNumForLong(String.valueOf(SystemConstant.SYSTEM_NO));
}
}
Map<String,IdentifierGenerator> map = applicationContext.getBeansOfType(IdentifierGenerator.class);
IdentifierGenerator ig = map.get("idGenerator");
System.out.println(ig.nextId(null));
//ServiceLoader<IdentifierGenerator> loader = ServiceLoader.load(IdentifierGenerator.class);
//System.err.println(loader);
*/
public static <T> Map<String,? extends T> getInterfaceImpl(Class<T> interfaceClass){
return applicationContext.getBeansOfType(interfaceClass);
}
}
| 35.333333 | 103 | 0.755346 |
66aae6faf1ad15d0ac3bf25e7f611474ad788bef | 1,880 | /*
* Copyright 2020 Alibaba Group Holding Limited.
*
* 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.alibaba.graphscope.gaia.plan.meta.object;
import com.google.common.base.Objects;
import java.util.UUID;
public class TraverserElement {
private UUID uuid;
// composite class
private CompositeObject object;
public TraverserElement(CompositeObject object) {
this.object = object;
this.uuid = UUID.randomUUID();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TraverserElement that = (TraverserElement) o;
return Objects.equal(uuid, that.uuid);
}
@Override
public int hashCode() {
return Objects.hashCode(uuid);
}
public CompositeObject getObject() {
return object;
}
public TraverserElement fork() {
if (!object.isGraphElement()) {
return new TraverserElement(object);
} else if (object.getElement() instanceof Vertex) {
return new TraverserElement(new CompositeObject(new Vertex()));
} else if (object.getElement() instanceof Edge) {
return new TraverserElement(new CompositeObject(new Edge()));
} else {
throw new UnsupportedOperationException();
}
}
}
| 30.819672 | 75 | 0.668085 |
15fdde96ca84290f2463b2b0dfa7d43f49cc919a | 5,852 | /*
* 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 co.edu.uniandes.csw.incidencias.resources;
import co.edu.uniandes.csw.incidencias.dtos.IncidenciaDTO;
import co.edu.uniandes.csw.incidencias.dtos.IncidenciaDetailDTO;
import co.edu.uniandes.csw.incidencias.ejb.IncidenciaLogic;
import co.edu.uniandes.csw.incidencias.entities.IncidenciaEntity;
import co.edu.uniandes.csw.incidencias.exceptions.BusinessLogicException;
import java.util.ArrayList;
import java.util.List;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author estudiante
*/
@Path("Incidencias")
@Produces("application/json")
@Consumes("application/json")
@RequestScoped
public class IncidenciaResource {
//transforma a DTO
private static final Logger LOGGER = Logger.getLogger(IncidenciaResource.class.getName());
private static final String NE = " no existe.";
private static final String RA = "El recurso /calificacions/";
@Inject
private IncidenciaLogic logic;
/**
*
* @param incidencia
* @return
* @throws BusinessLogicException
*/
@POST
public IncidenciaDTO createIncidencia(IncidenciaDTO incidencia) {
try {
LOGGER.log(Level.INFO, "BookResource createBook: input: {0}", incidencia);
IncidenciaDTO nuevoBookDTO = new IncidenciaDTO(logic.createIncidencia(incidencia.toEntity()));
LOGGER.log(Level.INFO, "IncidenciaResource createIncidencia: output: {0}", nuevoBookDTO);
return nuevoBookDTO;
} catch (BusinessLogicException ex) {
Logger.getLogger(IncidenciaResource.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
/**
*
* @return
*/
@GET
public List<IncidenciaDetailDTO> getIncidencias() {
LOGGER.info("IncidenciaResource getIncidencias: input: void");
List<IncidenciaDetailDTO> listaBooks = listEntity2DetailDTO(logic.getIncidencias());
LOGGER.log(Level.INFO, "IncidenciaResource getIncidencias: output: {0}", listaBooks);
return listaBooks;
}
/**
*
* @param incidenciaId
* @return
*/
@GET
@Path("{IncidenciaId: \\d+}")
public IncidenciaDetailDTO getIncidencia(@PathParam("IncidenciaId") Long incidenciaId) {
LOGGER.log(Level.INFO, "IncidenciaResource getIncidencia: input: {0}", incidenciaId);
IncidenciaEntity incidenciaEntity = logic.getIncidencia(incidenciaId);
if (incidenciaEntity == null) {
throw new WebApplicationException(RA+ incidenciaId + NE, 404);
}
IncidenciaDetailDTO bookDetailDTO = new IncidenciaDetailDTO(incidenciaEntity);
LOGGER.log(Level.INFO, "IncidenciaResource getIncidencia: output: {0}", bookDetailDTO);
return bookDetailDTO;
}
/**
* Actualiza una incidencia
* @param incidenciaId
* @param incidencia
* @return
* @throws BusinessLogicException
*/
@PUT
@Path("{IncidenciaId: \\d+}")
public IncidenciaDetailDTO updateBook(@PathParam("IncidenciaId") Long incidenciaId, IncidenciaDetailDTO incidencia) throws BusinessLogicException {
LOGGER.log(Level.INFO, "IncidenciaResource updateIncidencias: input: id: {0} , book: {1}", new Object[]{incidenciaId, incidencia});
incidencia.setId(incidenciaId);
if (logic.getIncidencia(incidenciaId) == null) {
throw new WebApplicationException(RA+ incidenciaId + NE, 404);
}
IncidenciaDetailDTO detailDTO = new IncidenciaDetailDTO(logic.updateIncidencia(incidenciaId, incidencia.toEntity()));
LOGGER.log(Level.INFO, "IncidenciaResource updateIncidencia: output: {0}", detailDTO);
return detailDTO;
}
/**
*
* @param incidenciasId
* @throws BusinessLogicException
*/
@DELETE
@Path("{IncidenciasId: \\d+}")
public void deleteBook(@PathParam("IncidenciasId") Long incidenciasId) throws BusinessLogicException {
LOGGER.log(Level.INFO, "IncidenciaResource deleteIncidencia: input: {0}", incidenciasId);
IncidenciaEntity entity = logic.getIncidencia(incidenciasId);
if (entity == null) {
throw new WebApplicationException(RA + incidenciasId + NE, 404);
}
logic.deleteIncidencia(incidenciasId);
LOGGER.info("IncidenciaResource deleteIncidencia: output: void");
}
/**
*
* @param entityList
* @return
*/
private List<IncidenciaDetailDTO> listEntity2DetailDTO(List<IncidenciaEntity> entityList) {
List<IncidenciaDetailDTO> list = new ArrayList<>();
for (IncidenciaEntity entity : entityList) {
list.add(new IncidenciaDetailDTO(entity));
}
return list;
}
/**
*
*
* @param incidenciasId
* @return
*/
@Path("{IncidenciasId: \\d+}/actuaciones")
public Class<ActuacionResource> getActuacionResource(@PathParam("IncidenciasId") Long incidenciasId) {
if (logic.getIncidencia(incidenciasId) == null) {
throw new WebApplicationException("El recurso /Incidencias/" + incidenciasId + "/actuaciones no existe.", 404);
}
return ActuacionResource.class;
}
}
| 35.253012 | 152 | 0.665584 |
b87222496f5b3a0ddccb64f5b0ca64f7fc84aaf5 | 375 | package faced.extend.server;
/**
* B模块.
*
* @author Zhang.Ge
* @version v1.0 2017年3月26日 下午2:25:07
*/
public class BModule {
public void api1() {
System.out.println("B模块接口1");
}
public void api2() {
System.out.println("B模块接口2");
}
public void api3() {
System.out.println("B模块接口3");
}
}
| 16.304348 | 39 | 0.514667 |
8e2428cb6cef121c7c7c0cc62ca150f3eefa0e8e | 3,977 | package iotserver;
import java.io.*;
import java.net.*;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.simple.*;
import org.json.simple.parser.*;
public class ConnectionHandler extends Thread {
final DataInputStream dis;
final DataOutputStream dos;
final Socket s;
final ServerGui gui;
// Constructor
public ConnectionHandler(Socket s, ServerGui _gui) throws IOException, ParseException {
this.gui = _gui;
this.s = s;
this.dis = new DataInputStream(s.getInputStream());
this.dos = new DataOutputStream(s.getOutputStream());
}
@Override
public void run() {
boolean auth = false;
while (true) {
try {
String received = dis.readUTF();
JSONParser jsonParser = new JSONParser();
Object obj = jsonParser.parse(received);
JSONObject message = (JSONObject) obj;
if (message.containsKey("AUTHUSER")) {
JSONObject userDetails = (JSONObject) message.get("AUTHUSER");
String userName = (String) userDetails.get("username");
String password = (String) userDetails.get("password");
auth = Authenticator.authClient(userName, password);
Logs.Log.log(Level.INFO, "Authenticating user credentials...");
dos.writeBoolean(auth);
if (auth) {
IotServer.clients.add(s);
gui.ClientCounterIncrement();
Logs.Log.log(Level.CONFIG, "Login approved, new client successfully connected");
} else {
s.close();
Thread.currentThread().interrupt();
Logs.Log.log(Level.WARNING, "Incorrect credentials, client shutting down...");
}
} else if (message.containsKey("AUTHSENSOR")) {
JSONObject userDetails = (JSONObject) message.get("AUTHSENSOR");
String sensorName = (String) userDetails.get("sensorName");
String password = (String) userDetails.get("password");
Logs.Log.log(Level.INFO, "Authenticating sensor credentials...");
boolean sensorAuth = Authenticator.authSensor(sensorName, password);
dos.writeBoolean(sensorAuth);
if (!sensorAuth) {
s.close();
Thread.currentThread().interrupt();
Logs.Log.log(Level.SEVERE, "Sensor could not be authenticated, terminating...");
}
} else {
s.close();
Thread.currentThread().interrupt();
Logs.Log.log(Level.WARNING, "Unexpected error, information is neither Sensor or User data");
}
while (true) {
received = dis.readUTF();
Iterator i = IotServer.clients.iterator();
while (i.hasNext()) {
Socket sock = (Socket) i.next();
try {
DataOutputStream output = new DataOutputStream(sock.getOutputStream());
output.writeUTF(received);
} catch (IOException e) {
IotServer.clients.remove(sock);
}
}
}
} catch (IOException e) {
IotServer.clients.remove(this.s);
if (auth) {
gui.ClientCounterDecrement();
}
break;
} catch (ParseException ex) {
Logger.getLogger(ConnectionHandler.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
| 41.427083 | 112 | 0.508926 |
9f7687ad39355122043492404aadf394409f9fa4 | 2,093 | package org.squiddev.plethora.core.builder;
import com.google.common.base.Strings;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Type;
import org.squiddev.plethora.api.method.IMethodBuilder;
import org.squiddev.plethora.api.method.IUnbakedContext;
import org.squiddev.plethora.api.method.MethodBuilder;
import org.squiddev.plethora.api.module.IModuleContainer;
import org.squiddev.plethora.api.module.SubtargetedModuleMethod;
import javax.annotation.Nonnull;
import java.lang.reflect.Method;
import static org.objectweb.asm.Opcodes.*;
@IMethodBuilder.Inject(SubtargetedModuleMethod.Inject.class)
public class SubtargetedModuleMethodBuilder extends MethodBuilder<SubtargetedModuleMethod.Inject> {
public SubtargetedModuleMethodBuilder() throws NoSuchMethodException {
super(SubtargetedModuleMethod.class.getMethod("apply", IUnbakedContext.class, Object[].class), SubtargetedModuleMethod.class);
}
@Override
public Class<?> getTarget(@Nonnull Method method, @Nonnull SubtargetedModuleMethod.Inject annotation) {
return IModuleContainer.class;
}
@Override
public void writeClass(@Nonnull Method method, @Nonnull SubtargetedModuleMethod.Inject annotation, @Nonnull String className, @Nonnull ClassWriter writer) {
MethodVisitor mv = writer.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
mv.visitCode();
mv.visitVarInsn(ALOAD, 0);
String name = annotation.name();
if (Strings.isNullOrEmpty(name)) name = method.getName();
mv.visitLdcInsn(name);
BuilderHelpers.writeModuleList(mv, annotation.module());
mv.visitLdcInsn(Type.getType(annotation.target()));
mv.visitLdcInsn(annotation.priority());
String doc = annotation.doc();
if (Strings.isNullOrEmpty(doc)) {
mv.visitInsn(ACONST_NULL);
} else {
mv.visitLdcInsn(doc);
}
mv.visitMethodInsn(INVOKESPECIAL, "org/squiddev/plethora/api/module/SubtargetedModuleMethod", "<init>", "(Ljava/lang/String;Ljava/util/Set;Ljava/lang/Class;ILjava/lang/String;)V", false);
mv.visitInsn(RETURN);
mv.visitMaxs(6, 1);
mv.visitEnd();
}
}
| 34.883333 | 189 | 0.784042 |
177cfe92a020b66e2cec9b9ed7ecc01576ad0208 | 988 | package com.mycompany.myapp.service.dto;
import com.mycompany.myapp.web.rest.EmployeeResourceIT;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import com.mycompany.myapp.web.rest.TestUtil;
public class EmployeeDTOTest {
@Test
public void dtoEqualsVerifier() throws Exception {
TestUtil.equalsVerifier(EmployeeDTO.class);
EmployeeDTO employeeDTO1 = new EmployeeDTO();
employeeDTO1.setUsername(EmployeeResourceIT.DEFAULT_USERNAME);
EmployeeDTO employeeDTO2 = new EmployeeDTO();
assertThat(employeeDTO1).isNotEqualTo(employeeDTO2);
employeeDTO2.setUsername(employeeDTO1.getUsername());
assertThat(employeeDTO1).isEqualTo(employeeDTO2);
employeeDTO2.setUsername(EmployeeResourceIT.UPDATED_USERNAME);
assertThat(employeeDTO1).isNotEqualTo(employeeDTO2);
employeeDTO1.setUsername(null);
assertThat(employeeDTO1).isNotEqualTo(employeeDTO2);
}
}
| 39.52 | 70 | 0.758097 |
52a98ec76559d6781b8a1e497a8bfdad52f5bedb | 1,609 | package com.example.notas.util;
import com.example.notas.model.Notas;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
public class FileManager {
public String readFile(String path, String fileName) {
File fileEvents = new File(path, fileName);
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(fileEvents));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
} catch (IOException e) { }
String result = text.toString();
return result;
}
public ArrayList<Notas> getListFile(String path){
ArrayList<Notas> list = new ArrayList<>();
File directory = new File(path);
File[] files = directory.listFiles();
if (files.length > 0){
for (int i = 0; i < files.length; i++){
Notas nota = new Notas();
nota.setId(Long.parseLong(files[i].getName()));
list.add(nota);
}
}
return list;
}
public void write(String path, String fileName, String addText){
File file = new File(path, fileName);
try {
FileWriter writer = new FileWriter(file);
writer.append(addText);
writer.flush();
writer.close();
}
catch (Exception e) {
}
}
}
| 28.732143 | 79 | 0.558732 |
1bdf740e3bd07a798aa2728ed5f6d7b569bcd1fe | 1,958 | package iotraceanalyze.model.analysis.file;
public class FileIdRegular implements FileComparable<FileIdRegular> {
private String hostName;
private long deviceId;
private long fileId;
public FileIdRegular(String hostName, long deviceId, long fileId) {
super();
this.hostName = hostName;
this.deviceId = deviceId;
this.fileId = fileId;
}
public String getHostName() {
return hostName;
}
public long getDeviceId() {
return deviceId;
}
public long getFileId() {
return fileId;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (deviceId ^ (deviceId >>> 32));
result = prime * result + (int) (fileId ^ (fileId >>> 32));
result = prime * result + ((hostName == null) ? 0 : hostName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
FileIdRegular other = (FileIdRegular) obj;
if (deviceId != other.deviceId)
return false;
if (fileId != other.fileId)
return false;
if (hostName == null) {
if (other.hostName != null)
return false;
} else if (!hostName.equals(other.hostName))
return false;
return true;
}
@Override
public int compareTo(FileIdRegular arg0) {
int cmp = hostName.compareTo(arg0.hostName);
if (cmp == 0) {
if (deviceId < arg0.deviceId) {
return -1;
} else if (deviceId > arg0.deviceId) {
return 1;
} else if (fileId < arg0.fileId) {
return -1;
} else if (fileId > arg0.fileId) {
return 1;
} else {
return 0;
}
} else {
return cmp;
}
}
@Override
public String toString() {
return hostName + ":" + deviceId + ":" + fileId;
}
@Override
public String toFileName() {
return hostName + "_" + deviceId + "_" + fileId;
}
}
| 22 | 76 | 0.613892 |
9be89883ea014ebe948f3a0c812a3bac9300335a | 1,457 | package com.emeraldcube.ais.objects;
public class GridRowMobile extends GridRow
{
// Field level representation of the row at this level for ADF use only, not part of JSON.
private String id;
private String value;
private String title;
private String datatype;
private Object internalValue;
private boolean editable;
private MathValue mathValue;
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setValue(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public void setDatatype(String datatype) {
this.datatype = datatype;
}
public String getDatatype() {
return datatype;
}
public void setInternalValue(Object internalValue) {
this.internalValue = internalValue;
}
public Object getInternalValue() {
return internalValue;
}
public void setEditable(boolean editable)
{
this.editable = editable;
}
public boolean getEditable()
{
return this.editable;
}
public void setMathValue(MathValue mathValue) {
this.mathValue = mathValue;
}
public MathValue getMathValue() {
return mathValue;
}
}
| 19.426667 | 94 | 0.619767 |
95094e86cf2da23199844803178ec0c927188b7e | 1,545 | /*
Faça um algoritmo que mostre os números que são divisíveis de um número
digitado pelo usuário. Além desse número, o usuário deve indicar também
o número inicial e final da busca.
Exemplo:
Número divisíveis: 9 De 30 até 238
*/
package semana1;
import java.util.Scanner;
public class Pratica03 {
public static void main(String[] args) {
// define variável ---------------------------------------------------------------------------------------------
int count;
// instancia do objeto teclado para receber o input do usuário -------------------------------------------------
Scanner teclado = new Scanner(System.in);
// solicita e recebe números do usuário -----------------------------------------------------------------------
System.out.print("Informe um número positivo inteiro para o ínicio: ");
int numero1 = teclado.nextInt();
System.out.print("Informe um número positivo inteiro para o final: ");
int numero2 = teclado.nextInt();
System.out.print("Informe o número para divisão: ");
int numero3 = teclado.nextInt();
// exibe resultado do divisor e seus divisores-----------------------------------------------------------------
System.out.printf("---\nNúmeros divisiveis por %d\nSão: ", numero3);
for(count = numero1; count<=numero2; count++){ //iteração para localizar o número divisíveis
if(count % numero3 == 0) {
System.out.print(count + " ");
}
}
}
}
| 36.785714 | 120 | 0.522977 |
3b54a2121e4961d5bc3e3c5b99df49582e3bb6ce | 4,824 | package com.noseparte.battle.utils;
import LockstepProto.Frame;
import LockstepProto.NetMessage;
import LockstepProto.S2CLockStep;
import com.google.protobuf.ByteString;
import com.noseparte.battle.BattleServerConfig;
import com.noseparte.battle.battle.BattleRoom;
import com.noseparte.battle.battle.BattleRoomMgr;
import com.noseparte.battle.battle.SLockStep;
import com.noseparte.battle.server.LinkMgr;
import com.noseparte.battle.server.Protocol;
import com.noseparte.battle.server.Session;
import com.noseparte.common.bean.Actor;
import com.noseparte.common.bean.BattleRoomResult;
import com.noseparte.common.utils.SpringContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import java.util.List;
@Slf4j
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class WatchBattleRoomJob implements Job {
public static final String NUM_EXECUTIONS = "NumExecutions";
Object nextRunnableLock = new Object();
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
BattleServerConfig battleServerConfig = SpringContextUtils.getBean("battleServerConfig", BattleServerConfig.class);
int redundancy = battleServerConfig.getRedundancy();
int intervalInMilliseconds = 1000 / battleServerConfig.getFrameSpeed();
int executeCount = battleServerConfig.getLifecycle() * 60 * 1000 / intervalInMilliseconds;
Trigger trigger = context.getTrigger();
JobDataMap jobDataMap = trigger.getJobDataMap();
TriggerKey key = trigger.getKey();
long startTime = (long) jobDataMap.get("startTime");
//在这里实现业务逻辑
if (log.isDebugEnabled()) {
log.debug("房间定时器{},{}执行.", key.getName(), key.getGroup());
}
long roomId = (long) jobDataMap.get("roomId");
BattleRoomMgr battleMgr = SpringContextUtils.getBean("battleRoomMgr", BattleRoomMgr.class);
BattleRoom battleRoom = battleMgr.getBattleRoomById(roomId);
JobUtil jobUtil = SpringContextUtils.getBean("jobUtil", JobUtil.class);
while (executeCount > 0) {
synchronized (nextRunnableLock) {
try {
// 广播帧
broadcastFrame(redundancy, key, battleRoom);
jobUtil.pauseJob(key.getName(), key.getGroup());
nextRunnableLock.wait(intervalInMilliseconds);
jobUtil.resumeJob(key.getName(), key.getGroup());
// 是否结束
long now = System.currentTimeMillis();
if (!battleMgr.checkBattleResult(battleRoom, now)) {
log.info("BattleRoom={}, game over.", roomId);
break;
}
} catch (InterruptedException | SchedulerException e) {
log.error("", e);
}
executeCount--;
}
}
// 战斗房间结束
BattleRoomResult battleRoomResult = battleRoom.getBattleRoomResult();
if (battleRoomResult.getWinners().size() == 0
&& battleRoomResult.getLosers().size() == 0) {
if (log.isInfoEnabled()) {
log.info("(5)---时间到了没有收到A和B的战斗结果,都判定输.");
}
// 时间到了没有结果,就都判定输
for (Actor actor : battleRoom.getActors()) {
battleRoomResult.getLosers().add(actor.getRoleId());
}
}
// 解散房间
battleMgr.roomOver(battleRoom);
}
private void broadcastFrame(int redundancy, TriggerKey key, BattleRoom battleRoom) {
// 帧
int influenceFrameCount = battleRoom.nextFrameNumber();
Frame.Builder frame = Frame.newBuilder();
frame.setInfluenceFrameCount(influenceFrameCount);
for (byte[] f : battleRoom.pollFrame()) {
frame.addCommands(ByteString.copyFrom(f));
}
frame.build();
// protocol
S2CLockStep.Builder s2CLockStep = S2CLockStep.newBuilder();
s2CLockStep.addF(frame);
for (influenceFrameCount -= 1; 0 < influenceFrameCount && 0 < redundancy--; influenceFrameCount--) {
s2CLockStep.addF(battleRoom.pullStoreFrame(influenceFrameCount));
}
byte[] msg = s2CLockStep.build().toByteArray();
//store frame
battleRoom.storeFrame(frame);
// 广播
List<Actor> actors = battleRoom.getActors();
for (Actor actor : actors) {
Session session = LinkMgr.getSession(actor.getRoleId());
if (null == session || !session.getChannel().isActive()) {
continue;
}
Protocol p = new SLockStep();
p.setType(NetMessage.S2C_LockStep_VALUE);
p.setMsg(msg);
session.getChannel().writeAndFlush(p);
}
}
}
| 39.219512 | 123 | 0.628731 |
23972f8072977cc5a25ebb4971850afb2153972d | 1,131 | package org.apache.shiro.grails.annotations;
import java.lang.annotation.Annotation;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.aop.AuthorizingAnnotationHandler;
/**
* Ties a Shiro @Requires* annotation instance to a Shiro annotation handler.
* This is because Shiro's annotation handlers require an annotation instance
* when invoked, but it's not worth getting this information at runtime when
* we can find it out on startup.
*/
public class AnnotationHandler {
private Annotation annotation;
private AuthorizingAnnotationHandler handler;
public AnnotationHandler(Annotation annotation, AuthorizingAnnotationHandler handler) {
this.annotation = annotation;
this.handler = handler;
}
/**
* Executes the stored authorizing annotation handler against the stored
* annotation. The end result is that an exception is thrown if the current
* user does not satisfy the semantics of the stored annotation.
*/
public void invoke() throws AuthorizationException {
this.handler.assertAuthorized(this.annotation);
}
}
| 36.483871 | 91 | 0.756852 |
07b8fbbe2618e3efe8224b5487415788beb20adf | 492 | package com.cai.work.ui;
import android.content.Context;
/**
* Created by clarence on 2018/4/17.
*/
public class Help {
private Context context;
private static class Holder {
public static Help help = new Help();
}
private Help() {
}
public static Help install() {
return Holder.help;
}
public Context getContext() {
return context;
}
public void setContext(Context context) {
this.context = context;
}
}
| 15.375 | 45 | 0.603659 |
de20beb05c993ddba0002aec308e36e729c5fae0 | 702 | package fizz;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class FizzBuzz {
public String fizz(IntStream range) {
return range.mapToObj(i -> intToFizzBuzzed(i)).
collect(Collectors.joining(", "));
}
private String intToFizzBuzzed(int x) {
if (x == 0) {
return "0";
} else if (Integer.toString(x).contains("3")) {
return "lucky";
} else if (x % 15 == 0) {
return "fizzbuzz";
} else if (x % 5 == 0) {
return "buzz";
} else if (x % 3 == 0) {
return "fizz";
} else {
return Integer.toString(x);
}
}
}
| 24.206897 | 55 | 0.501425 |
2b427da500efaf74fa96700c74fce45a5fd904e9 | 2,325 | package com.pwc.core.framework.processors.web.elements;
import com.pwc.core.framework.data.WebElementAttribute;
import com.pwc.core.framework.data.WebElementType;
import com.pwc.core.framework.service.WebElementBaseTest;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import org.openqa.selenium.WebElement;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class LabelElementTest extends WebElementBaseTest {
public static final String UNIT_TEST_LABEL = "Unit test label";
LabelElementImpl labelElement;
@Before
public void setUp() {
labelElement = new LabelElementImpl();
}
@Test
public void labelElementAppliesTest() {
createMockElement("777", WebElementAttribute.ID, WebElementType.LABEL, true);
boolean result = LabelElementImpl.applies(getMockWebElement());
Assert.assertTrue(result);
}
@Test
public void labelElementAppliesNoMatchTest() {
createMockElement("777", WebElementAttribute.ID, WebElementType.INPUT, true);
boolean result = LabelElementImpl.applies(getMockWebElement());
Assert.assertFalse(result);
}
@Test
public void webActionTest() {
WebElement mockDivElement = mock(WebElement.class);
when(mockDivElement.getAttribute(WebElementAttribute.ID.attribute)).thenReturn("777");
when(mockDivElement.getTagName()).thenReturn(WebElementType.LABEL.type);
when(mockDivElement.getText()).thenReturn(UNIT_TEST_LABEL);
labelElement.webAction(mockDivElement, UNIT_TEST_LABEL);
}
@Test
public void webActionClickableDivTest() {
WebElement mockDivElement = mock(WebElement.class);
when(mockDivElement.getAttribute(WebElementAttribute.ID.attribute)).thenReturn("777");
when(mockDivElement.getTagName()).thenReturn(WebElementType.LABEL.type);
when(mockDivElement.getText()).thenReturn(UNIT_TEST_LABEL);
labelElement.webAction(mockDivElement, UNIT_TEST_LABEL);
}
@Test(expected = AssertionError.class)
public void webActionExceptionTest() {
labelElement.webAction(null, WebElementAttribute.VALUE.attribute);
}
}
| 35.769231 | 94 | 0.742796 |
ee7aa68c69c2fd8b950a172832f978ac45db3aeb | 5,543 | package org.ovirt.engine.core.bll;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.when;
import static org.ovirt.engine.core.bll.CommandAssertUtils.checkSucceeded;
import static org.ovirt.engine.core.utils.MockConfigRule.mockConfig;
import java.util.List;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.VDSType;
import org.ovirt.engine.core.common.config.ConfigValues;
import org.ovirt.engine.core.common.queries.VdsIdParametersBase;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.RpmVersion;
import org.ovirt.engine.core.compat.Version;
import org.ovirt.engine.core.dao.VdsDAO;
import org.ovirt.engine.core.utils.MockConfigRule;
@RunWith(MockitoJUnitRunner.class)
public class GetoVirtISOsTest extends AbstractQueryTest<VdsIdParametersBase, GetoVirtISOsQuery<VdsIdParametersBase>> {
private static final String OVIRT_INIT_SUPPORTED_VERSION = "5.8";
private static final String OVIRT_ISO_PREFIX = "^rhevh-(.*)\\.*\\.iso$";
private static final String OVIRT_ISOS_REPOSITORY_PATH = "src/test/resources/ovirt-isos";
private static final String OVIRT_ISOS_DATA_DIR = ".";
private static final String AVAILABLE_OVIRT_ISO_VERSION = "RHEV Hypervisor - 6.2 - 20111010.0.el6";
private static final String UNAVAILABLE_OVIRT_ISO_VERSION = "RHEV Hypervisor - 8.2 - 20111010.0.el6";
private static final Version EXISTING_CLUSTER_VERSION = new Version("3.1");
private static final String OVIRT_NODEOS = "^rhevh.*";
@Rule
public MockConfigRule mcr = new MockConfigRule(
mockConfig(ConfigValues.oVirtISOsRepositoryPath, OVIRT_ISOS_REPOSITORY_PATH),
mockConfig(ConfigValues.DataDir, OVIRT_ISOS_DATA_DIR),
mockConfig(ConfigValues.OvirtIsoPrefix, OVIRT_ISO_PREFIX),
mockConfig(ConfigValues.OvirtInitialSupportedIsoVersion, OVIRT_INIT_SUPPORTED_VERSION),
mockConfig(ConfigValues.OvirtNodeOS, OVIRT_NODEOS),
mockConfig(ConfigValues.UserSessionTimeOutInterval, 60)
);
@Mock
private VdsDAO vdsDAO;
@Override
@Before
public void setUp() throws Exception {
super.setUp();
when(getDbFacadeMockInstance().getVdsDao()).thenReturn(vdsDAO);
}
@Test
public void testQueryWithHostId() {
Guid vdsId = Guid.newGuid();
VDS vds = new VDS();
vds.setId(vdsId);
vds.setVdsType(VDSType.oVirtNode);
vds.setHostOs(AVAILABLE_OVIRT_ISO_VERSION);
vds.setVdsGroupCompatibilityVersion(EXISTING_CLUSTER_VERSION);
when(vdsDAO.get(any(Guid.class))).thenReturn(vds);
when(getQueryParameters().getVdsId()).thenReturn(vdsId);
getQuery().setInternalExecution(true);
getQuery().executeCommand();
checkSucceeded(getQuery(), true);
checkReturnValueEmpty(getQuery());
}
@Test
public void testQueryClusterLevel() {
Guid vdsId = Guid.newGuid();
VDS vds = new VDS();
vds.setId(vdsId);
vds.setVdsType(VDSType.oVirtNode);
vds.setHostOs(UNAVAILABLE_OVIRT_ISO_VERSION);
vds.setVdsGroupCompatibilityVersion(EXISTING_CLUSTER_VERSION);
when(vdsDAO.get(any(Guid.class))).thenReturn(vds);
when(getQueryParameters().getVdsId()).thenReturn(vdsId);
getQuery().setInternalExecution(true);
getQuery().executeCommand();
checkSucceeded(getQuery(), true);
checkReturnValueEmpty(getQuery());
}
@Test
public void testQueryWithNonExistingHostId() {
when(getQueryParameters().getVdsId()).thenReturn(Guid.newGuid());
getQuery().setInternalExecution(true);
getQuery().executeCommand();
checkSucceeded(getQuery(), true);
checkReturnValueEmpty(getQuery());
}
@Test
public void testQueryWithoutHostId() {
getQuery().setInternalExecution(true);
getQuery().executeCommand();
checkSucceeded(getQuery(), true);
checkReturnValueEmpty(getQuery());
}
@Test
public void testQueryMultiplePaths() {
mcr.mockConfigValue(ConfigValues.oVirtISOsRepositoryPath, "src/test/resources/ovirt-isos:src/test/resources/rhev-isos");
getQuery().setInternalExecution(true);
getQuery().executeCommand();
checkSucceeded(getQuery(), true);
checkReturnValueEmpty(getQuery());
}
@SuppressWarnings("unchecked")
@Test
public void testPrefixChange() {
mcr.mockConfigValue(ConfigValues.OvirtIsoPrefix, "a different prefix");
getQuery().setInternalExecution(true);
getQuery().executeCommand();
checkSucceeded(getQuery(), true);
checkReturnValueEmpty(getQuery());
}
@SuppressWarnings("unchecked")
private static void checkReturnValue(GetoVirtISOsQuery<VdsIdParametersBase> query) {
List<RpmVersion> isosList = (List<RpmVersion>) query.getQueryReturnValue().getReturnValue();
assertTrue(!isosList.isEmpty());
}
@SuppressWarnings("unchecked")
private static void checkReturnValueEmpty(GetoVirtISOsQuery<VdsIdParametersBase> query) {
List<RpmVersion> isosList = (List<RpmVersion>) query.getQueryReturnValue().getReturnValue();
assertTrue(isosList.isEmpty());
}
}
| 37.201342 | 128 | 0.715136 |
caf3206a0f6059bd2d55b16a05b81872f580fcc6 | 511 | /*
* Copyright (C) 2016 the original author or authors.
*
* This file is part of jGrades Application Project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*/
package com.project;
import org.jgrades.logging.JgLogger;
import org.jgrades.logging.JgLoggerFactory;
public class StrangerClass {
public static final JgLogger LOGGER = JgLoggerFactory.getLogger(StrangerClass.class);
}
| 26.894737 | 89 | 0.735812 |
c3781763d9c8d809fc8441f578c13e8d297c18e4 | 1,735 | package com.github.harbby.ashtarte.api;
import com.github.harbby.gadtry.base.Iterators;
import com.github.harbby.gadtry.base.Serializables;
import com.github.harbby.gadtry.collection.tuple.Tuple2;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.stream.Stream;
public final class ShuffleManager {
public static <K, V> Iterator<Tuple2<K, V>> getReader(int shuffleId, int reduceId) {
File dataDir = new File("/tmp/shuffle/");
//todo: 此处为 demo
Iterator<Iterator<Tuple2<K, V>>> iterator = Stream.of(dataDir.listFiles())
.filter(x -> x.getName().startsWith("shuffle_" + shuffleId + "_")
&& x.getName().endsWith("_" + reduceId + ".data"))
.map(file -> {
ArrayList<Tuple2<K, V>> out = new ArrayList<>();
try {
DataInputStream dataInputStream = new DataInputStream(new FileInputStream(file));
int length = dataInputStream.readInt();
while (length != -1) {
byte[] bytes = new byte[length];
dataInputStream.read(bytes);
out.add(Serializables.byteToObject(bytes));
length = dataInputStream.readInt();
}
dataInputStream.close();
return out.iterator();
} catch (Exception e) {
throw new RuntimeException(e);
}
}).iterator();
return Iterators.concat(iterator);
}
}
| 41.309524 | 105 | 0.544092 |
aa539194a793496729e6cd9d1aae99083b6bd84d | 2,004 | /*--
* Copyright 2010 René M. de Bloois
*
* 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 solidbase.core;
import java.io.FileNotFoundException;
import solidstack.io.Resource;
import solidstack.io.SourceReader;
import solidstack.io.SourceReaders;
/**
* This class manages an SQL file's contents. It detects the encoding and reads commands from it.
*
* @author René M. de Bloois
* @since Apr 2010
*/
public class SQLFile
{
/**
* The underlying file.
*/
protected SourceReader reader;
/**
* Creates an new instance of an SQL file.
*
* @param resource The resource containing this SQL file.
*/
protected SQLFile( Resource resource )
{
try
{
this.reader = SourceReaders.forResource( resource, EncodingDetector.INSTANCE );
}
catch( FileNotFoundException e )
{
throw new FatalException( e.toString() ); // TODO e or e.toString()?
}
}
/**
* Close the SQL file. This will also close all underlying streams.
*/
protected void close()
{
if( this.reader != null )
{
this.reader.close();
this.reader = null;
}
}
/**
* Gets the encoding of the SQL file.
*
* @return The encoding of the SQL file.
*/
public String getEncoding()
{
return this.reader.getEncoding();
}
/**
* Returns a source for the SQL.
*
* @return A source for the SQL.
*/
public SQLSource getSource()
{
return new SQLSource( this.reader );
}
}
| 22.516854 | 98 | 0.658683 |
d901cf3eefc7bc074ddf70143d3e1be15cfe5207 | 927 | package org.atpfivt.jsyntrax.units.tracks.loop;
import org.atpfivt.jsyntrax.exceptions.LoopNotTwoArgsException;
import org.atpfivt.jsyntrax.units.Unit;
import org.atpfivt.jsyntrax.units.tracks.ComplexTrack;
import org.atpfivt.jsyntrax.units.tracks.Track;
import org.atpfivt.jsyntrax.visitors.Visitor;
import java.util.List;
public class Loop extends ComplexTrack {
public Loop(List<Unit> units) throws LoopNotTwoArgsException {
super(units);
if (units.size() != 2) {
throw new LoopNotTwoArgsException();
}
}
public Track getForwardPart() {
return getUnits().get(0).getTrack();
}
public Track getBackwardPart() {
return getUnits().get(1).getTrack();
}
public boolean isForwardNull() {
return getForwardPart() == null;
}
public boolean isBackwardNull() {
return getBackwardPart() == null;
}
public void accept(Visitor visitor) {
visitor.visitLoop(this);
}
}
| 23.175 | 64 | 0.720604 |
99e4d2a6d70d5b50e3d0ed5c49868b7e7778f17b | 171 | package pokecube.core.database.abilities.n;
import pokecube.core.database.abilities.Ability;
public class NeutralizingGas extends Ability
{
// TODO Implement this.
}
| 19 | 48 | 0.795322 |
3968a6a6f0603825226c36d727d895d78282392e | 848 | package model.executable;
import java.util.List;
import exception.SyntacticErrorException;
import model.Executable;
import model.LogHolder;
import model.TurtleLog;
/**
* @author billyu
* command type that operates on each turtle
* loops over each active turtle log to execute
*/
public abstract class TurtleCommand extends StandardCommand {
private LogHolder logHolder;
public TurtleCommand(List<Executable> argv) throws SyntacticErrorException {
super(argv);
}
@Override
public double execute(LogHolder log) throws SyntacticErrorException {
logHolder = log;
double result = 0;
for (TurtleLog active : log.getActiveLogs()) {
result = execute(active);
}
return result;
}
public abstract double execute(TurtleLog log) throws SyntacticErrorException;
protected LogHolder getLogHolder() {
return logHolder;
}
}
| 21.2 | 78 | 0.764151 |
47736d8d8767d8f71e4e9784711ba743c3cf694f | 6,292 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.jcr2spi;
import javax.jcr.InvalidItemStateException;
import javax.jcr.Item;
import javax.jcr.ItemExistsException;
import javax.jcr.PathNotFoundException;
import javax.jcr.RepositoryException;
import javax.jcr.lock.LockException;
import javax.jcr.nodetype.ConstraintViolationException;
import javax.jcr.nodetype.NoSuchNodeTypeException;
import javax.jcr.version.VersionException;
import org.apache.jackrabbit.test.AbstractJCRTest;
import org.apache.jackrabbit.test.NotExecutableException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <code>RemoveItemTest</code>...
*/
public abstract class RemoveItemTest extends AbstractJCRTest {
private static Logger log = LoggerFactory.getLogger(RemoveItemTest.class);
protected Item removeItem;
protected String removePath;
@Override
protected void setUp() throws Exception {
super.setUp();
removeItem = createRemoveItem();
removePath = removeItem.getPath();
}
@Override
protected void tearDown() throws Exception {
removeItem = null;
super.tearDown();
}
protected abstract Item createRemoveItem() throws NotExecutableException, RepositoryException, LockException, ConstraintViolationException, ItemExistsException, NoSuchNodeTypeException, VersionException;
/**
* Transiently removes a persisted item using {@link javax.jcr.Item#remove()}
* and test, whether that item cannot be access from the session any more.
*/
public void testRemoveItem() throws RepositoryException {
removeItem.remove();
// check if the node has been properly removed
try {
superuser.getItem(removePath);
fail("A transiently removed item should no longer be accessible from the session.");
} catch (PathNotFoundException e) {
// ok , works as expected
}
}
/**
* Same as {@link #testRemoveItem()}, but calls save() (persisting the removal)
* before executing the test.
*/
public void testRemoveItem2() throws RepositoryException, NotExecutableException {
removeItem.remove();
testRootNode.save();
try {
superuser.getItem(removePath);
fail("Persistently removed node should no longer be accessible from the session.");
} catch (PathNotFoundException e) {
// ok , works as expected
}
}
/**
* Test if a node, that has been transiently removed is not 'New'.
*/
public void testNotNewRemovedItem() throws RepositoryException {
removeItem.remove();
assertFalse("Transiently removed node must not be 'new'.", removeItem.isNew());
}
/**
* Same as {@link #testNotNewRemovedItem()} but calls save() before
* executing the test.
*/
public void testNotNewRemovedItem2() throws RepositoryException {
removeItem.remove();
testRootNode.save();
assertFalse("Removed node must not be 'new'.", removeItem.isNew());
}
/**
* Test if a node, that has be transiently remove is not 'Modified'.
*/
public void testNotModifiedRemovedItem() throws RepositoryException {
removeItem.remove();
assertFalse("Transiently removed node must not be 'modified'.", removeItem.isModified());
}
/**
* Same as {@link #testNotModifiedRemovedItem()} but calls save() before
* executing the test.
*/
public void testNotModifiedRemovedItem2() throws RepositoryException {
removeItem.remove();
testRootNode.save();
assertFalse("Removed node must not be 'modified'.", removeItem.isModified());
}
/**
* A removed item must throw InvalidItemStateException upon any call to an
* item specific method.
*/
public void testInvalidStateRemovedItem() throws RepositoryException {
removeItem.remove();
try {
removeItem.getName();
fail("Calling getName() on a removed node must throw InvalidItemStateException.");
} catch (InvalidItemStateException e) {
//ok
}
try {
removeItem.getPath();
fail("Calling getPath() on a removed node must throw InvalidItemStateException.");
} catch (InvalidItemStateException e) {
//ok
}
try {
removeItem.save();
fail("Calling save() on a removed node must throw InvalidItemStateException.");
} catch (InvalidItemStateException e) {
//ok
}
}
/**
* Same as {@link #testInvalidStateRemovedItem()} but calls save() before
* executing the test.
*/
public void testInvalidStateRemovedItem2() throws RepositoryException {
removeItem.remove();
testRootNode.save();
try {
removeItem.getName();
fail("Calling getName() on a removed node must throw InvalidItemStateException.");
} catch (InvalidItemStateException e) {
//ok
}
try {
removeItem.getPath();
fail("Calling getPath() on a removed node must throw InvalidItemStateException.");
} catch (InvalidItemStateException e) {
//ok
}
try {
removeItem.save();
fail("Calling save() on a removed node must throw InvalidItemStateException.");
} catch (InvalidItemStateException e) {
//ok
}
}
} | 34.571429 | 207 | 0.660521 |
6a9013ee9326a3019c5e68498ff57fa2367b58d7 | 3,623 | package io.thill.jacoio.slf4j;
import io.thill.jacoio.ConcurrentFile;
import org.slf4j.ILoggerFactory;
import org.slf4j.Logger;
import java.io.File;
import java.text.SimpleDateFormat;
import static io.thill.jacoio.slf4j.JacoioLogger.*;
public class JacoioLoggerFactory implements ILoggerFactory {
private static final String DEFAULT_LOG_LEVEL = "INFO";
private static final String DEFAULT_LOG_DIRECTORY = "log";
private static final String DEFAULT_LOG_FILENAME_PREFIX = "";
private static final String DEFAULT_LOG_FILENAME_SUFFIX = ".log";
private static final String DEFAULT_LOG_FILENAME_TIMESTAMP_FORMAT = "yyyyMMdd_HHmmss";
private static final String DEFAULT_LOG_TIMESTAMP_FORMAT = "yyyy/MM/dd HH:mm:ss.SSS";
private static final String DEFAULT_LOG_SIZE = Integer.toString(128 * 1024 * 1024);
private static final String DEFAULT_LOG_PREALLOCATE = Boolean.FALSE.toString();
private final LogWriter logWriter;
public JacoioLoggerFactory() {
LogWriter logWriter;
try {
final LogLevel logLevel = LogLevel.valueOf(System.getProperty(SYSKEY_LOG_LEVEL, DEFAULT_LOG_LEVEL));
final File location = new File(System.getProperty(SYSKEY_LOG_DIRECTORY, DEFAULT_LOG_DIRECTORY));
final int logSize = Integer.parseInt(System.getProperty(SYSKEY_LOG_SIZE, DEFAULT_LOG_SIZE));
final boolean preallocate = Boolean.parseBoolean(System.getProperty(SYSKEY_LOG_PREALLOCATE, DEFAULT_LOG_PREALLOCATE));
final String filenamePrefix = System.getProperty(SYSKEY_LOG_FILENAME_PREFIX, DEFAULT_LOG_FILENAME_PREFIX);
final String filenameSuffix = System.getProperty(SYSKEY_LOG_FILENAME_SUFFIX, DEFAULT_LOG_FILENAME_SUFFIX);
final String filenameTimestampFormat = System.getProperty(SYSKEY_LOG_FILENAME_TIMESTAMP_FORMAT, DEFAULT_LOG_FILENAME_TIMESTAMP_FORMAT);
final String logTimestampFormat = System.getProperty(SYSKEY_LOG_TIMESTAMP_FORMAT, DEFAULT_LOG_TIMESTAMP_FORMAT);
final StringBuilder stderr = new StringBuilder("Jacoio Logger:")
.append("\n Level: ").append(logLevel)
.append("\n Location: ").append(location.getAbsolutePath())
.append("\n Size: ").append(logSize)
.append("\n Preallocate: ").append(preallocate)
.append("\n Filename Prefix: ").append(filenamePrefix)
.append("\n Filename Suffix: ").append(filenameSuffix)
.append("\n Filename Timestamp Format: ").append(filenameTimestampFormat)
.append("\n Log Timestamp Format: ").append(logTimestampFormat);
System.err.println(stderr.toString());
location.mkdirs();
final ConcurrentFile concurrentFile = ConcurrentFile.map()
.location(location)
.capacity(logSize)
.framed(false)
.fillWithZeros(true)
.multiProcess(false)
.roll(r -> r
.enabled(true)
.asyncClose(true)
.preallocate(preallocate)
.fileNamePrefix(filenamePrefix)
.fileNameSuffix(filenameSuffix)
.dateFormat(filenameTimestampFormat)
).map();
logWriter = new LogWriter(logLevel, concurrentFile, new SimpleDateFormat(logTimestampFormat));
} catch(Throwable t) {
System.err.println("Could not initialize Jacoio Logger");
t.printStackTrace();
logWriter = new LogWriter(LogLevel.OFF, null, null);
}
this.logWriter = logWriter;
}
@Override
public Logger getLogger(String name) {
return new JacoioLogger(name, logWriter);
}
}
| 45.860759 | 141 | 0.701904 |
bf705d61ed2a064111e6d9fafadb1da84560da7b | 1,736 | /*
* package-info.java
*
* This source file is part of the FoundationDB open source project
*
* Copyright 2015-2018 Apple Inc. and the FoundationDB project 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.
*/
/**
* A layer for mapping potentially long strings to and from more compact tuple elements.
*
* <p>
* A string identifier that is part of a {@link com.apple.foundationdb.record.provider.foundationdb.keyspace.KeySpace} will be part of the key for every record and every index entry is a record store following that key space.
* Since FoundationDB does not do prefix compression, this can add up to a lot of space when the string is long enough to really express anything.
* Space is saved by replacing the string in the key {@link com.apple.foundationdb.tuple.Tuple} with an integer gotten by interning it.
* </p>
*
* <p>
* This interning operation is very similar to what the {@link com.apple.foundationdb.directory.DirectoryLayer} does, except that whereas the directory layer actually identifies space between the root of the key-value store,
* an interned path element might be anywhere in the path.
* </p>
*/
package com.apple.foundationdb.record.provider.foundationdb.layers.interning;
| 48.222222 | 225 | 0.758641 |
bcbfdf1f4cfe72270f72d913ef7b32fa6856cd77 | 9,704 | /* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.visualization.coauthorship;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import org.apache.commons.logging.Log;
import edu.cornell.mannlib.vitro.webapp.controller.visualization.VisualizationFrameworkConstants;
import edu.cornell.mannlib.vitro.webapp.visualization.constants.VOConstants;
import edu.cornell.mannlib.vitro.webapp.visualization.constants.VisConstants;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.Collaborator;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.SparklineData;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.YearToEntityCountDataElement;
import edu.cornell.mannlib.vitro.webapp.visualization.visutils.UtilityFunctions;
public class CoAuthorshipVisCodeGenerator {
/*
* There are 2 modes of sparkline that are available via this visualization.
* 1. Short Sparkline - This sparkline will render all the data points (or sparks),
* which in this case are the coauthors over the years, from the last 10 years.
*
* 2. Full Sparkline - This sparkline will render all the data points (or sparks)
* spanning the career of the person & last 10 years at the minimum, in case if
* the person started his career in the last 10 yeras.
* */
private static final String DEFAULT_VISCONTAINER_DIV_ID = "unique_coauthors_vis_container";
private Map<String, Set<Collaborator>> yearToUniqueCoauthors;
private Log log;
private SparklineData sparklineParameterVO;
private String individualURI;
public CoAuthorshipVisCodeGenerator(String individualURI,
String visMode,
String visContainer,
Map<String, Set<Collaborator>> yearToUniqueCoauthors,
Log log) {
this.individualURI = individualURI;
this.yearToUniqueCoauthors = yearToUniqueCoauthors;
this.log = log;
this.sparklineParameterVO = setupSparklineParameters(visMode, visContainer);
}
/**
* This method is used to setup parameters for the sparkline value object. These parameters
* will be used in the template to construct the actual html/javascript code.
* @param visMode Visualization mode
* @param providedVisContainerID Container ID
*/
private SparklineData setupSparklineParameters(String visMode,
String providedVisContainerID) {
SparklineData sparklineData = new SparklineData();
int numOfYearsToBeRendered = 0;
/*
* It was decided that to prevent downward curve that happens if there are no publications
* in the current year seems a bit harsh, so we consider only publications from the last 10
* complete years.
* */
int currentYear = Calendar.getInstance().get(Calendar.YEAR) - 1;
int shortSparkMinYear = currentYear
- VisConstants.MINIMUM_YEARS_CONSIDERED_FOR_SPARKLINE
+ 1;
/*
* This is required because when deciding the range of years over which the vis
* was rendered we dont want to be influenced by the "DEFAULT_PUBLICATION_YEAR".
* */
Set<String> publishedYears = new HashSet<String>(yearToUniqueCoauthors.keySet());
publishedYears.remove(VOConstants.DEFAULT_PUBLICATION_YEAR);
/*
* We are setting the default value of minPublishedYear to be 10 years before
* the current year (which is suitably represented by the shortSparkMinYear),
* this in case we run into invalid set of published years.
* */
int minPublishedYear = shortSparkMinYear;
String visContainerID = null;
if (yearToUniqueCoauthors.size() > 0) {
try {
minPublishedYear = Integer.parseInt(Collections.min(publishedYears));
} catch (NoSuchElementException | NumberFormatException e1) {
log.debug("vis: " + e1.getMessage() + " error occurred for "
+ yearToUniqueCoauthors.toString());
}
}
int minPubYearConsidered = 0;
/*
* There might be a case that the author has made his first publication within the
* last 10 years but we want to make sure that the sparkline is representative of
* at least the last 10 years, so we will set the minPubYearConsidered to
* "currentYear - 10" which is also given by "shortSparkMinYear".
* */
if (minPublishedYear > shortSparkMinYear) {
minPubYearConsidered = shortSparkMinYear;
} else {
minPubYearConsidered = minPublishedYear;
}
numOfYearsToBeRendered = currentYear - minPubYearConsidered + 1;
sparklineData.setNumOfYearsToBeRendered(numOfYearsToBeRendered);
int uniqueCoAuthorCounter = 0;
Set<Collaborator> allCoAuthorsWithKnownAuthorshipYears = new HashSet<Collaborator>();
List<YearToEntityCountDataElement> yearToUniqueCoauthorsCountDataTable =
new ArrayList<YearToEntityCountDataElement>();
for (int publicationYear = minPubYearConsidered;
publicationYear <= currentYear;
publicationYear++) {
String publicationYearAsString = String.valueOf(publicationYear);
Set<Collaborator> currentCoAuthors = yearToUniqueCoauthors
.get(publicationYearAsString);
Integer currentUniqueCoAuthors = null;
if (currentCoAuthors != null) {
currentUniqueCoAuthors = currentCoAuthors.size();
allCoAuthorsWithKnownAuthorshipYears.addAll(currentCoAuthors);
} else {
currentUniqueCoAuthors = 0;
}
yearToUniqueCoauthorsCountDataTable.add(
new YearToEntityCountDataElement(uniqueCoAuthorCounter,
publicationYearAsString,
currentUniqueCoAuthors));
uniqueCoAuthorCounter++;
}
/*
* For the purpose of this visualization I have come up with a term "Sparks" which
* essentially means data points.
* Sparks that will be rendered in full mode will always be the one's which have any year
* associated with it. Hence.
* */
sparklineData.setRenderedSparks(allCoAuthorsWithKnownAuthorshipYears.size());
sparklineData.setYearToEntityCountDataTable(yearToUniqueCoauthorsCountDataTable);
/*
* This is required only for the sparklines which convey collaborationships like
* coinvestigatorships and coauthorship. There are edge cases where a collaborator can be
* present for in a collaboration with known & unknown year. We do not want to repeat the
* count for this collaborator when we present it in the front-end.
* */
Set<Collaborator> totalUniqueCoInvestigators =
new HashSet<Collaborator>(allCoAuthorsWithKnownAuthorshipYears);
/*
* Total publications will also consider publications that have no year associated with
* them. Hence.
* */
Integer unknownYearCoauthors = 0;
if (yearToUniqueCoauthors.get(VOConstants.DEFAULT_PUBLICATION_YEAR) != null) {
unknownYearCoauthors = yearToUniqueCoauthors
.get(VOConstants.DEFAULT_PUBLICATION_YEAR).size();
totalUniqueCoInvestigators.addAll(
yearToUniqueCoauthors.get(VOConstants.DEFAULT_GRANT_YEAR));
}
sparklineData.setUnknownYearPublications(unknownYearCoauthors);
sparklineData.setTotalCollaborationshipCount(totalUniqueCoInvestigators.size());
if (providedVisContainerID != null) {
visContainerID = providedVisContainerID;
} else {
visContainerID = DEFAULT_VISCONTAINER_DIV_ID;
}
sparklineData.setVisContainerDivID(visContainerID);
/*
* By default these represents the range of the rendered sparks. Only in case of
* "short" sparkline mode we will set the Earliest RenderedPublication year to
* "currentYear - 10".
* */
sparklineData.setEarliestYearConsidered(minPubYearConsidered);
sparklineData.setEarliestRenderedPublicationYear(minPublishedYear);
sparklineData.setLatestRenderedPublicationYear(currentYear);
/*
* The Full Sparkline will be rendered by default. Only if the url has specific mention of
* SHORT_SPARKLINE_MODE_KEY then we render the short sparkline and not otherwise.
* */
if (VisualizationFrameworkConstants.SHORT_SPARKLINE_VIS_MODE.equalsIgnoreCase(visMode)) {
sparklineData.setEarliestRenderedPublicationYear(shortSparkMinYear);
sparklineData.setShortVisMode(true);
} else {
sparklineData.setShortVisMode(false);
}
if (yearToUniqueCoauthors.size() > 0) {
sparklineData.setFullTimelineNetworkLink(
UtilityFunctions.getCollaboratorshipNetworkLink(
individualURI,
VisualizationFrameworkConstants.PERSON_LEVEL_VIS,
VisualizationFrameworkConstants.COAUTHOR_VIS_MODE));
sparklineData.setDownloadDataLink(
UtilityFunctions.getCSVDownloadURL(
individualURI,
VisualizationFrameworkConstants.COAUTHORSHIP_VIS,
VisualizationFrameworkConstants.COAUTHORS_COUNT_PER_YEAR_VIS_MODE));
Map<String, Integer> yearToUniqueCoauthorsCount = new HashMap<String, Integer>();
for (Map.Entry<String, Set<Collaborator>> currentYearToCoAuthors
: yearToUniqueCoauthors.entrySet()) {
yearToUniqueCoauthorsCount.put(currentYearToCoAuthors.getKey(),
currentYearToCoAuthors.getValue().size());
}
sparklineData.setYearToActivityCount(yearToUniqueCoauthorsCount);
}
return sparklineData;
}
public SparklineData getValueObjectContainer() {
return this.sparklineParameterVO;
}
}
| 38.054902 | 98 | 0.732894 |
f96ecf4eb49489671fe7cca56d57f9ae402ef448 | 2,893 | /*
*AVISO LEGAL
© Copyright
*Este programa esta protegido por la ley de derechos de autor.
*La reproduccion o distribucion ilicita de este programa o de cualquiera de
*sus partes esta penado por la ley con severas sanciones civiles y penales,
*y seran objeto de todas las sanciones legales que correspondan.
*Su contenido no puede copiarse para fines comerciales o de otras,
*ni puede mostrarse, incluso en una version modificada, en otros sitios Web.
Solo esta permitido colocar hipervinculos al sitio web.
*/
package com.bydan.erp.seguridad.util;
import java.util.Set;
import java.util.HashSet;
import java.util.ArrayList;
import java.util.List;
import java.io.Serializable;
import java.util.Date;
import java.sql.Timestamp;
import org.hibernate.validator.*;
import com.bydan.framework.erp.business.entity.GeneralEntity;
import com.bydan.framework.erp.business.entity.GeneralEntityParameterReturnGeneral;
import com.bydan.framework.erp.business.entity.GeneralEntityReturnGeneral;
import com.bydan.framework.erp.business.entity.Classe;
import com.bydan.framework.erp.business.dataaccess.ConstantesSql;
//import com.bydan.framework.erp.business.entity.Mensajes;
import com.bydan.framework.erp.util.Constantes;
import com.bydan.framework.erp.util.DeepLoadType;
import com.bydan.erp.seguridad.util.SubSectorConstantesFunciones;
import com.bydan.erp.seguridad.business.entity.*;//SubSector
@SuppressWarnings("unused")
public class SubSectorParameterReturnGeneral extends GeneralEntityParameterReturnGeneral implements Serializable {
private static final long serialVersionUID=1L;
protected SubSector subsector;
protected List<SubSector> subsectors;
public List<Empresa> empresasForeignKey;
public List<Sector> sectorsForeignKey;
public SubSectorParameterReturnGeneral () throws Exception {
super();
this.subsectors= new ArrayList<SubSector>();
this.subsector= new SubSector();
this.empresasForeignKey=new ArrayList<Empresa>();
this.sectorsForeignKey=new ArrayList<Sector>();
}
public SubSector getSubSector() throws Exception {
return subsector;
}
public void setSubSector(SubSector newSubSector) {
this.subsector = newSubSector;
}
public List<SubSector> getSubSectors() throws Exception {
return subsectors;
}
public void setSubSectors(List<SubSector> newSubSectors) {
this.subsectors = newSubSectors;
}
public List<Empresa> getempresasForeignKey() {
return this.empresasForeignKey;
}
public List<Sector> getsectorsForeignKey() {
return this.sectorsForeignKey;
}
public void setempresasForeignKey(List<Empresa> empresasForeignKey) {
this.empresasForeignKey=empresasForeignKey;
}
public void setsectorsForeignKey(List<Sector> sectorsForeignKey) {
this.sectorsForeignKey=sectorsForeignKey;
}
}
| 29.520408 | 115 | 0.768406 |
fce727a4905d1ad75dc71b49a6558fb3f5a1fe59 | 6,810 | /**
* Copyright 2013 David Karnok
*
* 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 akarnokd.opengl.experiment;
import java.nio.FloatBuffer;
import java.util.concurrent.CancellationException;
import org.lwjgl.BufferUtils;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import static org.lwjgl.opengl.GL11.*;
import static java.lang.Math.*;
/**
*
*/
public class ShaderCalcModel {
public static void main(String[] args) {
G3D.init(800, 600);
Game game = new Game();
G3D.loop(30, game::tick);
}
static class Game {
Floor floor;
Box box;
int mousex = 100;
int mousey = 100;
public Game() {
floor = new Floor();
box = new Box();
box.setPos(0, -0.4f, -10);
box.setHeading(45);
box.setPitch(-1);
box.setRoll(0.1f);
Mouse.setGrabbed(true);
}
void tick() {
pollEvents();
floor.draw();
box.draw();
}
void pollEvents() {
Keyboard.poll();
if (Keyboard.isKeyDown(Keyboard.KEY_ESCAPE)) {
throw new CancellationException();
}
Mouse.setCursorPosition(mousex, mousey);
}
}
static class Floor {
void draw() {
glLoadIdentity();
glBegin(GL_QUADS);
glColor3f(.2f, .4f, 0);
glVertex3f(-100, -1, 100);
glVertex3f(-100, -1, -100);
glVertex3f(100, -1, -100);
glVertex3f(100, -1, 100);
glEnd();
}
}
static class Box {
float[] mat = { 1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
};
FloatBuffer posMat;
FloatBuffer headingMat;
FloatBuffer pitchMat;
FloatBuffer rollMat;
float posx;
float posy;
float posz;
float pitch;
float heading;
float roll;
public Box() {
posMat = BufferUtils.createFloatBuffer(mat.length);
headingMat = BufferUtils.createFloatBuffer(mat.length);
pitchMat = BufferUtils.createFloatBuffer(mat.length);
rollMat = BufferUtils.createFloatBuffer(mat.length);
posMat.put(mat);
headingMat.put(mat);
pitchMat.put(mat);
rollMat.put(mat);
}
void setPos(float x, float y, float z) {
posMat.put(12, x);
posMat.put(13, y);
posMat.put(14, z);
}
void setHeading(float a) {
headingMat.put(0, (float)cos(a));
headingMat.put(2, -(float)sin(a));
headingMat.put(8, (float)sin(a));
headingMat.put(10, (float)cos(a));
}
void setPitch(float p) {
pitchMat.put(5, (float)cos(p));
pitchMat.put(6, (float)sin(p));
pitchMat.put(9, -(float)sin(p));
pitchMat.put(10, (float)cos(p));
}
void setRoll(float r) {
rollMat.put(0, (float)cos(r));
rollMat.put(1, (float)sin(r));
rollMat.put(4, -(float)sin(r));
rollMat.put(5, (float)cos(r));
}
void draw() {
glLoadIdentity();
posMat.rewind();
glMultMatrix(posMat);
headingMat.rewind();
glMultMatrix(headingMat);
pitchMat.rewind();
glMultMatrix(pitchMat);
rollMat.rewind();
glMultMatrix(rollMat);
glColor3f(0.8f, 0.5f, 0.3f);
glBegin(GL_QUADS);
// front face
glNormal3f(0, 0, 1);
glTexCoord2f(0, 0);
glVertex3f(-1, -1, 1);
glTexCoord2f(1, 0);
glVertex3f(1, -1, 1);
glTexCoord2f(1, 1);
glVertex3f(1, 1, 1);
glTexCoord2f(0, 1);
glVertex3f(-1, 1, 1);
// backface
glNormal3f(0.0f, 0.0f, -1.0f);
glTexCoord2f(1.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, -1.0f);
glTexCoord2f(1.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, -1.0f);
glTexCoord2f(0.0f, 1.0f);
glVertex3f(1.0f, 1.0f, -1.0f);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(1.0f, -1.0f, -1.0f);
// Top Face
glNormal3f(0.0f, 1.0f, 0.0f);
glTexCoord2f(0.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, -1.0f);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-1.0f, 1.0f, 1.0f);
glTexCoord2f(1.0f, 0.0f);
glVertex3f(1.0f, 1.0f, 1.0f);
glTexCoord2f(1.0f, 1.0f);
glVertex3f(1.0f, 1.0f, -1.0f);
// Bottom Face
glNormal3f(0.0f, -1.0f, 0.0f);
glTexCoord2f(1.0f, 1.0f);
glVertex3f(-1.0f, -1.0f, -1.0f);
glTexCoord2f(0.0f, 1.0f);
glVertex3f(1.0f, -1.0f, -1.0f);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(1.0f, -1.0f, 1.0f);
glTexCoord2f(1.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, 1.0f);
// Right face
glNormal3f(1.0f, 0.0f, 0.0f);
glTexCoord2f(1.0f, 0.0f);
glVertex3f(1.0f, -1.0f, -1.0f);
glTexCoord2f(1.0f, 1.0f);
glVertex3f(1.0f, 1.0f, -1.0f);
glTexCoord2f(0.0f, 1.0f);
glVertex3f(1.0f, 1.0f, 1.0f);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(1.0f, -1.0f, 1.0f);
// Left Face
glNormal3f(-1.0f, 0.0f, 0.0f);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, -1.0f);
glTexCoord2f(1.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, 1.0f);
glTexCoord2f(1.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, 1.0f);
glTexCoord2f(0.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, -1.0f);
glEnd();
}
}
}
| 31.82243 | 81 | 0.473421 |
a3c9f02b75ddaf09d07b46651ade855783f8053c | 957 | package com.fasterxml.jackson.dataformat.ron.parser;
import com.fasterxml.jackson.dataformat.ron.InfTest;
import com.fasterxml.jackson.dataformat.ron.RONFactory;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import static org.junit.Assert.assertEquals;
public class InfParserTest extends InfTest {
private static RONParser newParser(String ron) throws IOException {
Reader reader = new StringReader(ron);
return new RONFactory().createParser(reader);
}
@Override
public void testFloat() throws IOException {
try (RONParser parser = newParser("inf")) {
assertEquals(Float.POSITIVE_INFINITY, parser.nextFloatValue(-1), 0.0001);
}
}
@Override
public void testDouble() throws IOException {
try (RONParser parser = newParser("inf")) {
assertEquals(Double.POSITIVE_INFINITY, parser.nextDoubleValue(-1), 0.0001);
}
}
}
| 29 | 87 | 0.704284 |
d75094823b6be8882b6070aacf29251c46e92c87 | 1,763 | /*
* Copyright © 2019 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.cdap.plugin.google.shopping.content.source;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapreduce.InputFormat;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.JobContext;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
/**
* Shopping content API input format.
*/
public class ShoppingContentInputFormat extends InputFormat {
@Override
public List<InputSplit> getSplits(JobContext context) {
Configuration configuration = context.getConfiguration();
String serviceAccountPath = configuration.get(ShoppingContentConstants.SERVICE_ACCOUNT_PATH);
String merchantId = configuration.get(ShoppingContentConstants.MERCHANT_ID);
List<InputSplit> splits = new ArrayList<>();
splits.add(new ShoppingContentSplit(serviceAccountPath, new BigInteger(merchantId)));
return splits;
}
@Override
public RecordReader createRecordReader(InputSplit split, TaskAttemptContext context) {
return new ShoppingContentRecordReader();
}
}
| 35.26 | 97 | 0.779921 |
1afc3ebe9c416580db73263bcb8443ad245337be | 1,182 | package com.blinkfox.fenix.jpa;
import javax.persistence.EntityManager;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean;
import org.springframework.data.repository.Repository;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;
/**
* 用来构造 {@link FenixJpaRepositoryFactory} 的实例.
*
* @author blinkfox on 2019-08-04.
* @see RepositoryFactorySupport
* @since v1.0.0
*/
public class FenixJpaRepositoryFactoryBean<T extends Repository<S, ID>, S, ID>
extends JpaRepositoryFactoryBean<T, S, ID> {
/**
* 用来创建一个新的 {@link FenixJpaRepositoryFactoryBean} 实例的构造方法.
*
* @param repositoryInterface must not be {@literal null}.
*/
public FenixJpaRepositoryFactoryBean(Class<? extends T> repositoryInterface) {
super(repositoryInterface);
}
/**
* 返回 {@link FenixJpaRepositoryFactory}.
*
* @param entityManager EntityManager 实体管理器.
* @return FenixJpaRepositoryFactory 实例
*/
@Override
protected RepositoryFactorySupport createRepositoryFactory(EntityManager entityManager) {
return new FenixJpaRepositoryFactory(entityManager);
}
}
| 30.307692 | 93 | 0.735195 |
7ae732b83126d8117b12ed4131c0cd397c662a8d | 1,061 | package org.javamaster.b2c.https;
import org.apache.catalina.connector.Connector;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* @author yudong
* @date 2018/4/13
*/
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Value("${http.port}")
private int port;
/**
* 配置http
*/
@Bean
public TomcatEmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setSecure(false);
connector.setPort(port);
tomcat.addAdditionalTomcatConnectors(connector);
return tomcat;
}
}
| 30.314286 | 99 | 0.763431 |
85b6a19b27802e596013618e598181cb86ab9de9 | 2,983 |
package mt.edu.um.cf2.jgribx;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
/**
*
* @author spidru
*/
public class CommandLine {
public static void main(String[] args)
{
Options options = new Options();
/* Version Information */
Option version = new Option("v", "version", false, "Show version information");
version.setRequired(false);
options.addOption(version);
/* File Information */
Option inputFile = new Option("i", "input", true, "Specify an input file");
inputFile.setRequired(false);
options.addOption(inputFile);
CommandLineParser parser = new DefaultParser();
HelpFormatter formatter = new HelpFormatter();
org.apache.commons.cli.CommandLine cmd = null;
try
{
cmd = parser.parse(options, args);
}
catch (ParseException e)
{
System.out.println(e.getMessage());
formatter.printHelp("JGribX", options);
System.exit(1);
}
/* If no arguments have been specified, display help */
if (cmd.getOptions().length == 0)
{
System.err.println("No arguments specified");
formatter.printHelp("JGribX", options);
System.exit(1);
}
if (cmd.hasOption("i"))
{
String inputFilePath = cmd.getOptionValue("i");
try
{
GribFile gribFile = new GribFile(inputFilePath);
// Print out generic GRIB file info
gribFile.getSummary(System.out);
List<String> params = gribFile.getParameterCodes();
System.out.println("Parameters:");
for (String param : params)
{
System.out.print(param + " ");
}
}
catch (FileNotFoundException e)
{
System.err.println("Cannot find file: " + inputFilePath);
}
catch (IOException e)
{
System.err.println("Could not open file: " + inputFilePath);
}
catch (NotSupportedException e)
{
System.err.println("GRIB file contains unsupported features: " + e);
}
catch (NoValidGribException e)
{
System.err.println("GRIB file is invalid: " + e);
}
}
if (cmd.hasOption("v"))
{
System.out.println("JGribX " + JGribX.getVersion());
}
}
}
| 30.438776 | 87 | 0.534361 |
751dfe8dda58f85fe24f3636be15fa8d4c54bc45 | 3,727 | package be.wegenenverkeer.atomium.server.spring;
/**
* Utility klasse om de SQL query op te bouwen om een een sync uit te voeren om het volgnummer in de atomium feed in the vullen voor een feed.
*/
public final class PostgreSqlSyncQueryProvider {
private PostgreSqlSyncQueryProvider() {
throw new UnsupportedOperationException("Constructor hidden.");
}
/**
* Bouw de SQL query die gebruikt kan worden om een volgnummer veld te zetten voor een tabel met events.
* Dat volgnummer zorgt voor een voorspelbare en consistente volgorde waarop de events in een atomium feed kopen.
* Gebruik van deze query voorkomt tussenvoegen van events en zorgt dat de events in verschillende thread kunnen geproduceerd worden.
*
* Deze query is gebouwd om atomic te zijn. De query bestaat uit 2 delen:
* 1) eerst worden de nieuwe atom_entries berekend via een common table expression.
* In Postgres kan dat via het WITH statement.
* https://www.postgresql.org/docs/current/static/queries-with.html
*
* * Bepaal eerst de huidige hoogste waarde van de bestaande atom entries. Dat wordt opgeslagen als max_atom_entry
* * Bepaal dan de lijst van items die nog geen atom_entry hebben, en orden die
* * Vervolgens bereken je voor die lijst de nieuwe atom_entry waarde
*
* 2) dan wordt deze table gebruikt om ook effectief de tabel te updaten. In Postgres kan dat handig
* via UPDATE ... FROM:
* https://www.postgresql.org/docs/current/static/sql-update.html
*
* @param table naar van de tabel waarin het volgnummer zit, vb "oproep_event"
* @param sequenceField veld dat gebruikt wordt om de volgorde aan te duiden, vb "atom_entry"
* @param orderBy deel van de SQL query om de volgorde van de items te bepalen, vb "oproep_event.creation_time ASC"
* @return volledige SQL query om de sync uit te voeren
*/
public static String syncQuery(String table, String sequenceField, String orderBy) {
return (""
+ "WITH\n"
+ " max_atom_entry -- max bepalen, basis voor zetten volgnummer, -1 als nog niet gezet zodat teller bij 0 begint\n"
+ " AS ( SELECT coalesce(max(${table}.${sequence-field}), -1) max_atom_entry\n"
+ " FROM ${table}),\n"
+ " to_number -- lijst met aan te passen records, moet dit apart bepalen omdat volgorde anders fout is\n"
+ " AS (\n"
+ " SELECT\n"
+ " ${table}.id,\n"
//+ " ${table}.creation_time,\n"
+ " max.max_atom_entry max_atom_entry\n"
+ " FROM ${table} CROSS JOIN max_atom_entry max\n"
+ " WHERE ${table}.${sequence-field} IS NULL\n"
+ " ORDER BY ${order-by}\n"
+ " ),\n"
+ " to_update -- lijst met wijzigingen opbouwen\n"
+ " AS (\n"
+ " SELECT\n"
+ " id,\n"
+ " (row_number()\n"
+ " OVER ()) + max_atom_entry new_value\n"
+ " FROM to_number\n"
+ " ORDER BY id ASC\n"
+ " )\n"
+ "-- wijzigingen toepassen\n"
+ "UPDATE ${table}\n"
+ "SET ${sequence-field} = to_update.new_value\n"
+ "FROM to_update\n"
+ "WHERE ${table}.id = to_update.id;")
.replace("${table}", table)
.replace("${sequence-field}", sequenceField)
.replace("${order-by}", orderBy);
}
}
| 52.492958 | 142 | 0.576603 |
a2c853a7cdcdd2daf53285d49b3457aaa940cc03 | 12,845 | package integration.tests;
import com.github.springtestdbunit.DbUnitTestExecutionListener;
import com.github.springtestdbunit.annotation.*;
import com.github.springtestdbunit.assertion.DatabaseAssertionMode;
import fr.mypr.MyPrApplication;
import fr.mypr.ihm.controller.RegistrationForm;
import integration.*;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.*;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.http.MediaType;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.test.context.*;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.transaction.TransactionalTestExecutionListener;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@ActiveProfiles({"integrationTest"})
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {IntegrationTestConfig.class})
@TestExecutionListeners({DependencyInjectionTestExecutionListener.class,
TransactionalTestExecutionListener.class,
DbUnitTestExecutionListener.class})
@WebAppConfiguration
public class RegistrationFormSubmitIT
{
private static final String EMAIL = "[email protected]";
private static final String MALFORMED_EMAIL = "john.smithatgmail.com";
private static final String PASSWORD = "password";
private static final String FIRST_NAME = "John";
private static final String LAST_NAME = "Smith";
@Autowired
private FilterChainProxy springSecurityFilterChain;
@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
@Before
public void setUp()
{
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
.addFilter(springSecurityFilterChain)
.build();
}
@Test
@DatabaseSetup("no-users.xml")
@ExpectedDatabase(value = "no-users.xml", assertionMode = DatabaseAssertionMode.NON_STRICT)
public void showRegistrationForm_should_render_registration_page_with_empty_form() throws Exception
{
mockMvc.perform(get("/user/register"))
.andExpect(status().isOk())
.andExpect(view().name("user/registrationForm"))
.andExpect(model().attribute("user", allOf(
hasProperty("email", isEmptyOrNullString()),
hasProperty("firstName", isEmptyOrNullString()),
hasProperty("lastName", isEmptyOrNullString()),
hasProperty("password", isEmptyOrNullString()),
hasProperty("confirmPassword", isEmptyOrNullString())
)));
}
@Test
@DatabaseSetup("no-users.xml")
@ExpectedDatabase(value = "no-users.xml", assertionMode = DatabaseAssertionMode.NON_STRICT)
public void registerUserAccount_should_render_registration_form_with_errors_when_registration_with_empty_form() throws Exception
{
mockMvc.perform(post("/user/register")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.sessionAttr(RegistrationForm.SESSION_ATTRIBUTE_USER_FORM, new RegistrationForm())
)
.andExpect(status().isOk())
.andExpect(view().name("user/registrationForm"))
.andExpect(model().attribute(RegistrationForm.MODEL_ATTRIBUTE_USER_FORM, allOf(
hasProperty(RegistrationForm.FIELD_NAME_EMAIL, isEmptyOrNullString()),
hasProperty(RegistrationForm.FIELD_NAME_FIRST_NAME, isEmptyOrNullString()),
hasProperty(RegistrationForm.FIELD_NAME_LAST_NAME, isEmptyOrNullString()),
hasProperty(RegistrationForm.FIELD_NAME_PASSWORD, isEmptyOrNullString()),
hasProperty(RegistrationForm.FIELD_NAME_CONFIRM_PASSWORD, isEmptyOrNullString())
)))
.andExpect(model().attributeHasFieldErrors(RegistrationForm.MODEL_ATTRIBUTE_USER_FORM,
RegistrationForm.FIELD_NAME_EMAIL,
RegistrationForm.FIELD_NAME_FIRST_NAME,
RegistrationForm.FIELD_NAME_LAST_NAME,
RegistrationForm.FIELD_NAME_PASSWORD,
RegistrationForm.FIELD_NAME_CONFIRM_PASSWORD
));
}
@Test
@DatabaseSetup("no-users.xml")
@ExpectedDatabase(value = "no-users.xml", assertionMode = DatabaseAssertionMode.NON_STRICT)
public void registerUserAccount_should_render_registration_form_with_errors_when_registration_with_too_long_values() throws Exception
{
String email = RandomStringUtils.random(101);
String firstName = RandomStringUtils.random(101);
String lastName = RandomStringUtils.random(101);
mockMvc.perform(post("/user/register")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param(RegistrationForm.FIELD_NAME_EMAIL, email)
.param(RegistrationForm.FIELD_NAME_FIRST_NAME, firstName)
.param(RegistrationForm.FIELD_NAME_LAST_NAME, lastName)
.param(RegistrationForm.FIELD_NAME_PASSWORD, PASSWORD)
.param(RegistrationForm.FIELD_NAME_CONFIRM_PASSWORD, PASSWORD)
.sessionAttr(RegistrationForm.SESSION_ATTRIBUTE_USER_FORM, new RegistrationForm())
)
.andExpect(status().isOk())
.andExpect(view().name("user/registrationForm"))
.andExpect(model().attribute(RegistrationForm.MODEL_ATTRIBUTE_USER_FORM, allOf(
hasProperty(RegistrationForm.FIELD_NAME_EMAIL, is(email)),
hasProperty(RegistrationForm.FIELD_NAME_FIRST_NAME, is(firstName)),
hasProperty(RegistrationForm.FIELD_NAME_LAST_NAME, is(lastName)),
hasProperty(RegistrationForm.FIELD_NAME_PASSWORD, is(PASSWORD)),
hasProperty(RegistrationForm.FIELD_NAME_CONFIRM_PASSWORD, is(PASSWORD))
)))
.andExpect(model().attributeHasFieldErrors(RegistrationForm.MODEL_ATTRIBUTE_USER_FORM,
RegistrationForm.FIELD_NAME_EMAIL,
RegistrationForm.FIELD_NAME_FIRST_NAME,
RegistrationForm.FIELD_NAME_LAST_NAME
));
}
@Test
@DatabaseSetup("no-users.xml")
@ExpectedDatabase(value = "no-users.xml", assertionMode = DatabaseAssertionMode.NON_STRICT)
public void registerUserAccount_should_render_registration_form_with_errors_when_registration_with_password_mismatch() throws Exception
{
String incorrectPassword = "mismatch";
mockMvc.perform(post("/user/register")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param(RegistrationForm.FIELD_NAME_EMAIL, EMAIL)
.param(RegistrationForm.FIELD_NAME_FIRST_NAME, FIRST_NAME)
.param(RegistrationForm.FIELD_NAME_LAST_NAME, LAST_NAME)
.param(RegistrationForm.FIELD_NAME_PASSWORD, PASSWORD)
.param(RegistrationForm.FIELD_NAME_CONFIRM_PASSWORD, incorrectPassword)
.sessionAttr(RegistrationForm.SESSION_ATTRIBUTE_USER_FORM, new RegistrationForm())
)
.andExpect(status().isOk())
.andExpect(view().name("user/registrationForm"))
.andExpect(model().attribute(RegistrationForm.MODEL_ATTRIBUTE_USER_FORM, allOf(
hasProperty(RegistrationForm.FIELD_NAME_EMAIL, is(EMAIL)),
hasProperty(RegistrationForm.FIELD_NAME_FIRST_NAME, is(FIRST_NAME)),
hasProperty(RegistrationForm.FIELD_NAME_LAST_NAME, is(LAST_NAME)),
hasProperty(RegistrationForm.FIELD_NAME_PASSWORD, is(PASSWORD)),
hasProperty(RegistrationForm.FIELD_NAME_CONFIRM_PASSWORD, is(incorrectPassword))
)))
.andExpect(model().attributeHasFieldErrors(RegistrationForm.MODEL_ATTRIBUTE_USER_FORM,
RegistrationForm.FIELD_NAME_PASSWORD,
RegistrationForm.FIELD_NAME_CONFIRM_PASSWORD
));
}
@Test
@DatabaseSetup("no-users.xml")
@ExpectedDatabase(value = "no-users.xml", assertionMode = DatabaseAssertionMode.NON_STRICT)
public void registerUserAccount_should_render_registration_form_with_errors_when_registration_with_malformed_email() throws Exception
{
mockMvc.perform(post("/user/register")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param(RegistrationForm.FIELD_NAME_EMAIL, MALFORMED_EMAIL)
.param(RegistrationForm.FIELD_NAME_FIRST_NAME, FIRST_NAME)
.param(RegistrationForm.FIELD_NAME_LAST_NAME, LAST_NAME)
.param(RegistrationForm.FIELD_NAME_PASSWORD, PASSWORD)
.param(RegistrationForm.FIELD_NAME_CONFIRM_PASSWORD, PASSWORD)
.sessionAttr(RegistrationForm.SESSION_ATTRIBUTE_USER_FORM, new RegistrationForm())
)
.andExpect(status().isOk())
.andExpect(view().name("user/registrationForm"))
.andExpect(model().attribute(RegistrationForm.MODEL_ATTRIBUTE_USER_FORM, allOf(
hasProperty(RegistrationForm.FIELD_NAME_EMAIL, is(MALFORMED_EMAIL)),
hasProperty(RegistrationForm.FIELD_NAME_FIRST_NAME, is(FIRST_NAME)),
hasProperty(RegistrationForm.FIELD_NAME_LAST_NAME, is(LAST_NAME)),
hasProperty(RegistrationForm.FIELD_NAME_PASSWORD, is(PASSWORD)),
hasProperty(RegistrationForm.FIELD_NAME_CONFIRM_PASSWORD, is(PASSWORD))
)))
.andExpect(model().attributeHasFieldErrors(RegistrationForm.MODEL_ATTRIBUTE_USER_FORM,
RegistrationForm.FIELD_NAME_EMAIL
));
}
@Test
@DatabaseSetup("users.xml")
@ExpectedDatabase(value = "users.xml", assertionMode = DatabaseAssertionMode.NON_STRICT)
public void registerUserAccount_should_render_registration_form_with_errors_when_registration_with_email_exists() throws Exception
{
mockMvc.perform(post("/user/register")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param(RegistrationForm.FIELD_NAME_EMAIL, IntegrationTestConstants.User.REGISTERED_USER.getEmail())
.param(RegistrationForm.FIELD_NAME_FIRST_NAME, FIRST_NAME)
.param(RegistrationForm.FIELD_NAME_LAST_NAME, LAST_NAME)
.param(RegistrationForm.FIELD_NAME_PASSWORD, PASSWORD)
.param(RegistrationForm.FIELD_NAME_CONFIRM_PASSWORD, PASSWORD)
.sessionAttr(RegistrationForm.SESSION_ATTRIBUTE_USER_FORM, new RegistrationForm())
)
.andExpect(status().isOk())
.andExpect(view().name("user/registrationForm"))
.andExpect(model().attribute(RegistrationForm.MODEL_ATTRIBUTE_USER_FORM, allOf(
hasProperty(RegistrationForm.FIELD_NAME_EMAIL, is(IntegrationTestConstants.User.REGISTERED_USER.getEmail())),
hasProperty(RegistrationForm.FIELD_NAME_FIRST_NAME, is(FIRST_NAME)),
hasProperty(RegistrationForm.FIELD_NAME_LAST_NAME, is(LAST_NAME)),
hasProperty(RegistrationForm.FIELD_NAME_PASSWORD, is(PASSWORD)),
hasProperty(RegistrationForm.FIELD_NAME_CONFIRM_PASSWORD, is(PASSWORD))
)))
.andExpect(model().attributeHasFieldErrors(RegistrationForm.MODEL_ATTRIBUTE_USER_FORM,
RegistrationForm.FIELD_NAME_EMAIL
));
}
@Test
@DatabaseSetup("no-users.xml")
@ExpectedDatabase(value = "register-user-expected.xml", assertionMode = DatabaseAssertionMode.NON_STRICT)
public void registerUserAccount_should_create_new_account_and_render_index_page_when_registration_ok() throws Exception
{
mockMvc.perform(post("/user/register")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param(RegistrationForm.FIELD_NAME_EMAIL, EMAIL)
.param(RegistrationForm.FIELD_NAME_FIRST_NAME, FIRST_NAME)
.param(RegistrationForm.FIELD_NAME_LAST_NAME, LAST_NAME)
.param(RegistrationForm.FIELD_NAME_PASSWORD, PASSWORD)
.param(RegistrationForm.FIELD_NAME_CONFIRM_PASSWORD, PASSWORD)
.sessionAttr(RegistrationForm.SESSION_ATTRIBUTE_USER_FORM, new RegistrationForm())
)
.andDo(print())
.andExpect(status().isFound())
.andExpect(redirectedUrl("/"));
}
}
| 51.38 | 136 | 0.733904 |
3298a5cf6e8641be4b8af521952ec6fc509f4b23 | 769 |
/**
* Lesson 003.
* <dl>
* <dt>課題4(Lesson 003-04)</dt>
* <dd>配列内の一番大きい値を返す。</dd>
* </dl>
*
* @author tomo-sato
*/
public class Lesson_003_04 {
public static void main(String[] args) {
int[] iarr = {32,1,2,1,32,654,113,21,32,212};
int ans = max(iarr);
System.out.println(ans);
}
/**
* 2つの数値を比較し大きいほうを返す。
*
* @param i 数値1
* @param j 数値2
* @return 比較結果
*/
public static int max(final int i, final int j) {
if (i < j) {
return j;
}
return i;
}
/**
* 配列内の一番大きい値を返す。
*
* @param iarr 数値配列
* @return 比較結果
*/
public static int max(int[] iarr){
int ans = iarr[0];
int j;
for(int i = 1; i < iarr.length; i++){
System.out.printf("loop count=%d\n", i);
j = iarr[i];
ans = max(ans, j);
}
return ans;
}
}
| 14.509434 | 50 | 0.548765 |
e2856f28be151b35e889231f98fbc2c3d60dd2a7 | 12,226 | package game_tact;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
public class dbFunctions {
public static int id;
public static int sId;
public static String gURL;
public static String Nsv;
public static String Ops;
public static String username;
public static String gmail;
public static String pass;
static ArrayList<Integer> stStat = new ArrayList<Integer>();
static ArrayList<String> komentarji = new ArrayList<String>();
public static int count=0;
public static int register(String usr, String email, String pass) {
Connection c = null;
Statement stmt = null;
int num = 1;
try {
Class.forName("org.postgresql.Driver");
c = DriverManager
.getConnection("jdbc:postgresql://kandula.db.elephantsql.com:5432/pjthwgkl",
"pjthwgkl", "sK9ZBSjmWuziwv4QEqlwYTrHnrh_XD-4");
System.out.println("Opened database successfully");
String sql="SELECT register('"+usr+"','"+email+"','"+pass+"')";
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while ( rs.next() ) {
num = rs.getInt(1);
System.out.println(id);
}
if(num==0) {
sql=" INSERT INTO uporabniki (username, gmail, geslo) VALUES ('"+usr+"', '"+email+"', '"+pass+"');";
stmt = c.createStatement();
stmt.executeUpdate(sql);
}
System.out.println(sql.toString());
rs.close();
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName()+": "+ e.getMessage() );
System.exit(0);
}
return num;
}
public static Boolean login(String email, String pass) {
Connection c = null;
Statement stmt = null;
Boolean id = false;
try {
Class.forName("org.postgresql.Driver");
c = DriverManager
.getConnection("jdbc:postgresql://kandula.db.elephantsql.com:5432/pjthwgkl",
"pjthwgkl", "sK9ZBSjmWuziwv4QEqlwYTrHnrh_XD-4");
System.out.println("Opened database successfully");
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery( "SELECT login('"+email+"','"+pass+"')" );
while ( rs.next() ) {
id = rs.getBoolean(1);
System.out.println(id);
}
rs.close();
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName()+": "+ e.getMessage() );
System.exit(0);
}
System.out.println("Operation done successfully");
return id;
}
public static void loginInfo(String email) {
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.postgresql.Driver");
c = DriverManager
.getConnection("jdbc:postgresql://kandula.db.elephantsql.com:5432/pjthwgkl",
"pjthwgkl", "sK9ZBSjmWuziwv4QEqlwYTrHnrh_XD-4");
System.out.println("Opened database successfully");
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery( "SELECT * FROM \"public\".\"uporabniki\"WHERE gmail='"+email+"'" );
while ( rs.next() ) {
id = rs.getInt("id");
username = rs.getString("username");
gmail = rs.getString("gmail");
pass = rs.getString("geslo");
System.out.println(id+","+username);
}
rs.close();
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName()+": "+ e.getMessage() );
System.exit(0);
}
System.out.println("Operation done successfully");
}
public static void updateUser(String email, String geslo, String usr) {
Connection c = null;
//Statement stmt = null;
try {
Class.forName("org.postgresql.Driver");
c = DriverManager
.getConnection("jdbc:postgresql://kandula.db.elephantsql.com:5432/pjthwgkl",
"pjthwgkl", "sK9ZBSjmWuziwv4QEqlwYTrHnrh_XD-4");
PreparedStatement ps=c.prepareStatement("SELECT posodobi(?,?,?,?)");
ps.setInt(1,id);
ps.setString(2,usr);
ps.setString(3,email);
ps.setString(4,geslo);
ResultSet rs = ps.executeQuery();
rs.next();
rs.close();
ps.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName()+": "+ e.getMessage() );
System.exit(0);
}
System.out.println("Operation done successfully");
}
public static void dodajKomentar(String opis) {
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.postgresql.Driver");
c = DriverManager
.getConnection("jdbc:postgresql://kandula.db.elephantsql.com:5432/pjthwgkl",
"pjthwgkl", "sK9ZBSjmWuziwv4QEqlwYTrHnrh_XD-4");
System.out.println("Opened database successfully");
String sql = "SELECT dodajKomentar("+id+",'"+opis+"',"+sId+")";
stmt = c.createStatement();
System.out.println(sql.toString());
ResultSet rs = stmt.executeQuery(sql);
rs.close();
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName()+": "+ e.getMessage() );
System.exit(0);
}
System.out.println("Operation done successfully");
}
public static void dodajStrategijo(String opis, String naslov, String url) {
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.postgresql.Driver");
c = DriverManager
.getConnection("jdbc:postgresql://kandula.db.elephantsql.com:5432/pjthwgkl",
"pjthwgkl", "sK9ZBSjmWuziwv4QEqlwYTrHnrh_XD-4");
System.out.println("Opened database successfully");
String sql = "SELECT dodajStrategijo("+id+",'"+opis+"','"+url+"','"+naslov+"')";
stmt = c.createStatement();
System.out.println(sql.toString());
ResultSet rs = stmt.executeQuery(sql);
rs.close();
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName()+": "+ e.getMessage() );
System.exit(0);
}
System.out.println("Operation done successfully");
}
public static void posodobiStrategijo(String opis, String naslov, String url) {
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.postgresql.Driver");
c = DriverManager
.getConnection("jdbc:postgresql://kandula.db.elephantsql.com:5432/pjthwgkl",
"pjthwgkl", "sK9ZBSjmWuziwv4QEqlwYTrHnrh_XD-4");
System.out.println("Opened database successfully");
String sql = "SELECT urediStrategijo("+id+",'"+opis+"','"+url+"','"+naslov+"',"+sId+")";
stmt = c.createStatement();
System.out.println(sql.toString());
ResultSet rs = stmt.executeQuery(sql);
rs.close();
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName()+": "+ e.getMessage() );
System.exit(0);
}
System.out.println("Operation done successfully");
getInfo();
}
public static void izbrisiStrategijo() {
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.postgresql.Driver");
c = DriverManager
.getConnection("jdbc:postgresql://kandula.db.elephantsql.com:5432/pjthwgkl",
"pjthwgkl", "sK9ZBSjmWuziwv4QEqlwYTrHnrh_XD-4");
System.out.println("Opened database successfully");
String sql = "SELECT izbrisiStrategijo("+sId+")";
stmt = c.createStatement();
System.out.println(sql.toString());
ResultSet rs = stmt.executeQuery(sql);
rs.close();
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName()+": "+ e.getMessage() );
System.exit(0);
}
System.out.println("Operation done successfully");
getInfo();
}
public static void nextStrat() {
if (count < stStat.size())
{
count++;
}
else
{
count=0;
}
getInfo();
}
public static void backStrat() {
if (count > 0)
{
count--;
}
else
{
count=0;
}
getInfo();
}
public static void getNum() {
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.postgresql.Driver");
c = DriverManager
.getConnection("jdbc:postgresql://kandula.db.elephantsql.com:5432/pjthwgkl",
"pjthwgkl", "sK9ZBSjmWuziwv4QEqlwYTrHnrh_XD-4");
System.out.println("Opened database successfully");
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery( "SELECT id FROM \"public\".\"strategije\" order by id desc ");
while ( rs.next() ) {
stStat.add(rs.getInt(1));
System.out.println(1);
}
rs.close();
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName()+": "+ e.getMessage() );
System.exit(0);
}
System.out.println("Operation done successfully");
}
public static void getInfo() {
int id_ = stStat.get(count);
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.postgresql.Driver");
c = DriverManager
.getConnection("jdbc:postgresql://kandula.db.elephantsql.com:5432/pjthwgkl",
"pjthwgkl", "sK9ZBSjmWuziwv4QEqlwYTrHnrh_XD-4");
System.out.println("Opened database successfully");
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery( "SELECT * FROM \"public\".\"strategije\" where id="+id_+"");
while ( rs.next() ) {
sId = rs.getInt(1);
gURL = rs.getString(3);
Nsv = rs.getString(2);
Ops = rs.getString(4);
}
rs.close();
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName()+": "+ e.getMessage() );
System.exit(0);
}
System.out.println(gURL+","+Nsv+","+Ops+","+id_);
}
public static void getKomentarji() {
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.postgresql.Driver");
c = DriverManager
.getConnection("jdbc:postgresql://kandula.db.elephantsql.com:5432/pjthwgkl",
"pjthwgkl", "sK9ZBSjmWuziwv4QEqlwYTrHnrh_XD-4");
System.out.println("Opened database successfully");
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery( "SELECT * FROM \"public\".\"komentarji\" where strategija_id="+sId+"");
while ( rs.next() ) {
komentarji.add(rs.getString(4)+": "+rs.getString(2));
}
rs.close();
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName()+": "+ e.getMessage() );
System.exit(0);
}
}
}
| 32.429708 | 116 | 0.53239 |
eae070139958f6c769c083cdfb4f48b2a07b342a | 1,690 | package ar.com.javacuriosities.jsf.filters;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebFilter(filterName = "AuthFilter", urlPatterns = {"*.xhtml"})
public class AuthorizationFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
try {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
HttpSession session = httpServletRequest.getSession(false);
String uri = httpServletRequest.getRequestURI();
if (shouldAllow(uri) || isLogged(session)) {
chain.doFilter(request, response);
} else {
httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/index.xhtml");
}
} catch (Exception e) {
// Log and Handle exception
e.printStackTrace();
}
}
@Override
public void destroy() {
}
private boolean isLogged(HttpSession session) {
return session != null && session.getAttribute("logged") != null;
}
private boolean shouldAllow(String uri) {
return uri.contains("/index.xhtml") || uri.contains("/redirect");
}
}
| 32.5 | 103 | 0.685207 |
f803d4f5eee2c766eee6c2798c16e6f317070eb3 | 4,574 | package egovframework.let.uss.olp.qtm.service;
import java.io.Serializable;
import org.apache.commons.lang3.builder.ToStringBuilder;
/**
* 설문템플릿 VO Class 구현
* @author 공통서비스 장동한
* @since 2009.03.20
* @version 1.0
* @see
*
* <pre>
* << 개정이력(Modification Information) >>
*
* 수정일 수정자 수정내용
* ------- -------- ---------------------------
* 2009.03.20 장동한 최초 생성
* 2011.08.31 JJY 경량환경 템플릿 커스터마이징버전 생성
*
* </pre>
*/
public class QustnrTmplatManageVO implements Serializable {
/**
* serialVersionUID
*/
private static final long serialVersionUID = 1L;
/** 설문템플릿 아이디 */
private String qestnrTmplatId = "";
/** 설문템플릿 유형 */
private String qestnrTmplatTy = "";
/** 설문템플 이미지경로 */
public byte[] qestnrTmplatImagepathnm;
/** 설문템플릿 설명 */
private String qestnrTmplatCn = "";
/** 서물템플릿경로명 */
private String qestnrTmplatCours;
/** 최초등록시점 */
private String frstRegisterPnttm = "";
/** 최초등록자아이디 */
private String frstRegisterId = "";
/** 최종수정자 시점 */
private String lastUpdusrPnttm = "";
/** 최종수정자아이디 */
private String lastUpdusrId = "";
/** 화면 명령 처리 */
private String cmd = "";
/**
* qestnrTmplatId attribute 를 리턴한다.
* @return the String
*/
public String getQestnrTmplatId() {
return qestnrTmplatId;
}
/**
* qestnrTmplatId attribute 값을 설정한다.
* @return qestnrTmplatId String
*/
public void setQestnrTmplatId(String qestnrTmplatId) {
this.qestnrTmplatId = qestnrTmplatId;
}
/**
* qestnrTmplatTy attribute 를 리턴한다.
* @return the String
*/
public String getQestnrTmplatTy() {
return qestnrTmplatTy;
}
/**
* qestnrTmplatTy attribute 값을 설정한다.
* @return qestnrTmplatTy String
*/
public void setQestnrTmplatTy(String qestnrTmplatTy) {
this.qestnrTmplatTy = qestnrTmplatTy;
}
/**
* qestnrTmplatImagepathnm attribute 값을 설정한다.
* @return qestnrTmplatImagepathnm byte[]
*/
public void setQestnrTmplatImagepathnm(byte[] qestnrTmplatImagepathnm) {
this.qestnrTmplatImagepathnm = qestnrTmplatImagepathnm;
}
/**
* qestnrTmplatCn attribute 를 리턴한다.
* @return the String
*/
public String getQestnrTmplatCn() {
return qestnrTmplatCn;
}
/**
* qestnrTmplatCn attribute 값을 설정한다.
* @return qestnrTmplatCn String
*/
public void setQestnrTmplatCn(String qestnrTmplatCn) {
this.qestnrTmplatCn = qestnrTmplatCn;
}
/**
* qestnrTmplatCours attribute 를 리턴한다.
* @return the String
*/
public String getQestnrTmplatCours() {
return qestnrTmplatCours;
}
/**
* qestnrTmplatCours attribute 값을 설정한다.
* @return qestnrTmplatCours String
*/
public void setQestnrTmplatCours(String qestnrTmplatCours) {
this.qestnrTmplatCours = qestnrTmplatCours;
}
/**
* frstRegisterPnttm attribute 를 리턴한다.
* @return the String
*/
public String getFrstRegisterPnttm() {
return frstRegisterPnttm;
}
/**
* frstRegisterPnttm attribute 값을 설정한다.
* @return frstRegisterPnttm String
*/
public void setFrstRegisterPnttm(String frstRegisterPnttm) {
this.frstRegisterPnttm = frstRegisterPnttm;
}
/**
* frstRegisterId attribute 를 리턴한다.
* @return the String
*/
public String getFrstRegisterId() {
return frstRegisterId;
}
/**
* frstRegisterId attribute 값을 설정한다.
* @return frstRegisterId String
*/
public void setFrstRegisterId(String frstRegisterId) {
this.frstRegisterId = frstRegisterId;
}
/**
* lastUpdusrPnttm attribute 를 리턴한다.
* @return the String
*/
public String getLastUpdusrPnttm() {
return lastUpdusrPnttm;
}
/**
* lastUpdusrPnttm attribute 값을 설정한다.
* @return lastUpdusrPnttm String
*/
public void setLastUpdusrPnttm(String lastUpdusrPnttm) {
this.lastUpdusrPnttm = lastUpdusrPnttm;
}
/**
* lastUpdusrId attribute 를 리턴한다.
* @return the String
*/
public String getLastUpdusrId() {
return lastUpdusrId;
}
/**
* lastUpdusrId attribute 값을 설정한다.
* @return lastUpdusrId String
*/
public void setLastUpdusrId(String lastUpdusrId) {
this.lastUpdusrId = lastUpdusrId;
}
/**
* cmd attribute 를 리턴한다.
* @return the String
*/
public String getCmd() {
return cmd;
}
/**
* cmd attribute 값을 설정한다.
* @return cmd String
*/
public void setCmd(String cmd) {
this.cmd = cmd;
}
/**
* toString 메소드를 대치한다.
*/
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
| 20.790909 | 74 | 0.644294 |
2fca845c4ccda900fd4a8f8154ff7c72063a87a9 | 611 | /**
* Description: provide the information for obtaining a best reference value for 1-move
*
* @ Author Create/Modi Note
* Xiaofeng Xie Aug 10, 2006
* Xiaofeng Xie Jun 02, 2008
* Xiaofeng Xie Aug 21, 2008 MAOS M01.00.00
*
* @version M01.00.00
* @since M01.00.00
*/
package maosKernel.behavior.greedy.referSel;
public class BestofAllReferSelectModel extends AbsFullReferSelectModel {
public BestofAllReferSelectModel() {}
protected boolean internIsAcceptableQuality(double newReferQuality) {
return (newReferQuality<ultimateQuality);
}
}
| 25.458333 | 88 | 0.690671 |
43fd353c4c85bebae646c10c842a5ca9261f5e58 | 3,690 | /*
* Copyright 2016 Davide Maestroni
*
* 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.github.dm.jrt.android.core.runner;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import com.github.dm.jrt.core.runner.Runner;
import com.github.dm.jrt.core.util.ConstantConditions;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.concurrent.Executor;
/**
* Utility class for creating and sharing runner instances, employing specific Android classes.
* <p>
* Created by davide-maestroni on 09/28/2014.
*/
@SuppressWarnings("WeakerAccess")
public class AndroidRunners {
private static final Runner sMainRunner = new MainRunner();
/**
* Avoid explicit instantiation.
*/
protected AndroidRunners() {
ConstantConditions.avoid();
}
/**
* Returns a runner employing the specified Handler.
*
* @param handler the Handler.
* @return the runner instance.
*/
@NotNull
public static Runner handlerRunner(@NotNull final Handler handler) {
return new HandlerRunner(handler);
}
/**
* Returns a runner employing the specified Handler thread.
*
* @param thread the thread.
* @return the runner instance.
*/
@NotNull
public static Runner handlerRunner(@NotNull final HandlerThread thread) {
if (!thread.isAlive()) {
thread.start();
}
return looperRunner(thread.getLooper());
}
/**
* Returns a runner employing the specified Looper.
*
* @param looper the Looper instance.
* @return the runner instance.
*/
@NotNull
public static Runner looperRunner(@NotNull final Looper looper) {
return new HandlerRunner(new Handler(looper));
}
/**
* Returns the shared runner employing the main thread Looper.
*
* @return the runner instance.
*/
@NotNull
public static Runner mainRunner() {
return sMainRunner;
}
/**
* Returns a runner employing the calling thread Looper.
*
* @return the runner instance.
*/
@NotNull
@SuppressWarnings("ConstantConditions")
public static Runner myRunner() {
return looperRunner(Looper.myLooper());
}
/**
* Returns a runner employing async tasks.
* <p>
* Beware of the caveats of using
* <a href="http://developer.android.com/reference/android/os/AsyncTask.html">AsyncTask</a>s
* especially on some platform versions.
*
* @return the runner instance.
*/
@NotNull
public static Runner taskRunner() {
return taskRunner(null);
}
/**
* Returns a runner employing async tasks running on the specified executor.
* <p>
* Beware of the caveats of using
* <a href="http://developer.android.com/reference/android/os/AsyncTask.html">AsyncTask</a>s
* especially on some platform versions.
* <p>
* Note also that the executor instance will be ignored on platforms with API level lower than
* {@value android.os.Build.VERSION_CODES#HONEYCOMB}.
*
* @param executor the executor.
* @return the runner instance.
*/
@NotNull
public static Runner taskRunner(@Nullable final Executor executor) {
return new AsyncTaskRunner(executor);
}
}
| 26.73913 | 96 | 0.704336 |
9cbafd3fe9e8ed9c6752c51b94aeb2a9bc568613 | 333 | package com.linktera.linkteraquiz.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.NoRepositoryBean;
import java.io.Serializable;
@NoRepositoryBean
public interface GenericRepository<T> extends JpaRepository<T,Long> {
T merge(T entity);
}
| 20.8125 | 70 | 0.777778 |
9c91e0d35f87fb2a4979fdc2de52194bad207b4e | 8,825 | /*
* Copyright @ 2015 Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.impl.neomedia.transform.dtls;
import org.ice4j.ice.*;
import org.jitsi.impl.neomedia.*;
import org.jitsi.impl.neomedia.transform.*;
import org.jitsi.service.neomedia.*;
/**
* Implements {@link SrtpControl.TransformEngine} (and, respectively,
* {@link org.jitsi.impl.neomedia.transform.TransformEngine}) for DTLS-SRTP.
*
* @author Lyubomir Marinov
*/
public class DtlsTransformEngine
implements SrtpControl.TransformEngine
{
/**
* The <tt>RTPConnector</tt> which uses this <tt>TransformEngine</tt>.
*/
private AbstractRTPConnector connector;
/**
* The indicator which determines whether
* {@link SrtpControl.TransformEngine#cleanup()} has been invoked on this
* instance to prepare it for garbage collection.
*/
private boolean disposed = false;
/**
* The <tt>DtlsControl</tt> which has initialized this instance.
*/
private final DtlsControlImpl dtlsControl;
/**
* The <tt>MediaType</tt> of the stream which this instance works for/is
* associated with.
*/
private MediaType mediaType;
/**
* The <tt>PacketTransformer</tt>s of this <tt>TransformEngine</tt> for
* data/RTP and control/RTCP packets.
*/
private final DtlsPacketTransformer[] packetTransformers
= new DtlsPacketTransformer[2];
/**
* Whether rtcp-mux is in use.
*
* When enabled, the <tt>DtlsPacketTransformer</tt> will, instead of
* establishing a DTLS session, wait for the transformer for RTP to
* establish one, and reuse it to initialize its SRTP transformer.
*/
private boolean rtcpmux = false;
/**
* The value of the <tt>setup</tt> SDP attribute defined by RFC 4145
* "TCP-Based Media Transport in the Session Description Protocol
* (SDP)" which determines whether this instance acts as a DTLS client
* or a DTLS server.
*/
private DtlsControl.Setup setup;
/**
* Initializes a new <tt>DtlsTransformEngine</tt> instance.
*/
public DtlsTransformEngine(DtlsControlImpl dtlsControl)
{
this.dtlsControl = dtlsControl;
}
/**
* {@inheritDoc}
*/
@Override
public void cleanup()
{
disposed = true;
/*
* SrtpControl.start(MediaType) starts its associated TransformEngine.
* We will use that mediaType to signal the normal stop then as well
* i.e. we will call setMediaType(null) first.
*/
setMediaType(null);
for (int i = 0; i < packetTransformers.length; i++)
{
DtlsPacketTransformer packetTransformer = packetTransformers[i];
if (packetTransformer != null)
{
packetTransformer.close();
packetTransformers[i] = null;
}
}
setConnector(null);
}
/**
* Initializes a new <tt>DtlsPacketTransformer</tt> instance which is to
* work on control/RTCP or data/RTP packets.
*
* @param componentID the ID of the component for which the new instance is
* to work
* @return a new <tt>DtlsPacketTransformer</tt> instance which is to work on
* control/RTCP or data/RTP packets (in accord with <tt>data</tt>)
*/
private DtlsPacketTransformer createPacketTransformer(int componentID)
{
DtlsPacketTransformer packetTransformer
= new DtlsPacketTransformer(this, componentID);
packetTransformer.setConnector(connector);
packetTransformer.setSetup(setup);
packetTransformer.setRtcpmux(rtcpmux);
packetTransformer.setMediaType(mediaType);
return packetTransformer;
}
/**
* Gets the <tt>DtlsControl</tt> which has initialized this instance.
*
* @return the <tt>DtlsControl</tt> which has initialized this instance
*/
DtlsControlImpl getDtlsControl()
{
return dtlsControl;
}
/**
* Gets the <tt>PacketTransformer</tt> of this <tt>TransformEngine</tt>
* which is to work or works for the component with a specific ID.
*
* @param componentID the ID of the component for which the returned
* <tt>PacketTransformer</tt> is to work or works
* @return the <tt>PacketTransformer</tt>, if any, which is to work or works
* for the component with the specified <tt>componentID</tt>
*/
private DtlsPacketTransformer getPacketTransformer(int componentID)
{
int index = componentID - 1;
DtlsPacketTransformer packetTransformer = packetTransformers[index];
if ((packetTransformer == null) && !disposed)
{
packetTransformer = createPacketTransformer(componentID);
if (packetTransformer != null)
packetTransformers[index] = packetTransformer;
}
return packetTransformer;
}
/**
* {@inheritDoc}
*/
public PacketTransformer getRTCPTransformer()
{
return getPacketTransformer(Component.RTCP);
}
/**
* {@inheritDoc}
*/
public PacketTransformer getRTPTransformer()
{
return getPacketTransformer(Component.RTP);
}
/**
* Indicates if SRTP extensions should be disabled which means we are
* currently working in pure DTLS mode.
* @return <tt>true</tt> if SRTP extensions should be disabled.
*/
boolean isSrtpDisabled()
{
return dtlsControl.isSrtpDisabled();
}
/**
* Sets the <tt>RTPConnector</tt> which is to use or uses this
* <tt>TransformEngine</tt>.
*
* @param connector the <tt>RTPConnector</tt> which is to use or uses this
* <tt>TransformEngine</tt>
*/
void setConnector(AbstractRTPConnector connector)
{
if (this.connector != connector)
{
this.connector = connector;
for (DtlsPacketTransformer packetTransformer : packetTransformers)
{
if (packetTransformer != null)
packetTransformer.setConnector(this.connector);
}
}
}
/**
* Sets the <tt>MediaType</tt> of the stream which this instance is to work
* for/be associated with.
*
* @param mediaType the <tt>MediaType</tt> of the stream which this instance
* is to work for/be associated with
*/
private void setMediaType(MediaType mediaType)
{
if (this.mediaType != mediaType)
{
this.mediaType = mediaType;
for (DtlsPacketTransformer packetTransformer : packetTransformers)
{
if (packetTransformer != null)
packetTransformer.setMediaType(this.mediaType);
}
}
}
/**
* Enables/disables rtcp-mux.
* @param rtcpmux whether to enable or disable.
*/
void setRtcpmux(boolean rtcpmux)
{
if (this.rtcpmux != rtcpmux)
{
this.rtcpmux = rtcpmux;
for (DtlsPacketTransformer packetTransformer : packetTransformers)
{
if (packetTransformer != null)
packetTransformer.setRtcpmux(rtcpmux);
}
}
}
/**
* Sets the DTLS protocol according to which this
* <tt>DtlsTransformEngine</tt> is to act either as a DTLS server or a DTLS
* client.
*
* @param setup the value of the <tt>setup</tt> SDP attribute to set on this
* instance in order to determine whether this instance is to act as a DTLS
* client or a DTLS server
*/
void setSetup(DtlsControl.Setup setup)
{
if (this.setup != setup)
{
this.setup = setup;
for (DtlsPacketTransformer packetTransformer : packetTransformers)
{
if (packetTransformer != null)
packetTransformer.setSetup(this.setup);
}
}
}
/**
* Starts this instance in the sense that it becomes fully operational.
*
* @param mediaType the <tt>MediaType</tt> of the stream which this instance
* is to work for/be associated with
*/
void start(MediaType mediaType)
{
setMediaType(mediaType);
}
}
| 30.431034 | 80 | 0.627989 |
882cf0490c25b67fb521b93638c73ce53e58bf85 | 2,706 |
//
// This file is auto-generated. Please don't modify it!
//
package org.opencv.features2d;
import org.opencv.core.Mat;
import org.opencv.core.MatOfFloat;
import org.opencv.core.MatOfInt;
// C++: class BRISK
//javadoc: BRISK
public class BRISK extends Feature2D {
protected BRISK(long addr) {
super(addr);
}
//
// C++: static Ptr_BRISK create(int thresh = 30, int octaves = 3, float patternScale = 1.0f)
//
//javadoc: BRISK::create(thresh, octaves, patternScale)
public static BRISK create(int thresh, int octaves, float patternScale) {
BRISK retVal = new BRISK(create_0(thresh, octaves, patternScale));
return retVal;
}
//javadoc: BRISK::create()
public static BRISK create() {
BRISK retVal = new BRISK(create_1());
return retVal;
}
//
// C++: static Ptr_BRISK create(vector_float radiusList, vector_int numberList, float dMax = 5.85f, float dMin = 8.2f, vector_int indexChange = std::vector<int>())
//
//javadoc: BRISK::create(radiusList, numberList, dMax, dMin, indexChange)
public static BRISK create(MatOfFloat radiusList, MatOfInt numberList, float dMax, float dMin, MatOfInt indexChange) {
Mat radiusList_mat = radiusList;
Mat numberList_mat = numberList;
Mat indexChange_mat = indexChange;
BRISK retVal = new BRISK(create_2(radiusList_mat.nativeObj, numberList_mat.nativeObj, dMax, dMin, indexChange_mat.nativeObj));
return retVal;
}
//javadoc: BRISK::create(radiusList, numberList)
public static BRISK create(MatOfFloat radiusList, MatOfInt numberList) {
Mat radiusList_mat = radiusList;
Mat numberList_mat = numberList;
BRISK retVal = new BRISK(create_3(radiusList_mat.nativeObj, numberList_mat.nativeObj));
return retVal;
}
@Override
protected void finalize() throws Throwable {
delete(nativeObj);
}
// C++: static Ptr_BRISK create(int thresh = 30, int octaves = 3, float patternScale = 1.0f)
private static native long create_0(int thresh, int octaves, float patternScale);
private static native long create_1();
// C++: static Ptr_BRISK create(vector_float radiusList, vector_int numberList, float dMax = 5.85f, float dMin = 8.2f, vector_int indexChange = std::vector<int>())
private static native long create_2(long radiusList_mat_nativeObj, long numberList_mat_nativeObj, float dMax, float dMin, long indexChange_mat_nativeObj);
private static native long create_3(long radiusList_mat_nativeObj, long numberList_mat_nativeObj);
// native support for java finalize()
private static native void delete(long nativeObj);
}
| 31.835294 | 167 | 0.698448 |
0bae85b90a5066a20f32ab811e66ecf00ddeaacd | 162 | package de.embl.cba.mobie.transform;
public abstract class AbstractSourceTransformer implements SourceTransformer
{
// Serialisation
protected String name;
}
| 18 | 76 | 0.820988 |
f6ff1844871db08f87cd931be67756078d6b1328 | 489 | package integration.connection;
import com.myproject.test.queries.jooq.util.Config;
import com.myproject.test.queries.jooq.util.ConnectionDb;
import org.junit.Assert;
import org.junit.Test;
import java.sql.Connection;
import java.sql.SQLException;
public class ConnectionDbTest {
@Test
public void checkConnection() throws SQLException {
Connection connection = ConnectionDb.getConnection(new Config());
Assert.assertFalse(connection.isClosed());
}
}
| 19.56 | 73 | 0.754601 |
79a559dc20bffbde0fed019edec9136caced0247 | 8,324 | package cord.common;
import java.util.Arrays;
import java.util.List;
import cord.roles.*;
public class AllRoles {
public Administrator Administrator;
public Consultant Consultant;
public ConsultantManager ConsultantManager;
public Controller Controller;
public FieldOperationsDirector FieldOperationsDirector;
public FinancialAnalystGlobal FinancialAnalystGlobal;
public FinancialAnalystOnProject FinancialAnalystOnProject;
public Fundraising Fundraising;
public Intern Intern;
public Leadership Leadership;
public Liason Liason;
public Marketing Marketing;
public ProjectManagerGlobal ProjectManagerGlobal;
public ProjectManagerOnProject ProjectManagerOnProject;
public RegionalCommunicationCoordinator RegionalCommunicationCoordinator;
public RegionalDirectorGlobal RegionalDirectorGlobal;
public RegionalDirectorOnProject RegionalDirectorOnProject;
public StaffMember StaffMember;
public Translator Translator;
public AllRoles(){
this.Administrator = new Administrator();
this.Consultant = new Consultant();
this.ConsultantManager = new ConsultantManager();
this.Controller = new Controller();
this.FieldOperationsDirector = new FieldOperationsDirector();
this.FinancialAnalystGlobal = new FinancialAnalystGlobal();
this.FinancialAnalystOnProject = new FinancialAnalystOnProject();
this.Fundraising = new Fundraising();
this.Intern = new Intern();
this.Leadership = new Leadership();
this.Liason = new Liason();
this.Marketing = new Marketing();
this.ProjectManagerGlobal = new ProjectManagerGlobal();
this.ProjectManagerOnProject = new ProjectManagerOnProject();
this.RegionalCommunicationCoordinator = new RegionalCommunicationCoordinator();
this.RegionalDirectorGlobal = new RegionalDirectorGlobal();
this.RegionalDirectorOnProject = new RegionalDirectorOnProject();
this.StaffMember = new StaffMember();
this.Translator = new Translator();
}
public BaseRole getRoleByStringName(String name){
switch (name){
case "AdministratorRole": return this.Administrator;
case "ConsultantRole": return this.Consultant;
case "ConsultantManagerRole": return this.ConsultantManager;
case "ControllerRole": return this.Controller;
case "FieldOperationsDirectorRole": return this.FieldOperationsDirector;
case "FinancialAnalystOnProjectRole": return this.FinancialAnalystOnProject;
case "FinancialAnalystGlobalRole": return this.FinancialAnalystGlobal;
case "FundraisingRole": return this.Fundraising;
case "InternRole": return this.Intern;
case "LeadershipRole": return this.Leadership;
case "LiasonRole": return this.Liason;
case "MarketingRole": return this.Marketing;
case "ProjectManagerOnProjectRole": return this.ProjectManagerOnProject;
case "ProjectManagerGlobalRole": return this.ProjectManagerGlobal;
case "RegionalCommunicationCoordinatorRole": return this.RegionalCommunicationCoordinator;
case "RegionalDirectorOnProjectRole": return this.RegionalDirectorOnProject;
case "RegionalDirectorGlobalRole": return this.RegionalDirectorGlobal;
case "StaffMemberRole": return this.StaffMember;
case "TranslatorRole": return this.Translator;
default: return null;
}
}
public List<BaseRole> allRolesList(){
return Arrays.asList(
this.Administrator,
this.Consultant,
this.ConsultantManager,
this.Controller,
this.FieldOperationsDirector,
this.FinancialAnalystGlobal,
this.FinancialAnalystOnProject,
this.Fundraising,
this.Intern,
this.Leadership,
this.Liason,
this.Marketing,
this.ProjectManagerGlobal,
this.ProjectManagerOnProject,
this.RegionalCommunicationCoordinator,
this.RegionalDirectorGlobal,
this.RegionalDirectorOnProject,
this.StaffMember,
this.Translator
);
}
public List<BaseRole> globalRolesList(){
return Arrays.asList(
this.Administrator,
this.ConsultantManager,
this.Controller,
this.FieldOperationsDirector,
this.FinancialAnalystGlobal,
this.Fundraising,
this.Leadership,
this.Marketing,
this.ProjectManagerGlobal,
this.RegionalDirectorGlobal,
this.RegionalDirectorOnProject,
this.StaffMember
);
}
public List<BaseRole> projectRolesList(){
return Arrays.asList(
this.Consultant,
this.FinancialAnalystOnProject,
this.Intern,
this.Liason,
this.ProjectManagerOnProject,
this.RegionalCommunicationCoordinator,
this.RegionalDirectorOnProject,
this.Translator
);
}
public static String getFrontendRoleNameFromApiRoleName(RoleNames role){
switch (role){
case AdministratorRole:
case ConsultantManagerRole:
case ConsultantRole:
case ControllerRole:
case FieldOperationsDirectorRole:
case FundraisingRole:
case InternRole:
case LeadershipRole:
case LiasonRole:
case MarketingRole:
case MentorRole:
case RegionalCommunicationCoordinatorRole:
case StaffMemberRole:
case TranslatorRole:
return role.name().replace("Role", "");
case ProjectManagerGlobalRole:
case RegionalDirectorGlobalRole:
case FinancialAnalystGlobalRole:
return role.name().replace("GlobalRole", "");
case ProjectManagerOnProjectRole:
case RegionalDirectorOnProjectRole:
case FinancialAnalystOnProjectRole:
return role.name().replace("OnProjectRole", "");
default:
System.out.println("frontend role name not found");
return null;
}
}
public static RoleNames getRoleNameEnumFromFeString(String roleName, Boolean isMember){
switch (roleName){
case "Administrator": return RoleNames.AdministratorRole;
case "Consultant": return RoleNames.ConsultantRole;
case "ConsultantManager": return RoleNames.ConsultantManagerRole;
case "Controller": return RoleNames.ControllerRole;
case "FieldOperationsDirector": return RoleNames.FieldOperationsDirectorRole;
case "FinancialAnalyst": if (isMember) return RoleNames.FinancialAnalystOnProjectRole;
return RoleNames.FinancialAnalystGlobalRole;
case "Fundraising": return RoleNames.FundraisingRole;
case "Intern": return RoleNames.InternRole;
case "Leadership": return RoleNames.LeadershipRole;
case "Liason": return RoleNames.LiasonRole;
case "Marketing": return RoleNames.MarketingRole;
case "ProjectManager": if (isMember) return RoleNames.ProjectManagerOnProjectRole;
return RoleNames.ProjectManagerGlobalRole;
case "RegionalCommunicationCoordinator": return RoleNames.RegionalCommunicationCoordinatorRole;
case "RegionalDirector": if (isMember) return RoleNames.RegionalDirectorOnProjectRole;
return RoleNames.RegionalDirectorGlobalRole;
case "StaffMember": return RoleNames.StaffMemberRole;
case "Translator": return RoleNames.TranslatorRole;
}
return null;
}
}
| 43.810526 | 124 | 0.636953 |
891752bdb8eedc9686cf7f2a4d31ac95f53da1a8 | 5,318 | /*
* This file is part of ELKI:
* Environment for Developing KDD-Applications Supported by Index-Structures
*
* Copyright (C) 2019
* ELKI Development Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.lmu.ifi.dbs.elki.gui.configurator;
import java.awt.GridBagLayout;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JPanel;
import javax.swing.border.SoftBevelBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.EventListenerList;
import de.lmu.ifi.dbs.elki.logging.LoggingUtil;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameterization.ListParameterization;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameterization.TrackParameters;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.ClassListParameter;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.ClassParameter;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.EnumParameter;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.FileParameter;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.Flag;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.Parameter;
/**
* A panel that contains configurators for parameters.
*
* @author Erich Schubert
* @since 0.4.0
*
* @opt nodefillcolor LemonChiffon
* @has - - - de.lmu.ifi.dbs.elki.gui.configurator.ParameterConfigurator
*/
public class ConfiguratorPanel extends JPanel implements ChangeListener {
/**
* Serial version
*/
private static final long serialVersionUID = 1L;
/**
* Keep a map of parameter
*/
private Map<Object, ParameterConfigurator> childconfig = new HashMap<>();
/**
* Child options
*/
private ArrayList<ParameterConfigurator> children = new ArrayList<>();
/**
* The event listeners for this panel.
*/
protected EventListenerList listenerList = new EventListenerList();
/**
* Constructor.
*/
public ConfiguratorPanel() {
super(new GridBagLayout());
}
/**
* Add parameter to this panel.
*
* @param param Parameter to add
* @param track Parameter tracking object
*/
public void addParameter(Object owner, Parameter<?> param, TrackParameters track) {
this.setBorder(new SoftBevelBorder(SoftBevelBorder.LOWERED));
ParameterConfigurator cfg = null;
{ // Find
Object cur = owner;
while(cur != null) {
cfg = childconfig.get(cur);
if(cfg != null) {
break;
}
cur = track.getParent(cur);
}
}
if(cfg != null) {
cfg.addParameter(owner, param, track);
return;
}
else {
cfg = makeConfigurator(param);
cfg.addChangeListener(this);
children.add(cfg);
}
}
private ParameterConfigurator makeConfigurator(Parameter<?> param) {
if(param instanceof Flag) {
return new FlagParameterConfigurator((Flag) param, this);
}
if(param instanceof ClassListParameter) {
ParameterConfigurator cfg = new ClassListParameterConfigurator((ClassListParameter<?>) param, this);
childconfig.put(param, cfg);
return cfg;
}
if(param instanceof ClassParameter) {
ParameterConfigurator cfg = new ClassParameterConfigurator((ClassParameter<?>) param, this);
childconfig.put(param, cfg);
return cfg;
}
if(param instanceof FileParameter) {
return new FileParameterConfigurator((FileParameter) param, this);
}
if(param instanceof EnumParameter) {
return new EnumParameterConfigurator((EnumParameter<?>) param, this);
}
return new TextParameterConfigurator(param, this);
}
@Override
public void stateChanged(ChangeEvent e) {
if(e.getSource() instanceof ParameterConfigurator) {
// TODO: check that e is in children?
fireValueChanged();
}
else {
LoggingUtil.warning("stateChanged triggered by unknown source: " + e.getSource());
}
}
public void addChangeListener(ChangeListener listener) {
listenerList.add(ChangeListener.class, listener);
}
public void removeChangeListener(ChangeListener listener) {
listenerList.remove(ChangeListener.class, listener);
}
protected void fireValueChanged() {
ChangeEvent evt = new ChangeEvent(this);
for(ChangeListener listener : listenerList.getListeners(ChangeListener.class)) {
listener.stateChanged(evt);
}
}
public void appendParameters(ListParameterization params) {
for(ParameterConfigurator cfg : children) {
cfg.appendParameters(params);
}
}
public void clear() {
removeAll();
childconfig.clear();
children.clear();
}
} | 31.099415 | 106 | 0.716435 |
712576f304d9552ff3b0ef949f93f28d2c9e6a1f | 35,812 | /*
* Copyright (C) 2011 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 android.net;
import static android.system.OsConstants.AF_INET;
import static android.system.OsConstants.AF_INET6;
import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
import android.app.Activity;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.IPackageManager;
import android.content.pm.PackageManager;
import android.os.Binder;
import android.os.IBinder;
import android.os.Parcel;
import android.os.ParcelFileDescriptor;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.os.UserHandle;
import com.android.internal.net.VpnConfig;
import java.net.DatagramSocket;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
/**
* VpnService is a base class for applications to extend and build their
* own VPN solutions. In general, it creates a virtual network interface,
* configures addresses and routing rules, and returns a file descriptor
* to the application. Each read from the descriptor retrieves an outgoing
* packet which was routed to the interface. Each write to the descriptor
* injects an incoming packet just like it was received from the interface.
* The interface is running on Internet Protocol (IP), so packets are
* always started with IP headers. The application then completes a VPN
* connection by processing and exchanging packets with the remote server
* over a tunnel.
*
* <p>Letting applications intercept packets raises huge security concerns.
* A VPN application can easily break the network. Besides, two of them may
* conflict with each other. The system takes several actions to address
* these issues. Here are some key points:
* <ul>
* <li>User action is required the first time an application creates a VPN
* connection.</li>
* <li>There can be only one VPN connection running at the same time. The
* existing interface is deactivated when a new one is created.</li>
* <li>A system-managed notification is shown during the lifetime of a
* VPN connection.</li>
* <li>A system-managed dialog gives the information of the current VPN
* connection. It also provides a button to disconnect.</li>
* <li>The network is restored automatically when the file descriptor is
* closed. It also covers the cases when a VPN application is crashed
* or killed by the system.</li>
* </ul>
*
* <p>There are two primary methods in this class: {@link #prepare} and
* {@link Builder#establish}. The former deals with user action and stops
* the VPN connection created by another application. The latter creates
* a VPN interface using the parameters supplied to the {@link Builder}.
* An application must call {@link #prepare} to grant the right to use
* other methods in this class, and the right can be revoked at any time.
* Here are the general steps to create a VPN connection:
* <ol>
* <li>When the user presses the button to connect, call {@link #prepare}
* and launch the returned intent, if non-null.</li>
* <li>When the application becomes prepared, start the service.</li>
* <li>Create a tunnel to the remote server and negotiate the network
* parameters for the VPN connection.</li>
* <li>Supply those parameters to a {@link Builder} and create a VPN
* interface by calling {@link Builder#establish}.</li>
* <li>Process and exchange packets between the tunnel and the returned
* file descriptor.</li>
* <li>When {@link #onRevoke} is invoked, close the file descriptor and
* shut down the tunnel gracefully.</li>
* </ol>
*
* <p>Services extending this class need to be declared with an appropriate
* permission and intent filter. Their access must be secured by
* {@link android.Manifest.permission#BIND_VPN_SERVICE} permission, and
* their intent filter must match {@link #SERVICE_INTERFACE} action. Here
* is an example of declaring a VPN service in {@code AndroidManifest.xml}:
* <pre>
* <service android:name=".ExampleVpnService"
* android:permission="android.permission.BIND_VPN_SERVICE">
* <intent-filter>
* <action android:name="android.net.VpnService"/>
* </intent-filter>
* </service></pre>
*
* <p> The Android system starts a VPN in the background by calling
* {@link android.content.Context#startService startService()}. In Android 8.0
* (API level 26) and higher, the system places VPN apps on the temporary
* whitelist for a short period so the app can start in the background. The VPN
* app must promote itself to the foreground after it's launched or the system
* will shut down the app.
*
* @see Builder
*/
public class VpnService extends Service {
/**
* The action must be matched by the intent filter of this service. It also
* needs to require {@link android.Manifest.permission#BIND_VPN_SERVICE}
* permission so that other applications cannot abuse it.
*/
public static final String SERVICE_INTERFACE = VpnConfig.SERVICE_INTERFACE;
/**
* Key for boolean meta-data field indicating whether this VpnService supports always-on mode.
*
* <p>For a VPN app targeting {@link android.os.Build.VERSION_CODES#N API 24} or above, Android
* provides users with the ability to set it as always-on, so that VPN connection is
* persisted after device reboot and app upgrade. Always-on VPN can also be enabled by device
* owner and profile owner apps through
* {@link android.app.admin.DevicePolicyManager#setAlwaysOnVpnPackage}.
*
* <p>VPN apps not supporting this feature should opt out by adding this meta-data field to the
* {@code VpnService} component of {@code AndroidManifest.xml}. In case there is more than one
* {@code VpnService} component defined in {@code AndroidManifest.xml}, opting out any one of
* them will opt out the entire app. For example,
* <pre> {@code
* <service android:name=".ExampleVpnService"
* android:permission="android.permission.BIND_VPN_SERVICE">
* <intent-filter>
* <action android:name="android.net.VpnService"/>
* </intent-filter>
* <meta-data android:name="android.net.VpnService.SUPPORTS_ALWAYS_ON"
* android:value=false/>
* </service>
* } </pre>
*
* <p>This meta-data field defaults to {@code true} if absent. It will only have effect on
* {@link android.os.Build.VERSION_CODES#O_MR1} or higher.
*/
public static final String SERVICE_META_DATA_SUPPORTS_ALWAYS_ON =
"android.net.VpnService.SUPPORTS_ALWAYS_ON";
/**
* Use IConnectivityManager since those methods are hidden and not
* available in ConnectivityManager.
*/
private static IConnectivityManager getService() {
return IConnectivityManager.Stub.asInterface(
ServiceManager.getService(Context.CONNECTIVITY_SERVICE));
}
/**
* Prepare to establish a VPN connection. This method returns {@code null}
* if the VPN application is already prepared or if the user has previously
* consented to the VPN application. Otherwise, it returns an
* {@link Intent} to a system activity. The application should launch the
* activity using {@link Activity#startActivityForResult} to get itself
* prepared. The activity may pop up a dialog to require user action, and
* the result will come back via its {@link Activity#onActivityResult}.
* If the result is {@link Activity#RESULT_OK}, the application becomes
* prepared and is granted to use other methods in this class.
*
* <p>Only one application can be granted at the same time. The right
* is revoked when another application is granted. The application
* losing the right will be notified via its {@link #onRevoke}. Unless
* it becomes prepared again, subsequent calls to other methods in this
* class will fail.
*
* <p>The user may disable the VPN at any time while it is activated, in
* which case this method will return an intent the next time it is
* executed to obtain the user's consent again.
*
* @see #onRevoke
*/
public static Intent prepare(Context context) {
try {
if (getService().prepareVpn(context.getPackageName(), null, context.getUserId())) {
return null;
}
} catch (RemoteException e) {
// ignore
}
return VpnConfig.getIntentForConfirmation();
}
/**
* Version of {@link #prepare(Context)} which does not require user consent.
*
* <p>Requires {@link android.Manifest.permission#CONTROL_VPN} and should generally not be
* used. Only acceptable in situations where user consent has been obtained through other means.
*
* <p>Once this is run, future preparations may be done with the standard prepare method as this
* will authorize the package to prepare the VPN without consent in the future.
*
* @hide
*/
@SystemApi
@RequiresPermission(android.Manifest.permission.CONTROL_VPN)
public static void prepareAndAuthorize(Context context) {
IConnectivityManager cm = getService();
String packageName = context.getPackageName();
try {
// Only prepare if we're not already prepared.
int userId = context.getUserId();
if (!cm.prepareVpn(packageName, null, userId)) {
cm.prepareVpn(null, packageName, userId);
}
cm.setVpnPackageAuthorization(packageName, userId, true);
} catch (RemoteException e) {
// ignore
}
}
/**
* Protect a socket from VPN connections. After protecting, data sent
* through this socket will go directly to the underlying network,
* so its traffic will not be forwarded through the VPN.
* This method is useful if some connections need to be kept
* outside of VPN. For example, a VPN tunnel should protect itself if its
* destination is covered by VPN routes. Otherwise its outgoing packets
* will be sent back to the VPN interface and cause an infinite loop. This
* method will fail if the application is not prepared or is revoked.
*
* <p class="note">The socket is NOT closed by this method.
*
* @return {@code true} on success.
*/
public boolean protect(int socket) {
return NetworkUtils.protectFromVpn(socket);
}
/**
* Convenience method to protect a {@link Socket} from VPN connections.
*
* @return {@code true} on success.
* @see #protect(int)
*/
public boolean protect(Socket socket) {
return protect(socket.getFileDescriptor$().getInt$());
}
/**
* Convenience method to protect a {@link DatagramSocket} from VPN
* connections.
*
* @return {@code true} on success.
* @see #protect(int)
*/
public boolean protect(DatagramSocket socket) {
return protect(socket.getFileDescriptor$().getInt$());
}
/**
* Adds a network address to the VPN interface.
*
* Both IPv4 and IPv6 addresses are supported. The VPN must already be established. Fails if the
* address is already in use or cannot be assigned to the interface for any other reason.
*
* Adding an address implicitly allows traffic from that address family (i.e., IPv4 or IPv6) to
* be routed over the VPN. @see Builder#allowFamily
*
* @throws IllegalArgumentException if the address is invalid.
*
* @param address The IP address (IPv4 or IPv6) to assign to the VPN interface.
* @param prefixLength The prefix length of the address.
*
* @return {@code true} on success.
* @see Builder#addAddress
*
* @hide
*/
public boolean addAddress(InetAddress address, int prefixLength) {
check(address, prefixLength);
try {
return getService().addVpnAddress(address.getHostAddress(), prefixLength);
} catch (RemoteException e) {
throw new IllegalStateException(e);
}
}
/**
* Removes a network address from the VPN interface.
*
* Both IPv4 and IPv6 addresses are supported. The VPN must already be established. Fails if the
* address is not assigned to the VPN interface, or if it is the only address assigned (thus
* cannot be removed), or if the address cannot be removed for any other reason.
*
* After removing an address, if there are no addresses, routes or DNS servers of a particular
* address family (i.e., IPv4 or IPv6) configured on the VPN, that <b>DOES NOT</b> block that
* family from being routed. In other words, once an address family has been allowed, it stays
* allowed for the rest of the VPN's session. @see Builder#allowFamily
*
* @throws IllegalArgumentException if the address is invalid.
*
* @param address The IP address (IPv4 or IPv6) to assign to the VPN interface.
* @param prefixLength The prefix length of the address.
*
* @return {@code true} on success.
*
* @hide
*/
public boolean removeAddress(InetAddress address, int prefixLength) {
check(address, prefixLength);
try {
return getService().removeVpnAddress(address.getHostAddress(), prefixLength);
} catch (RemoteException e) {
throw new IllegalStateException(e);
}
}
/**
* Sets the underlying networks used by the VPN for its upstream connections.
*
* <p>Used by the system to know the actual networks that carry traffic for apps affected by
* this VPN in order to present this information to the user (e.g., via status bar icons).
*
* <p>This method only needs to be called if the VPN has explicitly bound its underlying
* communications channels — such as the socket(s) passed to {@link #protect(int)} —
* to a {@code Network} using APIs such as {@link Network#bindSocket(Socket)} or
* {@link Network#bindSocket(DatagramSocket)}. The VPN should call this method every time
* the set of {@code Network}s it is using changes.
*
* <p>{@code networks} is one of the following:
* <ul>
* <li><strong>a non-empty array</strong>: an array of one or more {@link Network}s, in
* decreasing preference order. For example, if this VPN uses both wifi and mobile (cellular)
* networks to carry app traffic, but prefers or uses wifi more than mobile, wifi should appear
* first in the array.</li>
* <li><strong>an empty array</strong>: a zero-element array, meaning that the VPN has no
* underlying network connection, and thus, app traffic will not be sent or received.</li>
* <li><strong>null</strong>: (default) signifies that the VPN uses whatever is the system's
* default network. I.e., it doesn't use the {@code bindSocket} or {@code bindDatagramSocket}
* APIs mentioned above to send traffic over specific channels.</li>
* </ul>
*
* <p>This call will succeed only if the VPN is currently established. For setting this value
* when the VPN has not yet been established, see {@link Builder#setUnderlyingNetworks}.
*
* @param networks An array of networks the VPN uses to tunnel traffic to/from its servers.
*
* @return {@code true} on success.
*/
public boolean setUnderlyingNetworks(Network[] networks) {
try {
return getService().setUnderlyingNetworksForVpn(networks);
} catch (RemoteException e) {
throw new IllegalStateException(e);
}
}
/**
* Return the communication interface to the service. This method returns
* {@code null} on {@link Intent}s other than {@link #SERVICE_INTERFACE}
* action. Applications overriding this method must identify the intent
* and return the corresponding interface accordingly.
*
* @see Service#onBind
*/
@Override
public IBinder onBind(Intent intent) {
if (intent != null && SERVICE_INTERFACE.equals(intent.getAction())) {
return new Callback();
}
return null;
}
/**
* Invoked when the application is revoked. At this moment, the VPN
* interface is already deactivated by the system. The application should
* close the file descriptor and shut down gracefully. The default
* implementation of this method is calling {@link Service#stopSelf()}.
*
* <p class="note">Calls to this method may not happen on the main thread
* of the process.
*
* @see #prepare
*/
public void onRevoke() {
stopSelf();
}
/**
* Use raw Binder instead of AIDL since now there is only one usage.
*/
private class Callback extends Binder {
@Override
protected boolean onTransact(int code, Parcel data, Parcel reply, int flags) {
if (code == IBinder.LAST_CALL_TRANSACTION) {
onRevoke();
return true;
}
return false;
}
}
/**
* Private method to validate address and prefixLength.
*/
private static void check(InetAddress address, int prefixLength) {
if (address.isLoopbackAddress()) {
throw new IllegalArgumentException("Bad address");
}
if (address instanceof Inet4Address) {
if (prefixLength < 0 || prefixLength > 32) {
throw new IllegalArgumentException("Bad prefixLength");
}
} else if (address instanceof Inet6Address) {
if (prefixLength < 0 || prefixLength > 128) {
throw new IllegalArgumentException("Bad prefixLength");
}
} else {
throw new IllegalArgumentException("Unsupported family");
}
}
/**
* Helper class to create a VPN interface. This class should be always
* used within the scope of the outer {@link VpnService}.
*
* @see VpnService
*/
public class Builder {
private final VpnConfig mConfig = new VpnConfig();
private final List<LinkAddress> mAddresses = new ArrayList<LinkAddress>();
private final List<RouteInfo> mRoutes = new ArrayList<RouteInfo>();
public Builder() {
mConfig.user = VpnService.this.getClass().getName();
}
/**
* Set the name of this session. It will be displayed in
* system-managed dialogs and notifications. This is recommended
* not required.
*/
public Builder setSession(String session) {
mConfig.session = session;
return this;
}
/**
* Set the {@link PendingIntent} to an activity for users to
* configure the VPN connection. If it is not set, the button
* to configure will not be shown in system-managed dialogs.
*/
public Builder setConfigureIntent(PendingIntent intent) {
mConfig.configureIntent = intent;
return this;
}
/**
* Set the maximum transmission unit (MTU) of the VPN interface. If
* it is not set, the default value in the operating system will be
* used.
*
* @throws IllegalArgumentException if the value is not positive.
*/
public Builder setMtu(int mtu) {
if (mtu <= 0) {
throw new IllegalArgumentException("Bad mtu");
}
mConfig.mtu = mtu;
return this;
}
/**
* Add a network address to the VPN interface. Both IPv4 and IPv6
* addresses are supported. At least one address must be set before
* calling {@link #establish}.
*
* Adding an address implicitly allows traffic from that address family
* (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
*
* @throws IllegalArgumentException if the address is invalid.
*/
public Builder addAddress(InetAddress address, int prefixLength) {
check(address, prefixLength);
if (address.isAnyLocalAddress()) {
throw new IllegalArgumentException("Bad address");
}
mAddresses.add(new LinkAddress(address, prefixLength));
mConfig.updateAllowedFamilies(address);
return this;
}
/**
* Convenience method to add a network address to the VPN interface
* using a numeric address string. See {@link InetAddress} for the
* definitions of numeric address formats.
*
* Adding an address implicitly allows traffic from that address family
* (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
*
* @throws IllegalArgumentException if the address is invalid.
* @see #addAddress(InetAddress, int)
*/
public Builder addAddress(String address, int prefixLength) {
return addAddress(InetAddress.parseNumericAddress(address), prefixLength);
}
/**
* Add a network route to the VPN interface. Both IPv4 and IPv6
* routes are supported.
*
* Adding a route implicitly allows traffic from that address family
* (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
*
* @throws IllegalArgumentException if the route is invalid.
*/
public Builder addRoute(InetAddress address, int prefixLength) {
check(address, prefixLength);
int offset = prefixLength / 8;
byte[] bytes = address.getAddress();
if (offset < bytes.length) {
for (bytes[offset] <<= prefixLength % 8; offset < bytes.length; ++offset) {
if (bytes[offset] != 0) {
throw new IllegalArgumentException("Bad address");
}
}
}
mRoutes.add(new RouteInfo(new IpPrefix(address, prefixLength), null));
mConfig.updateAllowedFamilies(address);
return this;
}
/**
* Convenience method to add a network route to the VPN interface
* using a numeric address string. See {@link InetAddress} for the
* definitions of numeric address formats.
*
* Adding a route implicitly allows traffic from that address family
* (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
*
* @throws IllegalArgumentException if the route is invalid.
* @see #addRoute(InetAddress, int)
*/
public Builder addRoute(String address, int prefixLength) {
return addRoute(InetAddress.parseNumericAddress(address), prefixLength);
}
/**
* Add a DNS server to the VPN connection. Both IPv4 and IPv6
* addresses are supported. If none is set, the DNS servers of
* the default network will be used.
*
* Adding a server implicitly allows traffic from that address family
* (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
*
* @throws IllegalArgumentException if the address is invalid.
*/
public Builder addDnsServer(InetAddress address) {
if (address.isLoopbackAddress() || address.isAnyLocalAddress()) {
throw new IllegalArgumentException("Bad address");
}
if (mConfig.dnsServers == null) {
mConfig.dnsServers = new ArrayList<String>();
}
mConfig.dnsServers.add(address.getHostAddress());
return this;
}
/**
* Convenience method to add a DNS server to the VPN connection
* using a numeric address string. See {@link InetAddress} for the
* definitions of numeric address formats.
*
* Adding a server implicitly allows traffic from that address family
* (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
*
* @throws IllegalArgumentException if the address is invalid.
* @see #addDnsServer(InetAddress)
*/
public Builder addDnsServer(String address) {
return addDnsServer(InetAddress.parseNumericAddress(address));
}
/**
* Add a search domain to the DNS resolver.
*/
public Builder addSearchDomain(String domain) {
if (mConfig.searchDomains == null) {
mConfig.searchDomains = new ArrayList<String>();
}
mConfig.searchDomains.add(domain);
return this;
}
/**
* Allows traffic from the specified address family.
*
* By default, if no address, route or DNS server of a specific family (IPv4 or IPv6) is
* added to this VPN, then all outgoing traffic of that family is blocked. If any address,
* route or DNS server is added, that family is allowed.
*
* This method allows an address family to be unblocked even without adding an address,
* route or DNS server of that family. Traffic of that family will then typically
* fall-through to the underlying network if it's supported.
*
* {@code family} must be either {@code AF_INET} (for IPv4) or {@code AF_INET6} (for IPv6).
* {@link IllegalArgumentException} is thrown if it's neither.
*
* @param family The address family ({@code AF_INET} or {@code AF_INET6}) to allow.
*
* @return this {@link Builder} object to facilitate chaining of method calls.
*/
public Builder allowFamily(int family) {
if (family == AF_INET) {
mConfig.allowIPv4 = true;
} else if (family == AF_INET6) {
mConfig.allowIPv6 = true;
} else {
throw new IllegalArgumentException(family + " is neither " + AF_INET + " nor " +
AF_INET6);
}
return this;
}
private void verifyApp(String packageName) throws PackageManager.NameNotFoundException {
IPackageManager pm = IPackageManager.Stub.asInterface(
ServiceManager.getService("package"));
try {
pm.getApplicationInfo(packageName, 0, UserHandle.getCallingUserId());
} catch (RemoteException e) {
throw new IllegalStateException(e);
}
}
/**
* Adds an application that's allowed to access the VPN connection.
*
* If this method is called at least once, only applications added through this method (and
* no others) are allowed access. Else (if this method is never called), all applications
* are allowed by default. If some applications are added, other, un-added applications
* will use networking as if the VPN wasn't running.
*
* A {@link Builder} may have only a set of allowed applications OR a set of disallowed
* ones, but not both. Calling this method after {@link #addDisallowedApplication} has
* already been called, or vice versa, will throw an {@link UnsupportedOperationException}.
*
* {@code packageName} must be the canonical name of a currently installed application.
* {@link PackageManager.NameNotFoundException} is thrown if there's no such application.
*
* @throws PackageManager.NameNotFoundException If the application isn't installed.
*
* @param packageName The full name (e.g.: "com.google.apps.contacts") of an application.
*
* @return this {@link Builder} object to facilitate chaining method calls.
*/
public Builder addAllowedApplication(String packageName)
throws PackageManager.NameNotFoundException {
if (mConfig.disallowedApplications != null) {
throw new UnsupportedOperationException("addDisallowedApplication already called");
}
verifyApp(packageName);
if (mConfig.allowedApplications == null) {
mConfig.allowedApplications = new ArrayList<String>();
}
mConfig.allowedApplications.add(packageName);
return this;
}
/**
* Adds an application that's denied access to the VPN connection.
*
* By default, all applications are allowed access, except for those denied through this
* method. Denied applications will use networking as if the VPN wasn't running.
*
* A {@link Builder} may have only a set of allowed applications OR a set of disallowed
* ones, but not both. Calling this method after {@link #addAllowedApplication} has already
* been called, or vice versa, will throw an {@link UnsupportedOperationException}.
*
* {@code packageName} must be the canonical name of a currently installed application.
* {@link PackageManager.NameNotFoundException} is thrown if there's no such application.
*
* @throws PackageManager.NameNotFoundException If the application isn't installed.
*
* @param packageName The full name (e.g.: "com.google.apps.contacts") of an application.
*
* @return this {@link Builder} object to facilitate chaining method calls.
*/
public Builder addDisallowedApplication(String packageName)
throws PackageManager.NameNotFoundException {
if (mConfig.allowedApplications != null) {
throw new UnsupportedOperationException("addAllowedApplication already called");
}
verifyApp(packageName);
if (mConfig.disallowedApplications == null) {
mConfig.disallowedApplications = new ArrayList<String>();
}
mConfig.disallowedApplications.add(packageName);
return this;
}
/**
* Allows all apps to bypass this VPN connection.
*
* By default, all traffic from apps is forwarded through the VPN interface and it is not
* possible for apps to side-step the VPN. If this method is called, apps may use methods
* such as {@link ConnectivityManager#bindProcessToNetwork} to instead send/receive
* directly over the underlying network or any other network they have permissions for.
*
* @return this {@link Builder} object to facilitate chaining of method calls.
*/
public Builder allowBypass() {
mConfig.allowBypass = true;
return this;
}
/**
* Sets the VPN interface's file descriptor to be in blocking/non-blocking mode.
*
* By default, the file descriptor returned by {@link #establish} is non-blocking.
*
* @param blocking True to put the descriptor into blocking mode; false for non-blocking.
*
* @return this {@link Builder} object to facilitate chaining method calls.
*/
public Builder setBlocking(boolean blocking) {
mConfig.blocking = blocking;
return this;
}
/**
* Sets the underlying networks used by the VPN for its upstream connections.
*
* @see VpnService#setUnderlyingNetworks
*
* @param networks An array of networks the VPN uses to tunnel traffic to/from its servers.
*
* @return this {@link Builder} object to facilitate chaining method calls.
*/
public Builder setUnderlyingNetworks(Network[] networks) {
mConfig.underlyingNetworks = networks != null ? networks.clone() : null;
return this;
}
/**
* Create a VPN interface using the parameters supplied to this
* builder. The interface works on IP packets, and a file descriptor
* is returned for the application to access them. Each read
* retrieves an outgoing packet which was routed to the interface.
* Each write injects an incoming packet just like it was received
* from the interface. The file descriptor is put into non-blocking
* mode by default to avoid blocking Java threads. To use the file
* descriptor completely in native space, see
* {@link ParcelFileDescriptor#detachFd()}. The application MUST
* close the file descriptor when the VPN connection is terminated.
* The VPN interface will be removed and the network will be
* restored by the system automatically.
*
* <p>To avoid conflicts, there can be only one active VPN interface
* at the same time. Usually network parameters are never changed
* during the lifetime of a VPN connection. It is also common for an
* application to create a new file descriptor after closing the
* previous one. However, it is rare but not impossible to have two
* interfaces while performing a seamless handover. In this case, the
* old interface will be deactivated when the new one is created
* successfully. Both file descriptors are valid but now outgoing
* packets will be routed to the new interface. Therefore, after
* draining the old file descriptor, the application MUST close it
* and start using the new file descriptor. If the new interface
* cannot be created, the existing interface and its file descriptor
* remain untouched.
*
* <p>An exception will be thrown if the interface cannot be created
* for any reason. However, this method returns {@code null} if the
* application is not prepared or is revoked. This helps solve
* possible race conditions between other VPN applications.
*
* @return {@link ParcelFileDescriptor} of the VPN interface, or
* {@code null} if the application is not prepared.
* @throws IllegalArgumentException if a parameter is not accepted
* by the operating system.
* @throws IllegalStateException if a parameter cannot be applied
* by the operating system.
* @throws SecurityException if the service is not properly declared
* in {@code AndroidManifest.xml}.
* @see VpnService
*/
public ParcelFileDescriptor establish() {
mConfig.addresses = mAddresses;
mConfig.routes = mRoutes;
try {
return getService().establishVpn(mConfig);
} catch (RemoteException e) {
throw new IllegalStateException(e);
}
}
}
}
| 44.0492 | 100 | 0.645091 |
53c9ec71585adf4c75c10de78e4b2af8c3824b2f | 102 | package com.charlyghislain.authenticator.api.domain;
public enum WsHealthStatus {
UP,
DOWN
}
| 14.571429 | 52 | 0.745098 |
7bda6810e40d2882b59447413c1245d9d2682d5b | 1,487 | package com.zapstitch.analyzer.base;
/**
* @author Neeraj Nayal
* [email protected]
*/
public class Constants {
public static final String SESSION_APPUSER = "appUser";
public static final String SESSION_REPORT = "myReport";
public static final String CALLBACK_URI = "http://localhost:8080/dashboard";
public static final String USER_INFO_URL = "https://www.googleapis.com/oauth2/v1/userinfo";
public static final String REVOKE_URL = "https://accounts.google.com/o/oauth2/revoke?token=";
public static final String JSON_CONTENT = "application/json";
public static final String PLAIN_CONTENT = "text/plain";
public static final String STATE_IDENTIFIER = "zapAnalyzer;";
public static final String USER_ITSELF = "me";
public static final String MAIL_FORMAT = "metadata";
public static final String MAIL_TO = "To";
public static final String MAIL_FROM = "From";
public static final String MAIL_CC = "Cc";
public static final String MAIL_BCC = "Bcc";
public static final String PARAM_CODE = "code";
public static final String PARAM_STATE = "state";
public static final String PARAM_BASE_DATE = "basedate";
public static final String JSON_NAME = "name";
public static final String JSON_EMAIL = "email";
public static final String VIEW_ERROR = "error.jsp";
public static final String VIEW_DASHBOARD = "dashboard.jsp";
public static final String VIEW_INDEX = "index.jsp";
public static final String VIEW_OUT = "logout.jsp";
}
| 24.377049 | 94 | 0.747814 |
018f1ae43c53757d3171badfd33c3d94d5e11bf6 | 1,051 | package com.aravind.tot.service;
import com.aravind.tot.domain.Kingdom;
import com.aravind.tot.domain.Message;
import com.aravind.tot.domain.World;
import java.util.List;
import java.util.stream.Collectors;
public class MessageTransformer {
public static List<Message> transform(List<String> rawMessages, Kingdom from, World southeros) {
List<Message> collect = rawMessages
.stream()
.map(message -> message.split(" ", 2))
.map(strings -> new Message(
strings[1].replaceAll("\\s", ""),
getRecipientKingdom(strings[0], southeros),
from, false))
.map(MessageDecipher::decipher)
.map(MessageValidator::validate)
.filter(Message::getAcknowledged)
.distinct()
.collect(Collectors.toList());
return collect;
}
private static Kingdom getRecipientKingdom(String name, World world) {
return world.getListOfKingdoms()
.stream()
.filter(kingdom -> kingdom.getName().equals(name))
.findFirst()
.get();
}
}
| 29.194444 | 98 | 0.65176 |
de99088c2783951fd9f4cf955da088b0db4359b8 | 3,038 | package com.marklogic.hub.dataservices.ingestion;
import com.fasterxml.jackson.databind.JsonNode;
import com.marklogic.client.DatabaseClient;
import com.marklogic.client.dataservices.InputEndpoint;
import com.marklogic.client.document.JSONDocumentManager;
import com.marklogic.client.io.JacksonHandle;
import com.marklogic.client.io.StringHandle;
import com.marklogic.hub.AbstractHubCoreTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.BeforeEach;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.stream.Stream;
import static org.junit.Assert.*;
public class BulkIngestTest extends AbstractHubCoreTest {
DatabaseClient db;
@BeforeEach
public void setupTest() {
db = adminHubConfig.newStagingClient(null);
}
@Test
public void testBulkIngest() {
String prefix = "/bulkIngestTest";
String endpointState = "{\"next\":" + 0 + ", \"prefix\":\""+prefix+"\"}";
String workUnit = "{\"taskId\":"+1+"}";
runAsDataHubOperator();
InputEndpoint loadEndpt = InputEndpoint.on(adminHubConfig.newStagingClient(null),
adminHubConfig.newModulesDbClient().newTextDocumentManager().read("/data-hub/5/data-services/ingestion/bulkIngester.api", new StringHandle()));
InputEndpoint.BulkInputCaller loader = loadEndpt.bulkCaller();
loader.setEndpointState(new ByteArrayInputStream(endpointState.getBytes()));
loader.setWorkUnit(new ByteArrayInputStream(workUnit.getBytes()));
Stream<InputStream> input = Stream.of(
asInputStream("{\"docNum\":1, \"docName\":\"doc1\"}"),
asInputStream("{\"docNum\":2, \"docName\":\"doc2\"}"),
asInputStream("{\"docNum\":3, \"docName\":\"doc3\"}")
);
input.forEach(loader::accept);
loader.awaitCompletion();
checkResults("/bulkIngestTest/1/1.json");
checkResults("/bulkIngestTest/1/2.json");
checkResults("/bulkIngestTest/1/3.json");
}
public static InputStream asInputStream(String value) {
return new ByteArrayInputStream(value.getBytes());
}
void checkResults(String uri) {
JSONDocumentManager jd = db.newJSONDocumentManager();
JsonNode doc = jd.read(uri, new JacksonHandle()).get();
assertNotNull("Could not find file ",uri);
assertNotNull("document "+uri+" is null ",doc);
verifyDocumentContents(doc);
}
void verifyDocumentContents(JsonNode doc) {
String user = "test-data-hub-operator";
if (!isVersionCompatibleWith520Roles()) {
user = "flow-operator";
}
assertNotNull("Could not find createdOn DateTime", doc.get("envelope").get("headers").get("createdOn"));
assertEquals(user, doc.get("envelope").get("headers").get("createdBy").asText());
assertNotNull("Could not find Triples", doc.get("envelope").get("triples"));
assertNotNull("Could not find instance", doc.get("envelope").get("instance"));
}
}
| 38.948718 | 155 | 0.675115 |
0de4014b533a845bae9a644886e2e3cbf90c8eb1 | 195 | package melody.intermediates;
public interface CanonMelody17 {
melody.intermediates.CanonMelody18 b();
melody.intermediates.CanonMelody18 d();
melody.intermediates.CanonMelody18 g();
}
| 17.727273 | 41 | 0.784615 |
d33e7ab1368ecddd7c7cd80ee066ea50a0ecabd6 | 4,271 | package com.api.controller;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.api.entity.Imagem;
import com.api.entity.Produto;
import com.api.service.ImagemService;
import com.api.service.ProdutoService;
import com.google.common.net.HttpHeaders;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@Api(description = "Controle dos produtos")
@RestController
@RequestMapping("/api/produto")
public class ProdutoController {
@Autowired
ProdutoService service;
@Autowired
ImagemService imagemService;
@ApiOperation(value = "Cadastra um produto.")
@PostMapping()
public Produto create(@RequestBody Produto produto){
Produto entity = service.create(produto);
Imagem imagem = new Imagem();
imagem.setProduto(entity);
imagemService.create(imagem);
return entity;
}
@ApiOperation(value = "Uploade de Imagem.")
@PostMapping("/upload_anuncio_image/{codigo}")
public void uploadImagem(@RequestParam MultipartFile file, @PathVariable(value = "codigo") long codigo) {
String nome = StringUtils.cleanPath(file.getOriginalFilename());
Imagem imagem = imagemService.findByProduto(codigo);
try {
imagem.setNome(nome);
imagem.setImagem(file.getBytes());
imagemService.create(imagem);
} catch (IOException e) {
e.printStackTrace();
}
}
@ApiOperation(value = "Download de Imagem.")
@GetMapping("/download_anuncio_image/{codigo}")
ResponseEntity<byte[]> downLoadFile(@PathVariable(value = "codigo") Long codigo, HttpServletRequest request) {
Imagem imagem = imagemService.findByProduto(codigo);
String mimeType = request.getServletContext().getMimeType(imagem.getNome());
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType(mimeType))
.header(HttpHeaders.CONTENT_DISPOSITION, "inline;fileName=" + imagem.getNome())
.body(imagem.getImagem());
}
@ApiOperation(value = "Atualiza um produto.")
@PutMapping()
public Produto update(@RequestBody Produto produto) {
return service.update(produto);
}
@ApiOperation(value = "Busca um produto por código.")
@GetMapping(value = "/{codigo}")
public Produto findByCodigo(@PathVariable(value = "codigo") Long codigo) {
return service.findById(codigo);
}
@ApiOperation(value = "Retorna uma lista com todos os produtos por codigo da gondola.")
@GetMapping("/gondola/{codigo}")
public List<Produto> findByGondolaCodigo(@PathVariable(value = "codigo") Long codigo) {
return service.findByGondolaCodigo(codigo);
}
@ApiOperation(value = "Retorna uma lista com todos os produtos por cdescricao")
@GetMapping("/produtos_descricao/{descricao}")
public List<Produto> findByDescricao(@PathVariable(value = "descricao") String descricao) {
return service.findByDescricao(descricao);
}
@ApiOperation(value = "Retorna uma lista com todos os produtos.")
@GetMapping("")
public List<Produto> findAll() {
return service.findAll();
}
@ApiOperation(value = "Retorna uma lista com todos os produtos com destaque igual a true.")
@GetMapping("/destaque")
public List<Produto> findbyDestaqueEqualsTrue() {
return service.findByDestaque();
}
@ApiOperation(value = "Deleta um produto por código.")
@DeleteMapping(value = "/{codigo}")
public ResponseEntity<?> delete(@PathVariable(value = "codigo") Long codigo) {
service.delete(codigo);
return ResponseEntity.ok().build();
}
}
| 35.297521 | 114 | 0.760712 |
ff64312fd8aac1d8aeb94cec90fb2bbd1d56c415 | 1,214 | package org.helpboi.api.application.command.organisation;
import java.util.List;
import java.util.Objects;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import org.helpboi.api.application.Command;
import org.helpboi.api.domain.model.user.User;
public class GetAllOrganisationUsers extends Command<List<User>> {
@Min(1L)
@NotNull
private Long organisationId;
public GetAllOrganisationUsers(Long organisationId) {
this.organisationId = organisationId;
}
public Long getOrganisationId() {
return organisationId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
GetAllOrganisationUsers that = (GetAllOrganisationUsers) o;
return Objects.equals(organisationId, that.organisationId);
}
@Override
public int hashCode() {
return Objects.hash(organisationId);
}
@Override
public String toString() {
return "GetAllOrganisationUsers{" +
"organisationId=" + organisationId +
'}';
}
}
| 24.28 | 67 | 0.647446 |
e0e2644eec2aa633bee2b2490a9325fa27aa80ec | 12,817 | package com.github.vfyjxf.jeiutilities.jei.bookmark;
import com.github.vfyjxf.jeiutilities.JEIUtilities;
import com.github.vfyjxf.jeiutilities.config.JeiUtilitiesConfig;
import com.github.vfyjxf.jeiutilities.helper.IngredientHelper;
import com.github.vfyjxf.jeiutilities.helper.RecipeHelper;
import com.github.vfyjxf.jeiutilities.helper.ReflectionUtils;
import com.github.vfyjxf.jeiutilities.jei.ingredient.CraftingRecipeInfo;
import com.github.vfyjxf.jeiutilities.jei.ingredient.RecipeInfo;
import com.google.gson.*;
import mezz.jei.api.ingredients.IIngredientHelper;
import mezz.jei.api.ingredients.VanillaTypes;
import mezz.jei.api.recipe.IFocus;
import mezz.jei.api.recipe.IIngredientType;
import mezz.jei.api.recipe.IRecipeWrapper;
import mezz.jei.api.recipe.wrapper.ICraftingRecipeWrapper;
import mezz.jei.bookmarks.BookmarkList;
import mezz.jei.config.Config;
import mezz.jei.gui.Focus;
import mezz.jei.gui.ingredients.IIngredientListElement;
import mezz.jei.gui.overlay.IIngredientGridSource;
import mezz.jei.ingredients.IngredientListElementFactory;
import mezz.jei.ingredients.IngredientRegistry;
import mezz.jei.startup.ForgeModIdHelper;
import mezz.jei.util.Log;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.JsonToNBT;
import net.minecraft.nbt.NBTException;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ResourceLocation;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.tuple.Pair;
import javax.annotation.Nullable;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
import static com.github.vfyjxf.jeiutilities.jei.JeiUtilitiesPlugin.ingredientRegistry;
@SuppressWarnings({"rawtypes", "unused"})
public class RecipeBookmarkList extends BookmarkList {
public static final String MARKER_OTHER = "O:";
public static final String MARKER_STACK = "T:";
public static final String MARKER_RECIPE = "R:";
private final List<Object> list;
private final List<IIngredientGridSource.Listener> listeners;
public static BookmarkList create(IngredientRegistry ingredientRegistry) {
if (JeiUtilitiesConfig.getRecordRecipes()) {
return new RecipeBookmarkList(ingredientRegistry);
} else {
return new BookmarkList(ingredientRegistry);
}
}
public RecipeBookmarkList(IngredientRegistry ingredientRegistry) {
super(ingredientRegistry);
list = ReflectionUtils.getFieldValue(BookmarkList.class, this, "list");
listeners = ReflectionUtils.getFieldValue(BookmarkList.class, this, "listeners");
}
@Override
public void saveBookmarks() {
List<String> strings = new ArrayList<>();
for (IIngredientListElement<?> element : this.getIngredientList()) {
Object object = element.getIngredient();
if (object instanceof ItemStack) {
strings.add(MARKER_STACK + ((ItemStack) object).writeToNBT(new NBTTagCompound()));
} else if (object instanceof RecipeInfo) {
strings.add(MARKER_RECIPE + object);
} else {
strings.add(MARKER_OTHER + getUid(element));
}
}
File file = Config.getBookmarkFile();
if (file != null) {
try (FileWriter writer = new FileWriter(file)) {
IOUtils.writeLines(strings, "\n", writer);
} catch (IOException e) {
Log.get().error("Failed to save bookmarks list to file {}", file, e);
}
}
}
@Override
public void loadBookmarks() {
File file = Config.getBookmarkFile();
if (file == null || !file.exists()) {
return;
}
List<String> ingredientJsonStrings;
try (FileReader reader = new FileReader(file)) {
ingredientJsonStrings = IOUtils.readLines(reader);
} catch (IOException e) {
Log.get().error("Failed to load bookmarks from file {}", file, e);
return;
}
Collection<IIngredientType> otherIngredientTypes = new ArrayList<>(ingredientRegistry.getRegisteredIngredientTypes());
otherIngredientTypes.remove(VanillaTypes.ITEM);
list.clear();
getIngredientList().clear();
for (String ingredientJsonString : ingredientJsonStrings) {
if (ingredientJsonString.startsWith(MARKER_STACK)) {
String itemStackAsJson = ingredientJsonString.substring(MARKER_STACK.length());
try {
NBTTagCompound itemStackAsNbt = JsonToNBT.getTagFromJson(itemStackAsJson);
ItemStack itemStack = new ItemStack(itemStackAsNbt);
if (!itemStack.isEmpty()) {
ItemStack normalized = normalize(itemStack);
addToLists(normalized);
} else {
Log.get().warn("Failed to load bookmarked ItemStack from json string, the item no longer exists:\n{}", itemStackAsJson);
}
} catch (NBTException e) {
Log.get().error("Failed to load bookmarked ItemStack from json string:\n{}", itemStackAsJson, e);
}
} else if (ingredientJsonString.startsWith(MARKER_RECIPE)) {
String recipeInfoAsJson = ingredientJsonString.substring(MARKER_RECIPE.length());
RecipeInfo<?, ?> recipeInfo = loadInfoFromJson(recipeInfoAsJson, otherIngredientTypes);
if (recipeInfo != null) {
addToLists(recipeInfo);
}
} else if (ingredientJsonString.startsWith(MARKER_OTHER)) {
String uid = ingredientJsonString.substring(MARKER_OTHER.length());
Object ingredient = getUnknownIngredientByUid(otherIngredientTypes, uid);
if (ingredient != null) {
Object normalized = normalize(ingredient);
addToLists(normalized);
}
} else {
Log.get().error("Failed to load unknown bookmarked ingredient:\n{}", ingredientJsonString);
}
}
for (IIngredientGridSource.Listener listener : listeners) {
listener.onChange();
}
}
private <T> void addToLists(T ingredient) {
IIngredientType<T> ingredientType = ingredientRegistry.getIngredientType(ingredient);
IIngredientListElement<T> element = IngredientListElementFactory.createUnorderedElement(ingredientRegistry, ingredientType, ingredient, ForgeModIdHelper.getInstance());
if (element != null) {
list.add(ingredient);
getIngredientList().add(element);
}
}
private static <T> String getUid(IIngredientListElement<T> element) {
IIngredientHelper<T> ingredientHelper = element.getIngredientHelper();
return ingredientHelper.getUniqueId(element.getIngredient());
}
private RecipeInfo loadInfoFromJson(String recipeInfoString, Collection<IIngredientType> otherIngredientTypes) {
JsonObject jsonObject;
try {
jsonObject = new JsonParser().parse(recipeInfoString).getAsJsonObject();
} catch (JsonSyntaxException e) {
JEIUtilities.logger.error("Failed to parse recipe info string {}", recipeInfoString, e);
return null;
}
String ingredientUid = jsonObject.get("ingredient").getAsString();
String resultUid = jsonObject.get("result").getAsString();
String recipeCategoryUid = jsonObject.get("recipeCategoryUid").getAsString();
Object ingredientObject = loadIngredientFromJson(ingredientUid, otherIngredientTypes);
Object resultObject = loadIngredientFromJson(resultUid, otherIngredientTypes);
if (ingredientObject == null || resultObject == null) {
JEIUtilities.logger.error("Failed to load recipe info from json string:\n{}", recipeInfoString);
return null;
}
boolean isInputMode = jsonObject.get("isInputMode").getAsBoolean();
IFocus.Mode mode = isInputMode ? IFocus.Mode.INPUT : IFocus.Mode.OUTPUT;
if (jsonObject.has("registryName")) {
if (ingredientObject instanceof ItemStack && resultObject instanceof ItemStack) {
ResourceLocation registryName = new ResourceLocation(jsonObject.get("registryName").getAsString());
Pair<ICraftingRecipeWrapper, Integer> recipePair = RecipeHelper.getCraftingRecipeWrapperAndIndex(registryName, recipeCategoryUid, resultObject, new Focus<>(mode, ingredientObject));
if (recipePair == null) {
JEIUtilities.logger.error("Failed to find the corresponding recipe, found the invalid recipe record :\n{}", recipeInfoString);
return null;
}
return new CraftingRecipeInfo((ItemStack) ingredientObject,
(ItemStack) resultObject,
recipeCategoryUid,
recipePair.getRight(),
isInputMode,
recipePair.getLeft(),
registryName
);
}
}
if (jsonObject.has("inputs")) {
JsonArray inputsArray = jsonObject.get("inputs").getAsJsonArray();
Map<IIngredientType, List<String>> recipeUidMap = getRecipeUidMap(inputsArray);
Pair<IRecipeWrapper, Integer> recipePair = RecipeHelper.getRecipeWrapperAndIndex(recipeUidMap, recipeCategoryUid, resultObject, new Focus<>(mode, ingredientObject));
if (recipePair == null) {
JEIUtilities.logger.error("Failed to find the corresponding recipe, found the invalid recipe record :\n{}", recipeInfoString);
return null;
}
return new RecipeInfo<>(ingredientObject,
resultObject,
recipeCategoryUid,
recipePair.getRight(),
isInputMode,
recipePair.getLeft()
);
}
return null;
}
private Object loadIngredientFromJson(String ingredientString, Collection<IIngredientType> otherIngredientTypes) {
if (ingredientString.startsWith(MARKER_STACK)) {
String itemStackAsJson = ingredientString.substring(MARKER_STACK.length());
try {
NBTTagCompound itemStackAsNbt = JsonToNBT.getTagFromJson(itemStackAsJson);
ItemStack itemStack = new ItemStack(itemStackAsNbt);
if (!itemStack.isEmpty()) {
return IngredientHelper.getNormalize(itemStack);
} else {
JEIUtilities.logger.warn("Failed to load recipe info ItemStack from json string, the item no longer exists:\n{}", itemStackAsJson);
}
} catch (NBTException e) {
JEIUtilities.logger.error("Failed to load bookmarked ItemStack from json string:\n{}", itemStackAsJson, e);
}
} else if (ingredientString.startsWith(MARKER_OTHER)) {
String uid = ingredientString.substring(MARKER_OTHER.length());
Object ingredient = getUnknownIngredientByUid(otherIngredientTypes, uid);
if (ingredient != null) {
return IngredientHelper.getNormalize(ingredient);
}
} else {
JEIUtilities.logger.error("Failed to load unknown recipe info:\n{}", ingredientString);
}
return null;
}
private Map<IIngredientType, List<String>> getRecipeUidMap(JsonArray inputsArray) {
HashMap<IIngredientType, List<String>> recipeUidMap = new HashMap<>(inputsArray.size());
for (JsonElement element : inputsArray) {
if (element.isJsonArray()) {
List<String> inputsUidListInner = new ArrayList<>();
for (JsonElement elementInner : element.getAsJsonArray()) {
if (elementInner.isJsonPrimitive()) {
inputsUidListInner.add(elementInner.getAsString());
}
}
recipeUidMap.put(IngredientHelper.getIngredientType(inputsUidListInner), inputsUidListInner);
}
}
return recipeUidMap;
}
@Nullable
@SuppressWarnings("rawtypes")
private Object getUnknownIngredientByUid(Collection<IIngredientType> ingredientTypes, String uid) {
for (IIngredientType<?> ingredientType : ingredientTypes) {
Object ingredient = ingredientRegistry.getIngredientByUid(ingredientType, uid);
if (ingredient != null) {
return ingredient;
}
}
return null;
}
}
| 44.814685 | 197 | 0.644925 |
0e140aeea70109defa498017a471841928d19bfe | 1,774 | package org.aksw.commons.graph.index.jena;
import java.util.Comparator;
import java.util.function.Function;
import org.aksw.combinatorics.solvers.ProblemNeighborhoodAware;
import org.aksw.commons.graph.index.core.IsoMatcher;
import org.aksw.commons.graph.index.jgrapht.ProblemNodeMappingGraph;
import org.jgrapht.Graph;
import com.google.common.collect.BiMap;
public class IsoMatcherImpl<V, E, G extends Graph<V, E>>
implements IsoMatcher<G, V>
{
protected Function<BiMap<? extends V, ? extends V>, Comparator<V>> createVertexComparator;
protected Function<BiMap<? extends V, ? extends V>, Comparator<E>> createEdgeComparator;
public IsoMatcherImpl(
Function<BiMap<? extends V, ? extends V>, Comparator<V>> createVertexComparator,
Function<BiMap<? extends V, ? extends V>, Comparator<E>> createEdgeComparator) {
super();
this.createVertexComparator = createVertexComparator;
this.createEdgeComparator = createEdgeComparator;
}
public ProblemNeighborhoodAware<BiMap<V, V>, V> toProblem(BiMap<? extends V, ? extends V> baseIso, G viewGraph, G insertGraph) {
ProblemNeighborhoodAware<BiMap<V, V>, V> result = new ProblemNodeMappingGraph<V, E, G, V>(
baseIso, viewGraph, insertGraph,
createVertexComparator, createEdgeComparator);
//Stream<BiMap<V, V>> result = tmp.generateSolutions();
return result;
}
/**
* Make sure that baseIso is not modified
*/
@Override
public Iterable<BiMap<V, V>> match(BiMap<? extends V, ? extends V> baseIso, G viewGraph, G insertGraph) {
ProblemNeighborhoodAware<BiMap<V, V>, V> problem = toProblem(baseIso, viewGraph, insertGraph);
Iterable<BiMap<V, V>> result = () -> problem.generateSolutions().iterator();
return result;
}
} | 36.204082 | 131 | 0.726043 |
d4ff92ff6bb5237c3cebb95cd8dd36d7d873e5ed | 740 | package com.qthegamep.pattern.project2.exception.mapper;
import javax.inject.Inject;
import javax.validation.ConstraintViolationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
@Provider
public class ValidationExceptionMapper implements ExceptionMapper<ConstraintViolationException> {
private GeneralExceptionMapper generalExceptionMapper;
@Inject
public ValidationExceptionMapper(GeneralExceptionMapper generalExceptionMapper) {
this.generalExceptionMapper = generalExceptionMapper;
}
@Override
public Response toResponse(ConstraintViolationException exception) {
return generalExceptionMapper.toResponse(exception);
}
}
| 30.833333 | 97 | 0.810811 |
5689e8a8e0d192f458d7f2e93189e0aa4b506efb | 629 | package backend.util;
import backend.unit.properties.InteractionModifier;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @author Created by th174 on 4/28/2017.
*/
public interface HasPassiveModifiers extends VoogaEntity {
List<? extends InteractionModifier> getOffensiveModifiers();
List<? extends InteractionModifier> getDefensiveModifiers();
default List<? extends InteractionModifier> getAllModifiers() {
return Stream.of(getOffensiveModifiers(), getDefensiveModifiers()).flatMap(Collection::stream).collect(Collectors.toList());
}
}
| 28.590909 | 126 | 0.793323 |
4c760110615417e2072afe6563bead7d1d305d38 | 1,507 | import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import rx.Observable;
import rx.Subscriber;
import rx.schedulers.Schedulers;
import java.io.IOException;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.concurrent.CompletableFuture;
public class StreamHttpClient extends HttpClient {
@Override
public void exec(List<String> urls) throws IOException {
final Instant start = Instant.now();
Observable<Response> observable = Observable.empty();
for (String url : urls) {
observable = observable.concatWith(Observable.from(asyncHttpCall(url)));
}
observable
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.computation())
.zipWith(Observable.from(urls), (r, url) -> new Pair<>(r, url))
.map(pair -> "[" + pair._2 + "] OK! ")
.subscribe(new Subscriber<String>() {
@Override
public void onCompleted() {
System.out.println("TIME: " + Duration.between(start, Instant.now()).toMillis());
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(String s) {
System.out.println(s);
}
});
}
}
| 33.488889 | 105 | 0.560053 |
36fc927c4bdc7b8d53a7624249e2f25100534f4a | 3,992 | package com.premar.muvi.fragments.person_detail_fragments;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.premar.muvi.R;
import com.premar.muvi.adapter.PersonMoviesAdapter;
import com.premar.muvi.adapter.PersonTvAdapter;
import com.premar.muvi.api.ApiService;
import com.premar.muvi.api.ApiUtils;
import com.premar.muvi.model.PersonMovie;
import com.premar.muvi.model.PersonMovieResponse;
import com.premar.muvi.model.PersonTv;
import com.premar.muvi.model.PersonTvResponse;
import com.premar.muvi.temporary_storage.MovieCache;
import com.premar.muvi.utils.AppConstants;
import java.text.ParseException;
import java.util.Comparator;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static com.premar.muvi.utils.AppConstants.API_KEY;
/**
* A simple {@link Fragment} subclass.
*/
public class PersonTvFragment extends Fragment {
private Context context;
private ApiService apiService;
private RecyclerView recyclerView;
private int personId;
public PersonTvFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_person_tv, container, false);
context = getContext();
apiService = ApiUtils.getApiService();
personId = MovieCache.personId;
setUpRecyclerView(view);
getTvShows();
return view;
}
private void setUpRecyclerView(View view){
recyclerView = view.findViewById(R.id.person_tv_recycler_view);
if(context.getResources().getConfiguration().orientation== Configuration.ORIENTATION_PORTRAIT){
recyclerView.setLayoutManager(new GridLayoutManager(context,3));
} else {
recyclerView.setLayoutManager((new GridLayoutManager(context,5)));
}
}
private void getTvShows() {
apiService.getPersonTv(personId, API_KEY).enqueue(new Callback<PersonTvResponse>() {
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void onResponse(Call<PersonTvResponse> call, Response<PersonTvResponse> response) {
if (response.isSuccessful()){
if (response.body() != null){
PersonTvResponse personTvResponse = response.body();
List<PersonTv> personShows = personTvResponse.getPersonShows();
// Collections.sort(personMovies, new DateComparator());
PersonTvAdapter adapter = new PersonTvAdapter(getContext(), personShows);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
}
@Override
public void onFailure(Call<PersonTvResponse> call, Throwable t) {
}
});
}
class DateComparator implements Comparator<PersonMovie> {
public int compare(PersonMovie c1, PersonMovie c2){
try {
String year1 = AppConstants.getYear(c1.getRelease_date());
String year2 = AppConstants.getYear(c2.getRelease_date());
if(year1 == null || year2 == null){
return 0;
}
return year1.compareTo(year2);
} catch (ParseException e) {
e.printStackTrace();
}
return 0;
}
}
}
| 32.991736 | 103 | 0.660571 |
6a71d312716e8c5a649295befbded55bd5a26c3e | 2,523 | package gg.projecteden.nexus.features.resourcepack.decoration.types;
import gg.projecteden.nexus.features.resourcepack.decoration.common.Decoration;
import gg.projecteden.nexus.features.resourcepack.decoration.common.DisabledPlacement;
import gg.projecteden.nexus.features.resourcepack.decoration.common.DisabledRotation;
import gg.projecteden.nexus.features.resourcepack.decoration.common.Hitbox;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.bukkit.Material;
import org.bukkit.block.BlockFace;
import java.util.List;
import java.util.Map;
public class Table extends Decoration {
@Getter
private final TableSize size;
public Table(String name, int modelData, TableSize size) {
super(name, modelData, Material.LEATHER_HORSE_ARMOR, size.getHitboxes());
this.size = size;
this.disabledRotation = DisabledRotation.DEGREE_45;
this.disabledPlacements = List.of(DisabledPlacement.WALL, DisabledPlacement.CEILING);
this.defaultColor = getDefaultWoodColor();
}
@AllArgsConstructor
public enum TableSize {
_1x1(Hitbox.single(Material.BARRIER)),
_1x2(List.of(
Hitbox.origin(Material.BARRIER),
new Hitbox(Material.BARRIER, Map.of(BlockFace.EAST, 1))
)),
_2x2(List.of(
Hitbox.origin(Material.BARRIER),
new Hitbox(Material.BARRIER, Map.of(BlockFace.EAST, 1)),
new Hitbox(Material.BARRIER, Map.of(BlockFace.NORTH, 1)),
new Hitbox(Material.BARRIER, Map.of(BlockFace.NORTH, 1, BlockFace.EAST, 1))
)),
_2x3(List.of(
Hitbox.origin(Material.BARRIER),
new Hitbox(Material.BARRIER, Map.of(BlockFace.EAST, 1)),
new Hitbox(Material.BARRIER, Map.of(BlockFace.NORTH, 1)),
new Hitbox(Material.BARRIER, Map.of(BlockFace.WEST, 1)),
new Hitbox(Material.BARRIER, Map.of(BlockFace.NORTH, 1, BlockFace.EAST, 1)),
new Hitbox(Material.BARRIER, Map.of(BlockFace.NORTH, 1, BlockFace.WEST, 1))
)),
_3x3(List.of(
Hitbox.origin(Material.BARRIER),
new Hitbox(Material.BARRIER, Map.of(BlockFace.EAST, 1)),
new Hitbox(Material.BARRIER, Map.of(BlockFace.NORTH, 1)),
new Hitbox(Material.BARRIER, Map.of(BlockFace.WEST, 1)),
new Hitbox(Material.BARRIER, Map.of(BlockFace.SOUTH, 1)),
new Hitbox(Material.BARRIER, Map.of(BlockFace.NORTH, 1, BlockFace.EAST, 1)),
new Hitbox(Material.BARRIER, Map.of(BlockFace.NORTH, 1, BlockFace.WEST, 1)),
new Hitbox(Material.BARRIER, Map.of(BlockFace.SOUTH, 1, BlockFace.EAST, 1)),
new Hitbox(Material.BARRIER, Map.of(BlockFace.SOUTH, 1, BlockFace.WEST, 1))
)),
;
@Getter
final List<Hitbox> hitboxes;
}
}
| 38.815385 | 87 | 0.754657 |
17f4ebae81edab0df155016f8e7a41f10cfad005 | 993 | package hrms.HrmsProject.entities.concretes;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
@Entity
@Data
@Table(name = "resume_links")
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = false)
//@PrimaryKeyJoinColumn(name="user_id")
public class ResumeLink {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name= "id")
private int id;
@Column(name = "github_link")
private String githubLink;
@Column(name = "linkedin_link")
private String linkedinLink;
@ManyToOne()
@JoinColumn(name = "jobseeker_id")
private JobSeeker candidate;
} | 23.642857 | 52 | 0.803625 |
77bec5189e750d62a33db4e65a19101d99469b78 | 847 | package com.example.finalapp.dibbitz.model;
/**
* Created by KJ on 12/8/15.
*/
import com.example.finalapp.dibbitz.model.Dibbit;
import com.parse.Parse;
import com.parse.ParseACL;
import com.parse.ParseObject;
import com.parse.ParseUser;
import android.app.Application;
public class ParseApplication extends Application{
@Override
public void onCreate() {
super.onCreate();
// Add your initialization code here
Parse.initialize(this, "jNMKS9zcvkVoRIcGxCUX7ANncRFlhK9VhD0sBhcr", "hGutVVJezPf9aSz1r7Qtz7UlPjzuWZR8mQeS4R3x");
ParseUser.enableAutomaticUser();
ParseACL defaultACL = new ParseACL();
ParseObject.registerSubclass(Dibbit.class);
//Makes the default private
defaultACL.setPublicReadAccess(false);
ParseACL.setDefaultACL(defaultACL, true);
}
} | 24.2 | 119 | 0.72137 |
8340ce3f13554d08f65bd69198baedd6a97c9094 | 3,075 | package io.github.pureza.warbots.resources;
import java.util.NoSuchElementException;
import java.util.Properties;
/**
* Utility class to read .properties files.
*/
public class PropertiesReader {
/** The properties */
private Properties properties;
/**
* Creates a new reader for the given properties
*/
public PropertiesReader(Properties properties) {
this.properties = properties;
}
/**
* Reads a boolean value from the properties
*
* @throws IllegalArgumentException if the value is not 'true' or 'false'
* @throws NoSuchElementException if the property does not exist
*/
public boolean getBoolean(String propertyName) {
String value = properties.getProperty(propertyName);
if (value != null) {
if (value.equalsIgnoreCase("true")) {
return true;
} else if (value.equalsIgnoreCase("false")) {
return false;
} else {
throw new IllegalArgumentException("Invalid boolean value for property: " + propertyName);
}
} else {
throw new NoSuchElementException(propertyName);
}
}
/**
* Reads an integer value from the properties
*
* @throws IllegalArgumentException if the value is not a valid integer
* @throws NoSuchElementException if the property does not exist
*/
public int getInt(String propertyName) {
String value = properties.getProperty(propertyName);
if (value != null) {
return Integer.parseInt(value);
} else {
throw new NoSuchElementException(propertyName);
}
}
/**
* Reads a double value from the properties
*
* @throws IllegalArgumentException if the value is not a valid double
* @throws NoSuchElementException if the property does not exist
*/
public double getDouble(String propertyName) {
String value = properties.getProperty(propertyName);
if (value != null) {
return Double.parseDouble(value);
} else {
throw new NoSuchElementException(propertyName);
}
}
/**
* Reads a long value from the properties
*
* @throws IllegalArgumentException if the value is not a valid long
* @throws NoSuchElementException if the property does not exist
*/
public long getLong(String propertyName) {
String value = properties.getProperty(propertyName);
if (value != null) {
return Long.parseLong(value);
} else {
throw new NoSuchElementException(propertyName);
}
}
/**
* Reads a string value from the properties
*
* @throws NoSuchElementException if the property does not exist
*/
public String getString(String propertyName) {
String value = properties.getProperty(propertyName);
if (value != null) {
return value;
} else {
throw new NoSuchElementException(propertyName);
}
}
}
| 28.472222 | 106 | 0.618537 |
ae68e1333e81b079c741ce6d7d9c27dea5d21884 | 481 | /*
* 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 Praktikum_11;
public class AutoNim {
public static void main (String []args){
String ta="2015";
String kd_prodi="153";
String no_reg="0001";
String nim;
nim= ta.substring(2,4)+kd_prodi+no_reg;
System.out.println("NIM : "+nim);
}
}
| 24.05 | 79 | 0.644491 |
7db29fd755b26754646cfd8b45a65f340d5b5454 | 2,304 | package achecrawler.seedfinder;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import achecrawler.crawler.crawlercommons.fetcher.BaseFetchException;
import achecrawler.crawler.crawlercommons.fetcher.FetchedResult;
import achecrawler.crawler.crawlercommons.fetcher.http.SimpleHttpFetcher;
import achecrawler.util.TimeDelay;
import achecrawler.util.parser.BackLinkNeighborhood;
public class GoogleSearch implements SearchEngineApi {
private final SimpleHttpFetcher fetcher;
private int docsPerPage = 10;
private TimeDelay timer = new TimeDelay(5000);
public GoogleSearch(SimpleHttpFetcher fetcher) {
this.fetcher = fetcher;
}
public List<BackLinkNeighborhood> submitQuery(String query, int page) throws IOException {
timer.waitMinimumDelayIfNecesary();
// 21 -> max number allowed by google... decreases after
String queryUrl = "https://www.google.com/search?q=" + query + "&num="+docsPerPage + "&start="+page*docsPerPage;
System.out.println("URL:"+queryUrl);
try {
FetchedResult result = fetcher.get(queryUrl);
InputStream is = new ByteArrayInputStream(result.getContent());
Document doc = Jsoup.parse(is, "UTF-8", query);
is.close();
Elements searchItems = doc.select("div#search");
Elements linkHeaders = searchItems.select(".r");
Elements linksUrl = linkHeaders.select("a[href]");
List<BackLinkNeighborhood> links = new ArrayList<>();
for (Element link : linksUrl) {
String title = link.text();
String url = link.attr("href");
links.add(new BackLinkNeighborhood(url, title));
}
System.out.println(getClass().getSimpleName()+" hits: "+links.size());
return links;
} catch (IOException | BaseFetchException e) {
throw new IOException("Failed to download backlinks from Google.", e);
}
}
} | 36 | 120 | 0.65191 |
59e23814f0ccf7d7490a245765a757f05c295e31 | 5,266 | /*-
* #%L
* Genome Damage and Stability Centre SMLM ImageJ Plugins
*
* Software for single molecule localisation microscopy (SMLM)
* %%
* Copyright (C) 2011 - 2020 Alex Herbert
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
package uk.ac.sussex.gdsc.smlm.filters;
import java.util.Arrays;
/**
* Helper for the spot filter.
*/
public class SpotFilterHelper {
private IntBlockSumFilter sumFilter;
private int[] data;
/**
* Count neighbours within a 2n+1 region around each spot.
*
* <p>This is performed using a block sum filter which may sub-optimal for small lists of spots.
*
* <p>The dimensions of the data will be extracted from the spot x/y coordinates.
*
* @param spots the spots
* @param n The block size
* @return the neighbour count for each spot
*/
public int[] countNeighbours(Spot[] spots, int n) {
if (spots.length <= 1 || n <= 0) {
// No neighbours are possible
return new int[spots.length];
}
// Get the range for the sum filter using the limits.
// This prevents filtering too large an image.
int minx = spots[0].x;
int maxx = minx;
int miny = spots[0].y;
int maxy = miny;
for (int i = 1; i < spots.length; i++) {
if (maxx < spots[i].x) {
maxx = spots[i].x;
} else if (minx > spots[i].x) {
minx = spots[i].x;
}
if (maxy < spots[i].y) {
maxy = spots[i].y;
} else if (miny > spots[i].y) {
miny = spots[i].y;
}
}
return countNeighbours(spots, minx, miny, maxx, maxy, n);
}
/**
* Count neighbours within a 2n+1 region around each spot.
*
* <p>This is performed using a block sum filter which may sub-optimal for small lists of spots.
*
* @param spots the spots
* @param width The width of the data
* @param height The height of the data
* @param n The block size
* @return the neighbour count for each spot
*/
public int[] countNeighbours(Spot[] spots, int width, int height, int n) {
if (spots.length <= 1 || n <= 0) {
// No neighbours are possible
return new int[spots.length];
}
return countNeighbours(spots, 0, 0, width - 1, height - 1, n);
}
/**
* Count neighbours within a 2n+1 region around each spot.
*
* <p>This is performed using a block sum filter which may sub-optimal for small lists of spots.
*
* @param spots the spots
* @param minx the minx
* @param miny the miny
* @param maxx the maxx
* @param maxy the maxy
* @param n The block size
* @return the neighbour count for each spot
*/
private int[] countNeighbours(Spot[] spots, int minx, int miny, int maxx, int maxy, int n) {
if (spots.length <= 1 || n <= 0) {
// No neighbours are possible
return new int[spots.length];
}
// Initialise
if (sumFilter == null) {
sumFilter = new IntBlockSumFilter();
}
final int width = maxx - minx + 1;
final int height = maxy - miny + 1;
final int size = width * height;
if (data == null || data.length < size) {
data = new int[size];
} else {
Arrays.fill(data, 0, size, 0);
}
// Add the spots
for (int i = 0; i < spots.length; i++) {
data[(spots[i].x - minx) + (spots[i].y - miny) * width] = 1;
}
sumFilter.rollingBlockFilter(data, width, height, n);
final int[] count = new int[spots.length];
for (int i = 0; i < spots.length; i++) {
// Subtract the actual spot from the count
count[i] = data[(spots[i].x - minx) + (spots[i].y - miny) * width] - 1;
}
return count;
}
/**
* Count neighbours within a 2n+1 region around each spot.
*
* <p>This is performed using a block sum filter which may sub-optimal for small lists of spots.
*
* <p>The dimensions of the data will be extracted from the spot x/y coordinates.
*
* @param spots the spots
* @param n The block size
* @return the neighbour count for each spot
*/
public static int[] runCountNeighbours(Spot[] spots, int n) {
return new SpotFilterHelper().countNeighbours(spots, n);
}
/**
* Count neighbours within a 2n+1 region around each spot.
*
* <p>This is performed using a block sum filter which may sub-optimal for small lists of spots.
*
* @param spots the spots
* @param width The width of the data
* @param height The height of the data
* @param n The block size
* @return the neighbour count for each spot
*/
public static int[] runCountNeighbours(Spot[] spots, int width, int height, int n) {
return new SpotFilterHelper().countNeighbours(spots, width, height, n);
}
}
| 30.439306 | 98 | 0.632738 |
7898a90294029d6cae19e450da2df0e6e197784d | 984 | package com.example.ajaalimentoschange.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/")
public class PageController {
@GetMapping
public String index() {
return "nova_index";
}
@GetMapping("cadastro_cliente")
public String cadastro() {
return "nova_cadastro_cliente";
}
@GetMapping("fale_vendedor")
public String faleVendedor() {
return "nova_fale_vendedor";
}
@GetMapping("seja_fornecedor")
public String fornecedor() {
return "nova_seja_fornecedor";
}
@GetMapping("trabalhe")
public String trabalhe() {
return "nova_trabalhe";
}
@GetMapping("produto")
public String produto() {
return "original_produto";
}
@GetMapping("categorias")
public String categorias() {
return "nova_categorias";
}
@GetMapping("mapa")
public String mapa() {
return "nova_mapa";
}
}
| 19.294118 | 62 | 0.738821 |
5e980cf7f073358fadced2dafdbe6445d8724166 | 1,200 | package com.learn.netty.buf;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.util.CharsetUtil;
import java.nio.charset.Charset;
/**
* 一些声明信息
* Description: <br/>
* date: 2020/11/24 11:21<br/>
*
* @author ${李佳乐}<br/>
* @since JDK 1.8
*/
public class NettyByteBuf02 {
public static void main(String[] args) {
ByteBuf byteBuf = Unpooled.copiedBuffer("hello,world! 西安", CharsetUtil.UTF_8);
if (byteBuf.hasArray()) {
byte[] content = byteBuf.array();
System.out.println(new String(content, CharsetUtil.UTF_8));
System.out.println(byteBuf);
System.out.println(byteBuf.arrayOffset());
System.out.println(byteBuf.readerIndex());
System.out.println(byteBuf.writerIndex());
// for (int i = 0; i < byteBuf.capacity(); i++) {
// System.out.println(byteBuf.readByte());
// }
int len = byteBuf.readableBytes();
for (int i = 0; i < len; i++) {
System.out.println((char) byteBuf.getByte(i));
}
System.out.println(byteBuf.getCharSequence(0,6,CharsetUtil.UTF_8));
}
}
}
| 31.578947 | 86 | 0.5875 |
dc25ebfa74284b63ac947b97b204c3adf121c89d | 360 | package pers.zhc.tools.pi;
import pers.zhc.tools.jni.JNI;
public class JNICallback implements JNI.Pi.Callback {
private final StringBuilder sb;
public JNICallback(StringBuilder sb) {
this.sb = sb;
}
@Override
public void callback(int a) {
this.sb.append(a);
}
StringBuilder getSb() {
return sb;
}
}
| 17.142857 | 53 | 0.627778 |
3d8ad22466ce0d6463b9cfc98a5fd7d2093aaf65 | 3,199 | /*
* Copyright 2013 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.overlord.dtgov.ui.client.local.pages.deployments;
import javax.enterprise.context.Dependent;
import javax.inject.Inject;
import org.jboss.errai.ui.nav.client.local.TransitionAnchorFactory;
import org.overlord.commons.gwt.client.local.widgets.SortableTemplatedWidgetTable;
import org.overlord.dtgov.ui.client.local.ClientMessages;
import org.overlord.dtgov.ui.client.local.pages.DeploymentDetailsPage;
import org.overlord.dtgov.ui.client.shared.beans.Constants;
import org.overlord.dtgov.ui.client.shared.beans.DeploymentSummaryBean;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.InlineLabel;
/**
* A table of deployments.
*
* @author [email protected]
*/
@Dependent
public class DeploymentTable extends SortableTemplatedWidgetTable {
@Inject
protected ClientMessages i18n;
@Inject
protected TransitionAnchorFactory<DeploymentDetailsPage> toDetailsPageLinkFactory;
/**
* Constructor.
*/
public DeploymentTable() {
}
/**
* @see org.overlord.sramp.ui.client.local.widgets.common.SortableTemplatedWidgetTable#getDefaultSortColumn()
*/
@Override
public SortColumn getDefaultSortColumn() {
SortColumn sortColumn = new SortColumn();
sortColumn.columnId = Constants.SORT_COLID_DATE_INITIATED;
sortColumn.ascending = false;
return sortColumn;
}
/**
* @see org.overlord.monitoring.ui.client.local.widgets.common.SortableTemplatedWidgetTable#configureColumnSorting()
*/
@Override
protected void configureColumnSorting() {
setColumnSortable(0, Constants.SORT_COLID_NAME);
setColumnSortable(2, Constants.SORT_COLID_DATE_INITIATED);
sortBy(Constants.SORT_COLID_DATE_INITIATED, false);
}
/**
* Adds a single row to the table.
* @param deploymentSummaryBean
*/
public void addRow(final DeploymentSummaryBean deploymentSummaryBean) {
int rowIdx = this.rowElements.size();
DateTimeFormat format = DateTimeFormat.getFormat(i18n.format("date-format")); //$NON-NLS-1$
Anchor name = toDetailsPageLinkFactory.get("uuid", deploymentSummaryBean.getUuid()); //$NON-NLS-1$
name.setText(deploymentSummaryBean.getName());
InlineLabel type = new InlineLabel(deploymentSummaryBean.getType());
InlineLabel initiatedOn = new InlineLabel(format.format(deploymentSummaryBean.getInitiatedDate()));
add(rowIdx, 0, name);
add(rowIdx, 1, type);
add(rowIdx, 2, initiatedOn);
}
}
| 35.153846 | 120 | 0.733354 |
1551d706570a0d4a5a83215bd353cb652a60aacf | 310 | package cn.hdj.hdjblog.model.vo;
import lombok.Data;
import java.util.Date;
/**
* @author hdj
* @version 1.0
* @date 12/01/2020 16:22
* @description: 时间线归档--文章
*/
@Data
public class TimelinePostVO {
private Long id;
private String slug;
private String title;
private Date createTime;
}
| 15.5 | 32 | 0.677419 |
6c9cfb218151d66ac23fc94c2cce35dce481792f | 432 | package com.github.neuralnetworks.samples.mnist;
import com.github.neuralnetworks.input.InputConverter;
import com.github.neuralnetworks.util.Util;
public class MnistTargetSingleNeuronOutputConverter implements InputConverter {
private static final long serialVersionUID = 1L;
@Override
public void convert(Object input, float[] output) {
Util.fillArray(output, 0);
output[((Float) input).intValue()] = 1;
}
}
| 27 | 79 | 0.768519 |
027dc377b8cbe1e27e150b3fc24a2977856d6cf6 | 1,611 | package cloud.timo.TimoCloud.api.objects;
import java.net.InetAddress;
import java.util.Collection;
public interface BaseObject extends IdentifiableObject {
/**
* @return The base's name. Usually in the format BASE-1, ...
*/
String getName();
/**
* @param name A non-existing base name
*/
//APIRequestFuture<Void> setName(String name);
/**
* @return The base's ip address
*/
InetAddress getIpAddress();
/**
* @return The base's server's current average CPU load
*/
Double getCpuLoad();
/**
* If the current CPU load is higher than the max CPU load, no instances will be started by this base
*/
Double getMaxCpuLoad();
/**
* @return The amount of usable RAM in megabytes
*/
int getAvailableRam();
/**
* @return The maximum amount of RAM servers/proxies on this base may use in total in megabytes
*/
int getMaxRam();
/**
* @param ram The amount of ram in megabytes
*/
//APIRequestFuture<Void> setMaxRam(int ram);
/**
* @return Whether the base is currently connected to the Core
*/
boolean isConnected();
/**
* @return Whether the base is ready to start instances. This depends on whether it is connected to the core, its cpu load and available ram
*/
boolean isReady();
/**
* @return A collection of all servers started on this base
*/
Collection<ServerObject> getServers();
/**
* @return A collection of all proxies started on this base
*/
Collection<ProxyObject> getProxies();
}
| 23.347826 | 144 | 0.62694 |
cb9653017fc162356eb95e35db7847d2a0111168 | 632 | package dijkspicy.ms.server.proxy;
import com.google.inject.Guice;
import com.google.inject.Inject;
import org.junit.Test;
/**
* micro-service-template
*
* @author dijkspicy
* @date 2018/6/28
*/
public class ProxyTest {
@Inject
private XXProxy proxy;
@Inject
private XXProxy proxy2;
@Test
public void getInstance() throws NoSuchMethodException {
ProxyTest proxyTest = Guice.createInjector().getInstance(ProxyTest.class);
System.out.println(proxyTest.proxy.equals(proxyTest.proxy2));
System.out.println(Guice.createInjector().getInstance(XXProxy.class).count("adsf"));
}
} | 24.307692 | 92 | 0.710443 |
ab57debaadfc7c63fca61708856c2ea46f18821c | 350 | package com.site.blog.model.dto;
import com.site.blog.model.entity.Link;
import lombok.Data;
import java.util.List;
/**
* @Author: Yangzhengqian
* @Description:
* @Date:Created time 2020/11/9 下午1:33
* @Modified By:
*/
@Data
public class LinkDto {
List<Link> favoriteLinks;
List<Link> recommendLinks ;
List<Link> personalLinks;
}
| 16.666667 | 39 | 0.7 |
581b8acc449a0bf865ceec9e05a434f072c9d9bc | 2,807 | /*
* [The "BSD licence"]
* Copyright (c) 2010 Ben Gruver
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.jf.dexlib;
import org.jf.dexlib.Util.Input;
import java.io.UnsupportedEncodingException;
public class OdexDependencies {
public final int modificationTime;
public final int crc;
public final int dalvikBuild;
private final String[] dependencies;
private final byte[][] dependencyChecksums;
public OdexDependencies (Input in) {
modificationTime = in.readInt();
crc = in.readInt();
dalvikBuild = in.readInt();
int dependencyCount = in.readInt();
dependencies = new String[dependencyCount];
dependencyChecksums = new byte[dependencyCount][];
for (int i=0; i<dependencyCount; i++) {
int stringLength = in.readInt();
try {
dependencies[i] = new String(in.readBytes(stringLength), 0, stringLength-1, "US-ASCII");
} catch (UnsupportedEncodingException ex) {
throw new RuntimeException(ex);
}
dependencyChecksums[i] = in.readBytes(20);
}
}
public int getDependencyCount() {
return dependencies.length;
}
public String getDependency(int index) {
return dependencies[index];
}
public byte[] getDependencyChecksum(int index) {
return dependencyChecksums[index].clone();
}
}
| 36.454545 | 104 | 0.700036 |
f70a6a22b85ff0da76e67e9b223ad4e0b020b5c4 | 19,515 | package org.bukkit.inventory;
import com.google.common.collect.ImmutableMap;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.commons.lang.Validate;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.Utility;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.meta.Damageable;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.material.MaterialData;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Represents a stack of items.
* <p>
* <b>IMPORTANT: An <i>Item</i>Stack is only designed to contain <i>items</i>. Do not
* use this class to encapsulate Materials for which {@link Material#isItem()}
* returns false.</b>
*/
public class ItemStack implements Cloneable, ConfigurationSerializable {
private Material type = Material.AIR;
private int amount = 0;
private MaterialData data = null;
private ItemMeta meta;
@Utility
protected ItemStack() {}
/**
* Defaults stack size to 1, with no extra data.
* <p>
* <b>IMPORTANT: An <i>Item</i>Stack is only designed to contain
* <i>items</i>. Do not use this class to encapsulate Materials for which
* {@link Material#isItem()} returns false.</b>
*
* @param type item material
*/
public ItemStack(@NotNull final Material type) {
this(type, 1);
}
/**
* An item stack with no extra data.
* <p>
* <b>IMPORTANT: An <i>Item</i>Stack is only designed to contain
* <i>items</i>. Do not use this class to encapsulate Materials for which
* {@link Material#isItem()} returns false.</b>
*
* @param type item material
* @param amount stack size
*/
public ItemStack(@NotNull final Material type, final int amount) {
this(type, amount, (short) 0);
}
/**
* An item stack with the specified damage / durability
*
* @param type item material
* @param amount stack size
* @param damage durability / damage
* @deprecated see {@link #setDurability(short)}
*/
public ItemStack(@NotNull final Material type, final int amount, final short damage) {
this(type, amount, damage, null);
}
/**
* @param type the type
* @param amount the amount in the stack
* @param damage the damage value of the item
* @param data the data value or null
* @deprecated this method uses an ambiguous data byte object
*/
@Deprecated
public ItemStack(@NotNull final Material type, final int amount, final short damage, @Nullable final Byte data) {
Validate.notNull(type, "Material cannot be null");
this.type = type;
this.amount = amount;
if (damage != 0) {
setDurability(damage);
}
if (data != null) {
createData(data);
}
}
/**
* Creates a new item stack derived from the specified stack
*
* @param stack the stack to copy
* @throws IllegalArgumentException if the specified stack is null or
* returns an item meta not created by the item factory
*/
public ItemStack(@NotNull final ItemStack stack) throws IllegalArgumentException {
Validate.notNull(stack, "Cannot copy null stack");
this.type = stack.getType();
this.amount = stack.getAmount();
if (this.type.isLegacy()) {
this.data = stack.getData();
}
if (stack.hasItemMeta()) {
setItemMeta0(stack.getItemMeta(), type);
}
}
/**
* Gets the type of this item
*
* @return Type of the items in this stack
*/
@Utility
@NotNull
public Material getType() {
return type;
}
/**
* Sets the type of this item
* <p>
* Note that in doing so you will reset the MaterialData for this stack.
* <p>
* <b>IMPORTANT: An <i>Item</i>Stack is only designed to contain
* <i>items</i>. Do not use this class to encapsulate Materials for which
* {@link Material#isItem()} returns false.</b>
*
* @param type New type to set the items in this stack to
*/
@Utility
public void setType(@NotNull Material type) {
Validate.notNull(type, "Material cannot be null");
this.type = type;
if (this.meta != null) {
this.meta = Bukkit.getItemFactory().asMetaFor(meta, type);
}
if (type.isLegacy()) {
createData((byte) 0);
} else {
this.data = null;
}
}
/**
* Gets the amount of items in this stack
*
* @return Amount of items in this stack
*/
public int getAmount() {
return amount;
}
/**
* Sets the amount of items in this stack
*
* @param amount New amount of items in this stack
*/
public void setAmount(int amount) {
this.amount = amount;
}
/**
* Gets the MaterialData for this stack of items
*
* @return MaterialData for this item
*/
@Nullable
public MaterialData getData() {
Material mat = Bukkit.getUnsafe().toLegacy(getType());
if (data == null && mat != null && mat.getData() != null) {
data = mat.getNewData((byte) this.getDurability());
}
return data;
}
/**
* Sets the MaterialData for this stack of items
*
* @param data New MaterialData for this item
*/
public void setData(@Nullable MaterialData data) {
if (data == null) {
this.data = data;
} else {
Material mat = Bukkit.getUnsafe().toLegacy(getType());
if ((data.getClass() == mat.getData()) || (data.getClass() == MaterialData.class)) {
this.data = data;
} else {
throw new IllegalArgumentException("Provided data is not of type " + mat.getData().getName() + ", found " + data.getClass().getName());
}
}
}
/**
* Sets the durability of this item
*
* @param durability Durability of this item
* @deprecated durability is now part of ItemMeta. To avoid confusion and
* misuse, {@link #getItemMeta()}, {@link #setItemMeta(ItemMeta)} and
* {@link Damageable#setDamage(int)} should be used instead. This is because
* any call to this method will be overwritten by subsequent setting of
* ItemMeta which was created before this call.
*/
@Deprecated
public void setDurability(final short durability) {
ItemMeta meta = getItemMeta();
if (meta != null) {
((Damageable) meta).setDamage(durability);
setItemMeta(meta);
}
}
/**
* Gets the durability of this item
*
* @return Durability of this item
* @deprecated see {@link #setDurability(short)}
*/
@Deprecated
public short getDurability() {
ItemMeta meta = getItemMeta();
return (meta == null) ? 0 : (short) ((Damageable) meta).getDamage();
}
/**
* Get the maximum stacksize for the material hold in this ItemStack.
* (Returns -1 if it has no idea)
*
* @return The maximum you can stack this material to.
*/
@Utility
public int getMaxStackSize() {
Material material = getType();
if (material != null) {
return material.getMaxStackSize();
}
return -1;
}
private void createData(final byte data) {
this.data = type.getNewData(data);
}
@Override
@Utility
public String toString() {
StringBuilder toString = new StringBuilder("ItemStack{").append(getType().name()).append(" x ").append(getAmount());
if (hasItemMeta()) {
toString.append(", ").append(getItemMeta());
}
return toString.append('}').toString();
}
@Override
@Utility
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof ItemStack)) {
return false;
}
ItemStack stack = (ItemStack) obj;
return getAmount() == stack.getAmount() && isSimilar(stack);
}
/**
* This method is the same as equals, but does not consider stack size
* (amount).
*
* @param stack the item stack to compare to
* @return true if the two stacks are equal, ignoring the amount
*/
@Utility
public boolean isSimilar(@Nullable ItemStack stack) {
if (stack == null) {
return false;
}
if (stack == this) {
return true;
}
Material comparisonType = (this.type.isLegacy()) ? Bukkit.getUnsafe().fromLegacy(this.getData(), true) : this.type; // This may be called from legacy item stacks, try to get the right material
return comparisonType == stack.getType() && getDurability() == stack.getDurability() && hasItemMeta() == stack.hasItemMeta() && (hasItemMeta() ? Bukkit.getItemFactory().equals(getItemMeta(), stack.getItemMeta()) : true);
}
@NotNull
@Override
public ItemStack clone() {
try {
ItemStack itemStack = (ItemStack) super.clone();
if (this.meta != null) {
itemStack.meta = this.meta.clone();
}
if (this.data != null) {
itemStack.data = this.data.clone();
}
return itemStack;
} catch (CloneNotSupportedException e) {
throw new Error(e);
}
}
@Override
@Utility
public int hashCode() {
int hash = 1;
hash = hash * 31 + getType().hashCode();
hash = hash * 31 + getAmount();
hash = hash * 31 + (getDurability() & 0xffff);
hash = hash * 31 + (hasItemMeta() ? (meta == null ? getItemMeta().hashCode() : meta.hashCode()) : 0);
return hash;
}
/**
* Checks if this ItemStack contains the given {@link Enchantment}
*
* @param ench Enchantment to test
* @return True if this has the given enchantment
*/
public boolean containsEnchantment(@NotNull Enchantment ench) {
return meta == null ? false : meta.hasEnchant(ench);
}
/**
* Gets the level of the specified enchantment on this item stack
*
* @param ench Enchantment to check
* @return Level of the enchantment, or 0
*/
public int getEnchantmentLevel(@NotNull Enchantment ench) {
return meta == null ? 0 : meta.getEnchantLevel(ench);
}
/**
* Gets a map containing all enchantments and their levels on this item.
*
* @return Map of enchantments.
*/
@NotNull
public Map<Enchantment, Integer> getEnchantments() {
return meta == null ? ImmutableMap.<Enchantment, Integer>of() : meta.getEnchants();
}
/**
* Adds the specified enchantments to this item stack.
* <p>
* This method is the same as calling {@link
* #addEnchantment(org.bukkit.enchantments.Enchantment, int)} for each
* element of the map.
*
* @param enchantments Enchantments to add
* @throws IllegalArgumentException if the specified enchantments is null
* @throws IllegalArgumentException if any specific enchantment or level
* is null. <b>Warning</b>: Some enchantments may be added before this
* exception is thrown.
*/
@Utility
public void addEnchantments(@NotNull Map<Enchantment, Integer> enchantments) {
Validate.notNull(enchantments, "Enchantments cannot be null");
for (Map.Entry<Enchantment, Integer> entry : enchantments.entrySet()) {
addEnchantment(entry.getKey(), entry.getValue());
}
}
/**
* Adds the specified {@link Enchantment} to this item stack.
* <p>
* If this item stack already contained the given enchantment (at any
* level), it will be replaced.
*
* @param ench Enchantment to add
* @param level Level of the enchantment
* @throws IllegalArgumentException if enchantment null, or enchantment is
* not applicable
*/
@Utility
public void addEnchantment(@NotNull Enchantment ench, int level) {
Validate.notNull(ench, "Enchantment cannot be null");
if ((level < ench.getStartLevel()) || (level > ench.getMaxLevel())) {
throw new IllegalArgumentException("Enchantment level is either too low or too high (given " + level + ", bounds are " + ench.getStartLevel() + " to " + ench.getMaxLevel() + ")");
} else if (!ench.canEnchantItem(this)) {
throw new IllegalArgumentException("Specified enchantment cannot be applied to this itemstack");
}
addUnsafeEnchantment(ench, level);
}
/**
* Adds the specified enchantments to this item stack in an unsafe manner.
* <p>
* This method is the same as calling {@link
* #addUnsafeEnchantment(org.bukkit.enchantments.Enchantment, int)} for
* each element of the map.
*
* @param enchantments Enchantments to add
*/
@Utility
public void addUnsafeEnchantments(@NotNull Map<Enchantment, Integer> enchantments) {
for (Map.Entry<Enchantment, Integer> entry : enchantments.entrySet()) {
addUnsafeEnchantment(entry.getKey(), entry.getValue());
}
}
/**
* Adds the specified {@link Enchantment} to this item stack.
* <p>
* If this item stack already contained the given enchantment (at any
* level), it will be replaced.
* <p>
* This method is unsafe and will ignore level restrictions or item type.
* Use at your own discretion.
*
* @param ench Enchantment to add
* @param level Level of the enchantment
*/
public void addUnsafeEnchantment(@NotNull Enchantment ench, int level) {
ItemMeta itemMeta = (meta == null ? meta = Bukkit.getItemFactory().getItemMeta(type) : meta);
if (itemMeta != null) {
itemMeta.addEnchant(ench, level, true);
}
}
/**
* Removes the specified {@link Enchantment} if it exists on this
* ItemStack
*
* @param ench Enchantment to remove
* @return Previous level, or 0
*/
public int removeEnchantment(@NotNull Enchantment ench) {
int level = getEnchantmentLevel(ench);
if (level == 0 || meta == null) {
return level;
}
meta.removeEnchant(ench);
return level;
}
@Override
@NotNull
@Utility
public Map<String, Object> serialize() {
Map<String, Object> result = new LinkedHashMap<String, Object>();
result.put("v", Bukkit.getUnsafe().getDataVersion()); // Include version to indicate we are using modern material names (or LEGACY prefix)
result.put("type", getType().name());
if (getAmount() != 1) {
result.put("amount", getAmount());
}
ItemMeta meta = getItemMeta();
if (!Bukkit.getItemFactory().equals(meta, null)) {
result.put("meta", meta);
}
return result;
}
/**
* Required method for configuration serialization
*
* @param args map to deserialize
* @return deserialized item stack
* @see ConfigurationSerializable
*/
@NotNull
public static ItemStack deserialize(@NotNull Map<String, Object> args) {
int version = (args.containsKey("v")) ? ((Number) args.get("v")).intValue() : -1;
short damage = 0;
int amount = 1;
if (args.containsKey("damage")) {
damage = ((Number) args.get("damage")).shortValue();
}
Material type;
if (version < 0) {
type = Material.getMaterial(Material.LEGACY_PREFIX + (String) args.get("type"));
byte dataVal = (type != null && type.getMaxDurability() == 0) ? (byte) damage : 0; // Actually durable items get a 0 passed into conversion
type = Bukkit.getUnsafe().fromLegacy(new MaterialData(type, dataVal), true);
// We've converted now so the data val isn't a thing and can be reset
if (dataVal != 0) {
damage = 0;
}
} else {
type = Bukkit.getUnsafe().getMaterial((String) args.get("type"), version);
}
if (args.containsKey("amount")) {
amount = ((Number) args.get("amount")).intValue();
}
ItemStack result = new ItemStack(type, amount, damage);
if (args.containsKey("enchantments")) { // Backward compatiblity, @deprecated
Object raw = args.get("enchantments");
if (raw instanceof Map) {
Map<?, ?> map = (Map<?, ?>) raw;
for (Map.Entry<?, ?> entry : map.entrySet()) {
Enchantment enchantment = Enchantment.getByName(entry.getKey().toString());
if ((enchantment != null) && (entry.getValue() instanceof Integer)) {
result.addUnsafeEnchantment(enchantment, (Integer) entry.getValue());
}
}
}
} else if (args.containsKey("meta")) { // We cannot and will not have meta when enchantments (pre-ItemMeta) exist
Object raw = args.get("meta");
if (raw instanceof ItemMeta) {
((ItemMeta) raw).setVersion(version);
result.setItemMeta((ItemMeta) raw);
}
}
if (version < 0) {
// Set damage again incase meta overwrote it
if (args.containsKey("damage")) {
result.setDurability(damage);
}
}
return result;
}
/**
* Get a copy of this ItemStack's {@link ItemMeta}.
*
* @return a copy of the current ItemStack's ItemData
*/
@Nullable
public ItemMeta getItemMeta() {
return this.meta == null ? Bukkit.getItemFactory().getItemMeta(this.type) : this.meta.clone();
}
/**
* Checks to see if any meta data has been defined.
*
* @return Returns true if some meta data has been set for this item
*/
public boolean hasItemMeta() {
return !Bukkit.getItemFactory().equals(meta, null);
}
/**
* Set the ItemMeta of this ItemStack.
*
* @param itemMeta new ItemMeta, or null to indicate meta data be cleared.
* @return True if successfully applied ItemMeta, see {@link
* ItemFactory#isApplicable(ItemMeta, ItemStack)}
* @throws IllegalArgumentException if the item meta was not created by
* the {@link ItemFactory}
*/
public boolean setItemMeta(@Nullable ItemMeta itemMeta) {
return setItemMeta0(itemMeta, type);
}
/*
* Cannot be overridden, so it's safe for constructor call
*/
private boolean setItemMeta0(@Nullable ItemMeta itemMeta, @NotNull Material material) {
if (itemMeta == null) {
this.meta = null;
return true;
}
if (!Bukkit.getItemFactory().isApplicable(itemMeta, material)) {
return false;
}
this.meta = Bukkit.getItemFactory().asMetaFor(itemMeta, material);
Material newType = Bukkit.getItemFactory().updateMaterial(meta, material);
if (this.type != newType) {
this.type = newType;
}
if (this.meta == itemMeta) {
this.meta = itemMeta.clone();
}
return true;
}
}
| 32.579299 | 228 | 0.594824 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.