ammarnasr/codegen-350M-mono-java
Text Generation
•
Updated
•
38
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
|
---|---|---|---|---|---|
be195bee1eb66f3aa6482539a63f24e7a32bd903 | 38,424 | /****************************************************************************
* Copyright AGAT-Team (2014)
*
* Contributors:
* J.F. Randrianasoa
* K. Kurtz
* E. Desjardin
* N. Passat
*
* This software is a computer program whose purpose is to [describe
* functionalities and technical features of your software].
*
* This software is governed by the CeCILL-B license under French law and
* abiding by the rules of distribution of free software. You can use,
* modify and/ or redistribute the software under the terms of the CeCILL-B
* license as circulated by CEA, CNRS and INRIA at the following URL
* "http://www.cecill.info".
*
* As a counterpart to the access to the source code and rights to copy,
* modify and redistribute granted by the license, users are provided only
* with a limited warranty and the software's author, the holder of the
* economic rights, and the successive licensors have only limited
* liability.
*
* In this respect, the user's attention is drawn to the risks associated
* with loading, using, modifying and/or developing or reproducing the
* software by the user in light of its specific status of free software,
* that may mean that it is complicated to manipulate, and that also
* therefore means that it is reserved for developers and experienced
* professionals having in-depth computer knowledge. Users are therefore
* encouraged to load and test the software's suitability as regards their
* requirements in conditions enabling the security of their systems and/or
* data to be ensured and, more generally, to use and operate it in the
* same conditions as regards security.
*
* The fact that you are presently reading this means that you have had
* knowledge of the CeCILL-B license and that you accept its terms.
*
* The full license is in the file LICENSE, distributed with this software.
*****************************************************************************/
package evaluation.datastructure;
import java.awt.Color;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.TreeMap;
import datastructure.Node;
import ui.ImFrame;
import utils.ImTool;
import utils.LabelMatrix;
import utils.Log;
import utils.SegmentByConnexityRaw;
/**
*
* Segment of reference from a ground truth GT.
*
*/
public class SegReference{
/**
* Pixels of the segment according to its bounding box.
*/
public ArrayList<Point> bbPoints;
/**
* Height of the bounding box.
*/
public int bbHeight;
/**
* Width of the bounding box.
*/
public int bbWidth;
/**
* Best matching node.
*/
public Node bestN = null;
/**
* Best score of similarity associated with the best matched node 'lamda(S_i)'.
*/
public double bestSimilarityScore = 0.0;
/**
* Background color of the GT image.
*/
public int bgColor;
/**
* Bounding box including a margin.\n
*
* <ul>
* <li>boundingBox[0] is the cell coordinate of the upper-left point
* <li>boundingBox[1] is the cell coordinate of the lower-right point
* <li>boundingBox[2] is the row coordinate of the upper-left point
* <li>boundingBox[3] is the row coordinate of the lower-right point
* </ul>
*/
public int[] boundingBox = new int[4];
/**
* Path where the extracted GT informations are stored.
*/
public String gtPath;
/**
* Pixels of a segment contained in a GT image.
*/
public ArrayList<Point> gtPoints;
/**
* Path of the GT image associated to the segment.
*/
public String imgGtPath;
/**
* Height of the crop image containing only the segment.
*/
public int imgGtHeight;
/**
* Width of the GT image containing only the segment.
*/
public int imgGtWidth;
/**
* Index of the segment.
*/
public int index;
/**
* value[0] -> Number of segments in the class. <br>
* value[1] -> Size of all segments in the class. <br>
* value[2] -> Score f1 <br>
* value[3] -> Score f2 <br>
* Only the first segment of a list should contain this value.
*/
public TreeMap<Integer, Double[]> listOfAllSemanticLabels;
/**
* Number of pixels that will be added around the bounding box when computing a crop of the segment.
*/
public int margin;
/**
* A matrix containing the real valor of 'sigma_s(x)' i.e. < 0 for x in the segment, 0 on the border of the segment and > 0 outside the segment and contains also the value of 'Mu_alpha'.
* muMap[x][y][0] -> distance value <br>
* muMap[x][y][1] -> mu value
*/
public double[][][] muMap;
public static int nbSegs = 0;
/**
* Coordinates of the real bounding box without margins.
*/
public int[] realBoundingBox;
/**
* Thematic label.
*/
public int semanticLabel;
/**
* If true. the number of segments of each class and the total size of each class are computed.
* Only the first segment of the list should contain this value.
*/
public boolean sizeAndNbSet;
/**
* Prepare a segment of reference.
* @param index : identification of the segment.
* @param points ~ pixels contained in the segment of reference.
* @param semanticLabel : thematic label.
* @param bgColor : background color of the GT image.
*/
public SegReference(ArrayList<Point> points, int semanticLabel, int bgColor) {
this.index = ++SegReference.nbSegs;
this.gtPoints = points;
this.semanticLabel = semanticLabel;
this.bgColor = bgColor;
}
/**
* Prepare a segment of reference.
* @param imgGtPath : Path of an image containing only the segment having a white background.
* @param semanticLabel : thematic label
* @param bgColor : background color of the GT image.
* @param computeBB : if 'true', compute the bounding box and also fill a list of points having coordinates according to the bounding box.
*/
public SegReference(String imgGtPath, int semanticLabel, int bgColor, boolean computeBB){
this.index = ++SegReference.nbSegs;
/* Remember the gt crop image path. */
this.imgGtPath = imgGtPath;
/*
* Load the GT image.
*/
BufferedImage img = ImTool.read(this.imgGtPath);
this.imgGtWidth= img.getWidth();
this.imgGtHeight= img.getHeight();
/*
* Set the background color of the initial GT image containing the segments.
*/
// this.initBgColor(bgColor);
this.bgColor = bgColor;
/*
* Get the list of integer points.
*/
this.gtPoints = new ArrayList<Point>();
for(int x=0;x<this.imgGtWidth;x++) {
for(int y=0;y<this.imgGtHeight;y++) {
if(img.getRGB(x, y) != this.bgColor) {
Point p = new Point(x, y);
this.gtPoints.add(p);
}
}
}
/*
* Store a semantic label.
*/
this.semanticLabel = semanticLabel;
if(computeBB){
/*
* Compute the bounding box.
*/
this.computeRegionBoundingBox();
}
}
/**
* Create a segment of reference having a specified label.
* @param semanticLabel : thematic label.
* @param gtWidth : width of the GT image.
* @param gtHeight : height of the GT image.
* @param gtImgPath : path of the GT image.
* @param alpha : >0 allow controlling the degree of uncertainty.
*/
public SegReference(int semanticLabel, int gtWidth, int gtHeight, String gtImgPath, double alpha){
this.index = ++SegReference.nbSegs;
this.semanticLabel = semanticLabel;
this.imgGtWidth = gtWidth;
this.imgGtHeight = gtHeight;
this.imgGtPath = gtImgPath;
/* Pixel margin around the real bounding box */
if(alpha != 0) {
this.margin = (int)(Math.log((1 / 0.001) - 1) / alpha); /* in px */
}else {
this.margin = 0;
}
this.gtPoints = new ArrayList<Point>();
}
/**
* Create a segment of reference having a specified label.
* @param semanticLabel : thematic label.
* @param gtWidth : width of the GT image.
* @param gtHeight : height of the GT image.
* @param gtImgPath : path of the GT image.
* @param bgColor : background color of the GT image.
* @param alpha : >0 allow controlling the degree of uncertainty.
*/
public SegReference(int semanticLabel, int gtWidth, int gtHeight, String gtImgPath, int bgColor, double alpha){
this.index = ++SegReference.nbSegs;
this.semanticLabel = semanticLabel;
this.imgGtWidth = gtWidth;
this.imgGtHeight = gtHeight;
this.imgGtPath = gtImgPath;
this.bgColor = bgColor;
/* Pixel margin around the real bounding box */
if(alpha != 0) {
this.margin = (int)(Math.log((1 / 0.001) - 1) / alpha); /* in px */
}else {
this.margin = 0;
}
this.gtPoints = new ArrayList<Point>();
}
/**
* Add a pixel from a GT image.
* @param point ~ pixel to add.
*/
public void addGtPoint(Point point){
this.gtPoints.add(point);
}
/**
* Compute the bounding box BB of the segment and translate the pixels' location according to this BB.
* @return the real bounding box values.
*/
public int[] computeRegionBoundingBox() {
this.boundingBox = new int[4];
this.realBoundingBox = new int[4];
/* Compute a bounding box */
int minX = Integer.MAX_VALUE;
int maxX = Integer.MIN_VALUE;
int minY = Integer.MAX_VALUE;
int maxY = Integer.MIN_VALUE;
for(Point p : this.gtPoints) {
int x= p.x;
int y= p.y;
if(x < minX)
minX = x;
if(x > maxX)
maxX = x;
if(y < minY)
minY = y;
if(y > maxY)
maxY = y;
}
/* Remember the crop bounding box */
int minXMargin = minX - this.margin;
int maxXMargin = maxX + this.margin;
int minYMargin = minY - this.margin;
int maxYMargin = maxY + this.margin;
if(minXMargin >= 0) this.boundingBox[0] = minXMargin;
else this.boundingBox[0] = 0;
if(maxXMargin <= this.imgGtWidth) this.boundingBox[1] = maxXMargin;
else this.boundingBox[1] = this.imgGtWidth;
if(minYMargin >= 0) this.boundingBox[2] = minYMargin;
else this.boundingBox[2] = 0;
if(maxYMargin <= this.imgGtHeight) this.boundingBox[3] = maxYMargin;
else this.boundingBox[3] = this.imgGtHeight;
/* real bounding box values */
this.realBoundingBox[0] = minX;
this.realBoundingBox[1] = maxX;
this.realBoundingBox[2] = minY;
this.realBoundingBox[3] = maxY;
/* Compute the width and the height of the bounding box */
this.bbWidth = this.boundingBox[1] - this.boundingBox[0] + 1;
this.bbHeight = this.boundingBox[3] - this.boundingBox[2] + 1;
if(this.bbWidth <= 0) this.bbWidth = 1;
if(this.bbHeight <= 0) this.bbHeight = 1;
/* Update the pixel location values according to the bounding box */
this.gtToBB();
return realBoundingBox;
}
/**
* Removes a segment from a list of segments of reference according to its RGB integer color value.
* @param segReferences tree map containing some segments of reference.
* @param color of the segment to remove.
*/
public static void deleteSegment(TreeMap<Integer, SegReference> segReferences, int color) {
SegReference seg = segReferences.get(color);
if(seg != null){
segReferences.remove(color);
int i = 0;
for(Entry <Integer, SegReference> entry: segReferences.entrySet()) {
SegReference sr = entry.getValue();
sr.index = i++;
}
}
Log.println("Delete a seg. ref.", "nb. remaining segs.: "+ segReferences.size() +"\n");
}
/**
* Extracts all segments of a fat zone image and saves the valuable information in some files.
*
* @param gtImgPath : Path of the image GT having white background.
* @param alpha : >0 allow controlling the degree of uncertainty.
* @param generateCrops : saving map images and the segments in a file.
* @return
*/
public static TreeMap<Integer, SegReference> extractSegmentsOfReference(String gtImgPath, double alpha, boolean generateCrops){
Log.println("GT-EXTRACTION", "Starting");
/* Load the image */
BufferedImage gtImg = ImTool.read(gtImgPath);
int gtWidth = gtImg.getWidth();
int gtHeight = gtImg.getHeight();
/* Set containing list of segments of reference */
TreeMap<Integer, SegReference> listOfSegs = new TreeMap<Integer, SegReference>();
/* Get all the connected regions contained in the GT image */
SegmentByConnexityRaw sbc = new SegmentByConnexityRaw(gtImg);
LabelMatrix inputLabelMatrix = sbc.runForFullImage();
/* Extract the segments */
TreeMap<Integer, Double[]> semanticLabels = new TreeMap<Integer, Double[]>();
for(int y=0; y < gtHeight; ++y){
for(int x=0; x < gtWidth; ++x){
boolean isBlack = true;
int nbBands = Math.min(ImTool.getNbBandsOf(gtImg), 3);
for(int band = 0; band < nbBands; ++band) {
double val = ImTool.getPixelValue(x, y, band, gtImg);
if(val != 0) {
isBlack = false;
break;
}
}
if(!isBlack) { // drop the black background
int segLabNonSem = inputLabelMatrix.getLabel(x, y);
int rgbVal = gtImg.getRGB(x, y);
if(!listOfSegs.containsKey(segLabNonSem)){
/* create a segment of reference object, add it to the list with its semantic label */
int semanticLabel = rgbVal;
listOfSegs.put(segLabNonSem, new SegReference(semanticLabel, gtWidth, gtHeight, gtImgPath, alpha));
if(!semanticLabels.containsKey(semanticLabel)){
Double[] val = new Double[4];
val[0] = 0.0;
val[1] = 0.0;
val[2] = 0.0;
val[3] = 0.0;
semanticLabels.put(semanticLabel, val);
}
}
/* store the point ~ pixel in the segment of reference object */
listOfSegs.get(segLabNonSem).addGtPoint(new Point(x, y));
}
}
}
/* Use the first segment to store the information about the semantic labels */
listOfSegs.firstEntry().getValue().listOfAllSemanticLabels = semanticLabels;
/* Identify the correct path where the segment outputs will be stored */
String folderPath[] = gtImgPath.split("\\\\");
int lastIndex = folderPath.length - 1;
String gtImgName = folderPath[lastIndex];
String fpath[] = gtImgPath.split(gtImgName);
String gtPath = fpath[0] +"segref_("+ gtImgName +")";
/* Save a manifest file if it's not already existing */
String manifPath = gtPath +"//manifest";
File mf = new File(manifPath);
if(!mf.exists() || mf.isDirectory()){ /* create a file and register the number of segments and the 1st alpha used */
try {
/* global info on the list of segments */
new File(gtPath).mkdir();
PrintWriter manifWriter = new PrintWriter(manifPath, "UTF-8");
manifWriter.println(listOfSegs.size()); /* save <nb_segments> */
int it = 0;
for(Entry<Integer, Double[]> entry: semanticLabels.entrySet()){
manifWriter.print(entry.getKey());
if(it < semanticLabels.size() - 1)
manifWriter.print(";");
it++;
}
manifWriter.println();
manifWriter.print(alpha);
manifWriter.close();
} catch (Exception e){
e.printStackTrace();
}
}else{
/* add the current alpha in the manifest file */
try(FileWriter fw = new FileWriter(manifPath, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw)){
out.print(";"+ alpha); /* save alpha in the manifest file */
out.close();
bw.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/* Compute the distance map and save files for each segment of reference */
for(Map.Entry<Integer, SegReference> entry : listOfSegs.entrySet()){
SegReference s = entry.getValue();
s.muMap = DistanceMap.compute(s, alpha, gtPath);
if(generateCrops) {
String gtVisuPath = gtPath +"//gt-visu";
new File(gtVisuPath).mkdirs();
ImTool.save(s.toBufferedImage(), gtVisuPath +"//s-"+ s.index +".png");
}
}
int nbRegions = inputLabelMatrix.getNbRegions();
Log.println("Segment of reference", "number of segments including the background segments : "+ nbRegions);
Log.println("Segment of reference", "number of semantic labels : "+ semanticLabels.size());
return listOfSegs;
}
/**
* Get the set of pixels by considering their location in the bounding box.
* @return List of Point.
*/
public ArrayList<Point> getBbIntegerPoints(){
return this.bbPoints;
}
/**
* Get the set of pixels by considering their location in the GT image.
* @return List of Point.
*/
public ArrayList<Point> getPoints(){
return this.gtPoints;
}
/**
* From a saved file, get all segments. <br>
* The alpha considered for the mu maps is the first alpha mentioned in the manifest file. <br>
* @param path Folder containing save files. <br>
* @param visu if yes, show segments in windows. <br>
* @return a list of segments.
*/
public static TreeMap<Integer, SegReference> getSegReferences(String path, double alpha, boolean visu) {
/* Set containing list of segments of reference */
TreeMap<Integer, SegReference> listOfSegs = new TreeMap<Integer, SegReference>();
/* get important information for the manifest */
try {
/* read the manifest file and start to get information */
String manifPath = path +"//manifest";
BufferedReader br = new BufferedReader(new FileReader(manifPath));
String line = br.readLine(); /* got the number of segments */
String lineElems[];
String sep = ";";
int nbSegs = Integer.parseInt(line);
line = br.readLine();/* got the list of labels <lab1;lab2;...> */
lineElems = line.split(sep);
TreeMap<Integer, Double[]> semanticLabels = new TreeMap<Integer, Double[]>();
for(int i = 0; i < lineElems.length; ++i){
Double[] val = new Double[4];
val[0] = 0.0;
val[1] = 0.0;
val[2] = 0.0;
val[3] = 0.0;
semanticLabels.put(Integer.parseInt(lineElems[i]), val);
}
line = br.readLine(); /* got the alphas */
String alphas[] = line.split(sep);
/* parse each files corresponding to each segment */
for(int ns = 1; ns <= nbSegs; ++ns){
/* seg info */
String sPath = path +"//s-"+ ns;
BufferedReader segBr = new BufferedReader(new FileReader(sPath));
line = segBr.readLine(); /* got <index;semantic_label> */
lineElems = line.split(sep);
int index = Integer.parseInt(lineElems[0]);
int semanticLabel = Integer.parseInt(lineElems[1]);
line = segBr.readLine(); /* got <imgGtPath;imgGTWidth;imgGTHeight> */
lineElems = line.split(sep);
String gtImgPath = lineElems[0];
int gtWidth = Integer.parseInt(lineElems[1]);
int gtHeight = Integer.parseInt(lineElems[2]);
line = segBr.readLine(); /* got the real bounding box values <minX;maxX;minY;maxY> */
lineElems = line.split(sep);
int minX = Integer.parseInt(lineElems[0]);
int maxX = Integer.parseInt(lineElems[1]);
int minY = Integer.parseInt(lineElems[2]);
int maxY = Integer.parseInt(lineElems[3]);
line = segBr.readLine(); /* got the real int <bgcolor> */
int bgColor = Integer.parseInt(line);
/* create the base of the segment */
SegReference s = new SegReference(semanticLabel, gtWidth, gtHeight, gtImgPath, bgColor, alpha);
s.index = index; /* just in case */
s.bgColor = bgColor;
/* fill the crop bounding box information */
/* Remember the crop bounding box */
if(alpha >= 0){ /* use margin */
int minXMargin = minX - s.margin;
int maxXMargin = maxX + s.margin;
int minYMargin = minY - s.margin;
int maxYMargin = maxY + s.margin;
if(minXMargin >= 0) s.boundingBox[0] = minXMargin;
else s.boundingBox[0] = 0;
if(maxXMargin <= s.imgGtWidth) s.boundingBox[1] = maxXMargin;
else s.boundingBox[1] = s.imgGtWidth;
if(minYMargin >= 0) s.boundingBox[2] = minYMargin;
else s.boundingBox[2] = 0;
if(maxYMargin <= s.imgGtHeight) s.boundingBox[3] = maxYMargin;
else s.boundingBox[3] = s.imgGtHeight;
}else{
s.boundingBox[0] = minX;
s.boundingBox[1] = maxX;
s.boundingBox[2] = minY;
s.boundingBox[3] = maxY;
}
/* Compute the width and the height of the bounding box */
s.bbWidth = s.boundingBox[1] - s.boundingBox[0] + 1;
s.bbHeight = s.boundingBox[3] - s.boundingBox[2] + 1;
if(s.bbWidth <= 0) s.bbWidth = 1;
if(s.bbHeight <= 0) s.bbHeight = 1;
/* fill the gt points */
line = segBr.readLine(); /* got the <nbPoints> */
int nbPoints = Integer.parseInt(line);
for(int np = 0; np < nbPoints; ++np){
line = segBr.readLine(); /* got the gt point value */
String splited[] = line.split("_");
int x = Integer.parseInt(splited[0]);
int y = Integer.parseInt(splited[1]);
Point p = new Point(x, y);
s.gtPoints.add(p);
}
/* fill the bb points */
s.gtToBB();
/* add the segment in the list */
listOfSegs.put(ns, s);
/*
* In case of soft evaluation.
*/
/* check if the alpha exists in the manifest file */
if(alpha >=0 ){
int t = 0; // comme trouver
boolean found = false;
while(!found && t < alphas.length){
if(Double.parseDouble(alphas[t]) == alpha){
found = true;
}
t++;
}
if(!found){ /* compute an new mu map if the specified alpha is not found */
s.muMap = DistanceMap.compute(s, alpha, false, path);
s.margin = (int)(Math.log((1 / 0.001) - 1) / alpha); /* en px */
/* add the current alpha in the manifest file */
try(FileWriter fw = new FileWriter(manifPath, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw))
{
out.print(";"+ alpha); /* save alpha in the manifest file */
out.close();
bw.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}else{
String distancePath = path +"//dist-"+ s.index +"-"+ alpha +".csv";
String muPath = path +"//mu-"+ s.index +"-"+ alpha +".csv";
BufferedReader dBr = new BufferedReader(new FileReader(distancePath));
BufferedReader mBr = new BufferedReader(new FileReader(muPath));
String line2, lineElems2[];
s.muMap = new double[s.bbWidth][s.bbHeight][2];
for(int h=0; h<s.bbHeight; ++h){
line = dBr.readLine(); /* got one row from the distance file */
lineElems = line.split(sep);
line2 = mBr.readLine(); /* got one row from the mu file */
lineElems2 = line2.split(sep);
for(int w=0; w<s.bbWidth; ++w){
s.muMap[w][h][0] = Double.parseDouble(lineElems[w]); /* set the distance value */
s.muMap[w][h][1] = Double.parseDouble(lineElems2[w]); /* set the mu value */
}
}
dBr.close();
mBr.close();
}
}
/* visualize the crop */
if(visu){
/* generate the segment crop image */
int white = 255;
int black = 0;
LabelMatrix crop = new LabelMatrix(s.bbWidth, s.bbHeight);
for (int j = 0; j < s.bbHeight; ++j){
for(int i = 0; i < s.bbWidth; ++i){
Point tmpPoint = new Point(i, j);
if(s.getBbIntegerPoints().contains(tmpPoint)) {
crop.setLabel(white, i, j);
}
else{
crop.setLabel(black, i, j);
}
}
}
/* show images in windows */
BufferedImage cropImg = ImTool.generateRegions(crop, null);
ImTool.show(cropImg, 50);
}
segBr.close();
}
/* Use the first segment to store the information about the semantic labels */
listOfSegs.firstEntry().getValue().listOfAllSemanticLabels = semanticLabels;
br.close();
} catch (Exception e) {
e.printStackTrace();
}
return listOfSegs;
}
/**
* TODO obsolete
* From an image GT, get each segments.
* @param gtImgPath : Path of the image GT having white background.
* @param bgColor : background color of the GT image.
* @param alpha : >0 allow controlling the degree of uncertainty.
* @param computeDistanceMap : if true, compute the matrix of distance map and containing also the membership function.
* @param showMaps : if true, show the distance and the mu maps.
* @param save : saving map images and the segments in a file.
* @return
*/
public static TreeMap<Integer, SegReference> getSegReferences(String gtImgPath, int bgColor, double alpha, boolean computeDistanceMap, boolean showMaps, boolean save){
/* Load the image */
BufferedImage gtImg = ImTool.read(gtImgPath);
/* GT image width and height */
int gtWidth = gtImg.getWidth();
int gtHeight = gtImg.getHeight();
/* set the background color value */
int bgC = bgColor;
/* Set containing list of segments of reference */
TreeMap<Integer, SegReference> listOfSegs = new TreeMap<Integer, SegReference>();
/* Get all the segments contained in the GT image including its background */
SegmentByConnexityRaw sbc = new SegmentByConnexityRaw(gtImg);
LabelMatrix inputLabelMatrix = sbc.runForFullImage();
//inputLabelMatrix.print();
/* get all segments and drop the background */
TreeMap<Integer, Double[]> semanticLabels = new TreeMap<Integer, Double[]>();
for(int y=0; y < gtHeight; ++y){
for(int x=0; x < gtWidth; ++x){
int segLabNonSem = inputLabelMatrix.getLabel(x, y);
/* drop the background */
int rgbVal = gtImg.getRGB(x, y);
Color myColor = new Color(rgbVal);
rgbVal = ImTool.getRGBValueFrom(myColor.getRed(), myColor.getGreen(), myColor.getBlue());
System.out.println("\n\n rgbval: "+ rgbVal +", bgC: "+ bgC +"\n\n");
if(rgbVal != bgC){
if(!listOfSegs.containsKey(segLabNonSem)){
/* create a segment of reference object, add it to the list with its semantic label */
int semanticLabel = rgbVal;
listOfSegs.put(segLabNonSem, new SegReference(semanticLabel, gtWidth, gtHeight, gtImgPath, bgColor, alpha));
if(!semanticLabels.containsKey(semanticLabel)){
Double[] val = new Double[4];
val[0] = 0.0;
val[1] = 0.0;
val[2] = 0.0;
val[3] = 0.0;
semanticLabels.put(semanticLabel, val);
}
}
/* store the point ~ pixel in the segment of reference object */
listOfSegs.get(segLabNonSem).addGtPoint(new Point(x, y));
}
}
}
/* Use the first segment to store the information about the semantic labels */
listOfSegs.firstEntry().getValue().listOfAllSemanticLabels = semanticLabels;
/* preparing a path and a manifest file */
String path = null;
if(save){
/* set a correct path */
String folderPath[] = gtImgPath.split("//");
int lastIndex = folderPath.length - 1;
String gtImgName = folderPath[lastIndex];
String fpath[] = gtImgPath.split(gtImgName);
path = fpath[0] +"segref_("+ gtImgName +")";
/* save a manifest file if it's not already existing */
String manifPath = path +"//manifest";
File mf = new File(manifPath);
if(!mf.exists() || mf.isDirectory()){ /* create a file and register the number of segments and the 1st alpha used */
try {
/* global info on the list of segments */
new File(path).mkdir();
PrintWriter manifWriter = new PrintWriter(manifPath, "UTF-8");
manifWriter.println(listOfSegs.size()); /* save <nb_segments> */
int it = 0;
for(Entry<Integer, Double[]> entry: semanticLabels.entrySet()){
manifWriter.print(entry.getKey());
if(it < semanticLabels.size() - 1)
manifWriter.print(";");
it++;
}
manifWriter.println();
manifWriter.print(alpha);
manifWriter.close();
} catch (Exception e){
e.printStackTrace();
}
}else{
/* add the current alpha in the manifest file */
try(FileWriter fw = new FileWriter(manifPath, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw))
{
out.print(";"+ alpha); /* save alpha in the manifest file */
out.close();
bw.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
boolean visu = true;
/* visualize the crop */
if(visu){
BufferedImage imgWithBBRect = ImTool.clone(gtImg);
for(Map.Entry<Integer, SegReference> entry : listOfSegs.entrySet()){
SegReference s = entry.getValue();
System.out.println(s.index);
int realBoundingBox[] = s.computeRegionBoundingBox();
/* generate the segment crop image */
int white = 1;
int black = 0;
LabelMatrix crop = new LabelMatrix(s.bbWidth, s.bbHeight);
System.out.println("bbWidth: "+ s.bbWidth +" bbHeight: "+ s.bbHeight);
for (int j = 0; j < s.bbHeight; ++j){
for(int i = 0; i < s.bbWidth; ++i){
Point tmpPoint = new Point(i, j);
if(s.getBbIntegerPoints().contains(tmpPoint)) {
crop.setLabel(white, i, j);
}
else{
crop.setLabel(black, i, j);
}
}
}
/* show images in windows */
HashMap<Integer, Color> lut = new HashMap<Integer, Color>();
lut.put(0, Color.black);
lut.put(1, Color.white);
BufferedImage cropImg = ImTool.generateRegions(crop, lut);
ImTool.show(cropImg, 30);
/* draw bounding boxes */
Random rand = new Random();
int r = rand.nextInt();
int g = rand.nextInt();
int b = rand.nextInt();
int color = ImTool.getRGBValueFrom(r, g, b);
ImTool.drawRectangleOn(imgWithBBRect,
realBoundingBox[0],
realBoundingBox[1],
realBoundingBox[2],
realBoundingBox[3],
color);
}
ImTool.show(imgWithBBRect, 30);
}
/* Compute or not the distance map */
if(computeDistanceMap)
for(Map.Entry<Integer, SegReference> entry : listOfSegs.entrySet()){
SegReference s = entry.getValue();
s.muMap = DistanceMap.compute(s, alpha, showMaps, path);
}
int nbRegions = inputLabelMatrix.getNbRegions();
Log.println("Segment of reference", "number of segments including the background segments : "+ nbRegions);
Log.println("Segment of reference", "number of semantic labels : "+ semanticLabels.size());
return listOfSegs;
}
/**
* Convert an x coordinate of the bounding box to the real x coordinate of the input gt image.
* @param x coordinate in the bounding box.
* @return X real coordinate in the gt input image.
*/
public int getSegRealX(int x) {
return this.boundingBox[0] + x;
}
/**
* Convert an y coordinate of the bounding box to the real y coordinate of the input gt image.
* @param y coordinate in the bounding box.
* @return y real coordinate in the gt input image.
*/
public int getSegRealY(int y) {
return this.boundingBox[2] + y;
}
/**
* Convert the value of each point from the GT image to the bounding box;
*/
public void gtToBB(){
int xdecal = this.boundingBox[0];
int ydecal = this.boundingBox[2];
this.bbPoints = new ArrayList<Point>();
for(Point pixel : this.gtPoints){
int xGt = pixel.x; // X POSITION OF THE POINT IN THE GT IMAGE.
int yGt = pixel.y; // Y POSITION OF THE POINT IN THE GT IMAGE.
Point newPixel = new Point((xGt - xdecal), (yGt - ydecal));
this.bbPoints.add(newPixel);
}
}
// /**
// * Initialize the background color picked from the GT image.
// * @param bgColor
// */
// private void initBgColor(BgColor bgColor) {
//
// switch(bgColor){
// case WHITE:
// this.bgColor = 255;
// break;
// case BLACK:
// this.bgColor = 0;
// break;
// default :
// this.bgColor = 0;
// break;
// }
//
// }
// /**
// * Possible background color of the GT image.
// *
// */
// public enum BgColor{
// WHITE,
// BLACK
// }
/**
* Retain the best matching node 'n' and the associated similarity score lambda(S_i).
* @param n
* @param lambda
*/
public void setBestMatchedNode(Node n, double lambda){
this.bestN = n;
this.bestSimilarityScore = lambda;
}
/**
* Create an image representing the segment and show it in a window.
* @param percent defines how the image covers the screen
*
* Example of values are:
* <li> {@link ImFrame#IMAGE_REAL_SIZE }
* <li> {@link ImFrame#IMAGE_DEFAULT_SIZE }
*/
public void show(int percent) {
ImTool.show(this.toBufferedImage(), percent, "S-"+ this.index);
}
public static BufferedImage showBoundingBoxes(TreeMap<Integer, SegReference> segReferences, BufferedImage image, int percent, String title) {
BufferedImage imgWithBBRect = ImTool.clone(image);
for(Map.Entry<Integer, SegReference> entry : segReferences.entrySet()){
SegReference s = entry.getValue();
s.show(percent);
/* draw bounding boxes */
Random rand = new Random();
int r = rand.nextInt();
int g = rand.nextInt();
int b = rand.nextInt();
int color = ImTool.getRGBValueFrom(r, g, b);
ImTool.drawRectangleOn(imgWithBBRect,
s.realBoundingBox[0],
s.realBoundingBox[1],
s.realBoundingBox[2],
s.realBoundingBox[3],
color);
}
ImTool.show(imgWithBBRect, percent, title);
return imgWithBBRect;
}
public int size(){
return this.gtPoints.size();
}
public BufferedImage toBufferedImage() {
this.computeRegionBoundingBox();
/* Generate the segment crop image */
int white = 1;
int black = 0;
LabelMatrix crop = new LabelMatrix(this.bbWidth, this.bbHeight);
for (int j = 0; j < this.bbHeight; ++j){
for(int i = 0; i < this.bbWidth; ++i){
Point tmpPoint = new Point(i, j);
if(this.getBbIntegerPoints().contains(tmpPoint)) {
crop.setLabel(white, i, j);
}
else{
crop.setLabel(black, i, j);
}
}
}
/* Generate a buffered image from the label matrix */
HashMap<Integer, Color> lut = new HashMap<Integer, Color>();
lut.put(white, Color.white);
lut.put(black, Color.black);
return ImTool.generateRegions(crop, lut);
}
/**
* From a saved file, get all segments. <br>
* @param path Folder containing the saved files.
* @param alpha
* @param visu
* @return
*/
// public static TreeMap<Integer, SegReference> getSegReferences(String path, double alpha, boolean visu) {
//
// /* Set containing list of segments of reference */
// TreeMap<Integer, SegReference> listOfSegs = SegReference.getSegReferences(path, visu);
//
// /* fill the distance map and the mu map */
// String line, lineElems[];
// String sep = ";";
// try{
//
// for(Entry<Integer,SegReference> entry: listOfSegs.entrySet()){
//
// SegReference s = entry.getValue();
//
// String distancePath = path +"//dist-"+ s.index +"-"+ alpha +".csv";
// String muPath = path +"//mu-"+ s.index +"-"+ alpha +".csv";
// BufferedReader dBr = new BufferedReader(new FileReader(distancePath));
// BufferedReader mBr = new BufferedReader(new FileReader(muPath));
// String line2, lineElems2[];
// s.muMap = new double[s.bbWidth][s.bbHeight][2];
// for(int h=0; h<s.bbHeight; ++h){
// line = dBr.readLine(); /* got one row from the distance file */
// lineElems = line.split(sep);
// line2 = mBr.readLine(); /* got one row from the mu file */
// lineElems2 = line2.split(sep);
// for(int w=0; w<s.bbWidth; ++w){
//
// s.muMap[w][h][0] = Double.parseDouble(lineElems[w]); /* set the distance value */
// s.muMap[w][h][1] = Double.parseDouble(lineElems2[w]); /* set the mu value */
//
// }
// }
// dBr.close();
// mBr.close();
//
// }
//
// }catch(Exception e){
// e.printStackTrace();
// }
//
// /* verification if the mu map for the specified alpha is not already computed and stored in a file */
// String manifPath = path +"//manifest";
// try {
//
// BufferedReader br = new BufferedReader(new FileReader(manifPath));
// line = br.readLine(); /* got the <nb_segs> */
// line = br.readLine(); /* got the <lab1;lab2;...> */
//
// line = br.readLine(); /* got the list of alphas */
// lineElems = line.split(";");
// boolean found = false;
// int i = 0;
// while(!found && i < lineElems.length){
//
// if(Double.parseDouble(lineElems[i]) == alpha){
// found = true;
// }
// i++;
//
// }
//
// br.close();
//
// if(!found){ /* compute an new mu map if the specified alpha is not found */
//
// for(Map.Entry<Integer, SegReference> entry : listOfSegs.entrySet()){
//
// SegReference s = entry.getValue();
// s.muMap = DistanceMap.compute(s, alpha, false, path);
// s.margin = (int)(Math.log((1 / 0.001) - 1) / alpha); /* en px */
//
// }
//
// /* add the current alpha in the manifest file */
// try(FileWriter fw = new FileWriter(manifPath, true);
// BufferedWriter bw = new BufferedWriter(fw);
// PrintWriter out = new PrintWriter(bw))
// {
// out.print(";"+ alpha); /* save alpha in the manifest file */
// out.close();
// bw.close();
// fw.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
//
// }
//
// } catch (Exception e) {
// e.printStackTrace();
// }
//
//
// return listOfSegs;
// }
}
| 30.471055 | 188 | 0.617401 |
1e76d3629051c22a2099db90d2f37b4e39010c10 | 3,432 | package com.restaurant.dinner.admin.controller.base;
import com.restaurant.dinner.admin.ProjectProperties;
import com.restaurant.dinner.api.pojo.po.admin.TbSysUser;
import com.restaurant.dinner.api.pojo.vo.JsonObjectVo;
import com.restaurant.dinner.api.recipe.admin.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
* 登录接口
*
* @date 2016-11-06
* @author 赵梓彧 - [email protected]
*/
@Controller
@RequestMapping(value = "/")
public class LoginController {
private final static String LOGIN_MODE_NAME_OR_PHONE = "1";//登录方式:用户名或手机号(默认)
private final static String LOGIN_MODE_PHONE_IDENTIFYING_CODE = "2";//登录方式:手机验证码
private final static String LOGIN_MODE_QR_CODE = "3";//登录方式:二维码扫描
@Autowired
private SysUserService sysUserService;
@RequestMapping("/doLogin")
@ResponseBody
public JsonObjectVo<Object> doLogin(HttpServletRequest request, HttpSession httpSession) {
JsonObjectVo<Object> jsonObjectVo = new JsonObjectVo<>();
String loginMode = request.getParameter("mode");//登录方式(根据登录方式判断所需的请求参数)
TbSysUser user = null;
if (loginMode == null || LOGIN_MODE_NAME_OR_PHONE.equals(loginMode)) {
// 登录方式:用户名或手机号(默认)
String logincode = request.getParameter("code");
if (logincode == null) {
jsonObjectVo.setSuccess(false);
jsonObjectVo.setMsg("未输入用户名");
return jsonObjectVo;
}
String password = request.getParameter("password");
if (password == null) {
jsonObjectVo.setSuccess(false);
jsonObjectVo.setMsg("未输入密码");
return jsonObjectVo;
}
try {
user = sysUserService.loginByNameOrPhone(logincode, password);
} catch (Exception e) {
e.printStackTrace();
jsonObjectVo.setSuccess(false);
jsonObjectVo.setMsg(e.getMessage());
return jsonObjectVo;
}
} else if (LOGIN_MODE_PHONE_IDENTIFYING_CODE.equals(loginMode)) {
// 登录方式:手机验证码
} else if (LOGIN_MODE_QR_CODE.equals(loginMode)) {
// 登录方式:二维码扫描
} else {
jsonObjectVo.setSuccess(false);
jsonObjectVo.setMsg("登录方式不存在");
return jsonObjectVo;
}
if (user != null) {
httpSession.setAttribute(ProjectProperties.SESSION_USER_FULL_NAME, user.getFullName());
httpSession.setAttribute(ProjectProperties.SESSION_USER_ID, user.getId());
jsonObjectVo.setSuccess(true);
return jsonObjectVo;
} else {
jsonObjectVo.setSuccess(false);
jsonObjectVo.setMsg("用户名或密码错误");
return jsonObjectVo;
}
}
@RequestMapping("/doLogout")
public String doLogout(ModelMap map, HttpSession httpSession) {
httpSession.removeAttribute(ProjectProperties.SESSION_USER_FULL_NAME);
httpSession.removeAttribute(ProjectProperties.SESSION_USER_ID);
return "redirect:/login";// 跳转到[/login]处理器
}
}
| 36.903226 | 99 | 0.6588 |
4fca8674a11c67a60335e3c94a1e72a4e202335a | 4,908 | /*
* #%L
* AbstractSaslAuthenticator.java - mongodb-async-driver - Allanbank Consulting, Inc.
* %%
* Copyright (C) 2011 - 2014 Allanbank Consulting, 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.
* #L%
*/
package com.allanbank.mongodb.client.connection.auth;
import javax.security.sasl.SaslClient;
import javax.security.sasl.SaslException;
import com.allanbank.mongodb.Credential;
import com.allanbank.mongodb.bson.builder.BuilderFactory;
import com.allanbank.mongodb.bson.builder.DocumentBuilder;
import com.allanbank.mongodb.client.callback.ReplyCallback;
import com.allanbank.mongodb.client.connection.Connection;
import com.allanbank.mongodb.client.message.Command;
import com.allanbank.mongodb.error.MongoDbAuthenticationException;
/**
* AbstractSaslAuthenticator provides the basic logic for a SASL based
* authenticator.
*
* @api.no This class is <b>NOT</b> part of the drivers API. This class may be
* mutated in incompatible ways between any two releases of the
* extensions.
* @copyright 2014, Allanbank Consulting, Inc., All Rights Reserved
*/
public abstract class AbstractSaslAuthenticator
extends AbstractAuthenticator {
/** An empty set of bytes. */
public static final byte[] EMPTY_BYTES = SaslResponseCallback.EMPTY_BYTES;
/** The database to authenticate against. */
public static final String EXTERNAL = SaslResponseCallback.EXTERNAL;
/**
* Creates a new AbstractSaslAuthenticator.
*/
public AbstractSaslAuthenticator() {
super();
}
/**
* Starts to authenticate the user with the specified credentials.
*
* @param credentials
* The credentials to use to login to the database.
* @param connection
* The connection to authenticate the user with.
* @throws MongoDbAuthenticationException
* On a failure in the protocol to authenticate the user on the
* connection.
*/
public void startAuthentication(final Credential credentials,
final Connection connection) throws MongoDbAuthenticationException {
try {
final SaslClient client = createSaslClient(credentials, connection);
if (client != null) {
byte[] payload = EMPTY_BYTES;
if (client.hasInitialResponse()) {
payload = client.evaluateChallenge(payload);
}
sendStart(payload, connection, new SaslResponseCallback(client,
connection, myResults));
}
else {
throw new MongoDbAuthenticationException(
"Could not locate a SASL provider.");
}
}
catch (final SaslException e) {
throw new MongoDbAuthenticationException(e);
}
}
/**
* Creates the SASL Client.
*
* @param credentials
* The credentials to use in creating the client.
* @param connection
* The connection we are authenticating against.
* @return The {@link SaslClient} for the authentication.
* @throws MongoDbAuthenticationException
* On an authentication error.
* @throws SaslException
* On a SASL error.
*/
protected abstract SaslClient createSaslClient(
final Credential credentials, final Connection connection)
throws MongoDbAuthenticationException, SaslException;
/**
* The SASL mechanism name.
*
* @return The SASL mechanism name.
*/
protected abstract String getMechanism();
/**
* Sends an initial request to authenticate with the server.
*
* @param payload
* The payload for the request.
* @param connection
* The connection to authenticate.
* @param callback
* The callback to handle the reply.
*/
protected void sendStart(final byte[] payload, final Connection connection,
final ReplyCallback callback) {
final DocumentBuilder cmd = BuilderFactory.start();
cmd.add("saslStart", 1);
cmd.add("mechanism", getMechanism());
cmd.add("payload", payload);
connection.send(
new Command(EXTERNAL, Command.COMMAND_COLLECTION, cmd.build()),
callback);
}
} | 35.565217 | 85 | 0.650774 |
f45f2d1a7c077db9d6f15d548441f25b3a2bbc0d | 7,039 | package com.wavefront.agent.handlers;
import com.wavefront.agent.data.EntityPropertiesFactory;
import com.wavefront.common.SamplingLogger;
import com.wavefront.api.agent.ValidationConfiguration;
import com.wavefront.data.ReportableEntityType;
import org.apache.commons.lang.math.NumberUtils;
import wavefront.report.Histogram;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.logging.Logger;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* Caching factory for {@link ReportableEntityHandler} objects. Makes sure there's only one handler
* for each {@link HandlerKey}, which makes it possible to spin up handlers on demand at runtime,
* as well as redirecting traffic to a different pipeline.
*
* @author [email protected]
*/
public class ReportableEntityHandlerFactoryImpl implements ReportableEntityHandlerFactory {
private static final Logger logger = Logger.getLogger("sampling");
public static final Logger VALID_POINTS_LOGGER = new SamplingLogger(
ReportableEntityType.POINT, Logger.getLogger("RawValidPoints"),
getSystemPropertyAsDouble("wavefront.proxy.logpoints.sample-rate"),
"true".equalsIgnoreCase(System.getProperty("wavefront.proxy.logpoints")), logger::info);
public static final Logger VALID_HISTOGRAMS_LOGGER = new SamplingLogger(
ReportableEntityType.HISTOGRAM, Logger.getLogger("RawValidHistograms"),
getSystemPropertyAsDouble("wavefront.proxy.logpoints.sample-rate"),
"true".equalsIgnoreCase(System.getProperty("wavefront.proxy.logpoints")), logger::info);
private static final Logger VALID_SPANS_LOGGER = new SamplingLogger(
ReportableEntityType.TRACE, Logger.getLogger("RawValidSpans"),
getSystemPropertyAsDouble("wavefront.proxy.logspans.sample-rate"), false, logger::info);
private static final Logger VALID_SPAN_LOGS_LOGGER = new SamplingLogger(
ReportableEntityType.TRACE_SPAN_LOGS, Logger.getLogger("RawValidSpanLogs"),
getSystemPropertyAsDouble("wavefront.proxy.logspans.sample-rate"), false, logger::info);
private static final Logger VALID_EVENTS_LOGGER = new SamplingLogger(
ReportableEntityType.EVENT, Logger.getLogger("RawValidEvents"),
getSystemPropertyAsDouble("wavefront.proxy.logevents.sample-rate"), false, logger::info);
protected final Map<String, Map<ReportableEntityType, ReportableEntityHandler<?, ?>>> handlers =
new ConcurrentHashMap<>();
private final SenderTaskFactory senderTaskFactory;
private final int blockedItemsPerBatch;
private final ValidationConfiguration validationConfig;
private final Logger blockedPointsLogger;
private final Logger blockedHistogramsLogger;
private final Logger blockedSpansLogger;
private final Function<Histogram, Histogram> histogramRecompressor;
private final EntityPropertiesFactory entityPropertiesFactory;
/**
* Create new instance.
*
* @param senderTaskFactory SenderTaskFactory instance used to create SenderTasks
* for new handlers.
* @param blockedItemsPerBatch controls sample rate of how many blocked points are written
* into the main log file.
* @param validationConfig validation configuration.
*/
public ReportableEntityHandlerFactoryImpl(
final SenderTaskFactory senderTaskFactory, final int blockedItemsPerBatch,
@Nonnull final ValidationConfiguration validationConfig, final Logger blockedPointsLogger,
final Logger blockedHistogramsLogger, final Logger blockedSpansLogger,
@Nullable Function<Histogram, Histogram> histogramRecompressor,
EntityPropertiesFactory entityPropertiesFactory) {
this.senderTaskFactory = senderTaskFactory;
this.blockedItemsPerBatch = blockedItemsPerBatch;
this.validationConfig = validationConfig;
this.blockedPointsLogger = blockedPointsLogger;
this.blockedHistogramsLogger = blockedHistogramsLogger;
this.blockedSpansLogger = blockedSpansLogger;
this.histogramRecompressor = histogramRecompressor;
this.entityPropertiesFactory = entityPropertiesFactory;
}
@SuppressWarnings("unchecked")
@Override
public <T, U> ReportableEntityHandler<T, U> getHandler(HandlerKey handlerKey) {
Consumer<Long> receivedRateSink = rate ->
entityPropertiesFactory.get(handlerKey.getEntityType()).
reportReceivedRate(handlerKey.getHandle(), rate);
return (ReportableEntityHandler<T, U>) handlers.computeIfAbsent(handlerKey.getHandle(),
h -> new ConcurrentHashMap<>()).computeIfAbsent(handlerKey.getEntityType(), k -> {
switch (handlerKey.getEntityType()) {
case POINT:
return new ReportPointHandlerImpl(handlerKey, blockedItemsPerBatch,
senderTaskFactory.createSenderTasks(handlerKey), validationConfig, true,
receivedRateSink, blockedPointsLogger, VALID_POINTS_LOGGER, null);
case HISTOGRAM:
return new ReportPointHandlerImpl(handlerKey, blockedItemsPerBatch,
senderTaskFactory.createSenderTasks(handlerKey), validationConfig, true,
receivedRateSink, blockedHistogramsLogger, VALID_HISTOGRAMS_LOGGER,
histogramRecompressor);
case SOURCE_TAG:
return new ReportSourceTagHandlerImpl(handlerKey, blockedItemsPerBatch,
senderTaskFactory.createSenderTasks(handlerKey), receivedRateSink,
blockedPointsLogger);
case TRACE:
return new SpanHandlerImpl(handlerKey, blockedItemsPerBatch,
senderTaskFactory.createSenderTasks(handlerKey),
validationConfig, receivedRateSink, blockedSpansLogger, VALID_SPANS_LOGGER,
() -> entityPropertiesFactory.getGlobalProperties().getDropSpansDelayedMinutes());
case TRACE_SPAN_LOGS:
return new SpanLogsHandlerImpl(handlerKey, blockedItemsPerBatch,
senderTaskFactory.createSenderTasks(handlerKey), receivedRateSink,
blockedSpansLogger, VALID_SPAN_LOGS_LOGGER);
case EVENT:
return new EventHandlerImpl(handlerKey, blockedItemsPerBatch,
senderTaskFactory.createSenderTasks(handlerKey), receivedRateSink,
blockedPointsLogger, VALID_EVENTS_LOGGER);
default:
throw new IllegalArgumentException("Unexpected entity type " +
handlerKey.getEntityType().name() + " for " + handlerKey.getHandle());
}
});
}
@Override
public void shutdown(@Nonnull String handle) {
if (handlers.containsKey(handle)) {
handlers.get(handle).values().forEach(ReportableEntityHandler::shutdown);
}
}
private static double getSystemPropertyAsDouble(String propertyName) {
String sampleRateProperty = propertyName == null ? null : System.getProperty(propertyName);
return NumberUtils.isNumber(sampleRateProperty) ? Double.parseDouble(sampleRateProperty) : 1.0d;
}
}
| 50.640288 | 100 | 0.756926 |
216c9bf8e19623bdb9ab0f1918f9abd7802c76e1 | 359 | package dev.cheerfun.pixivic.biz.web.collection.dto;
import lombok.Data;
/**
* @author OysterQAQ
* @version 1.0
* @date 2020/5/2 8:01 下午
* @description UpdateIllustrationOrderDTO
*/
@Data
public class UpdateIllustrationOrderDTO {
private Integer upIllustrationId;
private Integer lowIllustrationId;
private Integer reOrderIllustrationId;
}
| 21.117647 | 52 | 0.760446 |
6bb8b6bc60cc560363a82acec40dceaa048537e8 | 2,540 | package minevalley.core.api.corporations;
import minevalley.core.api.Registered;
import minevalley.core.api.economy.BankAccount;
import java.util.List;
public interface Group extends Registered {
/**
* Gets the id of this group.
*
* @return id of group
*/
int getId();
/**
* Gets the name of this group.
*
* @return name of group
*/
String getName();
/**
* Sets the name of this group.
*
* @return Result of the rename
*/
RenameFeedback changeName(String name);
/**
* Gets this group's description
*
* @return description as string
*/
String getDescription();
/**
* Sets the description of this group.
*
* @param description description as string
*/
void setDescription(String description);
/**
* Changes the description of this group. Max. length = 150 chars; Min. length = 15 chars
*
* @param description description as string
* @return result of the description change
*/
RenameFeedback changeDescription(String description);
/**
* Gets whether this group is a company (otherwise: organization).
*
* @return true, if group is company
*/
boolean isCompany();
/**
* Gets this group's owner.
*
* @return unique id of owner as string
*/
String getOwner();
/**
* Gets a list of all operators.
*
* @return list of all operators' unique ids
*/
List<String> getOperators();
/**
* Gets the department, which is markes as default.
*
* @return group's default department
*/
Department getDefaultDepartment();
/**
* Gets a list of all departments.
*
* @return departments as list
*/
List<Department> getDepartments();
/**
* Removes the member with the specific unique id from this group.
*
* @param uniqueId member to remove
*/
void removeMember(String uniqueId);
/**
* Adds a member with the specific unique id to this group.
*
* @param uniqueId member to add
*/
void addMember(String uniqueId);
/**
* Gets the bank account of this group.
*
* @return bank account of group
*/
BankAccount getBankAccount();
/**
* Deletes this group.
*/
void delete();
enum RenameFeedback {
FORBIDDEN_CHARACTERS,
FORBIDDEN_WORDS,
ALREADY_USED,
TOO_LONG,
TOO_SHORT,
SUCCESS
}
}
| 20.650407 | 93 | 0.588583 |
df83c1cdb9a5218283b667719526cbba89902e85 | 849 | package uk.co.stikman.utils;
import java.util.HashMap;
import java.util.Map;
public class MimeTypes {
public static final Map<String, String> MIME_TYPES = new HashMap<>();
static {
MIME_TYPES.put(".css", "text/css");
MIME_TYPES.put(".js", "text/javascript");
MIME_TYPES.put(".html", "text/html");
MIME_TYPES.put(".htm", "text/html");
MIME_TYPES.put(".jpg", "image/jpeg");
MIME_TYPES.put(".jpeg", "image/jpeg");
MIME_TYPES.put(".png", "image/png");
MIME_TYPES.put(".gif", "image/gif");
}
public static String find(String filename) {
return find(filename, "application/octet-stream");
}
public static String find(String filename, String def) {
String s = filename;
int pos = s.lastIndexOf('.');
if (pos != -1)
s = s.substring(pos);
String x = MIME_TYPES.get(s);
if (x == null)
return def;
return x;
}
}
| 24.257143 | 70 | 0.656066 |
64d6cea235efbf895987581afc82f14882b24458 | 2,701 | package com.mooc.ppjoke.utils;
import android.content.ComponentName;
import androidx.fragment.app.FragmentActivity;
import androidx.navigation.ActivityNavigator;
import androidx.navigation.NavController;
import androidx.navigation.NavGraph;
import androidx.navigation.NavGraphNavigator;
import androidx.navigation.NavigatorProvider;
import androidx.navigation.fragment.FragmentNavigator;
import com.mooc.libcommon.global.AppGlobals;
import com.mooc.ppjoke.FixFragmentNavigator;
import com.mooc.ppjoke.model.Destination;
import java.util.HashMap;
public class NavGraphBuilder {
//需要和NavController相关联,所以该方法的参数就为此
//需要外部传入activity和containId
public static void build(NavController controller,FragmentActivity activity,int containerId){
//通过响应的Navigate创建相应的页面节点
NavigatorProvider provider = controller.getNavigatorProvider();
//分别获取FragmentNavigator和ActivityNavigator对象
// FragmentNavigator fragmentNavigator = provider.getNavigator(FragmentNavigator.class);
//使用自建的导航器FixFragmentNavigator
FixFragmentNavigator fragmentNavigator=new FixFragmentNavigator(activity,activity.getSupportFragmentManager(),containerId);
//创建完成之后需要添加到NavigatorProvider的hashMap中去
provider.addNavigator(fragmentNavigator);
ActivityNavigator activityNavigator=provider.getNavigator(ActivityNavigator.class);
//后面的数据要添加到改NavGraph中
NavGraph navGraph=new NavGraph(new NavGraphNavigator(provider));
HashMap<String, Destination> destConfig=AppConfig.getDestConfig();
for (Destination value : destConfig.values()) {
if (value.isFragment){
FragmentNavigator.Destination destination=fragmentNavigator.createDestination();
//向destination中填相应的字段
destination.setClassName(value.className);
destination.setId(value.id);
destination.addDeepLink(value.pageUrl);
navGraph.addDestination(destination);
}else {
ActivityNavigator.Destination destination=activityNavigator.createDestination();
destination.setId(value.id);
destination.addDeepLink(value.pageUrl);
destination.setComponentName(new ComponentName(AppGlobals.getApplication().getPackageName(),value.className));
navGraph.addDestination(destination);
}
//如果value是默认启动页
if (value.asStarter){
navGraph.setStartDestination(value.id);
}
}
//将navGraph赋值给controller
controller.setGraph(navGraph);
}
}
| 37.513889 | 132 | 0.701222 |
36c7bc3b7a72f7ec88f3f33b05e4aced3c9155b8 | 950 | package org.nautilus.plugin.factory;
import java.util.ArrayList;
import java.util.List;
import org.nautilus.plugin.extension.SelectionExtension;
import org.nautilus.plugin.extension.selection.BinaryTournamentWithRankingAndCrowdingDistanceSelectionExtension;
import org.uma.jmetal.operator.SelectionOperator;
import org.uma.jmetal.solution.Solution;
public class SelectionFactory {
private List<SelectionExtension> extensions = new ArrayList<>();
public SelectionFactory() {
extensions.add(new BinaryTournamentWithRankingAndCrowdingDistanceSelectionExtension());
}
public List<SelectionExtension> getExtensions() {
return extensions;
}
public SelectionOperator<List<? extends Solution<?>>, ? extends Solution<?>> getSelection(String selectionId) {
for (SelectionExtension extension : getExtensions()) {
if (selectionId.equalsIgnoreCase(extension.getId())) {
return extension.getSelection();
}
}
return null;
}
}
| 27.142857 | 112 | 0.789474 |
4e569df2f27f53b3523e1b1d15cf2c199a1be9b2 | 370 | package com.cn.luckymorning.study.optional;
/**
* Main
*
* @author lucky_morning
* @group com.cn.luckymorning.study.optional
* @date 2020/8/21 13:51
*/
public class Main {
public static void main(String[] args) {
System.out.println(OptionalDemo.testOptionalOrElse(null));
System.out.println(OptionalDemo.testOptionalOrElseGet(null));
}
}
| 21.764706 | 69 | 0.697297 |
d221688fc2520ac3e473f3706bbbe41614008cc4 | 1,355 | package cyclops.data;
import cyclops.reactive.ReactiveSeq;
import org.junit.Test;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
public class HashSet2Test {
@Test
public void duplicates(){
assertThat(HashSet.of(1,2,1,2,1,2).size(),equalTo(2));
}
@Test
public void nines(){
/** HashSet<Integer> hs = HashSet.<Integer>empty().plus(9).plus(-10).plus(8)
.plus(-9);
System.out.println("-9?"+hs.containsValue(-9));
**/
System.out.println(HashSet.<Long>empty().plus(9l).plus(-10l)
.plus(8l));
// .plus(-9l));
}
@Test
public void reversedRangeLongWithReverse(){
HashSet<Long> s = HashSet.rangeLong(10, -10);
// HashSet<Long> s = (HashSet)HashSet.rangeLong(10, -10).reverse();
//System.out.println(HashSet.fromStream(ReactiveSeq.rangeLong(10,-10).reverse()));
System.out.println("******************");
System.out.println("******************");
System.out.println(s.reverse());
/** System.out.println(((HashSet)s.reverse()).getMap());
assertThat(HashSet.rangeLong(10, -10).reverse().count(),equalTo(20L));
**/
}
}
//[0,-1,1,-2,2,-3,3,-4,4,-5,5,-6,6,-7,7,-8,-9,8,9,-10,9,-10]
//[-1,0,-2,1,-3,2,-4,3,-5,4,-6,5,-7,6,-8,7,-9,8,-10,9] | 32.261905 | 89 | 0.564576 |
553ebc82d7353a6489a0ab1c388b19bd4d851907 | 3,410 | package edu.uw.covidsafe.ble;
import android.bluetooth.le.AdvertiseCallback;
import android.bluetooth.le.AdvertiseSettings;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.os.ParcelUuid;
import android.util.Log;
import edu.uw.covidsafe.utils.ByteUtils;
import edu.uw.covidsafe.utils.Constants;
import edu.uw.covidsafe.utils.Utils;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class BluetoothScanHelper implements Runnable {
public static AdvertiseCallback advertiseCallback = new AdvertiseCallback() {
@Override
public void onStartSuccess(AdvertiseSettings settingsInEffect) {
Log.e("ble", "BLE advertisement added successfully "+settingsInEffect.toString());
}
@Override
public void onStartFailure(int errorCode) {
Log.e("ble", "Failed to add BLE advertisement, reason: " + errorCode);
}
};
static Context cxt;
public BluetoothScanHelper(Context cxt) {
this.cxt = cxt;
}
@Override
public void run() {
Log.e("ble","mytask-run ");
ScanSettings.Builder builder = new ScanSettings.Builder();
builder.setScanMode(ScanSettings.SCAN_MODE_LOW_POWER);
ScanFilter filter = new ScanFilter.Builder()
.setServiceUuid(new ParcelUuid(Constants.BEACON_SERVICE_UUID))
.build();
List<ScanFilter> filters = new LinkedList<ScanFilter>();
filters.add(filter);
Constants.scannedUUIDs = new HashSet<String>();
Constants.scannedUUIDsRSSIs = new HashMap<String,Integer>();
Constants.blueAdapter.getBluetoothLeScanner().startScan(filters, builder.build(), mLeScanCallback);
}
public static ScanCallback mLeScanCallback =
new ScanCallback() {
@Override
public void onScanResult(int callbackType, final ScanResult result) {
super.onScanResult(callbackType, result);
Map<ParcelUuid, byte[]> map = result.getScanRecord().getServiceData();
byte[] data = map.get(new ParcelUuid(Constants.BEACON_SERVICE_UUID));
Log.e("ble","onscanresult "+(data==null));
if (data != null && data.length == 16) {
String contactUuid = ByteUtils.byte2UUIDstring(data);
// Log.e("uuid","CONTACT "+contactUuid);
int rssi = result.getRssi();
if (Constants.scannedUUIDs != null &&
!Constants.scannedUUIDs.contains(contactUuid) &&
rssi >= Constants.rssiCutoff) {
// String[] elts = contactUuid.split("-");
Constants.scannedUUIDs.add(contactUuid);
Constants.scannedUUIDsRSSIs.put(contactUuid, rssi);
}
}
}
@Override
public void onScanFailed(int errorCode) {
super.onScanFailed(errorCode);
Log.e("ble", "error onscanfailed "+errorCode);
}
};
}
| 37.472527 | 107 | 0.607918 |
6e3258dc9af5ca5eb061c8d96a1e87bc0fb03b71 | 3,057 | package com.manoelcampos.exportador;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Classe abstrata que fornece uma implementação base para as subclasses
* que definem formatos específicos de exportação de dados.
*
* @author Manoel Campos da Silva Filho
*/
public abstract class AbstractExportadorListaProduto implements ExportadorListaProduto {
/**
* Colunas a serem exibidas na tabela gerada no processo de exportação.
*/
protected static final List<String> TITULOS_COLUNAS = Arrays.asList("ID", "Descrição", "Marca", "Modelo", "Estoque");
private List<Coluna> colunas;
public AbstractExportadorListaProduto() {
colunas = new ArrayList<>();
addNewColuna(Produto::getId, "Código");
addNewColuna(Produto::getDescricao, "Descrição");
}
protected void addCOluna(Coluna coluna) {
getColunas().add(coluna);
}
@Override
public final String exportar(List<Produto> listaProdutos) {
final StringBuilder sb = new StringBuilder();
sb.append(abrirTabela());
sb.append(abrirLinha());
for (Coluna coluna : getColunas()) {
sb.append(coluna.exportarCabecalho());
}
sb.append(fecharLinha());
sb.append("\n");
sb.append(fecharLinhaTitulos());
gerarLinhasProdutos(sb, listaProdutos);
sb.append(fecharTabela());
return sb.toString();
}
/**
* Gera o texto representando todas as linhas de uma tabela (em um formato definido pelas subclasses)
* contendo os dados dos produtos na lista de produtos.
*
* @param sb {@link StringBuilder} onde o texto gerado será adicionado
* @param listaProdutos
*/
private void gerarLinhasProdutos(StringBuilder sb, List<Produto> listaProdutos) {
for (Produto produto : listaProdutos) {
sb.append(gerarColunasLinha(produto));
}
}
/**
* Gera o texto representando uma única linha de uma tabela (em um formato definido pelas subclasses).
*
* @param produto valores a serem exibidos nas colunas, que podem ser:
* (i) os títulos das colunas (caso esteja sendo gerada a linha de cabeçalho da tabela) ou
* (ii) os valores de uma linha da tabela (caso esteja sendo gerado uma linha de conteúdo da tabela).
* Neste último caso, tal parâmetro deve conter os valores dos atributos de um objeto da lista de produtos.
* @return uma String representando a linha gerada com os valores
*/
protected String gerarColunasLinha(Produto produto) {
StringBuilder sb = new StringBuilder();
sb.append(abrirLinha());
for (Coluna coluna : getColunas()) {
sb.append(coluna.exportarDados(produto));
}
sb.append(fecharLinha());
sb.append("\n");
return sb.toString();
}
/**
* @return the colunas
*/
protected List<Coluna> getColunas() {
return colunas;
}
}
| 33.228261 | 126 | 0.643114 |
9e3157f15ba2990d331d4dc4cc5a3d6221586e5b | 458 | package lightsearch.server.initialization;
import org.springframework.stereotype.Service;
@Service("serverInitializer")
public class ServerInitializerImpl implements ServerInitializer {
private final BlacklistCreator blacklistCreator;
public ServerInitializerImpl(BlacklistCreator blacklistCreator) {
this.blacklistCreator = blacklistCreator;
}
@Override
public void initialize() {
blacklistCreator.create();
}
}
| 24.105263 | 69 | 0.766376 |
b07da2f2d7634a6c118664023480065eb091ebcb | 1,071 | package roundone.helper;
import roundone.helper.graph.Graph;
import roundone.helper.graph.Vertex;
import java.util.*;
public class TopologicalSort<T> {
private final Graph<T> graph;
private Stack<Vertex<T>> stack;
private Set<Vertex<T>> visited;
public TopologicalSort(Graph<T> graph) {
this.graph = graph;
this.stack = new Stack<>();
this.visited = new HashSet<>();
}
public List<Vertex<T>> sort() {
for (Vertex<T> tVertex : graph.getAllVertex()) {
if (!visited.contains(tVertex)) {
sortUtil(tVertex);
}
}
List<Vertex<T>> sortedElement = new ArrayList<>();
while (!stack.empty()) {
sortedElement.add(stack.pop());
}
return sortedElement;
}
private void sortUtil(Vertex<T> vertex) {
visited.add(vertex);
for (Vertex<T> vrtx : vertex.getAdjacentVertex()) {
if (!visited.contains(vrtx)) {
sortUtil(vrtx);
}
}
stack.add(vertex);
}
}
| 23.8 | 59 | 0.558357 |
4dcc5c21cfa9b816cf11a5ac3bc8b925be834eff | 1,765 | package com.mcml.space.patches;
import com.mcml.space.config.Patches;
import com.mcml.space.core.DataManager;
import com.mcml.space.core.EscapeLag;
import com.mcml.space.util.AzureAPI;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class AntiCrashOP implements Listener {
public static List<String> TheOps = new ArrayList();
public static void init() {
if (Patches.AntiCrashOPenable) {
AzureAPI.log("子模块 - 反崩溃OP 已启动");
if (!DataManager.data.isList("OpList")) {
Iterator var0 = Bukkit.getOperators().iterator();
while (var0.hasNext()) {
OfflinePlayer offplayer = (OfflinePlayer) var0.next();
TheOps.add(offplayer.getName());
}
AzureAPI.log("第一次运行模块,正在导入现有OP: " + TheOps);
save();
DataManager.save();
}
TheOps = DataManager.data.getStringList("OpList");
Bukkit.getPluginManager().registerEvents(new AntiCrashOP(), EscapeLag.plugin);
}
}
public static void save() {
DataManager.data.set("OpList", TheOps);
}
@EventHandler
public void onJoin(PlayerJoinEvent event) {
Player player = event.getPlayer();
if (Bukkit.getOperators().contains(player) && !TheOps.contains(player.getName())) {
player.setOp(false);
AzureAPI.log(player, Patches.AntiCrashOPWarnMessage);
}
}
}
| 30.431034 | 91 | 0.639093 |
929a24b4627cc14a954307b9ec0a98eb34316983 | 7,319 | package cellsociety.simulation;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import javafx.util.Pair;
/**
* Purpose: This class is used to make and manage grid for the WaTorWorld/Predation+Play simulation.
* Assumptions:
* Dependencies: Grid and Cell
* Use it in the same way as described in the general grid class except with a extra parameters for
* how long it takes fish to breed, sharks to breed, and sharks to die.
*
*/
public class WatorGrid extends Grid {
public static final int SHARK = 2;
public static final int FISH = 1;
public static final int EMPTY = 0;
public static final int ENERGY_FROM_FISH = 3;
private int fishTimeToBreed;
private int sharkTimeToBreed;
private int sharkDeathTime;
private Set<Integer> myFish = new HashSet();
private Set<Integer> mySharks= new HashSet();
private Set<Integer> emptyCells = new HashSet<>();
private Set<Integer> fishToRemove = new HashSet<>();
private Set<Integer> myFishToAdd = new HashSet<>();
private List<Point> neighborLocs;
/**
*
* @param cols
* @param rows
* @param sharkBreed time it takes for a shark to breed (produce a new shark)
* @param fishBreed time it takes for a fish to breed (produce a new fish)
* @param sharkDie amount of time it takes for a shark to die, food increases this by decreasing the
* time since the shark last ate.
* @param neighbors
* @param edges
*/
public WatorGrid(int cols, int rows, int sharkBreed, int fishBreed, int sharkDie, List<Point> neighbors, edgeType edges) {
super(cols, rows, neighbors, edges);
fishTimeToBreed = fishBreed;
sharkDeathTime = sharkDie;
sharkTimeToBreed = sharkBreed;
neighborLocs = neighbors;
}
@Override
public void updateCells(List<Cell> updateList) {
for (Cell cell : updateList) {
if (cell.getType() == SHARK) {
mySharks.add(cell.getX()*numColumns+ cell.getY());
}
else if (cell.getType() == FISH){
myFish.add(cell.getX() * numColumns + cell.getY());
}
}
for (Pair pair:findEmptyCells()){
emptyCells.add(calcLocation((int)pair.getKey(),(int)pair.getValue()));
emptyCells.removeAll(myFish);
emptyCells.removeAll(mySharks);
}
super.updateCells(updateList);
}
@Override
public List<Cell> checkForUpdates() {
ArrayList<Cell> updateList = new ArrayList<>();
updateList.addAll(updateSharks());
updateList.addAll(updateFish());
myFish.removeAll(fishToRemove);
myFish.addAll(myFishToAdd);
fishToRemove.clear();
myFishToAdd.clear();
return updateList;
}
private Collection<Cell> updateFish() {
ArrayList<Cell> updateList = new ArrayList<>();
for(Integer location: myFish){
int x = location/numColumns ;
int y = location % numColumns;
Cell curCell = myCellGrid[x][y];
List<Pair> emptySpots;
emptySpots = checkForNeighbors(x,y,emptyCells);
if (emptySpots.isEmpty()){
continue;
}
updateList.add(moveFish(emptySpots, x,y,curCell,updateList));
curCell.increaseAge();
}
return updateList;
}
private Cell moveFish(List<Pair> emptySpots, int x, int y, Cell curCell, List updateList) {
int randIndex = (int) (Math.random()*emptySpots.size());
Pair newCoordinates = emptySpots.get(randIndex);
int newx =(int) newCoordinates.getKey();
int newy = (int) newCoordinates.getValue();
curCell.setX(newx);
curCell.setY(newy);
myFishToAdd.add(calcLocation(newx,newy));
if (curCell.getAge() > fishTimeToBreed){
curCell.resetAge();
updateList.add(new Cell(FISH,x,y));
emptyCells.remove(calcLocation(x,y));
}
else{
updateList.add(new Cell(EMPTY,x,y));
fishToRemove.add(calcLocation(x,y));
emptyCells.add(calcLocation(x,y));
}
return curCell;
}
private Collection<Cell> updateSharks() {
ArrayList<Cell> updateList = new ArrayList<>();
List<Pair> fish;
List<Pair> emptySpots;
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numColumns; j++) {
Cell curCell = myCellGrid[i][j];
if (curCell.getType() == SHARK){
if (curCell.getTimeSinceEat() > sharkDeathTime){
updateList.add(new Cell(EMPTY,i,j));
emptyCells.add(calcLocation(i,j));
mySharks.remove(curCell);
continue;
}
fish = checkForNeighbors(i,j,myFish);
if (fish.isEmpty()){
emptySpots = checkForNeighbors(i,j,emptyCells);
if (!emptySpots.isEmpty()){
updateList.add(moveShark(emptySpots,i,j,curCell,false));
addNewSharkOrEmpty(updateList, i, j, curCell);
}
else{
curCell.increaseAge();
curCell.setTimeSinceEat(1);
}
}
else {
updateList.add(moveShark(fish, i, j, curCell, true));
addNewSharkOrEmpty(updateList, i, j, curCell);
}
}
}
}
return updateList;
}
private Integer calcLocation(int i, int j) {
return i * numColumns + j;
}
private void addNewSharkOrEmpty(ArrayList<Cell> updateList, int i, int j, Cell curCell) {
if (curCell.getAge() > sharkTimeToBreed) {
updateList.add(new Cell(SHARK, i, j));
mySharks.add(i*numColumns + j);
emptyCells.remove(calcLocation(i,j));
curCell.resetAge();
} else {
updateList.add(new Cell(EMPTY, i, j));
emptyCells.add(calcLocation(i,j));
}
}
private Cell moveShark(List<Pair> placesToMove, int i, int j, Cell curCell, boolean killFish) {
int randIndex = (int) (Math.random()*placesToMove.size());
Pair newCoordinates = placesToMove.get(randIndex);
int newx =(int) newCoordinates.getKey();
int newy = (int) newCoordinates.getValue();
if(killFish) {
myFish.remove(newx * numColumns + newy);
curCell.setTimeSinceEat(-ENERGY_FROM_FISH);
}
else {
emptyCells.remove(newx * numColumns + newy);
curCell.setTimeSinceEat(1);
}
mySharks.remove(i*numColumns + j);
mySharks.add(newx*numColumns + newy);
curCell.setX(newx);
curCell.setY(newy);
curCell.increaseAge();
return curCell;
}
private List<Pair> checkForNeighbors(int i, int j, Set lookingFor) {
List<Pair> neighbors = new ArrayList<>();
Integer sharkCoordinate = calcLocation(i,j);
Queue<Integer> neighborsToCheck = findNeighbors(sharkCoordinate);
while (neighborsToCheck.peek() != null) {
Integer currentCell = neighborsToCheck.remove();
if (lookingFor.contains(currentCell)) {
neighbors.add(new Pair(currentCell / numColumns, currentCell % numColumns));
}
}
return neighbors;
}
protected Queue<Integer> findNeighbors(int location) {
LinkedList<Integer> neighbors = new LinkedList<>();
for (Point p : neighborLocs) {
Integer validNeighbor = legalNeighbor(location/numColumns + p.x,location%numColumns + p.y);
if(validNeighbor != null) {
neighbors.add(validNeighbor);
}
}
return neighbors;
}
}
| 31.960699 | 124 | 0.643804 |
7a51fed45bb8975ef1cf3497cebc72d9fd222b59 | 701 | package com.prefecture.gestionlocale.model.dao;
import com.prefecture.gestionlocale.bean.Rue;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface RueDao extends JpaRepository<Rue, Long> {
Page<Rue> findByNomContainingOrQuartierNomContaining(String nom, String quartier, Pageable pageable);
Long countByNomAndQuartierId(String nom, Long quartierId);
Long countByNomAndIdNotAndQuartierId(String nom, Long id, Long quartierId);
List<Rue> findByQuartierIdOrderByNom(Long id);
}
| 35.05 | 105 | 0.820257 |
bac876c0e1a77fca82a4f0b966635e5b255dcb9f | 16,956 | package org.mockserver.socket;
import org.apache.commons.io.IOUtils;
import org.bouncycastle.asn1.*;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.asn1.x509.*;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.X509v3CertificateBuilder;
import org.bouncycastle.cert.bc.BcX509ExtensionUtils;
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.jcajce.JcaPEMWriter;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.bouncycastle.util.IPAddress;
import org.mockserver.configuration.ConfigurationProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.xml.bind.DatatypeConverter;
import java.io.*;
import java.math.BigInteger;
import java.security.*;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
/**
* @author jamesdbloom, ganskef
*/
public class KeyStoreFactory {
private static final Logger logger = LoggerFactory.getLogger(SSLFactory.class);
private static final String PROVIDER_NAME = BouncyCastleProvider.PROVIDER_NAME;
static {
Security.addProvider(new BouncyCastleProvider());
}
private static final String SIGNATURE_ALGORITHM = "SHA256WithRSAEncryption";
private static final String KEY_GENERATION_ALGORITHM = "RSA";
private static final boolean REGENERATE_FRESH_CA_CERTIFICATE = false;
/**
* Generates an 2048 bit RSA key pair using SHA1PRNG for the Certificate Authority.
*/
private static final int ROOT_KEYSIZE = 2048;
/**
* Generates an 1024 bit RSA key pair using SHA1PRNG for the server
* certificates. Thoughts: 2048 takes much longer time on older CPUs. And
* for almost every client, 1024 is sufficient.
*/
private static final int FAKE_KEYSIZE = 1024;
/**
* Current time minus 1 year, just in case software clock goes back due to
* time synchronization
*/
private static final Date NOT_BEFORE = new Date(System.currentTimeMillis() - 86400000L * 365);
/**
* The maximum possible value in X.509 specification: 9999-12-31 23:59:59,
* new Date(253402300799000L), but Apple iOS 8 fails with a certificate
* expiration date grater than Mon, 24 Jan 6084 02:07:59 GMT (issue #6).
*
* Hundred years in the future from starting the proxy should be enough.
*/
private static final Date NOT_AFTER = new Date(System.currentTimeMillis() + 86400000L * 365 * 100);
/**
* Create a random 2048 bit RSA key pair with the given length
*/
public static KeyPair generateKeyPair(int keySize) throws Exception {
KeyPairGenerator generator = KeyPairGenerator.getInstance(KEY_GENERATION_ALGORITHM, PROVIDER_NAME);
generator.initialize(keySize, new SecureRandom());
return generator.generateKeyPair();
}
private static SubjectKeyIdentifier createSubjectKeyIdentifier(Key key) throws IOException {
ASN1InputStream is = null;
try {
is = new ASN1InputStream(new ByteArrayInputStream(key.getEncoded()));
ASN1Sequence seq = (ASN1Sequence) is.readObject();
SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(seq);
return new BcX509ExtensionUtils().createSubjectKeyIdentifier(info);
} finally {
IOUtils.closeQuietly(is);
}
}
private static X509Certificate signCertificate(X509v3CertificateBuilder certificateBuilder, PrivateKey signedWithPrivateKey) throws OperatorCreationException, CertificateException {
ContentSigner signer = new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).setProvider(PROVIDER_NAME).build(signedWithPrivateKey);
return new JcaX509CertificateConverter().setProvider(PROVIDER_NAME).getCertificate(certificateBuilder.build(signer));
}
/**
* Create a certificate to use by a Certificate Authority, signed by a self signed certificate.
*/
public X509Certificate createCACert(PublicKey publicKey, PrivateKey privateKey) throws Exception {
//
// signers name
//
X500Name issuerName = new X500Name("CN=www.mockserver.com, O=MockServer, L=London, ST=England, C=UK");
//
// subjects name - the same as we are self signed.
//
X500Name subjectName = issuerName;
//
// serial
//
BigInteger serial = BigInteger.valueOf(new Random().nextInt(Integer.MAX_VALUE));
//
// create the certificate - version 3
//
X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuerName, serial, NOT_BEFORE, NOT_AFTER, subjectName, publicKey);
builder.addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyIdentifier(publicKey));
builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
KeyUsage usage = new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.cRLSign);
builder.addExtension(Extension.keyUsage, false, usage);
ASN1EncodableVector purposes = new ASN1EncodableVector();
purposes.add(KeyPurposeId.id_kp_serverAuth);
purposes.add(KeyPurposeId.id_kp_clientAuth);
purposes.add(KeyPurposeId.anyExtendedKeyUsage);
builder.addExtension(Extension.extendedKeyUsage, false, new DERSequence(purposes));
X509Certificate cert = signCertificate(builder, privateKey);
cert.checkValidity(new Date());
cert.verify(publicKey);
return cert;
}
/**
* Create a server certificate for the given domain and subject alternative names, signed by the given Certificate Authority.
*/
public X509Certificate createClientCert(PublicKey publicKey, X509Certificate certificateAuthorityCert, PrivateKey certificateAuthorityPrivateKey, PublicKey certificateAuthorityPublicKey, String domain, String[] subjectAlternativeNameDomains, String[] subjectAlternativeNameIps) throws Exception {
//
// signers name
//
X500Name issuer = new X509CertificateHolder(certificateAuthorityCert.getEncoded()).getSubject();
//
// subjects name - the same as we are self signed.
//
X500Name subject = new X500Name("CN=" + domain + ", O=MockServer, L=London, ST=England, C=UK");
//
// serial
//
BigInteger serial = BigInteger.valueOf(new Random().nextInt(Integer.MAX_VALUE));
//
// create the certificate - version 3
//
X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuer, serial, NOT_BEFORE, NOT_AFTER, subject, publicKey);
builder.addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyIdentifier(publicKey));
builder.addExtension(Extension.basicConstraints, false, new BasicConstraints(false));
//
// subject alternative name
//
List<ASN1Encodable> subjectAlternativeNames = new ArrayList<ASN1Encodable>();
if (subjectAlternativeNameDomains != null) {
subjectAlternativeNames.add(new GeneralName(GeneralName.dNSName, domain));
for (String subjectAlternativeNameDomain : subjectAlternativeNameDomains) {
subjectAlternativeNames.add(new GeneralName(GeneralName.dNSName, subjectAlternativeNameDomain));
}
}
if (subjectAlternativeNameIps != null) {
for (String subjectAlternativeNameIp : subjectAlternativeNameIps) {
if (IPAddress.isValidIPv6WithNetmask(subjectAlternativeNameIp)
|| IPAddress.isValidIPv6(subjectAlternativeNameIp)
|| IPAddress.isValidIPv4WithNetmask(subjectAlternativeNameIp)
|| IPAddress.isValidIPv4(subjectAlternativeNameIp)) {
subjectAlternativeNames.add(new GeneralName(GeneralName.iPAddress, subjectAlternativeNameIp));
}
}
}
if (subjectAlternativeNames.size() > 0) {
DERSequence subjectAlternativeNamesExtension = new DERSequence(subjectAlternativeNames.toArray(new ASN1Encodable[subjectAlternativeNames.size()]));
builder.addExtension(Extension.subjectAlternativeName, false, subjectAlternativeNamesExtension);
}
X509Certificate cert = signCertificate(builder, certificateAuthorityPrivateKey);
cert.checkValidity(new Date());
cert.verify(certificateAuthorityPublicKey);
return cert;
}
/**
* Create a KeyStore with a server certificate for the given domain and subject alternative names.
*/
KeyStore generateCertificate(KeyStore keyStore, String certificationAlias, String certificateAuthorityAlias, char[] keyStorePassword, String domain, String[] subjectAlternativeNameDomains, String[] subjectAlternativeNameIps) throws Exception {
//
// personal keys
//
KeyPair keyPair = generateKeyPair(FAKE_KEYSIZE);
PrivateKey clientPrivateKey = keyPair.getPrivate();
PublicKey clientPublicKey = keyPair.getPublic();
//
// ca keys
//
PrivateKey caPrivateKey = loadPrivateKeyFromPEMFile("org/mockserver/socket/CertificateAuthorityPrivateKey.pem");
X509Certificate caCert = (X509Certificate) loadCertificateFromKeyStore("org/mockserver/socket/CertificateAuthorityKeyStore.jks", certificateAuthorityAlias, keyStorePassword);
//
// regenerate ca private key and ca certificate (for development / debugging only)
//
if (REGENERATE_FRESH_CA_CERTIFICATE) {
KeyPair caKeyPair = generateKeyPair(ROOT_KEYSIZE);
PublicKey caPublicKey = caKeyPair.getPublic();
caPrivateKey = caKeyPair.getPrivate();
caCert = createCACert(caPublicKey, caPrivateKey);
KeyStore caKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
caKeyStore.load(readFileFromClassPathOrPath("org/mockserver/socket/CertificateAuthorityKeyStore.jks"), ConfigurationProperties.javaKeyStorePassword().toCharArray());
saveCertificateAsKeyStore(
caKeyStore,
false,
"CertificateAuthorityKeyStore.jks",
certificateAuthorityAlias,
clientPrivateKey,
keyStorePassword,
new X509Certificate[]{caCert},
caCert
);
saveCertificateAsPEMFile(caCert, "CertificateAuthorityCertificate.pem", false);
saveCertificateAsPEMFile(caPublicKey, "CertificateAuthorityPublicKey.pem", false);
saveCertificateAsPEMFile(caPrivateKey, "CertificateAuthorityPrivateKey.pem", false);
}
//
// generate client certificate
//
X509Certificate clientCert = createClientCert(clientPublicKey, caCert, caPrivateKey, caCert.getPublicKey(), domain, subjectAlternativeNameDomains, subjectAlternativeNameIps);
saveCertificateAsPEMFile(clientCert, "ClientCertificate.pem", true);
saveCertificateAsPEMFile(clientPublicKey, "ClientPublicKey.pem", true);
saveCertificateAsPEMFile(clientPrivateKey, "ClientPrivateKey.pem", true);
return saveCertificateAsKeyStore(
keyStore,
ConfigurationProperties.deleteGeneratedKeyStoreOnExit(),
ConfigurationProperties.javaKeyStoreFilePath(),
certificationAlias,
clientPrivateKey,
keyStorePassword,
new X509Certificate[]{clientCert, caCert},
caCert
);
}
/**
* Saves X509Certificate as Base-64 encoded PEM file.
*/
public void saveCertificateAsPEMFile(Object x509Certificate, String filename, boolean deleteOnExit) throws IOException {
File pemFile = new File(filename);
FileWriter pemfileWriter = new FileWriter(pemFile);
JcaPEMWriter jcaPEMWriter = null;
try {
jcaPEMWriter = new JcaPEMWriter(pemfileWriter);
jcaPEMWriter.writeObject(x509Certificate);
} finally {
IOUtils.closeQuietly(jcaPEMWriter);
IOUtils.closeQuietly(pemfileWriter);
}
if (deleteOnExit) {
pemFile.deleteOnExit();
}
}
/**
* Save X509Certificate in KeyStore file.
*/
private KeyStore saveCertificateAsKeyStore(KeyStore existingKeyStore, boolean deleteOnExit, String keyStoreFileName, String certificationAlias, Key privateKey, char[] keyStorePassword, Certificate[] chain, X509Certificate caCert) {
try {
KeyStore keyStore = existingKeyStore;
if (keyStore == null) {
// create new key store
keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null, keyStorePassword);
}
// add certificate
try {
keyStore.deleteEntry(certificationAlias);
} catch (KeyStoreException kse) {
// ignore as may not exist in keystore yet
}
keyStore.setKeyEntry(certificationAlias, privateKey, keyStorePassword, chain);
// add CA certificate
try {
keyStore.deleteEntry(SSLFactory.KEY_STORE_CA_ALIAS);
} catch (KeyStoreException kse) {
// ignore as may not exist in keystore yet
}
keyStore.setCertificateEntry(SSLFactory.KEY_STORE_CA_ALIAS, caCert);
// save as JKS file
File keyStoreFile = new File(keyStoreFileName);
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(keyStoreFile);
keyStore.store(fileOutputStream, keyStorePassword);
logger.trace("Saving key store to file [" + keyStoreFileName + "]");
} finally {
IOUtils.closeQuietly(fileOutputStream);
}
if (deleteOnExit) {
keyStoreFile.deleteOnExit();
}
return keyStore;
} catch (Exception e) {
throw new RuntimeException("Exception while saving KeyStore", e);
}
}
/**
* Load PrivateKey from PEM file.
*/
private RSAPrivateKey loadPrivateKeyFromPEMFile(String privateKeyFileName) {
try {
String publicKeyFile = IOUtils.toString(new InputStreamReader(KeyStoreFactory.class.getClassLoader().getResourceAsStream(privateKeyFileName)));
byte[] publicKeyBytes = DatatypeConverter.parseBase64Binary(publicKeyFile.replace("-----BEGIN RSA PRIVATE KEY-----", "").replace("-----END RSA PRIVATE KEY-----", ""));
return (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(publicKeyBytes));
} catch (Exception e) {
throw new RuntimeException("Exception reading private key from PEM file", e);
}
}
/**
* Load X509Certificate from KeyStore file.
*/
private Certificate loadCertificateFromKeyStore(String keyStoreFileName, String certificationAlias, char[] keyStorePassword) {
try {
InputStream inputStream = readFileFromClassPathOrPath(keyStoreFileName);
try {
logger.trace("Loading key store from file [" + keyStoreFileName + "]");
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
keystore.load(inputStream, keyStorePassword);
return keystore.getCertificate(certificationAlias);
} finally {
IOUtils.closeQuietly(inputStream);
}
} catch (Exception e) {
throw new RuntimeException("Exception while loading KeyStore from " + keyStoreFileName, e);
}
}
/**
* Load file from classpath and if not found then try file path
*/
private InputStream readFileFromClassPathOrPath(String keyStoreFileName) throws FileNotFoundException {
InputStream inputStream = getClass().getClassLoader().getResourceAsStream(keyStoreFileName);
if (inputStream == null) {
// load from path if not found in classpath
inputStream = new FileInputStream(keyStoreFileName);
}
return inputStream;
}
}
| 43.813953 | 300 | 0.681883 |
02463087f8121b8d8a824509b5d700f0eaa089a7 | 461 | package com.levelup.java.junit;
import static org.junit.Assert.assertFalse;
import org.junit.Ignore;
import org.junit.Test;
/**
* This java example will demonstrate ignoring
* a test with junit.
*
* @author Justin Musgrove
* @see <a href='http://www.leveluplunch.com/java/examples/junit-ignore-test/'>Ignore Test</a>
*
*/
public class IgnoreTest {
@Ignore("Ignore this test")
@Test
public void ignore_test_junit () {
assertFalse(true);
}
}
| 18.44 | 94 | 0.711497 |
5ceb301aeca344cde8cc7c10a25b33fa0a71a032 | 1,435 | package org.jboss.resteasy.util;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
import org.jboss.resteasy.spi.StringConverter;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.RuntimeDelegate;
import java.util.Set;
/**
* @author <a href="mailto:[email protected]">Bill Burke</a>
* @version $Revision: 1 $
*/
public class HeaderHelper
{
public static void setAllow(MultivaluedMap headers, String[] methods)
{
if (methods == null)
{
headers.remove("Allow");
return;
}
StringBuilder builder = new StringBuilder();
boolean isFirst = true;
for (String l : methods)
{
if (isFirst)
{
isFirst = false;
}
else
{
builder.append(", ");
}
builder.append(l);
}
headers.putSingle("Allow", builder.toString());
}
public static void setAllow(MultivaluedMap headers, Set<String> methods)
{
if (methods == null)
{
headers.remove("Allow");
return;
}
StringBuilder builder = new StringBuilder();
boolean isFirst = true;
for (String l : methods)
{
if (isFirst)
{
isFirst = false;
}
else
{
builder.append(", ");
}
builder.append(l);
}
headers.putSingle("Allow", builder.toString());
}
}
| 22.076923 | 75 | 0.55331 |
2d39f1b46f6a24f24abe792f2d7541e7d219804d | 1,510 | package com.jakubpetriska.gameengine.api;
import com.jakubpetriska.gameengine.api.components.Camera;
import com.jakubpetriska.gameengine.api.math.Matrix44;
/**
* Provides rendering functionality.
*/
public interface Renderer {
/**
* Gets called by the engine before the rendering of a frame starts (calls to render(Model)).
* <p/>
* This ensures that all updates to game objects are applied for given frame.
*/
void onStartRenderingFrame();
/**
* Renders model.
*
* @param mesh Mesh to render.
* @param transformation Transformation of the rendered object.
*/
void render(MeshData mesh, Color color, Matrix44 transformation);
/**
* Renders wireframe of the given mesh. Use
*
* @param mesh Mesh to render.
* @param color Color of the rendered wireframe.
* @param transformation Transformation of the rendered object.
*/
void renderWireframe(MeshData mesh, Color color, Matrix44 transformation);
/**
* Creates instance of MeshData with supplied data.
* Implementation can return a subclass of MeshData to which it can store it's specific
* data to use during rendering.
* <p/>
* Input parameters are similar to {@link MeshData}'s fields.
*/
MeshData createMeshData(
float[] vertices, float[] normals,
int[] trianglesVertices, int[] trianglesNormals);
void setCamera(Camera camera);
Camera getCamera();
}
| 30.2 | 97 | 0.660927 |
ba477017e66fb930f5fc7de7edf689cdf3d56fab | 986 | package javacore.Xnio.test;
import java.nio.file.Path;
import java.nio.file.Paths;
public class RelativizarTest {
public static void main(String[] args) {
Path dir = Paths.get("/home/caio");
Path classe = Paths.get("/home/caio/java/Pessoa.java");
Path pathToClasse = dir.relativize(classe);
System.out.println(pathToClasse);
Path absoluto1 = Paths.get("/home/caio");
Path absoluto2 = Paths.get("/usr/local");
Path absoluto3 = Paths.get("/home/caio/java/Pessoa.java");
Path relativo1 = Paths.get("temp");
Path relativo2 = Paths.get("temp/Funcionario.java");
System.out.println("1: " +absoluto1.relativize(absoluto3));
System.out.println("2: " +absoluto3.relativize(absoluto1));
System.out.println("3: " +absoluto1.relativize(absoluto2));
System.out.println("4: " +relativo1.relativize(relativo2));
System.out.println("5: " +absoluto1.relativize(relativo1));
}
}
| 36.518519 | 67 | 0.648073 |
16e9d5dd07a03e301a36ad92fffb15e5434226de | 1,393 | package net.elmosoft.splendid.browser;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.remote.DesiredCapabilities;
/**
* @author Aleksei_Mordas
*
*/
public class FirefoxFactory extends BrowserFactory {
private static final Logger LOGGER = LogManager.getLogger(FirefoxFactory.class);
@Override
public WebDriver createBrowser(boolean acceptUntrustedCerts,
boolean assumeUntrustedIssuer) {
FirefoxProfile profile = new FirefoxProfile();
LOGGER.info("Firefox profile was created");
profile.setAcceptUntrustedCertificates(acceptUntrustedCerts);
profile.setAssumeUntrustedCertificateIssuer(assumeUntrustedIssuer);
new DesiredCapabilities();
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability(FirefoxDriver.PROFILE, profile);
capabilities.setCapability("fake", "true");
capabilities.setCapability("media.navigator.permission.disabled", "true");
LOGGER.info("Firefox profile was set as capability");
WebDriverManager.firefoxdriver().setup();
return new FirefoxDriver(capabilities);
}
@Override
public WebDriver createBrowser() {
return new FirefoxDriver();
}
}
| 32.395349 | 81 | 0.806174 |
cd14a8741f41ac6aa78fadd298ca0fa98129049e | 3,041 | package com.anvil.adsama.nsaw.model;
import android.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class AlphaVantage implements Parcelable {
public static final Parcelable.Creator<AlphaVantage> CREATOR = new Creator<AlphaVantage>() {
@Override
public AlphaVantage createFromParcel(Parcel source) {
AlphaVantage alphaVantage = new AlphaVantage();
alphaVantage.mCompanyName = ((String) source.readValue((String.class.getClassLoader())));
alphaVantage.mLastRefreshTime = ((String) source.readValue((String.class.getClassLoader())));
alphaVantage.mOpen = ((float) source.readValue((float.class.getClassLoader())));
alphaVantage.mHigh = ((float) source.readValue((float.class.getClassLoader())));
alphaVantage.mLow = ((float) source.readValue((float.class.getClassLoader())));
alphaVantage.mClose = ((float) source.readValue((float.class.getClassLoader())));
alphaVantage.mVolume = ((float) source.readValue((float.class.getClassLoader())));
return alphaVantage;
}
@Override
public AlphaVantage[] newArray(int size) {
return new AlphaVantage[size];
}
};
@SerializedName("2. Symbol")
@Expose
private String mCompanyName;
@SerializedName("3. Last Refreshed")
@Expose
private String mLastRefreshTime;
@SerializedName("1. open")
@Expose
private float mOpen;
@SerializedName("2. high")
@Expose
private float mHigh;
@SerializedName("2. low")
@Expose
private float mLow;
@SerializedName("2. close")
@Expose
private float mClose;
@SerializedName("5. volume")
@Expose
private float mVolume;
private AlphaVantage() {
}
public AlphaVantage(String companyName, String refreshTime, float open, float high, float low, float close, float volume) {
mCompanyName = companyName;
mLastRefreshTime = refreshTime;
mOpen = open;
mHigh = high;
mLow = low;
mClose = close;
mVolume = volume;
}
public String getCompanyName() {
return mCompanyName;
}
public String getRefreshTime() {
return mLastRefreshTime;
}
public float getOpen() {
return mOpen;
}
public float getHigh() {
return mHigh;
}
public float getLow() {
return mLow;
}
public float getClose() {
return mClose;
}
public float getVolume() {
return mVolume;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(mCompanyName);
dest.writeValue(mLastRefreshTime);
dest.writeValue(mOpen);
dest.writeValue(mHigh);
dest.writeValue(mLow);
dest.writeValue(mClose);
dest.writeValue(mVolume);
}
} | 27.899083 | 127 | 0.634988 |
28ddafd877021e55db1d151a60799581d727ed80 | 4,796 | package com.cy.core.role.service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.cy.core.resource.dao.ResourceMapper;
import com.cy.core.resource.entity.Resource;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cy.base.entity.DataGrid;
import com.cy.core.role.dao.RoleMapper;
import com.cy.core.role.entity.Role;
import com.cy.core.user.entity.UserRole;
import com.cy.system.GetDictionaryInfo;
@Service("roleService")
public class RoleServiceImpl implements RoleService {
@Autowired
private RoleMapper roleMapper;
@Autowired
private ResourceMapper resourceMapper;
public DataGrid<Role> dataGrid(Map<String, Object> map) {
DataGrid<Role> dataGrid = new DataGrid<Role>();
long total = roleMapper.countRole(map);
dataGrid.setTotal(total);
int start = ((Integer) map.get("page") - 1) * (Integer) map.get("rows");
map.put("start", start);
List<Role> list = roleMapper.selectRole(map);
dataGrid.setRows(list);
return dataGrid;
}
public Role getById(long roleId) {
return roleMapper.getById(roleId);
}
public void save(Role role) {
role.setSystemAdmin(0);
roleMapper.add(role);
}
public void update(Role role) {
roleMapper.update(role);
}
public void delete(long id) {
try {
roleMapper.deleteRoleAndResource(id);
roleMapper.delete(id);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public Role selectResource(long roleId) {
return roleMapper.selectResource(roleId);
}
/**
* 创建人:Kent
* 创建时间:2016-07-26
* 描述:授权菜单和功能
* @param ids 授权菜单IDs
* @param actionIds 授权功能IDs
* @param id 角色ID
*/
public void updateGrant(String ids, String actionIds, long id) {
try {
roleMapper.deleteRoleAndResource(id);
if(!StringUtils.isBlank(ids)) {
List<Resource> menus = resourceMapper.selectMenuByIds(ids);
if(!StringUtils.isBlank(actionIds)){
List<Resource> actions = resourceMapper.selectActionByIds(actionIds);
menus.addAll(actions);
}
List<Map<String,Long>> roleResources = Lists.newArrayList();
for(Resource r : menus){
Map<String,Long> map = Maps.newHashMap();
map.put("roleId",id);
map.put("id",r.getId());
roleResources.add(map);
}
if(roleResources.size()>0) {
roleMapper.insertRoleAndResource1(roleResources);
}
}else if(!StringUtils.isBlank(actionIds)){
List<Resource> actions = resourceMapper.selectActionByIds(actionIds);
List<Map<String,Long>> roleResources = Lists.newArrayList();
for(Resource r : actions){
Map<String,Long> map = Maps.newHashMap();
map.put("roleId",id);
map.put("id",r.getId());
roleResources.add(map);
}
if(roleResources.size()>0) {
roleMapper.insertRoleAndResource1(roleResources);
}
}
/*String[] idAttr = ids.split(",");
for (String idStr : idAttr) {
if (idStr != null && !"".equals(idStr)) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("roleId", id);
map.put("id", Long.parseLong(idStr));
roleMapper.insertRoleAndResource(map);
}
}
// 刷新内存
GetDictionaryInfo.getInstance().reloadDictionaryInfoMap();*/
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public List<Role> selectAll() {
return roleMapper.selectAll();
}
public List<Role> getMenu(long roleId) {
return roleMapper.getMenu(roleId);
}
@Override
public List<Role> selectAllNoAdmin() {
return roleMapper.selectAllNoAdmin();
}
@Override
public List<Role> selectxAllNoAdmin() {
return roleMapper.selectxAllNoAdmin();
}
public List<Role> getMenuByUserRole(List<UserRole> userRoles) {
return roleMapper.getMenuByUserRole(userRoles);
}
@Override
public List<Role> getUserRoleByUserId(long userId) {
return roleMapper.getUserRoleByUserId(userId);
}
/**
* 创建人:Kent
* 创建时间:2016-07-25
* 描述:查询角色授权菜单
*
* @param roleId 角色ID
* @return 角色
*/
@Override
public Role selectMenu(long roleId) {
return roleMapper.selectMenu(roleId);
}
/**
* 创建人:Kent
* 创建时间:2016-07-25
* 描述:查询角色授权功能
*
* @param roleId
* @return 角色
*/
@Override
public Role selectAction(long roleId) {
return roleMapper.selectAction(roleId);
}
/**
* 创建人:kent
* 创建时间:2016-07-26
* 描述:通过功能查询该功能拥有的角色
*
* @param actionName
* @return
*/
@Override
public List<Role> getRolesByAction(String actionName) {
return roleMapper.selectRolesByAction(actionName);
}
/**
* 创建人:jiangling
* 创建时间:2016-08-03
* 描述:通过id查询删除标志位
* @param
* @return 删除标志位 Can_Del_Flag
*/
@Override
public int getDelFlag(long id) {
return roleMapper.getDelFlag(id);
}
}
| 23.742574 | 74 | 0.696622 |
cdcbc9cc582d53f53b24af9cd5f3840d7c225921 | 1,382 | package cn.yinjiahui.group_purchase.po;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
@Data
@TableName("address")
public class Address
{
@TableId(type= IdType.AUTO)
private Integer id;
private String name;
private float x;
private float y;
private String address_detailed;
public Address(String name, float x, float y,String address_detailed)
{
this.name = name;
this.x = x;
this.y = y;
this.address_detailed=address_detailed;
}
public Address()
{
}
public Integer getId()
{
return id;
}
public void setId(Integer id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public float getX()
{
return x;
}
public void setX(float x)
{
this.x = x;
}
public float getY()
{
return y;
}
public void setY(float y)
{
this.y = y;
}
public String getAddress_detailed()
{
return address_detailed;
}
public void setAddress_detailed(String address_detailed)
{
this.address_detailed = address_detailed;
}
}
| 16.452381 | 73 | 0.596961 |
ad9a4d9c1c29da704f4cd735accf5601bade35e8 | 7,923 | /*
* Copyright 2001 (C) MetaStuff, Ltd. All Rights Reserved.
*
* This software is open source.
* See the bottom of this file for the licence.
*
* $Id: Visdom.java,v 1.1.1.1 2001/05/22 08:12:37 jstrachan Exp $
*/
/*
* Dom4jGUI.java
*
* Created on 11. april 2001, 22:02
*/
package org.dom4j.visdom;
import org.dom4j.swing.TreeModelBuilder;
import org.dom4j.examples.*;
import javax.swing.*;
import javax.swing.tree.*;
import java.awt.*;
import java.net.*;
/**
*
* @author Pipo
* @version
*/
public class Visdom extends JFrame {
/** Creates new Dom4jGUI */
public Visdom() {
initComponents();
}
private void exitForm(java.awt.event.WindowEvent p_evt){
Action l_exit = Actions.get(Actions.EXIT);
l_exit.actionPerformed(null);
}
private void addWindowCloseListener(){
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
exitForm(evt);
}
}
);
}
private TreeModel createTreeModelFromDocument(){
return TreeModelBuilder.build(
ExampleDocumentBuilder.buildDocument());
}
private TreeModel createTreeModelFromFile(){
return TreeModelBuilder.build((org.dom4j.Document) Components.get(Components.CONFIG_DOC));
}
private JTree createTree(){
//JTree l_tree = new JTree(createTreeModelFromDocument());
JTree l_tree = new JTree(createTreeModelFromFile());
l_tree.setEditable(true);
return l_tree;
}
private void setSplitPane(){
JSplitPane l_split = new JSplitPane();
l_split.setLeftComponent(new JScrollPane(createTree()));
l_split.setRightComponent(new JLabel("VisDOM v0.01a"));
getContentPane().add(l_split);
}
public void initComponents(){
addWindowCloseListener();
setJMenuBar(MenuBuilder.buildMenuBar());
setSplitPane();
setSize(800, 600);
}
//******************************
// STATIC INITIALZATION METHODS
//******************************
private static void init(String args[]) throws MalformedURLException{
setConfigFile(args[0]);
setConfigDoc();
openToolBarWindow();
openFileSystemWindow();
openDomTreeWindow();
openXPathWindow();
openEditorWindow();
createConfigWindow();
}
private static void setConfigFile(String p_file){
Components.put(Components.CONFIG_FILE, p_file);
Components.lockKey(Components.CONFIG_FILE);
}
private static void setConfigDoc() throws MalformedURLException{
Components.put(Components.CONFIG_DOC, ExampleDocumentBuilder.readDocument(
(String) Components.get(Components.CONFIG_FILE) ));
}
private static void openToolBarWindow(){
JFrame l_toolBarWindow = WindowBuilder.buildToolBarWindow();
l_toolBarWindow.pack();
l_toolBarWindow.setSize(1000, 75);
l_toolBarWindow.setLocation(0,0);
l_toolBarWindow.show();
Components.put(Components.TOOLBAR_WINDOW, l_toolBarWindow);
Components.lockKey(Components.TOOLBAR_WINDOW);
}
private static void openFileSystemWindow(){
JFrame l_fileSystemWindow = WindowBuilder.buildFileSystemWindow();
l_fileSystemWindow.pack();
l_fileSystemWindow.setSize(300, 600);
l_fileSystemWindow.setLocation(0, 75);
l_fileSystemWindow.show();
Components.put(Components.FILESYSTEM_WINDOW, l_fileSystemWindow);
Components.lockKey(Components.FILESYSTEM_WINDOW);
}
private static void openDomTreeWindow(){
JFrame l_domTreeWindow = WindowBuilder.buildDomTreeWindow();
l_domTreeWindow.pack();
l_domTreeWindow.setSize(300, 600);
l_domTreeWindow.setLocation(300, 75);
l_domTreeWindow.show();
Components.put(Components.DOMTREE_WINDOW, l_domTreeWindow);
Components.lockKey(Components.DOMTREE_WINDOW);
}
private static void openXPathWindow(){
JFrame l_xpathWindow = WindowBuilder.buildXPathWindow();
l_xpathWindow.pack();
l_xpathWindow.setSize(300, 200);
l_xpathWindow.setLocation(300, 675);
l_xpathWindow.show();
Components.put(Components.XPATH_WINDOW, l_xpathWindow);
Components.lockKey(Components.XPATH_WINDOW);
}
private static void openEditorWindow(){
JFrame l_editorWindow = WindowBuilder.buildEditorWindow();
l_editorWindow.pack();
l_editorWindow.setSize(400,600);
l_editorWindow.setLocation(600, 75);
l_editorWindow.show();
Components.put(Components.EDITOR_WINDOW, l_editorWindow);
Components.lockKey(Components.EDITOR_WINDOW);
}
private static void createConfigWindow(){
}
/**
* Starts the Dom4jGui. Takes a configuration file path as argument.
* @param args the command line arguments
*/
public static void main (String args[]) {
try{
if(args.length == 1){
init(args);
}
printWelcomeText();
//Dom4jGUI l_frame = new Dom4jGUI();
//l_frame.pack();
//l_frame.setSize(800,600);
//l_frame.show();
}catch(Exception e){
System.out.println("Error starting FreeDOM: " + e.toString());
}
}
private static void printWelcomeText(){
System.out.println("*****************");
System.out.println(" VisDOM 1.00a ");
System.out.println("*****************");
}
}
/*
* Redistribution and use of this software and associated documentation
* ("Software"), with or without modification, are permitted provided
* that the following conditions are met:
*
* 1. Redistributions of source code must retain copyright
* statements and notices. Redistributions must also contain a
* copy of this document.
*
* 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 "DOM4J" must not be used to endorse or promote
* products derived from this Software without prior written
* permission of MetaStuff, Ltd. For written permission,
* please contact [email protected].
*
* 4. Products derived from this Software may not be called "DOM4J"
* nor may "DOM4J" appear in their names without prior written
* permission of MetaStuff, Ltd. DOM4J is a registered
* trademark of MetaStuff, Ltd.
*
* 5. Due credit should be given to the DOM4J Project
* (http://dom4j.org/).
*
* THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESSED 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
* METASTUFF, LTD. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Copyright 2001 (C) MetaStuff, Ltd. All Rights Reserved.
*
* $Id: Visdom.java,v 1.1.1.1 2001/05/22 08:12:37 jstrachan Exp $
*/
| 32.875519 | 99 | 0.64256 |
90d4c3bbc5912f51143c5f928a5d9959f42acef0 | 618 | package com.dojogrouppty.account;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
public class UserAuthenticationIntegrationTest {
private static final Logger logger
= LoggerFactory.getLogger(UserAuthenticationIntegrationTest.class);
@Test
public void testSimple() {
String p = "XXX";
BCryptPasswordEncoder pe = new BCryptPasswordEncoder();
String encPassword = pe.encode(p);
logger.debug("HELLB ---->[" + encPassword+"]");
}
}
| 29.428571 | 80 | 0.690939 |
99f9a992e548cf3c9225850db1f529e6d55ab96b | 11,543 | /*
* $Id$
*/
/*
Copyright (c) 2000-2008 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.
*/
package org.lockss.config;
import org.lockss.util.*;
import org.lockss.test.*;
import org.lockss.config.Tdb.TdbException;
import java.util.*;
/**
* Test class for <code>org.lockss.config.TdbPublisher</code>
*
* @author Philip Gust
* @version $Id$
*/
public class TestTdbPublisher extends LockssTestCase {
public void setUp() throws Exception {
super.setUp();
}
public void tearDown() throws Exception {
super.tearDown();
}
static Logger log = Logger.getLogger("TestTdbPublisher");
/**
* Test creating valid TdbPublisher.
*/
public void testValidPublisher() {
TdbPublisher publisher = null;
try {
publisher = new TdbPublisher("Test Publisher");
} catch (IllegalArgumentException ex) {
}
assertEquals("Test Publisher", publisher.getName());
}
/**
* Test creating TdbPublisher with null name.
*/
public void testNullPublisherName() {
TdbPublisher publisher = null;
try {
publisher = new TdbPublisher(null);
fail("TdbPublisher did not throw IllegalArgumentException for null constructor argument.");
} catch (IllegalArgumentException ex) {
}
assertNull(publisher);
}
/**
* Test equals() method for publisher.
* @throws TdbException for invalid Tdb operations
*/
public void testEquals() throws TdbException {
TdbPublisher publisher1 = new TdbPublisher("Test Publisher");
TdbTitle title1 = new TdbTitle("Test Title 1", "0000-0001");
publisher1.addTdbTitle(title1);
assertEquals(publisher1, publisher1);
// same as publisher1
TdbPublisher publisher2 = new TdbPublisher("Test Publisher");
TdbTitle title2 = new TdbTitle("Test Title 1", "0000-0002");
publisher2.addTdbTitle(title2);
assertEquals(publisher2, publisher2);
// differs from publisher1 by title name
TdbPublisher publisher3 = new TdbPublisher("Test Publisher");
TdbTitle title3 = new TdbTitle("Test Title 3", "0000-0003");
publisher3.addTdbTitle(title3);
assertNotEquals(publisher1, publisher3);
// differs from publisher3 by publisher name
TdbPublisher publisher4 = new TdbPublisher("Test Publisher 4");
TdbTitle title4 = new TdbTitle("Test Title 3", "0000-0004");
publisher4.addTdbTitle(title4);
assertNotEquals(publisher3, publisher4);
}
/**
* Test ISBNs and ISBNs
* @throws TdbException for invalid Tdb operations
*/
public void testIssns() throws TdbException {
TdbPublisher publisher = new TdbPublisher("Test Publisher");
TdbTitle title1 = new TdbTitle("Test Title 1", "TestTitle1");
publisher.addTdbTitle(title1);
TdbAu au1 = new TdbAu("Test AU 1", "pluginA");
title1.addTdbAu(au1);
au1.setPropertyByName("issn", "1234-5678");
au1.setPropertyByName("eissn", "2468-1357");
au1.setPropertyByName("issnl", "8765-4321");
au1.setAttr("isbn", "1234567890");
assertEquals(title1, publisher.getTdbTitleByIssn("1234-5678"));
assertEquals(title1, publisher.getTdbTitleByIssn("2468-1357"));
assertEquals(title1, publisher.getTdbTitleByIssn("8765-4321"));
assertSameElements(new TdbAu[] {au1},
publisher.getTdbAusByIsbn("1234567890"));
assertSameElements(new TdbTitle[] {title1},
publisher.getTdbTitlesByIssn("1234-5678"));
// add second title with same elements
TdbTitle title2 = new TdbTitle("Test Title 2", "TestTitle2");
publisher.addTdbTitle(title2);
TdbAu au2 = new TdbAu("Test AU 2", "pluginB");
title2.addTdbAu(au2);
au2.setPropertyByName("issn", "1234-5678");
au2.setPropertyByName("eissn", "2468-1357");
au2.setPropertyByName("issnl", "8765-4321");
au2.setAttr("isbn", "1234567890");
assertSameElements(new TdbAu[] {au1, au2},
publisher.getTdbAusByIsbn("1234567890"));
assertSameElements(new TdbTitle[] {title1, title2},
publisher.getTdbTitlesByIssn("1234-5678"));
}
/**
* Test addTitle() method.
* @throws TdbException for invalid Tdb operations
*/
public void testAddTitle() throws TdbException {
TdbPublisher publisher = new TdbPublisher("Test Publisher");
Collection<TdbTitle> titles = publisher.getTdbTitles();
assertEmpty(titles);
// add title
TdbTitle title = new TdbTitle("Test Title 1", "0000-0001");
publisher.addTdbTitle(title);
titles = publisher.getTdbTitles();
assertNotNull(titles);
assertEquals(1, titles.size());
// can't add null title
try {
publisher.addTdbTitle(null);
fail("TdbPublisher did not throw IllegalArgumentException adding null title.");
} catch (IllegalArgumentException ex) {
}
titles = publisher.getTdbTitles();
assertEquals(1, titles.size());
TdbTitle title2 = new TdbTitle("Test Title 2", title.getId());
try {
publisher.addTdbTitle(title2);
fail("TdbPublisher did not throw TdbException adding duplicate title");
} catch (TdbException ex) {
}
}
/**
* Test getTitlesByName() and getTitleById() methods.
* @throws TdbException for invalid Tdb operations
*/
public void testGetTitle() throws TdbException {
TdbPublisher publisher = new TdbPublisher("Test Publisher");
Collection<TdbTitle> titles = publisher.getTdbTitles();
assertEmpty(titles);
assertFalse(publisher.tdbTitleIterator().hasNext());
// add two titles
TdbTitle title1 = new TdbTitle("Journal Title", "1234-5678");
publisher.addTdbTitle(title1);
TdbTitle title2 = new TdbTitle("Book Title", "978-0521807678");
publisher.addTdbTitle(title2);
TdbTitle title3 = new TdbTitle("Book Title", "978-0345303066");
publisher.addTdbTitle(title3);
titles = publisher.getTdbTitles();
assertEquals(3, titles.size());
assertSameElements(ListUtil.list(title1, title2, title3),
ListUtil.fromIterator(publisher.tdbTitleIterator()));
assertEmpty(ListUtil.fromIterator(publisher.tdbAuIterator()));
TdbAu au1 = new TdbAu("Test AU1", "pluginA");
TdbAu au2 = new TdbAu("Test AU2", "pluginB");
TdbAu au3 = new TdbAu("Test AU3", "pluginC");
title1.addTdbAu(au1);
title1.addTdbAu(au2);
title3.addTdbAu(au3);
assertSameElements(ListUtil.list(au1, au2, au3),
ListUtil.fromIterator(publisher.tdbAuIterator()));
// get two titles by name
Collection<TdbTitle> getTitle1 = publisher.getTdbTitlesByName("Journal Title");
assertEquals(1, getTitle1.size());
assertEquals(title1, getTitle1.iterator().next());
Collection<TdbTitle> getTitle2 = publisher.getTdbTitlesByName("Book Title");
assertEquals(2, getTitle2.size());
assertTrue(getTitle2.contains(title2));
assertTrue(getTitle2.contains(title3));
// get title by ID
TdbTitle getTitleId2 = publisher.getTdbTitleById("978-0521807678");
assertEquals(title2, getTitleId2);
// get unknown title by name
Collection<TdbTitle> getTitleUnknown = publisher.getTdbTitlesByName("unknown");
assertEmpty(getTitleUnknown);
// get unknown title by ID
TdbTitle getTitleIdUnknown = publisher.getTdbTitleById("unknown");
assertNull(getTitleIdUnknown);
}
/**
* Test getTdbProviderCount() method.
* @throws TdbException for invalid Tdb operations
*/
public void testGetProvider() throws TdbException {
TdbPublisher publisher = new TdbPublisher("Test Publisher");
Collection<TdbTitle> titles = publisher.getTdbTitles();
assertEmpty(titles);
assertFalse(publisher.tdbTitleIterator().hasNext());
// add two titles
TdbTitle title1 = new TdbTitle("Journal Title", "1234-5678");
publisher.addTdbTitle(title1);
TdbTitle title2 = new TdbTitle("Book Title", "978-0521807678");
publisher.addTdbTitle(title2);
TdbTitle title3 = new TdbTitle("Book Title", "978-0345303066");
publisher.addTdbTitle(title3);
TdbAu au1 = new TdbAu("Test AU1", "pluginA");
new TdbProvider("provider1").addTdbAu(au1);
TdbAu au2 = new TdbAu("Test AU2", "pluginB");
new TdbProvider("provider2").addTdbAu(au2);
TdbAu au3 = new TdbAu("Test AU3", "pluginC");
new TdbProvider("provider3").addTdbAu(au3);
title1.addTdbAu(au1);
title1.addTdbAu(au2);
title3.addTdbAu(au3);
// ensure there are two providers: one that was
// explicitly added for au2, and one that was
// implicitly added for au1 and au3
assertEquals(3, publisher.getTdbProviderCount());
}
/**
* Test TdbAu.addPluginIdsForDifferences() method.
* @throws TdbException for invalid Tdb operations
*/
public void testAddPluginIdsForDifferences() throws TdbException {
TdbPublisher pub1 = new TdbPublisher("Test Publisher");
TdbTitle title1 = new TdbTitle("Test Title", "0000-0001");
TdbAu au1 = new TdbAu("Test AU1", "pluginA");
au1.setAttr("a", "A");
au1.setAttr("b", "A");
au1.setParam("x", "X");
au1.setPluginVersion("3");
title1.addTdbAu(au1);
pub1.addTdbTitle(title1);
// duplicate of pub1
TdbPublisher pub2 = new TdbPublisher("Test Publisher");
TdbTitle title2 = new TdbTitle("Test Title", "0000-0001");
TdbAu au2 = new TdbAu("Test AU1", "pluginA");
au2.setAttr("a", "A");
au2.setAttr("b", "A");
au2.setParam("x", "X");
au2.setPluginVersion("3");
title2.addTdbAu(au2);
pub2.addTdbTitle(title2);
TdbPublisher pub3 = new TdbPublisher("Test Publisher");
TdbTitle title3 = new TdbTitle("Test Title", "0000-0003");
TdbAu au3 = new TdbAu("Test AU1", "pluginB");
au3.setAttr("a", "A");
au3.setAttr("b", "A");
au3.setParam("x", "X");
au3.setPluginVersion("3");
title3.addTdbAu(au3);
pub3.addTdbTitle(title3);
// no differences becuase pub1 and pub2 are duplicates
Tdb.Differences diffs12 = new Tdb.Differences();
pub1.addDifferences(diffs12, pub2);
assertEquals(0, diffs12.getPluginIdsForDifferences().size());
// differences are 'pluginA' and 'pluginB'
Tdb.Differences diffs13 = new Tdb.Differences();
pub1.addDifferences(diffs13, pub3);
assertEquals(2, diffs13.getPluginIdsForDifferences().size());
}
}
| 34.663664 | 97 | 0.692974 |
3f9953fa32e0c35a8ee37d63034062628ec632bd | 2,715 | package com.landoop.avro.codec;
import org.apache.avro.file.Codec;
import org.apache.avro.file.DataFileConstants;
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream;
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
/**
* Implements bzip2 compression and decompression.
*/
public class BZip2Codec extends Codec {
public static final int DEFAULT_BUFFER_SIZE = 64 * 1024;
private ByteArrayOutputStream outputBuffer;
@Override
public String getName() {
return DataFileConstants.BZIP2_CODEC;
}
@Override
public ByteBuffer compress(ByteBuffer uncompressedData) throws IOException {
ByteArrayOutputStream baos = getOutputBuffer(uncompressedData.remaining());
BZip2CompressorOutputStream outputStream = new BZip2CompressorOutputStream(baos);
try {
outputStream.write(uncompressedData.array(),
uncompressedData.position(),
uncompressedData.remaining());
} finally {
outputStream.close();
}
ByteBuffer result = ByteBuffer.wrap(baos.toByteArray());
return result;
}
@Override
public ByteBuffer decompress(ByteBuffer compressedData) throws IOException {
ByteArrayInputStream bais = new ByteArrayInputStream(compressedData.array());
BZip2CompressorInputStream inputStream = new BZip2CompressorInputStream(bais);
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int readCount = -1;
while ((readCount = inputStream.read(buffer, compressedData.position(), buffer.length)) > 0) {
baos.write(buffer, 0, readCount);
}
ByteBuffer result = ByteBuffer.wrap(baos.toByteArray());
return result;
} finally {
inputStream.close();
}
}
@Override
public int hashCode() {
return getName().hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || obj.getClass() != getClass())
return false;
return true;
}
//get and initialize the output buffer for use.
private ByteArrayOutputStream getOutputBuffer(int suggestedLength) {
if (null == outputBuffer) {
outputBuffer = new ByteArrayOutputStream(suggestedLength);
}
outputBuffer.reset();
return outputBuffer;
}
} | 30.166667 | 106 | 0.660773 |
40f0a03868d512ba6e27b02d951265eede31c452 | 3,821 | package com.valarao.wordlesolver.controller;
import com.valarao.wordlesolver.cache.CacheManager;
import com.valarao.wordlesolver.calculator.ScoreCalculator;
import com.valarao.wordlesolver.loader.WordDatasetLoader;
import com.valarao.wordlesolver.model.CalculateInformationScoresRequest;
import com.valarao.wordlesolver.model.CalculateInformationScoresResponse;
import com.valarao.wordlesolver.model.PastGuess;
import com.valarao.wordlesolver.model.PredictiveScore;
import com.valarao.wordlesolver.model.RetrospectiveScore;
import com.valarao.wordlesolver.model.ValidationResult;
import com.valarao.wordlesolver.validation.InputValidationException;
import com.valarao.wordlesolver.validation.GuessValidator;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;
/**
* Controller managing the endpoint to calculate information scores for candidate guesses.
*/
@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
@Slf4j
public class ScoreController {
@Autowired
@NonNull
@Qualifier("reducedWordDatasetLoader")
private final WordDatasetLoader wordDatasetLoader;
@Autowired
@NonNull
private final ScoreCalculator<PredictiveScore> predictiveScoreCalculator;
@Autowired
@NonNull
private final ScoreCalculator<RetrospectiveScore> retrospectiveScoreCalculator;
@Autowired
@NonNull
private final CacheManager cacheManager;
@Autowired
@NonNull
@Qualifier("compositeGuessValidator")
private final GuessValidator guessValidator;
/***
*
* @param request Request with past guesses made.
* @return Response with calculated scores for candidate guesses.
*/
@PostMapping("/scores")
public CalculateInformationScoresResponse calculateInformationScores(
@RequestBody CalculateInformationScoresRequest request) {
validateGuesses(request.getGuesses());
List<String> allWords = wordDatasetLoader.load();
List<PastGuess> guesses = convertGuessWordsToUpperCase(request.getGuesses());
if (guesses.isEmpty()) {
return cacheManager.getScores();
}
List<PredictiveScore> predictiveScores = predictiveScoreCalculator.calculate(allWords, guesses);
return CalculateInformationScoresResponse.builder()
.topWord(predictiveScores.isEmpty() ? "" : predictiveScores.get(predictiveScores.size() - 1).getGuessWord())
.predictiveScores(predictiveScores)
.retrospectiveScores(retrospectiveScoreCalculator.calculate(allWords, guesses))
.build();
}
private List<PastGuess> convertGuessWordsToUpperCase(List<PastGuess> guesses) {
return guesses.stream()
.map(pastGuess -> pastGuess.toBuilder()
.guessWord(pastGuess.getGuessWord().toUpperCase(Locale.ROOT))
.build())
.collect(Collectors.toList());
}
private void validateGuesses(List<PastGuess> guesses) throws InputValidationException {
ValidationResult validationResult = guessValidator.validateAll(guesses);
if (!validationResult.isValid()) {
log.error(validationResult.getMessage());
throw new InputValidationException(validationResult.getMessage());
}
}
}
| 37.831683 | 124 | 0.750589 |
4c8f4c96e3dadd61c2939f86a6d97b036b8c3e73 | 1,846 | package com.youngadessi.demo.auth.controller;
import com.youngadessi.demo.auth.service.AuthenticationService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
@Validated
@RestController
@RequiredArgsConstructor
@RequestMapping("/auth")
public class AuthenticationController {
private final AuthenticationService authService;
private final PasswordEncoder passwordEncoder;
// private static final UserMapper USER_MAPPER = Mappers.getMapper(UserMapper.class);
@PostMapping("/signin")
public ResponseEntity<String> signin(@Valid @RequestBody LoginRequest loginRequest) {
return new ResponseEntity<>(authService.signin(loginRequest), HttpStatus.CREATED);
}
@PostMapping("/secure")
public ResponseEntity<String> secure() {
return new ResponseEntity<>("success", HttpStatus.CREATED);
}
// @PostMapping("/signup")
// public String signup(@RequestBody @Valid UserDTO userDTO) {
// return authService.signup(USER_MAPPER.toEntity(userDTO));
// }
//
// @DeleteMapping(value = "/{username}")
// public String delete(@PathVariable String username) {
// authService.delete(username);
// return username;
// }
//
// @GetMapping(value = "/me")
// public UserDTO whoami(HttpServletRequest req) {
// return USER_MAPPER.toDto(authService.whoami(req));
// }
}
| 32.385965 | 90 | 0.755688 |
a939bd24a3915d0cfcfb877ff812cc6027864d15 | 8,705 | /*
* (C) Copyright 2021 Radix DLT Ltd
*
* Radix DLT Ltd 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 com.radixdlt.api.service;
import org.json.JSONArray;
import org.json.JSONObject;
import com.google.inject.Inject;
import com.radixdlt.api.data.ActionType;
import com.radixdlt.api.data.action.TransactionAction;
import com.radixdlt.crypto.ECPublicKey;
import com.radixdlt.identifiers.REAddr;
import com.radixdlt.networks.Addressing;
import com.radixdlt.utils.UInt256;
import com.radixdlt.utils.functional.Failure;
import com.radixdlt.utils.functional.Result;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;
import static com.radixdlt.api.data.ApiErrors.INVALID_ACTION_DATA;
import static com.radixdlt.api.data.ApiErrors.MISSING_FIELD;
import static com.radixdlt.api.data.ApiErrors.UNSUPPORTED_ACTION;
import static com.radixdlt.application.validators.scrypt.ValidatorUpdateRakeConstraintScrypt.RAKE_MAX;
import static com.radixdlt.application.validators.scrypt.ValidatorUpdateRakeConstraintScrypt.RAKE_MIN;
import static com.radixdlt.application.validators.scrypt.ValidatorUpdateRakeConstraintScrypt.RAKE_PERCENTAGE_GRANULARITY;
import static com.radixdlt.identifiers.CommonErrors.UNABLE_TO_DECODE;
import static com.radixdlt.identifiers.CommonErrors.VALUE_OUT_OF_RANGE;
import static com.radixdlt.utils.functional.Result.allOf;
import static com.radixdlt.utils.functional.Result.wrap;
import static java.util.Optional.ofNullable;
public final class ActionParserService {
private final Addressing addressing;
@Inject
public ActionParserService(Addressing addressing) {
this.addressing = addressing;
}
public Result<List<TransactionAction>> parse(JSONArray actions) {
var list = new ArrayList<TransactionAction>();
for (var o : actions) {
if (!(o instanceof JSONObject)) {
return INVALID_ACTION_DATA.with(o).result();
}
var element = (JSONObject) o;
var result = param(element, "type")
.flatMap(ActionType::fromString)
.flatMap(type -> parseByType(type, element))
.onSuccess(list::add);
if (!result.isSuccess()) {
return result.map(List::of);
}
}
return Result.ok(list);
}
private Result<TransactionAction> parseByType(ActionType type, JSONObject element) {
switch (type) {
case UNKNOWN:
case MSG:
default:
return UNSUPPORTED_ACTION.with(type).result();
case TRANSFER:
return allOf(
from(element),
to(element),
amount(element),
rri(element)
).map(TransactionAction::transfer);
case UNSTAKE:
return allOf(
from(element),
validator(element),
amount(element)
).map(TransactionAction::unstake);
case STAKE:
return allOf(
from(element),
validator(element),
amount(element)
).map(TransactionAction::stake);
case BURN:
return allOf(
from(element),
rri(element),
amount(element)
).map(TransactionAction::burn);
case MINT:
return allOf(
to(element),
rri(element),
amount(element)
).map(TransactionAction::mint);
case REGISTER_VALIDATOR:
return allOf(
validator(element)
).map(TransactionAction::register);
case UNREGISTER_VALIDATOR:
return allOf(
validator(element)
).map(TransactionAction::unregister);
case UPDATE_VALIDATOR_METADATA:
return allOf(
validator(element),
optionalName(element),
optionalUrl(element)
).map(TransactionAction::updateMetadata);
case UPDATE_VALIDATOR_FEE:
return allOf(
validator(element),
fee(element)
).map(TransactionAction::updateValidatorFee);
case UPDATE_DELEGATION:
return allOf(
validator(element),
allowDelegation(element)
).map(TransactionAction::updateAllowDelegation);
case UPDATE_OWNER:
return allOf(
validator(element),
owner(element)
).map(TransactionAction::updateOwnerAddress);
case CREATE_FIXED:
return allOf(
to(element),
pubKey(element),
symbol(element),
name(element),
description(element),
iconUrl(element),
tokenUrl(element),
supply(element)
).map(TransactionAction::createFixed);
case CREATE_MUTABLE:
return allOf(
pubKey(element),
symbol(element),
name(element),
optionalDescription(element),
optionalIconUrl(element),
optionalTokenUrl(element)
).map(TransactionAction::createMutable);
}
}
private Result<ECPublicKey> pubKey(JSONObject element) {
return param(element, "publicKeyOfSigner")
.flatMap(ECPublicKey::fromHexString);
}
private Result<REAddr> rri(JSONObject element) {
// TODO: Need to verify symbol matches
return param(element, "rri")
.flatMap(p -> addressing.forResources().parseFunctional(p).map(t -> t.map((__, addr) -> addr)));
}
private static final Failure FEE_BOUNDS_FAILURE = VALUE_OUT_OF_RANGE.with(
(double) RAKE_MIN / (double) RAKE_PERCENTAGE_GRANULARITY + "",
(double) RAKE_MAX / (double) RAKE_PERCENTAGE_GRANULARITY + ""
);
private Result<Integer> fee(JSONObject element) {
return param(element, "validatorFee")
.flatMap(parameter -> wrap(UNABLE_TO_DECODE, () -> Double.parseDouble(parameter)))
.map(doublePercentage -> (int) (doublePercentage * RAKE_PERCENTAGE_GRANULARITY))
.filter(percentage -> percentage >= RAKE_MIN && percentage <= RAKE_MAX, FEE_BOUNDS_FAILURE);
}
private Result<Boolean> allowDelegation(JSONObject element) {
return param(element, "allowDelegation")
.flatMap(parameter ->
Stream.of("true", "false")
.filter(parameter::equals)
.findAny()
.map(Boolean::parseBoolean)
.map(Result::ok)
.orElseGet(() -> UNABLE_TO_DECODE.with(parameter).result())
);
}
private Result<REAddr> from(JSONObject element) {
return address(element, "from");
}
private Result<REAddr> owner(JSONObject element) {
return address(element, "owner");
}
private Result<REAddr> to(JSONObject element) {
return address(element, "to");
}
private Result<ECPublicKey> validator(JSONObject element) {
return param(element, "validator")
.flatMap(addressing.forValidators()::fromString);
}
private static Result<UInt256> amount(JSONObject element) {
return param(element, "amount")
.flatMap(UInt256::fromString);
}
private static Result<UInt256> supply(JSONObject element) {
return param(element, "supply")
.flatMap(UInt256::fromString);
}
private static Result<String> name(JSONObject element) {
return param(element, "name");
}
private static Result<Optional<String>> optionalName(JSONObject element) {
return optionalParam(element, "name");
}
private static Result<String> symbol(JSONObject element) {
return param(element, "symbol");
}
private static Result<Optional<String>> optionalUrl(JSONObject element) {
return optionalParam(element, "url");
}
private static Result<String> iconUrl(JSONObject element) {
return param(element, "iconUrl");
}
private static Result<Optional<String>> optionalIconUrl(JSONObject element) {
return optionalParam(element, "iconUrl");
}
private static Result<String> tokenUrl(JSONObject element) {
return param(element, "tokenUrl");
}
private static Result<Optional<String>> optionalTokenUrl(JSONObject element) {
return optionalParam(element, "tokenUrl");
}
private static Result<String> description(JSONObject element) {
return param(element, "description");
}
private static Result<Optional<String>> optionalDescription(JSONObject element) {
return optionalParam(element, "description");
}
private static Result<Optional<String>> optionalParam(JSONObject element, String name) {
return Result.ok(
ofNullable(element.opt(name))
.filter(String.class::isInstance)
.map(String.class::cast)
);
}
private Result<REAddr> address(JSONObject element, String name) {
return param(element, name)
.flatMap(addressing.forAccounts()::parseFunctional);
}
private static Result<String> param(JSONObject params, String name) {
return ofNullable(params.opt(name))
.map(Object::toString)
.map(Result::ok)
.orElseGet(() -> MISSING_FIELD.with(name).result());
}
}
| 28.540984 | 121 | 0.727972 |
b30c4a2ea15f0a794667e6952b46156ba645ee92 | 1,561 | /*
* Copyright Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags and
* the COPYRIGHT.txt file distributed with this work.
*
* 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.teiid.metadata;
import static org.junit.Assert.*;
import org.junit.Test;
public class TestTable {
@Test public void testCardinality() {
Table t = new Table();
assertEquals(-1, t.getCardinalityAsFloat(), 0);
t.setCardinality(1000);
assertEquals(1000, t.getCardinalityAsFloat(), 0);
t.setCardinality(100000111000111100L);
assertEquals(100000111000111100L/t.getCardinalityAsFloat(), 1, .01);
}
@Test public void testColumnPrecisionScale() {
Column c = new Column();
Datatype datatype = new Datatype();
datatype.setName("bigdecimal");
c.setDatatype(datatype);
c.setPrecision(0);
c.setScale(2);
assertEquals(2, c.getScale());
assertEquals(BaseColumn.DEFAULT_PRECISION, c.getPrecision());
}
}
| 32.520833 | 76 | 0.692505 |
8b8460733f5f2e826b4330521bde6fd7f6e0c7c1 | 3,410 | package org.gama.lang;
import java.io.Serializable;
import java.util.Iterator;
/**
* Kind of StringBuilder aimed at being simpler by its API.
*
* @author Guillaume Mary
*/
public class StringAppender implements Serializable, CharSequence {
private StringBuilder appender;
public StringAppender() {
appender = new StringBuilder();
}
public StringAppender(int capacity) {
appender = new StringBuilder(capacity);
}
public StringAppender(Object... s) {
this();
cat(s);
}
public StringAppender cat(Object s) {
appender.append(s);
return this;
}
public StringAppender cat(Object s1, Object s2) {
// we skip an array creation by calling cat() multiple times
return cat(s1).cat(s2);
}
public StringAppender cat(Object s1, Object s2, Object s3) {
// we skip an array creation by calling cat() multiple times
return cat(s1).cat(s2).cat(s3);
}
public StringAppender cat(Object... ss) {
for (Object s : ss) {
cat(s);
}
return this;
}
public StringAppender cat(Iterable ss) {
for (Object s : ss) {
cat(s);
}
return this;
}
public StringAppender catAt(int index, Object... ss) {
// We make this method uses cat() to ensure that any override of cat() is also used by this method
// otherwise we could simply use appender.insert(..)
// So, we swap this.appender with a new StringBuilder to make cat(..) fill it
StringBuilder previous = this.appender;
StringBuilder target = new StringBuilder();
this.appender = target;
// cat() will append to the temporary StringBuilder
cat(ss);
this.appender = previous;
// finally inserting at index
this.appender.insert(index, target);
return this;
}
public StringAppender catIf(boolean condition, Object... ss) {
if (condition) {
cat(ss);
}
return this;
}
public StringAppender ccat(Object... s) {
return ccat(s, s[s.length - 1], s.length - 1);
}
public StringAppender ccat(Iterable ss, Object sep) {
Iterator iterator = ss.iterator();
while (iterator.hasNext()) {
Object s = iterator.next();
cat(s).catIf(iterator.hasNext(), sep);
}
return this;
}
public StringAppender ccat(Object[] s, Object sep) {
return ccat(s, sep, s.length);
}
public StringAppender ccat(Object[] s, Object sep, int objectCount) {
if (s.length > 0) {
int lastIndex = objectCount < 1 ? 0 : objectCount - 1;
for (int i = 0; i < objectCount; i++) {
cat(s[i]).catIf(i != lastIndex, sep);
}
}
return this;
}
public StringAppender wrap(Object open, Object close) {
catAt(0, open).cat(close);
return this;
}
@Override
public String toString() {
return appender.toString();
}
public StringAppender cutTail(int nbChar) {
int newLength = length() - nbChar;
if (newLength > -1) {
appender.setLength(newLength);
}
return this;
}
public StringAppender cutHead(int nbChar) {
appender.delete(0, nbChar);
return this;
}
/**
* Gives access to delegate appender, because it can be usefull to append directly to the standard API StringBuilder
*
* @return the underlying appender
*/
public StringBuilder getAppender() {
return appender;
}
@Override
public int length() {
return appender.length();
}
@Override
public char charAt(int index) {
return appender.charAt(index);
}
@Override
public CharSequence subSequence(int start, int end) {
return appender.subSequence(start, end);
}
}
| 22.142857 | 117 | 0.677126 |
253472e2b2b8afcb77e326f40b01d801afa1f5ac | 4,113 | package ca.corefacility.bioinformatics.irida.ria.unit.web.services;
import java.util.List;
import java.util.Locale;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.context.MessageSource;
import ca.corefacility.bioinformatics.irida.exceptions.EntityNotFoundException;
import ca.corefacility.bioinformatics.irida.model.joins.impl.RelatedProjectJoin;
import ca.corefacility.bioinformatics.irida.model.project.Project;
import ca.corefacility.bioinformatics.irida.ria.web.exceptions.UIAddAssociatedProjectException;
import ca.corefacility.bioinformatics.irida.ria.web.exceptions.UIRemoveAssociatedProjectException;
import ca.corefacility.bioinformatics.irida.ria.web.projects.settings.dto.AssociatedProject;
import ca.corefacility.bioinformatics.irida.ria.web.services.UIAssociatedProjectsService;
import ca.corefacility.bioinformatics.irida.security.permissions.project.ProjectOwnerPermission;
import ca.corefacility.bioinformatics.irida.service.ProjectService;
import com.google.common.collect.ImmutableList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.*;
public class UIAssociatedProjectsServiceTest {
private UIAssociatedProjectsService service;
private ProjectService projectService;
// DATA
private final Long PROJECT_1_ID = 1L;
private final Long PROJECT_2_ID = 2L;
private final Long PROJECT_4_ID = 4L;
private final Project PROJECT_1 = new Project("PROJECT_1");
private final Project PROJECT_2 = new Project("PROJECT_2");
private final Project PROJECT_3 = new Project("PROJECT_3");
private final Project PROJECT_4 = new Project("PROJECT_4");
@BeforeEach
public void setUp() {
projectService = mock(ProjectService.class);
ProjectOwnerPermission projectOwnerPermission = mock(ProjectOwnerPermission.class);
MessageSource messageSource = mock(MessageSource.class);
service = new UIAssociatedProjectsService(projectService, projectOwnerPermission, messageSource);
PROJECT_1.setId(PROJECT_1_ID);
PROJECT_2.setId(PROJECT_2_ID);
PROJECT_4.setId(PROJECT_4_ID);
when(projectService.read(PROJECT_1_ID)).thenReturn(PROJECT_1);
when(projectService.read(PROJECT_2_ID)).thenReturn(PROJECT_2);
when(projectService.read(PROJECT_4_ID)).thenReturn(PROJECT_4);
List<RelatedProjectJoin> relatedProjectJoins = ImmutableList.of(new RelatedProjectJoin(PROJECT_1, PROJECT_2),
new RelatedProjectJoin(PROJECT_1, PROJECT_3), new RelatedProjectJoin(PROJECT_1, PROJECT_4));
when(projectService.getRelatedProjects(PROJECT_1)).thenReturn(relatedProjectJoins);
}
@Test
public void testGetAssociatedProjectsForProject() {
List<AssociatedProject> relatedProjectJoins = service.getAssociatedProjectsForProject(PROJECT_1_ID);
assertEquals(3, relatedProjectJoins.size());
verify(projectService, times(1)).read(PROJECT_1_ID);
verify(projectService, times(1)).getRelatedProjects(PROJECT_1);
}
@Test
public void testAddAssociatedProject() throws UIAddAssociatedProjectException {
service.addAssociatedProject(PROJECT_1_ID, PROJECT_2_ID, Locale.ENGLISH);
verify(projectService, times(1)).addRelatedProject(PROJECT_1, PROJECT_2);
when(projectService.read(PROJECT_4_ID)).thenThrow(new EntityNotFoundException("Cannot find project"));
assertThrows(UIAddAssociatedProjectException.class, () -> {
service.addAssociatedProject(PROJECT_1_ID, PROJECT_4_ID, Locale.ENGLISH);
});
}
@Test
public void testRemoveAssociatedProject() throws UIRemoveAssociatedProjectException {
service.removeAssociatedProject(PROJECT_1_ID, PROJECT_2_ID, Locale.ENGLISH);
verify(projectService, times(1)).read(PROJECT_1_ID);
verify(projectService, times(1)).read(PROJECT_2_ID);
verify(projectService, times(1)).removeRelatedProject(PROJECT_1, PROJECT_2);
when(projectService.read(PROJECT_4_ID)).thenThrow(new EntityNotFoundException("Cannot find project"));
assertThrows(UIRemoveAssociatedProjectException.class, () -> {
service.removeAssociatedProject(PROJECT_1_ID, PROJECT_4_ID, Locale.ENGLISH);
});
}
}
| 43.294737 | 111 | 0.822514 |
2fb5d9448a72fee7aa4e656f2b5a67b0cbc17e0c | 4,052 | package com.stackroute.userregistration.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.stackroute.userregistration.domain.User;
import com.stackroute.userregistration.service.UserService;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.mockito.Mockito.*;
import static org.mockito.internal.verification.VerificationModeFactory.times;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
public class UserControllerTest {
//Creating the object for the mockmvc to mock the service
@Autowired
MockMvc mockMvc;
//Mocking the user service
@Mock
UserService userService;
@InjectMocks
UserController userController;
@Before
public void setup()
{
MockitoAnnotations.initMocks(this);
//Building the usercontroller
mockMvc = MockMvcBuilders.standaloneSetup(userController).build();
}}
//Creating the testcase for the saving the user in the database
// @Test
// public void saveUserTest() throws Exception
// {
// //Sample user details
// User user = new User("1","Sahithi","[email protected]","pwd");
// //When the saveUser is called it has to return the saved user
// when(userService.saveUser(user)).thenReturn(user);
// //It has to perform the action whenever the user url template is called using the post method
// mockMvc.perform(post("/user")
// .contentType(MediaType.APPLICATION_JSON)
// .content(asJsonString(user)))
// .andExpect(status().isCreated());
// //It has to call the user only once
// verify(userService, times(1)).saveUser(Mockito.any(User.class));
// verifyNoMoreInteractions(userService);
// }
/* @Test
public void getAllUsersTest() throws Exception
{
//Sample user details
List<User> users = new ArrayList<>();
User user = new User("1","Sahithi","[email protected]","pwd");
User user1 = new User("1","premika","[email protected]","pwd");
users.add(user);
users.add(user1);
//Call the getuser method
when(userService.getUsers()).thenReturn(users);
mockMvc.perform(get("/user")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$", hasSize(2)));
//It has to call the getUsers only once
verify(userService, times(1)).getUsers();
verifyNoMoreInteractions(userService);
}
@Test
public void deleteUserTest() throws Exception
{
//Sample user details
User user = new User("1","Sahithi","[email protected]","pwd");
//When the deleteUser is called it has to return the deleted user
when(userService.deleteUser("1")).thenReturn(user);
mockMvc.perform(delete("/user/1")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
verify(userService, times(1)).deleteUser("1");
verifyNoMoreInteractions(userService);
}
//This method is used to change the object to the string
public static String asJsonString(final Object obj) {
try {
return new ObjectMapper().writeValueAsString(obj);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}*/
| 40.118812 | 103 | 0.682626 |
8f371c80db3fb6a968e09cd9e08e4db5900586d7 | 14,520 | package com.navismart.navismart.view;
import android.app.Dialog;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.ViewModelProviders;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.navismart.navismart.BuildConfig;
import com.navismart.navismart.R;
import com.navismart.navismart.adapters.ChatAdapter;
import com.navismart.navismart.model.ChatModel;
import com.navismart.navismart.utils.PreferencesHelper;
import com.navismart.navismart.viewmodelfactory.ContactAdminViewModelFactory;
import com.navismart.navismart.viewmodels.ContactAdminViewModel;
import org.json.JSONObject;
import java.util.ArrayList;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import static com.navismart.navismart.MainActivity.USER_TYPE;
import static com.navismart.navismart.MainActivity.getCurrentStringDate;
import static com.navismart.navismart.MainActivity.getCurrentStringTime;
import static com.navismart.navismart.adapters.ChatAdapter.SENDER_BOATER;
import static com.navismart.navismart.adapters.ChatAdapter.SENDER_MARINA;
public class ContactUsFragment extends Fragment {
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
private RecyclerView chatRecyclerView;
private FloatingActionButton sendButton;
private EditText msgEditText;
private TextView marinaChatName;
private ImageView moreIcon;
private Button deleteButton, cancelButton;
private FirebaseAuth auth;
private DatabaseReference databaseReference;
private String userID, userName, adminID;
private String receiverToken, senderToken, userToken, adminToken;
private PreferencesHelper preferencesHelper;
public ContactUsFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_chat, container, false);
preferencesHelper = new PreferencesHelper(getActivity());
chatRecyclerView = view.findViewById(R.id.chat_recycler_view);
sendButton = view.findViewById(R.id.send_button);
msgEditText = view.findViewById(R.id.msg_edit_text);
marinaChatName = view.findViewById(R.id.marinaChatName);
moreIcon = view.findViewById(R.id.more_icon);
msgEditText.setEnabled(false);
sendButton.setEnabled(false);
userName = getArguments().getString("userName");
userID = getArguments().getString("userID");
adminID = getArguments().getString("adminID");
if (USER_TYPE == SENDER_BOATER || USER_TYPE == SENDER_MARINA) {
marinaChatName.setText("Navismart");
} else {
marinaChatName.setText(userName);
}
auth = FirebaseAuth.getInstance();
databaseReference = FirebaseDatabase.getInstance().getReference();
databaseReference.child("users").child(userID).child("profile").child("fcm_token").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
userToken = dataSnapshot.getValue().toString();
databaseReference.child("users").child(adminID).child("profile").child("fcm_token").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
adminToken = dataSnapshot.getValue().toString();
if (USER_TYPE == SENDER_BOATER || USER_TYPE == SENDER_MARINA) {
receiverToken = adminToken;
senderToken = userToken;
} else {
receiverToken = userToken;
senderToken = adminToken;
}
msgEditText.setEnabled(true);
sendButton.setEnabled(true);
Log.d("ADMIN_TOKEN", adminToken);
Log.d("USER_TOKEN", userToken);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
Dialog deleteDialog = new Dialog(getContext());
deleteDialog.setContentView(R.layout.delete_chat_dialog);
deleteButton = deleteDialog.findViewById(R.id.delete_button);
cancelButton = deleteDialog.findViewById(R.id.cancel_delete);
cancelButton.setOnClickListener((View v) -> deleteDialog.dismiss());
deleteButton.setOnClickListener((View v) -> {
deleteAllChats();
deleteDialog.dismiss();
});
moreIcon.setOnClickListener((View v) -> {
PopupMenu popupMenu = new PopupMenu(getContext(), moreIcon);
popupMenu.getMenuInflater().inflate(R.menu.chat_options, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(item -> {
if (item.getItemId() == R.id.delete_chats) {
deleteDialog.show();
}
return true;
});
popupMenu.show();
});
sendButton.setOnClickListener((View v) -> {
if (!msgEditText.getText().toString().trim().isEmpty()) {
ChatModel chatModel = new ChatModel();
chatModel.setSENDER_TYPE(USER_TYPE);
chatModel.setMsg(msgEditText.getText().toString());
chatModel.setMsgTime(getCurrentStringTime());
chatModel.setMsgDate(getCurrentStringDate());
uploadMessage(chatModel);
}
});
if (USER_TYPE == SENDER_BOATER || USER_TYPE == SENDER_MARINA) {
ContactAdminViewModel contactAdminViewModel = ViewModelProviders.of(this, new ContactAdminViewModelFactory(adminID, userID)).get(ContactAdminViewModel.class);
LiveData<DataSnapshot> liveData = contactAdminViewModel.getDataSnapshotLiveData();
liveData.observe(this, dataSnapshot -> {
ArrayList<ChatModel> chatModelArrayList = new ArrayList<>();
for (DataSnapshot snapshot : dataSnapshot.child("messages").getChildren()) {
ChatModel chatModel = snapshot.getValue(ChatModel.class);
if (chatModel.getSENDER_TYPE() == SENDER_BOATER) {
chatModel.setMsgName(userName);
} else {
chatModel.setMsgName("Navismart");
}
chatModelArrayList.add(chatModel);
}
ChatAdapter reviewListAdapter = new ChatAdapter(chatModelArrayList, getContext());
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getContext());
((LinearLayoutManager) mLayoutManager).setStackFromEnd(true);
chatRecyclerView.setLayoutManager(mLayoutManager);
chatRecyclerView.setItemAnimator(new DefaultItemAnimator());
chatRecyclerView.setAdapter(reviewListAdapter);
});
} else {
ContactAdminViewModel contactAdminViewModel = ViewModelProviders.of(this, new ContactAdminViewModelFactory(userID, adminID)).get(ContactAdminViewModel.class);
LiveData<DataSnapshot> liveData = contactAdminViewModel.getDataSnapshotLiveData();
liveData.observe(this, dataSnapshot -> {
ArrayList<ChatModel> chatModelArrayList = new ArrayList<>();
for (DataSnapshot snapshot : dataSnapshot.child("messages").getChildren()) {
ChatModel chatModel = snapshot.getValue(ChatModel.class);
if (chatModel.getSENDER_TYPE() == SENDER_BOATER) {
chatModel.setMsgName("Navismart");
} else {
chatModel.setMsgName(userName);
}
chatModelArrayList.add(chatModel);
}
ChatAdapter reviewListAdapter = new ChatAdapter(chatModelArrayList, getContext());
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getContext());
((LinearLayoutManager) mLayoutManager).setStackFromEnd(true);
chatRecyclerView.setLayoutManager(mLayoutManager);
chatRecyclerView.setItemAnimator(new DefaultItemAnimator());
chatRecyclerView.setAdapter(reviewListAdapter);
});
}
return view;
}
private void deleteAllChats() {
DatabaseReference chatReference;
String id = "";
if (USER_TYPE == SENDER_BOATER || USER_TYPE == SENDER_MARINA)
id = adminID;
else
id = userID;
chatReference = databaseReference.child("users").child(auth.getCurrentUser().getUid()).child("contactAdmin").child(id).child("messages");
chatReference.setValue(null)
.addOnSuccessListener(aVoid -> Toast.makeText(getContext(), "Chats deleted successfully", Toast.LENGTH_SHORT).show()).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(getContext(), "Unable to delete chats", Toast.LENGTH_SHORT).show();
}
});
}
private void uploadMessage(ChatModel chatModel) {
DatabaseReference chatReference;
chatReference = databaseReference.child("users").child(userID).child("contactAdmin").child(adminID).child("messages");
chatReference.push().setValue(chatModel).addOnSuccessListener(aVoid -> msgEditText.setText(null));
chatReference = databaseReference.child("users").child(userID).child("contactAdmin").child(adminID).child("userName");
chatReference.setValue(userName);
chatReference = databaseReference.child("users").child(userID).child("contactAdmin").child(adminID).child("adminName");
chatReference.setValue("Navismart");
chatReference = databaseReference.child("users").child(adminID).child("contactAdmin").child(userID).child("messages");
chatReference.push().setValue(chatModel).addOnSuccessListener(aVoid -> msgEditText.setText(null));
chatReference = databaseReference.child("users").child(adminID).child("contactAdmin").child(userID).child("userName");
chatReference.setValue(userName);
chatReference = databaseReference.child("users").child(adminID).child("contactAdmin").child(userID).child("adminName");
chatReference.setValue("Navismart");
String userToken = "", adminToken = "";
if (USER_TYPE == SENDER_BOATER || USER_TYPE == SENDER_MARINA) {
adminToken = receiverToken;
userToken = preferencesHelper.getToken();
} else {
adminToken = preferencesHelper.getToken();
userToken = receiverToken;
}
chatReference = databaseReference.child("users").child(userID).child("contactAdmin").child(adminID).child("userToken");
chatReference.setValue(userToken);
chatReference = databaseReference.child("users").child(userID).child("contactAdmin").child(adminID).child("adminToken");
chatReference.setValue(adminToken);
chatReference = databaseReference.child("users").child(adminID).child("contactAdmin").child(userID).child("userToken");
chatReference.setValue(userToken);
chatReference = databaseReference.child("users").child(adminID).child("contactAdmin").child(userID).child("adminToken");
chatReference.setValue(adminToken);
sendNotification(receiverToken, chatModel.getMsg());
}
private void sendNotification(String regToken, String msg) {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
try {
OkHttpClient client = new OkHttpClient();
JSONObject json = new JSONObject();
JSONObject dataJson = new JSONObject();
dataJson.put("body", msg);
dataJson.put("title", auth.getCurrentUser().getDisplayName());
json.put("notification", dataJson);
json.put("to", regToken);
RequestBody body = RequestBody.create(JSON, json.toString());
Request request = new Request.Builder()
.header("Authorization", "key=" + BuildConfig.LEGACY_SERVER_KEY)
.url("https://fcm.googleapis.com/fcm/send")
.post(body)
.build();
Response response = client.newCall(request).execute();
String finalResponse = response.body().string();
} catch (Exception e) {
Log.d("Notification Error: ", e.toString());
}
return null;
}
}.execute();
}
}
| 43.603604 | 180 | 0.646901 |
Description: This dataset is drawn from TheStack Corpus, an open-source code dataset with over 3TB of GitHub data covering 48 programming languages. We selected a small portion of this dataset to optimize smaller language models for Java, a popular statically typed language.
Target Language: Java
Dataset Size:
Preprocessing:
Tokenizer: Byte Pair Encoding (BPE) tokenizer with tab and whitespace tokens. GPT-2 vocabulary extended with special tokens.
Training Sequences: Sequences constructed by joining training data text to reach a context length of 2048 tokens (1024 tokens for full fine-tuning).