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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
f1cdc4340bdbe95bfc1a27ec139a1ae79bef4a57
|
Java
|
msicsic/bankAccount
|
/business/src/main/java/com/sg/kata/bankaccount/business/portOut/AccountRepository.java
|
UTF-8
| 1,231
| 2.6875
| 3
|
[] |
no_license
|
package com.sg.kata.bankaccount.business.portOut;
import com.sg.kata.bankaccount.business.Account;
import com.sg.kata.bankaccount.business.AccountID;
import com.sg.kata.bankaccount.business.exceptions.AccountAlreadyExistsException;
import com.sg.kata.bankaccount.business.exceptions.UnknownAccountException;
import java.util.function.Function;
public interface AccountRepository {
/**
* Register a non existing account
* @param account the new account to store in this repo
* @throws AccountAlreadyExistsException if this account is already present in the repo
*/
void registerNew(Account account);
/**
* Performs the update operation on the aggregate corresponding to the ID
* @param id ID of an account
* @param update a lambda that receives the loaded account and perform an operation on it in a transaction
* @throws UnknownAccountException if account does not exist
*/
<R> R update(AccountID id, Function<Account, R> update);
/**
* Get an Account by its ID
* @param id ID of the account to retrieve
* @return the loaded Account
* @throws UnknownAccountException if this account does not exist
*/
Account get(AccountID id);
}
| true
|
e9cd3b72868648ff14d96f7e498b236b45ca5ce3
|
Java
|
CuttingWaveKnife/myproject
|
/service/security/impl/RoleServiceImpl.java
|
UTF-8
| 761
| 1.84375
| 2
|
[] |
no_license
|
package com.cb.service.security.impl;
import com.cb.common.core.dao.CommonDao;
import com.cb.common.core.service.impl.CommonServiceImpl;
import com.cb.dao.security.RoleDao;
import com.cb.model.security.Role;
import com.cb.service.security.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* Created by l on 2016/11/23.
*/
@Service
@Transactional
public class RoleServiceImpl extends CommonServiceImpl<Role, String> implements RoleService {
@Autowired
private RoleDao roleDao;
@Override
protected CommonDao<Role, String> getCommonDao() {
return roleDao;
}
}
| true
|
da4d7d64efe709784d1c8aed002f2453e169a01f
|
Java
|
acm-team/QuestForAdventure-jEngine
|
/src/org/acm_team/games/questforadventure/ConsoleOutput.java
|
UTF-8
| 887
| 3.078125
| 3
|
[] |
no_license
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.acm_team.games.questforadventure;
import java.io.*;
import java.util.*;
/**
*
* @author fusion2004
*/
public class ConsoleOutput implements Output {
private Queue<String> output;
private PrintStream out;
private String prompt;
public ConsoleOutput() {
output = new LinkedList<String>();
out = System.out;
prompt = ">";
}
public void add(String s) {
output.add(s);
}
public boolean isEmpty() {
return output.isEmpty();
}
public void flush() {
while(!output.isEmpty()) {
out.println(output.poll());
}
}
public void printPrompt() {
out.print(prompt+" ");
}
public void setPrompt(String prompt) {
this.prompt = prompt;
}
}
| true
|
492873ec09a4f99f9abb9c71fa97c2a4ba1a65ce
|
Java
|
dr-shakya/pocblockchain
|
/src/main/java/com/logica/pocblockchaintest/controller/BankController.java
|
UTF-8
| 2,847
| 2.125
| 2
|
[] |
no_license
|
package com.logica.pocblockchaintest.controller;
import com.logica.pocblockchaintest.dto.BankDTO;
import com.logica.pocblockchaintest.dto.CustomerDTO;
import com.logica.pocblockchaintest.dto.TransactionReceiptDTO;
import com.logica.pocblockchaintest.model.Transaction;
import com.logica.pocblockchaintest.services.mapper.TransactionMapperService;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.admin.Admin;
@RestController
@RequestMapping("bank")
@RequiredArgsConstructor
public class BankController {
public final static Logger LOGGER = LoggerFactory.getLogger(BankController.class);
private final Transaction transaction;
private final Web3j web3j;
private final Admin admin;
@GetMapping("{bankName}")
public ResponseEntity getBank(@PathVariable String bankName) throws Exception {
return ResponseEntity.ok(transaction.getBank(bankName).send());
}
@GetMapping("balance/{customerName}")
public ResponseEntity getBalance(@PathVariable String customerName) throws Exception {
return ResponseEntity.ok(transaction.getBalance(customerName).send());
}
@PostMapping
public ResponseEntity<?> addBank(@RequestBody BankDTO bankDTO) throws Exception {
String bankAddress = String.valueOf(admin.personalNewAccount(bankDTO.getAccountPassword()).send().getAccountId());
TransactionReceiptDTO transactionReceiptDTO = TransactionMapperService.transactionReceiptMapper(transaction.setBank(bankDTO.getBankName(), bankDTO.getAccountPassword(), bankAddress).send());
return new ResponseEntity<>(transactionReceiptDTO, HttpStatus.OK);
}
@PostMapping("customer")
public ResponseEntity<?> addCustomer(@RequestBody CustomerDTO customerDTO) throws Exception{
String customerAddress = String.valueOf(admin.personalNewAccount(customerDTO.getAccountPassword()).send().getAccountId());
TransactionReceiptDTO transactionReceiptDTO = TransactionMapperService.transactionReceiptMapper(transaction.setCustomer(customerDTO.getBankName(), customerDTO.getCustomerName(), customerDTO.getAccountPassword(), customerDTO.getBalance(), customerAddress).send());
return new ResponseEntity<>(transactionReceiptDTO, HttpStatus.OK);
}
@PostMapping("verify/{bankName}")
public ResponseEntity<?> verifyStatement(@PathVariable String bankName) throws Exception{
TransactionReceiptDTO transactionReceiptDTO = TransactionMapperService.transactionReceiptMapper(transaction.verifyStatement(bankName).send());
return new ResponseEntity<>(transactionReceiptDTO, HttpStatus.OK);
}
}
| true
|
e5be4a0ee7db95994759191734adf686cb762922
|
Java
|
AutomicDemo/Digital-Credit
|
/src/main/java/io/demo/credit/repository/UserRoleRepository.java
|
UTF-8
| 223
| 1.546875
| 2
|
[
"MIT"
] |
permissive
|
package io.demo.credit.repository;
import org.springframework.data.repository.CrudRepository;
import io.demo.credit.model.security.UserRole;
public interface UserRoleRepository extends CrudRepository<UserRole, Long> {
}
| true
|
737eaa1b7791737366faa9919946bc57d38c367c
|
Java
|
ntarannum/Software-Work
|
/CO2006_nt161/sprint3/miniproject/src/main/java/app/controller/UserInfoValidator.java
|
UTF-8
| 1,071
| 2.578125
| 3
|
[] |
no_license
|
package app.controller;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import app.domain.UserInfo;
public class UserInfoValidator implements Validator {
public boolean supports(Class<?> clazz) {
return UserInfo.class.equals(clazz);
}
@Override
public void validate(Object target, Errors errors) {
UserInfo dto = (UserInfo) target;
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "forenames", "", "Field cannot be empty.");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastnames", "", "Field cannot be empty.");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "login", "", "Field cannot be empty.");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "", "Field cannot be empty.");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password2", "", "Field cannot be empty.");
if (!dto.getPassword().equals(dto.getPassword2())) {
errors.rejectValue("password2", "", "Paswords do not match.");
}
}
}
| true
|
b8462daf91c06f72581eb68613118c9b2a51ab64
|
Java
|
kapild/algorithms-design-and-analysis
|
/programming-practice/src/main/java/challenges/leetcode/SetMatrixZeroes.java
|
UTF-8
| 1,542
| 3.359375
| 3
|
[] |
no_license
|
package challenges.leetcode;
import java.util.HashSet;
import java.util.Set;
import challenges.AbstractCustomTestRunner;
/**
* 73. Set Matrix Zeroes
*
* Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
*
* @author Hxkandwal
*/
public class SetMatrixZeroes extends AbstractCustomTestRunner {
// O(1) space solution
public void _setZeroesBetter(int[][] matrix) {
int col0 = 1;
for (int row = 0; row < matrix.length; row ++) {
if (matrix [row][0] == 0) col0 = 0;
for (int col = 1; col < matrix [0].length; col ++)
if (matrix [row][col] == 0) matrix [row][0] = matrix [0][col] = 0;
}
for (int row = matrix.length - 1; row >= 0; row --) {
for (int col = matrix [0].length - 1; col >= 1; col --)
if (matrix [row][0] == 0 || matrix [0][col] == 0) matrix [row][col] = 0;
if (col0 == 0) matrix [row][0] = 0;
}
}
public void _setZeroes(int[][] matrix) {
Set<Integer> rows = new HashSet<>(), cols = new HashSet<>();
for (int row = 0; row < matrix.length; row ++)
for (int col = 0; col < matrix [0].length; col ++)
if (matrix [row][col] == 0) { rows.add (row); cols.add (col); }
for (int row : rows) for (int col = 0; col < matrix [0].length; col ++) matrix [row][col] = 0;
for (int col : cols) for (int row = 0; row < matrix.length; row ++) matrix [row][col] = 0;
}
}
| true
|
d302965f628b865c004e43771023a7fda77d1945
|
Java
|
wjwancfb88/tbb
|
/equipment/src/main/java/com/dhwooden/ep/controller/wx/WXController.java
|
UTF-8
| 5,109
| 1.875
| 2
|
[] |
no_license
|
package com.dhwooden.ep.controller.wx;
import com.dhwooden.ep.util.HttpClientHelper;
import com.dhwooden.ep.util.PostJson;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
/**
* <p>
* 前端控制器
* </p>
*
* @author wk
* @since 2018-04-18
*/
@Controller
@RequestMapping("/wx/dl")
public class WXController {
private final Logger logger= LoggerFactory.getLogger(WXController.class);
String URL="https://open.weixin.qq.com/connect/oauth2/authorize";
private String token = "flag";
@RequestMapping("/syn")
@ResponseBody
public void syn() throws Exception {
// String url=URL+"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx119d493b885c9198&redirect_uri=http://app.tubaoyz.com/admin/entry/loading&response_type=code&scope=snsapi_base&state=s";
String url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxdb0d3982019dedcd&redirect_uri=http://61.153.182.58:3401/admin/entry/loading?flag=2&response_type=code&scope=snsapi_base&state=s#wechat_redirect";
// String url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxdb0d3982019dedcd&redirect_uri=http://61.153.182.58:3401/admin/entry/loading&response_type=code&scope=snsapi_base&state=s";
JSONObject jsonObject = HttpClientHelper.httpGet(url);
System.out.println(jsonObject);
}
@RequestMapping("/mypage")
@ResponseBody
public String mypage(String code) throws Exception {
String url="https://api.weixin.qq.com/sns/oauth2/access_token";
// JSONObject json=HttpClientHelper.httpGet(url);
String str = "appid=wx119d493b885c9198&secret=d1ac107caf422a22ef07e1467b63583e&code=\""+code+"\"&grant_type=authorization_code";
byte[] bytes = PostJson.post2(url, str, "UTF-8");
com.alibaba.fastjson.JSONObject json = com.alibaba.fastjson.JSONObject.parseObject(new String(bytes));
logger.info(json.toString());
//JSONObject ss = JSONObject.fromObject(json);
// String openid = json.getString("openid");
// String url=URL+"?appid=wx3e4a89adbc62b1e9&redirect_uri=http://www.xxx.com/wechat/event/myPreReg.html&response_type=code&scope=snsapi_base&state=s";
// HttpClientHelper.httpGet(url);
return "code";
}
@RequestMapping(value = "/wx",method = RequestMethod.GET)
@ResponseBody
public String wxInterface(HttpServletRequest request, HttpServletResponse response)throws Exception{
logger.info("开始验证微信服务器信息");
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
String signature = request.getParameter("signature");
String timestamp = request.getParameter("timestamp");
String nonce = request.getParameter("nonce");
String echostr = request.getParameter("echostr");
logger.info("signature : " + signature + ",timestamp : " + timestamp + ",nonce : " + nonce + ",echostr : " + echostr);
if (checkSignature(signature,timestamp,nonce)){
logger.info("微信服务器信息验证成功!");
return echostr;
}else{
return null;
}
}
public boolean checkSignature(String signature,String timestamp,String nonce){
String[] arr = new String[]{token,timestamp,nonce};
Arrays.sort(arr);
StringBuffer sb = new StringBuffer();
for (int i = 0;i < arr.length; i++){
sb.append(arr[i]);
}
String tempStr = null;
try{
tempStr = getSha1(sb.toString());
}catch (Exception e){
e.printStackTrace();
}
logger.info("微信签名加密认证!");
sb = null;
return tempStr != null ? tempStr.equals(signature) : false;
}
public static String getSha1(String str) {
if (str == null || str.length() == 0) {
return null;
}
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
try {
MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
mdTemp.update(str.getBytes("UTF-8"));
byte[] md = mdTemp.digest();
int j = md.length;
char buf[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
buf[k++] = hexDigits[byte0 & 0xf];
}
return new String(buf);
} catch (Exception e) {
// TODO: handle exception
return null;
}
}
}
| true
|
84529015a5e2f76c71bf7699fe53607893f300a2
|
Java
|
Sweety310897/6053_ADS
|
/ADS-Assignments/m20/updated modules/16.1 BST/BinarySearchTree.java
|
UTF-8
| 2,964
| 4.0625
| 4
|
[] |
no_license
|
/**
* Class for binary search tree.
* @param <Key> The key
* @param <Value> The values
*/
class BinarySearchTree<Key extends Comparable<Key>, Value> {
/**.
* starting element in the BST.
*/
private Node root;
/**.
* Class for node.
*/
class Node {
/**.
* Object of Book class with book details.
*/
private Key key;
/**.
* value of the book in Book class
*/
private Value value;
/**.
* Left and Right node of the BST
*/
private Node left, right;
/**.
* Constructs the object.
*
* @param k The key 1
* @param v The value
*/
Node(final Key k, final Value v) {
key = k;
value = v;
}
}
/**.
* This method is to add a key and value to BST.
* Time Complexity is O(N).
* because it calls another put method to add elements.
*
* @param key The key
* @param value The value
*/
public void put(final Key key, final Value value) {
if (key == null) {
return;
}
root = put(root, key, value);
}
/**.
* This method is to add element to BST
* Time Complexity is O(N) for worst case.
* element is added until it reaches to the
* position it should added at.
*
* @param node The node
* @param key The key
* @param value The value
*
* @return returns node
*/
public Node put(final Node node, final Key key,
final Value value) {
if (node == null) {
return new Node(key, value);
}
int cmp = key.compareTo(node.key);
if (cmp < 0) {
node.left = put(node.left, key, value);
} else if (cmp > 0) {
node.right = put(node.right, key, value);
} else {
node.value = value;
}
return node;
}
/**.
* This method is to return the value of that key
* Time Complexity is O(N)
*
* @param key The key
*
* @return returns the value.
*/
public Value get(final Key key) {
return get(root, key);
}
/**.
* This method is to return the value of that key
* Time Complexity is O(N)
*
* @param node the node where the book details and
* values.
* @param key The key
*
* @return returns the value of that key.
*/
private Value get(final Node node, final Key key) {
if (node == null) {
return null;
}
int cmp = key.compareTo(node.key);
if (cmp < 0) {
return get(node.left, key);
} else if (cmp > 0) {
return get(node.right, key);
} else {
return node.value;
}
}
}
| true
|
99c20f7398764dd24c8d3d06e4045694bbfe663a
|
Java
|
ggthjew4/Java-Hibernate-Design
|
/fackernate/src/main/java/practice/fackernate/SqlCreator.java
|
UTF-8
| 722
| 2
| 2
|
[] |
no_license
|
package practice.fackernate;
import practice.fackernate.mapping.MappingObject;
public interface SqlCreator {
/**
* insert into ${tableName} (${column}, ${column}..) values(?, ?..)
* @return
*/
String createSaveSql(MappingObject obj);
/**
* update ${tableName}
* set ${column} = ?, ${column} = ?
* where ${id} = ?
* @return
*/
String createUpdateSql(MappingObject obj);
/**
* delete from ${tableName{
* where ${id} = ?
* @param clazz
* @return
*/
String createDeleteSql(MappingObject obj);
/**
* select $[column}, ${column} from ${tableName}
* where ${id} = ?
* @param clazz
* @return
*/
String createGetSql(MappingObject obj);
}
| true
|
280477593bfff3f0f4649dd7c5c2fdadf6cb2aed
|
Java
|
01tanmay/Cogni-workspaces
|
/myworkspace/spring-demo/src/com/demo/anything/TestClass.java
|
UTF-8
| 179
| 2.171875
| 2
|
[] |
no_license
|
package com.demo.anything;
public class TestClass {
public static void main(String[] args) {
MyMath myMath = new MyMath();
System.out.println(myMath.divide(4, 4));
}
}
| true
|
3f8d1b3a29c81bb13310b2b294a4a2288e9e9317
|
Java
|
MagdaToczek/library
|
/src/main/java/com/library/library/service/DbService.java
|
UTF-8
| 1,095
| 2.34375
| 2
|
[] |
no_license
|
package com.library.library.service;
import com.library.library.domain.Book;
import com.library.library.domain.CopyOfBook;
import com.library.library.repository.LibraryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class DbService {
@Autowired
private LibraryRepository repository;
public List<Book> getBooks() {
return repository.findAll();
}
public Book saveBook(final Book book) {
return repository.save(book);
}
public void deleteBook(final Long id) {
repository.deleteById(id);
}
public List<Book> getBooksByAuthor(final String author) { return repository.findBookByAuthorIsContaining(author);}
public List<Book> getBooksByTitle(final String title) { return repository.findBookByTitleContaining(title);}
public CopyOfBook saveCopyOfBook(final CopyOfBook copyOfBook) { return repository.save(copyOfBook);}
public void deleteCopyOfBook(final Long id) {
repository.deleteById(id);
}
}
| true
|
b2056d59b3817d1ed17382e75da97ec08987b977
|
Java
|
Yasko1/JavaWeb
|
/Task3/src/by/javatraining/task3/exception/GeneralException.java
|
UTF-8
| 482
| 2.953125
| 3
|
[] |
no_license
|
package by.javatr.task3.exception;
/** General exception
* exception in our task
* can use as wrapper
*/
public class GeneralException extends Exception{
/**
* Class has 4 constructors
*/
public GeneralException(){}
public GeneralException(String message){
super(message);
}
public GeneralException(String message, Throwable e){
super(message,e);
}
public GeneralException(Throwable e) { super(e);}
}
| true
|
63a4fc7ec9b3cd9128391ba7fe55f813db3e9719
|
Java
|
yanyufeng89/plusJob
|
/src/main/java/com/jobplus/service/ISitesService.java
|
UTF-8
| 1,104
| 1.820313
| 2
|
[] |
no_license
|
package com.jobplus.service;
import com.jobplus.pojo.Sites;
import com.jobplus.pojo.MyCollect;
import com.jobplus.pojo.Page;
public interface ISitesService {
/**
* //同时 插入一条站点分享记录
* @param record
* @return
*/
int insertSiteAndSiteShare(Sites record);
/**
* 我分享的站点列表
* @param record
* @return
*/
Page<Sites> getSharedSiteList(Sites record);
/**
* 我收藏的站点列表
* @param record
* @return
*/
Page<Sites> getCollectedSiteList(Sites record);
/**
* 批量删除个人中心-我分享的站点
* @param conditions
* @return
*/
int delSharedSites(String conditions[]);
/**
* 获取站点详情 浏览数++
* @param record
* @return
*/
Sites getSiteDetail(Sites record);
MyCollect collectSite(MyCollect record);
int deleteByPrimaryKey(Integer id);
int insert(Sites record);
int insertSelective(Sites record);
Sites selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(Sites record);
int updateByPrimaryKeyWithBLOBs(Sites record);
int updateByPrimaryKey(Sites record);
}
| true
|
98892e2557d1d7113aec93736ad2065bf52d6b0d
|
Java
|
AananR/Math-Practice-App
|
/app/src/main/java/com/lab1/seg/simplepracticetestapp/MultiplicationQuestions.java
|
UTF-8
| 6,725
| 2.71875
| 3
|
[] |
no_license
|
package com.lab1.seg.simplepracticetestapp;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
public class MultiplicationQuestions extends AppCompatActivity {
private LinearLayout mLayout;
private EditText mEditText;
private Button mButton;
private TextView text;
//This will keep track of whats correct
int correct = 0;
int answer = 0;
int numQuestion = 0;
int percentageCorrect=50;
int counter= 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_multiplication_questions);
Bundle extras = getIntent().getExtras();
if (extras != null) {
numQuestion = extras.getInt("numQuestions");
percentageCorrect = extras.getInt("percentage");
counter = numQuestion;}
//We are just fetching the components for the xml
mLayout = (LinearLayout) findViewById(R.id.linearLayout);
mEditText = (EditText) findViewById(R.id.editText);
mButton = (Button) findViewById(R.id.button6);
text = (TextView) findViewById(R.id.textView45);
mEditText.setOnKeyListener(new View.OnKeyListener()
{
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER)) {
// Perform action on key press
mButton.performClick();
return true;
}
return false;
}
});
mButton.setOnClickListener(onClick());
//we call the math function on the on create for the first question
math();
}
//the onclick decrements the counter for turns as well as keeps track of the number of correct
private View.OnClickListener onClick() {
return new View.OnClickListener() {
@Override
public void onClick(View v) {
//my validation that the user is actually inputting an integer and positive
if( mEditText.getText().toString().length() == 0 ){
mEditText.setError( "A positive integer is required!" );}else{
try{
counter = counter-1;
int userAns = Integer.parseInt(mEditText.getText().toString());
if(userAns == answer){
correct=correct+1;
new AlertDialog.Builder(MultiplicationQuestions.this)
.setTitle("Correct")
.setMessage("You got it right!")
// Specifying a listener allows you to take an action before dismissing the dialog.
// The dialog is automatically dismissed when a dialog button is clicked.
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Continue with delete operation
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}else{
new AlertDialog.Builder(MultiplicationQuestions.this)
.setTitle("Incorrect")
.setMessage("You got it wrong!")
// Specifying a listener allows you to take an action before dismissing the dialog.
// The dialog is automatically dismissed when a dialog button is clicked.
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Continue with delete operation
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
//resetting the text box so it is empty
mEditText.setText("");
if(counter>0){
math();
}else{
//if the number of questions is complete we open a new activity that will show the user how they did
Intent i = new Intent(MultiplicationQuestions.this, SolutionPage.class);
//we are passing the variables here
i.putExtra("correct", correct);
i.putExtra("numQuestion", numQuestion );
i.putExtra("percentageCorrect", percentageCorrect);
startActivity(i);
}}catch (NumberFormatException e){
//have to increment again because of the try
counter = counter+1;
mEditText.setError( "A positive integer is required!" );
}}
}
};
}
//this function will set the question
public void math(){
//final LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
//final TextView textView = new TextView(this);
//textView.setLayoutParams(lparams);
text.setText("");
String question = MultiplicationQuestion();
text.setText("" + question);
//mLayout.addView(text);
}
//this function creates the questions
public String MultiplicationQuestion(){
int firstInt = (int) ((Math.random()*100)+1);
int secondInt = (int) ((Math.random()*100)+1);
answer = firstInt*secondInt;
String question = firstInt+" x "+secondInt+"=";
return question;
}
}
| true
|
5400138f92df8ad3a6cc15782897b9e131de45a2
|
Java
|
ren19890419/lvxing
|
/src/main/java/p655io/reactivex/internal/operators/maybe/MaybeToFlowable.java
|
UTF-8
| 392
| 1.710938
| 2
|
[] |
no_license
|
package p655io.reactivex.internal.operators.maybe;
import p655io.reactivex.Flowable;
import p655io.reactivex.MaybeSource;
/* renamed from: io.reactivex.internal.operators.maybe.a */
public final class MaybeToFlowable<T> extends Flowable<T> {
/* renamed from: b */
final MaybeSource<T> f27507b;
public MaybeToFlowable(MaybeSource<T> hVar) {
this.f27507b = hVar;
}
}
| true
|
5dd2febcf7a34357333be2c1d3ae5d35a83f59b0
|
Java
|
Doublefuck/securit
|
/src/main/java/com/mmall/common/RequestHolder.java
|
UTF-8
| 1,211
| 2.9375
| 3
|
[] |
no_license
|
package com.mmall.common;
import com.mmall.model.SysUser;
import javax.servlet.http.HttpServletRequest;
/**
* 将request中的信息放入到ThreadLocal中
* ThreadLocL相当于一个Map,其中的key对应的是当前线程
* Created by Administrator on 2018/3/3 0003.
*/
public class RequestHolder {
// 将用户信息存入到ThreadLocal中
private static final ThreadLocal<SysUser> userHolder = new ThreadLocal<SysUser>();
//将请求存入到ThreadLocal中
private static final ThreadLocal<HttpServletRequest> requestHolder = new ThreadLocal<HttpServletRequest>();
// 存放
public static void add(SysUser sysUser){
userHolder.set(sysUser); // 放入到ThreadLocal中
}
public static void add(HttpServletRequest request){
requestHolder.set(request); // 放入到ThreadLocal中
}
// 获取
public static SysUser getCurrentUser(){
return userHolder.get();
}
public static HttpServletRequest getCurrentRequest(){
return requestHolder.get();
}
// 销毁
public static void remove(){
userHolder.remove();
requestHolder.remove();
}
}
| true
|
34e4feece0b9dc9caba5d79c59ad77be2b0a97c0
|
Java
|
matthewglover/EchoServer
|
/src/main/java/Pipeable.java
|
UTF-8
| 651
| 2.890625
| 3
|
[] |
no_license
|
import java.io.IOException;
import java.util.Observable;
import java.util.Observer;
public abstract class Pipeable extends Observable implements Observer {
@Override
public void update(Observable o, Object arg) {
try {
onData((String) arg);
} catch(Exception e) {
throw new RuntimeException(e.getMessage());
}
}
public void onData(String data) throws IOException {
}
public void emitData(String data) {
setChanged();
notifyObservers(data);
}
public Pipeable pipeTo(Pipeable receiver) {
addObserver(receiver);
return receiver;
}
}
| true
|
08c6918cbe9f9be063af3832c2ec9308f5069fc7
|
Java
|
Finden-Labs/Android
|
/Braintree-Payments/ClientTokenData.java
|
UTF-8
| 704
| 2.390625
| 2
|
[] |
no_license
|
package com.pranjal;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class ClientTokenData {
@SerializedName("client_token")
@Expose
private String clientToken;
/**
*
* @return
* The clientToken
*/
public String getClientToken() {
return clientToken;
}
/**
*
* @param clientToken
* The client_token
*/
public void setClientToken(String clientToken) {
this.clientToken = clientToken;
}
public ClientTokenData withClientToken(String clientToken) {
this.clientToken = clientToken;
return this;
}
}
| true
|
97e1cd36fe1bf623ae5f58a647149ffe9b29eadb
|
Java
|
fcambarieri/rest-api-framework
|
/src/main/java/com/ml/project/api/core/controllers/PingController.java
|
UTF-8
| 820
| 2.125
| 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.ml.project.api.core.controllers;
import com.ml.project.api.core.services.MetricsService;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.inject.Inject;
/**
*
* @author fcambarieri
*/
public class PingController extends AbstractController {
@Inject MetricsService metricsService;
public void ping() {
try {
response.setStatus(200);
response.getWriter().write("pong");
} catch (IOException ex) {
Logger.getLogger(PingController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
| true
|
9b0cc42c41c8bdd6a0b0c521985358015caca943
|
Java
|
Ning1253/redstone-multimeter-fabric
|
/src/main/java/rsmm/fabric/server/ServerLogManager.java
|
UTF-8
| 2,171
| 2.296875
| 2
|
[
"MIT"
] |
permissive
|
package rsmm.fabric.server;
import net.minecraft.nbt.NbtCompound;
import net.minecraft.nbt.NbtList;
import rsmm.fabric.common.Meter;
import rsmm.fabric.common.TickPhase;
import rsmm.fabric.common.event.EventType;
import rsmm.fabric.common.event.MeterEvent;
import rsmm.fabric.common.log.LogManager;
import rsmm.fabric.common.network.packets.MeterLogsPacket;
public class ServerLogManager extends LogManager {
private final ServerMeterGroup meterGroup;
private int nextSubTick;
public ServerLogManager(ServerMeterGroup meterGroup) {
this.meterGroup = meterGroup;
}
@Override
protected ServerMeterGroup getMeterGroup() {
return meterGroup;
}
@Override
protected long getLastTick() {
return meterGroup.getMultimeter().getMultimeterServer().getMultimeter().getCurrentTick();
}
@Override
public void clearLogs() {
super.clearLogs();
nextSubTick = 0;
}
public void tick() {
nextSubTick = 0;
}
public void logEvent(Meter meter, EventType type, int metaData) {
if (!meter.isMetering(type)) {
return;
}
long tick = getLastTick();
int subTick = nextSubTick++;
TickPhase phase = meterGroup.getMultimeter().getCurrentTickPhase();
MeterEvent event = new MeterEvent(type, tick, subTick, phase, metaData);
meter.getLogs().add(event);
}
public void flushLogs() {
if (nextSubTick == 0) {
return;
}
NbtList list = new NbtList();
for (Meter meter : meterGroup.getMeters()) {
if (meter.getLogs().isEmpty()) {
continue;
}
long id = meter.getId();
NbtCompound logs = meter.getLogs().toNBT();
NbtCompound nbt = new NbtCompound();
nbt.putLong("id", id);
nbt.put("logs", logs);
nbt.putBoolean("powered", meter.isPowered());
nbt.putBoolean("active", meter.isActive());
list.add(nbt);
meter.getLogs().clear();
}
if (list.isEmpty()) {
return;
}
NbtCompound nbt = new NbtCompound();
nbt.putInt("subTickCount", nextSubTick);
nbt.put("logs", list);
MeterLogsPacket packet = new MeterLogsPacket(nbt);
meterGroup.getMultimeter().getMultimeterServer().getPacketHandler().sendPacketToPlayers(packet, meterGroup.getSubscribers());
}
}
| true
|
d2ba966d547623f5cbbff8178c45361d8d8e6be4
|
Java
|
wsws0521/IDEA-Vincent-MyJavaTools
|
/HexWebserviceTest/src/cn/vincent/xmlvend/client/MeterFaultReport.java
|
GB18030
| 1,631
| 2.046875
| 2
|
[] |
no_license
|
package cn.vincent.xmlvend.client;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
*
* A generic meter fault report, must be extended.
*
*
* <p>MeterFaultReport complex type Java ࡣ
*
* <p>ģʽƬָڴеԤݡ
*
* <pre>
* <complexType name="MeterFaultReport">
* <complexContent>
* <extension base="{http://www.nrs.eskom.co.za/xmlvend/meter/2.1/schema}CustFaultReport">
* <sequence>
* <element name="meterInfo" type="{http://www.nrs.eskom.co.za/xmlvend/base/2.1/schema}VendIDMethod"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "MeterFaultReport", namespace = "http://www.nrs.eskom.co.za/xmlvend/meter/2.1/schema", propOrder = {
"meterInfo"
})
public class MeterFaultReport
extends CustFaultReport
{
@XmlElement(required = true)
protected VendIDMethod meterInfo;
/**
* ȡmeterInfoԵֵ
*
* @return
* possible object is
* {@link VendIDMethod }
*
*/
public VendIDMethod getMeterInfo() {
return meterInfo;
}
/**
* meterInfoԵֵ
*
* @param value
* allowed object is
* {@link VendIDMethod }
*
*/
public void setMeterInfo(VendIDMethod value) {
this.meterInfo = value;
}
}
| true
|
b48c3ed1667d271da9edb258cb11c1bda6261853
|
Java
|
mazhaohui0710/cool-framework
|
/eiff-framework-log-parent/eiff-framework-log-cat/src/main/java/com/eiff/framework/log/cat/client/hug/TransactionHug.java
|
UTF-8
| 1,353
| 2.1875
| 2
|
[] |
no_license
|
package com.eiff.framework.log.cat.client.hug;
import java.util.Map;
import com.eiff.framework.log.api.HdLogger;
import com.eiff.framework.log.api.trace.Span;
import com.eiff.framework.log.api.trace.Tracer;
public class TransactionHug<V> {
private static HdLogger LOGGER = HdLogger.getLogger(TransactionHug.class);
private String type;
private String name;
Map<String, String> catContext;
Tracer tracer;
public TransactionHug(String type, String name) {
this.type = type;
this.name = name;
this.tracer = LOGGER.buildTracer();
catContext = this.tracer.getContext();
}
public TransactionHug() {
this.tracer = LOGGER.buildTracer();
catContext = this.tracer.getContext();
}
public V action(TransactionHugAction<V> action) throws Throwable {
this.tracer.buildContext(catContext, false);
Span span = this.tracer.createSpan(this.type, this.name);
LOGGER.logTraceInfoTMDC();
try {
V returnValue = action.work();
span.success();
return returnValue;
} catch (Throwable ex) {
span.failed(ex.getClass().getName());
throw ex;
} finally {
span.close();
LOGGER.cleanTraceInfoInMDC();
}
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| true
|
b47898f87d2181718c86d13572754b198dbae7b6
|
Java
|
tboqi/tbqapps
|
/javaApps/cw/src/java/message/com/cc/cw/dao/BroadcastDAO.java
|
UTF-8
| 731
| 2.15625
| 2
|
[] |
no_license
|
package com.cc.cw.dao;
import java.util.List;
import java.util.Map;
import com.cc.cw.domain.Broadcast;
public interface BroadcastDAO {
/** 发布一条新广播 */
public int add(Broadcast broadcast);
/** 根据发布时间倒序取的广播 实现分页 */
public List<Broadcast> getBroadcastOrderByDate(int start, int count);
public List<Broadcast> getBroadcastOrderByDate(String string, String key, int start, int count);
public List<Broadcast> getBroadcastOrderByDate(Map<String, Object> map, int start, int count);
public int getCount(String string, String key);
public int getCount(Map<String, Object> map);
public int getCount();
public void deleteByIds(String ids);
public Broadcast get(int id);
}
| true
|
ae8f35bb49a7163cc709cfb42fde6c5bf2508b65
|
Java
|
sultaniyad/CallMe
|
/app/src/main/java/com/iyad/sultan/callme/Controller/Adapter.java
|
UTF-8
| 2,555
| 2.4375
| 2
|
[] |
no_license
|
package com.iyad.sultan.callme.Controller;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.iyad.sultan.callme.Model.Contacts;
import com.iyad.sultan.callme.R;
import io.realm.RealmResults;
/**
* Created by salkhmis on 10/24/2016.
*/
public class Adapter extends RecyclerView.Adapter<Adapter.myViewHolder> {
//Interface
public interface ItemClickCallback {
void onImgPhoneClicked(String phoneNumber);
}
private ItemClickCallback itemClickCallback;
private RealmResults<Contacts> contactsRealmResults;
public void setItemClickedCallback(ItemClickCallback callback) {
itemClickCallback = callback;
}
public Adapter(RealmResults<Contacts> c) {
contactsRealmResults = c;
}
public void setAdapterData(RealmResults<Contacts> data) {
contactsRealmResults = data;
}
@Override
public myViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.row_item, parent, false);
// set the view's size, margins, paddings and layout parameters
myViewHolder vh = new myViewHolder(v);
return vh;
}
@Override
public void onBindViewHolder(final myViewHolder holder, int position) {
final Contacts contacts = contactsRealmResults.get(position);
holder.txtName.setText(contacts.getName());
holder.txtNumber.setText(contacts.getNumber());
}
@Override
public int getItemCount() {
return contactsRealmResults.size();
}
public class myViewHolder extends RecyclerView.ViewHolder {
private TextView txtName;
private TextView txtNumber;
private ImageView imgCall;
public myViewHolder(View itemView) {
super(itemView);
txtName = (TextView) itemView.findViewById(R.id.txt_name);
txtNumber = (TextView) itemView.findViewById(R.id.txt_number);
imgCall = (ImageView) itemView.findViewById(R.id.icon_imageview);
imgCall.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
itemClickCallback.onImgPhoneClicked(contactsRealmResults.get(getAdapterPosition()).getNumber());
}
});
}
}
}
| true
|
70b4f13f76a52b49479a06c3bac74302f3ea696b
|
Java
|
OrAviv/mmn14
|
/src/q1/Cell.java
|
UTF-8
| 828
| 3.9375
| 4
|
[] |
no_license
|
package q1;
// This Class purpose is to act as a generic Node for q1.List Class implementation.
public class Cell <E>
{
// data parameter
private E data;
// next cell parameter.
private Cell nextCell;
// Constructor
public Cell(E data)
{
this.setData(data);
}
// Constructor #2 - Creates a Node with a data for the new node & the next node to be attached to.
public Cell(E data, Cell <E> nextCell)
{
this.setData(data);
this.setNextCell(nextCell);
}
public void setData(E newData)
{
this.data = newData;
}
public E getData()
{
return this.data;
}
public void setNextCell(Cell nextCell)
{
this.nextCell = nextCell;
}
public Cell getNextCell()
{
return this.nextCell;
}
}
| true
|
49c87af0fac4924a77e2d6c0424ca36055f78b04
|
Java
|
vogti/AVR-Remote
|
/AVR-Remote/src/de/marcovogt/avrremote/Info.java
|
UTF-8
| 2,431
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
package de.marcovogt.avrremote;
import java.awt.Font;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.JButton;
import javax.swing.JTextPane;
import javax.swing.UIManager;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.ImageIcon;
public class Info extends JPanel {
private static final long serialVersionUID = 1L;
private JLabel heading;
private JLabel lblIcon;
private JTextPane txtpnCredit;
private JTextPane txtpnVersion;
private JButton btnBack;
public Info(MainWindow window) {
setBounds(100, 100, 220, 385);
setLayout(null);
heading = new JLabel("AVR Remote");
heading.setBounds(10, 11, 200, 37);
heading.setHorizontalAlignment(SwingConstants.CENTER);
heading.setFont(new Font("Tahoma", Font.PLAIN, 30));
add(heading);
lblIcon = new JLabel("");
lblIcon.setIcon(new ImageIcon(Info.class.getResource("/de/marcovogt/avrremote/icon-small.png")));
lblIcon.setBounds(10, 59, 85, 84);
add(lblIcon);
txtpnVersion = new JTextPane();
txtpnVersion.setText("Version: \r\n1.5\r\n\r\nDate: 11.08.2015");
txtpnVersion.setFont(new Font("Tahoma", Font.PLAIN, 14));
txtpnVersion.setEditable(false);
txtpnVersion.setBackground(UIManager.getColor("ScrollBar.foreground"));
txtpnVersion.setBounds(105, 59, 105, 96);
add(txtpnVersion);
txtpnCredit = new JTextPane();
txtpnCredit.setEditable(false);
txtpnCredit.setFont(new Font("Tahoma", Font.PLAIN, 14));
txtpnCredit.setText("This Software was developed by\r\n\r\nMarco Vogt\r\nmarcovogt.de\r\n\r\nmail@marcovogt.de");
txtpnCredit.setBackground(UIManager.getColor("ScrollBar.foreground"));
txtpnCredit.setBounds(10, 178, 200, 153);
add(txtpnCredit);
// Center Text
StyledDocument doc = txtpnCredit.getStyledDocument();
SimpleAttributeSet center = new SimpleAttributeSet();
StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);
doc.setParagraphAttributes(0, doc.getLength(), center, false);
btnBack = new JButton("Back");
btnBack.setFont(new Font("Tahoma", Font.PLAIN, 14));
btnBack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
window.showMain();
}
});
btnBack.setBounds(10, 337, 200, 37);
add(btnBack);
}
}
| true
|
ac3e022f793e2618e179591feff2d1f94ea3ac57
|
Java
|
JuneXi/LC
|
/leetcode/src/company/google/TheSkyLineProblem2.java
|
UTF-8
| 1,069
| 3.03125
| 3
|
[] |
no_license
|
package company.google;
import java.util.ArrayList;
import java.util.List;
public class TheSkyLineProblem2 {
public List<int[]> getSkyline(int[][] buildings) {
ArrayList<int[]> res = new ArrayList<int[]>();
if(buildings == null || buildings.length == 0 || buildings[0] == null || buildings[0].length == 0){
return res;
}
int size = 0;
for(int i = 0; i < buildings.length; i++){
if(buildings[i][1] > size){
size = buildings[i][1];
}
}
int[] map = new int[size + 1];
for(int i = 0; i < buildings.length;i++){
for(int j = buildings[i][0]; j<= buildings[i][1]; j++){
map[j] = Math.max(buildings[i][2], map[j]);
}
}
int cur = 0;
for(int i = 0; i <=size; i++){
if(map[i] > cur){
cur = map[i];
res.add(new int[] {i,cur});
}else if(map[i] < cur){
cur = map[i];
res.add(new int[] {i - 1, cur});
}else;
}
res.add(new int[] {size, 0});
return res;
}
}
| true
|
e6c2309bd753b2cf8c7de23178a3c96fb1ec531f
|
Java
|
chaos-dd/videoSearch_java
|
/src/main/java/casia/isiteam/videosearch/slave/SlaveSearchHandler.java
|
UTF-8
| 2,466
| 2.375
| 2
|
[] |
no_license
|
package casia.isiteam.videosearch.slave;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import casia.isiteam.videosearch.protocol.Protocol;
import casia.isiteam.videosearch.protocol.Protocol.Request;
import casia.isiteam.videosearch.util.ProtocolParam;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
public class SlaveSearchHandler extends
SimpleChannelInboundHandler<Protocol.Request> {
@Override
protected void messageReceived(ChannelHandlerContext ctx, Request msg)
throws Exception {
// TODO Auto-generated method stub
switch (msg.getHead().getMethodType()) {
case ADD_VIDEO:
handleAdd(ctx, msg);
break;
case DELETE_VIDEO:
handleDelete(ctx, msg);
break;
case SEARCH_VIDEO:
handleSearch(ctx, msg);
break;
default:
break;
}
}
private void handleAdd(ChannelHandlerContext ctx, Request msg){
}
private void handleDelete(ChannelHandlerContext ctx, Request msg){
}
private void handleSearch(ChannelHandlerContext ctx, Request msg) throws FileNotFoundException{
//ctx.pipeline().addFirst("fileTransfer",new ChunkedWriteHandler());
String context=msg.getBody().getContext();
String [] strs=ProtocolParam.seperator.split(context);
if(strs.length <=2){
}
String fileName=strs[0];
long fileSize=Long.parseLong(strs[1]);
ctx.pipeline().addFirst(new ChunkedReadHandler(fileName, fileSize));
}
}
class ChunkedReadHandler extends ChannelHandlerAdapter{
private long fileSize;
private File file;
private FileOutputStream ofs;
private long readedSize=0;
public ChunkedReadHandler(String fileName, long fileSize) throws FileNotFoundException{
this.fileSize=fileSize;
this.file = new File(fileName);
ofs=new FileOutputStream(this.file);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf buf= (ByteBuf) msg;
readedSize +=buf.readableBytes();
if(buf.isReadable()){
byte[] bytes=new byte[buf.readableBytes()];
buf.readBytes(bytes);
ofs.write(bytes);
}
if(readedSize >= fileSize){
ctx.pipeline().remove(this);
ofs.flush();
ofs.close();
System.out.println("close file");
}
buf.release();
}
}
| true
|
4e3f6ca27b93a8249c8fe7c9e2aecdcc95d5958a
|
Java
|
gauravt1996/Learning-Portal
|
/Code/src/gt/model/Subject.java
|
UTF-8
| 855
| 2.125
| 2
|
[] |
no_license
|
package gt.model;
public class Subject {
private String coid;
private String bid;
private String sid;
private String sname;
private String sicon;
private String sdesc;
public String getCoid() {
return coid;
}
public void setCoid(String coid) {
this.coid = coid;
}
public String getBid() {
return bid;
}
public void setBid(String bid) {
this.bid = bid;
}
public String getSid() {
return sid;
}
public void setSid(String sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getSicon() {
return sicon;
}
public void setSicon(String sicon) {
this.sicon = sicon;
}
public String getSdesc() {
return sdesc;
}
public void setSdesc(String sdesc) {
this.sdesc = sdesc;
}
}
| true
|
d0ed5ca19381a1441bb43fcf37ab7e0907eb2a49
|
Java
|
easemeng/java
|
/workspace/day04/src/com/igeek/string/StringTest2.java
|
GB18030
| 638
| 3.78125
| 4
|
[] |
no_license
|
package com.igeek.string;
public class StringTest2 {
public static void main(String[] args) {
String str1 = "hello";
//charAt ʾָ± ±Ӧַ
char c = str1.charAt(0);
System.out.println(c);
//equalsжֵַǷ ==
boolean flag = str1.equals("hello");
System.out.println(flag);
boolean flag2 = str1.equalsIgnoreCase("HeLLO");
System.out.println(flag2);
boolean flag3 = str1.startsWith("he");
System.out.println(flag3);
boolean flag4= str1.endsWith("dd");
System.out.println(flag4);
}
}
| true
|
80188dee7fb1f18251566bdfcf4823e9a7f023c8
|
Java
|
Lupicus/EnameledArmor
|
/src/main/java/com/lupicus/ea/data/EAModelProvider.java
|
UTF-8
| 4,644
| 1.796875
| 2
|
[
"MIT"
] |
permissive
|
package com.lupicus.ea.data;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import com.lupicus.ea.Main;
import com.lupicus.ea.item.EAArmorItem;
import com.lupicus.ea.item.ModItems;
import net.minecraft.data.PackOutput;
import net.minecraft.data.models.ItemModelGenerators;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.ArmorMaterial;
import net.minecraft.world.item.ArmorMaterials;
import net.minecraft.world.item.Item;
import net.minecraftforge.client.model.generators.ItemModelBuilder;
import net.minecraftforge.client.model.generators.ItemModelBuilder.OverrideBuilder;
import net.minecraftforge.client.model.generators.ItemModelProvider;
import net.minecraftforge.client.model.generators.ModelBuilder;
import net.minecraftforge.client.model.generators.ModelFile;
import net.minecraftforge.common.data.ExistingFileHelper;
import net.minecraftforge.registries.ForgeRegistries;
public class EAModelProvider extends ItemModelProvider
{
private static final List<TrimModelData> GENERATED_TRIM_MODELS = List.of(
new TrimModelData("quartz", 0.1F, Map.of()),
new TrimModelData("iron", 0.2F, Map.of(ArmorMaterials.IRON, "iron_darker")),
new TrimModelData("netherite", 0.3F, Map.of(ArmorMaterials.NETHERITE, "netherite_darker")),
new TrimModelData("redstone", 0.4F, Map.of()),
new TrimModelData("copper", 0.5F, Map.of()),
new TrimModelData("gold", 0.6F, Map.of(ArmorMaterials.GOLD, "gold_darker")),
new TrimModelData("emerald", 0.7F, Map.of()),
new TrimModelData("diamond", 0.8F, Map.of(ArmorMaterials.DIAMOND, "diamond_darker")),
new TrimModelData("lapis", 0.9F, Map.of()),
new TrimModelData("amethyst", 1.0F, Map.of()));
private Field fTextures = null;
public EAModelProvider(PackOutput output, ExistingFileHelper existingFileHelper)
{
super(output, Main.MODID, existingFileHelper);
try {
fTextures = ModelBuilder.class.getDeclaredField("textures");
fTextures.setAccessible(true);
}
catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void registerModels()
{
add(ModItems.EA_HELMET);
add(ModItems.EA_CHESTPLATE);
add(ModItems.EA_LEGGINGS);
add(ModItems.EA_BOOTS);
add(ModItems.EA_IRON_HELMET);
add(ModItems.EA_IRON_CHESTPLATE);
add(ModItems.EA_IRON_LEGGINGS);
add(ModItems.EA_IRON_BOOTS);
add(ModItems.EA_CHAINMAIL_HELMET);
add(ModItems.EA_CHAINMAIL_CHESTPLATE);
add(ModItems.EA_CHAINMAIL_LEGGINGS);
add(ModItems.EA_CHAINMAIL_BOOTS);
add(ModItems.EA_NETHERITE_HELMET);
add(ModItems.EA_NETHERITE_CHESTPLATE);
add(ModItems.EA_NETHERITE_LEGGINGS);
add(ModItems.EA_NETHERITE_BOOTS);
}
private void add(Item item)
{
if (item instanceof EAArmorItem)
{
EAArmorItem armor = (EAArmorItem) item;
ResourceLocation key = ForgeRegistries.ITEMS.getKey(armor);
makeTrims(armor, key);
ItemModelBuilder b = getBuilder(key.getPath());
basic(b, key);
// overrides
for (TrimModelData trim : GENERATED_TRIM_MODELS)
{
OverrideBuilder ob = b.override();
ob.model(getTrimBuilder(armor, key, trim));
ob.predicate(ItemModelGenerators.TRIM_TYPE_PREDICATE_ID, trim.itemModelIndex());
}
}
}
private ItemModelBuilder getTrimBuilder(EAArmorItem armor, ResourceLocation key, TrimModelData trim)
{
return getBuilder(key.getPath() + "_" + trim.name(armor.getMaterial()) + "_trim");
}
private void makeTrims(EAArmorItem armor, ResourceLocation key)
{
for (TrimModelData trim : GENERATED_TRIM_MODELS)
{
ItemModelBuilder b = getTrimBuilder(armor, key, trim);
basic(b, key);
Map<String, String> textures = getTextures(b);
textures.put("layer2", "minecraft:trims/items/" + armor.getType().getName() + "_trim_" + trim.name(armor.getMaterial()));
}
}
private void basic(ItemModelBuilder b, ResourceLocation key)
{
b.parent(new ModelFile.UncheckedModelFile("item/generated"));
String path = ITEM_FOLDER + "/" + key.getPath();
b.texture("layer0", path);
b.texture("layer1", path+ "_overlay");
}
@SuppressWarnings("unchecked")
private Map<String, String> getTextures(ItemModelBuilder b)
{
Map<String, String> ret = null;
try {
ret = (Map<String, String>) fTextures.get(b);
}
catch (Exception e) {
e.printStackTrace();
}
return ret;
}
static record TrimModelData(String name, float itemModelIndex, Map<ArmorMaterial, String> overrideArmorMaterials) {
public String name(ArmorMaterial mat) {
return this.overrideArmorMaterials.getOrDefault(mat, this.name);
}
}
}
| true
|
72c2c3ba95af6b880d995066f74b5d31b7eee14e
|
Java
|
ardeliaraminta/OOPFinalProject
|
/src/oopfinal/MainStaff.java
|
UTF-8
| 8,370
| 3.21875
| 3
|
[] |
no_license
|
package oopfinal;
import java.io.*;
import java.util.Scanner;
class MainStaff {
private static Scanner input;
public static void staff() {
// staff main menu ( register or login )
input = new Scanner(System.in);
System.out.println(" ------------------------------------");
System.out.println("\n\t\t\tStaff");
System.out.println(" ------------------------------------");
System.out.println("1)Register");
System.out.println("2)Login");
System.out.println();
System.out.println("Enter Choice : ");
int option = input.nextInt();
switch (option) {
case 1 -> staffRegister();
case 2 -> staffLogin();
default -> {
System.out.println("invalid choice !");
staff();
}
}
}
//new staff register
private static void staffRegister() {
try {
// create a file for the details of teh staff and staff verification
Scanner scan = new Scanner(System.in);
File staff = new File("staff.txt");
File custlog = new File("staffLog.txt");
BufferedWriter staffBW = new BufferedWriter(new FileWriter("staff.txt", true));
BufferedWriter logbw = new BufferedWriter(new FileWriter("staffLog.txt", true));
ClinicStaff st = new ClinicStaff();
if (staff.createNewFile()) {
} else {
staffBW.newLine();
}
if (custlog.createNewFile()) {
} else {
logbw.newLine();
}
// enter staff details
System.out.println("Enter your ID: ");
st.setStaffID(Integer.parseInt(scan.nextLine()));
System.out.println("Enter your Name: ");
st.setStaffName(scan.nextLine());
System.out.println("Enter your Email: ");
st.setStaffEmail(scan.nextLine());
System.out.println("Enter your Password: ");
st.setStaffPassword(scan.nextLine());
System.out.println("Enter your phone number: ");
st.setStaffPhoneNumber(Integer.parseInt(scan.nextLine()));
System.out.println("Status: Full-Time / Part-Time");
st.setStaffStatus(scan.nextLine());
// write in the txt
staffBW.write(st.getStaffID() + "\t" + st.getStaffName() + "\t" + st.getStaffEmail() + "\t" + st.getStaffPassword() + "\t" + st.getStaffPhoneNumber()+ "\t" + st.getStaffStatus());
logbw.write(st.getStaffID() + "\t" + st.getStaffPassword());
staffBW.close();
logbw.close();
System.out.println("\nSuccessfully wrote to the file.\n");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
private static void staffLogin() {
String password, line;
String id;
System.out.println("\t__________________________________");
System.out.println("\t| | LOGIN | |");
System.out.println("\t__________________________________");
System.out.println();
System.out.println("\tEnter your Staff ID: ");
id = input.next();
System.out.println("\tEnter your Password: ");
password = input.next();
try {
// to read a file staffLog for login verification
BufferedReader br = new BufferedReader(new FileReader("staffLog.txt"));
boolean authenticated = false;
// when the text file is not empty split text by tab
while ((line = br.readLine()) != null) {
String[] text = line.split("\t");
// if the first index = id entered or registered and second index = password
// proceed open staff menu
if (text[0].equals(id) && text[1].equals(password)) {
// if the data matched open staff menu
authenticated = true;
Main.setStaffID(id);
staffMenu();
}
}
//if either doesn't match
if (!authenticated) {
System.out.println("Wrong Password");
}
br.close();
} catch (IOException ex) {
System.out.println("File Not Found");
}
}
// option for the staff menu
public static void staffMenu() {
System.out.println(" Menu ");
System.out.println("--------------------------------");
System.out.println(" 1) View User Profile");
System.out.println(" 2) Cancel or Approve Appointment");
System.out.println();
System.out.println(" Enter choice :");
int options = input.nextInt();
switch (options) {
case 1 -> viewStaffProfile(); // to see the user profile
case 2 -> editAppointment(); // approve or decline incoming appointment from the customer
default -> {
System.out.println("Invalid Key!");
MainStaff.staff();
}
}
}
private static void editAppointment() {
try {
// scanner to read the file
Scanner appoint = new Scanner(new File("appointment.txt"));
StringBuilder buffer = new StringBuilder();
Scanner scan = new Scanner(System.in);
int count = 0;
// if there is data read per lines and split by tabs
while (appoint.hasNextLine()) {
String data = appoint.nextLine();
String[] text = data.split("\t");
// if the text file consist of 7 words it allows the staff to decline or accept the appointment
// to check if the data required is available
if (text.length == 8) {
System.out.println(data);
System.out.println("\nApprove/Reject: ");
String status = scan.next();
buffer.append(data).append("\t").append(status);
} else {
buffer.append(data);
}
count++;
if (count > 0) {
buffer.append("\n");
}
}
FileOutputStream output = new FileOutputStream("appointment.txt");
output.write(buffer.toString().getBytes());
output.close();
appoint.close();
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
// to see the details of the staff
private static void viewStaffProfile() {
try {
// to obtain the data
Scanner myReader = new Scanner(new File("staff.txt"));
// to split the words in the text file
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
String[] text = data.split("\t");
// if there is data containing the staff id, get the password and encrypt it ***** ( confidential )
if (data.contains(Main.getStaffID())) {
StringBuilder pwd = new StringBuilder();
for (int i = 0; i < text[1].length(); i++) {
pwd.append("*");
}
ClinicStaff staff = new ClinicStaff(Integer.parseInt(text[0]), text[1], text[2], text[3], Integer.parseInt(text[4]));
// print the staff details
System.out.println("\n\n\tProfile Data\n");
System.out.println("ID\t: " + staff.getStaffID());
System.out.println("Name\t: " + staff.getStaffName());
System.out.println("Email\t\t: " + staff.getStaffEmail());
System.out.println("Phone Number\t: 0" + staff.getStaffPhoneNumber());
System.out.println("Password\t: " + pwd);
}
}
System.out.println("\n\n");
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
| true
|
338e07531f6023d76bcfeb1154f4f6d52643c763
|
Java
|
jpmpassos/projetojsonbpostgresql
|
/src/main/java/br/com/medinapassos/base/dao/ClienteDAO.java
|
UTF-8
| 517
| 1.929688
| 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 br.com.medinapassos.base.dao;
import br.com.medinapassos.base.Cliente;
import java.util.List;
/**
*
* @author João Paulo
*/
public interface ClienteDAO {
public void salvar(Cliente cliente);
public void excluir(Cliente cliente);
public Cliente carregar(Integer codigo);
public List<Cliente> listar();
}
| true
|
73e51f03509ac10fd33eabc8762f444de124771b
|
Java
|
agermenos/codeFights
|
/src/com/sleepsoft/challenges/leetcode/ThreeSum.java
|
UTF-8
| 1,229
| 2.984375
| 3
|
[] |
no_license
|
package com.sleepsoft.challenges.leetcode;
import org.junit.jupiter.api.Test;
import java.util.*;
import java.util.stream.Collectors;
class ThreeSum {
public List<List<Integer>> threeSum(int[] nums) {
List<Integer>numList = Arrays.stream(nums).boxed().collect(Collectors.toList());
Set<List<Integer>> returnValues = new HashSet<>();
for (int k=0;k<nums.length-2;k++) {
for (int l=k+1;l<nums.length-1;l++) {
List<Integer> copyList = numList;
copyList.remove(k);
copyList.remove(l);
int c = -nums[k]-nums[l];
if (copyList.contains(c)) {
List<Integer> set = new ArrayList<>();
set.add(nums[k]);
set.add(nums[l]);
set.add(c);
Collections.sort(set);
returnValues.add (new ArrayList(set));
}
}
}
return new ArrayList(returnValues);
}
private void prepare(int[]sample, List<List<Integer>> expected){
}
@Test
public void test(){
int[] sample = new int[]{-1,0,1,2,-1,-4};
//List<List<Integer>> expected =
}
}
| true
|
8bddf046a265b48ac3b1a6fba8b03b255fc458e2
|
Java
|
aagalkin/Prog.Kiev
|
/Module2/Lesson2/Task3/IPhone5.java
|
UTF-8
| 229
| 2.21875
| 2
|
[] |
no_license
|
public class IPhone5 extends Phone{
public IPhone5(){
screenSize = 4;
imei = 3333333;
touch = true;
hasWifi = true;
name = "IPhone5";
sim = new SimCard(this);
}
}
| true
|
3f31626cd6ae9b24c6a348fcf074b5d0abcdb3dd
|
Java
|
tzbgithub/keqidao2
|
/qidao-api-service-dao/src/main/java/com/qidao/application/entity/organization/OrganizationDetail.java
|
UTF-8
| 805
| 1.617188
| 2
|
[] |
no_license
|
package com.qidao.application.entity.organization;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class OrganizationDetail {
private String name;
private String belong;
private String summary;
private String license;
private Integer status;
private String vipStartTime;
private String vipEndTime;
private String signTime;
private String addressDetail;
private String provinceName;
private String cityName;
private String areaName;
private String industryRemark;
private String backendImage;
private String scaleName;
private String label;
private String industry;
private Long scaleId;
}
| true
|
ffe9c7936946f679599f67bc778d93686c30299c
|
Java
|
harshp8l/deep-learning-lang-detection
|
/data/test/java/e0b9180cf24ef6b9df32d2cd42ec6035d9202936ProcessAmends.java
|
UTF-8
| 739
| 2.28125
| 2
|
[
"MIT"
] |
permissive
|
package org.bungeni.trackchanges.process.schema;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Ashok Hariharan
*/
public class ProcessAmends {
private List<ProcessAmend> processAmends = new ArrayList<ProcessAmend>(0);
/**
* @return the processAmends
*/
public List<ProcessAmend> getProcessAmends() {
return processAmends;
}
/**
* @param processAmends the processAmends to set
*/
public void setProcessAmends(List<ProcessAmend> processAmends) {
this.processAmends = processAmends;
}
public void addProcessAmend(ProcessAmend pAmend) {
this.processAmends.add(pAmend);
}
public void clear() {
this.processAmends.clear();
}
}
| true
|
32790e50ae43ccc816f6846809395bd8d80fc27d
|
Java
|
stanvanrooy/decompiled-instagram
|
/decompiled/instagram/sources/p000X/C031405q.java
|
UTF-8
| 1,427
| 1.90625
| 2
|
[] |
no_license
|
package p000X;
import android.content.Context;
import java.io.File;
import java.io.RandomAccessFile;
/* renamed from: X.05q reason: invalid class name and case insensitive filesystem */
public class C031405q extends C038208p {
/* JADX WARNING: Code restructure failed: missing block: B:11:0x0029, code lost:
r0 = move-exception;
*/
/* JADX WARNING: Code restructure failed: missing block: B:13:?, code lost:
r1.close();
*/
/* JADX WARNING: Missing exception handler attribute for start block: B:14:0x002d */
public final void A01(boolean z) {
if (!z) {
File file = this.A00;
AnonymousClass0FY.A00(file);
AnonymousClass0ZJ.A01(2147483648L, "AppUnpacker.fsync", -283075799);
try {
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
randomAccessFile.getFD().sync();
randomAccessFile.close();
AnonymousClass0ZJ.A00(2147483648L, -1677413782);
} catch (Throwable th) {
AnonymousClass0ZJ.A00(2147483648L, -1948416264);
throw th;
}
}
}
public final boolean A02(Context context, byte[] bArr) {
File file = this.A00;
AnonymousClass0FY.A00(file);
return !file.exists();
}
public C031405q(String str, String str2) {
super(str, str2);
}
}
| true
|
efe66af5f296dc5c8f2d20462eb58e047322999c
|
Java
|
learn-our-api/REST_API
|
/src/com/cxf/restapis/framework/diagnosis/util/LogManager.java
|
UTF-8
| 3,592
| 2.1875
| 2
|
[] |
no_license
|
package com.cxf.restapis.framework.diagnosis.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.cxf.restapis.framework.util.ValidationUtil;
/**
* <pre>
*
* Accela Automation
* File: LogManager.java
*
* Accela, Inc.
* Copyright (C): 2014
*
* Description:
* TODO
*
* Notes:
* $Id: LogManager.java 72642 2009-01-01 20:01:57Z ACHIEVO\tony.li $
*
* Revision History
* <Date>, <Who>, <What>
* Jul 2, 2014 tony.li Initial.
*
* </pre>
*/
public abstract class LogManager implements LogReader
{
public static String AAHome = null;
public static String AALog = null;
public final static String fileSplitor = "\\";
static{
// AAHome = AVProperties.getAAHome();
}
// private static AVLogger m_logger = AVLogger.getLogger(LogManager.class);
/**
*
* getLogReader
*
* @param type
* @return
* @throws Exception
*/
public static LogReader getLogReader(String type) throws Exception
{
if("BIZ".equals(type))
{
LogReader lr = new BizLogReader();
return lr;
}
else
{
throw new Exception("");
}
}
@Override
public List<String> getMatchedLog(String date,String traceID,int chunkSize) throws Exception
{
List<File> files = this.getLog(date);
if(!ValidationUtil.isEmpty(files))
{
return this.filterLog(files.get(0), traceID,chunkSize);
}
else
{
return null;
}
}
private boolean isWholeLine(String detail)
{
return detail.indexOf(" DEBUG ")>=0 ||detail.indexOf(" INFO ")>=0||detail.indexOf(" ERROR ")>=0||detail.indexOf(" WARN ")>=0 ;
}
private boolean matched(String intiLine, String traceID)
{
if (intiLine.indexOf(traceID) >= 0)
{
return true;
}
return false;
}
private List<String> filterLog(File file, String traceID,int chunkSize) throws IOException
{
List<String> list = new ArrayList<String>();
if(chunkSize <=0 || chunkSize > 500)
{
chunkSize = 100;
}
if(file.exists())
{
StringBuilder intiLine = null;
FileReader reader = null;
BufferedReader br = null;
try
{
Long start = System.nanoTime() ;
intiLine = new StringBuilder("");
reader = new FileReader(file);
br = new BufferedReader(reader);
String detail;
boolean matched = false;
int lineCount = 0;
int total = 0;
while ((detail = br.readLine()) != null)
{
total ++ ;
if (isWholeLine(detail))
{
if(matched(intiLine.toString(),traceID))
{
list.add(intiLine.toString());
}
intiLine = new StringBuilder(detail);
}
else
{
intiLine.append("\r\n");
intiLine.append(detail);
}
if (matched(intiLine.toString(), traceID) || matched)
{
if(lineCount >= chunkSize)
{
break;
}
if(!matched)
{
matched = true;
}
list.add(intiLine.toString());
lineCount ++;
}
}
// m_logger.info("Search traceId from biz log costed :" + (System.nanoTime()-start));
// m_logger.info("Searched rows :"+total );
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
finally
{
if(reader != null)
{
reader.close();
}
if(br != null)
{
br.close();
}
intiLine = null;
reader = null;
br = null;
}
}
return list;
}
}
/*
*$Log: av-env.bat,v $
*/
| true
|
7920c109d866b28b6bf462bdf7ccf115e35103a7
|
Java
|
przodownikR1/thymeleaf_kata
|
/src/test/java/pl/java/scalatech/RepositoryTest.java
|
UTF-8
| 3,117
| 2.28125
| 2
|
[
"MIT"
] |
permissive
|
package pl.java.scalatech;
import java.util.List;
import org.fest.assertions.Assertions;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ErrorCollector;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import pl.java.scalatech.config.RepositoryConfig;
import pl.java.scalatech.domain.Country;
import pl.java.scalatech.repository.country.CountryRepository;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { RepositoryConfig.class })
@ActiveProfiles(profiles="dev")
@Transactional
public class RepositoryTest {
@Rule
public ErrorCollector collector = new ErrorCollector();
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Autowired
private CountryRepository countryRepository;
@Before
public void init() {
countryRepository.deleteAll();
}
@Test
public void shouldBootstrapTest() {
Assertions.assertThat(countryRepository.count()).isZero();
}
@Test
public void shouldAddCountry() {
Country country = Country.builder().name("Poland").build();
countryRepository.save(country);
Assertions.assertThat(countryRepository.count()).isEqualTo(1l);
}
@Test
public void shouldFindCountry() {
Country country = Country.builder().name("Poland").build();
countryRepository.save(country);
List<Country> result = countryRepository.findAll();
Assertions.assertThat(result).contains(country);
}
@Test
public void shouldTryFindCountryAndThrowException() {
Country country = Country.builder().name("Poland").build();
countryRepository.save(country);
Country result = countryRepository.findOne(2l);
Assertions.assertThat(result).isEqualTo(country);
}
@Test
public void shouldTryFindCountryByNameAndThrowException() {
Country country = Country.builder().name("Poland").build();
countryRepository.save(country);
Country result = countryRepository.findByName("USA");
Assertions.assertThat(result).isNull();
}
@Test
public void shouldFindCountryByName() {
Country country = Country.builder().name("Poland").build();
countryRepository.save(country);
Country result = countryRepository.findByName("Poland");
Assertions.assertThat(result).isEqualTo(country);
}
@Test
public void shouldRemove() {
Country country = Country.builder().name("Poland").build();
countryRepository.save(country);
Assertions.assertThat(countryRepository.count()).isEqualTo(1l);
countryRepository.delete(country);
Assertions.assertThat(countryRepository.count()).isEqualTo(0);
}
}
| true
|
14cf9ddbb25740fb155112ccc494a8ea2ef8f52a
|
Java
|
cgarnier/Sprang
|
/src/main/java/com/twomoro/sprang/models/ControllerDetails.java
|
UTF-8
| 2,153
| 2.609375
| 3
|
[] |
no_license
|
package com.twomoro.sprang.models;
import com.twomoro.sprang.models.MethodDetails;
import org.springframework.web.bind.annotation.RequestMapping;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
/**
* Created by cgarnier on 24/04/14.
*/
public class ControllerDetails {
private final String config;
private String fullName;
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getServiceName() {
return serviceName;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
private String serviceName;
private Class contClass;
private String base;
public ArrayList<MethodDetails> methods;
public void setClass(Class c) {
this.contClass = c;
this.serviceName = contClass.getSimpleName().replace("Controller", "Service");
this.fullName = contClass.getName();
for (Annotation a : c.getAnnotations()) {
if (a instanceof RequestMapping) {
RequestMapping requestMapping = (RequestMapping) a;
this.base += requestMapping.value()[0].replace("*", "");
if(this.base.endsWith("/"))
this.base = this.base.substring(0, this.base.length() -1);
processMethods();
}
}
}
private void processMethods() {
for (Method method : contClass.getMethods()) {
for (Annotation annotation : method.getAnnotations()) {
if (annotation instanceof RequestMapping) {
RequestMapping req = (RequestMapping) annotation;
MethodDetails md = new MethodDetails(method, req, this.base, this.config);
this.methods.add(md);
}
}
}
}
public ControllerDetails(Class c, String config) {
this.config = config;
this.base = "";
this.methods = new ArrayList<MethodDetails>();
this.setClass(c);
}
}
| true
|
44d1c950610470bd0266aa12674325d7c2bc91f9
|
Java
|
TechnoSandy/PingPong
|
/Ball.java
|
UTF-8
| 2,221
| 3.15625
| 3
|
[] |
no_license
|
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Ball here.
*
* @author (Sandeep Satone)
* @version (V 1.0)
*/
public class Ball extends Actor
{
private int XSPEED = 5;
private int YSPEED = 5;
/**
* Act - do whatever the Ball wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
// Add your action code here.
collisionDetectRIGHT(XSPEED);
move();
topWall();
sideWall();
}
private void move(){setLocation(getX()+XSPEED, getY()+YSPEED);}
public void topWall(){
if(getY()> getWorld().getHeight() - getImage().getHeight()/2){
YSPEED = YSPEED * -1;
}
if(getY() <= getImage().getHeight()/2) {
YSPEED = YSPEED * -1;
}
}
public void sideWall(){
GameOver gameover = new GameOver();
if(getX()> getWorld().getWidth() - getImage().getHeight()/2){
// YSPEED = YSPEED * -1;
getWorld().showText("Player Right LOOSE", getWorld().getWidth()/2, getWorld().getHeight()/8);
getWorld().addObject(gameover, getWorld().getWidth()/2, getWorld().getHeight()/2);
// Greenfoot.playSound("gameover.wav");
Greenfoot.stop();
}
if(getX() <= getImage().getWidth()/2) {
// YSPEED = YSPEED * -1;
getWorld().showText("Player Left LOOSE", getWorld().getWidth()/2, getWorld().getHeight()/8);
getWorld().addObject(gameover, getWorld().getWidth()/2, getWorld().getHeight()/2);
// Greenfoot.playSound("gameover.wav");
Greenfoot.stop();
}
}
private int collisionDetectRIGHT(int SPEED){
Actor ball_1 = getOneIntersectingObject(RightBat.class);
Actor ball_2 = getOneIntersectingObject(LeftBat.class);
if(ball_1 != null || ball_2 != null ){
XSPEED = XSPEED * (-1);
Greenfoot.playSound("sound.wav");
}
return XSPEED;
}
}
| true
|
cb7e90f92a040ee275f1b106e3e6eb02bae026c7
|
Java
|
unizenscript/Denizen-For-Bukkit
|
/plugin/src/main/java/com/denizenscript/denizen/objects/properties/entity/EntitySmall.java
|
UTF-8
| 2,700
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
package com.denizenscript.denizen.objects.properties.entity;
import com.denizenscript.denizen.objects.EntityTag;
import com.denizenscript.denizencore.objects.core.ElementTag;
import com.denizenscript.denizencore.objects.Mechanism;
import com.denizenscript.denizencore.objects.ObjectTag;
import com.denizenscript.denizencore.objects.properties.Property;
import com.denizenscript.denizencore.tags.Attribute;
import org.bukkit.entity.ArmorStand;
public class EntitySmall implements Property {
public static boolean describes(ObjectTag entity) {
return entity instanceof EntityTag &&
((EntityTag) entity).getBukkitEntity() instanceof ArmorStand;
}
public static EntitySmall getFrom(ObjectTag entity) {
if (!describes(entity)) {
return null;
}
else {
return new EntitySmall((EntityTag) entity);
}
}
public static final String[] handledTags = new String[] {
"is_small"
};
public static final String[] handledMechs = new String[] {
"is_small"
};
private EntitySmall(EntityTag entity) {
this.entity = entity;
}
EntityTag entity;
@Override
public String getPropertyString() {
if (((ArmorStand) entity.getBukkitEntity()).isSmall()) {
return "true";
}
return null;
}
@Override
public String getPropertyId() {
return "small";
}
@Override
public ObjectTag getObjectAttribute(Attribute attribute) {
if (attribute == null) {
return null;
}
// <--[tag]
// @attribute <EntityTag.is_small>
// @returns ElementTag(Boolean)
// @mechanism EntityTag.is_small
// @group properties
// @description
// Returns whether the armor stand is small.
// -->
if (attribute.startsWith("is_small")) {
return new ElementTag(((ArmorStand) entity.getBukkitEntity()).isSmall())
.getObjectAttribute(attribute.fulfill(1));
}
return null;
}
@Override
public void adjust(Mechanism mechanism) {
// <--[mechanism]
// @object EntityTag
// @name is_small
// @input ElementTag(Boolean)
// @description
// Sets whether the armor stand is small.
// @tags
// <EntityTag.is_small>
// -->
if (mechanism.matches("is_small") && mechanism.requireBoolean()) {
((ArmorStand) entity.getBukkitEntity()).setSmall(mechanism.getValue().asBoolean());
}
}
}
| true
|
7dd6cc66d37c78243ed7f3e18cfab47360ec0aa3
|
Java
|
cooocy/trie-tree-search
|
/src/v3/graviti/Dataset.java
|
UTF-8
| 371
| 2.171875
| 2
|
[] |
no_license
|
package v3.graviti;
import v3.Associable;
public final class Dataset extends Associable {
public Dataset(String name, int frequency) {
super(name, frequency);
}
@Override
public String toString() {
return "Dataset{" +
"name='" + value + '\'' +
", frequency=" + frequency +
'}';
}
}
| true
|
d73105a36aef59fd68b807cf5de0eb9b39fa6392
|
Java
|
Fhernd/Java-Ejercicios
|
/JavaEjercicios/src/main/java/ejercicio0000022/CapturaJOptionPane.java
|
UTF-8
| 355
| 2.65625
| 3
|
[] |
no_license
|
package ejercicio0000022;
import javax.swing.JOptionPane;
/**
*
* @author John Ortiz Ordoñez
*/
public class CapturaJOptionPane {
public static void main(String[] args){
String nombre;
nombre = JOptionPane.showInputDialog("Ingrese su nombre: ");
JOptionPane.showMessageDialog(null, "Bienvenido, " + nombre);
}
}
| true
|
97f357fbce6b3b0ade73de2260fe3e8ac9d4ac39
|
Java
|
zy1256/JAVA
|
/99.REPORT/trunk/src/com/itwill/sungjuk/field/StudentArrayMain.java
|
UHC
| 413
| 2.765625
| 3
|
[] |
no_license
|
package com.itwill.sungjuk.field;
public class StudentArrayMain {
public static void main(String[] args) {
Student[] students = new Student[10];
//1.ü()
//2.ü
//3.й(̸,,) ã
//4.(й 2 л 0ó)
//5.лü ()
}
}
| true
|
f4cbc419297299bf6ea30cacaf46a81b0ef46b05
|
Java
|
fsnicolino/anathema
|
/Campaign_Plot/src/net/sf/anathema/campaign/module/NoteTypeConfiguration.java
|
UTF-8
| 2,892
| 1.84375
| 2
|
[] |
no_license
|
package net.sf.anathema.campaign.module;
import net.sf.anathema.campaign.note.model.IBasicItemData;
import net.sf.anathema.campaign.note.persistence.BasicDataItemPersister;
import net.sf.anathema.campaign.note.view.NoteView;
import net.sf.anathema.campaign.persistence.ISeriesPersistenceConstants;
import net.sf.anathema.campaign.presenter.NotePresenter;
import net.sf.anathema.campaign.presenter.TextEditorProperties;
import net.sf.anathema.campaign.view.SwingNoteView;
import net.sf.anathema.framework.IApplicationModel;
import net.sf.anathema.framework.item.IItemType;
import net.sf.anathema.framework.module.AbstractPersistableItemTypeConfiguration;
import net.sf.anathema.framework.persistence.IRepositoryItemPersister;
import net.sf.anathema.framework.presenter.ItemViewFactory;
import net.sf.anathema.framework.presenter.view.IItemTypeViewProperties;
import net.sf.anathema.framework.presenter.view.SimpleItemTypeViewProperties;
import net.sf.anathema.framework.repository.IItem;
import net.sf.anathema.framework.repository.ItemType;
import net.sf.anathema.framework.repository.RepositoryConfiguration;
import net.sf.anathema.framework.view.ItemView;
import net.sf.anathema.initialization.ItemTypeConfiguration;
import net.sf.anathema.initialization.reflections.Weight;
import net.sf.anathema.lib.exception.AnathemaException;
import net.sf.anathema.lib.file.RelativePath;
import net.sf.anathema.lib.resources.Resources;
@ItemTypeConfiguration
@Weight(weight = 20)
public class NoteTypeConfiguration extends AbstractPersistableItemTypeConfiguration {
public static final String NOTE_ITEM_TYPE_ID = "Note";
public static final IItemType ITEM_TYPE = new ItemType(NOTE_ITEM_TYPE_ID, new RepositoryConfiguration(".not", "Notes/"));
public NoteTypeConfiguration() {
super(ITEM_TYPE);
}
@Override
protected IRepositoryItemPersister createPersister(IApplicationModel model) {
return new BasicDataItemPersister(getItemType(), ISeriesPersistenceConstants.TAG_NOTE_ROOT);
}
@Override
protected ItemViewFactory createItemViewFactory(IApplicationModel model, final Resources resources) {
return new ItemViewFactory() {
@Override
public ItemView createView(IItem item) throws AnathemaException {
String printName = item.getDisplayName();
RelativePath icon = new PlotUI().getNoteIconPath();
NoteView basicItemView = new SwingNoteView(printName, icon, new TextEditorProperties(resources));
IBasicItemData basicItem = (IBasicItemData) item.getItemData();
new NotePresenter(basicItemView, resources, basicItem).initPresentation();
return basicItemView;
}
};
}
@Override
protected IItemTypeViewProperties createItemTypeCreationProperties(IApplicationModel anathemaModel, Resources resources) {
return new SimpleItemTypeViewProperties(getItemType(), new PlotUI().getNoteIconPath());
}
}
| true
|
408a745233ce6a63ca4a03b1929787a38b620ebd
|
Java
|
nnasta3/Android-Photo-Library
|
/app/src/main/java/com/example/genius/android45/MainActivity.java
|
UTF-8
| 9,342
| 1.992188
| 2
|
[] |
no_license
|
package com.example.genius.android45;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.hardware.input.InputManager;
import android.media.Image;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity {
private ListView listView;
private ArrayAdapter<Album> listAdapter;
private ArrayList<Album> albums = new ArrayList<>();
private Album selectedAlbum = null;
static public Album currAlbum = null;
Button saveButton;
EditText editAlbum;
Button cancelEdit;
ImageButton searchButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getIds();
hideEditButtons();
Toast.makeText(MainActivity.this, R.string.clickandhold, Toast.LENGTH_SHORT).show();
listView = findViewById(R.id.mainListView);
Album[] albumList = new Album[] {new Album("stock1"),
new Album("stock2"),
new Album("stock3")};
albums.addAll(Arrays.asList(albumList));
listAdapter = new ArrayAdapter<>(this, R.layout.support_simple_spinner_dropdown_item, albums);
listAdapter.add(new Album("stock4"));
listAdapter.add(new Album("stock5"));
listView.setAdapter(listAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Album selectedItem = (Album) parent.getItemAtPosition(position);
selectedAlbum = selectedItem;
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Album selectedItem = (Album) parent.getItemAtPosition(position);
selectedAlbum = selectedItem;
openAlbum();
return true;
}
});
// listView.setAdapter(
// new ArrayAdapter<>(this, R.layout.activity_main, albums)
// );
// albums = getResources().getStringArray(R.array.)
}
public void addAlbum(View view) {
hideEditButtons();
final AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
final View addAlbumView = getLayoutInflater().inflate(R.layout.add_album, null);
final EditText addAlbum = addAlbumView.findViewById(R.id.albumName);
final Button submitAlbum = addAlbumView.findViewById(R.id.submitAlbum);
System.out.println("check1");
submitAlbum.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String albumName = null;
if(!addAlbum.getText().toString().isEmpty()){
albumName = addAlbum.getText().toString();
for (Album a : albums){
if(albumName.equals(a.getName())){
Toast.makeText(MainActivity.this, R.string.error_duplicate_msg, Toast.LENGTH_SHORT).show();
return;
//selectedAlbum = null;
}
}
Album newAlbum = new Album(albumName);
albums.add(newAlbum);
//listAdapter.add(albumName);
listView.setAdapter(listAdapter);
selectedAlbum = null;
addAlbum.setText("");
Toast.makeText(MainActivity.this, "Album Successfully Added", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(MainActivity.this, R.string.empty_field, Toast.LENGTH_SHORT).show();
System.out.println("EMPTY FIELD");
}
// hides soft keyboard after submit is pressed
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(submitAlbum.getWindowToken(), 0);
}
});
addAlbumView.setVisibility(View.VISIBLE);
mBuilder.setView(addAlbumView);
mBuilder.show();
selectedAlbum = null;
// dialog = mBuilder.create();
// dialog.show();
}
public void delAlbum(View view) {
hideEditButtons();
if(selectedAlbum == null){
Toast.makeText(MainActivity.this, R.string.noSelection, Toast.LENGTH_SHORT).show();
return;
}
albums.remove(selectedAlbum);
listView.setAdapter(listAdapter);
selectedAlbum = null;
}
public void editAlbum(View view) {
editAlbum = findViewById(R.id.editAlbumName);
if(selectedAlbum == null){
Toast.makeText(MainActivity.this, R.string.noSelection, Toast.LENGTH_SHORT).show();
return;
}
if(!selectedAlbum.getName().isEmpty()){
editAlbum.setVisibility(View.VISIBLE);
saveButton.setVisibility(View.VISIBLE);
cancelEdit.setVisibility(View.VISIBLE);
editAlbum.setText(selectedAlbum.getName());
final Button saveButton = findViewById(R.id.saveAlbum);
saveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(editAlbum.getText().toString().equals(selectedAlbum.getName())){
Toast.makeText(MainActivity.this, R.string.error_duplicate_msg, Toast.LENGTH_SHORT).show();
selectedAlbum = null;
return;
}
int index = albums.indexOf(selectedAlbum);
Album selectedAlbum = albums.get(index);
String newAlbum = editAlbum.getText().toString();
for(Album a : albums){
if(newAlbum.equals(a.getName())){
selectedAlbum = null;
Toast.makeText(MainActivity.this, R.string.error_duplicate_msg, Toast.LENGTH_SHORT).show();
return;
}
}
selectedAlbum.setName(newAlbum);
listView.setAdapter(listAdapter);
hideEditButtons();
Toast.makeText(MainActivity.this, R.string.renamesuccess, Toast.LENGTH_SHORT).show();
selectedAlbum = null;
// hides soft keyboard after saved item
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(editAlbum.getWindowToken(), 0);
}
});
cancelEdit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
hideEditButtons();
selectedAlbum = null;
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(cancelEdit.getWindowToken(), 0);
}
});
}
else{
Toast.makeText(MainActivity.this, R.string.noSelection, Toast.LENGTH_SHORT).show();
}
}
public void openAlbum( ) {
System.out.println("OPEN ALBUM");
if(selectedAlbum == null){
Toast.makeText(MainActivity.this, R.string.noSelection, Toast.LENGTH_SHORT).show();
return;
}
if(selectedAlbum.getName().isEmpty()){
Toast.makeText(MainActivity.this, R.string.noSelection, Toast.LENGTH_SHORT).show();
return;
}
currAlbum = selectedAlbum;
Intent i = new Intent(MainActivity.this, PhotosActivity.class);
startActivity(i);
}
public void searchAlbum(View view) {
selectedAlbum = null;
startActivity(new Intent(MainActivity.this, SearchActivity.class));
}
private void getIds() {
editAlbum = findViewById(R.id.editAlbumName);
saveButton = findViewById(R.id.saveAlbum);
cancelEdit = findViewById(R.id.cancelEdit);
searchButton = findViewById(R.id.search);
}
public void hideEditButtons(){
saveButton.setVisibility(View.INVISIBLE);
editAlbum.setVisibility(View.INVISIBLE);
cancelEdit.setVisibility(View.INVISIBLE);
editAlbum.setText("");
}
}
| true
|
1db4da8a74b790e0c2816b81aa72419e90a3066a
|
Java
|
Nubunaga/AlgoDatakul
|
/Fråga6/src/OrderdQueue.java
|
UTF-8
| 7,345
| 3.65625
| 4
|
[] |
no_license
|
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Random;
/**
* This class will create an general ordered queue based on the ADT <em> QUEUE </em>
* and will be implemented in a <em> FIFO</em> mather meaning the first that goes in
* is the last to go out, however. Since the task is to make the queue be a priority
* queue, we have to rethink this approach.
* This means that instead of having the traditional queue, we have to rearrange them
* so the queue goes from highest to lowest, meaning the lowest number will be the last
* nr.
* An heavy usage of abstraction to hide the algorithm from the public interface has been
* made, thus protecting it from any changes from the public interface.
*
* @author Netanel Avraham Eklind
* @version 1 2019-04/09: Implementing code and importing old queue system.
* @version 2 2019-06/9 : Bug fixes of the sorting algorithm.
* <ref> C:\Users\tomas\Desktop\AlgoData\Fråga 5\src.FIFO.java</ref>
* Also the Same FIFO concept from last question i.e 5.
* runtime 0.0049 seconds.
* */
public class OrderdQueue<Item> implements Iterable<Item>{
private int stackSize;
private Node<Item> first;
private Node<Item> last;
/**
* Constructor for the node class.
* */
private class Node<Item>{
private Item item;
private Node<Item> next;
private Node<Item> prev;
}
/**
* Constructor for the circle double linked list stack.
* */
public OrderdQueue(){
first = null;
last = null;
stackSize = 0;
}
/**
* Enter the queue in a FIFO mather
* @param item generic input value.
* */
public void enterQueue(Item item){
Node<Item> node = new Node<>();
node.item = item;
if(isEmpty()){
setLast(node);
}
else{
newNode(node);
}
stackSize++;
printQueue();
}
public Item deenterQueue(){
Item item = last.item;
last.prev.next = last.next;
last = last.prev;
stackSize--;
printQueue();
return item;
}
/**
* Returns the state of the first (last) node in the system.
* @return true if it is null, false if has a node in it.
*/
public boolean isEmpty(){
return last == null;
}
public Item getItem(){
return first.item;
}
/**
* Inserts a new method in the list.
* @param node contains new value
* */
private void newNode(Node<Item> node){
Node<Item> temp = last;
if(nodeCompare(node,temp)){
temp.next = node;
node.prev = temp;
node.next = first;
last = node;
}
else{
orderInsert(node,temp);
}
}
/**
* compares the item in the node
* @param node contains the new value. in one case, the current.
* @param temp is the temporary pointer to the current item.
* */
private boolean nodeCompare(Node<Item> node, Node <Item> temp){
return (int) node.item <= (int) temp.item;
}
/**
* Checks for the values of the node and inserts accordingly.
* @param node is the new value.
* @param temp is the current looked on item.
* */
private void orderInsert(Node<Item> node, Node<Item> temp){
boolean flag = false;
while (temp != first){
if(nodeCompare(node,temp)){
node.next = temp.next;
temp.next.prev = node;
temp.next = node;
node.prev = temp;
flag = true;
break;
}
else{
temp = temp.prev;
}
}
if(!flag)orderHeadofQueue(node,temp);
}
/**
* Checks if the node should be head of the queue or not.
* */
private void orderHeadofQueue(Node<Item> node, Node<Item> temp){
if((nodeCompare(temp,node))){
node.next = temp;
temp.prev = node;
first = node;
node.prev = last;
}
else {
node.next = temp.next;
temp.next.prev = node;
temp.next = node;
node.prev = temp;
}
}
/**
* Set the last to a new node.
* */
private void setLast(Node node){
last = node;
first = node;
last.next = first;
last.prev = first;
}
/**
* Prints the queue in reverse
* */
private void printQueue(){
int count = 0;
Node node = last;
if(stackSize == 1){
System.out.println("["+node.item+"] ");
}
else {
while (count < stackSize) {
System.out.print("[" + node.item + "] ");
node = node.prev;
count++;
}
System.out.print("\n");
}
}
/**
* Returns an interator to the current stack, thus having the
* iterator, iterate through the items in the stack.
*
* @return ListIterator that is used to iterate through the stack
* item.
* */
public Iterator<Item> iterator(){
return new ListIterator(first);
}
private class ListIterator implements Iterator<Item>{
private Node<Item> current;
private ListIterator(Node<Item> first){
this.current = first;
}
/**
* Checks if the current node is linked to another node and returns
* the <code> Item </code>.
* @return Item an generic data value inside the node.
* */
public Item next(){
if(!hasNext())throw new NoSuchElementException();
Item item = current.item;
current = current.next;
return item;
}
/**
* Checks that the current node exist, meaning that
* <code> next() </code> can take that item.
* @return boolean true or false depending on the existence
* of an node.
* */
public boolean hasNext(){
return this.current != null;
}
}
/**
* This method serves as the start method for the virtual machine and contains a random integer
* generator that throws different numbers into the list.
* @param args contains an array of string given by the user in cmd.
* */
public static void main(String[] args){
long startTime;
long endTime;
double[] time = new double[5];
double runTime = 0;
OrderdQueue<Integer> orderQueue = new OrderdQueue<>();
Random random = new Random();
for(int i =0; i<5; i++){
startTime = System.nanoTime();
orderQueue.enterQueue(random.nextInt(10));
endTime = System.nanoTime();
time[i] = (endTime - startTime)/(1*Math.pow(10,9));
}
for(double d: time){
runTime += d;
}
runTime = runTime/5;
orderQueue.deenterQueue();
System.out.print("Mean runtime is : " + runTime);
}
}
| true
|
7b7d25be1515a1dddf2fc388058841b82be85685
|
Java
|
zhangchao1215/DoctorSixSixSix
|
/app/src/main/java/jiyun/com/doctorsixsixsix/view/JiaHaoDocView.java
|
UTF-8
| 414
| 1.757813
| 2
|
[] |
no_license
|
package jiyun.com.doctorsixsixsix.view;
import java.util.List;
import jiyun.com.doctorsixsixsix.modle.bean.JiaHaoDocBean;
/**
* 项目名称: 血压卫士
* 类描述:
* 创建人: Administrator
* 创建时间: 2017/6/13 11:18
* 修改人: 张超
* 修改内容:
* 修改时间:aa
*/
public interface JiaHaoDocView {
void JiaHao(List<JiaHaoDocBean.DataBean.ScheduleBean.RdtimeBean> lodaList);
}
| true
|
8f6675e54ca3302154d17ef08f737a870e393ff9
|
Java
|
caoyang4/Java
|
/src/juc/executors/thread/TestWaitNotify.java
|
UTF-8
| 897
| 3.0625
| 3
|
[] |
no_license
|
package src.juc.executors.thread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestWaitNotify {
public synchronized void doNotify(){
System.out.println("begin to notify");
notifyAll();
System.out.println("end to notify");
}
public synchronized void doWait(){
try {
System.out.println("begin to wait");
wait();
System.out.println("end to wait");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
TestWaitNotify test = new TestWaitNotify();
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(() -> test.doWait());
executorService.execute(() -> test.doNotify());
executorService.shutdown();
}
}
| true
|
80d95b134e5ff34fde2cdb4cdad8fecf9c179e18
|
Java
|
pabhi66/Rutgers-Classes
|
/Data Structure (interview questions\practice)/src/Stack_Queue_PQ/Stack.java
|
UTF-8
| 1,452
| 3.703125
| 4
|
[] |
no_license
|
package Stack_Queue_PQ;
import java.util.NoSuchElementException;
public class Stack {
private Node head;
private int size;
public Stack(){
this.head = null;
this.size = 0;
}
public Node push(int data){
Node temp = new Node(data);
if(head == null){
head = temp;
size++;
return head;
}
temp.next = head;
head = temp;
size++;
return head;
}
public int pop(){
if(head == null){
throw new NoSuchElementException();
}
int temp = peek();
head = head.next;
size--;
return temp;
}
public int peek(){
if(head == null)
throw new NoSuchElementException();
return head.data;
}
public boolean isEmpty(){
return head == null? true : false;
}
public int getSize(){
return this.size;
}
public void print(){
Node temp = head;
while(temp != null){
System.out.print(temp.data + " ");
temp = temp.next;
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Stack stack = new Stack();
stack.push(5);
stack.push(4);
stack.push(3);
stack.push(2);
stack.push(1);
stack.print();
stack.pop();
System.out.print("\n");
stack.print();
System.out.print("\n");
System.out.println(stack.peek() + " " + stack.getSize() + " " + stack.isEmpty());
java.util.Stack<Integer> s = new java.util.Stack<>();
s.push(100);
}
}
| true
|
41df2f553ecc592fa4a96ec833cc6bd313781557
|
Java
|
williamgong2015/2112
|
/src/test/testsA5/WorldTest.java
|
UTF-8
| 2,676
| 3.296875
| 3
|
[] |
no_license
|
package test.testsA5;
import java.io.IOException;
import org.junit.Test;
import game.constant.Constant;
import game.exceptions.SyntaxError;
import servlet.element.Critter;
import servlet.element.Food;
import servlet.element.Rock;
import servlet.world.Position;
import servlet.world.World;
/**
* Black box test of World,
* create a new world and initialize it with some elements,
* check it can be printed out as expected
*
* Random test of World,
* create a random size of new world and randomly insert a lot of elements,
* then print the world out, check if the program will crash
*
*/
public class WorldTest {
int session_id = 0;
@Test
public void defaultWorldTest() throws IOException, SyntaxError {
World w = new World();
w.printCoordinatesASCIIMap();
w.printASCIIMap();
}
/**
* Black box test of World #1
* Insert Food, Rock and Food into it, them print it in two ways
*/
@Test
public void blackBoxTest1() throws IOException, SyntaxError {
World w = new World(16,10,"test");
Constant.init();
Rock r = new Rock();
w.setElemAtPosition(r, new Position(1,2));
w.setElemAtPosition(r, new Position(3,7));
w.setElemAtPosition(r, new Position(2,8));
String file = "critter1.txt";
Critter c = new Critter(file, w.critterIDCount++, session_id);
c.setDir(5);
w.setElemAtPosition(c, new Position(3,3));
file = "critter2.txt";
c = new Critter(file, w.critterIDCount++, session_id);
w.setElemAtPosition(c, new Position(4,3));
Food f = new Food(10);
w.setElemAtPosition(f, new Position(0,1));
w.printASCIIMap();
System.out.println(w.printCoordinatesASCIIMap());
}
/**
* Black box test of World #2
* Insert a Critter into the world, print world to check the result
* Get the Critter and move it, print world to check the result,
* Delete the Critter from the world, print world to check the result
*/
@Test
public void blackBoxTest2() throws IOException, SyntaxError {
World w = new World(6,8,"test");
w.printCoordinatesASCIIMap();
String file = "critter1.txt";
Critter c = new Critter(file, w.critterIDCount++, session_id);
c.setDir(5);
Position origin = new Position(3,3);
w.setElemAtPosition(c, origin);
w.printASCIIMap();
System.out.println("-------------------");
// critter move ahead one step toward direction 5
c = (Critter) w.getElemAtPosition(origin);
Position p = c.getPosition();
p = p.getRelativePos(1, c.getDir());
w.removeElemAtPosition(origin);
w.setElemAtPosition(c, p);
w.printASCIIMap();
System.out.println("-------------------");
// delete critter
w.removeElemAtPosition(p);
System.out.println(w.printASCIIMap());
}
}
| true
|
9f3b2f9167ad04d95329bc1a389603d19d5793a3
|
Java
|
uryyyyyyy/javaSamples
|
/javaLang/src/main/java/com/github/uryyyyyyy/javaSamples/javaLang/annotation/impl/SampleTest.java
|
UTF-8
| 678
| 2.25
| 2
|
[] |
no_license
|
package com.github.uryyyyyyy.javaSamples.javaLang.annotation.impl;
import com.github.uryyyyyyy.javaSamples.javaLang.annotation.marker.TestAnnotation;
public class SampleTest {
@TestAnnotation public static void m1 () { } // テストは成功すべき
public static void m2 () { }
@TestAnnotation public static void m3 () { // テストは失敗すべき
throw new RuntimeException ("Boom");
}
public static void m4 () { }
@TestAnnotation public void m5() { } //illegal usage;
public static void m6 () { }
@TestAnnotation public static void m7 () { // テス ト は失敗すべき
throw new RuntimeException("Crash");
}
public static void m8 () { }
}
| true
|
214ffc8740156d26346c10e900b01aec183b941d
|
Java
|
eiribarren/M6-DAM2-epumer
|
/UF1/Proyecto tres en raya/src/Tablero.java
|
UTF-8
| 1,961
| 3.1875
| 3
|
[] |
no_license
|
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Tablero {
JFrame main;
Casilla[][] casillas;
public Tablero(Casilla.CasillaInterface listener) {
this.start(listener);
}
public void start(Casilla.CasillaInterface listener) {
main = new JFrame();
main.setSize(new Dimension(200*3,200*3));
casillas = new Casilla[3][3];
for ( int i = 0 ; i < 3 ; i++ ) {
for ( int j = 0 ; i < 3 ; i++ ) {
casillas[i][j] = new Casilla(listener, i , j);
main.add(casillas[i][j]);
}
}
main.setVisible(true);
main.pack();
}
public static class Casilla extends JPanel {
private CasillaInterface listener;
private Ficha ficha = null;
private int fila, columna;
public Casilla(CasillaInterface listener, int fila, int columna) {
this.listener = listener;
this.fila = fila;
this.columna = columna;
this.start();
}
public void start() {
this.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if ( ponerFicha( listener.getFichaJugadorActual() ) ) {
listener.cambiarTurno();
};
}
});
this.setSize(new Dimension(200,200));
this.setVisible(true);
}
public boolean ponerFicha( Ficha ficha ) {
if ( this.ficha == null ) {
this.ficha = ficha;
String urlImagen = "";
switch ( ficha.getForma() ) {
case CRUZ:
urlImagen = "cruz.png";
break;
case CIRCULO:
urlImagen = "patata.png";
break;
}
ficha.ponerImagen(200,200,urlImagen);
this.add(ficha);
return true;
} else {
return false;
}
}
public Ficha getFicha() {
return this.ficha;
}
public interface CasillaInterface {
abstract Ficha getFichaJugadorActual();
abstract void cambiarTurno();
}
}
}
| true
|
8ab35fa083ddd7b836b5df766c95d4bffd716bde
|
Java
|
tomasbargut/absence-app
|
/docs/servlet.example.java
|
UTF-8
| 764
| 2.171875
| 2
|
[] |
no_license
|
package servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
// TODO: Agregar el map correcto
@WebServlet("/servlet")
// TODO: Poner nombre de clase correcto
public class Servlet extends HttpServlet {
public Servlet(){
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
}
}
| true
|
178b14e4deec4634880946c5837e5e03c619884a
|
Java
|
E-Trapp/ETrapp-Web
|
/src/main/java/cat/udl/etrapp/server/models/EventComment.java
|
UTF-8
| 1,074
| 2.25
| 2
|
[] |
no_license
|
package cat.udl.etrapp.server.models;
import java.util.HashMap;
import java.util.Map;
public class EventComment {
private long id;
private String comment;
private long userId;
private long eventId;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public long getEventId() {
return eventId;
}
public void setEventId(long eventId) {
this.eventId = eventId;
}
public Map<String, Object> asMap() {
Map<String, Object> map = new HashMap<>();
// map.put("id", id);
map.put("comment", comment);
map.put("userId", userId);
map.put("eventId", eventId);
return map;
}
}
| true
|
1fe97eb4225189fbd256a5dbc40c04115bde1d23
|
Java
|
coderextreme/lircom
|
/src/main/java/f00f/net/irc/martyr/commands/AwayCommand.java
|
UTF-8
| 1,129
| 3.15625
| 3
|
[
"Apache-2.0"
] |
permissive
|
package f00f.net.irc.martyr.commands;
import f00f.net.irc.martyr.OutCommand;
/**
* Defines the AWAY message which is used to indicate that you are or are not away from the keyboard.
*
* @author Daniel Henninger
*/
public class AwayCommand implements OutCommand
{
String awayMessage = null;
/**
* A blank AWAY command indicates that you are no longer away.
*/
public AwayCommand()
{
// Nothing to do
}
/**
* An AWAY command with a message indicates that you are in fact away.
*
* @param awayMessage Message indicating why you are away.
*/
public AwayCommand(String awayMessage)
{
this.awayMessage = awayMessage;
}
/**
* @see f00f.net.irc.martyr.OutCommand#render()
*/
public String render()
{
String ret = getIrcIdentifier();
if (awayMessage != null && awayMessage.length() > 0) {
ret = ret + " " + awayMessage;
}
return ret;
}
/**
* @see f00f.net.irc.martyr.Command#getIrcIdentifier()
*/
public String getIrcIdentifier()
{
return "AWAY";
}
}
| true
|
bb222333385abe8ed1a7845a8dd6a2c3d9affe8c
|
Java
|
gabbyoliveira/REU_Summer2016
|
/ConTest files/TestControllerFactory.java
|
UTF-8
| 730
| 2.875
| 3
|
[] |
no_license
|
package conTest;
public class TestControllerFactory
{
public static TestController createTestController(String className)
{
try
{
Class<?> cls = Class.forName(className);
Object result = cls.newInstance();
if (result instanceof TestController)
return (TestController) result;
throw new RuntimeException("Cannot create test controller of type: " + className
+ ", received: " + result.getClass());
}
catch (ClassNotFoundException | InstantiationException | IllegalAccessException e)
{
throw new RuntimeException("Cannot create test controller.", e);
}
}
}
| true
|
489887fe68d3ed1d095731a5ba967430aabb0a9d
|
Java
|
alpiysl/miCollabDesktop
|
/src/test/java/miCollab/MiCollabDesktopApp.java
|
UTF-8
| 12,117
| 2.421875
| 2
|
[] |
no_license
|
package miCollab;
import io.appium.java_client.windows.WindowsDriver;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.event.InputEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.TimeUnit;
public class MiCollabDesktopApp {
public static WindowsDriver driver = null;
@BeforeMethod
public void setUp() {
DesiredCapabilities desiredCapabilities = new DesiredCapabilities();
desiredCapabilities.setCapability("app", "C:\\Program Files (x86)\\Mitel\\MiCollab\\MiCollab.exe");
desiredCapabilities.setCapability("platformName", "Windows");
desiredCapabilities.setCapability("deviceName", "WindowsPC");
try {
driver = new WindowsDriver(new URL("http://127.0.0.1:4723"), desiredCapabilities);
} catch (MalformedURLException e) {
e.printStackTrace();
}
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
}
@AfterMethod
public void cleanUp() throws MalformedURLException, InterruptedException {
DesiredCapabilities desiredCapabilities = new DesiredCapabilities();
desiredCapabilities.setCapability("app", "Root");
driver = new WindowsDriver(new URL("http://127.0.0.1:4723"), desiredCapabilities);
Actions actions = new Actions(driver);
actions.contextClick(driver.findElement(By.name("MiCollab - 1 running window"))).perform();
Thread.sleep(1000);
driver.findElement(By.name("Quit MiCollab")).click();
}
@AfterClass
public void tearDown() {
driver.quit();
}
@Test
public void incomingCallTest() throws InterruptedException, IOException, AWTException {
byte testDurationInDays = 30;
double screenHeight = Toolkit.getDefaultToolkit().getScreenSize().getHeight();
double screenWidth = Toolkit.getDefaultToolkit().getScreenSize().getWidth();
short lineXcoordinate = (short) (0.5515 * screenWidth);
short holdButtonXcoordinate = (short) (lineXcoordinate + (screenWidth - lineXcoordinate) / 2 + 90);
short holdButtonYcoordinate = (short) (screenHeight - 100);
short acceptButtonXcoordinate=(short)(lineXcoordinate + (screenWidth-lineXcoordinate)*0.685);
short acceptButtonYcoordinate = (short) ((screenHeight-40)*0.774);
int statusXcoordinate = (int) (screenWidth-200);
int statusYcoordinate = (int) (screenHeight-75);
LocalDateTime finalTime = LocalDateTime.now().plus(Duration.ofDays(testDurationInDays));
Thread.sleep(23000);
Actions action = new Actions(driver);
driver.findElement(By.name("System")).click();
driver.findElement(By.name("Maximize")).click();
Thread.sleep(3000);
Robot robot = new Robot();
//Clicking on OK button
robot.mouseMove((int) (screenWidth / 2), 544);
Thread.sleep(1000);
action.doubleClick().perform();
//Taking screenshot of before calls
File screenshotBeforeCall = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshotBeforeCall, new File(System.getProperty("user.dir") + "\\Screenshot1.png"));
BufferedImage beforeCallImage = ImageIO.read(screenshotBeforeCall);
//Clicking on Settings button
robot.mouseMove(90, 345);
action.click().perform();
Thread.sleep(1000);
//Taking screenshot of show stopper
File showStopper = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(showStopper, new File(System.getProperty("user.dir") + "\\showStopper.png"));
BufferedImage showStopperImage = ImageIO.read(showStopper);
//Clicking on Home button
robot.mouseMove(90, 116);
action.click().perform();
//Taking screenshot of the status
File statusScreenshot =((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
BufferedImage statusImage=ImageIO.read(statusScreenshot);
BufferedImage statusImagePartial = statusImage.getSubimage(statusXcoordinate, statusYcoordinate, 200,35);
ImageIO.write(statusImagePartial, "png",statusScreenshot);
FileUtils.copyFile(statusScreenshot,new File(System.getProperty("user.dir")+"\\status.png"));
int numberOfIncomingCalls = 0;
while (LocalDateTime.now().isBefore(finalTime)) {
File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File(System.getProperty("user.dir") + "\\Screenshot1.png"));
BufferedImage screenshotImage = ImageIO.read(screenshot);
//Checking the status
File statusCheckScreenshot =((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
BufferedImage statusCheckImage=ImageIO.read(statusCheckScreenshot);
BufferedImage statusCheckImagePartial = statusCheckImage.getSubimage(statusXcoordinate, statusYcoordinate, 200,35);
ImageIO.write(statusCheckImagePartial, "png",statusCheckScreenshot);
FileUtils.copyFile(statusCheckScreenshot,new File(System.getProperty("user.dir")+"\\statusCheck.png"));
if(!isSimilarSensitive(statusImagePartial, statusCheckImagePartial)){
robot.mouseMove((int) (screenWidth-70), (int) (screenHeight-60));
action.click().build().perform();
action.release().perform();
Thread.sleep(1000);
robot.mouseMove((int)(screenWidth-50), (int)(screenHeight-215));
action.click().build().perform();
action.release().perform();
Thread.sleep(1000);
robot.mouseMove((int)(screenWidth/2), (int)(screenHeight/2));
action.click().build().perform();
action.release().perform();
}
if (isSimilarSensitive(screenshotImage, beforeCallImage)) {
Thread.sleep(500);
} else if (isSimilarSensitive(screenshotImage, showStopperImage)) {
break;
} else {
LocalTime incomingCallTime = LocalTime.now();
short holdPeriod = 2;
numberOfIncomingCalls++;
boolean flag = true;
while (flag) {
robot.mouseMove(acceptButtonXcoordinate, acceptButtonYcoordinate);
action.click().perform();
action.keyDown(Keys.CONTROL).sendKeys(Keys.NUMPAD1).perform();
action.release().sendKeys(Keys.CONTROL).perform();
Thread.sleep(300);
File screenshotAfterCall = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshotAfterCall, new File(System.getProperty("user.dir") + "\\Screenshot2.png"));
BufferedImage afterCallImage = ImageIO.read(screenshotAfterCall);
if (LocalTime.now().isAfter(incomingCallTime.plus(holdPeriod, ChronoUnit.MINUTES).minus(5, ChronoUnit.SECONDS)) && LocalTime.now().isBefore(incomingCallTime.plus(holdPeriod, ChronoUnit.MINUTES))) {
Robot newRobot = new Robot();
newRobot.mouseMove(holdButtonXcoordinate, holdButtonYcoordinate);
action.click().perform();
Thread.sleep(3000);
action.click().perform();
holdPeriod = (short) (holdPeriod + 2);
}
if (!isSimilar(afterCallImage, beforeCallImage)) {
Thread.sleep(300);
} else if (isSimilar(afterCallImage, showStopperImage)) {
break;
} else {
flag = false;
}
}
}
}
System.out.println("Number of incoming calls during the test = " + numberOfIncomingCalls);
robot.mouseMove(90, 270);
action.click().perform();
Thread.sleep(1000);
File callHistory = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(callHistory, new File(System.getProperty("user.dir") + "\\callHistory.png"));
Thread.sleep(1000);
}
public boolean isSimilar(BufferedImage actual, BufferedImage expectedImage) {
double percentage = 1000;
int w1 = actual.getWidth();
int w2 = expectedImage.getWidth();
int h1 = actual.getHeight();
int h2 = expectedImage.getHeight();
if ((w1 != w2) || (h1 != h2)) {
System.out.println("Both images should have same dimensions");
} else {
long diff = 0;
for (int j = 0; j < h1; j++) {
for (int i = 0; i < w1; i++) {
//Getting the RGB values of a pixel
int pixel1 = actual.getRGB(i, j);
Color color1 = new Color(pixel1, true);
int r1 = color1.getRed();
int g1 = color1.getGreen();
int b1 = color1.getBlue();
int pixel2 = expectedImage.getRGB(i, j);
Color color2 = new Color(pixel2, true);
int r2 = color2.getRed();
int g2 = color2.getGreen();
int b2 = color2.getBlue();
//sum of differences of RGB values of the two images
long data = Math.abs(r1 - r2) + Math.abs(g1 - g2) + Math.abs(b1 - b2);
diff = diff + data;
}
}
double avg = diff / (w1 * h1 * 3);
percentage = (avg / 255) * 100;
//System.out.println("Difference: " + percentage);
}
if (percentage > 2) {
return false;
} else return true;
}
public boolean isSimilarSensitive(BufferedImage actual, BufferedImage expectedImage) {
double percentage = 1000;
int w1 = actual.getWidth();
int w2 = expectedImage.getWidth();
int h1 = actual.getHeight();
int h2 = expectedImage.getHeight();
if ((w1 != w2) || (h1 != h2)) {
System.out.println("Both images should have same dimensions");
} else {
long diff = 0;
for (int j = 0; j < h1; j++) {
for (int i = 0; i < w1; i++) {
//Getting the RGB values of a pixel
int pixel1 = actual.getRGB(i, j);
Color color1 = new Color(pixel1, true);
int r1 = color1.getRed();
int g1 = color1.getGreen();
int b1 = color1.getBlue();
int pixel2 = expectedImage.getRGB(i, j);
Color color2 = new Color(pixel2, true);
int r2 = color2.getRed();
int g2 = color2.getGreen();
int b2 = color2.getBlue();
//sum of differences of RGB values of the two images
long data = Math.abs(r1 - r2) + Math.abs(g1 - g2) + Math.abs(b1 - b2);
diff = diff + data;
}
}
double avg = diff / (w1 * h1 * 3);
percentage = (avg / 255) * 100;
//System.out.println("Difference: " + percentage);
}
if (percentage > 0.10) {
return false;
} else return true;
}
}
| true
|
feb182b6983742fdfe1345be789edba5964749bb
|
Java
|
jessije/ViktorClasses
|
/src/com/Concurenccy/eight/SleepTask.java
|
UTF-8
| 309
| 2.90625
| 3
|
[] |
no_license
|
package com.Concurenccy.eight;
public class SleepTask implements Runnable {
@Override
public void run() {
try {
System.out.println("I am sleeping....");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| true
|
49249cd89cb5e84125be2bd448de1672290776f0
|
Java
|
EDACC/edacc_aac
|
/src/edacc/configurator/aac/racing/Default.java
|
UTF-8
| 6,993
| 2.28125
| 2
|
[
"MIT"
] |
permissive
|
package edacc.configurator.aac.racing;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import edacc.api.API;
import edacc.configurator.aac.AAC;
import edacc.configurator.aac.Parameters;
import edacc.configurator.aac.SolverConfiguration;
import edacc.model.ConfigurationScenarioDAO;
public class Default extends RacingMethods {
SolverConfiguration bestSC;
int incumbentNumber;
int num_instances;
HashSet<Integer> stopEvalSolverConfigIds = new HashSet<Integer>();
public Default(AAC proar, Random rng, API api, Parameters parameters, List<SolverConfiguration> firstSCs, List<SolverConfiguration> referenceSCs) throws Exception {
super(proar, rng, api, parameters, firstSCs, referenceSCs);
incumbentNumber = 0;
num_instances = ConfigurationScenarioDAO.getConfigurationScenarioByExperimentId(parameters.getIdExperiment()).getCourse().getInitialLength();
if (!firstSCs.isEmpty()) {
// TODO: ...
initBestSC(firstSCs.get(0));
}
}
private void initBestSC(SolverConfiguration sc) throws Exception {
this.bestSC = firstSCs.get(0);
bestSC.setIncumbentNumber(incumbentNumber++);
pacc.log("i " + pacc.getWallTime() + " ," + bestSC.getCost() + ", n.A.," + bestSC.getIdSolverConfiguration() + ", n.A.," + bestSC.getParameterConfiguration().toString());
int expansion = 0;
if (bestSC.getJobCount() < parameters.getMaxParcoursExpansionFactor() * num_instances) {
expansion = Math.min(parameters.getMaxParcoursExpansionFactor() * num_instances - bestSC.getJobCount(), parameters.getInitialDefaultParcoursLength());
pacc.expandParcoursSC(bestSC, expansion);
}
if (expansion > 0) {
pacc.log("c Expanding parcours of best solver config " + bestSC.getIdSolverConfiguration() + " by " + expansion);
}
// update the status of the jobs of bestSC and if first level wait
// also for jobs to finish
if (expansion > 0) {
pacc.log("c Waiting for currently best solver config " + bestSC.getIdSolverConfiguration() + " to finish " + expansion + "job(s)");
while (true) {
pacc.updateJobsStatus(bestSC);
if (bestSC.getNotStartedJobs().isEmpty() && bestSC.getRunningJobs().isEmpty()) {
break;
}
pacc.sleep(1000);
}
pacc.validateIncumbent(bestSC);
} else {
pacc.updateJobsStatus(bestSC);
}
}
public String toString(){
return "This is the racing method or ROAR";
}
@Override
public int compareTo(SolverConfiguration sc1, SolverConfiguration sc2) {
return sc1.compareTo(sc2);
}
@Override
public void solverConfigurationsFinished(List<SolverConfiguration> scs) throws Exception {
for (SolverConfiguration sc : scs) {
if (sc == bestSC)
continue;
int comp = compareTo(sc, bestSC);
if (!stopEvalSolverConfigIds.contains(sc.getIdSolverConfiguration()) && comp >= 0) {
if (sc.getJobCount() == bestSC.getJobCount()) {
sc.setFinished(true);
// all jobs from bestSC computed and won against
// best:
if (comp > 0) {
bestSC = sc;
sc.setIncumbentNumber(incumbentNumber++);
pacc.log("new incumbent: " + sc.getIdSolverConfiguration() + ":" + pacc.getWallTime() + ":" + pacc.getCumulatedCPUTime() + ":" + sc.getCost());
pacc.log("i " + pacc.getWallTime() + "," + sc.getCost() + ",n.A. ," + sc.getIdSolverConfiguration() + ",n.A. ," + sc.getParameterConfiguration().toString());
pacc.validateIncumbent(bestSC);
}
// api.updateSolverConfigurationCost(sc.getIdSolverConfiguration(),
// sc.getCost(),
// statistics.getCostFunction());
// listNewSC.remove(i);
} else {
int generated = pacc.addRandomJob(sc.getJobCount(), sc, bestSC, Integer.MAX_VALUE - sc.getNumber());
pacc.log("c Generated " + generated + " jobs for solver config id " + sc.getIdSolverConfiguration());
pacc.addSolverConfigurationToListNewSC(sc);
}
} else {// lost against best on part of the actual (or should not be evaluated anymore)
// parcours:
stopEvalSolverConfigIds.remove(sc.getIdSolverConfiguration());
sc.setFinished(true);
if (parameters.isDeleteSolverConfigs())
api.removeSolverConfig(sc.getIdSolverConfiguration());
pacc.log("d Solver config " + sc.getIdSolverConfiguration() + " with cost " + sc.getCost() + " lost against best solver config on " + sc.getJobCount() + " runs.");
if (bestSC.getJobCount() < parameters.getMaxParcoursExpansionFactor() * num_instances) {
pacc.log("c Expanding parcours of best solver config " + bestSC.getIdSolverConfiguration() + " by 1");
pacc.expandParcoursSC(bestSC, 1);
pacc.addSolverConfigurationToListNewSC(bestSC);
}
}
}
}
@Override
public void solverConfigurationsCreated(List<SolverConfiguration> scs) throws Exception {
if (scs.isEmpty())
return;
if (bestSC == null) {
initBestSC(scs.get(0));
scs.remove(0);
}
for (SolverConfiguration sc : scs) {
// add 1 random job from the best configuration with the
// priority corresponding to the level
// lower levels -> higher priorities
pacc.addRandomJob(parameters.getMinRuns(), sc, bestSC, Integer.MAX_VALUE - sc.getNumber());
pacc.addSolverConfigurationToListNewSC(sc);
}
}
@Override
public int computeOptimalExpansion(int coreCount, int jobs, int listNewSCSize) {
int res = 0;
if (coreCount < parameters.getMinCPUCount() || coreCount > parameters.getMaxCPUCount()) {
pacc.log("w Warning: Current core count is " + coreCount);
}
int min_sc = (Math.max(Math.round(4.f * coreCount), 8) - jobs) / parameters.getMinRuns();
if (min_sc > 0) {
res = (Math.max(Math.round(6.f * coreCount), 8) - jobs) / parameters.getMinRuns();
}
if (listNewSCSize == 0 && res == 0) {
res = 1;
}
return res;
/*
* TODO: was geschickteres implementieren, denn von diesem Wert haengt
* sehr stark der Grad der parallelisierung statt. denkbar ware noch
* api.getNumComputingUnits(); wenn man die Methode haette. eine andere
* geschicktere Moeglichkeit ist es: Anzahl cores = numCores Gr��e der
* besseren solver configs in letzter runde = numBests Anzahl der jobs
* die in der letzten Iteration berechnet wurden = numJobs Anzahl der
* neuen solver configs beim letzten Aufruf zur�ckgeliefert wurden =
* lastExpansion CPUTimeLimit = time Dann kann man die Anzahl an neuen
* konfigs berechnen durch newNumConfigs = TODO
*/
}
@Override
public List<String> getParameters() {
List<String> p = new LinkedList<String>();
return p;
}
@Override
public List<SolverConfiguration> getBestSolverConfigurations() {
List<SolverConfiguration> res = new LinkedList<SolverConfiguration>();
if (bestSC != null) {
res.add(bestSC);
}
return res;
}
@Override
public void stopEvaluation(List<SolverConfiguration> scs) throws Exception {
for (SolverConfiguration sc : scs) {
stopEvalSolverConfigIds.add(sc.getIdSolverConfiguration());
}
}
@Override
public void raceFinished() {
// TODO Auto-generated method stub
}
}
| true
|
cbf24030710d8ca89f0a14f081fd2ffbd945828c
|
Java
|
iambilalamri/e-min-school
|
/src/main/java/com/bamri/school/repository/FormationRepository.java
|
UTF-8
| 480
| 1.945313
| 2
|
[] |
no_license
|
package com.bamri.school.repository;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import org.springframework.web.bind.annotation.CrossOrigin;
import com.bamri.school.entities.Formation;
@RepositoryRestResource
@CrossOrigin("*")
public interface FormationRepository extends JpaRepository<Formation, Long>{
Optional<Formation> findByCode(String code);
}
| true
|
79bae5ab0b4632e0194aca8f27b999ca4e1abbca
|
Java
|
NetCine/NetCine
|
/Proyecto cine/src/bbdd/BD_Compra.java
|
ISO-8859-10
| 5,363
| 2.8125
| 3
|
[] |
no_license
|
package bbdd;
import java.sql.*;
import modelos.*;
/**
* Clase para lo refente al objeto compra
* @author Javier
*
*/
public class BD_Compra extends BD_Conector {
private static Statement s;
private static ResultSet reg;
public BD_Compra(String file){
super (file);
}
/**
* Metodo para dar de alta una compra
* @author Javier
* @param Compr
* @return
*/
public boolean aadirCompra(Compra Compr){
String consulta = "INSERT INTO compras VALUES('" + Compr.getCodCompra() + "','" +Compr.getCodCliente()+"','" + Compr.getCodSesion() +"','" +Compr.getNumEntradas()+"','" + Compr.getPrecioEntradas() + "')";
try{
this.abrir();
s=c.createStatement();
s.executeUpdate(consulta);
s.close();
this.cerrar();
return true;
}
catch ( SQLException e){
this.cerrar();
return false;
}
}
/**
* Metodo para calcular el codigo de compra
* @author Javier
* @return
*/
public int contadorCompras(){
String consulta = "SELECT COUNT(CodCompra) FROM compras";
int numero=0;
try{
String t="";
this.abrir();
s=c.createStatement();
reg=s.executeQuery(consulta);
if ( reg.next())
numero= reg.getInt(1);
s.close();
this.cerrar();
return numero;
}
catch ( SQLException e){
return -1;
}
}
/**
* Metodo para sacar la ultima compra de un cliente
* @author Javier
* @return
*/
public String UltimaCompraCliente(String codCliente){
String consulta = "SELECT MAX(SUBSTR(codcompra,3,4)) FROM compras WHERE codcliente = '"+codCliente+"'";
String cod="";
try{
String t="";
this.abrir();
s=c.createStatement();
reg=s.executeQuery(consulta);
if ( reg.next())
cod= reg.getString(1);
s.close();
this.cerrar();
return cod;
}
catch ( SQLException e){
return null;
}
}
/**
* Metodo para sacar las entradas compradas para poder restarlas en el campo peliculas y sumarlas en la tabla sesion.
* @author Javier
* @return
*/
public int CantidadUltimaCompra(String codCompra){
String consulta = "SELECT numentradas FROM compras WHERE codcompra = '"+codCompra+"'";
int numero=0;
try{
String t="";
this.abrir();
s=c.createStatement();
reg=s.executeQuery(consulta);
if ( reg.next())
numero= reg.getInt(1);
s.close();
this.cerrar();
return numero;
}
catch ( SQLException e){
return -1;
}
}
/**
* Metodo para sacar el precio de las entradas.
* @author Javier
* @return
*/
public double precioUltimaCompra(String codCompra){
String consulta = "SELECT precioentradas FROM compras WHERE codcompra = '"+codCompra+"'";
int numero=0;
try{
String t="";
this.abrir();
s=c.createStatement();
reg=s.executeQuery(consulta);
if ( reg.next())
numero= reg.getInt(1);
s.close();
this.cerrar();
return numero;
}
catch ( SQLException e){
return -1;
}
}
/**
* Funcion que devuelve el codigo de sesion de la ultima compra (EDITAR COMPRA)
* @author Javier
* @return
*/
public String CodSesionUltimaCompra(String codCompra){
String consulta = "SELECT codsesion FROM compras WHERE codcompra = '"+codCompra+"'";
String cod="";
try{
String t="";
this.abrir();
s=c.createStatement();
reg=s.executeQuery(consulta);
if ( reg.next())
cod= reg.getString(1);
s.close();
this.cerrar();
return cod;
}
catch ( SQLException e){
return "A";
}
}
/**
* Funcion que resta el numero de butacas compradas y el dinero que costaban estas(EDITAR COMPRA)
* @author Javier
* @return
*/
public int RestaButacasyDinero(int entradas, String codCompra, double precio){
String consulta = "UPDATE compras SET numentradas = numentradas - "+entradas+" , precioentradas = precioentradas - "+precio+" WHERE codcompra = '"+codCompra+"'";
try{
this.abrir();
s=c.createStatement();
int n=s.executeUpdate(consulta);
s.close();
this.cerrar();
return n;
}
catch ( SQLException e){
return -1;
}
}
/**
* Funcion que suma el numero de butacas compradas y el dinero que cuestan estas(EDITAR COMPRA)
* @author Javier
* @return
*/
public int SumaButacasyDinero(int entradas, String codCompra, double precio){
String consulta = "UPDATE compras SET numentradas = numentradas + "+entradas+" , precioentradas = precioentradas + "+precio+" WHERE codcompra = '"+codCompra+"'";
try{
this.abrir();
s=c.createStatement();
int n=s.executeUpdate(consulta);
s.close();
this.cerrar();
return n;
}
catch ( SQLException e){
return -1;
}
}
/**
* Funcion para editar el CodSesion de una compra ya realizada(EDITAR PELI)
* @author Javier
* @return
*/
public int EditarNumSesion(String codSesion, String codCompra){
String consulta = "UPDATE compras SET codsesion = '"+codSesion+"' WHERE codcompra = '"+codCompra+"'";
try{
this.abrir();
s=c.createStatement();
int n=s.executeUpdate(consulta);
s.close();
this.cerrar();
return n;
}
catch ( SQLException e){
return -1;
}
}
}
| true
|
93e4a7ceef30601af9a2cf9370886bae013efd3f
|
Java
|
zys870135491/springcloud2020
|
/cloud-customer-order80/src/main/java/com/zys/springcloud/Controller/OrderController.java
|
UTF-8
| 1,171
| 1.976563
| 2
|
[] |
no_license
|
package com.zys.springcloud.Controller;
import com.zys.springcloud.entities.CommonResult;
import com.zys.springcloud.entities.Payment;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
@RestController
public class OrderController {
//public static final String PAYMENT_URL = "http://localhost:8001";
public static final String PAYMENT_URL = "http://CLOUD-PROVIDER-PAYMENT";
/* @Value("${service-url.nacos-user-service}")
private String nacos_user_service;*/
@Resource
private RestTemplate restTemplate;
@GetMapping("/customer/payment/create")
public CommonResult<Payment> create(@RequestBody Payment payment){
return restTemplate.postForObject(PAYMENT_URL + "/payment/create",payment, CommonResult.class);
}
@GetMapping("/customer/payment/get/{id}")
public CommonResult<Payment> orderId(@PathVariable("id")Long id){
CommonResult forObject = restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
return forObject;
}
}
| true
|
b581a25d827390deb61332254744da43f2d45229
|
Java
|
qiuchili/ggnn_graph_classification
|
/program_data/JavaProgramData/22/630.java
|
UTF-8
| 1,174
| 2.828125
| 3
|
[
"MIT"
] |
permissive
|
package <missing>;
public class GlobalMembers
{
public static int Main()
{
void trans(int * x,int * y);
int[] a = new int[300];
int i;
int j;
int n = 0;
String c = new String(new char[300]);
for (i = 1;i <= 300;i++)
{
String tempVar = ConsoleInput.scanfRead();
if (tempVar != null)
{
a[i - 1] = Integer.parseInt(tempVar);
}
String tempVar2 = ConsoleInput.scanfRead(null, 1);
if (tempVar2 != null)
{
c = tangible.StringFunctions.changeCharacter(c, i - 1, tempVar2);
}
n++;
if (c.charAt(i - 1) == '\n')
{
break;
}
}
if (n == 1)
{
System.out.print("No");
}
else
{
for (i = 1;i <= n - 1;i++)
{
for (j = 1;j <= n - i;j++)
{
if (a[j - 1] < a[j])
{
trans((a + j - 1), (a + j));
}
}
}
for (i = 1;i <= n - 1;i++)
{
if (a[i - 1] > a[i])
{
System.out.printf("%d",a[i]);
break;
}
if (i == n - 1)
{
System.out.print("No");
}
}
}
return 0;
}
public static void trans(tangible.RefObject<Integer> x, tangible.RefObject<Integer> y)
{
int z;
z = x.argValue;
x.argValue = y.argValue;
y.argValue = z;
}
}
| true
|
9b0e46094a742841f065f0df19fe0d086a143b2f
|
Java
|
imka239/MethodsTranslation4
|
/src/main/helper/LeafTemplate.java
|
UTF-8
| 402
| 2.28125
| 2
|
[] |
no_license
|
package main.helper;
import java.util.List;
import static main.helper.Templates.*;
public class LeafTemplate {
public void print(AllInfo allInfo) {
List<Leaf> leafs = allInfo.getLeafs();
var leafsStr = new StringBuilder();
leafs.forEach(l -> leafsStr.append(l.name.toUpperCase()).append(','));
makeSource("Leaf", String.format(enumTemplate, leafsStr));
}
}
| true
|
a7de8ad6acb307541676b196286e9f3edd745825
|
Java
|
Elblonko/kepler
|
/display-redirect/src/au/edu/jcu/kepler/hydrant/MonitorValueBatch.java
|
UTF-8
| 3,334
| 2.03125
| 2
|
[] |
no_license
|
/*
* Copyright (C) 2007-2008 James Cook University (http://www.jcu.edu.au).
*
* This program was developed as part of the ARCHER project (Australian
* (Research Enabling Environment) funded by a Systemic Infrastructure
* Initiative (SII) grant and supported by the Australian Department of
* Innovation, Industry, Science and Research.
* Permission is hereby granted, without written agreement and without
* license or royalty fees, to use, copy, modify, and distribute this
* software and its documentation for any purpose, provided that the above
* copyright notice and the following two paragraphs appear in all copies
* of this software.
* IN NO EVENT SHALL THE JAMES COOK UNIVERSITY BE LIABLE TO ANY PARTY FOR
* DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING
* OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE
* JAMES COOK UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* THE JAMES COOK UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
* PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE JAMES COOK UNIVERSITY
* HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
* ENHANCEMENTS, OR MODIFICATIONS.
*/
package au.edu.jcu.kepler.hydrant;
import java.util.HashMap;
import ptolemy.actor.injection.PortableContainer;
import ptolemy.actor.lib.Sink;
import ptolemy.actor.lib.gui.MonitorValue;
import ptolemy.actor.lib.gui.TextFieldContainerInterface;
import ptolemy.data.StringToken;
import ptolemy.data.Token;
import ptolemy.kernel.util.IllegalActionException;
import ptolemy.kernel.util.NameDuplicationException;
///////////////////////////////////////////////////////////////////
////MonitorValueBatch
/**
<p>
MonitorValueBatch is the implementation of the TextFieldContainerInterface that saves the content for
ptolemy.actor.lib.gui.MonitorValue actor into a file.
</p>
@author Jianwu Wang
@version $Id: MonitorValueBatch.java 62778 2012-01-12 04:21:43Z cxh $
@since Kepler 2.3
*/
public class MonitorValueBatch implements TextFieldContainerInterface {
@Override
public void init(Sink sink) throws IllegalActionException,
NameDuplicationException {
_monitorValue = (MonitorValue) sink;
}
@Override
public void place(PortableContainer container) {
// TODO Auto-generated method stub
}
@Override
public void setValue(Token token) {
// write tokens to the output source
// _output.append(tokenValue+"\n");
// System.out.println(_output);
// System.out.println("--------");
ReplacementManager man = ReplacementUtils
.getReplacementManager(_monitorValue);
HashMap data_map = new HashMap();
// String name = title.getExpression();
String name = _monitorValue.getFullName();
data_map.put("name", name);
data_map.put("type", _type);
data_map.put("append", false);
String value = token.toString();
if (token instanceof StringToken) {
value = ((StringToken) token).stringValue();
}
data_map.put("output", value);
man.writeData(data_map);
_output = null;
}
/** Reference to the MonitorValue actor */
private MonitorValue _monitorValue;
private StringBuffer _output;
private String _type = "txt";
}
| true
|
2542ade812eede2e382882814214c5e139d5d747
|
Java
|
empratysg/Study-And-Example
|
/app/src/main/java/com/genie/study/texttimer/TimerTextViewFragment.java
|
UTF-8
| 2,404
| 2.234375
| 2
|
[] |
no_license
|
package com.genie.study.texttimer;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import com.genie.study.R;
/**
* Created by Genie on 7/8/2017.
*/
public class TimerTextViewFragment extends Fragment implements View.OnClickListener {
private static final String EXTRA_INPUT_SOURCE = "extra_input_source";
private TimerTextView timerTextView;
private EditText input;
private String inputSource;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null)
inputSource = savedInstanceState.getString(EXTRA_INPUT_SOURCE);
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(EXTRA_INPUT_SOURCE, inputSource);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_timer, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
timerTextView = view.findViewById(R.id.timer);
input = view.findViewById(R.id.input_time);
view.findViewById(R.id.change_fragment).setOnClickListener(this);
view.findViewById(R.id.set_input).setOnClickListener(this);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.change_fragment:
getFragmentManager().beginTransaction().replace(R.id.frame, new AnotherFragment()).addToBackStack(null).commit();
break;
case R.id.set_input:
String source = input.getText().toString();
if (!TextUtils.isEmpty(source.trim())) {
inputSource = source;
timerTextView.setSourceTime(source);
}
break;
}
}
}
| true
|
80775a1dd93fcba9168718bc4830eeda44e0e65c
|
Java
|
laoqianlaile/xwoa
|
/02branches/kxoa/src/main/java/com/centit/bbs/service/impl/VBbsThemeUserManagerImpl.java
|
UTF-8
| 1,440
| 1.9375
| 2
|
[] |
no_license
|
package com.centit.bbs.service.impl;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.centit.bbs.dao.VBbsThemeReplayDao;
import com.centit.bbs.dao.VBbsThemeUserDao;
import com.centit.bbs.po.VBbsThemeReplay;
import com.centit.bbs.po.VBbsThemeUser;
import com.centit.bbs.service.VBbsThemeUserManager;
import com.centit.core.service.BaseEntityManagerImpl;
import com.centit.core.utils.PageDesc;
public class VBbsThemeUserManagerImpl extends
BaseEntityManagerImpl<VBbsThemeUser> implements VBbsThemeUserManager {
private static final long serialVersionUID = 1L;
public static final Log log = LogFactory.getLog(VBbsThemeUserManager.class);
private VBbsThemeUserDao vBbsThemeUserDao;
private VBbsThemeReplayDao vBbsThemeReplayDao;
public void setVBbsThemeUserDao(VBbsThemeUserDao baseDao) {
this.vBbsThemeUserDao = baseDao;
setBaseDao(this.vBbsThemeUserDao);
}
@Override
public List<VBbsThemeReplay> getThemeReplyList(Map<String, Object> filterMap, PageDesc pageDesc) {
return vBbsThemeReplayDao.listObjects(filterMap, pageDesc);
}
public VBbsThemeReplayDao getvBbsThemeReplayDao() {
return vBbsThemeReplayDao;
}
public void setvBbsThemeReplayDao(VBbsThemeReplayDao vBbsThemeReplayDao) {
this.vBbsThemeReplayDao = vBbsThemeReplayDao;
}
}
| true
|
434afbf761779a0ab781f56331adaebd5a8d4d62
|
Java
|
DevrisOfStar/SWEA
|
/src/Problem_6958/Solution.java
|
UTF-8
| 901
| 3.40625
| 3
|
[
"MIT"
] |
permissive
|
package Problem_6958;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Solution {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
for (int t = 1; t <= T; t++) {
String temp = br.readLine();
int N = Integer.parseInt(temp.split(" ")[0]);
int M = Integer.parseInt(temp.split(" ")[1]);
int a = 0; // 사람수
int b = 0; // 정답수
for(int i = 0; i< N; i++) {
temp = br.readLine();
int tem = 0;
for(int j = 0 ; j < M; j++) {
if(temp.charAt(j*2) == '1') tem++;
}
if(b < tem) {
b = tem;
a = 1;
}
else if(b == tem) {
a++;
}
}
System.out.printf("#%d %d %d\n",t, a, b);
}
}
}
| true
|
bf9566238dd5a0a7b2f42c89a1b55c2ec22fb89d
|
Java
|
simingye/leetcode
|
/src/RemoveLinkedListElements/RemoveLinkedListElements.java
|
UTF-8
| 1,235
| 3.65625
| 4
|
[] |
no_license
|
package RemoveLinkedListElements;
/**
* Created by Siming on 6/19/15.
*/
public class RemoveLinkedListElements
{
public ListNode removeElements (ListNode head, int val)
{
if (head == null)
return null;
ListNode current = head.next;
ListNode previous = head;
ListNode newHead = head;
while ( current != null)
{
if (current.val == val)
{
previous.next = current.next;
current = current.next;
}
else
{
current = current.next;
previous = previous.next;
}
}
while (newHead != current)
{
if (newHead.val == val)
{
newHead = newHead.next;
}
else
{
return newHead;
}
}
return newHead;
}
public static void main(String[] args) {
RemoveLinkedListElements test = new RemoveLinkedListElements();
ListNode node1 = new ListNode(1);
ListNode node2 = new ListNode(1);
node1.next = node2;
System.out.println(test.removeElements(node1,1));
}
}
| true
|
25a29aa336f2557818d00150798ed2cd309a39f4
|
Java
|
Hvosten/JavaFXProjects
|
/src/main/java/SimpleCalculator/Controller.java
|
UTF-8
| 8,659
| 2.875
| 3
|
[] |
no_license
|
package SimpleCalculator;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
import javafx.scene.layout.GridPane;
public class Controller {
@FXML private GridPane gridBox;
@FXML private TextField displayField;
@FXML private Button zeroButton;
@FXML private Button oneButton;
@FXML private Button twoButton;
@FXML private Button threeButton;
@FXML private Button fourButton;
@FXML private Button fiveButton;
@FXML private Button sixButton;
@FXML private Button sevenButton;
@FXML private Button eightButton;
@FXML private Button nineButton;
@FXML private Button doubleZeroButton;
@FXML private Button dotButton;
@FXML private Button clearButton;
@FXML private Button deleteButton;
@FXML private Button revertButton;
@FXML private Button leftBracketButton;
@FXML private Button rightBracketButton;
@FXML private Button additionButton;
@FXML private Button subtractionButton;
@FXML private Button divisionButton;
@FXML private Button multiplicationButton;
@FXML private Button equalButton;
private String currDisplay = "0";
private String previousOperation = "n/a";
private final MathEvaluator evaluator = new MathEvaluator();
private static final int MAX_LENGTH = 30;
public void initialize(){
setNewDisplay();
addListeners();
}
private void setNewDisplay() {
displayField.textProperty().setValue(currDisplay);
}
private void addListeners() {
addKeyListeners();
addButtonListeners();
}
private void addButtonListeners() {
zeroButton.setOnAction(onClickAddToDisplay("0"));
oneButton.setOnAction(onClickAddToDisplay("1"));
twoButton.setOnAction(onClickAddToDisplay("2"));
threeButton.setOnAction(onClickAddToDisplay("3"));
fourButton.setOnAction(onClickAddToDisplay("4"));
fiveButton.setOnAction(onClickAddToDisplay("5"));
sixButton.setOnAction(onClickAddToDisplay("6"));
sevenButton.setOnAction(onClickAddToDisplay("7"));
eightButton.setOnAction(onClickAddToDisplay("8"));
nineButton.setOnAction(onClickAddToDisplay("9"));
doubleZeroButton.setOnAction(onClickAddToDisplay("00"));
leftBracketButton.setOnAction(onClickAddToDisplay("("));
rightBracketButton.setOnAction(onClickAddToDisplay(")"));
additionButton.setOnAction(onClickAddOperation("+"));
subtractionButton.setOnAction(onClickAddOperation("-"));
divisionButton.setOnAction(onClickAddOperation("/"));
multiplicationButton.setOnAction(onClickAddOperation("*"));
dotButton.setOnAction(onClickAddOperation("."));
clearButton.setOnAction(event -> {
currDisplay = "0";
setNewDisplay();
});
deleteButton.setOnAction(event -> {
currDisplay = (currDisplay.length()==1 || !noErrorOnDisplay()) ? "0" : currDisplay.substring(0,currDisplay.length()-1);
setNewDisplay();
});
equalButton.setOnAction(event -> {
if(noErrorOnDisplay()){
previousOperation = currDisplay;
try {
currDisplay = evaluator.calculate(currDisplay).stripTrailingZeros().toPlainString();
} catch (Exception e) {
currDisplay = "ERROR";
}
setNewDisplay();
}
});
revertButton.setOnAction(event -> {
if(!previousOperation.equals("n/a")){
currDisplay = previousOperation;
setNewDisplay();
}
});
}
private void addKeyListeners() {
gridBox.setOnKeyPressed(keyEvent -> {
KeyCombination plusCombination = new KeyCodeCombination(KeyCode.EQUALS,KeyCombination.SHIFT_DOWN);
KeyCombination leftBracketCombination = new KeyCodeCombination(KeyCode.DIGIT9,KeyCombination.SHIFT_DOWN);
KeyCombination rightBracketCombination = new KeyCodeCombination(KeyCode.DIGIT0,KeyCombination.SHIFT_DOWN);
String addend = "";
if(plusCombination.match(keyEvent)){
addend = "+";
if(noErrorOnDisplay() && isPlaceOnDisplay(addend))
currDisplay += addend;
}
else if(leftBracketCombination.match(keyEvent)){
addend = "(";
if (noErrorOnDisplay() && isPlaceOnDisplay(addend))
currDisplay = (currDisplay.equals("0")) ? addend : currDisplay + addend;
}
else if(rightBracketCombination.match(keyEvent)){
addend = ")";
if (noErrorOnDisplay() && isPlaceOnDisplay(addend))
currDisplay = (currDisplay.equals("0")) ? addend : currDisplay + addend;
}
else {
switch (keyEvent.getCode()) {
case BACK_SPACE:
currDisplay = (currDisplay.length() == 1 || !noErrorOnDisplay()) ? "0" : currDisplay.substring(0, currDisplay.length() - 1);
break;
case DELETE:
currDisplay = "0";
break;
case DIGIT0:
case DIGIT1:
case DIGIT2:
case DIGIT3:
case DIGIT4:
case DIGIT5:
case DIGIT6:
case DIGIT7:
case DIGIT8:
case DIGIT9:
case NUMPAD0:
case NUMPAD1:
case NUMPAD2:
case NUMPAD3:
case NUMPAD4:
case NUMPAD5:
case NUMPAD6:
case NUMPAD7:
case NUMPAD8:
case NUMPAD9:
addend = keyEvent.getText();
if (noErrorOnDisplay() && isPlaceOnDisplay(addend))
currDisplay = (currDisplay.equals("0")) ? addend : currDisplay + addend;
break;
case ADD:
case MINUS:
case SUBTRACT:
case DIVIDE:
case SLASH:
case MULTIPLY:
case PERIOD:
addend = keyEvent.getText();
if (noErrorOnDisplay() && isPlaceOnDisplay(addend))
currDisplay += addend;
break;
case DECIMAL:
addend = ".";
if (noErrorOnDisplay() && isPlaceOnDisplay(addend))
currDisplay += addend;
break;
case EQUALS:
if (noErrorOnDisplay()) {
previousOperation = currDisplay;
try {
currDisplay = evaluator.calculate(currDisplay).stripTrailingZeros().toPlainString();
} catch (Exception e) {
currDisplay = "ERROR";
}
}
break;
case R:
if (!previousOperation.equals("n/a"))
currDisplay = previousOperation;
break;
}
}
setNewDisplay();
});
}
private EventHandler<ActionEvent> onClickAddToDisplay(String addend){
return event -> {
if(noErrorOnDisplay() && isPlaceOnDisplay(addend)){
currDisplay = (currDisplay.equals("0")) ? addend : currDisplay + addend;
setNewDisplay();
}
};
}
private EventHandler<ActionEvent> onClickAddOperation(String operand){
return event -> {
if(noErrorOnDisplay() && isPlaceOnDisplay(operand)){
currDisplay += operand;
setNewDisplay();
}
};
}
private boolean noErrorOnDisplay() {
return !currDisplay.equals("ERROR");
}
private boolean isPlaceOnDisplay(String addend) {
return currDisplay.length() + addend.length() <= MAX_LENGTH;
}
}
| true
|
86c8c9351ce0d0de8b3cd2ebb3cd1f8981d96be8
|
Java
|
ocpadm/instruction
|
/frontend-web/src/main/java/com/nocom/inst/util/Resources.java
|
UTF-8
| 2,834
| 1.875
| 2
|
[] |
no_license
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2015, Red Hat, Inc. and/or its affiliates, and individual
* contributors by the @authors tag. See the copyright.txt in the
* distribution for a full listing of individual contributors.
*
* 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.nocom.inst.util;
import java.net.URI;
import java.net.URISyntaxException;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import org.apache.commons.lang3.exception.ContextedRuntimeException;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import com.nocom.inst.keycloak.BearerTokenFilter;
import com.nocom.inst.rest.MemberResourceRESTService;
import com.nocom.inst.websockets.MemberClientEndpoint;
/**
* This class uses CDI to alias Java EE resources, such as the persistence context, to CDI beans
*
* <p>
* Example injection on a managed bean field:
* </p>
*
* <pre>
* @Inject
* private EntityManager em;
* </pre>
*/
public class Resources {
@Inject
BearerTokenFilter bearerTokenFilter;
@Produces
@RequestScoped
public FacesContext produceFacesContext() {
return FacesContext.getCurrentInstance();
}
/**
*
* Construct RestEasy proxied service endpoint.
*
* @param CDI
* Injection Point
* @return JAX-RS WebTarget for resourcing members
*/
@Produces
MemberResourceRESTService getRESTClient(InjectionPoint ip) {
return new ResteasyClientBuilder().connectionPoolSize(20).build().target(System.getProperty("MemberEndpointURL")).register(bearerTokenFilter).proxy(MemberResourceRESTService.class);
}
/**
*
* construct WebSockets client endpointt.
*
* @param CDI
* Injection Point
* @return WebSockets client endpoint
*/
@Produces
MemberClientEndpoint getWebSocketsClient(InjectionPoint ip) {
try {
return new MemberClientEndpoint(new URI(System.getProperty("MemberWebSocketsEndpointURL")));
} catch (URISyntaxException e) {
throw new ContextedRuntimeException(e).addContextValue("URI ", System.getProperty("MemberWebSocketsEndpointURL"));
}
}
}
| true
|
c6617f6ebe0c0d5798da0ba2572114b1df0edaa8
|
Java
|
adilkhansatemirov/AlgorithmsAndOther
|
/Week_7-14/src/Week13/HashMap.java
|
UTF-8
| 924
| 3.34375
| 3
|
[] |
no_license
|
package Week13;
import java.util.Map;
public class HashMap {
public static void main(String[] args) {
Map<String,String> map = new java.util.HashMap<>();
map.put("a","astronaut");
map.put("b","builder");
System.out.println(mapBully(map));
}
public static Map<String,String> mapBully(Map<String, String> map){
if(!(map.get("a")==null)){
map.put("b",map.get("a"));
map.put("a","");
}
return map;
}
public static Map<String, String> mapShare(Map<String, String> map) {
map.remove("c");
if(map.containsKey("a")){
map.put("b",map.get("a"));
}
return map;
}
public static Map<String, String> mapAB(Map<String, String> map) {
if(map.containsKey("a") && map.containsKey("b")){
map.put("ab",map.get("a")+map.get("b"));
}
return map;
}
}
| true
|
d3745deb50fc7d14cdd8cf853b4e76d21b1d7201
|
Java
|
Thunderducky/TOTNSmain
|
/src/eric/prototype/camera/BasicGame.java
|
UTF-8
| 2,274
| 2.328125
| 2
|
[] |
no_license
|
package eric.prototype.camera;
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display; // Import LWJGL Display
import org.lwjgl.opengl.DisplayMode; // Import LWJGL DisplayMode
import org.lwjgl.opengl.GL11; // Import LWJGL GL11
import org.lwjgl.input.Keyboard; // Import LWJGL Input
import org.lwjgl.input.Mouse;
import javax.swing.JOptionPane; // Import Swing JOptionPane
import org.lwjgl.util.glu.GLU;
import org.newdawn.slick.opengl.TextureLoader;
import org.newdawn.slick.util.ResourceLoader;
import com.linearoja.Assets;
import com.linearoja.cm.Image;
public class BasicGame {
private boolean done = false;
private float rotquad = 0.0f;
private Cube testCube;
Renderer gameRenderer;
CameraController cc;
public BasicGame() throws LWJGLException
{
gameRenderer = new Renderer();
}
public void Initialize()
{
// Set the Matrices
gameRenderer.Initialize();
testCube = new Cube();
Mouse.setCursorPosition(400, 300);
Mouse.setGrabbed(true);
cc = new CameraController(gameRenderer.camera);
try
{
Image image = Assets.camerademoassets.images.Grass;
image.loadData();
testCube.texture = image.getTexture();
testCube.ApplyTextureDefault();
}
catch(Exception e)
{
}
}
public boolean Update()
{
int dx = Mouse.getDX();
int dy = Mouse.getDY();
cc.camera.yaw += dx * 0.05f;
cc.camera.pitch -= dy * 0.05f;
float speed = 0.0005f;
if(Keyboard.isKeyDown(Keyboard.KEY_W))
cc.walkForward(speed, cc.camera.yaw);
if(Keyboard.isKeyDown(Keyboard.KEY_S))
cc.walkBackwards(speed, cc.camera.yaw);
if(Keyboard.isKeyDown(Keyboard.KEY_A))
cc.strafeLeft(speed, cc.camera.yaw);
if(Keyboard.isKeyDown(Keyboard.KEY_D))
cc.strafeRight(speed, cc.camera.yaw);
if(Keyboard.isKeyDown(Keyboard.KEY_SPACE))
cc.camera.position.y -= speed;
if(Keyboard.isKeyDown(Keyboard.KEY_LSHIFT))
cc.camera.position.y += speed;
gameRenderer.DrawCube(testCube);
done = Keyboard.isKeyDown(Keyboard.KEY_ESCAPE) || Display.isCloseRequested();
return !done;
}
public void Shutdown()
{
Display.destroy();
}
}
| true
|
fd6bd0a53f3aac9afa04b704e00c3c8fae047aee
|
Java
|
cerenercan/seniorproj
|
/main/java/com/example/resources/Current.java
|
UTF-8
| 309
| 1.65625
| 2
|
[] |
no_license
|
package com.example.resources;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.*;
import org.springframework.web.client.RestTemplate;
import java.text.DecimalFormat;
@Getter
@Setter
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class Current {
private Double temp_c;
}
| true
|
6f0b15bca11cdadeff2fdb25523d27e0805b2656
|
Java
|
AliceBlog/aliceBlog-java
|
/core/src/main/java/com/witdor/core/model/TechnologyFilesModel.java
|
UTF-8
| 1,682
| 2.34375
| 2
|
[
"MIT"
] |
permissive
|
package com.witdor.core.model;
import com.witdor.core.model.base.BaseModel;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.io.Serializable;
/**
* 把今天最好的表现当作明天最新的起点..~
* いま 最高の表現 として 明日最新の始発..~
* Today the best performance as tomorrow newest starter!
* Created by IntelliJ IDEA.
*
* @author: xiaomo
* @github: https://github.com/qq83387856
* @email: hupengbest@163.com
* @QQ_NO: 83387856
* @Date: 2016/9/5 17:17
* @Description: 技术文档表
* @Copyright(©) 2016 by xiaomo.
**/
@Entity
@Table(name = "technology")
public class TechnologyFilesModel extends BaseModel implements Serializable {
@Column(name = "title", columnDefinition = "text")
private String title;
@Column(name = "content", columnDefinition = "longtext")
private String content;
private String author;
private String img;
private String[] tags;
public String[] getTags() {
return tags;
}
public void setTags(String[] tags) {
this.tags = tags;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
}
| true
|
a566d220d97285c097144417b710ba8e18ab08e9
|
Java
|
frc-2175/SwerveDriveRobot
|
/src/org/usfirst/frc2175/pid/WheelSpeedPIDController.java
|
UTF-8
| 1,229
| 2.609375
| 3
|
[] |
no_license
|
package org.usfirst.frc2175.pid;
import org.usfirst.frc2175.config.RobotConfig;
import org.usfirst.frc2175.loopers.Loopable;
import edu.wpi.first.wpilibj.CANTalon;
import edu.wpi.first.wpilibj.Encoder;
public class WheelSpeedPIDController extends PIDController implements Loopable {
private CANTalon driveTalon;
private Encoder driveEncoder;
private double tolerance;
public WheelSpeedPIDController(CANTalon driveTalon, Encoder driveEncoder,
RobotConfig robotConfig) {
double p = robotConfig.getControlLoopConfig().getSpeedPID_p();
double i = robotConfig.getControlLoopConfig().getSpeedPID_i();
double d = robotConfig.getControlLoopConfig().getSpeedPID_d();
setPID(p, i, d);
double min = -robotConfig.getControlLoopConfig().getSpeedPID_range();
double max = robotConfig.getControlLoopConfig().getSpeedPID_range();
setOutputRange(min, max);
this.tolerance =
robotConfig.getControlLoopConfig().getAnglePID_tolerance();
}
public boolean isOnTarget() {
return onTarget(tolerance);
}
@Override
public void update() {
driveTalon.set(calculate(driveEncoder.getDistance()));
}
}
| true
|
770c89f5f6322a0224e552b9eea995b458675f17
|
Java
|
Libbomc/jx
|
/src/main/java/com/mall/service/impl/AboutusServiceImpl.java
|
UTF-8
| 1,528
| 2.078125
| 2
|
[] |
no_license
|
package com.mall.service.impl;
import com.mall.dao.AboutusMapper;
import com.mall.pojo.Aboutus;
import com.mall.service.AboutusService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Created by on 2018/4/10.
*/
@Service("AboutusService")
public class AboutusServiceImpl implements AboutusService {
@Autowired
private AboutusMapper aboutusMapper;
@Override
public boolean addAboutus(Aboutus aboutus) {
boolean flag = false;
try {
aboutusMapper.insert(aboutus);
flag = true;
} catch (Exception e) {
System.out.println("添加失败");
e.printStackTrace();
}
return flag;
}
@Override
public boolean updateAboutus(Aboutus aboutus) {
boolean flag = false;
try {
aboutusMapper.updateByPrimaryKeySelective(aboutus);
flag = true;
} catch (Exception e) {
System.out.println("修改失败");
e.printStackTrace();
}
return flag;
}
public boolean deleteAboutus(Integer aboutusId) {
boolean flag = false;
//System.out.println(aboutusId);
try {
aboutusMapper.deleteByPrimaryKey(aboutusId);
//System.out.println(aboutusId);
flag = true;
} catch (Exception e) {
System.out.println("删除失败");
e.printStackTrace();
}
return flag;
}
}
| true
|
ff92ab3e568dd154f23357cede9e0d02883a29c0
|
Java
|
yuexiaoguang/spring4
|
/spring-messaging/src/main/java/org/springframework/messaging/handler/HandlerMethodSelector.java
|
UTF-8
| 1,064
| 2.421875
| 2
|
[] |
no_license
|
package org.springframework.messaging.handler;
import java.lang.reflect.Method;
import java.util.Set;
import org.springframework.core.MethodIntrospector;
import org.springframework.util.ReflectionUtils.MethodFilter;
/**
* 定义用于搜索处理器方法的算法, 包括接口和父类, 同时还处理参数化方法以及接口和基于类的代理.
*
* @deprecated as of Spring 4.2.3, in favor of the generalized and refined {@link MethodIntrospector}
*/
@Deprecated
public abstract class HandlerMethodSelector {
/**
* 选择给定处理器类型的处理器方法.
* <p>调用者通过{@link MethodFilter}参数定义感兴趣的处理器方法.
*
* @param handlerType 用于搜索处理器方法的处理器类型
* @param handlerMethodFilter 帮助识别感兴趣的处理器方法的{@link MethodFilter}
*
* @return 选定的方法, 或空集
*/
public static Set<Method> selectMethods(Class<?> handlerType, MethodFilter handlerMethodFilter) {
return MethodIntrospector.selectMethods(handlerType, handlerMethodFilter);
}
}
| true
|
6cfb368790843d8080e90c59e0931e08a29ec97c
|
Java
|
grudloff/POO-Tarea_1
|
/Etapa2/MyWorld.java
|
UTF-8
| 685
| 3.03125
| 3
|
[] |
no_license
|
import java.io.*;
public class MyWorld {
private double t0=0;
public MyWorld(){
this(System.out);
}
public MyWorld(PrintStream output){
out=output;
}
public void setRobot(Robot r) {
this.r=r;
}
public void printStateDescription(){
out.println("Time" + ",\t" + r.getDescription());
}
private void printState(double t){
out.println(t + ",\t" + r.toString());
}
public void simulate (double delta_t, double endTime) { // simulate time passing by
for (double t=t0 ; t < endTime; t += delta_t) {
r.moveDelta_t(delta_t);
printState(t);
t0=t;
}
}
private Robot r;
private PrintStream out;
}
| true
|
b4e3ced9cc79aa21258a255b5007957b672565ae
|
Java
|
hhungit/java-crm-api
|
/src/main/java/com/bys/crm/domain/erp/model/BRBranchs.java
|
UTF-8
| 4,207
| 1.835938
| 2
|
[] |
no_license
|
package com.bys.crm.domain.erp.model;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.hibernate.annotations.Type;
import org.joda.time.DateTime;
import com.bys.crm.domain.DomainEntity;
import com.bys.crm.domain.erp.constant.AAStatus;
@Entity
@Table(name = "BRBranchs")
public class BRBranchs extends DomainEntity<Integer> {
@Id
@Column(name = "BRBranchID")
private Integer id;
@Column(name = "BRBranchName")
private String name;
@Column(name = "BRBranchNo")
private String branchNumber;
@Column(name = "BRBranchDesc")
private String description;
@Column(name = "BRBranchType")
private String type;
@Column(name = "BRBranchActiveCheck")
private Boolean check;
@Column(name = "BRBranchParentID")
private Long parentId;
@Column(name = "BRBranchBankCode")
private String bankCode;
@Column(name = "BRBranchBankName")
private String bankName;
@Column(name = "BRBranchTaxNumber")
private String tax;
@Column(name = "BRBranchContactLevel")
private String contactLevel;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "FK_GELocationID")
private GELocations location;
@Column(name = "AAStatus")
private String status;
@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
@Column(name = "AACreatedDate")
private DateTime createdDate;
@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
@Column(name = "AAUpdatedDate")
private DateTime modifiedDate;
@ManyToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE })
@JoinTable(name = "HREmployeeGroups",
joinColumns = @JoinColumn(name = "FK_BRBranchID"),
inverseJoinColumns = @JoinColumn(name = "FK_HREmployeeID"))
private Set<HREmployees> employees;
public BRBranchs() {
this.status = AAStatus.Alive.name();
this.check = true;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBranchNumber() {
return branchNumber;
}
public void setBranchNumber(String branchNumber) {
this.branchNumber = branchNumber;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Boolean isCheck() {
return check;
}
public void setCheck(Boolean check) {
this.check = check;
}
public Long getParentId() {
return parentId;
}
public void setParentId(Long parentId) {
this.parentId = parentId;
}
public String getBankCode() {
return bankCode;
}
public void setBankCode(String bankCode) {
this.bankCode = bankCode;
}
public String getBankName() {
return bankName;
}
public void setBankName(String bankName) {
this.bankName = bankName;
}
public String getTax() {
return tax;
}
public void setTax(String tax) {
this.tax = tax;
}
public GELocations getLocation() {
return location;
}
public void setLocation(GELocations location) {
this.location = location;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public DateTime getCreatedDate() {
return createdDate;
}
public void setCreatedDate(DateTime createdDate) {
this.createdDate = createdDate;
}
public DateTime getModifiedDate() {
return modifiedDate;
}
public void setModifiedDate(DateTime modifiedDate) {
this.modifiedDate = modifiedDate;
}
public String getContactLevel() {
return contactLevel;
}
public void setContactLevel(String contactLevel) {
this.contactLevel = contactLevel;
}
public Set<HREmployees> getEmployees() {
return employees;
}
public void setEmployees(Set<HREmployees> employees) {
this.employees = employees;
}
}
| true
|
69a01051940506734aa3a4beeaaa3298a0a16a94
|
Java
|
alexguterres/aonde-almocar
|
/src/main/java/com/guterres/module/votacao/rest/VotingController.java
|
UTF-8
| 638
| 2.03125
| 2
|
[] |
no_license
|
package com.guterres.module.votacao.rest;
import org.springframework.web.bind.annotation.RestController;
import com.guterres.module.votacao.domain.Restaurant;
import com.guterres.module.votacao.domain.dto.VotingResponse;
import com.guterres.module.votacao.service.VotingService;
import com.guterres.module.votacao.service.impl.VotingServiceImpl;
@RestController
public class VotingController {
private VotingService votingService = new VotingServiceImpl();
public Restaurant result() {
return null;
}
public VotingResponse vote(Long idUsuario, Long idRestaurant) {
return votingService.vote(idUsuario, idRestaurant);
}
}
| true
|
d10b5e5ea28e0b4c4ad805d1cc69b6cc6d35a07f
|
Java
|
andrejss88/AutomationFramework
|
/java11-httpclient/src/test/java/com/github/statuscodes/AsyncPlayground.java
|
UTF-8
| 2,393
| 2.828125
| 3
|
[] |
no_license
|
package com.github.statuscodes;
import org.junit.jupiter.api.Test;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpHeaders;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import static java.net.http.HttpResponse.BodyHandlers;
import static java.util.stream.Collectors.joining;
class AsyncPlayground {
@Test
void printAllDetails() {
var client = HttpClient.newHttpClient();
var request = HttpRequest.newBuilder()
.GET()
.setHeader("User-Agent", "Java 11 HttpClient Bot")
.uri(URI.create("https://api.github.com/"))
.build();
CompletableFuture<HttpResponse<String>> future = client.sendAsync(request, BodyHandlers.ofString());
Function<HttpResponse<String>, String> extractBody = HttpResponse::body;
Function<HttpResponse<String>, HttpHeaders> extractHeaders = HttpResponse::headers;
Function<HttpResponse<String>, HttpRequest> extractRequest = HttpResponse::request;
future.thenApply(extractBody)
.thenApply(req -> {
System.out.println("Response body is: ");
System.out.println(req);
return req;
});
future.thenApply(extractHeaders)
.thenApply(headers -> {
System.out.println("Response headers are: ");
prettyPrintMap(headers.map());
return headers;
});
future.thenApply(extractRequest)
.thenApply(req -> {
System.out.println("Request Sent: ");
System.out.println(req);
System.out.println("Request Headers were: ");
prettyPrintMap(req.headers().map());
return req;
});
future.join(); // block until CompletableFuture is complete
}
private static void prettyPrintMap(Map<String, List<String>> req) {
String content = req.entrySet()
.stream()
.map(e -> e.getKey() + "=\"" + e.getValue() + "\"")
.collect(joining(" \n "));
System.out.println(content);
}
}
| true
|
9bfa1c5296b42e982e9b190ccb304ba97f2f24df
|
Java
|
maxis7567/Learning-Blocks
|
/app/src/main/java/com/nova/maxis7567/learningblocks1/tools/Picasso.java
|
UTF-8
| 1,915
| 2.453125
| 2
|
[] |
no_license
|
package com.nova.maxis7567.learningblocks1.tools;
import android.util.Log;
import android.widget.ImageView;
import com.nova.maxis7567.learningblocks1.R;
import com.squareup.picasso.Callback;
import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.NetworkPolicy;
public class Picasso {
public static void load(final String url, final ImageView imageView, final int placeHolder){
if (url==null){
com.squareup.picasso.Picasso.get().load(R.drawable.template_image1);
}else
com.squareup.picasso.Picasso.get()
.load(url)
.networkPolicy(NetworkPolicy.OFFLINE)
.placeholder(placeHolder)
.into(imageView, new Callback() {
@Override
public void onSuccess() {
Log.e("Picasso", "fetch image success in first time.");
}
@Override
public void onError(Exception e) {
com.squareup.picasso.Picasso.get().load(url)
.networkPolicy(NetworkPolicy.NO_CACHE)
.memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
.placeholder(placeHolder)
.into(imageView, new Callback() {
@Override
public void onSuccess() {
Log.e("Picasso", "fetch image success in try again.");
}
@Override
public void onError(Exception e) {
Log.e("Picasso", e.getMessage());
}
});
}
});
}
}
| true
|
84912e61ea1a000d15807283b64a04c55d62acea
|
Java
|
xypp3/AndroidOfflineAudio
|
/ClientSide/app/src/main/java/com/example/lessonia/AudioPlayer.java
|
UTF-8
| 4,821
| 2.46875
| 2
|
[] |
no_license
|
package com.example.lessonia;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.net.Uri;
import android.os.Bundle;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class AudioPlayer extends AppCompatActivity {
Button playButton;
SeekBar positionBar;
TextView elapsedTimeLabel, remainingTimeLabel, titleLabel;
MediaPlayer mediaPlayer;
int totalTime;
String fileName, filePath; // default value
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audio_player);
//Init data from intent (passed on from previous activity)
fileName = getIntent().getStringExtra("titleLabel");
filePath = getIntent().getStringExtra("filePath");
// Set up action bar
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true); // back button
playButton = (Button) findViewById(R.id.playButton);
elapsedTimeLabel = (TextView) findViewById(R.id.elapsedTimeLabel);
remainingTimeLabel = (TextView) findViewById(R.id.remainingTimeLabel);
titleLabel = (TextView) findViewById(R.id.titleLabel);
titleLabel.setText(fileName);
// Initialize media player
// if (!fileName.equals("MV_Jack_Stauber_Buttercup.mp3")){
// mediaPlayer = MediaPlayer.create(this, R.raw.music);
// }else{
// //TODO try media player below when files added
// }
mediaPlayer = MediaPlayer.create(this, Uri.parse(filePath));
mediaPlayer.setLooping(false);
mediaPlayer.seekTo(0);
mediaPlayer.setVolume(0.5f,0.5f);
totalTime = mediaPlayer.getDuration();
// Time tracker Bar
positionBar = (SeekBar) findViewById(R.id.positionBar);
positionBar.setMax(totalTime);
positionBar.setOnSeekBarChangeListener(
new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int time, boolean user) {
if (user){
mediaPlayer.seekTo(time);
positionBar.setProgress(time);
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {}
}
);
// Update image of time tracker bar
new Thread(new Runnable() {
@Override
public void run() { // run once thread is started
while(mediaPlayer != null){
try {
Message msg = new Message();
msg.what = mediaPlayer.getCurrentPosition(); // gets the current position in the file
handler.sendMessage(msg); // apply the new position
Thread.sleep(1000);
}catch (InterruptedException e){}
}
}
}).start();
}
private Handler handler = new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
int currentPosition = msg.what;
// updates bar
positionBar.setProgress(currentPosition);
// updates labels
String elapsedTime = createTimeLabel(currentPosition);
elapsedTimeLabel.setText(elapsedTime);
String remainingTime = createTimeLabel(totalTime - currentPosition);
remainingTimeLabel.setText("-"+remainingTime);
}
};
private String createTimeLabel(int time){
String timeLabel = "";
int minutes = time/1000/60;
int seconds = time/1000 % 60;
timeLabel = minutes + ":";
if (seconds < 10) timeLabel += "0";
timeLabel += seconds;
return timeLabel;
}
public void playButtonClick(View view){
// If paused start, else stop
if(!mediaPlayer.isPlaying()){
mediaPlayer.start();
playButton.setBackgroundResource(R.drawable.stop);
}else{
mediaPlayer.stop();
playButton.setBackgroundResource(R.drawable.play);
}
}
}
| true
|
9faf23be9d74518a6d55576c2845f6d22e57354a
|
Java
|
nikenking/JavaBase
|
/src/com/dell/Day27/MaxChildString.java
|
UTF-8
| 5,677
| 3.59375
| 4
|
[] |
no_license
|
package com.dell.Day27;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
abstract class abstc{
public abstract void printfly();
}
public class MaxChildString {
public static void main(String[] args) {
String a = "123";
System.out.println(a.intern());
abstc abstc = new abstc() {
@Override
public void printfly() {
}//匿名内部类if i can show time
};
abstc.printfly();
}
}
//1.给定一个字符串,判断该字符串中是否包含某个子串.如果包含,求出子串的所有出现位置.
// “abceefedbcdiubc”,字串“bc”,出现的位置是1,8,13
// public static boolean indexOf(int start,int end,String s,String targ){
// return targ.equals(s.substring(start,end));
// }
// public static void main(String[] args) {
// String a = "abceefedbcdiubc";
// String b = "bc";
// int len = b.length();
// for (int i = 0; i <= a.length()-len; i++) {
// if (indexOf(i,len+i,a,b)) System.out.print(i+"\t");
// }
// }
//2.编写程序,将控制台输入的字符串全部转为大写
// public static void main(String[] args) {
// String s = new Scanner(System.in).nextLine();
// for (int i = 0; i < s.length(); i++) {
// if (s.charAt(i)<=122&&s.charAt(i)>=97){
// System.out.print((char) (s.charAt(i)-32));
// }
// }
// }
//3.将字符串“test”变为“tset”
// public static String indexReverse(int start,int end,String s){
// String mid = s.substring(start,end+1);
// char[] list = mid.toCharArray();
// for (int i = 0; i < list.length/2; i++) {
// char tem = list[i];
// list[i] = list[list.length-i-1];
// list[list.length-i-1] = tem;
// }
// return s.substring(0,start)+new String(list)+s.substring(end+1,s.length());
// }
// public static void main(String[] args) {
// String a = "123456";
// System.out.println(indexReverse(1, 4, a));
// }
//4.将字符串“To be or not to be”每一个单词都逆序,结果为“oT eb ro ton ot eb ”(可以用StringBuffer类,可以自学)
// public static void main(String[] args) {
// String[] a = "To be or not to be".split(" ");
// for (String s : a) {
// StringBuffer temp = new StringBuffer(s);
// temp.reverse();
// System.out.print(temp+" ");
// }
// }
//5.输入一个字符串,判断该字符串是不是邮箱地址
// public static void main(String[] args) {
// String text = "157562176fdfsfsdfsfdsfsdfs11@163.com";
// if (text.split("@")[0].length()<=13){
// String regEx = "[\\w]{5,13}@[\\w]{3,5}.[\\w]{1,}";
// Pattern pattern = Pattern.compile(regEx);
// Matcher matcher = pattern.matcher(text);
// while (matcher.find()){
// System.out.println(matcher.group(0));
// }
// }else{
// System.out.println("邮箱过长");
// }
// }
//6.统计一个字符串中出现的大写字母的次数
// public static void main(String[] args) {
// String s = "SdfFDFfdfFdFD";
// int count=0;
// for (char c : s.toCharArray()) {
// if (c>=65&&c<=90)count++;
// }
// System.out.println(count);
// }
////7.输入一串数字字符串,计算每个数字出现的次数
// public static Integer toInteger(char s){
// return Integer.parseInt(String.valueOf(s));
// }
// public static void main(String[] args) {
// Map<Integer,Integer> map = new HashMap<>();
// String s = "1548943184511348465";
// for (int i = 0; i < s.length(); i++) {
// if (map.get(toInteger(s.charAt(i)))!=null){
// map.replace(toInteger(s.charAt(i)),map.get(toInteger(s.charAt(i)))+1);
// }else map.put(toInteger(s.charAt(i)),1);
// }
// System.out.println(map);
// }
////8.public static int countC(String s){
// int count = 0;
// for (char c : s.toCharArray()) {
// if (String.valueOf(c).toLowerCase().equals("c"))count++;
// }
// return count;
//}
// public static void toUpCase(String s){
// String[] list = s.split(" ");
// int i = 0;
// for (String s1 : list) {
// char[] tmp = s1.toCharArray();
// if (tmp[0]>=97&&tmp[0]<=122){
// tmp[0] = (char) (tmp[0]-32);
// list[i] = new String(tmp);
// }i++;
// }
// for (String s1 : list) {
// System.out.print(s1+" ");
// }
// }
// public static void reverse(String s){
// StringBuffer buffer = new StringBuffer(s);
// buffer.reverse();
// System.out.println("StringBuffer:\n"+buffer);
// char[] list = s.toCharArray();
// for (int i = 0; i < list.length/2; i++) {
// char tem = list[i];
// list[i] = list[list.length-i-1];
// list[list.length-i-1] = tem;
// }
// s = new String(list);
// System.out.println("For 循环:\n"+s);
// }
// public static void toPrivate(String s){
// String[] list = s.split("\\s");
// for (String s1 : list) {
// System.out.print("["+s1+"] ");
// }
// }
// public static void main(String[] args) {
// String know = "this is a test of java";
// countC(know);
// toUpCase(know);
// reverse(know);
// toPrivate(know);
// }
| true
|
8fc147e85d7f62887e72e7df5f0818552ca8362e
|
Java
|
ecabanasv/x20132484_CA_DS
|
/src/main/java/MasterGUI.java
|
UTF-8
| 3,168
| 2.796875
| 3
|
[] |
no_license
|
// Panel control with 3 services button: Booking, Occupancy and Temperature
// AWT Libraries
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.net.ssl.SSLException;
// Swing Libraries
import javax.swing.*;
// gRPC Libraries
import grpc.smbuilding.booking.BookingGUI;
import grpc.smbuilding.occupancy.OccupancyGUI;
import grpc.smbuilding.temperature.TemperatureGUI;
public class MasterGUI {
private JFrame MasterF;
public static void main(String[] args) throws SSLException, InterruptedException {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MasterGUI window = new MasterGUI();
window.MasterF.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
// Constructor MasterGUI
public MasterGUI() {
initialize();
}
// Interface MasterGUI
private void initialize() {
MasterF = new JFrame();
MasterF.setTitle("Mini Smart Building: Panel Control");
MasterF.setBounds(750, 0, 400, 80);
MasterF.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BoxLayout bl = new BoxLayout(MasterF.getContentPane(), BoxLayout.Y_AXIS);
MasterF.getContentPane().setLayout(bl);
JPanel panel_service_1 = new JPanel();
MasterF.getContentPane().add(panel_service_1);
panel_service_1.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
// Button Booking service
JButton btnButton1 = new JButton("Check Rooms");
btnButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
@SuppressWarnings("unused")
BookingGUI gBooking = new BookingGUI();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
});
panel_service_1.add(btnButton1);
// Button Occupancy service
JButton btnButton2 = new JButton("Occupancy report");
btnButton2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
@SuppressWarnings("unused")
OccupancyGUI gOccupancy = new OccupancyGUI();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
});
panel_service_1.add(btnButton2);
// Button Temperature service
JButton btnButton3 = new JButton("Temperature");
btnButton3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
@SuppressWarnings("unused")
TemperatureGUI gTemperature = new TemperatureGUI();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
});
panel_service_1.add(btnButton3);
}
}
| true
|
85d7c3091ad26d8029f245cbf28846bb5d7073fe
|
Java
|
LUCKYZHOUSTAR/ProjectTest
|
/ProjectTest/src/main/java/DistributeDataBase/rule/ruleengine/rule/CartesianProductBasedListResultRule.java
|
UTF-8
| 11,322
| 2.0625
| 2
|
[] |
no_license
|
/**
*
*/
package DistributeDataBase.rule.ruleengine.rule;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import DistributeDataBase.common.sqljep.function.Comparative;
import DistributeDataBase.rule.ruleengine.enumerator.Enumerator;
import DistributeDataBase.rule.ruleengine.enumerator.EnumeratorImp;
import DistributeDataBase.rule.ruleengine.util.RuleUtils;
/**
* @ClassName: CartesianProductBasedListResultRule
* @Description:
* @author LUCKY
* @date 2016年5月17日 下午7:01:31
*
*/
public abstract class CartesianProductBasedListResultRule extends ListAbstractResultRule {
private static final Logger log = LoggerFactory
.getLogger(CartesianProductBasedListResultRule.class);
Enumerator enumerator = new EnumeratorImp();
public Map<String, Field> eval(Map<String, Comparative> argumentsMap) {
Map enumeratedMap = prepareEnumeratedMap(argumentsMap);
if (log.isDebugEnabled()) {
log.debug("Sampling filed message : " + enumeratedMap);
}
Map map = evalElement(enumeratedMap);
decideWhetherOrNotToThrowSpecEmptySetRuntimeException(map);
return map;
}
private void decideWhetherOrNotToThrowSpecEmptySetRuntimeException(Map<String, Field> map) {
if (((map == null) || (map.isEmpty()))
&& (ruleRequireThrowRuntimeExceptionWhenSetIsEmpty()))
throw new EmptySetRuntimeException();
}
public Map<String, Set<Object>> prepareEnumeratedMap(Map<String, Comparative> argumentsMap) {
if (log.isDebugEnabled()) {
log.debug("eval at CartesianProductRule ,param is " + argumentsMap);
}
Map enumeratedMap = RuleUtils.getSamplingField(argumentsMap, this.parameters);
return enumeratedMap;
}
public Set<String> evalWithoutSourceTrace(Map<String, Set<Object>> enumeratedMap,
String mappingTargetColumn, Set<Object> mappingKeys) {
if (enumeratedMap.size() == 0) {
return evalZeroArgumentExpression();
}
if (enumeratedMap.size() == 1) {
return evalOneArgumentExpression(enumeratedMap, mappingTargetColumn, mappingKeys);
}
return evalMutiargumentsExpression(enumeratedMap, mappingTargetColumn, mappingKeys);
}
private Set<String> evalMutiargumentsExpression(Map<String, Set<Object>> enumeratedMap,
String mappingTargetColumn,
Set<Object> mappingKeys) {
if ((mappingTargetColumn != null) || (mappingKeys != null)) {
throw new IllegalArgumentException("多列枚举不支持使用映射规则");
}
CartesianProductCalculator cartiesianProductCalculator = new CartesianProductCalculator(
enumeratedMap);
Set set = new HashSet(16);
for (SamplingField samplingField : cartiesianProductCalculator) {
evalOnceAndAddToReturnSet(set, samplingField, 16);
}
return set;
}
private Set<String> evalZeroArgumentExpression() {
List columns = new ArrayList(1);
SamplingField samplingField = new SamplingField(columns, 1);
Set set = new HashSet();
evalOnceAndAddToReturnSet(set, samplingField, 0);
if (((set == null) || (set.isEmpty()))
&& (ruleRequireThrowRuntimeExceptionWhenSetIsEmpty())) {
throw new EmptySetRuntimeException();
}
return set;
}
private Set<String> evalOneArgumentExpression(Map<String, Set<Object>> enumeratedMap,
String mappingTargetColumn,
Set<Object> mappingKeys) {
List columns = new ArrayList(1);
Set enumeratedValues = null;
for (Map.Entry entry : enumeratedMap.entrySet()) {
columns.add(entry.getKey());
enumeratedValues = (Set) entry.getValue();
}
SamplingField samplingField = new SamplingField(columns, 1);
Set set = new HashSet(enumeratedValues.size());
if (mappingKeys == null) {
evalNormal(set, enumeratedValues, samplingField);
} else {
evalWithMappingKey(mappingTargetColumn, mappingKeys, set, enumeratedValues,
samplingField);
}
if (((set == null) || (set.isEmpty()))
&& (ruleRequireThrowRuntimeExceptionWhenSetIsEmpty())) {
throw new EmptySetRuntimeException();
}
return set;
}
private void evalWithMappingKey(String mappingTargetColumn, Set<Object> mappingKeys,
Set<String> set, Set<Object> enumeratedValues,
SamplingField samplingField) {
samplingField.setMappingTargetKey(mappingTargetColumn);
Iterator itr;
Iterator i$;
if (mappingKeys.size() == enumeratedValues.size()) {
itr = mappingKeys.iterator();
for (i$ = enumeratedValues.iterator(); i$.hasNext();) {
Object value = i$.next();
Object oneTargetKey = itr.next();
samplingField.clear();
samplingField.setMappingValue(oneTargetKey);
samplingField.add(0, value);
evalOnceAndAddToReturnSet(set, samplingField, enumeratedValues.size());
}
} else {
throw new IllegalArgumentException("mapping映射后的targetKeys和输入的参数个数不等,mapping :"
+ mappingKeys + " " + "enumeratedValues is :"
+ enumeratedValues);
}
}
private void evalNormal(Set<String> set, Set<Object> enumeratedValues,
SamplingField samplingField) {
for (Iterator i$ = enumeratedValues.iterator(); i$.hasNext();) {
Object value = i$.next();
samplingField.clear();
samplingField.add(0, value);
evalOnceAndAddToReturnSet(set, samplingField, enumeratedValues.size());
}
}
public Map<String, Field> evalElement(Map<String, Set<Object>> enumeratedMap) {
if (enumeratedMap.size() == 1) {
List columns = new ArrayList(1);
Set enumeratedValues = null;
for (Map.Entry entry : enumeratedMap.entrySet()) {
columns.add(entry.getKey());
enumeratedValues = (Set) entry.getValue();
}
SamplingField samplingField = new SamplingField(columns, 1);
Map map = new HashMap(enumeratedValues.size());
for (Iterator i$ = enumeratedValues.iterator(); i$.hasNext();) {
Object value = i$.next();
samplingField.clear();
samplingField.add(0, value);
evalOnceAndAddToReturnMap(map, samplingField, enumeratedValues.size());
}
return map;
}
if (enumeratedMap.size() == 0) {
List columns = new ArrayList(1);
SamplingField samplingField = new SamplingField(columns, 1);
Map map = new HashMap(1);
evalOnceAndAddToReturnMap(map, samplingField, 1);
return map;
}
CartesianProductCalculator cartiesianProductCalculator = new CartesianProductCalculator(
enumeratedMap);
Map map = new HashMap(16);
for (SamplingField samplingField : cartiesianProductCalculator) {
evalOnceAndAddToReturnMap(map, samplingField, 16);
}
return map;
}
protected boolean ruleRequireThrowRuntimeExceptionWhenSetIsEmpty() {
return false;
}
void evalOnceAndAddToReturnSet(Set<String> set, SamplingField samplingField, int valueSetSize) {
ResultAndMappingKey resultAndMappingKey = evalueateSamplingField(samplingField);
String targetIndex = resultAndMappingKey.result;
if (targetIndex != null)
set.add(targetIndex);
else
throw new IllegalArgumentException("规则引擎的结果不能为null");
}
void evalOnceAndAddToReturnMap(Map<String, Field> map, SamplingField samplingField,
int valueSetSize) {
ResultAndMappingKey returnAndMappingKey = evalueateSamplingField(samplingField);
if (returnAndMappingKey != null) {
String dbIndexStr = returnAndMappingKey.result;
if (StringUtils.isBlank(dbIndexStr)) {
throw new IllegalArgumentException("根据dbRule计算出的结果不能为null");
}
String[] dbIndexes = dbIndexStr.split(",");
List values;
Field colMap;
int index;
for (String dbIndex : dbIndexes) {
List lists = samplingField.getColumns();
values = samplingField.getEnumFields();
colMap = prepareColumnMap(map, samplingField, dbIndex,
returnAndMappingKey.mappingTargetColumn, returnAndMappingKey.mappingKey);
index = 0;
for (String column : lists) {
Object value = values.get(index);
Set set = prepareEnumeratedSet(valueSetSize, colMap, column);
set.add(value);
index++;
}
}
}
}
private Set<Object> prepareEnumeratedSet(int valueSetSize, Field colMap, String column) {
Set set = (Set) colMap.sourceKeys.get(column);
if (set == null) {
set = new HashSet(valueSetSize);
colMap.sourceKeys.put(column, set);
}
return set;
}
private Field prepareColumnMap(Map<String, Field> map, SamplingField samplingField,
String targetIndex, String mappngTargetColumn,
Object mappingValue) {
Field colMap = (Field) map.get(targetIndex);
if (colMap == null) {
int size = samplingField.getColumns().size();
colMap = new Field(size);
map.put(targetIndex, colMap);
}
if ((mappngTargetColumn != null) && (colMap.mappingTargetColumn == null)) {
colMap.mappingTargetColumn = mappngTargetColumn;
}
if (mappingValue != null) {
if (colMap.mappingKeys == null) {
colMap.mappingKeys = new HashSet();
}
colMap.mappingKeys.add(mappingValue);
}
return colMap;
}
public abstract ResultAndMappingKey evalueateSamplingField(SamplingField paramSamplingField);
}
| true
|
3d0690ae99ba2e770b4905047ee00fb2a4a32449
|
Java
|
dkgecov/Bar-Management
|
/src/main/java/bar/model/Order.java
|
UTF-8
| 4,747
| 2.453125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package bar.model;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
@Entity
@XmlRootElement
@Table(name = "ORDERS")
@NamedQueries({ @NamedQuery(name = "findById", query = "SELECT o FROM Order o WHERE o.status = :status"),
@NamedQuery(name = "findByStatus", query = "SELECT o FROM Order o WHERE o.status = :status"),
@NamedQuery(name = "getAcceptedAndOverdue", query = "SELECT o FROM Order o WHERE o.executor = :executor AND (o.status = :status1 OR o.status = :status2)"),
@NamedQuery(name = "setOrderAsOverdue", query = "SELECT o FROM Order o WHERE o.executor = :executor AND (o.status = :status1 OR o.status = :status2)"), })
public class Order implements Serializable {
private static final long serialVersionUID = 735934458877201921L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToOne
private User executor;
@Enumerated(EnumType.STRING)
private Status status;
@Temporal(TemporalType.DATE)
private Date dateOfOrder;
@Temporal(TemporalType.DATE)
private Date dateOfAcceptance;
@ManyToMany
private List<Item> itemsInOrder = new ArrayList<>();
private float totalPrice;
private int tableNumber;
private int count;
public Order(int tableNumber, String itemName, int count) {
this.tableNumber = tableNumber;
this.count = count;
this.status = Status.WAITING;
this.dateOfAcceptance = new Date();
this.totalPrice = 0.0f;
}
public Order() {
this.status = Status.WAITING;
this.dateOfAcceptance = new Date();
this.totalPrice = 0.0f;
this.tableNumber = -1;
this.count = 0;
}
public Order( List<Item> itemsInOrder) {
super();
this.status = Status.WAITING;
this.dateOfOrder=new Date();
this.totalPrice = 0.0f;
this.itemsInOrder=itemsInOrder;
this.tableNumber = -1;
this.count = 0;
}
public Long getId() {
return this.id;
}
public void setId(final Long id) {
this.id = id;
}
public User getExecutor() {
return executor;
}
public void setExecutor(User executor) {
this.executor = executor;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public Date getDateOfOrder() {
return dateOfOrder;
}
public void setDateOfOrder(Date dateOfOrder) {
this.dateOfOrder = dateOfOrder;
}
public Date getDateOfAcceptance() {
return dateOfAcceptance;
}
public void setDateOfAcceptance(Date dateOfAcceptance) {
this.dateOfAcceptance = dateOfAcceptance;
}
public double getTotalPrice() {
return totalPrice;
}
private void setTotalPrice(float totalPrice) {
this.totalPrice = totalPrice;
}
public void calculateTotalPrice() {
float sumPrice = 0.0f;
for (Item item : itemsInOrder) {
sumPrice += Float.parseFloat(item.getPrice());
}
setTotalPrice(sumPrice);
}
public int getTableNumber() {
return tableNumber;
}
public int getCount() {
return count;
}
void setTableNumber(int tableNumber) {
this.tableNumber = tableNumber;
}
void setCount(int count) {
this.count = count;
}
@Override
public String toString() {
String result = getClass().getSimpleName() + " ";
if (id != null)
result += ", id: " + id;
if (executor != null)
result += "executor: " + executor.getUserName();
if (status != null)
result += ", status: " + status;
if (dateOfOrder != null)
result += ", dateOfOrder: " + dateOfOrder.toString();
if (itemsInOrder != null && !itemsInOrder.isEmpty()) {
result += "\nordered items:\n";
for (Item item : itemsInOrder) {
result += " " + item.getItemName() + ": " + item.getPrice() + "\n";
}
if (getTotalPrice() != 0.0f)
calculateTotalPrice();
result += "Total price: " + getTotalPrice() + "\n";
}
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Order)) {
return false;
}
Order other = (Order) obj;
if (id != null) {
if (!id.equals(other.id)) {
return false;
}
}
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
}
| true
|
a73074cd2881ba7b82a073a5b02cb0bf7ef68b12
|
Java
|
fracz/refactor-extractor
|
/results-java/neo4j--neo4j/f33aa2d69f3125cf4569806a7bc52532f7537519/after/StandaloneDatabase.java
|
UTF-8
| 9,857
| 1.75
| 2
|
[] |
no_license
|
/**
* Copyright (c) 2002-2011 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.ha;
import java.io.File;
import java.io.PrintStream;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.junit.Ignore;
import org.neo4j.kernel.HighlyAvailableGraphDatabase;
import org.neo4j.kernel.ha.AbstractBroker;
import org.neo4j.kernel.ha.Broker;
import org.neo4j.kernel.ha.CommunicationProtocol;
import org.neo4j.kernel.ha.FakeMasterBroker;
import org.neo4j.kernel.ha.FakeSlaveBroker;
import org.neo4j.kernel.ha.MasterClient;
import org.neo4j.management.HighAvailability;
import org.neo4j.test.SubProcess;
import slavetest.Job;
@Ignore
public class StandaloneDatabase
{
private final Controller process;
public static StandaloneDatabase withDefaultBroker( String testMethodName, File path,
int machineId, String zooKeeperConnection, String haServer, String[] extraArgs )
{
return new StandaloneDatabase( testMethodName, new Bootstrap( path, machineId,//
HighlyAvailableGraphDatabase.CONFIG_KEY_HA_SERVER, haServer,//
HighlyAvailableGraphDatabase.CONFIG_KEY_HA_ZOO_KEEPER_SERVERS, zooKeeperConnection )
{
@Override
HighlyAvailableGraphDatabase start( String storeDir, Map<String, String> config )
{
HighlyAvailableGraphDatabase db = new HighlyAvailableGraphDatabase( storeDir,
config );
System.out.println( "Started HA db (w/ zoo keeper)" );
return db;
}
} );
}
public static StandaloneDatabase withFakeBroker( String testMethodName, File path,
int machineId, final int masterId, String[] extraArgs )
{
StandaloneDatabase standalone = new StandaloneDatabase( testMethodName, new Bootstrap(
path, machineId )
{
@Override
HighlyAvailableGraphDatabase start( String storeDir, Map<String, String> config )
{
final Broker broker;
if ( machineId == masterId )
{
broker = new FakeMasterBroker( machineId, storeDir );
}
else
{
broker = new FakeSlaveBroker( new MasterClient( "localhost",
CommunicationProtocol.PORT, storeDir ), masterId, machineId, storeDir );
}
HighlyAvailableGraphDatabase db = new HighlyAvailableGraphDatabase( storeDir,
config, AbstractBroker.wrapSingleBroker( broker ) );
System.out.println( "Started HA db (w/o zoo keeper)" );
return db;
}
} );
standalone.awaitStarted();
return standalone;
}
private StandaloneDatabase( String testMethodName, Bootstrap bootstrap )
{
process = new HaDbProcess( testMethodName ).start( bootstrap );
}
@Override
public String toString()
{
return getClass().getSimpleName() + process;
}
public void awaitStarted()
{
process.awaitStarted();
}
public <T> T executeJob( Job<T> job ) throws Exception
{
return process.executeJob( job );
}
public int getMachineId()
{
return process.getMachineId();
}
public void pullUpdates()
{
process.pullUpdates();
}
public void shutdown()
{
SubProcess.stop( process );
}
// <IMPLEMENTATION>
public interface Controller
{
void pullUpdates();
void awaitStarted();
int getMachineId();
<T> T executeJob( Job<T> job ) throws Exception;
}
public static abstract class Bootstrap implements Serializable
{
private final String[] config;
private final File storeDir;
final int machineId;
private Bootstrap( File storeDir, int machineId, String... config )
{
this.storeDir = storeDir;
this.machineId = machineId;
this.config = config;
}
final HighlyAvailableGraphDatabase start()
{
Map<String, String> params = new HashMap<String, String>();
params.put( HighlyAvailableGraphDatabase.CONFIG_KEY_HA_MACHINE_ID,
Integer.toString( machineId ) );
for ( int i = 0; i < config.length; i += 2 )
{
params.put( config[i], config[i + 1] );
}
return start( storeDir.getAbsolutePath(), params );
}
abstract HighlyAvailableGraphDatabase start( String storeDir, Map<String, String> config );
}
private static class HaDbProcess extends SubProcess<Controller, Bootstrap> implements
Controller
{
private static class DatabaseReference
{
final HighlyAvailableGraphDatabase graph;
DatabaseReference( HighlyAvailableGraphDatabase graph )
{
this.graph = graph;
}
}
private transient volatile DatabaseReference db = null;
private final String testMethodName;
private HaDbProcess( String testMethodName )
{
this.testMethodName = testMethodName;
}
private HighlyAvailableGraphDatabase db()
{
DatabaseReference ref = db;
if ( ref == null ) throw new IllegalStateException( "database has not been started" );
if ( ref.graph == null )
throw new IllegalStateException( "database has been shut down" );
return ref.graph;
}
private synchronized boolean db( HighlyAvailableGraphDatabase graph )
{
if ( db != null && graph != null )
{
return false;
}
db = new DatabaseReference( graph );
return true;
}
@Override
public String toString()
{
return testMethodName;
}
@Override
protected void startup( Bootstrap bootstrap )
{
System.setOut( new TimestampStream( System.out ) );
System.setErr( new TimestampStream( System.err ) );
if ( db != null ) throw new IllegalStateException( "already started" );
System.out.println( "About to start" );
HighlyAvailableGraphDatabase graph = null;
try
{
graph = bootstrap.start();
}
finally
{
if ( !db( graph ) && graph != null )
{
graph.shutdown();
throw new IllegalStateException( "already started" );
}
}
}
@Override
protected void shutdown()
{
System.out.println( "Shutdown started" );
DatabaseReference ref = db;
try
{
if ( ref.graph != null ) ref.graph.shutdown();
}
finally
{
db( null );
}
System.out.println( "Shutdown completed" );
super.shutdown();
}
public void awaitStarted()
{
boolean interrupted = false;
while ( this.db == null )
{
try
{
Thread.sleep( 100 );
}
catch ( InterruptedException e )
{
interrupted = true;
Thread.interrupted();
}
}
if ( interrupted ) Thread.currentThread().interrupt();
}
public <T> T executeJob( Job<T> job ) throws Exception
{
HighlyAvailableGraphDatabase database = db();
System.out.println( "Executing job " + job );
T result = job.execute( database );
System.out.println( "Job " + job + " executed" );
return result;
}
public int getMachineId()
{
return Integer.parseInt( db().getManagementBean( HighAvailability.class ).getMachineId() );
}
public void pullUpdates()
{
HighlyAvailableGraphDatabase database = db();
System.out.println( "pullUpdates" );
database.pullUpdates();
}
}
private static class TimestampStream extends PrintStream
{
ThreadLocal<DateFormat> timestamp = new ThreadLocal<DateFormat>()
{
@Override
protected DateFormat initialValue()
{
return new SimpleDateFormat( "[HH:mm:ss:SS] " );
}
};
TimestampStream( PrintStream out )
{
super( out );
}
@Override
public void println( String string )
{
super.println( timestamp.get().format( new Date() ) + string );
}
}
}
| true
|
380bb592bc43d9c3799f25dedd81cca9761de253
|
Java
|
lotockijj/workspace
|
/Hello World/src/softserve3/Circle.java
|
UTF-8
| 1,347
| 3.046875
| 3
|
[] |
no_license
|
package softserve3;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.List;
public class Circle implements Serializable{
private double radius;
//constructors, getters, setters goes here
public double getCircleLength() {
return 2 * Math.PI * radius;
}
public double getSquare() {
return Math.PI * radius * radius;
}
public class Cylider extends Circle {
private double height;
@Override
public double getSquare() {
return 2 * super.getSquare() + height * getCircleLength();
}
}
// public List readCollectionFromFile(String filePath) {
// try {
// FileInputStream fis = new FileInputStream(filePath);
// ObjectInputStream ois = new ObjectInputStream(fis);
// List resultList = (ArrayList) ois.readObject();
// ois.close();
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// throw new RuntimeException();
// }
// }
public void writeCollectionToFile(String filePath) {
try {
FileOutputStream fos = new FileOutputStream(filePath);
ObjectOutputStream oos = new ObjectOutputStream(fos);
// oos.writeObject(list);
// oos.writeObject(r1);
oos.close();
} catch (Exception e){
e.printStackTrace();
}
}
}
| true
|
c702e6a1c40962b791f963db0b410f5d8a2579e6
|
Java
|
vbhv12/TravelManager
|
/src/travel/management/system/Hotels.java
|
UTF-8
| 5,180
| 2.828125
| 3
|
[] |
no_license
|
package travel.management.system;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
public class Hotels extends JFrame implements ActionListener {
JTable t1;
String[] x={"S.No.","Hotel Name","Charges per day","Ac Charges","Location"};
String[][] y=new String[120][5];
int i=0,j=0;
JButton b1,b2;
JTextField text0,text1,text2,text3;
Choice c1;
Hotels(){
setLayout(null);
setBounds(200,100,1000,400);
JPanel p1=new JPanel();
p1.setBackground(Color.BLACK);
add(p1);
JLabel l1=new JLabel("Hotels");
l1.setBounds(715,25,200,25);
l1.setForeground(new Color(148,0,211));
l1.setFont(new Font("Tahoma",Font.PLAIN,25));
add(l1);
p1.setBounds(0,0,650,400);
p1.setLayout(null);
ResultSet rs = null;
try{
Conn c=new Conn();
String sql="select * from hotels";
rs=c.s.executeQuery(sql);
while(rs.next()){
y[i][j++]=i+1+"";
y[i][j++]=rs.getString("name");
y[i][j++]="Rs: "+rs.getString("cost_per_day");
y[i][j++]="Rs: "+rs.getString("ac_charges");
y[i][j++]=rs.getString("location");
i++;
j=0;
}
}
catch (Exception exp){
exp.printStackTrace();
}
t1=new JTable(y,x);
t1.getColumnModel().getColumn(0).setPreferredWidth(50);
t1.getColumnModel().getColumn(4).setPreferredWidth(150);
JScrollPane scroll =new JScrollPane(t1);
scroll.setBounds(0,0,650,400);
p1.add(scroll);
JLabel l2=new JLabel("Hotel Name");
l2.setBounds(675,65,200,25);
l2.setFont(new Font("Tahoma",Font.PLAIN,16));
add(l2);
text0=new JTextField();
text0.setBounds(675,95,200,25);
text0.setBorder(BorderFactory.createEmptyBorder());
add(text0);
JLabel l3=new JLabel("Charges per day");
l3.setBounds(675,125,200,25);
l3.setFont(new Font("Tahoma",Font.PLAIN,16));
add(l3);
text1=new JTextField();
text1.setBounds(675,150,200,25);
text1.setBorder(BorderFactory.createEmptyBorder());
add(text1);
l2=new JLabel("AC Charges");
l2.setBounds(675,180,200,25);
l2.setFont(new Font("Tahoma",Font.PLAIN,16));
add(l2);
text2=new JTextField();
text2.setBounds(675,205,200,25);
text2.setBorder(BorderFactory.createEmptyBorder());
add(text2);
l3=new JLabel("Location");
l3.setBounds(675,235,200,25);
l3.setFont(new Font("Tahoma",Font.PLAIN,16));
add(l3);
c1=new Choice();
try{
Conn c=new Conn();
rs=c.s.executeQuery("Select * from dest ");
while(rs.next()){
c1.add(rs.getString("name"));
}
}
catch (Exception e){
}
c1.setBounds(675,260,200,25);
add(c1);
b1=new JButton("ADD");
b1.setBounds(675,300,70,25);
b1.setBackground(Color.BLACK);
b1.setForeground(Color.white);
add(b1);
b1.addActionListener((ActionListener)this);
b2=new JButton("Delete");
b2.setBounds(780,300,80,25);
b2.setBackground(Color.BLACK);
b2.setForeground(Color.white);
add(b2);
b2.addActionListener((ActionListener) this);
}
public static void main(String[] args) {
new Hotels().setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==b1) {
try {
Conn c = new Conn();
String hotel = text0.getText();
String dayC=text1.getText();
String ac_c=text2.getText();
String Loc=c1.getSelectedItem();
String sql = "insert into hotels values ('" + hotel + "','" + dayC + "','" + ac_c + "','" + Loc + "')";
System.out.println(sql);
c.s.executeUpdate(sql);
} catch (Exception ex) {
ex.printStackTrace();
}
JOptionPane.showMessageDialog(null, "Added Data Successfully!!");
this.setVisible(false);
}
else{
int row=t1.getSelectedRow();
System.out.println(row);
String dest1=t1.getModel().getValueAt(row,1).toString();
String loc=t1.getModel().getValueAt(row,4).toString();
try{
Conn c=new Conn();
System.out.println(dest1);
System.out.println(loc);
c.s.executeUpdate("delete from hotels where name='" + dest1 + "' and location='"+loc+"'");
JOptionPane.showMessageDialog(null, "Hotel Deleted Successfully!!!");
this.setVisible(false);
new CustomerDetails();
}
catch(Exception ae){
ae.printStackTrace();
}
}
}
}
| true
|
5dd3189cbf95c2f55be85d5c7d82d2f5a50d8bb1
|
Java
|
wb-brave/spring-springboot-java-Learn-develop
|
/Program_wubin/src/main/java/thinkinjava/chapter17/exercise/Exer14.java
|
UTF-8
| 3,992
| 3.453125
| 3
|
[] |
no_license
|
package thinkinjava.chapter17.exercise;
import util.sets.CountingMapData;
import java.util.Map;
import java.util.Properties;
/**
* @author wubin
* @Description
* @project Learn-develop
* @package thinkinjava.chapter17.exercise
* @email wubin326@qq.com
* @date 2018/12/13
* Modification History:
* Date Author Version Description
* ----------------------------------------------------------------------
* 2018/12/13 wubin 0.0.1
*/
public class Exer14 {
public static void printKeys(Map<Integer,String> map) {
System.out.print("Size = " + map.size() + ", ");
System.out.print("Keys: ");
System.out.println(map.keySet()); // Produce a set of the keys
}
// more general version, taking Map<Object,Object> arg:
public static void printKeys2(Map<Object,Object> map) {
System.out.print("Size = " + map.size() + ", ");
System.out.print("Keys: ");
System.out.println(map.keySet()); // Produce a set of the keys
}
public static void test(Map<Integer,String> map) {
System.out.println(map.getClass().getSimpleName());
map.putAll(new CountingMapData(25));
// Map has 'Set' behavior for keys:
map.putAll(new CountingMapData(25));
printKeys(map);
// Producing a collection of the values:
System.out.print("Values: ");
System.out.println(map.values());
System.out.println(map);
System.out.println("map.containsKey(11): " + map.containsKey(11));
System.out.println("map.get(11): " + map.get(11));
System.out.println("map.containsValue(\"F0\"): " + map.containsValue("F0"));
Integer key = map.keySet().iterator().next();
System.out.println("First key in map: " + key);
map.remove(key);
printKeys(map);
map.clear();
System.out.println("map.isEmpty(): " + map.isEmpty());
map.putAll(new CountingMapData(25));
// Operations on the Set change the Map:
map.keySet().removeAll(map.keySet());
System.out.println("map.isEmpty(): " + map.isEmpty());
}
// more general version, taking Map<Object,Object> arg:
public static void test2(Map<Object,Object> map) {
System.out.println(map.getClass().getSimpleName());
map.putAll(new CountingMapData(25));
// Map has 'Set' behavior for keys:
map.putAll(new CountingMapData(25));
printKeys2(map);
// Producing a collection of the values:
System.out.print("Values: ");
System.out.println(map.values());
System.out.println(map);
System.out.println("map.containsKey(11): " + map.containsKey(11));
System.out.println("map.get(11): " + map.get(11));
System.out.println("map.containsValue(\"F0\"): " + map.containsValue("F0"));
Object key = map.keySet().iterator().next();
System.out.println("First key in map: " + key);
map.remove(key);
printKeys2(map);
map.clear();
System.out.println("map.isEmpty(): " + map.isEmpty());
map.putAll(new CountingMapData(25));
// Operations on the Set change the Map:
map.keySet().removeAll(map.keySet());
System.out.println("map.isEmpty(): " + map.isEmpty());
}
public static void main(String[] args) {
// Method test(Map<Integer,String>() cannot be applied:
// test(new java.util.Properties());
// test(new Properties());
// test(new HashMap<Object,Object>());
// test(new HashMap<String,String>());
// Incompatible:
// Map<Integer,String> misp = new Properties();
// Map<String,String> mssp = new Properties();
// OK:
Map<Object,Object> moop = new Properties();
// but test(Map<Integer,String>() cannot be applied:
// test(moop);
// Using more general version, taking Map<Object,Object> arg:
test2(new Properties()); // OK
}
}
| true
|
190ec6119a37f8e6fae87b07dbc2d398880b0b98
|
Java
|
qyl123/Test
|
/fangkuaiA3/src/com/MyPanel.java
|
GB18030
| 2,703
| 2.703125
| 3
|
[] |
no_license
|
package com;
import gamerole.GameMap;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import javax.swing.*;
public class MyPanel extends JPanel implements Runnable,MouseMotionListener,KeyListener,MouseListener
{
private static final long serialVersionUID = 1L;
public GameMap gameMap=new GameMap();
public MyPanel( ) {
//ʼ
GameTool.initRes();
}
/*Ϸ*/
public void paint(Graphics g) {
super.paint(g) ;//ʾ֮ǰȲһεĺۼpaint()еһӣ
GameTool.g=g;
/*1 Ʊ*/
GameTool.res.paintOne(0, 0,GameTool.bgX, GameTool.bgY, GameTool.RES_BACK);
gameMap.paint();
}
/*д߳еrun()*/
@Override
public void run() {
while(true) {
GameTool.timeclip++ ;
gameMap.update();
try {
/*˶ٶ*/
Thread.sleep(500) ; //
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace() ;
}
/*ػ*/
repaint() ; //ʵ˶
}
}
/*д¼*/
@Override
public void mouseDragged(MouseEvent e) {
// TODO Auto-generated method stub
System.out.println(" mouseDragged" +e.getX()+"," + e.getY() );
//e.getX() e.getY())
}
@Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent arg0) {
//System.out.println( arg0.getKeyCode());
//
gameMap.keyPressed(arg0.getKeyCode());
//ػ
repaint() ;
}
@Override
public void keyReleased(KeyEvent arg0) {
//System.out.println( arg0.getKeyCode());
}
@Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
//System.out.println( arg0.getKeyCode());
}
@Override
public void mouseClicked(MouseEvent arg0) {
System.out.println("mouseClicked"+ arg0.getX()+"," + arg0.getY());
gameMap.mouseClicked(arg0.getX(), arg0.getY() );
//¼ػ
repaint() ;
}
@Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
| true
|
f4bf768fca882663b41916430eb45d41f0827e9e
|
Java
|
tanghaibin/spring-cloud-learn
|
/learn-stream/src/main/java/com/hobson/cloud/stream/SmsListener.java
|
UTF-8
| 532
| 2.125
| 2
|
[] |
no_license
|
package com.hobson.cloud.stream;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;
/**
* 短信监听器
*
* @author haibin.tang
* @create 2020-02-21 12:24 PM
**/
@Slf4j
@Component
public class SmsListener {
@StreamListener(SmsSink.INPUT)
public void listener(Message<SmsBean> smsBeanMessage) {
log.info("接收到短信消息 -->> {}", smsBeanMessage);
}
}
| true
|
f146c53cacae8bee1a261d0cd174cfb70f546400
|
Java
|
upitersobaka/JavaRushTasksGitHub
|
/1.JavaSyntax/src/com/javarush/task/task09/task0926/Solution.java
|
UTF-8
| 955
| 3.5
| 4
|
[] |
no_license
|
package com.javarush.task.task09.task0926;
import java.util.ArrayList;
/*
Список из массивов чисел
*/
public class Solution {
public static void main(String[] args) {
ArrayList<int[]> list = createList();
printList(list);
}
public static ArrayList<int[]> createList() {
//напишите тут ваш код
ArrayList<int[]> al = new ArrayList();
int task[] = {5,2,4,7,0};
int item[];
for(int x : task) {
if(x > 0) {
item = new int[x];
for (int y = 0; y < x; y++) {
item[y] = y;
}
} else item = new int[0];
al.add(item);
}
return al;
}
public static void printList(ArrayList<int[]> list) {
for (int[] array : list) {
for (int x : array) {
System.out.println(x);
}
}
}
}
| true
|
9ea276240626c0162997f0134a1d1b89af5dfaeb
|
Java
|
Jarrah19/learningJava
|
/practice.10.31/src/e03/PartTimeWorker.java
|
UTF-8
| 821
| 3.3125
| 3
|
[] |
no_license
|
package e03;
/**
* @author 崔英俊
* date: 2019-10-31
* version: 1.0
*/
public class PartTimeWorker implements Worker {
private String name;
private int workHours;
private int hourly;
public PartTimeWorker(String name, int workHours, int hourly) {
this.name = name;
this.workHours = workHours;
this.hourly = hourly;
}
public PartTimeWorker(int workHours, int hourly) {
this.workHours = workHours;
this.hourly = hourly;
}
@Override
public String getName() {
return name;
}
public void setWorkHours(int workHours) {
this.workHours = workHours;
}
public void setHourly(int hourly) {
this.hourly = hourly;
}
@Override
public int salary() {
return workHours * hourly;
}
}
| true
|