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 |
|---|---|---|---|---|---|
7f71865b21e5dca9e2334ea60a09874e4cab855e | 2,005 | /*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.http.server.reactive;
import java.net.URI;
import java.util.Random;
import org.junit.Test;
import reactor.core.publisher.Mono;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import static org.junit.Assert.*;
/**
* @author Arjen Poutsma
*/
public class EchoHandlerIntegrationTests extends AbstractHttpHandlerIntegrationTests {
private static final int REQUEST_SIZE = 4096 * 3;
private final Random rnd = new Random();
@Override
protected EchoHandler createHttpHandler() {
return new EchoHandler();
}
@Test
public void echo() throws Exception {
RestTemplate restTemplate = new RestTemplate();
byte[] body = randomBytes();
RequestEntity<byte[]> request = RequestEntity.post(new URI("http://localhost:" + port)).body(body);
ResponseEntity<byte[]> response = restTemplate.exchange(request, byte[].class);
assertArrayEquals(body, response.getBody());
}
private byte[] randomBytes() {
byte[] buffer = new byte[REQUEST_SIZE];
rnd.nextBytes(buffer);
return buffer;
}
/**
* @author Arjen Poutsma
*/
public static class EchoHandler implements HttpHandler {
@Override
public Mono<Void> handle(ServerHttpRequest request, ServerHttpResponse response) {
return response.writeWith(request.getBody());
}
}
}
| 26.381579 | 101 | 0.746135 |
54a62724de089c9abdf5046fc67ce85c3515323b | 3,138 | /*
* Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.misc;
/**
* The request processor allows functors (Request instances) to be created
* in arbitrary threads, and to be posted for execution in a non-restricted
* thread.
*
* @author Steven B. Byrne
*/
public class RequestProcessor implements Runnable {
private static Queue<Request> requestQueue;
private static Thread dispatcher;
/**
* Queues a Request instance for execution by the request procesor
* thread.
*/
public static void postRequest(Request req) {
lazyInitialize();
requestQueue.enqueue(req);
}
/**
* Process requests as they are queued.
*/
public void run() {
lazyInitialize();
while (true) {
try {
Request req = requestQueue.dequeue();
try {
req.execute();
} catch (Throwable t) {
// do nothing at the moment...maybe report an error
// in the future
}
} catch (InterruptedException e) {
// do nothing at the present time.
}
}
}
/**
* This method initiates the request processor thread. It is safe
* to call it after the thread has been started. It provides a way for
* clients to deliberately control the context in which the request
* processor thread is created
*/
public static synchronized void startProcessing() {
if (dispatcher == null) {
dispatcher = new Thread(new RequestProcessor(), "Request Processor");
dispatcher.setPriority(Thread.NORM_PRIORITY + 2);
dispatcher.start();
}
}
/**
* This method performs lazy initialization.
*/
private static synchronized void lazyInitialize() {
if (requestQueue == null) {
requestQueue = new Queue<Request>();
}
}
}
| 32.350515 | 81 | 0.643085 |
ab524384bd72d9f2b63552fe37d08d27f5cafb14 | 996 | package com.nativapps.arpia.database.dao;
import com.nativapps.arpia.database.EntityDao;
import com.nativapps.arpia.database.entity.Email;
import java.util.List;
/**
*
* @author Gustavo Pacheco <ryctabo@gmail.com>
* @version 1.0
*/
public class EmailDaoController extends EntityDao<Email, Long>
implements EmailDao {
private static final EmailDaoController INSTANCE = new EmailDaoController();
private EmailDaoController() {
super(Email.class);
}
public static EmailDaoController getInstance() {
return INSTANCE;
}
@Override
public List<Email> getAllByPersonId(Long personId) {
return executeNamedQueryForList("email.findAllByPersonId",
new Parameter("personId", personId));
}
@Override
public boolean exists(String address) {
return executeNamedQuery("email.findByAddress",
new Parameter("address", address)) != null;
}
}
| 26.210526 | 81 | 0.655622 |
0617d232108f69b1dba0f655c9d7f173ed4986fa | 2,916 | package net.ccfish.jvue.rest.test;
import java.util.ArrayList;
import java.util.Collection;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import net.ccfish.jvue.JvueApiApplication;
import net.ccfish.jvue.config.WebSecurityConfig;
import net.ccfish.jvue.security.JwtUserDetails;
import net.ccfish.jvue.security.mock.MockCurrentUserArgumentResolver;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = JvueApiApplication.class, webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@ActiveProfiles(profiles = "test")
public class AuthControllerTest {
@Autowired
private WebApplicationContext context;
protected MockMvc mockMvc;
@Before
public void setupMockMvc() throws Exception {
mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
}
// /**
// * 未登录 测试
// *
// * @throws Exception
// */
// @Test
// public void testGetPage() throws Exception {
//
// // 未登录
// setAnon();
//
// RequestBuilder request = MockMvcRequestBuilders.get("/auth/page");
// mockMvc.perform(request).andExpect(MockMvcResultMatchers.status().isUnauthorized())
// .andDo(MockMvcResultHandlers.print());
// }
//
// /**
// * 已登录用户
// *
// * @throws Exception
// */
// @Test
// public void testGetPageAuthed() throws Exception {
//
// // 登录用户
// setAdmin();
//
// RequestBuilder request = MockMvcRequestBuilders.get("/auth/page");
// mockMvc.perform(request).andExpect(MockMvcResultMatchers.status().isOk()).andDo(MockMvcResultHandlers.print());
//
// }
protected void setAnon() {
MockCurrentUserArgumentResolver.jwtUser = null;
}
protected void setAdmin() {
Collection<? extends GrantedAuthority> authorities = new ArrayList<>();
JwtUserDetails jwtUser = new JwtUserDetails(1L, "mock", "mock",
1, "mock user", "",
authorities, new ArrayList<>());
MockCurrentUserArgumentResolver.jwtUser = jwtUser;
}
}
| 32.764045 | 116 | 0.752743 |
eab410ab8a25391a3fb51d468027b0bb395bd2ed | 108 | package com.github.uchan_nos.c_helper.analysis.values;
public abstract class ScalarValue extends Value {
}
| 21.6 | 54 | 0.824074 |
15ea17894d7ca05351729c4626719eddbc280bea | 7,241 | package hch.opencv.resident;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewFrame;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.android.Utils;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewListener2;
import org.opencv.imgproc.Imgproc;
//import android.support.v7.app.AppCompatActivity;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.WindowManager;
import android.view.SurfaceView;
import android.app.Activity;
import java.io.IOException;
import java.io.InputStream;
public class ScannerActivity extends Activity implements CvCameraViewListener2{
private static final String TAG = "ScannerActivity";
private CameraBridgeViewBase mOpenCvCameraView;
private Mat mRgba;
private Mat mSubRgba;
private ResidentDetector mDetector;
private boolean mIsContinue=true;//是否继续扫描
private String mScanResult;//身份证号扫描结果
private int mMargin;//内容框留白大小
private WorkThread mThread;
private static final int SUCCESSED = 1;
private static final int FAILED=0;
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == SUCCESSED) {
Bundle data=msg.getData();
mScanResult=data.getString("ScanResult");
//数据是使用Intent返回
Intent intent = new Intent();
//把返回数据存入Intent
intent.putExtra("ScanResult",mScanResult);
//设置返回数据
setResult(RESULT_OK, intent);
//关闭Activity
finish();
Log.i(TAG, mScanResult);
}else if(msg.what==FAILED){
mIsContinue=true;
}
}
};
//工作线程,用于识别身份证号
private class WorkThread extends Thread {
public Handler mWorkerHandler = null;
public WorkThread(){
super();
}
@Override
public void run() {
Looper.prepare();
mWorkerHandler = new Handler() {
public void handleMessage(Message msg) {
if(msg.what==1){
if(mDetector.recognize(mSubRgba)){
SendMessage(mHandler,SUCCESSED,mDetector.getScanResult());
this.getLooper().quit();
}else{
SendMessage(mHandler,FAILED,mDetector.getScanResult());
}
}
}
};
Looper.myLooper().loop();
}
}
private void SendMessage(Handler handler,int what, String scanResult){
Message msg = new Message();
msg.what = what;
Bundle data=new Bundle();
data.putString("ScanResult",scanResult);
msg.setData(data);
handler.sendMessage(msg);
}
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
@Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS:
{
Log.i(TAG, "OpenCV loaded successfully");
mOpenCvCameraView.enableView();
AssetManager assetManager=getResources().getAssets();
try{
InputStream trainStream=assetManager.open("train-images.idx3-ubyte");
InputStream labelStream=assetManager.open("train-labels.idx1-ubyte");
mDetector=new ResidentDetector(trainStream,labelStream);
}catch(IOException e){
Log.i(TAG,e.getMessage());
}
} break;
default:
{
super.onManagerConnected(status);
} break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "called onCreate");
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_scanner);
mOpenCvCameraView = (CameraBridgeViewBase) findViewById(R.id.opencv_java_surface_view);
mOpenCvCameraView.setVisibility(SurfaceView.VISIBLE);
mOpenCvCameraView.setCvCameraViewListener(this);
mMargin=((ResidentJavaCameraView)mOpenCvCameraView).getMargin();
mThread=new WorkThread();
mThread.start();
}
@Override
public void onPause()
{
super.onPause();
if (mOpenCvCameraView != null)
mOpenCvCameraView.disableView();
}
@Override
public void onResume()
{
super.onResume();
if (!OpenCVLoader.initDebug()) {
Log.d(TAG, "Internal OpenCV library not found. Using OpenCV Manager for initialization");
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_0_0, this, mLoaderCallback);
} else {
Log.d(TAG, "OpenCV library found inside package. Using it!");
mLoaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
}
}
public void onDestroy() {
super.onDestroy();
if (mOpenCvCameraView != null)
mOpenCvCameraView.disableView();
}
public void onCameraViewStarted(int width, int height) {
//mDetector=new ResidentDetector();
/*try{
String file_path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/sample.jpg";
Bitmap myBitmap = BitmapFactory.decodeFile(file_path);
mSubRgba=new Mat(myBitmap.getHeight(),myBitmap.getWidth(), CvType.CV_8UC4);
Imgproc.cvtColor(mSubRgba,mSubRgba,Imgproc.COLOR_BGR2RGB);
Utils.bitmapToMat(myBitmap,mSubRgba);
}catch(Exception e){
Log.e(TAG,e.getMessage());
}*/
}
public void onCameraViewStopped() {
}
public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
mRgba= inputFrame.rgba();
mSubRgba = mRgba.submat(mMargin, mRgba.rows()-2*mMargin, mMargin, mRgba.cols()-2*mMargin);
//ResidentDetector.saveMatToBmp(mSubRgba,"原始输入图像");
if(mIsContinue==true){
Message msg = mHandler.obtainMessage();
msg.what = 1;
mThread.mWorkerHandler.sendMessage(msg);
mIsContinue=false;
}
return mRgba;
}
}
| 35.669951 | 106 | 0.58735 |
dbbf775ebac8738da0aed73604d60d9b1e8bdd96 | 8,285 | package com.example.picupload;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
private Button mTakePhoto;
private ImageView mImageView;
private static final String TAG = "upload";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTakePhoto = (Button) findViewById(R.id.take_photo);
mImageView = (ImageView) findViewById(R.id.imageview);
mTakePhoto.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
int id = v.getId();
switch (id) {
case R.id.take_photo:
takePhoto();
break;
}
}
private void takePhoto() {
// Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
// intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
// startActivityForResult(intent, 0);
dispatchTakePictureIntent();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
Log.i(TAG, "onActivityResult: " + this);
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == Activity.RESULT_OK) {
setPic();
// Bitmap bitmap = (Bitmap) data.getExtras().get("data");
// if (bitmap != null) {
// mImageView.setImageBitmap(bitmap);
// try {
// sendPhoto(bitmap);
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
}
}
private void sendPhoto(Bitmap bitmap) throws Exception {
new UploadTask().execute(bitmap);
}
private class UploadTask extends AsyncTask<Bitmap, Void, Void> {
protected Void doInBackground(Bitmap... bitmaps) {
if (bitmaps[0] == null)
return null;
setProgress(0);
Bitmap bitmap = bitmaps[0];
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); // convert Bitmap to ByteArrayOutputStream
InputStream in = new ByteArrayInputStream(stream.toByteArray()); // convert ByteArrayOutputStream to ByteArrayInputStream
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httppost = new HttpPost(
"http://192.168.8.84:8003/savetofile.php"); // server
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("myFile",
System.currentTimeMillis() + ".jpg", in);
httppost.setEntity(reqEntity);
Log.i(TAG, "request " + httppost.getRequestLine());
HttpResponse response = null;
try {
response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if (response != null)
Log.i(TAG, "response " + response.getStatusLine().toString());
} finally {
}
} finally {
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
@Override
protected void onProgressUpdate(Void... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Toast.makeText(MainActivity.this, R.string.uploaded, Toast.LENGTH_LONG).show();
}
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Log.i(TAG, "onResume: " + this);
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
Log.i(TAG, "onSaveInstanceState");
}
String mCurrentPhotoPath;
static final int REQUEST_TAKE_PHOTO = 1;
File photoFile = null;
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
/**
* http://developer.android.com/training/camera/photobasics.html
*/
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
String storageDir = Environment.getExternalStorageDirectory() + "/picupload";
File dir = new File(storageDir);
if (!dir.exists())
dir.mkdir();
File image = new File(storageDir + "/" + imageFileName + ".jpg");
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
Log.i(TAG, "photo path = " + mCurrentPhotoPath);
return image;
}
private void setPic() {
// Get the dimensions of the View
int targetW = mImageView.getWidth();
int targetH = mImageView.getHeight();
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW/targetW, photoH/targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor << 1;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
Matrix mtx = new Matrix();
mtx.postRotate(90);
// Rotating Bitmap
Bitmap rotatedBMP = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), mtx, true);
if (rotatedBMP != bitmap)
bitmap.recycle();
mImageView.setImageBitmap(rotatedBMP);
try {
sendPhoto(rotatedBMP);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| 28.66782 | 124 | 0.694991 |
bc4cba09d7e5577096a7956064238fc860d891b6 | 11,395 | /*
* 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.servicecomb.toolkit.codegen;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.apache.commons.lang3.StringUtils;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.SupportingFile;
import io.swagger.codegen.languages.AbstractJavaCodegen;
import io.swagger.codegen.languages.SpringCodegen;
import io.swagger.codegen.mustache.CamelCaseLambda;
public class ServiceCombCodegen extends AbstractJavaCodegen implements CodegenConfig {
private static final String DEFAULT_LIBRARY = "SpringMVC";
private static final String POJO_LIBRARY = "POJO";
private static final String JAX_RS_LIBRARY = "JAX-RS";
private static final String SPRING_BOOT_LIBRARY = "SpringBoot";
private String mainClassPackage;
private String providerProject = "provider";
private String consumerProject = "consumer";
private String modelProject = "model";
private String applicationId = "defaultApp";
private String microserviceName = "defaultService";
private String consumerTemplateFolder = "consumer";
private String providerTemplateFolder = "provider";
private String modelTemplateFolder = "model";
private String apiConsumerTemplate = consumerTemplateFolder + "/apiConsumer.mustache";
private String apiConsumerTemplateForPojo = consumerTemplateFolder + "/pojo/apiConsumer.mustache";
private String modelConsumerTemplate = consumerTemplateFolder + "/model.mustache";
private String pojoApiImplTemplate = "apiImpl.mustache";
@Override
public CodegenType getTag() {
return CodegenType.SERVER;
}
@Override
public String getName() {
return "ServiceComb";
}
@Override
public String getHelp() {
return "Generates a ServiceComb server library.";
}
public ServiceCombCodegen() {
super();
outputFolder = "generated-code/ServiceComb";
modelDocTemplateFiles.remove("model_doc.mustache");
apiDocTemplateFiles.remove("api_doc.mustache");
apiTestTemplateFiles.remove("api_test.mustache");
embeddedTemplateDir = templateDir = "ServiceComb";
modelTemplateFiles.put(modelTemplateFolder + "/model.mustache", ".java");
modelTemplateFiles.remove("model.mustache");
groupId = "domain.orgnization.project";
artifactId = "sample";
apiPackage = groupId + "." + artifactId + ".api";
modelPackage = groupId + "." + artifactId + ".model";
mainClassPackage = groupId + "." + artifactId;
supportedLibraries.put(DEFAULT_LIBRARY, "ServiceComb Server application using the SpringMVC programming model.");
supportedLibraries.put(POJO_LIBRARY, "ServiceComb Server application using the POJO programming model.");
supportedLibraries.put(JAX_RS_LIBRARY, "ServiceComb Server application using the JAX-RS programming model.");
supportedLibraries.put(SPRING_BOOT_LIBRARY, "ServiceComb Server application using the SpringBoot programming model.");
setLibrary(DEFAULT_LIBRARY);
CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use");
library.setDefault(DEFAULT_LIBRARY);
library.setEnum(supportedLibraries);
library.setDefault(DEFAULT_LIBRARY);
cliOptions.add(library);
}
@Override
public String modelFileFolder() {
return outputFolder + "/" + modelProject + "/" + sourceFolder + "/" + modelPackage().replace('.', '/');
}
@Override
public String apiFileFolder() {
return outputFolder + "/" + providerProject + "/" + sourceFolder + "/" + apiPackage().replace('.', '/');
}
@Override
public String apiFilename(String templateName, String tag) {
if (apiConsumerTemplate.equals(templateName) || apiConsumerTemplateForPojo.equals(templateName)) {
String suffix = apiTemplateFiles().get(templateName);
return apiConsumerFolder() + File.separator + toApiFilename(tag) + suffix;
}
if (POJO_LIBRARY.equals(getLibrary())) {
if ("apiImpl.mustache".equals(templateName)) {
String suffix = apiTemplateFiles().get(templateName);
return apiFileFolder() + File.separator + additionalProperties.get("classnameImpl") + suffix;
}
if ("api.mustache".equals(templateName)) {
String suffix = apiTemplateFiles().get(templateName);
return pojoApiInterfaceFolder() + File.separator + camelize(tag) + "Api" + suffix;
}
}
return super.apiFilename(templateName, tag);
}
private String pojoApiInterfaceFolder() {
return outputFolder + "/" + modelProject + "/" + sourceFolder + "/" + apiPackage().replace('.', '/');
}
private String apiConsumerFolder() {
return outputFolder + "/" + consumerProject + "/" + sourceFolder + "/" + apiPackage().replace('.', '/');
}
@Override
public Map<String, Object> postProcessOperationsWithModels(Map<String, Object> objs, List<Object> allModels) {
Map operations = (Map) objs.get("operations");
String classnameImpl = (String) operations.get("classname") + "Impl";
operations.put("classnameImpl", classnameImpl);
additionalProperties.put("classnameImpl", classnameImpl);
return super.postProcessOperationsWithModels(objs, allModels);
}
@Override
public void processOpts() {
super.processOpts();
importMapping.put("OffsetDateTime", "java.time.OffsetDateTime");
additionalProperties.put("dateLibrary", "java8");
if (StringUtils.isEmpty((String) additionalProperties.get("mainClassPackage"))) {
additionalProperties.put("mainClassPackage", mainClassPackage);
} else {
mainClassPackage = (String) additionalProperties.get("mainClassPackage");
}
additionalProperties.put("camelcase", new CamelCaseLambda());
additionalProperties.put("getGenericClassType", new GetGenericClassTypeLambda());
additionalProperties.put("removeImplSuffix", new RemoveImplSuffixLambda());
additionalProperties.put("applicationId", applicationId);
additionalProperties.put("microserviceName", microserviceName);
boolean isMultipleModule = (boolean) Optional.ofNullable(additionalProperties.get("isMultipleModule")).orElse(true);
if (isMultipleModule) {
processParentProjectOpts();
}
switch ((String) Optional.ofNullable(additionalProperties.get(ProjectMetaConstant.SERVICE_TYPE)).orElse("")) {
case "provider":
processProviderProjectOpts();
processPojoProvider();
break;
case "consumer":
processConsumerProjectOpts();
processPojoConsumer();
apiTemplateFiles().remove("api.mustache");
break;
case "all":
default:
processProviderProjectOpts();
processPojoProvider();
processConsumerProjectOpts();
processPojoConsumer();
}
processModelProjectOpts();
}
private void processPojoProvider() {
if (!POJO_LIBRARY.equals(getLibrary())) {
return;
}
apiTemplateFiles.put(pojoApiImplTemplate, ".java");
additionalProperties.put("isPOJO", true);
}
private void processPojoConsumer() {
if (!POJO_LIBRARY.equals(getLibrary())) {
return;
}
apiTemplateFiles.remove(apiConsumerTemplate);
apiTemplateFiles.put(apiConsumerTemplateForPojo, "Consumer.java");
additionalProperties.put("isPOJO", true);
}
@Override
public void postProcessModelProperty(CodegenModel model, CodegenProperty property) {
super.postProcessModelProperty(model, property);
model.imports.remove("ApiModelProperty");
model.imports.remove("ApiModel");
}
private void processModelProjectOpts() {
supportingFiles.add(new SupportingFile("model/pom.mustache",
modelProject,
"pom.xml")
);
}
private void processParentProjectOpts() {
supportingFiles.add(new SupportingFile("project/pom.mustache",
"",
"pom.xml")
);
}
private void processProviderProjectOpts() {
supportingFiles.add(new SupportingFile("pom.mustache",
providerProject,
"pom.xml")
);
supportingFiles.add(new SupportingFile("Application.mustache",
mainClassFolder(providerProject),
"Application.java")
);
supportingFiles.add(new SupportingFile("log4j2.mustache",
resourcesFolder(providerProject),
"log4j2.xml")
);
supportingFiles.add(new SupportingFile(providerTemplateFolder + "/microservice.mustache",
resourcesFolder(providerProject),
"microservice.yaml")
);
}
private void processConsumerProjectOpts() {
String newConsumerTemplateFolder = consumerTemplateFolder;
if (SPRING_BOOT_LIBRARY.equals(getLibrary())) {
newConsumerTemplateFolder += "/springboot";
}
supportingFiles.add(new SupportingFile(newConsumerTemplateFolder + "/pom.mustache",
consumerProject,
"pom.xml")
);
supportingFiles.add(new SupportingFile(newConsumerTemplateFolder + "/Application.mustache",
mainClassFolder(consumerProject),
"Application.java")
);
supportingFiles.add(new SupportingFile("log4j2.mustache",
resourcesFolder(consumerProject),
"log4j2.xml")
);
supportingFiles.add(new SupportingFile(consumerTemplateFolder + "/microservice.mustache",
resourcesFolder(consumerProject),
"microservice.yaml")
);
apiTemplateFiles.put(apiConsumerTemplate, "Consumer.java");
}
@Override
public Map<String, Object> postProcessModelsEnum(Map<String, Object> objs) {
objs = super.postProcessModelsEnum(objs);
SpringCodegen springCodegen = new SpringCodegen();
return springCodegen.postProcessModelsEnum(objs);
}
@Override
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
SpringCodegen springCodegen = new SpringCodegen();
return springCodegen.postProcessOperations(objs);
}
@Override
public String toApiName(String name) {
if (name.length() == 0) {
return "DefaultApi";
}
String apiName = (String) additionalProperties.get("apiName");
if (apiName != null) {
return apiName;
}
return initialCaps(name) + "Api";
}
private String mainClassFolder(String projectPath) {
return projectPath + File.separator + sourceFolder + File.separator + mainClassPackage.replace(".", File.separator);
}
private String resourcesFolder(String projectPath) {
return projectPath + File.separator + projectFolder + File.separator + "resources";
}
} | 33.613569 | 122 | 0.719351 |
012fb57ddce673b5e37a9689bbf2a32c7f2cec07 | 9,960 | /*
* Copyright (c) 2005-2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.event.core.sharedmemory;
import org.apache.axis2.clustering.ClusteringFault;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.event.core.sharedmemory.util.SharedMemoryCacheConstants;
import org.wso2.carbon.event.core.sharedmemory.util.SharedMemoryCacheUtil;
import org.wso2.carbon.event.core.subscription.Subscription;
import org.wso2.carbon.event.core.exception.EventBrokerException;
import javax.cache.Cache;
import javax.cache.CacheConfiguration;
import javax.cache.CacheManager;
import javax.cache.Caching;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* this class is used to keep the details of the subscription storage. Simply this contains
* maps to keep the subscription object details with the topic details
*/
@SuppressWarnings("serial")
public class SharedMemorySubscriptionStorage implements Serializable {
private static boolean topicSubscriptionCacheInit =false;
private static boolean tenantIDInMemorySubscriptionStorageCacheInit = false;
private static final Log log = LogFactory.getLog(SharedMemorySubscriptionStorage.class);
/**
* Cache to keep the subscription details with the topics. This is important in finding subscriptions
* for a particular topic when publishing a message to a topic.
*/
public static Cache<String, SubscriptionContainer> getTopicSubscriptionCache() {
if (topicSubscriptionCacheInit) {
return Caching.getCacheManagerFactory()
.getCacheManager(SharedMemoryCacheConstants.INMEMORY_EVENT_CACHE_MANAGER)
.getCache(SharedMemoryCacheConstants.TOPIC_SUBSCRIPTION_CACHE);
} else {
CacheManager cacheManager = Caching.getCacheManagerFactory()
.getCacheManager(SharedMemoryCacheConstants.INMEMORY_EVENT_CACHE_MANAGER);
topicSubscriptionCacheInit = true;
return cacheManager.<String, SubscriptionContainer>createCacheBuilder(SharedMemoryCacheConstants.TOPIC_SUBSCRIPTION_CACHE).
setExpiry(CacheConfiguration.ExpiryType.MODIFIED, new CacheConfiguration.Duration(TimeUnit.SECONDS,
SharedMemoryCacheConstants.CACHE_INVALIDATION_TIME)).
setExpiry(CacheConfiguration.ExpiryType.ACCESSED, new CacheConfiguration.Duration(TimeUnit.SECONDS,
SharedMemoryCacheConstants.CACHE_INVALIDATION_TIME)).
setStoreByValue(false).build();
}
}
public static Cache<String, String> getSubscriptionIDTopicNameCache() {
if (tenantIDInMemorySubscriptionStorageCacheInit) {
return Caching.getCacheManagerFactory()
.getCacheManager(SharedMemoryCacheConstants.INMEMORY_EVENT_CACHE_MANAGER)
.getCache(SharedMemoryCacheConstants.SUBSCRIPTION_ID_TOPIC_NAME_CACHE);
} else {
CacheManager cacheManager = Caching.getCacheManagerFactory()
.getCacheManager(SharedMemoryCacheConstants.INMEMORY_EVENT_CACHE_MANAGER);
tenantIDInMemorySubscriptionStorageCacheInit = true;
return cacheManager.<String, String>createCacheBuilder(SharedMemoryCacheConstants.SUBSCRIPTION_ID_TOPIC_NAME_CACHE).
setExpiry(CacheConfiguration.ExpiryType.MODIFIED, new CacheConfiguration.Duration(TimeUnit.SECONDS,
SharedMemoryCacheConstants.CACHE_INVALIDATION_TIME)).
setExpiry(CacheConfiguration.ExpiryType.ACCESSED, new CacheConfiguration.Duration(TimeUnit.SECONDS,
SharedMemoryCacheConstants.CACHE_INVALIDATION_TIME)).
setStoreByValue(false).build();
}
}
public SharedMemorySubscriptionStorage() {
}
public void addSubscription(Subscription subscription) {
String topicName = getTopicName(subscription.getTopicName());
SubscriptionContainer subscriptionsContainer = getTopicSubscriptionCache().get(topicName);
if (subscriptionsContainer == null){
subscriptionsContainer = new SubscriptionContainer(topicName);
}
subscriptionsContainer.getSubscriptionsCache().put(subscription.getId(), subscription);
getTopicSubscriptionCache().put(topicName, subscriptionsContainer);
getSubscriptionIDTopicNameCache().put(subscription.getId(), topicName);
//send cluster message to inform other nodes about subscription added to the system, so that everyone can add new one.
try {
SharedMemoryCacheUtil.sendAddSubscriptionClusterMessage(topicName, subscription.getId(),
subscription.getTenantId(),
subscription.getTenantDomain());
} catch (ClusteringFault e) {
//This happen due to hazelcast clustering not setup correctly. subscription cluster will not send to other nodes.
log.error("Subscription cluster message sending failed",e);
}
}
public List<Subscription> getMatchingSubscriptions(String topicName) {
topicName = getTopicName(topicName);
List<Subscription> subscriptions = new ArrayList<Subscription>();
List<String> matchingTopicNames = getTopicMatchingNames(topicName);
for (String matchingTopicName : matchingTopicNames){
if (getTopicSubscriptionCache().get(matchingTopicName) != null){
SubscriptionContainer matchingContainer = getTopicSubscriptionCache().get(matchingTopicName);
Iterator<String> keysOfSubscription = matchingContainer.getSubscriptionsCache().keys();
while(keysOfSubscription.hasNext()) {
String key = keysOfSubscription.next();
subscriptions.add(matchingContainer.getSubscriptionsCache().get(key));
}
}
}
return subscriptions;
}
public void unSubscribe(String subscriptionID) throws EventBrokerException {
String topicName = getTopicName(getSubscriptionIDTopicNameCache().get(subscriptionID));
if (topicName == null){
throw new EventBrokerException("Subscription with ID " + subscriptionID + " does not exits");
}
SubscriptionContainer subscriptionContainer = getTopicSubscriptionCache().get(topicName);
if (subscriptionContainer == null){
throw new EventBrokerException("Subscription with ID " + subscriptionID + " does not exits");
}
subscriptionContainer.getSubscriptionsCache().remove(subscriptionID);
getSubscriptionIDTopicNameCache().remove(subscriptionID);
}
public void renewSubscription(Subscription subscription) throws EventBrokerException {
String topicName = getTopicName(subscription.getTopicName());
SubscriptionContainer subscriptionContainer = getTopicSubscriptionCache().get(topicName);
if (subscriptionContainer == null){
throw new EventBrokerException("There is no subscriptions with topic " + topicName);
}
Subscription existingSubscription = subscriptionContainer.getSubscriptionsCache().get(subscription.getId());
if (existingSubscription == null){
throw new EventBrokerException("There is no subscription with subscription id " + subscription.getId());
}
existingSubscription.setExpires(subscription.getExpires());
existingSubscription.setProperties(subscription.getProperties());
String val = subscription.getProperties().get("notVerfied");
if(val == null) {
getSubscriptionIDTopicNameCache().put(subscription.getId()+"-notVerfied", "false");
} else {
if("true".equalsIgnoreCase(val)) {
getSubscriptionIDTopicNameCache().put(subscription.getId()+"-notVerfied", "true");
} else {
getSubscriptionIDTopicNameCache().put(subscription.getId()+"-notVerfied", "false");
}
}
}
private List<String> getTopicMatchingNames(String topicName) {
List<String> matchingTopicNames = new ArrayList<String>();
if (topicName.equals("/")) {
matchingTopicNames.add("/#");
} else {
String currentTopicName = "";
String[] topicParts = topicName.split("/");
//the first part if the split parts are "" since always topics start with /
int i = 0;
while (i < (topicParts.length)) {
currentTopicName = currentTopicName + topicParts[i] + "/";
matchingTopicNames.add(currentTopicName + "#");
if (i == (topicParts.length - 1)||i == (topicParts.length - 2)) {
matchingTopicNames.add(currentTopicName + "*");
}
i++;
}
}
matchingTopicNames.add(topicName);
return matchingTopicNames;
}
private String getTopicName(String topicName){
if (!topicName.startsWith("/")){
topicName = "/" + topicName;
}
if (topicName.endsWith("/") && (topicName.length() != 1)){
topicName = topicName.substring(0, topicName.lastIndexOf('/'));
}
return topicName;
}
}
| 43.876652 | 135 | 0.693876 |
702ccbdaed9111bfc24104df76ac34a347e7ee84 | 3,855 | package net.contargo.intermodal.domain;
import com.fasterxml.jackson.annotation.JsonInclude;
/**
* A location used in drop off, pick up and stops of an {@link Transport}. Also used to specify the city of birth of a
* {@link Person}.
*
* @author Isabell Dürlich - duerlich@synyx.de
* @version 2018-04
* @name_german Ort
* @name_english location
* @source DIGIT - Standardisierung des Datenaustauschs für alle Akteure der intermodalen Kette zur Gewährleistung
* eines effizienten Informationsflusses und einer zukunftsfähigen digitalen Kommunikation
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Location {
/**
* @definition_german Eigenname Terminal
* @definition_english name of terminal
*/
private String designation;
private String city;
/**
* e.g. loading place, sea or hinterland terminal
*/
private String type;
private String postalCode;
private Coordinates coordinates;
Location() {
// OK
}
/**
* Creates a new builder for {@link Location}.
*
* @return new builder
*/
public static Builder newBuilder() {
return new Builder();
}
/**
* Creates a new builder with the values of another {@link Location}.
*
* @param location that should be copied.
*
* @return new builder with values of given location.
*/
public static Builder newBuilder(Location location) {
return new Builder().withDesignation(location.getDesignation())
.withCity(location.getCity())
.withCoordinates(location.getCoordinates())
.withPostalCode(location.getPostalCode())
.withType(location.getType());
}
public String getDesignation() {
return designation;
}
public String getCity() {
return city;
}
public String getType() {
return type;
}
public String getPostalCode() {
return postalCode;
}
public Coordinates getCoordinates() {
return coordinates;
}
public static final class Builder {
private String designation;
private String city;
private String type;
private String postalCode;
private Coordinates coordinates;
private Builder() {
}
public Builder withDesignation(String designation) {
this.designation = designation;
return this;
}
public Builder withCity(String city) {
this.city = city;
return this;
}
public Builder withType(String type) {
this.type = type;
return this;
}
public Builder withPostalCode(String postalCode) {
this.postalCode = postalCode;
return this;
}
public Builder withCoordinates(Coordinates coordinates) {
this.coordinates = coordinates;
return this;
}
public Location build() {
Location location = new Location();
location.coordinates = this.coordinates;
location.postalCode = this.postalCode;
location.city = this.city;
location.designation = this.designation;
location.type = this.type;
return location;
}
/**
* Validates the input and builds {@link Location}. Throws IllegalStateException if input doesn't fulfill the
* minimum requirement of {@link Location}.
*
* @return new {@link Location} with attributes specified in {@link Builder}
*/
public Location buildAndValidate() {
Location location = this.build();
MinimumRequirementValidator.validate(location);
return location;
}
}
}
| 21.657303 | 118 | 0.60441 |
e45b34f10f6130bb00ac93ee8f7fdb1d1be7bfe0 | 1,503 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.recoveryservicesbackup.models;
import com.azure.core.util.ExpandableStringEnum;
import com.fasterxml.jackson.annotation.JsonCreator;
import java.util.Collection;
/** Defines values for BackupEngineType. */
public final class BackupEngineType extends ExpandableStringEnum<BackupEngineType> {
/** Static value Invalid for BackupEngineType. */
public static final BackupEngineType INVALID = fromString("Invalid");
/** Static value DpmBackupEngine for BackupEngineType. */
public static final BackupEngineType DPM_BACKUP_ENGINE = fromString("DpmBackupEngine");
/** Static value AzureBackupServerEngine for BackupEngineType. */
public static final BackupEngineType AZURE_BACKUP_SERVER_ENGINE = fromString("AzureBackupServerEngine");
/**
* Creates or finds a BackupEngineType from its string representation.
*
* @param name a name to look for.
* @return the corresponding BackupEngineType.
*/
@JsonCreator
public static BackupEngineType fromString(String name) {
return fromString(name, BackupEngineType.class);
}
/**
* Gets known BackupEngineType values.
*
* @return known BackupEngineType values.
*/
public static Collection<BackupEngineType> values() {
return values(BackupEngineType.class);
}
}
| 35.785714 | 108 | 0.74185 |
4cbc95fab07bf1848394dc93af63fde809830bef | 14,278 | package com.components.se.factory;
import java.io.Closeable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.CodeSource;
import java.security.ProtectionDomain;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import org.apache.log4j.Logger;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.ie.InternetExplorerDriverService;
import org.openqa.selenium.ie.InternetExplorerOptions;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.safari.SafariDriver;
import org.openqa.selenium.safari.SafariOptions;
import com.control.ControlCenter;
import com.enums.ContextConstant;
import com.exception.UIException;
public class WebDriverFactory {
static final Logger logger = Logger.getLogger(WebDriverFactory.class);
static int closeAllIEInstance = 0;
/**
* Initializes browser. IE , CHROME and Firefox(default) For Selenium grid
* Platform default Platform set is WINDOWS The options available are - WINDOWS,
* Windows 8, Windows 10, Linux, Unix, MAC, Vista
*
* @param context:ITestContext
* @return WebDriver
* @throws UIException
* @throws IOException
* @throws Exception
* throw a Exception
*/
public static WebDriver initWebDriver(Map<String, String> params) throws UIException, IOException {
String platform = params.get("PLATFORM");
boolean runWithSeleniumGrid = params.containsKey("runWithSeleniumGrid")
&& params.get("runWithSeleniumGrid").equalsIgnoreCase("True");
String hubUrl = params.get("HUB_URL");
Platform env = null;
String os = System.getProperty("os.name", "generic").toLowerCase(Locale.ENGLISH);
if (platform == null) {
if (os.indexOf("mac") >= 0)
env = Platform.MAC;
else if (os.indexOf("win") >= 0)
env = Platform.WINDOWS;
else if (os.indexOf("nux") >= 0)
env = Platform.LINUX;
} else {
if (platform != null && platform.equalsIgnoreCase("Windows")) {
env = Platform.WINDOWS;
} else if (platform != null && platform.equalsIgnoreCase("Windows 8")) {
env = Platform.WIN8;
} else if (platform != null && platform.equalsIgnoreCase("Windows 10")) {
env = Platform.WIN10;
} else if (platform != null && platform.equalsIgnoreCase("MAC")) {
env = Platform.MAC;
} else if (platform != null && platform.equalsIgnoreCase("LINUX")) {
env = Platform.LINUX;
} else if (platform != null && platform.equalsIgnoreCase("UNIX")) {
env = Platform.UNIX;
} else if (platform != null && platform.equalsIgnoreCase("Vista")) {
env = Platform.VISTA;
}
}
if (params.containsKey("browser")) {
if (params.get("browser").equalsIgnoreCase("chrome")) {
try {
System.setProperty("webdriver.chrome.driver",
ControlCenter.getInstance().getDirectory(ContextConstant.CHRONE_DRIVER));
// URI
// driver=getDriver(ControlCenter.getInstance().getDirectory(ContextConstant.CHRONE_DRIVER));
// System.setProperty("webdriver.chrome.driver",new
// File(driver).getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
throw new UIException(e.getMessage(), e);
}
ChromeOptions options = new ChromeOptions();
Map<String, Object> prefs = new HashMap<String, Object>();
prefs.put("credentials_enable_service", false);
prefs.put("profile.password_manager_enabled", false);
prefs.put("profile.default_content_settings.popups", 0);
options.setExperimentalOption("prefs", prefs);
options.addArguments("test-type");
options.addArguments("--disable-popup-blocking");
options.addArguments("disable-infobars");
options.addArguments("--allow-cross-origin-auth-prompt");
logger.info("Browser parameter is Chrome");
if (runWithSeleniumGrid) {
return new RemoteWebDriver(new URL(hubUrl), options);
} else {
return new ChromeDriver(options);
}
} else if (params.get("browser").equalsIgnoreCase("ie")) {
try {
System.setProperty("webdriver.ie.driver",
ControlCenter.getInstance().getDirectory(ContextConstant.IE_DRIVER));
URI driver = getDriver(ControlCenter.getInstance().getDirectory(ContextConstant.IE_DRIVER));
System.setProperty("webdriver.ie.driver", new File(driver).getAbsolutePath());
} catch (Exception e) {
throw new UIException(e.getMessage(), e);
}
String cmd64Bit = "REG ADD \"HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\FEATURE_BFCACHE\" /F /V \"iexplore.exe\" /T REG_DWORD /D 0";
String cmd32Bit = "REG ADD \"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\FEATURE_BFCACHE\" /F /V \"iexplore.exe\" /T REG_DWORD /D 0";
String cmdPopUp64Bit = "REG ADD \"HKEY_CURRENT_USER\\Software\\Wow6432Node\\Microsoft\\Internet Explorer\\New Windows\" /F /V \"PopupMgr\" /T REG_SZ /D \"no\"";
String cmdPopUp32Bit = "REG ADD \"HKEY_CURRENT_USER\\Software\\Microsoft\\Internet Explorer\\New Windows\" /F /V \"PopupMgr\" /T REG_SZ /D \"no\"";
String cmdZoomDelete = "REG DELETE \"HKEY_CURRENT_USER\\Software\\Microsoft\\Internet Explorer\\Zoom\" /F /V \"ZoomFactor\" /T REG_DWORD /D \"100000\"";
String cmdZoomAdd = "REG ADD \"HKEY_CURRENT_USER\\Software\\Microsoft\\Internet Explorer\\Zoom\" /F /V \"ZoomFactor\" /T REG_DWORD /D \"100000\"";
String cmdUncheckRecovery = "REG ADD \"HKEY_CURRENT_USER\\Software\\Microsoft\\Internet Explorer\\Recovery\" /F /V \"AutoRecover\" /T REG_DWORD /D \"00000002\"";
if (os.indexOf("win") >= 0) { // && osArch.indexOf("amd64")>=0) {
try {
Runtime.getRuntime().exec(cmdZoomDelete);
Runtime.getRuntime().exec(cmd64Bit);
Runtime.getRuntime().exec(cmd32Bit);
Runtime.getRuntime().exec(cmdPopUp64Bit);
Runtime.getRuntime().exec(cmdPopUp32Bit);
Runtime.getRuntime().exec(cmdUncheckRecovery);
Runtime.getRuntime().exec(cmdZoomAdd);
} catch (Exception e) {
String message = "Set registry for IE failed";
logger.error(message, e);
throw new UIException(message, e);
}
String taskkillIEDriver = null;
String taskkillIE = null;
if (!runWithSeleniumGrid) {
try {
if (closeAllIEInstance == 0)
Runtime.getRuntime().exec(taskkillIEDriver);
} catch (WebDriverException e) {
logger.info(
"All open instances of IEDriver closed on test client before starting the execution on IE");
}
try {
if (closeAllIEInstance == 0)
Runtime.getRuntime().exec(taskkillIE);
} catch (WebDriverException e) {
logger.info(
"All open instances of IE browser closed on test client before starting the execution on IE");
}
closeAllIEInstance++;
}
}
// Setting for 32 bit driver
InternetExplorerDriverService.Builder builder = new InternetExplorerDriverService.Builder();
InternetExplorerDriverService service = builder.build();
InternetExplorerOptions option = new InternetExplorerOptions();
option.setCapability(InternetExplorerDriver.ENABLE_ELEMENT_CACHE_CLEANUP, false);
option.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
option.setCapability(CapabilityType.SUPPORTS_ALERTS, true); // uncommneted
option.setCapability("ignoreProtectedModeSettings", true);
option.setCapability(InternetExplorerDriver.NATIVE_EVENTS, true);
option.setCapability("disable-popup-blocking", true);
option.setCapability("unexpectedAlertBehaviour", "ignore");
option.setCapability(InternetExplorerDriver.ENABLE_PERSISTENT_HOVERING, false);
option.setCapability("enableFullPageScreenshot", false); // Changed from true to false
option.setCapability(CapabilityType.TAKES_SCREENSHOT, "true");
option.setCapability("ignoreZoomSetting", true);
option.setCapability(CapabilityType.SUPPORTS_FINDING_BY_CSS, true);
option.setCapability(CapabilityType.SUPPORTS_LOCATION_CONTEXT, true);
option.setCapability(InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION, true);
option.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
option.setCapability("screenResolution", "1386*768");
logger.info("Browser parameter is IE");
if (runWithSeleniumGrid) {
RemoteWebDriver remoteDriver = new RemoteWebDriver(new URL(hubUrl), option);
return remoteDriver;
} else {
return new InternetExplorerDriver(service, option);
}
} else if (params.get("browser").equalsIgnoreCase("safari")) {
SafariOptions options = new SafariOptions();
if (runWithSeleniumGrid) {
return new RemoteWebDriver(new URL(hubUrl), options);
} else {
return new SafariDriver(options);
}
} else {
logger.info("Browser parameter is Firefox");
logger.info("Cannot find browser parameter, firefox will be used as default browser");
System.setProperty("webdriver.gecko.driver",
ControlCenter.getInstance().getDirectory(ContextConstant.GECKO_DRIVER));
FirefoxOptions option = new FirefoxOptions();
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("dom.disable_open_during_load", false);
// option.setCapability(FirefoxDriver.PROFILE, profile);
if (runWithSeleniumGrid) {
return new RemoteWebDriver(new URL(hubUrl), option);
} else {
return new FirefoxDriver(option);
}
}
} else {
try {
logger.info("Cannot find browser parameter, firefox will be used as default browser");
System.setProperty("webdriver.gecko.driver",
ControlCenter.getInstance().getDirectory(ContextConstant.GECKO_DRIVER));
// URI
// driver=getDriver(ControlCenter.getInstance().getDirectory(ContextConstant.GECKO_DRIVER));
// System.setProperty("webdriver.gecko.driver",new
// File(driver).getAbsolutePath());
FirefoxOptions option = new FirefoxOptions();
// FirefoxProfile profile = new FirefoxProfile();
// profile.setPreference("dom.disable_open_during_load", false);
// option.setCapability(FirefoxDriver.PROFILE, profile);
if (runWithSeleniumGrid) {
return new RemoteWebDriver(new URL(hubUrl), option);
} else {
return new FirefoxDriver(option);
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
/**
* Get the driver from the jar file. IE , CHROME and Firefox(default)
*
* @param driverPath:String
* @return URI
* @throws URISyntaxException
* throw an URISyntaxException
* @throws ZipException
* throw a ZipException
* @throws IOException
* throw an IOException
*/
public static URI getDriver(String driverPath) throws URISyntaxException, ZipException, IOException {
final URI uri;
final URI exe;
uri = getJarURI();
exe = getFile(uri, driverPath);
return exe;
}
/**
* Get the jar URI
*
* @return URI
* @throws URISyntaxException
* throw an URISyntaxException
*/
private static URI getJarURI() throws URISyntaxException {
final ProtectionDomain domain;
final CodeSource source;
final URL url;
final URI uri;
domain = WebDriverFactory.class.getProtectionDomain();
source = domain.getCodeSource();
url = source.getLocation();
uri = url.toURI();
return (uri);
}
/**
* Get the driver from the jar file
*
* @param where:URI
* @param fileName:
* String
* @return URI
* @throws ZipException
* throw a ZipException
* @throws IOException
* throw an IOException
*/
private static URI getFile(final URI where, final String fileName) throws ZipException, IOException {
final File location;
final URI fileURI;
location = new File(where);
// not in a JAR, just return the path on disk
if (location.isDirectory()) {
fileURI = URI.create(where.toString() + fileName);
} else {
final ZipFile zipFile;
zipFile = new ZipFile(location);
try {
fileURI = extract(zipFile, fileName);
} finally {
zipFile.close();
}
}
return (fileURI);
}
/**
* extract the driver exe from the jar file
*
* @param ZipFile:ZipFile
* @param fileName:
* String
* @return URI
* @throws IOException
* throw an IOException
*/
private static URI extract(final ZipFile zipFile, final String fileName) throws IOException {
final File tempFile;
final ZipEntry entry;
final InputStream zipStream;
OutputStream fileStream;
tempFile = File.createTempFile(fileName, Long.toString(System.currentTimeMillis()));
tempFile.deleteOnExit();
entry = zipFile.getEntry(fileName);
if (entry == null) {
throw new FileNotFoundException("cannot find file: " + fileName + " in archive: " + zipFile.getName());
}
zipStream = zipFile.getInputStream(entry);
fileStream = null;
try {
final byte[] buf;
int i;
fileStream = new FileOutputStream(tempFile);
buf = new byte[1024];
i = 0;
while ((i = zipStream.read(buf)) != -1) {
fileStream.write(buf, 0, i);
}
} finally {
close(zipStream);
close(fileStream);
}
tempFile.setExecutable(true);
/*
* String os = System.getProperty("os.name",
* "generic").toLowerCase(Locale.ENGLISH); if (os.indexOf("mac") >= 0)
* Runtime.getRuntime().exec("chmod +x " + tempFile);
*/
return (tempFile.toURI());
}
/**
* close the stream
*
* @param stream:Closeable
*/
private static void close(final Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (final IOException ex) {
logger.error(ex.getMessage(), ex);
}
}
}
} | 35.167488 | 188 | 0.702689 |
90c2cc97e710d3ba170ad52067f7c0efc21ad875 | 2,192 | /*
* 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.axiom.ts.soap;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.soap.SOAPFactory;
import org.apache.axiom.testing.multiton.AdapterType;
import org.apache.axiom.testutils.suite.Dimension;
import org.apache.axiom.testutils.suite.MatrixTestCase;
@AdapterType
public abstract class SOAPElementTypeAdapter implements Dimension {
public interface Getter {
OMElement invoke(OMElement parent);
}
public interface Setter {
void invoke(OMElement parent, OMElement child);
}
private final Class<? extends OMElement> type;
private final Getter getter;
private final Setter setter;
SOAPElementTypeAdapter(Class<? extends OMElement> type, Getter getter, Setter setter) {
this.type = type;
this.getter = getter;
this.setter = setter;
}
@Override
public final void addTestParameters(MatrixTestCase testCase) {
testCase.addTestParameter("type", type.getSimpleName());
}
public final Class<? extends OMElement> getType() {
return type;
}
public final Getter getGetter() {
return getter;
}
public final Setter getSetter() {
return setter;
}
public abstract OMElement create(SOAPFactory factory);
public abstract OMElement create(SOAPFactory factory, SOAPElementType parentType, OMElement parent);
}
| 32.716418 | 104 | 0.723084 |
d25f0a0d981ccdaff1ed263acdaf2b7da080c663 | 2,387 | package model.animal;
import View.helper.Graphics;
import View.helper.Pen;
import View.helper.PenContainer;
import javafx.animation.Animation;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
/**
* This is the Turtle class, which extends the Animal class, but contains an image for the turtle
*
* @author Aninda Manocha
* @author Teddy Franceschi
* @author Jordan Frazier
*/
public class Turtle extends Animal {
private ImageView turtleImageView;
private Graphics graphic = new Graphics();
private Image turtleAppearance;
private Pen actualPen;
private ImageView imageView;
private String imagePath;
private Animation animalGif;
public Turtle(PenContainer penColor) {
super();
setImagePath("turtleLogo.png");
turtleAppearance = graphic.createImage(imagePath);
setImageView(new ImageView(turtleAppearance));
turtleImageView = graphic.createImageView(turtleAppearance);
actualPen = new Pen(getX(), getY());
}
@Deprecated
public Turtle(double width, double height) {
super(width, height);
setImagePath("turtleLogo.png");
turtleAppearance = graphic.createImage(imagePath);
setImageView(new ImageView(turtleAppearance));
turtleImageView = graphic.createImageView(turtleAppearance);
actualPen = new Pen(getX(), getY());
}
@Deprecated
public Turtle(double width, double height, double x, double y) {
super(width, height, x, y);
setImagePath("turtleLogo.png");
turtleAppearance = graphic.createImage(imagePath);
setImageView(new ImageView(turtleAppearance));
turtleImageView = graphic.createImageView(turtleAppearance);
actualPen = new Pen(getX(), getY());
}
public Animation getGif(){
return animalGif;
}
@Override
public void update() {
// TODO - update turtle
setChanged();
notifyObservers();
}
/***** GETTERS *****/
@Override
public Image getImage() {
return turtleAppearance;
}
@Override
public ImageView getImageView() {
return imageView;
}
@Override
public String getImagePath() {
return imagePath;
}
@Override
public Pen getActualPen() {
return actualPen;
}
/***** SETTERS *****/
@Override
public void setImage(Image image) {
this.turtleAppearance = image;
}
@Override
public void setImageView(ImageView imageView) {
this.imageView = imageView;
}
@Override
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
}
| 22.518868 | 97 | 0.735233 |
e7f3d861a476b2eb8ec567913ea664fd0c783af0 | 6,092 | /**
* Copyright 2013 deib-polimi
* Contact: deib-polimi <marco.miglierina@polimi.it>
*
* 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 it.polimi.modaclouds.cpimlibrary.entitymng.statements.builders;
import it.polimi.modaclouds.cpimlibrary.entitymng.ReflectionUtils;
import it.polimi.modaclouds.cpimlibrary.entitymng.statements.Statement;
import it.polimi.modaclouds.cpimlibrary.entitymng.statements.UpdateStatement;
import it.polimi.modaclouds.cpimlibrary.entitymng.statements.builders.lexer.Token;
import it.polimi.modaclouds.cpimlibrary.entitymng.statements.builders.lexer.TokenType;
import it.polimi.modaclouds.cpimlibrary.entitymng.statements.utils.CompareOperator;
import lombok.extern.slf4j.Slf4j;
import javax.persistence.CascadeType;
import javax.persistence.JoinTable;
import javax.persistence.Query;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
/**
* Builder for UPDATE statements.
*
* @author Fabio Arcidiacono.
* @see it.polimi.modaclouds.cpimlibrary.entitymng.statements.builders.StatementBuilder
*/
@Slf4j
public class UpdateBuilder extends StatementBuilder {
/**
* Read the builder configuration and instantiate the builder accordingly.
*
* @see it.polimi.modaclouds.cpimlibrary.entitymng.statements.builders.BuildersConfiguration
*/
public UpdateBuilder() {
super();
if (BuildersConfiguration.getInstance().isFollowingCascades()) {
super.followCascades(Arrays.asList(CascadeType.ALL, CascadeType.MERGE));
}
}
/* (non-Javadoc)
*
* @see StatementBuilder#initStatement()
*/
@Override
protected Statement initStatement() {
return new UpdateStatement();
}
/* (non-Javadoc)
*
* @see StatementBuilder#onFiled(it.polimi.modaclouds.cpimlibrary.entitymng.statements.Statement, Object, java.lang.reflect.Field)
*/
@Override
protected void onFiled(Statement statement, Object entity, Field field) {
super.addField(statement, entity, field);
}
/* (non-Javadoc)
*
* @see StatementBuilder#onRelationalField(it.polimi.modaclouds.cpimlibrary.entitymng.statements.Statement, Object, java.lang.reflect.Field)
*/
@Override
protected void onRelationalField(Statement statement, Object entity, Field field) {
super.addRelationalFiled(statement, entity, field);
}
/* (non-Javadoc)
*
* @see StatementBuilder#onIdField(it.polimi.modaclouds.cpimlibrary.entitymng.statements.Statement, Object, java.lang.reflect.Field)
*/
@Override
protected void onIdField(Statement statement, Object entity, Field idFiled) {
String jpaColumnName = ReflectionUtils.getJPAColumnName(idFiled);
Object idValue = ReflectionUtils.getFieldValue(entity, idFiled);
log.debug("id filed is {}, will be {} = {}", idFiled.getName(), jpaColumnName, idValue);
statement.addCondition(jpaColumnName, CompareOperator.EQUAL, idValue);
}
/* (non-Javadoc)
*
* @see StatementBuilder#generateJoinTableStatement(Object, Object, javax.persistence.JoinTable)
*/
@Override
protected Statement generateJoinTableStatement(Object entity, Object element, JoinTable joinTable) {
/* no need to update joinTable */
return null;
}
/* (non-Javadoc)
*
* @see StatementBuilder#generateInverseJoinTableStatement(Object, javax.persistence.JoinTable)
*/
@Override
protected Statement generateInverseJoinTableStatement(Object entity, JoinTable joinTable) {
/* no need to update joinTable */
return null;
}
/* (non-Javadoc)
*
* @see StatementBuilder#handleQuery(javax.persistence.Query, java.util.ArrayList)
*/
@Override
protected Statement handleQuery(Query query, List<Token> tokens) {
Iterator<Token> itr = tokens.iterator();
String objectParam = "";
boolean wherePart = false;
Statement statement = new UpdateStatement();
while (itr.hasNext()) {
Token current = itr.next();
switch (current.getType()) {
case SET:
case WHITESPACE:
/* fall through */
break;
case UPDATE:
super.setTableName(itr, statement);
objectParam = super.nextTokenOfType(TokenType.STRING, itr);
log.debug("JPQL object parameter is {}", objectParam);
break;
case WHERE:
wherePart = true;
break;
case COLUMN:
String column = super.getJPAColumnName(current, objectParam, statement.getTable());
String operator = super.nextTokenOfType(TokenType.COMPAREOP, itr);
Object value = super.getNextParameterValue(itr, query);
log.debug("found column will be {} {} {}", column, operator, value);
if (wherePart) {
statement.addCondition(column, operator, value);
} else {
/* is in the SET part */
statement.addField(column, value);
}
break;
case LOGICOP:
log.debug("found logic operator {}", current.getData());
statement.addCondition(current.getData());
}
}
return statement;
}
}
| 38.075 | 144 | 0.651182 |
3ca15997cd244aac27a8f2a448033f408ac5ef7a | 420 | package businessDelegate;
import lombok.Data;
/**
* Created by zhengwenzhan on 2019-03-13
*/
@Data
public class BusinessLookup {
private EjbService ejbService;
private JmsService jmsService;
public BusinessService getService(ServiceType serviceType) {
if (ServiceType.EJB.equals(serviceType)) {
return ejbService;
} else {
return jmsService;
}
}
}
| 17.5 | 64 | 0.654762 |
71e63d47d5bdee1458c8583057fb16cb20dec4f8 | 2,479 | /*
* Copyright 2010 Hippo.
*
* 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.onehippo.forge.jcrshell.diff;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class NodeChange extends Change {
/** logger */
private static final Logger log = LoggerFactory.getLogger(NodeChange.class);
NodeChange(Node node) throws RepositoryException {
super(node);
}
private Node getNode() {
return (Node) getItem();
}
@Override
public boolean isPropertyChange() {
return false;
}
@Override
public String getType() {
try {
return getNode().getPrimaryNodeType().getName();
} catch (RepositoryException e) {
log.warn("Error while getting type for '{}': {}", getPath(), e.getMessage());
log.debug("Stack:", e);
return "< unknown >";
}
}
protected int getIndex() {
try {
return getNode().getIndex();
} catch (RepositoryException e) {
log.warn("Error while getting index for '{}': {}", getPath(), e.getMessage());
log.debug("Stack:", e);
return 0;
}
}
@Override
public int compareTo(Change o) {
int superCmp = super.compareTo(o);
if (superCmp != 0) {
return superCmp;
}
NodeChange nc = (NodeChange) o;
if (getIndex() == nc.getIndex()) {
return 0;
}
return (getIndex() < nc.getIndex() ? -1 : 1);
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
} else if (obj instanceof Change) {
return compareTo((Change) obj) == 0;
} else {
return false;
}
}
@Override
public int hashCode() {
return getName().hashCode() + getIndex();
}
} | 27.241758 | 90 | 0.58814 |
10268c87a76b3a8be2d693cd5712102202ef1529 | 7,954 | package org.apache.continuum.builder.distributed.util;
/*
* 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.
*/
import org.apache.continuum.builder.utils.ContinuumBuildConstant;
import org.apache.continuum.dao.BuildResultDao;
import org.apache.continuum.dao.ProjectDao;
import org.apache.maven.continuum.ContinuumException;
import org.apache.maven.continuum.model.project.BuildResult;
import org.apache.maven.continuum.model.project.Project;
import org.apache.maven.continuum.model.project.ProjectDependency;
import org.apache.maven.continuum.model.scm.ChangeFile;
import org.apache.maven.continuum.model.scm.ChangeSet;
import org.apache.maven.continuum.model.scm.ScmResult;
import org.apache.maven.continuum.store.ContinuumStoreException;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Component( role = org.apache.continuum.builder.distributed.util.DistributedBuildUtil.class )
public class DistributedBuildUtil
{
private Logger log = LoggerFactory.getLogger( DistributedBuildUtil.class );
@Requirement
private ProjectDao projectDao;
@Requirement
private BuildResultDao buildResultDao;
public BuildResult convertMapToBuildResult( Map<String, Object> context )
{
BuildResult buildResult = new BuildResult();
updateBuildResultFromMap( buildResult, context );
return buildResult;
}
public void updateBuildResultFromMap( BuildResult buildResult, Map<String, Object> context )
{
buildResult.setStartTime( ContinuumBuildConstant.getStartTime( context ) );
buildResult.setEndTime( ContinuumBuildConstant.getEndTime( context ) );
buildResult.setError( ContinuumBuildConstant.getBuildError( context ) );
buildResult.setExitCode( ContinuumBuildConstant.getBuildExitCode( context ) );
buildResult.setState( ContinuumBuildConstant.getBuildState( context ) );
buildResult.setTrigger( ContinuumBuildConstant.getTrigger( context ) );
buildResult.setUsername( ContinuumBuildConstant.getUsername( context ) );
buildResult.setBuildUrl( ContinuumBuildConstant.getBuildAgentUrl( context ) );
}
public List<ProjectDependency> getModifiedDependencies( BuildResult oldBuildResult, Map<String, Object> context )
throws ContinuumException
{
if ( oldBuildResult == null )
{
return null;
}
try
{
Project project = projectDao.getProjectWithAllDetails( ContinuumBuildConstant.getProjectId( context ) );
List<ProjectDependency> dependencies = project.getDependencies();
if ( dependencies == null )
{
dependencies = new ArrayList<ProjectDependency>();
}
if ( project.getParent() != null )
{
dependencies.add( project.getParent() );
}
if ( dependencies.isEmpty() )
{
return null;
}
List<ProjectDependency> modifiedDependencies = new ArrayList<ProjectDependency>();
for ( ProjectDependency dep : dependencies )
{
Project dependencyProject = projectDao.getProject( dep.getGroupId(), dep.getArtifactId(),
dep.getVersion() );
if ( dependencyProject != null )
{
long nbBuild = buildResultDao.getNbBuildResultsInSuccessForProject( dependencyProject.getId(),
oldBuildResult.getEndTime() );
if ( nbBuild > 0 )
{
log.debug( "Dependency changed: " + dep.getGroupId() + ":" + dep.getArtifactId() + ":" +
dep.getVersion() );
modifiedDependencies.add( dep );
}
else
{
log.debug( "Dependency not changed: " + dep.getGroupId() + ":" + dep.getArtifactId() + ":" +
dep.getVersion() );
}
}
else
{
log.debug( "Skip non Continuum project: " + dep.getGroupId() + ":" + dep.getArtifactId() + ":" +
dep.getVersion() );
}
}
return modifiedDependencies;
}
catch ( ContinuumStoreException e )
{
log.warn( "Can't get the project dependencies", e );
}
return null;
}
public ScmResult getScmResult( Map<String, Object> context )
{
Map<String, Object> map = ContinuumBuildConstant.getScmResult( context );
if ( !map.isEmpty() )
{
ScmResult scmResult = new ScmResult();
scmResult.setCommandLine( ContinuumBuildConstant.getScmCommandLine( map ) );
scmResult.setCommandOutput( ContinuumBuildConstant.getScmCommandOutput( map ) );
scmResult.setException( ContinuumBuildConstant.getScmException( map ) );
scmResult.setProviderMessage( ContinuumBuildConstant.getScmProviderMessage( map ) );
scmResult.setSuccess( ContinuumBuildConstant.isScmSuccess( map ) );
scmResult.setChanges( getScmChanges( map ) );
return scmResult;
}
return null;
}
public List<ChangeSet> getScmChanges( Map<String, Object> context )
{
List<ChangeSet> changes = new ArrayList<ChangeSet>();
List<Map<String, Object>> scmChanges = ContinuumBuildConstant.getScmChanges( context );
if ( scmChanges != null )
{
for ( Map<String, Object> map : scmChanges )
{
ChangeSet changeSet = new ChangeSet();
changeSet.setAuthor( ContinuumBuildConstant.getChangeSetAuthor( map ) );
changeSet.setComment( ContinuumBuildConstant.getChangeSetComment( map ) );
changeSet.setDate( ContinuumBuildConstant.getChangeSetDate( map ) );
setChangeFiles( changeSet, map );
changes.add( changeSet );
}
}
return changes;
}
private void setChangeFiles( ChangeSet changeSet, Map<String, Object> context )
{
List<Map<String, Object>> changeFiles = ContinuumBuildConstant.getChangeSetFiles( context );
if ( changeFiles != null )
{
for ( Map<String, Object> map : changeFiles )
{
ChangeFile changeFile = new ChangeFile();
changeFile.setName( ContinuumBuildConstant.getChangeFileName( map ) );
changeFile.setRevision( ContinuumBuildConstant.getChangeFileRevision( map ) );
changeFile.setStatus( ContinuumBuildConstant.getChangeFileStatus( map ) );
changeSet.addFile( changeFile );
}
}
}
}
| 39.572139 | 118 | 0.624466 |
feae1a24dfad213400c830de9096e0bc09f975b3 | 729 | package com.lijq.mybatis.v2;
import com.lijq.mybatis.dao.User;
import com.lijq.mybatis.v2.executor.BaseExecutor;
import com.lijq.mybatis.v2.session.Configuration;
import com.lijq.mybatis.v2.session.SqlSession;
import org.junit.Test;
/**
* @author Lijq
* @date 2018/4/9 16:57
* @description
*/
public class V2Test {
@Test
public void test(){
Configuration configuration = new Configuration().buildMappers(UserMapper.class).buildInterceptors(new DemoInterceptor());
SqlSession sqlSession = new SqlSession(configuration);
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.selectByPrimaryKey("1");
System.out.println(user);
}
}
| 21.441176 | 130 | 0.716049 |
53417beaa1030556918feb3aea971a59511c87c4 | 286 | package method;
public class Walking {
public static void main(String[] args) {
double Cal = calculateCalory(5000);
System.out.println("소모 칼로리: " + Cal + "kcal");
}
private static double calculateCalory(int walk) {
double result = walk * 0.02;
return result;
}
}
| 17.875 | 51 | 0.660839 |
1a3693f95de679c915dca206752ef2ce2d2a178c | 3,559 | /*******************************************************************************
* Copyright (c) 2015 OpenDSE
*
* 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 net.sf.opendse.optimization;
import org.opt4j.core.Individual;
import org.opt4j.core.IndividualSet;
import org.opt4j.core.IndividualSetListener;
import org.opt4j.core.common.archive.CrowdingArchive;
import org.opt4j.core.optimizer.Archive;
import org.opt4j.core.optimizer.OptimizerIterationListener;
import org.opt4j.core.optimizer.Population;
import org.opt4j.core.start.Constant;
import com.google.inject.Inject;
/**
* A class that clears the population if no new individuals (individuals that
* are either dominated or dominate other population members) came into the
* population for a defined number of iterations. This state, where no new
* individuals are generated for a defined period of time is considered as a
* stagnation. The population is then cleared and new individuals are created
* from scratch to prevent being stuck in a local optimum.
*
* @author lukasiewycz
*
*/
public class StagnationRestart implements IndividualSetListener, OptimizerIterationListener {
protected final Archive archive = new CrowdingArchive(100);
protected final Population population;
protected int iteration = 0;
protected int lastUpdate = 0;
protected final int diff;
@Inject
public StagnationRestart(Population population,
@Constant(value = "maximalNumberStagnatingGenerations", namespace = StagnationRestart.class) int diff) {
this.population = population;
this.diff = diff;
}
@Override
public void iterationComplete(int iteration) {
this.iteration = iteration;
for (Individual in0 : population) {
for (Individual in1 : archive) {
if (in0.getObjectives().dominates(in1.getObjectives())) {
// new individuals are found
lastUpdate = iteration;
}
}
}
archive.update(population);
if (iteration - lastUpdate > diff) {
// the case where no individuals were found for the last diff
// generations
lastUpdate = iteration;
archive.clear();
population.clear();
}
}
@Override
public void individualAdded(IndividualSet collection, Individual individual) {
// No reaction needed
}
@Override
public void individualRemoved(IndividualSet collection, Individual individual) {
// No reaction needed
}
}
| 36.316327 | 108 | 0.70694 |
74e1e94809fd07f1af941217ff87ac0ea9659b4c | 739 | /*
* XML Type: FileIDType
* Namespace: urn:com.io7m.cardant.inventory:1
* Java type: com.io7m.cardant.protocol.inventory.v1.beans.FileIDType
*
* Automatically generated - do not modify.
*/
package com.io7m.cardant.protocol.inventory.v1.beans.impl;
import javax.xml.namespace.QName;
import org.apache.xmlbeans.QNameSet;
/**
* An XML FileIDType(@urn:com.io7m.cardant.inventory:1).
*
* This is a complex type.
*/
public class FileIDTypeImpl extends com.io7m.cardant.protocol.inventory.v1.beans.impl.IDTypeImpl implements com.io7m.cardant.protocol.inventory.v1.beans.FileIDType {
private static final long serialVersionUID = 1L;
public FileIDTypeImpl(org.apache.xmlbeans.SchemaType sType) {
super(sType);
}
}
| 29.56 | 165 | 0.749662 |
cff3e48b43e331df10b90d305d5815e58278c015 | 539 | package com.john.lazy;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* @Description: spring5.0-2018
* @Author: johnwonder
* @Date: 2021/6/15
*/
public class LazyAnnotaionDemo {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx
= new AnnotationConfigApplicationContext();
ctx.register(LazyConfigBean.class);
ctx.refresh();
//https://blog.csdn.net/niugang0920/article/details/115900565
ctx.getBean(Bean1.class);
// ctx.getBean(Bean2.class);
}
}
| 22.458333 | 81 | 0.751391 |
21241817f82ac13fbcdfe4b126e22a8050e3ac95 | 633 | package com.jbtits.otus.lecture16.ms.dataSets;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
@Entity
@Table(name = "user")
public class UserDataSet extends DataSet {
@Column(name = "name", unique = true)
private String name;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Column(name = "password")
private String password;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
} | 20.419355 | 46 | 0.658768 |
148f92e6826a8fca91f741a4f47fd3510c8c9820 | 1,480 | package com.rallydev.rest.response;
import com.google.gson.JsonArray;
/**
* Represents a WSAPI response from querying for objects.
*/
public class QueryResponse extends Response {
/**
* Create a new query response from the specified JSON encoded string.
*
* @param queryResponse the JSON encoded string
*/
public QueryResponse(String queryResponse) {
super(queryResponse);
}
/**
* Get the name of the root JSON result
*
* @return the root element name
*/
@Override
protected String getRoot() {
return "QueryResult";
}
/**
* Get the total number of objects that matched the query
*
* @return the total number of objects
*/
public int getTotalResultCount() {
return result.get("TotalResultCount").getAsInt();
}
/**
* Get the results of the query
* <p>Depending on the limit of the original request this may include one or more pages.</p>
*
* @return the results
*/
public JsonArray getResults() {
return result.getAsJsonArray("Results");
}
/**
* Get the page size of the results
*
* @return the page size
*/
public int getPageSize() {
return result.get("PageSize").getAsInt();
}
/**
* Get the start index of the results
*
* @return the start index
*/
public int getStart() {
return result.get("StartIndex").getAsInt();
}
}
| 22.424242 | 96 | 0.602027 |
21858b0ebb88a59b011dc7334d8dd5d3aaad889d | 5,908 | package de.pacheco.popularMovies;
import de.pacheco.popularMovies.databinding.ActivityMainBinding;
import de.pacheco.popularMovies.model.Movie;
import de.pacheco.popularMovies.model.MoviesViewModel;
import de.pacheco.popularMovies.recycleviews.MoviePosterAdapter;
import de.pacheco.popularMovies.util.MoviesUtil;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.Collections;
import java.util.List;
import static de.pacheco.android.utilities.UtilsKt.calculateNoOfColumns;
public class MoviesFragment extends Fragment {
public static final String BUNDLE_SELECTION = "Selection";
private static final String TAG = MoviesFragment.class.getSimpleName();
private static final String BUNDLE_LAYOUT = "BUNDLE_LAYOUT";
private MoviePosterAdapter moviePosterAdapter;
private List<Movie> movies = Collections.emptyList();
private List<Movie> favorites;
private List<Movie> populars;
private List<Movie> topRated;
private String selection = MoviesUtil.POPULAR;
private GridLayoutManager layoutManager;
private String oldSelection;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
ActivityMainBinding binding = ActivityMainBinding.inflate(inflater);
binding.spinnerSortBy.setOnItemSelectedListener(getSpinnerListener());
binding.rvMovieOverview.setHasFixedSize(true);
layoutManager = new GridLayoutManager(getContext(), calculateNoOfColumns(getContext()),
RecyclerView.VERTICAL, false);
binding.rvMovieOverview.setLayoutManager(layoutManager);
moviePosterAdapter = new MoviePosterAdapter(getActivity());
binding.rvMovieOverview.setAdapter(moviePosterAdapter);
setupViewModel();
//data is set within spinner listener, which is called after created
return binding.getRoot();
}
/**
* If the activity is re-created, it receives the same ViewModelProvider instance that was created by the first activity.
*/
@SuppressWarnings("ConstantConditions")
private void setupViewModel() {
MoviesViewModel moviesViewModel = new ViewModelProvider(this).get(MoviesViewModel.class);
moviesViewModel.getFavouriteMovies().observe(getActivity(),
list -> {
favorites = list;
if (selection.equals(MoviesUtil.FAVOURITES)) {
setMovieData(MoviesUtil.FAVOURITES);
}
});
moviesViewModel.getPopularMovies().observe(getActivity(),
list -> {
populars = list;
if (selection.equals(MoviesUtil.POPULAR)) {
setMovieData(MoviesUtil.POPULAR);
}
});
moviesViewModel.getTopRatedMovies().observe(getActivity(),
list -> {
topRated = list;
if (selection.equals(MoviesUtil.TOP_RATED)) {
setMovieData(MoviesUtil.TOP_RATED);
}
});
}
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable(BUNDLE_LAYOUT,
layoutManager.onSaveInstanceState());
outState.putString(BUNDLE_SELECTION, selection);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
selection = savedInstanceState.getString(BUNDLE_SELECTION);
setMovieData(selection);
Parcelable savedRecyclerLayoutState = savedInstanceState.getParcelable(BUNDLE_LAYOUT);
layoutManager.onRestoreInstanceState(savedRecyclerLayoutState);
}
}
private void setMovieData(String selection) {
if (selection == null) {
selection = MoviesUtil.POPULAR;
}
switch (selection) {
case MoviesUtil.POPULAR:
moviePosterAdapter.setMovieData(populars);
movies = populars;
break;
case MoviesUtil.TOP_RATED:
moviePosterAdapter.setMovieData(topRated);
movies = topRated;
break;
case MoviesUtil.FAVOURITES:
default:
moviePosterAdapter.setMovieData(favorites);
movies = favorites;
break;
}
}
public AdapterView.OnItemSelectedListener getSpinnerListener() {
return new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if (i == 0) {
selection = MoviesUtil.POPULAR;
} else if (i == 1) {
selection = MoviesUtil.TOP_RATED;
} else {
selection = MoviesUtil.FAVOURITES;
}
if (oldSelection != null && !oldSelection.equals(selection)) {
layoutManager.scrollToPositionWithOffset(0, 0);
}
setMovieData(selection);
oldSelection = selection;
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
};
}
} | 39.386667 | 132 | 0.645396 |
dbde59378485bdb1c4c96e53e83e120e1c836959 | 5,487 | package com.vipul.covidstatus.adapters;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.vipul.covidstatus.data.PerCountryData;
import com.vipul.covidstatus.R;
import com.vipul.covidstatus.models.CountrywiseModel;
import java.text.NumberFormat;
import java.util.ArrayList;
public class CountrywiseAdapter extends RecyclerView.Adapter<CountrywiseAdapter.ViewHolder> {
private Context mContext;
private ArrayList<CountrywiseModel> arrayList;
private CountrywiseAdapter.OnItemClickListner mListner;
private static final String COUNTRY_NAME = "country";
private static final String COUNTRY_CONFIRMED = "cases";
private static final String COUNTRY_ACTIVE = "active";
private static final String COUNTRY_DECEASED = "deaths";
private static final String COUNTRY_NEW_CONFIRMED = "todayCases";
private static final String COUNTRY_TESTS = "tests";
private static final String COUNTRY_NEW_DECEASED = "todayDeaths";
private static final String COUNTRY_FLAGURL = "flag";
private static final String COUNTRY_RECOVERED = "recovered";
public static final String COUNTRY_NEW_RECOVERED = "todayRecovered";
public interface OnItemClickListner {
void onItemClick(int position);
}
public void setOnItemClickListner(OnItemClickListner listner) {
mListner = listner;
}
public CountrywiseAdapter(Context context, ArrayList<CountrywiseModel> countrywiseModelArrayList) {
mContext = context;
arrayList = countrywiseModelArrayList;
}
@NonNull
@Override
public CountrywiseAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.countrywise_list_layout, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull CountrywiseAdapter.ViewHolder holder, final int position) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CountrywiseModel clickedItem = arrayList.get(position);
Intent perCountryIntent = new Intent(mContext, PerCountryData.class);
perCountryIntent.putExtra(COUNTRY_NAME, clickedItem.getCountry());
perCountryIntent.putExtra(COUNTRY_CONFIRMED, clickedItem.getConfirmed());
perCountryIntent.putExtra(COUNTRY_ACTIVE, clickedItem.getActive());
perCountryIntent.putExtra(COUNTRY_RECOVERED, clickedItem.getRecovered());
perCountryIntent.putExtra(COUNTRY_DECEASED, clickedItem.getDeceased());
perCountryIntent.putExtra(COUNTRY_NEW_CONFIRMED, clickedItem.getNewConfirmed());
perCountryIntent.putExtra(COUNTRY_NEW_DECEASED, clickedItem.getNewDeceased());
perCountryIntent.putExtra(COUNTRY_TESTS, clickedItem.getTests());
perCountryIntent.putExtra(COUNTRY_FLAGURL, clickedItem.getFlag());
perCountryIntent.putExtra(COUNTRY_NEW_RECOVERED, clickedItem.getNewRecovered());
mContext.startActivity(perCountryIntent);
}
});
CountrywiseModel currentItem = arrayList.get(position);
String countryName = currentItem.getCountry();
String countryTotal = currentItem.getConfirmed();
String countryFlag = currentItem.getFlag();
String countryRank = String.valueOf(position+1);
int countryTotalInt = Integer.parseInt(countryTotal);
holder.rankTextView.setText(countryRank+".");
holder.countryTotalCases.setText(NumberFormat.getInstance().format(countryTotalInt));
holder.countryName.setText(countryName);
Glide.with(mContext).load(countryFlag).into(holder.flagImage);
}
@Override
public int getItemCount() {
return arrayList.size();
}
public void filterList(ArrayList<CountrywiseModel> filteredList) {
arrayList = filteredList;
notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView countryName, countryTotalCases, rankTextView;
ImageView flagImage;
public ViewHolder(View itemView) {
super(itemView);
countryName = itemView.findViewById(R.id.country_name_textview);
countryTotalCases = itemView.findViewById(R.id.country_confirmed_textview);
flagImage = itemView.findViewById(R.id.flag_image);
rankTextView = itemView.findViewById(R.id.country_rank);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mListner != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListner.onItemClick(position);
}
}
}
});
}
}
}
| 40.947761 | 108 | 0.677784 |
983f4dacf9f1a380faaa78a4990610978563bade | 3,444 | /**
* 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.openejb.client;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.ObjectStreamException;
public class EJBObjectProxyHandle implements Externalizable {
private static final long serialVersionUID = -8325446328982364608L;
public static final ThreadLocal<Resolver> resolver = new DefaultedThreadLocal<Resolver>(new ClientSideResovler());
private transient EJBObjectHandler handler;
private transient ProtocolMetaData metaData;
public EJBObjectProxyHandle() {
}
public EJBObjectProxyHandle(final EJBObjectHandler handler) {
this.handler = handler;
}
public void setMetaData(final ProtocolMetaData metaData) {
this.metaData = metaData;
}
@Override
public void writeExternal(final ObjectOutput out) throws IOException {
// write out the version of the serialized data for future use
out.writeByte(1);
handler.client.setMetaData(metaData);
handler.client.writeExternal(out);
handler.ejb.setMetaData(metaData);
handler.ejb.writeExternal(out);
handler.server.setMetaData(metaData);
handler.server.writeExternal(out);
out.writeObject(handler.primaryKey);
out.writeObject(handler.authenticationInfo);
}
@Override
public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
final byte version = in.readByte(); // future use
final ClientMetaData client = new ClientMetaData();
final EJBMetaDataImpl ejb = new EJBMetaDataImpl();
final ServerMetaData server = new ServerMetaData();
client.setMetaData(metaData);
ejb.setMetaData(metaData);
server.setMetaData(metaData);
client.readExternal(in);
ejb.readExternal(in);
server.readExternal(in);
final Object primaryKey = in.readObject();
final JNDIContext.AuthenticationInfo authenticationInfo = JNDIContext.AuthenticationInfo.class.cast(in.readObject());
handler = EJBObjectHandler.createEJBObjectHandler(ejb, server, client, primaryKey, authenticationInfo);
}
private Object readResolve() throws ObjectStreamException {
return resolver.get().resolve(handler);
}
public static interface Resolver {
Object resolve(EJBObjectHandler handler);
}
public static class ClientSideResovler implements Resolver {
@Override
public Object resolve(final EJBObjectHandler handler) {
return handler.createEJBObjectProxy();
}
}
}
| 33.764706 | 125 | 0.721545 |
f400bf311170d9b556333db8f1c91f21b3298d73 | 1,062 | package fiji.plugin.trackmate.gui;
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.ImageIcon;
public final class GuiConstants
{
public static final Font FONT = new Font( "Arial", Font.PLAIN, 10 );
public static final Font BIG_FONT = new Font( "Arial", Font.PLAIN, 14 );
public static final Font SMALL_FONT = FONT.deriveFont( 8 );
public static final Dimension TEXTFIELD_DIMENSION = new Dimension( 40, 18 );
public static final ImageIcon TRACKMATE_ICON = new ImageIcon( GuiConstants.class.getResource( "Logo50x50-color-nofont-72p.png" ) );
public static final ImageIcon ICON_REFRESH = new ImageIcon( GuiConstants.class.getResource( "arrow_refresh_small.png" ) );
public static final ImageIcon ICON_PREVIEW = new ImageIcon( GuiConstants.class.getResource( "flag_checked.png" ) );
public static final ImageIcon ICON_ADD = new ImageIcon( GuiConstants.class.getResource( "add.png" ) );
public static final ImageIcon ICON_REMOVE = new ImageIcon( GuiConstants.class.getResource( "delete.png" ) );
private GuiConstants()
{}
}
| 33.1875 | 132 | 0.764595 |
7e88ce67f40d5b2ca2136dbd97cd93fbd2cb5c41 | 235 | package org.jeecg.modules.ticket.vo;
import lombok.Data;
@Data
public class OperateVO {
private String ticketId;
private String takerId;
private String nextTakerIds;
private String variable;
private String comment;
}
| 12.368421 | 36 | 0.753191 |
cafbc6e6186f159386bc3e92856d2c89ab3c09de | 4,841 | package io.tornadofaces.component.slider;
import io.tornadofaces.component.util.ComponentUtils;
import io.tornadofaces.component.util.StyleClass;
import io.tornadofaces.json.JSONArray;
import io.tornadofaces.json.JSONObject;
import io.tornadofaces.util.WidgetBuilder;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.render.FacesRenderer;
import javax.faces.render.Renderer;
import java.io.IOException;
import static io.tornadofaces.component.util.ComponentUtils.encodeAjaxBehaviors;
import static io.tornadofaces.component.util.ComponentUtils.findComponent;
@FacesRenderer(rendererType = SliderRenderer.RENDERER_TYPE, componentFamily = ComponentUtils.COMPONENT_FAMILY)
public class SliderRenderer extends Renderer {
public static final String RENDERER_TYPE = "io.tornadofaces.component.SliderRenderer";
public void encodeChildren(FacesContext context, UIComponent component) throws IOException {
for (UIComponent child : component.getChildren())
if (!(child instanceof SliderHeader))
child.encodeAll(context);
}
public boolean getRendersChildren() {
return true;
}
public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
ResponseWriter writer = context.getResponseWriter();
Slider slider = (Slider) component;
writer.startElement("div", component);
writer.writeAttribute("id", slider.getClientId(), null);
StyleClass.of("slider").add(slider.getStyleClass()).write(writer);
writer.startElement("input", component);
writer.writeAttribute("type", "hidden", null);
String lowerId = slider.getLowerClientId(context);
writer.writeAttribute("id", lowerId, null);
writer.writeAttribute("name", lowerId, null);
Integer lowerValue = slider.getLower();
if (lowerValue != null)
writer.writeAttribute("value", lowerValue.toString(), "lower");
writer.endElement("input");
writer.startElement("input", component);
writer.writeAttribute("type", "hidden", null);
String upperId = slider.getUpperClientId(context);
writer.writeAttribute("id", upperId, null);
writer.writeAttribute("name", upperId, null);
Integer upperValue = slider.getUpper();
if (upperValue != null)
writer.writeAttribute("value", upperValue.toString(), "upper");
writer.endElement("input");
// Support rendering of dynamic SliderHeader
for (UIComponent child : component.getChildren())
if (child instanceof SliderHeader)
child.encodeAll(context);
if (slider.getHeader()) {
writer.startElement("div", slider);
writer.writeAttribute("id", slider.getClientId(context) + "_header", null);
writer.writeAttribute("class", "slider-header", null);
// min
writer.startElement("span", slider);
writer.writeAttribute("class", "slider-min", null);
writer.writeText(String.format("%s", slider.getMin()), null);
writer.endElement("span");
// max
writer.startElement("span", slider);
writer.writeAttribute("class", "slider-max", null);
writer.writeText(String.format("%s", slider.getMax()), null);
writer.endElement("span");
// value
writer.startElement("h4", slider);
writer.writeText(String.format("%s", slider.getLower()), null);
Integer upper = slider.getUpper();
if (upper != null)
writer.writeText(" - " + upper, null);
writer.endElement("h4");
writer.endElement("div");
}
writer.startElement("div", slider);
writer.writeAttribute("class", "slider-content", null);
}
public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
Slider slider = (Slider) component;
ResponseWriter writer = context.getResponseWriter();
writer.endElement("div"); // slider-content
writer.endElement("div"); // slider
WidgetBuilder builder = new WidgetBuilder(context, slider)
.initWithDomReady()
.attr("lowerId", slider.getLowerClientId(context))
.attr("upperId", slider.getUpperClientId(context))
.attr("throttle", slider.getThrottle())
.attr("header", slider.getHeader())
.nativeAttr("settings", slider.getSettings().toString())
.nativeAttr("onSlide", slider.getOnSlide())
.nativeAttr("labelFormatter", slider.getLabelFormatter());
String lowerTarget = slider.getLowerTarget();
if (lowerTarget != null)
builder.attr("lowerTarget", slider.getParent().findComponent(lowerTarget).getClientId());
String upperTarget = slider.getUpperTarget();
if (upperTarget != null)
builder.attr("upperTarget", slider.getParent().findComponent(upperTarget).getClientId());
JSONArray flipBehaviors = encodeAjaxBehaviors(context, "change", slider);
if (flipBehaviors != null) {
JSONObject behaviors = new JSONObject();
behaviors.put("change", flipBehaviors);
builder.nativeAttr("behaviors", behaviors.toString());
}
builder.finish();
}
} | 36.674242 | 110 | 0.742202 |
63434d916c845a8743b5c7d42e238bbd1032d8e9 | 508 | package wuest.markus.vertretungsplan;
public class HWGrade {
private int _id;
private String _GradeName;
public HWGrade(){}
public HWGrade(String GradeName) {
this._GradeName = GradeName;
}
public void set_id(int _id) {
this._id = _id;
}
public void set_GradeName(String _GradeName) {
this._GradeName = _GradeName;
}
public int get_id() {
return _id;
}
public String get_GradeName() {
return _GradeName;
}
}
| 16.933333 | 50 | 0.612205 |
de50bbdc688e5da8918e89cc591bfed0809370b2 | 1,446 | // Copyright 2014 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.testutil;
import com.google.devtools.build.lib.util.Clock;
import java.util.concurrent.TimeUnit;
/**
* A fake clock for testing.
*/
public final class ManualClock implements Clock {
private long currentTimeMillis = 0L;
@Override
public long currentTimeMillis() {
return currentTimeMillis;
}
/**
* Nano time should not be confused with wall time. Nano time is only mean to compute time
* differences. Because of this, we shift the time returned by 1000s, to test that the users
* of this class do not rely on nanoTime == currentTimeMillis.
*/
@Override
public long nanoTime() {
return TimeUnit.MILLISECONDS.toNanos(currentTimeMillis)
+ TimeUnit.SECONDS.toNanos(1000);
}
public void advanceMillis(long time) {
currentTimeMillis += time;
}
}
| 30.765957 | 94 | 0.732365 |
648d27cec117a531ba7426e241dd955da99eae03 | 904 | package com.revature.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnFactory {
private static ConnFactory cf = new ConnFactory();
private static final String url = "jdbc:oracle:thin:@java2004usf.c3ze8kvqgwxn.us-east-2.rds.amazonaws.com:1521:ORCL";
private static final String user = "vgdemo";
private static final String password = "p4ssw0rd";
private ConnFactory() {
super();
}
public static synchronized ConnFactory getInstance() {
if(cf==null)
cf = new ConnFactory();
return cf;
}
public Connection getConnection() {
Connection conn = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
}
| 23.789474 | 118 | 0.719027 |
0d73cd1105ce79a5459cf8e0dfe53b20829ba722 | 1,280 | package com.javarush.task.task19.task1922;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
/*
Ищем нужные строки
*/
public class Solution {
public static List<String> words = new ArrayList<String>();
static {
words.add("файл");
words.add("вид");
words.add("В");
}
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
BufferedReader fileReader = new BufferedReader(new FileReader(reader.readLine()));
reader.close();
String lines;
while ((lines = fileReader.readLine()) != null){
String[] strArray = lines.split(" ");
int count = 0;
for(String strList: words){
for (String s : strArray) {
if (strList.equals(s)) {
count++;
}
}
}
if(count == 2){
System.out.println(lines);
}
//System.out.println(count);
}
fileReader.close();
}
}
| 26.666667 | 90 | 0.536719 |
85280f7e420c2e7b5e974fe7606e4370bc55bc12 | 210 | package com.moneromint.solo.stratum.message;
import com.fasterxml.jackson.annotation.JsonProperty;
public enum StratumMethod {
@JsonProperty("login")
LOGIN,
@JsonProperty("submit")
SUBMIT,
}
| 17.5 | 53 | 0.733333 |
d6164b5df12042c8f472f798a721f935c8347e19 | 464 | package com.mars.start.startmap.impl;
import com.mars.start.startmap.StartMap;
import com.mars.start.startmap.StartParam;
/**
* 加载JDBC模块
*/
public class StartJDBC implements StartMap {
/**
* 加载JDBC模块
* @param startParam 参数
* @throws Exception 异常
*/
@Override
public void load(StartParam startParam) throws Exception {
if(startParam.getInitJdbc() != null){
startParam.getInitJdbc().init();
}
}
}
| 20.173913 | 62 | 0.642241 |
293551030d3bc48a23e3a2ea58cc658b05f922ee | 2,416 | /*
* 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.sling.testing.mock.jcr;
import java.util.Set;
import javax.jcr.NamespaceRegistry;
import javax.jcr.RepositoryException;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
/**
* Mock {@link NamespaceRegistry} implementation.
*/
class MockNamespaceRegistry implements NamespaceRegistry {
private final BiMap<String, String> namespacePrefixMapping = HashBiMap.create();
public MockNamespaceRegistry() {
this.namespacePrefixMapping.put("jcr", "http://www.jcp.org/jcr/1.0");
}
@Override
public String getURI(final String prefix) throws RepositoryException {
return this.namespacePrefixMapping.get(prefix);
}
@Override
public String getPrefix(final String uri) throws RepositoryException {
return this.namespacePrefixMapping.inverse().get(uri);
}
@Override
public void registerNamespace(final String prefix, final String uri) throws RepositoryException {
this.namespacePrefixMapping.put(prefix, uri);
}
@Override
public void unregisterNamespace(final String prefix) throws RepositoryException {
this.namespacePrefixMapping.remove(prefix);
}
@Override
public String[] getPrefixes() throws RepositoryException {
Set<String> keys = this.namespacePrefixMapping.keySet();
return keys.toArray(new String[keys.size()]);
}
@Override
public String[] getURIs() throws RepositoryException {
Set<String> values = this.namespacePrefixMapping.values();
return values.toArray(new String[values.size()]);
}
}
| 34.514286 | 101 | 0.731788 |
76cc8ad7a6c81599092f64a7456e79996021ade9 | 900 | package com.github.cc3002.finalreality.Controller;
import com.github.cc3002.finalreality.model.character.Enemy;
import java.util.List;
public interface IEnemyTeam {
/**
* Return the enemies.
*/
List<Enemy> getTeam();
/**
* Add a enemy to the enemies.
*/
void addTeammate(Enemy opponent);
/**
* Remove a enemy of the enemies.
*/
void removeTeammate(Enemy opponent);
/**
* Return the enemy with the same name.
*/
Enemy getOpponent(String name);
/**
* Return the life of the enemy.
*/
int checkLife(Enemy opponent);
/**
* Return the defense of the enemy.
*/
int checkDef(Enemy opponent);
/**
* Return the attack of the enemy.
*/
int checkAtk(Enemy opponent);
/**
* returns true if there is a enemy with the name.
*/
boolean isInTeam(String name);
}
| 18.75 | 60 | 0.598889 |
777d66c031967d044a6e7a42d7ef3f3e353190b7 | 454 | package com.aem.ugam.core.service.impl;
import com.aem.ugam.core.service.MultiService;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.propertytypes.ServiceRanking;
@Component(service = MultiService.class,immediate = true,name = "serviceA")
@ServiceRanking(1000)
public class MultiServiceAImpl implements MultiService {
@Override
public String getName() {
return "MultiServiceAImpl";
}
}
| 28.375 | 75 | 0.77533 |
c2ebe8716b7a3eb3060c9bd855bd0c9d1dd9ce32 | 1,096 | package com.lichkin.application.apis.api50000.U.n00;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.lichkin.framework.defines.LKFrameworkStatics;
import com.lichkin.framework.web.annotations.LKApiType;
import com.lichkin.framework.web.enums.ApiType;
import com.lichkin.springframework.controllers.ApiKeyValues;
import com.lichkin.springframework.controllers.LKApiBusUpdateController;
import com.lichkin.springframework.entities.impl.SysPssStorageEntity;
import com.lichkin.springframework.services.LKApiBusUpdateService;
@RestController("SysPssStorageU00Controller")
@RequestMapping(value = LKFrameworkStatics.WEB_MAPPING_API + "/SysPssStorage/U")
@LKApiType(apiType = ApiType.COMPANY_BUSINESS)
public class C extends LKApiBusUpdateController<I, SysPssStorageEntity> {
@Autowired
private S service;
@Override
protected LKApiBusUpdateService<I, SysPssStorageEntity> getService(I cin, ApiKeyValues<I> params) {
return service;
}
}
| 36.533333 | 100 | 0.843978 |
35307aae3f547a50dbb336cacae1d7ae82da7dc0 | 3,802 | // This file is auto-generated, don't edit it. Thanks.
package com.antgroup.antchain.openapi.ent.models;
import com.aliyun.tea.*;
public class ExecTokenRedeemRequest extends TeaModel {
// OAuth模式下的授权token
@NameInMap("auth_token")
public String authToken;
@NameInMap("product_instance_id")
public String productInstanceId;
// 业务单号
@NameInMap("biz_id")
@Validation(required = true)
public String bizId;
// 链 ID
@NameInMap("chain_id")
@Validation(required = true)
public String chainId;
// 合约 ID
@NameInMap("contract_id")
@Validation(required = true)
public String contractId;
// 币种,目前仅支持 CNY
@NameInMap("currency")
@Validation(required = true)
public String currency;
// 调用方
@NameInMap("source")
@Validation(required = true)
public String source;
// 要兑现的用户VID
@NameInMap("target_user")
@Validation(required = true)
public String targetUser;
// Token总金额,token_price*token_number 的结果,单位为分
@NameInMap("token_amount")
@Validation(required = true)
public Long tokenAmount;
// 兑现的Token数目
@NameInMap("token_number")
@Validation(required = true)
public Long tokenNumber;
// 兑现的Token单价,单位为分
@NameInMap("token_price")
@Validation(required = true)
public Long tokenPrice;
public static ExecTokenRedeemRequest build(java.util.Map<String, ?> map) throws Exception {
ExecTokenRedeemRequest self = new ExecTokenRedeemRequest();
return TeaModel.build(map, self);
}
public ExecTokenRedeemRequest setAuthToken(String authToken) {
this.authToken = authToken;
return this;
}
public String getAuthToken() {
return this.authToken;
}
public ExecTokenRedeemRequest setProductInstanceId(String productInstanceId) {
this.productInstanceId = productInstanceId;
return this;
}
public String getProductInstanceId() {
return this.productInstanceId;
}
public ExecTokenRedeemRequest setBizId(String bizId) {
this.bizId = bizId;
return this;
}
public String getBizId() {
return this.bizId;
}
public ExecTokenRedeemRequest setChainId(String chainId) {
this.chainId = chainId;
return this;
}
public String getChainId() {
return this.chainId;
}
public ExecTokenRedeemRequest setContractId(String contractId) {
this.contractId = contractId;
return this;
}
public String getContractId() {
return this.contractId;
}
public ExecTokenRedeemRequest setCurrency(String currency) {
this.currency = currency;
return this;
}
public String getCurrency() {
return this.currency;
}
public ExecTokenRedeemRequest setSource(String source) {
this.source = source;
return this;
}
public String getSource() {
return this.source;
}
public ExecTokenRedeemRequest setTargetUser(String targetUser) {
this.targetUser = targetUser;
return this;
}
public String getTargetUser() {
return this.targetUser;
}
public ExecTokenRedeemRequest setTokenAmount(Long tokenAmount) {
this.tokenAmount = tokenAmount;
return this;
}
public Long getTokenAmount() {
return this.tokenAmount;
}
public ExecTokenRedeemRequest setTokenNumber(Long tokenNumber) {
this.tokenNumber = tokenNumber;
return this;
}
public Long getTokenNumber() {
return this.tokenNumber;
}
public ExecTokenRedeemRequest setTokenPrice(Long tokenPrice) {
this.tokenPrice = tokenPrice;
return this;
}
public Long getTokenPrice() {
return this.tokenPrice;
}
}
| 24.849673 | 95 | 0.657023 |
a11257b33cd07e0efd22b5818e7d93ec771755a5 | 3,721 | package ad.simple.library;
import android.app.DialogFragment;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.concurrent.ExecutionException;
/*
Created by pugman on 16.01.18.
Contact the developer - sckalper@gmail.com
company - A2Lab
*/
/**
* Created for displaying fullscreen advertising
*/
public class BannerView extends DialogFragment implements View.OnClickListener{
private static final String ARG_PACKAGE_NAME = "ad_package_name";
private String adUrl = null;
/**
*
* @param packageName on which to return ad's url
*/
public static BannerView newInstance(@NonNull String packageName){
Bundle args = new Bundle();
args.putString(ARG_PACKAGE_NAME, packageName);
BannerView fragment = new BannerView();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//attribute that makes the banner view full-screen
setStyle(STYLE_NO_FRAME, android.R.style.Theme_Holo_Light);
Bundle args = getArguments();
String packageName = args != null ? args.getString(ARG_PACKAGE_NAME) : "";
HttpGetRequest request = new HttpGetRequest();
try{
adUrl = request.execute(packageName).get();
} catch(InterruptedException e){
Log.e("RESULT", "Interrupted: " + e.getMessage());
} catch(ExecutionException e){
Log.e("RESULT", "Execution failed: " + e.getMessage());
}
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState){
//Banner view layout
FrameLayout contentView = new FrameLayout(getActivity());
//Create and init web view
WebView bannerView = new WebView(contentView.getContext());
FrameLayout.LayoutParams bannerLayoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT);
bannerView.setLayoutParams(bannerLayoutParams);
contentView.addView(bannerView);
//Create and init close icon
int closeIconSize = getActivity().getResources().getDimensionPixelOffset(R.dimen.bottomSheetPadding);
int margin = getActivity().getResources().getDimensionPixelOffset(R.dimen.activity_horizontal_margin);
ImageView closeBut = new ImageView(contentView.getContext());
FrameLayout.LayoutParams closeLayoutParams = new FrameLayout.LayoutParams(closeIconSize, closeIconSize);
closeLayoutParams.gravity = Gravity.END;
closeLayoutParams.topMargin = margin;
closeLayoutParams.rightMargin = margin;
closeBut.setLayoutParams(closeLayoutParams);
closeBut.setPadding(3, 3, 3, 3);
closeBut.setScaleType(ImageView.ScaleType.CENTER_CROP);
closeBut.setImageResource(R.drawable.ic_close);
closeBut.setOnClickListener(this);
contentView.addView(closeBut);
//Set up web view and start displaying url content
WebViewClient bannerClient = new WebViewClient();
bannerView.setWebViewClient(bannerClient);
if(adUrl == null) {
Log.e("BANNER_VIEW", "Url == null. Url cannot be loaded or was not initialized for requested package name");
Toast.makeText(getActivity(), "Cannot load advertising", Toast.LENGTH_SHORT).show();
dismiss();
} else{
bannerView.loadUrl(adUrl);
}
return contentView;
}
@Override
public void onClick(View v){
//Called when close icon pressed
dismiss();
}
}
| 33.827273 | 119 | 0.772373 |
34e194191af2d3bfbea7209e8044df7ec0be15d0 | 4,467 | package org.bian.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.bian.dto.SDBranchCurrencyDistributionRetrieveOutputModelBranchCurrencyDistributionOfferedServiceBranchCurrencyDistributionServiceRecordBranchCurrencyDistributionServicePoliciesandGuidelines;
import javax.validation.Valid;
/**
* SDBranchCurrencyDistributionRetrieveOutputModelBranchCurrencyDistributionOfferedServiceBranchCurrencyDistributionServiceRecord
*/
public class SDBranchCurrencyDistributionRetrieveOutputModelBranchCurrencyDistributionOfferedServiceBranchCurrencyDistributionServiceRecord {
private String branchCurrencyDistributionServiceType = null;
private String branchCurrencyDistributionServiceVersion = null;
private String branchCurrencyDistributionServiceDescription = null;
private SDBranchCurrencyDistributionRetrieveOutputModelBranchCurrencyDistributionOfferedServiceBranchCurrencyDistributionServiceRecordBranchCurrencyDistributionServicePoliciesandGuidelines branchCurrencyDistributionServicePoliciesandGuidelines = null;
private String branchCurrencyDistributionServiceSchedule = null;
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: Refers to the different types of services offered
* @return branchCurrencyDistributionServiceType
**/
public String getBranchCurrencyDistributionServiceType() {
return branchCurrencyDistributionServiceType;
}
public void setBranchCurrencyDistributionServiceType(String branchCurrencyDistributionServiceType) {
this.branchCurrencyDistributionServiceType = branchCurrencyDistributionServiceType;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: The version details of the service when appropriate
* @return branchCurrencyDistributionServiceVersion
**/
public String getBranchCurrencyDistributionServiceVersion() {
return branchCurrencyDistributionServiceVersion;
}
public void setBranchCurrencyDistributionServiceVersion(String branchCurrencyDistributionServiceVersion) {
this.branchCurrencyDistributionServiceVersion = branchCurrencyDistributionServiceVersion;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: Description of the offered service
* @return branchCurrencyDistributionServiceDescription
**/
public String getBranchCurrencyDistributionServiceDescription() {
return branchCurrencyDistributionServiceDescription;
}
public void setBranchCurrencyDistributionServiceDescription(String branchCurrencyDistributionServiceDescription) {
this.branchCurrencyDistributionServiceDescription = branchCurrencyDistributionServiceDescription;
}
/**
* Get branchCurrencyDistributionServicePoliciesandGuidelines
* @return branchCurrencyDistributionServicePoliciesandGuidelines
**/
public SDBranchCurrencyDistributionRetrieveOutputModelBranchCurrencyDistributionOfferedServiceBranchCurrencyDistributionServiceRecordBranchCurrencyDistributionServicePoliciesandGuidelines getBranchCurrencyDistributionServicePoliciesandGuidelines() {
return branchCurrencyDistributionServicePoliciesandGuidelines;
}
public void setBranchCurrencyDistributionServicePoliciesandGuidelines(SDBranchCurrencyDistributionRetrieveOutputModelBranchCurrencyDistributionOfferedServiceBranchCurrencyDistributionServiceRecordBranchCurrencyDistributionServicePoliciesandGuidelines branchCurrencyDistributionServicePoliciesandGuidelines) {
this.branchCurrencyDistributionServicePoliciesandGuidelines = branchCurrencyDistributionServicePoliciesandGuidelines;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: Schedule defining when the accessed service is available
* @return branchCurrencyDistributionServiceSchedule
**/
public String getBranchCurrencyDistributionServiceSchedule() {
return branchCurrencyDistributionServiceSchedule;
}
public void setBranchCurrencyDistributionServiceSchedule(String branchCurrencyDistributionServiceSchedule) {
this.branchCurrencyDistributionServiceSchedule = branchCurrencyDistributionServiceSchedule;
}
}
| 45.581633 | 310 | 0.860981 |
2b38ddf3a82bf98b5a4d83db9518fd331eea338d | 1,624 | package data.users_profile;
import com.wrapper.spotify.SpotifyApi;
import com.wrapper.spotify.exceptions.SpotifyWebApiException;
import com.wrapper.spotify.model_objects.specification.User;
import com.wrapper.spotify.requests.data.users_profile.GetUsersProfileRequest;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
public class GetUsersProfileExample {
private static final String accessToken = "taHZ2SdB-bPA3FsK3D7ZN5npZS47cMy-IEySVEGttOhXmqaVAIo0ESvTCLjLBifhHOHOIuhFUKPW1WMDP7w6dj3MAZdWT8CLI2MkZaXbYLTeoDvXesf2eeiLYPBGdx8tIwQJKgV8XdnzH_DONk";
private static final String userId = "user_id";
private static final SpotifyApi spotifyApi = new SpotifyApi.Builder()
.setAccessToken(accessToken)
.build();
private static final GetUsersProfileRequest getUsersProfileRequest = spotifyApi.getUsersProfile(userId)
.build();
public static void getUsersProfile_Sync() {
try {
final User user = getUsersProfileRequest.execute();
System.out.println("Display name: " + user.getDisplayName());
} catch (IOException | SpotifyWebApiException e) {
System.out.println("Error: " + e.getMessage());
}
}
public static void getUsersProfile_Async() {
try {
final Future<User> userFuture = getUsersProfileRequest.executeAsync();
// ...
final User user = userFuture.get();
System.out.println("Display name: " + user.getDisplayName());
} catch (InterruptedException | ExecutionException e) {
System.out.println("Error: " + e.getCause().getMessage());
}
}
} | 36.088889 | 193 | 0.748768 |
59e0cfef4c5aaaba02c1b85e5bcb163cdc1d53c2 | 3,603 | package com.codepath.apps.restclienttemplate;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.fragment.app.DialogFragment;
/**
* A simple {@link Fragment} subclass.
* Use the {@link ComposeFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class ComposeFragment extends DialogFragment implements TextView.OnEditorActionListener {
public static final String TAG = "ComposeActivity";
public static final int MAX_TWEET_LENGTH = 140;
EditText etCompose;
Button btnTweet;
TextView etCharCount;
TwitterClient client;
// 1. Defines the listener interface with a method passing back data result.
public interface EditNameDialogListener {
void onFinishEditDialog(String inputText);
}
public ComposeFragment() {
// Required empty public constructor
// Empty constructor is required for DialogFragment
// Make sure not to add arguments to the constructor
// Use `newInstance` instead as shown below
}
public static ComposeFragment newInstance(String title) {
ComposeFragment fragment = new ComposeFragment();
Bundle args = new Bundle();
args.putString("title", title);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_compose, container);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Get field from view
etCompose = (EditText) view.findViewById(R.id.etCompose);
// btnTweet = view.findViewById(R.id.btnTweet);
// etCharCount = view.findViewById(R.id.etCharCount);
// Fetch arguments from bundle and set title
String title = getArguments().getString("title", "Enter Name");
getDialog().setTitle(title);
// Show soft keyboard automatically and request focus to field
etCompose.requestFocus();
getDialog().getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
// 2. Setup a callback when the "Done" button is pressed on keyboard
etCompose.setOnEditorActionListener(this);
}
// Fires whenever the textfield has an action performed
// In this case, when the "Done" button is pressed
// REQUIRES a 'soft keyboard' (virtual keyboard)
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (EditorInfo.IME_ACTION_DONE == actionId) {
// Return input text back to activity through the implemented listener
EditNameDialogListener listener = (EditNameDialogListener) getActivity();
listener.onFinishEditDialog(etCompose.getText().toString());
// Close the dialog and return back to the parent activity
dismiss();
return true;
}
return false;
}
} | 36.765306 | 96 | 0.70247 |
451a70510ec8a19f2d1147db1efb2f52bab39a2e | 1,394 | package edu.internet2.middleware.grouper.changeLog.consumer.model;
import com.squareup.moshi.Json;
import java.util.List;
import java.util.Objects;
public class GroupsOdata {
@Json(name = "@odata.context") public final String context;
@Json(name = "value") public final List<Group> groups;
@Json(name="@odata.nextLink") public String nextPage;
public GroupsOdata(String context, List<Group> groups) {
this.context = context;
this.groups = groups;
}
public GroupsOdata(String context, List<Group> groups, String nextPage) {
this.context = context;
this.groups = groups;
this.nextPage = nextPage;
}
@Override
public String toString() {
return "GroupsOdata{" +
"context='" + context + '\'' +
", groups=" + groups +
", nextPage='" + nextPage + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
GroupsOdata that = (GroupsOdata) o;
return Objects.equals(context, that.context) &&
Objects.equals(groups, that.groups) &&
Objects.equals(nextPage, that.nextPage);
}
@Override
public int hashCode() {
return Objects.hash(context, groups, nextPage);
}
}
| 29.041667 | 77 | 0.590387 |
eaf5a5a7f68ac5b1db3691470d3f5814f0cd57ea | 4,931 | /*
* 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.olingo.commons.core.edm;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.olingo.commons.api.edm.Edm;
import org.apache.olingo.commons.api.edm.EdmBindingTarget;
import org.apache.olingo.commons.api.edm.EdmEntitySet;
import org.apache.olingo.commons.api.edm.EdmException;
import org.apache.olingo.commons.api.edm.EdmOperation;
import org.apache.olingo.commons.api.edm.EdmParameter;
import org.apache.olingo.commons.api.edm.EdmReturnType;
import org.apache.olingo.commons.api.edm.FullQualifiedName;
import org.apache.olingo.commons.api.edm.constants.EdmTypeKind;
import org.apache.olingo.commons.api.edm.provider.CsdlOperation;
import org.apache.olingo.commons.api.edm.provider.CsdlParameter;
public abstract class AbstractEdmOperation extends EdmTypeImpl implements EdmOperation {
private final CsdlOperation operation;
private Map<String, EdmParameter> parameters;
private List<String> parameterNames;
private EdmReturnType returnType;
protected AbstractEdmOperation(final Edm edm, final FullQualifiedName name, final CsdlOperation operation,
final EdmTypeKind kind) {
super(edm, name, kind, operation);
this.operation = operation;
}
@Override
public EdmParameter getParameter(final String name) {
if (parameters == null) {
createParameters();
}
return parameters.get(name);
}
@Override
public List<String> getParameterNames() {
if (parameterNames == null) {
createParameters();
}
return Collections.unmodifiableList(parameterNames);
}
private void createParameters() {
if (parameters == null) {
final Map<String, EdmParameter> parametersLocal = new LinkedHashMap<String, EdmParameter>();
final List<CsdlParameter> providerParameters = operation.getParameters();
if (providerParameters != null) {
final List<String> parameterNamesLocal = new ArrayList<String>(providerParameters.size());
for (CsdlParameter parameter : providerParameters) {
parametersLocal.put(parameter.getName(), new EdmParameterImpl(edm, parameter));
parameterNamesLocal.add(parameter.getName());
}
parameters = parametersLocal;
parameterNames = parameterNamesLocal;
} else {
parameterNames = Collections.emptyList();
}
}
}
@Override
public EdmEntitySet getReturnedEntitySet(final EdmEntitySet bindingParameterEntitySet) {
EdmEntitySet returnedEntitySet = null;
if (bindingParameterEntitySet != null && operation.getEntitySetPath() != null) {
final EdmBindingTarget relatedBindingTarget =
bindingParameterEntitySet.getRelatedBindingTarget(operation.getEntitySetPath());
if (relatedBindingTarget == null) {
throw new EdmException("Cannot find entity set with path: " + operation.getEntitySetPath());
}
if (relatedBindingTarget instanceof EdmEntitySet) {
returnedEntitySet = (EdmEntitySet) relatedBindingTarget;
} else {
throw new EdmException("BindingTarget with name: " + relatedBindingTarget.getName()
+ " must be an entity set");
}
}
return returnedEntitySet;
}
@Override
public EdmReturnType getReturnType() {
if (returnType == null && operation.getReturnType() != null) {
returnType = new EdmReturnTypeImpl(edm, operation.getReturnType());
}
return returnType;
}
@Override
public boolean isBound() {
return operation.isBound();
}
@Override
public FullQualifiedName getBindingParameterTypeFqn() {
if (isBound()) {
CsdlParameter bindingParameter = operation.getParameters().get(0);
return bindingParameter.getTypeFQN();
}
return null;
}
@Override
public Boolean isBindingParameterTypeCollection() {
if (isBound()) {
CsdlParameter bindingParameter = operation.getParameters().get(0);
return bindingParameter.isCollection();
}
return null;
}
@Override
public String getEntitySetPath() {
return operation.getEntitySetPath();
}
}
| 34.482517 | 108 | 0.730481 |
67be724f24b15993965ac11e800c9087d56f0a38 | 771 | /*
* Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.types;
/**
* General purpose interface, useful for extending. Defines methods to get object
* name and description. This version is useful for objects providing a fixed, implementation defined
* name and description. In future the description type should be changed to {@link I18nString} so that a
* localized value is returned, however the intention is that the description returned by this
* interface is aimed at admin only.
*
* @author K. Benedyczak
*/
public interface DescribedObject extends NamedObject
{
/**
* @return human readable description of the object.
*/
String getDescription();
}
| 33.521739 | 106 | 0.753567 |
800602f237ebf67824e322af34357b46eba5b4bd | 21,990 | package com.imarcats.market.management;
import java.util.Date;
import com.imarcats.interfaces.client.v100.dto.MarketOperatorDto;
import com.imarcats.interfaces.client.v100.exception.ExceptionLanguageKeys;
import com.imarcats.interfaces.client.v100.exception.MarketRuntimeException;
import com.imarcats.internal.server.infrastructure.testutils.MockDatastoresBase;
import com.imarcats.internal.server.interfaces.market.MarketInternal;
import com.imarcats.market.management.admin.MarketManagementAdminSystem;
import com.imarcats.market.management.admin.MarketOperatorAdminstrationSubSystem;
import com.imarcats.model.Market;
import com.imarcats.model.MarketOperator;
import com.imarcats.model.types.ActivationStatus;
import com.imarcats.model.types.AuditEntryAction;
public class MarketOperatorAdminstrationSubSystemTest extends ManagementTestBase {
public void testCreate() throws Exception {
MockDatastoresBase datastores = createDatastores();
MarketManagementAdminSystem adminSystem =
new MarketManagementAdminSystem(datastores, datastores, datastores, datastores, datastores, datastores, datastores, null);
String businessEntityCode = "TEST_BE";
// test create market operator
String mktOptCode1 = "MYTESTKKTOPT";
MarketOperatorDto mktOpt1 = createMarketOperator1(mktOptCode1);
mktOpt1.setBusinessEntityCode(businessEntityCode);
String ownerUserID = "ownerUserID";
mktOpt1.setOwnerUserID(ownerUserID);
String user = "test";
// successful creation
testCreateMarketOperator(mktOpt1, adminSystem, user);
checkAuditTrail(AuditEntryAction.Created, user, mktOptCode1, MarketOperator.class.getSimpleName(), adminSystem);
// check market operator
MarketOperator mktOpt1Loaded = datastores.findMarketOperatorByCode(mktOptCode1);
assertEquals(mktOptCode1, mktOpt1Loaded.getCode());
assertEquals(ownerUserID, mktOpt1Loaded.getOwnerUserID());
assertEquals(ActivationStatus.Created, mktOpt1Loaded.getActivationStatus());
assertEquals(user, mktOpt1Loaded.getCreationAudit().getUserID());
}
private void testCreateMarketOperator(MarketOperatorDto mktOpt,
MarketManagementAdminSystem adminSystem,
String user) {
openTransaction();
adminSystem.createMarketOperator(mktOpt, user);
commitTransaction();
}
public void testChange() throws Exception {
MockDatastoresBase datastores = createDatastores();
MarketManagementAdminSystem adminSystem =
new MarketManagementAdminSystem(datastores, datastores, datastores, datastores, datastores, datastores, datastores, null);
String user = "test";
String businessEntityCode = "TEST_BE";
// test create market operator
String mktOptCode1 = "MYTESTKKTOPT";
MarketOperatorDto mktOpt1 = createMarketOperator1(mktOptCode1);
mktOpt1.setLastUpdateTimestamp(new Date());
mktOpt1.setActivationStatus(com.imarcats.interfaces.client.v100.dto.types.ActivationStatus.Created);
mktOpt1.setBusinessEntityCode(businessEntityCode);
createMarketOperatorInDatastore(mktOpt1, datastores);
// test change market operator
MarketOperatorDto mktOpt1Changed = createMarketOperator1(mktOptCode1);
mktOpt1Changed.setDescription("New Descrition");
mktOpt1Changed.setBusinessEntityCode("BOGUS");
mktOpt1Changed.setLastUpdateTimestamp(new Date());
// change approved market operator
setMarketOperatorToApproved(mktOptCode1, datastores);
// recreate MarketOperator to get a later version
mktOpt1Changed = createMarketOperator1(mktOptCode1);
mktOpt1Changed.setDescription(mktOpt1Changed.getDescription());
mktOpt1Changed.setBusinessEntityCode("IMARCATS");
mktOpt1Changed.setLastUpdateTimestamp(new Date());
// recreate MarketOperator to get a later version
mktOpt1Changed = createMarketOperator1(mktOptCode1);
mktOpt1Changed.setDescription(mktOpt1Changed.getDescription());
mktOpt1Changed.setBusinessEntityCode("BOGUS");
mktOpt1Changed.setLastUpdateTimestamp(new Date());
mktOpt1Changed.setBusinessEntityCode(businessEntityCode);
String ownerUserID = "ownerUserID1";
mktOpt1Changed.setOwnerUserID(ownerUserID);
// non-existent market operator
mktOpt1Changed.setCode(mktOptCode1 + "1");
try {
testChangeMarketOperator(mktOpt1Changed, adminSystem,
user);
fail();
} catch (MarketRuntimeException e) {
assertEquals(ExceptionLanguageKeys.NON_EXISTENT_MARKET_OPERATOR, e.getLanguageKey());
} finally {
commitTransaction();
}
mktOpt1Changed.setCode(mktOptCode1);
// approved
try {
testChangeMarketOperator(mktOpt1Changed, adminSystem,
user);
fail();
} catch (MarketRuntimeException e) {
assertEquals(ExceptionLanguageKeys.MARKET_OPERATOR_ONLY_IN_CREATED_OR_SUSPEDED_STATE_CAN_BE_CHANGED, e.getLanguageKey());
} finally {
commitTransaction();
}
setMarketOperatorToSuspended(mktOptCode1, datastores);
// recreate MarketOperator to get a later version
MarketOperator mktOpt1Loaded = datastores.findMarketOperatorByCode(mktOptCode1);
mktOpt1Changed = createMarketOperator1(mktOptCode1);
mktOpt1Changed.setDescription(mktOpt1Changed.getDescription());
mktOpt1Changed.setBusinessEntityCode(businessEntityCode);
mktOpt1Changed.setOwnerUserID(ownerUserID);
mktOpt1Changed.setLastUpdateTimestamp(new Date());
mktOpt1Changed.setVersionNumber(mktOpt1Loaded.getVersionNumber());
// make sure that audit entries are far apart enough
Thread.sleep(1000);
// successful change
testChangeMarketOperator(mktOpt1Changed, adminSystem, user);
checkAuditTrail(AuditEntryAction.Changed, user, mktOptCode1, MarketOperator.class.getSimpleName(), adminSystem);
// check change of market operator
mktOpt1Loaded = datastores.findMarketOperatorByCode(mktOptCode1);
assertEquals(mktOptCode1, mktOpt1Loaded.getCode());
assertEquals(mktOpt1Changed.getDescription(), mktOpt1Loaded.getDescription());
assertEquals(ActivationStatus.Suspended, mktOpt1Loaded.getActivationStatus());
assertEquals(user, mktOpt1Loaded.getChangeAudit().getUserID());
setMarketOperatorToSuspended(mktOptCode1, datastores);
// recreate MarketOperator to get a later version
mktOpt1Changed = createMarketOperator1(mktOptCode1);
mktOpt1Changed.setDescription(mktOpt1Changed.getDescription());
mktOpt1Changed.setBusinessEntityCode(businessEntityCode);
mktOpt1Changed.setOwnerUserID(ownerUserID);
mktOpt1Changed.setLastUpdateTimestamp(new Date());
mktOpt1Changed.setVersionNumber(mktOpt1Loaded.getVersionNumber());
Thread.sleep(1000);
// successful change
testChangeMarketOperator(mktOpt1Changed, adminSystem, user);
// overwrite with older version
openTransaction();
datastores.findMarketOperatorByCode(mktOpt1Changed.getCode()).setDescription("Test Decr");
commitTransaction();
try {
testChangeMarketOperator(mktOpt1Changed, adminSystem,
user);
fail();
} catch (MarketRuntimeException e) {
assertEquals(ExceptionLanguageKeys.MARKET_OPERATOR_CANNOT_BE_OVERWRITTEN_WITH_AN_OLDER_VERSION, e.getLanguageKey());
} finally {
commitTransaction();
}
}
private void testChangeMarketOperator(MarketOperatorDto mktOptChanged,
MarketManagementAdminSystem adminSystem,
String user) {
openTransaction();
adminSystem.changeMarketOperator(mktOptChanged, user);
commitTransaction();
}
public void testSetMarketOperatorMasterAgreementDocument() throws Exception {
MockDatastoresBase datastores = createDatastores();
MarketManagementAdminSystem adminSystem =
new MarketManagementAdminSystem(datastores, datastores, datastores, datastores, datastores, datastores, datastores, null);
String businessEntityCode = "TestBusinessEntity";
String user = "test";
// test create market operator
String mktOptCode1 = "MYTESTKKTOPT";
MarketOperatorDto mktOpt1 = createMarketOperator1(mktOptCode1);
mktOpt1.setActivationStatus(com.imarcats.interfaces.client.v100.dto.types.ActivationStatus.Created);
mktOpt1.setBusinessEntityCode(businessEntityCode);
mktOpt1.setLastUpdateTimestamp(new Date());
createMarketOperatorInDatastore(mktOpt1, datastores);
// test set market operator agreement document
String mktOptAgreementDocument = "My Mkt Opt Agreement Documement";
// non-existent market operator
try {
adminSystem.setMarketOperatorMasterAgreementDocument("BOGUS", mktOptAgreementDocument, user);
fail();
} catch (MarketRuntimeException e) {
assertEquals(ExceptionLanguageKeys.NON_EXISTENT_MARKET_OPERATOR, e.getLanguageKey());
}
testSetMarketOperationDocument(mktOptCode1, mktOptAgreementDocument,
adminSystem, user);
checkAuditTrail(AuditEntryAction.Changed, user, mktOptCode1, MarketOperator.class.getSimpleName(), adminSystem);
// check market operator agreement set
MarketOperator mktOpt1Loaded = datastores.findMarketOperatorByCode(mktOptCode1);
assertEquals(mktOptCode1, mktOpt1Loaded.getCode());
assertEquals(mktOptAgreementDocument, mktOpt1Loaded.getMarketOperatorAgreement());
setMarketOperatorToApproved(mktOptCode1, datastores);
// try changing agreement document
try {
adminSystem.setMarketOperatorMasterAgreementDocument(mktOptCode1, "New Document", user);
fail();
} catch (MarketRuntimeException e) {
assertEquals(ExceptionLanguageKeys.MARKET_OPERATOR_ONLY_IN_CREATED_OR_SUSPEDED_STATE_CAN_BE_CHANGED, e.getLanguageKey());
}
setMarketOperatorToSuspended(mktOptCode1, datastores);
// successful change - suspended
testSetMarketOperationDocument(mktOptCode1, "New Document", adminSystem, user);
setMarketOperatorToCreated(mktOptCode1, datastores);
// successful change - created
testSetMarketOperationDocument(mktOptCode1, "New Document", adminSystem, user);
}
private void testSetMarketOperationDocument(String mktOptCode,
String mktOptAgreementDocument,
MarketManagementAdminSystem adminSystem,
String user) {
openTransaction();
adminSystem.setMarketOperatorMasterAgreementDocument(mktOptCode, mktOptAgreementDocument, user);
commitTransaction();
}
@SuppressWarnings("deprecation")
public void testApproveSuspend() throws Exception {
MockDatastoresBase datastores = createDatastores();
MarketManagementAdminSystem adminSystem =
new MarketManagementAdminSystem(datastores, datastores, datastores, datastores, datastores, datastores, datastores, null);
String businessEntityCode = "TBE";
String ownerUserID = "ownerUserID";
String user = "test";
// test create market operator
String mktOptCode1 = "MYTESTKKTOPT";
MarketOperatorDto mktOpt1 = createMarketOperator1(mktOptCode1);
mktOpt1.setActivationStatus(com.imarcats.interfaces.client.v100.dto.types.ActivationStatus.Created);
mktOpt1.setBusinessEntityCode(businessEntityCode);
mktOpt1.setOwnerUserID(ownerUserID);
mktOpt1.setLastUpdateTimestamp(new Date());
createMarketOperatorInDatastore(mktOpt1, datastores);
// no market operator agreement
try {
testApprove(user, adminSystem, mktOptCode1);
fail();
} catch (MarketRuntimeException e) {
assertEquals(ExceptionLanguageKeys.MARKET_OPERATOR_MUST_HAVE_MARKET_OPERATOR_AGREEMENT_DOCUMENT, e.getLanguageKey());
} finally {
commitTransaction();
}
openTransaction();
datastores.findMarketOperatorByCode(mktOptCode1).setMarketOperatorAgreement("Test");
commitTransaction();
// non-existent market operator
try {
adminSystem.approveMarketOperator("BOGUS", new Date(), user);
fail();
} catch (MarketRuntimeException e) {
assertEquals(ExceptionLanguageKeys.NON_EXISTENT_MARKET_OPERATOR, e.getLanguageKey());
}
// stale object
try {
Date lastUpdateTimestamp = new Date();
lastUpdateTimestamp.setMinutes(lastUpdateTimestamp.getMinutes() - 10);
adminSystem.approveMarketOperator(mktOptCode1, lastUpdateTimestamp, user);
fail();
} catch (MarketRuntimeException e) {
assertEquals(ExceptionLanguageKeys.STALE_OBJECT_CANNOT_BE_APPROVED, e.getLanguageKey());
}
// successful approval
testApprove(user, adminSystem, mktOptCode1);
checkAuditTrail(AuditEntryAction.Approved, user, mktOptCode1, MarketOperator.class.getSimpleName(), adminSystem);
// check market operator approval
MarketOperator mktOpt1Loaded = datastores.findMarketOperatorByCode(mktOptCode1);
assertEquals(mktOptCode1, mktOpt1Loaded.getCode());
assertEquals(ActivationStatus.Approved, mktOpt1Loaded.getActivationStatus());
assertEquals(user, mktOpt1Loaded.getApprovalAudit().getUserID());
// try approving again
try {
testApprove(user, adminSystem, mktOptCode1);
fail();
} catch (MarketRuntimeException e) {
assertEquals(ExceptionLanguageKeys.MARKET_OPERATOR_ONLY_IN_CREATED_OR_SUSPEDED_STATE_CAN_BE_APPROVED, e.getLanguageKey());
} finally {
commitTransaction();
}
// add dependent market
String marketCode = "TestMarketCode";
Market market = createMarket(marketCode);
market.setMarketOperatorCode(mktOptCode1);
market.setActivationStatus(ActivationStatus.Activated);
createMarketInDatastore(market, datastores);
// dependent market
try {
testSuspend(mktOptCode1, adminSystem, user);
fail();
} catch (MarketRuntimeException e) {
assertEquals(ExceptionLanguageKeys.MARKET_OPERATOR_CAN_ONLY_BE_SUSPENDED_IF_DEPENDENT_OBJECTS_ARE_SUSPENDED, e.getLanguageKey());
} finally {
commitTransaction();
}
// suspend market
setMarketToSuspended(marketCode, datastores);
setMarketOperatorToSuspended(mktOptCode1, datastores);
// not approved
try {
testSuspend(mktOptCode1, adminSystem, user);
fail();
} catch (MarketRuntimeException e) {
assertEquals(ExceptionLanguageKeys.MARKET_OPERATOR_NOT_IN_CREATED_OR_SUSPEDED_STATE_CAN_BE_SUSPENDED, e.getLanguageKey());
} finally {
commitTransaction();
}
setMarketOperatorToApproved(mktOptCode1, datastores);
// successful suspend
testSuspend(mktOptCode1, adminSystem, user);
// somehow this does not work in GAE tests
// pm = saveToDatastore(pm);
//
// checkAuditTrail(AuditEntryAction.Suspended, approverUserSession.getUserName(), marketOperatorCode1, MarketOperator.class.getSimpleName(), adminSystem);
// pm = saveToDatastore(pm);
// check market operator after suspend
mktOpt1Loaded = datastores.findMarketOperatorByCode(mktOptCode1);
assertEquals(mktOptCode1, mktOpt1Loaded.getCode());
assertEquals(ActivationStatus.Suspended, mktOpt1Loaded.getActivationStatus());
assertEquals(user, mktOpt1Loaded.getSuspensionAudit().getUserID());
}
private void testSuspend(String mktOptCode,
MarketManagementAdminSystem adminSystem,
String user) {
openTransaction();
adminSystem.suspendMarketOperator(mktOptCode, user);
commitTransaction();
}
private void testApprove(
String user,
MarketManagementAdminSystem adminSystem, String mktOptCode1) {
openTransaction();
adminSystem.approveMarketOperator(mktOptCode1, new Date(), user);
commitTransaction();
}
public void testDelete() throws Exception {
MockDatastoresBase datastores = createDatastores();
MarketManagementAdminSystem adminSystem =
new MarketManagementAdminSystem(datastores, datastores, datastores, datastores, datastores, datastores, datastores, null);
String businessEntityCode = "TestBusinessEntity";
String user = "test";
// test create market operator
String mktOptCode1 = "MYTESTKKTOPT";
MarketOperatorDto mktOpt1 = createMarketOperator1(mktOptCode1);
mktOpt1.setActivationStatus(com.imarcats.interfaces.client.v100.dto.types.ActivationStatus.Created);
mktOpt1.setBusinessEntityCode(businessEntityCode);
mktOpt1.setLastUpdateTimestamp(new Date());
createMarketOperatorInDatastore(mktOpt1, datastores);
MarketManagementContextImpl context = createMarketManagementContext();
setMarketOperatorToApproved(mktOptCode1, datastores);
context = createMarketManagementContext();
// make sure that audit entries are far apart enough
Thread.sleep(1000);
// approved market operator
try {
testDelete(mktOptCode1, adminSystem, user, context);
fail();
} catch (MarketRuntimeException e) {
assertEquals(ExceptionLanguageKeys.MARKET_OPERATOR_ONLY_IN_CREATED_OR_SUSPEDED_STATE_CAN_BE_DELETED, e.getLanguageKey());
} finally {
commitTransaction();
}
setMarketOperatorToSuspended(mktOptCode1, datastores);
// add dependent market
String marketCode = "TestMarketCode";
Market market = createMarket(marketCode);
market.setMarketOperatorCode(mktOptCode1);
market.setActivationStatus(ActivationStatus.Activated);
createMarketInDatastore(market, datastores);
// dependent market
try {
testDelete(mktOptCode1, adminSystem, user, context);
fail();
} catch (MarketRuntimeException e) {
assertEquals(ExceptionLanguageKeys.MARKET_OPERATOR_THAT_HAS_NO_DEPENDENT_MARKET_CAN_BE_DELETED, e.getLanguageKey());
} finally {
commitTransaction();
}
// remove dependency on market operator
openTransaction();
MarketInternal marketInternal = datastores.findMarketBy(marketCode);
marketInternal.getMarketModel().setMarketOperatorCode("BOGUS");
commitTransaction();
// make sure that audit entries are far apart enough
Thread.sleep(1000);
// successful delete
testDelete(mktOptCode1, adminSystem, user, context);
// check mkt opt after delete
Object mktOpt1Loaded = datastores.findMarketOperatorByCode(mktOptCode1);
assertEquals(null, mktOpt1Loaded);
checkAuditTrailForDeleteObject(user, mktOptCode1, MarketOperator.class.getSimpleName(), adminSystem);
}
private void testDelete(String mktOptCode,
MarketManagementAdminSystem adminSystem, String user,
MarketManagementContextImpl context) {
openTransaction();
adminSystem.deleteMarketOperator(mktOptCode, user, context);
commitTransaction();
}
public void testSetupChangedMarketOperator() throws Exception {
MarketOperator marketOperatorProduct = new MarketOperator();
// reset system fields - as they will not be copied
marketOperatorProduct.setActivationStatus(com.imarcats.model.types.ActivationStatus.Activated);
marketOperatorProduct.setMarketOperatorAgreement("testDef");
marketOperatorProduct.setCreationAudit(createAudit());
marketOperatorProduct.setChangeAudit(createAudit());
marketOperatorProduct.setApprovalAudit(createAudit());
marketOperatorProduct.setSuspensionAudit(createAudit());
MarketOperator newMarketOperator = new MarketOperator();
MarketOperatorAdminstrationSubSystem.setupChangedMarketOperator(marketOperatorProduct, newMarketOperator);
assertEqualsMarketOperator(marketOperatorProduct, newMarketOperator);
}
public void testLoadAndChange() throws Exception {
MockDatastoresBase datastores = createDatastores();
MarketManagementAdminSystem adminSystem =
new MarketManagementAdminSystem(datastores, datastores, datastores, datastores, datastores, datastores, datastores, null);
String user = "test";
// create market operator
String mktOptCode1 = "TEST_MKT_OPT";
MarketOperatorDto mktOpt1 = createMarketOperator1(mktOptCode1);
String businessEntityCode = "TEST_BE";
mktOpt1.setBusinessEntityCode(businessEntityCode);
mktOpt1.setOwnerUserID(user);
mktOpt1.setLastUpdateTimestamp(new Date());
mktOpt1.setActivationStatus(com.imarcats.interfaces.client.v100.dto.types.ActivationStatus.Created);
mktOpt1.setActivationStatus(com.imarcats.interfaces.client.v100.dto.types.ActivationStatus.Created);
createMarketOperatorInDatastore(mktOpt1, datastores);
// market operator code will be capitalized
mktOptCode1 = mktOptCode1.toUpperCase();
// load market operator
MarketOperator marketOperatorToBeChanged = datastores.findMarketOperatorByCode(mktOptCode1);
marketOperatorToBeChanged.setDescription("New Descr");
String manipulatorUser = "testManipulator";
// change market operator
marketOperatorToBeChanged.setOwnerUserID(manipulatorUser);
testChange(marketOperatorToBeChanged, adminSystem, user);
// test changed
MarketOperator mktOpt1Loaded = datastores.findMarketOperatorByCode(mktOptCode1);
assertEquals(mktOptCode1, mktOpt1Loaded.getCode());
assertEquals(marketOperatorToBeChanged.getDescription(), mktOpt1Loaded.getDescription());
// assertEqualsBusinessEntity(marketOperatorToBeChanged.getBusinessEntity(), mktOpt1Loaded.getBusinessEntity());
}
private void testChange(MarketOperator marketOperatorToBeChanged,
MarketManagementAdminSystem adminSystem, String user) {
openTransaction();
adminSystem.changeMarketOperator(marketOperatorToDto(marketOperatorToBeChanged), user);
commitTransaction();
}
}
| 38.989362 | 159 | 0.742383 |
acebd01cf86e82e6319d3ec0f6c683d701c18bf3 | 1,871 | /*
* Copyright (c) Huawei Technologies Co., Ltd. 2020-2021. All rights reserved.
*/
package com.lubanops.stresstest.redis.jedis;
import com.huawei.apm.core.agent.common.BeforeResult;
import com.huawei.apm.core.agent.interceptor.InstanceMethodInterceptor;
import com.huawei.apm.core.lubanops.bootstrap.log.LogFactory;
import com.lubanops.stresstest.config.ConfigFactory;
import com.lubanops.stresstest.core.Reflection;
import com.lubanops.stresstest.core.Tester;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.logging.Logger;
/**
* Jedis pool 拦截器,返回影子redis 连接。
*
* @author yiwei
* @since 2021/10/21
*/
public class JedisPoolInterceptor implements InstanceMethodInterceptor {
private static final Logger LOGGER = LogFactory.getLogger();
@Override
public void before(Object obj, Method method, Object[] arguments, BeforeResult beforeResult) {
}
@Override
public Object after(Object obj, Method method, Object[] arguments, Object result) {
if (!Tester.isTest() || !ConfigFactory.getConfig().isRedisShadowRepositories()) {
return result;
}
if (ShadowJedisFactory.getInstance().isShadowClient(result)) {
return result;
}
Object shadowPool = ShadowJedisFactory.getInstance().getShadowPool(obj);
if (shadowPool == null) {
return result;
}
try {
Object shadowJedis = method.invoke(shadowPool);
Reflection.invokeDeclared("close", result);
return shadowJedis;
} catch (IllegalAccessException | InvocationTargetException e) {
LOGGER.severe("Cannot new shadow jedis from pool.");
}
return result;
}
@Override
public void onThrow(Object obj, Method method, Object[] arguments, Throwable throwable) {
}
}
| 32.824561 | 98 | 0.695885 |
3d54d042f228bd1b6fbf8edb6832238d44528193 | 3,410 | /*
* Copyright 2017 - 2018 The ModiTect 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.moditect.model;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
* A pattern for matching dependences (requires directives). Any matching
* dependence will be amended with the pattern's modifiers or it will be
* excluded, if the pattern isn't inclusive.
*
* @author Gunnar Morling
*/
public class DependencePattern {
private static final Pattern PATTERN = Pattern.compile( "((.*)\\s+)?(.*?)" );
private final boolean inclusive;
private final Pattern pattern;
private final Set<String> modifiers;
public static List<DependencePattern> parsePatterns(String patterns) {
if ( patterns == null ) {
return Collections.emptyList();
}
return Arrays.stream( patterns.trim().split(";") )
.map( DependencePattern::parsePattern )
.collect( Collectors.toList() );
}
public static DependencePattern parsePattern(String pattern) {
pattern = pattern.trim();
Matcher matcher = PATTERN.matcher( pattern );
if ( !matcher.matches() ) {
throw new IllegalArgumentException( "Invalid dependence pattern: " + pattern );
}
else {
if ( matcher.group( 3 ) != null ) {
return new DependencePattern( matcher.group( 3 ), matcher.group( 2 ) );
}
else {
return new DependencePattern( matcher.group( 2 ), null );
}
}
}
private DependencePattern(String pattern, String modifiers) {
if (pattern.startsWith("!")) {
pattern = pattern.substring(1);
this.inclusive = false;
}
else {
this.inclusive = true;
}
this.pattern = Pattern.compile( pattern.replace( ".", "\\." ).replace( "*", ".*" ) );
if ( modifiers == null ) {
this.modifiers = Collections.emptySet();
}
else {
this.modifiers = Arrays.stream( modifiers.split( "\\s" ) )
.map( String::trim )
.collect( Collectors.toSet() );
}
}
public boolean matches(String packageName ) {
return pattern.matcher( packageName ).matches();
}
public Pattern getPattern() {
return pattern;
}
public Set<String> getModifiers() {
return modifiers;
}
public boolean isMatchAll() {
return ".*".equals( pattern.pattern() );
}
public boolean isInclusive() {
return inclusive;
}
@Override
public String toString() {
return "DependencePattern[pattern=" + pattern + ",modifiers=" + modifiers + "]";
}
}
| 29.912281 | 93 | 0.613196 |
a112b62f827c8b614812fd1b9bb945cf648bd5d3 | 1,683 | package com.pelleplutt.operandi.proc;
import java.util.Map;
import com.pelleplutt.operandi.proc.Processor.M;
public class MMapRef implements MSet {
Map<Object, String> jm;
public MMapRef(Map<Object, String> jm) {
this.jm = jm;
}
@Override
public int size() {
return jm.size();
}
@Override
public void add(M m) {
MSet tuple = (MSet)m.ref;
jm.put(tuple.get(0).getRaw(), tuple.get(1).asString());
}
@Override
public void insert(int ix, M m) {
}
@Override
public void set(M mix, M m) {
jm.put(mix.getRaw(), m.asString());
}
@Override
public void put(Object key, M m) {
jm.put(key, m.asString());
}
@Override
public M get(M m) {
return new M(jm.get(m.getRaw()));
}
@Override
public M get(int ix) {
return getElement(ix);
}
@Override
public void remove(M m) {
jm.remove(m.getRaw());
}
@Override
public M getElement(int ix) {
Object keys[] = jm.keySet().toArray();
if (ix < 0) ix = keys.length + ix;
Object key = keys[ix];
if (jm.get(key) == null) return null;
M mval = new M(jm.get(key));
MListMap res = new MListMap();
res.makeTup();
res.tup[0] = new M(key);
res.tup[1] = mval;
M mres = new M();
mres.type = Processor.TSET;
mres.ref = res;
return mres;
}
@Override
public int getType() {
return TMAP;
}
@Override
public MSet copyShallow() {
MListMap ml = new MListMap();
int len = size();
ml.makeMap();
Object keys[] = jm.keySet().toArray();
for (int i = 0; i < len; i++) {
ml.map.put(keys[i], new M().copy(new M(jm.get(keys[i]))));
}
ml.type = getType();
return ml;
}
}
| 18.910112 | 64 | 0.579323 |
5944599005166b82c81ad1a2f61157d87547d86f | 309 | package latmod.lib.annotations;
import java.lang.annotation.*;
/**
* Created by LatvianModder on 26.03.2016.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface NumberBounds
{
double min() default Double.NEGATIVE_INFINITY;
double max() default Double.POSITIVE_INFINITY;
} | 22.071429 | 47 | 0.779935 |
e58510475e27bbbd72576336026ed81dc05c28ec | 1,313 | package com.platypii.baseline.lasers;
import com.platypii.baseline.events.ProfileLayerEvent;
import com.platypii.baseline.views.charts.layers.ProfileLayer;
import androidx.annotation.NonNull;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.greenrobot.eventbus.EventBus;
/**
* Class to maintain the list of currently selected laser profile layers
* TODO: Persist
*/
public class LaserLayers {
@NonNull
public final List<ProfileLayer> layers = new ArrayList<>();
public void add(@NonNull ProfileLayer layer) {
if (layers.contains(layer)) {
// Don't add duplicate layer
return;
}
layers.add(layer);
EventBus.getDefault().post(new ProfileLayerEvent.ProfileLayerAdded(layer));
}
public void update(@NonNull ProfileLayer layer) {
EventBus.getDefault().post(new ProfileLayerEvent.ProfileLayerUpdated(layer));
}
public void remove(@NonNull String id) {
for (Iterator<ProfileLayer> it = layers.iterator(); it.hasNext(); ) {
final ProfileLayer layer = it.next();
if (layer.id().equals(id)) {
it.remove();
EventBus.getDefault().post(new ProfileLayerEvent.ProfileLayerRemoved(layer));
}
}
}
}
| 29.177778 | 93 | 0.665651 |
eee07c3c7b312e1f82e926919c1a46a10449c386 | 96 | package PrismaMod.actions.MonsterActions.Rider;
@Deprecated
public class MonstrousStrength {
}
| 16 | 47 | 0.833333 |
accfcb2be6e10a0f166369ef41389f724988a6c8 | 999 | package org.jeecg.modules.tools.service.impl;
import org.jeecg.modules.tools.entity.RunningToolsLicensemonitor;
import org.jeecg.modules.tools.mapper.RunningToolsLicensemonitorMapper;
import org.jeecg.modules.tools.service.IRunningToolsLicensemonitorService;
import org.springframework.stereotype.Service;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
/**
* @Description: License监控表
* @Author: jeecg-boot
* @Date: 2021-01-07
* @Version: V1.0
*/
@Service
public class RunningToolsLicensemonitorServiceImpl extends ServiceImpl<RunningToolsLicensemonitorMapper, RunningToolsLicensemonitor> implements IRunningToolsLicensemonitorService {
@Autowired
private RunningToolsLicensemonitorMapper runningToolsLicensemonitorMapper;
@Override
public List<RunningToolsLicensemonitor> selectByMainId(String mainId) {
return runningToolsLicensemonitorMapper.selectByMainId(mainId);
}
}
| 35.678571 | 180 | 0.841842 |
de9923f48a9af11d3959fde1c2e52a7c3490faed | 1,778 | /**
* AddPetViewModelFactory.java
* @author Aavash Sthapit
* As you can see in the PetDao when we want to update a Pet, we need to call the
* loadPetById method, which requires the id of the pet of a parameter. Therefore,
* the ViewModel for the EditorActivity will need the id of the Pet, so we need to pass this value
* to the ViewModel. For that, we need to create a ViewModel factory.
* We can not create ViewModel on our own. We need ViewModelProviders utility provided by Android to create ViewModels.
*
* But ViewModelProviders can only instantiate ViewModels with no arg constructor.
*
* So if I have a ViewModel with multiple arguments, then I need to use a Factory that I can pass to
* ViewModelProviders to use when an instance of MyViewModel is required.
*
* Argument is sent here.
*/
package com.example.android.pets;
import android.arch.lifecycle.ViewModel;
import android.arch.lifecycle.ViewModelProvider;
import android.support.annotation.NonNull;
import com.example.android.pets.data.PetsDatabase;
public class AddPetViewModelFactory extends ViewModelProvider.NewInstanceFactory {
private final PetsDatabase database;
private final int petId;
/**
* Constructor to initialize those member variables
* @param database instance
* @param petId to be edited
*/
public AddPetViewModelFactory(PetsDatabase database, int petId){
this.database = database;
this.petId = petId;
}
/**
* @param modelClass to be used.
* @param <T> required class
* @return AddTaskViewModel that uses our parameters in the constructor.
*/
@Override
public <T extends ViewModel> T create(@NonNull Class<T> modelClass){
return (T) new AddPetViewModel(database, petId);
}
}
| 35.56 | 119 | 0.732846 |
6492e086231f2c79303c3056d9b6eb6317f2a76e | 4,196 | package GUI;
import Listeners.*;
import UnitTest.MemoryTest;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import java.io.IOException;
public class OptionsEV {
private static JTextField textField;
private static JTextArea responseArea;
private JPanel panel;
private PlugAndCharge instance = new PlugAndCharge();
public OptionsEV() {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
panel = new JPanel();
panel.setLayout(new GridBagLayout());
panel.setBackground(Color.LIGHT_GRAY);
GridBagConstraints gbc = new GridBagConstraints();
// TOP LABEL
JLabel lblPCT = new JLabel("Emulate Vehicle Options");
lblPCT.setFont(new Font("Vernanda", Font.BOLD, 16));
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.anchor = GridBagConstraints.NORTH;
gbc.gridy = 0;
gbc.insets = new Insets(20, 10, 10, 0);
gbc.weightx = 0.25;
panel.add(lblPCT, gbc);
// RIVIAN LOGO
JButton logoButton = new JButton();
try {
Image logo = ImageIO.read(getClass().getResource("/Assets/img/logo.png"));
Image resizedLogo = logo.getScaledInstance(screenSize.width * 1/12, screenSize.height * 1/9, Image.SCALE_SMOOTH);
logoButton.setIcon(new ImageIcon(resizedLogo));
} catch (IOException e){
e.printStackTrace();
}
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 2;
gbc.gridy = 0;
gbc.insets = new Insets(0, 0, 0, 0);
gbc.weightx = 0.05;
gbc.anchor = GridBagConstraints.NORTH;
gbc.anchor = GridBagConstraints.EAST;
logoButton.setBackground(null);
logoButton.setBackground(Color.LIGHT_GRAY);
logoButton.setBorder(null);
logoButton.setFocusPainted(false);
panel.add(logoButton, gbc);
// BACK BUTTON
JButton backButton = new JButton("Back");
backButton.setFont(new Font("Vernanda", Font.PLAIN, 14));
gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
BackListener BackListener = new BackListener();
backButton.addActionListener(BackListener);
backButton.setBackground(Color.WHITE);
gbc.gridx = 0;
gbc.gridy = 1;
gbc.insets = new Insets(30, 10, 30, 0);
gbc.weightx = 0.25;
gbc.weighty = 0.8;
panel.add(backButton, gbc);
// USE ISO BUTTON
JButton isoButton = new JButton("Use ISO15118");
ISOListener ISOListener = new ISOListener();
gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
isoButton.addActionListener(ISOListener);
isoButton.setBackground(Color.WHITE);
isoButton.setFont(new Font("Vernanda", Font.PLAIN, 14));
gbc.gridx = 0;
gbc.gridy = 2;
gbc.insets = new Insets(30, 10, 30, 0);
gbc.weightx = 0.25;
gbc.weighty = 0.8;
panel.add(isoButton, gbc);
// JSCROLLPANE FOR OUTPUT
textField = new JTextField(80);
responseArea = new JTextArea(10, 80);
responseArea.setEditable(false);
responseArea.setLineWrap(true);
responseArea.setForeground(Color.WHITE);
Font font = new Font("Courier", Font.BOLD, 14);
responseArea.setFont(font);
responseArea.setBackground(Color.DARK_GRAY);
JScrollPane scrollPane = new JScrollPane(responseArea);
gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.gridwidth = 3;
gbc.gridheight = 5;
gbc.gridx = 1;
gbc.gridy = 1;
gbc.insets = new Insets(0, 10, 0, 10);
gbc.weightx = 1;
gbc.weighty = 1;
panel.add(scrollPane, gbc);
}
public JPanel getUI(){
return panel;
}
public static JTextField getTextField(){
return textField;
}
public static JTextArea getResponseArea(){
return responseArea;
}
public static void setResponseArea(JTextArea area){
responseArea = area;
}
} | 32.527132 | 125 | 0.617255 |
e65ba57f4126fe3782942e3604668245867af0ea | 1,002 | package net.stone_labs.strainsofascension.effects.strains;
import net.minecraft.entity.effect.StatusEffectInstance;
import net.minecraft.entity.effect.StatusEffects;
import net.minecraft.server.network.ServerPlayerEntity;
import net.stone_labs.strainsofascension.artifacts.ArtifactState;
import net.stone_labs.strainsofascension.StrainManager;
import net.stone_labs.strainsofascension.effects.BasicEffect;
public class BlindnessStrain extends BasicEffect
{
public static boolean doBlindness = true;
@Override
public void effect(ServerPlayerEntity player, byte layer, ArtifactState artifactState)
{
if (layer < 5)
return;
if (!doBlindness)
return;
if (!NightVisionStrain.CanCancelBlindness(layer) || player.getStatusEffect(StatusEffects.NIGHT_VISION) == null)
player.addStatusEffect(new StatusEffectInstance(StatusEffects.BLINDNESS, StrainManager.effectDurationBlindness, 0, true, false, StrainManager.showIcon));
}
}
| 37.111111 | 165 | 0.775449 |
72caeb2bf43a19acdd71a4642e0aa4ea4d82ce28 | 239 | package org.javaturk.wap.ch08.temperatureConverter.domain;
public class InvalidArgumentException extends Exception {
private static String message = "Invalid value passed: ";
public InvalidArgumentException(){
super(message);
}
}
| 21.727273 | 58 | 0.786611 |
369e0935ad9505b9628b7e1c5dd7da85e09b0513 | 801 | package com.hzqing.system.rest.converter;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hzqing.system.api.dto.button.AddElementRequest;
import com.hzqing.system.api.dto.button.ElementDto;
import com.hzqing.system.api.dto.button.ElementListRequest;
import com.hzqing.system.api.dto.button.UpdateElementRequest;
import com.hzqing.system.rest.vo.ElementVO;
import org.mapstruct.Mapper;
/**
* @author hzqing
* @date 2019-08-12 22:07
*/
@Mapper(componentModel = "spring")
public interface ElementConverter {
ElementVO dto2vo(ElementDto data);
Page<ElementVO> dto2Vo(Page<ElementDto> data);
AddElementRequest vo2Dto(ElementVO buttonVO);
UpdateElementRequest vo2UpdateDto(ElementVO buttonVO);
ElementListRequest vo2ListDto(ElementVO buttonVO);
}
| 28.607143 | 66 | 0.792759 |
95d85961861d637545be4a9f1b4c4e463140fd39 | 2,073 | package com.sudhar.netizenEditor.ImageEditor;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;
public class RotateTouchListener implements View.OnTouchListener{
private RelativeLayout.LayoutParams layoutParams;
private RelativeLayout layBg;
private int pivx=0;
private int pivy=0;
private int pos=0;
private float startDegree=0;
private int basex = 0;
private int basey = 0;
private View rootview,childview;
public RotateTouchListener(View rootview,View childview) {
// this.ctx = ctx;
// this.mDrawableBackground = mDrawableBackground;
// mGestureListener = new GestureDetector(ctx,new DragTouchListener.GestureListener());
this.rootview = rootview;
this.childview = childview;
}
@Override
public boolean onTouch(View v, MotionEvent event) {
layoutParams = (RelativeLayout.LayoutParams) rootview.getLayoutParams();
layBg = ((RelativeLayout) rootview.getParent());
int[] arrayOfInt = new int[2];
layBg.getLocationOnScreen(arrayOfInt);
int i = (int) event.getRawX() - arrayOfInt[0];
int j = (int) event.getRawY() - arrayOfInt[1];
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
startDegree = rootview.getRotation();
pivx = (layoutParams.leftMargin + rootview.getWidth() / 2);
pivy = (layoutParams.topMargin + rootview.getHeight() / 2);
basex = (i - pivx);
basey = (pivy - j);
break;
case MotionEvent.ACTION_MOVE:
int k = pivx;
int m = pivy;
j = (int) (Math.toDegrees(Math.atan2(basey, basex))
- Math.toDegrees(Math.atan2(m - j, i - k)));
i = j;
if (j < 0) {
i = j + 360;
}
rootview.setRotation((startDegree + i) % 360.0F);
break;
}
return true;
}
}
| 33.435484 | 94 | 0.583213 |
e1331798bdd200ebf7f94d6c974ad87647e0659d | 1,036 | package com.github.st1hy.countthemcalories.activities.tags.fragment.model;
import com.github.st1hy.countthemcalories.database.Tag;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import org.parceler.Parcel;
import org.parceler.ParcelConstructor;
import java.util.List;
@Parcel
public class Tags {
final List<Tag> tags;
@ParcelConstructor
public Tags(List<Tag> tags) {
this.tags = ImmutableList.copyOf(tags);
}
public List<Tag> getTags() {
return tags;
}
public boolean isEmpty() {
return tags.isEmpty();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Tags tags1 = (Tags) o;
return tags.equals(tags1.tags);
}
@Override
public int hashCode() {
return tags.hashCode();
}
@Override
public String toString() {
return "Tags: " + Iterables.toString(tags);
}
}
| 20.72 | 74 | 0.642857 |
f550e4560eec19e9cf99c136238a4082e6862e78 | 322 | package org.innovateuk.ifs.workflow.audit;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
public interface ProcessHistoryRepository extends CrudRepository<ProcessHistory, Long> {
void deleteByProcessId(long processId);
List<ProcessHistory> findByProcessId(long processId);
} | 26.833333 | 88 | 0.819876 |
aba011cda70878bf404c0dbbbda760a627d349a6 | 877 | package com.timtrense.quic.impl;
import java.net.DatagramPacket;
import java.time.Instant;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
/**
* A {@link DatagramPacket} that was received by a {@link Receiver}
*
* @author Tim Trense
*/
@Data
@RequiredArgsConstructor
@AllArgsConstructor
public class ReceivedDatagram {
/**
* the actual received datagram
*/
private @NonNull DatagramPacket datagram;
/**
* the timestamp of receiving
*/
private @NonNull Instant receiveTime;
/**
* a counter given by the {@link Receiver}
*/
private long number;
/**
* how many times the datagram could not be parsed,
* possibly due to the lack of decryption material because of reordering on the network
*/
private short parseRetryCount = 0;
}
| 23.078947 | 91 | 0.697834 |
2bf364c030f79d23b05ea6a0ab018eff03486216 | 5,914 | /*
* Copyright (c) 2000, 2004, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package goodman.com.sun.corba.se.spi.ior.iiop;
import com.sun.corba.se.spi.ior.IOR ;
import com.sun.corba.se.spi.ior.iiop.IIOPProfile;
import com.sun.corba.se.spi.orb.ORB;
import com.sun.corba.se.spi.orb.ORBVersion;
import com.sun.corba.se.spi.orb.ORBVersionFactory;
import com.sun.corba.se.impl.orbutil.ORBUtility;
import com.sun.corba.se.impl.protocol.giopmsgheaders.Message;
public class GIOPVersion {
// Static fields
public static final GIOPVersion V1_0 = new GIOPVersion((byte)1, (byte)0);
public static final GIOPVersion V1_1 = new GIOPVersion((byte)1, (byte)1);
public static final GIOPVersion V1_2 = new GIOPVersion((byte)1, (byte)2);
public static final GIOPVersion V1_3 = new GIOPVersion((byte)1, (byte)3);
// Major version 13 indicates Java serialization,
// Minor version [00-FF] is the version number.
public static final GIOPVersion V13_XX =
new GIOPVersion((byte)13, (byte)Message.JAVA_ENC_VERSION);
public static final GIOPVersion DEFAULT_VERSION = V1_2;
public static final int VERSION_1_0 = 0x0100;
public static final int VERSION_1_1 = 0x0101;
public static final int VERSION_1_2 = 0x0102;
public static final int VERSION_1_3 = 0x0103;
public static final int VERSION_13_XX =
((0x0D << 8) & 0x0000FF00) | Message.JAVA_ENC_VERSION;
// Instance variables
private byte major = (byte) 0;
private byte minor = (byte) 0;
// Constructor
public GIOPVersion() {}
public GIOPVersion(byte majorB, byte minorB) {
this.major = majorB;
this.minor = minorB;
}
public GIOPVersion(int major, int minor) {
this.major = (byte)major;
this.minor = (byte)minor;
}
// Accessor methods
public byte getMajor() {
return this.major;
}
public byte getMinor() {
return this.minor;
}
// General methods
public boolean equals(GIOPVersion gv){
return gv.major == this.major && gv.minor == this.minor ;
}
public boolean equals(Object obj) {
if (obj != null && (obj instanceof GIOPVersion))
return equals((GIOPVersion)obj);
else
return false;
}
public int hashCode()
{
return 37*major + minor ;
}
public boolean lessThan(GIOPVersion gv) {
if (this.major < gv.major) {
return true;
} else if (this.major == gv.major) {
if (this.minor < gv.minor) {
return true;
}
}
return false;
}
public int intValue()
{
return (major << 8 | minor);
}
public String toString()
{
return major + "." + minor;
}
public static GIOPVersion getInstance(byte major, byte minor)
{
switch(((major << 8) | minor)) {
case VERSION_1_0:
return GIOPVersion.V1_0;
case VERSION_1_1:
return GIOPVersion.V1_1;
case VERSION_1_2:
return GIOPVersion.V1_2;
case VERSION_1_3:
return GIOPVersion.V1_3;
case VERSION_13_XX:
return GIOPVersion.V13_XX;
default:
return new GIOPVersion(major, minor);
}
}
public static GIOPVersion parseVersion(String s)
{
int dotIdx = s.indexOf('.');
if (dotIdx < 1 || dotIdx == s.length() - 1)
throw new NumberFormatException("GIOP major, minor, and decimal point required: " + s);
int major = Integer.parseInt(s.substring(0, dotIdx));
int minor = Integer.parseInt(s.substring(dotIdx + 1, s.length()));
return GIOPVersion.getInstance((byte)major, (byte)minor);
}
/**
* This chooses the appropriate GIOP version.
*
* @return the GIOP version 13.00 if Java serialization is enabled, or
* smallest(profGIOPVersion, orbGIOPVersion)
*/
public static GIOPVersion chooseRequestVersion(ORB orb, IOR ior ) {
GIOPVersion orbVersion = orb.getORBData().getGIOPVersion();
IIOPProfile prof = ior.getProfile() ;
GIOPVersion profVersion = prof.getGIOPVersion();
// Check if the profile is from a legacy Sun ORB.
ORBVersion targetOrbVersion = prof.getORBVersion();
if (!(targetOrbVersion.equals(ORBVersionFactory.getFOREIGN())) &&
targetOrbVersion.lessThan(ORBVersionFactory.getNEWER())) {
// we are dealing with a SUN legacy orb which emits 1.1 IORs,
// in spite of being able to handle only GIOP 1.0 messages.
return V1_0;
}
// Now the target has to be (FOREIGN | NEWER*)
byte prof_major = profVersion.getMajor();
byte prof_minor = profVersion.getMinor();
byte orb_major = orbVersion.getMajor();
byte orb_minor = orbVersion.getMinor();
if (orb_major < prof_major) {
return orbVersion;
} else if (orb_major > prof_major) {
return profVersion;
} else { // both major version are the same
if (orb_minor <= prof_minor) {
return orbVersion;
} else {
return profVersion;
}
}
}
public boolean supportsIORIIOPProfileComponents()
{
return getMinor() > 0 || getMajor() > 1;
}
// IO methods
public void read(org.omg.CORBA.portable.InputStream istream) {
this.major = istream.read_octet();
this.minor = istream.read_octet();
}
public void write(org.omg.CORBA.portable.OutputStream ostream) {
ostream.write_octet(this.major);
ostream.write_octet(this.minor);
}
}
| 26.881818 | 99 | 0.604498 |
837ab723146068532fb30e7304c35480fd158a3e | 1,109 | /*
* Copyright 2020 nuwansa.
*
* 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.cloudimpl.db4j.core.impl;
import java.nio.ByteBuffer;
import java.nio.LongBuffer;
/** @author nuwansa */
public class Database {
void put(Object data) {}
public static void main(String[] args) {
ByteBuffer buf = ByteBuffer.allocateDirect(1024);
LongBuffer buf2 = buf.asLongBuffer();
buf2.put(5);
LongBuffer buf3 = buf2.slice();
buf2.flip();
buf3.put(buf2);
// buf2.flip();
buf2 = buf.asLongBuffer();
System.out.println(buf2.get(0) + " :" + buf2.get(1));
}
}
| 29.184211 | 75 | 0.695221 |
e61e0176128d12d93b09068f6dbfe3a1004a5b1f | 13,488 | import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.awt.event.ActionEvent;
import javax.swing.JCheckBox;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import javax.swing.JRadioButton;
import javax.swing.JComboBox;
public class Registration extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
private JTextField textField_4;
JCheckBox chckbxAdmin;
JCheckBox chckbxFaculty;
JCheckBox chckbxStudent;
String sex=null;
//String selected_month;
//String selected_date;
// String selected_year;
ButtonGroup g,g1;
int count=0;
private JLabel lblSex;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Registration frame = new Registration();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Registration() {
super("Registration Page...");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 666, 303);
setLocationRelativeTo(this);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblEnterName = new JLabel("Enter Name*");
lblEnterName.setBounds(163, 46, 118, 14);
contentPane.add(lblEnterName);
textField = new JTextField();
textField.setBounds(318, 40, 156, 20);
contentPane.add(textField);
textField.setColumns(10);
JLabel lblEnterEmail = new JLabel("Enroll Number*");
lblEnterEmail.setBounds(163, 77, 118, 14);
contentPane.add(lblEnterEmail);
textField_1 = new JTextField();
textField_1.setBounds(318, 71, 156, 20);
contentPane.add(textField_1);
textField_1.setColumns(10);
JLabel lblContactNumber = new JLabel("Contact Number*");
lblContactNumber.setBounds(163, 108, 118, 14);
contentPane.add(lblContactNumber);
textField_2 = new JTextField();
textField_2.setBounds(318, 102, 156, 20);
contentPane.add(textField_2);
textField_2.setColumns(10);
JLabel lblEnterPassword = new JLabel("Enter Password*");
lblEnterPassword.setBounds(163, 139, 118, 14);
contentPane.add(lblEnterPassword);
textField_3 = new JTextField();
textField_3.setBounds(318, 133, 156, 20);
contentPane.add(textField_3);
textField_3.setColumns(10);
JLabel lblReenterPassword = new JLabel("Re-enter Password*");
lblReenterPassword.setBounds(163, 167, 118, 14);
contentPane.add(lblReenterPassword);
textField_4 = new JTextField();
textField_4.setBounds(318, 164, 156, 20);
contentPane.add(textField_4);
textField_4.setColumns(10);
String uname=textField.getText();
String enroll=textField_1.getText();
String contct=textField_2.getText();
System.out.println(contct);
String pass=textField_3.getText();
String repass=textField_4.getText();
JButton btnReset = new JButton("RESET");
btnReset.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
textField.setText(null);
textField_1.setText(null);
textField_2.setText(null);
textField_3.setText(null);
textField_4.setText(null);
g.clearSelection();
count=0;
dispose();
}
});
btnReset.setBounds(274, 227, 89, 23);
contentPane.add(btnReset);
JButton btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
Login obj=new Login();
obj.setVisible(true);
dispose();
}
});
btnLogin.setBounds(385, 227, 89, 23);
contentPane.add(btnLogin);
JLabel lblNew = new JLabel(new ImageIcon("reg.jpg"));
lblNew.setBounds(21, 43, 118, 152);
contentPane.add(lblNew);
g=new ButtonGroup();
chckbxStudent = new JCheckBox("Student");
chckbxStudent.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
count=1;
}
});
g.add(chckbxStudent);
chckbxStudent.setBounds(163, 197, 97, 23);
contentPane.add(chckbxStudent);
chckbxFaculty = new JCheckBox("Faculty");
chckbxFaculty.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
count=2;
}
});
g.add(chckbxFaculty);
chckbxFaculty.setBounds(274, 197, 97, 23);
contentPane.add(chckbxFaculty);
chckbxAdmin = new JCheckBox("Admin");
chckbxAdmin.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e)
{
count=3;
}
});
g.add(chckbxAdmin);
chckbxAdmin.setBounds(377, 197, 97, 23);
contentPane.add(chckbxAdmin);
lblSex = new JLabel("Sex*");
lblSex.setBounds(524, 40, 46, 14);
contentPane.add(lblSex);
g1=new ButtonGroup();
JCheckBox chckbxMale = new JCheckBox("Male");
chckbxMale.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e)
{
sex="male";
}
});
chckbxMale.setBounds(524, 68, 97, 23);
contentPane.add(chckbxMale);
JCheckBox chckbxFemale = new JCheckBox("Female");
chckbxFemale.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e)
{
sex="female";
}
});
chckbxFemale.setBounds(524, 101, 97, 23);
contentPane.add(chckbxFemale);
g1.add(chckbxMale);
g1.add(chckbxFemale);
JLabel lblDob = new JLabel("DOB *");
lblDob.setBounds(524, 139, 46, 14);
contentPane.add(lblDob);
JLabel lblMm = new JLabel("MM");
lblMm.setBounds(524, 167, 30, 14);
contentPane.add(lblMm);
JLabel lblDd = new JLabel("DD");
lblDd.setBounds(524, 197, 30, 14);
contentPane.add(lblDd);
JLabel lblYyyy = new JLabel("YYYY");
lblYyyy.setBounds(524, 231, 46, 14);
contentPane.add(lblYyyy);
JComboBox comboBox = new JComboBox();
comboBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e)
{
//selected_month=(String)comboBox.getSelectedItem();
// System.out.println(selected_month);
}
});
comboBox.setBounds(575, 164, 65, 20);
comboBox.addItem("select");
comboBox.addItem("01");
comboBox.addItem("02");
comboBox.addItem("03");
comboBox.addItem("04");
comboBox.addItem("05");
comboBox.addItem("06");
comboBox.addItem("07");
comboBox.addItem("08");
comboBox.addItem("09");
comboBox.addItem("10");
comboBox.addItem("11");
comboBox.addItem("12");
contentPane.add(comboBox);
JComboBox comboBox_1 = new JComboBox();
comboBox_1.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e)
{
//selected_date=(String)comboBox_1.getSelectedItem();
}
});
comboBox_1.addItem("select");
comboBox_1.addItem("01");
comboBox_1.addItem("02");
comboBox_1.addItem("03");
comboBox_1.addItem("04");
comboBox_1.addItem("05");
comboBox_1.addItem("06");
comboBox_1.addItem("07");
comboBox_1.addItem("08");
comboBox_1.addItem("09");
comboBox_1.addItem("10");
comboBox_1.addItem("11");
comboBox_1.addItem("12");
comboBox_1.addItem("13");
comboBox_1.addItem("14");
comboBox_1.addItem("15");
comboBox_1.addItem("16");
comboBox_1.addItem("17");
comboBox_1.addItem("18");
comboBox_1.addItem("19");
comboBox_1.addItem("20");
comboBox_1.addItem("21");
comboBox_1.addItem("22");
comboBox_1.addItem("23");
comboBox_1.addItem("24");
comboBox_1.addItem("25");
comboBox_1.addItem("26");
comboBox_1.addItem("27");
comboBox_1.addItem("28");
comboBox_1.addItem("29");
comboBox_1.setBounds(575, 194, 65, 20);
comboBox_1.addItem("30");
comboBox_1.addItem("31");
contentPane.add(comboBox_1);
JComboBox comboBox_2 = new JComboBox();
comboBox_2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e)
{
//selected_year=(String)comboBox_2.getSelectedItem();
}
});
comboBox_2.setBounds(575, 228, 65, 20);
comboBox_2.addItem("select");
comboBox_2.addItem("1970");
comboBox_2.addItem("1971");
comboBox_2.addItem("1972");
comboBox_2.addItem("1973");
comboBox_2.addItem("1974");
comboBox_2.addItem("1975");
comboBox_2.addItem("1976");
comboBox_2.addItem("1977");
comboBox_2.addItem("1978");
comboBox_2.addItem("1979");
comboBox_2.addItem("1980");
comboBox_2.addItem("1981");
comboBox_2.addItem("1982");
comboBox_2.addItem("1983");
comboBox_2.addItem("1984");
comboBox_2.addItem("1985");
comboBox_2.addItem("1986");
comboBox_2.addItem("1987");
comboBox_2.addItem("1988");
comboBox_2.addItem("1989");
comboBox_2.addItem("1990");
comboBox_2.addItem("1991");
comboBox_2.addItem("1992");
comboBox_2.addItem("1993");
comboBox_2.addItem("1994");
comboBox_2.addItem("1995");
contentPane.add(comboBox_2);
JLabel label = new JLabel("*");
label.setBounds(141, 201, 16, 14);
contentPane.add(label);
JButton btnSave = new JButton("SAVE");
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
int flag=0;
int flag1=0;
String selected_month=(String)comboBox.getSelectedItem();
String selected_date=(String)comboBox_1.getSelectedItem();
String selected_year=(String)comboBox_2.getSelectedItem();
String uname=textField.getText();
String enroll=textField_1.getText();
String contct=textField_2.getText();
System.out.println(contct);
String pass=textField_3.getText();
String repass=textField_4.getText();
if(uname.length()==0||enroll.length()==0||contct.length()==0||pass.length()==0||repass.length()==0)
{
JOptionPane.showMessageDialog(getParent(),"plz fill all query","Error",JOptionPane.ERROR_MESSAGE);
}
else if(selected_month.equals("select")||selected_date.equals("select")||selected_year.equals("select"))
{
JOptionPane.showMessageDialog(getParent(),"plz select your DOB","Error",JOptionPane.ERROR_MESSAGE);
}
else if(sex==null)
{
JOptionPane.showMessageDialog(getParent(),"plz select your sex","Error",JOptionPane.ERROR_MESSAGE);
}
else if(count==0)
{
JOptionPane.showMessageDialog(getParent(),"plz select any usertype","Error",JOptionPane.ERROR_MESSAGE);
}
else if(!pass.equals(repass))
{
JOptionPane.showMessageDialog(getParent(),"passwords are not matching","Error",JOptionPane.ERROR_MESSAGE);
}
else if(contct.length()!=10 )
{
JOptionPane.showMessageDialog(getParent(),"wrong contact number","Error",JOptionPane.ERROR_MESSAGE);
}
else
{
String query1="insert into login values (?,?,?)";
Connection con1=DBInfo1.con;
try
{
PreparedStatement ps=con1.prepareStatement(query1);
ps.setString(1,uname);
ps.setString(2,pass);
String str="";
if(count==1)
{
str="student";
}
else if(count==2)
{
str="faculty";
}
else if(count==3)
{
str="admin";
}
ps.setString(3,str);
flag1=ps.executeUpdate();
//con1.close();
//ps.close();
// DBInfo1.con.close();
}
catch(Exception ea)
{
ea.printStackTrace();
}
}
//---------------------------------------------------------------------------------------------------------------------------------------
String darling="insert into registration values(?,?,?,?,?,?,?,?)";
Connection con=DBInfo1.con;
try
{
PreparedStatement ps1=con.prepareStatement(darling);
ps1.setString(1,uname);
ps1.setString(2,enroll);
ps1.setString(3,contct);
ps1.setString(4,pass);
ps1.setString(5,sex);
ps1.setString(6,selected_date);
ps1.setString(7,selected_month);
ps1.setString(8,selected_year);
flag=ps1.executeUpdate();
System.out.println(flag1+"------------------------------------");
}
catch(Exception ea)
{
ea.printStackTrace();
}
//-----------------------------------------------------------------------------------------------------------------------------
if(flag==0||flag1==0)
{
JOptionPane.showMessageDialog(getParent(),"Registration Failed","Error",JOptionPane.ERROR_MESSAGE);
}
if(flag!=0 && flag1!=0)
{
JOptionPane.showMessageDialog(getParent(),"registration sucessful");
}
}
});
btnSave.setBounds(163, 227, 89, 23);
contentPane.add(btnSave);
}
}
| 28.04158 | 140 | 0.636788 |
5a53ce0e524aa098f3cbbb08fca41fefde038ff7 | 599 | package com.embed.candy;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import com.swarmconnect.Swarm;
public class CandyPreferenceActivity extends PreferenceActivity {
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.addPreferencesFromResource(R.xml.game_prefs);
Swarm.setActive(this);
}
@Override
public void onResume() {
super.onResume();
Swarm.setActive(this);
}
@Override
public void onPause() {
super.onPause();
Swarm.setInactive(this);
}
}
| 20.655172 | 66 | 0.716194 |
d208db8364d8f804aa8f1487d95959a1e850f1f1 | 375 | package ruboweb.pushetta.back.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import ruboweb.pushetta.back.model.User;
/**
* CRUD Repository for the entity
*/
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
User findUserByToken(String token);
}
| 23.4375 | 68 | 0.776 |
f2111f4dce9bbfc8459628cfb8d98cc311ec436b | 505 | package org.metaworks.viewer;
import java.util.*;
import org.metaworks.*;
public class LinkView extends AbstractWebViewer{
public LinkView(String action){
if(action!=null)
attributes.put("action", action);
}
public LinkView(){
this(null);
}
/////////////////// implements ///////////////////
public String getViewerHTML(Instance rec, String colName){
return "<a href='"+getAttribute("action")+"?" +rec.getKeyQueryString()+ "'>"+rec.get(colName)+"</a>";
}
} | 21.041667 | 104 | 0.607921 |
a90eaf1f5c879490795b127674fa38c1ae4915cf | 265 | package com.auth0.net;
interface CustomizableRequest<T> extends Request<T> {
CustomizableRequest<T> addHeader(String name, String value);
CustomizableRequest<T> addParameter(String name, Object value);
CustomizableRequest<T> setBody(Object body);
}
| 24.090909 | 67 | 0.762264 |
ec62e2ca0c82f9c275cce4e42799dd975111eb6d | 2,332 | package model;
public class PokerHand extends Hand
{
private int myNumberCards;
private int myMaxNumberCards;
private int myRanking;
public PokerHand(int maxNum)
{
super(maxNum);
if (this.isHighCard())
{
myRanking = 1;
}
if (this.isPair())
{
myRanking = 2;
}
if (this.isTwoPair())
{
myRanking = 3;
}
if (this.isThreeOfKind())
{
myRanking = 4;
}
if (this.isStraight())
{
myRanking = 5;
}
if (this.isFlush())
{
myRanking = 6;
}
if (this.isFullHouse())
{
myRanking = 7;
}
if (this.isFourOfKind())
{
myRanking = 8;
}
if (this.isStraightFlush())
{
myRanking = 9;
}
if (this.isRoyalFlush())
{
myRanking = 10;
}
}
public PokerHandRanking determineRanking()
{
if (this.getRanking() == 2)
{
return PokerHandRanking.PAIR;
}
else if (this.getRanking() == 3)
{
return PokerHandRanking.TWO_PAIR;
}
else if (this.getRanking() == 4)
{
return PokerHandRanking.THREE_OF_KIND;
}
else if (this.getRanking() == 5)
{
return PokerHandRanking.STRAIGHT;
}
else if (this.getRanking() == 6)
{
return PokerHandRanking.FLUSH;
}
else if (this.getRanking() == 7)
{
return PokerHandRanking.FULL_HOUSE;
}
else if (this.getRanking() == 8)
{
return PokerHandRanking.FOUR_OF_KIND;
}
else if (this.getRanking() == 9)
{
return PokerHandRanking.STRAIGHT_FLUSH;
}
else if (this.getRanking() == 10)
{
return PokerHandRanking.ROYAL_FLUSH;
}
else
{
return PokerHandRanking.HIGH_CARD;
}
}
public int compareTo(PokerHand pokerHand)
{
return 0;
}
public String toString()
{
return null;
}
public int getRanking()
{
return myRanking;
}
public int getNumberCards()
{
return 0;
}
public int getMaxNumberCards()
{
return 0;
}
public boolean isHighCard()
{
return true;
}
public boolean isPair()
{
return false;
}
public boolean isTwoPair()
{
return false;
}
public boolean isThreeOfKind()
{
return false;
}
public boolean isStraight()
{
return false;
}
public boolean isFlush()
{
return false;
}
public boolean isFullHouse()
{
return false;
}
public boolean isFourOfKind()
{
return false;
}
public boolean isStraightFlush()
{
return false;
}
public boolean isRoyalFlush()
{
return false;
}
}
| 13.25 | 43 | 0.629503 |
56817453771266813aedd3046fa259fd60880dec | 1,012 | package blue.internal.core.message;
import blue.core.message.Topic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
/**
* @author Jin Zheng
* @since 1.0 2021-01-06
*/
public abstract class AbstractProducer<T extends Topic> implements Producer<T>, InitializingBean
{
private static Logger logger = LoggerFactory.getLogger(AbstractProducer.class);
protected String name;
protected ProducerListener<T, Object> listener;
public AbstractProducer()
{
}
@Override
public void afterPropertiesSet() throws Exception
{
if (this.listener == null)
{
this.listener = new LoggerProducerListener<>();
logger.info("Producer '{}' default ProducerListener is null, use LoggerProducerListener", name);
}
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
@Override
public void setProducerListener(ProducerListener<T, Object> listener)
{
this.listener = listener;
}
}
| 20.653061 | 99 | 0.745059 |
7dcb05cc7e0e9734841a0db46326cfd8bdb04fa1 | 4,589 | package com.example.flicks;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import cz.msebera.android.httpclient.Header;
public class MovieTrailerActivity extends YouTubeBaseActivity {
// constants
// base URL for API
public final static String API_BASE_URL = "https://api.themoviedb.org/3";
// parameter name for API key
public final static String API_KEY_PARAM = "api_key";
// tag for logging from this activity
public final static String TAG = "MovieTrailerActivity";
// instance values - associated with specific instance of movie list activity
AsyncHttpClient client;
// id of YouTube video
String ytId;
private void getYouTube(String vidId) {
// create url
String url = API_BASE_URL + "/movie/" + vidId + "/videos?api_key=";
// set request parameters (appended to URL)
RequestParams params = new RequestParams();
params.put(API_KEY_PARAM, getString(R.string.api_key)); // API key, always required
client = new AsyncHttpClient();
// GET request expecting JSON object response
client.get(url, params, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
// parse JSON response results value as JSON array
// get YouTube link
try {
JSONArray results = response.getJSONArray("results");
// assign YouTube key from JSON object
ytId = results.getJSONObject(0).getString("key");
Log.i(TAG, "Returned movie YouTube id" + ytId);
// resolve player view from layout
YouTubePlayerView playerView = (YouTubePlayerView) findViewById(R.id.player);
// initialize with API key stored in secrets.xml
playerView.initialize(getString(R.string.youtube_key), new YouTubePlayer.OnInitializedListener() {
@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
// do work here to cue or play video, etc.
youTubePlayer.cueVideo(ytId);
}
@Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
// log error
Log.e("MovieTrailerActivity", "Error initializing YouTube player");
}
});
} catch (JSONException e) {
logError("Failed to parse movie videos link", e, true);
}
}
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
logError("Failed to get data from movie videos endpoint", throwable, true);
}
});
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_trailer);
int movieId = (Integer) getIntent().getExtras().getInt("movie_id");
Log.i("MOVIE ID", Integer.toString(movieId));
// TODO - add try catch statement?? code may already account for this
getYouTube(Integer.toString(movieId));
}
// handle errors, log and alert user of silent failures (if indicated)
// Throwable - base class of all errors/exceptions in Java
private void logError(String message, Throwable error, boolean alertUser) {
// always log error
Log.e(TAG, message, error);
// optionally fail non-silently - alert user
if (alertUser) {
// show long toast with error message
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
}
}
| 41.342342 | 151 | 0.633907 |
86dee39e335f9e7c342b6db5ba6c73b0cb19ceef | 611 | package net.timardo.forgekit.capabilities.world.chunk;
import net.minecraft.nbt.NBTBase;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.Capability.IStorage;
public class BukkitChunkCapStorage implements IStorage<IBukkitChunkCap> {
@Override
public NBTBase writeNBT(Capability<IBukkitChunkCap> capability, IBukkitChunkCap instance, EnumFacing side) {
return null;
}
@Override
public void readNBT(Capability<IBukkitChunkCap> capability, IBukkitChunkCap instance, EnumFacing side,
NBTBase nbt) {
}
}
| 27.772727 | 109 | 0.818331 |
7f0b7744388ad805a44564b17627f716ddb62add | 2,154 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.tsunami.plugins.portscan.nmap;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.inject.Provides;
import com.google.tsunami.plugin.PluginBootstrapModule;
import com.google.tsunami.plugins.portscan.nmap.client.NmapBinaryPath;
import java.io.FileNotFoundException;
import java.nio.file.Files;
import java.nio.file.Paths;
/** A {@link PluginBootstrapModule} for {@link NmapPortScanner}. */
public class NmapPortScannerBootstrapModule extends PluginBootstrapModule {
private static final ImmutableList<String> DEFAULT_NMAP_BINARY_PATHS =
ImmutableList.of("/usr/bin/nmap", "/usr/local/bin/nmap");
@Override
protected void configurePlugin() {
registerPlugin(NmapPortScanner.class);
}
@Provides
@NmapBinaryPath
public String provideNmapBinaryPath(NmapPortScannerConfigs configs) throws FileNotFoundException {
if (!Strings.isNullOrEmpty(configs.nmapBinaryPath)) {
if (Files.exists(Paths.get(configs.nmapBinaryPath))) {
return configs.nmapBinaryPath;
}
throw new FileNotFoundException(
String.format(
"Nmap binary '%s' from config file was not found.", configs.nmapBinaryPath));
}
for (String nmapBinaryPath : DEFAULT_NMAP_BINARY_PATHS) {
if (Files.exists(Paths.get(nmapBinaryPath))) {
return nmapBinaryPath;
}
}
throw new FileNotFoundException(
"Unable to find a valid nmap binary. Make sure Tsunami config contains a valid nmap binary"
+ " path.");
}
}
| 35.311475 | 100 | 0.737233 |
acd74efec46ce841bb1a9c74b10eb1bade40995a | 1,836 | package com.github.walterfan.devaid.domain;
public class Site {
private long siteID;
private String siteName;
private String siteUrl;
private int categoryID;
private int userID;
public Site() {
}
public Site(long siteID, String siteName) {
this.siteID = siteID;
this.siteName = siteName;
}
public Site(String siteName) {
this.siteName = siteName;
}
public long getSiteID() {
return siteID;
}
public void setSiteID(long siteID) {
this.siteID = siteID;
}
public String getSiteName() {
return siteName;
}
public void setSiteName(String siteName) {
this.siteName = siteName;
}
public String getSiteUrl() {
return siteUrl;
}
public void setSiteUrl(String siteUrl) {
this.siteUrl = siteUrl;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((siteName == null) ? 0 : siteName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof Site))
return false;
Site other = (Site) obj;
if (siteName == null) {
if (other.siteName != null)
return false;
} else if (!siteName.equals(other.siteName))
return false;
return true;
}
public String toString() {
return siteName;
}
/**
* @return the categoryID
*/
public int getCategoryID() {
return categoryID;
}
/**
* @param categoryID the categoryID to set
*/
public void setCategoryID(int categoryID) {
this.categoryID = categoryID;
}
/**
* @return the userID
*/
public int getUserID() {
return userID;
}
/**
* @param userID the userID to set
*/
public void setUserID(int userID) {
this.userID = userID;
}
}
| 19.125 | 53 | 0.625817 |
71d52d60e283f93cc82ff3c95215d368a29f7546 | 378 | // (c)2016 Flipboard Inc, All Rights Reserved.
package com.tutao.rxdemo.network.api;
import com.tutao.rxdemo.model.GankBeautyResult;
import retrofit2.http.GET;
import retrofit2.http.Path;
import rx.Observable;
public interface GankApi {
@GET("data/福利/{number}/{page}")
Observable<GankBeautyResult> getBeauties(@Path("number") int number, @Path("page") int page);
}
| 23.625 | 97 | 0.743386 |
73567c27adc1f70f8e23909e48398f6016af384e | 2,277 | package ibis.deploy.monitoring.visualization.gridvision.swing.listeners;
import ibis.deploy.monitoring.collection.MetricDescription;
import ibis.deploy.monitoring.visualization.gridvision.JungleGoggles;
import ibis.deploy.monitoring.visualization.gridvision.exceptions.MetricDescriptionNotAvailableException;
import java.awt.event.ItemEvent;
public class MetricListener implements GoggleListener {
JungleGoggles goggles;
MetricDescription[] myDescs;
public MetricListener(JungleGoggles goggles, String label) {
this.goggles = goggles;
myDescs = new MetricDescription[6];
try {
myDescs[0] = goggles.getMetricDescription("CPU");
myDescs[1] = goggles.getMetricDescription("Load");
myDescs[2] = goggles.getMetricDescription("MEM_SYS");
myDescs[3] = goggles.getMetricDescription("MEM_HEAP");
myDescs[4] = goggles.getMetricDescription("MEM_NONHEAP");
myDescs[5] = goggles.getMetricDescription("Bytes_Sent_Per_Sec");
} catch (MetricDescriptionNotAvailableException e) {
e.printStackTrace();
}
try {
if (label.compareTo("CPU Usage") == 0) {
myDescs = new MetricDescription[1];
myDescs[0] = goggles.getMetricDescription("CPU");
} else if (label.compareTo("System Load Average")== 0) {
myDescs = new MetricDescription[1];
myDescs[0] = goggles.getMetricDescription("Load");
} else if (label.compareTo("System Memory Usage")== 0) {
myDescs = new MetricDescription[1];
myDescs[0] = goggles.getMetricDescription("MEM_SYS");
} else if (label.compareTo("Java Heap Memory Usage")== 0) {
myDescs = new MetricDescription[1];
myDescs[0] = goggles.getMetricDescription("MEM_HEAP");
} else if (label.compareTo("Java Nonheap Memory Usage")== 0) {
myDescs = new MetricDescription[1];
myDescs[0] = goggles.getMetricDescription("MEM_NONHEAP");
}
} catch (MetricDescriptionNotAvailableException e) {
e.printStackTrace();
}
}
public void itemStateChanged(ItemEvent arg0) {
if (arg0.getStateChange() == ItemEvent.DESELECTED || arg0.getStateChange() == ItemEvent.SELECTED) {
goggles.toggleMetrics(myDescs);
}
}
public GoggleListener clone(String label) {
return new MetricListener(goggles, label);
}
}
| 36.142857 | 106 | 0.71278 |
5a064c536f162e9e9d08e1520068e176948a4814 | 1,998 | package com.doodeec.maroonfrog.data.model;
import com.doodeec.maroonfrog.data.persister.PackagingPersister;
import com.google.gson.annotations.SerializedName;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
import java.util.List;
import static com.doodeec.maroonfrog.data.storage.DBHelper.TABLE_NAME_MEALCAT;
@DatabaseTable(tableName = TABLE_NAME_MEALCAT)
public class MealCategory implements MealAdapterItem, DBEntity {
@SerializedName("id") @DatabaseField(id = true) String id;
@SerializedName("name") @DatabaseField String name;
@SerializedName("packaging") @DatabaseField(persisterClass = PackagingPersister.class) Packaging packaging;
@SerializedName("description") @DatabaseField String description;
@SerializedName("displaySeq") @DatabaseField Integer displaySeq;
@SerializedName("meals") List<Meal> meals;
private boolean expanded = false;
public void setExpanded(boolean expanded) {
this.expanded = expanded;
}
public boolean isExpanded() {
return expanded;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public List<Meal> getMeals() {
return meals;
}
@Override public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MealCategory category = (MealCategory) o;
return id != null ? id.equals(category.id) : category.id == null;
}
@Override public int hashCode() {
return id != null ? id.hashCode() : 0;
}
@Override public String toString() {
return "MealCategory[" +
"id=" + id +
",name=" + name +
// ",meals=" + meals +
",pack=" + packaging +
",desc=" + description +
// ",seq=" + displaySeq +
// ",exp=" + expanded +
"]";
}
}
| 28.140845 | 111 | 0.625626 |
4e99d2b65ae44b2d9915e17858be5d7b30869c1b | 2,207 | package org.bhavaya.ui.options;
import org.bhavaya.util.Transform;
/**
* Description
*
* @author Vladimir Hrmo
* @version $Revision: 1.3 $
*/
public class Option {
private Object target;
private String propertyBeanPath;
private String optionLabel;
private String optionDescription;
private Object[] beanCollection;
private Transform getTransform;
private Transform setTransform;
public Option(Object target, String propertyBeanPath, String optionLabel, String optionDescription) {
this(target, propertyBeanPath, optionLabel, optionDescription, null, null);
}
public Option(Object target, String propertyBeanPath, String optionLabel, String optionDescription, Transform getTransform, Transform setTransform) {
this(target, propertyBeanPath, optionLabel, optionDescription, null, getTransform, setTransform);
}
public Option(Object target, String propertyBeanPath, String optionLabel, String optionDescription, Object[] beanCollection) {
this(target, propertyBeanPath, optionLabel, optionDescription, beanCollection, null, null);
}
public Option(Object target, String propertyBeanPath, String optionLabel, String optionDescription, Object[] beanCollection, Transform getTransform, Transform setTransform) {
this.target = target;
this.propertyBeanPath = propertyBeanPath;
this.optionLabel = optionLabel;
this.optionDescription = optionDescription;
this.beanCollection = beanCollection;
this.getTransform = getTransform;
this.setTransform = setTransform;
}
public String toString() {
return optionLabel;
}
public Object getTarget() {
return target;
}
public String getPropertyBeanPath() {
return propertyBeanPath;
}
public String getOptionLabel() {
return optionLabel;
}
public String getOptionDescription() {
return optionDescription;
}
public Object[] getBeanCollection() {
return beanCollection;
}
public Transform getGetTransform() {
return getTransform;
}
public Transform getSetTransform() {
return setTransform;
}
}
| 29.426667 | 178 | 0.707295 |
18de999aaed7cc06409ad57cf45a0b042150863a | 9,896 | /*
* Copyright 2008-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package egovframework.hyb.mbl.pus.service.impl;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import egovframework.hyb.mbl.pus.service.EgovPushDeviceAPIService;
import egovframework.hyb.mbl.pus.service.PushDeviceAPIDefaultVO;
import egovframework.hyb.mbl.pus.service.PushDeviceAPIVO;
import egovframework.rte.fdl.cmmn.EgovAbstractServiceImpl;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.MulticastResult;
import com.google.android.gcm.server.Result;
import com.google.android.gcm.server.Sender;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import javapns.communication.ConnectionToAppleServer;
import javapns.communication.exceptions.CommunicationException;
import javapns.communication.exceptions.KeystoreException;
import javapns.devices.Device;
import javapns.devices.implementations.basic.BasicDevice;
import javapns.notification.AppleNotificationServerBasicImpl;
import javapns.notification.PushNotificationManager;
import javapns.notification.PushNotificationPayload;
import javapns.notification.PushedNotification;
/**
* @Class Name : EgovPushDeviceAPIServiceImpl.java
* @Description : EgovPushDeviceAPIServiceImpl Class
* @Modification Information
* @
* @ 수정일 수정자 수정내용
* @ --------- --------- -------------------------------
* @ 2016.06.20 신성학 최초생성
*
* @author 디바이스 API 실행환경 개발팀
* @since 2016. 06.20
* @version 1.0
* @see
*
* Copyright (C) by Ministry of Interior All right reserved.
*/
@Service("EgovPushDeviceAPIService")
public class EgovPushDeviceAPIServiceImpl extends EgovAbstractServiceImpl implements EgovPushDeviceAPIService {
private static final Logger LOGGER = LoggerFactory.getLogger(EgovPushDeviceAPIServiceImpl.class);
private static String APNS_CERTIFICATE_PATH = "C:/eclipse-jee-mars-2-win32-x86_64/egov_push_test_cert.p12";
private static String APNS_CERTIFICATE_PWD = "egov1234"; // 푸시 인증서 비밀번호
private static String APNS_DEV_HOST = "gateway.sandbox.push.apple.com"; // 개발용 푸시 전송서버
private static String APNS_HOST = "gateway.push.apple.com"; // 운영 푸시 전송서버
private static int APNS_PORT = 2195; // 이건..개발용 운영용 나뉘는지 확인해보자
private static int APNS_BADGE = 1; // App 아이콘 우측상단에 표시할 숫자
private static String APNS_SOUND = "default"; // 푸시 알림음
private static String GCM_SERVER_API_KEY = "AIzaSyD1kFG9Z3Kw-rvQgCl-0t4idpDetYE3UYM"; // GCM Server API Key
/** PushAPIDAO */
@Resource(name="PushDeviceAPIDAO")
private PushDeviceAPIDAO pushDeviceAPIDAO;
/**
* 알림 설정 정보를 등록한다.
* @param vo - 등록할 정보가 담긴 PushDeviceAPIVO
* @return 등록 결과
* @exception Exception
*/
/* public int insertVibrator(PushDeviceAPIVO vo) throws Exception {
LOGGER.debug(vo.toString());
return (Integer)PushDeviceAPIVO.insertVibrator(vo);
}
*/
/**
* 알림 설정 정보 목록을 조회한다.
* @param VO - 조회할 정보가 담긴 VibratorAPIVO
* @return 알림 설정 정보 목록
* @exception Exception
*/
public List<?> selectPushDeviceList(PushDeviceAPIVO searchVO) throws Exception {
return pushDeviceAPIDAO.selectPushDeviceList(searchVO);
}
/**
* Push Notification을 위해 Device 정보를 등록한다.
* @param vo - 등록할 정보가 담긴 PushAPIVO
* @return 등록 결과
* @exception Exception
*/
public int insertPushDevice(PushDeviceAPIVO vo) throws Exception {
LOGGER.debug(vo.toString());
return (Integer)pushDeviceAPIDAO.insertPushDevice(vo);
}
/**
* Push Notification을 서버에 요청한다.
* @param vo - 등록할 정보가 담긴 PushAPIVO
* @return 등록 결과
* @exception Exception
*/
public int insertPushInfo(PushDeviceAPIVO vo) throws Exception {
LOGGER.debug(vo.toString());
// Android GCM, iOS APNS 푸쉬 메시지를 발송한다.
if (vo.getOsType().equals("Android")) {
sendGCMPush(vo.getTokenId(), vo.getMessage());
} else if (vo.getOsType().equals("iOS")) {
sendAPNSPush(vo.getTokenId(), vo.getMessage());
}
return (Integer)pushDeviceAPIDAO.insertPushInfo(vo);
}
public int sendGCMPush(String pushRegId, String pushMessage) {
Sender sender = new Sender(GCM_SERVER_API_KEY); // 서버 API Key 입력
//String regId = "APA91bEDOiYUc2vb5KbECqK52DGeJgC9KmtOiUDLJed2pz4BLazPfTHNmHfJFJWm3n4I3xJVtIktDor5FI2TW0DjUwxPi9q4Vk3fIPBaO93_wsKqJUBSvuIwuZKRVlz3uu6xVmv0y6MGyzc-jTlXpSjRr4zGf1oLyg"; // 단말기 RegID 입력
Message message = new Message.Builder().addData("message", pushMessage).build();
List<String> list = new ArrayList<String>();
list.add(pushRegId);
MulticastResult multiResult;
try {
multiResult = sender.send(message, list, 5);
if (multiResult != null) {
List<Result> resultList = multiResult.getResults();
for (Result result : resultList) {
System.out.println(result.getMessageId());
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return 1;
}
return 0;
}
public int sendAPNSPush(String tokenId, String pushMessage) {
ArrayList<String> myTokens = new ArrayList<String>();
myTokens.add(tokenId);
HashMap<String, Object> map_pushInfo = new HashMap<String, Object>();
map_pushInfo.put("sender_nick", "egovDeviceAPI");
map_pushInfo.put("msg", pushMessage);
int result = sendPushIOS(myTokens, map_pushInfo);
return result;
}
public int sendPushIOS(ArrayList<String> tokens, HashMap<String, Object> map_pushInfo){
// 아이폰 푸시전송 - 최대 한글전송길이 45글자 (보낸이 + 내용)
int result = 0;
// 1. 푸시 기본정보 초기화
String sender_nick = (String)map_pushInfo.get("sender_nick");
String msg = (String)map_pushInfo.get("msg");
// 2. 싱글캐스트 or 멀티캐스트 구분
boolean single_push = true;
if(tokens.size()==1){
single_push = true;
}else{
single_push = false;
}
try{
// 3. 푸시 데이터 생성
PushNotificationPayload payLoad = new PushNotificationPayload();
JSONObject jo_body = new JSONObject();
JSONObject jo_aps = new JSONObject();
JSONArray ja = new JSONArray();
jo_aps.put("alert",msg);
jo_aps.put("badge",APNS_BADGE);
jo_aps.put("sound",APNS_SOUND);
jo_aps.put("content-available",1);
jo_body.put("aps",jo_aps);
jo_body.put("sender_nick",sender_nick);
payLoad = payLoad.fromJSON(jo_body.toString());
PushNotificationManager pushManager = new PushNotificationManager();
pushManager.initializeConnection(
new AppleNotificationServerBasicImpl(APNS_CERTIFICATE_PATH, APNS_CERTIFICATE_PWD,ConnectionToAppleServer.KEYSTORE_TYPE_PKCS12, APNS_DEV_HOST, APNS_PORT));
List<PushedNotification> notifications = new ArrayList<PushedNotification>();
if (single_push){
// 싱글캐스트 푸시 전송
Device device = new BasicDevice();
device.setToken(tokens.get(0));
PushedNotification notification = pushManager.sendNotification(device, payLoad);
notifications.add(notification);
}else{
// 멀티캐스트 푸시 전송
List<Device> device = new ArrayList<Device>();
for (String token : tokens){
device.add(new BasicDevice(token));
}
notifications = pushManager.sendNotifications(payLoad, device);
}
List<PushedNotification> failedNotifications = PushedNotification.findFailedNotifications(notifications);
List<PushedNotification> successfulNotifications = PushedNotification.findSuccessfulNotifications(notifications);
int failed = failedNotifications.size();
int successful = successfulNotifications.size();
if(failed > 0){
result = 1; // 푸시 실패건 발생
}else{
result = 0; // 푸시 모두 성공
}
}catch(KeystoreException ke){
result = 2;
}catch(CommunicationException ce){
result = 3;
}catch (Exception e) {
result = 4;
e.printStackTrace();
}
return result;
}
/**
* Push Notification 기기 상세 조회를 한다.
* @param vo - 등록할 정보가 담긴 PushDeviceAPIVO
* @return 조회 결과
* @exception Exception
*/
public PushDeviceAPIVO selectPushDevice(PushDeviceAPIVO vo) throws Exception {
return pushDeviceAPIDAO.selectPushDevice(vo);
}
/**
* Push Notification 송신 메세지 조회를 한다.
* @param vo - 등록할 정보가 담긴 PushDeviceAPIVO
* @return 조회 결과
* @exception Exception
*/
public List<?> selectPushMessageList(PushDeviceAPIVO VO) throws Exception {
return pushDeviceAPIDAO.selectPushMessageList(VO);
}
}
| 35.725632 | 201 | 0.653496 |
5c93e98e1afcf75e3f9ab666cb5ab48bf3d4a402 | 610 | package CoinFlip;
public class CountFlips {
public static void main(String[] args) {
final int NUM_FLIPS = 1000;
int heads = 0, tails = 0;
Coin myCoin = new Coin();
for (int count = 1; count <= NUM_FLIPS; count++)
{
myCoin.flip();
if (myCoin.isHeads())
heads++;
else
tails++;
}
System.out.println("The number flips: " + NUM_FLIPS);
System.out.println("The number of heads: " + heads);
System.out.println("The number of tails: " + tails);
}
}
| 25.416667 | 61 | 0.495082 |
e43436e5b105f5885cb1c6321ca329e88eb982ff | 353 | package org.mongodb.morphia.entities;
import org.bson.types.ObjectId;
import org.mongodb.morphia.annotations.Entity;
import org.mongodb.morphia.annotations.Id;
import org.mongodb.morphia.annotations.Indexed;
@Entity
public class NamedIndexOnValue {
@Id
private ObjectId id;
@Indexed(name = "value_ascending")
private long value = 4;
}
| 23.533333 | 47 | 0.767705 |
78382702aba46333091b7d5d9baa5f9b054c604a | 497 | package io.github.jzdayz.spring.framework;
import org.springframework.core.ResolvableType;
import java.util.ArrayList;
public class ResolvableTypeTests {
public static void main(String[] args) {
test1();
}
private static void test1() {
ResolvableType resolvableType = ResolvableType.forClass(B.class);
System.out.println();
}
private static class A<T>{
private T t;
}
private static class B extends ArrayList<A<String>> {
}
}
| 19.88 | 73 | 0.665996 |
4caaf64547731bd3313f73996bac901394f498c8 | 2,769 | /*
* Copyright 2018 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.geometry;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.geometry.PrimitiveArrays.Cursor;
import com.google.common.io.BaseEncoding;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import junit.framework.TestCase;
@GwtCompatible
public class VectorCoderTest extends TestCase {
public void testDecodeFromByteString() {
List<String> expected = Lists.newArrayList("fuji", "mutsu");
byte[] b = BaseEncoding.base16().decode("00000010040966756A696D75747375");
PrimitiveArrays.Bytes data = PrimitiveArrays.Bytes.fromByteArray(b);
int offset = 3;
List<String> v = VectorCoder.STRING.decode(data, data.cursor(offset));
assertEquals(expected, v);
}
public void testEmpty() throws IOException {
checkEncodedStringVector(Lists.newArrayList(), 1);
}
public void testEmptyString() throws IOException {
checkEncodedStringVector(Lists.newArrayList(""), 2);
}
public void testRepeatedEmptyStrings() throws IOException {
checkEncodedStringVector(Lists.newArrayList("", "", ""), 4);
}
public void testOneString() throws IOException {
checkEncodedStringVector(Lists.newArrayList("apples"), 8);
}
public void testTwoStrings() throws IOException {
checkEncodedStringVector(Lists.newArrayList("fuji", "mustu"), 12);
}
public void testTwoBigStrings() throws IOException {
checkEncodedStringVector(
Lists.newArrayList(Strings.repeat("x", 10000), Strings.repeat("y", 100000)), 110007);
}
private void checkEncodedStringVector(List<String> input, int expectedBytes) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
VectorCoder.STRING.encode(input, output);
assertEquals(expectedBytes, output.size());
PrimitiveArrays.Bytes data = PrimitiveArrays.Bytes.fromByteArray(output.toByteArray());
Cursor cursor = data.cursor();
List<String> actual = VectorCoder.STRING.decode(data, cursor);
assertEquals(input, actual);
assertEquals(expectedBytes, cursor.position);
}
}
| 35.5 | 99 | 0.749368 |
e3aaae9388b387774f18af5de145c934aad23f21 | 1,036 | package org.apache.spark.ml.tree;
/**
* Parameters for Random Forest algorithms.
*/
interface RandomForestParams extends org.apache.spark.ml.tree.TreeEnsembleParams {
/**
* Number of trees to train (>= 1).
* If 1, then no bootstrapping is used. If > 1, then bootstrapping is done.
* TODO: Change to always do bootstrapping (simpler). SPARK-7130
* (default = 20)
* <p>
* Note: The reason that we cannot add this to both GBT and RF (i.e. in TreeEnsembleParams)
* is the param <code>maxIter</code> controls how many trees a GBT has. The semantics in the algorithms
* are a bit different.
* @group param
* @return (undocumented)
*/
public org.apache.spark.ml.param.IntParam numTrees () ;
/**
* @deprecated This method is deprecated and will be removed in 3.0.0.
* @group setParam
* @param value (undocumented)
* @return (undocumented)
*/
public org.apache.spark.ml.tree.RandomForestParams setNumTrees (int value) ;
/** @group getParam */
public int getNumTrees () ;
}
| 35.724138 | 105 | 0.679537 |
49e225f92480f2cdb12d27b33dac5bf25329304b | 463 | package ru.job4j.strategy;
import org.junit.Ignore;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
@Ignore
public class SquareTest {
@Test
public void whenDraweSquare() {
Square square = new Square();
assertThat(square.draw(),
is(new StringBuilder().append("+++++++\n").append("+ +\n").append("+ +\n").append("+++++++\n").toString())
);
}
}
| 23.15 | 130 | 0.600432 |
574b7110c1cb395a7b970d4f3f9951cbb25f302b | 1,324 | package ru.assisttech.sdk.processor;
import android.app.Activity;
import ru.assisttech.sdk.AssistResult;
import ru.assisttech.sdk.storage.AssistTransaction;
/**
* Callbacks for AssistProcessor {@link AssistBaseProcessor}
*/
public interface AssistProcessorListener {
/**
* Called when AssistProcessor finished without errors.
*
* @param id transaction ID {@link AssistTransaction}
* @param result result given by AssistProcessor
*/
void onFinished(long id, AssistResult result);
/**
* Called when error encountered by AssistProcessor
*
* @param id transaction ID {@link AssistTransaction}
* @param message error description.
*/
void onError(long id, String message);
/**
* Called when there is network error
*
* @param id transaction ID {@link AssistTransaction}
* @param message error description.
*/
void onNetworkError(long id, String message);
/**
* Called when AssistProcessor was stopped (e.g. by user).
*
* @param id transaction ID {@link AssistTransaction}
*/
void onTerminated(long id);
/**
* Called when AssistProcessor creates new top Activity.
*
* @param activity new created Activity
*/
void onActivityCreated(Activity activity);
}
| 25.960784 | 62 | 0.666163 |
ebb1ea2d6026fd2edbbdde9b197fa24aece0e4c3 | 3,556 | // CHANGES
// This is a customized copy of soot.tagkits.JasminAttribute class.
// It decodes the CodeAttribute format.
// Read comments on CodeAttr.java for more information.
// Feng Qian
// Jan 25, 2001
/* Soot - a J*va Optimization Framework
* Copyright (C) 2000 Patrice Pominville and Feng Qian
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/*
* Modified by the Sable Research Group and others 1997-1999.
* See the 'credits' file distributed with Soot for the complete list of
* contributors. (Soot is distributed at http://www.sable.mcgill.ca/soot)
*/
package jas;
import java.util.*;
import java.io.*;
/**
* This class must be extended by Attributes that can
* be emitted in Jasmin. The attributes must format their data
* in Base64 and if Unit references they may contain must be emitted as
* labels embedded and
* escaped in the attribute's Base64 data stream at the location where the value
* of their pc is to occur. For example:
<pre>
aload_1
iload_2
label2:
iaload
label3:
iastore
iinc 2 1
label0:
iload_2
aload_0
arraylength
label4:
if_icmplt label1
return
.code_attribute ArrayCheckAttribute "%label2%Aw==%label3%Ag==%label4%Ag=="
</pre>
*
*/
class CodeAttributeDecoder
{
public static byte[] decode(String attr, Hashtable labelToPc)
{
List attributeHunks = new LinkedList();
int attributeSize = 0;
int tableSize = 0;
StringTokenizer st = new StringTokenizer(attr, "%", true);
boolean isLabel = false;
byte[] pcArray;
while(st.hasMoreTokens()) {
String token = st.nextToken();
if( token.equals( "%" ) ) {
isLabel = !isLabel;
continue;
}
if(isLabel) {
Integer pc = (Integer) labelToPc.get(token);
if(pc == null)
throw new RuntimeException("PC is null, the token is "+token);
int pcvalue = pc.intValue();
if(pcvalue > 65535)
throw new RuntimeException("PC great than 65535, the token is "+token+" : " +pcvalue);
pcArray = new byte[2];
pcArray[1] = (byte)(pcvalue&0x0FF);
pcArray[0] = (byte)((pcvalue>>8)&0x0FF);
attributeHunks.add(pcArray);
attributeSize += 2;
tableSize++;
} else {
byte[] hunk = Base64.decode(token.toCharArray());
attributeSize += hunk.length;
attributeHunks.add(hunk);
}
}
attributeSize += 2;
byte[] attributeValue = new byte[attributeSize];
attributeValue[0] = (byte)((tableSize>>8)&0x0FF);
attributeValue[1] = (byte)(tableSize&0x0FF);
int index = 2;
Iterator it = attributeHunks.iterator();
while(it.hasNext()) {
byte[] hunk = (byte[]) it.next();
for(int i = 0; i < hunk.length; i++) {
attributeValue[index++] = hunk[i];
}
}
if(index != (attributeSize))
throw new RuntimeException("Index does not euqal to attrubute size :"+index+" -- "+attributeSize);
return attributeValue;
}
}
| 25.768116 | 103 | 0.681665 |
4664650f5aa66ead3bd8b4b1ed5f059548dd1fff | 1,077 | package com.devmate.pub.client.models;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Objects;
@JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE)
public class CustomersMeta {
@JsonProperty("total")
private Integer total;
protected CustomersMeta() {}
public CustomersMeta(Integer total) {
this.total = total;
}
public int getTotal() {
return total;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("CustomersMeta{");
sb.append("total=").append(total);
sb.append('}');
return sb.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CustomersMeta that = (CustomersMeta) o;
return Objects.equal(total, that.total);
}
@Override
public int hashCode() {
return Objects.hashCode(total);
}
}
| 25.046512 | 69 | 0.648097 |
f14507ff9a60e10701da5030f9a6b976f8008c41 | 873 | import java.awt.Color;
import acm.graphics.*;
public class myPiece
{
protected int x;//x board coordinate
protected int y;//y board coordinate
protected int gx;//x pixel coordinate
protected int gy;//y pixel coordinate
protected Color color;//piece color
protected GOval piece;
public myPiece(int pieceX, int pieceY, int pieceWidth, Color pieceColor, int offset)
{//offset is for smaller miniCircle width when game is won
x=pieceX;
y=pieceY;
gx=pieceX*(pieceWidth+Connect4Game.xPieceBorder)+Connect4Game.xBorder;
gy=pieceY*(pieceWidth+Connect4Game.yPieceBorder)+2*Connect4Game.yBorder;
color=pieceColor;
piece = (offset==0)? new GOval(gx,gy, pieceWidth, pieceWidth) : new GOval(gx+pieceWidth/2-offset/2,gy+pieceWidth/2-offset/2, offset, offset);
piece.setFillColor(pieceColor);
piece.setFilled(true);
}//Piece constructor
}//class Piece
| 30.103448 | 143 | 0.756014 |
d289d8c713052ccb2b566b606a1f29a7e6550b44 | 1,052 | package seedu.recruit.logic.parser;
import static seedu.recruit.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.recruit.logic.parser.CommandParserTestUtil.assertParseFailure;
import static seedu.recruit.logic.parser.CommandParserTestUtil.assertParseSuccess;
import static seedu.recruit.testutil.TypicalIndexes.INDEX_FIRST;
import org.junit.Test;
import seedu.recruit.logic.commands.SelectCompanyCommand;
/**
* Test scope: similar to {@code DeleteCandidateCommandParserTest}.
* @see DeleteCandidateCommandParserTest
*/
public class SelectCompanyCommandParserTest {
private SelectCompanyCommandParser parser = new SelectCompanyCommandParser();
@Test
public void parse_validArgs_returnsSelectCommand() {
assertParseSuccess(parser, "1", new SelectCompanyCommand(INDEX_FIRST));
}
@Test
public void parse_invalidArgs_throwsParseException() {
assertParseFailure(parser, "a", String.format(MESSAGE_INVALID_COMMAND_FORMAT,
SelectCompanyCommand.MESSAGE_USAGE));
}
}
| 33.935484 | 85 | 0.794677 |
b1359e20e1f3fa33841686710d8847c86e0816db | 2,398 | /*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.currysrc.processors;
import com.google.currysrc.api.process.Context;
import com.google.currysrc.api.process.Processor;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.Name;
import org.eclipse.jdt.core.dom.QualifiedName;
import org.eclipse.jdt.core.dom.rewrite.ASTRewrite;
/**
* Changes any qualified names in the AST that start with {@code oldPrefix} to start with
* {@code newPrefix} instead.
*/
public final class ModifyQualifiedNames implements Processor {
private final String oldPrefix;
private final String newPrefix;
public ModifyQualifiedNames(String oldPrefix, String newPrefix) {
this.oldPrefix = oldPrefix;
this.newPrefix = newPrefix;
}
@Override
public void process(Context context, CompilationUnit cu) {
final ASTRewrite rewrite = context.rewrite();
ASTVisitor visitor = new ASTVisitor(true /* visitDocTags */) {
@Override
public boolean visit(QualifiedName node) {
Name qualifier = node.getQualifier();
if (qualifier != null) {
String fullyQualifiedName = qualifier.getFullyQualifiedName();
if (fullyQualifiedName.startsWith(oldPrefix)) {
String newQualifierString = newPrefix + fullyQualifiedName
.substring(oldPrefix.length());
Name newQualifier = node.getAST().newName(newQualifierString);
rewrite.replace(qualifier, newQualifier, null /* editGroup */);
}
}
return false;
}
};
cu.accept(visitor);
}
@Override
public String toString() {
return "ModifyQualifiedNames{" +
"oldPrefix='" + oldPrefix + '\'' +
", newPrefix='" + newPrefix + '\'' +
'}';
}
}
| 33.305556 | 89 | 0.69558 |
a4033f40c2accc1f40bdaa1dc39ca7e3caf98ecd | 708 | package javax.microedition.sensor;
/**
* Basic implementation of the JSR256 LimitCondition class
*
* @author Lawrie Griffiths
*/
public class LimitCondition extends OperatorTest implements Condition {
private double limit;
private String operator;
public LimitCondition(double limit, String operator) {
this.limit = limit;
this.operator = operator;
}
public boolean isMet(double doubleValue) {
return test(doubleValue, limit, operator);
}
public boolean isMet(Object value) {
return false;
}
public final double getLimit() {
return limit;
}
public final String getOperator() {
return operator;
}
public String toString() {
return " " + operator + " " + limit;
}
}
| 19.135135 | 71 | 0.716102 |
ce301f2beb8e2118a47130b6f5935d7120ea7d2c | 7,926 | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package android.support.v4.hardware.display;
import android.content.Context;
import android.hardware.display.DisplayManager;
import android.view.Display;
import android.view.WindowManager;
import java.util.WeakHashMap;
public abstract class DisplayManagerCompat
{
private static class DisplayManagerCompatApi14Impl extends DisplayManagerCompat
{
public Display getDisplay(int i)
{
Display display = mWindowManager.getDefaultDisplay();
// 0 0:aload_0
// 1 1:getfield #24 <Field WindowManager mWindowManager>
// 2 4:invokeinterface #31 <Method Display WindowManager.getDefaultDisplay()>
// 3 9:astore_2
if(display.getDisplayId() == i)
//* 4 10:aload_2
//* 5 11:invokevirtual #37 <Method int Display.getDisplayId()>
//* 6 14:iload_1
//* 7 15:icmpne 20
return display;
// 8 18:aload_2
// 9 19:areturn
else
return null;
// 10 20:aconst_null
// 11 21:areturn
}
public Display[] getDisplays()
{
return (new Display[] {
mWindowManager.getDefaultDisplay()
});
// 0 0:iconst_1
// 1 1:anewarray Display[]
// 2 4:dup
// 3 5:iconst_0
// 4 6:aload_0
// 5 7:getfield #24 <Field WindowManager mWindowManager>
// 6 10:invokeinterface #31 <Method Display WindowManager.getDefaultDisplay()>
// 7 15:aastore
// 8 16:areturn
}
public Display[] getDisplays(String s)
{
if(s == null)
//* 0 0:aload_1
//* 1 1:ifnonnull 9
return getDisplays();
// 2 4:aload_0
// 3 5:invokevirtual #42 <Method Display[] getDisplays()>
// 4 8:areturn
else
return new Display[0];
// 5 9:iconst_0
// 6 10:anewarray Display[]
// 7 13:areturn
}
private final WindowManager mWindowManager;
DisplayManagerCompatApi14Impl(Context context)
{
// 0 0:aload_0
// 1 1:invokespecial #12 <Method void DisplayManagerCompat()>
mWindowManager = (WindowManager)context.getSystemService("window");
// 2 4:aload_0
// 3 5:aload_1
// 4 6:ldc1 #14 <String "window">
// 5 8:invokevirtual #20 <Method Object Context.getSystemService(String)>
// 6 11:checkcast #22 <Class WindowManager>
// 7 14:putfield #24 <Field WindowManager mWindowManager>
// 8 17:return
}
}
private static class DisplayManagerCompatApi17Impl extends DisplayManagerCompat
{
public Display getDisplay(int i)
{
return mDisplayManager.getDisplay(i);
// 0 0:aload_0
// 1 1:getfield #27 <Field DisplayManager mDisplayManager>
// 2 4:iload_1
// 3 5:invokevirtual #32 <Method Display DisplayManager.getDisplay(int)>
// 4 8:areturn
}
public Display[] getDisplays()
{
return mDisplayManager.getDisplays();
// 0 0:aload_0
// 1 1:getfield #27 <Field DisplayManager mDisplayManager>
// 2 4:invokevirtual #36 <Method Display[] DisplayManager.getDisplays()>
// 3 7:areturn
}
public Display[] getDisplays(String s)
{
return mDisplayManager.getDisplays(s);
// 0 0:aload_0
// 1 1:getfield #27 <Field DisplayManager mDisplayManager>
// 2 4:aload_1
// 3 5:invokevirtual #39 <Method Display[] DisplayManager.getDisplays(String)>
// 4 8:areturn
}
private final DisplayManager mDisplayManager;
DisplayManagerCompatApi17Impl(Context context)
{
// 0 0:aload_0
// 1 1:invokespecial #15 <Method void DisplayManagerCompat()>
mDisplayManager = (DisplayManager)context.getSystemService("display");
// 2 4:aload_0
// 3 5:aload_1
// 4 6:ldc1 #17 <String "display">
// 5 8:invokevirtual #23 <Method Object Context.getSystemService(String)>
// 6 11:checkcast #25 <Class DisplayManager>
// 7 14:putfield #27 <Field DisplayManager mDisplayManager>
// 8 17:return
}
}
DisplayManagerCompat()
{
// 0 0:aload_0
// 1 1:invokespecial #28 <Method void Object()>
// 2 4:return
}
public static DisplayManagerCompat getInstance(Context context)
{
WeakHashMap weakhashmap = sInstances;
// 0 0:getstatic #26 <Field WeakHashMap sInstances>
// 1 3:astore_3
weakhashmap;
// 2 4:aload_3
JVM INSTR monitorenter ;
// 3 5:monitorenter
DisplayManagerCompat displaymanagercompat = (DisplayManagerCompat)sInstances.get(((Object) (context)));
// 4 6:getstatic #26 <Field WeakHashMap sInstances>
// 5 9:aload_0
// 6 10:invokevirtual #34 <Method Object WeakHashMap.get(Object)>
// 7 13:checkcast #2 <Class DisplayManagerCompat>
// 8 16:astore_2
Object obj = ((Object) (displaymanagercompat));
// 9 17:aload_2
// 10 18:astore_1
if(displaymanagercompat != null) goto _L2; else goto _L1
// 11 19:aload_2
// 12 20:ifnonnull 49
_L1:
if(android.os.Build.VERSION.SDK_INT < 17)
break MISSING_BLOCK_LABEL_53;
// 13 23:getstatic #40 <Field int android.os.Build$VERSION.SDK_INT>
// 14 26:bipush 17
// 15 28:icmplt 53
obj = ((Object) (new DisplayManagerCompatApi17Impl(context)));
// 16 31:new #9 <Class DisplayManagerCompat$DisplayManagerCompatApi17Impl>
// 17 34:dup
// 18 35:aload_0
// 19 36:invokespecial #43 <Method void DisplayManagerCompat$DisplayManagerCompatApi17Impl(Context)>
// 20 39:astore_1
_L3:
sInstances.put(((Object) (context)), obj);
// 21 40:getstatic #26 <Field WeakHashMap sInstances>
// 22 43:aload_0
// 23 44:aload_1
// 24 45:invokevirtual #47 <Method Object WeakHashMap.put(Object, Object)>
// 25 48:pop
_L2:
weakhashmap;
// 26 49:aload_3
JVM INSTR monitorexit ;
// 27 50:monitorexit
return ((DisplayManagerCompat) (obj));
// 28 51:aload_1
// 29 52:areturn
obj = ((Object) (new DisplayManagerCompatApi14Impl(context)));
// 30 53:new #6 <Class DisplayManagerCompat$DisplayManagerCompatApi14Impl>
// 31 56:dup
// 32 57:aload_0
// 33 58:invokespecial #48 <Method void DisplayManagerCompat$DisplayManagerCompatApi14Impl(Context)>
// 34 61:astore_1
goto _L3
//* 35 62:goto 40
context;
// 36 65:astore_0
weakhashmap;
// 37 66:aload_3
JVM INSTR monitorexit ;
// 38 67:monitorexit
throw context;
// 39 68:aload_0
// 40 69:athrow
}
public abstract Display getDisplay(int i);
public abstract Display[] getDisplays();
public abstract Display[] getDisplays(String s);
public static final String DISPLAY_CATEGORY_PRESENTATION = "android.hardware.display.category.PRESENTATION";
private static final WeakHashMap sInstances = new WeakHashMap();
static
{
// 0 0:new #21 <Class WeakHashMap>
// 1 3:dup
// 2 4:invokespecial #24 <Method void WeakHashMap()>
// 3 7:putstatic #26 <Field WeakHashMap sInstances>
//* 4 10:return
}
}
| 34.46087 | 109 | 0.581378 |
fc69d19c87e7f2b4ff269e452b2f7363647f3661 | 750 | package psidev.psi.mi.jami.xml.io.writer.elements.impl.extended;
import javax.xml.stream.XMLStreamWriter;
/**
* Xml writer for open cv terms
*
* @author Marine Dumousseau (marine@ebi.ac.uk)
* @version $Id$
* @since <pre>12/11/13</pre>
*/
public class XmlOpenCvTermWriter extends psidev.psi.mi.jami.xml.io.writer.elements.impl.XmlOpenCvTermWriter {
/**
* <p>Constructor for XmlOpenCvTermWriter.</p>
*
* @param writer a {@link javax.xml.stream.XMLStreamWriter} object.
*/
public XmlOpenCvTermWriter(XMLStreamWriter writer) {
super(writer);
}
/** {@inheritDoc} */
@Override
protected void initialiseXrefWriter() {
super.setXrefWriter(new XmlDbXrefWriter(getStreamWriter()));
}
}
| 25.862069 | 109 | 0.681333 |
f18affd9338c62f015302c5914736a8f31e950a9 | 1,218 | /*
* Copyright © 2018 Edwin Njeru (mailnjeru@gmail.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 io.github.ghacupha.keeper.book.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collector;
public class ImmutableListCollector {
/**
* @param <t> Type of collection
* @return An Immutable {@link List} {@link Collection}
*/
public static <t> Collector<t, List<t>, List<t>> toImmutableList() {
return Collector.of(ArrayList::new, List::add, (left, right) -> {
left.addAll(right);
return left;
}, Collections::unmodifiableList);
}
}
| 32.918919 | 75 | 0.698686 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.