blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 132 | path stringlengths 2 382 | src_encoding stringclasses 34
values | length_bytes int64 9 3.8M | score float64 1.5 4.94 | int_score int64 2 5 | detected_licenses listlengths 0 142 | license_type stringclasses 2
values | text stringlengths 9 3.8M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
d9db35856260697ee3195c1f2bb46695167eb8d6 | Java | beerkitsakon/opencvtest1 | /app/src/main/java/com/example/kuro/opencvtest1/MainActivity.java | UTF-8 | 5,208 | 2.0625 | 2 | [] | no_license | package com.example.kuro.opencvtest1;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Camera;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.JavaCamera2View;
import org.opencv.android.JavaCameraView;
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.imgproc.Imgproc;
public class MainActivity extends AppCompatActivity implements CameraBridgeViewBase.CvCameraViewListener2 {
private static final String TAG = "Mytag";
Mat mRGBa,imgGray,imgCanny;
ImageView show_image;
BaseLoaderCallback mloadercallback=new BaseLoaderCallback(this) {
@Override
public void onManagerConnected(int status) {
switch (status){
case BaseLoaderCallback.SUCCESS:{
break;
}
default:{
super.onManagerConnected(status);
break;
}
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 0);
}
show_image = (ImageView) findViewById(R.id.show_image);
Button cap_button = (Button) findViewById(R.id.capture_button);
cap_button.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 1888);
break;
default:
break;
}
return true;
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1888 && resultCode == RESULT_OK) {
Bitmap mphoto = (Bitmap) data.getExtras().get("data");
Mat mat = new Mat();
Mat edge = new Mat();
Bitmap bmp32 = mphoto.copy(Bitmap.Config.ARGB_8888, true);
Utils.bitmapToMat(bmp32, mat);
/* mRGBa = new Mat(mphoto.getHeight(), mphoto.getWidth(),CvType.CV_8UC4);
imgGray = new Mat(mphoto.getHeight(), mphoto.getWidth(),CvType.CV_8UC1);
imgCanny = new Mat(mphoto.getHeight(), mphoto.getWidth(),CvType.CV_8UC1); */
mRGBa = new Mat(mat.size(),CvType.CV_8UC4);
imgGray = new Mat(mat.size(),CvType.CV_8UC1);
imgCanny = new Mat(mat.size(),CvType.CV_8UC1);
Imgproc.cvtColor(mat, imgGray, Imgproc.COLOR_RGB2GRAY);
/* Imgproc.cvtColor(imgGray, mat, Imgproc.COLOR_GRAY2BGR);
//To compate with default android standard (4 channel), so we need to change from 1 channel to 4 channel before we display
Imgproc.cvtColor(mat, mat, Imgproc.COLOR_BGR2BGRA);*/
// Imgproc.Canny(imgGray, mat, 50, 150);
Imgproc.Canny(imgGray, imgCanny, 50, 150);
Utils.matToBitmap(imgCanny, bmp32);
// mRGBa = bmp32;
show_image.setImageBitmap(bmp32);
//Imgproc finalimage = Imgproc.cvtColor(bmp32, imgGray, Imgproc.COLOR_YUV420sp2GRAY);
mat.release();
}
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
protected void onResume(){
super.onResume();
if(!OpenCVLoader.initDebug()){
Log.d(TAG,"Opencv not loaded");
mloadercallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
}
else
{
Log.d(TAG,"Opencv loaded successfully");
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION,this,mloadercallback);
}
}
@Override
public void onCameraViewStarted(int width, int height) {
}
@Override
public void onCameraViewStopped() {
}
@Override
public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
return null;
}
}
| true |
3a5c0af0150cc977623cce7c4b83ad41023b62c4 | Java | sezya-kot/SailorSystem | /Sailor/src/com/sezyakot/sailor/OrderItemsTemp.java | UTF-8 | 535 | 1.679688 | 2 | [] | no_license | package com.sezyakot.sailor;
import com.google.gson.annotations.SerializedName;
/**
* Created by Android on 04.09.2014.
*/
public class OrderItemsTemp {
@SerializedName("type") private int mType;
@SerializedName("item") private int mItemId;
@SerializedName("unit_detail") private int mUnitDetailId;
@SerializedName("price") private double mPrice;
@SerializedName("quantity") private int mQuantity;
}
| true |
b8db7bd98654850077b9fd9cc0ab50b5152f4b20 | Java | robmoral/SpringBoot-Jenkin-Maven | /src/main/java/com/example/myself/myself/UserRepoInterface.java | UTF-8 | 564 | 1.78125 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.example.myself.myself;
/**
*
* @author robmoral
*/
import org.springframework.data.repository.reactive.ReactiveCrudRepository;
import org.springframework.stereotype.Repository;
import reactor.core.publisher.Flux;
@Repository
public interface UserRepoInterface extends ReactiveCrudRepository<Users,Long> {
Flux<Users> findByLastName(String lastName);
}
| true |
8d1869c7181a327cbd566f00c8bc03a4089f8953 | Java | Abealkindy/FreakManga | /app/src/main/java/com/otongsoetardjoe/freakmangabrandnew/utils/Const.java | UTF-8 | 1,322 | 1.539063 | 2 | [] | no_license | package com.otongsoetardjoe.freakmangabrandnew.utils;
public class Const {
/**
* Neko URLs
**/
public static final String BASE_URL_NEKO = "https://nekopoi.care/";
public static final String BASE_PAGE_NEKO_HEN = "https://nekopoi.care/category/hentai/page/%1$s";
public static final String BASE_PAGE_NEKO_JAV = "https://nekopoi.care/category/jav/page/%1$s";
/**
* Manga URLs
**/
//Global use URLs
public static final String BASE_URL = "https://nhentai.net";
public static final String BASE_URL_HENCAFE = "https://hentai.cafe";
public static final String BASE_PAGE_URL = "/?page=%1$s";
public static final String OTHER_PAGE_URL = "?page=%1$s";
public static final String POPULAR_SORT = "/popular";
//Search URLs
public static final String BASE_SEARCH_URL = "/search/?q=%1$s&page=%2$s";
public static final String POPULAR_SORT_SEARCH = "&sort=popular";
//Tag URL
public static final String BASE_TAGS_URL = "/tags/";
//Artist URL
public static final String BASE_ARTIST_URL = "/artists/";
//Character URL
public static final String BASE_CHAR_URL = "/characters/";
//Parodies URL
public static final String BASE_PARODIES_URL = "/parodies/";
//Groups URL
public static final String BASE_GROUP_URL = "/groups/";
}
| true |
a3ee0ced065b3b8a54ae8fc90decd03ff952f3b9 | Java | kabigon-li/sizaikanri-java | /src/main/java/co/jp/mamol/myapp/action/DeleAction.java | UTF-8 | 1,170 | 1.929688 | 2 | [] | no_license | package co.jp.mamol.myapp.action;
import java.util.List;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;
import co.jp.mamol.myapp.dto.CategoryDto;
import co.jp.mamol.myapp.dto.UserDto;
import co.jp.mamol.myapp.form.BuyRequestForm;
import co.jp.mamol.myapp.form.DeleForm;
import co.jp.mamol.myapp.service.BuyRequsetService;
@Results({ @Result(name = "delete", location = "/WEB-INF/jsp/deleteConfirm.jsp") })
public class DeleAction extends BaseAction {
DeleForm form = new DeleForm();
@Autowired
BuyRequsetService service;
//初期表示
@Action("/deleconfirm/init")
public String init() {
List<CategoryDto> categoryList = service.getCategory();
form.setCategoryList(categoryList);
return "delete";
}
public DeleForm getForm() {
return form;
}
public void setForm(DeleForm form) {
this.form = form;
}
public BuyRequsetService getService() {
return service;
}
public void setService(BuyRequsetService service) {
this.service = service;
}
}
| true |
3c4a64c7ff61a237fd31538306328c9918d04fd6 | Java | ybak/karazam-santian | /src/main/java/com/klzan/p2p/vo/schedule/ScheduleJobVo.java | UTF-8 | 1,994 | 1.960938 | 2 | [] | no_license | package com.klzan.p2p.vo.schedule;
import com.klzan.p2p.common.vo.BaseVo;
/**
* Created by suhao Date: 2017/4/18 Time: 16:14
*
* @version: 1.0
*/
public class ScheduleJobVo extends BaseVo {
/**
* spring bean名称
*/
private String beanName;
/**
* 方法名
*/
private String methodName;
/**
* 参数
*/
private String params;
/**
* 任务key
*/
private String key;
/**
* 任务计划执行次数
*/
private Integer planCount;
/**
* 已执行次数
*/
private Integer excutedCount;
/**
* cron表达式
*/
private String cronExpression;
/**
* 备注
*/
private String remark;
public String getBeanName() {
return beanName;
}
public void setBeanName(String beanName) {
this.beanName = beanName;
}
public String getMethodName() {
return methodName;
}
public void setMethodName(String methodName) {
this.methodName = methodName;
}
public String getParams() {
return params;
}
public void setParams(String params) {
this.params = params;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public Integer getPlanCount() {
return planCount;
}
public void setPlanCount(Integer planCount) {
this.planCount = planCount;
}
public Integer getExcutedCount() {
return excutedCount;
}
public void setExcutedCount(Integer excutedCount) {
this.excutedCount = excutedCount;
}
public String getCronExpression() {
return cronExpression;
}
public void setCronExpression(String cronExpression) {
this.cronExpression = cronExpression;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
}
| true |
c4a4dba2547cd825136ea6d05050c1e690812581 | Java | dankin96/PlayMate | /src/main/java/com/technostart/playmate/frame_reader/CvFrameReader.java | UTF-8 | 1,466 | 2.96875 | 3 | [] | no_license | package com.technostart.playmate.frame_reader;
import org.opencv.core.Mat;
import org.opencv.videoio.VideoCapture;
import java.io.Closeable;
import java.io.IOException;
public class CvFrameReader implements FrameReader<Mat>, Closeable {
private VideoCapture capture;
private int frameNumber;
public CvFrameReader(String fileName) {
capture = new VideoCapture(fileName);
frameNumber = (int) capture.get(7);
}
@Override
public Mat read() {
Mat frame = new Mat();
if (capture.isOpened()) {
capture.read(frame);
}
return frame;
}
@Override
public Mat next() {
int index = getCurrentFrameNumber() + 1;
if (index >= frameNumber) {
index = frameNumber - 2;
capture.set(1, index);
}
return read();
}
@Override
public Mat prev() {
int index = getCurrentFrameNumber() - 2;
if (index < 0) index = 0;
capture.set(1, index);
return read();
}
@Override
public Mat get(int index) {
if (0 <= index && index < frameNumber) {
capture.set(1, index);
}
return read();
}
@Override
public int getCurrentFrameNumber() {
return (int) capture.get(1);
}
@Override
public int getFramesNumber() {
return frameNumber;
}
@Override
public void close() {
capture.release();
}
}
| true |
04dc0b1c275c2b2cd3355fc115a9b6b586c7057a | Java | elumixor/Sims-5 | /java/src/devices/Piano.java | UTF-8 | 571 | 2.84375 | 3 | [] | no_license | package devices;
import Animate.Human.Human;
import responsive.events.Event;
public class Piano extends Device implements Satisfier {
public Piano() {super(1.f, .005f);}
@Override
protected void consume() {}
@Override
public boolean satisfy(Human player) {
System.out.printf("%s tries to plays the piano, Happiness: %.0f%%%n", player.name, player.happiness.get() * 100f);
return use(2, 5,
() -> player.happiness.satisfyBy(.3f),
() -> Event.delayed(event -> satisfy(player), 15, 0), player);
}
}
| true |
8f77aaaa7fd41a7df6d2839aae54296235655242 | Java | jhuilin/CS-316-PrincipleOfProgrammingLanguage | /Interpreter/src/AddTermItem.java | UTF-8 | 488 | 3.296875 | 3 | [] | no_license | import java.util.*;
class AddTermItem extends TermItem
{
AddTermItem(Term t)
{
term = t;
}
void printParseTree(String indent)
{
IO.displayln(indent + indent.length() + " +");
term.printParseTree(indent);
}
@Override
Val Eval(HashMap<String, Val> state)
{
if (term.Eval(state) instanceof BoolVal)
{
System.out.println("Error: + operator cannot be applied to " + term.Eval(state));
return null;
}
return (term.Eval(state));
}
} | true |
50bc5aeb34c69265bade58bfd05a3382b72bfa1c | Java | RenanOliveiraSC/Algoritimos | /Algoritimos.zip_expanded/Algoritimos/src/exercicios4/D_exercicio.java | WINDOWS-1252 | 168 | 2.296875 | 2 | [] | no_license | package exercicios4;
public class D_exercicio {
public static void main(String[] args) {
if (1 == 1) {
System.out.println("1 igual a 1");
}
}
}
| true |
5a7845a8ef194a75665ee8c6ec58ab70158ae28f | Java | oneintegralanomaly/ProjectMini_Group03 | /miniproject/miniproject/src/controller/RegisterController.java | UTF-8 | 3,306 | 2.265625 | 2 | [] | no_license | package controller;
import com.jfoenix.controls.JFXButton;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ResourceBundle;
import javafx.animation.Interpolator;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.StackPane;
import javafx.util.Duration;
public class RegisterController implements Initializable {
@FXML
private AnchorPane container;
@FXML
private JFXButton loginButton1;
@FXML
private TextField name;
@FXML
private TextField id;
@FXML
private PasswordField pwd;
@FXML
private JFXButton membersBtn;
@Override
public void initialize(URL url, ResourceBundle rb) {
membersBtn.setOnAction(e->membersAction(e));
}
@FXML
private void open_login_form(MouseEvent event) throws IOException {
Parent root = FXMLLoader.load(getClass().getResource("Login.fxml"));
Scene scene = loginButton1.getScene();
root.translateYProperty().set(scene.getHeight());
StackPane parentContainer = (StackPane) scene.getRoot();
parentContainer.getChildren().add(root);
Timeline timeline = new Timeline();
KeyValue kv = new KeyValue(root.translateYProperty(), 0, Interpolator.EASE_IN);
KeyFrame kf = new KeyFrame(Duration.seconds(1), kv);
timeline.getKeyFrames().add(kf);
timeline.setOnFinished(event1 -> {
parentContainer.getChildren().remove(container);
});
timeline.play();
}
public void membersAction(ActionEvent event){
String uName = name.getText();
String uId = id.getText();
String uPwd = pwd.getText();
String jdbcUrl = "jdbc:mysql://localhost:3306/mysql?useUnicode=true&serverTimezone=Asia/Seoul";
String dbId = "root";
String dbPw = "1234";
Connection conn = null;
PreparedStatement pstmt = null;
String sql = "";
int num = 0;
new RegisterController();
String name = uName;
String id = uId;
String pw = uPwd;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection(jdbcUrl, dbId, dbPw);
sql = "INSERT INTO bingo.members VALUES(?,?,?,?)";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, num);
pstmt.setString(2, name);
pstmt.setString(3, id);
pstmt.setString(4, pw);
pstmt.executeUpdate();
}
catch (Exception e) {
e.printStackTrace();
} finally{
if(pstmt!=null) try{pstmt.close();}catch(SQLException ex){}
if(conn!=null) try{conn.close();}catch(SQLException ex){}
}
}
}
| true |
fa35cd882891af73624a5bf0a4ae35ba0de5894e | Java | monalisa8/fencewithspark | /src/main/java/com/wrkspot/emp/fence/model/UserFence2.java | UTF-8 | 3,142 | 1.78125 | 2 | [] | no_license | package com.wrkspot.emp.fence.model;
import org.mongodb.morphia.annotations.Entity;
import org.mongodb.morphia.annotations.Id;
import java.util.Date;
@Entity
public class UserFence2 {
public String get_id() {
return _id;
}
public void set_id(String _id) {
this._id = _id;
}
public String getEmployeeID() {
return employeeID;
}
public void setEmployeeID(String employeeID) {
this.employeeID = employeeID;
}
public String getSiteID() {
return siteID;
}
public void setSiteID(String siteID) {
this.siteID = siteID;
}
public String getClientID() {
return clientID;
}
public void setClientID(String clientID) {
this.clientID = clientID;
}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
public String getFloor() {
return floor;
}
public void setFloor(String floor) {
this.floor = floor;
}
public String getWing() {
return wing;
}
public void setWing(String wing) {
this.wing = wing;
}
public String getRoom_identifier() {
return room_identifier;
}
public void setRoom_identifier(String room_identifier) {
this.room_identifier = room_identifier;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public String getRange() {
return range;
}
public void setRange(String range) {
this.range = range;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public String getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(String updatedAt) {
this.updatedAt = updatedAt;
}
public String getUpdatedBy() {
return updatedBy;
}
public void setUpdatedBy(String updatedBy) {
this.updatedBy = updatedBy;
}
public double getConfidencePercentage() {
return confidencePercentage;
}
public void setConfidencePercentage(double confidencePercentage) {
this.confidencePercentage = confidencePercentage;
}
@Id
String _id;
String employeeID;
String siteID;
String clientID;
Date timestamp;
String floor;
String wing;
String room_identifier;
String name;
String type;
String uuid;
String range;
Date createdAt;
String createdBy;
String updatedAt;
String updatedBy;
double confidencePercentage;
}
| true |
a3c1b3797fd9469d93ddce10864922bd60bf958b | Java | YohooShop/back-end | /mall-admin/src/main/java/com/yoooho/mall/service/impl/SmsShopConfigServiceImpl.java | UTF-8 | 1,444 | 2.140625 | 2 | [] | no_license | package com.yoooho.mall.service.impl;
import com.yoooho.mall.mapper.SmsShopConfigMapper;
import com.yoooho.mall.model.SmsShopConfig;
import com.yoooho.mall.model.SmsShopConfigExample;
import com.yoooho.mall.service.SmsShopConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class SmsShopConfigServiceImpl implements SmsShopConfigService {
@Autowired
SmsShopConfigMapper shopConfigMapper;
@Override
public int save(SmsShopConfig smsShopConfig) {
List<SmsShopConfig> shopConfigs = getList();
if (shopConfigs.size() == 0) {
return shopConfigMapper.insertSelective(smsShopConfig);
}else {
smsShopConfig.setId(shopConfigs.get(0).getId());
return shopConfigMapper.updateByPrimaryKeySelective(smsShopConfig);
}
}
@Override
public SmsShopConfig get() {
List<SmsShopConfig> shopConfigs = getList();
if (shopConfigs.size() == 0) {
SmsShopConfig shopConfig = new SmsShopConfig();
shopConfig.setStartUsing(false);
return shopConfig;
}else {
return shopConfigs.get(0);
}
}
@Override
public List<SmsShopConfig> getList(){
SmsShopConfigExample example = new SmsShopConfigExample();
return shopConfigMapper.selectByExample(example);
}
}
| true |
cdf9d49338e2af05244724257f7d8b4f5eb99a96 | Java | littleyang/time-machine | /time-common/src/main/java/com/vanke/common/queue/producer/MessageQueueDispatcher.java | UTF-8 | 1,269 | 2.390625 | 2 | [] | no_license | package com.vanke.common.queue.producer;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Component;
import com.vanke.common.model.base.BaseObject;
@Component("messageQueueDispatcher")
public class MessageQueueDispatcher {
/**
* Jms消息模版
*/
@Autowired
@Qualifier("jmsQueueTemplate")
private JmsTemplate jmsQueueTemplate;
/**
* 任务队列
*/
@Autowired
@Qualifier("taskDestination")
private Destination taskDestination;
/**
* 将消息分发到任务队列
* @param object
*/
public void dispatchToTaskDestination(final BaseObject object){
MessageCreator messageCreator = new MessageCreator() {
public Message createMessage(Session session) throws JMSException {
ObjectMessage message = session.createObjectMessage();
message.setObject(object);
return message;
}
};
jmsQueueTemplate.send(this.taskDestination, messageCreator);
}
}
| true |
b7a1ff6e36e5641bb0447e1031b0cd34f71461ab | Java | lonlylocly/lonlylocly.github.io | /code/tree/BinarySearchTree.java | UTF-8 | 5,341 | 3.328125 | 3 | [
"MIT"
] | permissive | package tree;
public class BinarySearchTree<K extends Comparable,V> {
Item<K,V> root = null;
int size = 0;
/**
* O(lg n) average, because traverses all tree height
* O(n) worst case, if tree is list
*/
public void insert(K k, V v) {
if (k == null) {
throw new IllegalArgumentException();
}
Item<K,V> i = new Item<K,V>(k, v);
size += 1;
if (root == null) {
root = i;
return;
}
Item<K,V> x = root;
Item<K,V> p = root;
while (true) {
if (x == null) {
break;
}
p = x;
// less than
if (x.getK().compareTo(k) <= 0){
x = x.getR();
} else {
x = x.getL();
}
}
i.setP(p);
if (p.getK().compareTo(k) <= 0){
p.setR(i);
} else {
p.setL(i);
}
}
// same as insert
public Item<K,V> search(K k) {
Item<K,V> x = root;
while(x != null && !k.equals(x.getK())) {
if (x.getK().compareTo(k) <= 0) {
x = x.getR();
} else {
x = x.getL();
}
}
return x;
}
// O(1) when one child or none
// O(lg N) if two
public void delete(Item<K,V> i) {
if (i.getL() == null && i.getR() == null) {
if (i.getP() != null) {
declineChild(i, null);
} else {
root = null;
}
} else if (i.getL() != null && i.getR() != null) {
Item<K,V> s = successor(i);
declineChild(s, s.getR());
i.setK(s.getK());
i.setV(s.getV());
} else {
Item<K,V> x = i.getL();
if (x == null) {
x = i.getR();
}
if (i.getP() != null) {
declineChild(i, x);
} else {
root = x;
x.setP(null);
}
}
size -= 1;
}
private void declineChild(Item<K,V> c, Item<K,V> newC) {
Item<K,V> p = c.getP();
if (c.getP().getR() == c) {
c.getP().setR(newC);
} else if(c.getP().getL() == c) {
c.getP().setL(newC);
} else {
throw new IllegalStateException();
}
if (newC != null) {
newC.setP(p);
}
}
public Item<K,V> treeMin(Item<K,V> i) {
return treeLimit(i, true);
}
public Item<K,V> treeMax(Item<K,V> i) {
return treeLimit(i, false);
}
// O(ln N) since traverses all tree high
public Item<K,V> treeLimit(Item<K,V> i, boolean min) {
Item<K,V> x = i;
Item<K,V> p = i;
while (x != null) {
p = x;
if (min) {
x = x.getL();
} else {
x = x.getR();
}
}
return p;
}
// O(lg N) again
public Item<K,V> successor(Item<K,V> i) {
if (i.getR() != null) {
return treeMin(i.getR());
}
Item<K,V> p = i.getP();
while (p!= null && p.getR() == i) {
p = p.getP();
}
return p;
}
public Item<K,V> predecessor(Item<K,V> i) {
if (i.getL() != null) {
return treeMax(i.getL());
}
Item<K,V> p = i.getP();
while (p!= null && p.getL() == i) {
p = p.getP();
}
return p;
}
public int size() {
return size;
}
public void printAsc(){
printAsc(root);
System.out.println(";;");
}
// depth-first, O(N) - prints all elements, in-order
public void printAsc(Item<K,V> i){
if (i==null) {
return;
}
printAsc(i.getL());
System.out.println(i);
printAsc(i.getR());
}
public void printTree() {
printTree(root, 1);
}
// depth-first, O(N), pre-order
public void printTree(Item<K,V> i, int t) {
if (i == null) {
System.out.println(";;");
return;
}
String tab = "";
for(int j = 0; j < t; j++) {
tab += " ";
}
System.out.println(i + ";; p: " + i.getP());
System.out.print(tab + "R: ");
printTree(i.getR(), t + 1);
System.out.print(tab + "L: ");
printTree(i.getL(), t + 1);
}
public static void main(String[] args) {
BinarySearchTree<Integer,String> t = new BinarySearchTree<Integer,String>();
t.printTree();
int size = 0;
for(int i : new int[]{1, 5, 34, 12, 9, 28}) {
t.insert(i, "Item " + i);
size += 1;
assert t.size() == size;
}
t.printTree();
assert t.successor(t.search(12)).getK().equals(28);
for(int i : new int[]{5, 12, 9, 1, 34, 28}) {
System.out.println("Remove " + i);
Item s = t.search(i);
assert s.getK().equals(i);
t.delete(s);
size -= 1;
assert t.size() == size;
assert t.size() >= 0;
t.printTree();
}
assert false;
}
}
| true |
2958aaab9f7717b1655cf8ae9303684061ff2f8f | Java | chensongxian/java_ee | /src/main/java/com/csx/jdbc/DMLTest.java | UTF-8 | 3,069 | 3.0625 | 3 | [] | no_license | package com.csx.jdbc;
import org.junit.Test;
import java.sql.Connection;
import java.sql.Statement;
/**
* @author csx
* @Package com.csx.jdbc
* @Description: TODO
* @date 2019/1/4 0004
*/
public class DMLTest {
/**
* jdbc协议:数据库子协议:主机:端口/连接的数据库
*/
private static final String URL = "jdbc:mysql://localhost:3306/day17";
/**
* 用户名
*/
private static final String USER = "root";
/**
* 密码
*/
private static final String PASSWORD = "root";
/**
* 增加
*/
@Test
public void testInsert(){
Connection conn = null;
Statement stmt = null;
try {
//通过工具类获取连接对象
conn = JdbcUtil.getConnection();
//3.创建Statement对象
stmt = conn.createStatement();
//4.sql语句
String sql = "INSERT INTO student(NAME,gender) VALUES('李四','女')";
//5.执行sql
int count = stmt.executeUpdate(sql);
System.out.println("影响了"+count+"行");
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally{
// 关闭资源
JdbcUtil.close(conn, stmt);
}
}
/**
* 修改
*/
@Test
public void testUpdate(){
Connection conn = null;
Statement stmt = null;
//模拟用户输入
String name = "陈六";
int id = 3;
try {
//通过工具类获取连接对象
conn = JdbcUtil.getConnection();
//3.创建Statement对象
stmt = conn.createStatement();
//4.sql语句
String sql = "UPDATE student SET NAME='"+name+"' WHERE id="+id+"";
System.out.println(sql);
//5.执行sql
int count = stmt.executeUpdate(sql);
System.out.println("影响了"+count+"行");
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally{
//关闭资源
JdbcUtil.close(conn, stmt);
}
}
/**
* 删除
*/
@Test
public void testDelete(){
Connection conn = null;
Statement stmt = null;
//模拟用户输入
int id = 3;
try {
//通过工具类获取连接对象
conn = JdbcUtil.getConnection();
//3.创建Statement对象
stmt = conn.createStatement();
//4.sql语句
String sql = "DELETE FROM student WHERE id="+id+"";
System.out.println(sql);
//5.执行sql
int count = stmt.executeUpdate(sql);
System.out.println("影响了"+count+"行");
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally{
//关闭资源
JdbcUtil.close(conn, stmt);
}
}
}
| true |
6a28cd7788123bffc5f5f36eb6189942cd1b6ffe | Java | onap/aai-sparky-be | /sparkybe-onap-service/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/ElasticSearchAggregation.java | UTF-8 | 2,241 | 1.734375 | 2 | [
"Apache-2.0"
] | permissive | /**
* ============LICENSE_START===================================================
* SPARKY (AAI UI service)
* ============================================================================
* Copyright © 2017 AT&T Intellectual Property.
* Copyright © 2017 Amdocs
* 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.
* ============LICENSE_END=====================================================
*
* ECOMP and OpenECOMP are trademarks
* and service marks of AT&T Intellectual Property.
*/
package org.onap.aai.sparky.dal.elasticsearch.entity;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
public class ElasticSearchAggregation {
@JsonProperty("doc_count_error_upper_bound")
private int docCountErrorUpperBound;
@JsonProperty("sum_other_doc_count")
private int sumOtherDocCount;
private List<BucketEntity> buckets;
public ElasticSearchAggregation() {
buckets = new ArrayList<BucketEntity>();
}
public int getDocCountErrorUpperBound() {
return docCountErrorUpperBound;
}
public void setDocCountErrorUpperBound(int docCountErrorUpperBound) {
this.docCountErrorUpperBound = docCountErrorUpperBound;
}
public int getSumOtherDocCount() {
return sumOtherDocCount;
}
public void setSumOtherDocCount(int sumOtherDocCount) {
this.sumOtherDocCount = sumOtherDocCount;
}
public List<BucketEntity> getBuckets() {
return buckets;
}
public void setBuckets(List<BucketEntity> buckets) {
this.buckets = buckets;
}
public void addBucket(BucketEntity bucket) {
buckets.add(bucket);
}
}
| true |
0b67384164af5469c3cc2342c29b9161b835618b | Java | whatafree/JCoffee | /benchmark/bigclonebenchdata_completed/14370985.java | UTF-8 | 735 | 2.953125 | 3 | [] | no_license |
class c14370985 {
public static String encrypt(String password) {
String sign = password;
try {
java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
md.update(sign.getBytes());
byte[] hash = md.digest();
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < hash.length; i++) {
if ((0xff & hash[i]) < 0x10) hexString.append("0" + Integer.toHexString((0xFF & hash[i]))); else hexString.append(Integer.toHexString(0xFF & hash[i]));
}
sign = hexString.toString();
} catch (Exception nsae) {
nsae.printStackTrace();
}
return sign;
}
}
| true |
b4151f6c86f5d3b7e7a280005aedbfac30b359ae | Java | jacoparker/Algorithms | /Daily Coding Problem/Problem33.java | UTF-8 | 1,804 | 4.25 | 4 | [] | no_license | // Good morning! Here's your coding interview problem for today.
// This problem was asked by Microsoft.
// Compute the running median of a sequence of numbers. That is, given a stream of numbers, print out the median of the list so far on each new element.
// Recall that the median of an even-numbered list is the average of the two middle numbers.
// For example, given the sequence [2, 1, 5, 7, 2, 0, 5], your algorithm should print out:
// 2
// 1.5
// 2
// 3.5
// 2
// 2
// 2
class Solution
{
public static void runningMedian(double[] sequence)
{
double[] orderedSeq = new double[sequence.length];
System.out.println(sequence[0]);
orderedSeq[0] = sequence[0];
for (int i=1; i < sequence.length; i++)
{
int j = 0;
double curr = sequence[i];
while (j < i && curr > orderedSeq[j]) j += 1;
// swap values
double prev = orderedSeq[j];
orderedSeq[j++] = curr;
while (j < i)
{
double tmp = orderedSeq[j];
orderedSeq[j] = prev;
prev = orderedSeq[j+1];
j += 1;
}
orderedSeq[i] = prev;
if (i % 2 == 1) // number is even (index odd since starting at 0)
System.out.println((orderedSeq[i/2]+orderedSeq[i/2 + 1]) / 2);
else // number is odd
System.out.println(orderedSeq[i/2]);
}
for (int i=0; i < orderedSeq.length; i++)
System.out.println("Index " + i + ": " + orderedSeq[i]);
}
}
public class Problem33
{
public static void main(String[] args)
{
double[] testData = {2, 1, 5, 7, 2, 0, 5};
Solution.runningMedian(testData);
}
}
| true |
ae933a26b5b19f6a6ec7f872a4af1932fef59f14 | Java | mayifuGitHub/ss | /src/main/java/myf/service/impl/UserServiceImpl.java | UTF-8 | 846 | 2.09375 | 2 | [] | no_license | package myf.service.impl;
import java.lang.annotation.Retention;
import java.util.List;
import myf.bean.User;
import myf.mapper.UserMapper;
import myf.service.UserService;
public class UserServiceImpl implements UserService{
private UserMapper userMapper;
public void setUserMapper(UserMapper userMapper) {
this.userMapper=userMapper;
}
public User getUser(String id) {
// TODO Auto-generated method stub
return null;
}
public List<User> getAllUser() {
// TODO Auto-generated method stub
return null;
}
public void addUser(User user) {
// TODO Auto-generated method stub
}
public boolean delUser(String id) {
// TODO Auto-generated method stub
return false;
}
public boolean updateUser(User user) {
// TODO Auto-generated method stub
return false;
}
}
| true |
3ff512fd5f5200dc232bc36f3347e2288bc97155 | Java | marschall/threeten-jpa | /threeten-jpa-oracle-impl/src/main/java/com/github/marschall/threeten/jpa/oracle/impl/TimestamptzConverter.java | UTF-8 | 7,956 | 2.375 | 2 | [
"MIT"
] | permissive | package com.github.marschall.threeten.jpa.oracle.impl;
import static java.lang.Byte.toUnsignedInt;
import static java.time.ZoneOffset.UTC;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import oracle.sql.TIMESTAMP;
import oracle.sql.TIMESTAMPTZ;
import oracle.sql.ZONEIDMAP;
/**
* Converts between {@link TIMESTAMPTZ}/{@link TIMESTAMP} and java.time times and back.
*/
public final class TimestamptzConverter {
private static final int INV_ZONEID = -1;
// magic
private static final int SIZE_TIMESTAMPTZ = 13;
private static final int SIZE_TIMESTAMP = 11;
private static final int OFFSET_HOUR = 20;
private static final int OFFSET_MINUTE = 60;
private static final byte REGIONIDBIT = (byte) 0b1000_0000; // -128
// Byte 0: Century, offset is 100 (value - 100 is century)
// Byte 1: Decade, offset is 100 (value - 100 is decade)
// Byte 2: Month UTC
// Byte 3: Day UTC
// Byte 4: Hour UTC, offset is 1 (value-1 is UTC hour)
// Byte 5: Minute UTC, offset is 1 (value-1 is UTC Minute)
// Byte 6: Second, offset is 1 (value-1 is seconds)
// Byte 7: nanoseconds (most significant bit)
// Byte 8: nanoseconds
// Byte 9: nanoseconds
// Byte 10: nanoseconds (least significant bit)
// Byte 11: Hour UTC-offset of Timezone, offset is 20 (value-20 is UTC-hour offset)
// Byte 12: Minute UTC-offset of Timezone, offset is 60 (value-60 is UTC-minute offset)
/**
* Converts {@link OffsetDateTime} to {@link TIMESTAMPTZ}.
*
* @param attribute the value to be converted, possibly {@code null}
* @return the converted data, possibly {@code null}
*/
public static TIMESTAMPTZ offsetDateTimeToTimestamptz(OffsetDateTime attribute) {
if (attribute == null) {
return null;
}
byte[] bytes = newTimestamptzBuffer();
ZonedDateTime utc = attribute.atZoneSameInstant(UTC);
writeDateTime(bytes, utc.toLocalDateTime());
ZoneOffset offset = attribute.getOffset();
writeZoneOffset(bytes, offset);
return new TIMESTAMPTZ(bytes);
}
/**
* Converts {@link TIMESTAMPTZ} to {@link OffsetDateTime}.
*
* @param dbData the data from the database to be converted, possibly {@code null}
* @return the converted value, possibly {@code null}
*/
public static OffsetDateTime timestamptzToOffsetDateTime(TIMESTAMPTZ dbData) {
if (dbData == null) {
return null;
}
byte[] bytes = dbData.toBytes();
OffsetDateTime utc = extractUtc(bytes);
if (isFixedOffset(bytes)) {
ZoneOffset offset = extractOffset(bytes);
return utc.withOffsetSameInstant(offset);
} else {
ZoneId zoneId = extractZoneId(bytes);
return utc.atZoneSameInstant(zoneId).toOffsetDateTime();
}
}
/**
* Converts {@link ZonedDateTime} to {@link TIMESTAMPTZ}.
*
* @param attribute the value to be converted, possibly {@code null}
* @return the converted data, possibly {@code null}
*/
public static TIMESTAMPTZ zonedDateTimeToTimestamptz(ZonedDateTime attribute) {
if (attribute == null) {
return null;
}
byte[] bytes = newTimestamptzBuffer();
ZonedDateTime utc = attribute.withZoneSameInstant(UTC);
writeDateTime(bytes, utc.toLocalDateTime());
String zoneId = attribute.getZone().getId();
int regionCode = ZONEIDMAP.getID(zoneId);
if (isValidRegionCode(regionCode)) {
writeZoneId(bytes, regionCode);
} else {
writeZoneOffset(bytes, attribute.getOffset());
}
return new TIMESTAMPTZ(bytes);
}
/**
* Converts {@link TIMESTAMPTZ} to {@link ZonedDateTime}.
*
* @param dbData the data from the database to be converted, possibly {@code null}
* @return the converted value, possibly {@code null}
*/
public static ZonedDateTime timestamptzToZonedDateTime(TIMESTAMPTZ dbData) {
if (dbData == null) {
return null;
}
byte[] bytes = dbData.toBytes();
OffsetDateTime utc = extractUtc(bytes);
if (isFixedOffset(bytes)) {
ZoneOffset offset = extractOffset(bytes);
return utc.atZoneSameInstant(offset);
} else {
ZoneId zoneId = extractZoneId(bytes);
return utc.atZoneSameInstant(zoneId);
}
}
/**
* Converts {@link LocalDateTime} to {@link TIMESTAMP}.
*
* @param attribute the value to be converted, possibly {@code null}
* @return the converted data, possibly {@code null}
*/
public static TIMESTAMP localDateTimeToTimestamp(LocalDateTime attribute) {
if (attribute == null) {
return null;
}
byte[] bytes = newTimestampBuffer();
writeDateTime(bytes, attribute);
return new TIMESTAMP(bytes);
}
/**
* Converts {@link TIMESTAMP} to {@link LocalDateTime}.
*
* @param dbData the data from the database to be converted, possibly {@code null}
* @return the converted value, possibly {@code null}
*/
public static LocalDateTime timestampToLocalDateTime(TIMESTAMP dbData) {
if (dbData == null) {
return null;
}
byte[] bytes = dbData.toBytes();
return extractLocalDateTime(bytes);
}
private static LocalDateTime extractLocalDateTime(byte[] bytes) {
int year = ((toUnsignedInt(bytes[0]) - 100) * 100) + (toUnsignedInt(bytes[1]) - 100);
int month = bytes[2];
int dayOfMonth = bytes[3];
int hour = bytes[4] - 1;
int minute = bytes[5] - 1;
int second = bytes[6] - 1;
int nanoOfSecond = (toUnsignedInt(bytes[7]) << 24)
| (toUnsignedInt(bytes[8]) << 16)
| (toUnsignedInt(bytes[9]) << 8)
| toUnsignedInt(bytes[10]);
return LocalDateTime.of(year, month, dayOfMonth, hour, minute, second, nanoOfSecond);
}
private static OffsetDateTime extractUtc(byte[] bytes) {
return OffsetDateTime.of(extractLocalDateTime(bytes), UTC);
}
private static boolean isFixedOffset(byte[] bytes) {
return (bytes[11] & REGIONIDBIT) == 0;
}
private static ZoneOffset extractOffset(byte[] bytes) {
int hours = bytes[11] - 20;
int minutes = bytes[12] - 60;
if ((hours == 0) && (minutes == 0)) {
return ZoneOffset.UTC;
}
return ZoneOffset.ofHoursMinutes(hours, minutes);
}
private static ZoneId extractZoneId(byte[] bytes) {
// high order bits
int regionCode = (bytes[11] & 0b1111111) << 6;
// low order bits
regionCode += (bytes[12] & 0b11111100) >> 2;
String regionName = ZONEIDMAP.getRegion(regionCode);
return ZoneId.of(regionName);
}
private static boolean isValidRegionCode(int regionCode) {
return regionCode != INV_ZONEID;
}
private static byte[] newTimestamptzBuffer() {
return new byte[SIZE_TIMESTAMPTZ];
}
private static byte[] newTimestampBuffer() {
return new byte[SIZE_TIMESTAMP];
}
private static void writeDateTime(byte[] bytes, LocalDateTime utc) {
int year = utc.getYear();
bytes[0] = (byte) ((year / 100) + 100);
bytes[1] = (byte) ((year % 100) + 100);
bytes[2] = (byte) utc.getMonthValue();
bytes[3] = (byte) utc.getDayOfMonth();
bytes[4] = (byte) (utc.getHour() + 1);
bytes[5] = (byte) (utc.getMinute() + 1);
bytes[6] = (byte) (utc.getSecond() + 1);
int nano = utc.getNano();
bytes[7] = (byte) (nano >>> 24);
bytes[8] = (byte) ((nano >>> 16) & 0xFF);
bytes[9] = (byte) ((nano >>> 8) & 0xFF);
bytes[10] = (byte) (nano & 0xFF);
}
private static void writeZoneOffset(byte[] bytes, ZoneOffset offset) {
int totalMinutes = offset.getTotalSeconds() / 60;
bytes[11] = (byte) ((totalMinutes / 60) + OFFSET_HOUR);
bytes[12] = (byte) ((totalMinutes % 60) + OFFSET_MINUTE);
}
private static void writeZoneId(byte[] bytes, int regionCode) {
bytes[11] = (byte) (REGIONIDBIT | ((regionCode & 0b1111111000000) >>> 6));
bytes[12] = (byte) ((regionCode & 0b111111) << 2);
}
private TimestamptzConverter() {
throw new AssertionError("not instantiable");
}
}
| true |
1bfacc1750d88e89f451aaee2e6d779c7cb3ffab | Java | lancal/codenvy | /core/codenvy-hosted-sso-client/src/main/java/com/codenvy/auth/sso/client/EnvironmentContextResolver.java | UTF-8 | 1,190 | 1.84375 | 2 | [] | no_license | /*
* [2012] - [2016] Codenvy, S.A.
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Codenvy S.A. and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to Codenvy S.A.
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Codenvy S.A..
*/
package com.codenvy.auth.sso.client;
import org.eclipse.che.commons.env.EnvironmentContext;
import javax.servlet.http.HttpServletRequest;
/**
* SSOContextResolver get parameter of environment such as workspaceId and accountId from EnvironmentContext.
*
* @author Sergii Kabashniuk
*/
public class EnvironmentContextResolver implements SSOContextResolver {
@Override
public RolesContext getRequestContext(HttpServletRequest request) {
EnvironmentContext context = EnvironmentContext.getCurrent();
return new RolesContext(context.getWorkspaceId(), context.getAccountId());
}
}
| true |
cddf8c2caf45629a1fa8f90581922a37d007bf7a | Java | johannesweber/Techniken-der-Programmentwicklung-WS1314 | /TPE_freiwilligeUebungen/generischeTypen/aufgabeAff/PairList.java | UTF-8 | 507 | 3.09375 | 3 | [] | no_license | package aufgabeAff;
import java.util.LinkedList;
/**
* Created by Johannes on 01.01.14.
*/
public class PairList <Pair> extends LinkedList<Pair>{
private int max;
public PairList(int max){
this.max = max;
}
public void add(int index, Pair objekt){
if(index < this.max){
this.add(index, objekt);
}else{
System.out.println("Max. Laenge erreicht.");
}
}
public Pair get(int index){
return this.get(index);
}
}
| true |
563ce80e42fefafb305d81b34f34780bea4ccac9 | Java | zhansong/myCodeing | /TestDemo/src/com/nio/SelectorDemo.java | UTF-8 | 2,078 | 2.953125 | 3 | [
"Apache-2.0"
] | permissive | package com.nio;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
public class SelectorDemo {
public static void main(String[] args) throws Exception {
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.configureBlocking(false);
ServerSocket serverSocket = ssc.socket();
serverSocket.bind(new InetSocketAddress("127.0.0.1", 8853));
Selector selector = Selector.open();
ssc.register(selector, SelectionKey.OP_ACCEPT);
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (true) {
int num = selector.select();
if (num < 1) {
continue;
}
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> iterator = keys.iterator();
while (iterator.hasNext()) {
SelectionKey sk = iterator.next();
if ((sk.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) {
ServerSocketChannel sc = (ServerSocketChannel) sk
.channel();
SocketChannel accept = sc.accept();
accept.configureBlocking(false);
SelectionKey key = accept.register(selector, SelectionKey.OP_READ);
key.attach(accept);
iterator.remove();
} else if ((sk.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) {
{
iterator.remove();
SocketChannel sc = (SocketChannel) sk.channel();
int size = 0;
String last = "";
while ((size = sc.read(buffer)) > 0) {
char[] chars = CharUtil.getChars(buffer.array());
last = String.valueOf(chars[chars.length-1]);
System.out.println(chars);
}
buffer.flip();
String result = "return the success!" + last;
byte[] bytes = CharUtil.getBytes(result.toCharArray());
ByteBuffer send = ByteBuffer.wrap(bytes);
if(send.hasRemaining()) {
sc.write(send);
}
send.clear();
sc.close();
}
}
}
}
}
} | true |
e86a79851f75a9e5cb9f01621e45bc2c5f4fae00 | Java | mbeider/fizteh-java-2014 | /src/ru/fizteh/fivt/students/VasilevKirill/proxy/tests/TestingInterface.java | UTF-8 | 531 | 2.53125 | 3 | [] | no_license | package ru.fizteh.fivt.students.VasilevKirill.proxy.tests;
import java.io.IOException;
import java.util.List;
/**
* Created by Kirill on 30.11.2014.
*/
public interface TestingInterface {
void noArgumentsMethod();
void oneArgumentMethod(String a);
void twoArgumentMethod(Integer a, Integer b);
void listArgumentsMethod(List<String> list);
void cyclicArgumentsMethod(List<Object> list);
Integer smthReturningMethod();
Object nullReturningMethod();
Integer exceptionMethod() throws IOException;
}
| true |
89e20d7d8b62bf5431d33e3422786d325fa84817 | Java | dorianverna17/AutoManagement | /src/Employees/Employee.java | UTF-8 | 7,668 | 3.109375 | 3 | [] | no_license | package Employees;
import Cars.Bus;
import Cars.Car;
import Cars.Truck;
import Cars.Vehicle;
import app.AutoService;
import java.util.ArrayList;
import java.util.Calendar;
// Voi considera ca orice angajat se poate ocupa de masini
// (fie el asistent, mecanic sau director - avand in vedere ca
// se precizeaza ca angajatii iau in primire masini)
public abstract class Employee{
protected int ID;
protected String lastname;
protected String firstname;
protected Date birth_date;
protected Date hiring_date;
protected double coefficient;
// Aici retin vehiculele de care se ocupa in prezent angajatul
protected ArrayList<Pair<Car, Integer>> car_list;
protected Pair<Bus, Integer> bus;
protected Pair<Truck, Integer> truck;
// Voi modela cozile utilizand ArrayList-uri
protected ArrayList<Pair<Car, Integer>> car_queue;
protected ArrayList<Pair<Bus, Integer>> bus_queue;
protected ArrayList<Pair<Truck, Integer>> truck_queue;
// timp de asteptare - de ajutor in cazul in care toti angajatii sunt ocupati
protected int time_to_wait_cars;
protected int time_to_wait_bus;
protected int time_to_wait_truck;
// variabila pe care o folosesc pentru a contoriza cat de solicitat este angajatul
protected int requested;
public Employee(String lastname, String firstname, Date birth_date, Date hiring_date) {
// auto-increment pentru ID
this.ID = AutoService.getInstance().getEmployees().size();
// celelalte campuri sunt setate cu datele de la tastatura
this.lastname = lastname;
this.firstname = firstname;
this.birth_date = birth_date;
this.hiring_date = hiring_date;
car_queue = new ArrayList<>();
bus_queue = new ArrayList<>();
truck_queue = new ArrayList<>();
car_list = new ArrayList<>();
bus = null;
truck = null;
time_to_wait_cars = 0;
time_to_wait_bus = 0;
time_to_wait_truck = 0;
}
public double calculateSalary() {
int years_old = getYearsInCompany();
return years_old * coefficient * 1000;
}
// pentru anii in companie voi face aproximare prin adaos
public int getYearsInCompany() {
int currentYear = Calendar.getInstance().get(Calendar.YEAR);
int currentMonth = Calendar.getInstance().get(Calendar.MONTH);
int currentDay = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
Date currentDate = new Date(currentYear, currentMonth, currentDay);
Date comparisonDate = new Date(hiring_date.getYear(), currentMonth, currentDay);
int number_years = 0;
number_years = currentYear - hiring_date.getYear();
if (comparisonDate.compareTo(currentDate) > 0)
number_years++;
return number_years;
}
// voi considera acel timp estimativ ca fiind % 3 ore din numarul de km
// pe care ii are la bord vehiculul
public void addCarToQueue(Car car) {
car_queue.add(car_queue.size(), new Pair<>(car, car.getNr_kilometres() % 3 + 1));
time_to_wait_cars += car.getNr_kilometres() % 3 + 1;
}
public void addBusToQueue(Bus bus) {
bus_queue.add(bus_queue.size(), new Pair<>(bus, bus.getNr_kilometres() % 3 + 1));
time_to_wait_bus += bus.getNr_kilometres() % 3 + 1;
}
public void addTruckToQueue(Truck truck) {
truck_queue.add(truck_queue.size(), new Pair<>(truck, truck.getNr_kilometres() % 3 + 1));
time_to_wait_truck += truck.getNr_kilometres() % 3 + 1;
}
// metode pe care o apelez atunci angajatul finalizeaza masina, iar clientul o preia
public void removeCar(int id) {
int aux = -1;
for (int i = 0; i < car_list.size(); i++) {
if (car_list.get(i).getValue1().getID() == id)
aux = i;
}
if (aux == -1) {
System.out.println("De masina nu s-a ocupat acest angajat");
} else {
car_list.remove(aux);
if (car_queue.size() != 0) {
car_list.add(car_queue.get(0));
car_queue.remove(0);
}
}
}
public void removeBus() {
if (this.bus == null) {
System.out.println("Acest angajat nu s-a ocupat de niciun autobuz");
} else {
if (bus_queue.size() != 0)
this.bus = bus_queue.get(0);
}
}
public void removeTruck() {
if (this.truck == null) {
System.out.println("Acest angajat nu s-a ocupat de niciun camion");
} else {
if (truck_queue.size() != 0)
this.truck = truck_queue.get(0);
}
}
public boolean addToCarList(Car car) {
if (car_list.size() == 3)
return false;
else {
car_list.add(new Pair<>(car, car.getNr_kilometres() % 3 + 1));
if (car_list.size() == 3) {
time_to_wait_cars += car.getNr_kilometres() % 3 + 1;
}
}
return true;
}
public boolean addBus(Bus bus) {
if (this.bus != null)
return false;
else {
this.bus = new Pair<>(bus, bus.getNr_kilometres() % 3 + 1);
time_to_wait_bus = bus.getNr_kilometres() % 3 + 1;
}
return true;
}
public boolean addTruck(Truck truck) {
if (this.truck != null)
return false;
else {
this.truck = new Pair<>(truck, truck.getNr_kilometres() % 3 + 1);
time_to_wait_truck += truck.getNr_kilometres() % 3 + 1;
}
return true;
}
public int getRequested() {
return requested;
}
public void setRequested(int requested) {
this.requested = requested;
}
public ArrayList<Pair<Car, Integer>> getCar_list() {
return car_list;
}
public Pair<Bus, Integer> getBus() {
return bus;
}
public Pair<Truck, Integer> getTruck() {
return truck;
}
public ArrayList<Pair<Car, Integer>> getCar_queue() {
return car_queue;
}
public ArrayList<Pair<Bus, Integer>> getBus_queue() {
return bus_queue;
}
public ArrayList<Pair<Truck, Integer>> getTruck_queue() {
return truck_queue;
}
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public Date getBirth_date() {
return birth_date;
}
public void setBirth_date(Date birth_date) {
this.birth_date = birth_date;
}
public Date getHiring_date() {
return hiring_date;
}
public int getTime_to_wait_cars() {
return time_to_wait_cars;
}
public int getTime_to_wait_bus() {
return time_to_wait_bus;
}
public int getTime_to_wait_truck() {
return time_to_wait_truck;
}
public Double getMoneyEarned() {
double money = 0d;
for (Pair<Car, Integer> carIntegerPair : car_list) {
money += (double) carIntegerPair.getValue1().getInsurancePolicyDiscount() / 100;
}
if (bus != null)
money += (double) bus.getValue1().getInsurancePolicyDiscount() / 100;
if (truck != null)
money += (double) truck.getValue1().getInsurancePolicyDiscount() / 100;
return money;
}
}
| true |
16bc786b51c0da0c546e86691a64f76fcb0839d5 | Java | Mrjiangzhu/test | /src/main/java/com/ruofeng/app/framework/codegen/service/GeneratorService2.java | UTF-8 | 7,192 | 1.898438 | 2 | [] | no_license | package com.ruofeng.app.framework.codegen.service;
import com.google.common.io.Files;
import com.ruofeng.app.common.utils.StringUtils;
import com.ruofeng.app.framework.codegen.dao.GeneratorDao;
import com.ruofeng.app.framework.codegen.model.GeneratorParam;
import com.ruofeng.app.framework.codegen.model.ModelConfig;
import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.ResourceLoader;
import org.beetl.core.Template;
import org.beetl.core.resource.ClasspathResourceLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static com.ruofeng.app.common.utils.StringUtils.templateIt;
@Service
public class GeneratorService2 {
private Logger log = LoggerFactory.getLogger(GeneratorService2.class);
private String kotlinPath = null;
private String beetlsqlPath = null;
private String webPath = null;
private String beetlPath = System.getProperty("user.dir") + "\\src\\main\\resources\\btl\\kotlinGenerator\\";
Map<String, File> beetlmap = null;
@Autowired
public GeneratorDao dao;
public GeneratorService2() {
this.kotlinPath = "\\src\\main\\java\\";
this.beetlsqlPath = "\\src\\main\\resources\\sql\\";
this.webPath = "\\src\\main\\resources\\static\\";
}
public void makeKotlin(GeneratorParam param) throws IOException {
beetlmap = getBtlMap(param.getVersion());
param.getTableList().forEach((ModelConfig it) -> {
String pkgPath = "";
if (param.getPublicPkg() != null) {
pkgPath = param.getPublicPkg().replace(".", "\\");
}
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("param", param);
paramMap.put("kotlinPath", kotlinPath);
paramMap.put("pkgPath", pkgPath);
paramMap.put("webPath", webPath);
paramMap.put("beetlsqlPath", beetlsqlPath);
paramMap.put("it", it);
String htmlPath=StringUtils.subSpliString(it.getFileRelativePath(),"\\","/",-3);
String pathTpl = "${param.projectPath}${webPath}"+htmlPath;
paramMap.put("path", templateIt(pathTpl, paramMap));
String[] makeTypeArray = it.getMakeType().toLowerCase().split(",");
for (String currentType : makeTypeArray) {
switch (currentType) {
case "model": {
makeByBackFont("model", it.getClassName(), it, paramMap, param);
break;
}
case "sqlmd": {
File f = beetlmap.get("sql");
String[] extNameArray = f.getName().split("\\.");
String fileAbsolutePathTpl = "${param.projectPath}${beetlsqlPath}${pkgPath}${it.fileRelativePath}."
+ extNameArray[extNameArray.length - 1];
String fileAbsolutePath = templateIt(fileAbsolutePathTpl, paramMap);
makeByRltPath(it, fileAbsolutePath, param.getVersion() + "/" + f.getName());
break;
}
case "dao": {
makeByBackFont("dao", it.getClassName() + "Dao", it, paramMap, param);
break;
}
case "service": {
makeByBackFont("service", it.getClassName() + "Service", it, paramMap, param);
break;
}
case "controller": {
makeByBackFont("controller", it.getClassName() + "Controller", it, paramMap, param);
break;
}
case "htmljs": {
makeByRltPath(it, templateIt("${path}\\list.html", paramMap),
param.getVersion() + "/list.btl.html");
makeByRltPath(it, templateIt("${path}\\list.js", paramMap), param.getVersion() + "/list.btl.js");
makeByRltPath(it, templateIt("${path}\\edit.html", paramMap),
param.getVersion() + "/edit.btl.html");
makeByRltPath(it, templateIt("${path}\\edit.js", paramMap), param.getVersion() + "/edit.btl.js");
makeByRltPath(it, templateIt("${path}\\setting.html", paramMap),
param.getVersion() + "/setting.btl.html");
makeByRltPath(it, templateIt("${path}\\setting.js", paramMap),
param.getVersion() + "/setting.btl.js");
makeByRltPath(it, templateIt("${path}\\list.html", paramMap),
param.getVersion() + "/list.btl.html");
}
}
}
});
}
public void makeByBackFont(String beetlFirstName, String fileName, ModelConfig it, Map<String, Object> paramMap,
GeneratorParam param) {
File f = beetlmap.get(beetlFirstName);
String[] extNameArray = f.getName().split("\\.");
String extendName = extNameArray[extNameArray.length - 1];
String fileAbsolutePathTpl = "${param.projectPath}${kotlinPath}${pkgPath}${it.fileRelativePath}/" + fileName
+ "." + extendName;
String fileAbsolutePath = templateIt(fileAbsolutePathTpl, paramMap);
makeByRltPath(it, fileAbsolutePath, param.getVersion() + "/" + f.getName());
}
public void makeByRltPath(ModelConfig model, String fileAbsolutePath, String btlStr) {
ClasspathResourceLoader resourceLoader = new ClasspathResourceLoader("/btl/kotlinGenerator/");
Configuration cfg = null;
try {
cfg = Configuration.defaultConfiguration();
GroupTemplate gt = new GroupTemplate((ResourceLoader) resourceLoader, cfg);
Template t = gt.getTemplate(btlStr);
t.binding("model", model);
String str = t.render();
this.writeStrToFile(str, fileAbsolutePath);
} catch (IOException e) {
e.printStackTrace();
}
}
public File getTargetFile(String file) throws IOException {
File modelKtFile = new File(file);
if (!modelKtFile.getParentFile().exists()) {
modelKtFile.getParentFile().mkdirs();
}
modelKtFile.createNewFile();
return modelKtFile;
}
/**
* @param content
* @param fileStr
* @throws IOException 写入content到fileStr对应的文件中
*/
public void writeStrToFile(String content, String fileStr) throws IOException {
File modelKtFile = this.getTargetFile(fileStr);
Files.write(content.getBytes(), modelKtFile);
}
public Map<String, File> getBtlMap(String version) {
Map<String, File> beetlsMap = new HashMap<String, File>();
for (String s : new File(beetlPath + version).list()) {
File f = new File(s);
beetlsMap.put(f.getName().split("\\.")[0], f);
}
return beetlsMap;
}
} | true |
1bc72ef5c33841ede6dca250fa1950aacff4e817 | Java | kishlayakunj/Stock-Manager | /app/src/main/java/com/siementory/siementory/IssueNewStockActivity.java | UTF-8 | 6,654 | 2.203125 | 2 | [] | no_license | package com.siementory.siementory;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class IssueNewStockActivity extends AppCompatActivity implements View.OnClickListener {
String projectID, stockName, stockID, userID;
private FirebaseDatabase firebaseDatabase, firebaseDatabase2;
private DatabaseReference databaseReference, databaseReference2;
TextView tvStockName, tvQuantityPresent;
EditText etRecieverName,etIssueQuantity,etDOI;
Button btIssue;
String getPresentQuantity, updatedQuantity;
@Override
protected void onCreate(Bundle savedInstanceState) {
Bundle extras = getIntent().getExtras();
if (extras != null) {
projectID = extras.getString("PROJECT_ID");
//The key argument here must match that used in the other activity
}
extras = getIntent().getExtras();
if (extras != null) {
stockName = extras.getString("STOCK_NAME");
//The key argument here must match that used in the other activity
}
extras = getIntent().getExtras();
if (extras != null) {
userID = extras.getString("USER_ID");
//The key argument here must match that used in the other activity
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_issue_new_stock);
tvStockName = (TextView) findViewById(R.id.tvStockName);
tvQuantityPresent = (TextView) findViewById(R.id.tvQuantityExisting);
etRecieverName = (EditText) findViewById(R.id.etRecieverName);
etIssueQuantity = (EditText) findViewById(R.id.etIssueQuantity);
etDOI = (EditText) findViewById(R.id.etDOI);
findViewById(R.id.btIssue).setOnClickListener(this);
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference().child("users").child(userID).child("projects").child(projectID);
databaseReference.child("stock_details").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()
) {
if (ds.child("stock_name").getValue().toString().equalsIgnoreCase(stockName)) {
stockID = (ds.getKey());
tvStockName.setText(ds.child("stock_name").getValue().toString());
stockName = tvStockName.getText().toString();
tvQuantityPresent.setText(ds.child("stock_quantity").getValue().toString());
getPresentQuantity = tvQuantityPresent.getText().toString();
break;
} else continue;
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void createIssueNode(){
String recieverName = etRecieverName.getText().toString().trim();
final String issueQuantity = etIssueQuantity.getText().toString().trim();
String doi = etDOI.getText().toString().trim();
if (recieverName.isEmpty()) {
etRecieverName.setError("Receiver name is required");
etRecieverName.requestFocus();
}
if (issueQuantity.isEmpty()) {
etIssueQuantity.setError("Please enter quantity");
etIssueQuantity.requestFocus();
}
if (doi.isEmpty()) {
etDOI.setError("Please enter a valid date");
etDOI.requestFocus();
}
int temp1 = Integer.parseInt(getPresentQuantity);
int temp2 = Integer.parseInt(issueQuantity);
if(temp1>=temp2)
{
Toast.makeText(getApplicationContext(),"Stock issued successfully!", Toast.LENGTH_LONG).show();
int temp3 = temp1 - temp2;
updatedQuantity = String.valueOf(temp3);
firebaseDatabase2 = FirebaseDatabase.getInstance();
databaseReference2 = firebaseDatabase.getReference().child("users").child(userID).child("projects").child(projectID);
databaseReference2.child("stock_details").child(stockID).child("stock_quantity").setValue(updatedQuantity);
DatabaseReference issueReference = databaseReference2.child("issue_details").push();
issueReference.child("stock_name").setValue(stockName);
issueReference.child("receiver_name").setValue(recieverName);
issueReference.child("quantity_issued").setValue(issueQuantity);
issueReference.child("date_of_issue").setValue(doi);
Intent intent1 = new Intent(IssueNewStockActivity.this, RegisterActivity.class);
intent1.putExtra("USER_ID",userID);
intent1.putExtra("PROJECT_ID", projectID);
//intent1.putExtra("UPDATED_QUANTITY",updatedQuantity);
//intent.putExtra("STOCK_NAME",stockName);
//intent.putExtra("STOCK_ID",stockID);
startActivity(intent1);
finish();
}
else {
updatedQuantity=getPresentQuantity;
databaseReference.child("stock_details").child(stockID).child("stock_quantity").setValue(updatedQuantity);
Toast.makeText(getApplicationContext(),"Please enter issue quantity less than stock quantity", Toast.LENGTH_LONG).show();
//Intent intent = new Intent(IssueNewStockActivity.this, IssueNewStockActivity.class);
Intent intent = getIntent();
intent.putExtra("USER_ID",userID);
intent.putExtra("PROJECT_ID", projectID);
finish();
startActivity(intent);
}
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btIssue:
createIssueNode();
break;
}
}
}
| true |
b0c30f4e134b510c5c1bd9c69ea48f1008ce7f69 | Java | epinter/Partner-Center-Java | /src/main/java/com/microsoft/store/partnercenter/models/products/InventoryRestriction.java | UTF-8 | 1,324 | 2.078125 | 2 | [
"MIT"
] | permissive | // -----------------------------------------------------------------------
// <copyright file="InventoryRestriction.java" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
package com.microsoft.store.partnercenter.models.products;
import java.util.Map;
/**
* Class that represents an inventory restriction.
*/
public class InventoryRestriction
{
/**
* Gets or sets the reason code.
*/
private String __ReasonCode;
public String getReasonCode()
{
return __ReasonCode;
}
public void setReasonCode( String value )
{
__ReasonCode = value;
}
/**
* Gets or sets the description.
*/
private String __Description;
public String getDescription()
{
return __Description;
}
public void setDescription( String value )
{
__Description = value;
}
/**
* Gets or sets the set of properties that further describe this restriction.
*/
private Map<String, String> __Properties;
public Map<String, String> getProperties()
{
return __Properties;
}
public void setProperties( Map<String, String> value )
{
__Properties = value;
}
} | true |
d5ca7fdb6b3d265119d67adf762c3a0b5a464f73 | Java | Charlesciezki/JavaDiceGame | /GameEnd.java | UTF-8 | 547 | 3.734375 | 4 | [] | no_license | package diceGame;
public class GameEnd {
int player1Score; //these don't need to be here just put it for a ref
int player2Score;
public void victory(int player1Score, int player2Score){
if (player1Score == 11 && player2Score == 11){
System.out.println("The game is over! It's a tie!");
System.exit(0);
} else if (player1Score == 11){
System.out.println("Player 1 wins!");
System.exit(0);
} else if (player2Score == 11){
System.out.println("Player 2 wins!");
System.exit(0);
}
}
}
| true |
25a986e18e03122bbc6d4d182f91001d03036afe | Java | TomasCybas/Objektinis-programavimas | /src/namudarbas2/uzduotis1/uzduotis1.java | UTF-8 | 801 | 3.015625 | 3 | [] | no_license | package namudarbas2.uzduotis1;
import java.util.Scanner;
public class uzduotis1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Įveskite kraštinės a ilgį: ");
int a = sc.nextInt();
System.out.print("Įveskite kraštinės b ilgį: ");
int b = sc.nextInt();
System.out.print("Įveskite kraštinės c ilgį: ");
int c = sc.nextInt();
System.out.print("Įveskite kraštinės d ilgį: ");
int d = sc.nextInt();
sc.close();
if((a == b && c == d) || (a == c && b == d) || (a == d && c == b)){
System.out.println("Galima sudaryti stačiakampį");
} else {
System.out.println("Stačiakampo sudaryti negalima");
}
}
}
| true |
44cba88c6e3d2d63fc194c88e9d972a4a89a230f | Java | moo1o/JavaStudy | /SwingEx05/src/SwingEx05.java | UTF-8 | 859 | 3.109375 | 3 | [] | no_license | import java.awt.*;
import javax.swing.*;
public class SwingEx05 extends JFrame{
SwingEx05(){
setTitle("4x4 Color Frame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridLayout grid = new GridLayout(4, 4);
setLayout(grid);
Color[] colorset = {Color.RED, new Color(255, 187, 0), Color.YELLOW, Color.GREEN, new Color(0, 216, 255),
new Color(3, 0, 102), new Color(153, 0, 133), new Color(130, 110, 93), Color.PINK, Color.LIGHT_GRAY,
Color.WHITE, new Color(48, 0, 0), Color.BLACK, new Color(255, 187, 0), new Color(3, 0, 102), new Color(153, 0, 133)};
for(int i=0 ; i<16 ; i++){
JLabel label = new JLabel(Integer.toString(i));
label.setOpaque(true);
label.setBackground(colorset[i]);
add(label);
}
setSize(600, 240);
setVisible(true);
}
public static void main(String [] args){
new SwingEx05();
}
}
| true |
3425a0acec1b45ac1713c40945a302684f1c61a7 | Java | tigerfintech/openapi-java-sdk | /src/main/java/com/tigerbrokers/stock/openapi/client/https/domain/quote/item/DepthEntry.java | UTF-8 | 900 | 2.34375 | 2 | [] | no_license | package com.tigerbrokers.stock.openapi.client.https.domain.quote.item;
import java.io.Serializable;
/**
* 作者:ltc
* 时间:2019/08/13
*/
public class DepthEntry implements Serializable {
/**
* 价格
*/
private Double price;
/**
* 订单数量
*/
private Integer count;
/**
* 股数
*/
private Integer volume;
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
public Integer getVolume() {
return volume;
}
public void setVolume(Integer volume) {
this.volume = volume;
}
@Override
public String toString() {
return "DepthEntry{" +
"price=" + price +
", count=" + count +
", volume=" + volume +
'}';
}
}
| true |
1f0e090799dfb4865f9f09d5c1ce8c1830a51776 | Java | HerperPlain/hpcloud-parent | /hpcloud-crm/hpcloud-crm-controller/src/main/java/com/hpsgts/hpcloud/crm/UserController.java | UTF-8 | 792 | 1.882813 | 2 | [] | no_license | package com.hpsgts.hpcloud.crm;
import com.hpsgts.hpcloud.common.controller.BaseController;
import com.hpsgts.hpcloud.crm.services.base.BaseService;
import com.hpsgts.hpcloud.model.crm.entity.SysUserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author 黄朴(Hp.Plain)
* @date 2018-1-21
* @packageName com.hpsgts.hpcloud.crm
* @projectName hpcloud-parent
* @company G翔时代技术服务有限公司
*/
@RestController
public class UserController extends BaseController{
@Autowired
BaseService<SysUserEntity> baseService;
@RequestMapping("/hello")
public String hello(){
return "1111111";
}
}
| true |
aa473f2b98e6bf78b0b300f92dfefd1b439094bf | Java | SAIKRISHNADRS/knowevo | /java/knowevo/src/knowevo/springbox/gephibox/GephiDBBuilder.java | UTF-8 | 4,654 | 1.875 | 2 | [] | no_license | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package knowevo.springbox.gephibox;
import java.awt.Color;
import java.io.*;
import java.sql.*;
import java.util.*;
import knowevo.springbox.DBBuilder;
import knowevo.springbox.ScoreMachine;
import org.gephi.data.attributes.api.AttributeController;
import org.gephi.data.attributes.api.AttributeModel;
import org.gephi.graph.api.*;
import org.gephi.io.exporter.api.*;
import org.gephi.io.exporter.preview.*;
import org.gephi.io.importer.api.Container;
import org.gephi.io.importer.api.EdgeDefault;
import org.gephi.io.importer.api.ImportController;
import org.gephi.io.importer.plugin.database.EdgeListDatabaseImpl;
import org.gephi.io.importer.plugin.database.ImporterEdgeList;
import org.gephi.io.processor.plugin.DefaultProcessor;
import org.gephi.layout.plugin.force.StepDisplacement;
import org.gephi.layout.plugin.force.yifanHu.YifanHuLayout;
import org.gephi.preview.api.PreviewController;
import org.gephi.preview.api.PreviewModel;
import org.gephi.preview.api.PreviewProperty;
import org.gephi.preview.types.EdgeColor;
import org.gephi.preview.types.DependantOriginalColor;
import org.gephi.project.api.ProjectController;
import org.gephi.project.api.Workspace;
import org.openide.util.Lookup;
/**
*
* @author sasho
*/
public class GephiDBBuilder extends DBBuilder {
private ProjectController pc;
private Workspace workspace;
private GraphModel graphModel;
private AttributeModel attributeModel;
private Graph gephiGraph;
private SVGExporter exporter;
private ExportController ec;
private PreviewModel previewModel;
public static void getGraphFor(ScoreMachine sm, String name, int max_depth, String out, boolean peers_only)
throws SQLException
{
GephiDBBuilder dbb = new GephiDBBuilder(sm);
dbb.buildGraph(name, max_depth, peers_only);
dbb.convertGraph();
dbb.converge(100);
dbb.export(out);
}
private GephiDBBuilder(ScoreMachine sm) {
super(sm);
try {
pc = Lookup.getDefault().lookup(ProjectController.class);
pc.newProject();
workspace = pc.getCurrentWorkspace();
//Get controllers and models
graphModel = Lookup.getDefault().lookup(GraphController.class).getModel();
attributeModel = Lookup.getDefault().lookup(AttributeController.class).getModel();
gephiGraph = graphModel.getDirectedGraph();
ec = Lookup.getDefault().lookup(ExportController.class);
exporter = (SVGExporter) ec.getExporter("svg");
exporter.setWorkspace(workspace);
previewModel = Lookup.getDefault().lookup(PreviewController.class).getModel();
}
catch (Exception e) {
e.printStackTrace();
}
}
private void export(String name) {
try {
ec.exportFile(new File(name), exporter);
} catch (IOException ex) {
ex.printStackTrace();
}
}
public void converge(int times) {
YifanHuLayout layout = new YifanHuLayout(null, new StepDisplacement(1f));
layout.setGraphModel(graphModel);
layout.resetPropertiesValues();
layout.setOptimalDistance(30f);
layout.initAlgo();
for (int i = 0; i < times && layout.canAlgo(); i++) {
layout.goAlgo();
}
//Preview
previewModel.getProperties().putValue(PreviewProperty.SHOW_NODE_LABELS, Boolean.TRUE);
previewModel.getProperties().putValue(PreviewProperty.EDGE_COLOR, new EdgeColor(Color.BLUE));
previewModel.getProperties().putValue(PreviewProperty.EDGE_THICKNESS, new Float(0.1f));
previewModel.getProperties().putValue(PreviewProperty.NODE_LABEL_COLOR, new DependantOriginalColor(Color.RED));
previewModel.getProperties().putValue(PreviewProperty.NODE_LABEL_FONT, previewModel.getProperties().getFontValue(PreviewProperty.NODE_LABEL_FONT).deriveFont(14));
}
@Override
public void convertNode(knowevo.springbox.Node node) {
Node n = graphModel.factory().newNode(node.getName());
n.getNodeData().setLabel(node.getName());
gephiGraph.addNode(n);
}
@Override
public void convertEdge(knowevo.springbox.Edge edge) {
Node parent = gephiGraph.getNode(edge.getFirst().getName());
Node child = gephiGraph.getNode(edge.getSecond().getName());
Edge e = graphModel.factory().newEdge(parent, child, edge.getScore(), edge.isDirected());
gephiGraph.addEdge(e);
}
}
| true |
fd660cb9569c775d70be118379ed5322816c42f3 | Java | Lulucy1587/java | /SubComplex.java | UTF-8 | 174 | 2.5 | 2 | [] | no_license |
public class SubComplex{
float p,q;
SubComplex(float a,float b,float c,float d) {
p=a-c;
q=b-d;
}
float sub2() {
return p;
}
float sub3() {
return q;
}
}
| true |
154718bc7222e1c8f9d02c8774a4c499a3b8e801 | Java | florianmorath/Advanced-Systems-Lab | /test/ch/ethz/asl/RequestUnitTest.java | UTF-8 | 1,769 | 2.5 | 2 | [] | no_license | package ch.ethz.asl;
import org.junit.jupiter.api.Test;
import java.nio.ByteBuffer;
import static org.junit.jupiter.api.Assertions.*;
class RequestUnitTest {
@Test
void endOfLineExists() {
ByteBuffer b1 = ByteBuffer.allocate(100);
b1.put("get key1 key2\r\n".getBytes());
ByteBuffer b2 = ByteBuffer.allocate(100);
b2.put("set key1 0 500 30\r\nxxxxxxxxxxxxxxxxxxxx\r\n".getBytes());
ByteBuffer b3 = ByteBuffer.allocate(100);
b3.put("set key1 0 500 30\r\nxxxx\r\nxxxxxxxxxxxxxxxx\r\n".getBytes());
ByteBuffer b4 = ByteBuffer.allocate(100);
b4.put("get key1 key2".getBytes());
ByteBuffer b5 = ByteBuffer.allocate(100);
b5.put("set key1 0 500 30\r\nxxxx\r\nxxxxxxxxxxxxxxxx".getBytes());
assertTrue(Request.endOfLineExists(b1));
assertTrue(Request.endOfLineExists(b2));
assertTrue(Request.endOfLineExists(b3));
assertFalse(Request.endOfLineExists(b4));
assertFalse(Request.endOfLineExists(b5));
}
@Test
void parseRequest() {
ByteBuffer b1 = ByteBuffer.allocate(100);
b1.put("get key1 key2\r\n".getBytes());
ByteBuffer b2 = ByteBuffer.allocate(100);
b2.put("set key1 0 500 30\r\nxxxxxxxxxxxxxxxxxxxx\r\n".getBytes());
ByteBuffer b3 = ByteBuffer.allocate(100);
b3.put("key1 0 500 30\r\nxxxx\r\nxxxxxxxxxxxxxxxx\r\n".getBytes());
ByteBuffer b4 = ByteBuffer.allocate(100);
b4.put("key1 key2".getBytes());
Request req1 = new Request(b1, null);
assertTrue(req1.type == Request.Type.GET);
Request req2 = new Request(b2, null);
assertTrue(req2.type == Request.Type.SET);
Request req3 = new Request(b3, null);
assertTrue(req3.type == Request.Type.INVALID);
Request req4 = new Request(b4, null);
assertTrue(req4.type == Request.Type.INVALID);
}
} | true |
a0d404d196ccc4d29306a521009588f7b073cb36 | Java | j-walk3r/Projeto-Risk-Zones-Mobile | /app/src/main/java/br/com/riskzones/controller/Usuario.java | UTF-8 | 1,739 | 1.953125 | 2 | [] | no_license | package br.com.riskzones.controller;
/**
* Created by Jhones on 22/05/2016.
*/
public class Usuario {
private int cod;
private String nome;
private String email;
private String sexo;
private String raca;
private String datNascimento;
private String senha;
private String ativo;
private String idUsuario;
private String idFacebook;
public int getCod() {
return cod;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getSexo() {
return sexo;
}
public void setSexo(String sexo) {
this.sexo = sexo;
}
public String getRaca() {
return raca;
}
public void setRaca(String raca) {
this.raca = raca;
}
public String getDatNascimento() {
return datNascimento;
}
public void setDatNascimento(String datNascimento) {
this.datNascimento = datNascimento;
}
public String getSenha() {
return senha;
}
public void setSenha(String senha) {
this.senha = senha;
}
public String getAtivo() {
return ativo;
}
public void setAtivo(String ativo) {
this.ativo = ativo;
}
public String getIdUsuario() {
return idUsuario;
}
public void setIdUsuario(String idUsuario) {
this.idUsuario = idUsuario;
}
public String getIdFacebook() {
return idFacebook;
}
public void setIdFacebook(String idFacebook) {
this.idFacebook = idFacebook;
}
}
| true |
a18c9bc8505252c1ef418a825cee367ea88fdf12 | Java | chetan253/code-ground | /leetcode/SumofLeftLeaves.java | UTF-8 | 380 | 2.703125 | 3 | [] | no_license | iclass Solution {
public int sumOfLeftLeaves(TreeNode root) {
return dfs(root, -1);
}
public int dfs(TreeNode node, int dir) {
if(node == null){
return 0;
}
if(dir == 0 && node.left == null && node.right == null){
return node.val;
}
return dfs(node.left, 0) + dfs(node.right, 1);
}
}
| true |
2f0e48145a628c8b2a8c68f5478915d59f642b15 | Java | ljervis/Flashback_Music_Application | /app/src/androidTest/java/com/example/ajcin/flashbackmusicteam16/SongListSorterTest.java | UTF-8 | 2,608 | 2.8125 | 3 | [] | no_license | package com.example.ajcin.flashbackmusicteam16;
import org.junit.Before;
import org.junit.Test;
import java.time.LocalDateTime;
import java.util.ArrayList;
import static org.junit.Assert.*;
/**
* Created by sqin8 on 3/10/2018.
*/
public class SongListSorterTest {
ArrayList<Song> songs;
Song song1;
Song song2;
Song song3;
Song song4;
@Before
public void setUp(){
songs = new ArrayList<>();
song1 = new ResourceSong("Apple","Apple", "Apple",0 );
song2 = new ResourceSong("Banana", "Banana", "Banana", 0);
song4 = new ResourceSong("Orange", "Orange", "Orange",0);
song3 = new ResourceSong("Fruit", "Fruit", "Fruit",0);
song2.favorite_song();
song3.favorite_song();
TimeMachine.useFixedClockAt(LocalDateTime.of(2017, 2, 8, 12, 00));
song2.addDateTime(LocalDateTime.of(2017, 2, 7, 12, 00));
song3.addDateTime(LocalDateTime.of(2017, 2, 8, 12, 00));
songs.add(song1);
songs.add(song2);
songs.add(song3);
songs.add(song4);
}
@Test
public void testTitle(){
SongListSorter sorter = new SongListSorterTitle(songs);
sorter.sort();
assertTrue(songs.get(0) == song1);
assertTrue(songs.get(1) == song2);
assertTrue(songs.get(2) == song3);
assertTrue(songs.get(3) == song4);
}
@Test
public void testAlbum(){
SongListSorter sorter = new SongListSorterAlbum(songs);
sorter.sort();
assertTrue(songs.get(0) == song1);
assertTrue(songs.get(1) == song2);
assertTrue(songs.get(2) == song3);
assertTrue(songs.get(3) == song4);
}
@Test
public void testArtist(){
SongListSorter sorter = new SongListSorterArtist(songs);
sorter.sort();
assertTrue(songs.get(0) == song1);
assertTrue(songs.get(1) == song2);
assertTrue(songs.get(2) == song3);
assertTrue(songs.get(3) == song4);
}
@Test
public void testFavs(){
SongListSorter sorter = new SongListSorterFavs(songs);
sorter.sort();
assertTrue(songs.get(0) == song2);
assertTrue(songs.get(1) == song3);
assertTrue(songs.get(2) == song1);
assertTrue(songs.get(3) == song4);
}
@Test
public void testRecent(){
SongListSorter sorter = new SongListSorterRecent(songs);
sorter.sort();
assertTrue(songs.get(0) == song2);
assertTrue(songs.get(1) == song3);
assertTrue(songs.get(2) == song1);
assertTrue(songs.get(3) == song4);
}
}
| true |
7365b5685164fc24c49e1621475e138283f8c4fd | Java | sahiljamwal/CruxOnline-CB-HB | /Recursion/PrintPermutation.java | UTF-8 | 783 | 4.0625 | 4 | [] | no_license | package Recursion;
import java.util.Scanner;
/**
* Given a String your task is to print all permutations of string using
* recursion
*
* @author sahil
*
*/
public class PrintPermutation {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String str = s.next();
printPermutaions(str, "");
s.close();
}
private static void printPermutaions(String question, String answer) {
// Base Case
if (question.length() == 0) {
System.out.println(answer);
return;
}
// for each character in string
for (int i = 0; i < question.length(); i++) {
char character = question.charAt(i);
String remaingString = question.substring(0, i) + question.substring(i + 1);
printPermutaions(remaingString, answer + character);
}
}
}
| true |
9b7d23dfb2612678f974f5cbd15a3e6956fb998b | Java | bame1506/rootbeer1 | /src/org/trifort/rootbeer/generate/opencl/tweaks/ParallelCompileJob.java | UTF-8 | 3,609 | 1.960938 | 2 | [
"MIT"
] | permissive | /*
* Copyright 2012 Phil Pratt-Szeliga and other contributors
* http://chirrup.org/
*
* See the file LICENSE for copying permission.
*/
package org.trifort.rootbeer.generate.opencl.tweaks;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.trifort.rootbeer.configuration.RootbeerPaths;
import org.trifort.rootbeer.util.CompilerRunner;
import org.trifort.rootbeer.util.CudaPath;
import org.trifort.rootbeer.util.WindowsCompile;
public class ParallelCompileJob
{
private final File m_generated;
private final CudaPath m_cudaPath;
private final String m_gencodeOptions;
private final boolean m_m32;
private CompileResult m_result;
public ParallelCompileJob
(
final File generated ,
final CudaPath cuda_path ,
final String gencode_options,
final boolean m32
)
{
m_generated = generated;
m_cudaPath = cuda_path;
m_gencodeOptions = gencode_options;
m_m32 = m32;
}
public void compile()
{
List<byte[]> file_contents;
try {
String model_string = m_m32 ? "-m32" : "-m64";
String file_string = m_m32 ? "_32" : "_64";
File code_file = new File(RootbeerPaths.v().getRootbeerHome() +
"code_file" + file_string + ".ptx");
String command;
if (File.separator.equals("/")) {
command = m_cudaPath.get() + "/nvcc " + model_string + " " +
m_gencodeOptions + "-I/usr/local/cuda/include -fatbin " + m_generated.getAbsolutePath() +
" -o " + code_file.getAbsolutePath();
CompilerRunner runner = new CompilerRunner();
List<String> errors = runner.run(command);
if (errors.isEmpty() == false) {
m_result = new CompileResult(m_m32, null, errors);
return;
}
} else {
WindowsCompile compile = new WindowsCompile();
String nvidia_path = m_cudaPath.get();
command = "\"" + nvidia_path + "\" " + model_string + " " + m_gencodeOptions +
" -fatbin \"" + m_generated.getAbsolutePath() + "\" -o \"" +
code_file.getAbsolutePath() + "\"" + compile.endl();
List<String> errors = compile.compile(command, !m_m32);
if (errors.isEmpty() == false) {
m_result = new CompileResult(m_m32, null, errors);
return;
}
}
file_contents = readFile(code_file);
} catch(Exception ex){
file_contents = null;
ex.printStackTrace();
}
m_result = new CompileResult(m_m32, file_contents, new ArrayList<String>());
}
private List<byte[]> readFile(File file) throws Exception
{
InputStream is = new FileInputStream(file);
List<byte[]> ret = new ArrayList<byte[]>();
while(true){
byte[] buffer = new byte[4096];
int len = is.read(buffer);
if(len == -1)
break;
byte[] short_buffer = new byte[len];
for(int i = 0; i < len; ++i){
short_buffer[i] = buffer[i];
}
ret.add(short_buffer);
}
return ret;
}
public CompileResult getResult(){ return m_result; }
}
| true |
e31086e10ae57db432c53c3f9e4d36e17c145cff | Java | namratabary/BMI-Calculator-App | /app/src/main/java/com/example/p/ViewActivity.java | UTF-8 | 894 | 1.78125 | 2 | [] | no_license | package com.example.p;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
public class ViewActivity extends AppCompatActivity {
ListView lvdata;
Button btnViewBack;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
lvdata = findViewById(R.id.lvData);
btnViewBack = findViewById(R.id.btnViewBack);
btnViewBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent j = new Intent(ViewActivity.this,CalActivity.class);
startActivity(j);
finish();
}
});
}
}
| true |
910554fa9af3cf24dd8bc4a550253598e00bdfe5 | Java | arnabjyotiboruah/Dithok_Project | /src/main/java/com/dithok/myCommerce/dto/UserAddressDto.java | UTF-8 | 2,291 | 2.421875 | 2 | [] | no_license | package com.dithok.myCommerce.dto;
public class UserAddressDto{
private String house_number;
private String street;
private String city;
private String state;
private String country;
private String zip_code;
private String latitude;
private String longitude;
private String email;
public String getHouse_number(){
return house_number;
}
public void setHouse_number(String house_number){
this.house_number = house_number;
}
public String getStreet(){
return street;
}
public void setStreet(String street){
this.street = street;
}
public String getCity(){
return city;
}
public void setCity(String city){
this.city = city;
}
public String getCountry(){
return country;
}
public void setCountry(String country){
this.country = country;
}
public String getState(){
return state;
}
public void setState(String state){
this.state = state;
}
public String getZip_code(){
return zip_code;
}
public void setZip_code(String zip_code){
this.zip_code = zip_code;
}
public String getLatitude(){
return latitude;
}
public void setLatitude(String latitude){
this.latitude = latitude;
}
public String getLongitude(){
return longitude;
}
public void setLongitude(String longitude){
this.longitude = longitude;
}
public String getEmail(){
return email;
}
public void setEmail(String email){
this.email = email;
}
public UserAddressDto() {
super();
// TODO Auto-generated constructor stub
}
public UserAddressDto(
String house_number,
String street,
String city,
String state,
String country,
String zip_code,
String latitude,
String longitude,
String email
){
this.house_number = house_number;
this.street = street;
this.city = city;
this.state = state;
this.country = country;
this.zip_code = zip_code;
this.latitude = latitude;
this.longitude = longitude;
this.email = email;
}
}
| true |
197fc24597a99163a318fc3e8a222ec4e1da4372 | Java | playframework/netty-reactive-streams | /netty-reactive-streams-http/src/main/java/com/typesafe/netty/http/StreamedHttpResponse.java | UTF-8 | 400 | 1.984375 | 2 | [
"Apache-2.0"
] | permissive | package com.typesafe.netty.http;
import io.netty.handler.codec.http.HttpResponse;
/**
* Combines {@link HttpResponse} and {@link StreamedHttpMessage} into one
* message. So it represents an http response with a stream of
* {@link io.netty.handler.codec.http.HttpContent} messages that can be subscribed to.
*/
public interface StreamedHttpResponse extends HttpResponse, StreamedHttpMessage {
}
| true |
505d9dadbf0ca99d9f1a70f4a88ff2dd986a46f5 | Java | zetlas1610/MKCore | /src/main/java/com/chaosbuffalo/mkcore/core/talents/PassiveTalent.java | UTF-8 | 778 | 2.5625 | 3 | [] | no_license | package com.chaosbuffalo.mkcore.core.talents;
import com.chaosbuffalo.mkcore.abilities.PassiveTalentAbility;
import net.minecraft.util.ResourceLocation;
public class PassiveTalent extends BaseTalent implements IAbilityTalent<PassiveTalentAbility> {
private final PassiveTalentAbility ability;
public PassiveTalent(ResourceLocation name, PassiveTalentAbility ability) {
super(name);
this.ability = ability;
}
@Override
public PassiveTalentAbility getAbility() {
return ability;
}
@Override
public TalentType<?> getTalentType() {
return TalentType.PASSIVE;
}
@Override
public String toString() {
return "PassiveTalent{" +
"ability=" + ability +
'}';
}
}
| true |
5b4f7e8fa14e8af1baf19c89ca697df3340fd887 | Java | GTZL1/TB-server | /app/database/player/Player.java | UTF-8 | 1,109 | 2.609375 | 3 | [
"CC0-1.0"
] | permissive | package database.player;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "player")
public class Player {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id_player")
private Long idPlayer;
@Column(name="username")
private String username;
@Column(name="password_hash")
private String passwordHash;
public Player() {
}
//used only in tests
public Player(Long idPlayer, String username, String passwordHash) {
this.idPlayer = idPlayer;
this.username = username;
this.passwordHash = passwordHash;
}
public Long getIdPlayer(){
return idPlayer;
}
public String getUsername() {
return this.username;
}
public String getPasswordHash(){
return this.passwordHash;
}
public void setUsername(String username) {
this.username = username;
}
public void setPasswordHash(String passwordHash) {
this.passwordHash = passwordHash;
}
}
| true |
0ec1fc7f5b73c72a927a5e08c9ec232927061b34 | Java | mmccmaxmarcus/javaAgespisa | /src/main/java/br/com/agespisa/entidade/Poco.java | UTF-8 | 1,475 | 2.375 | 2 | [] | no_license | package br.com.agespisa.entidade;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
@SuppressWarnings("serial")
@Entity
public class Poco extends GenericEntidade {
@Column(nullable = true, length = 100)
private String endereco;
@Column(nullable = true)
private Short numero;
@JoinColumn(nullable = false)
@ManyToOne
private Cidade cidade;
@Column(length = 10, nullable = true, name="coluna_edutora")
private String colunaEdutora;
@Column(nullable= true, length = 10)
private String vazaoPoco;
@Column(nullable = true, length = 200)
private String descricao;
public String getVazaoPoco() {
return vazaoPoco;
}
public void setVazaoPoco(String vazaoPoco) {
this.vazaoPoco = vazaoPoco;
}
public String getColunaEdutora() {
return colunaEdutora;
}
public void setColunaEdutora(String colunaEdutora) {
this.colunaEdutora = colunaEdutora;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public String getEndereco() {
return endereco;
}
public void setEndereco(String endereco) {
this.endereco = endereco;
}
public Cidade getCidade() {
return cidade;
}
public void setCidade(Cidade cidade) {
this.cidade = cidade;
}
public Short getNumero() {
return numero;
}
public void setNumero(Short numero) {
this.numero = numero;
}
}
| true |
3519eb70a23e9502e92a4231ee10b9d3120129a7 | Java | daijiejay/daijie | /daijie-jdbc/src/main/java/org/daijie/jdbc/mybatis/example/ExampleBuilder.java | UTF-8 | 6,856 | 2.59375 | 3 | [] | no_license | package org.daijie.jdbc.mybatis.example;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;
public abstract class ExampleBuilder {
private static ThreadLocal<Example> threadExample = new ThreadLocal<Example>();
public static Builder create(Class<?> className) {
Builder builder = new Builder();
return builder.createCriteria(className);
}
@SuppressWarnings({"rawtypes"})
public static class Builder {
private ThreadLocal<Criteria> threadCriteria = new ThreadLocal<Criteria>();
public Builder createCriteria(Class<?> className) {
Example example = new Example(className);
threadExample.set(example);
threadCriteria.set(example.createCriteria());
return this;
}
public Example build() {
return threadExample.get();
}
public Builder orderByDesc(String property) {
threadExample.get().orderBy(property).desc();
return this;
}
public Builder orderByAsc(String property) {
threadExample.get().orderBy(property).asc();
return this;
}
public Builder andIsNull(String property) {
threadCriteria.get().andIsNull(property);
return this;
}
public Builder andIsNotNull(String property) {
threadCriteria.get().andIsNotNull(property);
return this;
}
public Builder andEqualTo(String property, Object value) {
threadCriteria.get().andEqualTo(property, value);
return this;
}
public Builder andNotEqualTo(String property, Object value) {
threadCriteria.get().andNotEqualTo(property, value);
return this;
}
public Builder andGreaterThan(String property, Object value) {
threadCriteria.get().andGreaterThan(property, value);
return this;
}
public Builder andGreaterThanOrEqualTo(String property, Object value) {
threadCriteria.get().andGreaterThanOrEqualTo(property, value);
return this;
}
public Builder andLessThan(String property, Object value) {
threadCriteria.get().andLessThan(property, value);
return this;
}
public Builder andLessThanOrEqualTo(String property, Object value) {
threadCriteria.get().andLessThanOrEqualTo(property, value);
return this;
}
public Builder andIn(String property, Iterable values) {
threadCriteria.get().andIn(property, values);
return this;
}
public Builder andNotIn(String property, Iterable values) {
threadCriteria.get().andNotIn(property, values);
return this;
}
public Builder andBetween(String property, Object value1, Object value2) {
threadCriteria.get().andBetween(property, value1, value2);
return this;
}
public Builder andNotBetween(String property, Object value1, Object value2) {
threadCriteria.get().andNotBetween(property, value1, value2);
return this;
}
public Builder andLike(String property, String value) {
threadCriteria.get().andLike(property, value);
return this;
}
public Builder andNotLike(String property, String value) {
threadCriteria.get().andNotLike(property, value);
return this;
}
public Builder andCondition(String condition) {
threadCriteria.get().andCondition(condition);
return this;
}
public Builder andCondition(String condition, Object value) {
threadCriteria.get().andCondition(condition, value);
return this;
}
public Builder andEqualTo(Object param) {
threadCriteria.get().andEqualTo(param);
return this;
}
public Builder andAllEqualTo(Object param) {
threadCriteria.get().andAllEqualTo(param);
return this;
}
public Builder orIsNull(String property) {
threadCriteria.get().orIsNull(property);
return this;
}
public Builder orIsNotNull(String property) {
threadCriteria.get().orIsNotNull(property);
return this;
}
public Builder orEqualTo(String property, Object value) {
threadCriteria.get().orEqualTo(property, value);
return this;
}
public Builder orNotEqualTo(String property, Object value) {
threadCriteria.get().orNotEqualTo(property, value);
return this;
}
public Builder orGreaterThan(String property, Object value) {
threadCriteria.get().orGreaterThan(property, value);
return this;
}
public Builder orGreaterThanOrEqualTo(String property, Object value) {
threadCriteria.get().orGreaterThanOrEqualTo(property, value);
return this;
}
public Builder orLessThan(String property, Object value) {
threadCriteria.get().orLessThan(property, value);
return this;
}
public Builder orLessThanOrEqualTo(String property, Object value) {
threadCriteria.get().orLessThanOrEqualTo(property, value);
return this;
}
public Builder orIn(String property, Iterable values) {
threadCriteria.get().orIn(property, values);
return this;
}
public Builder orNotIn(String property, Iterable values) {
threadCriteria.get().orNotIn(property, values);
return this;
}
public Builder orBetween(String property, Object value1, Object value2) {
threadCriteria.get().orBetween(property, value1, value2);
return this;
}
public Builder orNotBetween(String property, Object value1, Object value2) {
threadCriteria.get().orNotBetween(property, value1, value2);
return this;
}
public Builder orLike(String property, String value) {
threadCriteria.get().orLike(property, value);
return this;
}
public Builder orNotLike(String property, String value) {
threadCriteria.get().orNotLike(property, value);
return this;
}
public Builder orCondition(String condition) {
threadCriteria.get().orCondition(condition);
return this;
}
public Builder orCondition(String condition, Object value) {
threadCriteria.get().orCondition(condition, value);
return this;
}
public Builder orEqualTo(Object param) {
threadCriteria.get().orEqualTo(param);
return this;
}
public Builder orAllEqualTo(Object param) {
threadCriteria.get().orAllEqualTo(param);
return this;
}
}
}
| true |
51626470891ef7f52847a910c5156cec29f534ac | Java | shashikanthsb/enggproject | /pgr/pgr-master/src/main/java/org/egov/pgr/repository/EscalationTimeTypeRepository.java | UTF-8 | 5,335 | 1.554688 | 2 | [] | no_license | /*
* eGov suite of products aim to improve the internal efficiency,transparency,
* accountability and the service delivery of the government organizations.
*
* Copyright (C) <2015> eGovernments Foundation
*
* The updated version of eGov suite of products as by eGovernments Foundation
* is available at http://www.egovernments.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/ or
* http://www.gnu.org/licenses/gpl.html .
*
* In addition to the terms of the GPL license to be adhered to in using this
* program, the following additional terms are to be complied with:
*
* 1) All versions of this program, verbatim or modified must carry this
* Legal Notice.
*
* 2) Any misrepresentation of the origin of the material is prohibited. It
* is required that all modified versions of this material be marked in
* reasonable ways as different from the original version.
*
* 3) This license does not grant any rights to any user of the program
* with regards to rights under trademark law for use of the trade names
* or trademarks of eGovernments Foundation.
*
* In case of any queries, you can reach eGovernments Foundation at contact@egovernments.org.
*/
package org.egov.pgr.repository;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import org.egov.pgr.domain.model.EscalationTimeType;
import org.egov.pgr.repository.builder.EscalationTimeTypeQueryBuilder;
import org.egov.pgr.repository.rowmapper.EscalationTimeTypeRowMapper;
import org.egov.pgr.web.contract.EscalationTimeTypeGetReq;
import org.egov.pgr.web.contract.EscalationTimeTypeReq;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
@Repository
public class EscalationTimeTypeRepository {
public static final Logger LOGGER = LoggerFactory.getLogger(EscalationTimeTypeRepository.class);
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
private EscalationTimeTypeQueryBuilder escalationTimeTypeQueryBuilder;
@Autowired
private EscalationTimeTypeRowMapper escalationRowMapper;
public EscalationTimeTypeReq persistCreateEscalationTimeType(final EscalationTimeTypeReq escalationTimeTypeRequest) {
LOGGER.info("EscalationTimeTypeRequest::" + escalationTimeTypeRequest);
final String escalationTimeTypeInsert = escalationTimeTypeQueryBuilder.insertEscalationTimeType();
final EscalationTimeType ecalationTimeType = escalationTimeTypeRequest.getEscalationTimeType();
final Object[] obj = new Object[] { ecalationTimeType.getGrievanceType().getId(), ecalationTimeType.getNoOfHours(),
ecalationTimeType.getDesignation(), ecalationTimeType.getTenantId(),
Long.valueOf(escalationTimeTypeRequest.getRequestInfo().getUserInfo().getId()),
Long.valueOf(escalationTimeTypeRequest.getRequestInfo().getUserInfo().getId()),
new Date(new java.util.Date().getTime()), new Date(new java.util.Date().getTime()) };
jdbcTemplate.update(escalationTimeTypeInsert, obj);
return escalationTimeTypeRequest;
}
public List<EscalationTimeType> getAllEscalationTimeTypes(final EscalationTimeTypeGetReq escalationGetRequest) {
LOGGER.info("EscalationTimeType search Request::" + escalationGetRequest);
final List<Object> preparedStatementValues = new ArrayList<>();
final String queryStr = escalationTimeTypeQueryBuilder.getQuery(escalationGetRequest, preparedStatementValues);
final List<EscalationTimeType> escalationTypes = jdbcTemplate.query(queryStr,
preparedStatementValues.toArray(), escalationRowMapper);
return escalationTypes;
}
public EscalationTimeTypeReq persistUpdateEscalationTimeType(final EscalationTimeTypeReq escalationTimeTypeRequest) {
LOGGER.info("EscalationTimeTypeRequest::" + escalationTimeTypeRequest);
final String escalationTimeTypeInsert = escalationTimeTypeQueryBuilder.updateEscalationTimeType();
final EscalationTimeType ecalationTimeType = escalationTimeTypeRequest.getEscalationTimeType();
final Object[] obj = new Object[] { ecalationTimeType.getGrievanceType().getId(), ecalationTimeType.getNoOfHours(),
ecalationTimeType.getDesignation(), ecalationTimeType.getTenantId(),
Long.valueOf(escalationTimeTypeRequest.getRequestInfo().getUserInfo().getId()),
Long.valueOf(escalationTimeTypeRequest.getRequestInfo().getUserInfo().getId()),
new Date(new java.util.Date().getTime()), new Date(new java.util.Date().getTime()), ecalationTimeType.getId()};
jdbcTemplate.update(escalationTimeTypeInsert, obj);
return escalationTimeTypeRequest;
}
}
| true |
062ccd4b01785537b10fe25b7fc6dac58bfc17bb | Java | freekeeper9966/wctf | /src/main/java/cn/gin/wctf/common/util/JedisUtils.java | UTF-8 | 21,043 | 2.65625 | 3 | [
"Apache-2.0"
] | permissive | package cn.gin.wctf.common.util;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.exceptions.JedisException;
/**
* <p>使用 Jedis 操作 Redis 数据库的工具类。适用于集群生产环境下的缓存支持类,因为 Shiro 的自定义 Session 模块需要一个 Session 持久化方案,而
* 工作与 JVM 之内的 EhCache 是很难完成不同 JVM 之间的缓存同步的。Redis 作为一个独立的内存缓存与数据持久化系统,很容易实现这个功能</p>
* <p>单机生产环境下可以参考 {@link CacheUtils},使用 EhCache 实现的缓存支持类。</p>
*
* @author Gintoki
* @version 2017-10-15
*/
public class JedisUtils {
/**
* The default root logger.
*/
private static final Logger logger = LoggerFactory.getLogger(JedisUtils.class);
/**
* 常用缓存时间
*/
public static final int ONE_DAY = 86400;
/**
* jedis 连接池
**/
private static JedisPool jedisPool = SpringContextHolder.getBean(JedisPool.class);
/**
* 获取String缓存,在默认的redis 默认索引库中
* @param key 缓存键
* @return
*/
public static String get(String key) {
return get(key, RedisIndex.SYSTEM_CACHE);
}
/**
* 获取String缓存,在指定的redis数据库中
* @param key 缓存键
* @param index 数据库的索引下标
* @return
*/
public static String get(String key, RedisIndex index) {
String value = null;
Jedis jedis = null;
try {
jedis = getResource();
jedis.select(index.getIndex());
if (jedis.exists(key)) {
value = jedis.get(key);
value = StringUtils.isNotBlank(value) && !"nil".equalsIgnoreCase(value) ? value : null;
logger.debug("get {} = {} from redis", key, value);
}
} catch (Exception e) {
jedisPool.returnBrokenResource(jedis);
logger.warn("get {} = {}", key, value, e);
} finally {
jedisPool.returnResource(jedis); // 归还资源
}
return value;
}
/**
* 获取List缓存
* @param key 缓存键
* @return 值
*/
public static List<String> getList(String key) {
return getList(key, RedisIndex.SYSTEM_CACHE);
}
/**
* 获取List缓存
* @param key 缓存键
* @param index 数据库的索引下标
* @return 值
*/
public static List<String> getList(String key, RedisIndex index) {
List<String> value = null;
Jedis jedis = null;
try {
jedis = getResource();
jedis.select(index.getIndex());
if (jedis.exists(key)) {
value = jedis.lrange(key, 0, -1);
logger.debug("getList {} = {}", key, value);
}
} catch (Exception e) {
jedisPool.returnBrokenResource(jedis);
logger.warn("getList {} = {}", key, value, e);
} finally {
jedisPool.returnResource(jedis);
}
return value;
}
/**
* 获取Set缓存
* @param key 缓存键
* @return 值
*/
public static Set<String> getSet(String key) {
return getSet(key, RedisIndex.SYSTEM_CACHE);
}
/**
* 获取Set缓存
* @param key 缓存键
* @param index 数据库的索引下标
* @return 值
*/
public static Set<String> getSet(String key, RedisIndex index) {
Set<String> value = null;
Jedis jedis = null;
try {
jedis = getResource();
jedis.select(index.getIndex());
if (jedis.exists(key)) {
value = jedis.smembers(key);
logger.debug("getSet {} = {}", key, value);
}
} catch (Exception e) {
jedisPool.returnBrokenResource(jedis);
logger.warn("getSet {} = {}", key, value, e);
} finally {
jedisPool.returnResource(jedis);
}
return value;
}
/**
* 获取Map缓存
* @param key 缓存键
* @return 值
*/
public static Map<String, String> getMap(String key) {
return getMap(key, RedisIndex.SYSTEM_CACHE);
}
/**
* 获取Map缓存
* @param key 缓存键
* @param index 数据库的索引下标
* @return 值
*/
public static Map<String, String> getMap(String key, RedisIndex index) {
Map<String, String> value = null;
Jedis jedis = null;
try {
jedis = getResource();
jedis.select(index.getIndex());
if (jedis.exists(key)) {
value = jedis.hgetAll(key);
logger.debug("getMap {} = {}", key, value);
}
} catch (Exception e) {
jedisPool.returnBrokenResource(jedis);
logger.warn("getMap {} = {}", key, value, e);
} finally {
jedisPool.returnResource(jedis);
}
return value;
}
/**
* 获取Object缓存
* @param key 缓存键
* @return 值
*/
public static Object getObject(String key) {
return getObject(key, RedisIndex.SYSTEM_CACHE);
}
/**
* 获取Object缓存
* @param key 缓存键
* @param index 数据库的索引下标
* @return 值
*/
public static Object getObject(String key, RedisIndex index) {
Object value = null;
Jedis jedis = null;
try {
jedis = getResource();
jedis.select(index.getIndex());
if (jedis.exists(getBytesKey(key))) {
value = toObject(jedis.get(getBytesKey(key)));
logger.debug("getObject {} = {}", key, value);
}
} catch (Exception e) {
jedisPool.returnBrokenResource(jedis);
logger.warn("getObject {} = {}", key, value, e);
} finally {
jedisPool.returnResource(jedis);
}
return value;
}
/**
* 获取Object List缓存
* @param key 缓存键
* @return 值
*/
public static List<Object> getObjectList(String key) {
return getObjectList(key, RedisIndex.SYSTEM_CACHE);
}
/**
* 获取Object List缓存
* @param key 缓存键
* @param index 数据库的索引下标
* @return 值
*/
public static List<Object> getObjectList(String key, RedisIndex index) {
List<Object> value = null;
Jedis jedis = null;
try {
jedis = getResource();
jedis.select(index.getIndex());
if (jedis.exists(getBytesKey(key))) {
List<byte[]> list = jedis.lrange(getBytesKey(key), 0, -1);
value = Lists.newArrayList();
for (byte[] bs : list) {
value.add(toObject(bs));
}
logger.debug("getObjectList {} = {}", key, value);
}
} catch (Exception e) {
jedisPool.returnBrokenResource(jedis);
logger.warn("getObjectList {} = {}", key, value, e);
} finally {
jedisPool.returnResource(jedis);
}
return value;
}
/**
* 获取Object Set缓存
* @param key 缓存键
* @return 值
*/
public static Set<Object> getObjectSet(String key) {
return getObjectSet(key, RedisIndex.SYSTEM_CACHE);
}
/**
* 获取Object Set缓存
* @param key 缓存键
* @param index 数据库的索引下标
* @return 值
*/
public static Set<Object> getObjectSet(String key, RedisIndex index) {
Set<Object> value = null;
Jedis jedis = null;
try {
jedis = getResource();
jedis.select(index.getIndex());
if (jedis.exists(getBytesKey(key))) {
value = Sets.newHashSet();
Set<byte[]> set = jedis.smembers(getBytesKey(key));
for (byte[] bs : set) {
value.add(toObject(bs));
}
logger.debug("getObjectSet {} = {}", key, value);
}
} catch (Exception e) {
jedisPool.returnBrokenResource(jedis);
logger.warn("getObjectSet {} = {}", key, value, e);
} finally {
jedisPool.returnResource(jedis);
}
return value;
}
/**
* 获取Object Map缓存
* @param key 缓存键
* @return 值
*/
public static Map<String, Object> getObjectMap(String key) {
return getObjectMap(key, RedisIndex.SYSTEM_CACHE);
}
/**
* 获取Object Map缓存
* @param key 缓存键
* @param index 数据库的索引下标
* @return 值
*/
public static Map<String, Object> getObjectMap(String key, RedisIndex index) {
Map<String, Object> value = null;
Jedis jedis = null;
try {
jedis = getResource();
jedis.select(index.getIndex());
if (jedis.exists(getBytesKey(key))) {
value = Maps.newHashMap();
Map<byte[], byte[]> map = jedis.hgetAll(getBytesKey(key));
for (Map.Entry<byte[], byte[]> e : map.entrySet()) {
value.put(StringUtils.toString(e.getKey()), toObject(e.getValue()));
}
logger.debug("getObjectMap {} = {}", key, value);
}
} catch (Exception e) {
jedisPool.returnBrokenResource(jedis);
logger.warn("getObjectMap {} = {}", key, value, e);
} finally {
jedisPool.returnResource(jedis);
}
return value;
}
/**
* 设置缓存数据
* @param key 缓存键
* @param value 缓存值
* @param timeout 数据的超时时间,0为不超时
* @return 是否设置成功,redis格式
*/
public static String set(String key, String value, RedisIndex index) {
String result = null;
Jedis jedis = null;
try {
jedis = getResource();
jedis.select(index.getIndex());
result = jedis.set(key, value);
logger.debug("set {} = {}", key, value);
} catch (Exception e) {
jedisPool.returnBrokenResource(jedis);
logger.warn("set {} = {}", key, value, e);
} finally {
jedisPool.returnResource(jedis);
}
return result;
}
/**
* 设置缓存数据
* @param key 缓存键
* @param value 缓存值
* @param timeout 数据的超时时间,0为不超时
* @return 是否设置成功,redis格式
*/
public static String set(String key, String value, int timeout) {
return set(key, value, timeout, RedisIndex.SYSTEM_CACHE);
}
/**
* 设置缓存数据
* @param key 缓存键
* @param value 缓存值
* @param timeout 数据的超时时间,0为不超时
* @param index 数据库的索引下标
* @return 是否设置成功,redis格式
*/
public static String set(String key, String value, int timeout, RedisIndex index) {
String result = null;
Jedis jedis = null;
try {
jedis = getResource();
jedis.select(index.getIndex());
result = jedis.set(key, value);
if (timeout != 0) {
jedis.expire(key, timeout);
}
logger.debug("set {} = {}", key, value);
} catch (Exception e) {
jedisPool.returnBrokenResource(jedis);
logger.warn("set {} = {}", key, value, e);
} finally {
jedisPool.returnResource(jedis);
}
return result;
}
/**
* 设置List缓存
* @param key 缓存键
* @param value 缓存值
* @param timeout 数据的超时时间,0为不超时
* @return
*/
public static long setList(String key, List<String> value, int timeout) {
return setList(key, value, timeout, RedisIndex.SYSTEM_CACHE);
}
/**
* 设置List缓存
* @param key 缓存键
* @param value 缓存值
* @param timeout 数据的超时时间,0为不超时
* @param index 数据库的索引下标
* @return
*/
public static long setList(String key, List<String> value, int timeout, RedisIndex index) {
long result = 0;
Jedis jedis = null;
try {
jedis = getResource();
jedis.select(index.getIndex());
if (jedis.exists(key)) {
jedis.del(key);
}
result = jedis.rpush(key, (String[]) value.toArray());
if (timeout != 0) {
jedis.expire(key, timeout);
}
logger.debug("setList {} = {}", key, value);
} catch (Exception e) {
jedisPool.returnBrokenResource(jedis);
logger.warn("setList {} = {}", key, value, e);
} finally {
jedisPool.returnResource(jedis);
}
return result;
}
/**
* 设置Set缓存
* @param key 缓存键
* @param value 缓存值
* @param timeout 数据的超时时间,0为不超时
* @return
*/
public static long setSet(String key, Set<String> value, int timeout) {
return setSet(key, value, timeout, RedisIndex.SYSTEM_CACHE);
}
/**
* 设置Set缓存
* @param key 缓存键
* @param value 缓存值
* @param timeout 数据的超时时间,0为不超时
* @param index 数据库的索引下标
* @return
*/
public static long setSet(String key, Set<String> value, int timeout, RedisIndex index) {
long result = 0;
Jedis jedis = null;
try {
jedis = getResource();
jedis.select(index.getIndex());
if (jedis.exists(key)) {
jedis.del(key);
}
result = jedis.sadd(key, (String[]) value.toArray());
if (timeout != 0) {
jedis.expire(key, timeout);
}
logger.debug("setSet {} = {}", key, value);
} catch (Exception e) {
jedisPool.returnBrokenResource(jedis);
logger.warn("setSet {} = {}", key, value, e);
} finally {
jedisPool.returnResource(jedis);
}
return result;
}
/**
* 设置Map缓存
* @param key 缓存键
* @param value 缓存值
* @param timeout 数据的超时时间,0为不超时
* @return
*/
public static String setMap (String key, Map<String, String> value, int timeout) {
return setMap(key, value, timeout, RedisIndex.SYSTEM_CACHE);
}
/**
* 设置Map缓存
* @param key 缓存键
* @param value 缓存值
* @param timeout 数据的超时时间,0为不超时
* @param index 数据库的索引下标
* @return
*/
public static String setMap(String key, Map<String, String> value, int timeout, RedisIndex index) {
if(value.size() > 0) {
String result = null;
Jedis jedis = null;
try {
jedis = getResource();
jedis.select(index.getIndex());
if (jedis.exists(key)) {
jedis.del(key);
}
result = jedis.hmset(key, value);
if (timeout != 0) {
jedis.expire(key, timeout);
}
logger.debug("setMap {} = {}", key, value);
} catch (Exception e) {
jedisPool.returnBrokenResource(jedis);
logger.warn("setMap {} = {}", key, value, e);
} finally {
jedisPool.returnResource(jedis);
}
return result;
}
return StringUtils.EMPTY;
}
/**
* 设置对象缓存
* @param key 缓存键
* @param value 缓存值
* @param timeout 数据的超时时间,0为不超时
* @return
*/
public static String setObject(String key, Object value, int timeout) {
return setObject(key, value, timeout, RedisIndex.SYSTEM_CACHE);
}
/**
* 设置对象缓存
* @param key 缓存键
* @param value 缓存值
* @param timeout 数据的超时时间,0为不超时
* @param index 数据库的索引下标
* @return
*/
public static String setObject(String key, Object value, Integer timeout, RedisIndex index) {
String result = null;
Jedis jedis = null;
try {
jedis = getResource();
jedis.select(index.getIndex());
result = jedis.set(getBytesKey(key), toBytes(value));
if (timeout != null) {
jedis.expire(key, timeout);
}
logger.debug("setObject {} = {}", key, value);
} catch (Exception e) {
jedisPool.returnBrokenResource(jedis);
logger.warn("setObject {} = {}", key, value, e);
} finally {
jedisPool.returnResource(jedis);
}
return result;
}
/**
* 设置Object List缓存
* @param key 缓存键
* @param value 缓存值
* @param timeout timeout 数据的超时时间,0为不超时
* @return
*/
public static long setObjectList(String key, List<Object> value, int timeout) {
return setObjectList(key, value, timeout, RedisIndex.SYSTEM_CACHE);
}
/**
* 设置Object List缓存
* @param key 缓存键
* @param value 缓存值
* @param timeout timeout 数据的超时时间,0为不超时
* @param index 数据库的索引下标
* @return
*/
public static long setObjectList(String key, List<Object> value, int timeout, RedisIndex index) {
long result = 0;
Jedis jedis = null;
try {
jedis = getResource();
jedis.select(index.getIndex());
if (jedis.exists(getBytesKey(key))) {
jedis.del(key);
}
List<byte[]> list = Lists.newArrayList();
for (Object o : value) {
list.add(toBytes(o));
}
result = jedis.rpush(getBytesKey(key), (byte[][]) list.toArray());
if (timeout != 0) {
jedis.expire(key, timeout);
}
logger.debug("setObjectList {} = {}", key, value);
} catch (Exception e) {
jedisPool.returnBrokenResource(jedis);
logger.warn("setObjectList {} = {}", key, value, e);
} finally {
jedisPool.returnResource(jedis);
}
return result;
}
/**
* 设置Set缓存
* @param key 缓存键
* @param value 缓存值
* @param timeout 超时时间,0为不超时
* @return
*/
public static long setObjectSet(String key, Set<Object> value, int timeout) {
return setObjectSet(key, value, timeout, RedisIndex.SYSTEM_CACHE);
}
/**
* 设置Set缓存
* @param key 缓存键
* @param value 缓存值
* @param timeout 超时时间,0为不超时
* @param index 数据库的索引下标
* @return
*/
public static long setObjectSet(String key, Set<Object> value, int timeout, RedisIndex index) {
long result = 0;
Jedis jedis = null;
try {
jedis = getResource();
jedis.select(index.getIndex());
if (jedis.exists(getBytesKey(key))) {
jedis.del(key);
}
Set<byte[]> set = Sets.newHashSet();
for (Object o : value) {
set.add(toBytes(o));
}
result = jedis.sadd(getBytesKey(key), (byte[][]) set.toArray());
if (timeout != 0) {
jedis.expire(key, timeout);
}
logger.debug("setObjectSet {} = {}", key, value);
} catch (Exception e) {
jedisPool.returnBrokenResource(jedis);
logger.warn("setObjectSet {} = {}", key, value, e);
} finally {
jedisPool.returnResource(jedis);
}
return result;
}
/**
* 设置Map缓存
* @param key 缓存键
* @param value 缓存值
* @param timeout 超时时间,0为不超时
* @return
*/
public static String setObjectMap(String key, Map<String, Object> value, int timeout) {
return setObjectMap(key, value, timeout, RedisIndex.SYSTEM_CACHE);
}
/**
* 设置Map缓存
* @param key 缓存键
* @param value 缓存值
* @param timeout 超时时间,0为不超时
* @param index 数据库的索引下标
* @return
*/
public static String setObjectMap(String key, Map<String, Object> value, int timeout, RedisIndex index) {
String result = null;
Jedis jedis = null;
try {
jedis = getResource();
jedis.select(index.getIndex());
if (jedis.exists(getBytesKey(key))) {
jedis.del(key);
}
Map<byte[], byte[]> map = Maps.newHashMap();
for (Map.Entry<String, Object> e : value.entrySet()) {
map.put(getBytesKey(e.getKey()), toBytes(e.getValue()));
}
result = jedis.hmset(getBytesKey(key), (Map<byte[], byte[]>) map);
if (timeout != 0) {
jedis.expire(key, timeout);
}
logger.debug("setObjectMap {} = {}", key, value);
} catch (Exception e) {
jedisPool.returnBrokenResource(jedis);
logger.warn("setObjectMap {} = {}", key, value, e);
} finally {
jedisPool.returnResource(jedis);
}
return result;
}
/**
* 删除默认缓存区中的指定缓存
* @param key 缓存键
* @return
*/
public static long del(String key) {
return del(key, RedisIndex.SYSTEM_CACHE);
}
/**
* 删除默认缓存区中的指定缓存
* @param key 缓存键
* @return
*/
public static long del(String key, RedisIndex index) {
long result = 0;
Jedis jedis = null;
try {
jedis = getResource();
jedis.select(index.getIndex());
if (jedis.exists(key)){
result = jedis.del(key);
logger.debug("del {}", key);
}else{
logger.debug("del {} not exists", key);
}
} catch (Exception e) {
jedisPool.returnBrokenResource(jedis);
logger.warn("del {}", key, e);
} finally {
jedisPool.returnResource(jedis);
}
return result;
}
/**
* 移除 Map 缓存中的值
* @param key - Map对应的键
* @param mapKey - 要删除Map中缓存的键
* @return
*/
public static long mapRemove(String key, String mapKey) {
long result = 0;
Jedis jedis = null;
try {
jedis = getResource();
result = jedis.hdel(key, mapKey);
logger.debug("mapRemove {} {}", key, mapKey);
} catch (Exception e) {
jedisPool.returnBrokenResource(jedis);
logger.warn("mapRemove {} {}", key, mapKey, e);
} finally {
jedisPool.returnResource(jedis);
}
return result;
}
/**
* 获取redis资源
* @return
* @throws JedisException
*/
public static Jedis getResource() throws JedisException {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
} catch (JedisException e) {
jedisPool.returnBrokenResource(jedis);
logger.warn("getResource()", e);
throw e;
}
return jedis;
}
/**
* 获取byte[]类型Key
* @param key
* @return
*/
public static byte[] getBytesKey(Object object) {
if (object instanceof String) {
return StringUtils.getBytes((String) object);
} else {
return ObjectUtils.serialize(object);
}
}
/**
* 获取byte[]类型Key
* @param key
* @return
*/
public static Object getObjectKey(byte[] key) {
try {
return StringUtils.toString(key);
} catch (UnsupportedOperationException e) {
try {
return JedisUtils.toObject(key);
} catch (UnsupportedOperationException ex) {
ex.printStackTrace();
}
}
return null;
}
/**
* Object转换byte[]类型
* @param key
* @return
*/
public static byte[] toBytes(Object object) {
return ObjectUtils.serialize(object);
}
/**
* byte[]型转换Object
* @param key
* @return
*/
public static Object toObject(byte[] bytes) {
return ObjectUtils.unserialize(bytes);
}
public static void returnResource(Jedis jedis) {
jedisPool.returnResource(jedis);
}
}
| true |
7f4cf4ea4244b36f857f3d8b5d2b3ac5dd0c0e14 | Java | AlanFoster/Java-Game-Engine | /gameEngine/entitysystem/systems/DeleteSystem.java | UTF-8 | 1,665 | 3.015625 | 3 | [] | no_license | package entitysystem.systems;
import java.util.List;
import entitysystem.core.Entity;
import entitysystem.core.EntityManager;
import entitysystem.core.ProcessEntitySystem;
import entitysystems.components.Children;
import entitysystems.components.DeleteComponent;
/**
* Deletes all entities which have the {@link DeleteComponent} added to them.
* This just offers a means of logically removing everything that requires it at
* a specific logical interval. For instance one system may wish to delete an
* entity from the world, but it shouldn'd do immediately as other systems may
* also wish to handle some logic to do with the entity too. This allows us to
* 'delay' an entity's deletion to the next time the {@link DeleteSystem} gets
* its logical update.
* <p>
* It is suggested that the {@link DeleteSystem} either runs last, or first, in
* order to keep with the logical idea of a deleted entity still being available
* throughout all systems until the next game loop.
* <p>
*
* @author Alan Foster
* @version 1.0
*/
public class DeleteSystem extends ProcessEntitySystem {
public DeleteSystem(EntityManager entityManager) {
super(entityManager);
}
@Override
public void refreshList() {
entityList = entityManager.getEntitiesContaining(DeleteComponent.class);
}
@Override
public void processEntity(Entity entity) {
// Ensure that we also remove any children entites owned by the parent
Children childrenComponent = entity.getComponent(Children.class);
if (childrenComponent != null) {
for (Entity child : childrenComponent.children) {
entityManager.removeEntity(child);
}
}
entityManager.removeEntity(entity);
}
} | true |
26ada8b65407e56f098c7bbdd7061d5a32b33727 | Java | DzaNemo/QuizApp | /app/src/main/java/link/quizassgn/PlayQuizActivity.java | UTF-8 | 3,591 | 2.3125 | 2 | [] | no_license | package link.quizassgn;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
import link.quizassgn.data.DatabaseHelper;
public class PlayQuizActivity extends AppCompatActivity {
List<Questions> questionList;
int score = 0;
int questID = 0;
Questions currentQuestion;
TextView questionTextView;
RadioButton rb1, rb2, rb3;
Button nextBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_quiz);
DatabaseHelper dbHelp = new DatabaseHelper(this);
questionList = dbHelp.getAllQuestions();
currentQuestion = questionList.get(questID);
questionTextView = findViewById(R.id.questionTxtView);
rb1 = findViewById(R.id.radio_btn_1);
rb2 = findViewById(R.id.radio_btn_2);
rb3 = findViewById(R.id.radio_btn_3);
nextBtn = findViewById(R.id.button_next);
setQuestionView();
nextBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
RadioGroup radioGroup = findViewById(R.id.radioGroup);
RadioButton answer = findViewById(radioGroup.getCheckedRadioButtonId());
radioGroup.clearCheck();
if (answer != null && currentQuestion.getAnswer().contentEquals(answer.getText())) {
score++;
}
if (questID < 5 ){
currentQuestion = questionList.get(questID);
setQuestionView();
}else{
Intent resultIntent = new Intent(PlayQuizActivity.this,ResultActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("score",score);
resultIntent.putExtras(bundle);
startActivity(resultIntent);
finish();
/* AlertDialog.Builder builder = new AlertDialog.Builder(PlayQuizActivity.this);
builder.setMessage("Your score is " + score + " of possible 5 points");
builder.setCancelable(false);
builder.setPositiveButton("New Game", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
recreate();
}
});
builder.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();*/
}
}
});
}
private void setQuestionView() {
questionTextView.setText(currentQuestion.getQuestion());
rb1.setText(currentQuestion.getOptionA());
rb2.setText(currentQuestion.getOptionB());
rb3.setText(currentQuestion.getOptionC());
questID++;
}
}
| true |
b04ab18754a5bab728e40a6b2a8304e92c2f9e23 | Java | Syntea/xdef | /xdef-buildtools/src/main/java/buildtools/Canonize.java | UTF-8 | 6,305 | 2.671875 | 3 | [
"Apache-2.0"
] | permissive | package buildtools;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.Date;
/** Canonize sources.
* <p>1. Remove all white spaces after last non-blank character
* at the end of line and replace leading spaces by tabs.
* <p>2. Check and generate message report classes.
* @author Vaclav Trojan
*/
public class Canonize {
/** Charset of sources. */
static final String JAVA_SOURCE_CHARSET = "UTF-8";
/** if true the header (copyright) info text is generated from the file. */
static boolean _hdr = false;
/** if true the _tail (modification) info text is generated from the file.*/
static boolean _tail = false;
/** just prevent user to create an instance of this class. */
private Canonize() {}
/** Canonize sources. Remove all trailing white spaces on all lines and
* handle with leading spaces an all lines according to argument
* <code>tabs</code>.
* Insert or update header or _tail information to sources
* according to value of arguments <code>_hdr</code> and <code>_tail</code>.
* If the argument <code>dirTree</code> is true, do it with all specified
* files in child directories.
* @param projectBase file name of project directory.
* @param filename name of file (wildcards are possible).
* @param dirTree If <code>true<code> then dirTree process in child
* subdirectories.
* @param hdr If <code>true</code> then leading standard copyright
* information is inserted before the first line of Java source or it
* replaces the existing one. The template for the copyright information is
* taken from the file <code>hdrinfo.txt</code>the root directory
* <code>java</code> (under which are projects).If the argument's value
* is <code>false</code> then the top of source remains unchanged.
* @param tail If <code>true</code> then log information is added after the
* last line of Java source or it replaces the existing one.The template
* used for the log information is taken from the file
* <code>tailinfo.txt</code> in the root directory
* <code>java</code> (under which are projects). If the value of this
* argument is <code>false</code> then the end source remains unchanged.
*/
private static void doSources(final String projectBase,
final String filename,
final boolean dirTree) {
try {
File f = new File(projectBase, filename).getCanonicalFile();
if (!f.exists() || !f.isDirectory()) {
System.err.println("[ERROR] " + f.getAbsolutePath()
+ " not exists or it is not directory");
return;
}
String home = f.getAbsolutePath().replace('\\', '/');
if (!home.endsWith("/")) {
home += '/';
}
if (home.endsWith("/data/")) {
return; //do not process data directories
}
String hdrTemplate = null;
String tailTemplate = null;
System.out.println("Directory: " + home);
CanonizeSource.canonize(home + "*.java",
dirTree,
true,
4,
hdrTemplate, tailTemplate, JAVA_SOURCE_CHARSET, true);
// CanonizeSource.canonize(home + "*.xml",
// dirTree,
// false,
// -1,
// null, null, JAVA_SOURCE_CHARSET, true);
// CanonizeSource.canonize(home + "*.html",
// dirTree,
// false,
// -1,
// null, null, JAVA_SOURCE_CHARSET, true);
// CanonizeSource.canonize(home + "*.xdef",
// dirTree,
// false,
// -1,
// null, null, JAVA_SOURCE_CHARSET, true);
CanonizeSource.canonize(home + "*.properties",
dirTree,
false,
-1,
null, null, JAVA_SOURCE_CHARSET, true);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
/** Update release date in the file changelog.md.
* @param projectBase base project directory.
* @param date actual date.
*/
private static void updateDateInChangeLog(final String projectBase,
final String date) {
try {
File f = new File(projectBase, "changelog.md");
Reader fr = new InputStreamReader(new FileInputStream(f),
Charset.forName("UTF-8"));
BufferedReader bufrdr = new BufferedReader(fr);
StringBuilder sb = new StringBuilder();
String line;
boolean wasVer = false;
boolean changed = false;
while ((line = bufrdr.readLine()) != null) {
int ndx;
if (!wasVer && line.indexOf('$') < 0
&& line.startsWith("# Version ")
&& (ndx = line.indexOf(" release-date")) > 0) {
String s =
line.substring(0, ndx) + " release-date " + date;
changed = !s.equals(line);
line = s;
wasVer = true;
}
sb.append(line).append('\n');
}
bufrdr.close();
if (changed) {
Writer wr = new OutputStreamWriter(new FileOutputStream(f),
Charset.forName("UTF-8"));
wr.write(sb.toString());
wr.close();
System.out.println("Updated date in changelog.md");
} else {
System.out.println("Date in changelog.md not changed");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
/** Canonize sources.
* @param args array with command line parameters (no parameters used).
*/
public static void main(String... args) {
String projectBase;
try {
File baseDir = args == null || args.length == 0
? new File("../xdef") : new File(args[0]);
if (!baseDir.exists() || !baseDir.isDirectory()) {
throw new RuntimeException("Base is not directory.");
}
projectBase = baseDir.getCanonicalPath().replace('\\', '/');
} catch (Exception ex) {
throw new RuntimeException("Can't find project base directory");
}
ResetPreprocessorSwitches.main(projectBase);
_hdr = false;
_tail = false;
int i = projectBase.lastIndexOf('/');
if (i < 0) {
throw new RuntimeException("Unknown build structure");
}
// Canonize sources: replace leading spaces with tabs and remove
// trailing white spaces.
doSources(projectBase, "/src/main/java", true);
doSources(projectBase, "/src/main/resources/org", true);
doSources(projectBase, "/src/test/java", true);
// register report messages
GenReportTables.main(projectBase);
// // update date in files changelog.md and in pom.xml
// String date = String.format("%tF", new Date()); // actual date
// updateDateInChangeLog(projectBase, date);
// updateDateInPomXml(date);
}
} | true |
1df22ae63bc9748a5c2a10a94cd0ef1339a52b90 | Java | gruelbox/transaction-outbox | /transactionoutbox-spring/src/test/java/com/gruelbox/transactionoutbox/acceptance/Utils.java | UTF-8 | 953 | 2.5 | 2 | [
"Apache-2.0"
] | permissive | package com.gruelbox.transactionoutbox.acceptance;
import com.gruelbox.transactionoutbox.ThrowingRunnable;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class Utils {
private static final Logger LOGGER = LoggerFactory.getLogger(Utils.class);
@SuppressWarnings({"SameParameterValue", "WeakerAccess", "UnusedReturnValue"})
static boolean safelyRun(String gerund, ThrowingRunnable runnable) {
try {
runnable.run();
return true;
} catch (Exception e) {
LOGGER.error("Error when {}", gerund, e);
return false;
}
}
@SuppressWarnings("unused")
static void safelyClose(AutoCloseable... closeables) {
safelyClose(Arrays.asList(closeables));
}
private static void safelyClose(Iterable<? extends AutoCloseable> closeables) {
closeables.forEach(
d -> {
if (d == null) return;
safelyRun("closing resource", d::close);
});
}
}
| true |
f3b6e741c65fc874ea6c4af75198ec2b0f3ab6a3 | Java | gimeneko01/prueba | /Petagramaejercicios/Petagramejercicios-master/app/src/main/java/fragment/IRecylclerViewFragmentView.java | UTF-8 | 378 | 1.671875 | 2 | [] | no_license | package fragment;
import java.util.ArrayList;
import adapter.MascotaAdaptador;
import freezone.ec.petagram.Mascota;
public interface IRecylclerViewFragmentView {
public void generarLinearLayoutVertical();
public MascotaAdaptador crearAdaptador(ArrayList<Mascota> mascotas);
public void inicializarAdaptadorRV(MascotaAdaptador adaptador);
}
| true |
44a26c0657c542a582239430b8edc2ec180b33f2 | Java | Telokin/projektowanie-serwisow-www-furman-175ic | /projekt_strony_internetowej1/src/main/java/pl/furmanj/oiw/service/NoteRepo.java | UTF-8 | 964 | 1.960938 | 2 | [] | no_license | package pl.furmanj.oiw.service;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import pl.furmanj.oiw.model.Author;
import pl.furmanj.oiw.model.Note;
import java.util.List;
@Repository
public interface NoteRepo extends JpaRepository<Note, Long> {
Note findAllById(Long id);
@Query("SELECT note FROM Note note WHERE note.categories LIKE %:name%")
List<Note> findAllByCategoriesContains(@Param("name") String name);
@Query("SELECT note FROM Note note LEFT JOIN Author a ON note.author =a WHERE note.author =:user")
List<Note> findAllByAuthor(@Param("user") Author user);
@Modifying
@Query("DELETE FROM Note note WHERE note.id =:note_id")
void deleteById(@Param("note_id") Long id);
}
| true |
1f240fa8b341d4c6d5eaa0740b836bd356187f7d | Java | ewingcode/education | /src/com/web/service/OrderRoleService.java | UTF-8 | 1,227 | 2.1875 | 2 | [] | no_license | package com.web.service;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Repository;
import com.core.jdbc.BaseDao;
import com.core.jdbc.DaoException;
import com.web.exception.OrderException;
import com.web.model.OrderRole;
/**
*
* 签单角色负责人配置服務
*
*/
@Repository("orderRoleService")
public class OrderRoleService {
@Resource
private BaseDao baseDao;
public int getChargerType(int roleId) throws DaoException, OrderException {
List<OrderRole> list = baseDao
.find("roleId=" + roleId, OrderRole.class);
/*
* if (list.isEmpty()) { throw new
* OrderException("could not found charger for roleid:" + roleId); }
*/
if (!list.isEmpty() && list.size() == 1)
return list.get(0).getCharger();
return 0;
}
public int getRoleId(int chargerType) throws DaoException, OrderException {
List<OrderRole> list = baseDao.find("charger=" + chargerType,
OrderRole.class);
/*
* if (list.isEmpty()) { throw new
* OrderException("could not found roleid for chargerType:" +
* chargerType); } return list.get(0).getRoleId();
*/
if (!list.isEmpty() && list.size() == 1)
return list.get(0).getRoleId();
return 0;
}
}
| true |
63855e3dc0e74b140ec07eadfa53a57654a2706b | Java | projetomyevents/MyEventsApi | /src/main/java/br/com/myevents/model/dto/CityDTO.java | UTF-8 | 586 | 2.09375 | 2 | [] | no_license | package br.com.myevents.model.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* Representa um contrato de uma cidade.
*/
@NoArgsConstructor
@AllArgsConstructor
@Data
public class CityDTO implements Serializable {
private static final long serialVersionUID = 1L;
/**
* A chave primária da cidade.
*/
private Integer id;
/**
* O nome da cidade.
*/
private String name;
/**
* O identificador do estado da cidade.
*/
private Integer stateId;
}
| true |
c946fbf4b42ebbe2aff5f97728d1fc1dcb866815 | Java | fasseg/elasticstore | /elasticstore-server/src/main/java/org/elasticstore/server/config/ElasticstoreConfiguration.java | UTF-8 | 1,984 | 1.632813 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2014 Frank Asseg
*
* 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.elasticstore.server.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JSR310Module;
import org.elasticsearch.client.Client;
import org.elasticstore.server.elasticsearch.ElasticSearchNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity;
@Configuration
@EnableAutoConfiguration
@EnableWebMvcSecurity
@ComponentScan(basePackages = {"org.elasticstore.server"})
public class ElasticstoreConfiguration {
@Autowired
public ElasticSearchNode elasticSearchNode;
@Bean
public Client elasticSearchClient() {
return elasticSearchNode.getClient();
}
@Bean
@Primary
public ObjectMapper objectMapper() {
final ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JSR310Module());
return mapper;
}
@Bean
public ElasticStoreSecurityConfigurer elasticStoreSecurityConfiguration() {
return new ElasticStoreSecurityConfigurer();
}
}
| true |
7950948557560b183e790dcd7ebe92f1834d9055 | Java | jjmnbv/shop | /shop-service/src/main/java/com/rt/shop/service/impl/EvaluateServiceImpl.java | UTF-8 | 449 | 1.523438 | 2 | [] | no_license | package com.rt.shop.service.impl;
import org.springframework.stereotype.Service;
import com.rt.shop.entity.Evaluate;
import com.rt.shop.mapper.EvaluateMapper;
import com.rt.shop.service.IEvaluateService;
import com.rt.shop.service.impl.support.BaseServiceImpl;
/**
*
* Evaluate 表数据服务层接口实现类
*
*/
@Service
public class EvaluateServiceImpl extends BaseServiceImpl<EvaluateMapper, Evaluate> implements IEvaluateService {
} | true |
9dc10700266b9da0b766c85edb5dc23976a2aa87 | Java | deltaena/MadGuidesApp | /app/src/main/java/com/example/madguidesapp/android/customViews/IconButton.java | UTF-8 | 1,941 | 2.296875 | 2 | [] | no_license | package com.example.madguidesapp.android.customViews;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.util.AttributeSet;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.example.madguidesapp.R;
import com.google.android.material.snackbar.Snackbar;
import java.util.ArrayList;
import java.util.List;
public class IconButton extends androidx.appcompat.widget.AppCompatImageView {
private ConnectivityManager connectivityManager;
private List<OnClickListener> listeners = new ArrayList<>();
public IconButton(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
int[] attributes = {
R.attr.performsAsync
};
TypedArray typedArray = context.obtainStyledAttributes(attrs, attributes);
boolean performsAsync = typedArray.getBoolean(0, false);
if(performsAsync) {
listeners.add(click -> {
this.setClickable(false);
});
}
this.setClickable(true);
this.setOnClickListener(click -> {
if(connectivityManager.getActiveNetwork() == null)
Snackbar.make(click.getRootView(), context.getString(R.string.operationDispatchDelayedCon), Snackbar.LENGTH_LONG).show();
listeners.forEach(listener -> listener.onClick(click));
});
}
public void addListener(@Nullable OnClickListener l) {
if(listeners.size() == 2){
listeners.remove(listeners.size()-1);
}
listeners.add(l);
}
public void enable(){
this.setClickable(true);
}
public boolean isEnabled(){
return this.isClickable();
}
}
| true |
db49af0d0913e84fdfbc45b140b846eab208195a | Java | leetompkins/Week7_CST100_Java_Exercises_Lee_Tompkins | /ReplaceWords.java | UTF-8 | 1,912 | 3.75 | 4 | [] | no_license |
/* Program: ReplaceWords
* File: ReplaceWords.java
* Summary: Exercise 12.27, A program that goes looks at all exercise files in a directory and pads the numbers with a 0 if the number is single digit
* For example, file: Exercise2_9 would become Exercise02_09
* Author: Lee Tompkins
* Date: August 8 2016
*
*/
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Scanner;
public class ReplaceWords {
public static void main(String[] args) throws IOException {
// Create array for files with .txt extenstions
ArrayList<File> txtFiles = new ArrayList<File>();
// Create console scanner
Scanner inputConsole = new Scanner(System.in);
// Request input
System.out.print("Enter in the Directory path to pad .txt file names. ");
// Save input
String inputPath = inputConsole.nextLine();
// Create file array
File[] folderFiles = new File(inputPath).listFiles();
for(int i = 0; i < folderFiles.length; i++) {
// add files with .txt extension
if (folderFiles[i].getName().endsWith(".txt")) {
txtFiles.add(folderFiles[i]);
}
}
// Go though files and replace names if parameters met
for (int i = 0; i < txtFiles.size(); i++) {
String fileName = txtFiles.get(i).getName();
String ints[] = fileName.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
if (ints[1].length() < 2) {
ints[1] = "0" + ints[1];
}
if (ints[3].length() < 2) {
ints[3] = "0" + ints[3];
}
// Replace the file name
String newfileName = ints[0] + ints[1] + ints[2] + ints[3] + ints[4];
Path newFilePath = Paths.get(txtFiles.get(i).getAbsolutePath());
try {
Files.move(newFilePath, newFilePath.resolveSibling(newfileName));
// Catch exception
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
| true |
32ac0cc0d09958bde7683464a61ed8fdc9731f86 | Java | Jackbin910/springDemo | /springDemo/src/main/java/com/yangbin1/spring/bean/annotation/controller/UserController.java | UTF-8 | 874 | 2.234375 | 2 | [] | no_license | /**
* @Title: UserController.java
* @Package com.yangbin1.spring.bean.annotation.controller
* @Description: TODO(用一句话描述该文件做什么)
* @author: yangbin1
* @date: Sep 22, 2018 10:57:28 PM
*/
package com.yangbin1.spring.bean.annotation.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import com.yangbin1.spring.bean.annotation.service.UserService;
/**
* @ClassName: UserController
* @Description:表现层
* @author: yangbin1
* @date: Sep 22, 2018 10:57:28 PM
*
*/
@Controller
public class UserController {
@Autowired
private UserService userService;
public void execute() {
System.out.println("UserController execute...");
userService.add();
}
}
| true |
918aa55ce5dd08feacef761d4bfc048626b25574 | Java | StephenImp/BigDataDemo | /hbase/src/main/java/com/cn/mapreduce/mr1/WriteFruitMRReducer.java | UTF-8 | 967 | 2.609375 | 3 | [] | no_license | package com.cn.mapreduce.mr1;
import java.io.IOException;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.mapreduce.TableReducer;
import org.apache.hadoop.io.NullWritable;
/**
* Created by MOZi on 2019/4/9.
*
* 用于将读取到的fruit表中的数据写入到fruit_mr表中
*
* valueout 指定类型为 Mutation
*
* Put是实现类之一,所以在Mapper端指定valueout 为 Put类型
*
* Put 存放的是 一个 rowKey 下的所有 cell
*/
public class WriteFruitMRReducer extends TableReducer<ImmutableBytesWritable, Put, NullWritable> {
@Override
protected void reduce(ImmutableBytesWritable key, Iterable<Put> values, Context context)
throws IOException, InterruptedException {
//读出来的每一行数据写入到fruit_mr表中
for(Put put: values){
context.write(NullWritable.get(), put);
}
}
}
| true |
73b7667e402d9554f444259da1217d63b8faf1be | Java | EdsionGeng/knowledge | /src/main/java/com/wsd/knowledge/entity/FileDetail.java | UTF-8 | 8,306 | 2.171875 | 2 | [] | no_license | package com.wsd.knowledge.entity;
import java.util.Comparator;
/**
* @Author EdsionGeng
* @Description 文件具体信息实体类
* @Date:10:56 2017/11/1
*/
//@Entity
public class FileDetail implements Comparable<FileDetail> {
// @Id
//@GeneratedValue
private int id;
// @Column(name = "departmentName", nullable = false, length = 32, columnDefinition = " '部门名字'")
private String departmentName;//上传部门
// @Column(name = "userId", nullable = false, columnDefinition = " '用户ID'")
private int userId;//上传用户ID
//文件种类 0 普通文件 1部门文件 2 公司文件
private int fileSpecies;
//@Column(name = "username", nullable = false, length = 32, columnDefinition = " '用户名字'")
private String username;//上传用户ID
//@Column(name = "fileNo", nullable = false, length = 32, columnDefinition = " '文件编号'")
private String fileNo;//文件编号
// @Column(name = "title", nullable = false, length = 96, columnDefinition = " '文件标题'")
private String title;//文件标题
// @Column(name = "fileStyle", nullable = false, length = 32, columnDefinition = " '文件类型'")
private String fileStyle;//文件类型
// @Column(name = "fileContent", nullable = false, length = 4896, columnDefinition = " '文件内容'")
private String fileContent;//文件内容
// @Column(name = "fileSize", nullable = false, length = 64, columnDefinition = " '文件大小'")
private String fileSize;//文件大小
// @Column(name = "fileUrl", length = 688, columnDefinition = " '附件URL'")
private String fileUrl;//附件URL
// @Column(name = "fileStyleId", nullable = false, columnDefinition = " '文件类型层级ID'")
private int fileStyleId;
// @Column(name = "photoUrl", nullable = false, length = 64, columnDefinition = " '封面图片URL'")
private String photoUrl;//封面图片URL
// @Column(name = "addFileTime", nullable = false, columnDefinition = " '添加文件时间 yyyy-MM-dd hh:mm格式'")
private String addFileTime;//添加文件时间
//@Column(name = "lookPcs", nullable = false, columnDefinition = " '文件查看次数'")
private int lookPcs;//文件查看次数
//@Column(name = "downloadPcs", nullable = false, columnDefinition = " '文件下载次数'")
private int downloadPcs;//文件下载次数
//@Column(name = "updatePcs", nullable = false, columnDefinition = " '文件修改次数'")
private int updatePcs;//文件下载次数
//@Column(name = "fileDisplay", columnDefinition = " '文件是否显示 0 不显示 1显示'")
private int fileDisplay;//文件是否显示 0 不显示 1显示
//附件描述
private String enclosureInfo;
//人员组别id
private int userGroupId;
//各公司Id
private String companyId;
public String getCompanyId() {
return companyId;
}
public void setCompanyId(String companyId) {
this.companyId = companyId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getFileStyle() {
return fileStyle;
}
public void setFileStyle(String fileStyle) {
this.fileStyle = fileStyle;
}
public String getFileContent() {
return fileContent;
}
public void setFileContent(String fileContent) {
this.fileContent = fileContent;
}
public String getFileUrl() {
return fileUrl;
}
public void setFileUrl(String fileUrl) {
this.fileUrl = fileUrl;
}
public String getPhotoUrl() {
return photoUrl;
}
public void setPhotoUrl(String photoUrl) {
this.photoUrl = photoUrl;
}
public String getFileSize() {
return fileSize;
}
public String getFileNo() {
return fileNo;
}
public void setFileNo(String fileNo) {
this.fileNo = fileNo;
}
public void setFileSize(String fileSize) {
this.fileSize = fileSize;
}
public int getFileStyleId() {
return fileStyleId;
}
public void setFileStyleId(int fileStyleId) {
this.fileStyleId = fileStyleId;
}
public int getUpdatePcs() {
return updatePcs;
}
public void setUpdatePcs(int updatePcs) {
this.updatePcs = updatePcs;
}
public int getFileDisplay() {
return fileDisplay;
}
public void setFileDisplay(int fileDisplay) {
this.fileDisplay = fileDisplay;
}
public String getAddFileTime() {
return addFileTime;
}
public void setAddFileTime(String addFileTime) {
this.addFileTime = addFileTime;
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
public int getLookPcs() {
return lookPcs;
}
public void setLookPcs(int lookPcs) {
this.lookPcs = lookPcs;
}
public int getDownloadPcs() {
return downloadPcs;
}
public void setDownloadPcs(int downloadPcs) {
this.downloadPcs = downloadPcs;
}
public String getEnclosureInfo() {
return enclosureInfo;
}
public void setEnclosureInfo(String enclosureInfo) {
this.enclosureInfo = enclosureInfo;
}
public int getFileSpecies() {
return fileSpecies;
}
public void setFileSpecies(int fileSpecies) {
this.fileSpecies = fileSpecies;
}
public int getUserGroupId() {
return userGroupId;
}
public void setUserGroupId(int userGroupId) {
this.userGroupId = userGroupId;
}
public FileDetail(String departmentName, String username, int userId, int fileStyleId, String fileNo, String title, String fileStyle, String fileContent, String fileUrl, String photoUrl, int lookPcs, int downloadPcs, int updatePcs, String fileSize, int fileDisplay, String enclosureInfo, String addFileTime, int fileSpecies, int userGroupId,String companyId) {
this.departmentName = departmentName;
this.username = username;
this.fileStyleId = fileStyleId;
this.userId = userId;
this.fileNo = fileNo;
this.title = title;
this.fileStyle = fileStyle;
this.fileContent = fileContent;
this.fileUrl = fileUrl;
this.photoUrl = photoUrl;
this.lookPcs = lookPcs;
this.downloadPcs = downloadPcs;
this.updatePcs = updatePcs;
this.fileSize = fileSize;
this.fileDisplay = fileDisplay;
this.enclosureInfo = enclosureInfo;
this.addFileTime = addFileTime;
this.fileSpecies = fileSpecies;
this.userGroupId = userGroupId;
this.companyId=companyId;
}
// f.id,f.departmentName,f.username,f.fileSize,f.fileNo,f.title,f.fileUrl,f.photoUrl,f.enclosureInfo,f.addFileTime
public FileDetail(int id, String departmentName, String username, String fileNo, String title, String fileSize, String fileUrl, String photoUrl, String addFileTime, String enclosureInfo) {
this.id = id;
this.departmentName = departmentName;
this.username = username;
this.fileNo = fileNo;
this.title = title;
this.fileSize = fileSize;
this.fileUrl = fileUrl;
this.photoUrl = photoUrl;
this.addFileTime = addFileTime;
this.enclosureInfo = enclosureInfo;
}
public FileDetail() {
}
@Override
public int compareTo(FileDetail o) {
//按创建时间排序
if (o.getAddFileTime().compareTo(this.getAddFileTime()) > 0) {
return 1;
}
if (o.getAddFileTime().compareTo(this.getAddFileTime()) < 0) {
return -1;
}
return 0;
}
}
| true |
6c730ee5fdb015fa2d7cd601d839e3e8ee93dee9 | Java | kandaozai/java_ssm_new | /RebateMall_SSM/src/com/zgx/web/PersonalController.java | UTF-8 | 9,195 | 1.960938 | 2 | [] | no_license | package com.zgx.web;
import java.io.IOException;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.sf.json.JSONSerializer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.druid.sql.visitor.functions.Now;
import com.zgx.po.Enrollmenttable;
import com.zgx.po.Signtable;
import com.zgx.po.Signuptable;
import com.zgx.po.Stotetable;
import com.zgx.service.ICompanyService;
import com.zgx.service.IEnrollmentService;
import com.zgx.service.ISignupService;
import com.zgx.service.IStoreService;
import com.zgx.service.IsignService;
import com.zgx.vo.JsonReturn;
import com.zgx.vo.publicArry;
/**
*
* 我的资料 基本信息
*
* @author 星月
*
*/
@Controller
@RequestMapping("/personalWeb")
public class PersonalController {
@Autowired
private ICompanyService companyService;//公司
@Autowired
private IEnrollmentService enrollmentService;// 投资登记表
@Autowired
private ISignupService signupService;//用户(登录)
@Autowired
private IStoreService wdhfJlService;//积分记录WdhfJlServiceImpl
@Autowired
private IsignService signservice;//签到
// //两个人登录时的限制
// public String xianzhe(HttpServletRequest req)
// throws ServletException, IOException {
// HttpSession session = req.getSession();
// String PD="";
// Signuptable tabel = (Signuptable) session.getAttribute("SESSION_USER");// 获取登录数据
//
// try{
//
// Signuptable chongxie=signupService.findByIdparmint(tabel.getSignupId());
// if(chongxie.getEdition() == tabel.getEdition()){}else{ PD="1";}
//
// }catch (Exception e) {
// PD="";
// }
// return PD;
//
// }
// if(xianzhe(req).equals("1")){
// req.getSession().removeAttribute("SESSION_USER");
// req.setAttribute("CDX", "1");
// return "/MainIndex";//首页
// }
//我的基本资料基本信息jsp
@RequestMapping("/wdzl")
public String wdzl(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
HttpSession session = req.getSession();
Signuptable tabel = (Signuptable) session.getAttribute("SESSION_USER");// 获取登录数据
String str11 ="";
String str22 ="";
try{str11 = tabel.getLiving().replace("A","---");//将Living中所有的A替换为空格
}catch (Exception e) {str11 ="";}
try{str22 = tabel.getHomeaddress().replace("A"," ---");//将Living中所有的A替换为空格
}catch (Exception e) {str22="";}
req.setAttribute("Livingreq", str11);
req.setAttribute("Homeaddressreq", str22);
//数据刷新的需要
Signuptable chongxie=signupService.findByIdparmint(tabel.getSignupId());
session.setAttribute("SESSION_USER", chongxie);
if(tabel != null){
Signtable signtable2=signservice.findByIdQDparmint(tabel.getSignid());//初步 签到查询
Date date=new Date();
SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
String str=dateFormat.format(date);//当前时间
String str1=dateFormat.format(signtable2.getSigntime());//查询出的时间 oooo
if(str1.equals(str)){//已签到
req.setAttribute("qiandao", 1);
}
//投资平台数量 获取conpanytable的总行数,把总行数绑定到JSP投资平台数量中
Integer conpanytable = companyService.getTotalRow(" 1=1 ");//count 改为 1+1
req.setAttribute("conpanytable", conpanytable);
//总资产 投资平台总额 + 返利累计收益 ???? 写下面的
String total = enrollmentService.findByTotal();
if(total == null){total = "0" ;}
req.setAttribute("total", total);
//(自身的)投资总额
String lump = enrollmentService.findByLump(tabel.getSignupId());
if(lump == null){
lump = "0" ;
}
req.setAttribute("lump", lump);
//返利累计收益 没有单个乘 统一乘以 4.5%
String sum = enrollmentService.findBySum(tabel.getSignupId());
if(sum == null){
sum = "0" ;
}
req.setAttribute("sum", sum);
//用户注册信息
req.setAttribute("signuptable", chongxie);
try{
req.setAttribute("SignUpIdCS", tabel.getSignupId());
req.setAttribute("SignUpNameCS", tabel.getSignupname());
req.setAttribute("HeadportraitCS", tabel.getHeadportrait());
req.setAttribute("PhonenumberCS", tabel.getPhonenumber());//手机号码
req.setAttribute("IdnumberCS", tabel.getIdnumber());//身份证
req.setAttribute("BankcardCS", tabel.getBankcard());//银行卡
req.setAttribute("MailboxCS", tabel.getMailbox());//邮箱
req.setAttribute("RebateFreezeCS", tabel.getRebatefreeze());// 返利冻结
req.setAttribute("TXFreezeCS", tabel.getTxfreeze());// 提现冻结
req.setAttribute("SumCS", tabel.getSum());//可用金额
Stotetable wdjfjlb = wdhfJlService.findById(tabel.getSignid());
req.setAttribute("wdjfjlb", wdjfjlb);
}catch (Exception e) {
}
//总资产 这个
int intlump=0;
try{
intlump=Integer.parseInt(lump);// (自身的)投资总额
}catch (Exception e) {
intlump=0;
}
int intSum=tabel.getSum();//可用金额
int intRebatefreeze=tabel.getRebatefreeze();//冻结金额
int intTxfreeze=tabel.getTxfreeze();//现提金额
req.setAttribute("zong", intlump+intSum+intRebatefreeze+intTxfreeze);
// 跳转到我的账户
return "/Personal";
}else{
return "redirect:/mainsy/MainIndex.do";//重定向首页
}
}
@RequestMapping("/PerInvestment")
public String PerInvestment(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
return "/PerInvestment";
}
//统计图跳转
@RequestMapping("/statisticaljt")
public String statisticaljt(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
Signuptable tabel = (Signuptable) session.getAttribute("SESSION_USER");// 获取登录数据
try{
request.setAttribute("SignUpIdCS", tabel.getSignupId());
request.setAttribute("SignUpNameCS", tabel.getSignupname());
request.setAttribute("HeadportraitCS", tabel.getHeadportrait());
}catch (Exception e) {
}
SimpleDateFormat sy=new SimpleDateFormat("yyyy");
String yesenan=sy.format(new Date());//2019
request.setAttribute("yesenna", yesenan);
return "/StatisticalChart";
}
/**
* Sting转java.sql.Date
* @param 返回java.sql.Date格式的
* */
public static java.sql.Date strToDate(String strDate) {
String str = strDate;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date d = null;
try {
d = format.parse(str);
} catch (Exception e) {
e.printStackTrace();
}
java.sql.Date date = new java.sql.Date(d.getTime());
return date;
}
//1至12个月的统计投资账单
@ResponseBody
@RequestMapping("/tzzd")
public Object tzzd(HttpServletRequest req, HttpServletResponse resp){
HttpSession session = req.getSession();
Signuptable tabel = (Signuptable) session.getAttribute("SESSION_USER");// 获取登录数据
//获取当前年的每个月(设置起始年)投资金额 和收益金额总和
publicArry jr =new publicArry();//定一个2个数组的vo 发送过去
SimpleDateFormat sy=new SimpleDateFormat("yyyy");
String yesenan=sy.format(new Date());//2019
BigDecimal[] intarger=new BigDecimal[12];//投资金额数组
BigDecimal[] intargertow=new BigDecimal[12];//收益金额数组
BigDecimal caxun=new BigDecimal("0");
BigDecimal caxuntow=new BigDecimal("0");
for(int i=1;i<13;i++){
String pingjie="-0"+i+"-01";
java.sql.Date shijian=strToDate(yesenan+pingjie);//"2019-01-01"
try{
caxun=enrollmentService.findByIdAndTime(shijian,tabel.getSignupId());//(2019-01-01(sql时间)、2)
caxuntow=enrollmentService.findByIdAndTimeSY(shijian,tabel.getSignupId());//审核成功的就算入
}catch (Exception e) {
caxun=new BigDecimal("0");
caxuntow=new BigDecimal("0");
}
if(caxun==null){
caxun=new BigDecimal("0");
}
if(caxuntow==null){
caxuntow=new BigDecimal("0");
}
intarger[i-1]=caxun;
intargertow[i-1]=caxuntow;
}
jr.setArgerint(intargertow);
jr.setArgerinttwo(intarger);
return JSONSerializer.toJSON(jr);//需要引用架包文件lib里
}
}
| true |
47f907b9014886822e7a8257b26972f188dd37b8 | Java | percussion/percussioncms | /modules/perc-toolkit/src/main/java/com/percussion/pso/restservice/model/FolderInfo.java | UTF-8 | 1,771 | 1.773438 | 2 | [
"LicenseRef-scancode-dco-1.1",
"Apache-2.0",
"OFL-1.1",
"LGPL-2.0-or-later"
] | permissive | /*
* Copyright 1999-2023 Percussion Software, 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.percussion.pso.restservice.model;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;
@XmlRootElement
public class FolderInfo {
private FolderAcl folderAcl;
private String pubFileName;
private String globalTemplate;
List<ItemRef> folderItems;
@XmlElementWrapper(name="Contents")
@XmlElement(name="Item")
public List<ItemRef> getFolderItems() {
return folderItems;
}
public void setFolderItems(List<ItemRef> folderItems) {
this.folderItems = folderItems;
}
public void setFolderAcl(FolderAcl folderAcl) {
this.folderAcl = folderAcl;
}
@XmlElement
public FolderAcl getFolderAcl() {
return folderAcl;
}
public void setPubFileName(String pubFileName) {
this.pubFileName = pubFileName;
}
@XmlAttribute
public String getPubFileName() {
return pubFileName;
}
public void setGlobalTemplate(String globalTemplate) {
this.globalTemplate = globalTemplate;
}
@XmlAttribute
public String getGlobalTemplate() {
return globalTemplate;
}
}
| true |
f805d667796e82fdfa07503f69e4ddd428cfee22 | Java | Yuta2049/EPAM-Final-project-OnlineStore | /src/main/java/com/epam/training/onlineStore/dto/impl/ProductDAOImpl.java | UTF-8 | 1,905 | 2.359375 | 2 | [] | no_license | package com.epam.training.onlineStore.dto.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import com.epam.training.onlineStore.dto.ProductDAO;
import com.epam.training.onlineStore.dto.mapper.ProductMapper;
import com.epam.training.onlineStore.model.Product;
@Repository
public class ProductDAOImpl implements ProductDAO {
private final JdbcTemplate jdbcTemplate;
@Autowired
public ProductDAOImpl(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
public List<Product> getAll() {
return this.jdbcTemplate.query("SELECT * FROM product", new ProductMapper());
}
@Override
public Product findById(long id) {
return this.jdbcTemplate.queryForObject("SELECT * FROM product WHERE id = ?",
new Object[]{id}, new ProductMapper());
}
@Override
public long add(Product product) {
return this.jdbcTemplate.update("INSERT INTO PRODUCT (name, price, description) VALUES"
+ "(?,?,?)"
, product.getName()
, product.getPrice()
, product.getDescription());
}
@Override
public long edit(Product product) {
return this.jdbcTemplate.update("UPDATE PRODUCT SET name = ?, price = ?, description = ? WHERE id = 2"
, product.getName()
, product.getPrice()
, product.getDescription());
//, product.getId());
// return getJdbcTemplate().update(
// "UPDATE "
// + getTable()
// + " SET title = ?, idAuthor = ?, idGenre = ?"
// + getWhereId()
// , entity.getTitle()
// , entity.getAuthor().getId()
// , entity.getGenre().getId()
// , id);
}
}
| true |
3956358bbca97268202b61ce3d787fde68f587de | Java | D1987/CutUrl | /src/main/java/classes/DBConnect.java | UTF-8 | 912 | 2.78125 | 3 | [] | no_license | package classes;
import java.sql.*;
import java.util.ResourceBundle;
/*class dlya soedinenniya s bd*/
public class DBConnect
{
synchronized public Connection getConnection() throws SQLException {
ResourceBundle resource = ResourceBundle.getBundle("database");
String host = resource.getString("HOST");
String driver = resource.getString("DRIVER");
String user = resource.getString("USERNAME");
String pass = resource.getString("PASSWORD");
try {
Class.forName(driver).newInstance();
} catch (ClassNotFoundException e) {
throw new SQLException("Драйвер не загружен!");
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return DriverManager.getConnection(host, user, pass);
}
}
| true |
b24559819fef72d9d5ae00280d079b54a280045e | Java | sridharanselvaraj/JavaOnly | /DataDrivenFramework/src/test/java/com/sri/listeners/CustomListeners.java | UTF-8 | 2,040 | 2.015625 | 2 | [] | no_license | package com.sri.listeners;
import com.relevantcodes.extentreports.LogStatus;
import com.sri.base.TestBase;
import com.sri.utils.TestUtil;
import org.testng.*;
import java.io.IOException;
public class CustomListeners extends TestBase implements ITestListener {
@Override
public void onTestStart(ITestResult iTestResult) {
test=reports.startTest(iTestResult.getName().toUpperCase());
//runmodes -Y
}
@Override
public void onTestSuccess(ITestResult iTestResult) {
test.log(LogStatus.PASS,iTestResult.getName().toUpperCase()+" PASS");
reports.endTest(test);
reports.flush();
}
@Override
public void onTestFailure(ITestResult iTestResult) {
System.setProperty("org.uncommons.reportng.escape-output", "false");
try {
TestUtil.captureScreenshot();
} catch (IOException e) {
e.printStackTrace();
}
test.log(LogStatus.FAIL,iTestResult.getName().toUpperCase()+" Failed with exception :"+iTestResult.getThrowable());
// test.log(LogStatus.FAIL,test.addScreenCapture(TestUtil.screenshotName));
Reporter.log("Click to see Screenshot");
Reporter.log("<a target=\"_blank\" href="+TestUtil.screenshotName+">ScreenShot</a>");
Reporter.log("<br>");
Reporter.log("<br>");
Reporter.log("<a target=\"_blank\" href="+TestUtil.screenshotName+"><img src="+TestUtil.screenshotName+" height=200 width=200></img></a>");
reports.endTest(test);
reports.flush();
}
@Override
public void onTestSkipped(ITestResult iTestResult) {
test.log(LogStatus.SKIP,iTestResult.getName().toUpperCase()+" Skipped the runner test ");
reports.endTest(test);
reports.flush();
}
@Override
public void onTestFailedButWithinSuccessPercentage(ITestResult iTestResult) {
}
@Override
public void onStart(ITestContext iTestContext) {
}
@Override
public void onFinish(ITestContext iTestContext) {
}
}
| true |
dc60fbd6d7094256b0db7d93492d858d80296f82 | Java | jackbwaite/Jack-s-Projects | /Music/test/TransposeTester.java | UTF-8 | 1,615 | 2.90625 | 3 | [] | no_license | import org.junit.Test;
import org.junit.jupiter.api.Assertions;
public class TransposeTester {
@Test
public void testNote() {
Note.setNumHalfSteps(3);
Note note = new Note("a");
note.transpose();
Assertions.assertEquals(note.getNote(), "c");
}
@Test
public void testOneVoice() {
Parser p = new Parser(new Input(getClass().getResourceAsStream("/correctly_transposed_2steps.gmn")));
p.printScore();
Note.setNumHalfSteps(2);
Parser p2 = new Parser(new Input(getClass().getResourceAsStream("/one_voice_only_notes.gmn")));
p2.printScore();
Assertions.assertEquals(p.getFile(), p2.getFile());
}
@Test
public void testMozart() {
Note.setNumHalfSteps(0);
Parser p = new Parser(new Input(getClass().getResourceAsStream("/correctly_transposed_mozart_-4steps.gmn")));
p.printScore();
Note.setNumHalfSteps(-4);
Parser p2 = new Parser(new Input(getClass().getResourceAsStream("/full_simple_notes.gmn")));
p2.printScore();
Assertions.assertEquals(p2.getFile(), p.getFile());
}
/**
* Note that this test method will fill a desired file with the transpose sheet music, so you'll have
* to fill in your own file path.
*/
@Test
public void fillScore() {
Note.setNumHalfSteps(2);
Parser p = new Parser("C:\\Users\\jackb\\IdeaProjects\\Music\\resources\\bach.gmn",
"C:\\Users\\jackb\\IdeaProjects\\Music\\resources\\fill_with_transposed_mozart_-4steps.gmn");
p.printScore();
}
}
| true |
c155fb13caf8624e4fe4854a619ecab3b754922f | Java | Relucent/yyl_leetcode | /src/main/java/yyl/leetcode/bean/TreeNode.java | UTF-8 | 5,810 | 3.71875 | 4 | [
"Apache-2.0"
] | permissive | package yyl.leetcode.bean;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Queue;
import java.util.function.Consumer;
/**
* Definition for a binary tree node.
*/
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) {
val = x;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((left == null) ? 0 : left.hashCode());
result = prime * result + ((right == null) ? 0 : right.hashCode());
result = prime * result + val;
return result;
}
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (object == null || getClass() != object.getClass()) {
return false;
}
TreeNode other = (TreeNode) object;
if (left == null) {
if (other.left != null) {
return false;
}
} else if (!left.equals(other.left)) {
return false;
}
if (right == null) {
if (other.right != null) {
return false;
}
} else if (!right.equals(other.right)) {
return false;
}
return val == other.val;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
Deque<TreeNode> queue = new ArrayDeque<>();
queue.add(this);
int level = 1;
builder.append("[");
TreeNode dummyNull = new TreeNode(Integer.MIN_VALUE);
int nullTails = 0;
while (!queue.isEmpty()) {
if (level > 5) {
nullTails = 0;
builder.append("...,");
break;
}
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
if (node == dummyNull) {
nullTails++;
builder.append("null,");
} else {
nullTails = 0;
builder.append(node.val).append(",");
TreeNode left = node.left;
TreeNode right = node.right;
queue.add(left == null ? dummyNull : left);
queue.add(right == null ? dummyNull : right);
}
}
level++;
}
if (nullTails > 0) {
// "null,".length() = 5
builder.setLength(builder.length() - 5 * nullTails);
}
builder.deleteCharAt(builder.length() - 1);
builder.append("]");
return builder.toString();
}
/**
* 创建二叉树
* @param values 二叉树节点数据
* @return 二叉树跟节点
*/
public static TreeNode create(String input) {
// 处理"[","]"
input = input.trim();
input = input.substring(1, input.length() - 1);
if (input.length() == 0) {
return null;
}
// 分割字符串,获取根结点
String[] parts = input.split(",");
String item = parts[0];
TreeNode root = new TreeNode(Integer.parseInt(item));
// 将根结点加入到双链表中
Queue<TreeNode> nodeQueue = new ArrayDeque<>();
nodeQueue.add(root);
int index = 1;
// 遍历双链表
while (!nodeQueue.isEmpty()) {
// 获取双链表的头结点作为当前结点
TreeNode node = nodeQueue.poll();
// 判断左子节点是否为空
// 判断是否还有结点可以构建的左子节点
if (index == parts.length) {
break;
}
{
String part = parts[index++];
if (!"null".equals(part)) {
nodeQueue.add(node.left = new TreeNode(Integer.parseInt(part)));
}
}
// 判断右子节点是否为空
// 判断是否还有结点可以构建的右子节点
if (index == parts.length) {
break;
}
{
String part = parts[index++];
if (!"null".equals(part)) {
nodeQueue.add(node.right = new TreeNode(Integer.parseInt(part)));
}
}
}
return root;
}
/**
* 前序遍历,根左右(DLR)
* @param root 根节点
* @param action 回调动作
*/
public static void preorderTraversal(TreeNode root, Consumer<TreeNode> action) {
if (root != null) {
action.accept(root);
preorderTraversal(root.left, action);
preorderTraversal(root.right, action);
}
}
/**
* 中序遍历,左根右(LDR)
* @param root 根节点
* @param action 回调动作
*/
public static void inorderTraversal(TreeNode root, Consumer<TreeNode> action) {
if (root != null) {
preorderTraversal(root.left, action);
action.accept(root);
preorderTraversal(root.right, action);
}
}
/**
* 后序遍历,左右根(LRD)
* @param root 根节点
* @param action 回调动作
*/
public static void postorderTraversal(TreeNode root, Consumer<TreeNode> action) {
if (root != null) {
preorderTraversal(root.left, action);
preorderTraversal(root.right, action);
action.accept(root);
}
}
}
| true |
197f31bbbd18a2bc0d04bebc4aa221fd92bdfdd6 | Java | tvtu2105/Mobile_Android_Travel_Assistant | /Source/TravelAsisstant/app/src/main/java/com/ygaps/travelapp/Component/LogInClient.java | UTF-8 | 278 | 1.96875 | 2 | [] | no_license | package com.ygaps.travelapp.Component;
public class LogInClient
{
private String emailPhone;
private String password;
public LogInClient(String emailPhone, String password)
{
this.emailPhone = emailPhone;
this.password = password;
}
}
| true |
e887ac784d1f00db8da48ec2cbfc3e440e33710d | Java | mertdumanli/Java-Spring-MVC-Rest-Company-All-Project | /src/main/java/com/works/repositories/_jpa/LikeRepository.java | UTF-8 | 1,359 | 1.875 | 2 | [] | no_license | package com.works.repositories._jpa;
import com.works.entities.LikeManagement;
import com.works.entities.projections.LikeInfo;
import com.works.entities.projections.LikeInfoAccordingToCustomer;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import javax.transaction.Transactional;
import java.util.List;
import java.util.Optional;
@Transactional
public interface LikeRepository extends JpaRepository<LikeManagement, Integer> {
@Query(value = "select sum(score) as totalScore, product_id as productID from like_management group by product_id", nativeQuery = true)
List<LikeInfo> findAllLikes();
@Query(value = "SELECT\n" +
"\tcustomer.id AS cid,\n" +
"\tCONCAT( customer.NAME, \" \", customer.surname ) AS cname,\n" +
"\tscore,\n" +
"\tproduct_id as pid\n" +
"FROM\n" +
"\tlike_management\n" +
"\tINNER JOIN `user` AS customer \n" +
"WHERE\n" +
"\tcustomer.id = like_management.customer_id", nativeQuery = true)
List<LikeInfoAccordingToCustomer> findAllLikesAccordingToCustomer();
Optional<LikeManagement> findByCustomer_IdEqualsAndProduct_IdEquals(Integer id, Integer id1);
}
| true |
eaff41bea6a36b40c977d98b09a55e399b4eabb5 | Java | yiweijian/collaboration-markdown-editor | /src/main/java/Preview.java | UTF-8 | 1,104 | 2.296875 | 2 | [] | no_license | import com.vladsch.flexmark.Extension;
import com.vladsch.flexmark.ast.Node;
import com.vladsch.flexmark.ext.tables.TablesExtension;
import com.vladsch.flexmark.html.HtmlRenderer;
import com.vladsch.flexmark.parser.Parser;
import com.vladsch.flexmark.parser.ParserEmulationProfile;
import com.vladsch.flexmark.util.options.MutableDataSet;
import java.util.Arrays;
public class Preview implements Runnable{
public void run(){
String text = GUI.editorPane.getText();
// GUI.editorPane2.setContentType("text/html");
MutableDataSet options = new MutableDataSet();
options.setFrom(ParserEmulationProfile.MARKDOWN);
options.set(Parser.EXTENSIONS, Arrays.asList(new Extension[]{TablesExtension.create()}));
Parser parser = Parser.builder(options).build();
HtmlRenderer renderer = HtmlRenderer.builder(options).build();
// System.out.println(GUI.editorPane2.getText());
Node document = parser.parse(text);
String html = renderer.render(document);
System.out.println(html);
GUI.editorPane2.setText(html);
}
}
| true |
ca27c91d80abbc4986e37291abf3e8211e4602eb | Java | cristian-ruiz-s-ing/Lab08CVDS | /src/main/java/edu/eci/cvds/test/ServiciosAlquilerTest.java | UTF-8 | 6,039 | 2.4375 | 2 | [] | no_license | package edu.eci.cvds.test;
import static org.junit.Assert.assertEquals;
import java.util.List;
import java.sql.Date;
import com.google.inject.Inject;
import edu.eci.cvds.samples.entities.Cliente;
import edu.eci.cvds.samples.entities.Item;
import edu.eci.cvds.samples.entities.TipoItem;
import edu.eci.cvds.samples.services.ExcepcionServiciosAlquiler;
import edu.eci.cvds.samples.services.ServiciosAlquiler;
import edu.eci.cvds.samples.services.ServiciosAlquilerFactory;
import org.apache.ibatis.session.SqlSession;
import org.junit.Before;
import org.junit.Test;
import org.junit.Assert;
public class ServiciosAlquilerTest {
@Inject
private SqlSession sqlSession;
ServiciosAlquiler serviciosAlquiler;
public ServiciosAlquilerTest() {
serviciosAlquiler = ServiciosAlquilerFactory.getInstance().getServiciosAlquilerTesting();
}
@Before
public void setUp() {
}
@Test
public void validRegistrarCliente() {
try {
Cliente cliente = new Cliente("Lola", 3158119, "311234567", "calle 200", "loop@gmail.com", false, null);
serviciosAlquiler.registrarCliente(cliente);
Cliente clienteCheck = serviciosAlquiler.consultarCliente(cliente.getDocumento());
assertEquals(cliente.getDocumento(), clienteCheck.getDocumento());
} catch (ExcepcionServiciosAlquiler e) {
Assert.assertFalse(false);
}
}
@Test
public void invalidRegistrarCliente() {
boolean r = false;
try {
Cliente cliente = new Cliente("Lola", 3158200, "311234567", "calle 200", "looping@gmail.com", false, null);
serviciosAlquiler.registrarCliente(cliente);
Cliente cliente2 = new Cliente("pepe", 3158200, "311234567", "calle 201", "pol@gmail.com", false, null);
serviciosAlquiler.registrarCliente(cliente2);
} catch (ExcepcionServiciosAlquiler e) {
r = true;
}
Assert.assertTrue(r);
}
@Test
public void validConsultarCliente() {
try {
Cliente cliente = serviciosAlquiler.consultarCliente(2158119);
assertEquals(2158119, cliente.getDocumento());
} catch (ExcepcionServiciosAlquiler e) {
Assert.assertFalse(false);
}
}
@Test
public void invalidConsultarCliente() {
try {
Cliente cliente = serviciosAlquiler.consultarCliente(2158110);
Assert.assertNull(cliente);
} catch (ExcepcionServiciosAlquiler e) {
Assert.assertFalse(false);
}
}
@Test
public void validConsultarClientes() {
try {
List<Cliente> clientes = serviciosAlquiler.consultarClientes();
Assert.assertTrue(clientes.size() > 0);
} catch (ExcepcionServiciosAlquiler e) {
Assert.assertFalse(false);
}
}
@Test
public void validRegistrarItem() {
try {
Date fecha2 = new Date(120, 11, 25);
TipoItem tipo2 = new TipoItem(91, "Belico");
Item item = new Item(tipo2, 14 , "The pacific" , "serie", fecha2, 140, "dvd", "Belico");
serviciosAlquiler.registrarItem(item);
Item itemCheck = serviciosAlquiler.consultarItem(item.getId());
assertEquals(item.getId(), itemCheck.getId());
} catch (ExcepcionServiciosAlquiler e) {
Assert.assertFalse(false);
}
}
@Test
public void invalidRegistrarItem() {
boolean r = false;
try {
Date fecha2 = new Date(120, 11, 25);
TipoItem tipo2 = new TipoItem(91, "Belico");
Item item = new Item(tipo2, 15 , "The pacific" , "serie", fecha2, 140, "dvd", "Belico");
serviciosAlquiler.registrarItem(item);
Item item2 = new Item(tipo2, 15 , "Ocean" , "serie", fecha2, 140, "dvd", "Belico");
serviciosAlquiler.registrarItem(item2);
} catch (ExcepcionServiciosAlquiler e) {
r = true;
}
Assert.assertTrue(r);
}
@Test
public void validConsultarItem() {
try {
Item item = serviciosAlquiler.consultarItem(93);
assertEquals(93, item.getId());
} catch (ExcepcionServiciosAlquiler e) {
Assert.assertFalse(false);
}
}
@Test
public void invalidConsultarItem() {
try {
Item item = serviciosAlquiler.consultarItem(0);
Assert.assertNull(item);
} catch (ExcepcionServiciosAlquiler e) {
Assert.assertFalse(false);
}
}
@Test
public void validConsultarItemsDisponibles() {
try {
List<Item> items = serviciosAlquiler.consultarItemsDisponibles();
Assert.assertTrue(items.size() > 0);
} catch (ExcepcionServiciosAlquiler e) {
Assert.assertFalse(false);
}
}
@Test
public void validVetarCliente() {
try {
serviciosAlquiler.vetarCliente(2158119, true);
Cliente cliente = serviciosAlquiler.consultarCliente(2158119);
assertEquals(true, cliente.isVetado());
} catch (ExcepcionServiciosAlquiler e) {
Assert.assertFalse(false);
}
}
@Test
public void validRegistrarAlquiler() {
try {
//Se busca el item disponible
Date fecharegistro = java.sql.Date.valueOf("2020-10-10");
List<Item> itDis = serviciosAlquiler.consultarItemsDisponibles();
Item it = itDis.get(0);
//Se alquila
Cliente cl = serviciosAlquiler.consultarCliente(2158119);
serviciosAlquiler.registrarAlquilerCliente(fecharegistro, cl.getDocumento(), it, 10);
} catch (ExcepcionServiciosAlquiler e) {
Assert.assertFalse(false);
}
}
@Test
public void registrarAlquilerSinItem() {
boolean r = false;
try {
//Crea item
Date fecharegistro = java.sql.Date.valueOf("2020-10-11");
Date fecha = java.sql.Date.valueOf("2020-10-10");
TipoItem tipo2 = new TipoItem(91, "Belico");
Item item = new Item(tipo2, 16 , "pororo" , "serie", fecha, 140, "dvd", "Belico");
//Intenta hacer alquiler
serviciosAlquiler.registrarAlquilerCliente(fecharegistro, 2158119, item, 15);
} catch ( ExcepcionServiciosAlquiler e) {
r = true;
}
Assert.assertTrue(r);
}
} | true |
9123c614c348190a0e8825b55f7b7f84c0ea66df | Java | nguyenxuankiet262/PhucLongWebserviceServer | /app/src/main/java/com/dhkhtn/xk/phuclongserverappver2/Adapter/UserAdapter.java | UTF-8 | 4,069 | 2.234375 | 2 | [] | no_license | package com.dhkhtn.xk.phuclongserverappver2.Adapter;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.Toast;
import com.dhkhtn.xk.phuclongserverappver2.Model.User;
import com.dhkhtn.xk.phuclongserverappver2.R;
import com.dhkhtn.xk.phuclongserverappver2.Retrofit.IPhucLongAPI;
import com.dhkhtn.xk.phuclongserverappver2.Utils.Common;
import com.dhkhtn.xk.phuclongserverappver2.ViewHolder.UserViewHolder;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class UserAdapter extends RecyclerView.Adapter<UserViewHolder> {
Context context;
List<User> userList;
IPhucLongAPI mService;
public UserAdapter(Context context, List<User> userList) {
this.context = context;
this.userList = userList;
}
@NonNull
@Override
public UserViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemview = LayoutInflater.from(context).inflate(R.layout.item_user_layout,parent,false);
return new UserViewHolder(itemview);
}
@Override
public void onBindViewHolder(@NonNull final UserViewHolder holder, final int position) {
mService = Common.getAPI();
holder.number_user.setText(userList.get(position).getPhone());
if(!TextUtils.isEmpty(userList.get(position).getAddress())){
holder.name_user.setText(userList.get(position).getName());
holder.address_user.setText(userList.get(position).getAddress());
}
if(userList.get(position).getActive() == 1){
holder.active_switch.setChecked(true);
}
else{
holder.active_switch.setChecked(false);
}
holder.active_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(Common.isConnectedToInternet(context)){
if(isChecked){
mService.updateActiveUser(userList.get(position).getPhone(), 1)
.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
Toast.makeText(context, "Tài khoản " + userList.get(position).getPhone() + " đã mở khóa!", Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(Call<String> call, Throwable t) {
}
});
}else{
mService.updateActiveUser(userList.get(position).getPhone(), 0)
.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
Toast.makeText(context, "Tài khoản " + userList.get(position).getPhone() + " đã bị khóa!", Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(Call<String> call, Throwable t) {
}
});
}
}
else{
Toast.makeText(context,"Kiểm tra kết nối mạng!", Toast.LENGTH_SHORT).show();
}
}
});
}
@Override
public int getItemCount() {
return userList.size();
}
}
| true |
21973e65cf588c798bf3613f2857929d0532f73a | Java | bppan/spider | /src/main/java/studio/geek/shixiseng/ShixisengHttpClient.java | UTF-8 | 7,287 | 2.234375 | 2 | [] | no_license | package studio.geek.shixiseng;
import org.apache.log4j.Logger;
import studio.geek.core.AbstractHttpClient;
import studio.geek.core.SimpleThreadPoolExecutor;
import studio.geek.core.ThreadPoolMonitor;
import studio.geek.shixiseng.task.JobDetailListPageTask;
import studio.geek.shixiseng.task.JobDetailPageTask;
import studio.geek.util.SimpleLogger;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Created by Liuqi
* Date: 2017/4/8.
*/
public class ShixisengHttpClient extends AbstractHttpClient{
private static Logger logger = SimpleLogger.getSimpleLogger(ShixisengHttpClient.class);
private volatile static ShixisengHttpClient shixisengHttpClient;
/**
* 统计用户数量
*/
public static AtomicInteger parseJobCount = new AtomicInteger(0);
private static long startTime = System.currentTimeMillis();
public static volatile boolean isStop = false;//是否关闭的标志位
public ShixisengHttpClient getInstance() {
if (shixisengHttpClient == null) {
synchronized (ShixisengHttpClient.class) {
if (shixisengHttpClient == null) {
shixisengHttpClient = new ShixisengHttpClient();
}
}
}
return shixisengHttpClient;
}
private ShixisengHttpClient() {
}
/**
* 列表页下载多线程
*/
ThreadPoolExecutor listPageThreadPool;
/**
* 详情页下载线程池
*/
private ThreadPoolExecutor detailPageThreadPool;
/**
* 详情列表页下载线程池
*/
private ThreadPoolExecutor detailListPageThreadPool;
private void intiThreadPool() {
detailPageThreadPool = new SimpleThreadPoolExecutor(10,
10,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
"detailPageThreadPool");
listPageThreadPool = new SimpleThreadPoolExecutor(50, 80,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(5000),
new ThreadPoolExecutor.DiscardPolicy(), "listPageThreadPool");
new Thread(new ThreadPoolMonitor(detailPageThreadPool, "DetailPageDownloadThreadPool")).start();
new Thread(new ThreadPoolMonitor(listPageThreadPool, "ListPageDownloadThreadPool")).start();
new Thread(new ThreadPoolMonitor(listPageThreadPool, "ListPageDownloadThreadPool")).start();
detailListPageThreadPool = new SimpleThreadPoolExecutor(20,
30,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(2000),
new ThreadPoolExecutor.DiscardPolicy(),
"detailListPageThreadPool");
new Thread(new ThreadPoolMonitor(detailListPageThreadPool, "DetailListPageThreadPool")).start();
}
public void startCrawl(String url) {
detailPageThreadPool.execute(new JobDetailPageTask(url));
manageHttpClient();
}
/**
* 管理客户端
* 关闭整个爬虫
*/
public void manageHttpClient() {
while (true) {
/**
* 下载网页数
*/
long downloadPageCount = detailPageThreadPool.getTaskCount();
/* if (downloadPageCount >= Config.downloadPageCount &&
! ZhiHuHttpClient.getInstance().getDetailPageThreadPool().isShutdown()) {
isStop = true;
*
* shutdown 下载网页线程池
ZhiHuHttpClient.getInstance().getDetailPageThreadPool().shutdown();
}
if(ZhiHuHttpClient.getInstance().getDetailPageThreadPool().isTerminated() &&
!ZhiHuHttpClient.getInstance().getListPageThreadPool().isShutdown()){
*
* 下载网页线程池关闭后,再关闭解析网页线程池
ZhiHuHttpClient.getInstance().getListPageThreadPool().shutdown();
}
if(ZhiHuHttpClient.getInstance().getListPageThreadPool().isTerminated()){
*
* 关闭线程池Monitor
ThreadPoolMonitor.isStopMonitor = true;
*
* 关闭ProxyHttpClient客户端
ProxyHttpClient.getInstance().getProxyTestThreadExecutor().shutdownNow();
ProxyHttpClient.getInstance().getProxyDownloadThreadExecutor().shutdownNow();
logger.info("--------------爬取结果--------------");
logger.info("获取用户数:" + parseUserCount.get());
break;
}*/
/**
* 待补充
*/
if (downloadPageCount >= 10 &&
!detailListPageThreadPool.isShutdown()) {
isStop = true;
detailListPageThreadPool.shutdown();
}
if(detailListPageThreadPool.isShutdown()){
//关闭数据库连接
Map<Thread, Connection> map = JobDetailListPageTask.getConnectionMap();
for(Connection cn : map.values()){
try {
if (cn != null && !cn.isClosed()){
cn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
break;
}
double costTime = (System.currentTimeMillis() - startTime) / 1000.0;//单位s
logger.debug("抓取速率:" + parseJobCount.get() / costTime + "个/s");
// logger.info("downloadFailureProxyPageSet size:" + ProxyHttpClient.downloadFailureProxyPageSet.size());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// System.exit(0);
}
public ThreadPoolExecutor getDetailPageThreadPool() {
return detailPageThreadPool;
}
public ThreadPoolExecutor getListPageThreadPool() {
return listPageThreadPool;
}
public ThreadPoolExecutor getDetailListPageThreadPool() {
return detailListPageThreadPool;
}
/*public void doTask() throws IOException {
String path = "http://www.shixiseng.com/interns?k=java&p=1";
//get方法设置参数要?号
StringBuilder sb = new StringBuilder(path);
// sb.append("?");
//sb.append("username=").append(URLEncoder.encode("HttpClientGET","utf-8"));
HttpClient httpClient = new DefaultHttpClient();//浏览器
//2指定请求方式
HttpGet httpGet = new HttpGet(sb.toString());
//3.执行请求
HttpResponse httpResponse = httpClient.execute(httpGet);
//4 判断请求是否成功
int status = httpResponse.getStatusLine().getStatusCode();
if (status == 200) {
//读取响应内容
String result = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
System.out.println(result);
}
}
*/
}
| true |
c3831c1f3f71a4931b36fb51018f8044cae91c8b | Java | sikomo/test | /src/test/O1C.java | UTF-8 | 657 | 3.078125 | 3 | [] | no_license | package test;
public class O1C {
private int unAttribut;
private int unAutreAttribut;
private O2C lienO2;
private O3C lienO3;
public O1C(O3C lienO3) {
lienO2 = new O2C(); /* un lien de composition est créé */
this.lienO3 = lienO3; /* un lien d’agrégation est créé */
}
public void jeTravaillePourO1() {
lienO2.jeTravaillePourO2(); /* un message vers O2 */
lienO3.jeTravaillePourO3(); /* un message vers O3 */
}
public int uneAutreMethode(int a) {
return a;
}
protected void finalize() /* appel de cette méthode quand l’objet est effacé de la mémoire */{
System.out.println("aaahhhh... un Objet O1 se meurt ...");
}
}
| true |
50e6e77472cddb561f135a63696871007069df3d | Java | Collap/collap | /api/src/main/java/io/collap/plugin/ModuleFactory.java | UTF-8 | 2,723 | 2.59375 | 3 | [
"BSD-2-Clause"
] | permissive | package io.collap.plugin;
import io.collap.Collap;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
public class ModuleFactory extends PluginFactory {
private static final Logger logger = Logger.getLogger (ModuleFactory.class.getName ());
private Collap collap;
public ModuleFactory (PluginManager pluginManager, Collap collap) {
super (pluginManager);
this.collap = collap;
}
@Override
public Plugin create (File file) {
Map<String, Object> configuration = loadConfiguration (file, "module.yaml");
if (configuration == null) {
logger.severe ("Configuration not found! (File: " + file.getName () + ")");
return null;
}
String moduleName = (String) configuration.get ("name");
List<String> dependencyNames = (List<String>) configuration.get ("dependencies"); /* Note: May be null! */
String mainClassName = (String) configuration.get ("mainClass");
/* Check if all mandatory config options are set. */
if (mainClassName == null) return null;
if (moduleName == null) return null;
/* Check if plugin with the name is already registered. */
if (isPluginAlreadyRegistered (moduleName)) {
logger.severe ("Plugin '" + moduleName + "' is already registered");
return null;
}
/* Load the main class from the jar.
* Although the classes are in the classpath we need a module instance. */
URL fileUrl = null;
try {
fileUrl = file.toURI ().toURL ();
}catch (MalformedURLException e) {
e.printStackTrace ();
}
if (fileUrl == null) return null;
Class mainClass = null;
try {
mainClass = Class.forName (mainClassName);
}catch (ClassNotFoundException e) {
e.printStackTrace ();
}
if (mainClass == null) return null;
/* Create new instance of module main class. */
Object obj = null;
try {
obj = mainClass.getConstructor ().newInstance ();
} catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
e.printStackTrace ();
}
if (obj == null) return null;
/* Cast to Module. */
Module module = (Module) obj;
module.setName (moduleName);
module.setCollap (collap);
if (dependencyNames != null) module.setDependencyNames (dependencyNames);
return module;
}
}
| true |
ebcf465595f9823ba70ac025e1eee0133d72bcdb | Java | jtransc/jtransc-examples | /stress/src/main/java/com/stress/sub0/sub3/sub5/Class1036.java | UTF-8 | 394 | 2.171875 | 2 | [] | no_license | package com.stress.sub0.sub3.sub5;
import com.jtransc.annotation.JTranscKeep;
@JTranscKeep
public class Class1036 {
public static final String static_const_1036_0 = "Hi, my num is 1036 0";
static int static_field_1036_0;
int member_1036_0;
public void method1036()
{
System.out.println(static_const_1036_0);
}
public void method1036_1(int p0, String p1)
{
System.out.println(p1);
}
}
| true |
85a304fe01fcb7d20b077264538c55430fa0b9f7 | Java | KoichaDev/OBJ2000B-1-18H-Objektorientert-programmering-1 | /06 - Lineære datastrukturer/UnionArrayList/src/exercise_11_14/UnionArrayList.java | UTF-8 | 1,306 | 3.765625 | 4 | [] | no_license | package exercise_11_14;
import java.util.*;
public class UnionArrayList {
public static void main(String[] args) {
ArrayList <Integer> list = new ArrayList();
ArrayList <Integer> list2 = new ArrayList();
for(int i = 1; i <= 3; i++) {
list.add(randomNumbers(1,4));
list2.add(randomNumbers(5, 10));
}
System.out.println("List: " + list);
System.out.println("List2: " + list2);
ArrayList <Integer> list3 = union(list, list2);
for(int i = 0; i < list3.size(); i++) {
list3.get(i);
}
System.out.println("List3: " + list3);
}
public static ArrayList<Integer> union(ArrayList<Integer> list, ArrayList<Integer> list2) {
ArrayList <Integer> unionList = new ArrayList();
for(int i = 0; i < list.size(); i++) {
unionList.add(list.get(i));
}
for(int i = 0; i < list2.size(); i++) {
unionList.add(list2.get(i));
}
Collections.sort(unionList);
return unionList;
}
public static int randomNumbers(int min, int max) {
int range = (max - min) + 1;
return (int) (Math.random() * range) + min;
}
}
| true |
250d39f40781308c98dd31ebd9a958bdd10afcdb | Java | asilah/GE | /GE/src/main/java/org/gestion/emp/models/DepartementForm.java | UTF-8 | 1,230 | 2.109375 | 2 | [] | no_license | package org.gestion.emp.models;
import org.gestion.emp.entities.Departement;
import org.gestion.emp.entities.Employe;
public class DepartementForm {
private Long codeDept;
private String nom;
private String ville;
private String description;
private Long chefDept;
private String submit;
public String getSubmit() {
return submit;
}
public void setSubmit(String submit) {
this.submit = submit;
}
private Departement departement;
public Long getCodeDept() {
return codeDept;
}
public void setCodeDept(Long codeDept) {
this.codeDept = codeDept;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getVille() {
return ville;
}
public void setVille(String ville) {
this.ville = ville;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Long getChefDept() {
return chefDept;
}
public void setChefDept(Long chefDept) {
this.chefDept = chefDept;
}
public Departement getDepartement() {
return departement;
}
public void setDepartement(Departement departement) {
this.departement = departement;
}
}
| true |
a37b4f936d385d50dc0b936f1a447d1da474d9c5 | Java | glingo/sand-box | /src/main/java/component/resource/reference/ResourceReference.java | UTF-8 | 1,906 | 2.8125 | 3 | [] | no_license | package component.resource.reference;
import java.io.File;
import component.resource.FileSystem;
public class ResourceReference {
public static final String ANY_TYPE = "any";
public static final String STRING = "string";
public static final String FILE = "file";
public static final String MEMORY = "memory";
public static final String CLASSPATH = "classpath";
public static ResourceReference reference(String type, String resource) {
return new ResourceReference(type, resource);
}
public static ResourceReference inline(String resource) {
return reference(STRING, resource);
}
public static ResourceReference memory(String name) {
return reference(MEMORY, name);
}
public static ResourceReference file(String path) {
return reference(FILE, path);
}
public static ResourceReference file(File path) {
return reference(FILE, path.getAbsolutePath());
}
public static ResourceReference classpath(String path) {
return reference(CLASSPATH, path);
}
private final String type;
private final String path;
public ResourceReference(String type, String path) {
this.type = type;
this.path = path;
}
public String getType() {
return type;
}
public String getPath() {
return path;
}
public ResourceReference relativeTo(ResourceReference parent) {
if (!getType().equals(parent.getType())) {
// show smthing
return this;
}
if (FileSystem.isRelative(getPath())) {
return new ResourceReference(parent.getType(), FileSystem.resolve(parent.getPath(), getPath()));
}
return this;
}
@Override
public String toString() {
return "ResourceReference{" + "type=" + type + ", path=" + path + '}';
}
}
| true |
2c27563db3aaa5676efb1255fac567948dab71bb | Java | armaandhir/moneewise | /src/main/java/com/armaandhir/moneewise/service/ExpenseDescService.java | UTF-8 | 430 | 2.0625 | 2 | [] | no_license | package com.armaandhir.moneewise.service;
import com.armaandhir.moneewise.model.ExpenseDesc;
public interface ExpenseDescService {
/**
* Inserts the description for the given Expense
* @param inExpenseDesc
* @return
*/
public ExpenseDesc addDesc (ExpenseDesc inExpenseDesc);
/**
* Gets the description of the given Expense
* @param expenseId
* @return
*/
public ExpenseDesc getDesc (Long expenseId);
}
| true |
7d1e5c0f9f9e7ac1038827625abc8e1d0c02f359 | Java | RyanTech/myali | /main/src/com/alipay/mobile/commonui/widget/APFrameLayout.java | UTF-8 | 789 | 1.648438 | 2 | [] | no_license | package com.alipay.mobile.commonui.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.FrameLayout;
public class APFrameLayout extends FrameLayout
implements APViewInterface
{
public APFrameLayout(Context paramContext)
{
super(paramContext);
}
public APFrameLayout(Context paramContext, AttributeSet paramAttributeSet)
{
super(paramContext, paramAttributeSet);
}
public APFrameLayout(Context paramContext, AttributeSet paramAttributeSet, int paramInt)
{
super(paramContext, paramAttributeSet, paramInt);
}
}
/* Location: /Users/don/DeSources/alipay/backup/zhifubaoqianbao_52/classes-dex2jar.jar
* Qualified Name: com.alipay.mobile.commonui.widget.APFrameLayout
* JD-Core Version: 0.6.2
*/ | true |
f244257f2469370422d107bd39b5700e072896ac | Java | DanishRanjan/CRUX-JAVA- | /HackerBlocks/LinkedList_oddeven.java | UTF-8 | 4,833 | 3.6875 | 4 | [] | no_license | package HackerBlocks;
import java.util.Scanner;
public class LinkedList_oddeven {
private class Node {
int data;
Node next;
Node(int data, Node next) {
this.data = data;
this.next = next;
}
}
private Node head;
private Node tail;
private int size;
public LinkedList_oddeven() {
this.head = null;
this.tail = null;
this.size = 0;
}
public LinkedList_oddeven(Node head, Node tail, int size) {
this.head = head;
this.tail = tail;
this.size = size;
}
// O(1)
public int size() {
return this.size;
}
// O(1)
public boolean isEmpty() {
return this.size() == 0;
}
// O(1)
public int getFirst() throws Exception {
if (this.isEmpty()) {
throw new Exception("List is empty.");
}
return this.head.data;
}
// O(1)
public int getLast() throws Exception {
if (this.isEmpty()) {
throw new Exception("List is empty.");
}
return this.tail.data;
}
// O(N)
public int getAt(int idx) throws Exception {
Node temp = this.getNodeAt(idx);
return temp.data;
}
// O(N)
private Node getNodeAt(int idx) throws Exception {
if (this.isEmpty()) {
throw new Exception("List is empty");
}
if (idx < 0 || idx >= this.size()) {
throw new Exception("Invalid arguments");
}
Node retVal = this.head;
for (int i = 0; i < idx; i++) {
retVal = retVal.next;
}
return retVal;
}
// O(1)
public void addFirst(int data) {
Node node = new Node(data, this.head);
if (this.size() == 0) {
this.head = node;
this.tail = node;
} else {
this.head = node;
}
this.size++;
}
// O(1)
public void addLast(int data) {
Node node = new Node(data, null);
if (this.size() == 0) {
this.head = node;
this.tail = node;
} else {
this.tail.next = node;
this.tail = node;
}
this.size++;
}
// O(n)
public void addAt(int idx, int data) throws Exception {
if (idx < 0 || idx > this.size()) {
throw new Exception("Invalid arguments");
}
if (idx == 0) {
this.addFirst(data);
} else if (idx == this.size()) {
this.addLast(data);
} else {
Node nm1 = this.getNodeAt(idx - 1);
Node n = nm1.next;
Node node = new Node(data, n);
nm1.next = node;
this.size++;
}
}
// O(1)
public int removeFirst() throws Exception {
if (this.isEmpty()) {
throw new Exception("List is empty");
}
int retVal = this.head.data;
if (this.size() == 1) {
this.head = null;
this.tail = null;
} else {
this.head = this.head.next;
}
this.size--;
return retVal;
}
// O(n)
public int removeLast() throws Exception {
if (this.isEmpty()) {
throw new Exception("List is empty");
}
int retVal = this.tail.data;
if (this.size() == 1) {
this.head = null;
this.tail = null;
} else {
Node sm2 = this.getNodeAt(this.size() - 2);
sm2.next = null;
this.tail = sm2;
}
this.size--;
return retVal;
}
// O(n)
public int removeAt(int idx) throws Exception {
if (this.isEmpty()) {
throw new Exception("List is empty");
}
if (idx < 0 || idx >= this.size()) {
throw new Exception("Invalid arguments");
}
if (idx == 0) {
return this.removeFirst();
} else if (idx == this.size() - 1) {
return this.removeLast();
} else {
Node nm1 = this.getNodeAt(idx - 1);
Node n = nm1.next;
Node np1 = n.next;
nm1.next = np1;
this.size--;
return n.data;
}
}
// O(n)
public void reverse(int k) throws Exception{
LinkedList_oddeven prev = null;
while (this.size != 0) {
LinkedList_oddeven curr = new LinkedList_oddeven();
for (int i = 0; i < k && this.size != 0; i++) {
curr.addFirst(this.removeFirst());
}
if (prev == null) {
prev = curr;
} else {
prev.tail.next = curr.head;
prev.tail = curr.tail;
prev.size += curr.size;
}
}
this.head = prev.head;
this.tail = prev.tail;
this.size = prev.size;
}
public void partition() throws Exception{
LinkedList_oddeven odd = new LinkedList_oddeven();
LinkedList_oddeven even = new LinkedList_oddeven();
while(this.size!=0) {
int n = this.removeFirst();
if(n%2==0) {
even.addLast(n);
}else {
odd.addLast(n);
}
}
while(even.size!=0) {
odd.addLast(even.removeFirst());
}
this.head = odd.head;
this.tail = odd.tail;
this.size = odd.size;
}
public void display() {
Node temp = this.head;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
}
static Scanner scn = new Scanner(System.in);
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
LinkedList_oddeven ll = new LinkedList_oddeven();
int n = scn.nextInt();
for (int j = 0; j < n; j++) {
int item = scn.nextInt();
ll.addLast(item);
}
ll.partition();
ll.display();
}
}
| true |
c4036356a9e0cc34bdae2cba0176805832a3e608 | Java | aronnec/domainmath-ide | /Jalview 2.8/src/jalview/ws/seqfetcher/ASequenceFetcher.java | UTF-8 | 13,000 | 2.03125 | 2 | [] | no_license | /*
* Jalview - A Sequence Alignment Editor and Viewer (Version 2.8)
* Copyright (C) 2012 J Procter, AM Waterhouse, LM Lui, J Engelhardt, G Barton, M Clamp, S Searle
*
* This file is part of Jalview.
*
* Jalview is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Jalview is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with Jalview. If not, see <http://www.gnu.org/licenses/>.
*/
package jalview.ws.seqfetcher;
import jalview.datamodel.AlignmentI;
import jalview.datamodel.DBRefEntry;
import jalview.datamodel.SequenceI;
import jalview.util.DBRefUtils;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import java.util.Vector;
public class ASequenceFetcher
{
/**
* set of databases we can retrieve entries from
*/
protected Hashtable<String, Map<String, DbSourceProxy>> FETCHABLEDBS;
public ASequenceFetcher()
{
super();
}
/**
* get list of supported Databases
*
* @return database source string for each database - only the latest version
* of a source db is bound to each source.
*/
public String[] getSupportedDb()
{
if (FETCHABLEDBS == null)
return null;
String[] sf = new String[FETCHABLEDBS.size()];
Enumeration e = FETCHABLEDBS.keys();
int i = 0;
while (e.hasMoreElements())
{
sf[i++] = (String) e.nextElement();
}
;
return sf;
}
public boolean isFetchable(String source)
{
Enumeration e = FETCHABLEDBS.keys();
while (e.hasMoreElements())
{
String db = (String) e.nextElement();
if (source.compareToIgnoreCase(db) == 0)
return true;
}
jalview.bin.Cache.log.warn("isFetchable doesn't know about '" + source
+ "'");
return false;
}
public SequenceI[] getSequences(jalview.datamodel.DBRefEntry[] refs)
{
SequenceI[] ret = null;
Vector<SequenceI> rseqs = new Vector();
Hashtable<String, List<String>> queries = new Hashtable();
for (int r = 0; r < refs.length; r++)
{
if (!queries.containsKey(refs[r].getSource()))
{
queries.put(refs[r].getSource(), new ArrayList<String>());
}
List<String> qset = queries.get(refs[r].getSource());
if (!qset.contains(refs[r].getAccessionId()))
{
qset.add(refs[r].getAccessionId());
}
}
Enumeration<String> e = queries.keys();
while (e.hasMoreElements())
{
List<String> query = null;
String db = null;
db = e.nextElement();
query = queries.get(db);
if (!isFetchable(db))
{
reportStdError(db, query, new Exception(
"Don't know how to fetch from this database :" + db));
continue;
}
Iterator<DbSourceProxy> fetchers = getSourceProxy(db).iterator();
Stack<String> queriesLeft = new Stack<String>();
// List<String> queriesFailed = new ArrayList<String>();
queriesLeft.addAll(query);
while (fetchers.hasNext())
{
List<String> queriesMade = new ArrayList<String>();
HashSet queriesFound = new HashSet<String>();
try
{
DbSourceProxy fetcher = fetchers.next();
boolean doMultiple = fetcher.getAccessionSeparator() != null; // No
// separator
// - no
// Multiple
// Queries
while (!queriesLeft.isEmpty())
{
StringBuffer qsb = new StringBuffer();
do
{
if (qsb.length() > 0)
{
qsb.append(fetcher.getAccessionSeparator());
}
String q = queriesLeft.pop();
queriesMade.add(q);
qsb.append(q);
} while (doMultiple && !queriesLeft.isEmpty());
AlignmentI seqset = null;
try
{
// create a fetcher and go to it
seqset = fetcher.getSequenceRecords(qsb.toString()); // ,
// queriesFailed);
} catch (Exception ex)
{
System.err.println("Failed to retrieve the following from "
+ db);
System.err.println(qsb);
ex.printStackTrace(System.err);
}
// TODO: Merge alignment together - perhaps
if (seqset != null)
{
SequenceI seqs[] = seqset.getSequencesArray();
if (seqs != null)
{
for (int is = 0; is < seqs.length; is++)
{
rseqs.addElement(seqs[is]);
DBRefEntry[] frefs = DBRefUtils.searchRefs(seqs[is]
.getDBRef(), new DBRefEntry(db, null, null));
if (frefs != null)
{
for (DBRefEntry dbr : frefs)
{
queriesFound.add(dbr.getAccessionId());
queriesMade.remove(dbr.getAccessionId());
}
}
seqs[is] = null;
}
}
else
{
if (fetcher.getRawRecords() != null)
{
System.out.println("# Retrieved from " + db + ":"
+ qsb.toString());
StringBuffer rrb = fetcher.getRawRecords();
/*
* for (int rr = 0; rr<rrb.length; rr++) {
*/
String hdr;
// if (rr<qs.length)
// {
hdr = "# " + db + ":" + qsb.toString();
/*
* } else { hdr = "# part "+rr; }
*/
System.out.println(hdr);
if (rrb != null)
System.out.println(rrb);
System.out.println("# end of " + hdr);
}
}
}
}
} catch (Exception ex)
{
reportStdError(db, queriesMade, ex);
}
if (queriesMade.size() > 0)
{
System.out.println("# Adding " + queriesMade.size()
+ " ids back to queries list for searching again (" + db
+ ".");
queriesLeft.addAll(queriesMade);
}
}
}
if (rseqs.size() > 0)
{
ret = new SequenceI[rseqs.size()];
Enumeration sqs = rseqs.elements();
int si = 0;
while (sqs.hasMoreElements())
{
SequenceI s = (SequenceI) sqs.nextElement();
ret[si++] = s;
s.updatePDBIds();
}
}
return ret;
}
public void reportStdError(String db, List<String> queriesMade,
Exception ex)
{
System.err.println("Failed to retrieve the following references from "
+ db);
int n = 0;
for (String qv : queriesMade)
{
System.err.print(" " + qv + ";");
if (n++ > 10)
{
System.err.println();
n = 0;
}
}
System.err.println();
ex.printStackTrace();
}
/**
* Retrieve an instance of the proxy for the given source
*
* @param db
* database source string TODO: add version string/wildcard for
* retrieval of specific DB source/version combinations.
* @return an instance of DbSourceProxy for that db.
*/
public List<DbSourceProxy> getSourceProxy(String db)
{
List<DbSourceProxy> dbs;
Map<String, DbSourceProxy> dblist = FETCHABLEDBS.get(db);
if (dblist == null)
{
return new ArrayList<DbSourceProxy>();
}
;
if (dblist.size() > 1)
{
DbSourceProxy[] l = dblist.values().toArray(new DbSourceProxy[0]);
int i = 0;
String[] nm = new String[l.length];
// make sure standard dbs appear first, followed by reference das sources, followed by anything else.
for (DbSourceProxy s : l)
{
nm[i++] = ""+s.getTier()+s.getDbName().toLowerCase();
}
jalview.util.QuickSort.sort(nm, l);
dbs = new ArrayList<DbSourceProxy>();
for (i = l.length - 1; i >= 0; i--)
{
dbs.add(l[i]);
}
}
else
{
dbs = new ArrayList<DbSourceProxy>(dblist.values());
}
return dbs;
}
/**
* constructs and instance of the proxy and registers it as a valid
* dbrefsource
*
* @param dbSourceProxy
* reference for class implementing
* jalview.ws.seqfetcher.DbSourceProxy
* @throws java.lang.IllegalArgumentException
* if class does not implement jalview.ws.seqfetcher.DbSourceProxy
*/
protected void addDBRefSourceImpl(Class dbSourceProxy)
throws java.lang.IllegalArgumentException
{
DbSourceProxy proxy = null;
try
{
Object proxyObj = dbSourceProxy.getConstructor(null)
.newInstance(null);
if (!DbSourceProxy.class.isInstance(proxyObj))
{
throw new IllegalArgumentException(
dbSourceProxy.toString()
+ " does not implement the jalview.ws.seqfetcher.DbSourceProxy");
}
proxy = (DbSourceProxy) proxyObj;
} catch (IllegalArgumentException e)
{
throw e;
} catch (Exception e)
{
// Serious problems if this happens.
throw new Error("DBRefSource Implementation Exception", e);
}
addDbRefSourceImpl(proxy);
}
/**
* add the properly initialised DbSourceProxy object 'proxy' to the list of
* sequence fetchers
*
* @param proxy
*/
protected void addDbRefSourceImpl(DbSourceProxy proxy)
{
if (proxy != null)
{
if (FETCHABLEDBS == null)
{
FETCHABLEDBS = new Hashtable<String, Map<String, DbSourceProxy>>();
}
Map<String, DbSourceProxy> slist = FETCHABLEDBS.get(proxy
.getDbSource());
if (slist == null)
{
FETCHABLEDBS.put(proxy.getDbSource(),
slist = new Hashtable<String, DbSourceProxy>());
}
slist.put(proxy.getDbName(), proxy);
}
}
/**
* test if the database handler for dbName contains the given dbProperty when
* a dbName resolves to a set of proxies - this method will return the result
* of the test for the first instance. TODO implement additional method to
* query all sources for a db to find one with a particular property
*
* @param dbName
* @param dbProperty
* @return true if proxy has the given property
*/
public boolean hasDbSourceProperty(String dbName, String dbProperty)
{
// TODO: decide if invalidDbName exception is thrown here.
List<DbSourceProxy> proxies = getSourceProxy(dbName);
if (proxies != null)
{
for (DbSourceProxy proxy : proxies)
{
if (proxy.getDbSourceProperties() != null)
{
return proxy.getDbSourceProperties().containsKey(dbProperty);
}
}
}
return false;
}
/**
* select sources which are implemented by instances of the given class
*
* @param class that implements DbSourceProxy
* @return null or vector of source names for fetchers
*/
public String[] getDbInstances(Class class1)
{
if (!jalview.ws.seqfetcher.DbSourceProxy.class.isAssignableFrom(class1))
{
throw new Error(
"Implmentation Error - getDbInstances must be given a class that implements jalview.ws.seqfetcher.DbSourceProxy (was given '"
+ class1 + "')");
}
if (FETCHABLEDBS == null)
{
return null;
}
String[] sources = null;
Vector src = new Vector();
Enumeration dbs = FETCHABLEDBS.keys();
while (dbs.hasMoreElements())
{
String dbn = (String) dbs.nextElement();
for (DbSourceProxy dbp : FETCHABLEDBS.get(dbn).values())
{
if (class1.isAssignableFrom(dbp.getClass()))
{
src.addElement(dbn);
}
}
}
if (src.size() > 0)
{
src.copyInto(sources = new String[src.size()]);
}
return sources;
}
public DbSourceProxy[] getDbSourceProxyInstances(Class class1)
{
ArrayList<DbSourceProxy> prlist = new ArrayList<DbSourceProxy>();
for (String fetchable : getSupportedDb())
for (DbSourceProxy pr : getSourceProxy(fetchable))
{
if (class1.isInstance(pr))
{
prlist.add(pr);
}
}
if (prlist.size() == 0)
{
return null;
}
return prlist.toArray(new DbSourceProxy[0]);
}
}
| true |
49b11a0626deb7b7aaa83f45b9214319d4f6f22b | Java | SirLyle/ExNihiloFabrico | /src/main/java/exnihilofabrico/mixins/BottleUseMixin.java | UTF-8 | 2,197 | 2.1875 | 2 | [
"MIT"
] | permissive | package exnihilofabrico.mixins;
import exnihilofabrico.impl.BottleHarvestingImpl;
import net.minecraft.block.BlockState;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.GlassBottleItem;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ActionResult;
import net.minecraft.util.Hand;
import net.minecraft.util.TypedActionResult;
import net.minecraft.util.hit.BlockHitResult;
import net.minecraft.util.hit.HitResult;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.RayTraceContext;
import net.minecraft.world.World;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(GlassBottleItem.class)
public abstract class BottleUseMixin extends Item {
public BottleUseMixin(Settings settings) { super(settings); }
@Shadow
native protected ItemStack fill(ItemStack emptyBottle, PlayerEntity player, ItemStack filledBottle);
@Inject(at=@At("RETURN"), method="use", cancellable = true)
public void use(World world, PlayerEntity user, Hand hand, CallbackInfoReturnable<TypedActionResult<ItemStack>> cir) {
ItemStack held = cir.getReturnValue().getValue();
if(held.getItem() instanceof GlassBottleItem) {
HitResult hitResult = rayTrace(world, user, RayTraceContext.FluidHandling.SOURCE_ONLY);
if (hitResult.getType() == HitResult.Type.BLOCK) {
BlockPos blockPos = ((BlockHitResult)hitResult).getBlockPos();
if (world.canPlayerModifyAt(user, blockPos)) {
BlockState target = world.getBlockState(blockPos);
ItemStack result = BottleHarvestingImpl.INSTANCE.getResult(target);
if(!result.isEmpty()) {
cir.setReturnValue(new TypedActionResult<>(ActionResult.SUCCESS, this.fill(held, user, result)));
return;
}
}
}
}
cir.cancel();
}
}
| true |
94695a1a3f9f92194375c5cd5fd4ec7c43796bd4 | Java | regulyator/otus_java_homework | /hw06-SOLID/src/main/java/ru/otus/homework/atm/exceptions/IncorrectSumOrNominalException.java | UTF-8 | 321 | 2.359375 | 2 | [] | no_license | package ru.otus.homework.atm.exceptions;
public class IncorrectSumOrNominalException extends RuntimeException {
public IncorrectSumOrNominalException(String message) {
super(message);
}
public IncorrectSumOrNominalException(String message, Throwable cause) {
super(message, cause);
}
}
| true |
8c73e86c7b3a1a9662a29a185fc58411ac8ba957 | Java | roy2015/daily_experiment | /daily_experiment_core/src/main/java/com/guo/roy/research/leetcode/stage1/stage10/TestSolutionInterview1704.java | UTF-8 | 1,318 | 3.625 | 4 | [] | no_license | package com.guo.roy.research.leetcode.stage1.stage10;
import org.slf4j.LoggerFactory;
/**
* @author guojun
* @date 2020/8/8
*
*
* 面试题 17.04. 消失的数字
* 数组nums包含从0到n的所有整数,但其中缺了一个。请编写代码找出那个缺失的整数。你有办法在O(n)时间内完成吗?
*
* 注意:本题相对书上原题稍作改动
*
* 示例 1:
*
* 输入:[3,0,1]
* 输出:2
*
*
* 示例 2:
*
* 输入:[9,6,4,2,3,5,7,0,1]
* 输出:8
*
*
*/
public class TestSolutionInterview1704 {
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(TestSolutionInterview1704.class);
static class Solution {
/**
* 三分钟搞定。。。
* @param nums
* @return
*/
public int missingNumber(int[] nums) {
int len = nums.length;
int sum = (1 + len) * len /2 ;
int actualSum = 0;
for(int i = 0; i < len; i++) {
actualSum += nums[i];
}
return sum - actualSum;
}
}
public static void main(String[] args) {
logger.info("{}",new Solution().missingNumber(new int[]{3,0,1}));//2
logger.info("{}",new Solution().missingNumber(new int[]{9,6,4,2,3,5,7,0,1}));//8
}
}
| true |
5417daa4bc1563dec23e1081472a37bed07b25ff | Java | Kestrong/rocketmq | /rocketmq-spring-boot-starter/src/test/java/com/xjbg/rocketmq/Application.java | UTF-8 | 393 | 1.601563 | 2 | [
"Apache-2.0"
] | permissive | package com.xjbg.rocketmq;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author kesc
* @since 2019/4/5
*/
@SpringBootApplication(scanBasePackages = "com.xjbg.rocketmq")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
| true |
32ca8dad230ffd60e909bacce92a6561c56e994f | Java | SharaC/BibliotecaJDBC | /NetBeansProjects/BibliotecaFinal/BibliotecaFinal/src/biblioteca/Prestamo.java | UTF-8 | 8,424 | 3.109375 | 3 | [] | no_license |
package biblioteca;
import java.util.Arrays;
import java.util.Scanner;
import biblioteca.Informacion;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Prestamo extends Informacion {
Informacion objeto = new Informacion ();
Scanner teclado= new Scanner(System.in);
public void inicializar(){
Prestamo objeto3= new Prestamo();
boolean salir =false;
do{
System.out.println("Ingrese la opción de gestion de prestamo que desee asi: \n"
+ "'1' para prestar un libro, '2' para devolver un libro prestado,\n"
+ "'3' para consultar todos los libros prestados, '4' para regresar al menú principal ");
int opcion= teclado.nextInt();
try{
switch(opcion){
case 1:
objeto3.Prestar();
break;
case 2:
objeto3.devolver();
break;
case 3:
objeto3.mostrar();
break;
case 4:
salir=true;
break;
default:
System.out.println("Instruccion incorrecta, debe volver al menú principal \n");
salir= true;
}
}catch (Exception e){}
}while (salir==false);
}
public void Prestar(){
objeto.buscar();
System.out.println("Ingrese su cedula");
String cedula= teclado.next();
int nueva_cantidad= cantidad-1;
//System.out.println(nueva_cantidad);
Scanner lector =new Scanner(System.in);
try {
System.out.println("Intentando conectar a la base de datos...");
Class.forName("com.mysql.jdbc.Driver");
//Connection con= DriverManager.getConnection("jdbc:mysql://localhost/biblioteca", user, password);// crea conexion
Connection con= DriverManager.getConnection("jdbc:mysql://db4free.net/contactos_saca", user2, password2);
//System.out.println("conexión exitosa...");
Statement estado= con.createStatement();
//cargar todos los contactos
ResultSet resultado = estado.executeQuery("SELECT * FROM `prestados`");
//System.out.println(resultado.next());
while (resultado.next()==true){// mirar si la siguiente linea tiene algo
System.out.println(resultado.getString("id")+"\t" + resultado.getString("nombre")
+"\t"+ resultado.getString("cedula"));
}
resultado = estado.executeQuery("SELECT * FROM `prestados`");
estado.executeUpdate("INSERT INTO `prestados` VALUES (NULL, '"+nombre+"', '"+cedula+"')");
System.out.println("\n");
System.out.println("El prestamo del libro fue exitoso");
System.out.println("Libro prestado \t Cedula del prestador");
resultado = estado.executeQuery("SELECT * FROM `prestados` WHERE `nombre` LIKE '"+nombre+"' AND `cedula` LIKE '"+cedula+"'"); // no distingue mayus ni minusculas, pero si los espacios.
while (resultado.next()){// mirar si la siguiente linea tiene algo
System.out.println(resultado.getString("nombre")
+"\t\t"+ resultado.getString("cedula"));
}
//System.out.println(nombre);
ResultSet resultado2 = estado.executeQuery("SELECT * FROM `libros`");
resultado2 = estado.executeQuery("SELECT * FROM `libros` WHERE `nombre` LIKE '"+nombre+"'");
if(resultado2.next()==true){
ide= resultado2.getInt("id");
// System.out.println(ide);
estado.executeUpdate("UPDATE `contactos_saca`.`libros` SET `cantidad` = '"+nueva_cantidad+"' WHERE `libros`.`id` = '"+ide+"';");
}
}catch (SQLException ex) {
System.out.println("error de mysql");// genera un error de sintaxis mysql
} catch (Exception e){
System.out.println("se ha encontrado un error que es: "+e.getMessage());
}
}
public void devolver(){
Scanner teclado= new Scanner(System.in);
System.out.println("Ingrese su cedula");
String cedula1= teclado.nextLine();
System.out.println("Ingrese el nombre del libro que desea devolver");
String nombre1= teclado.nextLine();
Scanner lector =new Scanner(System.in);
try {
System.out.println("Intentando conectar a la base de datos...");
Class.forName("com.mysql.jdbc.Driver");
//Connection con= DriverManager.getConnection("jdbc:mysql://localhost/biblioteca", user, password);// crea conexion
Connection con= DriverManager.getConnection("jdbc:mysql://db4free.net/contactos_saca", user2, password2);
Statement estado= con.createStatement();
ResultSet resultado = estado.executeQuery("SELECT * FROM `prestados`");
resultado = estado.executeQuery("SELECT * FROM `prestados` WHERE `cedula` LIKE '"+cedula1+"' and `nombre` like '"+nombre1+"'"); // no distingue mayus ni minusculas, pero si los espacios.
if(resultado.next()==true){
int ide2= resultado.getInt("id");
estado.executeUpdate("DELETE FROM `prestados` WHERE `prestados`.`id` = '"+ide2+"';");
ResultSet resultado2 = estado.executeQuery("SELECT * FROM `libros`");
resultado2 = estado.executeQuery("SELECT * FROM `libros` WHERE `nombre` LIKE '"+nombre1+"'");
int nueva_cantidad= cantidad +1;
if(resultado2.next()==true){
ide2= resultado2.getInt("id");
//System.out.println(ide);
estado.executeUpdate("UPDATE `contactos_saca`.`libros` SET `cantidad` = '"+nueva_cantidad+"' WHERE `libros`.`id` = '"+ide2+"';");
}
}else System.out.println("\n El libro no existe en la base de datos de libros prestados");
}catch (SQLException ex) {
System.out.println("error de mysql");// genera un error de sintaxis mysql
} catch (Exception e){
System.out.println("se ha encontrado un error que es: "+e.getMessage());
}
}
public void mostrar(){
//System.out.println("Ingrese su cedula");
//String cedula= teclado.next();
Scanner lector =new Scanner(System.in);
try {
System.out.println("Intentando conectar a la base de datos...");
Class.forName("com.mysql.jdbc.Driver");
//Connection con= DriverManager.getConnection("jdbc:mysql://localhost/biblioteca", user, password);// crea conexion
Connection con= DriverManager.getConnection("jdbc:mysql://db4free.net/contactos_saca", user2, password2);
Statement estado= con.createStatement();
ResultSet resultado = estado.executeQuery("SELECT * FROM `prestados`");
System.out.println("\n Nombre del libro \t Cédula del prestador");
while (resultado.next()){// mirar si la siguiente linea tiene algo
System.out.println(resultado.getString("nombre")
+"\t \t \t"+ resultado.getString("cedula"));
}
System.out.println("\t");
}catch (SQLException ex) {
System.out.println("error de mysql");// genera un error de sintaxis mysql
} catch (Exception e){
System.out.println("se ha encontrado un error que es: "+e.getMessage());
}
}
}
| true |
2ff6bfeead8fdf076ed6f59e8c9d2e8e806fce65 | Java | noobchen/ADS-Controller | /src/main/java/com/ads/cm/strategy/area/SmspStrategy.java | UTF-8 | 1,354 | 2.1875 | 2 | [] | no_license | package com.ads.cm.strategy.area;
import com.ads.cm.repository.area.areaBean.Area;
import com.ads.cm.util.phone.PhoneUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Author: cyc
* Date: 12-3-22
* Time: 上午10:41
* Description: to write something
*/
public class SmspStrategy implements AreaStrategy {
private final Logger logger = LoggerFactory.getLogger(SmspStrategy.class);
@Override
public Area getArea(Area conditionArea) {
if (StringUtils.isNotEmpty(conditionArea.getSmsp())) {
Area area = (Area) conditionArea.getAreaBySmsp().getEventResult();
if (null != area && StringUtils.isNotEmpty(conditionArea.getImsi())) {
int defaultProviderId = PhoneUtils.getProviderId(conditionArea.getImsi());
if (defaultProviderId != area.getProvider_id()) {
logger.debug("defaultProviderId:{} area:{} isn't equals.", defaultProviderId, conditionArea);
area.setProvider_id(defaultProviderId);
}
logger.debug("find area:{} info by smsp:{}.", area.toString(), conditionArea.getSmsp());
return area;
} else {
return null;
}
} else {
return null;
}
}
}
| true |
4fd6b9f457cb11d22c341151131f1e89d1adaf88 | Java | gaopu/PersonalBlog | /src/main/java/com/blog/service/ArticleServiceImpl.java | UTF-8 | 4,989 | 2.3125 | 2 | [] | no_license | package com.blog.service;
import com.blog.mapper.ArticleCategoryMapper;
import com.blog.mapper.ArticleMapper;
import com.blog.mapper.CommentMapper;
import com.blog.po.Article;
import com.blog.po.Comment;
import com.blog.utils.PageParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.List;
/**
* Created by geekgao on 15-10-12.
*/
@Service
public class ArticleServiceImpl implements ArticleService {
@Autowired
private ArticleMapper articleMapper;
@Autowired
private ArticleCategoryMapper articleCategoryMapper;
@Autowired
private CommentMapper commentMapper;
@Override
public List<Article> getAllArticle() throws IOException {
return articleMapper.getAllArticle();
}
@Override
public int getAuthorId(int id) throws IOException {
return articleMapper.getArticle(id).getAuthor_Id();
}
@Override
public String getTitle(int id) throws IOException {
return articleMapper.getArticle(id).getTitle();
}
@Override
public Date getTime(int id) throws IOException {
return articleMapper.getArticle(id).getTime();
}
@Override
public int getReadNum(int id) throws IOException {
return articleMapper.getReadNum(id);
}
@Override
public int getCommentNum(int id) throws IOException {
return articleMapper.getCommentNum(id);
}
@Override
public boolean isDeleted(int id) throws IOException {
return articleMapper.getArticle(id).getDeleted().equals("y");
}
@Override
public void insert(Article article) throws IOException {
articleMapper.insert(article);
}
@Override
public int getLatestId() throws IOException {
return articleMapper.getLatestId();
}
@Override
public List<Article> getCommonArticle() throws IOException {
return articleMapper.getCommonArticle();
}
@Override
public List<Article> getDeletedArticle() throws IOException {
return articleMapper.getDeletedArticle();
}
@Override
public void moveToDusbin(int articleId) throws IOException {
articleMapper.moveToDusbin(articleId);
}
@Override
public void delete(int articleId) throws IOException {
//删除文章的分类信息
articleCategoryMapper.delete(articleId);
/*删除文章的评论信息*/
//删除本文章所有的评论的回复
List<Comment> replies = commentMapper.selectRep(articleId);
for (Comment r:replies) {
commentMapper.delete(r.getId());
}
//删除本文章所有的评论
List<Comment> comments = commentMapper.selectCom(articleId);
for (Comment c:comments) {
commentMapper.delete(c.getId());
}
//删除文章
articleMapper.delete(articleId);
}
@Override
public void recover(int articleId) throws IOException {
articleMapper.recover(articleId);
}
@Override
public int getRowCount() throws IOException {
return articleMapper.getRowCount();
}
@Override
public PageParam getPagedArticle(PageParam pageParam) throws IOException {
int currPage = pageParam.getCurrPage();
// limit offset, size
int offset = (currPage - 1) * PageParam.pageSize;
int size = PageParam.pageSize;
List<Article> articleList = articleMapper.getPagedArticle(offset,size);
pageParam.setData(articleList);
return pageParam;
}
@Override
public void setCategory(int id, int[] selectedId) throws IOException {
articleMapper.delCategory(id);
for (int i = 0; i < selectedId.length;i++){
articleMapper.setCategory(id,selectedId[i]);
}
}
@Override
public String getPeek(int id) throws IOException {
return articleMapper.getPeek(id);
}
@Override
public void increasePageView(HttpSession session,String articleId) throws IOException {
//session里面添加[read:1,2,3],代表浏览过id分别为1,2,3的文章
String read = (String) session.getAttribute("read");
//没有浏览过任何文章
if (read == null) {
session.setAttribute("read",articleId);
} else {
//已经阅读过的文章id
String[] readIds = read.split(",");
for (String id:readIds) {
//已经阅读过本篇文章
if (id.equals(articleId)) {
return;
}
}
}
//到这说明没有浏览过本篇文章
articleMapper.increaseReadNum(articleId);
if (read == null) {
session.setAttribute("read",articleId);
} else {
session.setAttribute("read",read + "," + articleId);
}
}
}
| true |
5a1060e504dcb76eb0f452e7c417b2dbb833e592 | Java | jungting20/data-structure | /listStack/listStack.java | UTF-8 | 1,840 | 3.640625 | 4 | [] | no_license | package listStack;
public class listStack {
node head;
node top;
public listStack(){
head = new node();
top = head;
}
public boolean isEmpty(){
if(this.head.getNext() == null){
return true;
}
else
return false;
}
public void push(int data){
node newNode = new node(data);
top = newNode;
if(isEmpty()){
this.head.setnext(newNode);
return ;
}
node ptr;
ptr = this.head;
while(ptr.getNext() != null)
ptr = ptr.getNext();
ptr.setnext(newNode);
}
public int pop(){
if(isEmpty()){
System.out.println("List is empty");
return -1;
}
int data;
data = this.top.getData();
node ptr = this.head;
while(ptr.getNext().getNext() != null)
ptr = ptr.getNext();
top = ptr;
ptr.setnext(null);
return data;
}
public void printList(){
if(isEmpty()){
System.out.println("List is empty");
return ;
}
node ptr = this.head.getNext();
System.out.print("List : ");
while(ptr != null){
System.out.print(ptr.getData() + " ");
ptr = ptr.getNext();
}
System.out.println();
}
public static void main(String[] args){
listStack stack = new listStack();
stack.push(1);
stack.printList();
System.out.println("pop : " + stack.pop());
stack.printList();
stack.push(1);
stack.push(2);
stack.push(3);
stack.printList();
System.out.println("pop : " + stack.pop());
stack.printList();
}
}
class node{
int data;
node next;
node(){
this.next = null;
}
node(int data){
this.data = data;
this.next = null;
}
void setData(int data){
this.data = data;
}
int getData(){
return this.data;
}
void setnext(node next){
this.next = next;
}
node getNext(){
return this.next;
}
} | true |
299810b8bbfe039f20287f21ad674c6d1aff083d | Java | enioka-Haute-Couture/jqm | /jqm-all/jqm-model/src/main/java/com/enioka/jqm/jdbc/DbImplMySql.java | UTF-8 | 6,507 | 2.328125 | 2 | [
"Apache-2.0",
"CC-BY-3.0"
] | permissive | package com.enioka.jqm.jdbc;
import java.io.Console;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import com.enioka.jqm.model.JobInstance;
import com.enioka.jqm.model.Queue;
public class DbImplMySql extends DbAdapter
{
private String sequenceSql, sequenceSqlRetrieval;
@Override
public void prepare(Properties p, Connection cnx)
{
super.prepare(p, cnx);
// We do NOT want to use paginateQuery on each poll query as we want polling to be as painless as possible, so we pre-paginate it.
queries.put("ji_select_poll", queries.get("ji_select_poll") + " LIMIT ?");
sequenceSqlRetrieval = adaptSql("SELECT next FROM __T__JQM_SEQUENCE WHERE name = ?");
sequenceSql = adaptSql("UPDATE __T__JQM_SEQUENCE SET next = next + 1 WHERE name = ?");
}
@Override
public String adaptSql(String sql)
{
if (sql.contains("CREATE SEQUENCE"))
{
return "";
}
return sql.replace("MEMORY TABLE", "TABLE").replace("JQM_PK.nextval", "?").replace(" DOUBLE", " DOUBLE PRECISION")
.replace("UNIX_MILLIS()", "ROUND(UNIX_TIMESTAMP(NOW(4)) * 1000)").replace("IN(UNNEST(?))", "IN(?)")
.replace("CURRENT_TIMESTAMP - 1 MINUTE", "(UNIX_TIMESTAMP() - 60)")
.replace("CURRENT_TIMESTAMP - ? SECOND", "(NOW() - INTERVAL ? SECOND)").replace("FROM (VALUES(0))", "FROM DUAL")
.replace("DNS||':'||PORT", "CONCAT(DNS, ':', PORT)").replace(" TIMESTAMP ", " TIMESTAMP(3) ")
.replace("CURRENT_TIMESTAMP", "FFFFFFFFFFFFFFFFF@@@@").replace("FFFFFFFFFFFFFFFFF@@@@", "UTC_TIMESTAMP(3)")
.replace("TIMESTAMP(3) NOT NULL", "TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3)").replace("__T__", this.tablePrefix);
}
@Override
public boolean compatibleWith(DatabaseMetaData product) throws SQLException
{
return (product.getDatabaseProductName().contains("MySQL")
&& ((product.getDatabaseMajorVersion() == 5 && product.getDatabaseMinorVersion() >= 6)
|| product.getDatabaseMajorVersion() > 5))
|| (product.getDatabaseProductName().contains("MariaDB") && product.getDatabaseMajorVersion() >= 10);
}
@Override
public List<String> preSchemaCreationScripts()
{
List<String> res = new ArrayList<String>();
res.add("/sql/mysql.sql");
return res;
}
@Override
public void beforeUpdate(Connection cnx, QueryPreparation q)
{
// There is no way to do parameterized IN(?) queries with MySQL so we must rewrite these queries as IN(?, ?, ?...)
// This cannot be done at startup, as the ? count may be different for each call.
if (q.sqlText.contains("IN(?)"))
{
int index = q.sqlText.indexOf("IN(?)");
int nbIn = 0;
while (index >= 0)
{
index = q.sqlText.indexOf("IN(?)", index + 1);
nbIn++;
}
int nbList = 0;
ArrayList<Object> newParams = new ArrayList<Object>(q.parameters.size() + 10);
for (Object o : q.parameters)
{
if (o instanceof List<?>)
{
nbList++;
List<?> vv = (List<?>) o;
if (vv.size() == 0)
{
throw new DatabaseException("Cannot do a query whith an empty list parameter");
}
newParams.addAll(vv);
String newPrm[] = new String[vv.size()];
for (int j = 0; j < vv.size(); j++)
{
newPrm[j] = "?";
}
StringBuilder sb = new StringBuilder();
for (int j = 0; j < vv.size(); j++)
{
sb.append("?,");
}
q.sqlText = q.sqlText.replaceFirst("IN\\(\\?\\)", "IN(" + sb.substring(0, sb.length() - 1) + ")");
}
else
{
newParams.add(o);
}
}
q.parameters = newParams;
if (nbList != nbIn)
{
throw new DatabaseException("Mismatch: count of list parameters and of IN clauses is different.");
}
}
// Manually generate a new ID for INSERT orders. (with one exception - history inserts do not need a generated ID)
if (!q.sqlText.startsWith("INSERT INTO") || q.queryKey.startsWith("history_insert"))
{
return;
}
PreparedStatement s = null;
PreparedStatement s2 = null;
try
{
s = cnx.prepareStatement(sequenceSql);
s.setString(1, "MAIN");
s.executeUpdate();
s2 = cnx.prepareStatement(sequenceSqlRetrieval);
s2.setString(1, "MAIN");
ResultSet rs = s2.executeQuery();
if (!rs.next())
{
throw new NoResultException("The query returned zero rows when one was expected.");
}
q.preGeneratedKey = rs.getInt(1);
q.parameters.add(0, q.preGeneratedKey);
}
catch (SQLException e)
{
throw new DatabaseException(q.sqlText + " - " + sequenceSql + " - while fetching new ID from table sequence", e);
}
finally
{
DbHelper.closeQuietly(s);
DbHelper.closeQuietly(s2);
}
}
@Override
public void setNullParameter(int position, PreparedStatement s) throws SQLException
{
// Absolutely stupid: set to null regardless of type.
s.setObject(position, null);
}
@Override
public String paginateQuery(String sql, int start, int stopBefore, List<Object> prms)
{
int pageSize = stopBefore - start;
sql = String.format("%s LIMIT ? OFFSET ?", sql);
prms.add(pageSize);
prms.add(start);
return sql;
}
@Override
public List<JobInstance> poll(DbConn cnx, Queue queue, int headSize)
{
return JobInstance.select(cnx, "ji_select_poll", queue.getId(), headSize);
}
}
| true |
6c7f393a3312b370b33aa2a6fc6c439578754531 | Java | IOIIIO/DisneyPlusSource | /sources/com/bamtech/sdk4/useractivity/internal/UserActivityComponent.java | UTF-8 | 1,708 | 1.632813 | 2 | [] | no_license | package com.bamtech.sdk4.useractivity.internal;
import com.bamtech.sdk4.plugin.PluginRegistry;
import com.bamtech.sdk4.useractivity.UserActivityPlugin;
import kotlin.Metadata;
@Metadata(mo31005bv = {1, 0, 3}, mo31006d1 = {"\u0000\u0018\n\u0002\u0018\u0002\n\u0002\u0010\u0000\n\u0000\n\u0002\u0010\u0002\n\u0000\n\u0002\u0018\u0002\n\u0002\b\u0002\ba\u0018\u00002\u00020\u0001:\u0001\u0006J\u0010\u0010\u0002\u001a\u00020\u00032\u0006\u0010\u0004\u001a\u00020\u0005H&¨\u0006\u0007"}, mo31007d2 = {"Lcom/bamtech/sdk4/useractivity/internal/UserActivityComponent;", "", "inject", "", "plugin", "Lcom/bamtech/sdk4/useractivity/UserActivityPlugin;", "Builder", "plugin-user-activity_release"}, mo31008k = 1, mo31009mv = {1, 1, 15})
/* compiled from: UserActivityComponent.kt */
public interface UserActivityComponent {
@Metadata(mo31005bv = {1, 0, 3}, mo31006d1 = {"\u0000\u0018\n\u0002\u0018\u0002\n\u0002\u0010\u0000\n\u0000\n\u0002\u0018\u0002\n\u0002\b\u0002\n\u0002\u0018\u0002\n\u0000\bg\u0018\u00002\u00020\u0001J\b\u0010\u0002\u001a\u00020\u0003H&J\u0010\u0010\u0004\u001a\u00020\u00002\u0006\u0010\u0005\u001a\u00020\u0006H'¨\u0006\u0007"}, mo31007d2 = {"Lcom/bamtech/sdk4/useractivity/internal/UserActivityComponent$Builder;", "", "build", "Lcom/bamtech/sdk4/useractivity/internal/UserActivityComponent;", "registry", "pluginRegistry", "Lcom/bamtech/sdk4/plugin/PluginRegistry;", "plugin-user-activity_release"}, mo31008k = 1, mo31009mv = {1, 1, 15})
/* compiled from: UserActivityComponent.kt */
public interface Builder {
UserActivityComponent build();
Builder registry(PluginRegistry pluginRegistry);
}
void inject(UserActivityPlugin userActivityPlugin);
}
| true |
41bbfecc59bf6d81321347059da4fd6441b9d97c | Java | eliaidam/zang-java | /src/main/java/com/zang/api/domain/enums/CarrierLookupStatus.java | UTF-8 | 698 | 2.34375 | 2 | [
"MIT"
] | permissive | package com.zang.api.domain.enums;
import java.util.HashMap;
import java.util.Map;
import org.codehaus.jackson.annotate.JsonCreator;
import com.zang.api.domain.enums.util.EnumUtil;
public enum CarrierLookupStatus {
DELIVRD, UNDELIV, UNKNOWN, REJECTED;
private static Map<CarrierLookupStatus, String> map;
static {
map = new HashMap<CarrierLookupStatus, String>();
map.put(DELIVRD, "DELIVRD");
map.put(UNDELIV, "UNDELIV");
map.put(UNKNOWN, "UNKNOWN");
map.put(REJECTED, "REJECTED");
}
@JsonCreator
public static CarrierLookupStatus forValue(String s) {
return EnumUtil.getValue(s, map, null);
}
@Override
public String toString() {
return map.get(this);
}
}
| true |