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
|
|---|---|---|---|---|---|
e5aef2a658bb404d61abe0cd6afbe2e32ee8026c
| 1,625
|
/*
* Copyright (C) 2020 Tirasa (info@tirasa.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.syncope.client.enduser.rest;
import static org.apache.syncope.client.enduser.rest.BaseRestClient.LOG;
import static org.apache.syncope.client.enduser.rest.BaseRestClient.getService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.syncope.common.lib.SyncopeClientException;
import org.apache.syncope.common.lib.to.AttrTO;
import org.apache.syncope.common.rest.api.service.ConfigurationService;
public class ConfigurationRestClient extends BaseRestClient {
private static final long serialVersionUID = -2942072025958227690L;
public static String getFormLayout(final String name) {
try {
AttrTO confParam = getService(ConfigurationService.class).get(name);
return CollectionUtils.isNotEmpty(confParam.getValues()) ? confParam.getValues().get(0) : null;
} catch (SyncopeClientException e) {
LOG.error("While reading configuration parameter [{}]", name, e);
}
return null;
}
}
| 40.625
| 107
| 0.739692
|
f8208f3b8ca2ba53a54dabebd8bd93cfd18e8933
| 1,743
|
/*
*/
package io.moquette.broker;
import java.io.File;
/**
* Created by andrea on 08/12/15.
*/
public class BrokerConstants {
public static final String PERSISTENT_STORE_PROPERTY_NAME = "persistent_store";
public static final String AUTOSAVE_INTERVAL_PROPERTY_NAME = "autosave_interval";
public static final String PASSWORD_FILE_PROPERTY_NAME = "password_file";
public static final String PORT_PROPERTY_NAME = "port";
public static final String HOST_PROPERTY_NAME = "host";
public static final String DEFAULT_MOQUETTE_STORE_MAP_DB_FILENAME = "moquette_store.mapdb";
public static final String DEFAULT_PERSISTENT_PATH = System.getProperty("user.dir") + File.separator + DEFAULT_MOQUETTE_STORE_MAP_DB_FILENAME;
public static final String WEB_SOCKET_PORT_PROPERTY_NAME = "websocket_port";
public static final String WSS_PORT_PROPERTY_NAME = "secure_websocket_port";
public static final String SSL_PORT_PROPERTY_NAME = "ssl_port";
public static final String JKS_PATH_PROPERTY_NAME = "jks_path";
public static final String KEY_STORE_PASSWORD_PROPERTY_NAME = "key_store_password";
public static final String KEY_MANAGER_PASSWORD_PROPERTY_NAME = "key_manager_password";
public static final String ALLOW_ANONYMOUS_PROPERTY_NAME = "allow_anonymous";
public static final String ACL_FILE_PROPERTY_NAME = "acl_file";
public static final String AUTHORIZATOR_CLASS_NAME = "authorizator_class";
public static final String AUTHENTICATOR_CLASS_NAME = "authenticator_class";
public static final int PORT = 1883;
public static final int WEBSOCKET_PORT = 8080;
public static final String HOST = "0.0.0.0";
public static final String NEED_CLIENT_AUTH = "need_client_auth";
}
| 52.818182
| 146
| 0.787149
|
a838ceaf5d1602d6d0574632a92e90afec751d9c
| 31,212
|
/*
* Copyright 2016-present Tzutalin
*
* 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 mayank.example.rtcamera;
import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Point;
import android.media.Image;
import android.media.Image.Plane;
import android.media.ImageReader;
import android.media.ImageReader.OnImageAvailableListener;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Trace;
import android.support.annotation.RequiresApi;
import android.util.Base64;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;
import android.widget.ImageView;
import com.chaquo.python.PyObject;
import com.chaquo.python.Python;
import com.tzutalin.dlib.Constants;
import com.tzutalin.dlib.FaceDet;
import com.tzutalin.dlib.VisionDetRet;
import com.tzutalin.dlibtest.ImageUtils;
import junit.framework.Assert;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static java.lang.Math.PI;
import static java.lang.Math.atan2;
import static java.lang.Math.log;
/**
* Class that takes in preview frames and converts the image to Bitmaps to process with dlib lib.
*/
public class finalOnGetImageListener implements OnImageAvailableListener {
private static final boolean SAVE_PREVIEW_BITMAP = false;
//324, 648, 972, 1296, 224, 448, 672, 976, 1344
private static final int INPUT_SIZE = 976;
private static final String TAG = "finalOnGetImageListener";
private static final Map<Integer, String> emotionMap = createMap();
private int mScreenRotation = 90;
private List<VisionDetRet> results;
private int mPreviewWdith = 0;
private int mPreviewHeight = 0;
private byte[][] mYUVBytes;
private int[] mRGBBytes = null;
private Bitmap mRGBframeBitmap = null;
private Bitmap mCroppedBitmap = null;
private Bitmap mResizedBitmap = null;
private Bitmap mInversedBipmap = null;
private boolean mIsComputing = false;
private Handler mInferenceHandler;
private Context mContext;
private FaceDet mFaceDet;
private ImageView imageView;
private TrasparentTitleView mTransparentTitleView;
private FloatingCameraWindow mWindow;
private Paint mFaceLandmardkPaint;
private Paint myPaint;
private Paint bluePaint;
private int mframeNum = 0;
private EmotionInference emotionInference;
private String filename;
private Canvas canvas;
private ArrayList<Point> landmarks;
private int count = 0;
private File mediaStorageDir;
private File mediaStorageDir2;
private File mediaStorageDir3;
private BufferedWriter bufferedWriter;
private String LogFileName;
private String tempLogFileName;
private ArrayList<String> boxesList;
private ArrayList<ArrayList> landmarksList;
private ArrayList<Float>hogList;
List<PyObject> hogList1;
private String logOrNot;
private String SaveOrNot;
private File fileLogfile;
private double imagefileCounter;
private static Map<Integer, String> createMap() {
Map<Integer, String> myMap = new HashMap<>();
myMap.put(0, "Bored");
myMap.put(1, "Confused");
myMap.put(2, "Delighted");
myMap.put(3, "Frustrated");
return myMap;
}
public void initialize(
final Context context,
final AssetManager assetManager,
final TrasparentTitleView scoreView,
final Handler handler) throws IOException {
this.mContext = context;
this.mTransparentTitleView = scoreView;
this.mInferenceHandler = handler;
mFaceDet = new FaceDet(Constants.getFaceShapeModelPath());
mWindow = new FloatingCameraWindow(mContext);
mWindow.release();
mFaceLandmardkPaint = new Paint();
mFaceLandmardkPaint.setColor(Color.GREEN);
mFaceLandmardkPaint.setStrokeWidth(2);
mFaceLandmardkPaint.setStyle(Paint.Style.STROKE);
myPaint = new Paint();
myPaint.setColor(Color.RED);
myPaint.setStrokeWidth(1);
myPaint.setStyle(Paint.Style.STROKE);
bluePaint = new Paint();
bluePaint.setColor(Color.BLUE);
bluePaint.setStrokeWidth(4);
bluePaint.setStyle(Paint.Style.STROKE);
emotionInference = new EmotionInference(context);
imagefileCounter = 0;
mediaStorageDir = new File(Environment.getExternalStorageDirectory(), "RoboFeel");
//RoboFeel directory
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("App", "failed to create directory - Robofeel");
}
}
mediaStorageDir2 = new File(mediaStorageDir, "Images");
//images directory
if (!mediaStorageDir2.exists()) {
if (!mediaStorageDir2.mkdirs()) {
Log.d("App", "failed to create directory - images");
}
}
try {
logOrNot = getToLogOrNotVariable();
} catch (JSONException e) {
//default
logOrNot = "false";
e.printStackTrace();
}
try {
SaveOrNot = getToSaveImagesOrNotVariable();
} catch (JSONException e) {
//default
SaveOrNot = "false";
e.printStackTrace();
}
Date currentTime = Calendar.getInstance().getTime();
Log.d("Listener","Creating log file for current session");
if(logOrNot.equals("true"));
{
mediaStorageDir3 = new File(mediaStorageDir2, "Images_"+currentTime);
//images per session directory
if (!mediaStorageDir3.exists()) {
if (!mediaStorageDir3.mkdirs()) {
Log.d("App", "failed to create directory - images per session");
}
}
LogFileName = mediaStorageDir + "/RoboFeelLogs_" + currentTime + ".json";
tempLogFileName = mediaStorageDir + "/TEMPRoboFeelLogs_" + currentTime + ".json";
// Define the File Path and its Name
fileLogfile = new File(LogFileName);
FileWriter fileWriter = new FileWriter(fileLogfile);
bufferedWriter = new BufferedWriter(fileWriter);
}
}
public void deInitialize() throws Exception {
synchronized (finalOnGetImageListener.this) {
cleanLogFile();
if (mFaceDet != null) {
mFaceDet.release();
}
if (mWindow != null) {
mWindow.release();
}
}
}
public static String convertStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
reader.close();
return sb.toString();
}
public void cleanLogFile() throws Exception {
bufferedWriter.close();
File file = new File(tempLogFileName);
Log.d(TAG,"Delete last incomplete entry");
FileInputStream reader = new FileInputStream(LogFileName);
BufferedWriter writer = new BufferedWriter(new FileWriter(tempLogFileName));
String jsonfiletext = convertStreamToString(reader);
String finalText_for_comma = jsonfiletext;
try {
String finalText_for_bracket = jsonfiletext.substring(0, jsonfiletext.lastIndexOf('{'));
finalText_for_comma = finalText_for_bracket.substring(0, finalText_for_bracket.length() - 1);
}
catch(Exception e){
e.printStackTrace();
}
writer.write(finalText_for_comma);
fileLogfile.delete();
if(file.renameTo(fileLogfile)) {
Log.d(TAG,"renamed");
} else {
Log.d(TAG,"Error");
}
writer.close();
reader.close();
}
private void drawResizedBitmap(final Bitmap src, final Bitmap dst) {
Display getOrient = ((WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int orientation = Configuration.ORIENTATION_UNDEFINED;
Point point = new Point();
getOrient.getSize(point);
int screen_width = point.x;
int screen_height = point.y;
//Log.d(TAG, String.format("screen size (%d,%d)", screen_width, screen_height));
if (screen_width < screen_height) {
orientation = Configuration.ORIENTATION_PORTRAIT;
mScreenRotation = -90;
} else {
orientation = Configuration.ORIENTATION_LANDSCAPE;
mScreenRotation = 0;
}
if (Build.MODEL.equals("Nexus 6P")){
// rotate camera 180°
//Log.d(TAG, "Nexus 6p device being used.");
mScreenRotation = +90;
}
Assert.assertEquals(dst.getWidth(), dst.getHeight());
final float minDim = Math.min(src.getWidth(), src.getHeight());
final Matrix matrix = new Matrix();
// We only want the center square out of the original rectangle.
final float translateX = -Math.max(0, (src.getWidth() - minDim) / 2);
final float translateY = -Math.max(0, (src.getHeight() - minDim) / 2);
matrix.preTranslate(translateX, translateY);
final float scaleFactor = dst.getHeight() / minDim;
matrix.postScale(scaleFactor, scaleFactor);
// Rotate around the center if necessary.
if (mScreenRotation != 0) {
matrix.postTranslate(-dst.getWidth() / 2.0f, -dst.getHeight() / 2.0f);
matrix.postRotate(mScreenRotation);
matrix.postTranslate(dst.getWidth() / 2.0f, dst.getHeight() / 2.0f);
}
final Canvas canvas = new Canvas(dst);
canvas.drawBitmap(src, matrix, null);
}
public Bitmap imageSideInversion(Bitmap src) {
Matrix sideInversion = new Matrix();
sideInversion.setScale(-1, 1);
Bitmap inversedImage = Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), sideInversion, false);
return inversedImage;
}
@Override
public void onImageAvailable(final ImageReader reader) {
Log.e("finalOnGetImageListener","Image Avaialble");
Image image = null;
try {
image = reader.acquireLatestImage();
/*
TO LOG:
1. imageFilename
2. Number of faces detected
3. Bounding boxes of faces
4. Landmarks
5. HOG
*/
if (image == null) {
Log.d(TAG,"returning null");
return;
}
// No mutex needed as this method is not reentrant.
if (mIsComputing) {
image.close();
return;
}
mIsComputing = true;
Trace.beginSection("imageAvailable");
final Plane[] planes = image.getPlanes();
// Initialize the storage bitmaps once when the resolution is known.
if (mPreviewWdith != image.getWidth() || mPreviewHeight != image.getHeight()) {
Log.d(TAG,"seting sizes..");
mPreviewWdith = image.getWidth();
mPreviewHeight = image.getHeight();
//Log.d(TAG, String.format("Initializing at size %dx%d", mPreviewWdith, mPreviewHeight));
mRGBBytes = new int[mPreviewWdith * mPreviewHeight];
mRGBframeBitmap = Bitmap.createBitmap(mPreviewWdith, mPreviewHeight, Config.ARGB_8888);
mCroppedBitmap = Bitmap.createBitmap(INPUT_SIZE, INPUT_SIZE, Config.ARGB_8888);
mYUVBytes = new byte[planes.length][];
for (int i = 0; i < planes.length; ++i) {
mYUVBytes[i] = new byte[planes[i].getBuffer().capacity()];
}
}
Log.d("Planes length", String.valueOf(planes.length));
for (int i = 0; i < planes.length; ++i) {
planes[i].getBuffer().get(mYUVBytes[i]);
}
final int yRowStride = planes[0].getRowStride();
final int uvRowStride = planes[1].getRowStride();
final int uvPixelStride = planes[1].getPixelStride();
ImageUtils.convertYUV420ToARGB8888(
mYUVBytes[0],
mYUVBytes[1],
mYUVBytes[2],
mRGBBytes,
mPreviewWdith,
mPreviewHeight,
yRowStride,
uvRowStride,
uvPixelStride,
false);
image.close();
} catch (final Exception e) {
if (image != null) {
image.close();
}
Log.e(TAG, "Exception!", e);
Trace.endSection();
return;
}
mRGBframeBitmap.setPixels(mRGBBytes, 0, mPreviewWdith, 0, 0, mPreviewWdith, mPreviewHeight);
drawResizedBitmap(mRGBframeBitmap, mCroppedBitmap);
mInversedBipmap = imageSideInversion(mCroppedBitmap);
mResizedBitmap = Bitmap.createScaledBitmap(mInversedBipmap, (int) (INPUT_SIZE / 4.5), (int) (INPUT_SIZE / 4.5), true);
mInferenceHandler.post(
new Runnable() {
@Override
public void run() {
if (!new File(Constants.getFaceShapeModelPath()).exists()) {
//mTransparentTitleView.setText("Copying landmark model to " + Constants.getFaceShapeModelPath());
FileUtils.copyFileFromRawToOthers(mContext, R.raw.shape_predictor_68_face_landmarks, Constants.getFaceShapeModelPath());
}
if (mframeNum % 5 == 0) {
long startTime = System.currentTimeMillis();
synchronized (finalOnGetImageListener.this) {
Log.e(TAG, "detect_being_called");
results = mFaceDet.detect(mResizedBitmap);
if (results != null) {
Log.e(TAG, results.toString());
}
}
long endTime = System.currentTimeMillis();
//mTransparentTitleView.setText("Time cost: " + String.valueOf((endTime - startTime) / 1000f) + " sec");
Log.e("onGetImageListener", results.toString());
// Draw on bitmap
boxesList = new ArrayList();
landmarksList = new ArrayList<>();
if (results.size() != 0) {
for (final VisionDetRet ret : results) {
float resizeRatio = 4.5f;
// Draw landmark
landmarks = ret.getFaceLandmarks();
String name = landmarks.get(0).getClass().getName();
Log.e("landmarks type = ", name);
landmarksList.add(landmarks);
boxesList.add(ret.toString());
String s = ret.getLabel();
Log.d(TAG, "label = " + s);
findEmotion(landmarks, resizeRatio);
}
}
/*
TO LOG:
1. imageFilename
2. Number of faces detected
3. Bounding boxes of faces
4. Landmarks
5. HOG
*/
// Draw on bitmap
if (results.size() != 0) {
/*
READ CONFIG.JSON AND SEE IF VALUES HAVE TO BE LOGGED OR NOT
*/
if (logOrNot.equalsIgnoreCase("true")) {
//logging code
Date imageTime = Calendar.getInstance().getTime();
Date time = Calendar.getInstance().getTime();
filename = mediaStorageDir3 + "/images_" + imageTime.toString() + "_" + imagefileCounter + ".jpg";
if (SaveOrNot.equalsIgnoreCase("true")) {
//to save images or not
try (FileOutputStream out = new FileOutputStream(filename)) {
//save bitmap
//bmp.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
Python py = Python.getInstance();
PyObject pyobj = py.getModule("image_processing");
Bitmap mTestBitmap = mResizedBitmap.copy(mResizedBitmap.getConfig(), true);
String HOGimgString = getStringImage(mTestBitmap);
//Log.e("boxes list size = ", boxesList.get(0));
PyObject obj = pyobj.callAttr("main", HOGimgString, boxesList);
String str = obj.asList().get(0).toString();
hogList1 = obj.asList().get(1).asList();
// hogList = new ArrayList<>();
// for(int i=0; i< hogList1.size();i++)
// {
// hogList.add(hogList1.get(i).toFloat());
// }
Log.e("HOG size = ",Integer.toString(hogList1.size()));
byte data[] = android.util.Base64.decode(str, Base64.DEFAULT);
final Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
//mResizedBitmap.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
bmp.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
// PNG is a lossless format, the compression factor (100) is ignored
} catch (IOException e) {
e.printStackTrace();
}
} else {
filename = "Image-not-saved";
}
imagefileCounter++;
JSONObject objectToLog = new JSONObject();
try {
objectToLog.put("ImageFilename", filename);
objectToLog.put("Number of Faces", results.size());
objectToLog.put("Bounding boxes", boxesList);
objectToLog.put("Landmarks", landmarksList);
objectToLog.put("HOGS",hogList1);
//Log.e("checking it",objectToLog.toString());
String userString = objectToLog.toString();
bufferedWriter.write(userString);
bufferedWriter.write("\n");
} catch (JSONException | IOException e) {
e.printStackTrace();
}
}
// Draw on bitmap
for (final VisionDetRet ret : results) {
float resizeRatio = 4.5f;
// Draw landmark
landmarks = ret.getFaceLandmarks();
String s = ret.getLabel();
Log.d(TAG, "label = " + s);
//findEmotion(landmarks, resizeRatio);
drawOnBitmap(landmarks, resizeRatio);
}
}
}
mframeNum++;
// mWindow.setRGBBitmap(mInversedBipmap);
mIsComputing = false;
}
});
Trace.endSection();
}
private String getStringImage(Bitmap mInversedBipmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
mInversedBipmap.compress(Bitmap.CompressFormat.PNG,100,baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = android.util.Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
private void drawOnBitmap(ArrayList<Point> landmarks, float resizeRatio) {
Canvas canvas = new Canvas(mInversedBipmap);
float[] xlist = new float[68];
float[] ylist = new float[68];
float x_coord;
float y_coord;
float x_mean;
float y_mean;
int index = 0;
float x_sum = 0;
float y_sum = 0;
for (Point point : landmarks) {
int pointX = (int) (point.x * resizeRatio);
int pointY = (int) (point.y * resizeRatio);
canvas.drawCircle(pointX, pointY, 4, mFaceLandmardkPaint);
x_coord = pointX;
y_coord = pointY;
//Log.d("TAG", "x coord = " + x_coord);
//Log.d("TAG", "y coord = " + y_coord);
x_sum += x_coord;
y_sum += y_coord;
//Log.d("TAG", "x sum = " + x_sum);
//Log.d("TAG", "y sum= " + y_sum);
xlist[index] = x_coord;
ylist[index] = y_coord;
index++;
}
x_mean = x_sum / index;
y_mean = y_sum / index;
canvas.drawCircle(x_mean, y_mean, 4, bluePaint);
for (int i = 0; i < 68; i++) {
canvas.drawLine(x_mean, y_mean, xlist[i], ylist[i], myPaint);
}
}
private String getToLogOrNotVariable() throws IOException, JSONException {
String dataPath = "/sdcard/Download" + "/config.json";
String logOrNot;
InputStream is = new FileInputStream(dataPath);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String myJson = new String(buffer, "UTF-8");
JSONObject obj = new JSONObject(myJson);
logOrNot = obj.getString("robofeel_log_items_or_not");
Log.d("myJson-LogOrNot",logOrNot);
return logOrNot;
}
private String getToSaveImagesOrNotVariable() throws IOException, JSONException {
String dataPath = "/sdcard/Download" + "/config.json";
String SaveOrNot;
InputStream is = new FileInputStream(dataPath);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String myJson = new String(buffer, "UTF-8");
JSONObject obj = new JSONObject(myJson);
SaveOrNot = obj.getString("robofeel_save_images_or_not");
Log.d("myJson-LogOrNot",SaveOrNot);
return SaveOrNot;
}
private void findEmotion(ArrayList<Point> landmarks, float resizeRatio) {
Log.d("Emotion", "Finding Emotion");
int index = 0;
float x_sum = 0;
float y_sum = 0;
float[] xlist = new float[68];
float[] ylist = new float[68];
float x_coord;
float y_coord;
float x_mean;
float y_mean;
for (Point point : landmarks) {
int pointX = (int) (point.x * resizeRatio);
int pointY = (int) (point.y * resizeRatio);
//canvas.drawCircle(pointX, pointY, 4, mFaceLandmardkPaint);
//Log.d(TAG, "Landmark number - " + count);
//Log.d(TAG, "X, Y Coordinates = (" + pointX + "," + pointY + ")");
//count++;
x_coord = pointX;
y_coord = pointY;
//Log.d("TAG", "x coord = " + x_coord);
//Log.d("TAG", "y coord = " + y_coord);
x_sum += x_coord;
y_sum += y_coord;
//Log.d("TAG", "x sum = " + x_sum);
//Log.d("TAG", "y sum= " + y_sum);
xlist[index] = x_coord;
ylist[index] = y_coord;
index++;
}
//Log.d(TAG, "Xlist = " + xlist);
//Log.d(TAG, "Ylist = " + ylist.toString());
x_mean = x_sum / index;
y_mean = y_sum / index;
//Log.d(TAG, "x_central = " + x_mean);
//Log.d(TAG, "y_central = " + y_mean);
//Log.d(TAG, "Index = " + index);
//Log.d("TAG", "OUTSIDE LOOP");
//Log.d("TAG", "Index = " + index);
//Log.d("TAG", "x sum = " + x_sum);
//Log.d("TAG", "y sum= " + y_sum);
//canvas.drawCircle(x_mean, y_mean, 4, bluePaint);
//for (int i = 0; i < 68; i++) {
// canvas.drawLine(x_mean, y_mean, xlist[i], ylist[i], myPaint);
//}
float[] xcentral = new float[68];
float[] ycentral = new float[68];
float n1;
float n2;
for (int i = 0; i < 68; i++) {
n1 = xlist[i] - x_mean;
n2 = ylist[i] - y_mean;
xcentral[i] = n1;
ycentral[i] = n2;
}
float[] landmarks_vectorised = new float[136];
int landmarks_index = 0;
float max = -1;
for (int i = 0; i < 68; i++) {
float d = (float) Math.sqrt(Math.pow(xcentral[i] - x_mean, 2) + Math.pow(ycentral[i] - y_mean, 2));
landmarks_vectorised[landmarks_index] = (float) d;
//Log.d(TAG, "landmarks_index = " + landmarks_index + " d = " + d);
if (max <= d) max = d;
landmarks_index++;
float angle = (float) (atan2(ycentral[i] - y_mean, xcentral[i] - x_mean) * 180 / PI);
landmarks_vectorised[landmarks_index] = (float) angle;
//Log.d(TAG, "landmarks_index = " + landmarks_index + " angle = " + angle);
if (max <= angle) max = angle;
landmarks_index++;
}
List input;
input = new ArrayList();
for (int i = 0; i < landmarks_vectorised.length; i++) {
//Log.d(TAG, "index = " + i + " val = " + landmarks_vectorised[i]);
float n;
n = landmarks_vectorised[i];
n = n / max;
input.add(n);
}
int required_size = 136;
if (input.size() == required_size) {// calling emotionPrediction function only when input size is 136
emotionPrediction(input);
Log.d(TAG, "Size of input = " + required_size);
Log.d(TAG, "Input = " + input.toString());
}
}
private void emotionPrediction(List input) {
List random_list;
random_list = new ArrayList();
float n1 = 1;
float n2 = 2;
float n3 = 3;
float n4 = 4;
float n5 = 5;
float n6 = 6;
random_list.add(n1);
random_list.add(n2);
random_list.add(n3);
random_list.add(n4);
random_list.add(n5);
random_list.add(n6);
Log.d("Mayank", "Random list = " + random_list.toString());
float[] random_array = toFloatArray(random_list);
Log.d("Mayank", "Random array = " + random_array.toString());
float[] results = emotionInference.getEmotionProb(toFloatArray(input));
Log.d(TAG, "In emotion prediction function");
Log.d("Mayank", "results = " + results.toString());
if (results.length > 0) {
Log.d(TAG, "Length of results > 0");
float max_emotion = -1;
int max_index = -1;
for (int i = 0; i < results.length; i++) {
Log.d(TAG, "results[" + i + "] = " + results[i]);
if (max_emotion < results[i]) {
max_emotion = results[i];
max_index = i;
}
}
String emotion = emotionMap.get(max_index);
Log.d(TAG, "emotion = " + emotion);
//Toast.makeText(mContext.getApplicationContext(), "Emotion = " + emotion, Toast.LENGTH_SHORT).show();
try {
mTransparentTitleView.setText("Emotion = " + emotion);
}
catch(Exception e)
{
Log.d(TAG, String.valueOf(e.getStackTrace()));
}
}
}
private float[] toFloatArray(List list) {
int i = 0;
float[] array = new float[list.size()];
for (Object f : list) {
array[i++] = f != null ? (float) f : Float.NaN;
}
return array;
}
}
| 35.793578
| 148
| 0.527489
|
1593c80b169156d75d494d27c560a0949b10854c
| 2,111
|
package commitminer.analysis.flow.factories;
import java.util.Map;
import org.apache.commons.lang3.tuple.Pair;
import org.mozilla.javascript.ast.AstNode;
import org.mozilla.javascript.ast.ScriptNode;
import commitminer.analysis.flow.abstractdomain.Addresses;
import commitminer.analysis.flow.abstractdomain.Change;
import commitminer.analysis.flow.abstractdomain.Environment;
import commitminer.analysis.flow.abstractdomain.Helpers;
import commitminer.analysis.flow.abstractdomain.Store;
import commitminer.analysis.flow.abstractdomain.Variable;
import commitminer.analysis.flow.trace.Trace;
import commitminer.cfg.CFG;
/**
* Initializes the environment from a JavaScript file AST.
*/
public class EnvironmentFactory {
private static final Integer GLOBAL_DEFINER_ID = -1;
/**
* Creates an initial environment for a function by lifting local variables
* and functions into the environment. Local variables are initialized to
* undefined in the store, while functions are initialized to objects.
*
* Variables are initialized in the store after the environment has been
* computed. Variables that point to functions are initialized recursively
* so that their closure can be properly computed.
* @param script The root of the AST for the file under analysis.
* @param store The initial store, variable values and functions will be
* initialized here.
* @param trace The trace, which should be empty initially.
* @return The initial ρ ∈ Environment
*/
public static Pair<Environment, Store> createInitialEnvironment(ScriptNode script, Store store, Map<AstNode, CFG> cfgs, Trace trace) {
Environment env = createBaseEnvironment();
store = Helpers.lift(env, store, script, cfgs, trace);
return Pair.of(env, store);
}
/**
* @return The global environment of builtins, without user defined variables.
*/
private static Environment createBaseEnvironment() {
Environment env = new Environment();
env = env.strongUpdate("this", new Variable(GLOBAL_DEFINER_ID, "this", Change.u(), new Addresses(StoreFactory.global_binding_Addr, Change.u())));
return env;
}
}
| 39.092593
| 147
| 0.778304
|
330980c8e57ac5d37b52b932d74d8aeafc8d27d9
| 300
|
package com.qlzw.smartwc.repository;
import com.qlzw.smartwc.model.Mp_dev_link;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface Mp_dev_linkRepository extends JpaRepository <Mp_dev_link,Long> {}
| 30
| 84
| 0.82
|
351e23cef0f116a663c72fb9e6c442a52e2792bb
| 1,601
|
package org.wefine.spring.config.core;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(final HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/css/**", "/index.html").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasRole("USER")
.antMatchers("/shared/**").hasAnyRole("USER", "ADMIN")
.and()
.logout().logoutSuccessUrl("/index.html")
.and()
.formLogin().loginPage("/login.html").failureUrl("/error.html")
.and()
.exceptionHandling()
.accessDeniedPage("/403.html");
}
@Override
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("jim").password("demo").roles("ADMIN")
.and()
.withUser("bob").password("demo").roles("USER")
.and()
.withUser("ted").password("demo").roles("USER", "ADMIN");
}
}
| 39.04878
| 107
| 0.671455
|
eb6e890472b58910d4d3be462b64d989bb72471a
| 1,176
|
package com.joymain.jecs.bd.service;
import java.util.List;
import com.joymain.jecs.service.Manager;
import com.joymain.jecs.bd.model.JbdCaculateLog;
import com.joymain.jecs.bd.dao.JbdCaculateLogDao;
import com.joymain.jecs.util.data.CommonRecord;
import com.joymain.jecs.util.data.Pager;
public interface JbdCaculateLogManager extends Manager {
/**
* Retrieves all of the jbdCaculateLogs
*/
public List getJbdCaculateLogs(JbdCaculateLog jbdCaculateLog);
/**
* Gets jbdCaculateLog's information based on id.
* @param id the jbdCaculateLog's id
* @return jbdCaculateLog populated jbdCaculateLog object
*/
public JbdCaculateLog getJbdCaculateLog(final String id);
/**
* Saves a jbdCaculateLog's information
* @param jbdCaculateLog the object to be saved
*/
public void saveJbdCaculateLog(JbdCaculateLog jbdCaculateLog);
/**
* Removes a jbdCaculateLog from the database by id
* @param id the jbdCaculateLog's id
*/
public void removeJbdCaculateLog(final String id);
//added for getJbdCaculateLogsByCrm
public List getJbdCaculateLogsByCrm(CommonRecord crm, Pager pager);
}
| 30.153846
| 71
| 0.736395
|
fa324f1dd0e13ab94bf417f65aa1ae556001c805
| 470
|
package com.blazemeter.jmeter.citrix.client.events;
import com.blazemeter.jmeter.citrix.client.CitrixClient;
/**
* Represents details about events occured during a Citrix session.
*/
public interface EventInfo {
/**
* Gets the source of this event
*
* @return the source of this event
*/
CitrixClient getSource();
/**
* Gets the timestamp of this event
*
* @return the timestamp of this event
*/
long getTimestamp();
}
| 19.583333
| 68
| 0.670213
|
7356f6474936700dd6ef65fe4f9c804485770fad
| 707
|
package measure.base;
import java.util.Set;
/**
* @author rabbanyk
*
* @param <V>
*
* <pre> argmin_m d(x,m) </pre>
*/
public class Medoid<V> implements Centroid<V>{
Proximity<V> proximity;
public Medoid(Proximity<V> distance){
this.proximity = distance;
}
public V findCentroid(Set<V> X) {
V center = null;
double sum = 0, sumd;
for (V x : X) {
sumd = 0;
for (V y : X) if(x!=y){
sumd += proximity.getProximity(y, x).doubleValue();
}
if(center == null || (proximity.isSimilarity()?(sum < sumd):(sum > sumd))){
center = x;
sum = sumd;
}
}
return center;
}
public String toString(){
return "MedoidBasedOn "+proximity;
}
}
| 14.729167
| 78
| 0.577086
|
557e8947d6bec278ed8b2cfad90fced5f940cc1d
| 4,544
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.structureView;
import com.intellij.testFramework.TestDataPath;
import org.jetbrains.kotlin.test.JUnit3RunnerWithInners;
import org.jetbrains.kotlin.test.KotlinTestUtils;
import org.jetbrains.kotlin.test.TestMetadata;
import org.jetbrains.kotlin.test.TestRoot;
import org.junit.runner.RunWith;
/*
* This class is generated by {@link org.jetbrains.kotlin.generators.tests.TestsPackage}.
* DO NOT MODIFY MANUALLY.
*/
@SuppressWarnings("all")
@TestRoot("idea/tests")
@TestDataPath("$CONTENT_ROOT")
@RunWith(JUnit3RunnerWithInners.class)
@TestMetadata("testData/structureView/fileStructure")
public class KotlinFileStructureTestGenerated extends AbstractKotlinFileStructureTest {
private void runTest(String testDataFilePath) throws Exception {
KotlinTestUtils.runTest(this::doTest, this, testDataFilePath);
}
@TestMetadata("AnonymousObjectMembers.kt")
public void testAnonymousObjectMembers() throws Exception {
runTest("testData/structureView/fileStructure/AnonymousObjectMembers.kt");
}
@TestMetadata("CheckLocationForKotlin.kt")
public void testCheckLocationForKotlin() throws Exception {
runTest("testData/structureView/fileStructure/CheckLocationForKotlin.kt");
}
@TestMetadata("CheckMemberLocationForJava.kt")
public void testCheckMemberLocationForJava() throws Exception {
runTest("testData/structureView/fileStructure/CheckMemberLocationForJava.kt");
}
@TestMetadata("DoNotShowParentsInLocationJava.kt")
public void testDoNotShowParentsInLocationJava() throws Exception {
runTest("testData/structureView/fileStructure/DoNotShowParentsInLocationJava.kt");
}
@TestMetadata("EmptyFile.kt")
public void testEmptyFile() throws Exception {
runTest("testData/structureView/fileStructure/EmptyFile.kt");
}
@TestMetadata("InheritedDelegationMethods.kt")
public void testInheritedDelegationMethods() throws Exception {
runTest("testData/structureView/fileStructure/InheritedDelegationMethods.kt");
}
@TestMetadata("InheritedInnerClasses.kt")
public void testInheritedInnerClasses() throws Exception {
runTest("testData/structureView/fileStructure/InheritedInnerClasses.kt");
}
@TestMetadata("InheritedJavaMembers.kt")
public void testInheritedJavaMembers() throws Exception {
runTest("testData/structureView/fileStructure/InheritedJavaMembers.kt");
}
@TestMetadata("InheritedLocalKotlin.kt")
public void testInheritedLocalKotlin() throws Exception {
runTest("testData/structureView/fileStructure/InheritedLocalKotlin.kt");
}
@TestMetadata("InheritedMembers.kt")
public void testInheritedMembers() throws Exception {
runTest("testData/structureView/fileStructure/InheritedMembers.kt");
}
@TestMetadata("InheritedMembersOfEnum.kt")
public void testInheritedMembersOfEnum() throws Exception {
runTest("testData/structureView/fileStructure/InheritedMembersOfEnum.kt");
}
@TestMetadata("InheritedMembersWithSubstitutedTypes.kt")
public void testInheritedMembersWithSubstitutedTypes() throws Exception {
runTest("testData/structureView/fileStructure/InheritedMembersWithSubstitutedTypes.kt");
}
@TestMetadata("InheritedSAMConversion.kt")
public void testInheritedSAMConversion() throws Exception {
runTest("testData/structureView/fileStructure/InheritedSAMConversion.kt");
}
@TestMetadata("InheritedSynthesizedFromDataClass.kt")
public void testInheritedSynthesizedFromDataClass() throws Exception {
runTest("testData/structureView/fileStructure/InheritedSynthesizedFromDataClass.kt");
}
@TestMetadata("LocalElements.kt")
public void testLocalElements() throws Exception {
runTest("testData/structureView/fileStructure/LocalElements.kt");
}
@TestMetadata("Render.kt")
public void testRender() throws Exception {
runTest("testData/structureView/fileStructure/Render.kt");
}
@TestMetadata("SeveralClasses.kt")
public void testSeveralClasses() throws Exception {
runTest("testData/structureView/fileStructure/SeveralClasses.kt");
}
@TestMetadata("Simple.kt")
public void testSimple() throws Exception {
runTest("testData/structureView/fileStructure/Simple.kt");
}
}
| 39.172414
| 158
| 0.761664
|
996a6fb135984f43187e418094a16697d3be0c56
| 586
|
/**
*
*/
package com.joelgtsantos.cmstriton.filters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.netflix.zuul.ZuulFilter;
/**
* @author Joel Santos
*
* cms-triton 2018
*/
public class RouteFilter extends ZuulFilter {
Logger logger = LoggerFactory.getLogger(RouteFilter.class);
@Override
public String filterType() {
return "route";
}
@Override
public int filterOrder() {
return 1;
}
@Override
public boolean shouldFilter() {
return true;
}
@Override
public Object run() {
logger.info("Inside Route Filter");
return null;
}
}
| 14.65
| 60
| 0.703072
|
aeec0f0fbcc91e5bf169f4babae62d69cb96e769
| 768
|
package com.orgofarmsgroup.api.v1.users.dto;
public class UserDto {
private String userId;
private String email;
private String firstName;
private String message;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
| 18.731707
| 48
| 0.614583
|
044cdb8d66fd2af036d4b4d3c1ffb4073421fc23
| 2,447
|
/**
* Copyright (c) 2008, http://www.snakeyaml.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yaml.snakeyaml.issues.issue116;
import junit.framework.TestCase;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.error.YAMLException;
public class NoFieldsTest extends TestCase {
public void testEmptyClass() {
Empty empty = new Empty();
Yaml yaml = new Yaml();
String result = yaml.dump(empty);
assertEquals("!!org.yaml.snakeyaml.issues.issue116.Empty {}\n", result);
Object emptyParsed = yaml.load(result);
assertTrue(emptyParsed instanceof Empty);
}
public void testHiddenParameter() {
Hidden hidden = new Hidden();
Yaml yaml = new Yaml();
try {
yaml.dump(hidden);
fail("an exception should have been thrown");
} catch (YAMLException e) {
assertEquals(e.getMessage(),
"No JavaBean properties found in org.yaml.snakeyaml.issues.issue116.Hidden");
}
Object hiddenParsed = yaml.load("!!org.yaml.snakeyaml.issues.issue116.Hidden {}\n");
assertTrue(hiddenParsed instanceof Hidden);
}
public void testSpecialHiddenParameter() {
HiddenSpecial hidden = new HiddenSpecial("qwerty");
Yaml yaml = new Yaml();
try {
yaml.dump(hidden);
fail("an exception should have been thrown");
} catch (YAMLException e) {
assertEquals(e.getMessage(),
"No JavaBean properties found in org.yaml.snakeyaml.issues.issue116.HiddenSpecial");
}
HiddenSpecial hs = (HiddenSpecial) yaml
.load("!!org.yaml.snakeyaml.issues.issue116.HiddenSpecial foo\n");
assertEquals("foo".hashCode(), hs.retrieveMyVerySpecialField());
}
}
class Empty {
}
class Hidden {
@SuppressWarnings("unused")
private int inaccessableField;
}
| 34.464789
| 104
| 0.655497
|
71c184ba7dad2b328eda8481862ae808f59d4b6d
| 3,179
|
package math;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.rules.ExpectedException;
/**
* The ArithmeticOperationsTest provides tests for the ArithmeticOperations class
* that serve as hands-on practice on Unit Testing.
*
* @author Stamatis Liakos
* @version 1.0
* @since 2021-05-05
*/
public class ArithmeticOperationsTest {
ArithmeticOperations ao = new ArithmeticOperations();
@Test
public void test_divide1() {
Assert.assertEquals(2.0, ao.divide(10.5, 5.25), 0.0001);
}
@Test
public void test_divide2() {
Assert.assertEquals(0.0, ao.divide(0.0, 2.35), 0.0001);
}
@Test
public void test_divide3() {
Assert.assertEquals(Double.MAX_VALUE, ao.divide(Double.MAX_VALUE, 1.00), 0.0001);
}
@Test
public void test_divide4() {
Assert.assertEquals(Double.MIN_VALUE, ao.divide(Double.MIN_VALUE, 1.00), 0.0001);
}
@Test
public void test_divide5() {
Assert.assertEquals(0.0, ao.divide(10.2, Double.MAX_VALUE), 0.0001);
}
@Test
public void test_divide6() {
Assert.assertEquals(-5.00, ao.divide(10.00, -2.00), 0.0001);
}
@Test
public void test_divide7() {
Assert.assertEquals(5.00, ao.divide(-10.00, -2.00), 0.0001);
}
/*
* A unit test that checks an invalid zero input
* that causes an IllegalArgumentException
*/
@Test (expected = ArithmeticException.class)
public void testDivideShouldCauseAnException() {
double zero = 0.0;
ao.divide(7.35, zero);
}
@Test
public void test_mutliply1() {
Assert.assertEquals(10, ao.multiply(5, 2));
}
@Test
public void test_multiply2() {
Assert.assertEquals(700, ao.multiply(20, 35));
}
@Test
public void test_multiply3() {
Assert.assertEquals(0, ao.multiply(0, 35));
}
@Test
public void test_multiply4() {
Assert.assertEquals(0, ao.multiply(8, 0));
}
@Test
public void test_multiply5() {
Assert.assertEquals(0, ao.multiply(Integer.MAX_VALUE, 0));
}
@Test
public void test_multiply6() {
Assert.assertEquals(0, ao.multiply(0, Integer.MAX_VALUE));
}
@Rule
public ExpectedException th1 = ExpectedException.none();
@Test
public void test_multiply_RuleException1() {
th1.expect(IllegalArgumentException.class);
th1.expectMessage("x & y should be >= 0");
ao.multiply(-1, 5);
}
@Rule
public ExpectedException th2 = ExpectedException.none();
@Test
public void test_multiply_RuleException2() {
th2.expect(IllegalArgumentException.class);
th2.expectMessage("x & y should be >= 0");
ao.multiply(2, -7);
}
@Rule
public ExpectedException th3 = ExpectedException.none();
@Test
public void test_multiply_RuleException3() {
th3.expect(IllegalArgumentException.class);
th3.expectMessage("The product does not fit in an Integer variable");
ao.multiply(Integer.MAX_VALUE, 10);
}
@Rule
public ExpectedException th4 = ExpectedException.none();
@Test
public void test_multiply_RuleException4() {
th4.expect(IllegalArgumentException.class);
th4.expectMessage("The product does not fit in an Integer variable");
ao.multiply(9, Integer.MAX_VALUE);
}
}
| 22.546099
| 83
| 0.712174
|
294cd445826d29c7225892202308767f244c5ca4
| 2,660
|
package com.github.kerner1000.etoro.stats.taxonomyservice.persistence;
import com.github.kerner1000.etoro.stats.model.Taxonomy;
import javax.persistence.*;
import java.util.Objects;
@Entity
@Table(name = "taxonomies")
public class TaxonomyEntity implements Taxonomy {
@GeneratedValue
@Id
private int id;
/**
* Optimistic locking.
*/
@Version
private int version;
/**
* E.g., "sector".
*/
private String identifier;
/**
* E.g., "Technology".
*/
private String value;
@ManyToOne
private TickerEntity tickerEntity;
public TaxonomyEntity() {
}
public TaxonomyEntity(String identifier, String value) {
this.value = value;
this.identifier = identifier;
}
public TaxonomyEntity(String identifier) {
this.identifier = identifier;
}
@Override
public boolean isComplete() {
return getValue() != null;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TaxonomyEntity that = (TaxonomyEntity) o;
return identifier.equals(that.identifier) && tickerEntity.equals(that.tickerEntity);
}
@Override
public int hashCode() {
return Objects.hash(identifier, tickerEntity);
}
@Override
public String toString() {
return "TaxonomyEntity{" +
"id=" + id +
", version=" + version +
", identifier='" + identifier + '\'' +
", value='" + value + '\'' +
", tickerEntity=" + tickerEntity +
'}';
}
@Override
public String getInstrument() {
if(getTickerEntity() == null)
return null;
return getTickerEntity().getName();
}
// Getter / Setter //
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
@Override
public String getIdentifier() {
return identifier;
}
@Override
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
public TickerEntity getTickerEntity() {
return tickerEntity;
}
public void setTickerEntity(TickerEntity tickerEntity) {
this.tickerEntity = tickerEntity;
}
}
| 20.305344
| 92
| 0.576692
|
d247a836722c0c2f0cfb9b9472ea16b926fa2095
| 372
|
import java.util.*;
public class Darshan{
public static void main(String args[]){
System.out.println("darshan");
Scanner input = new Scanner(System.in);
System.out.println("Enter the First number: ");
int num1 = input.nextInt();
System.out.println("Enter the Second number: ");
int num2 = input.nextInt();
int sum = num1 + num2;
System.out.println("Sum is :" + sum);
}
}
| 24.8
| 48
| 0.704301
|
46f773ca0df363f1db610161392c9e8836c4465a
| 3,131
|
package petkov.nn;
/**
* Created by sam_petkov 21.05.2021
*/
import org.apache.spark.ml.classification.MultilayerPerceptronClassificationModel;
import org.apache.spark.ml.classification.MultilayerPerceptronClassifier;
import org.apache.spark.ml.evaluation.MulticlassClassificationEvaluator;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SparkSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import petkov.data.IdxReader;
import petkov.data.LabeledImage;
import java.io.IOException;
import java.util.List;
// SImple Neural Network
public class NeuralNetwork {
private final static Logger LOGGER = LoggerFactory.getLogger(NeuralNetwork.class);
private SparkSession sparkSession;
private MultilayerPerceptronClassificationModel model;
// Initialization
public void init() {
initSparkSession();
if (model == null) {
LOGGER.info("Loading the Neural Network from saved model ... ");
model = MultilayerPerceptronClassificationModel.load("C:\\Users\\petko\\Documents\\GitHub\\DigitRecognizer\\resources\\nnTrainedModels\\ModelWith60000");
LOGGER.info("Loading from saved model is done");
}
}
// Training
public void train(Integer trainData, Integer testFieldValue) {
initSparkSession();
List<LabeledImage> labeledImages = IdxReader.loadData(trainData);
List<LabeledImage> testLabeledImages = IdxReader.loadTestData(testFieldValue);
Dataset<Row> train = sparkSession.createDataFrame(labeledImages, LabeledImage.class).checkpoint();
Dataset<Row> test = sparkSession.createDataFrame(testLabeledImages, LabeledImage.class).checkpoint();
int[] layers = new int[]{784, 128, 64, 10};
MultilayerPerceptronClassifier trainer = new MultilayerPerceptronClassifier()
.setLayers(layers)
.setBlockSize(128)
.setSeed(1234L)
.setMaxIter(100);
model = trainer.fit(train);
evalOnTest(test);
evalOnTest(train);
}
// Accuracy
private void evalOnTest(Dataset<Row> test) {
Dataset<Row> result = model.transform(test);
Dataset<Row> predictionAndLabels = result.select("prediction", "label");
MulticlassClassificationEvaluator evaluator = new MulticlassClassificationEvaluator()
.setMetricName("accuracy");
LOGGER.info("Test set accuracy = " + evaluator.evaluate(predictionAndLabels));
}
// Apache Class for building data frames
private void initSparkSession() {
if (sparkSession == null) {
sparkSession = SparkSession.builder()
.master("local[*]")
.appName("Digit Recognizer")
.getOrCreate();
}
sparkSession.sparkContext().setCheckpointDir("checkPoint");
}
// Predict the number
public LabeledImage predict(LabeledImage labeledImage) {
double predict = model.predict(labeledImage.getFeatures());
labeledImage.setLabel(predict);
return labeledImage;
}
}
| 35.988506
| 165
| 0.689556
|
0580044d325cfa2a65303ec0e4c573e6cbe88942
| 5,306
|
package spelling;
/**
* class to test NearbyWords
*/
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import dictionary.DictionaryLoader;
import dictionary.DictionaryTrie;
/**
* @author UC San Diego MOOC team
* @author Belnarto
*/
public class NearByWordsTester {
// if change file or number of words also change number in testcases
private String dict4kPath = "/dictionaries/Dict4k.txt";
private DictionaryTrie dict = new DictionaryTrie();
private NearbyWords nearByWords = new NearbyWords(dict);
private List<String> retList;
/**
* Setting up same conditions for test case
*
* @throws java.lang.Exception
*/
public void initializeTestConditions() throws Exception {
DictionaryLoader.loadDictionary(dict, dict4kPath);
retList = new ArrayList<String>();
}
/**
* Test the substitution method
*/
@Test
public void TestSubstitution() {
try {
initializeTestConditions();
} catch (Exception e) {
e.printStackTrace();
}
nearByWords.substitution(null, retList);
assertEquals("Test null string", 0, retList.size());
nearByWords.substitution("", retList);
assertEquals("Test empty string", 0, retList.size());
nearByWords.substitution("h", retList);
assertEquals("Test 1 letter", 2, retList.size());
retList = new ArrayList<String>();
nearByWords.substitution("he", retList);
assertEquals("Test 1+ letters", 4, retList.size());
retList = null;
try {
nearByWords.substitution("he", retList);
fail("Pointer to list is null");
} catch (NullPointerException e) {
}
}
/**
* Test the insertions method
*/
@Test
public void TestInsertions() {
try {
initializeTestConditions();
} catch (Exception e) {
e.printStackTrace();
}
nearByWords.insertions(null, retList);
assertEquals("Test null string", 0, retList.size());
nearByWords.insertions("", retList);
assertEquals("Test empty string", 0, retList.size());
nearByWords.insertions("h", retList);
assertEquals("Test 1 letter", 2, retList.size());
retList = new ArrayList<String>();
nearByWords.insertions("he", retList);
assertEquals("Test 1+ letters", 4, retList.size());
retList = null;
try {
nearByWords.insertions("he", retList);
fail("Pointer to list is null");
} catch (NullPointerException e) {
}
}
/**
* Test the deletions method
*/
@Test
public void TestDeletions() {
try {
initializeTestConditions();
} catch (Exception e) {
e.printStackTrace();
}
nearByWords.deletions(null, retList);
assertEquals("Test null string", 0, retList.size());
nearByWords.deletions("", retList);
assertEquals("Test empty string", 0, retList.size());
nearByWords.deletions("h", retList);
assertEquals("Test 1 letter", 0, retList.size());
retList = new ArrayList<String>();
nearByWords.deletions("am", retList);
assertEquals("Test 1+ letters", 1, retList.size());
retList = null;
try {
nearByWords.deletions("he", retList);
fail("Pointer to list is null");
} catch (NullPointerException e) {
}
}
/**
* Test the distance one method
*/
@Test
public void TestDistanceOne() {
try {
initializeTestConditions();
} catch (Exception e) {
e.printStackTrace();
}
retList = nearByWords.distanceOne(null);
assertEquals("Test null string", 0, retList.size());
retList = nearByWords.distanceOne("");
assertEquals("Test empty string", 0, retList.size());
retList = nearByWords.distanceOne("h");
assertEquals("Test 1 letter", 4, retList.size());
retList = nearByWords.distanceOne("am");
assertEquals("Test 1+ letters", 6, retList.size());
retList = nearByWords.distanceOne("hello");
assertEquals("Test 1+ letters", 1, retList.size());
}
/**
* Test the suggestions method
*/
@Test
public void TestSuggestions() {
try {
initializeTestConditions();
} catch (Exception e) {
e.printStackTrace();
}
retList = nearByWords.suggestions(null, 10);
assertEquals("Test null string", 0, retList.size());
retList = nearByWords.suggestions("", 10);
assertEquals("Test empty string", 0, retList.size());
retList = nearByWords.suggestions("h", 10);
assertEquals("Test 1 letter", 10, retList.size());
retList = nearByWords.suggestions("am", 10);
assertEquals("Test 1+ letters(1)", 10, retList.size());
retList = nearByWords.suggestions("kang", 10);
assertEquals("Test 1+ letters(2)", 10, retList.size());
retList = nearByWords.suggestions("kangaro", 10);
assertEquals("Test 1+ letters(3)", 0, retList.size());
}
}
| 26.79798
| 72
| 0.587637
|
860d08e161d694bc1434dbe2d23b9884c55365ae
| 3,008
|
package com.blamejared.crafttweaker.api.data;
import com.blamejared.crafttweaker.impl.data.ByteData;
import com.blamejared.crafttweaker.impl.data.DoubleData;
import com.blamejared.crafttweaker.impl.data.FloatData;
import com.blamejared.crafttweaker.impl.data.IntData;
import com.blamejared.crafttweaker.impl.data.LongData;
import com.blamejared.crafttweaker.impl.data.ShortData;
import org.junit.jupiter.api.Test;
import java.math.BigDecimal;
import static org.assertj.core.api.Assertions.assertThat;
class NumberConverterTest {
@Test
@SuppressWarnings("ConstantConditions")
public void nullReturnsNull() {
//Arrange - none
//Act
final IData convert = NumberConverter.convertNumber(null);
//Assert
assertThat(convert).isNull();
}
@Test
public void integerReturnsIntegerData() {
//Arrange
final int value = 13;
//Act
final IData convert = NumberConverter.convertNumber(value);
//Assert
assertThat(convert).isEqualTo(new IntData(value));
}
@Test
public void byteReturnsByteData() {
//Arrange
final byte value = 13;
//Act
final IData convert = NumberConverter.convertNumber(value);
//Assert
assertThat(convert).isEqualTo(new ByteData(value));
}
@Test
public void doubleReturnsDoubleData() {
//Arrange
final double value = 13;
//Act
final IData convert = NumberConverter.convertNumber(value);
//Assert
assertThat(convert).isEqualTo(new DoubleData(value));
}
@Test
public void floatReturnsFloatData() {
//Arrange
final float value = 13;
//Act
final IData convert = NumberConverter.convertNumber(value);
//Assert
assertThat(convert).isEqualTo(new FloatData(value));
}
@Test
public void longReturnsLongData() {
//Arrange
final long value = 13;
//Act
final IData convert = NumberConverter.convertNumber(value);
//Assert
assertThat(convert).isEqualTo(new LongData(value));
}
@Test
public void shortReturnsShortData() {
//Arrange
final short value = 13;
//Act
final IData convert = NumberConverter.convertNumber(value);
//Assert
assertThat(convert).isEqualTo(new ShortData(value));
}
@Test
public void unknownNumberTypeReturnsDoubleData() {
//Arrange
final double doubleValue = 123;
final BigDecimal bigDecimal = new BigDecimal(doubleValue);
//Act
final IData convert = NumberConverter.convertNumber(bigDecimal);
//Assert
assertThat(convert)
.isInstanceOf(DoubleData.class)
.isEqualTo(new DoubleData(doubleValue));
}
}
| 26.156522
| 72
| 0.610372
|
f45504f35fe03ff7bf20aadcd5721622d9e92dd0
| 1,566
|
package com.chao.peakmusic.activity;
import android.os.Build;
import android.os.Handler;
import android.view.View;
import com.chao.peakmusic.R;
import com.chao.peakmusic.base.BaseActivity;
import com.chao.peakmusic.utils.NavigationManager;
/**
* 引导页
* Created by Chao on 2017-12-18.
*/
public class GuideActivity extends BaseActivity {
private Handler mHandler;
@Override
public int getLayout() {
return R.layout.activity_guide;
}
@Override
public void initView() {
toggleHideyBar();
}
@Override
public void initData() {
mHandler = new Handler();
mHandler.postDelayed(run, 2000);
}
private void toggleHideyBar() {
int uiOptions = getWindow().getDecorView().getSystemUiVisibility();
int newUiOptions = uiOptions;
newUiOptions ^= View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
if (Build.VERSION.SDK_INT >= 16) {
newUiOptions ^= View.SYSTEM_UI_FLAG_FULLSCREEN;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
newUiOptions ^= View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
}
getWindow().getDecorView().setSystemUiVisibility(newUiOptions);
}
private Runnable run = new Runnable() {
@Override
public void run() {
NavigationManager.gotoHome(mContext);
finish();
}
};
@Override
protected void onDestroy() {
super.onDestroy();
mHandler.removeCallbacks(run);
mHandler = null;
run = null;
}
}
| 24.092308
| 75
| 0.637292
|
43f2222f0200c13c95249cad208627ab8913af7e
| 1,173
|
package org.dhaval.java.pattern;
import java.io.ObjectStreamException;
/**
* Represents singleton pattern class.
*
* @author dhaval
*
*/
/* Marking it as a final so that it cannot be extended. */
public final class Singleton {
/* A private constructor to prevent instantiation of the class from outside. */
private Singleton(){}
/* Marking the instance variable volatile. So that only fully initialized
* value can be seen by any thread.
*/
private static volatile Singleton instance = null;
public static Singleton getInstance(){
/*
* Single check to prevent unnecessary synchronization
* when instance is already initialized.
*/
if(instance == null){
/*
* Synchronization to prevent two threads to initialize the class
* at the same time.
*/
synchronized(Singleton.class){
if(instance == null){
instance = new Singleton();
}
}
}
return instance;
}
/*
* Implementing readResolve method to prevent deserialization of object.
* In that case returning the same singleton object present in the memory.
*/
private Object readResolve() throws ObjectStreamException{
return instance;
}
}
| 23.46
| 80
| 0.702472
|
7c824d43bd366d97156514899da91f6e0b509dda
| 5,221
|
package com.eg.android.criminalintent;
import android.content.Intent;
import android.icu.text.LocaleDisplayNames;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
/**
* @author Datuu
* @date on 2018/1/27.
* @email yiyun0331@163.com
*/
public class CrimeListFragment extends Fragment {
private RecyclerView mCrimeRecyclerView;
private CrimeAdapter mAdapter;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_crime_list,
container, false);
mCrimeRecyclerView = view.findViewById(R.id.crime_recycler_view);
/**
* RecyclerView 类不会亲自摆放屏幕上的列表项。实际上,摆放的任务被委托给了
LayoutManager。除了在屏幕上摆放列表项,LayoutManager还负责定义屏幕滚动行为
GridLayoutManager类,以网格形式展示列表项
*/
mCrimeRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
updateUI();
return view;
}
private void updateUI() {
//数据表对象
CrimeLab crimeLab = CrimeLab.get(getActivity());
List<Crime> crimes = crimeLab.getCrimes();
//数据适配
mAdapter = new CrimeAdapter(crimes);
mCrimeRecyclerView.setAdapter(mAdapter);
}
//viewholder主要负责一个条目中 初始化控件
private class CrimeHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView mTitleTextView;
private TextView mDateTextView;
private Crime mCrime;
private ImageView mImageView;
public CrimeHolder(LayoutInflater inflater, ViewGroup parent) {
super(inflater.inflate(R.layout.list_item_crime, parent, false));
itemView.setOnClickListener(this);
mTitleTextView = itemView.findViewById(R.id.crime_title);
mDateTextView = itemView.findViewById(R.id.crime_date);
mImageView = itemView.findViewById(R.id.crime_solved);
}
//区别构建一个新的holder类
public CrimeHolder(LayoutInflater inflater, ViewGroup parent, int type) {
super(inflater.inflate(R.layout.list_item_crimepo, parent, false));
itemView.setOnClickListener(this);
mTitleTextView = itemView.findViewById(R.id.crime_title);
mDateTextView = itemView.findViewById(R.id.crime_date);
mImageView = itemView.findViewById(R.id.buttonpo);
mImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d("tag", ">>>>>>>>>>>>>>mag");
}
});
}
public void bind(Crime crime) {
mCrime = crime;
mTitleTextView.setText(mCrime.getTitle());
// //日期格式化 封装一下
FormatDates date =new FormatDates(mCrime.getDate());
mDateTextView.setText(date.getDates());
mImageView.setVisibility(crime.isSolved() ? View.VISIBLE : View.GONE);
}
@Override
public void onClick(View view) {
// Toast.makeText(getActivity(), mCrime.getTitle() + "c",
// Toast.LENGTH_SHORT).show();
//fragment 跳转到CrimeActivity
// Intent intent = new Intent(getActivity(), CrimeActivity.class);
Intent intent = CrimeActivity.newIntent(getActivity(), mCrime.getId());
startActivity(intent);
}
}
//条目管理
private class CrimeAdapter extends RecyclerView.Adapter<CrimeHolder> {
private List<Crime> mCrimes;
private static final int TYPE_ONE = 0;
public CrimeAdapter(List<Crime> crimes) {
mCrimes = crimes;
}
@Override
public CrimeHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
//这里获取crime对象里的值 对type viewtype mRequiresPolice 对应相关的不同对象进行区分返回holder
int type = getItemViewType(viewType);
Log.d("tag", ">>>>>>>a>>>>>:" + type + ">>>>>>" + viewType);
if (type == TYPE_ONE) {
return new CrimeHolder(layoutInflater, parent);
} else {
return new CrimeHolder(layoutInflater, parent, 1);
}
}
@Override
public void onBindViewHolder(CrimeHolder holder, int position) {
Crime crime = mCrimes.get(position);
holder.bind(crime);
}
@Override
public int getItemCount() {
return mCrimes.size();
}
@Override
public int getItemViewType(int position) {
//这里关联viewtype mRequiresPolice
return mCrimes.get(position).getRequiresPolice();
}
}
}
| 33.254777
| 123
| 0.639724
|
0fcc03d9dc368a404870bd23c3d720b76983a532
| 5,095
|
package io.ideploy.deployment.admin.dao.deploy;
import io.ideploy.deployment.admin.po.deploy.DeployHistoryPO;
import io.ideploy.deployment.admin.vo.stat.LowQualityRank;
import io.ideploy.deployment.admin.vo.stat.StatProjectResult;
import io.ideploy.deployment.common.Constants;
import io.ideploy.deployment.common.enums.DeployResult;
import io.ideploy.deployment.common.enums.DeployStatus;
import io.ideploy.deployment.common.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.Date;
import java.util.List;
import static org.junit.Assert.*;
/**
* 功能:测试 DeployHistoryDao
* 详细:
*
* @author linyi, 2017/2/27.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath*:applicationContext.xml")
@Profile("dev")
public class DeployHistoryDaoTest extends AbstractTransactionalJUnit4SpringContextTests {
@Autowired
private DeployHistoryDao deployHistoryDao;
@Test
public void testUpdateStatus() {
DeployHistoryPO po = createDeployHistoryPO();
deployHistoryDao.insert(po);
assertTrue(po.getHistoryId() > 0);
DeployHistoryPO tmp = deployHistoryDao.get(po.getHistoryId());
assertEq(po, tmp);
short newStatus = DeployStatus.DEPLOYED.getValue();
int rows = deployHistoryDao.updateStatus(po.getHistoryId(), newStatus, po.getDeployStatus());
assertTrue(rows > 0);
tmp = deployHistoryDao.get(po.getHistoryId());
assertTrue(tmp.getDeployStatus() == newStatus);
}
@Test
public void testUpdateStatusAndResult() {
DeployHistoryPO po = createDeployHistoryPO();
deployHistoryDao.insert(po);
assertTrue(po.getHistoryId() > 0);
DeployHistoryPO tmp = deployHistoryDao.get(po.getHistoryId());
assertEq(po, tmp);
short newStatus = DeployStatus.DEPLOYED.getValue();
short result = DeployResult.SUCCESS.getValue();
int success = po.getDeployServers();
int rows = deployHistoryDao.updateResultAndStatus(po.getHistoryId(), result, po.getDeployServers(), success, newStatus, po.getDeployStatus());
assertTrue(rows > 0);
tmp = deployHistoryDao.get(po.getHistoryId());
assertTrue(tmp.getDeployStatus() == newStatus);
assertTrue(tmp.getResult() == result);
assertTrue(tmp.getSuccessCount() == success);
}
/**
* 仅测试语法,不测试逻辑
*/
@Test
public void testStatProject() {
Date startTime = DateUtil.currentStartDate();
Date endTime = DateUtil.currentEndDate();
List<StatProjectResult> list = deployHistoryDao.statProject(startTime, endTime, DeployStatus.DEPLOYED.getValue());
assertNotNull(list);
}
/**
* 仅测试语法,不测试逻辑
*/
@Test
public void testStatLowQualityModule() {
Date startTime = DateUtil.currentStartDate();
Date endTime = DateUtil.currentEndDate();
int[] envId = {1};
String envStr = StringUtils.join(envId, ",");
List<LowQualityRank> ranks = deployHistoryDao.statLowQualityModule(startTime,
endTime, envStr, DeployStatus.DEPLOYED.getValue(),
DeployResult.SUCCESS.getValue(), Constants.LOW_QUALITY_DEPLOY_TIMES);
assertNotNull(ranks);
}
private DeployHistoryPO createDeployHistoryPO() {
DeployHistoryPO po = new DeployHistoryPO();
po.setRealName("andy");
po.setProjectId(1);
po.setVersionNo("123");
po.setEnvId(1);
po.setAccountId(1);
po.setConcurrentServerPercentage((short)50);
po.setTitle("test-1");
po.setTagName("/tags/20170201");
po.setDeployStatus(DeployStatus.WAITING_FOR_DEPLOYMENT.getValue());
po.setResult(DeployResult.NONE.getValue());
po.setModuleId(1);
po.setModuleName("module-1");
po.setDeployTimeInterval((short)20);
po.setDeployServers(1);
po.setSuccessCount(0);
po.setCreateTime(new Date());
return po;
}
private void assertEq(DeployHistoryPO po1, DeployHistoryPO po2) {
assertNotNull(po1);
assertNotNull(po2);
assertTrue(po1.getHistoryId() == po2.getHistoryId());
assertEquals(po1.getTitle(), po2.getTitle());
assertEquals(po1.getRealName(), po2.getRealName());
assertEquals(po1.getTagName(), po2.getTagName());
assertEquals(po1.getModuleName(), po2.getModuleName());
assertTrue(po1.getDeployStatus() == po2.getDeployStatus());
assertTrue(po1.getResult() == po2.getResult());
assertTrue(po1.getDeployServers() == po2.getDeployServers());
assertTrue(po1.getSuccessCount() == po2.getSuccessCount());
}
}
| 38.308271
| 150
| 0.693817
|
461fc235a6d7ebe88fd800ef3f4c6bd410b1d109
| 622
|
package nl.lucasridder.RealIP.util.exception.phase;
import nl.lucasridder.RealIP.util.exception.RealIPException;
/**
* An exception thrown during the initialization phase of TCPShield
*/
public class InitializationException extends RealIPException {
public InitializationException(Throwable throwable) {
super("An exception occured during the initalization process", throwable);
}
public InitializationException(String message) {
super(message);
}
public InitializationException(String message, Throwable throwable) {
super(message, throwable);
}
public InitializationException() {
super();
}
}
| 21.448276
| 76
| 0.78135
|
86423c3015367c2ed3eeeee272bc3c7798366084
| 19,555
|
package com.estar.utils;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;
import android.text.Editable;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.RelativeSizeSpan;
import android.util.TypedValue;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 常用工具类
* Created by ding on 2016/5/23.
*/
public class CommonUtils {
public static final String SYS_EMUI = "sys_emui";
public static final String SYS_MIUI = "sys_miui";
public static final String SYS_FLYME = "sys_flyme";
private static final String KEY_MIUI_VERSION_CODE = "ro.miui.ui.version.code";
private static final String KEY_MIUI_VERSION_NAME = "ro.miui.ui.version.name";
private static final String KEY_MIUI_INTERNAL_STORAGE = "ro.miui.internal.storage";
private static final String KEY_EMUI_API_LEVEL = "ro.build.hw_emui_api_level";
private static final String KEY_EMUI_VERSION = "ro.build.version.emui";
private static final String KEY_EMUI_CONFIG_HW_SYS_VERSION = "ro.confg.hw_systemversion";
/**
* 获取手机厂商 华为、小米、魅族
* @return
*/
public static String getSystem(){
String SYS = "";
try {
Properties prop= new Properties();
prop.load(new FileInputStream(new File(Environment.getRootDirectory(), "build.prop")));
if(prop.getProperty(KEY_MIUI_VERSION_CODE, null) != null
|| prop.getProperty(KEY_MIUI_VERSION_NAME, null) != null
|| prop.getProperty(KEY_MIUI_INTERNAL_STORAGE, null) != null){
SYS = SYS_MIUI;//小米
}else if(prop.getProperty(KEY_EMUI_API_LEVEL, null) != null
||prop.getProperty(KEY_EMUI_VERSION, null) != null
||prop.getProperty(KEY_EMUI_CONFIG_HW_SYS_VERSION, null) != null){
SYS = SYS_EMUI;//华为
}else if(getMeizuFlymeOSFlag().toLowerCase().contains("flyme")){
SYS = SYS_FLYME;//魅族
}
} catch (IOException e){
e.printStackTrace();
return SYS;
}
return SYS;
}
public static String getMeizuFlymeOSFlag() {
return getSystemProperty("ro.build.display.id", "");
}
private static String getSystemProperty(String key, String defaultValue) {
try {
Class<?> clz = Class.forName("android.os.SystemProperties");
Method get = clz.getMethod("get", String.class, String.class);
return (String)get.invoke(clz, key, defaultValue);
} catch (Exception e) {
}
return defaultValue;
}
/**
px转换dp
*/
public static int dp2px(Context context,int dp) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
context.getResources().getDisplayMetrics());
}
/**
* 用来判断服务是否运行.
* @param
* @param className 判断的服务名字
* @return true 在运行 false 不在运行
*/
public static boolean isServiceRunning(Context mContext,String className) {
boolean isRunning = false;
ActivityManager activityManager = (ActivityManager)
mContext.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> serviceList
= activityManager.getRunningServices(30);
if (!(serviceList.size()>0)) {
return false;
}
for (int i=0; i<serviceList.size(); i++) {
if (serviceList.get(i).service.getClassName().equals(className) == true) {
isRunning = true;
break;
}
}
return isRunning;
}
/**
* 生成二维码
* @param url 二维码链接
* @param width 图片宽
* @param height
* @return
*/
public static Bitmap createImage(String url,int width,int height) {
try {
// 需要引入core包
QRCodeWriter writer = new QRCodeWriter();
if (url == null || "".equals(url) || url.length() < 1) {
return null;
}
// 把输入的文本转为二维码
BitMatrix martix = writer.encode(url, BarcodeFormat.QR_CODE,
width, height);
Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
BitMatrix bitMatrix = new QRCodeWriter().encode(url,
BarcodeFormat.QR_CODE, width, height, hints);
int[] pixels = new int[width * height];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
if (bitMatrix.get(x, y)) {
pixels[y * width + x] = 0xff000000;
} else {
pixels[y * width + x] = 0xffffffff;
}
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
} catch (WriterException e) {
e.printStackTrace();
return null;
}
}
/**
* 去掉字符串空格
* @param str
* @return
*/
public static String deleteSpace(String str){
return replaceNULL(str).replaceAll(" ", "");
}
/**
* 验证手机格式
*/
public static boolean isMobileNO(String mobiles) {
/*
移动:134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
联通:130、131、132、152、155、156、185、186
电信:133、153、180、189、(1349卫通)
总结起来就是第一位必定为1,第二位必定为3或5或8、7,其他位置的可以为0-9
*/
// String telRegex = "[1][3578]\\d{9}";//"[1]"代表第1位为数字1,"[358]"代表第二位可以为3、5、8中的一个,"\\d{9}"代表后面是可以是0~9的数字,有9位。
String telRegex = "[1]\\d{10}";//"[1]"代表第1位为数字1,"[358]"代表第二位可以为3、5、8中的一个,"\\d{9}"代表后面是可以是0~9的数字,有9位。
if (TextUtils.isEmpty(mobiles)) return false;
else return mobiles.matches(telRegex);
}
//判断email格式是否正确
public static boolean isEmail(String email) {
String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
Pattern p = Pattern.compile(str);
Matcher m = p.matcher(email);
return m.matches();
}
/**
* 比较date1-date2差几天
*
* @param date1
* @param date2
* @return
*/
public static int dateDiff(Date date1, Date date2) {
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);
long ldate1 = date1.getTime() + cal1.get(Calendar.ZONE_OFFSET) + cal1.get(Calendar.DST_OFFSET);
long ldate2 = date2.getTime() + cal2.get(Calendar.ZONE_OFFSET) + cal2.get(Calendar.DST_OFFSET);
// Use integer calculation, truncate the decimals
int hr1 = (int) (ldate1 / 3600000); // 60*60*1000
int hr2 = (int) (ldate2 / 3600000);
int days1 = hr1 / 24;
int days2 = hr2 / 24;
int dateDiff = days1 - days2;
return dateDiff;
}
/**
*
* 得到两个日期之间的相差的自然月数
* @param nowDate
* @param oldDate
* @return
* @throws ParseException
*/
public static int getYearMounthDays(String nowDate, String oldDate){
int result = 0;
int result_M = 0;
int result_Y = 0;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
try {
c1.setTime(sdf.parse(nowDate));
c2.setTime(sdf.parse(oldDate));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
result_M = c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH);
result_Y = c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR);
result=result_M+result_Y*12;
// Log.e("CarQuoteActivity"," nowDate="+nowDate+" oldDate="+oldDate+
// " result_M="+result_M+" result_Y="+result_Y+" result="+result);
return Math.abs(result);
}
/**
* 计算两个时间相差天数
* @param str1
* @param str2
* @return
*/
public static int getIntervalDays(String str1, String str2) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = null;
Date date2 = null;
try {
date1 = formatter.parse(str1);
date2 = formatter.parse(str2);
} catch (ParseException e) {
e.printStackTrace();
}
int dif = dateDiff(date1,date2);
return dif;
}
/**
* 计算两个时间相差天数
* @param fDate
* @param oDate
* @return
*/
public static int daysOfTwo(Date fDate, Date oDate) {
if (null == fDate || null == oDate) {
return -1;
}
long intervalMilli = oDate.getTime() - fDate.getTime();
int re=(int) (intervalMilli / (24 * 60 * 60 * 1000));
return Math.abs(re);
}
/**
* 判断查询时间端 合法
* @param date1
* @param date2
* @return 0 date1 相等 date2 date1 小于 date2 date1 大于 date2
*/
public static Integer compareTime(String date1,String date2){
java.text.DateFormat df=new SimpleDateFormat("yyyy-MM-dd");
java.util.Calendar c1=java.util.Calendar.getInstance();
java.util.Calendar c2=java.util.Calendar.getInstance();
try
{
c1.setTime(df.parse(date1));
c2.setTime(df.parse(date2));
}catch(java.text.ParseException e){
// System.err.println("格式不正确");
}
int result=c1.compareTo(c2);
if(result==0){
// System.out.println("c1相等c2");
}else if(result<0) {
// System.out.println("c1小于c2");
}else {
// System.out.println("c1大于c2");
}
return result;
}
/**
* 将null替换为""
*
* @param str
* @return
*/
public static String replaceNULL(String str) {
return null == str || "null".equals(str) || "".equals(str.trim()) ? "" : str.trim();
}
/**
* EditText 控件输入 数字、字母提示
*
* @param view
*/
public static void addTextChangedListener(Activity activity,EditText view) {
view.addTextChangedListener(new EditTextWatcher(activity, view, "只能输入数字或字母", new EditTextWatcher.EditTextWatcherInterface() {
public boolean checkInput(Editable editTextString) {
return checkfilename(editTextString);
}
}));
}
//校验只能输入数字和字母
public static boolean checkfilename(Editable s) {
String str = s.toString();
if (str.length() > s.toString().trim().length()) {
return true;
} else {
str = s.toString().trim();
}
String pattern = "^[A-Za-z0-9*]+$";
Pattern p = Pattern.compile(pattern);
Matcher result = p.matcher(str);
return !result.find();
}
/**
* str 转 double 四舍五入 保留两位小数
* @return
*/
public static double getDoubleForString(String str){
if(replaceNULL(str).equals("")){
str ="0";
}
if (isDouble(str)){
double db=Double.parseDouble(str);
BigDecimal b=new BigDecimal(db);
double d=b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
return d;
}
return 0;
}
/**
* 四舍五入 保留两位小数
* @param db
* @return
*/
public static float getForFloat(float db){
BigDecimal b=new BigDecimal(db);
float d=b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
return d;
}
/**
* 四舍五入 保留两位小数
* @param db
* @return
*/
public static double getForDouble(double db){
BigDecimal b=new BigDecimal(db);
double d=b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
return d;
}
/**
* 判断字符是否double类型
* @param str
* @return
*/
public static boolean isDouble(String str)
{
try
{
Double.parseDouble(str);
return true;
}
catch(NumberFormatException ex){
}
return false;
}
/**
* 初始化标题
*
* @param str
* @return
*/
public static Spannable getTitle(String str) {
Spannable wordtoSpan = new SpannableString(str);
wordtoSpan = new SpannableString(str);
wordtoSpan.setSpan(new RelativeSizeSpan(1f), 0, str.indexOf("-"),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
wordtoSpan.setSpan(new RelativeSizeSpan(0.8f), str.lastIndexOf("-"),
str.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return wordtoSpan;
}
/**
* EditText设置错误提示信息
* @param editTextt
* @param msg
*/
public static void setEditEorr(EditText editTextt,String msg){
editTextt.setError(Html.fromHtml("<font color=#C7000A>"+msg+"</font>"));
editTextt.requestFocus();
}
/**
* EditText非空判断
* @param editTextt
* @param msg
* @return
*/
public static boolean setEditTextEorr(EditText editTextt,String msg){
if ("".equals(editTextt.getText().toString().trim())) {
editTextt.setError(Html.fromHtml("<font color=#C7000A>"+msg+"</font>"));
editTextt.requestFocus();
return true;
}
return false;
}
/**
* TextView非空判断
* @param textView
* @param msg
* @return
*/
public static boolean setTextViewEorr(TextView textView, String msg){
if ("".equals(textView.getText().toString().trim())) {
// actv_carNme.setError("车型名称不能为空!");
textView.setError(Html.fromHtml("<font color=#C7000A>"+msg+"</font>"));
textView.requestFocus();
return true;
}
return false;
}
/**
* 根据key值键值对应的下拉框初始化
*
* @param valueId XML中定义显示字符串数组value的ID
* @param keyId XML中定义显示字符串数组所对应的key值字符串数组的ID
* @param key 传入默认选中的key值,可以为空
*/
public static String initViewByKey(Context context, int valueId, int keyId, String key) {
String[] values = context.getResources().getStringArray(valueId);
String[] keys = context.getResources().getStringArray(keyId);
int count = values.length < keys.length ? values.length : keys.length;
for (int i = 0; i < count; i++) {
if (key != null && !"".equals(key)) {
if (keys[i].equals(key)) {
return values[i];
}
}
}
return "";
}
/**
* 根据key值键值对应的下拉框初始化
*
* @param key 传入默认选中的key值,可以为空
*/
public static String initViewByKey(Context context, String[] values, String[] keys, String key) {
int count = values.length < keys.length ? values.length : keys.length;
for (int i = 0; i < count; i++) {
if (key != null && !"".equals(key)) {
if (keys[i].equals(key)) {
return values[i];
}
}
}
return "";
}
/**
* 根据key值键值对应的下拉框初始化
*
* @param valueId XML中定义显示字符串数组value的ID
* @param keyId XML中定义显示字符串数组所对应的key值字符串数组的ID
* @param key 传入默认选中的key值,可以为空
*/
public static void initTextViewByKey(Activity activity, TextView view, int valueId, int keyId, String key) {
String[] values = activity.getResources().getStringArray(valueId);
String[] keys = activity.getResources().getStringArray(keyId);
int count = values.length < keys.length ? values.length : keys.length;
for (int i = 0; i < count; i++) {
if (key != null && !"".equals(key)) {
if (keys[i].equals(key)) {
view.setText(values[i]);
return ;
}
}else{
view.setText("");
}
}
return ;
}
/**
* 关闭输入法
*
* @param
*/
protected static void closeInput(Activity activity) {
try {
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 调用自定义键盘
* @param tv
* @param type
*/
public static void showKeyboardDialog(Context context,TextView tv,String str, KeyboardDialog.INPUT_TYPE type){
KeyboardDialog keyboardDialog = new KeyboardDialog(context);
keyboardDialog.show(tv,str, type);
// keyboardDialog.show(loginBtn, KeyboardDialog.INPUT_TYPE.CARNO);//车牌号
// keyboardDialog.show(loginBtn, KeyboardDialog.INPUT_TYPE.IDNUMBER);//身份证
// keyboardDialog.show(loginBtn, KeyboardDialog.INPUT_TYPE.RACKNO);//车架号
}
/**
* 判断是否是银行卡号
* @param cardId
* @return
*/
public static boolean checkBankCard(String cardId) {
char bit = getBankCardCheckCode(cardId
.substring(0, cardId.length() - 1));
if (bit == 'N') {
return false;
}
return cardId.charAt(cardId.length() - 1) == bit;
}
private static char getBankCardCheckCode(String nonCheckCodeCardId) {
if (nonCheckCodeCardId == null
|| nonCheckCodeCardId.trim().length() == 0
|| !nonCheckCodeCardId.matches("\\d+")) {
// 如果传的不是数据返回N
return 'N';
}
char[] chs = nonCheckCodeCardId.trim().toCharArray();
int luhmSum = 0;
for (int i = chs.length - 1, j = 0; i >= 0; i--, j++) {
int k = chs[i] - '0';
if (j % 2 == 0) {
k *= 2;
k = k / 10 + k % 10;
}
luhmSum += k;
}
return (luhmSum % 10 == 0) ? '0' : (char) ((10 - luhmSum % 10) + '0');
}
/**
* 验证邮箱地址是否正确
* @param email
* @return
*/
public static boolean checkEmail(String email){
boolean flag = false;
try{
String check = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
Pattern regex = Pattern.compile(check);
Matcher matcher = regex.matcher(email);
flag = matcher.matches();
}catch(Exception e){
flag = false;
}
return flag;
}
}
| 30.795276
| 150
| 0.565687
|
2bbac9fe685050bb3d10593870f024760827246f
| 541
|
package com.czbix.smbsteamer.dao.model;
public class PasswordCredential extends Credential {
private final String mUsername;
private final String mPassword;
public PasswordCredential(String username, String password) {
mUsername = username;
mPassword = password;
}
@Override
public boolean isAnonymous() {
return false;
}
@Override
public String getUsername() {
return mUsername;
}
@Override
public String getPassword() {
return mPassword;
}
}
| 20.037037
| 65
| 0.654344
|
34f7003949169e5c57e8b22d511d4c5697e0d899
| 852
|
package net.franckbenault.linearalgebra.operation;
import org.apache.commons.math3.linear.ArrayRealVector;
import org.apache.commons.math3.linear.RealVector;
public class Distances {
public static void main(String[] args) {
double[] dataA = {1.0, 1.0, -1.0, 0.0};
RealVector vectorA = new ArrayRealVector(dataA);
double[] dataB = {0.0, 0.0, 0.0, 1.0};
RealVector vectorB = new ArrayRealVector(dataB);
double l1distance = vectorA.getL1Distance(vectorB);
System.out.println("l1distance="+l1distance);
double l2distance = vectorA.getDistance(vectorB);
System.out.println("l2distance="+l2distance);
double cosineDistance = vectorA.cosine(vectorB);
System.out.println("cosineDistance="+cosineDistance);
vectorA.unitize();
vectorB.unitize();
System.out.println(vectorA);
System.out.println(vectorB);
}
}
| 25.818182
| 55
| 0.725352
|
137e8eb3734bf74d447c575bdf4d42bafedd67ac
| 2,024
|
package com.viewshine.exportexcel.exceptions;
import com.viewshine.exportexcel.entity.vo.ResultVO;
import com.viewshine.exportexcel.exceptions.enums.BusinessErrorCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* 这个表示异常处理类,只有@RestController或者Controller中抛出的异常才会进入这个方法中。其他的都不会进入这个异常处理。
* @author ChangWei[changwei@viewshine.cn]
*/
@RestControllerAdvice
public class CommonExceptionHandler {
private static final Logger logger = LoggerFactory.getLogger(CommonExceptionHandler.class);
/**
* JSON格式的数据在不满足验证条件的时候,抛出:{@link MethodArgumentNotValidException MethodArgumentNotValidException}异常
* 处理这个异常
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResultVO<Void> methodArgumentNotValidExceptionHandle(MethodArgumentNotValidException exception) {
FieldError fieldError = exception.getBindingResult().getFieldError();
MethodParameter parameter = exception.getParameter();
logger.error("在执行{}.{}的时候出现绑定JSON数据参数异常,字段名称为:{},提示消息:{}",
parameter.getDeclaringClass().getName(), parameter.getMethod().getName(), fieldError.getField(),
fieldError.getDefaultMessage());
return ResultVO.errorResult(fieldError.getDefaultMessage());
}
/**
* 用于处理在导出Excel中出现的异常问题
*/
@ExceptionHandler(BusinessException.class)
public ResultVO<Void> businessExceptionHandle(BusinessException businessException) {
BusinessErrorCode errorCode = businessException.getErrorCode();
logger.error("执行业务逻辑出现错误:错误编码是:[{}],错误消息是:[{}]",
errorCode.getCode(), errorCode.getMessage());
return ResultVO.errorResult(errorCode.getCode(), errorCode.getMessage());
}
}
| 42.166667
| 112
| 0.763834
|
afc6805c4173201ee8932c380e6c574720e8d010
| 1,258
|
package de.rieckpil.learning.highperformancejpa;
import de.rieckpil.learning.highperformancejpa.entity.Person;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.hibernate.cache.internal.StandardQueryCache;
import org.hibernate.jpa.QueryHints;
import org.hibernate.stat.SecondLevelCacheStatistics;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import java.util.List;
@Slf4j
@Component
@Profile("querycaching")
@Transactional
public class HibernateQueryCaching implements CommandLineRunner {
@PersistenceContext
private EntityManager entityManager;
@Override
public void run(String... args) {
List<Person> persons = entityManager.createQuery("SELECT p FROM Person p ORDER BY p.id", Person.class)
.setMaxResults(5)
.setHint(QueryHints.HINT_CACHEABLE, true)
.getResultList();
for (Person p : persons) {
System.out.println("p = " + p);
p.setName(p.getName().toUpperCase());
}
}
}
| 29.952381
| 110
| 0.741653
|
e9a88ff94f3be5c35c8fb89a34426227508dd67c
| 2,319
|
package com.socket.pad.paddemo.model;
import java.util.ArrayList;
import java.util.List;
public class RecInfoModel {
/*
* 压力表的值,以0.1MPA为单位
* */
private int pressureNum;
/*
* 百分表值
* */
ArrayList<Integer> percentList = new ArrayList<>();
private int percentAverage;
private int status;
/*
* 系数,暂时为空
* */
private int coefficient;
private int time;
/*
* 机器编码
* */
private String xn;
/*
* 序号
* */
private String xh;
/*
* 1 上载状态 ,2 上载记录
* */
int flag ;
@Override
public String toString() {
return "recv mode is pressureNum="+pressureNum+" percentList.size= "+percentList.size()
+" percentAverage = "+percentAverage+" time"+time+" xn=="+xn+" xh="+xh +" flag= "+flag+
"status = "+status;
}
public String getXn() {
return xn;
}
public void setXn(String xn) {
this.xn = xn;
}
public String getXh() {
return xh;
}
public void setXh(String xh) {
this.xh = xh;
}
public int getPressureNum() {
return pressureNum;
}
public void setPressureNum(int pressureNum) {
this.pressureNum = pressureNum;
}
public int getPercentAverage() {
return percentAverage;
}
public void setPercentAverage(int percentAverage) {
this.percentAverage = percentAverage;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public int getCoefficient() {
return coefficient;
}
public void setCoefficient(int coefficient) {
this.coefficient = coefficient;
}
public int getTime() {
return time;
}
public void setTime(int time) {
this.time = time;
}
public ArrayList<Integer> getPercentList() {
return percentList;
}
public void setPercentList(ArrayList<Integer> percentList) {
this.percentList = percentList;
}
public int getFlag() {
return flag;
}
public void setFlag(int flag) {
this.flag = flag;
}
}
| 18.552
| 107
| 0.53342
|
33656d88253799b2ca38861cb7af7fc0b6bb7273
| 2,014
|
/**
* Licensed to JumpMind Inc under one or more contributor
* license agreements. See the NOTICE file distributed
* with this work for additional information regarding
* copyright ownership. JumpMind Inc licenses this file
* to you under the GNU General Public License, version 3.0 (GPLv3)
* (the "License"); you may not use this file except in compliance
* with the License.
*
* You should have received a copy of the GNU General Public License,
* version 3.0 (GPLv3) along with this library; if not, see
* <http://www.gnu.org/licenses/>.
*
* 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.jumpmind.security;
import org.jumpmind.properties.TypedProperties;
public class SecurityServiceFactory {
public enum SecurityServiceType { CLIENT, SERVER }
public static ISecurityService create() {
return create(SecurityServiceType.CLIENT, null);
}
public static ISecurityService create(SecurityServiceType serviceType, TypedProperties properties) {
try {
if (properties == null) {
properties = new TypedProperties(System.getProperties());
}
String className = properties.get(SecurityConstants.CLASS_NAME_SECURITY_SERVICE,
serviceType == SecurityServiceType.SERVER ? "org.jumpmind.security.BouncyCastleSecurityService" : SecurityService.class.getName());
ISecurityService securityService = (ISecurityService) Class.forName(className).newInstance();
securityService.init();
return securityService;
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| 39.490196
| 151
| 0.695631
|
26f32a64d8b230d899695d9f32c6d42a6c4938cf
| 2,688
|
package seedu.recruit.logic.parser;
import static seedu.recruit.logic.parser.CliSyntax.PREFIX_ADDRESS;
import static seedu.recruit.logic.parser.CliSyntax.PREFIX_AGE;
import static seedu.recruit.logic.parser.CliSyntax.PREFIX_AGE_RANGE;
import static seedu.recruit.logic.parser.CliSyntax.PREFIX_COMPANY_NAME;
import static seedu.recruit.logic.parser.CliSyntax.PREFIX_EDUCATION;
import static seedu.recruit.logic.parser.CliSyntax.PREFIX_JOB;
import static seedu.recruit.logic.parser.CliSyntax.PREFIX_NAME;
import static seedu.recruit.logic.parser.CliSyntax.PREFIX_REVERSE;
import static seedu.recruit.logic.parser.CliSyntax.PREFIX_SALARY;
import static seedu.recruit.logic.parser.CommandParserTestUtil.assertParseFailure;
import static seedu.recruit.logic.parser.CommandParserTestUtil.assertParseSuccess;
import org.junit.Test;
import seedu.recruit.logic.commands.SortJobOfferCommand;
public class SortJobOfferCommandParserTest {
private SortJobOfferCommandParser parser = new SortJobOfferCommandParser();
@Test
public void parse_validArguments_success() {
assertParseSuccess(parser, PREFIX_COMPANY_NAME.toString(),
new SortJobOfferCommand(PREFIX_COMPANY_NAME));
assertParseSuccess(parser, PREFIX_JOB.toString(),
new SortJobOfferCommand(PREFIX_JOB));
assertParseSuccess(parser, PREFIX_AGE_RANGE.toString(),
new SortJobOfferCommand(PREFIX_AGE_RANGE));
assertParseSuccess(parser, PREFIX_EDUCATION.toString(),
new SortJobOfferCommand(PREFIX_EDUCATION));
assertParseSuccess(parser, PREFIX_SALARY.toString(),
new SortJobOfferCommand(PREFIX_SALARY));
assertParseSuccess(parser, PREFIX_REVERSE.toString(),
new SortJobOfferCommand(PREFIX_REVERSE));
}
@Test
public void parse_invalidArguments_failure() {
String expectedMessage = SortJobOfferCommand.MESSAGE_TAG_USAGE;
assertParseFailure(parser, PREFIX_ADDRESS.toString(), expectedMessage);
assertParseFailure(parser, PREFIX_AGE.toString(), expectedMessage);
assertParseFailure(parser, PREFIX_NAME.toString(), expectedMessage);
assertParseFailure(parser, "1", expectedMessage);
assertParseFailure(parser, "n", expectedMessage);
assertParseFailure(parser, "/n", expectedMessage);
assertParseFailure(parser, " ", expectedMessage);
assertParseFailure(parser, "", expectedMessage);
assertParseFailure(parser, PREFIX_AGE_RANGE.toString() + PREFIX_JOB.toString(), expectedMessage);
assertParseFailure(parser, PREFIX_EDUCATION.toString() + PREFIX_REVERSE.toString(), expectedMessage);
}
}
| 48.872727
| 109
| 0.764137
|
18857a9d46a137e963dae2bf1575511f18ef7b0a
| 3,957
|
package com.t70.vector.client.constant;
public enum ErrorCode
{
// <editor-fold defaultstate="collapsed" desc="Internal Logic Errors">
/*
* The first block of 256 values (0x00000000 - 0x000000FF) are reserved for these types of errors.
*/
/**
* There was some sort of unknown error.
*/
UNKNOWN_ERROR(0x00000000),
/**
* The error code was not set on the validation error.
*/
UNSET_ERROR_CODE(0x00000001),
// </editor-fold>
// <editor-fold default-state="collapsed" desc="Object Level Error Codes">
/*
* These errors detail issues on a single object. (E.g. object not found etc.)
*
* The block of number from 256 to 4095 (0x00000100 - 0x00000FFF) are reserved for these types of errors.
*/
/**
* The user does not have access to the object specified.
*
* This error code was chosen to match that of the HTTP status code.
*/
FORBIDDEN(403),
/**
* The object was not found.
*
* This error code was chosen to match that of the HTTP status code.
*/
OBJECT_NOT_FOUND(404),
// <editor-fold>
// <editor-fold default-state="collapse" desc="Generic Property Errors">
/*
* These errors can be combined with specific errors to provide some additional details for trying to hunt for a
* proper response to send to the user or to allow for customer code to react to the issue in some generic but known
* way.
*
* We reserve the upper byte of the 32-bit integer space for these errors: 0x01000000 - 0xFF000000
*/
/**
* The supplied value cannot be reused.
*/
PROPERTY_ALREADY_IN_USE(0x01000000),
/**
* The property was missing and is required.
*/
PROPERTY_REQUIRED(0x02000000),
/**
* The property exceeds some maximum.
*/
PROPERTY_TOO_LARGE(0x03000000),
/**
* The property exceeds some minimum.
*/
PROPERTY_TOO_SMALL(0x04000000),
/**
* The value of the property is out of range of a specific limit.
*/
PROPERTY_OUT_OF_RANGE(0x05000000),
/**
* The value for the property is invalid.
* <p>
* Example: <code>Invalid email address</code>
* </p>
*/
PROPERTY_INVALID_VALUE(0x06000000),
// <editor-fold default-state="collapse" desc="Specific Errors">
/*
* For errors that are very specific that cannot be expressed with the generic errors above.
*
* The reserved range is from 0x00001000 - 0x00FFFFFF
*/
// </editor-fold>
// </editor-fold>
;
private Integer m_value;
private ErrorCode(int value)
{
m_value = value;
}
public int getValue()
{
return m_value;
}
public static ErrorCode fromInteger(int errorCodeId)
{
switch (errorCodeId)
{
// Internal error mappings
case 0x00000000:
return ErrorCode.UNKNOWN_ERROR;
case 0x00000001:
return ErrorCode.UNSET_ERROR_CODE;
// Object level error mappings
case 403:
return ErrorCode.FORBIDDEN;
case 404:
return ErrorCode.OBJECT_NOT_FOUND;
// Property level error mappings.
case 0x01000000:
return ErrorCode.PROPERTY_ALREADY_IN_USE;
case 0x02000000:
return ErrorCode.PROPERTY_REQUIRED;
case 0x03000000:
return ErrorCode.PROPERTY_TOO_LARGE;
case 0x04000000:
return ErrorCode.PROPERTY_TOO_SMALL;
case 0x05000000:
return ErrorCode.PROPERTY_OUT_OF_RANGE;
case 0x06000000:
return ErrorCode.PROPERTY_INVALID_VALUE;
default:
return ErrorCode.UNKNOWN_ERROR;
}
}
}
| 24.57764
| 121
| 0.590852
|
6a482c5a0ac75107e5b6fbbeabcd512534ecfd52
| 1,865
|
package org.coderdreams.webapp.page;
import java.util.Optional;
import org.apache.wicket.markup.Markup;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.coderdreams.dao.ComplexUserRepository;
import org.coderdreams.dom.ComplexUser;
import org.coderdreams.dom.ComplexUserDetails;
import org.coderdreams.dom.PhysicalAddress;
import org.coderdreams.enums.StatusType;
import org.coderdreams.webapp.BasePage;
public class HibernateTestPage extends BasePage implements IBasePage {
@SpringBean
private ComplexUserRepository complexUserRepository;
public HibernateTestPage() {
super();
ComplexUserDetails details = new ComplexUserDetails();
details.setHeight(95.0d);
details.setWeight(220.0d);
details.setNickname("micky");
details.getFavoriteMovies().add("Terminator");
details.getFavoriteMovies().add("Star Trek");
PhysicalAddress a1 = new PhysicalAddress();
a1.setId(System.nanoTime());
a1.setAddress1("123 test");
a1.setCity("NY");
details.getAddresses().add(a1);
PhysicalAddress a2 = new PhysicalAddress();
a2.setId(System.nanoTime());
a2.setPrimary(true);
a2.setAddress1("444 primary st");
a2.setCity("NY");
details.getAddresses().add(a2);
ComplexUser u = new ComplexUser();
u.setStatus(StatusType.ACTIVE);
u.setEmail("test@test.com");
u.setDisplayName("roman");
u.setUserDetails(details);
u = complexUserRepository.save(u);
Optional<ComplexUser> u2 = complexUserRepository.findById(u.getId());
if(u2.isPresent()) {
u2.get().getUserDetails().setMobilePhone("123-666-6666");
complexUserRepository.save(u2.get());
}
setMarkup(Markup.of(String.valueOf(u.getId())));
}
}
| 30.57377
| 77
| 0.673458
|
09f1cce44e2cb40fb8192053cf401ef3f4bde822
| 4,424
|
package uk.gov.justice.digital.delius.service;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.MockitoAnnotations;
import uk.gov.justice.digital.delius.jpa.standard.entity.Event;
import uk.gov.justice.digital.delius.jpa.standard.entity.OffenderPrisoner;
import uk.gov.justice.digital.delius.jpa.standard.repository.EventRepository;
import uk.gov.justice.digital.delius.jpa.standard.repository.OffenderPrisonerRepository;
import java.time.LocalDate;
import java.util.List;
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.*;
import static uk.gov.justice.digital.delius.util.EntityHelper.*;
class OffenderPrisonerServiceTest {
private OffenderPrisonerRepository offenderPrisonerRepository;
private EventRepository eventRepository;
private OffenderPrisonerService offenderPrisonerService;
@Captor
private ArgumentCaptor<Set<OffenderPrisoner>> offenderPrisonersCaptor;
@BeforeEach
void setUp() {
MockitoAnnotations.initMocks(this);
offenderPrisonerRepository = mock(OffenderPrisonerRepository.class);
eventRepository = mock(EventRepository.class);
offenderPrisonerService = new OffenderPrisonerService(eventRepository, offenderPrisonerRepository);
when(eventRepository.findByOffenderId(anyLong())).thenReturn(List.of(aCustodyEvent()));
}
@Test
void willDeleteExistingByOffenderId() {
offenderPrisonerService.refreshOffenderPrisonersFor(anOffender().toBuilder().offenderId(99L).build());
verify(offenderPrisonerRepository).deleteAllByOffenderId(99L);
}
@Test
void willCollateAllEventsWithPrisonerNumbers() {
when(eventRepository.findByOffenderId(99L)).thenReturn(List.of(
anEvent(),
custodyEvent("12345A", LocalDate.now()),
custodyEvent("12345B", LocalDate.now().minusDays(1)),
custodyEvent("12345C", LocalDate.now().minusDays(2)),
custodyEvent("12345D", LocalDate.now().minusDays(3)),
custodyEvent(null, LocalDate.now().minusDays(4)),
anEvent(),
anEvent()
));
offenderPrisonerService.refreshOffenderPrisonersFor(anOffender().toBuilder().offenderId(99L).build());
verify(offenderPrisonerRepository).saveAll(offenderPrisonersCaptor.capture());
assertThat(offenderPrisonersCaptor.getValue()).containsExactlyInAnyOrder(
OffenderPrisoner.builder().prisonerNumber("12345A").offenderId(99L).build(),
OffenderPrisoner.builder().prisonerNumber("12345B").offenderId(99L).build(),
OffenderPrisoner.builder().prisonerNumber("12345C").offenderId(99L).build(),
OffenderPrisoner.builder().prisonerNumber("12345D").offenderId(99L).build()
);
}
@Test
void willSetPrisonNumberFromLatestCustodialEvent() {
when(eventRepository.findByOffenderId(99L)).thenReturn(List.of(
anEvent(),
custodyEvent("12345C", LocalDate.now().minusDays(2)),
custodyEvent("12345B", LocalDate.now().minusDays(1)),
custodyEvent("12345A", LocalDate.now()),
custodyEvent("12345D", LocalDate.now().minusDays(3)),
custodyEvent(null, LocalDate.now().minusDays(4)),
anEvent(),
anEvent()
));
var offender = offenderPrisonerService.refreshOffenderPrisonersFor(anOffender().toBuilder().offenderId(99L).build());
assertThat(offender.getMostRecentPrisonerNumber()).isEqualTo("12345A");
}
private Event custodyEvent(String prisonNumber, LocalDate disposalStartDate) {
final var custody = aCustodyEvent()
.getDisposal()
.getCustody()
.toBuilder()
.prisonerNumber(prisonNumber)
.build();
final var disposal = aCustodyEvent()
.getDisposal()
.toBuilder()
.custody(custody)
.startDate(disposalStartDate)
.build();
return aCustodyEvent()
.toBuilder()
.disposal(disposal)
.build();
}
}
| 40.962963
| 125
| 0.672016
|
eff039e4ba59840d95573aecdcb5eb8be3bddf8f
| 2,001
|
package jetbrains.mps.baseLanguage.lightweightdsl.actions;
/*Generated by MPS */
import jetbrains.mps.openapi.actions.descriptor.NodeFactory;
import org.jetbrains.mps.openapi.model.SNode;
import org.jetbrains.mps.openapi.model.SModel;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SNodeOperations;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SLinkOperations;
import jetbrains.mps.baseLanguage.lightweightdsl.behavior.DSLClassMember__BehaviorDescriptor;
import org.jetbrains.mps.openapi.language.SConcept;
import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory;
import org.jetbrains.mps.openapi.language.SContainmentLink;
public class ModifiersFactories {
public static class NodeFactory_8823436878019221504 implements NodeFactory {
public void setup(SNode newNode, SNode sampleNode, SNode enclosingNode, int index, SModel model) {
SNode propertyDescriptor = SNodeOperations.getNodeAncestor(enclosingNode, CONCEPTS.PropertyDescriptor$B2, true, false);
if ((propertyDescriptor != null)) {
SLinkOperations.setTarget(newNode, LINKS.value$urNO, SNodeOperations.cast(DSLClassMember__BehaviorDescriptor.create_id7ay_HjIOVVe.invoke(propertyDescriptor, model), CONCEPTS.PropertyInstance$7w));
}
}
}
private static final class CONCEPTS {
/*package*/ static final SConcept PropertyDescriptor$B2 = MetaAdapterFactory.getConcept(0xc7d5b9dda05f4be2L, 0xbc73f2e16994cc67L, 0x72b255a0447fbb31L, "jetbrains.mps.baseLanguage.lightweightdsl.structure.PropertyDescriptor");
/*package*/ static final SConcept PropertyInstance$7w = MetaAdapterFactory.getConcept(0xc7d5b9dda05f4be2L, 0xbc73f2e16994cc67L, 0x59e9926e840d9151L, "jetbrains.mps.baseLanguage.lightweightdsl.structure.PropertyInstance");
}
private static final class LINKS {
/*package*/ static final SContainmentLink value$urNO = MetaAdapterFactory.getContainmentLink(0xc7d5b9dda05f4be2L, 0xbc73f2e16994cc67L, 0x7a7325178c68eba9L, 0x7a7325178c68f138L, "value");
}
}
| 58.852941
| 229
| 0.824588
|
c34d43355be788607c6828f2b5d18313fdf51c9b
| 1,455
|
package top.chenqwwq.leetcode.daily._20201030;
/**
* 463. 岛屿的周长
* 给定一个包含 0 和 1 的二维网格地图,其中 1 表示陆地 0 表示水域。
* <p>
* 网格中的格子水平和垂直方向相连(对角线方向不相连)。整个网格被水完全包围,但其中恰好有一个岛屿(或者说,一个或多个表示陆地的格子相连组成的岛屿)。
* <p>
* 岛屿中没有“湖”(“湖” 指水域在岛屿内部且不和岛屿周围的水相连)。格子是边长为 1 的正方形。网格为长方形,且宽度和高度均不超过 100 。计算这个岛屿的周长。
* <p>
* <p>
* <p>
* 示例 :
* <p>
* 输入:
* [[0,1,0,0],
* [1,1,1,0],
* [0,1,0,0],
* [1,1,0,0]]
* <p>
* 输出: 16
* <p>
* 解释: 它的周长是下面图片中的 16 个黄色的边:
*
* @author chen
* @date 2020/10/30
**/
public class Solution {
// 可以一直往右和下进行探测,一次以2为单位加减
private int[][] CHANGES = new int[][]{
{1, 0},
{0, 1},
{0, -1},
{-1, 0}
};
public int islandPerimeter(int[][] grid) {
if (grid == null || grid.length == 0) {
return 0;
}
int total = 0, coincide = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == 0) {
continue;
}
// 陆地块数
total++;
// 重合边数
for (int[] change : CHANGES) {
int q = i + change[0], p = j + change[1];
if (q >= 0 && q < grid.length && p >= 0 && p < grid[0].length && grid[q][p] == 1) {
coincide++;
}
}
}
}
return 4 * total - coincide;
}
}
| 22.734375
| 103
| 0.414433
|
dbe34c446a117ee211f251e9e5c883eaf570e26d
| 3,627
|
/**
* Copyright 2011-2017 Asakusa Framework Team.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.asakusafw.windgate.core;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
/**
* The profile context.
* @since 0.2.4
* @version 0.9.1
*/
public class ProfileContext {
private final ClassLoader classLoader;
private final ParameterList contextParameters;
private final Map<Class<?>, Object> resources;
/**
* Creates a new instance.
* @param classLoader the class loader to load services
* @param contextParameters the context parameters
* @throws IllegalArgumentException if some parameters were {@code null}
*/
public ProfileContext(ClassLoader classLoader, ParameterList contextParameters) {
if (classLoader == null) {
throw new IllegalArgumentException("classLoader must not be null"); //$NON-NLS-1$
}
if (contextParameters == null) {
throw new IllegalArgumentException("contextParameters must not be null"); //$NON-NLS-1$
}
this.classLoader = classLoader;
this.contextParameters = contextParameters;
this.resources = Collections.emptyMap();
}
private ProfileContext(ClassLoader classLoader, ParameterList contextParameters, Map<Class<?>, Object> resources) {
this.classLoader = classLoader;
this.contextParameters = contextParameters;
this.resources = resources;
}
/**
* Creates a new context with system variables as context parameters.
* @param classLoader current class loader
* @return the created context object
* @throws IllegalArgumentException if some parameters were {@code null}
*/
public static ProfileContext system(ClassLoader classLoader) {
return new ProfileContext(classLoader, new ParameterList(System.getenv()));
}
/**
* Creates a new context with the additional resource.
* @param <T> the resource type
* @param type the resource type
* @param object the resource
* @return the created context
* @since 0.9.1
*/
public <T> ProfileContext withResource(Class<T> type, T object) {
Map<Class<?>, Object> copy = new LinkedHashMap<>(resources);
copy.put(type, object);
return new ProfileContext(classLoader, contextParameters, copy);
}
/**
* Returns a class loader to load services.
* @return the class loader
*/
public ClassLoader getClassLoader() {
return classLoader;
}
/**
* Returns context parameters (may be environment variables).
* @return the context parameters
*/
public ParameterList getContextParameters() {
return contextParameters;
}
/**
* Returns an optional resource.
* @param <T> the resource type
* @param type the resource type
* @return the related resource
* @since 0.9.1
*/
public <T> Optional<T> findResource(Class<T> type) {
return Optional.ofNullable(type.cast(resources.get(type)));
}
}
| 32.675676
| 119
| 0.677144
|
fe546b4bfe708b6eff2951fec17b48346fe9a70f
| 1,899
|
package allow.simulator.mobility.data;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import allow.simulator.entity.Person;
import allow.simulator.entity.TransportationEntity;
import allow.simulator.util.Coordinate;
public abstract class Stop {
// Id of stop
protected final String stopId;
// Position of the stop
protected final Coordinate position;
// Transportation entities waiting at the stop
protected final Queue<TransportationEntity> transportationEntities;
// Passengers waiting at the stop
protected final Queue<Person> passengers;
/**
* Creates new instance of a stop.
*
* @param stopId Id of the stop.
* @param position Location of the stop.
*/
protected Stop(String stopId, Coordinate position) {
this.stopId = stopId;
this.position = position;
transportationEntities = new ConcurrentLinkedQueue<TransportationEntity>();
passengers = new ConcurrentLinkedQueue<Person>();
}
/**
* Returns the Id of the stop.
*
* @return Id of the stop.
*/
public String getStopId() {
return stopId;
}
/**
* Returns the position of this stop.
*
* @return Position of this stop.
*/
public Coordinate getPosition() {
return position;
}
/**
* Checks if there are any passengers waiting at this stop.
*
* @return True if there are passengers waiting, false otherwise
*/
public boolean hasWaitingPersons() {
return passengers.isEmpty();
}
/**
* Adds a waiting passengers to this stop.
*
* @param passenger Passenger to add to this stop
*/
public void addWaitingPerson(Person passenger) {
passengers.add(passenger);
}
/**
* Removes a waiting passenger from this stop.
*
* @param p Passenger to remove from this stop
*/
public void removeWaitingPerson(Person passenger) {
passengers.remove(passenger);
}
public String toString() {
return "[Stop" + stopId + "]";
}
}
| 22.341176
| 77
| 0.716166
|
d3c53a8758c07037156f1492939856d5538a5912
| 3,091
|
package com.cookpad.prism.merge;
import java.io.IOException;
import java.time.Clock;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
import com.cookpad.prism.SchemaBuilder;
import com.cookpad.prism.SchemaBuilder.BadColumnsError;
import com.cookpad.prism.merge.MergeJobWorker.MergePlan;
import com.cookpad.prism.merge.MergeJobWorker.MergePlanExecutor;
import com.cookpad.prism.objectstore.PrismObjectStore;
import com.cookpad.prism.objectstore.PrismObjectStoreFactory;
import com.cookpad.prism.record.Schema;
import com.cookpad.prism.dao.OneToMany;
import com.cookpad.prism.dao.PrismMergeRange;
import com.cookpad.prism.dao.PrismMergeRangeMapper;
import com.cookpad.prism.dao.PrismPartition;
import com.cookpad.prism.dao.PrismPartitionMapper;
import com.cookpad.prism.dao.PrismSmallObject;
import com.cookpad.prism.dao.PrismSmallObjectMapper;
import com.cookpad.prism.dao.PrismTable;
import com.cookpad.prism.dao.PrismTableMapper;
import com.cookpad.prism.dao.StreamColumn;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import lombok.RequiredArgsConstructor;
@Component
@Lazy
@RequiredArgsConstructor
public class RebuildCmd {
private final ParallelParquetMerger parallelParquetMerger;
private final PrismMergeRangeMapper mergeRangeMapper;
private final PrismSmallObjectMapper smallObjectMapper;
private final PrismPartitionMapper partitionMapper;
private final PrismTableMapper tableMapper;
private final PrismObjectStoreFactory objectStoreFactory;
private final Clock clock;
public void run(int tableId, List<LocalDate> partitionDates) throws BadColumnsError, IOException {
OneToMany<PrismTable, StreamColumn> tableWithColumns = tableMapper.findWithColumns(tableId);
PrismTable table = tableWithColumns.getOne();
Schema schema = new SchemaBuilder().build(tableWithColumns.getOne(), tableWithColumns.getMany());
PrismObjectStore prismObjectStore = this.objectStoreFactory.create(table);
MergePlanExecutor planExecutor = MergePlanExecutor.of(
mergeRangeMapper,
parallelParquetMerger,
prismObjectStore,
clock
);
for (LocalDate date : partitionDates) {
PrismPartition partition = this.partitionMapper.findByTableIdAndDate(tableId, date);
if (partition == null) {
continue;
}
List<PrismMergeRange> mergeRanges = this.mergeRangeMapper.findAllInPartition(partition.getId());
for (PrismMergeRange mergeRange : mergeRanges) {
List<PrismSmallObject> smallObjects = this.smallObjectMapper.findAllObjectsInRange(partition.getId(), mergeRange.getLowerBound(), mergeRange.getUpperBound());
MergePlan plan = new MergePlan(partition, mergeRange.getLowerBound(), false, smallObjects, Optional.empty());
planExecutor.execute(schema, plan);
}
this.partitionMapper.updateCurrentManifestVersion(partition.getId(), -1);
}
}
}
| 44.797101
| 174
| 0.761566
|
c6826e83ae271c1a2c9ba2d1e576620a08bee64c
| 1,036
|
package org.microprofile.test;
import java.nio.ByteBuffer;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.microprofile.common.buffer.MultiByteBuffer;
public class MultiByteBufferTest2 {
public static void main(String[] args) {
ConcurrentLinkedQueue<ByteBuffer> recycleByteBufferQueue = new ConcurrentLinkedQueue<>();
MultiByteBuffer multiByteBuffer = new MultiByteBuffer();
for (int i = 0; i < 500; i++) {
byte[] randBytes = new byte[1024];
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
byteBuffer.get(randBytes);
byteBuffer.flip();
multiByteBuffer.put(byteBuffer);
}
multiByteBuffer.mark();
for (int i = 1; i < 500 * 1024; i++) {
multiByteBuffer.get();
}
long a = System.nanoTime();
multiByteBuffer.clear(recycleByteBufferQueue);
System.out.println(System.nanoTime() - a);
System.out.println(multiByteBuffer);
}
}
| 34.533333
| 98
| 0.625483
|
8dac5319d617e6083f743193afba1a3851725346
| 1,691
|
package cola.machine.game.myblocks.world.chunks;
import java.util.Map;
import cola.machine.game.myblocks.math.Vector3i;
import cola.machine.game.myblocks.model.IBlock;
import cola.machine.game.myblocks.world.chunks.blockdata.TeraArray;
public interface Chunk {
/**
* 得到chunk的 大块区域坐标 类似时区
* @return
*/
Vector3i getPos();
IBlock getBlock(Vector3i pos);
IBlock getBlock(int x, int y, int z);
public void setBlock(int x, int y, int z, int block) ;
//public void setBlock(int x, int y, int z, Integer block) ;
IBlock setBlock(int x, int y, int z, IBlock block);
IBlock setBlock(Vector3i pos, IBlock block);
/* void setLiquid(Vector3i pos, LiquidData state);
void setLiquid(int x, int y, int z, LiquidData newState);
LiquidData getLiquid(Vector3i pos);
LiquidData getLiquid(int x, int y, int z);*/
Vector3i getChunkWorldPos();
/**
* 得到精准的世界坐标 类似经纬度
* @return
*/
int getChunkWorldPosX();
int getChunkWorldPosY();
int getChunkWorldPosZ();
Vector3i getBlockWorldPos(Vector3i blockPos);
Vector3i getBlockWorldPos(int x, int y, int z);
int getBlockWorldPosX(int x);
int getBlockWorldPosY(int y);
int getBlockWorldPosZ(int z);
int getChunkSizeX();
int getChunkSizeY();
void setBlockData(TeraArray blockData);
int getChunkSizeZ();
TeraArray getBlockData();
int getBlockData(int x,int y,int z);
Integer[] zip();
public void disposeMesh();
public void build() ;
void setNeedUpdate(boolean b);
boolean isNeedUpdate();
Map<Integer, IBlock> getBlockMap();
void setBlockStatus(int x, int y, int z, int dir);
}
| 21.405063
| 67
| 0.672383
|
7444c724f3c44ec1a21547b6a8ca53bf2eff4915
| 2,571
|
// $ANTLR 2.7.7 (20080509): "Vlogpp.g" -> "VlogppLexer.java"$
/*
*************************************************************************
*************************************************************************
** **
** V2KPARSE **
** Copyright (C) 2008-2009 Karl W. Pfalzer **
** **
** This program is free software; you can redistribute it and/or **
** modify it under the terms of the GNU General Public License **
** as published by the Free Software Foundation; either version 2 **
** of the License, or (at your option) any later version. **
** **
** This program is distributed in the hope that it will be useful, **
** but WITHOUT ANY WARRANTY; without even the implied warranty of **
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the **
** GNU General Public License for more details. **
** **
** You should have received a copy of the GNU General Public License **
** along with this program; if not, write to the **
** Free Software Foundation, Inc. **
** 51 Franklin Street, Fifth Floor **
** Boston, MA 02110-1301, USA. **
** **
*************************************************************************
*************************************************************************
*/
package v2k.parser;
import java.util.LinkedList;
public interface VlogppLexerTokenTypes {
int EOF = 1;
int NULL_TREE_LOOKAHEAD = 3;
int TIC_DIRECTIVE = 4;
int MACRO_EXPAND = 5;
int MACRO_EXPAND_PARMS = 6;
int MACRO_EXPAND_PARMS2 = 7;
int PAREN_CLOSURE = 8;
int PAREN_CLOSURE2 = 9;
int CURLY_CLOSURE = 10;
int CURLY_CLOSURE2 = 11;
int IDENT = 12;
int STRING = 13;
int UNSIZED_NUMBER = 14;
int DIGIT = 15;
int TIC_TIMESCALE = 16;
int TIMESCALE_VALUE = 17;
int TIC_DEFINE = 18;
int TIC_DEFINE_PARMS = 19;
int TIC_INCLUDE = 20;
int DEFINE = 21;
int WS = 22;
int CNTRL = 23;
int SKIP_DIRECTIVE = 24;
int SL_COMMENT = 25;
int ML_COMMENT = 26;
int COMMENT = 27;
int DUMMY = 28;
}
| 42.147541
| 74
| 0.433294
|
e8490e418be756368d9bd57b44ef77f8904c0c5e
| 13,245
|
/*
* Copyright (c) 2015, Alachisoft. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alachisoft.tayzgrid.socketserver.util;
import com.alachisoft.tayzgrid.socketserver.SocketServer;
import com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResultProtocol;
import com.alachisoft.tayzgrid.common.protobuf.KeyExceptionPackageResponseProtocol;
import com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResponseProtocol;
import com.alachisoft.tayzgrid.common.protobuf.ExceptionProtocol;
import com.alachisoft.tayzgrid.common.protobuf.KeyValuePackageResponseProtocol;
import com.alachisoft.tayzgrid.common.protobuf.ValueProtocol;
import com.alachisoft.tayzgrid.caching.CompressedValueEntry;
import com.alachisoft.tayzgrid.caching.UserBinaryObject;
import com.alachisoft.tayzgrid.common.util.CacheKeyUtil;
import com.alachisoft.tayzgrid.runtime.datasourceprovider.OperationResult;
import java.util.Iterator;
import java.util.Map;
import com.google.protobuf.ByteString;
import java.io.IOException;
import java.util.List;
public final class KeyPackageBuilder
{
/**
* Make a package containing quote separated keys from list
*
* @param keysList list of keys to be packaged
* @return key package being constructed
*/
public static String PackageKeys(java.util.ArrayList keyList)
{
StringBuilder keyPackage = new StringBuilder(keyList.size() * 256);
for (int i = 0; i < keyList.size(); i++)
{
keyPackage.append((String) keyList.get(i) + "\"");
}
return keyPackage.toString();
}
/**
* Make a package containing quote separated keys from list
*
* @param keysList list of keys to be packaged
* @return key package being constructed
*/
public static String PackageKeys(java.util.Collection keyList)
{
String packagedKeys = "";
if (keyList != null && keyList.size() > 0)
{
StringBuilder keyPackage = new StringBuilder(keyList.size() * 256);
java.util.Iterator ie = keyList.iterator();
while (ie.hasNext())
{
keyPackage.append((String) ie.next() + "\"");
}
packagedKeys = keyPackage.toString();
}
return packagedKeys;
}
public static void PackageKeys(Iterator dicEnu, tangible.RefObject<String> keyPackage, tangible.RefObject<Integer> keyCount)
{
StringBuilder keys = new StringBuilder(1024);
keyCount.argvalue = 0;
Map.Entry pair;
while (dicEnu.hasNext())
{
pair = (Map.Entry) dicEnu.next();
keys.append(pair.getKey() + "\"");
keyCount.argvalue++;
}
keyPackage.argvalue = keys.toString();
}
public static void PackageKeys(java.util.Iterator enumerator, java.util.List<ByteString> keys, String serializationContext) throws IOException
{
if (enumerator instanceof Iterator)
{
Iterator ide = (Iterator) ((enumerator instanceof Iterator) ? enumerator : null);
Object nextValue;
while (ide.hasNext())
{
nextValue = ide.next();
keys.add(CacheKeyUtil.toByteString(nextValue, serializationContext));
}
}
else
{
while (enumerator.hasNext())
{
keys.add(CacheKeyUtil.toByteString(enumerator.next(), serializationContext));
}
}
}
/**
* Makes a key and data package form the keys and values of hashtable
*
* @param dic HashMap containing the keys and values to be packaged
* @param keys Contains packaged keys after execution
* @param data Contains packaged data after execution
* @param currentContext Current cache
*/
public static java.util.ArrayList<KeyValuePackageResponseProtocol.KeyValuePackageResponse> PackageKeysValues(java.util.HashMap dic, String serializationContext) throws IOException
{
int estimatedSize = 0;
java.util.ArrayList<KeyValuePackageResponseProtocol.KeyValuePackageResponse> ListOfKeyPackageResponse = new java.util.ArrayList<KeyValuePackageResponseProtocol.KeyValuePackageResponse>();
if (dic != null && dic.size() > 0)
{
KeyValuePackageResponseProtocol.KeyValuePackageResponse.Builder keyPackageResponse = KeyValuePackageResponseProtocol.KeyValuePackageResponse.newBuilder();
Iterator enu = dic.entrySet().iterator();
Map.Entry pair;
while (enu.hasNext())
{
pair = (Map.Entry) enu.next();
UserBinaryObject ubObject = (UserBinaryObject) ((((CompressedValueEntry) pair.getValue()).Value instanceof UserBinaryObject) ? ((CompressedValueEntry) pair.getValue()).Value : null);
ValueProtocol.Value.Builder valueBuilder = ValueProtocol.Value.newBuilder();
for (int i = 0; i < ubObject.getDataList().size(); i++)
{
Object[] test = ubObject.getData();
valueBuilder.addData(ByteString.copyFrom((byte[]) test[i]));
}
keyPackageResponse.addKeys(CacheKeyUtil.toByteString(pair.getKey(), serializationContext));
keyPackageResponse.addFlag((int) ((CompressedValueEntry) pair.getValue()).Flag.getData());
keyPackageResponse.addValues(valueBuilder.build());
estimatedSize = estimatedSize + ubObject.getSize();
if (estimatedSize >= SocketServer.CHUNK_SIZE_FOR_OBJECT)
{
ListOfKeyPackageResponse.add(keyPackageResponse.build());
estimatedSize = 0;
}
}
if (estimatedSize != 0)
{
ListOfKeyPackageResponse.add(keyPackageResponse.build());
}
}
else
{
ListOfKeyPackageResponse.add(KeyValuePackageResponseProtocol.KeyValuePackageResponse.newBuilder().build());
}
return ListOfKeyPackageResponse;
}
/**
* Makes a key and data package form the keys and values of hashtable
*
* @param dic HashMap containing the keys and values to be packaged
* @param keys Contains packaged keys after execution
* @param data Contains packaged data after execution
* @param currentContext Current cache
*/
public static KeyValuePackageResponseProtocol.KeyValuePackageResponse PackageKeysValues(java.util.HashMap dic, KeyValuePackageResponseProtocol.KeyValuePackageResponse keyPackageResponse, String serializationContext) throws IOException
{
if (dic != null && dic.size() > 0)
{
if (keyPackageResponse == null)
{
keyPackageResponse = KeyValuePackageResponseProtocol.KeyValuePackageResponse.newBuilder().build();
}
;
Iterator enu = dic.entrySet().iterator();
Map.Entry pair;
while (enu.hasNext())
{
pair = (Map.Entry) enu.next();
keyPackageResponse.getKeysList().add(CacheKeyUtil.toByteString(pair.getKey(), serializationContext));
keyPackageResponse.getFlagList().add((int) ((CompressedValueEntry) pair.getValue()).Flag.getData());
UserBinaryObject ubObject = (UserBinaryObject) ((((CompressedValueEntry) pair.getValue()).Value instanceof UserBinaryObject) ? ((CompressedValueEntry) pair.getValue()).Value : null);
ValueProtocol.Value.Builder valueBuilder = ValueProtocol.Value.newBuilder();
ValueProtocol.Value value = valueBuilder.build();
value.getDataList().addAll((List) ubObject.getDataList());
keyPackageResponse.getValuesList().add(value);
}
}
return keyPackageResponse;
}
/**
* Makes a key and data package form the keys and values of hashtable, for bulk operations
*
* @param dic HashMap containing the keys and values to be packaged
* @param keys Contains packaged keys after execution
* @param data Contains packaged data after execution
*/
public static void PackageKeysExceptions(java.util.HashMap dic, KeyExceptionPackageResponseProtocol.KeyExceptionPackageResponse.Builder keyExceptionPackage, String serializationContext) throws IOException
{
if (dic != null && dic.size() > 0)
{
Iterator enu = dic.entrySet().iterator();
Map.Entry pair;
while (enu.hasNext())
{
pair = (Map.Entry) enu.next();
Exception ex = (Exception) ((pair.getValue() instanceof Exception) ? pair.getValue() : null);
if (ex != null)
{
keyExceptionPackage.addKeys(CacheKeyUtil.toByteString(pair.getKey(), serializationContext));
ExceptionProtocol.Exception.Builder excBuilder = ExceptionProtocol.Exception.newBuilder();
excBuilder.setMessage(ex.getMessage());
excBuilder.setException(ex.toString());
excBuilder.setType(ExceptionProtocol.Exception.Type.GENERALFAILURE);
ExceptionProtocol.Exception exc = excBuilder.build();
keyExceptionPackage.addExceptions(exc);
}
//for DS write failed operations
if (pair.getValue() instanceof OperationResult.Status) {
OperationResult.Status status = (OperationResult.Status) pair.getValue();
if (status == OperationResult.Status.Failure || status == OperationResult.Status.FailureDontRemove) {
keyExceptionPackage.addKeys(CacheKeyUtil.toByteString(pair.getKey(), serializationContext));
ExceptionProtocol.Exception.Builder excBuilder = ExceptionProtocol.Exception.newBuilder();
excBuilder.setMessage(ex.getMessage());
excBuilder.setException(ex.toString());
excBuilder.setType(ExceptionProtocol.Exception.Type.GENERALFAILURE);
ExceptionProtocol.Exception exc = excBuilder.build();
keyExceptionPackage.addExceptions(exc);
}
}
}
}
}
/**
* Package keys and values where values can be Exception or not. If they are no exception, currently, 0 bytes is returned
*
* @param dic
* @param keyPackage
* @param dataPackage
*/
public static void PackageMisc(java.util.Map dic, DSUpdatedCallbackResponseProtocol.DSUpdatedCallbackResponse.Builder results, String serializationContext) throws IOException
{
if (dic != null && dic.size() > 0)
{
Iterator enu = dic.entrySet().iterator();
Map.Entry keyVal;
while (enu.hasNext())
{
keyVal = (Map.Entry) enu.next();
DSUpdatedCallbackResultProtocol.DSUpdatedCallbackResult.Builder resultBuilder = DSUpdatedCallbackResultProtocol.DSUpdatedCallbackResult.newBuilder();
resultBuilder.setKey(CacheKeyUtil.toByteString(keyVal.getKey(), serializationContext));
if (keyVal.getValue() instanceof Exception)
{
resultBuilder.setSuccess(false);
ExceptionProtocol.Exception.Builder exBuilder = ExceptionProtocol.Exception.newBuilder();
exBuilder.setMessage(((Exception) keyVal.getValue()).getMessage());
exBuilder.setException(((Exception) keyVal.getValue()).toString());
exBuilder.setType(ExceptionProtocol.Exception.Type.GENERALFAILURE);
ExceptionProtocol.Exception ex = exBuilder.build();
resultBuilder.setException(ex);
}
else if (keyVal.getValue() instanceof OperationResult.Status)
{
switch ((OperationResult.Status)keyVal.getValue())
{
case Success:
resultBuilder.setSuccess(true);
break;
case Failure:
case FailureDontRemove:
resultBuilder.setSuccess(false);
break;
}
}
DSUpdatedCallbackResultProtocol.DSUpdatedCallbackResult result = resultBuilder.build();
results.addResult(result);
}
}
}
}
| 42.588424
| 238
| 0.626803
|
3f4d90e3612a80c14bd236e5e54b6d7762fa4360
| 1,415
|
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot.subsystems;
import com.revrobotics.CANSparkMax;
import com.revrobotics.CANSparkMaxLowLevel.MotorType;
import edu.wpi.first.wpilibj2.command.SubsystemBase;
import frc.robot.Constants;
public class DriveTrain extends SubsystemBase {
/** Creates a new DriveTrain. */
CANSparkMax frontLeft = new CANSparkMax(Constants.frontLeftMotor, MotorType.kBrushless);
CANSparkMax backLeft = new CANSparkMax(Constants.backLeftMotor, MotorType.kBrushless);
CANSparkMax frontRight = new CANSparkMax(Constants.frontRightMotor, MotorType.kBrushless);
CANSparkMax backRight = new CANSparkMax(Constants.backRightMotor, MotorType.kBrushless);
public DriveTrain() {
}
public void drive(double left, double right){
double checkLeft = Math.abs(left);
double checkRight = Math.abs(right);
if(checkLeft > 0.25){
frontLeft.set(left);
backLeft.set(left);
}else{
frontLeft.set(0);
backLeft.set(0);
}
if(checkRight > 0.25){
frontRight.set(-right);
backRight.set(-right);
}else{
frontRight.set(0);
backRight.set(0);
}
}
@Override
public void periodic() {
// This method will be called once per scheduler run
}
}
| 27.745098
| 92
| 0.719435
|
3d920c44dcfcd8990640927996053f4f8d8355cf
| 3,135
|
/*
* Copyright 2017 ~ 2025 the original author or authors. <wanglsir@gmail.com, 983708408@qq.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.wl4g.component.common.serialize;
import com.wl4g.component.common.serialize.JaxbUtils;
import com.wl4g.component.common.serialize.xmlbean.MqttData;
/**
* {@link JaxbUtilsTests}
*
* <pre>
* Step 1: Convert the sample XML data into an XSD definition file.
* Recommended online conversion: <a href=
"https://www.freeformatter.com/xsd-generator.html#ad -output">https://www.freeformatter.com/xsd-generator.html#ad -output</a>
*
* Step 2: Generate the JAXB class from the XSD definition file. For example,
* Use Eclipse: Select XSD file -> Right-click -> Generate -> JAXB classes...
* Use IDEA: Tools > JAXB > Generate Jaca Code From Xml Schema Using JAXB...
* </pre>
*
* @author Wangl.sir <wanglsir@gmail.com, 983708408@qq.com>
* @version v1.0 2020-07-21
* @since
*/
public class JaxbUtilsTests {
public static void main(String[] args) {
String xml = "";
xml += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
xml += "<mqttData>";
xml += " <Session id=\"10\">";
xml += " <DataCollector id=\"ncyt02_dc\">";
xml += " <time>2016-11-22T03:39:30Z</time>";
xml += " <type Type=\"Yk\">";
xml += " <yk pId=\"0\">1</yk>";
xml += " <yk pId=\"1\">1</yk>";
xml += " <yk pId=\"2\">1</yk>";
xml += " <yk pId=\"3\">0</yk>";
xml += " <yk pId=\"4\">1</yk>";
xml += " <yk pId=\"5\">1</yk>";
xml += " <yk pId=\"6\">0</yk>";
xml += " <yk pId=\"7\">1</yk>";
xml += " <yk pId=\"8\">0</yk>";
xml += " </type>";
xml += " <type Type=\"Yt\">";
xml += " <yt pId=\"0\">30.00</yt>";
xml += " <yt pId=\"1\">40.00</yt>";
xml += " <yt pId=\"2\">50.00</yt>";
xml += " <yt pId=\"3\">60.00</yt>";
xml += " <yt pId=\"4\">70.00</yt>";
xml += " <yt pId=\"5\">80.00</yt>";
xml += " <yt pId=\"6\">90.00</yt>";
xml += " <yt pId=\"7\">100.00</yt>";
xml += " <yt pId=\"8\">11.000</yt>";
xml += " </type>";
xml += " </DataCollector>";
xml += " </Session>";
xml += "</mqttData>";
System.out.println("------serialization-------");
MqttData msg = JaxbUtils.fromXml(xml, MqttData.class);
System.out.println(msg.getSession().getDataCollector().getTime());
System.out.println("\n\n");
System.out.println("------serialization-------");
System.out.println(JaxbUtils.toXml(msg, "UTF-8", MqttData.class));
}
}
| 37.321429
| 126
| 0.565869
|
d7e06cb5ee5d7c28733c91a2f6a3e9cc171a0bd3
| 1,540
|
package com.github.jordanpottruff.jgml;
import org.junit.Test;
import static com.github.jordanpottruff.jgml.MatMNTest.assertMatricesEqual;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class MatNTest {
private static final double ERROR_MARGIN = .001;
private static final MatN MAT2_A = new MatN(new double[][]{{1.0, 2.0}, {3.0, 4.0}});
private static final MatN MAT2_B = new MatN(new double[][]{{2.0, 3.0}, {4.0, 5.0}});
@Test
public void testInvert() {
MatN inverted = new MatN(new double[][]{{-1.0, -2.0}, {-3.0, -4.0}});
assertMatricesEqual(inverted, MAT2_A.invert(), ERROR_MARGIN);
}
@Test
public void testAdd() {
MatN sum = new MatN(new double[][]{{3.0, 5.0}, {7.0, 9.0}});
assertMatricesEqual(sum, MAT2_A.add(MAT2_B), ERROR_MARGIN);
}
@Test
public void testSubtract() {
MatN diff = new MatN(new double[][]{{-1.0, -1.0}, {-1.0, -1.0}});
assertMatricesEqual(diff, MAT2_A.subtract(MAT2_B), ERROR_MARGIN);
}
@Test
public void testScale() {
MatN scaled = new MatN(new double[][]{{5.0, 10.0}, {15.0, 20.0}});
assertMatricesEqual(scaled, MAT2_A.scale(5.0), ERROR_MARGIN);
}
@Test
public void testDeterminant() {
assertEquals(-2.0, MAT2_A.determinant(), ERROR_MARGIN);
}
@Test
public void testInverse() {
MatN inverse = new MatN(new double[][]{{-2.0, 1.0}, {1.5, -0.5}});
assertMatricesEqual(inverse, MAT2_A.inverse(), ERROR_MARGIN);
}
}
| 31.428571
| 88
| 0.617532
|
11c2d02b3335172a1ba51ea43abc0c1007bbe360
| 4,575
|
package io.magentys.cinnamon.webdriver.conditions;
import io.magentys.cinnamon.webdriver.actions.synthetic.DomEvent;
import io.magentys.cinnamon.webdriver.elements.*;
import org.openqa.selenium.WebElement;
import static io.magentys.cinnamon.webdriver.conditions.Conditions.not;
public final class ElementConditions {
// Suppresses default constructor, ensuring non-instantiability.
private ElementConditions() {
}
public static Condition<WebElement> displayed = new DisplayedCondition();
public static Condition<WebElement> hidden = not(displayed);
public static Condition<WebElement> empty = new EmptyCondition();
public static Condition<WebElement> notEmpty = not(empty);
public static Condition<WebElement> enabled = new EnabledCondition();
public static Condition<WebElement> disabled = not(enabled);
public static Condition<WebElement> inViewPort = new InViewPortCondition();
public static Condition<WebElement> obscured = new ObscuredCondition();
public static Condition<WebElement> notObscured = not(obscured);
public static Condition<WebElement> selected = new SelectedCondition();
public static Condition<WebElement> deselected = not(selected);
public static Condition<WebElement> clickable = new AndCondition<>(displayed, enabled, notObscured);
public static Condition<WebElement> present = new Condition<WebElement>() {
@Override
public boolean apply(final WebElement element) {
return null != element;
}
@Override
public String toString() {
return "present";
}
};
public static Condition<WebElement> attributeContains(final String attribute, final String value) {
return new AttributeContainsCondition(attribute, value);
}
public static Condition<WebElement> attributeEquals(final String attribute, final String value) {
return new AttributeEqualsCondition(attribute, value);
}
public static Condition<WebElement> attributeMatches(final String attribute, final String regex) {
return new AttributeMatchesCondition(attribute, regex);
}
public static Condition<WebElement> attributeMatches(final String attribute, final String regex, final int flags) {
return new AttributeMatchesCondition(attribute, regex, flags);
}
public static Condition<WebElement> cssPropertyContains(final String cssProperty, final String value) {
return new CssPropertyContainsCondition(cssProperty, value);
}
public static Condition<WebElement> cssPropertyEquals(final String cssProperty, final String value) {
return new CssPropertyEqualsCondition(cssProperty, value);
}
public static Condition<WebElement> cssPropertyMatches(final String cssProperty, final String regex) {
return new CssPropertyMatchesCondition(cssProperty, regex);
}
public static Condition<WebElement> cssPropertyMatches(final String cssProperty, final String regex, final int flags) {
return new CssPropertyMatchesCondition(cssProperty, regex, flags);
}
public static Condition<WebElement> eventListenerRegistered(final DomEvent event) {
return new EventListenerRegisteredCondition(event);
}
public static Condition<WebElement> innerHtmlContains(final String text) {
return new InnerHtmlContainsCondition(text);
}
public static Condition<WebElement> innerHtmlContainsIgnoreCase(final String text) {
return new InnerHtmlContainsCondition(true, text);
}
public static Condition<WebElement> positionUnchanged(final long delayIntervalMillis) {
return new PositionUnchangedCondition(delayIntervalMillis);
}
public static Condition<WebElement> textContains(final String... text) {
return new TextContainsCondition(text);
}
public static Condition<WebElement> textContainsIgnoreCase(final String... text) {
return new TextContainsCondition(true, text);
}
public static Condition<WebElement> textEquals(final String text) {
return new TextEqualsCondition(text);
}
public static Condition<WebElement> textEqualsIgnoreCase(final String text, final boolean ignoreCase) {
return new TextEqualsCondition(true, text);
}
public static Condition<WebElement> textMatches(final String text) {
return new TextMatchesCondition(text);
}
public static Condition<WebElement> textMatches(final String text, final int flags) {
return new TextMatchesCondition(flags, text);
}
}
| 36.895161
| 123
| 0.740546
|
afe04e3a6adf82c98b68f3194777e82961fbf766
| 2,276
|
package project.sudokugames.model.component;
import tests.slidingtiles.R;
import project.model.component.BasicTile;
public class SudokuTile extends BasicTile {
public SudokuTile(int id) {
this.id = id;
assignBackground(id);
}
public void setId(int id) {
this.id = id;
}
@Override
public int getId() {
return this.id;
}
private boolean isGenerated = false;
private int background;
/**
* Return the background id.
*
* @return the background id
*/
public int getBackground() {
System.out.println("id is..." + id);
assignBackground(id);
return background;
}
/*
* set the tile to solid tile
* */
void setTrait() {
this.isGenerated = true;
}
public boolean generated() {
return this.isGenerated;
}
private void assignBackground(int id) {
switch (id) {
case 1:
background = (generated()) ? R.drawable.ngtf1 : R.drawable.tf1;
break;
case 2:
background = (generated()) ? R.drawable.ngtf2 : R.drawable.tf2;
break;
case 3:
background = (generated()) ? R.drawable.ngtf3 : R.drawable.tf3;
break;
case 4:
background = (generated()) ? R.drawable.ngtf4 : R.drawable.tf4;
break;
case 5:
background = (generated()) ? R.drawable.ngtf5 : R.drawable.tf5;
break;
case 6:
background = (generated()) ? R.drawable.ngtf6 : R.drawable.tf6;
break;
case 7:
background = (generated()) ? R.drawable.ngtf7 : R.drawable.tf7;
break;
case 8:
background = (generated()) ? R.drawable.ngtf8 : R.drawable.tf8;
break;
case 9:
background = (generated()) ? R.drawable.ngtf9 : R.drawable.tf9;
break;
case -1: // for selected case
background = R.drawable.sudoku_selected;
break;
default:
background = R.drawable.tf0;
break;
}
}
}
| 26.16092
| 79
| 0.5
|
87db38de76a0b525d21f5b4558e30bed6c7a201c
| 3,944
|
package com.rainbowcard.client.ui.adapter;
import android.content.Context;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.baidu.mapapi.search.core.PoiInfo;
import com.rainbowcard.client.R;
import java.util.ArrayList;
import java.util.List;
import butterknife.ButterKnife;
import butterknife.InjectView;
/**
* Created by gc on 16-10-31.
*/
public class SearchKeywordListAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater mLayoutInflater;
private List<PoiInfo> mKeywordInfos;
private String mKeyword;
public SearchKeywordListAdapter(Context context) {
mContext = context;
mLayoutInflater = LayoutInflater.from(context);
mKeywordInfos = new ArrayList<PoiInfo>();
}
public void setConsumptions(List<PoiInfo> list) {
mKeywordInfos.clear();
mKeywordInfos.addAll(list);
notifyDataSetChanged();
}
public void clear(){
mKeywordInfos.clear();
notifyDataSetChanged();
}
public void setKeyword(String keyword){
mKeyword = keyword;
}
public void addConsumptions(List<PoiInfo> list) {
mKeywordInfos.addAll(list);
notifyDataSetChanged();
}
public List<PoiInfo> getKeywords(){
return mKeywordInfos;
}
@Override
public int getCount() {
return mKeywordInfos.size();
}
@Override
public Object getItem(int i) {
return mKeywordInfos.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
final ViewHolder holder;
if (view == null) {
view = mLayoutInflater.inflate(R.layout.item_keywords_list, viewGroup, false);
holder = new ViewHolder(view);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
final PoiInfo keywordInfo = mKeywordInfos.get(i);
if(!TextUtils.isEmpty(keywordInfo.name)){
SpannableStringBuilder style=new SpannableStringBuilder(keywordInfo.name);
int fstart=keywordInfo.name.indexOf(mKeyword);
int fend=fstart + mKeyword.length();
if(fend > keywordInfo.name.length() || fstart < 0){
holder.titleTv.setText(keywordInfo.name);
}else {
style.setSpan(new ForegroundColorSpan(mContext.getResources().getColor(R.color.detail_fgm_select)), fstart, fend, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
holder.titleTv.setText(style);
}
}
if(!TextUtils.isEmpty(keywordInfo.address)){
SpannableStringBuilder style=new SpannableStringBuilder(keywordInfo.address);
int fstart=keywordInfo.address.indexOf(mKeyword);
int fend=fstart + mKeyword.length();
if(fend > keywordInfo.name.length() || fstart < 0){
holder.addrTv.setText(keywordInfo.address);
}else {
style.setSpan(new ForegroundColorSpan(mContext.getResources().getColor(R.color.detail_fgm_select)), fstart, fend, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
holder.addrTv.setText(style);
}
}
return view;
}
static class ViewHolder {
@InjectView(R.id.title)
TextView titleTv;
@InjectView(R.id.addr)
TextView addrTv;
ViewHolder(View view){
ButterKnife.inject(this, view);
}
}
}
| 30.338462
| 167
| 0.630578
|
aece31afed3467d3cb730ad91402b33ef6fa6eaa
| 13,253
|
package org.nearbyshops.enduserappnew.ShopItemByItem.NewCarts;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import org.nearbyshops.enduserappnew.DaggerComponentBuilder;
import org.nearbyshops.enduserappnew.ItemDetailNew.ItemDetailFragment;
import org.nearbyshops.enduserappnew.ItemDetailNew.ItemDetailNew;
import org.nearbyshops.enduserappnew.Login.Login;
import org.nearbyshops.enduserappnew.Model.Item;
import org.nearbyshops.enduserappnew.Model.Shop;
import org.nearbyshops.enduserappnew.ModelEndPoints.ShopItemEndPoint;
import org.nearbyshops.enduserappnew.ModelRoles.User;
import org.nearbyshops.enduserappnew.Preferences.UtilityFunctions;
import org.nearbyshops.enduserappnew.R;
import org.nearbyshops.enduserappnew.API.ShopItemService;
import org.nearbyshops.enduserappnew.ShopHome.ShopHome;
import org.nearbyshops.enduserappnew.ShopItemByItem.Interfaces.NotifyFillCartsChanged;
import org.nearbyshops.enduserappnew.ShopItemByItem.Interfaces.NotifyNewCartsChanged;
import org.nearbyshops.enduserappnew.Preferences.PrefLocation;
import org.nearbyshops.enduserappnew.ShopsByCategory.Interfaces.NotifySort;
import org.nearbyshops.enduserappnew.ShopsByCategory.Interfaces.NotifyTitleChanged;
import org.nearbyshops.enduserappnew.Preferences.PrefLogin;
import org.nearbyshops.enduserappnew.ShopItemByItemNew.SlidingLayerSort.PrefSortShopItems;
import org.nearbyshops.enduserappnew.Preferences.PrefShopHome;
import java.util.ArrayList;
import javax.inject.Inject;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class NewCartsFragment extends Fragment
implements SwipeRefreshLayout.OnRefreshListener,
AdapterNewCarts.NotifyAddToCart, NotifyFillCartsChanged,
NotifySort {
Item item;
@Inject
ShopItemService shopItemService;
RecyclerView recyclerView;
AdapterNewCarts adapter;
ArrayList<Object> dataset = new ArrayList<>();
GridLayoutManager layoutManager;
SwipeRefreshLayout swipeContainer;
// NotifyPagerAdapter notifyPagerAdapter;
boolean isDestroyed;
// TextView itemDescription;
// TextView itemName;
// ImageView itemImage;
// TextView priceRange;
// TextView shopCount;
//
//
// @Bind(R.id.item_rating)
// TextView itemRating;
//
// @Bind(R.id.rating_count)
// TextView ratingCount;
private int limit = 10;
int offset = 0;
int item_count = 0;
public NewCartsFragment() {
DaggerComponentBuilder.getInstance()
.getNetComponent()
.Inject(this);
}
public static NewCartsFragment newInstance(Item item) {
NewCartsFragment fragment = new NewCartsFragment();
Bundle args = new Bundle();
args.putParcelable("item",item);
fragment.setArguments(args);
return fragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
setRetainInstance(true);
View rootView = inflater.inflate(R.layout.fragment_new_carts, container, false);
ButterKnife.bind(this,rootView);
item = getArguments().getParcelable("item");
dataset.add(0,item);
recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
swipeContainer = (SwipeRefreshLayout)rootView.findViewById(R.id.swipeContainer);
if(swipeContainer!=null) {
swipeContainer.setOnRefreshListener(this);
swipeContainer.setColorSchemeResources(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
}
// bindings for Item
// itemDescription = (TextView) rootView.findViewById(R.id.itemDescription);
// itemName = (TextView) rootView.findViewById(R.id.itemName);
// itemImage = (ImageView) rootView.findViewById(R.id.itemImage);
// priceRange = (TextView) rootView.findViewById(R.id.price_range);
// shopCount = (TextView) rootView.findViewById(R.id.shop_count);
// bindItem();
if(savedInstanceState == null)
{
makeRefreshNetworkCall();
}
else
{
onViewStateRestored(savedInstanceState);
}
setupRecyclerView();
return rootView;
}
void setupRecyclerView()
{
adapter = new AdapterNewCarts(dataset,getActivity(),this,item,(AppCompatActivity) getActivity(),this);
recyclerView.setAdapter(adapter);
layoutManager = new GridLayoutManager(getActivity(),1);
// layoutManager.setAutoMeasureEnabled(true);
recyclerView.setLayoutManager(layoutManager);
//recyclerView.addItemDecoration(
// new DividerItemDecoration(this,DividerItemDecoration.VERTICAL_LIST)
//);
//recyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.HORIZONTAL_LIST));
//itemCategoriesList.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL_LIST));
DisplayMetrics metrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
// layoutManager.setSpanCount(metrics.widthPixels/400);
int spanCount = (int) (metrics.widthPixels/(230 * metrics.density));
if(spanCount==0){
spanCount = 1;
}
layoutManager.setSpanCount(spanCount);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if(layoutManager.findLastVisibleItemPosition()==dataset.size())
{
// trigger fetch next page
if(dataset.size()== previous_position)
{
return;
}
// trigger fetch next page
if((offset+limit)<=item_count)
{
offset = offset + limit;
makeNetworkCall(false, false);
}
previous_position = dataset.size();
}
}
});
}
int previous_position = -1;
@Override
public void onRefresh() {
// dataset.clear();
offset=0;
makeNetworkCall(false, true);
}
void makeRefreshNetworkCall()
{
swipeContainer.post(new Runnable() {
@Override
public void run() {
swipeContainer.setRefreshing(true);
try {
onRefresh();
} catch (IllegalArgumentException ex)
{
ex.printStackTrace();
}
}
});
}
void makeNetworkCall(final boolean notifyChange, final boolean clearDataset)
{
User endUser = PrefLogin.getUser(getActivity());
Integer endUserID = null;
if(endUser != null)
{
endUserID = endUser.getUserID();
}
String current_sort = "";
current_sort = PrefSortShopItems.getSort(getContext())
+ " " + PrefSortShopItems.getAscending(getContext());
// Network Available
Call<ShopItemEndPoint> call = shopItemService.getShopItemEndpoint(
null,null,item.getItemID(),
PrefLocation.getLatitude(getActivity()),
PrefLocation.getLongitude(getActivity()),
null, null,
null,
endUserID,
false,
null,null,null,null,
null,true,current_sort,
limit,offset,null,true
);
call.enqueue(new Callback<ShopItemEndPoint>() {
@Override
public void onResponse(Call<ShopItemEndPoint> call, Response<ShopItemEndPoint> response) {
if(isDestroyed)
{
return;
}
if(response.body()!=null)
{
if(clearDataset)
{
dataset.clear();
dataset.add(0,item);
}
dataset.addAll(response.body().getResults());
item_count = response.body().getItemCount();
if(notifyChange)
{
if(getActivity() instanceof NotifyNewCartsChanged)
{
((NotifyNewCartsChanged)getActivity()).notifyNewCartsChanged();
}
}
}
/*else
{
// dataset.clear();
adapter.notifyDataSetChanged();
if(notifyChange)
{
if(getActivity() instanceof NotifyNewCartsChanged)
{
((NotifyNewCartsChanged)getActivity()).notifyNewCartsChanged();
}
}
}
*/
adapter.notifyDataSetChanged();
notifyTitleChanged();
swipeContainer.setRefreshing(false);
}
@Override
public void onFailure(Call<ShopItemEndPoint> call, Throwable t) {
if(isDestroyed)
{
return;
}
showToastMessage("Network Request failed !");
swipeContainer.setRefreshing(false);
}
});
}
private void showLoginDialog()
{
// FragmentManager fm = getActivity().getSupportFragmentManager();
// LoginDialog loginDialog = new LoginDialog();
// loginDialog.show(fm,"serviceUrl");
Intent intent = new Intent(getActivity(),Login.class);
startActivity(intent);
}
void showToastMessage(String message)
{
if(getActivity()!=null)
{
Toast.makeText(getActivity(),message,Toast.LENGTH_SHORT).show();
}
}
@Override
public void notifyAddToCart() {
// change to true
// dataset.clear();
swipeContainer.post(new Runnable() {
@Override
public void run() {
swipeContainer.setRefreshing(true);
offset = 0;
makeNetworkCall(true,true);
}
});
}
@Override
public void listItemHeaderClick(Item item) {
Intent intent = new Intent(getActivity(), ItemDetailNew.class);
// intent.putExtra(ItemDetail.ITEM_DETAIL_INTENT_KEY,item);
String itemJson = UtilityFunctions.provideGson().toJson(item);
intent.putExtra(ItemDetailFragment.TAG_JSON_STRING,itemJson);
getActivity().startActivity(intent);
}
@Override
public void notifyShopLogoClick(Shop shop) {
// Intent intent = new Intent(getActivity(), MarketDetail.class);
// intent.putExtra(MarketDetail.SHOP_DETAIL_INTENT_KEY,shop);
// startActivity(intent);
Intent shopHomeIntent = new Intent(getActivity(), ShopHome.class);
PrefShopHome.saveShop(shop,getActivity());
startActivity(shopHomeIntent);
}
@Override
public void notifyFilledCartsChanged() {
// onRefresh();
// dataset.clear();
// makeNetworkCall(false);
makeRefreshNetworkCall();
}
void notifyTitleChanged()
{
if(getActivity() instanceof NotifyTitleChanged)
{
((NotifyTitleChanged) getActivity())
.NotifyTitleChanged(
" New Carts (" + String.valueOf(dataset.size()-1) + "/" + item_count + ")",1
);
}
}
@Override
public void onDestroyView() {
super.onDestroyView();
isDestroyed = true;
}
@Override
public void notifySortChanged() {
makeRefreshNetworkCall();
}
public int getItemCount() {
return item_count;
}
}
| 25.784047
| 123
| 0.593526
|
4fd5d3a78082e78fc96be6f485fb0e90359417a8
| 8,897
|
package net.sourceforge.ondex.algorithm.graphquery.nodepath;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import net.sourceforge.ondex.algorithm.pathmodel.Path;
import net.sourceforge.ondex.core.ONDEXConcept;
import net.sourceforge.ondex.core.ONDEXEntity;
import net.sourceforge.ondex.core.ONDEXRelation;
/**
* A two-color singly linked list.
* <p/>
* This is intended for capturing branching, tree-shaped path clusters without duplication.
*
* @author Matthew Pocock
* @param <EA> the current entity type for this EntityNode
* @param <EB> the last entity type in the path
*/
public abstract class PathNode<EA extends ONDEXEntity, EB extends ONDEXEntity> implements Path {
private final EA entity;
private final PathNode<EB, EA> previous;
abstract protected List<ONDEXEntity> buildEntityList(int size);
abstract protected List<ONDEXConcept> buildConceptList(int size);
abstract protected List<ONDEXRelation> buildRelationList(int size);
abstract protected void collectConcepts(Set<ONDEXConcept> concepts);
abstract protected void collectRelations(Set<ONDEXRelation> relations);
final protected int length;
public PathNode(EA entity, PathNode<EB, EA> previous) {
this.entity = entity;
this.previous = previous;
if (previous != null)
this.length = previous.getLength() + 1;
else
this.length = 1;
}
public int getLength() {
return length;
}
public EA getEntity() {
return entity;
}
public PathNode<EB, EA> getPrevious() {
return previous;
}
public boolean equals(Object obj) {
if (obj instanceof PathNode) {
return ((PathNode) obj).length == length
&& ((PathNode) obj).getConceptsInPositionOrder().equals(this.getConceptsInPositionOrder())
&& ((PathNode) obj).getRelationsInPositionOrder().equals(this.getRelationsInPositionOrder());
}
return false;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[CONCEPTS] ");
for (ONDEXConcept concept : getConceptsInPositionOrder()) {
sb.append(concept.getId() + " ");
sb.append(' ');
}
sb.append("[RELATIONS] ");
for (ONDEXRelation relation : getRelationsInPositionOrder()) {
sb.append(relation.getId());
sb.append(' ');
}
return sb.toString();
}
public boolean containsEntity(ONDEXEntity entityToCheck) {
if (this.entity.equals(entityToCheck)) {
return true;
} else if (previous != null && previous.containsEntity(entityToCheck)) {
return true;
}
return false;
}
public boolean containsEntityId(int id, Class<? extends ONDEXEntity> entityType) {
if (entityType.isInstance(entity) && entity.getId() == id) {
return true;
} else if (previous != null && previous.containsEntityId(id, entityType)) {
return true;
}
return false;
}
@Override
public ONDEXEntity getEntityAtPosition(int i) {
return buildEntityList((length + 1) / 2).get(i);
}
@Override
public Set<ONDEXConcept> getAllConcepts() {
Set<ONDEXConcept> concepts = new HashSet<ONDEXConcept>((length + 1) / 2);
collectConcepts(concepts);
return concepts;
}
@Override
public Set<ONDEXRelation> getAllRelations() {
Set<ONDEXRelation> relations = new HashSet<ONDEXRelation>((length + 1) / 2);
collectRelations(relations);
return relations;
}
@Override
public List<ONDEXConcept> getConceptsInPositionOrder() {
return buildConceptList((length + 1) / 2);
}
@Override
public List<ONDEXRelation> getRelationsInPositionOrder() {
return buildRelationList((length + 1) / 2);
}
@Override
public Iterator<ONDEXEntity> iterator() {
return buildEntityList(length).iterator();
}
public static class FirstConceptNode extends PathNode<ONDEXConcept, ONDEXRelation> {
public FirstConceptNode(ONDEXConcept entity) {
super(entity, null);
}
@Override
public int getConceptLength() {
return 1;
}
@Override
public int getRelationLength() {
return 0;
}
@Override
public int getLength() {
return 1;
}
@Override
public void collectConcepts(Set<ONDEXConcept> concepts) {
concepts.add(getEntity());
}
@Override
public void collectRelations(Set<ONDEXRelation> relations) {
// nothing to do
}
@Override
public ONDEXEntity getStartingEntity() {
return getEntity();
}
@Override
protected List<ONDEXEntity> buildEntityList(int size) {
List<ONDEXEntity> el = new ArrayList<ONDEXEntity>(size);
el.add(getEntity());
return el;
}
@Override
protected List<ONDEXConcept> buildConceptList(int size) {
List<ONDEXConcept> cl = new ArrayList<ONDEXConcept>(size);
cl.add(getEntity());
return cl;
}
@Override
protected List<ONDEXRelation> buildRelationList(int size) {
return new ArrayList<ONDEXRelation>(size);
}
}
public static class ConceptNode extends PathNode<ONDEXConcept, ONDEXRelation> {
public ConceptNode(ONDEXConcept entity, PathNode<ONDEXRelation, ONDEXConcept> previous) {
super(entity, previous);
}
@Override
public int getConceptLength() {
return 1 + getPrevious().getConceptLength();
}
@Override
public int getRelationLength() {
return getPrevious().getConceptLength();
}
@Override
public int getLength() {
return 1 + getPrevious().getLength();
}
@Override
public void collectConcepts(Set<ONDEXConcept> concepts) {
concepts.add(getEntity());
getPrevious().collectConcepts(concepts);
}
@Override
public void collectRelations(Set<ONDEXRelation> relations) {
getPrevious().collectRelations(relations);
}
@Override
public ONDEXEntity getStartingEntity() {
return getPrevious().getStartingEntity();
}
@Override
protected List<ONDEXEntity> buildEntityList(int size) {
List<ONDEXEntity> el = getPrevious().buildEntityList(size);
el.add(getEntity());
return el;
}
@Override
protected List<ONDEXConcept> buildConceptList(int size) {
List<ONDEXConcept> cl = getPrevious().buildConceptList(size);
cl.add(getEntity());
return cl;
}
@Override
protected List<ONDEXRelation> buildRelationList(int size) {
return getPrevious().buildRelationList(size);
}
}
public static class RelationNode extends PathNode<ONDEXRelation, ONDEXConcept> {
public RelationNode(ONDEXRelation entity, PathNode<ONDEXConcept, ONDEXRelation> previous) {
super(entity, previous);
}
@Override
public int getConceptLength() {
return getPrevious().getConceptLength();
}
@Override
public int getRelationLength() {
return 1 + getPrevious().getRelationLength();
}
@Override
public int getLength() {
return 1 + getPrevious().getLength();
}
@Override
public void collectConcepts(Set<ONDEXConcept> concepts) {
getPrevious().collectConcepts(concepts);
}
@Override
public void collectRelations(Set<ONDEXRelation> relations) {
relations.add(getEntity());
getPrevious().collectRelations(relations);
}
@Override
public ONDEXEntity getStartingEntity() {
return getPrevious().getStartingEntity();
}
@Override
protected List<ONDEXEntity> buildEntityList(int size) {
List<ONDEXEntity> el = getPrevious().buildEntityList(size);
el.add(getEntity());
return el;
}
@Override
protected List<ONDEXConcept> buildConceptList(int size) {
return getPrevious().buildConceptList(size);
}
@Override
protected List<ONDEXRelation> buildRelationList(int size) {
List<ONDEXRelation> rl = getPrevious().buildRelationList(size);
rl.add(getEntity());
return rl;
}
}
}
| 29.363036
| 113
| 0.607508
|
38b92a01e9397df30342a7c2d869bfcacc8a4313
| 741
|
package com.houarizegai.springdemo;
public class BaseballCoach implements Coach {
private FortuneService fortuneService;
private String name;
public BaseballCoach() {
}
public BaseballCoach(FortuneService fortuneService) {
this.fortuneService = fortuneService;
}
public void setName(String name) {
System.out.println("setName called, value=" + name);
this.name = name;
}
public FortuneService getFortuneService() {
return fortuneService;
}
public void setFortuneService(FortuneService fortuneService) {
this.fortuneService = fortuneService;
}
public String getDailyWorkout() {
return "Spend 30 minutes on batting practice";
}
}
| 22.454545
| 66
| 0.681511
|
ad6acdf0b451fa14a416eecaea211ff1c384f10b
| 616
|
class Solution {
public String XXX(String[] strs) {
//["flower","flow","flight"]
var str1 = strs[0].toCharArray();
//存储结果
var cp = new StringBuilder();
boolean a=false;
for (int i = 0; i < str1.length; i++) {
for (int j = 1; j < strs.length; j++) {
if (strs[j].length() <= i || strs[j].charAt(i) != str1[i]) {
a=true;
break;
}
}
if(a){
break;
}
cp.append(str1[i]);
}
return cp.toString();
}
}
| 25.666667
| 76
| 0.378247
|
1a70ec828467febf773a8d51d66314e374a256da
| 2,141
|
package com.codepath.apps.mysimpletweets.Models;
import com.activeandroid.Model;
import com.activeandroid.annotation.Column;
import com.activeandroid.annotation.Table;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.Serializable;
@Table(name = "UserNew")
public class User extends Model implements Serializable {
@Column(name = "userId", unique = true, onUniqueConflict = Column.ConflictAction.REPLACE)
private long userId;
@Column(name = "name")
private String name;
@Column(name = "screenName")
private String screenName;
@Column(name = "profileImageUrl")
private String profileImageUrl;
private String description;
private int numFollowers;
private int numFollowing;
private int numTweets;
public int getNumTweets() {
return numTweets;
}
public String getName() {
return name;
}
public long getUserId() {
return userId;
}
public String getScreenName() {
return screenName;
}
public String getProfileImageUrl() {
return profileImageUrl;
}
public String getDescription() {
return description;
}
public int getNumFollowers() {
return numFollowers;
}
public int getNumFollowing() {
return numFollowing;
}
public static User fromJson(JSONObject json) {
User user = new User();
try {
user.name = json.getString("name");
user.userId = json.getLong("id");
user.screenName = json.getString("screen_name");
user.profileImageUrl = json.getString("profile_image_url");
user.description = json.getString("description");
user.numFollowers = json.getInt("followers_count");
user.numFollowing = json.getInt("friends_count");
user.numTweets = json.getInt("statuses_count");
} catch (JSONException e) {
e.printStackTrace();
}
user.save();
return user;
}
public String getDisplayName() {
return "<B>" + getName() + "</B>" + " @" + getScreenName();
}
}
| 23.788889
| 93
| 0.631014
|
1bb5be4db262c1fa0a774664581a9d5797cc13af
| 850
|
package com.animo.jRest.test;
import com.animo.jRest.annotation.FollowRedirects;
import com.animo.jRest.annotation.HEADERS;
import com.animo.jRest.annotation.PATH;
import com.animo.jRest.annotation.REQUEST;
import com.animo.jRest.util.APICall;
import com.animo.jRest.util.HTTP_METHOD;
/**
* Created by animo on 23/12/17.
*/
public interface TestApiInterface {
@REQUEST(endpoint = "",type = HTTP_METHOD.GET)
@HEADERS("fasdfdasf:fdfasdfa")
@FollowRedirects(false)
APICall<Void,String> testFollowRedirectFalse();
@REQUEST(endpoint = "",type = HTTP_METHOD.GET)
@HEADERS("fasdfdasf:fdfasdfa")
@FollowRedirects(true)
APICall<Void,String> testFollowRedirectTrue();
@REQUEST(endpoint = "",type = HTTP_METHOD.GET)
@HEADERS("fasdfdasf:fdfasdfa")
APICall<Void,String> testFollowRedirectNone();
}
| 26.5625
| 51
| 0.727059
|
91937044e45266976a305d131c3a4527cf713299
| 666
|
package com.tvd12.ezyfox.testing.reflect;
import static org.testng.Assert.assertEquals;
import org.testng.annotations.Test;
import com.tvd12.ezyfox.reflect.EzyFields;
import com.tvd12.test.base.BaseTest;
public class EzyFieldsTest extends BaseTest {
@Override
public Class<?> getTestClass() {
return EzyFields.class;
}
@Test
public void test() {
assert EzyFields.getFields(null).isEmpty();
assertEquals(EzyFields.getAnnotatedFields(ClassB.class, ExampleAnnotation.class).size(), 2);
}
public static class ClassA {
@ExampleAnnotation
String value;
}
public static class ClassB extends ClassA {
@ExampleAnnotation
String name;
}
}
| 19.588235
| 94
| 0.756757
|
39b355218a1c361ac399a7a6c2f661970714583f
| 8,679
|
/**
* Copyright 2012 Tobias Gierke <tobias.gierke@code-sourcery.de>
*
* 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 de.codesourcery.asm.rewrite;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.instrument.Instrumentation;
import java.security.ProtectionDomain;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.objectweb.asm.ClassReader;
import de.codesourcery.asm.util.IClassReaderProvider;
import de.codesourcery.asm.util.IJoinpointFilter;
/**
* A Java instrumentation agent that applies the {@link ProfilingRewriter} to
* selected classes.
*
* <p>To use this agent, it needs to be part of a JAR file with a 'Pre-mainclass:' attribute in it's manifest
* file that points to this class.</p>
*
* <p>An example JVM invocation would look like</p>
*
* <pre>
* java "-javaagent:target/profilingagent.jar=packages=TestClass;debug=true" ...
* </pre>
*
* <p>
* The agent supports the following agent options of which only <code>packages</code> is mandatory. Multiple
* options need to be separated by semicolons (packages=a;debug=true;...)</p>
*
* <table border="1">
* <tr>
* <td>Option</td>
* <td>Mandatory?</td>
* <td>Description</td>
* <td>Example</td>
* </tr>
* <tr>
* <td>packages</td>
* <td>YES</td>
* <td>comma-separated list of patterns a fully-qualified classname needs to match in order to be instrumented</td>
* <td>packages=some.package,some.package.MyClass,ClassInAnyPackage</td>
* </tr>
* <tr>
* <td>debug</td>
* <td>no</td>
* <td>comma-separated list of patterns a fully-qualified classname needs to match in order to be instrumented</td>
* <td>debug=true</td>
* </tr>
* <tr>
* <td>debugDir</td>
* <td>no</td>
* <td>name of directory where instrumented classes should be written to</td>
* <td>debugDir=/tmp</td>
* </tr>
* </table>
* </p>
*
* @author tobias.gierke@code-sourcery.de
* @see ProfilingRewriter
*/
public class ProfilingClassTransformer
{
private static final String OPTION_DEBUG = "debug";
private static final String OPTION_DEBUG_WRITE_CLASSFILES = "debugDir";
private static final String OPTION_PACKAGES = "packages";
public static void premain(String agentArgs, Instrumentation inst)
{
// parse options
final Map<String, String> options = parseArgs( agentArgs);
if ( StringUtils.isBlank( options.get(OPTION_PACKAGES ) ) )
{
throw new RuntimeException("Agent "+ProfilingClassTransformer.class.getName()+" requires the 'packages=....' option");
}
final boolean debug = options.containsKey(OPTION_DEBUG);
final String[] packages = options.get(OPTION_PACKAGES ).split(",");
if ( ArrayUtils.isEmpty( packages ) )
{
throw new RuntimeException("Agent "+ProfilingClassTransformer.class.getName()+" requires at least one pattern with the 'packages=....' option");
}
if ( debug ) {
System.out.println("ProfilingClassTransformer activated (packages: "+StringUtils.join(packages," , " )+")");
}
final IJoinpointFilter filter = new IJoinpointFilter() {
@Override
public boolean matches(String clazz, String methodName)
{
return true;
}
@Override
public boolean matches(String clazz)
{
for ( String p : packages ) {
if ( clazz.contains( p ) ) {
return true;
}
}
return false;
}
};
final File debugOutputDir = options.containsKey( OPTION_DEBUG_WRITE_CLASSFILES ) ? new File( options.get( OPTION_DEBUG_WRITE_CLASSFILES ) ) : null;
inst.addTransformer(new MyTransformer(filter,debug,debugOutputDir) , false ); // no re-transformation support
}
private static Map<String,String> parseArgs(String arguments)
{
final Map<String,String> result = new HashMap<>();
if ( StringUtils.isBlank( arguments ) ) {
return result;
}
for ( String pair : arguments.split(";") ) {
final String[] keyValue = pair.split("=");
if ( keyValue.length != 2 ) {
throw new IllegalArgumentException("Malformed agent options: '"+arguments+"'");
}
result.put( keyValue[0] , keyValue[1] );
}
return result;
}
public static final class MyTransformer implements ClassFileTransformer
{
private final ProfilingRewriter rewriter = new ProfilingRewriter();
private final IJoinpointFilter filter;
private final boolean debug;
private final File debugWriteClassfiles;
public MyTransformer(IJoinpointFilter filter,boolean debug,File debugWriteClassfiles)
{
this.filter = filter;
this.debug = debug;
if ( debug ) {
rewriter.setDebugMode( true );
rewriter.setVerboseMode( true );
}
this.debugWriteClassfiles = debugWriteClassfiles;
}
public byte[] transform(ClassLoader l, String name, Class<?> c,ProtectionDomain d, final byte[] b) throws IllegalClassFormatException
{
final String fqName = name.replace("/",".");
if ( ! filter.matches( fqName ) ) {
return b;
}
if ( debug ) {
System.out.println("Transforming class "+fqName);
}
final IClassReaderProvider provider = new IClassReaderProvider() {
@Override
public ClassReader getClassReader() throws IOException
{
return new ClassReader(b);
}
@Override
public String getClassName()
{
return fqName;
}
};
try {
final byte[] result = rewriter.rewrite(provider, filter);
if ( debugWriteClassfiles != null )
{
writeDebugClassfile( fqName , result );
}
return result;
}
catch (Exception e) {
e.printStackTrace();
throw new IllegalClassFormatException("Transformer failed for class "+fqName);
}
}
private void writeDebugClassfile(String fqName , byte[] data)
{
final File outfile = new File( debugWriteClassfiles , fqName.replace(".",File.separator)+".class" );
final File outputFolder = outfile.getParentFile();
if ( ! outputFolder.exists() ) {
outputFolder.mkdirs();
}
if ( outputFolder.exists() && outputFolder.isDirectory() )
{
if ( debug ) {
System.out.println("Writing transformed class "+fqName+" to "+outfile.getAbsolutePath());
}
FileOutputStream out = null;
try {
out = new FileOutputStream( outfile );
out.write( data );
} catch(Exception e) {
System.err.println("Failed to write transformed class "+fqName+" to "+outfile.getAbsolutePath()+" ("+e.getMessage()+")");
}
finally {
try {
if ( out != null) {
out.close();
}
} catch(Exception e) { /* ok */ }
}
}
}
}
}
| 35.863636
| 168
| 0.569305
|
6f0bfb2ac364c90770e6aa545401628b84ac9a39
| 450
|
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class ExerciseTwoTest {
ExerciseTwo t2 = new ExerciseTwo();
// The two tests to check the if statement in xMethod.
@Test
void testxMethod1() {
assertEquals("***3", t2.xMethod(3), "Must be ***3");
}
@Test
void testxMethod2() {
assertEquals("incorrect number", t2.xMethod(-1), "Must print out 'incorrect number'");
}
}
| 25
| 90
| 0.671111
|
ae694adff574a6db96c710ad0983e6534931aff7
| 1,975
|
package com.zhuli.mail.annotation;
import android.content.Context;
import android.text.TextUtils;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Properties;
/**
* Copyright (C), 2003-2021, 深圳市图派科技有限公司
* Date: 2021/9/7
* Description: 实现注解绑定Properties字段
* Author: zl
*/
public class AutoProperties {
/**
* 实现注解绑定Properties文件的字段
* @param context 当前Activity
* @param fileName Properties配置文件的文件名
*/
public static void bind(Context context, String fileName){
Properties properties = new Properties();
try {
//加载配置文件
properties.load(context.getAssets().open(fileName));
} catch (IOException e) {
e.printStackTrace();
}
// 获取类信息
Class<? extends Context> aClass = context.getClass();
// 获取所有属性
Field[] declaredFields = aClass.getDeclaredFields();
if (declaredFields.length == 0) {
return;
}
for (Field field : declaredFields) {
// 获取属性上的注解
BindString annotation = field.getAnnotation(BindString.class);
if (annotation != null) {
//获取注解的值
String key = annotation.value();
if (TextUtils.isEmpty(key)) {
// 如果注解没有设置key,则设置字段的名称为key
key = field.getName();
}
try {
// 获取到传递过来的值 这种获取到的数据不用判断类型,后面直接赋值给属性即可
String value = properties.getProperty(key);
if (TextUtils.isEmpty(key)) {
return;
}
// 设置属性可改变(私有属性才需要进行设置,共有属性设置了也没关系)
field.setAccessible(true);
// 设置值到当前页面的属性上面
field.set(context, value);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
}
| 28.214286
| 74
| 0.525063
|
4123392e5aabb43ef92273d96ca693cc5d8fe41e
| 18,858
|
/**
*/
package roadblock.emf.ibl.Ibl;
import java.util.Collection;
import java.util.List;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.EObjectImpl;
import org.eclipse.emf.ecore.util.EObjectContainmentEList;
import org.eclipse.emf.ecore.util.InternalEList;
/**
* <!-- begin-user-doc --> A representation of the model object '
* <em><b>Cell</b></em>'. <!-- end-user-doc -->
*
* <!-- begin-model-doc -->
* Attempt at generating javadoc from EMF.
* <!-- end-model-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link roadblock.emf.ibl.Ibl.Cell#getDisplayName <em>Display Name</em>}</li>
* <li>{@link roadblock.emf.ibl.Ibl.Cell#getDeviceList <em>Device List</em>}</li>
* <li>{@link roadblock.emf.ibl.Ibl.Cell#getProcessList <em>Process List</em>}</li>
* <li>{@link roadblock.emf.ibl.Ibl.Cell#getRuleList <em>Rule List</em>}</li>
* <li>{@link roadblock.emf.ibl.Ibl.Cell#getMoleculeList <em>Molecule List</em>}</li>
* <li>{@link roadblock.emf.ibl.Ibl.Cell#getATGCCommandList <em>ATGC Command List</em>}</li>
* <li>{@link roadblock.emf.ibl.Ibl.Cell#getID <em>ID</em>}</li>
* <li>{@link roadblock.emf.ibl.Ibl.Cell#getVariableAssignmentList <em>Variable Assignment List</em>}</li>
* <li>{@link roadblock.emf.ibl.Ibl.Cell#getProperties <em>Properties</em>}</li>
* </ul>
*
* @see roadblock.emf.ibl.Ibl.IblPackage#getCell()
* @model kind="class"
* @generated
*/
public class Cell extends EObjectImpl implements IVisitable, IMoleculeContainer, IRuleContainer {
/**
* The default value of the '{@link #getDisplayName() <em>Display Name</em>}' attribute.
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @see #getDisplayName()
* @generated
* @ordered
*/
protected static final String DISPLAY_NAME_EDEFAULT = null;
/**
* The cached value of the '{@link #getDisplayName() <em>Display Name</em>}' attribute.
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @see #getDisplayName()
* @generated
* @ordered
*/
protected String displayName = DISPLAY_NAME_EDEFAULT;
/**
* The cached value of the '{@link #getDeviceList() <em>Device List</em>}' containment reference list.
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @see #getDeviceList()
* @generated
* @ordered
*/
protected EList<Device> deviceList;
/**
* The cached value of the '{@link #getProcessList() <em>Process List</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getProcessList()
* @generated
* @ordered
*/
protected EList<Kinetics> processList;
/**
* The cached value of the '{@link #getRuleList() <em>Rule List</em>}' containment reference list.
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @see #getRuleList()
* @generated
* @ordered
*/
protected EList<Rule> ruleList;
/**
* The cached value of the '{@link #getMoleculeList() <em>Molecule List</em>}' containment reference list.
* <!-- begin-user-doc
* --> <!-- end-user-doc -->
* @see #getMoleculeList()
* @generated
* @ordered
*/
protected EList<MolecularSpecies> moleculeList;
/**
* The cached value of the '{@link #getATGCCommandList()
* <em>ATGC Command List</em>}' containment reference list. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @see #getATGCCommandList()
* @generated
* @ordered
*/
protected EList<ATGCDirective> atgcCommandList;
/**
* The default value of the '{@link #getID() <em>ID</em>}' attribute. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @see #getID()
* @generated
* @ordered
*/
protected static final String ID_EDEFAULT = null;
/**
* The cached value of the '{@link #getID() <em>ID</em>}' attribute. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @see #getID()
* @generated
* @ordered
*/
protected String id = ID_EDEFAULT;
/**
* The cached value of the '{@link #getVariableAssignmentList()
* <em>Variable Assignment List</em>}' containment reference list. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @see #getVariableAssignmentList()
* @generated
* @ordered
*/
protected EList<EMFVariableAssignment> variableAssignmentList;
/**
* The cached value of the '{@link #getProperties() <em>Properties</em>}' containment reference list.
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @see #getProperties()
* @generated
* @ordered
*/
protected EList<IProperty> properties;
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
protected Cell() {
super();
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return IblPackage.Literals.CELL;
}
/**
* Returns the value of the '<em><b>Display Name</b></em>' attribute. <!--
* begin-user-doc -->
* <p>
* If the meaning of the '<em>Display Name</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
*
* @return the value of the '<em>Display Name</em>' attribute.
* @see #setDisplayName(String)
* @see roadblock.emf.ibl.Ibl.IblPackage#getCell_DisplayName()
* @model
* @generated
*/
public String getDisplayName() {
return displayName;
}
/**
* Sets the value of the '{@link roadblock.emf.ibl.Ibl.Cell#getDisplayName <em>Display Name</em>}' attribute.
* <!-- begin-user-doc --> <!--
* end-user-doc -->
* @param value the new value of the '<em>Display Name</em>' attribute.
* @see #getDisplayName()
* @generated
*/
public void setDisplayName(String newDisplayName) {
String oldDisplayName = displayName;
displayName = newDisplayName;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, IblPackage.CELL__DISPLAY_NAME, oldDisplayName, displayName));
}
/**
* Returns the value of the '<em><b>Device List</b></em>' containment reference list.
* The list contents are of type {@link roadblock.emf.ibl.Ibl.Device}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Device List</em>' containment reference list
* isn't clear, there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Device List</em>' containment reference list.
* @see roadblock.emf.ibl.Ibl.IblPackage#getCell_DeviceList()
* @model containment="true"
* @generated
*/
public List<Device> getDeviceList() {
if (deviceList == null) {
deviceList = new EObjectContainmentEList<Device>(Device.class, this, IblPackage.CELL__DEVICE_LIST);
}
return deviceList;
}
/**
* Returns the value of the '<em><b>Process List</b></em>' containment reference list.
* The list contents are of type {@link roadblock.emf.ibl.Ibl.Kinetics}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Process List</em>' containment reference list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Process List</em>' containment reference list.
* @see roadblock.emf.ibl.Ibl.IblPackage#getCell_ProcessList()
* @model containment="true"
* @generated
*/
public List<Kinetics> getProcessList() {
if (processList == null) {
processList = new EObjectContainmentEList<Kinetics>(Kinetics.class, this, IblPackage.CELL__PROCESS_LIST);
}
return processList;
}
/**
* Returns the value of the '<em><b>Rule List</b></em>' containment reference list.
* The list contents are of type {@link roadblock.emf.ibl.Ibl.Rule}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Rule List</em>' containment reference list
* isn't clear, there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Rule List</em>' containment reference list.
* @see roadblock.emf.ibl.Ibl.IblPackage#getCell_RuleList()
* @model containment="true"
* @generated
*/
public List<Rule> getRuleList() {
if (ruleList == null) {
ruleList = new EObjectContainmentEList<Rule>(Rule.class, this, IblPackage.CELL__RULE_LIST);
}
return ruleList;
}
/**
* Returns the value of the '<em><b>Molecule List</b></em>' containment reference list.
* The list contents are of type {@link roadblock.emf.ibl.Ibl.MolecularSpecies}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Molecule List</em>' containment reference list
* isn't clear, there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Molecule List</em>' containment reference list.
* @see roadblock.emf.ibl.Ibl.IblPackage#getCell_MoleculeList()
* @model containment="true"
* @generated
*/
public List<MolecularSpecies> getMoleculeList() {
if (moleculeList == null) {
moleculeList = new EObjectContainmentEList<MolecularSpecies>(MolecularSpecies.class, this, IblPackage.CELL__MOLECULE_LIST);
}
return moleculeList;
}
/**
* Returns the value of the '<em><b>ATGC Command List</b></em>' containment reference list.
* The list contents are of type {@link roadblock.emf.ibl.Ibl.ATGCDirective}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>ATGC Command List</em>' containment reference
* list isn't clear, there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>ATGC Command List</em>' containment reference list.
* @see roadblock.emf.ibl.Ibl.IblPackage#getCell_ATGCCommandList()
* @model containment="true"
* @generated
*/
public List<ATGCDirective> getATGCCommandList() {
if (atgcCommandList == null) {
atgcCommandList = new EObjectContainmentEList<ATGCDirective>(ATGCDirective.class, this, IblPackage.CELL__ATGC_COMMAND_LIST);
}
return atgcCommandList;
}
/**
* Returns the value of the '<em><b>ID</b></em>' attribute. <!--
* begin-user-doc -->
* <p>
* If the meaning of the '<em>ID</em>' attribute isn't clear, there really
* should be more of a description here...
* </p>
* <!-- end-user-doc -->
*
* @return the value of the '<em>ID</em>' attribute.
* @see #setID(String)
* @see roadblock.emf.ibl.Ibl.IblPackage#getCell_ID()
* @model
* @generated
*/
public String getID() {
return id;
}
/**
* Sets the value of the '{@link roadblock.emf.ibl.Ibl.Cell#getID <em>ID</em>}' attribute.
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @param value the new value of the '<em>ID</em>' attribute.
* @see #getID()
* @generated
*/
public void setID(String newID) {
String oldID = id;
id = newID;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, IblPackage.CELL__ID, oldID, id));
}
/**
* Returns the value of the '<em><b>Variable Assignment List</b></em>' containment reference list.
* The list contents are of type {@link roadblock.emf.ibl.Ibl.EMFVariableAssignment}.
* <!-- begin-user-doc
* -->
* <p>
* If the meaning of the '<em>Variable Assignment List</em>' containment
* reference list isn't clear, there really should be more of a description
* here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Variable Assignment List</em>' containment reference list.
* @see roadblock.emf.ibl.Ibl.IblPackage#getCell_VariableAssignmentList()
* @model containment="true"
* @generated
*/
public List<EMFVariableAssignment> getVariableAssignmentList() {
if (variableAssignmentList == null) {
variableAssignmentList = new EObjectContainmentEList<EMFVariableAssignment>(EMFVariableAssignment.class, this, IblPackage.CELL__VARIABLE_ASSIGNMENT_LIST);
}
return variableAssignmentList;
}
/**
* Returns the value of the '<em><b>Properties</b></em>' containment reference list.
* The list contents are of type {@link roadblock.emf.ibl.Ibl.IProperty}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Properties</em>' reference list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Properties</em>' containment reference list.
* @see roadblock.emf.ibl.Ibl.IblPackage#getCell_Properties()
* @model containment="true"
* @generated
*/
public List<IProperty> getProperties() {
if (properties == null) {
properties = new EObjectContainmentEList<IProperty>(IProperty.class, this, IblPackage.CELL__PROPERTIES);
}
return properties;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @model
* @generated NOT
*/
public <TResult> TResult accept(IVisitor<TResult> visitor) {
return visitor.visit(this);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case IblPackage.CELL__DEVICE_LIST:
return ((InternalEList<?>)getDeviceList()).basicRemove(otherEnd, msgs);
case IblPackage.CELL__PROCESS_LIST:
return ((InternalEList<?>)getProcessList()).basicRemove(otherEnd, msgs);
case IblPackage.CELL__RULE_LIST:
return ((InternalEList<?>)getRuleList()).basicRemove(otherEnd, msgs);
case IblPackage.CELL__MOLECULE_LIST:
return ((InternalEList<?>)getMoleculeList()).basicRemove(otherEnd, msgs);
case IblPackage.CELL__ATGC_COMMAND_LIST:
return ((InternalEList<?>)getATGCCommandList()).basicRemove(otherEnd, msgs);
case IblPackage.CELL__VARIABLE_ASSIGNMENT_LIST:
return ((InternalEList<?>)getVariableAssignmentList()).basicRemove(otherEnd, msgs);
case IblPackage.CELL__PROPERTIES:
return ((InternalEList<?>)getProperties()).basicRemove(otherEnd, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case IblPackage.CELL__DISPLAY_NAME:
return getDisplayName();
case IblPackage.CELL__DEVICE_LIST:
return getDeviceList();
case IblPackage.CELL__PROCESS_LIST:
return getProcessList();
case IblPackage.CELL__RULE_LIST:
return getRuleList();
case IblPackage.CELL__MOLECULE_LIST:
return getMoleculeList();
case IblPackage.CELL__ATGC_COMMAND_LIST:
return getATGCCommandList();
case IblPackage.CELL__ID:
return getID();
case IblPackage.CELL__VARIABLE_ASSIGNMENT_LIST:
return getVariableAssignmentList();
case IblPackage.CELL__PROPERTIES:
return getProperties();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case IblPackage.CELL__DISPLAY_NAME:
setDisplayName((String)newValue);
return;
case IblPackage.CELL__DEVICE_LIST:
getDeviceList().clear();
getDeviceList().addAll((Collection<? extends Device>)newValue);
return;
case IblPackage.CELL__PROCESS_LIST:
getProcessList().clear();
getProcessList().addAll((Collection<? extends Kinetics>)newValue);
return;
case IblPackage.CELL__RULE_LIST:
getRuleList().clear();
getRuleList().addAll((Collection<? extends Rule>)newValue);
return;
case IblPackage.CELL__MOLECULE_LIST:
getMoleculeList().clear();
getMoleculeList().addAll((Collection<? extends MolecularSpecies>)newValue);
return;
case IblPackage.CELL__ATGC_COMMAND_LIST:
getATGCCommandList().clear();
getATGCCommandList().addAll((Collection<? extends ATGCDirective>)newValue);
return;
case IblPackage.CELL__ID:
setID((String)newValue);
return;
case IblPackage.CELL__VARIABLE_ASSIGNMENT_LIST:
getVariableAssignmentList().clear();
getVariableAssignmentList().addAll((Collection<? extends EMFVariableAssignment>)newValue);
return;
case IblPackage.CELL__PROPERTIES:
getProperties().clear();
getProperties().addAll((Collection<? extends IProperty>)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case IblPackage.CELL__DISPLAY_NAME:
setDisplayName(DISPLAY_NAME_EDEFAULT);
return;
case IblPackage.CELL__DEVICE_LIST:
getDeviceList().clear();
return;
case IblPackage.CELL__PROCESS_LIST:
getProcessList().clear();
return;
case IblPackage.CELL__RULE_LIST:
getRuleList().clear();
return;
case IblPackage.CELL__MOLECULE_LIST:
getMoleculeList().clear();
return;
case IblPackage.CELL__ATGC_COMMAND_LIST:
getATGCCommandList().clear();
return;
case IblPackage.CELL__ID:
setID(ID_EDEFAULT);
return;
case IblPackage.CELL__VARIABLE_ASSIGNMENT_LIST:
getVariableAssignmentList().clear();
return;
case IblPackage.CELL__PROPERTIES:
getProperties().clear();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case IblPackage.CELL__DISPLAY_NAME:
return DISPLAY_NAME_EDEFAULT == null ? displayName != null : !DISPLAY_NAME_EDEFAULT.equals(displayName);
case IblPackage.CELL__DEVICE_LIST:
return deviceList != null && !deviceList.isEmpty();
case IblPackage.CELL__PROCESS_LIST:
return processList != null && !processList.isEmpty();
case IblPackage.CELL__RULE_LIST:
return ruleList != null && !ruleList.isEmpty();
case IblPackage.CELL__MOLECULE_LIST:
return moleculeList != null && !moleculeList.isEmpty();
case IblPackage.CELL__ATGC_COMMAND_LIST:
return atgcCommandList != null && !atgcCommandList.isEmpty();
case IblPackage.CELL__ID:
return ID_EDEFAULT == null ? id != null : !ID_EDEFAULT.equals(id);
case IblPackage.CELL__VARIABLE_ASSIGNMENT_LIST:
return variableAssignmentList != null && !variableAssignmentList.isEmpty();
case IblPackage.CELL__PROPERTIES:
return properties != null && !properties.isEmpty();
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (displayName: ");
result.append(displayName);
result.append(", ID: ");
result.append(id);
result.append(')');
return result.toString();
}
} // Cell
| 32.457831
| 157
| 0.678545
|
f7ef324bb0a1492dc555f9eab1421a3bb63c9cbd
| 1,806
|
/*
* Copyright 2016 BananaRama.
*
* 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 sql.basic;
import org.bananarama.crud.sql.column.SqlTypeConverter;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import org.bananarama.exception.BananaRamaException;
/**
*
* @author Guglielmo De Concini
*/
public class LocalDateTimeConverter implements SqlTypeConverter<LocalDateTime>{
@Override
public LocalDateTime read(ResultSet rs, int index) throws BananaRamaException {
try{
Timestamp ts;
return (ts = rs.getTimestamp(index)) == null ? null : ts.toLocalDateTime();
}
catch(SQLException ex){
throw new BananaRamaException("Can't convert LocalDateTime ",ex);
}
}
@Override
public void write(PreparedStatement ps, int index, LocalDateTime obj) throws BananaRamaException {
try{
if(obj == null)
ps.setNull(index, java.sql.Types.TIMESTAMP);
else
ps.setTimestamp(index, Timestamp.valueOf(obj));
}
catch(SQLException ex){
throw new BananaRamaException("Can't convert LocalDateTime ",ex);
}
}
}
| 30.610169
| 102
| 0.684385
|
0e7926714d3ae50ad48c7672f70a267b4b58ca72
| 1,805
|
package com.dp.bigdata.taurus.web.servlet;
//
//import java.text.SimpleDateFormat;
//import java.util.ArrayList;
//
//import org.restlet.data.MediaType;
//import org.restlet.resource.ClientResource;
//
//import com.dp.bigdata.taurus.restlet.resource.IAttemptsResource;
//import com.dp.bigdata.taurus.restlet.resource.ITasksResource;
//import com.dp.bigdata.taurus.restlet.resource.IUsersResource;
//import com.dp.bigdata.taurus.restlet.shared.AttemptDTO;
//import com.dp.bigdata.taurus.restlet.shared.TaskDTO;
//import com.dp.bigdata.taurus.restlet.shared.UserDTO;
/**
* RestletClientSample
*
* @author damon.zhu
*/
public class RestletClientSample{
public static void main(String args[]){
// ClientResource cr = new ClientResource("http://10.1.77.85:8182/api/task");
// ITasksResource resource = cr.wrap(ITasksResource.class);
// cr.accept(MediaType.APPLICATION_XML);
// ArrayList<TaskDTO> tasks = resource.retrieve();
//
// SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
// for(TaskDTO dto : tasks){
// System.out.println(formatter.format(dto.getAddtime()));
// }
//
// String url = "http://10.1.77.85:8182/api/attempt?task_id=" + "task_201209241101_0001&pageSize=10";
// ClientResource cr1 = new ClientResource(url);
// cr1.setRequestEntityBuffering(true);
// IAttemptsResource resource1 = cr1.wrap(IAttemptsResource.class);
// cr1.accept(MediaType.APPLICATION_JSON);
// ArrayList<AttemptDTO> attempts = resource1.retrieve();
// for(AttemptDTO dto : attempts){
// System.out.println(dto.getStartTime());
// System.out.println(dto.getStatus());
// }
}
}
| 36.1
| 110
| 0.660388
|
964d340a91af50dd20ef4f254de9a54961e35b01
| 2,760
|
package eu.thog92.isbrh;
import eu.thog92.isbrh.registry.RenderRegistry;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.renderer.*;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.resources.IResourceManager;
import net.minecraft.client.resources.model.IBakedModel;
import net.minecraft.client.settings.GameSettings;
import net.minecraft.util.BlockPos;
import net.minecraft.world.IBlockAccess;
public class ISBRHDispatcher extends BlockRendererDispatcher
{
private final BlockRendererDispatcher oldDispatcher;
public ISBRHDispatcher(BlockRendererDispatcher oldDispatcher, BlockModelShapes modelShapes, GameSettings settings)
{
super(modelShapes, settings);
this.oldDispatcher = oldDispatcher;
}
@Override
public boolean renderBlock(IBlockState state, BlockPos pos, IBlockAccess blockAccess, WorldRenderer worldRendererIn)
{
final boolean result = oldDispatcher.renderBlock(state, pos, blockAccess, worldRendererIn);
if(!result && state.getBlock().getRenderType() > 4)
{
return RenderRegistry.instance().renderBlock(state.getBlock().getRenderType(), state, pos, blockAccess, worldRendererIn);
}
return result;
}
@Override
public void renderBlockBrightness(IBlockState state, float brightness)
{
oldDispatcher.renderBlockBrightness(state, brightness);
if(state.getBlock().getRenderType() > 4)
RenderRegistry.instance().renderBlockBrightness(state.getBlock().getRenderType(), state, brightness);
}
@Override
public void renderBlockDamage(IBlockState state, BlockPos pos, TextureAtlasSprite texture, IBlockAccess blockAccess)
{
oldDispatcher.renderBlockDamage(state, pos, texture, blockAccess);
if(state.getBlock().getRenderType() > 4)
RenderRegistry.instance().renderBlock(state.getBlock().getRenderType(), state, pos, blockAccess, Tessellator.getInstance().getWorldRenderer());
}
@Override
public BlockModelRenderer getBlockModelRenderer()
{
return oldDispatcher.getBlockModelRenderer();
}
@Override
public IBakedModel getModelFromBlockState(IBlockState state, IBlockAccess worldIn, BlockPos pos)
{
return oldDispatcher.getModelFromBlockState(state, worldIn, pos);
}
@Override
public boolean isRenderTypeChest(Block block, int meta)
{
return oldDispatcher.isRenderTypeChest(block, meta);
}
@Override
public void onResourceManagerReload(IResourceManager resourceManager)
{
oldDispatcher.onResourceManagerReload(resourceManager);
}
}
| 35.384615
| 155
| 0.734058
|
610b8e8bccd2f916ace08540128ec25cea32ce4d
| 793
|
package com.jgrouse.util.jdbc;
import com.jgrouse.util.ExceptionAwareRunnable;
import com.jgrouse.util.ExceptionAwareSupplier;
import java.sql.SQLException;
public class JdbcRuntimeException extends RuntimeException {
public JdbcRuntimeException(final Throwable cause) {
super(cause);
}
public static void unchecked(final ExceptionAwareRunnable<SQLException> runnable) {
try {
runnable.run();
} catch (final SQLException e) {
throw new JdbcRuntimeException(e);
}
}
public static <T> T asUnchecked(final ExceptionAwareSupplier<T, SQLException> supplier) {
try {
return supplier.get();
} catch (final SQLException e) {
throw new JdbcRuntimeException(e);
}
}
}
| 25.580645
| 93
| 0.663304
|
70cbe721ff15dd080145ca366c0e52f0e2eb11df
| 3,494
|
package net.minecraft.client.game;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.settings.Settings;
import net.minecraft.crash.CrashReport;
import net.minecraft.init.Bootstrap;
import org.lwjgl.Sys;
import org.lwjgl.opengl.GL11;
import org.lwjgl.util.glu.GLU;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import static net.minecraft.logging.Log.MAIN;
public class ErrorGuy {
private final Minecraft mc;
public ErrorGuy(Minecraft mc) {
this.mc = mc;
}
/**
* adds core server Info (GL version , Texture pack, isModded, type), and the worldInfo to the crash report
*/
public CrashReport addGraphicsAndWorldToCrashReport(CrashReport crash) {
crash.getCategory().addCrashSectionCallable("Версия игры", () -> "Implario Client (1.8.8)");
crash.getCategory().addCrashSectionCallable("LWJGL", Sys::getVersion);
crash.getCategory().addCrashSectionCallable("OpenGL", () -> GL11.glGetString(GL11.GL_RENDERER) + " GL version " + GL11.glGetString(GL11.GL_VERSION) + ", " + GL11.glGetString(GL11.GL_VENDOR));
crash.getCategory().addCrashSectionCallable("GL Caps", OpenGlHelper::getLogText);
crash.getCategory().addCrashSectionCallable("Использование VBOs", () -> Settings.USE_VBO.b() ? "Yes" : "No");
crash.getCategory().addCrashSectionCallable("Тип", () -> "Client (map_client.txt)");
crash.getCategory().addCrashSectionCallable("Пакеты ресурсов", () -> {
StringBuilder stringbuilder = new StringBuilder();
for (Object s : Settings.resourcePacks) {
if (stringbuilder.length() > 0) stringbuilder.append(", ");
stringbuilder.append(s);
if (Settings.incompatibleResourcePacks.contains(String.valueOf(s)))
stringbuilder.append(" (несовместимый)");
}
return stringbuilder.toString();
});
crash.getCategory().addCrashSectionCallable("Язык",
() -> mc.mcLanguageManager.getCurrentLanguage().toString());
crash.getCategory().addCrashSectionCallable("Позиция профайлера",
() -> mc.getProfiler().isEnabled() ? mc.getProfiler().getNameOfLastSection() : "N/A (профайлер отключен)");
crash.getCategory().addCrashSectionCallable("CPU", OpenGlHelper::getCPU);
if (mc.theWorld != null) {
mc.theWorld.addWorldInfoToCrashReport(crash);
}
return crash;
}
/**
* Wrapper around displayCrashReportInternal
*/
public void displayCrashReport(CrashReport crashReportIn) {
File file1 = new File(Minecraft.getMinecraft().mcDataDir, "gamedata/logs/crash-reports");
File file2 = new File(file1, "crash-" + new SimpleDateFormat("yyyy-MM-dd_HH.mm.ss").format(new Date()) + "-client.txt");
Bootstrap.print(crashReportIn.getCompleteReport());
if (crashReportIn.getFile() != null) {
Bootstrap.print("#@!@# Game crashed! Crash report saved to: #@!@# " + crashReportIn.getFile());
System.exit(-1);
}
if (crashReportIn.saveToFile(file2)) {
Bootstrap.print("#@!@# Game crashed! Crash report saved to: #@!@# " + file2.getAbsolutePath());
System.exit(-1);
}
Bootstrap.print("#@?@# Game crashed! Crash report could not be saved. #@?@#");
System.exit(-2);
}
/**
* Checks for an OpenGL error. If there is one, prints the error ID and error string.
*/
public void checkGLError(String message) {
int i = GL11.glGetError();
if (i == 0) return;
String s = GLU.gluErrorString(i);
MAIN.error("########## ОШИБКА OpenGL ##########");
MAIN.error("Процесс: " + message);
MAIN.error(i + ": " + s);
}
}
| 35.653061
| 193
| 0.708643
|
43de039aa326412b88c2e191615908927cce6d70
| 981
|
package ch.jalu.configme.demo;
import ch.jalu.configme.SettingsHolder;
import ch.jalu.configme.properties.Property;
import static ch.jalu.configme.properties.PropertyInitializer.newProperty;
/**
* Sample file with property fields. You can have multiple classes with property fields
* to separate the properties thematically as your configuration grows.
*/
public class TitleConfig implements SettingsHolder {
public static final Property<String> TITLE_TEXT =
newProperty("title.text", "Test");
public static final Property<Integer> TITLE_SIZE =
newProperty("title.size", 12);
public static final Property<String> SUBTITLE_TEXT =
newProperty("subtitle.text", "hello world");
public static final Property<Integer> SUBTITLE_SIZE =
newProperty("subtitle.size", 10);
public static final Property<Color> SUBTITLE_COLOR =
newProperty(Color.class, "subtitle.color", Color.ORANGE);
private TitleConfig() {
}
}
| 30.65625
| 87
| 0.735984
|
819f74cbe443786fdc32480c84f4e8cab656b59d
| 2,512
|
package panels;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.SwingWorker;
import entity.ReactionTime;
import interfaces.TestListener;
public class ReactionPanel extends JPanel {
private static final long serialVersionUID = 1L;
private TestListener testListener;
private int numTests = 10;
private int test = 0;
private SwingWorker<Boolean, Void> worker;
List<ReactionTime> reactionTimes = new ArrayList<>();
Long startTime = 0L;
public ReactionPanel() {
JLabel textLabel = new JLabel("Press spacebar when color changes", SwingConstants.CENTER);
setLayout(new BorderLayout());
add(textLabel, BorderLayout.CENTER);
setBackground(Color.red);
addComponentListener(new ComponentAdapter() {
public void componentShown(ComponentEvent e) {
startTest();
}
});
}
public void setNumTests(int num) {
this.numTests = num;
}
public void startTest() {
setBackground(Color.red);
reactionTimes.clear();
worker = new SwingWorker<Boolean, Void>() {
@Override
protected Boolean doInBackground() throws Exception {
Random random = new Random();
test = 0;
while (test < numTests) {
Thread.sleep(random.nextInt(5000) + 3000);
setBackground(Color.green);
startTime = System.currentTimeMillis();
test++;
}
return true;
}
};
worker.execute();
}
public void stop() {
if (worker != null) {
worker.cancel(true);
testListener.testComplete();
}
}
public void setTestListener(TestListener testListener) {
this.testListener = testListener;
}
public boolean hasData() {
return reactionTimes.size() != 0;
}
public void onSpacebar() {
long currentTime = System.currentTimeMillis();
if (getBackground() == Color.green) {
long reactionTime = currentTime - startTime;
reactionTimes.add(new ReactionTime(new Date(), reactionTime));
setBackground(Color.red);
if (test == numTests) {
testListener.testComplete();
}
}
}
public long getAverageReactionTime() {
return Math.round(reactionTimes.stream().mapToLong(a -> a.getReactionTime()).average().getAsDouble());
}
public List<ReactionTime> getReactionTimes() {
return reactionTimes;
}
}
| 21.288136
| 104
| 0.716561
|
c8cf7cf080ff86b9da958e1f424d3470f8defeb6
| 1,363
|
package com.vinsol.spree.utils;
/**
* Created by vaibhav on 10/30/15.
*/
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
public class Blender {
public static Bitmap blendDrawable(Bitmap bitmap, int color) {
Bitmap resourceBlendedBitmap = Blender.getBlendedBitmap(bitmap, color);
return resourceBlendedBitmap;
}
public static Bitmap getBlendedBitmap(Bitmap bitmap, int color) {
Bitmap greyScaleBitmap = bitmap;
Bitmap colorBitmap = Bitmap.createBitmap(greyScaleBitmap.getWidth(), greyScaleBitmap.getHeight(), Bitmap.Config.ARGB_8888);
colorBitmap.eraseColor(color);
Bitmap blendedBitmap = Bitmap.createBitmap(greyScaleBitmap.getWidth(), greyScaleBitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(blendedBitmap);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.ADD));
c.drawBitmap(greyScaleBitmap, 0, 0 , null);
c.drawBitmap(colorBitmap, 0, 0, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
c.drawBitmap(greyScaleBitmap, 0, 0 , paint);
paint.setXfermode(null);
return blendedBitmap;
}
}
| 33.243902
| 133
| 0.721203
|
bb1ed280967acdb52baaa8a54e83f98e9941b088
| 3,865
|
package com.vmware.config.section;
import com.vmware.config.CalculatedProperty;
import com.vmware.config.ConfigurableProperty;
import com.vmware.util.StringUtils;
import com.vmware.util.scm.Git;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import java.util.TreeMap;
public class GitRepoConfig {
private final Logger log = LoggerFactory.getLogger(this.getClass());
private final Git git = new Git();
@ConfigurableProperty(commandLine = "-tb,--tracking-branch",
help = "Tracking branch to use as base for reviews and for pushing commits. Combined with defaultGitRemote if no remote specified.",
methodNameForValueCalculation = "determineTrackingBranchPath")
public String trackingBranch;
@ConfigurableProperty(commandLine = "-p,--parent", help = "Parent branch to use for the git diff to upload to review board. Combined with defaultGitRemote if no remote specified.")
public String parentBranch;
@ConfigurableProperty(commandLine = "-b,--branch", help = "Optional value to set if using the local branch name for review board is not desired")
public String targetBranch;
@ConfigurableProperty(help = "Default git remote. Remote used for pushing to master or other remote branches.")
public String defaultGitRemote;
@ConfigurableProperty(help = "Map of remote branches, $USERNAME is substituted for the real username.")
public TreeMap<String, String> remoteBranches;
@ConfigurableProperty(commandLine = "-rb,--remote-branch", help = "Remote branch name to use")
public String remoteBranchToUse;
@ConfigurableProperty(commandLine = "--use-git-tracking-branch", help = "Use git tracking branch as tracking branch for review and sandbox")
public boolean useGitTrackingBranch;
@ConfigurableProperty(commandLine = "--max-commits", help = "Max number of commits to check")
public int maxCommitsToCheck;
@ConfigurableProperty(commandLine = "--since-date", help = "Commits since date")
public Date sinceDate;
public String trackingBranchPath() {
return String.valueOf(determineTrackingBranchPath().getValue());
}
public CalculatedProperty determineTrackingBranchPath() {
if (useGitTrackingBranch) {
String gitTrackingBranch = getGitTrackingBranch();
if (gitTrackingBranch != null) {
return new CalculatedProperty(gitTrackingBranch, "git tracking branch");
}
}
if (trackingBranch.contains("/")) {
return new CalculatedProperty(trackingBranch, "trackingBranch");
}
return new CalculatedProperty(defaultGitRemote + "/" + trackingBranch, "trackingBranch");
}
private String getGitTrackingBranch() {
if (git.workingDirectoryIsInGitRepo()) {
return git.getTrackingBranch();
} else {
return null;
}
}
public String parentBranchPath() {
if (parentBranch.startsWith("/")) { // assuming local branch
return parentBranch.substring(1);
}
// check if it has a slash or is a relative path
if (parentBranch.contains("/") || parentBranch.toLowerCase().contains("head")) {
return parentBranch;
}
return defaultGitRemote + "/" + parentBranch;
}
public String determineBranchName() {
Git git = new Git();
if (!git.workingDirectoryIsInGitRepo()) {
return "";
}
String targetBranchValue = git.currentBranch();
log.debug("Using local git branch {}", targetBranchValue);
if (StringUtils.isNotEmpty(targetBranch)) {
log.info("Setting branch property to {} (read from application config)", targetBranch);
targetBranchValue = targetBranch;
}
return targetBranchValue;
}
}
| 39.438776
| 184
| 0.683571
|
23cdd61ac3bca6bf06970dc2ca52fa74000dda7c
| 3,547
|
package com.vmware.vim25;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for HostSharedGpuCapabilities complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="HostSharedGpuCapabilities">
* <complexContent>
* <extension base="{urn:vim25}DynamicData">
* <sequence>
* <element name="vgpu" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="diskSnapshotSupported" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
* <element name="memorySnapshotSupported" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
* <element name="suspendSupported" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
* <element name="migrateSupported" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "HostSharedGpuCapabilities", propOrder = {
"vgpu",
"diskSnapshotSupported",
"memorySnapshotSupported",
"suspendSupported",
"migrateSupported"
})
public class HostSharedGpuCapabilities
extends DynamicData
{
@XmlElement(required = true)
protected String vgpu;
protected boolean diskSnapshotSupported;
protected boolean memorySnapshotSupported;
protected boolean suspendSupported;
protected boolean migrateSupported;
/**
* Gets the value of the vgpu property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getVgpu() {
return vgpu;
}
/**
* Sets the value of the vgpu property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setVgpu(String value) {
this.vgpu = value;
}
/**
* Gets the value of the diskSnapshotSupported property.
*
*/
public boolean isDiskSnapshotSupported() {
return diskSnapshotSupported;
}
/**
* Sets the value of the diskSnapshotSupported property.
*
*/
public void setDiskSnapshotSupported(boolean value) {
this.diskSnapshotSupported = value;
}
/**
* Gets the value of the memorySnapshotSupported property.
*
*/
public boolean isMemorySnapshotSupported() {
return memorySnapshotSupported;
}
/**
* Sets the value of the memorySnapshotSupported property.
*
*/
public void setMemorySnapshotSupported(boolean value) {
this.memorySnapshotSupported = value;
}
/**
* Gets the value of the suspendSupported property.
*
*/
public boolean isSuspendSupported() {
return suspendSupported;
}
/**
* Sets the value of the suspendSupported property.
*
*/
public void setSuspendSupported(boolean value) {
this.suspendSupported = value;
}
/**
* Gets the value of the migrateSupported property.
*
*/
public boolean isMigrateSupported() {
return migrateSupported;
}
/**
* Sets the value of the migrateSupported property.
*
*/
public void setMigrateSupported(boolean value) {
this.migrateSupported = value;
}
}
| 25.156028
| 104
| 0.634621
|
95a65bf1f5ceb5b7d73cdf2dcfc986f9eb7277a3
| 592
|
package com.github.jstrainer.filter;
public class AlphaFilter implements Filter<Alpha, String> {
private static final String LATIN_RANGE = "a-zA-Z";
private static final String ACCENT_RANGE = "À-ú";
private static final String SPACE = "\\s";
@Override
public String filter(String value, Alpha annotation) {
if (value == null) {
return value;
}
String characters = LATIN_RANGE;
if (annotation.allowAccents()) {
characters += ACCENT_RANGE;
}
if (annotation.allowSpace()) {
characters += SPACE;
}
return value.replaceAll("[^" + characters + "]", "");
}
}
| 19.733333
| 59
| 0.679054
|
7faba25177563548363400019455256e0dcdcb16
| 6,127
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.streaming.tests;
import org.apache.http.HttpHost;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.refresh.RefreshRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import static org.apache.flink.util.Preconditions.checkNotNull;
/** The type Elasticsearch 7 client. */
public class Elasticsearch7Client implements ElasticsearchClient {
private static final Logger LOG = LoggerFactory.getLogger(Elasticsearch7Client.class);
private final RestHighLevelClient restClient;
/**
* Instantiates a new Elasticsearch 7 client.
*
* @param addressExternal The address to access Elasticsearch from the host machine (outside of
* the containerized environment).
*/
public Elasticsearch7Client(String addressExternal) {
checkNotNull(addressExternal);
HttpHost httpHost = HttpHost.create(addressExternal);
RestClientBuilder restClientBuilder = RestClient.builder(httpHost);
this.restClient = new RestHighLevelClient(restClientBuilder);
checkNotNull(restClient);
}
@Override
public void deleteIndex(String indexName) {
DeleteIndexRequest request = new DeleteIndexRequest(indexName);
try {
restClient.indices().delete(request, RequestOptions.DEFAULT);
} catch (IOException e) {
LOG.error("Cannot delete index {}", indexName, e);
}
// This is needed to avoid race conditions between tests that reuse the same index
refreshIndex(indexName);
}
@Override
public void refreshIndex(String indexName) {
RefreshRequest refresh = new RefreshRequest(indexName);
try {
restClient.indices().refresh(refresh, RequestOptions.DEFAULT);
} catch (IOException e) {
LOG.error("Cannot delete index {}", indexName, e);
} catch (ElasticsearchException e) {
if (e.status() == RestStatus.NOT_FOUND) {
LOG.info("Index {} not found", indexName);
}
}
}
@Override
public void createIndexIfDoesNotExist(String indexName, int shards, int replicas) {
GetIndexRequest request = new GetIndexRequest(indexName);
CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName);
createIndexRequest.settings(
Settings.builder()
.put("index.number_of_shards", shards)
.put("index.number_of_replicas", replicas));
try {
boolean exists = restClient.indices().exists(request, RequestOptions.DEFAULT);
if (!exists) {
restClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
} else {
LOG.info("Index already exists {}", indexName);
}
} catch (IOException e) {
LOG.error("Cannot create index {}", indexName, e);
}
}
@Override
public void close() throws Exception {
restClient.close();
}
@Override
public List<KeyValue<Integer, String>> fetchAll(QueryParams params) {
try {
SearchResponse response =
restClient.search(
new SearchRequest(params.indexName())
.source(
new SearchSourceBuilder()
.sort(params.sortField(), SortOrder.ASC)
.from(params.from())
.size(params.pageLength())
.trackTotalHits(params.trackTotalHits())),
RequestOptions.DEFAULT);
SearchHit[] searchHits = response.getHits().getHits();
return Arrays.stream(searchHits)
.map(
searchHit ->
KeyValue.of(
Integer.valueOf(searchHit.getId()),
searchHit.getSourceAsMap().get("value").toString()))
.collect(Collectors.toList());
} catch (IOException e) {
LOG.error("Fetching records failed", e);
return Collections.emptyList();
}
}
}
| 41.398649
| 99
| 0.64077
|
9b9ea4d4c1bd52e7059ca3a3a3731b1bd04ab508
| 5,280
|
/*
* Copyright 2019 Clsaa Group
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.clsaa.tiad.eventbus.bus.impl;
import com.clsaa.tiad.eventbus.bus.EventBus;
import com.clsaa.tiad.eventbus.bus.EventBusOptions;
import com.clsaa.tiad.eventbus.bus.EventOptions;
import com.clsaa.tiad.eventbus.coder.Coder;
import com.clsaa.tiad.eventbus.enums.EventFeatures;
import com.clsaa.tiad.transaction.listener.ListenerCache;
import com.clsaa.tiad.transaction.listener.TiadTransactionListener;
import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
import io.vertx.core.eventbus.Message;
import io.vertx.core.eventbus.impl.MessageImpl;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.TransactionMQProducer;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@Slf4j
public class RocketMQEventBus implements DistributeEventBus {
static ThreadLocal<String> threadLocal = new ThreadLocal<>();
private String namesrvAddr;
private Coder coder;
private Map<String, DefaultMQProducer> cacheDefault = new ConcurrentHashMap<>();
private Map<String, TransactionMQProducer> cacheTransaction = new ConcurrentHashMap<>();
@SneakyThrows
@Override
public EventBus send(String topic, String group, Object event, EventOptions options) {
DefaultMQProducer producer = null;
TransactionMQProducer transactionMQProducer = null;
if (cacheDefault.containsKey(group) || cacheTransaction.containsKey(group)) {
producer = cacheDefault.get(group) == null ? cacheTransaction.get(group) : cacheDefault.get(group);
} else if (!options.getEventFeatures().equals(EventFeatures.TRANSACTIONAL)) {
producer = new DefaultMQProducer(group);
producer.setNamesrvAddr(namesrvAddr);
producer.start();
cacheDefault.put(group, producer);
} else {
transactionMQProducer = new TransactionMQProducer("please_rename_unique_group_name");
}
String str = coder.encode(event);
final org.apache.rocketmq.common.message.Message msg =
new org.apache.rocketmq.common.message.Message(topic, "topic", str.getBytes(RemotingHelper.DEFAULT_CHARSET));
SendResult sendResult = null;
if (options.getEventFeatures().equals(EventFeatures.TRANSACTIONAL)) {
final String tag = threadLocal.get();
if (tag != null && tag.startsWith("transaction_tag")) {
final String key = tag.split("-")[1];
final Class<? extends TiadTransactionListener> aClass = ListenerCache.get(key);
final TiadTransactionListener tiadTransactionListener = aClass.newInstance();
transactionMQProducer.setTransactionListener(tiadTransactionListener);
sendResult = producer.sendMessageInTransaction(msg, null);
}
} else {
sendResult = producer.send(msg);
}
log.info(sendResult.toString());
return this;
}
@Override
public <T> EventBus send(String topic, String group, Object event, EventOptions options, Handler<AsyncResult<Message<T>>> replyHandler) {
throw new UnsupportedOperationException("not support reply");
}
@SneakyThrows
@Override
public <T> EventBus consumer(String topic, String group, Handler<Message<T>> handler) {
DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(group);
consumer.setNamesrvAddr(namesrvAddr);
consumer.subscribe(topic, "*");
consumer.registerMessageListener((MessageListenerConcurrently) (msgs, context) -> {
for (MessageExt msg : msgs) {
final String s = new String(msg.getBody());
final Message message = new MessageImpl(null, null, null, coder.decode(s),
null, false, null, null);
handler.handle(message);
}
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
});
return this;
}
@Override
public EventBus init(EventBusOptions eventBusOptions) {
this.namesrvAddr = eventBusOptions.getNamesrvAddr();
this.coder = eventBusOptions.getCoder();
return this;
}
}
| 44.369748
| 141
| 0.707386
|
1912af5d09c4be8c2c909a8b266cc8d84b94592c
| 327
|
// Add Digits
// Leetcode problem 258
// https://leetcode.com/problems/add-digits/
class Solution {
public int addDigits(int num) {
int sum = 0;
while(num > 0){
sum += num % 10;
num /= 10;
}
if(sum < 10)
return sum;
return addDigits(sum);
}
}
| 20.4375
| 44
| 0.489297
|
5bf89b8437997ef9a0e06b8c1cdd4d36a7c84a41
| 1,294
|
/**
*/
package org.github.mongopadplusplus.util;
import java.util.Map;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.xmi.util.XMLProcessor;
import org.github.mongopadplusplus.MongoPadPPPackage;
/**
* This class contains helper methods to serialize and deserialize XML documents
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class MongoPadPPXMLProcessor extends XMLProcessor {
/**
* Public constructor to instantiate the helper.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MongoPadPPXMLProcessor() {
super((EPackage.Registry.INSTANCE));
MongoPadPPPackage.eINSTANCE.eClass();
}
/**
* Register for "*" and "xml" file extensions the MongoPadPPResourceFactoryImpl factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected Map<String, Resource.Factory> getRegistrations() {
if (registrations == null) {
super.getRegistrations();
registrations.put(XML_EXTENSION, new MongoPadPPResourceFactoryImpl());
registrations.put(STAR_EXTENSION, new MongoPadPPResourceFactoryImpl());
}
return registrations;
}
} //MongoPadPPXMLProcessor
| 25.372549
| 90
| 0.685471
|
c07b24e277ea27bd39ccad68d6699f8e1420a822
| 4,093
|
package org.uma.jmetal.runner.multiobjective;
//NSGAIII
import org.uma.jmetal.algorithm.Algorithm;
import org.uma.jmetal.algorithm.multiobjective.ansga.aNSGABuilder;
import org.uma.jmetal.operator.CrossoverOperator;
import org.uma.jmetal.operator.MutationOperator;
import org.uma.jmetal.operator.SelectionOperator;
import org.uma.jmetal.operator.impl.crossover.SBXCrossover;
import org.uma.jmetal.operator.impl.mutation.PolynomialMutation;
import org.uma.jmetal.operator.impl.selection.BinaryTournamentSelection;
import org.uma.jmetal.util.comparator.RankingAndCrowdingDistanceComparator;
import org.uma.jmetal.problem.Problem;
import org.uma.jmetal.solution.DoubleSolution;
import org.uma.jmetal.util.*;
import org.uma.jmetal.util.fileoutput.SolutionListOutput;
import org.uma.jmetal.util.fileoutput.impl.DefaultFileOutputContext;
import org.uma.jmetal.util.pseudorandom.JMetalRandom;
import java.io.FileNotFoundException;
import java.util.List;
/**
* Class to configure and run the aNSGARunner algorithm
*/
public class aNSGARunner extends AbstractAlgorithmRunner {
/**
* @param args Command line arguments.
* @throws JMetalException
* @throws FileNotFoundException Invoking command:
* java org.uma.jmetal.runner.multiobjective.NSGAIIRunner problemName [referenceFront]
*/
public static double main(String[] args) throws JMetalException, FileNotFoundException {
// declares the type of the problem to solve
Problem<DoubleSolution> problem;
Algorithm<List<DoubleSolution>> algorithm;
CrossoverOperator<DoubleSolution> crossover;
MutationOperator<DoubleSolution> mutation;
SelectionOperator<List<DoubleSolution>, DoubleSolution> selection;
String referenceParetoFront = "";
// JMetalRandom.getInstance().setSeed(1);
// String problemName = "org.uma.jmetal.problem.multiobjective.zdt.ZDT1";
// referenceParetoFront = "/pareto_fronts/ZDT1.pf";
String problemName = args[0];
referenceParetoFront = args[1];
problem = ProblemUtils.loadProblem(problemName);
// operators and algorithm are configured
double crossoverProbability = 0.9;
double crossoverDistributionIndex = 20.0;
crossover = new SBXCrossover(crossoverProbability, crossoverDistributionIndex);
double mutationProbability = 1.0 / problem.getNumberOfVariables();
double mutationDistributionIndex = 20.0;
mutation = new PolynomialMutation(mutationProbability, mutationDistributionIndex);
selection = new BinaryTournamentSelection<DoubleSolution>(
new RankingAndCrowdingDistanceComparator<DoubleSolution>());
// selection = new BinaryTournamentSelection<DoubleSolution>();
// from NSGAIIIRunner
algorithm = new aNSGABuilder<>(problem)
.setCrossoverOperator(crossover)
.setMutationOperator(mutation)
.setSelectionOperator(selection)
.setMaxIterations(300)
.setPopulationSize(100)
.setReferenceParetoFront(referenceParetoFront)
.build();
// print
AlgorithmRunner algorithmRunner = new AlgorithmRunner.Executor(algorithm)
.execute();
List<DoubleSolution> population = algorithm.getResult();
long computingTime = algorithmRunner.getComputingTime();
new SolutionListOutput(population)
.setSeparator("\t")
.setVarFileOutputContext(new DefaultFileOutputContext("VAR.tsv"))
.setFunFileOutputContext(new DefaultFileOutputContext("FUN.tsv"))
.print();
// JMetalLogger.logger.info("Total execution time: " + computingTime + "ms");
// JMetalLogger.logger.info("Objectives values have been written to file FUN.tsv");
// JMetalLogger.logger.info("Variables values have been written to file VAR.tsv");
// printFinalSolutionSet(population);
return getHypervolume(population, referenceParetoFront);
}
}
| 43.084211
| 120
| 0.713169
|
75414c23321415e688dc721d043e188857c90733
| 530
|
/**
* Polygons can have an arbitrary number of points, have points that are
* editable, points that move with the polygon as the polygon is dragged, and
* other critical polygon features.<br><br>
*
* All classes in this package should extend the <code>GenericPolygon</code>
* abstract class and give it an AdjustablePolygon, specifying its color, anchor
* color, and more.
*
* @version 1.0
* @author Team 0
* @see {@link udel.GardenProject.plotObjects.PlotObject}
*/
package udel.GardenProject.plotObjects.polygons;
| 37.857143
| 80
| 0.743396
|
b0d92fee4053494e90ffedcc5953b506f6c5b0ff
| 9,981
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package view;
import controller.ControllerCliente;
import model.Cliente;
/**
*
* @author paulosouza
*/
public class Teste extends javax.swing.JFrame {
/**
* Creates new form Teste
*/
public Teste() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jTextFieldNome = new javax.swing.JTextField();
jTextFieldEndereco = new javax.swing.JTextField();
jTextFieldNumeroCasa = new javax.swing.JTextField();
jTextFieldTelefone = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jTextFieldObservacao = new javax.swing.JTextField();
jButtonSalvar = new javax.swing.JButton();
jLabel6 = new javax.swing.JLabel();
jTextFieldPerimetro = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTextFieldEndereco.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextFieldEnderecoActionPerformed(evt);
}
});
jLabel1.setText("Nome:");
jLabel2.setText("endereço:");
jLabel3.setText("Número:");
jLabel3.setToolTipText("");
jLabel4.setText("Teleffone:");
jLabel4.setToolTipText("");
jLabel5.setText("Observação:");
jButtonSalvar.setText("Salvar");
jButtonSalvar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonSalvarActionPerformed(evt);
}
});
jLabel6.setText("Parimetro:");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jButtonSalvar))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4)
.addComponent(jLabel2)
.addComponent(jLabel1)
.addComponent(jLabel5)
.addGroup(layout.createSequentialGroup()
.addGap(6, 6, 6)
.addComponent(jLabel3))
.addComponent(jLabel6))
.addGap(20, 20, 20)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextFieldNumeroCasa)
.addComponent(jTextFieldTelefone)
.addComponent(jTextFieldObservacao)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextFieldNome, javax.swing.GroupLayout.DEFAULT_SIZE, 171, Short.MAX_VALUE)
.addComponent(jTextFieldEndereco))
.addGap(1, 1, 1))
.addComponent(jTextFieldPerimetro))))
.addGap(124, 124, 124))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(43, 43, 43)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextFieldNome)
.addComponent(jLabel1))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextFieldEndereco)
.addComponent(jLabel2))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextFieldNumeroCasa)
.addComponent(jLabel3))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextFieldTelefone)
.addComponent(jLabel4))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(jTextFieldObservacao))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(jTextFieldPerimetro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jButtonSalvar)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jTextFieldEnderecoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldEnderecoActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextFieldEnderecoActionPerformed
private void jButtonSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSalvarActionPerformed
// TODO add your handling code here:
Cliente cliente = new Cliente();
cliente.setNome(jTextFieldNome.getText());
cliente.setEndereco(jTextFieldEndereco.getText());
cliente.setNumerocasa(Integer.parseInt(jTextFieldNumeroCasa.getText()));
cliente.setTelefone(Integer.parseInt(jTextFieldTelefone.getText()));
cliente.setObservacao(jTextFieldObservacao.getText());
cliente.setPerimetro(jTextFieldPerimetro.getText());
ControllerCliente controllerCliente = new ControllerCliente();
controllerCliente.criarNovoCliente(cliente);
}//GEN-LAST:event_jButtonSalvarActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Teste.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Teste.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Teste.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Teste.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Teste().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButtonSalvar;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JTextField jTextFieldEndereco;
private javax.swing.JTextField jTextFieldNome;
private javax.swing.JTextField jTextFieldNumeroCasa;
private javax.swing.JTextField jTextFieldObservacao;
private javax.swing.JTextField jTextFieldPerimetro;
private javax.swing.JTextField jTextFieldTelefone;
// End of variables declaration//GEN-END:variables
}
| 46.859155
| 173
| 0.630398
|
8698f5f97670236c332c50e11e24ea8014a781cf
| 13,371
|
package com.catyee.generator.plugin.generator;
import com.catyee.generator.config.JoinEntry;
import com.catyee.generator.config.JoinTarget;
import org.apache.commons.lang3.tuple.Pair;
import org.mybatis.generator.api.*;
import org.mybatis.generator.api.dom.xml.Attribute;
import org.mybatis.generator.api.dom.xml.Document;
import org.mybatis.generator.api.dom.xml.XmlElement;
import org.mybatis.generator.codegen.XmlConstants;
import org.mybatis.generator.codegen.mybatis3.MyBatis3FormattingUtilities;
import org.mybatis.generator.config.Context;
import org.mybatis.generator.config.TableConfiguration;
import org.mybatis.generator.internal.DefaultShellCallback;
import org.mybatis.generator.internal.XmlFileMergerJaxp;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import static org.mybatis.generator.internal.util.StringUtility.stringHasValue;
import static org.mybatis.generator.internal.util.messages.Messages.getString;
public class JoinResultXmlMapperGenerator {
private final ShellCallback shellCallback;
private final Context context;
private final IntrospectedTable introspectedTable;
private final JoinEntry joinEntry;
public JoinResultXmlMapperGenerator(Context context, IntrospectedTable introspectedTable, JoinEntry joinEntry) {
this.shellCallback = new DefaultShellCallback(true);
this.context = context;
this.introspectedTable = introspectedTable;
this.joinEntry = joinEntry;
}
public void generate() {
GeneratedXmlFile xmlFile = getGeneratedXmlFile();
writeGeneratedXmlFile(xmlFile);
}
private void addElements(XmlElement parentElement) {
XmlElement answer = new XmlElement("resultMap");
String joinResultMapId = JoinEntry.getJoinResultMapId(introspectedTable.getFullyQualifiedTable().getDomainObjectName());
answer.addAttribute(new Attribute("id", joinResultMapId));
String returnType = introspectedTable.getBaseRecordType();
answer.addAttribute(new Attribute("type", returnType));
addResultMapElements(answer);
parentElement.addElement(answer);
}
private void addResultMapElements(XmlElement answer) {
// add primaryKey
for (IntrospectedColumn introspectedColumn : introspectedTable.getPrimaryKeyColumns()) {
XmlElement resultElement = new XmlElement("id");
resultElement.addAttribute(generateColumnAttribute(introspectedColumn));
resultElement.addAttribute(new Attribute("property", introspectedColumn.getJavaProperty()));
resultElement.addAttribute(new Attribute("jdbcType", introspectedColumn.getJdbcTypeName()));
if (stringHasValue(introspectedColumn.getTypeHandler())) {
resultElement.addAttribute(new Attribute("typeHandler", introspectedColumn.getTypeHandler()));
}
answer.addElement(resultElement);
}
// add columns
for (IntrospectedColumn introspectedColumn : introspectedTable.getNonPrimaryKeyColumns()) {
XmlElement resultElement = new XmlElement("result");
resultElement.addAttribute(generateColumnAttribute(introspectedColumn));
resultElement.addAttribute(new Attribute("property", introspectedColumn.getJavaProperty()));
resultElement.addAttribute(new Attribute("jdbcType", introspectedColumn.getJdbcTypeName()));
if (stringHasValue(introspectedColumn.getTypeHandler())) {
resultElement.addAttribute(new Attribute("typeHandler", introspectedColumn.getTypeHandler()));
}
answer.addElement(resultElement);
}
List<Pair<String, JoinTarget>> sortResult = sort(joinEntry.getDetails());
// add join columns
for (Pair<String, JoinTarget> detail : sortResult) {
JoinTarget target = detail.getRight();
XmlElement joinElement = new XmlElement(target.getType() == JoinTarget.JoinType.MORE ? "collection" : "association");
joinElement.addAttribute(new Attribute("property", target.getFiledName()));
IntrospectedTable targetTable = GeneratorUtils.getIntrospectedTable(context, target.getRightTable());
String type = targetTable.getBaseRecordType();
joinElement.addAttribute(new Attribute(target.getType() == JoinTarget.JoinType.MORE ? "ofType" : "javaType", type));
addJoinElements(targetTable, joinElement);
answer.addElement(joinElement);
}
}
private void addJoinElements(IntrospectedTable targetTable, XmlElement joinElement) {
for (IntrospectedColumn targetColumn : targetTable.getPrimaryKeyColumns()) {
XmlElement resultElement = new XmlElement("id");
String targetRenamedColumnName = MyBatis3FormattingUtilities.getRenamedColumnNameForResultMap(targetColumn);
Attribute columnAttribute = new Attribute("column",
GeneratorUtils.generateAliasedColumn(targetTable.getFullyQualifiedTable().getIntrospectedTableName(),
targetRenamedColumnName));
resultElement.addAttribute(columnAttribute);
resultElement.addAttribute(new Attribute("property", targetColumn.getJavaProperty()));
resultElement.addAttribute(new Attribute("jdbcType", targetColumn.getJdbcTypeName()));
if (stringHasValue(targetColumn.getTypeHandler())) {
resultElement.addAttribute(new Attribute("typeHandler", targetColumn.getTypeHandler()));
}
joinElement.addElement(resultElement);
}
for (IntrospectedColumn targetColumn : targetTable.getNonPrimaryKeyColumns()) {
XmlElement resultElement = new XmlElement("result");
String targetRenamedColumnName = MyBatis3FormattingUtilities.getRenamedColumnNameForResultMap(targetColumn);
Attribute columnAttribute = new Attribute("column",
GeneratorUtils.generateAliasedColumn(targetTable.getFullyQualifiedTable().getIntrospectedTableName(),
targetRenamedColumnName));
resultElement.addAttribute(columnAttribute);
resultElement.addAttribute(new Attribute("property", targetColumn.getJavaProperty()));
resultElement.addAttribute(new Attribute("jdbcType", targetColumn.getJdbcTypeName()));
if (stringHasValue(targetColumn.getTypeHandler())) {
resultElement.addAttribute(new Attribute("typeHandler", targetColumn.getTypeHandler()));
}
joinElement.addElement(resultElement);
}
}
private List<String> calAllRenamedColumnNames(IntrospectedTable introspectedTable) {
return introspectedTable.getAllColumns().stream()
.map(MyBatis3FormattingUtilities::getRenamedColumnNameForResultMap)
.collect(Collectors.toList());
}
private GeneratedXmlFile getGeneratedXmlFile() {
Document document = getDocument();
return new GeneratedXmlFile(document, calculateMyBatis3XmlMapperFileName(), calculateSqlMapPackage(),
joinEntry.getTargetProject(), false, context.getXmlFormatter());
}
private Document getDocument() {
Document document = new Document(XmlConstants.MYBATIS3_MAPPER_PUBLIC_ID, XmlConstants.MYBATIS3_MAPPER_SYSTEM_ID);
document.setRootElement(getSqlMapElement());
if (!context.getPlugins().sqlMapDocumentGenerated(document,
introspectedTable)) {
document = null;
}
return document;
}
private XmlElement getSqlMapElement() {
XmlElement answer = new XmlElement("mapper");
String namespace = introspectedTable.getMyBatis3SqlMapNamespace();
answer.addAttribute(new Attribute("namespace",
namespace));
context.getCommentGenerator().addRootComment(answer);
addElements(answer);
return answer;
}
private String calculateMyBatis3XmlMapperFileName() {
TableConfiguration tableConfiguration = introspectedTable.getTableConfiguration();
FullyQualifiedTable fullyQualifiedTable = introspectedTable.getFullyQualifiedTable();
StringBuilder sb = new StringBuilder();
if (stringHasValue(tableConfiguration.getMapperName())) {
String mapperName = tableConfiguration.getMapperName();
int ind = mapperName.lastIndexOf('.');
if (ind == -1) {
sb.append(mapperName);
} else {
sb.append(mapperName.substring(ind + 1));
}
sb.append(".xml");
} else {
sb.append(fullyQualifiedTable.getDomainObjectName());
sb.append("Mapper.xml");
}
return sb.toString();
}
private String calculateSqlMapPackage() {
StringBuilder sb = new StringBuilder();
TableConfiguration tableConfiguration = introspectedTable.getTableConfiguration();
FullyQualifiedTable fullyQualifiedTable = introspectedTable.getFullyQualifiedTable();
sb.append(joinEntry.getTargetPackage());
sb.append(fullyQualifiedTable.getSubPackageForClientOrSqlMap(false));
if (stringHasValue(tableConfiguration.getMapperName())) {
String mapperName = tableConfiguration.getMapperName();
int ind = mapperName.lastIndexOf('.');
if (ind != -1) {
sb.append('.').append(mapperName.substring(0, ind));
}
} else if (stringHasValue(fullyQualifiedTable.getDomainObjectSubPackage())) {
sb.append('.').append(fullyQualifiedTable.getDomainObjectSubPackage());
}
return sb.toString();
}
private Attribute generateColumnAttribute(IntrospectedColumn introspectedColumn) {
return new Attribute("column", MyBatis3FormattingUtilities.getRenamedColumnNameForResultMap(introspectedColumn));
}
private void writeGeneratedXmlFile(GeneratedXmlFile gxf) {
File targetFile;
String source;
try {
File directory = shellCallback.getDirectory(gxf.getTargetProject(), gxf.getTargetPackage());
targetFile = new File(directory, gxf.getFileName());
if (targetFile.exists()) {
if (gxf.isMergeable()) {
source = XmlFileMergerJaxp.getMergedSource(gxf, targetFile);
} else if (shellCallback.isOverwriteEnabled()) {
source = gxf.getFormattedContent();
} else {
source = gxf.getFormattedContent();
targetFile = getUniqueFileName(directory, gxf.getFileName());
}
} else {
source = gxf.getFormattedContent();
}
writeFile(targetFile, source, "UTF-8");
} catch (Exception e) {
throw new RuntimeException("write file failed.", e);
}
}
/**
* Gets the unique file name.
*
* @param directory the directory
* @param fileName the file name
* @return the unique file name
*/
private File getUniqueFileName(File directory, String fileName) {
File answer = null;
// try up to 1000 times to generate a unique file name
StringBuilder sb = new StringBuilder();
for (int i = 1; i < 1000; i++) {
sb.setLength(0);
sb.append(fileName);
sb.append('.');
sb.append(i);
File testFile = new File(directory, sb.toString());
if (!testFile.exists()) {
answer = testFile;
break;
}
}
if (answer == null) {
throw new RuntimeException(getString("RuntimeError.3", directory.getAbsolutePath()));
}
return answer;
}
/**
* Writes, or overwrites, the contents of the specified file.
*
* @param file the file
* @param content the content
* @param fileEncoding the file encoding
* @throws IOException Signals that an I/O exception has occurred.
*/
private void writeFile(File file, String content, String fileEncoding) throws IOException {
FileOutputStream fos = new FileOutputStream(file, false);
OutputStreamWriter osw;
if (fileEncoding == null) {
osw = new OutputStreamWriter(fos);
} else {
osw = new OutputStreamWriter(fos, fileEncoding);
}
try (BufferedWriter bw = new BufferedWriter(osw)) {
bw.write(content);
}
}
private List<Pair<String, JoinTarget>> sort(List<Pair<String, JoinTarget>> joinDetails) {
List<Pair<String, JoinTarget>> oneTypeJoinDetails = new ArrayList<>();
List<Pair<String, JoinTarget>> moreTypeJoinDetails = new ArrayList<>();
for (Pair<String, JoinTarget> detail : joinDetails) {
if (detail.getRight().getType() == JoinTarget.JoinType.MORE) {
moreTypeJoinDetails.add(detail);
}
if (detail.getRight().getType() == JoinTarget.JoinType.ONE) {
oneTypeJoinDetails.add(detail);
}
}
oneTypeJoinDetails.addAll(moreTypeJoinDetails);
return oneTypeJoinDetails;
}
}
| 43.271845
| 129
| 0.666293
|
26dbd8408a127eacf9d47e65621d796104654153
| 6,611
|
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2021 DBeaver Corp and others
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jkiss.dbeaver.tools.transfer.ui.wizard;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.jkiss.dbeaver.tools.transfer.DataTransferPipe;
import org.jkiss.dbeaver.tools.transfer.DataTransferSettings;
import org.jkiss.dbeaver.tools.transfer.IDataTransferNode;
import org.jkiss.dbeaver.tools.transfer.internal.DTMessages;
import org.jkiss.dbeaver.ui.UIUtils;
import org.jkiss.dbeaver.ui.dialogs.ActiveWizardPage;
/**
* This page hosts other settings pages.
* Since 21.2.5 we don't use composite page anymore.
*/
@Deprecated
class DataTransferPageSettings extends ActiveWizardPage<DataTransferWizard> {
private IWizardPage producerSettingsPage;
private IWizardPage consumerSettingsPage;
DataTransferPageSettings() {
super(DTMessages.data_transfer_wizard_settings_name);
setTitle(DTMessages.data_transfer_wizard_settings_title);
setDescription(DTMessages.data_transfer_wizard_settings_description);
}
@Override
public String getTitle() {
DataTransferSettings dtSettings = getWizard().getSettings();
StringBuilder title = new StringBuilder();
String producerName = dtSettings.getProducer() == null ? "null" : dtSettings.getProducer().getName();
String consumerName = dtSettings.getConsumer() == null ? "null" : dtSettings.getConsumer().getName();
title.append(DTMessages.data_transfer_wizard_settings_title).append(" (").append(producerName).append(" to ").append(consumerName);
if (dtSettings.getProcessor() != null) {
title.append(", ").append(dtSettings.getProcessor().getName());
}
title.append(")");
return title.toString();
}
@Override
public void createControl(Composite parent) {
initializeDialogUnits(parent);
Composite composite = UIUtils.createComposite(parent, 1);
setControl(composite);
}
private void createSettingsPages(Composite composite) {
DataTransferSettings dtSettings = getWizard().getSettings();
{
DataTransferPipe dataPipe = dtSettings.getDataPipes().get(0);
StringBuilder title = new StringBuilder();
String producerName = dtSettings.getProducer() == null ? "null" : dtSettings.getProducer().getName();
String consumerName = dtSettings.getConsumer() == null ? "null" : dtSettings.getConsumer().getName();
title.append(DTMessages.data_transfer_wizard_settings_title).append(" (").append(producerName).append(" to ").append(consumerName);
if (dtSettings.getProcessor() != null) {
title.append(", ").append(dtSettings.getProcessor().getName());
}
title.append(")");
setTitle(title.toString());
producerSettingsPage = getSettingsPage(dataPipe.getProducer());
consumerSettingsPage = getSettingsPage(dataPipe.getConsumer());
}
Composite settingsComposite = composite;
if (producerSettingsPage != null && consumerSettingsPage != null) {
SashForm sash = new SashForm(composite, SWT.HORIZONTAL);
sash.setLayoutData(new GridData(GridData.FILL_BOTH));
settingsComposite = sash;
}
if (producerSettingsPage != null) {
producerSettingsPage.setWizard(getWizard());
Composite producerGroup = UIUtils.createPlaceholder(settingsComposite, 1);
UIUtils.createInfoLabel(producerGroup, producerSettingsPage.getTitle());
Composite settingPanel = new Composite(producerGroup, SWT.NONE);
settingPanel.setLayoutData(new GridData(GridData.FILL_BOTH));
settingPanel.setLayout(new FillLayout());
producerSettingsPage.createControl(settingPanel);
if (producerSettingsPage instanceof ActiveWizardPage) {
((ActiveWizardPage) producerSettingsPage).activatePage();
}
}
if (consumerSettingsPage != null) {
consumerSettingsPage.setWizard(getWizard());
Composite consumerGroup = UIUtils.createPlaceholder(settingsComposite, 1);
UIUtils.createInfoLabel(consumerGroup, consumerSettingsPage.getTitle());
Composite settingPanel = new Composite(consumerGroup, SWT.NONE);
settingPanel.setLayoutData(new GridData(GridData.FILL_BOTH));
settingPanel.setLayout(new FillLayout());
consumerSettingsPage.createControl(settingPanel);
if (consumerSettingsPage instanceof ActiveWizardPage) {
((ActiveWizardPage) consumerSettingsPage).activatePage();
}
}
}
private IWizardPage getSettingsPage(IDataTransferNode node) {
DataTransferWizard.NodePageSettings producerInfo = getWizard().getNodeInfo(node);
return producerInfo == null ? null : producerInfo.settingsPage;
}
@Override
public void activatePage()
{
Composite composite = (Composite) getControl();
UIUtils.disposeChildControls(composite);
createSettingsPages(composite);
composite.layout(true, true);
updatePageCompletion();
}
@Override
public void deactivatePage() {
if (producerSettingsPage instanceof ActiveWizardPage) {
((ActiveWizardPage) producerSettingsPage).deactivatePage();
}
if (consumerSettingsPage instanceof ActiveWizardPage) {
((ActiveWizardPage) consumerSettingsPage).deactivatePage();
}
}
@Override
protected boolean determinePageCompletion()
{
return (producerSettingsPage == null || producerSettingsPage.isPageComplete()) &&
(consumerSettingsPage == null || consumerSettingsPage.isPageComplete());
}
}
| 40.808642
| 143
| 0.691423
|
68fba9573d19c623b61f7fee81694dd591c07671
| 5,937
|
/*
* Licensed to Crate under one or more contributor license agreements.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership. Crate 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.
*
* However, if you have executed another commercial license agreement
* with Crate these terms will supersede the license and you may use the
* software solely pursuant to the terms of the relevant commercial
* agreement.
*/
package io.crate.expression.scalar;
import io.crate.data.Input;
import io.crate.execution.engine.aggregation.impl.KahanSummationForDouble;
import io.crate.execution.engine.aggregation.impl.KahanSummationForFloat;
import io.crate.metadata.NodeContext;
import io.crate.metadata.Scalar;
import io.crate.metadata.TransactionContext;
import io.crate.metadata.functions.Signature;
import io.crate.types.ArrayType;
import io.crate.types.DataType;
import io.crate.types.DataTypes;
import java.math.BigDecimal;
import java.util.List;
import java.util.function.Function;
import static io.crate.expression.scalar.array.ArrayArgumentValidators.ensureInnerTypeIsNotUndefined;
public class ArraySumFunction<T extends Number, R extends Number> extends Scalar<R, List<T>> {
public static final String NAME = "array_sum";
private final DataType<R> returnType;
private final Function summationFunction;
private final Function<List<BigDecimal>, BigDecimal> numericFunction = list -> {
BigDecimal sum = BigDecimal.ZERO;
boolean hasNotNull = false;
for (int i = 0; i < list.size(); i++) {
var item = list.get(i);
if (item != null) {
hasNotNull = true;
sum = sum.add(item);
}
}
return hasNotNull ? sum : null;
};
private final Function<List<Float>, Float> floatFunction = list -> {
var kahanSummationForFloat = new KahanSummationForFloat();
float sum = 0;
boolean hasNotNull = false;
for (int i = 0; i < list.size(); i++) {
var item = list.get(i);
if (item != null) {
hasNotNull = true;
sum = kahanSummationForFloat.sum(sum, item);
}
}
return hasNotNull ? sum : null;
};
private final Function<List<Double>, Double> doubleFunction = list -> {
var kahanSummationForDouble = new KahanSummationForDouble();
double sum = 0;
boolean hasNotNull = false;
for (int i = 0; i < list.size(); i++) {
var item = list.get(i);
if (item != null) {
hasNotNull = true;
sum = kahanSummationForDouble.sum(sum, item);
}
}
return hasNotNull ? sum : null;
};
private final Function<List<Number>, Long> longFunction = list -> {
Long sum = 0L;
boolean hasNotNull = false;
for (int i = 0; i < list.size(); i++) {
var item = list.get(i);
if (item != null) {
hasNotNull = true;
sum = Math.addExact(sum, item.longValue());
}
}
return hasNotNull ? sum : null;
};
public static void register(ScalarFunctionModule module) {
module.register(
Signature.scalar(
NAME,
new ArrayType(DataTypes.NUMERIC).getTypeSignature(),
DataTypes.NUMERIC.getTypeSignature()
),
ArraySumFunction::new
);
for (var supportedType : DataTypes.NUMERIC_PRIMITIVE_TYPES) {
DataType inputDependantOutputType = DataTypes.LONG;
if (supportedType == DataTypes.FLOAT || supportedType == DataTypes.DOUBLE) {
inputDependantOutputType = supportedType;
}
module.register(
Signature.scalar(
NAME,
new ArrayType(supportedType).getTypeSignature(),
inputDependantOutputType.getTypeSignature()
),
ArraySumFunction::new
);
}
}
private final Signature signature;
private final Signature boundSignature;
private ArraySumFunction(Signature signature, Signature boundSignature) {
this.signature = signature;
this.boundSignature = boundSignature;
returnType = (DataType<R>) signature.getReturnType().createType();
if (returnType == DataTypes.FLOAT) {
summationFunction = floatFunction;
} else if (returnType == DataTypes.DOUBLE) {
summationFunction = doubleFunction;
} else if (returnType == DataTypes.NUMERIC) {
summationFunction = numericFunction;
} else {
summationFunction = longFunction;
}
ensureInnerTypeIsNotUndefined(boundSignature.getArgumentDataTypes(), signature.getName().name());
}
@Override
public Signature signature() {
return signature;
}
@Override
public Signature boundSignature() {
return boundSignature;
}
@Override
public R evaluate(TransactionContext txnCtx, NodeContext nodeCtx, Input[] args) {
List<T> values = (List) args[0].value();
if (values == null || values.isEmpty()) {
return null;
}
return returnType.implicitCast(summationFunction.apply(values));
}
}
| 34.517442
| 105
| 0.62759
|
400afa587d860763ac5c8f0f2434bb505ca4e8a4
| 5,465
|
package co.edu.uniandes.csw.grupos.ejb;
import co.edu.uniandes.csw.grupos.entities.GrupoDeInteresEntity;
import co.edu.uniandes.csw.grupos.entities.EventoEntity;
import co.edu.uniandes.csw.grupos.exceptions.BusinessLogicException;
import co.edu.uniandes.csw.grupos.persistence.GrupoDeInteresPersistence;
import co.edu.uniandes.csw.grupos.persistence.EventoPersistence;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.inject.Inject;
/**
* Clase que implementa la conexion con la persistencia para la entidad de
* Evento(Evento).
*
* @author ISIS2603
*/
@Stateless
public class EventoLogic {
private static final Logger LOGGER = Logger.getLogger(EventoLogic.class.getName());
@Inject
private EventoPersistence persistence;
@Inject
private GrupoDeInteresPersistence grupoPersistence;
/**
* Se encarga de crear un Evento en la base de datos.
*
* @param eventoEntity Objeto de EventoEntity con los datos nuevos
* @param gruposId id del GrupoDeInteres el cual sera padre del nuevo Evento.
* @return Objeto de EventoEntity con los datos nuevos y su ID.
* @throws BusinessLogicException si gruposId no es el mismo que tiene el
* entity.
*
*/
public EventoEntity createEvento(Long gruposId, EventoEntity eventoEntity) throws BusinessLogicException {
LOGGER.log(Level.INFO, "Inicia proceso de crear evento");
GrupoDeInteresEntity grupo = grupoPersistence.find(gruposId);
if (!validateString(eventoEntity.getNombre())) {
throw new BusinessLogicException("El nombre es inválido");
}
if(grupoPersistence.find(gruposId)==null)
{
throw new BusinessLogicException("El grupo no es valido");
}
eventoEntity.setGrupo(grupo);
LOGGER.log(Level.INFO, "Termina proceso de creación del evento");
return persistence.create(eventoEntity);
}
/**
* Obtiene la lista de los registros de Evento que pertenecen a un GrupoDeInteres.
*
* @param gruposId id del GrupoDeInteres el cual es padre de los Eventos.
* @return Colección de objetos de EventoEntity.
*/
public List<EventoEntity> getEventos(Long gruposId) {
LOGGER.log(Level.INFO, "Inicia proceso de consultar los eventos asociados al grupo con id = {0}", gruposId);
GrupoDeInteresEntity grupoEntity = grupoPersistence.find(gruposId);
LOGGER.log(Level.INFO, "Termina proceso de consultar los eventos asociados al grupo con id = {0}", gruposId);
return grupoEntity.getEventos();
}
/**
* Obtiene los datos de una instancia de Evento a partir de su ID. La
* existencia del elemento padre GrupoDeInteres se debe garantizar.
*
* @param gruposId El id del Libro buscado
* @param eventosId Identificador de la Evento a consultar
* @return Instancia de EventoEntity con los datos del Evento consultado.
*
*/
public EventoEntity getEvento(Long gruposId, Long eventosId) {
LOGGER.log(Level.INFO, "Inicia proceso de consultar el evento con id = {0} del grupo con id = " + gruposId, eventosId);
return persistence.find(gruposId, eventosId);
}
/**
* Actualiza la información de una instancia de Evento.
*
* @param eventoEntity Instancia de EventoEntity con los nuevos datos.
* @param gruposId id del GrupoDeInteres el cual sera padre del Evento actualizado.
* @return Instancia de EventoEntity con los datos actualizados.
*
*/
public EventoEntity updateEvento(Long gruposId, EventoEntity eventoEntity) {
LOGGER.log(Level.INFO, "Inicia proceso de actualizar el evento con id = {0} del grupo con id = " + gruposId, eventoEntity.getId());
GrupoDeInteresEntity grupoEntity = grupoPersistence.find(gruposId);
eventoEntity.setGrupo(grupoEntity);
persistence.update(eventoEntity);
LOGGER.log(Level.INFO, "Termina proceso de actualizar el evento con id = {0} del grupo con id = " + gruposId, eventoEntity.getId());
return eventoEntity;
}
/**
* Elimina una instancia de Evento de la base de datos.
*
* @param eventosId Identificador de la instancia a eliminar.
* @param gruposId id del GrupoDeInteres el cual es padre del Evento.
* @throws BusinessLogicException Si la evento no esta asociada al grupo.
*
*/
public void deleteEvento(Long gruposId, Long eventosId) throws BusinessLogicException {
LOGGER.log(Level.INFO, "Inicia proceso de borrar el evento con id = {0} del grupo con id = " + gruposId, eventosId);
EventoEntity old = getEvento(gruposId, eventosId);
if (old == null) {
throw new BusinessLogicException("El evento con id = " + eventosId + " no esta asociado a el grupo con id = " + gruposId);
}
persistence.delete(old.getId());
LOGGER.log(Level.INFO, "Termina proceso de borrar el evento con id = {0} del grupo con id = " + gruposId, eventosId);
}
/**
* Verifica que el string no sea invalido.
*
* @param string a verificar
* @return true si el name es valido.
*/
private boolean validateString(String string) {
return !(string == null || string.isEmpty());
}
}
| 42.695313
| 141
| 0.676304
|
ef7f0937756519a105199a99511b8c42a43c1faf
| 2,768
|
/* Copyright 2004 - 2007 Kasper Nielsen <kasper@codehaus.org> Licensed under
* the Apache 2.0 License, see http://coconut.codehaus.org/license.
*/
package org.coconut.management.service.file;
import java.io.File;
import org.coconut.core.Log;
import org.coconut.filter.Filter;
import org.coconut.management.annotation.ManagedOperation;
import org.coconut.management.service.ServiceMonitorStatus;
import org.coconut.management.service.spi.AbstractServiceMonitor;
import org.coconut.management.service.spi.AbstractServiceMonitorSession;
/**
* @author <a href="mailto:kasper@codehaus.org">Kasper Nielsen</a>
* @version $Id: Cache.java,v 1.2 2005/04/27 15:49:16 kasper Exp $
*/
public abstract class FileServiceMonitor<V> extends AbstractServiceMonitor {
private String filename;
/**
* @return the filename
*/
public synchronized String getFilename() {
return filename;
}
/**
* @param filename
* the filename to set
*/
public synchronized void setFilename(String filename) {
this.filename = filename;
}
static class FileFilterServiceSession extends AbstractServiceMonitorSession<Boolean> {
private final File name;
private final Filter<File> filter;
private final String ok;
private final String error;
/**
* @return the name
*/
@ManagedOperation(defaultValue = "filename", description = "the name of the file to check")
public synchronized String getName() {
return name.getPath();
}
/**
* @param name
*/
public FileFilterServiceSession(final String name, final Filter<File> filter,
String ok, String error) {
if (name == null) {
throw new NullPointerException("name is null");
} else if (filter == null) {
throw new NullPointerException("filter is null");
}
this.name = new File(name);
this.filter = filter;
this.ok = ok;
this.error = error;
}
/**
* @see org.coconut.management2.service.AbstractServiceCheckerSession#doRun()
*/
@Override
protected Boolean doRun() {
log(Log.Level.Info, "Starting check on " + name);
if (filter.accept(name)) {
setStatus(ServiceMonitorStatus.OK);
log(Log.Level.Info, ok);
return true;
} else {
setStatus(ServiceMonitorStatus.ERROR);
log(Log.Level.Info, error);
return false;
}
}
}
}
| 31.454545
| 100
| 0.582731
|
7bb3cffe07e266d5a615a50d6cda3e562d30652c
| 496
|
package com.example.demo.lombok.step1;
import lombok.AllArgsConstructor;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
@AllArgsConstructor
public class User {
@NonNull int id;
@NonNull String name;
String email;
// public User(int id, String name, String email) {
// super();
// this.id = id;
// this.name = name;
// this.email = email;
// }
// public User(int id, String name) {
// super();
// this.id = id;
// this.name = name;
// }
}
| 17.714286
| 51
| 0.679435
|
09a96e1c38e76627f2d9d8164b4e149f04897082
| 407
|
package com.cheng.market.member.dao;
import com.cheng.market.member.entity.MemberCollectSubjectEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 会员收藏的专题活动
*
* @author cheng
* @email 1227257035@qq.com
* @date 2021-02-03 17:48:07
*/
@Mapper
public interface MemberCollectSubjectDao extends BaseMapper<MemberCollectSubjectEntity> {
}
| 22.611111
| 89
| 0.783784
|
e3b9b2e7b3a1e91e332f92e17a95d57160667b1e
| 1,361
|
package io.github.jroy.advent.twentytwenty.daythirteen;
import io.github.jroy.advent.common.Utils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class PartOne {
public static void main(String[] args) throws IOException {
List<String> input = Utils.getDayInput();
System.out.println("Solution: " + getWaitTime(Long.parseLong(input.get(0)), getBusIds(input.get(1))));
}
public static long getWaitTime(long departStartTime, List<Long> busIds) {
long shortestBusId = -1;
long shortestTime = Long.MAX_VALUE;
for (long busId : busIds) {
boolean cont = true;
long multiplier = departStartTime / busId;
while (cont) {
long wait = busId * multiplier;
if (wait >= departStartTime) {
if (wait < shortestTime) {
shortestTime = wait;
shortestBusId = busId;
}
cont = false;
continue;
}
multiplier++;
}
}
return (shortestTime - departStartTime) * shortestBusId;
}
public static List<Long> getBusIds(String line) {
List<Long> list = new ArrayList<>();
for (String id : line.split(",")) {
if (id.equals("x")) {
continue;
}
list.add(Long.parseLong(id));
}
Collections.sort(list);
return list;
}
}
| 26.686275
| 106
| 0.623071
|
56c54b449ef13772d7e6fa141a151d8a5295c37e
| 1,553
|
/*
* Copyright 2019 Arcus Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
*
*/
package com.iris.driver.groovy;
import com.iris.driver.DeviceDriverContext;
import com.iris.driver.service.executor.DriverExecutors;
/**
* @deprecated Use {@link DriverExecutors} instead
*/
public abstract class GroovyContextObject {
private static final ThreadLocal<DeviceDriverContext> ContextRef = new ThreadLocal<DeviceDriverContext>();
public static DeviceDriverContext getContext() throws IllegalStateException {
DeviceDriverContext context = ContextRef.get();
if(context == null) {
return new GroovyTypeCheckingDeviceDriverContext();
}
return context;
}
// TODO restrict access to these calls, currently public for test cases
public static boolean isContextSet() {
return ContextRef.get() != null;
}
public static void setContext(DeviceDriverContext context) {
ContextRef.set(context);
}
public static void clearContext() {
ContextRef.remove();
}
}
| 29.301887
| 109
| 0.726336
|
6577ce4dffba6f061a8db26d2a114378dbcb4356
| 743
|
package at.jku.cg.sar.gui;
import java.awt.BorderLayout;
import java.util.List;
import javax.swing.JFrame;
import at.jku.cg.sar.gui.graphics.LineGraphDataSet;
import at.jku.cg.sar.gui.graphics.LineGraphPanel;
public class LineGraphViewer {
private final JFrame frame;
private final LineGraphPanel panel;
public LineGraphViewer(List<LineGraphDataSet> data) {
this("Line Graph Viewer", data);
}
public LineGraphViewer(String title, List<LineGraphDataSet> data) {
this.frame = new JFrame();
this.frame.setSize(800, 600);
this.frame.setTitle(title);
this.frame.setLayout(new BorderLayout());
this.panel = new LineGraphPanel(data);
this.frame.add(panel, BorderLayout.CENTER);
this.frame.setVisible(true);
}
}
| 21.852941
| 68
| 0.748318
|
93e04019853c84e35673d33cde053cee76adf28c
| 139
|
package ru.vyarus.java.generics.resolver.cases.order;
/**
* @author Vyacheslav Rusakov
* @since 17.12.2018
*/
public class Base<K> {
}
| 15.444444
| 53
| 0.697842
|
3d145a24b97e01f3a8499a9b2bc0c16d031ddcb1
| 663
|
package de.vogella.swt.widgets;
import org.eclipse.swt.SWT;
import org.eclipse.swt.program.Program;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Link;
import org.eclipse.swt.widgets.Shell;
public class LinkExample {
public static void main(String[] args) {
Display display = Display.getDefault();
Shell shell = new Shell(display);
Link link = new Link(shell, SWT.NONE);
link.setText("<A>http://www.vogella.de</A>");
Program.launch(link.getText());
link.pack();
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
}
| 25.5
| 48
| 0.671192
|
1def86bd32331674ff6e74da554de79fb09c78a9
| 2,669
|
package it.univaq.mwt.business.model;
import static javax.persistence.AccessType.PROPERTY;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Access;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
@Entity
@Access(PROPERTY)
public class Album implements Serializable {
private int id;
private String nome;
private float durata;
private int anno;
private Set<Canzone> canzoni = new HashSet<Canzone>();
private Gruppo gruppo;
private static final long serialVersionUID = 1L;
public Album() {
super();
}
public Album(int id, String nome, float durata, int anno,
Set<Canzone> canzoni, Gruppo gruppo) {
super();
this.id = id;
this.nome = nome;
this.durata = durata;
this.anno = anno;
this.canzoni = canzoni;
this.gruppo = gruppo;
}
public Album(String nome, float durata, int anno,
Set<Canzone> canzoni, Gruppo gruppo) {
super();
this.nome = nome;
this.durata = durata;
this.anno = anno;
this.canzoni = canzoni;
this.gruppo = gruppo;
}
public Album(int id, String nome, float durata, int anno) {
super();
this.id = id;
this.nome = nome;
this.durata = durata;
this.anno = anno;
}
public Album(String nome, float durata, int anno) {
super();
this.nome = nome;
this.durata = durata;
this.anno = anno;
}
@Id
//@GeneratedValue(strategy=GenerationType.SEQUENCE)
@GeneratedValue(generator="AlbSeq")
@SequenceGenerator(name="AlbSeq",sequenceName="ALBUM_SEQ",allocationSize=1)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public float getDurata() {
return durata;
}
public void setDurata(float durata) {
this.durata = durata;
}
public int getAnno() {
return anno;
}
public void setAnno(int anno) {
this.anno = anno;
}
@OneToMany(fetch=FetchType.EAGER, cascade={CascadeType.ALL}, mappedBy="album")
public Set<Canzone> getCanzoni() {
return canzoni;
}
public void setCanzoni(Set<Canzone> canzoni) {
this.canzoni = canzoni;
}
public void removeCanzone(Canzone c){
this.canzoni.remove(canzoni);
}
@ManyToOne
public Gruppo getGruppo() {
return gruppo;
}
public void setGruppo(Gruppo gruppo) {
this.gruppo = gruppo;
}
public void addCanzone(Canzone c){
canzoni.add(c);
}
}
| 18.280822
| 79
| 0.703634
|
61c7c3e78a3b8e26764461bfebe8d02b6944234c
| 2,383
|
/*
* The MIT License
* Copyright © 2014-2021 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.monostate;
/**
* The MonoState pattern ensures that all instances of the class will have the same state. This can
* be used a direct replacement of the Singleton pattern.
*
* <p>In the following example, The {@link LoadBalancer} class represents the app's logic. It
* contains a series of Servers, which can handle requests of type {@link Request}. Two instances of
* LoadBalancer are created. When a request is made to a server via the first LoadBalancer the state
* change in the first load balancer affects the second. So if the first LoadBalancer selects the
* Server 1, the second LoadBalancer on a new request will select the Second server. If a third
* LoadBalancer is created and a new request is made to it, then it will select the third server as
* the second load balancer has already selected the second server.
*/
public class App {
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {
var loadBalancer1 = new LoadBalancer();
var loadBalancer2 = new LoadBalancer();
loadBalancer1.serverRequest(new Request("Hello"));
loadBalancer2.serverRequest(new Request("Hello World"));
}
}
| 44.962264
| 100
| 0.739824
|
292d341554e979cb377cf74da2e622e7a19ca692
| 2,058
|
/*
* Copyright 2018-2019 the Justify authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.leadpony.justify.internal.base;
/**
* Utility class operating on ASCII characters.
*
* @author leadpony
*/
public final class AsciiCode {
private AsciiCode() {
}
/**
* Determines if the specified character is an alphabet and an ASCII code.
*
* @param c the character to test.
* @return {@code true} if the specified character is an alphabet.
*/
public static boolean isAlphabetic(int c) {
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
}
/**
* Determines if the specified character is a digit and an ASCII code.
*
* @param c the character to test.
* @return {@code true} if the specified character is a digit.
*/
public static boolean isDigit(int c) {
return c >= '0' && c <= '9';
}
public static boolean isAlphanumeric(int c) {
return isAlphabetic(c) || isDigit(c);
}
public static boolean isHexDigit(int c) {
return isDigit(c)
|| (c >= 'A' && c <= 'F')
|| (c >= 'a' && c <= 'f');
}
private static final int RADIX = 10;
public static int hexDigitToValue(int c) {
if (isDigit(c)) {
return c - '0';
} else if (c >= 'a' && c <= 'f') {
return RADIX + (c - 'a');
} else if (c >= 'A' && c <= 'F') {
return RADIX + (c - 'A');
}
throw new IllegalArgumentException();
}
}
| 28.583333
| 78
| 0.584062
|
5bfa09077cfc3d0d95a97506bd65c6df8fa4c6d9
| 1,844
|
package app.jchester.androidpermission;
import android.Manifest;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import app.jchester.library.Permission;
public class MainActivity extends AppCompatActivity {
private Permission permission;
private TextView permissionStatus;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
permission = new Permission(this,
new String[] {Manifest.permission.CAMERA, Manifest.permission.CALL_PHONE});
permissionStatus = findViewById(R.id.permission_status);
findViewById(R.id.grant_permission).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
grantPermission();
}
});
}
private void grantPermission() {
permission.executeWithPermission(this, new Permission.PermissionCallback() {
@Override
public void onPermissionsGranted(Permission permission) {
permissionStatus.setText("All permissions are granted");
}
@Override
public void onPermissionsDenied(Permission permission) {
permissionStatus.setText("Denied permissions: " + permission.getDeniedPermissions());
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
permission.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
| 33.527273
| 121
| 0.691974
|
13c311763826f80aab19afc89798c56dd1eed9ba
| 848
|
/**
* Copyright 2016 Bryan Kelly
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License.
*
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.github.btkelly.gandalf.utils;
import android.app.Activity;
import androidx.annotation.NonNull;
/**
* Created by bryankelly on 5/17/16.
*/
public interface OnUpdateSelectedListener {
void onUpdateSelected(@NonNull Activity activity);
}
| 29.241379
| 78
| 0.75
|
bb9868700e6ca4ab577ffbdd27e33eda71bf3842
| 4,804
|
package mobi.parchment.widget.adapterview;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
/**
* Created by Emir Hasanbegovic
*/
public class ChildTouchGestureListener extends AdapterAnimator {
private final OnClickListener mOnClickListener;
private OnLongClickListener mOnLongClickListener;
private int mScaledTouchSlop;
private View mInitialTouchView;
private boolean mIsChildConsumingTouch;
private boolean mIsSingleTapUp;
public ChildTouchGestureListener(final ViewGroup viewGroup, final boolean isViewPager, final boolean isVertical, final OnClickListener onClickListener, final OnLongClickListener onLongClickListener, final LayoutManagerBridge layoutManagerBridge, final ViewConfiguration viewConfiguration) {
super(viewGroup, isViewPager, isVertical, layoutManagerBridge, viewConfiguration);
mOnClickListener = onClickListener;
mOnLongClickListener = onLongClickListener;
mScaledTouchSlop = viewConfiguration.getScaledTouchSlop();
}
@Override
public void onLongPress(final MotionEvent motionEvent) {
if (mInitialTouchView != null) {
mInitialTouchView.setPressed(false);
onItemLongClick(mInitialTouchView);
super.onLongPress(motionEvent);
}
mInitialTouchView = null;
super.onLongPress(motionEvent);
}
@Override
public boolean onScroll(final MotionEvent e1, final MotionEvent e2, final float distanceX, final float distanceY) {
final float xTouchSlop = getXTouchSlop(e1, e2);
final float yTouchSlop = getYTouchSlop(e1, e2);
if (xTouchSlop > mScaledTouchSlop || yTouchSlop > mScaledTouchSlop ) {
if (mInitialTouchView != null) {
mInitialTouchView.setPressed(false);
mInitialTouchView = null;
}
return super.onScroll(e1, e2, distanceX, distanceY);
}
return false;
}
@Override
public boolean onSingleTapUp(MotionEvent motionEvent) {
mIsSingleTapUp = true;
if (!mIsChildConsumingTouch && mInitialTouchView != null) {
onItemClick(mInitialTouchView);
return super.onSingleTapUp(motionEvent, mInitialTouchView);
}
mInitialTouchView = null;
return super.onSingleTapUp(motionEvent);
}
@Override
public void onShowPress(final MotionEvent event) {
if (!mIsChildConsumingTouch && mInitialTouchView != null){
mInitialTouchView.setPressed(true);
}
super.onShowPress(event);
}
@Override
public boolean onDown(final MotionEvent event) {
mInitialTouchView = null;
mIsSingleTapUp = false;
final ViewGroup viewGroup = getViewGroup();
final int pointerCount = event.getPointerCount();
for (int p = 0; p < pointerCount; p++) {
final double touchX = event.getX(p);
final double touchY = event.getY(p);
for (int i = viewGroup.getChildCount() - 1; i >= 0; i--) {
final View child = viewGroup.getChildAt(i);
final float childLeft = child.getLeft();
final float childTop = child.getTop();
final float childRight = child.getWidth() + childLeft;
final float childBottom = child.getHeight() + childTop;
final boolean xFits = touchX >= childLeft && touchX <= childRight;
final boolean yFits = touchY >= childTop && touchY <= childBottom;
if (xFits && yFits) {
mInitialTouchView = child;
return super.onDown(event);
}
}
}
return super.onDown(event);
}
private void onItemLongClick(final View view) {
if (mOnLongClickListener== null) {
return;
}
mOnLongClickListener.onLongClick(view);
}
private void onItemClick(final View view) {
if (mOnClickListener == null) {
return;
}
mOnClickListener.onClick(view);
}
public void onCancel() {
stopTouch();
}
@Override
public void onUp() {
stopTouch();
super.onUp();
}
private void stopTouch() {
if (!mIsSingleTapUp && mInitialTouchView != null){
mInitialTouchView.setPressed(false);
}
mIsSingleTapUp = false;
mInitialTouchView = null;
mIsChildConsumingTouch = false;
}
public void setIsChildConsumingTouch(final boolean isChildConsumingTouch) {
mIsChildConsumingTouch = isChildConsumingTouch;
}
}
| 32.90411
| 294
| 0.644463
|
e02385e1081572a549cdf294341799812b29da52
| 893
|
package tech.quantit.northstar.strategy.api.model;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import org.springframework.data.mongodb.core.mapping.Document;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import xyz.redtorch.pb.CoreEnum.PositionDirectionEnum;
@Document
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ModulePositionInfo {
private String moduleName;
@NotNull
private String unifiedSymbol;
@NotNull
private PositionDirectionEnum positionDir;
private String openTradingDay;
private long openTime;
private double multiplier;
@NotNull
@Min(value=1, message="开仓价格应该为正数")
private double openPrice;
@Min(value=0, message="止损价不能为负数")
private double stopLossPrice;
@NotNull
@Min(value=1, message="手数应该为大于零的整数")
private int volume;
}
| 21.261905
| 62
| 0.807391
|
fae49980c8d82da18679ec9dac9702974f4d5855
| 2,323
|
package net.minecraft.client.gui;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.GlStateManager;
public class GuiLockIconButton extends GuiButton {
private boolean locked;
public GuiLockIconButton(int p_i45538_1_, int p_i45538_2_, int p_i45538_3_) {
super(p_i45538_1_, p_i45538_2_, p_i45538_3_, 20, 20, "");
}
public boolean isLocked() {
return this.locked;
}
public void setLocked(boolean lockedIn) {
this.locked = lockedIn;
}
public void func_191745_a(Minecraft p_191745_1_, int p_191745_2_, int p_191745_3_, float p_191745_4_) {
if (this.visible) {
Icon guilockiconbutton$icon;
p_191745_1_.getTextureManager().bindTexture(GuiButton.BUTTON_TEXTURES);
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
boolean flag = (p_191745_2_ >= this.xPosition && p_191745_3_ >= this.yPosition && p_191745_2_ < this.xPosition + this.width && p_191745_3_ < this.yPosition + this.height);
if (this.locked) {
if (!this.enabled) {
guilockiconbutton$icon = Icon.LOCKED_DISABLED;
} else if (flag) {
guilockiconbutton$icon = Icon.LOCKED_HOVER;
} else {
guilockiconbutton$icon = Icon.LOCKED;
}
} else if (!this.enabled) {
guilockiconbutton$icon = Icon.UNLOCKED_DISABLED;
} else if (flag) {
guilockiconbutton$icon = Icon.UNLOCKED_HOVER;
} else {
guilockiconbutton$icon = Icon.UNLOCKED;
}
drawTexturedModalRect(this.xPosition, this.yPosition, guilockiconbutton$icon.getX(), guilockiconbutton$icon.getY(), this.width, this.height);
}
}
enum Icon {
LOCKED(0, 146),
LOCKED_HOVER(0, 166),
LOCKED_DISABLED(0, 186),
UNLOCKED(20, 146),
UNLOCKED_HOVER(20, 166),
UNLOCKED_DISABLED(20, 186);
private final int x;
private final int y;
Icon(int p_i45537_3_, int p_i45537_4_) {
this.x = p_i45537_3_;
this.y = p_i45537_4_;
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\client\gui\GuiLockIconButton.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
| 30.168831
| 177
| 0.653465
|
66a15b283f6653d55baee6bb005ea7e0fcdb8137
| 762
|
package com.fxb.socket.multithreading;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
/**
* @create by: wangxiyue on 2017/7/14 16:56.
* @ClassName:
* @userfor:
* @description:
*/
public class MyClient {
public static void main(String[] args) throws IOException{
Socket s = new Socket("127.0.0.1",52134);
new Thread(new ClientThread(s)).start();
//本次Socket的发送流
PrintStream ps = new PrintStream(s.getOutputStream());
String line = null;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (null != (line=br.readLine())) {
ps.println(line);
}
}
}
| 26.275862
| 81
| 0.654856
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.