hexsha stringlengths 40 40 | size int64 8 1.04M | content stringlengths 8 1.04M | avg_line_length float64 2.24 100 | max_line_length int64 4 1k | alphanum_fraction float64 0.25 0.97 |
|---|---|---|---|---|---|
a2d9d1886414f44d1f4353d9fec8f4491bce69b4 | 3,004 | package movie;
import javax.persistence.*;
import org.hibernate.annotations.SourceType;
import org.springframework.beans.BeanUtils;
import java.util.List;
@Entity
@Table(name="Book_table")
public class Book {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private Integer qty;
private String seat;
private String movieName;
private String status="Registered";
private Integer totalPrice;
@PostPersist
public void onPostPersist(){
Booked booked = new Booked();
BeanUtils.copyProperties(this, booked);
booked.publishAfterCommit();
//Following code causes dependency to external APIs
// it is NOT A GOOD PRACTICE. instead, Event-Policy mapping is recommended.
movie.external.Payment payment = new movie.external.Payment();
System.out.println("*********************");
System.out.println("결제 이벤트 발생");
System.out.println("*********************");
// mappings goes here
payment.setBookingId(booked.getId());
payment.setStatus("Paid");
payment.setTotalPrice(booked.getTotalPrice());
BookApplication.applicationContext.getBean(movie.external.PaymentService.class)
.pay(payment);
}
@PreRemove
public void onPreRemove(){
if("PaidComplete".equals(status)){
Canceled canceled = new Canceled();
BeanUtils.copyProperties(this, canceled);
canceled.publishAfterCommit();
System.out.println("*********************");
System.out.println("취소 이벤트 발생");
System.out.println("*********************");
//Following code causes dependency to external APIs
// it is NOT A GOOD PRACTICE. instead, Event-Policy mapping is recommended.
movie.external.Payment payment = new movie.external.Payment();
payment.setBookingId(canceled.getId());
payment.setStatus("Canceled");
BookApplication.applicationContext.getBean(movie.external.PaymentService.class)
.pay(payment);
}
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getQty() {
return qty;
}
public void setQty(Integer qty) {
this.qty = qty;
}
public String getSeat() {
return seat;
}
public void setSeat(String seat) {
this.seat = seat;
}
public String getMovieName() {
return movieName;
}
public void setMovieName(String movieName) {
this.movieName = movieName;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Integer getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(Integer totalPrice) {
this.totalPrice = totalPrice;
}
}
| 25.033333 | 91 | 0.597204 |
5abf51565982e59dcbf8d215e9809f37a09e9c6d | 1,855 | package self.learning.interview.coding.questionbank.algorithm;
import java.util.Scanner;
public class Solution4 {
/* The function moves non-empty elements in Y[] in the beginning and then merge it with X[] */
private static int[] specialMerge(final int[] X, final int[] Y) {
/* moves non-empty elements of Y[] in the beginning */
int k = 0;
for (int index = 0; index < Y.length; index++) {
if (Y[index] != 0) Y[k++] = Y[index];
}
/* merge X[0..k-1] and Y[0..n-1] to X[0..m-1] */
return merge(X, X.length - 1, Y, k - 1);
}
private static int[] merge(final int[] array1, int N, final int[] array2, int M) {
int k = M + N + 1; // size of array2[] is (k+1)
/* run till array2[] or array1[] has elements left
* and put next greater element in next free position in array2[] from end */
while (M >= 0 && N >= 0) {
array2[k--] = array2[M] > array1[N] ? array2[M--] : array1[N--];
}
/* copy remaining elements of array1[] (if any) to array2[] */
while (N >= 0) array2[k--] = array1[N--];
return array2;
}
public static void main(String[] args) {
final Scanner consoleReader = new Scanner(System.in);
final int smalledArraySize = consoleReader.nextInt();
final int[] array1 = new int[smalledArraySize];
for (int index = 0; index < smalledArraySize; index++) array1[index] = consoleReader.nextInt();
final int biggerArraySize = consoleReader.nextInt();
final int[] array2 = new int[biggerArraySize];
for (int index = 0; index < biggerArraySize; index++) array2[index] = consoleReader.nextInt();
final int[] mergedArray = specialMerge(array1, array2);
for (int value : mergedArray) System.out.print(value + " ");
}
}
| 37.857143 | 103 | 0.586523 |
306219c40f087316c73d16967dcaccee8f25b142 | 235 | package com.nuhkoca.udacitymoviesapp.view.review;
/**
* Created by nuhkoca on 3/1/18.
*/
public interface FullReviewActivityView {
void onReviewLoaded();
void onBottomSheetCreated();
void onReviewOpenedOnBrowser();
}
| 16.785714 | 49 | 0.72766 |
443b49c73c71fb14009a2efb4590b4062b7385d4 | 6,975 | /**
* Copyright (c) 2009 Perforce Software. All rights reserved.
*/
package com.perforce.team.ui.shelve;
import java.text.MessageFormat;
import com.perforce.team.core.p4java.IP4PendingChangelist;
import com.perforce.team.core.p4java.IP4Resource;
import com.perforce.team.core.p4java.P4Runnable;
import com.perforce.team.core.p4java.P4Runner;
import com.perforce.team.ui.dialogs.FileListViewer;
import com.perforce.team.ui.dialogs.P4StatusDialog;
import com.perforce.team.ui.shelve.UpdateShelveDialog.Option;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.viewers.CheckStateChangedEvent;
import org.eclipse.jface.viewers.ICheckStateListener;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
/**
* @author Kevin Sawicki (ksawicki@perforce.com)
*
*/
public class ShelveFileDialog extends P4StatusDialog {
private FileListViewer viewer;
private IP4PendingChangelist list;
private IP4Resource[] allFiles;
private IP4Resource[] checkedFiles;
private IP4Resource[] selectedFiles;
private Option option;
private Label countLabel;
/**
* Creates a shelve file dialog
*
* @param parent
* @param list
* @param resources
* @param checked
*/
public ShelveFileDialog(Shell parent, IP4PendingChangelist list,
IP4Resource[] resources, IP4Resource[] checked) {
this(parent, list, resources, checked, Option.UPDATE);
}
/**
* Creates a shelve file dialog
*
* @param parent
* @param list
* @param resources
* @param checked
* @param option
*/
public ShelveFileDialog(Shell parent, IP4PendingChangelist list,
IP4Resource[] resources, IP4Resource[] checked, Option option) {
super(parent);
setModalResizeStyle();
if (option == Option.DELETE) {
setTitle(MessageFormat.format(
Messages.ShelveFileDialog_DeleteShelvedFiles, list.getId()));
} else {
setTitle(MessageFormat.format(
Messages.ShelveFileDialog_ShelveFiles, list.getId()));
}
this.allFiles = getFiles(resources);
this.list = list;
if (checked != null) {
this.checkedFiles = checked;
} else {
this.checkedFiles = this.allFiles;
}
this.option = option;
setModalResizeStyle();
}
/**
* Get the selected files
*
* @return - selected files
*/
public IP4Resource[] getSelectedFiles() {
return selectedFiles;
}
private void updateCount() {
int count = viewer.getCheckedElements().length;
int max = viewer.getTable().getItemCount();
countLabel.setText(MessageFormat.format(
Messages.ShelveFileDialog_FilesNumSelected, count, max));
if (count == 0) {
setErrorMessage(Messages.ShelveFileDialog_MustSelectAtLeastOneFile,
null);
} else {
setErrorMessage(null);
}
}
/**
* @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
*/
@Override
protected Control createDialogArea(Composite parent) {
Composite dialogArea = (Composite) super.createDialogArea(parent);
Composite composite = new Composite(dialogArea, SWT.NONE);
GridLayout cLayout = new GridLayout(2, false);
cLayout.marginHeight = 0;
cLayout.marginWidth = 0;
composite.setLayout(cLayout);
composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
countLabel = new Label(composite, SWT.LEFT);
GridData clData = new GridData(SWT.FILL, SWT.FILL, true, false);
clData.verticalIndent = 5;
clData.horizontalSpan = 2;
countLabel.setLayoutData(clData);
viewer = new FileListViewer(composite, allFiles, checkedFiles, false);
((GridData) viewer.getTable().getLayoutData()).horizontalSpan = 2;
updateCount();
viewer.addCheckStateListener(new ICheckStateListener() {
public void checkStateChanged(CheckStateChangedEvent event) {
updateCount();
}
});
return dialogArea;
}
/**
* Update the store variables representing the current selection of
* changelist and files
*/
public void updateSelection() {
Object[] elements = viewer.getCheckedElements();
selectedFiles = new IP4Resource[elements.length];
for (int i = 0; i < elements.length; i++) {
selectedFiles[i] = (IP4Resource) elements[i];
}
}
/**
* @see org.eclipse.jface.dialogs.StatusDialog#createButtonsForButtonBar(org.eclipse.swt.widgets.Composite)
*/
@Override
protected void createButtonsForButtonBar(Composite parent) {
((GridLayout) parent.getLayout()).makeColumnsEqualWidth = false;
String okLabel = null;
if (this.option == Option.DELETE) {
okLabel = Messages.ShelveFileDialog_Delete;
} else {
okLabel = Messages.ShelveFileDialog_Shelve;
}
okStatusButton = createButton(parent, IDialogConstants.OK_ID, okLabel,
true);
Button advanced = createButton(parent, IDialogConstants.DETAILS_ID,
Messages.ShelveFileDialog_Advanced, false);
advanced.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
updateSelection();
cancelPressed();
P4Runner.schedule(new P4Runnable() {
@Override
public void run(IProgressMonitor monitor) {
ShelveChangelistAction action = new ShelveChangelistAction();
action.updateShelveNumbered(list, selectedFiles, option);
}
@Override
public String getTitle() {
return MessageFormat
.format(Messages.ShelveFileDialog_UpdatingShelvedChangelist,
list.getId());
}
});
}
});
createButton(parent, IDialogConstants.CANCEL_ID,
IDialogConstants.CANCEL_LABEL, false);
}
/**
* @see org.eclipse.jface.dialogs.Dialog#okPressed()
*/
@Override
protected void okPressed() {
updateSelection();
super.okPressed();
}
}
| 32.900943 | 111 | 0.631971 |
8e33b7d47282e9016caf891515fca232e50af6f7 | 922 | package com.exam.service.impl;
import com.exam.entity.Admin;
import com.exam.entity.Student;
import com.exam.entity.Teacher;
import com.exam.mapper.LoginMapper;
import com.exam.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @author PlutoWu
* @date 2021/05/24
*/
@Service
public class LoginServiceImpl implements LoginService {
@Autowired
private LoginMapper loginMapper;
@Override
public Admin adminLogin(Integer username, String password) {
return loginMapper.adminLogin(username,password);
}
@Override
public Teacher teacherLogin(Integer username, String password) {
return loginMapper.teacherLogin(username,password);
}
@Override
public Student studentLogin(Integer username, String password) {
return loginMapper.studentLogin(username,password);
}
}
| 25.611111 | 68 | 0.751627 |
fdf49b504774923190e8c92ef875e62478f26d1f | 2,529 | package com.shri.springsecurity.web.controller;
import javax.validation.Valid;
import com.shri.springsecurity.persistence.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.shri.springsecurity.web.model.User;
@Controller
@RequestMapping("/")
public class UserController {
private final UserRepository userRepository;
//
@Autowired
public UserController(UserRepository userRepository) {
this.userRepository = userRepository;
}
@RequestMapping
public ModelAndView list() {
Iterable<User> users = this.userRepository.findAll();
return new ModelAndView("users/list", "users", users);
}
@RequestMapping("{id}")
public ModelAndView view(@PathVariable("id") User user) {
return new ModelAndView("users/view", "user", user);
}
@RequestMapping(params = "form", method = RequestMethod.GET)
public String createForm(@ModelAttribute User user) {
return "users/form";
}
@RequestMapping(method = RequestMethod.POST)
public ModelAndView create(@Valid User user, BindingResult result, RedirectAttributes redirect) {
if (result.hasErrors()) {
return new ModelAndView("users/form", "formErrors", result.getAllErrors());
}
user = this.userRepository.save(user);
redirect.addFlashAttribute("globalMessage", "Successfully created a new user");
return new ModelAndView("redirect:/{user.id}", "user.id", user.getId());
}
@RequestMapping("foo")
public String foo() {
throw new RuntimeException("Expected exception in controller");
}
@RequestMapping(value = "delete/{id}")
public ModelAndView delete(@PathVariable("id") Long id) {
this.userRepository.deleteUser(id);
return new ModelAndView("redirect:/");
}
@RequestMapping(value = "modify/{id}", method = RequestMethod.GET)
public ModelAndView modifyForm(@PathVariable("id") User user) {
return new ModelAndView("users/form", "user", user);
}
}
| 34.175676 | 101 | 0.719257 |
ae2c3337857106d1ddc4a96ac5ccbb10db544d06 | 813 | package com.xiaosa.spring;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;
/**
* @author yongcezhang
* @date 2021/4/7 20:37
*/
@Component
public class testBeanfactoryPostProcessors implements BeanFactoryPostProcessor {
/**
* 改变bean的类
* @param beanFactory the bean factory used by the application context
* @throws BeansException
*/
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
// GenericBeanDefinition gf = (GenericBeanDefinition) beanFactory.getBeanDefinition("cityService");
// gf.setBeanClass(XXService.class);
}
}
| 30.111111 | 104 | 0.810578 |
99540fdd74a839c6a55664c17d7b1c36ac9079e3 | 767 | package com.xiaoleilu.hutool.json;
import com.xiaoleilu.hutool.getter.OptNullBasicTypeFromObjectGetter;
/**
* 用于JSON的Getter类,提供各种类型的Getter方法
* @author Looly
*
* @param <K> Key类型
*/
public abstract class JSONGetter<K> extends OptNullBasicTypeFromObjectGetter<K>{
/**
* 获得JSONArray对象
*
* @param key KEY
* @return JSONArray对象,如果值为null或者非JSONArray类型,返回null
*/
public JSONArray getJSONArray(K key) {
Object o = this.getObj(key);
return o instanceof JSONArray ? (JSONArray) o : null;
}
/**
* 获得JSONObject对象
*
* @param key KEY
* @return JSONArray对象,如果值为null或者非JSONObject类型,返回null
*/
public JSONObject getJSONObject(K key) {
Object object = this.getObj(key);
return object instanceof JSONObject ? (JSONObject) object : null;
}
}
| 21.914286 | 80 | 0.720991 |
e8a6716124bc691f9b5d9950d58c9b867ffca147 | 6,640 | package predict;
import data.Checkin;
import data.PredictionDataset;
import data.Sequence;
import data.SequenceDataset;
import demo.Demo;
import model.ShareHMM;
import myutils.ScoreCell;
import myutils.TopKSearcher;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public abstract class Predictor {
List<Double> accuracyList = new ArrayList<Double>();
int U;
int[] userNumPred;
int[][] userNumCorrectK;
List<Integer> KList;
// Input: a database of length-2 movements;
public void predict(PredictionDataset mdb, List<Integer> KList) throws IOException {
U = SequenceDataset.getNumUsers();
userNumPred = new int[U];
userNumCorrectK = new int[U][KList.size()];
this.KList = KList;
if(Demo.underlyingDistribution.equals("2dGaussian")){
predictGeo(mdb, KList);
}
else if(Demo.underlyingDistribution.equals("multinomial")){
predictItem(mdb, KList);
}
if(Demo.saveUserAcc)
writeUserAcc();
}
public void predictGeo(PredictionDataset mdb, List<Integer> KList) {
int[] numCorrectK = new int[KList.size()];
int Kmax = KList.get(KList.size()-1);
for (int i=0; i<mdb.size(); i++) {
// int step = mdb.size()/100;
// if(i%step == 0)
// System.out.println("prediction ..." + i/step + "%");
Sequence m = mdb.getSeq(i);
int u = SequenceDataset.userIdList.indexOf(m.getUserId());
userNumPred[u]++;
Set<Checkin> candidate = mdb.getCands(i);
TopKSearcher tks = new TopKSearcher();
tks.init(Kmax);
for (Checkin p : candidate) {
ScoreCell sc = calcScore(m, p);
tks.add(sc);
}
ScoreCell [] topKResults = new ScoreCell[Kmax];
topKResults = tks.getTopKList(topKResults);
int queueLength = Kmax;
for (int j = 0; j < Kmax; j++)
if(topKResults[j] == null)
queueLength--;
sort(topKResults, queueLength);
for (int j = 0; j < KList.size(); j++)
{
// System.out.println("topKResults" + topKResults[j].getScore());
for (int k = 0; k < Math.min(queueLength, KList.get(j)); k++){
if (m.getCheckin(1).getId() == topKResults[k].getId()) {
numCorrectK[j]++;
userNumCorrectK[u][j]++;
// System.out.println(candidate.size() + " +");
} else {
// System.out.println(candidate.size() + " -");
}
}
}
}
for (int j = 0; j < KList.size(); j++){
accuracyList.add((double) numCorrectK[j] / (double) mdb.size());
}
}
public void predictItem(PredictionDataset mdb, List<Integer> KList) {
int[] numCorrectK = new int[KList.size()];
int Kmax = KList.get(KList.size()-1);
for (int i=0; i<mdb.size(); i++) {
int step = mdb.size()/100;
if(i%step == 0)
System.out.println("prediction ..." + i/step + "%");
Sequence m = mdb.getSeq(i);
int u = SequenceDataset.userIdList.indexOf(m.getUserId());
// userNumPred[u]++;
Set<Checkin> candidate = mdb.getCands(i);
// // use all items for candidates
// Set<Checkin> candidate = new HashSet<Checkin>();
// for (int j=0; j<SequenceDataset.getD(); j++) {
// candidate.add(new Checkin(j, 0, m.getCheckin(0).getUserId(), j));
// }
TopKSearcher tks = new TopKSearcher();
tks.init(Kmax);
for (Checkin p : candidate) {
ScoreCell sc = calcScore(m, p);
tks.add(sc);
}
ScoreCell [] topKResults = new ScoreCell[Kmax];
topKResults = tks.getTopKList(topKResults);
int queueLength = Kmax;
for (int j = 0; j < Kmax; j++)
if(topKResults[j] == null)
queueLength--;
sort(topKResults, queueLength);
for (int j = 0; j < KList.size(); j++)
{
// System.out.println("topKResults" + topKResults[j].getScore());
for (int k = 0; k < Math.min(queueLength, KList.get(j)); k++){
// result get Id is equal to checkin item Id
if (m.getCheckin(1).getItemId() == topKResults[k].getId()) {
numCorrectK[j]++;
userNumCorrectK[u][j]++;
// System.out.println(candidate.size() + " +");
} else {
// System.out.println(candidate.size() + " -");
}
}
}
}
for (int j = 0; j < KList.size(); j++){
accuracyList.add((double) numCorrectK[j] / (double) mdb.size());
}
}
public abstract ScoreCell calcScore(Sequence m, Checkin p);
public void sort(ScoreCell[] topKResults, int queueLength){
ScoreCell swap;
for (int i = 0; i < Math.min(topKResults.length-1, queueLength); i++)
for (int j = i+1; j < Math.min(topKResults.length, queueLength); j++)
if(topKResults[i].getScore() < topKResults[j].getScore()){
swap = topKResults[i];
topKResults[i] = topKResults[j];
topKResults[j] = swap;
}
}
public boolean isCorrect(Sequence m, ScoreCell [] topKResult) {
int groundTruth = m.getCheckin(1).getId();
for (int i = 0; i < topKResult.length; i++)
if (groundTruth == topKResult[i].getId())
return true;
return false;
}
public List<Double> getAccuracy() {
return accuracyList;
}
void writeUserAcc() throws IOException {
FileWriter fw;
String dir = "../result/txt/userPred/";
File fileDir = new File(dir);
fileDir.mkdirs();
fw = new FileWriter(dir + Demo.dataset + Demo.method + ".txt");
// first line: title
String title = "userNumPred ";
for (int j = 0; j < userNumCorrectK[0].length; j++) {
title += "top" + KList.get(j) + " ";
}
fw.write(title + "\n");
// then one user per line
for (int u = 0; u < U; u++) {
fw.write(String.valueOf(userNumPred[u]));fw.write(" ");
for (int j = 0; j < userNumCorrectK[0].length; j++) {
fw.write(String.valueOf(userNumCorrectK[u][j]));fw.write(" ");
}
fw.write("\n");
}
fw.close();
}
}
| 35.132275 | 88 | 0.533584 |
afc21c44fedf585f2012c7b55ab476cfbbe79ea4 | 479 | public class test_code_point
{
public static void main(/*String[] argv*/)
{
String s = "!𐤇𐤄𐤋𐤋𐤅";
assert(s.codePointAt(1) == 67847);
assert(s.codePointBefore(3) == 67847);
assert(s.codePointCount(1,5) >= 2);
assert(s.offsetByCodePoints(1,2) >= 3);
StringBuilder sb = new StringBuilder();
sb.appendCodePoint(0x10907);
assert(org.cprover.CProverString.charAt(s, 1) == org.cprover.CProverString.charAt(sb.toString(), 0));
}
}
| 31.933333 | 107 | 0.634656 |
5ad029ca07d65c933db947264603d38d51595a32 | 3,580 | /*
* XML Type: descriptionType
* Namespace: http://openejb.apache.org/xml/ns/corba-tss-config-2.1
* Java type: org.apache.geronimo.corba.xbeans.csiv2.tss.TSSDescriptionType
*
* Automatically generated - do not modify.
*/
package org.apache.geronimo.corba.xbeans.csiv2.tss.impl;
/**
* An XML descriptionType(@http://openejb.apache.org/xml/ns/corba-tss-config-2.1).
*
* This is an atomic type that is a restriction of org.apache.geronimo.corba.xbeans.csiv2.tss.TSSDescriptionType.
*/
public class TSSDescriptionTypeImpl extends org.apache.xmlbeans.impl.values.JavaStringHolderEx implements org.apache.geronimo.corba.xbeans.csiv2.tss.TSSDescriptionType
{
private static final long serialVersionUID = 1L;
public TSSDescriptionTypeImpl(org.apache.xmlbeans.SchemaType sType)
{
super(sType, true);
}
protected TSSDescriptionTypeImpl(org.apache.xmlbeans.SchemaType sType, boolean b)
{
super(sType, b);
}
private static final javax.xml.namespace.QName LANG$0 =
new javax.xml.namespace.QName("http://www.w3.org/XML/1998/namespace", "lang");
/**
* Gets the "lang" attribute
*/
public java.lang.String getLang()
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue)get_store().find_attribute_user(LANG$0);
if (target == null)
{
return null;
}
return target.getStringValue();
}
}
/**
* Gets (as xml) the "lang" attribute
*/
public org.apache.xmlbeans.XmlLanguage xgetLang()
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.XmlLanguage target = null;
target = (org.apache.xmlbeans.XmlLanguage)get_store().find_attribute_user(LANG$0);
return target;
}
}
/**
* True if has "lang" attribute
*/
public boolean isSetLang()
{
synchronized (monitor())
{
check_orphaned();
return get_store().find_attribute_user(LANG$0) != null;
}
}
/**
* Sets the "lang" attribute
*/
public void setLang(java.lang.String lang)
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue)get_store().find_attribute_user(LANG$0);
if (target == null)
{
target = (org.apache.xmlbeans.SimpleValue)get_store().add_attribute_user(LANG$0);
}
target.setStringValue(lang);
}
}
/**
* Sets (as xml) the "lang" attribute
*/
public void xsetLang(org.apache.xmlbeans.XmlLanguage lang)
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.XmlLanguage target = null;
target = (org.apache.xmlbeans.XmlLanguage)get_store().find_attribute_user(LANG$0);
if (target == null)
{
target = (org.apache.xmlbeans.XmlLanguage)get_store().add_attribute_user(LANG$0);
}
target.set(lang);
}
}
/**
* Unsets the "lang" attribute
*/
public void unsetLang()
{
synchronized (monitor())
{
check_orphaned();
get_store().remove_attribute(LANG$0);
}
}
}
| 28.870968 | 167 | 0.582961 |
cfb08b88d81f871fb0ba85dbc12aee818868a103 | 133 | package com.astronomvm.core.model.meta.operation.trigger;
public class ScheduledMetaFlowTriggerMeta extends MetaFlowTriggerMeta {
}
| 26.6 | 71 | 0.857143 |
b0750f8f9fd259867ecfc32560d2ecea8773da47 | 7,940 | package de.dlyt.yanndroid.oneui.preference;
import android.app.Dialog;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.SystemClock;
import android.util.AttributeSet;
import androidx.annotation.NonNull;
import java.util.ArrayList;
import java.util.Collections;
import de.dlyt.yanndroid.oneui.R;
import de.dlyt.yanndroid.oneui.dialog.ClassicColorPickerDialog;
import de.dlyt.yanndroid.oneui.dialog.DetailedColorPickerDialog;
import de.dlyt.yanndroid.oneui.preference.internal.PreferenceImageView;
public class ColorPickerPreference extends Preference implements Preference.OnPreferenceClickListener,
ClassicColorPickerDialog.OnColorSetListener,
DetailedColorPickerDialog.OnColorSetListener {
private static int CLASSIC = 0;
private static int DETAILED = 1;
PreferenceViewHolder mViewHolder;
Dialog mDialog;
PreferenceImageView mPreview;
private int mValue = Color.BLACK;
private ArrayList<Integer> mUsedColors = new ArrayList();
private long mLastClickTime;
private boolean mAlphaSliderEnabled = false;
private int mPickerType = CLASSIC;
public ColorPickerPreference(Context context) {
this(context, null);
}
public ColorPickerPreference(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public ColorPickerPreference(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
public static int convertToColorInt(String argb) throws IllegalArgumentException {
if (!argb.startsWith("#")) {
argb = "#" + argb;
}
return Color.parseColor(argb);
}
@Override
protected Object onGetDefaultValue(TypedArray a, int index) {
int colorInt;
String mHexDefaultValue = a.getString(index);
if (mHexDefaultValue != null && mHexDefaultValue.startsWith("#")) {
colorInt = convertToColorInt(mHexDefaultValue);
return colorInt;
} else {
return a.getColor(index, Color.BLACK);
}
}
@Override
protected void onSetInitialValue(Object defaultValue) {
onColorSet(defaultValue == null ? getPersistedInt(mValue) : (Integer) defaultValue);
}
private void init(Context context, AttributeSet attrs) {
setWidgetLayoutResource(R.layout.oui_color_picker_preference_widget);
setOnPreferenceClickListener(this);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ColorPickerPreference);
mAlphaSliderEnabled = a.getBoolean(R.styleable.ColorPickerPreference_showAlphaSlider, false);
mPickerType = a.getInt(R.styleable.ColorPickerPreference_pickerType, CLASSIC);
a.recycle();
}
@Override
public void onBindViewHolder(@NonNull PreferenceViewHolder holder) {
super.onBindViewHolder(holder);
mViewHolder = holder;
mPreview = (PreferenceImageView) holder.findViewById(R.id.imageview_widget);
setPreviewColor();
}
private void setPreviewColor() {
if (mPreview == null) {
return;
}
GradientDrawable drawable = (GradientDrawable) getContext().getDrawable(R.drawable.oui_color_picker_preference_preview).mutate();
drawable.setColor(mValue);
mPreview.setBackground(drawable);
}
@Override
public void onColorSet(int color) {
if (isPersistent()) {
persistInt(color);
}
mValue = color;
callChangeListener(color);
addRecentColor(color);
setPreviewColor();
}
@Override
public boolean onPreferenceClick(@NonNull Preference preference) {
long uptimeMillis = SystemClock.uptimeMillis();
if (uptimeMillis - mLastClickTime > 600L) {
showDialog(null);
}
mLastClickTime = uptimeMillis;
return false;
}
private void showDialog(Bundle state) {
if (mPickerType == CLASSIC) {
ClassicColorPickerDialog dialog = new ClassicColorPickerDialog(getContext(), this, mValue, getRecentColors());
dialog.setNewColor(mValue);
dialog.setTransparencyControlEnabled(mAlphaSliderEnabled);
if (state != null)
dialog.onRestoreInstanceState(state);
dialog.show();
mDialog = dialog;
} else if (mPickerType == DETAILED) {
DetailedColorPickerDialog dialog = new DetailedColorPickerDialog(getContext(), this, mValue, getRecentColors(), mAlphaSliderEnabled);
dialog.setNewColor(mValue);
dialog.setTransparencyControlEnabled(mAlphaSliderEnabled);
if (state != null)
dialog.onRestoreInstanceState(state);
dialog.show();
mDialog = dialog;
}
}
public void setAlphaSliderEnabled(boolean enable) {
mAlphaSliderEnabled = enable;
}
public void setPickerType(int type) {
mPickerType = type;
}
private void addRecentColor(int color) {
for (int i = 0; i < mUsedColors.size(); i++) {
if (mUsedColors.get(i) == color)
mUsedColors.remove(i);
}
if (mUsedColors.size() > 5) {
mUsedColors.remove(0);
}
mUsedColors.add(color);
}
private int[] getRecentColors() {
int[] usedColors = new int[mUsedColors.size()];
ArrayList<Integer> reverseUsedColor = new ArrayList<>(mUsedColors);
Collections.reverse(reverseUsedColor);
for (int i = 0; i < reverseUsedColor.size(); i++) {
usedColors[i] = reverseUsedColor.get(i);
}
return usedColors;
}
@Override
protected Parcelable onSaveInstanceState() {
final Parcelable superState = super.onSaveInstanceState();
if (mDialog == null || !mDialog.isShowing()) {
return superState;
}
final SavedState myState = new SavedState(superState);
myState.dialogBundle = mDialog.onSaveInstanceState();
return myState;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
if (state == null || !(state instanceof SavedState)) {
super.onRestoreInstanceState(state);
return;
}
SavedState myState = (SavedState) state;
super.onRestoreInstanceState(myState.getSuperState());
showDialog(myState.dialogBundle);
}
public String toString(ArrayList<Integer> arrList) {
int n = arrList.size();
if (n == 0)
return "0";
String str = "";
for (int i = arrList.size() - 1; i > 0; i--) {
int nums = arrList.get(i);
str += nums;
}
return str;
}
private static class SavedState extends BaseSavedState {
public static final Parcelable.Creator<SavedState> CREATOR =
new Parcelable.Creator<SavedState>() {
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
Bundle dialogBundle;
public SavedState(Parcel source) {
super(source);
dialogBundle = source.readBundle();
}
public SavedState(Parcelable superState) {
super(superState);
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeBundle(dialogBundle);
}
}
}
| 31.259843 | 145 | 0.637783 |
5fdd53acdd95573c23decacd569da418c9bc71c3 | 14,107 | /*
* Copyright 2013 Christian Felde (cfelde [at] cfelde [dot] com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cfelde.rpqueue.test;
import com.cfelde.rpqueue.Resource;
import com.cfelde.rpqueue.ResourcePriorityBlockingQueue;
import com.cfelde.rpqueue.Task;
import com.cfelde.rpqueue.schedulers.AllAllocator;
import com.cfelde.rpqueue.schedulers.FixedPrioritizer;
import com.cfelde.rpqueue.schedulers.PayloadAllocator;
import com.cfelde.rpqueue.utils.ImmutableByteArray;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* @author cfelde
*/
public class TestResourcePriorityBlockingQueue {
public TestResourcePriorityBlockingQueue() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
for (String name: ResourcePriorityBlockingQueue.getAllQueues().keySet().toArray(new String[0])) {
ResourcePriorityBlockingQueue.shutdownQueue(name);
}
}
@Test
public void ensureUniqueQueue() {
assertTrue(ResourcePriorityBlockingQueue.createQueue("ensureUniqueQueue1", new FixedPrioritizer(), new AllAllocator()));
assertFalse(ResourcePriorityBlockingQueue.createQueue("ensureUniqueQueue1", new FixedPrioritizer(), new AllAllocator()));
}
@Test
public void singlePubSingleSub() {
assertTrue(ResourcePriorityBlockingQueue.createQueue("q1", new FixedPrioritizer(), new AllAllocator(), 1000));
ResourcePriorityBlockingQueue pub = ResourcePriorityBlockingQueue.getPublisherQueue("q1");
ResourcePriorityBlockingQueue sub = ResourcePriorityBlockingQueue.getSubscriberQueue("q1", new Resource(ImmutableByteArray.fromString("sub1"), null));
assertTrue(pub.isEmpty());
assertTrue(sub.isEmpty());
Task task = new Task(ImmutableByteArray.fromString("task1"), ImmutableByteArray.fromString("payload1"));
assertTrue(pub.offer(task));
assertEquals(1, pub.size());
assertEquals(1, sub.size());
assertEquals(task, sub.peek());
assertEquals(task, sub.poll());
assertNull(sub.peek());
assertNull(sub.poll());
assertTrue(pub.isEmpty());
assertTrue(sub.isEmpty());
}
@Test
public void singlePubTwoSub() {
assertTrue(ResourcePriorityBlockingQueue.createQueue("q1", new FixedPrioritizer(), new AllAllocator(), 1000));
ResourcePriorityBlockingQueue pub = ResourcePriorityBlockingQueue.getPublisherQueue("q1");
ResourcePriorityBlockingQueue sub1 = ResourcePriorityBlockingQueue.getSubscriberQueue("q1", new Resource(ImmutableByteArray.fromString("sub1"), null));
ResourcePriorityBlockingQueue sub2 = ResourcePriorityBlockingQueue.getSubscriberQueue("q1", new Resource(ImmutableByteArray.fromString("sub2"), null));
assertTrue(pub.isEmpty());
assertTrue(sub1.isEmpty());
assertTrue(sub2.isEmpty());
Task task = new Task(ImmutableByteArray.fromString("task1"), ImmutableByteArray.fromString("payload1"));
assertTrue(pub.offer(task));
assertEquals(1, pub.size());
assertEquals(1, sub1.size());
assertEquals(1, sub2.size());
assertEquals(task, sub1.peek());
assertEquals(task, sub2.peek());
assertEquals(task, sub1.poll());
assertNull(sub2.poll());
assertNull(sub1.peek());
assertNull(sub1.poll());
assertTrue(pub.isEmpty());
assertTrue(sub1.isEmpty());
assertTrue(sub2.isEmpty());
}
@Test
public void singlePubTwoDedicatedSub() {
ImmutableByteArray payload1 = ImmutableByteArray.fromString("payload1");
ImmutableByteArray payload2 = ImmutableByteArray.fromString("payload2");
Resource resource1 = new Resource(ImmutableByteArray.fromString("resource1"), payload1);
Resource resource2 = new Resource(ImmutableByteArray.fromString("resource2"), payload2);
assertTrue(ResourcePriorityBlockingQueue.createQueue("q1", new FixedPrioritizer(), new PayloadAllocator(), 1000));
ResourcePriorityBlockingQueue pub = ResourcePriorityBlockingQueue.getPublisherQueue("q1");
ResourcePriorityBlockingQueue sub1 = ResourcePriorityBlockingQueue.getSubscriberQueue("q1", resource1);
ResourcePriorityBlockingQueue sub2 = ResourcePriorityBlockingQueue.getSubscriberQueue("q1", resource2);
assertTrue(pub.isEmpty());
assertTrue(sub1.isEmpty());
assertTrue(sub2.isEmpty());
Task task1 = new Task(ImmutableByteArray.fromString("task1"), payload1);
assertTrue(pub.offer(task1));
assertEquals(1, pub.size());
assertEquals(1, sub1.size());
assertEquals(0, sub2.size());
Task task2 = new Task(ImmutableByteArray.fromString("task2"), payload2);
assertTrue(pub.offer(task2));
assertEquals(2, pub.size());
assertEquals(1, sub1.size());
assertEquals(1, sub2.size());
assertEquals(task1, sub1.peek());
assertEquals(task2, sub2.peek());
assertEquals(2, pub.size());
assertEquals(task1, sub1.poll());
assertEquals(1, pub.size());
assertEquals(task2, sub2.poll());
assertEquals(0, pub.size());
assertNull(sub1.peek());
assertNull(sub1.poll());
assertNull(sub2.peek());
assertNull(sub2.poll());
assertTrue(pub.isEmpty());
assertTrue(sub1.isEmpty());
assertTrue(sub2.isEmpty());
}
@Test
public void maxLimitBlock1() throws InterruptedException {
final int maxSize = 100;
assertTrue(ResourcePriorityBlockingQueue.createQueue("q1", new FixedPrioritizer(), new AllAllocator(), maxSize));
final ResourcePriorityBlockingQueue queue = ResourcePriorityBlockingQueue.getSubscriberQueue("q1", new Resource(ImmutableByteArray.fromString("r1"), null));
assertEquals(0, queue.size());
assertEquals(maxSize, queue.remainingCapacity());
for (int i = 0; i < maxSize; i++) {
assertTrue(queue.offer(new Task(ImmutableByteArray.fromLong(i), ImmutableByteArray.fromUUID(UUID.randomUUID()))));
}
assertFalse(queue.offer(new Task(ImmutableByteArray.fromLong(100), ImmutableByteArray.fromUUID(UUID.randomUUID()))));
assertEquals(maxSize, queue.size());
assertEquals(0, queue.remainingCapacity());
final AtomicBoolean didOffer = new AtomicBoolean();
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
queue.offer(new Task(ImmutableByteArray.fromLong(100), ImmutableByteArray.fromUUID(UUID.randomUUID())), Long.MAX_VALUE, TimeUnit.MILLISECONDS);
didOffer.set(true);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
});
t.start();
Thread.sleep(1000);
assertTrue(t.isAlive());
assertFalse(didOffer.get());
assertNotNull(queue.poll());
t.join();
assertTrue(didOffer.get());
assertEquals(maxSize, queue.size());
assertEquals(0, queue.remainingCapacity());
}
@Test
public void maxLimitBlock2() throws InterruptedException {
final int maxSize = 100;
assertTrue(ResourcePriorityBlockingQueue.createQueue("q1", new FixedPrioritizer(), new AllAllocator(), maxSize));
final ResourcePriorityBlockingQueue queue = ResourcePriorityBlockingQueue.getSubscriberQueue("q1", new Resource(ImmutableByteArray.fromString("r1"), null));
assertEquals(0, queue.size());
assertEquals(maxSize, queue.remainingCapacity());
for (int i = 0; i < maxSize; i++) {
assertTrue(queue.offer(new Task(ImmutableByteArray.fromLong(i), ImmutableByteArray.fromUUID(UUID.randomUUID()))));
}
assertFalse(queue.offer(new Task(ImmutableByteArray.fromLong(100), ImmutableByteArray.fromUUID(UUID.randomUUID()))));
assertEquals(maxSize, queue.size());
assertEquals(0, queue.remainingCapacity());
final AtomicBoolean didOffer = new AtomicBoolean();
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
queue.offer(new Task(ImmutableByteArray.fromLong(100), ImmutableByteArray.fromUUID(UUID.randomUUID())), Long.MAX_VALUE, TimeUnit.MILLISECONDS);
didOffer.set(true);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
});
t.start();
Thread.sleep(1000);
assertTrue(t.isAlive());
assertFalse(didOffer.get());
assertTrue(queue.remove(queue.peek()));
t.join();
assertTrue(didOffer.get());
assertEquals(maxSize, queue.size());
assertEquals(0, queue.remainingCapacity());
}
@Test
public void drainTo1() {
final int maxSize = 1000;
assertTrue(ResourcePriorityBlockingQueue.createQueue("q1", new FixedPrioritizer(), new AllAllocator()));
final ResourcePriorityBlockingQueue queue = ResourcePriorityBlockingQueue.getSubscriberQueue("q1", new Resource(ImmutableByteArray.fromString("r1"), null));
for (int i = 0; i < maxSize; i++) {
assertTrue(queue.offer(new Task(ImmutableByteArray.fromLong(i), ImmutableByteArray.fromUUID(UUID.randomUUID()))));
}
List<Task> tasks = new ArrayList<Task>();
queue.drainTo(tasks);
assertEquals(maxSize, tasks.size());
assertTrue(queue.isEmpty());
}
@Test
public void drainTo2() {
final int maxSize = 1000;
assertTrue(ResourcePriorityBlockingQueue.createQueue("q1", new FixedPrioritizer(), new AllAllocator()));
final ResourcePriorityBlockingQueue queue1 = ResourcePriorityBlockingQueue.getPublisherQueue("q1");
final ResourcePriorityBlockingQueue queue2 = ResourcePriorityBlockingQueue.getSubscriberQueue("q1", new Resource(ImmutableByteArray.fromString("r1"), null));
for (int i = 0; i < maxSize; i++) {
assertTrue(queue1.offer(new Task(ImmutableByteArray.fromLong(i), ImmutableByteArray.fromUUID(UUID.randomUUID()))));
}
final AtomicBoolean gotException = new AtomicBoolean();
try {
queue1.drainTo(queue1);
} catch (IllegalArgumentException ex) {
gotException.set(true);
}
assertTrue(gotException.get());
gotException.set(false);
try {
queue1.drainTo(queue2);
} catch (IllegalArgumentException ex) {
gotException.set(true);
}
assertTrue(gotException.get());
gotException.set(false);
try {
queue2.drainTo(queue1);
} catch (IllegalArgumentException ex) {
gotException.set(true);
}
assertTrue(gotException.get());
gotException.set(false);
try {
queue2.drainTo(queue2);
} catch (IllegalArgumentException ex) {
gotException.set(true);
}
assertTrue(gotException.get());
assertFalse(queue1.isEmpty());
assertFalse(queue2.isEmpty());
assertEquals(maxSize, queue1.size());
assertEquals(maxSize, queue2.size());
}
@Test
public void iterator() {
final int maxSize = 1000;
assertTrue(ResourcePriorityBlockingQueue.createQueue("q1", new FixedPrioritizer(), new AllAllocator()));
final ResourcePriorityBlockingQueue queue1 = ResourcePriorityBlockingQueue.getPublisherQueue("q1");
final ResourcePriorityBlockingQueue queue2 = ResourcePriorityBlockingQueue.getSubscriberQueue("q1", new Resource(ImmutableByteArray.fromString("r1"), null));
for (int i = 0; i < maxSize; i++) {
assertTrue(queue1.offer(new Task(ImmutableByteArray.fromLong(i), ImmutableByteArray.fromUUID(UUID.randomUUID()))));
}
Iterator<Task> it1 = queue1.iterator();
for (int i = 0; i < maxSize; i++) {
assertTrue(it1.hasNext());
assertNotNull(it1.next());
}
assertFalse(it1.hasNext());
Iterator<Task> it2 = queue2.iterator();
for (int i = 0; i < maxSize; i++) {
assertTrue(it2.hasNext());
assertNotNull(it2.next());
}
assertFalse(it2.hasNext());
}
} | 37.419098 | 165 | 0.626781 |
c2d5df864f21e096eb82e0b1c2014b63407c4612 | 409 | package com.algaworks.algafood.domain.exception;
public class CidadeNaoEncontradaException extends EntidadeNaoEncontradaException {
private static final long serialVersionUID = 1L;
public CidadeNaoEncontradaException(String mensagem) {
super(mensagem);
}
public CidadeNaoEncontradaException(Long cidadeId) {
this(String.format("Não existe um cadastro de cidade com código %d", cidadeId));
}
}
| 25.5625 | 82 | 0.797066 |
7a7c260b849bd084de780c98d84ab20de345f510 | 690 | package com.luoluo.delaymq.mysql;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.*;
import java.io.Serializable;
import java.util.Date;
/**
* @ClassName ConsumerMsgData
* @Description: 消费数据记录
* @Author luoluo
* @Date 2020/7/9
* @Version V1.0
**/
@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class ConsumerMsg extends AbstractDataBO implements Serializable {
@JsonIgnore
private String msgId;
private String topic;
private String consumerGroup;
private String consumerStatus;
private Date consumerTime;
private Date executeTime;
private int retryCount;
private Date retryNextTime;
}
| 16.829268 | 73 | 0.746377 |
a37637fc27ffdab444a9b721006e5c36ffb71063 | 998 | package injection;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.jupiter.api.extension.ParameterResolutionException;
import org.junit.jupiter.api.extension.ParameterResolver;
import org.junit.platform.commons.util.AnnotationUtils;
public class UserParameterResolver implements ParameterResolver {
@Override
public boolean supports(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
return parameterContext.getParameter().getType() == User.class;
}
@Override
public Object resolve(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
User user = new User();
user.setName("Foo Bar");
if (AnnotationUtils.isAnnotated(parameterContext.getParameter(), Full.class)) {
user.setPhoneNumer("123456789");
}
return user;
}
}
| 39.92 | 135 | 0.768537 |
6d631c30f725b49efe6bf1b0692b5854170eace3 | 903 | package com.custom.rest;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.lcs.wc.product.LCSProduct;
import com.lcs.wc.util.FormatHelper;
import wt.util.WTException;
@JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE)
@JsonPropertyOrder({ "objectIdentifier", "productName" })
public class ProductProxy{
private LCSProduct product;
public ProductProxy(LCSProduct product) {
this.product = product;
}
@JsonProperty("objectIdentifier")
public String getObjectIdentifier(){
return (FormatHelper.getObjectId(product));
}
@JsonProperty("productName")
public String getProductName() throws WTException {
return product.getValue("productName").toString();
}
}
| 30.1 | 120 | 0.776301 |
c28ae2465cf47ecb4127e2dc81221238a4545599 | 887 | package com.example.demo.controller;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
//@Component // normal component
@WebFilter // java ee servlet filter
public class MyServletFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("! MyServletFilter initialised");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("! filter called for: " + servletRequest.getScheme());
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
System.out.println("! MyServletFilter destroyed");
}
}
| 31.678571 | 152 | 0.746336 |
dfff1835e28559feab58472987b24ac3a68ae7bd | 2,301 | /*
* Copyright 2001-2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.tools.ant.taskdefs.condition;
import org.apache.tools.ant.BuildException;
/**
* Simple String comparison condition.
*
* @since Ant 1.4
* @version $Revision: 1.10.2.4 $
*/
public class Equals implements Condition {
private String arg1, arg2;
private boolean trim = false;
private boolean caseSensitive = true;
/**
* Set the first string
*
* @param a1 the first string
*/
public void setArg1(String a1) {
arg1 = a1;
}
/**
* Set the second string
*
* @param a2 the second string
*/
public void setArg2(String a2) {
arg2 = a2;
}
/**
* Should we want to trim the arguments before comparing them?
* @param b if true trim the arguments
* @since Ant 1.5
*/
public void setTrim(boolean b) {
trim = b;
}
/**
* Should the comparison be case sensitive?
* @param b if true use a case sensitive comparison (this is the
* default)
* @since Ant 1.5
*/
public void setCasesensitive(boolean b) {
caseSensitive = b;
}
/**
* @return true if the two strings are equal
* @exception BuildException if the attributes are not set correctly
*/
public boolean eval() throws BuildException {
if (arg1 == null || arg2 == null) {
throw new BuildException("both arg1 and arg2 are required in "
+ "equals");
}
if (trim) {
arg1 = arg1.trim();
arg2 = arg2.trim();
}
return caseSensitive ? arg1.equals(arg2) : arg1.equalsIgnoreCase(arg2);
}
}
| 25.853933 | 79 | 0.608866 |
3a427c07e4646de4caf0e03effdcacf976e0356c | 969 | /* Periodic thread in Java */
import javax.realtime.*;
public class Sporadic_task {
public static void main(String[] args)
{
/* period: 30ms */
RelativeTime period = new RelativeTime(3000 /* ms */, 0 /* ns */);
/* release parameters for periodic thread: */
SporadicParameters sporadicParameters = new SporadicParameters(period);
sporadicParameters.setMinimumInterarrival(period);
sporadicParameters.setMitViolationBehavior(SporadicParameters.mitViolationExcept);
/* create periodic thread: */
RealtimeThread realtimeThread = new RealtimeThread(null, sporadicParameters)
{
public void run()
{
while(true)
{
System.out.println("Sporadic task released");
try {
Thread.sleep(30);
} catch (InterruptedException ie) {
// ignore
}
}
}
};
/* start periodic thread: */
realtimeThread.start();
}
}
| 23.634146 | 86 | 0.616099 |
c94ffa1068a504bea9d1d8da06eb53642e78318c | 147 | package com.wentong.mytest;
import lombok.Data;
@Data
public class Address {
private String streetName;
private String streetNumber;
}
| 12.25 | 32 | 0.741497 |
22d3bb055be21268f848c97c6cfb149cdda4c3df | 3,783 | /*
* Copyright 2016 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.cpman.impl;
import org.onosproject.cpman.SystemInfo;
import java.util.Objects;
import static com.google.common.base.MoreObjects.toStringHelper;
/**
* Implementation class of storing system specification.
*/
public final class DefaultSystemInfo implements SystemInfo {
private final int numOfCores;
private final int numOfCpus;
private final int cpuSpeedMhz;
private final int totalMemoryMbytes;
private DefaultSystemInfo(int numOfCores, int numOfCpus,
int cpuSpeedMhz, int totalMemoryMbytes) {
this.numOfCores = numOfCores;
this.numOfCpus = numOfCpus;
this.cpuSpeedMhz = cpuSpeedMhz;
this.totalMemoryMbytes = totalMemoryMbytes;
}
@Override
public int coreCount() {
return this.numOfCores;
}
@Override
public int cpuCount() {
return this.numOfCpus;
}
@Override
public int cpuSpeed() {
return this.cpuSpeedMhz;
}
@Override
public int totalMemory() {
return this.totalMemoryMbytes;
}
@Override
public int hashCode() {
return Objects.hash(numOfCores, numOfCpus, cpuSpeedMhz, totalMemoryMbytes);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof DefaultSystemInfo) {
final DefaultSystemInfo other = (DefaultSystemInfo) obj;
return Objects.equals(this.numOfCores, other.numOfCores) &&
Objects.equals(this.numOfCpus, other.numOfCpus) &&
Objects.equals(this.cpuSpeedMhz, other.cpuSpeedMhz) &&
Objects.equals(this.totalMemoryMbytes, other.totalMemoryMbytes);
}
return false;
}
@Override
public String toString() {
return toStringHelper(this)
.add("numOfCores", numOfCores)
.add("numOfCpus", numOfCpus)
.add("cpuSpeedMhz", cpuSpeedMhz)
.add("totalMemoryMbytes", totalMemoryMbytes)
.toString();
}
/**
* ControlMetricsSystemSpec builder class.
*/
public static final class Builder implements SystemInfo.Builder {
private int numOfCores;
private int numOfCpus;
private int cpuSpeedMHz;
private int totalMemoryBytes;
@Override
public SystemInfo.Builder numOfCores(int numOfCores) {
this.numOfCores = numOfCores;
return this;
}
@Override
public Builder numOfCpus(int numOfCpus) {
this.numOfCpus = numOfCpus;
return this;
}
@Override
public Builder cpuSpeed(int cpuSpeedMhz) {
this.cpuSpeedMHz = cpuSpeedMhz;
return this;
}
@Override
public Builder totalMemory(int totalMemoryBytes) {
this.totalMemoryBytes = totalMemoryBytes;
return this;
}
@Override
public DefaultSystemInfo build() {
return new DefaultSystemInfo(numOfCores, numOfCpus, cpuSpeedMHz, totalMemoryBytes);
}
}
}
| 28.877863 | 95 | 0.633888 |
5840441ed21a446a249fd6593bd3daf350409b00 | 6,984 |
package de.fraunhofer.iem.swan.io.doc.ssldoclet;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
/**
* <p>Java-Klasse für ConstructorType complex type.
*
* <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
*
* <pre>
* <complexType name="ConstructorType">
* <simpleContent>
* <extension base="<http://www.w3.org/2001/XMLSchema>string">
* <attribute name="final" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="interface" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="line" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="modifier" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="signature" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="static" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="synchronized" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="synthetic" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="visibility" type="{http://www.w3.org/2001/XMLSchema}string" />
* </extension>
* </simpleContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ConstructorType", propOrder = {
"value"
})
public class ConstructorType {
@XmlValue
protected String value;
@XmlAttribute(name = "final")
protected String _final;
@XmlAttribute(name = "interface")
protected String _interface;
@XmlAttribute(name = "line")
protected String line;
@XmlAttribute(name = "modifier")
protected String modifier;
@XmlAttribute(name = "signature")
protected String signature;
@XmlAttribute(name = "static")
protected String _static;
@XmlAttribute(name = "synchronized")
protected String _synchronized;
@XmlAttribute(name = "synthetic")
protected String synthetic;
@XmlAttribute(name = "visibility")
protected String visibility;
/**
* Ruft den Wert der value-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getValue() {
return value;
}
/**
* Legt den Wert der value-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setValue(String value) {
this.value = value;
}
/**
* Ruft den Wert der final-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getFinal() {
return _final;
}
/**
* Legt den Wert der final-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFinal(String value) {
this._final = value;
}
/**
* Ruft den Wert der interface-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getInterface() {
return _interface;
}
/**
* Legt den Wert der interface-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setInterface(String value) {
this._interface = value;
}
/**
* Ruft den Wert der line-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLine() {
return line;
}
/**
* Legt den Wert der line-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLine(String value) {
this.line = value;
}
/**
* Ruft den Wert der modifier-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getModifier() {
return modifier;
}
/**
* Legt den Wert der modifier-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setModifier(String value) {
this.modifier = value;
}
/**
* Ruft den Wert der signature-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSignature() {
return signature;
}
/**
* Legt den Wert der signature-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSignature(String value) {
this.signature = value;
}
/**
* Ruft den Wert der static-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getStatic() {
return _static;
}
/**
* Legt den Wert der static-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setStatic(String value) {
this._static = value;
}
/**
* Ruft den Wert der synchronized-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSynchronized() {
return _synchronized;
}
/**
* Legt den Wert der synchronized-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSynchronized(String value) {
this._synchronized = value;
}
/**
* Ruft den Wert der synthetic-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSynthetic() {
return synthetic;
}
/**
* Legt den Wert der synthetic-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSynthetic(String value) {
this.synthetic = value;
}
/**
* Ruft den Wert der visibility-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getVisibility() {
return visibility;
}
/**
* Legt den Wert der visibility-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setVisibility(String value) {
this.visibility = value;
}
}
| 22.973684 | 101 | 0.545819 |
2e0cffe097b75441bcf5820f123b8ec0443fc772 | 469 | package com.hrm.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Transaction {
private Integer trade_tr_id;
private Integer user_id;
private Integer product_id;
private Integer specification_id;
private String product_name;
private String transaction_time;
private Integer number;
private String authority_time;
}
| 23.45 | 38 | 0.754797 |
fcf856f2387a1abec061e1b0faa288a75ba524c1 | 135 | package com.hy.cat;
/**
* @author CXQ
* @date 2021/11/12
*/
public enum Sex {
/**
* 设置性别
*/
male,female,公,母;
}
| 9 | 20 | 0.481481 |
fcebbee78698711680ce22f8760eb41e56ee1547 | 6,373 | package openperipheral.addons.glasses;
import com.google.common.collect.Maps;
import java.util.Map;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.ScaledResolution;
import openmods.network.event.NetworkEvent;
import openperipheral.addons.Config;
import openperipheral.addons.glasses.GlassesEvent.GlassesComponentMouseButtonEvent;
import openperipheral.addons.glasses.GlassesEvent.GlassesComponentMouseWheelEvent;
import openperipheral.addons.glasses.GlassesEvent.GlassesKeyDownEvent;
import openperipheral.addons.glasses.GlassesEvent.GlassesKeyUpEvent;
import openperipheral.addons.glasses.GlassesEvent.GlassesMouseButtonEvent;
import openperipheral.addons.glasses.GlassesEvent.GlassesMouseDragEvent;
import openperipheral.addons.glasses.GlassesEvent.GlassesMouseWheelEvent;
import openperipheral.addons.glasses.GlassesEvent.GlassesSignalCaptureEvent;
import openperipheral.addons.glasses.client.TerminalManagerClient;
import openperipheral.addons.glasses.client.TerminalManagerClient.DrawableHitInfo;
import openperipheral.addons.utils.GuiUtils;
import openperipheral.addons.utils.GuiUtils.GuiElements;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
public class GuiCapture extends GuiScreen {
private int backgroundColor = 0x2A00FF00;
private final long guid;
private int mouseButtonsDown;
private float lastDragX;
private float lastDragY;
private int dragInterval;
private float dragThresholdSquared = Config.defaultDragThreshold * Config.defaultDragThreshold;
private int dragPeriod = Config.defaultDragPeriod;
private final Map<GuiElements, Boolean> originalState;
private final Map<GuiElements, Boolean> updatedState;
public GuiCapture(long guid) {
this.guid = guid;
this.originalState = GuiUtils.storeGuiElementsState();
this.updatedState = Maps.newEnumMap(GuiElements.class);
}
@Override
public void handleMouseInput() {
super.handleMouseInput();
final int button = Mouse.getEventButton();
final int wheel = Mouse.getEventDWheel();
final int mx = Mouse.getEventX();
final int my = Mouse.getEventY();
final float scaleX = (float)this.width / this.mc.displayWidth;
final float scaleY = (float)this.height / this.mc.displayHeight;
final float x = mx * scaleX;
final float y = this.height - my * scaleY;
if (button != -1 || wheel != 0) {
final ScaledResolution resolution = new ScaledResolution(this.mc, this.mc.displayWidth, this.mc.displayHeight);
final DrawableHitInfo hit = TerminalManagerClient.instance.findDrawableHit(guid, resolution, x, y);
if (button != -1) {
final boolean state = Mouse.getEventButtonState();
createMouseButtonEvent(button, state, hit).sendToServer();
final boolean draggingStarted = updateButtonCounter(state);
if (draggingStarted) resetDraggingLimiter(x, y);
}
if (wheel != 0) createMouseWheelEvent(wheel, hit).sendToServer();
}
{
final float dx = (x - lastDragX);
final float dy = (y - lastDragY);
if (canSendDragEvent(dx, dy)) {
createDragEvent(dx, dy).sendToServer();
resetDraggingLimiter(x, y);
}
}
}
private boolean updateButtonCounter(boolean isPressed) {
if (isPressed) {
return ++this.mouseButtonsDown == 1;
} else {
this.mouseButtonsDown = Math.max(this.mouseButtonsDown - 1, 0); // first event may be mouse_up, from keyboard click
}
return false;
}
private void resetDraggingLimiter(float x, float y) {
this.lastDragX = x;
this.lastDragY = y;
this.dragInterval = dragPeriod;
}
private boolean canSendDragEvent(float dx, float dy) {
if (mouseButtonsDown <= 0) return false;
if (dragInterval >= 0) return false;
final float d = dx * dx + dy * dy;
return d >= dragThresholdSquared;
}
@Override
public void updateScreen() {
super.updateScreen();
--dragInterval;
}
private NetworkEvent createDragEvent(float dx, float dy) {
return new GlassesMouseDragEvent(guid, dx, dy);
}
private NetworkEvent createMouseButtonEvent(int button, boolean state, DrawableHitInfo hit) {
return hit != null? new GlassesComponentMouseButtonEvent(guid, hit.id, hit.surfaceType, hit.dx, hit.dy, button, state) : new GlassesMouseButtonEvent(guid, button, state);
}
private NetworkEvent createMouseWheelEvent(int wheel, DrawableHitInfo hit) {
return hit != null? new GlassesComponentMouseWheelEvent(guid, hit.id, hit.surfaceType, hit.dx, hit.dy, wheel) : new GlassesMouseWheelEvent(guid, wheel);
}
@Override
public void handleKeyboardInput() {
final int key = Keyboard.getEventKey();
if (key == Keyboard.KEY_ESCAPE) {
this.mc.displayGuiScreen(null);
this.mc.setIngameFocus();
} else {
final boolean state = Keyboard.getEventKeyState();
if (state) {
final char ch = sanitizeKeyChar(Keyboard.getEventCharacter());
final boolean isRepeat = Keyboard.isRepeatEvent();
new GlassesKeyDownEvent(guid, ch, key, isRepeat).sendToServer();
} else {
new GlassesKeyUpEvent(guid, key).sendToServer();
}
}
// looks like twitch controls
super.handleKeyboardInput();
}
private static char sanitizeKeyChar(char ch) {
switch (Character.getType(ch)) {
case Character.PRIVATE_USE: // special case for Macs
case Character.UNASSIGNED:
return 0;
default:
return ch;
}
}
@Override
public void drawScreen(int mouseX, int mouseY, float partialTickTime) {
drawRect(0, 0, width, height, backgroundColor);
}
@Override
public void initGui() {
new GlassesSignalCaptureEvent(guid, true).sendToServer();
Keyboard.enableRepeatEvents(false);
}
@Override
public void onGuiClosed() {
new GlassesSignalCaptureEvent(guid, false).sendToServer();
Keyboard.enableRepeatEvents(false);
GuiUtils.loadGuiElementsState(originalState);
}
@Override
public boolean doesGuiPauseGame() {
return false;
}
public long getGuid() {
return guid;
}
public void setBackground(int backgroundColor) {
this.backgroundColor = backgroundColor;
}
public void setKeyRepeat(boolean repeat) {
Keyboard.enableRepeatEvents(repeat);
}
public void setDragParameters(int threshold, int period) {
this.dragPeriod = period;
this.dragThresholdSquared = threshold * threshold;
}
public void updateGuiElementsState(Map<GuiElements, Boolean> visibility) {
updatedState.putAll(visibility);
}
public void forceGuiElementsState() {
GuiUtils.loadGuiElementsState(updatedState);
}
}
| 30.061321 | 172 | 0.75914 |
cfeaf6118092a9c601e089e9548ac40b5b636aa5 | 765 | package org.hugh.structural.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* 被代理对象必须有接口
*
* @author Hao Du
* @version 1.0
* @date 2021/6/12
*/
public class JdkProxy<T> implements InvocationHandler{
private final T target;
public JdkProxy(T target) {
this.target = target;
}
public Object proxy() {
return Proxy.newProxyInstance(target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 参数增加
// 执行过程增强
// 返回值增加
return method.invoke(target, args);
}
}
| 21.857143 | 87 | 0.63268 |
3b33238b6d9205994e579b01fc3a12096f08a531 | 1,242 | package jp.wasabeef.fresco.processors;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import com.facebook.imagepipeline.request.BasePostprocessor;
import java.util.ArrayList;
import java.util.List;
public class CombinePostProcessors extends BasePostprocessor {
private List<BasePostprocessor> mProcessors;
private CombinePostProcessors(List<BasePostprocessor> processors) {
super();
mProcessors = processors;
}
@Override
public void process(Bitmap dest, Bitmap src) {
Canvas canvas = new Canvas(dest);
Paint paint = new Paint();
canvas.drawBitmap(src, 0, 0, paint);
for(BasePostprocessor processor : mProcessors) {
processor.process(dest, dest);
}
}
public static class Builder {
private List<BasePostprocessor> processors;
public Builder() {
processors = new ArrayList<BasePostprocessor>();
}
public Builder add(BasePostprocessor processor) {
processors.add(processor);
return this;
}
public CombinePostProcessors build() {
return new CombinePostProcessors(processors);
}
}
}
| 24.84 | 71 | 0.664251 |
e5e97b512a28f8a39e097adf77a315b0cdbc613b | 20,616 | package cn.k12soft.servo.module.charge.service;
import cn.k12soft.servo.domain.*;
import cn.k12soft.servo.domain.enumeration.StudentAccountOpType;
import cn.k12soft.servo.module.account.domain.StudentAccount;
import cn.k12soft.servo.module.account.service.StudentAccountChangeRecordService;
import cn.k12soft.servo.module.account.service.StudentAccountService;
import cn.k12soft.servo.module.charge.domain.ChargePlan;
import cn.k12soft.servo.module.charge.domain.StudentCharge;
import cn.k12soft.servo.module.charge.domain.VacationSummary;
import cn.k12soft.servo.module.charge.repository.StudentChargePlanRepository;
import cn.k12soft.servo.module.expense.domain.ExpenseEntry;
import cn.k12soft.servo.module.expense.domain.ExpensePeriodType;
import cn.k12soft.servo.module.expense.domain.PaybackResult;
import cn.k12soft.servo.module.expense.service.PaybackService;
import cn.k12soft.servo.module.revenue.domain.Income;
import cn.k12soft.servo.module.revenue.domain.IncomeDetail;
import cn.k12soft.servo.module.revenue.domain.IncomeSrc;
import cn.k12soft.servo.module.revenue.service.IncomeDetailService;
import cn.k12soft.servo.module.revenue.service.IncomeService;
import cn.k12soft.servo.module.studentChargeRecord.service.StudentChargeRecordService;
import cn.k12soft.servo.module.wxLogin.service.WxService;
import cn.k12soft.servo.repository.SchoolRepository;
import cn.k12soft.servo.service.AbstractEntityService;
import cn.k12soft.servo.service.InterestKlassService;
import cn.k12soft.servo.service.KlassService;
import cn.k12soft.servo.service.StudentService;
import cn.k12soft.servo.util.Times;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.time.temporal.TemporalAdjusters;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import static cn.k12soft.servo.domain.enumeration.StudentChargeStatus.END;
import static cn.k12soft.servo.domain.enumeration.StudentChargeStatus.EXCUTE;
@Service
@Transactional
public class StudentChargePlanService extends AbstractEntityService<StudentCharge, Integer> {
private static final Logger logger = LoggerFactory.getLogger(StudentChargePlanService.class);
private final StudentChargeRecordService studentChargeRecordService;
private final WxService wxService;
private final SchoolRepository schoolRepository;
@Autowired
public StudentChargePlanService(StudentChargePlanRepository entityRepository, StudentChargeRecordService studentChargeRecordService, WxService wxService, SchoolRepository schoolRepository) {
super(entityRepository);
this.studentChargeRecordService = studentChargeRecordService;
this.wxService = wxService;
this.schoolRepository = schoolRepository;
}
@Override
protected StudentChargePlanRepository getEntityRepository() {
return (StudentChargePlanRepository) super.getEntityRepository();
}
public void save(List<StudentCharge> list) {
getEntityRepository().save(list);
}
public List<StudentCharge> findByStudentId(int studentId) {
return getEntityRepository().findByStudentId(studentId);
}
public List<StudentCharge> findByCreateAtBetween(Instant startInstant, Instant endInstant) {
return getEntityRepository().findByCreateAtBetween(startInstant, endInstant);
}
public List<StudentCharge> findPayList(int studentId, int klassId, long monthStartTime, long monthEndTime) {
if (studentId > 0) {
return getEntityRepository()
.findAllByStudentIdAndPaymentAtBetween(studentId, Instant.ofEpochMilli(monthStartTime), Instant.ofEpochMilli(monthEndTime));
} else {
return getEntityRepository()
.findAllByKlassIdAndPaymentAtBetween(klassId, Instant.ofEpochMilli(monthStartTime), Instant.ofEpochMilli(monthEndTime));
}
}
public Page<StudentCharge> findNotPayList(int schoolId, int studentId, int klassId, long monthStartTime, long monthEndTime,
Pageable pageable) {
if (studentId == 0 && klassId == 0) {
School school = new School(schoolId);
return getEntityRepository().findBySchoolIdAndPaymentAtIsNullAndCreateAtAfter(schoolId, Instant.ofEpochMilli(monthEndTime), pageable);
} else {
if (studentId > 0) {
return getEntityRepository()
.findAllByStudentIdAndPaymentAtIsNullAndCreateAtAfter(studentId, Instant.ofEpochMilli(monthStartTime), pageable);
} else {
return getEntityRepository()
.findAllByKlassIdAndPaymentAtIsNullAndCreateAtAfter(klassId, Instant.ofEpochMilli(monthStartTime), pageable);
}
}
}
public Page<StudentCharge> findArrearsList(Integer schoolId, int studentId, int klassId, long monthStartTime, long monthEndTime,
Pageable pageable) {
long zeroHourTime = Times.getZeroTimeOfToday();
if (studentId == 0 && klassId == 0) {
return getEntityRepository()
.findAllBySchoolIdAndPaymentAtIsNullAndEndAtBeforeAndCreateAtAfter(schoolId, Instant.ofEpochMilli(zeroHourTime), pageable);
} else {
if (studentId > 0) {
return getEntityRepository()
.findAllByStudentIdAndPaymentAtIsNullAndEndAtBeforeAndCreateAtAfter(studentId, Instant.ofEpochMilli(zeroHourTime),
Instant.ofEpochMilli(monthStartTime), pageable);
} else {
return getEntityRepository()
.findAllByKlassIdAndPaymentAtIsNullAndEndAtBeforeAndCreateAtAfter(klassId, Instant.ofEpochMilli(zeroHourTime),
Instant.ofEpochMilli(monthStartTime), pageable);
}
}
}
public Page<StudentCharge> findArrearsListByRemainMoney(Integer schoolId, int studentId, int klassId, long monthStartTime, long monthEndTime,
Pageable pageable){
// long zeroHourTime = Times.getZeroTimeOfToday();
if (studentId == 0 && klassId == 0) {
return getEntityRepository().findAllBySchoolIdAndRemainMoneyLessThan(schoolId, 0f, pageable);
// .findAllBySchoolIdAndPaymentAtIsNullAndEndAtBeforeAndCreateAtAfter(schoolId, Instant.ofEpochMilli(zeroHourTime), pageable);
} else {
if (studentId > 0) {
return getEntityRepository().findAllByStudentIdAndRemainMoneyLessThan(studentId, 0f, pageable);
// .findAllByStudentIdAndPaymentAtIsNullAndEndAtBeforeAndCreateAtAfter(studentId, Instant.ofEpochMilli(zeroHourTime),
// Instant.ofEpochMilli(monthStartTime), pageable);
} else {
return getEntityRepository().findAllByKlassIdAndRemainMoneyLessThan(klassId, 0f, pageable);
// .findAllByKlassIdAndPaymentAtIsNullAndEndAtBeforeAndCreateAtAfter(klassId, Instant.ofEpochMilli(zeroHourTime),
// Instant.ofEpochMilli(monthStartTime), pageable);
}
}
}
public List<StudentCharge> findRemainMoneyList(int studentId, int klassId, long monthStartTime, long monthEndTime) {
if (studentId > 0) {
List<StudentCharge> studentChargesList = getEntityRepository()
.findByStudentIdAndCreateAtBetween(studentId, Instant.ofEpochMilli(monthStartTime), Instant.ofEpochMilli(monthEndTime));
return studentChargesList;
} else {
List<StudentCharge> studentChargeList = getEntityRepository()
.findByKlassIdAndCreateAtBetween(klassId, Instant.ofEpochMilli(monthStartTime), Instant.ofEpochMilli(monthEndTime));
return studentChargeList;
}
}
public void updateByChargePlan(ChargePlan chargePlan) {
getEntityRepository().updateByChargePlan(chargePlan.getExpenseEntry(), chargePlan.getPeriodDiscount(), chargePlan.getIdentDiscount(),
chargePlan.getEndAt(), chargePlan.getMoney());
}
public void deleteByChargePlan(Integer changePlanId) {
getEntityRepository().deleteByChargePlan(changePlanId);
}
public StudentCharge getByStudentIdAndExpenseId(int studentId, ExpenseEntry expenseEntry) {
return getEntityRepository().findByStudentIdAndExpenseEntry(studentId, expenseEntry);
}
public List<StudentCharge> findAllBySchoolAndExpenseEntry(Integer schoolId, ExpenseEntry expenseEntry) {
return getEntityRepository().findAllBySchoolIdAndExpenseEntry(schoolId, expenseEntry.getId());
}
public void deleteByExpenseEntry(ExpenseEntry entry) {
getEntityRepository().deleteByExpenseEntry(entry);
}
public void deductExpenses(StudentService studentService, IncomeService incomeService, KlassService klassService, InterestKlassService interestKlassService, PaybackService paybackService,
StudentAccountService studentAccountService, IncomeDetailService incomeDetailService, StudentAccountChangeRecordService studentAccountChangeRecordService) {
long currentTime = System.currentTimeMillis();
List<School> schoolList = this.schoolRepository.findAll();
for (School school : schoolList) {
Integer schoolId = school.getId();
LocalDate lastMonthDate = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth()).minusDays(2);
LocalDate firstDayOfMonth = lastMonthDate.with(TemporalAdjusters.firstDayOfMonth());
LocalDate lastDayOfMonth = lastMonthDate.with(TemporalAdjusters.lastDayOfMonth()).plusDays(1);
logger.info("[deductExpenses] begin ...");
// List<StudentCharge> list = this.getAll();
// 需要查询周期为非一次性、没有结束周期的、教师经过确认的
List<StudentCharge> list = this.getEntityRepository().findAllByStatusAndCreateAt(schoolId, firstDayOfMonth, lastDayOfMonth);
Map<String, Income> klassIncomeMap = new HashMap<>(); // 班级收入
Map<Integer, PaybackResult> paybackResultMap = new HashMap<>();
Map<Integer, VacationSummary> vacationSummaryMap = new HashMap<>();
int yyyyMM = Times.time2yyyyMM(System.currentTimeMillis());
for (StudentCharge studentCharge : list) {
ExpensePeriodType periodType = studentCharge.getExpensePeriodType();
// 年,半年,季度,月 这4中周期类型,才需要按月扣钱
if (!studentCharge.isPeriodDeduct()) {
continue;
}
float monthlyMoney = 0f;
if (periodType == ExpensePeriodType.YEAR) {
monthlyMoney = studentCharge.calcPayMoney() / 12;
} else if (periodType == ExpensePeriodType.HALF_YEAR) {
monthlyMoney = studentCharge.calcPayMoney() / 6;
} else if (periodType == ExpensePeriodType.QUARTER) {
monthlyMoney = studentCharge.calcPayMoney() / 3;
} else if (periodType == ExpensePeriodType.MONTH) {
monthlyMoney = studentCharge.calcPayMoney();
}
float inComeMoney = monthlyMoney;
// 从账户表里扣除费用,如果不够,记录到studentCharge的remainMoney, 表示欠费, 欠费的,缴费时补扣
boolean isInCome = true; // true: 算入园所收入表
StudentAccount studentAccount = studentAccountService.findByStudentId(studentCharge.getStudentId());
if (studentAccount == null || studentAccount.getMoney() <= 0) {
isInCome = false;
} else {
if (studentAccount.getMoney() > inComeMoney) {
studentAccount.setMoney(studentAccount.getMoney() - inComeMoney); // 账户扣款
} else {
studentCharge.setRemainMoney(studentCharge.getRemainMoney() - (inComeMoney - studentAccount.getMoney())); // 账户不够,还要补交(inComeMoney-studentAccount.getMoney())
inComeMoney = studentAccount.getMoney(); // 实际扣除的钱为账户剩余额度
studentAccount.setMoney(0f); // 账户不够,直接设置为0
}
studentAccountChangeRecordService.create(studentAccount.getStudent().getId(), studentAccount, studentCharge.getKlassId(), inComeMoney, null, StudentAccountOpType.MONTHLY_TASK); // 账户变化明细
}
// // 当前周期结束了,生成下一个周期的收费计划
// boolean success = studentCharge.checkAndCreateNext(currentTime);
// if(!success){
// continue;
// }
if (isInCome) {
String key = studentCharge.getSchoolId() + "_" + studentCharge.getKlassType().getId() + "_" + studentCharge.getKlassId() + "_" + studentCharge.getExpenseEntry().getId();
Income income = klassIncomeMap.get(key);
if (income == null) {
income = new Income(studentCharge.getSchoolId());
income.setStudentChargeId(studentCharge.getId());
income.setKlassType(studentCharge.getKlassType().getId());
income.setKlassId(studentCharge.getKlassId());
income.setExpenseId(studentCharge.getExpenseEntry().getId());
income.setNames(studentCharge.getExpenseEntry().getName());
income.setMoney(0f);
Klass klass = klassService.get(studentCharge.getKlassId());// 有可能是兴趣班的ID、、指定学生时分成两个,学生普通班,学生兴趣班
if (klass != null) {
income.setKlassName(klass.getName());
} else {
InterestKlass interestKlass = interestKlassService.get(studentCharge.getKlassId());
income.setKlassName(interestKlass.getName());
}
klassIncomeMap.put(key, income);
}
income.setMoney(income.getMoney() + inComeMoney);
}
VacationSummary vacationSummary = vacationSummaryMap.get(studentCharge.getStudentId());
if (vacationSummary == null) {
vacationSummary = paybackService.getVacationSummary(studentCharge.getStudentId(), lastMonthDate, lastMonthDate);
vacationSummaryMap.put(studentCharge.getStudentId(), vacationSummary);
}
PaybackResult paybackResult = new PaybackResult();
paybackService.calc(studentCharge, paybackResult, lastMonthDate, vacationSummary.getTermArr(), vacationSummary.getYearArr());
paybackResultMap.put(studentCharge.getStudentId(), paybackResult);
studentCharge.setPaybackMoney(paybackResult.getMoney());
//检查是否要生成下一个周期的收费计划
if (isInCome) {
boolean isNext = studentCharge.checkAndCreateNext(currentTime);
}
studentCharge.setStatus(EXCUTE);
studentCharge.settCheck(false);
this.save(studentCharge);
// 统计班级收入
CompletableFuture completableFuture = CompletableFuture.runAsync(() -> {
this.studentChargeRecordService.countStudentChargeKlass(studentCharge);
});
// 微信服务推送
// CompletableFuture completableFuture = CompletableFuture.supplyAsync(()->{
// String msg = "您的幼儿有新的缴费项目,请及时查收!";
// wxService.sendStudentPlan(studentCharge, msg);
// return null;
// });
IncomeDetail incomeDetail = new IncomeDetail();
if (isInCome) {
incomeDetail.setMoney(inComeMoney); // 扣的费用
}
incomeDetail.setStudentId(studentCharge.getStudentId());
incomeDetail.setStudentName(studentCharge.getStudentName());
incomeDetail.setExpenseId(studentCharge.getExpenseEntry().getId());
incomeDetail.setTheYearMonth(yyyyMM);
incomeDetail.setRefundMoney(paybackResult.getMoney());
incomeDetail.setCreateAt(Instant.now());
incomeDetailService.save(incomeDetail);
logger.info(
"[deductExpenses] dec money studentId=" + studentCharge.getStudentId() + " money=" + studentCharge.getMoney() + " decMoney="
+ inComeMoney + " remainMoney=" + studentCharge.getRemainMoney());
}
for (Income income : klassIncomeMap.values()) {
income.setCreateAt(Instant.now());
income.setTheYearMonth(yyyyMM);
income.setSrc(IncomeSrc.MONTHLY_DEDUCT.getId());
incomeService.save(income);
}
// 上个月请假天数
LocalDate lastMonthBeginLocalDate = lastMonthDate.with(TemporalAdjusters.firstDayOfMonth());
LocalDate lastMonthEndLocalDate = lastMonthDate.with(TemporalAdjusters.lastDayOfMonth());
Collection<Vacation> vacationList = paybackService.getAllByCreateAt(lastMonthBeginLocalDate, lastMonthEndLocalDate);
Map<Integer, StudentAccount> tmpStudentAccountMap = new HashMap<>();
for (Vacation vacation : vacationList) {
StudentAccount studentAccount = tmpStudentAccountMap.get(vacation.getStudentId());
if (studentAccount == null) {
studentAccount = studentAccountService.findByStudentId(vacation.getStudentId());
if (studentAccount != null) {
studentAccount.setLeaveDays(0);// 清除上上个月的
tmpStudentAccountMap.put(vacation.getStudentId(), studentAccount);
}
}
if (studentAccount != null) {
// 累加这上个月的请假天数
studentAccount.setLeaveDays(studentAccount.getLeaveDays() + Times.getIntervalDays(vacation.getToDate(), vacation.getFromDate()));
}
}
for (StudentAccount studentAccount : tmpStudentAccountMap.values()) {
PaybackResult paybackResult = paybackResultMap.get(studentAccount.getStudent().getId());
if (paybackResult != null) {
studentAccount.setPaybackMoney(paybackResult.getMoney());
}
studentAccountService.save(studentAccount);
}
}
}
public List<StudentCharge> findByKlassIdAndCreateAtBetween(Integer klassId, Instant startInstant, Instant endInstant) {
return getEntityRepository().findByKlassIdAndCreateAtBetween(klassId, startInstant, endInstant);
}
public List<StudentCharge> findByKlassIdAndExpenseEntryAndCreateAtBetween(int klassId, ExpenseEntry expenseEntry, Instant startInstant, Instant endInstant) {
return getEntityRepository().findByKlassIdAndExpenseEntryAndCreateAtBetween(klassId, expenseEntry, startInstant, endInstant);
}
public List<StudentCharge> findUnCheck(Actor actor, Integer klassId) {
Integer schoolId = actor.getSchoolId();
LocalDate localDate = LocalDate.now();
Instant first = localDate.atStartOfDay().with(TemporalAdjusters.firstDayOfMonth()).toInstant(ZoneOffset.UTC);
Instant second = localDate.plusMonths(1).atStartOfDay().with(TemporalAdjusters.firstDayOfMonth()).toInstant(ZoneOffset.UTC);
return this.getEntityRepository().findAllBySchoolIdAndKlassIdAndStatusAndCreateAtBetween(schoolId, klassId, EXCUTE, first, second);
}
public void tCheck(Actor actor, Integer id) {
StudentCharge studentCharge = this.getEntityRepository().findOne(id);
studentCharge.settCheck(true);
this.getEntityRepository().save(studentCharge);
}
public void endStuCharge(Actor actor, Integer id) {
StudentCharge studentCharge = this.getEntityRepository().findOne(id);
studentCharge.setStatus(END);
this.getEntityRepository().save(studentCharge);
}
}
| 54.829787 | 206 | 0.664872 |
53ee74a4689bd7c2c81b344269b536c6b0f2ff7e | 4,289 | package DnD.gui;
import java.awt.*;
import java.awt.event.*;
import java.util.LinkedList;
import DnD.model.ClassInfo;
import DnD.model.MUBase;
import DnD.model.MagicUser;
/** This is the GUI panel for basic magic user information (spellbooks)
* It creates, displays and coordinates 2 other panels:
* PanelSpellList: the list of spells
* PanelSpellDetail: detail of a single spell from the list
*/
public class PanelClassMUBase extends PanelClassInfo implements ActionListener
{
// This stops the Java compiler from complaining
private static final long serialVersionUID = 1;
// GUI stuff
PanelSpellList itsSpellList;
PanelSpellDetail itsSpellDetail;
// Other stuff
public PanelClassMUBase(PanelRootData rootData) throws NoSuchFieldException, IllegalAccessException
{
super(rootData);
}
protected void createGui(MainGui.GuiCfg guiCfg) throws NoSuchFieldException, IllegalAccessException
{
// summary list of spells
guiCfg.gc.gridwidth = 2;
guiCfg.gc.fill = GridBagConstraints.BOTH;
guiCfg.gc.weighty = 1.0;
guiCfg.gc.weightx = 1.0;
itsSpellList= new PanelSpellList(this, "Spells", ((MUBase)itsData).itsSpellBook.itsContents);
MainGui.addGui(guiCfg, itsSpellList);
// detail form for currently selected spell
itsSpellDetail = new PanelSpellDetail(this);
guiCfg.gc.weightx = 2.0;
guiCfg.gc.gridwidth = GridBagConstraints.REMAINDER;
MainGui.addGui(guiCfg, itsSpellDetail);
// Control buttons
guiCfg.gc.fill = GridBagConstraints.NONE;
guiCfg.gc.anchor = GridBagConstraints.WEST;
guiCfg.gc.weightx = 0.0;
guiCfg.gc.weighty = 0.0;
guiCfg.gc.gridwidth = 1;
MainGui.addGui(guiCfg, itsButApply);
guiCfg.gc.gridwidth = GridBagConstraints.REMAINDER;
MainGui.addGui(guiCfg, itsButRevert);
// set focus traversal order
java.util.List<Component> lst = new LinkedList<Component>();
lst.add(itsSpellList.itsButAdd);
for(FieldMap fm : itsSpellDetail.itsFields)
lst.add(fm.itsTF);
lst.add(itsSpellDetail.itsButApply);
setFocusOrder(lst);
}
// This tells my superclass my specific data model class
public Class<? extends ClassInfo> getDataClass()
{
return MagicUser.class;
}
public void _resetAll() throws Exception
{
MUBase muBase = (MUBase)itsData;
// list box (spells)
itsSpellList.setList(muBase.itsSpellBook.itsContents);
}
public void _applyAll()
{
itsSpellDetail.applyAll();
itsSpellList.applyAll();
}
public void _revertAll()
{
java.util.List<MUBase.Spell> lst;
int idx;
MUBase.Spell sp;
lst = ((MUBase)itsData).itsSpellBook.itsContents;
itsSpellList.setList(lst);
// pick the first spell (if any)
idx = (lst.isEmpty() ? -1 : 0);
itsSpellList.refreshList(idx);
sp = (idx < 0 ? null : lst.get(idx));
itsSpellDetail.setData(sp);
}
public void enableAll(boolean ef)
{
itsSpellList.enableAll(ef);
itsSpellDetail.enableAll(ef);
}
// PanelSpellList calls this when a spell is selected
public void pickSpell(int idx)
{
if(idx == -1)
itsSpellDetail.setData(null);
else
itsSpellDetail.setData(((MUBase)itsData).itsSpellBook.itsContents.get(idx));
}
// PanelSpellList calls this to add a new spell
public void addSpell(int idx)
{
MUBase.Spell sp;
// Create a new spell, add it to the list
sp = new MUBase.Spell();
((MUBase)itsData).itsSpellBook.itsContents.add(idx, sp);
// The following refreshes the list and selects the item
// which causes it to be displayed in the detail pane
itsSpellList.refreshList(idx);
// Display it in the detail pane
itsSpellDetail.setData(sp);
}
// PanelSpellList calls this to delete a spell
public void delSpell(int idx)
{
java.util.List<MUBase.Spell> lst = ((MUBase)itsData).itsSpellBook.itsContents;
MUBase.Spell sp;
lst.remove(idx);
if(idx >= lst.size())
idx--;
itsSpellList.refreshList(idx);
sp = (idx < 0 ? null : lst.get(idx));
itsSpellDetail.setData(sp);
}
// PanelSpellDetail calls this when a spell is applied
public void applySpell(MUBase.Spell sp)
{
itsSpellList.refreshList();
}
// Returns the grid bag height of this panel
public int gbHeight()
{
return super.gbHeight() + 8;
}
}
| 26.80625 | 101 | 0.703194 |
b684c704688c2e309ba7ae54bb9c3670bb9fcfe2 | 1,968 | package thor12022.hardcorewither.entity;
import thor12022.hardcorewither.ModInformation;
import net.minecraft.entity.EnumCreatureAttribute;
import net.minecraft.entity.IEntityLivingData;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.ai.EntityAIAttackOnCollide;
import net.minecraft.entity.boss.EntityWither;
import net.minecraft.entity.monster.EntitySkeleton;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.util.DamageSource;
import net.minecraft.world.World;
public class EntitySkeletonMinion extends EntitySkeleton
{
public static final String UNLOCALIZED_NAME = "SkeletonMinion";
public static final String LOCALIZED_NAME = ModInformation.ID + "." + UNLOCALIZED_NAME;
public EntitySkeletonMinion(World p_i1731_1_)
{
super(p_i1731_1_);
setSkeletonType(1);
}
@Override
public EnumCreatureAttribute getCreatureAttribute()
{
return EnumCreatureAttribute.UNDEAD;
}
@Override
public boolean attackEntityFrom(DamageSource p_70097_1_, float p_70097_2_)
{
if (p_70097_1_.getEntity() != null && p_70097_1_.getEntity().getClass() == EntityWither.class)
{
return false;
}
return super.attackEntityFrom(p_70097_1_, p_70097_2_);
}
@Override
protected void dropFewItems(boolean p_70628_1_, int p_70628_2_)
{}
@Override
public IEntityLivingData onSpawnWithEgg(IEntityLivingData livingData)
{
// Apply the Wither Skeleton's standard attributes
this.tasks.addTask(4, new EntityAIAttackOnCollide(this, EntityPlayer.class, 1.2D, false));
this.setCurrentItemOrArmor(0, new ItemStack(Items.stone_sword));
this.getEntityAttribute(SharedMonsterAttributes.attackDamage).setBaseValue(4.0D);
return livingData;
}
@Override
protected boolean isValidLightLevel()
{
return true;
}
}
| 31.238095 | 100 | 0.754065 |
23e6011985e7f92654ff063844f7127b7794e493 | 997 | package com.ilargia.games.systems;
import com.badlogic.gdx.utils.Array;
import com.ilargia.games.components.View;
import com.ilargia.games.core.CoreMatcher;
import com.ilargia.games.core.Entity;
import com.ilargia.games.core.Pool;
import com.ilargia.games.core.Pools;
import com.ilargia.games.entitas.Group;
import com.ilargia.games.entitas.interfaces.*;
import com.ilargia.games.entitas.matcher.TriggerOnEvent;
public class ScoreSystem implements ISetPools<Pools>, IReactiveSystem<Entity>, IInitializeSystem {
private Pools _pools;
@Override
public void setPools(Pools pools) {
_pools = pools;
}
@Override
public TriggerOnEvent getTrigger() {
return CoreMatcher.GameBoardElement().OnEntityRemoved();
}
@Override
public void initialize() {
_pools.score.setScore(0);
}
@Override
public void execute(Array<Entity> entities) {
_pools.score.replaceScore(_pools.score.getScore().value + entities.size);
}
}
| 24.317073 | 98 | 0.728185 |
4bf01c91885d3a8aea814b4f4fa7531aebd202db | 6,885 | package mekanism.common.tile;
import ic2.api.tile.IWrenchable;
import io.netty.buffer.ByteBuf;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import mekanism.api.Coord4D;
import mekanism.api.MekanismConfig.general;
import mekanism.api.Range4D;
import mekanism.common.Mekanism;
import mekanism.common.base.IChunkLoadHandler;
import mekanism.common.base.ITileComponent;
import mekanism.common.base.ITileNetwork;
import mekanism.common.block.BlockMachine.MachineType;
import mekanism.common.frequency.Frequency;
import mekanism.common.frequency.FrequencyManager;
import mekanism.common.frequency.IFrequencyHandler;
import mekanism.common.network.PacketDataRequest.DataRequestMessage;
import mekanism.common.network.PacketTileEntity.TileEntityMessage;
import mekanism.common.security.ISecurityTile;
import mekanism.common.util.MekanismUtils;
import net.minecraft.block.Block;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import cpw.mods.fml.common.Optional.Interface;
import cpw.mods.fml.common.Optional.Method;
@Interface(iface = "ic2.api.tile.IWrenchable", modid = "IC2")
public abstract class TileEntityBasicBlock extends TileEntity implements IWrenchable, ITileNetwork, IChunkLoadHandler, IFrequencyHandler
{
/** The direction this block is facing. */
public int facing;
public int clientFacing;
/** The players currently using this block. */
public HashSet<EntityPlayer> playersUsing = new HashSet<EntityPlayer>();
/** A timer used to send packets to clients. */
public int ticker;
public boolean redstone = false;
public boolean redstoneLastTick = false;
public boolean doAutoSync = true;
public List<ITileComponent> components = new ArrayList<ITileComponent>();
@Override
public void updateEntity()
{
if(!worldObj.isRemote && general.destroyDisabledBlocks)
{
MachineType type = MachineType.get(getBlockType(), getBlockMetadata());
if(type != null && !type.isEnabled())
{
Mekanism.logger.info("[Mekanism] Destroying machine of type '" + type.name + "' at coords " + Coord4D.get(this) + " as according to config.");
worldObj.setBlockToAir(xCoord, yCoord, zCoord);
return;
}
}
for(ITileComponent component : components)
{
component.tick();
}
onUpdate();
if(!worldObj.isRemote)
{
if(doAutoSync && playersUsing.size() > 0)
{
for(EntityPlayer player : playersUsing)
{
Mekanism.packetHandler.sendTo(new TileEntityMessage(Coord4D.get(this), getNetworkedData(new ArrayList())), (EntityPlayerMP)player);
}
}
}
ticker++;
redstoneLastTick = redstone;
}
@Override
public void onChunkLoad()
{
markDirty();
}
public void open(EntityPlayer player)
{
playersUsing.add(player);
}
public void close(EntityPlayer player)
{
playersUsing.remove(player);
}
@Override
public void handlePacketData(ByteBuf dataStream)
{
if(worldObj.isRemote)
{
facing = dataStream.readInt();
redstone = dataStream.readBoolean();
if(clientFacing != facing)
{
MekanismUtils.updateBlock(worldObj, xCoord, yCoord, zCoord);
worldObj.notifyBlocksOfNeighborChange(xCoord, yCoord, zCoord, worldObj.getBlock(xCoord, yCoord, zCoord));
clientFacing = facing;
}
for(ITileComponent component : components)
{
component.read(dataStream);
}
}
}
@Override
public ArrayList getNetworkedData(ArrayList data)
{
data.add(facing);
data.add(redstone);
for(ITileComponent component : components)
{
component.write(data);
}
return data;
}
@Override
public void invalidate()
{
super.invalidate();
for(ITileComponent component : components)
{
component.invalidate();
}
}
@Override
public void validate()
{
super.validate();
if(worldObj.isRemote)
{
Mekanism.packetHandler.sendToServer(new DataRequestMessage(Coord4D.get(this)));
}
}
/**
* Update call for machines. Use instead of updateEntity -- it's called every tick.
*/
public abstract void onUpdate();
@Override
public void readFromNBT(NBTTagCompound nbtTags)
{
super.readFromNBT(nbtTags);
facing = nbtTags.getInteger("facing");
redstone = nbtTags.getBoolean("redstone");
for(ITileComponent component : components)
{
component.read(nbtTags);
}
}
@Override
public void writeToNBT(NBTTagCompound nbtTags)
{
super.writeToNBT(nbtTags);
nbtTags.setInteger("facing", facing);
nbtTags.setBoolean("redstone", redstone);
for(ITileComponent component : components)
{
component.write(nbtTags);
}
}
@Override
@Method(modid = "IC2")
public boolean wrenchCanSetFacing(EntityPlayer entityPlayer, int side)
{
return true;
}
@Override
@Method(modid = "IC2")
public short getFacing()
{
return (short)facing;
}
@Override
public void setFacing(short direction)
{
if(canSetFacing(direction))
{
facing = direction;
}
if(!(facing == clientFacing || worldObj.isRemote))
{
Mekanism.packetHandler.sendToReceivers(new TileEntityMessage(Coord4D.get(this), getNetworkedData(new ArrayList())), new Range4D(Coord4D.get(this)));
markDirty();
clientFacing = facing;
}
}
/**
* Whether or not this block's orientation can be changed to a specific direction. True by default.
* @param facing - facing to check
* @return if the block's orientation can be changed
*/
public boolean canSetFacing(int facing)
{
return true;
}
@Override
@Method(modid = "IC2")
public boolean wrenchCanRemove(EntityPlayer entityPlayer)
{
return true;
}
@Override
@Method(modid = "IC2")
public float getWrenchDropRate()
{
return 1.0F;
}
@Override
@Method(modid = "IC2")
public ItemStack getWrenchDrop(EntityPlayer entityPlayer)
{
return getBlockType().getPickBlock(null, worldObj, xCoord, yCoord, zCoord, entityPlayer);
}
public boolean isPowered()
{
return redstone;
}
public boolean wasPowered()
{
return redstoneLastTick;
}
public void onPowerChange() {}
public void onNeighborChange(Block block)
{
if(!worldObj.isRemote)
{
updatePower();
}
}
private void updatePower()
{
boolean power = worldObj.isBlockIndirectlyGettingPowered(xCoord, yCoord, zCoord);
if(redstone != power)
{
redstone = power;
Mekanism.packetHandler.sendToReceivers(new TileEntityMessage(Coord4D.get(this), getNetworkedData(new ArrayList())), new Range4D(Coord4D.get(this)));
onPowerChange();
}
}
/**
* Called when block is placed in world
*/
public void onAdded()
{
updatePower();
}
@Override
public Frequency getFrequency(FrequencyManager manager)
{
if(manager == Mekanism.securityFrequencies && this instanceof ISecurityTile)
{
return ((ISecurityTile)this).getSecurity().getFrequency();
}
return null;
}
}
| 22.067308 | 151 | 0.729412 |
46cfd9d3c4bfeecad70b9de9195a27183dddbe00 | 4,392 | package com.djontleman.album;
import org.junit.jupiter.params.provider.EnumSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
@Repository("postgresAlbum")
public class AlbumDataAccessService implements AlbumDAO{
private JdbcTemplate jdbcTemplate;
private AlbumRowMapper albumRowMapper;
@Autowired
public AlbumDataAccessService(JdbcTemplate jdbcTemplate, AlbumRowMapper albumRowMapper) {
this.jdbcTemplate = jdbcTemplate;
this.albumRowMapper = albumRowMapper;
}
// || ====================== Create/POST ====================== ||
@Override
public int postAlbum(Album album) {
String sql = """
INSERT
INTO albums (album_name, album_type, release_date)
VALUES (?, ?::album_type, ?, ?);
""";
return jdbcTemplate.update(
sql, album.getName(), album.getType().getStringRep(), album.getReleaseDate()
);
}
// || ====================== Read/GET ====================== ||
@Override
public List<Album> getAllAlbums() {
String sql = """
SELECT *
FROM albums;
""";
List<Album> albums = jdbcTemplate.query(sql, albumRowMapper);
return albums;
}
@Override
// @EnumSource(value = AlbumType.class)
public List<Album> getAllAlbumsWhereAlbumType(AlbumType albumType) {
String sql = """
SELECT *
FROM albums
WHERE album_type = ?::album_type;
""";
List<Album> albums = jdbcTemplate.query(sql, albumRowMapper, albumType.getStringRep());
return albums;
}
@Override
public int getCountAllAlbums() {
String sql = """
SELECT COUNT(*)
FROM albums;
""";
int countAlbums = jdbcTemplate.queryForObject(sql, Integer.class);
return countAlbums;
}
@Override
public int getCountAlbumsWhereAlbumType(AlbumType albumType) {
String sql = """
SELECT COUNT(*)
FROM albums
WHERE album_type = ?::album_type;
""";
int countAlbums = jdbcTemplate.queryForObject(sql, Integer.class, albumType.getStringRep());
return countAlbums;
}
@Override
public Optional<Album> getAlbumById(int id) {
String sql = """
SELECT *
FROM albums
WHERE id = ?;
""";
Optional<Album> album = jdbcTemplate.query(sql, albumRowMapper, id)
.stream()
.findFirst();
return album;
}
@Override
public List<Album> getAlbumsBySongId(int id) {
String sql = """
SELECT * FROM albums
INNER JOIN albums_songs ON albums.id = albums_songs.album_id
WHERE albums_songs.song_id = ?;
""";
return jdbcTemplate.query(sql, albumRowMapper, id);
}
@Override
public List<Album> getAlbumsByLabelId(int id) {
String sql = """
SELECT * FROM albums
INNER JOIN albums_labels ON albums.id = albums_labels.album_id
WHERE albums_labels.label_id = ?;
""";
return jdbcTemplate.query(sql, albumRowMapper, id);
}
// || ====================== Update/PUT/PATCH ====================== ||
@Override
public int putAlbum(int id, Album album) {
String sql = """
UPDATE albums
SET album_name = ?, album_type = ?::album_type, release_date = ?
WHERE id = ?;
""";
return jdbcTemplate.update(
sql,
album.getName(), album.getType().getStringRep(), album.getReleaseDate(),
id);
}
// || ====================== Delete/DELETE ====================== ||
@Override
public int deleteAlbum(int id) {
String sql = """
DELETE FROM albums
WHERE id = ?;
""";
return jdbcTemplate.update(sql, id);
}
}
| 30.929577 | 100 | 0.535747 |
1cb31a050d6d0b0e62f6f29b1867e61157b39bf6 | 8,727 | /*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package top.dcenter.ums.security.core.api.oauth.repository.jdbc;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.util.MultiValueMap;
import top.dcenter.ums.security.core.api.oauth.repository.exception.DuplicateConnectionException;
import top.dcenter.ums.security.core.api.oauth.repository.exception.NoSuchConnectionException;
import top.dcenter.ums.security.core.api.oauth.repository.exception.NotConnectedException;
import top.dcenter.ums.security.core.api.oauth.entity.AuthTokenPo;
import top.dcenter.ums.security.core.api.oauth.entity.ConnectionData;
import top.dcenter.ums.security.core.api.oauth.entity.ConnectionKey;
import java.util.List;
import java.util.Set;
/**
* A data access interface for managing a global store of users connections to service providers.
* Provides data access operations.
* @author Keith Donald
* @author YongWu zheng
* @version V2.0 Created by 2020-10-08 20:10
*/
@SuppressWarnings({"unused", "UnusedReturnValue"})
public interface UsersConnectionRepository {
/**
* 根据 providerId 与 providerUserId 获取 ConnectionData list.
* @param providerId 第三方服务商, 如: qq, github
* @param providerUserId 第三方用户 Id
* @return connection data list
*/
List<ConnectionData> findConnectionByProviderIdAndProviderUserId(String providerId, String providerUserId);
/**
* Find the ids of the users who are connected to the specific provider user accounts.
* @param providerId 第三方服务商, 如: qq, github
* @param providerUserIds the set of provider user ids e.g. ("987665", "435796", "584444").
* @return the set of user ids connected to those service provider users, or empty if none.
*/
Set<String> findUserIdsConnectedTo(String providerId, Set<String> providerUserIds);
/**
* 获取 userId 的所有绑定信息.
* Find all connections the current user has across all providers.
* The returned map contains an entry for each provider the user is connected to.
* The key for each entry is the providerId, and the value is the list of {@link ConnectionData}s that exist between the user and that provider.
* For example, if the user is connected once to Facebook and twice to Twitter, the returned map would contain two entries with the following structure:
* <pre>
* {
* "qq" -> Connection("Jack") ,
* "github" -> Connection("Tomas"), Connection("Jessica")
* }
* </pre>
* The returned map is sorted by providerId and entry values are ordered by rank.
* Returns an empty map if the user has no connections.
* @param userId the userId
* @return all connections the current user has across all providers.
*/
MultiValueMap<String, ConnectionData> findAllConnections(String userId);
/**
* 获取 userId 和 providerId 的所以绑定信息.
* Find the connections the current user has to the provider registered by the given id e.g. 'qq'.
* The returned list is ordered by connection rank.
* Returns an empty list if the user has no connections to the provider.
* @param userId 本地账户用户 Id
* @param providerId the provider id e.g. "qq"
* @return the connections the user has to the provider, or an empty list if none
*/
List<ConnectionData> findConnections(String userId, String providerId);
/**
* 获取 userId 和 providerUserIds 的所以绑定信息.
* Find the connections the current user has to the given provider users.
* The providerUsers parameter accepts a map containing an entry for each provider the caller is interested in.
* The key for each entry is the providerId e.g. "qq", and the value is a list of provider user ids to fetch
* connections to e.g. ("987665", "435796", "584444").
* The returned map has the same structure and order, except the provider userId values have been replaced by Connection instances.
* If no connection exists between the current user and a given provider user, a null value is returned for that position.
* @param userId 本地账户用户 Id
* @param providerUserIds 第三方用户 Id
* @return the provider user connection map
*/
MultiValueMap<String, ConnectionData> findConnectionsToUsers(String userId, MultiValueMap<String, String> providerUserIds);
/**
* 获取 userId 和 providerId 的所以 rank 值最小的绑定信息.
* Get the "primary" connection the current user.
* If the user has multiple connections to the provider, this method returns the one with the top rank (or priority).
* Useful for direct use by application code to obtain a parameterized Connection instance.
* @param userId 本地账户用户 Id
* @param providerId the provider id e.g. "qq"
* @return the primary connection
* @throws NotConnectedException if the user is not connected to the provider of the API
*/
ConnectionData getPrimaryConnection(String userId, String providerId) throws NotConnectedException;
/**
* 绑定.
* Add a new connection to this repository for the current user.
* After the connection is added, it can be retrieved later using one of the finders defined in this interface.
* @param connection the new connection to add to this repository
* @throws DuplicateConnectionException if the user already has this connection
* @return ConnectionData 这里返回值的目的主要为了更新 spring cache
*/
ConnectionData addConnection(ConnectionData connection);
/**
* Update a Connection already added to this repository.
* Merges the field values of the given connection object with the values stored in the repository.
* @param connection the existing connection to update in this repository
* @return ConnectionData 这里返回值的目的主要为了更新 spring cache
*/
ConnectionData updateConnection(ConnectionData connection);
/**
* 解除绑定.
* Remove all Connections between the current user and the provider from this repository.
* Does nothing if no provider connections exist.
* @param userId 本地账户用户 Id
* @param providerId the provider id e.g. "qq"
*/
void removeConnections(String userId, String providerId);
/**
* 解除绑定.
* Remove a single Connection for the current user from this repository.
* Does nothing if no such connection exists.
* @param userId 本地账户用户 Id
* @param connectionKey the connection key
*/
void removeConnection(String userId, ConnectionKey connectionKey);
/**
* 根据 userId 与 providerId 获取 ConnectionData. 获取 userId 和 providerId 的所以 rank 值最小的绑定信息.
* @param userId 本地账户用户 Id
* @param providerId the provider id e.g. "qq"
* @return ConnectionData
*/
ConnectionData findPrimaryConnection(String userId, String providerId);
/**
* 根据 userId 和 connectionKey 获取 ConnectionData. 获取 userId 和 providerId, provideUserId 的绑定信息.
* @param userId 本地账户用户 Id
* @param connectionKey connectionKey
* @return ConnectionData
* @throws NoSuchConnectionException no such connection exception
*/
ConnectionData getConnection(String userId, ConnectionKey connectionKey) throws NoSuchConnectionException;
/**
* 根据 userId 获取 ConnectionData list. 获取 userId 的所有绑定信息.
* @param userId 本地账户用户 Id
* @return connection data list
*/
List<ConnectionData> findAllListConnections(String userId);
/**
* 根据 userId 通过指定 providerUsersCriteriaSql 与 parameters 的 sql 获取 ConnectionData list
* @param parameters sql 的 where 条件 与 对应参数
* @param providerUsersCriteriaSql providerUsersCriteriaSql
* @param userId 本地账户用户 Id
* @return connection data list
*/
List<ConnectionData> findConnectionsToUsers(MapSqlParameterSource parameters, String providerUsersCriteriaSql, String userId);
/**
* 根据 {@code AuthTokenPo#getId()} 更新 {@link ConnectionData}.<br>
* 注意: 使用这个接口更新会使 spring cache 缓存更新延迟, 出现缓存强一致性问题, 这接口目的用于 refreshToken 的定时任务, 更新
* 时间一般在凌晨 1-5 点.
* @param token {@link AuthTokenPo}
* @return 返回更新过的 {@link ConnectionData}, 还可以顺便更新 spring cache
*/
ConnectionData updateConnectionByTokenId(AuthTokenPo token);
/**
* 根据 tokenId 查找 {@link ConnectionData}<br>
* 注意: 这里不做 spring cache 缓存处理, 这个接口主要用于 refreshToken 的定时任务, 只调用一次, 缓存无意义
* @param tokenId {@code AuthTokenPo#getId()}
* @return ConnectionData
*/
ConnectionData findConnectionByTokenId(Long tokenId);
}
| 44.075758 | 153 | 0.744586 |
d1b251518578caac04c56c84348c98309bde2d37 | 1,315 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jena.dboe.storage;
import org.apache.jena.sparql.core.Transactional;
/** Component access functions for the parts of an RDF Database */
public interface DatabaseRDF {
/**
* @return the triples/quads storage.
*/
public StorageRDF getData();
/**
* @return the prefixes storage.
*/
public StoragePrefixes getStoragePrefixes();
/**
* @return the {@link Transactional} for this database.
*/
public Transactional getTransactional();
}
| 32.073171 | 75 | 0.719392 |
f638cbf1313d887f37b8724fb08d096e6a93e442 | 3,107 | /**
* Copyright © 2010-2017 Atilika Inc. and contributors (see CONTRIBUTORS.md)
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. A copy of the
* License is distributed with this work in the LICENSE.md file. You may
* also obtain a copy of the License from
*
* 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.atilika.kuromoji.viterbi;
public class ViterbiLattice {
static final String BOS = "BOS";
static final String EOS = "EOS";
private final int dimension;
private final ViterbiNode[][] startIndexArr;
private final ViterbiNode[][] endIndexArr;
private final int[] startSizeArr;
private final int[] endSizeArr;
public ViterbiLattice(int dimension) {
this.dimension = dimension;
startIndexArr = new ViterbiNode[dimension][];
endIndexArr = new ViterbiNode[dimension][];
startSizeArr = new int[dimension];
endSizeArr = new int[dimension];
}
public ViterbiNode[][] getStartIndexArr() {
return startIndexArr;
}
public ViterbiNode[][] getEndIndexArr() {
return endIndexArr;
}
public int[] getStartSizeArr() {
return startSizeArr;
}
public int[] getEndSizeArr() {
return endSizeArr;
}
public void addBos() {
ViterbiNode bosNode = new ViterbiNode(-1, BOS, 0, 0, 0, -1, ViterbiNode.Type.KNOWN);
addNode(bosNode, 0, 1);
}
public void addEos() {
ViterbiNode eosNode = new ViterbiNode(-1, EOS, 0, 0, 0, dimension - 1, ViterbiNode.Type.KNOWN);
addNode(eosNode, dimension - 1, 0);
}
void addNode(ViterbiNode node, int start, int end) {
addNodeToArray(node, start, getStartIndexArr(), getStartSizeArr());
addNodeToArray(node, end, getEndIndexArr(), getEndSizeArr());
}
private void addNodeToArray(final ViterbiNode node, final int index, ViterbiNode[][] arr, int[] sizes) {
int count = sizes[index];
expandIfNeeded(index, arr, count);
arr[index][count] = node;
sizes[index] = count + 1;
}
private void expandIfNeeded(final int index, ViterbiNode[][] arr, final int count) {
if (count == 0) {
arr[index] = new ViterbiNode[10];
}
if (arr[index].length <= count) {
arr[index] = extendArray(arr[index]);
}
}
private ViterbiNode[] extendArray(ViterbiNode[] array) {
ViterbiNode[] newArray = new ViterbiNode[array.length * 2];
System.arraycopy(array, 0, newArray, 0, array.length);
return newArray;
}
boolean tokenEndsWhereCurrentTokenStarts(int startIndex) {
return getEndSizeArr()[startIndex + 1] != 0;
}
}
| 31.704082 | 108 | 0.650467 |
5e58020f7f3bd94b9fbe8b02f8972475e1a45ced | 5,215 | /*
* IntPTI: integer error fixing by proper-type inference
* Copyright (c) 2017.
*
* Open-source component:
*
* CPAchecker
* Copyright (C) 2007-2014 Dirk Beyer
*
* Guava: Google Core Libraries for Java
* Copyright (C) 2010-2006 Google
*
*
*/
package org.sosy_lab.cpachecker.util.refinement;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import org.sosy_lab.common.log.LogManager;
import org.sosy_lab.cpachecker.core.CPAcheckerResult.Result;
import org.sosy_lab.cpachecker.core.counterexample.CounterexampleInfo;
import org.sosy_lab.cpachecker.core.interfaces.Statistics;
import org.sosy_lab.cpachecker.core.interfaces.StatisticsProvider;
import org.sosy_lab.cpachecker.core.reachedset.ReachedSet;
import org.sosy_lab.cpachecker.cpa.arg.ARGBasedRefiner;
import org.sosy_lab.cpachecker.cpa.arg.ARGPath;
import org.sosy_lab.cpachecker.cpa.arg.ARGReachedSet;
import org.sosy_lab.cpachecker.exceptions.CPAException;
import org.sosy_lab.cpachecker.exceptions.RefinementFailedException;
import org.sosy_lab.cpachecker.exceptions.RefinementFailedException.Reason;
import org.sosy_lab.cpachecker.util.statistics.StatCounter;
import org.sosy_lab.cpachecker.util.statistics.StatisticsWriter;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.logging.Level;
/**
* This is a {@link ARGBasedRefiner} that delegates each refinement
* to a list of given {@link ARGBasedRefiner}s (in the given order)
* until one succeeds.
*/
public final class DelegatingARGBasedRefiner implements ARGBasedRefiner, StatisticsProvider {
private final List<ARGBasedRefiner> refiners;
private final List<StatCounter> totalRefinementsSelected;
private final List<StatCounter> totalRefinementsFinished;
private final LogManager logger;
public DelegatingARGBasedRefiner(final LogManager pLogger, final ARGBasedRefiner... pRefiners) {
logger = pLogger;
refiners = ImmutableList.copyOf(pRefiners);
totalRefinementsSelected = new ArrayList<>();
totalRefinementsFinished = new ArrayList<>();
for (int i = 0; i < refiners.size(); i++) {
totalRefinementsSelected.add(new StatCounter("Number of selected refinement"));
totalRefinementsFinished.add(new StatCounter("Number of finished refinement"));
}
assert refiners.size() > 0;
assert refiners.size() == totalRefinementsSelected.size();
assert refiners.size() == totalRefinementsFinished.size();
}
@Override
public CounterexampleInfo performRefinementForPath(
final ARGReachedSet reached,
ARGPath pErrorPath)
throws CPAException, InterruptedException {
CounterexampleInfo cex = null;
// TODO here, we could sort the refiners to get a better result,
// like the score-based sorting from ValueAnalysisDelegatingRefiner
logger.logf(Level.FINE, "starting refinement with %d refiners", refiners.size());
for (int i = 0; i < refiners.size(); i++) {
totalRefinementsSelected.get(i).inc();
try {
logger.logf(Level.FINE, "starting refinement %d of %d with %s", i + 1, refiners.size(),
refiners.get(i).getClass().getSimpleName());
cex = refiners.get(i).performRefinementForPath(reached, pErrorPath);
if (cex.isSpurious()) {
logger.logf(Level.FINE, "refinement %d of %d was successful", i + 1, refiners.size());
totalRefinementsFinished.get(i).inc();
break;
}
} catch (RefinementFailedException e) {
if (Reason.RepeatedCounterexample != e.getReason()) {
throw e; // propagate exception
} else {
// ignore and try the next refiner
logger.logf(Level.FINE, "refinement %d of %d reported repeated counterexample, "
+ "restarting refinement with next refiner", i + 1, refiners.size());
}
}
}
if (cex == null) {
// TODO correct reason?
throw new RefinementFailedException(Reason.RepeatedCounterexample, pErrorPath);
}
logger.log(Level.FINE, "refinement finished");
return Preconditions.checkNotNull(cex);
}
@Override
public void collectStatistics(Collection<Statistics> pStatsCollection) {
pStatsCollection.add(new Statistics() {
@Override
public String getName() {
return DelegatingARGBasedRefiner.class.getSimpleName();
}
@Override
public void printStatistics(
final PrintStream pOut,
final Result pResult,
final ReachedSet pReached) {
StatisticsWriter writer = StatisticsWriter.writingStatisticsTo(pOut);
for (int i = 0; i < refiners.size(); i++) {
pOut.println(String
.format("Analysis %d (%s):", i + 1, refiners.get(i).getClass().getSimpleName()));
writer.beginLevel().put(totalRefinementsSelected.get(i));
writer.beginLevel().put(totalRefinementsFinished.get(i));
writer.spacer();
}
}
});
for (ARGBasedRefiner refiner : refiners) {
if (refiner instanceof StatisticsProvider) {
((StatisticsProvider) refiner).collectStatistics(pStatsCollection);
}
}
}
}
| 34.309211 | 98 | 0.707191 |
446b81923e170593db0fe3fece90ecd268fbcc5e | 218 | package com.sbur.service;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class SburRedisServiceApplicationTests {
@Test
void contextLoads() {
}
}
| 15.571429 | 60 | 0.793578 |
a7e1e8a268c2714c13ce7ef8d0d6af7a81c25931 | 1,653 | package com.wuhaowen.rxsocketio;
import android.support.annotation.NonNull;
import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.FlowableOnSubscribe;
import io.socket.client.Socket;
public class RxSocketIO {
public static Flowable<Msg> on(@NonNull final Socket socket, @NonNull final String event) {
return Flowable.<Msg>create(emitter -> socket.on(event, args -> {
if (!emitter.isCancelled()) {
emitter.onNext(new Msg(event, args));
}
}), BackpressureStrategy.DROP).doFinally(() -> socket.off(event));
}
public static Flowable<Msg> on(@NonNull final Socket socket, @NonNull final String... events) {
return Flowable.create((FlowableOnSubscribe<Msg>) emitter -> {
for (String event : events) {
socket.on(event, args -> {
if (!emitter.isCancelled()) {
emitter.onNext(new Msg(event, args));
}
});
}
}, BackpressureStrategy.DROP).doFinally(() -> {
for (String event : events) {
socket.off(event);
}
}
);
}
public static Flowable<Msg> once(@NonNull final Socket socket, @NonNull final String event) {
return Flowable.<Msg>create(emitter -> socket.once(event, args -> {
if (!emitter.isCancelled()) {
emitter.onNext(new Msg(event, args));
emitter.onComplete();
}
}), BackpressureStrategy.DROP).doFinally(() -> socket.off(event));
}
}
| 33.06 | 99 | 0.564428 |
6cca425ab49d0c08380be863cfcd66716fa1a14f | 1,606 | package step;
import io.qameta.allure.Step;
import model.CleanRs;
import model.Order;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.testng.Assert;
import org.testng.asserts.SoftAssert;
import utils.ResponseUtil;
public class OrderStep extends BaseStep {
private final static Logger LOGGER = LogManager.getLogger(OrderStep.class.getSimpleName());
@Step("Проверка маппинга запроса/ответа")
public void checkRqRsMapping() {
LOGGER.info("Проверка маппинга запроса/ответа");
Order expected = createRq;
Order actual = ResponseUtil.getResponseBodyAsClass(response, Order.class);
SoftAssert softAssert = new SoftAssert();
softAssert.assertEquals(actual.getId(), expected.getId(), "id в запросе и ответе отличается");
softAssert.assertEquals(actual.getPrice(), expected.getPrice(), "price в запросе и ответе отличается");
softAssert.assertEquals(actual.getQuantity(), expected.getQuantity(), "quantity в запросе и ответе отличается");
softAssert.assertEquals(actual.getSide().toLowerCase(), expected.getSide().toLowerCase(), "side в запросе и ответе отличается");
softAssert.assertAll();
}
@Step("Проверка сообщения ответа при очистке книги заказов")
public void checkCleanRsMessage() {
LOGGER.info("Проверка сообщения ответа при очистке книги заказов");
String message = ResponseUtil.getResponseBodyAsClass(response, CleanRs.class).getMessage();
Assert.assertEquals(message, "Order book is clean.", "Сообщение ответа не соответствует ожидаемому");
}
}
| 44.611111 | 136 | 0.737235 |
e42553506729638d25c605acc29ec4a209ce3168 | 546 | package com.lynxcat.entities;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class NightingaleNote {
private String id;
private String ident;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getIdent() {
return ident;
}
public void setIdent(String ident) {
this.ident = ident;
}
public NightingaleNote(String id, String ident) {
this.id = id;
this.ident = ident;
}
public NightingaleNote() {
}
}
| 15.6 | 61 | 0.712454 |
f5ccb9e7822d01739a22b224e6be71ee873cb835 | 7,772 | /*******************************************************************************
* Copyright 2021 Danny Kunz
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package org.omnaest.genomics.gpcrdb;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.StringEscapeUtils;
import org.omnaest.genomics.gpcrdb.GPCRDBRestAPIUtils.GPCRRestAccessor;
import org.omnaest.genomics.gpcrdb.domain.Receptor;
import org.omnaest.genomics.gpcrdb.domain.raw.Protein;
import org.omnaest.genomics.gpcrdb.domain.raw.ProteinFamily;
import org.omnaest.utils.CollectorUtils;
import org.omnaest.utils.cache.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GPCRDBUtils
{
private static final Logger LOG = LoggerFactory.getLogger(GPCRDBUtils.class);
public static interface GPCRDBDataAccessor
{
public SpeciesGPCRDBDataAccessor forSpecies(String species);
public SpeciesGPCRDBDataAccessor forHuman();
public GPCRDBDataAccessor usingCache(Cache cache);
public GPCRDBDataAccessor usingLocalCache();
}
public static interface SpeciesGPCRDBDataAccessor
{
public Stream<Receptor> getReceptors();
}
public static GPCRDBDataAccessor getInstance()
{
return new GPCRDBDataAccessor()
{
private GPCRRestAccessor restAccessor = GPCRDBRestAPIUtils.getInstance();
@Override
public SpeciesGPCRDBDataAccessor forSpecies(String species)
{
return new SpeciesGPCRDBDataAccessor()
{
private Map<String, Protein> nameToProtein = this.createNameToProteinMap(species);
@Override
public Stream<Receptor> getReceptors()
{
return this.nameToProtein.entrySet()
.stream()
.map(entry -> this.createReceptor(this.normalizeName(entry.getKey()), entry.getValue()));
}
private Map<String, Protein> createNameToProteinMap(String species)
{
Map<String, Set<String>> parentToChildren = new HashMap<>();
Map<String, ProteinFamily> nameToFamily = new HashMap<>();
restAccessor.getProteinFamilies()
.forEach(family ->
{
//
String name = family.getName();
nameToFamily.put(name, family);
//
ProteinFamily parent = family.getParent();
if (parent != null)
{
String parentName = parent.getName();
if (parentName != null)
{
parentToChildren.computeIfAbsent(parentName, pn -> new HashSet<>())
.add(name);
}
}
});
Set<String> recptorNames = nameToFamily.keySet()
.stream()
.filter(name -> parentToChildren.getOrDefault(name, Collections.emptySet())
.isEmpty())
.collect(CollectorUtils.toSortedSet());
Map<String, Protein> nameToProtein = recptorNames.stream()
.peek(name -> LOG.info("Resolving receptor: " + name))
.map(name -> nameToFamily.get(name))
.map(family -> restAccessor.getProtein(family.getSlug()))
.flatMap(proteins -> proteins.stream())
// .peek(protein -> LOG.info("Species: " + protein.getSpecies()))
.filter(protein -> StringUtils.equalsIgnoreCase(species, protein.getSpecies()))
.collect(Collectors.toMap(p -> p.getName(), p -> p));
return nameToProtein;
}
private String normalizeName(String name)
{
return StringEscapeUtils.unescapeHtml4(name)
.replaceAll("\\<[^\\>]+\\>", "");
}
private Receptor createReceptor(String name, Protein protein)
{
return new Receptor()
{
@Override
public String getName()
{
return name;
}
@Override
public String getNameHtmlEncoded()
{
return protein.getName();
}
@Override
public String getUniprotId()
{
return protein.getAccession();
}
@Override
public Set<String> getGenes()
{
return protein.getGenes();
}
};
}
};
}
@Override
public SpeciesGPCRDBDataAccessor forHuman()
{
return this.forSpecies("Homo sapiens");
}
@Override
public GPCRDBDataAccessor usingLocalCache()
{
this.restAccessor.usingLocalCache();
return this;
}
@Override
public GPCRDBDataAccessor usingCache(Cache cache)
{
this.restAccessor.usingCache(cache);
return this;
}
};
}
}
| 42.010811 | 210 | 0.429619 |
9ca21e09af6757b893cd141a7582203b55a02a64 | 1,518 | package org.zongjieli.leetcode.question.daily.year2021.month12.week4;
import java.util.Arrays;
/**
* 冬季已经来临,设计一个有固定加热半径的供暖器向所有房屋供暖
* 在加热器的加热半径范围内的每个房屋都可以获得供暖
* 现在,给出位于一条水平线上的房屋 houses 和供暖器 heaters 的位置
* 请找出并返回可以覆盖所有房屋的最小加热半径
*
* 说明:所有供暖器都遵循半径标准,加热的半径也一样
*
* 1 <= houses.length, heaters.length <= 3 * 10^4
* 1 <= houses[i], heaters[i] <= 10^9
*
* @author Li.zongjie
* @date 2021/12/20
* @version 1.0
*/
public class Z1Heater {
private int findRadius(int[] houses, int[] heaters) {
Arrays.sort(houses);
Arrays.sort(heaters);
int result = 0;
int heaterIndex = 0;
int temp;
for (int house : houses) {
int current = Math.abs(heaters[heaterIndex] - house);
while (heaterIndex < heaters.length - 1 && (temp = Math.abs(heaters[heaterIndex + 1] - house)) <= current) {
current = temp;
heaterIndex++;
}
result = Math.max(current, result);
}
return result;
}
public static void main(String[] args) {
Z1Heater test = new Z1Heater();
// 1
System.out.println(test.findRadius(new int[]{1,2,3,4}, new int[]{1,4}));
// 1
System.out.println(test.findRadius(new int[]{1,2,3}, new int[]{2}));
// 3
System.out.println(test.findRadius(new int[]{1,5}, new int[]{2}));
// 0
System.out.println(test.findRadius(new int[]{1,2,3,9,10,1000,17}, new int[]{1,2,3,9,10,50,1000,1001,17}));
}
}
| 29.764706 | 120 | 0.576416 |
9e8815df4dec59da866fe9ac3c4e0364283f5759 | 3,046 | package users;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.*;
import com.google.gson.Gson;
import client.Constants;
import client.ClientCommunication;
import client.ClientCommunication.Transmitter;
import json.JsonDataContract;
public class LogIn {
private String email;
private String password;
private final String MSG_TYPE="LOGIN";
public boolean loginUser()
{
System.out.println("Enter your email ID");
Scanner sc=new Scanner(System.in);
this.email=sc.nextLine();
System.out.println("Enter password");
Scanner pass_sc=new Scanner(System.in);
this.password=pass_sc.nextLine();
Gson gson=new Gson();
JsonDataContract jdc=new JsonDataContract();
jdc.setMessageType(MSG_TYPE);
jdc.setEmail(this.email);
jdc.setPassword(this.password);
System.out.println(client.Constants.clientIp);
jdc.setClientIp(client.Constants.clientIp);
jdc.setClientPort(String.valueOf(client.Constants.clientPort));
String clientData=gson.toJson(jdc,JsonDataContract.class);
boolean Result=sendData(clientData);
return Result;
}
public boolean sendData(String clientData)
{
boolean Success=true;
client.SocketDetails socketDetails=new client.SocketDetails();
try {
socketDetails.setIn(new DataInputStream(client.Constants.socket.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
socketDetails.setOut(new OutputStreamWriter(client.Constants.socket.getOutputStream(), StandardCharsets.UTF_8));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
client.ClientCommunication clComm=new client.ClientCommunication();
client.ClientCommunication.Transmitter tr=clComm.new Transmitter();//class within class
client.JsonDataContract jdc1=tr.sendDataToServer(clientData,socketDetails);
System.out.println("Got back JSON");
System.out.println("Status: "+jdc1.getStatus());
System.out.println("Message Type: "+jdc1.getMessageType());
System.out.println("Error Value: "+jdc1.getErrorValue());
//TODO:may set userId latter thru changes in JsonDataContract and Server-Side Module
//TODO:If incorrect email, don't save or go back or redirect someplace else
if(jdc1.getErrorValue().isEmpty())//CORRECT CREDENTIALS
{
users.Constants.myEmail=jdc1.getEmail();
}
else if(jdc1.getErrorValue().equals(users.Constants.WRONG_EMAIL))
{
System.out.println("Incorrect Email");
return false;
}
else if(jdc1.getErrorValue().equals(users.Constants.WRONG_PASSWORD))
{
System.out.println("Incorrect Password");
return false;
}
return Success;
}
}
| 26.034188 | 116 | 0.714051 |
786e5042314f412512908d49a7e181f746e4d52e | 233 | package com.suk.blog.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.suk.blog.entity.Tags;
/**
* 书签 数据层
*
* @author suk
* @date 2019-09-27
*/
public interface TagsMapper extends BaseMapper<Tags> {
} | 16.642857 | 55 | 0.725322 |
93f688bdec1af12c1e132cb6d86db84f6c37c757 | 755 | package com.simibubi.create.lib.mixin.accessor;
import java.util.Map;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.renderer.entity.EntityRenderDispatcher;
import net.minecraft.client.renderer.entity.EntityRenderer;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.player.Player;
@Environment(EnvType.CLIENT)
@Mixin(EntityRenderDispatcher.class)
public interface EntityRenderDispatcherAccessor {
@Accessor("renderers")
Map<EntityType<?>, EntityRenderer<?>> getRenderers();
@Accessor("playerRenderers")
Map<String, EntityRenderer<? extends Player>> getPlayerRenderers();
}
| 31.458333 | 68 | 0.817219 |
aad438a53437965d6fd1e3bd7d19f0259c0ff83b | 1,581 | package org.jamocha.sample.im;
import java.util.Calendar;
import java.util.List;
public class Message {
public static final int QUEUED = 100;
public static final int SENT = 200;
public static final int DELAYED = 300;
public static final int RECEIVED = 400;
public static final int RETURNED = 500;
private String senderId;
private String receiverId;
private String text;
@SuppressWarnings("rawtypes")
private List images;
@SuppressWarnings("rawtypes")
private List files;
private Calendar sendTime;
private int messageStatus;
public Message() {
super();
}
public String getSenderId() {
return senderId;
}
public void setSenderId(String senderId) {
this.senderId = senderId;
}
public String getReceiverId() {
return receiverId;
}
public void setReceiverId(String receiverId) {
this.receiverId = receiverId;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
@SuppressWarnings("rawtypes")
public List getImages() {
return images;
}
@SuppressWarnings("rawtypes")
public void setImages(List images) {
this.images = images;
}
@SuppressWarnings("rawtypes")
public List getFiles() {
return files;
}
@SuppressWarnings("rawtypes")
public void setFiles(List files) {
this.files = files;
}
public Calendar getSendTime() {
return sendTime;
}
public void setSendTime(Calendar sendTime) {
this.sendTime = sendTime;
}
public int getMessageStatus() {
return messageStatus;
}
public void setMessageStatus(int messageStatus) {
this.messageStatus = messageStatus;
}
}
| 21.364865 | 50 | 0.73055 |
75c2353e6ac3bdf310072572e196eb77dbe17f4e | 2,323 | package tutoraid.ui;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import tutoraid.model.student.Student;
/**
* A UI component that displays information of a {@code Student}. The full student card displays every progress entry.
*/
public class FullStudentCard extends Card<Student> {
private static final String FXML = "StudentListCard.fxml";
private static final String LABEL_STUDENT_NAME = "";
private static final String LABEL_STUDENT_PHONE = "Mobile";
private static final String LABEL_PARENT_NAME = "Parent";
private static final String LABEL_PARENT_PHONE = "Parent Mobile";
private static final String LABEL_PROGRESS = "Progress";
private static final String LABEL_LESSONS = "Lessons";
/**
* Note: Certain keywords such as "location" and "resources" are reserved keywords in JavaFX.
* As a consequence, UI elements' variable names cannot be set to such keywords
* or an exception will be thrown by JavaFX during runtime.
*
* @see <a href="https://github.com/se-edu/addressbook-level4/issues/336">The issue on StudentBook level 4</a>
*/
@FXML
private HBox cardPane;
@FXML
private Label id;
@FXML
private Label studentName;
@FXML
private Label studentPhone;
@FXML
private Label parentName;
@FXML
private Label parentPhone;
@FXML
private Label progress;
@FXML
private Label lessons;
/**
* Creates a {@code StudentCard} with the given {@code Student} and index to display.
*/
public FullStudentCard(Student student, int displayedIndex) {
super(FXML, student, displayedIndex);
id.setText(displayedIndex + ". ");
studentName.setText(formatCardLabel(LABEL_STUDENT_NAME, student.getStudentName().fullName));
studentPhone.setText(formatCardLabel(LABEL_STUDENT_PHONE, student.getStudentPhone().value));
parentName.setText(formatCardLabel(LABEL_PARENT_NAME, student.getParentName().fullName));
parentPhone.setText(formatCardLabel(LABEL_PARENT_PHONE, student.getParentPhone().value));
progress.setText(formatCardLabel(LABEL_PROGRESS, student.getProgressList().toString()));
lessons.setText(formatCardLabel(LABEL_LESSONS, student.getLessons().toString()));
}
}
| 37.467742 | 118 | 0.719759 |
5b99894c86b985c1db4fe3088c0934db271cdf8f | 351 | package com.multi.thread.chapter7.section7.example1;
/**
* @Description
* @Author dongzonglei
* @Date 2018/12/24 下午6:18
*/
public class StateUncatchExceptionHandler implements Thread.UncaughtExceptionHandler {
public void uncaughtException(Thread t, Throwable e) {
System.out.println("静态的异常处理");
e.printStackTrace();
}
}
| 23.4 | 86 | 0.717949 |
d8593b64751b54267be65144818c46a6124d9a8d | 332 | package org.sakaiproject.tool.assessment.entity.api;
import org.sakaiproject.entitybroker.entityprovider.EntityProvider;
/**
* Entity Provider for samigo Item
*
* @author Unicon
*
*/
public interface PublishedItemEntityProvider extends EntityProvider {
public final static String ENTITY_PREFIX = "sam_publisheditem";
}
| 20.75 | 69 | 0.786145 |
5927fb63513d156b0c1c67f1ec0f8c8a46950dc5 | 2,542 | package de.lyca.xslt.conf;
import static de.lyca.xslt.ResourceUtils.getSource;
import static de.lyca.xslt.ResourceUtils.readResource;
import static java.nio.charset.StandardCharsets.ISO_8859_1;
import static java.nio.charset.StandardCharsets.UTF_16;
import static java.nio.charset.StandardCharsets.UTF_8;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import javax.xml.transform.Source;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import de.lyca.xslt.Transform;
@RunWith(Parameterized.class)
public class ConfOutputTests {
private static final Charset ISO_8859_6 = Charset.forName("ISO-8859-6");
private static final Charset SHIFT_JIS = Charset.forName("SHIFT_JIS");
private static final String PACKAGE = '/' + ConfOutputTests.class.getPackage().getName().replace('.', '/')
+ "/output/";
private String name;
private Charset encoding;
@Parameters(name = "{0}")
public static Collection<Object[]> params() {
Collection<Object[]> result = new ArrayList<>();
// 22: EBCDIC-CP-IT encoding problem, so who cares ;-)
// 59: Some whitespace problems?
// 63: Html tag vs. xml tag issues?
// Rest non existent
int[] exclude = { 22, 31, 59, 63, 83, 108 };
for (int i = 1; i < 115; i++) {
if (Arrays.binarySearch(exclude, i) >= 0) {
continue;
}
if (i == 26 || i == 86) {
result.add(new Object[] { String.format("output%02d", i), ISO_8859_1 });
} else if (i == 73) {
result.add(new Object[] { String.format("output%02d", i), SHIFT_JIS });
} else if (i == 78 || i == 79) {
result.add(new Object[] { String.format("output%02d", i), ISO_8859_6 });
} else if (i == 80) {
result.add(new Object[] { String.format("output%02d", i), UTF_16 });
} else {
result.add(new Object[] { String.format("output%02d", i), UTF_8 });
}
}
return result;
}
public ConfOutputTests(String name, Charset encoding) {
this.name = PACKAGE + name;
this.encoding = encoding;
}
@Test
public void confOutputTest() throws Exception {
final Source xsl = getSource(name + ".xsl");
final Source xml = getSource(name + ".xml");
final String expected = readResource(name + ".out", encoding);
final Transform t = new Transform(xml, xsl);
Assert.assertEquals(expected, t.getResultString());
}
}
| 33.012987 | 108 | 0.666011 |
857894b49e16471de25b174e21de2113704838d6 | 1,425 | package com.tirthal.learning.oop.design.principles.clazz.solid.ocp.parsing.good;
// NOTE - For simplicity I kept all classes in same file, but you can have separate file for each class
/**
* Abstract class to define parse() specification, which follows OCP. Why?
*
* Well if you need to extend support for more types like CSV, then you don't need to change existing class/method. Just add new class called
* CsvParser extending FileParser. That means, you just need code review and testing of new CsvParser class. This is the beauty of OCP.
*
* @author tirthalp
*
*/
abstract class FileParser {
String filePath;
String expression;
public FileParser(String filePath, String expression) {
this.filePath = filePath;
this.expression = expression;
}
abstract String parse();
}
/**
* Implementation class for XML Parser
*
* @author tirthalp
*
*/
class XMLParser extends FileParser {
public XMLParser(String filePath, String expression) {
super(filePath, expression);
}
@Override
String parse() {
// TODO: implement xml parsing logic using xpath
return "";
}
}
/**
* Implementation class for TXT Parser
*
* @author tirthalp
*
*/
class TextParser extends FileParser {
public TextParser(String filePath, String expression) {
super(filePath, expression);
}
@Override
String parse() {
// TODO: implement text parsing logic using regular expression
return "";
}
}
| 22.265625 | 141 | 0.72 |
83d5d416b37d0faec2bc736381e266c377efa039 | 2,338 | package org.innovateuk.ifs.assessment.feedback.viewmodel;
import org.innovateuk.ifs.assessment.resource.AssessmentResource;
import org.innovateuk.ifs.competition.resource.CompetitionResource;
import org.innovateuk.ifs.form.resource.FormInputResource;
import org.innovateuk.ifs.form.resource.QuestionResource;
import org.junit.Test;
import java.time.ZonedDateTime;
import java.util.List;
import static org.innovateuk.ifs.assessment.builder.AssessmentResourceBuilder.newAssessmentResource;
import static org.innovateuk.ifs.competition.builder.CompetitionResourceBuilder.newCompetitionResource;
import static org.innovateuk.ifs.form.builder.FormInputResourceBuilder.newFormInputResource;
import static org.innovateuk.ifs.form.builder.QuestionResourceBuilder.newQuestionResource;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
public class AssessmentFeedbackViewModelTest {
@Test
public void testGetAppendixFileDescription() throws Exception {
final String questionShortName = "Technical approach";
AssessmentResource assessmentResource = newAssessmentResource().withApplication(1L).build();
CompetitionResource competitionResource = newCompetitionResource().withAssessorDeadlineDate(ZonedDateTime.now()).withAssessorAcceptsDate(ZonedDateTime.now()).build();
QuestionResource questionResource = newQuestionResource().withShortName(questionShortName).build();
List<FormInputResource> formInputResources = newFormInputResource().build(2);
AssessmentFeedbackViewModel assessmentFeedbackViewModel = new AssessmentFeedbackViewModel(
assessmentResource,
competitionResource,
questionResource,
null,
formInputResources,
false,
false,
null,
null,
"template document",
null
);
assertEquals("View technical approach appendix", assessmentFeedbackViewModel.getAppendixFileDescription());
assertEquals("View template document", assessmentFeedbackViewModel.getTemplateDocumentFileDescription());
assertFalse(assessmentFeedbackViewModel.isAppendixExists());
assertFalse(assessmentFeedbackViewModel.isTemplateDocumentExists());
}
}
| 46.76 | 174 | 0.759624 |
1659b9bc8e64b8ca57e0a4f1c2f7c09a81caf89d | 606 | package com.example.application.service;
import com.example.application.entity.Book;
import com.example.application.entity.User;
import com.example.application.repository.BookRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class BookService {
@Autowired
BookRepository bookRepository;
public List<Book> loadBook(){
return bookRepository.findAll();
}
public List<Book>loadBookByUser(User user){
return bookRepository.findAllById(user.getId());
}
}
| 24.24 | 62 | 0.767327 |
b6ac42891ee023d831f8e2c8d560147f4240a516 | 2,990 | public void execute() {
try {
if (getValue("srcfile") == null) throw new InstantiationException("You need to choose a sourcefile");
File src = (File) getValue("srcfile");
if (getValue("destfile1") == null) throw new InstantiationException("You need to choose a destination file for the first part of the PDF");
File file1 = (File) getValue("destfile1");
if (getValue("destfile2") == null) throw new InstantiationException("You need to choose a destination file for the second part of the PDF");
File file2 = (File) getValue("destfile2");
int pagenumber = Integer.parseInt((String) getValue("pagenumber"));
PdfReader reader = new PdfReader(src.getAbsolutePath());
int n = reader.getNumberOfPages();
System.out.println("There are " + n + " pages in the original file.");
if (pagenumber < 2 || pagenumber > n) {
throw new DocumentException("You can't split this document at page " + pagenumber + "; there is no such page.");
}
Document document1 = new Document(reader.getPageSizeWithRotation(1));
Document document2 = new Document(reader.getPageSizeWithRotation(pagenumber));
PdfWriter writer1 = PdfWriter.getInstance(document1, new FileOutputStream(file1));
PdfWriter writer2 = PdfWriter.getInstance(document2, new FileOutputStream(file2));
document1.open();
PdfContentByte cb1 = writer1.getDirectContent();
document2.open();
PdfContentByte cb2 = writer2.getDirectContent();
PdfImportedPage page;
int rotation;
int i = 0;
while (i < pagenumber - 1) {
i++;
document1.setPageSize(reader.getPageSizeWithRotation(i));
document1.newPage();
page = writer1.getImportedPage(reader, i);
rotation = reader.getPageRotation(i);
if (rotation == 90 || rotation == 270) {
cb1.addTemplate(page, 0, -1f, 1f, 0, 0, reader.getPageSizeWithRotation(i).height());
} else {
cb1.addTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
}
while (i < n) {
i++;
document2.setPageSize(reader.getPageSizeWithRotation(i));
document2.newPage();
page = writer2.getImportedPage(reader, i);
rotation = reader.getPageRotation(i);
if (rotation == 90 || rotation == 270) {
cb2.addTemplate(page, 0, -1f, 1f, 0, 0, reader.getPageSizeWithRotation(i).height());
} else {
cb2.addTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
}
document1.close();
document2.close();
} catch (Exception e) {
e.printStackTrace();
}
}
| 52.45614 | 152 | 0.551505 |
0c94f2d5f43fbcc02f7d124142f062b5a5536d78 | 609 | package com.jumpcutfindo.happyholidays.client.entity;
import com.jumpcutfindo.happyholidays.client.entity.model.SantaModel;
import com.jumpcutfindo.happyholidays.common.entity.christmas.santa.BaseSantaEntity;
import net.minecraft.client.renderer.entity.EntityRendererProvider;
import software.bernie.geckolib3.renderers.geo.GeoEntityRenderer;
public class SantaEntityRenderer extends GeoEntityRenderer<BaseSantaEntity> {
public SantaEntityRenderer(EntityRendererProvider.Context renderManager) {
super(renderManager, new SantaModel<>());
this.shadowRadius = 1.0F;
}
}
| 40.6 | 85 | 0.799672 |
bdbb51aee1c51c64b1e6d5ae8080eabc612873a8 | 1,348 | /*
* Copyright (C) 2019 Toshiba Corporation
* SPDX-License-Identifier: Apache-2.0
*/
package org.wcardinal.controller.data.internal;
import com.fasterxml.jackson.databind.JsonNode;
import org.wcardinal.controller.data.SLockable;
import org.wcardinal.util.thread.AutoCloseableReentrantLock;
public interface SBase<T> extends SLockable {
int getType();
long getRevision();
void setReadOnly(boolean isReadOnly);
boolean isReadOnly();
void setNonNull(boolean isNonNull);
boolean isNonNull();
// A soft SBase sets its value to null immediately after receiving acknowledge messages.
void setSoft(boolean isSoft);
boolean isSoft();
void compact( long authorizedRevision );
// A weak SBase sets its value to null immediately after sending it without waiting acknowledge messages.
void setWeak( boolean isWeak );
boolean isWeak();
// A loose SBase accepts update messages which revisions are greater than or equals to the revision it has.
void setLoose( boolean isLoose );
boolean isLoose();
boolean isInitialized();
void uninitialize();
void setParent( SParent parent );
Object pack( SData sdata );
SChange unpack( JsonNode valueNode, long revision, SData sdata ) throws Exception;
void override( long revision );
void onAuthorized( long authorizedRevision );
void setLock(final AutoCloseableReentrantLock lock);
}
| 27.510204 | 108 | 0.773739 |
10a282391ec58082252ffd9850430bf600192cfd | 2,429 | package de.redsix.pdfcompare;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.CoreMatchers.equalTo;
import de.redsix.pdfcompare.cli.CliArguments;
import de.redsix.pdfcompare.cli.CliArgumentsImpl;
import org.junit.jupiter.api.Test;
public class CliArgumentsTest {
@Test
public void cliIsAvailableWhenExpectedAndActualFilenameAreProvided() {
CliArguments cliArguments = new CliArgumentsImpl(new String[]{"expected.pdf", "actual.pdf"});
assertThat(cliArguments.areAvailable(), is(true));
}
@Test
public void cliIsNotAvailableWhenOnlyOneFilenameIsProvided() {
CliArguments cliArguments = new CliArgumentsImpl(new String[]{"expected.pdf"});
assertThat(cliArguments.areAvailable(), is(false));
}
@Test
public void cliIsNotAvailableWhenMoreArgumentsAreProvidedThanExpected() {
CliArguments cliArguments = new CliArgumentsImpl(new String[]{"a.pdf", "b.pdf", "c.pdf"});
assertThat(cliArguments.areAvailable(), is(false));
}
@Test
public void cliIsNotAvailableWhenNoArgumentsAreProvided() {
CliArguments cliArguments = new CliArgumentsImpl(new String[]{});
assertThat(cliArguments.areAvailable(), is(false));
}
@Test
public void provideExpectedAndActualFilename() {
CliArguments cliArguments = new CliArgumentsImpl(new String[]{"expected.pdf", "actual.pdf"});
assertThat(cliArguments.getExpectedFile().isPresent(), is(true));
assertThat(cliArguments.getExpectedFile().get(), equalTo("expected.pdf"));
assertThat(cliArguments.getActualFile().isPresent(), is(true));
assertThat(cliArguments.getActualFile().get(), equalTo("actual.pdf"));
}
@Test
public void provideOutputFilenameWithShortArgument() {
CliArguments cliArguments = new CliArgumentsImpl(new String[]{"-o", "result.pdf"});
assertThat(cliArguments.getOutputFile().isPresent(), is(true));
assertThat(cliArguments.getOutputFile().get(), equalTo("result.pdf"));
}
@Test
public void provideOutputFilenameWithLongArgument() {
CliArguments cliArguments = new CliArgumentsImpl(new String[]{"--output", "result.pdf"});
assertThat(cliArguments.getOutputFile().isPresent(), is(true));
assertThat(cliArguments.getOutputFile().get(), equalTo("result.pdf"));
}
}
| 35.720588 | 101 | 0.711816 |
52c742ee6f1c8de46cf844a1868e661025c845f2 | 2,486 | package com.rainbow.bridge.biz.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.Date;
/**
* <p>
* 同步目标数据源
* </p>
*
* @author gujiachun
* @since 2021-09-27
*/
@TableName("sync_target")
@ApiModel(value="SyncTargetEntity对象", description="同步目标数据源")
public class SyncTargetEntity extends BridgeEntity {
@ApiModelProperty(value = "主键")
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
@ApiModelProperty(value = "数据源名称")
private String name;
@ApiModelProperty(value = "目标数据源类型 mysql、es、redis、rocketmq")
private String type;
@ApiModelProperty(value = "备注")
private String remark;
@ApiModelProperty(value = "环境代码")
private String env;
@ApiModelProperty(value = "创建时间")
private Date createdTime;
@ApiModelProperty(value = "更新时间")
private Date updatedTime;
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 getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getEnv() {
return env;
}
public void setEnv(String env) {
this.env = env;
}
public Date getCreatedTime() {
return createdTime;
}
public void setCreatedTime(Date createdTime) {
this.createdTime = createdTime;
}
public Date getUpdatedTime() {
return updatedTime;
}
public void setUpdatedTime(Date updatedTime) {
this.updatedTime = updatedTime;
}
@Override
public String toString() {
return "SyncTargetEntity{" +
"id=" + id +
", name=" + name +
", type=" + type +
", remark=" + remark +
", env=" + env +
", createdTime=" + createdTime +
", updatedTime=" + updatedTime +
"}";
}
}
| 23.018519 | 65 | 0.581657 |
0eecf4d89d9d3dc42ab16c48df1d67773ae37922 | 566 | package pers.mine.nookblog.entity;
import lombok.Data;
import lombok.ToString;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @author yebukong
* @description 后台用户
* @since 2018-10-23 10:02
*/
@Data
@ToString(callSuper = true)
@Component
@ConfigurationProperties(prefix = "mine-info")
public class CMSUser extends BaseEntity{
public static final String SESSION_NAME = "cms_user_info";
private String userID;
private String userName;
private String password;
}
| 23.583333 | 75 | 0.772085 |
43c4573bce166c3ea5bf124f964dec3c46666c90 | 126 | package org.lukosan.salix;
public interface SalixTemplate extends SalixScoped {
String getName();
String getSource();
} | 14 | 52 | 0.761905 |
c12739684a804417a887647ce6f12a6cfafa7aa4 | 1,774 | /**
* Copyright (c) 2003 by Bradley Keith Neuberg, bkn3@columbia.edu.
*
* Redistributions in source code form must reproduce the above copyright and this condition.
*
* The contents of this file are subject to the Sun Project JXTA License Version 1.1 (the "License");
* you may not use this file except in compliance with the License. A copy of the License is available
* at http://www.jxta.org/jxta_license.html.
*/
package org.p2psockets;
import java.io.*;
import java.net.*;
/** This class wraps the many exceptions that can be thrown from P2PInetAddress
* so that clients only have to deal with one type of exception. We subclass
* java.net.UnknownHostException so that client's who used the previous InetAddress
* methods can use our P2PInetAddress methods without having to catch a new kind
* of exception.
*/
public class P2PInetAddressException extends UnknownHostException {
private Throwable t;
public P2PInetAddressException(Throwable t) {
this.t = t;
}
public Throwable getCause() {
return t.getCause();
}
public String getLocalizedMessage() {
return t.getLocalizedMessage();
}
public String getMessage() {
return t.getMessage();
}
public StackTraceElement[] getStackTrace() {
return t.getStackTrace();
}
public Throwable initCause(Throwable cause) {
return t.initCause(cause);
}
public void printStackTrace() {
t.printStackTrace();
}
public void printStackTrace(PrintStream s) {
t.printStackTrace(s);
}
public void printStackTrace(PrintWriter s) {
t.printStackTrace(s);
}
public void setStackTrace(StackTraceElement[] stackTrace) {
t.setStackTrace(stackTrace);
}
public String toString() {
return t.toString();
}
} | 26.477612 | 104 | 0.709132 |
6f20dad73202c89fe5dabcae8666ac68803f5a52 | 736 | package com.xuxd.kafka.console.service;
import com.xuxd.kafka.console.beans.ResponseData;
import com.xuxd.kafka.console.beans.enums.AlterType;
import org.apache.kafka.clients.admin.ConfigEntry;
/**
* kafka-console-ui.
*
* @author xuxd
* @date 2021-11-02 19:57:43
**/
public interface ConfigService {
ResponseData getTopicConfig(String topic);
ResponseData getBrokerConfig(String brokerId);
ResponseData getBrokerLoggerConfig(String brokerId);
ResponseData alterBrokerConfig(String brokerId, ConfigEntry entry, AlterType type);
ResponseData alterBrokerLoggerConfig(String brokerId, ConfigEntry entry, AlterType type);
ResponseData alterTopicConfig(String topic, ConfigEntry entry, AlterType type);
}
| 27.259259 | 93 | 0.78125 |
5e7e4fb1cd5e2c2b09569eb5127f632b3331f0cc | 70,849 | /*
* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
package sun.jvm.hotspot;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.math.*;
import javax.swing.*;
import javax.swing.tree.*;
import java.util.*;
import sun.jvm.hotspot.code.*;
import sun.jvm.hotspot.compiler.*;
import sun.jvm.hotspot.debugger.*;
import sun.jvm.hotspot.gc_implementation.parallelScavenge.*;
import sun.jvm.hotspot.gc_interface.*;
import sun.jvm.hotspot.interpreter.*;
import sun.jvm.hotspot.memory.*;
import sun.jvm.hotspot.oops.*;
import sun.jvm.hotspot.runtime.*;
import sun.jvm.hotspot.ui.*;
import sun.jvm.hotspot.ui.tree.*;
import sun.jvm.hotspot.ui.classbrowser.*;
import sun.jvm.hotspot.utilities.*;
/** The top-level HotSpot Debugger. FIXME: make this an embeddable
component! (Among other things, figure out what to do with the
menu bar...) */
public class HSDB implements ObjectHistogramPanel.Listener, SAListener {
public static void main(String[] args) {
new HSDB(args).run();
}
//--------------------------------------------------------------------------------
// Internals only below this point
//
private HotSpotAgent agent;
private JDesktopPane desktop;
private boolean attached;
/** List <JMenuItem> */
private java.util.List attachMenuItems;
/** List <JMenuItem> */
private java.util.List detachMenuItems;
private JMenu toolsMenu;
private JMenuItem showDbgConsoleMenuItem;
private JMenuItem computeRevPtrsMenuItem;
private JInternalFrame attachWaitDialog;
private JInternalFrame threadsFrame;
private JInternalFrame consoleFrame;
private WorkerThread workerThread;
// These had to be made data members because they are referenced in inner classes.
private String pidText;
private int pid;
private String execPath;
private String coreFilename;
private void doUsage() {
System.out.println("Usage: java HSDB [[pid] | [path-to-java-executable [path-to-corefile]] | help ]");
System.out.println(" pid: attach to the process whose id is 'pid'");
System.out.println(" path-to-java-executable: Debug a core file produced by this program");
System.out.println(" path-to-corefile: Debug this corefile. The default is 'core'");
System.out.println(" If no arguments are specified, you can select what to do from the GUI.\n");
HotSpotAgent.showUsage();
}
private HSDB(String[] args) {
switch (args.length) {
case (0):
break;
case (1):
if (args[0].equals("help") || args[0].equals("-help")) {
doUsage();
System.exit(0);
}
// If all numbers, it is a PID to attach to
// Else, it is a pathname to a .../bin/java for a core file.
try {
int unused = Integer.parseInt(args[0]);
// If we get here, we have a PID and not a core file name
pidText = args[0];
} catch (NumberFormatException e) {
execPath = args[0];
coreFilename = "core";
}
break;
case (2):
execPath = args[0];
coreFilename = args[1];
break;
default:
System.out.println("HSDB Error: Too many options specified");
doUsage();
System.exit(1);
}
}
private void run() {
// At this point, if pidText != null we are supposed to attach to it.
// Else, if execPath != null, it is the path of a jdk/bin/java
// and coreFilename is the pathname of a core file we are
// supposed to attach to.
agent = new HotSpotAgent();
workerThread = new WorkerThread();
attachMenuItems = new java.util.ArrayList();
detachMenuItems = new java.util.ArrayList();
JFrame frame = new JFrame("HSDB - HotSpot Debugger");
frame.setSize(800, 600);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
//
// File menu
//
JMenu menu = new JMenu("File");
menu.setMnemonic(KeyEvent.VK_F);
JMenuItem item;
item = createMenuItem("Attach to HotSpot process...",
new ActionListener() {
public void actionPerformed(ActionEvent e) {
showAttachDialog();
}
});
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.ALT_MASK));
item.setMnemonic(KeyEvent.VK_A);
menu.add(item);
attachMenuItems.add(item);
item = createMenuItem("Open HotSpot core file...",
new ActionListener() {
public void actionPerformed(ActionEvent e) {
showOpenCoreFileDialog();
}
});
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.ALT_MASK));
item.setMnemonic(KeyEvent.VK_O);
menu.add(item);
attachMenuItems.add(item);
item = createMenuItem("Connect to debug server...",
new ActionListener() {
public void actionPerformed(ActionEvent e) {
showConnectDialog();
}
});
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.ALT_MASK));
item.setMnemonic(KeyEvent.VK_S);
menu.add(item);
attachMenuItems.add(item);
item = createMenuItem("Detach",
new ActionListener() {
public void actionPerformed(ActionEvent e) {
detach();
}
});
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, ActionEvent.ALT_MASK));
item.setMnemonic(KeyEvent.VK_S);
menu.add(item);
detachMenuItems.add(item);
// Disable detach menu items at first
setMenuItemsEnabled(detachMenuItems, false);
menu.addSeparator();
item = createMenuItem("Exit",
new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.ALT_MASK));
item.setMnemonic(KeyEvent.VK_X);
menu.add(item);
menuBar.add(menu);
//
// Tools menu
//
toolsMenu = new JMenu("Tools");
toolsMenu.setMnemonic(KeyEvent.VK_T);
item = createMenuItem("Class Browser",
new ActionListener() {
public void actionPerformed(ActionEvent e) {
showClassBrowser();
}
});
item.setMnemonic(KeyEvent.VK_B);
toolsMenu.add(item);
item = createMenuItem("Code Viewer",
new ActionListener() {
public void actionPerformed(ActionEvent e) {
showCodeViewer();
}
});
item.setMnemonic(KeyEvent.VK_C);
toolsMenu.add(item);
item = createMenuItem("Compute Reverse Ptrs",
new ActionListener() {
public void actionPerformed(ActionEvent e) {
fireComputeReversePtrs();
}
});
computeRevPtrsMenuItem = item;
item.setMnemonic(KeyEvent.VK_M);
toolsMenu.add(item);
item = createMenuItem("Deadlock Detection",
new ActionListener() {
public void actionPerformed(ActionEvent e) {
showDeadlockDetectionPanel();
}
});
item.setMnemonic(KeyEvent.VK_D);
toolsMenu.add(item);
item = createMenuItem("Find Object by Query",
new ActionListener() {
public void actionPerformed(ActionEvent e) {
showFindByQueryPanel();
}
});
item.setMnemonic(KeyEvent.VK_Q);
toolsMenu.add(item);
item = createMenuItem("Find Pointer",
new ActionListener() {
public void actionPerformed(ActionEvent e) {
showFindPanel();
}
});
item.setMnemonic(KeyEvent.VK_P);
toolsMenu.add(item);
item = createMenuItem("Find Value In Heap",
new ActionListener() {
public void actionPerformed(ActionEvent e) {
showFindInHeapPanel();
}
});
item.setMnemonic(KeyEvent.VK_V);
toolsMenu.add(item);
item = createMenuItem("Find Value In Code Cache",
new ActionListener() {
public void actionPerformed(ActionEvent e) {
showFindInCodeCachePanel();
}
});
item.setMnemonic(KeyEvent.VK_A);
toolsMenu.add(item);
item = createMenuItem("Heap Parameters",
new ActionListener() {
public void actionPerformed(ActionEvent e) {
showHeapParametersPanel();
}
});
item.setMnemonic(KeyEvent.VK_H);
toolsMenu.add(item);
item = createMenuItem("Inspector",
new ActionListener() {
public void actionPerformed(ActionEvent e) {
showInspector(null);
}
});
item.setMnemonic(KeyEvent.VK_R);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, ActionEvent.ALT_MASK));
toolsMenu.add(item);
item = createMenuItem("Memory Viewer",
new ActionListener() {
public void actionPerformed(ActionEvent e) {
showMemoryViewer();
}
});
item.setMnemonic(KeyEvent.VK_M);
toolsMenu.add(item);
item = createMenuItem("Monitor Cache Dump",
new ActionListener() {
public void actionPerformed(ActionEvent e) {
showMonitorCacheDumpPanel();
}
});
item.setMnemonic(KeyEvent.VK_D);
toolsMenu.add(item);
item = createMenuItem("Object Histogram",
new ActionListener() {
public void actionPerformed(ActionEvent e) {
showObjectHistogram();
}
});
item.setMnemonic(KeyEvent.VK_O);
toolsMenu.add(item);
item = createMenuItem("Show System Properties",
new ActionListener() {
public void actionPerformed(ActionEvent e) {
showSystemProperties();
}
});
item.setMnemonic(KeyEvent.VK_S);
toolsMenu.add(item);
item = createMenuItem("Show VM Version",
new ActionListener() {
public void actionPerformed(ActionEvent e) {
showVMVersion();
}
});
item.setMnemonic(KeyEvent.VK_M);
toolsMenu.add(item);
item = createMenuItem("Show -XX flags",
new ActionListener() {
public void actionPerformed(ActionEvent e) {
showCommandLineFlags();
}
});
item.setMnemonic(KeyEvent.VK_X);
toolsMenu.add(item);
toolsMenu.setEnabled(false);
menuBar.add(toolsMenu);
//
// Windows menu
//
JMenu windowsMenu = new JMenu("Windows");
windowsMenu.setMnemonic(KeyEvent.VK_W);
item = createMenuItem("Console",
new ActionListener() {
public void actionPerformed(ActionEvent e) {
showConsole();
}
});
item.setMnemonic(KeyEvent.VK_C);
windowsMenu.add(item);
showDbgConsoleMenuItem = createMenuItem("Debugger Console",
new ActionListener() {
public void actionPerformed(ActionEvent e) {
showDebuggerConsole();
}
});
showDbgConsoleMenuItem.setMnemonic(KeyEvent.VK_D);
windowsMenu.add(showDbgConsoleMenuItem);
showDbgConsoleMenuItem.setEnabled(false);
menuBar.add(windowsMenu);
frame.setJMenuBar(menuBar);
desktop = new JDesktopPane();
frame.getContentPane().add(desktop);
GraphicsUtilities.reshapeToAspectRatio(frame, 4.0f/3.0f, 0.75f, Toolkit.getDefaultToolkit().getScreenSize());
GraphicsUtilities.centerInContainer(frame, Toolkit.getDefaultToolkit().getScreenSize());
frame.setVisible(true);
Runtime.getRuntime().addShutdownHook(new java.lang.Thread() {
public void run() {
detachDebugger();
}
});
if (pidText != null) {
attach(pidText);
} else if (execPath != null) {
attach(execPath, coreFilename);
}
}
// FIXME: merge showAttachDialog, showOpenCoreFileDialog, showConnectDialog
private void showAttachDialog() {
// FIXME: create filtered text field which only accepts numbers
setMenuItemsEnabled(attachMenuItems, false);
final JInternalFrame attachDialog = new JInternalFrame("Attach to HotSpot process");
attachDialog.getContentPane().setLayout(new BorderLayout());
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
attachDialog.setBackground(panel.getBackground());
panel.add(new JLabel("Enter process ID:"));
final JTextField pidTextField = new JTextField(10);
ActionListener attacher = new ActionListener() {
public void actionPerformed(ActionEvent e) {
attachDialog.setVisible(false);
desktop.remove(attachDialog);
workerThread.invokeLater(new Runnable() {
public void run() {
attach(pidTextField.getText());
}
});
}
};
pidTextField.addActionListener(attacher);
panel.add(pidTextField);
attachDialog.getContentPane().add(panel, BorderLayout.NORTH);
Box vbox = Box.createVerticalBox();
panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
JTextArea ta = new JTextArea(
"Enter the process ID of a currently-running HotSpot process. On " +
"Solaris and most Unix operating systems, this can be determined by " +
"typing \"ps -u <your username> | grep java\"; the process ID is the " +
"first number which appears on the resulting line. On Windows, the " +
"process ID is present in the Task Manager, which can be brought up " +
"while logged on to the desktop by pressing Ctrl-Alt-Delete.");
ta.setLineWrap(true);
ta.setWrapStyleWord(true);
ta.setEditable(false);
ta.setBackground(panel.getBackground());
panel.add(ta);
vbox.add(panel);
Box hbox = Box.createHorizontalBox();
hbox.add(Box.createGlue());
JButton button = new JButton("OK");
button.addActionListener(attacher);
hbox.add(button);
hbox.add(Box.createHorizontalStrut(20));
button = new JButton("Cancel");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
attachDialog.setVisible(false);
desktop.remove(attachDialog);
setMenuItemsEnabled(attachMenuItems, true);
}
});
hbox.add(button);
hbox.add(Box.createGlue());
panel = new JPanel();
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
panel.add(hbox);
vbox.add(panel);
attachDialog.getContentPane().add(vbox, BorderLayout.SOUTH);
desktop.add(attachDialog);
attachDialog.setSize(400, 300);
GraphicsUtilities.centerInContainer(attachDialog);
attachDialog.show();
pidTextField.requestFocus();
}
// FIXME: merge showAttachDialog, showOpenCoreFileDialog, showConnectDialog
private void showOpenCoreFileDialog() {
setMenuItemsEnabled(attachMenuItems, false);
final JInternalFrame dialog = new JInternalFrame("Open Core File");
dialog.getContentPane().setLayout(new BorderLayout());
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
dialog.setBackground(panel.getBackground());
Box hbox = Box.createHorizontalBox();
Box vbox = Box.createVerticalBox();
vbox.add(new JLabel("Path to core file:"));
vbox.add(new JLabel("Path to Java executable:"));
hbox.add(vbox);
vbox = Box.createVerticalBox();
final JTextField corePathField = new JTextField(40);
final JTextField execPathField = new JTextField(40);
vbox.add(corePathField);
vbox.add(execPathField);
hbox.add(vbox);
final JButton browseCorePath = new JButton("Browse ..");
final JButton browseExecPath = new JButton("Browse ..");
browseCorePath.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser(new File("."));
int retVal = fileChooser.showOpenDialog(dialog);
if (retVal == JFileChooser.APPROVE_OPTION) {
corePathField.setText(fileChooser.getSelectedFile().getPath());
}
}
});
browseExecPath.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser(new File("."));
int retVal = fileChooser.showOpenDialog(dialog);
if (retVal == JFileChooser.APPROVE_OPTION) {
execPathField.setText(fileChooser.getSelectedFile().getPath());
}
}
});
vbox = Box.createVerticalBox();
vbox.add(browseCorePath);
vbox.add(browseExecPath);
hbox.add(vbox);
panel.add(hbox);
dialog.getContentPane().add(panel, BorderLayout.NORTH);
ActionListener attacher = new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialog.setVisible(false);
desktop.remove(dialog);
workerThread.invokeLater(new Runnable() {
public void run() {
attach(execPathField.getText(), corePathField.getText());
}
});
}
};
corePathField.addActionListener(attacher);
execPathField.addActionListener(attacher);
vbox = Box.createVerticalBox();
panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
JTextArea ta = new JTextArea(
"Enter the full path names to the core file from a HotSpot process " +
"and the Java executable from which it came. The latter is typically " +
"located in the JDK/JRE directory under the directory " +
"jre/bin/<arch>/native_threads.");
ta.setLineWrap(true);
ta.setWrapStyleWord(true);
ta.setEditable(false);
ta.setBackground(panel.getBackground());
panel.add(ta);
vbox.add(panel);
hbox = Box.createHorizontalBox();
hbox.add(Box.createGlue());
JButton button = new JButton("OK");
button.addActionListener(attacher);
hbox.add(button);
hbox.add(Box.createHorizontalStrut(20));
button = new JButton("Cancel");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialog.setVisible(false);
desktop.remove(dialog);
setMenuItemsEnabled(attachMenuItems, true);
}
});
hbox.add(button);
hbox.add(Box.createGlue());
panel = new JPanel();
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
panel.add(hbox);
vbox.add(panel);
dialog.getContentPane().add(vbox, BorderLayout.SOUTH);
desktop.add(dialog);
dialog.setSize(500, 300);
GraphicsUtilities.centerInContainer(dialog);
dialog.show();
corePathField.requestFocus();
}
// FIXME: merge showAttachDialog, showOpenCoreFileDialog, showConnectDialog
private void showConnectDialog() {
// FIXME: create filtered text field which only accepts numbers
setMenuItemsEnabled(attachMenuItems, false);
final JInternalFrame dialog = new JInternalFrame("Connect to HotSpot Debug Server");
dialog.getContentPane().setLayout(new BorderLayout());
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
dialog.setBackground(panel.getBackground());
panel.add(new JLabel("Enter machine name:"));
final JTextField pidTextField = new JTextField(40);
ActionListener attacher = new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialog.setVisible(false);
desktop.remove(dialog);
workerThread.invokeLater(new Runnable() {
public void run() {
connect(pidTextField.getText());
}
});
}
};
pidTextField.addActionListener(attacher);
panel.add(pidTextField);
dialog.getContentPane().add(panel, BorderLayout.NORTH);
Box vbox = Box.createVerticalBox();
panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
JTextArea ta = new JTextArea(
"Enter the name of a machine on which the HotSpot \"Debug Server\" is " +
"running and is attached to a process or core file.");
ta.setLineWrap(true);
ta.setWrapStyleWord(true);
ta.setEditable(false);
ta.setBackground(panel.getBackground());
panel.add(ta);
vbox.add(panel);
Box hbox = Box.createHorizontalBox();
hbox.add(Box.createGlue());
JButton button = new JButton("OK");
button.addActionListener(attacher);
hbox.add(button);
hbox.add(Box.createHorizontalStrut(20));
button = new JButton("Cancel");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialog.setVisible(false);
desktop.remove(dialog);
setMenuItemsEnabled(attachMenuItems, true);
}
});
hbox.add(button);
hbox.add(Box.createGlue());
panel = new JPanel();
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
panel.add(hbox);
vbox.add(panel);
dialog.getContentPane().add(vbox, BorderLayout.SOUTH);
desktop.add(dialog);
dialog.setSize(400, 300);
GraphicsUtilities.centerInContainer(dialog);
dialog.show();
pidTextField.requestFocus();
}
public void showThreadOopInspector(JavaThread thread) {
showInspector(new OopTreeNodeAdapter(thread.getThreadObj(), null));
}
public void showInspector(SimpleTreeNode adapter) {
showPanel("Inspector", new Inspector(adapter), 1.0f, 0.65f);
}
public void showLiveness(Oop oop, LivenessPathList liveness) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
PrintStream tty = new PrintStream(bos);
int numPaths = liveness.size();
for (int i = 0; i < numPaths; i++) {
tty.println("Path " + (i + 1) + " of " + numPaths + ":");
liveness.get(i).printOn(tty);
}
JTextArea ta = new JTextArea(bos.toString());
ta.setLineWrap(true);
ta.setWrapStyleWord(true);
ta.setEditable(false);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
JScrollPane scroller = new JScrollPane();
scroller.getViewport().add(ta);
panel.add(scroller, BorderLayout.CENTER);
bos = new ByteArrayOutputStream();
tty = new PrintStream(bos);
tty.print("Liveness result for ");
Oop.printOopValueOn(oop, tty);
JInternalFrame frame = new JInternalFrame(bos.toString());
frame.setResizable(true);
frame.setClosable(true);
frame.setIconifiable(true);
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(panel, BorderLayout.CENTER);
frame.pack();
desktop.add(frame);
GraphicsUtilities.reshapeToAspectRatio(frame, 0.5f / 0.2f, 0.5f, frame.getParent().getSize());
frame.show();
}
private void fireComputeReversePtrs() {
// Possible this might have been computed elsewhere
if (VM.getVM().getRevPtrs() != null) {
computeRevPtrsMenuItem.setEnabled(false);
return;
}
workerThread.invokeLater(new Runnable() {
public void run() {
HeapProgress progress = new HeapProgress("Reverse Pointers Analysis");
try {
ReversePtrsAnalysis analysis = new ReversePtrsAnalysis();
analysis.setHeapProgressThunk(progress);
analysis.run();
computeRevPtrsMenuItem.setEnabled(false);
} catch (OutOfMemoryError e) {
final String errMsg = formatMessage(e.toString(), 80);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JOptionPane.showInternalMessageDialog(desktop,
"Error computing reverse pointers:" + errMsg,
"Error",
JOptionPane.WARNING_MESSAGE);
}
});
} finally {
// make sure the progress bar goes away
progress.heapIterationComplete();
}
}
});
}
// Simple struct containing signal information
class SignalInfo {
public int sigNum;
public String sigName;
}
// Need to have mutable vframe as well as visible memory panel
abstract class StackWalker implements Runnable {
protected JavaVFrame vf;
protected AnnotatedMemoryPanel annoPanel;
StackWalker(JavaVFrame vf, AnnotatedMemoryPanel annoPanel) {
this.vf = vf;
this.annoPanel = annoPanel;
}
}
public void showThreadStackMemory(final JavaThread thread) {
// dumpStack(thread);
JavaVFrame vframe = getLastJavaVFrame(thread);
if (vframe == null) {
JOptionPane.showInternalMessageDialog(desktop,
"Thread \"" + thread.getThreadName() +
"\" has no Java frames on its stack",
"Show Stack Memory",
JOptionPane.INFORMATION_MESSAGE);
return;
}
JInternalFrame stackFrame = new JInternalFrame("Stack Memory for " + thread.getThreadName());
stackFrame.getContentPane().setLayout(new BorderLayout());
stackFrame.setResizable(true);
stackFrame.setClosable(true);
stackFrame.setIconifiable(true);
final long addressSize = agent.getTypeDataBase().getAddressSize();
boolean is64Bit = (addressSize == 8);
// This is somewhat of a hack to guess a thread's stack limits since the
// JavaThread doesn't support this functionality. However it is nice in that
// it locks us into the active region of the thread's stack and not its
// theoretical limits.
//
sun.jvm.hotspot.runtime.Frame tmpFrame = thread.getCurrentFrameGuess();
Address sp = tmpFrame.getSP();
Address starting = sp;
Address maxSP = starting;
Address minSP = starting;
RegisterMap tmpMap = thread.newRegisterMap(false);
while ((tmpFrame != null) && (!tmpFrame.isFirstFrame())) {
tmpFrame = tmpFrame.sender(tmpMap);
if (tmpFrame != null) {
sp = tmpFrame.getSP();
if (sp != null) {
maxSP = AddressOps.max(maxSP, sp);
minSP = AddressOps.min(minSP, sp);
}
}
}
// It is useful to be able to see say +/- 8K on the current stack range
AnnotatedMemoryPanel annoMemPanel = new AnnotatedMemoryPanel(agent.getDebugger(), is64Bit, starting,
minSP.addOffsetTo(-8192),
maxSP.addOffsetTo( 8192));
stackFrame.getContentPane().add(annoMemPanel, BorderLayout.CENTER);
desktop.add(stackFrame);
GraphicsUtilities.reshapeToAspectRatio(stackFrame, 4.0f / 3.0f, 0.85f, stackFrame.getParent().getSize());
stackFrame.show();
// Stackmap computation for interpreted frames is expensive; do
// all stackwalking work in another thread for better GUI
// responsiveness
workerThread.invokeLater(new StackWalker(vframe, annoMemPanel) {
public void run() {
Address startAddr = null;
// As this is a debugger, we want to provide potential crash
// information to the user, i.e., by marking signal handler frames
// on the stack. Since this system is currently targeted at
// annotating the Java frames (interpreted or compiled) on the
// stack and not, for example, "external" frames (note the current
// absence of a PC-to-symbol lookup mechanism at the Debugger
// level), we want to mark any Java frames which were interrupted
// by a signal. We do this by making two passes over the stack,
// one which finds signal handler frames and puts the parent
// frames in a table and one which finds Java frames and if they
// are in the table indicates that they were interrupted by a signal.
Map interruptedFrameMap = new HashMap();
{
sun.jvm.hotspot.runtime.Frame tmpFrame = thread.getCurrentFrameGuess();
RegisterMap tmpMap = thread.newRegisterMap(false);
while ((tmpFrame != null) && (!tmpFrame.isFirstFrame())) {
if (tmpFrame.isSignalHandlerFrameDbg()) {
// Add some information to the map that we can extract later
sun.jvm.hotspot.runtime.Frame interruptedFrame = tmpFrame.sender(tmpMap);
SignalInfo info = new SignalInfo();
info.sigNum = tmpFrame.getSignalNumberDbg();
info.sigName = tmpFrame.getSignalNameDbg();
interruptedFrameMap.put(interruptedFrame, info);
}
tmpFrame = tmpFrame.sender(tmpMap);
}
}
while (vf != null) {
String anno = null;
JavaVFrame curVFrame = vf;
sun.jvm.hotspot.runtime.Frame curFrame = curVFrame.getFrame();
Method interpreterFrameMethod = null;
if (curVFrame.isInterpretedFrame()) {
anno = "Interpreted frame";
} else {
anno = "Compiled frame";
if (curVFrame.isDeoptimized()) {
anno += " (deoptimized)";
}
}
if (curVFrame.mayBeImpreciseDbg()) {
anno += "; information may be imprecise";
}
if (curVFrame.isInterpretedFrame()) {
// Find the codelet
InterpreterCodelet codelet = VM.getVM().getInterpreter().getCodeletContaining(curFrame.getPC());
String description = null;
if (codelet != null) {
description = codelet.getDescription();
}
if (description == null) {
anno += "\n(Unknown interpreter codelet)";
} else {
anno += "\nExecuting in codelet \"" + description + "\" at PC = " + curFrame.getPC();
}
} else if (curVFrame.isCompiledFrame()) {
anno += "\nExecuting at PC = " + curFrame.getPC();
}
if (startAddr == null) {
startAddr = curFrame.getSP();
}
// FIXME: some compiled frames with empty oop map sets have been
// found (for example, Vector's inner Enumeration class, method
// "hasMoreElements"). Not sure yet why these cases are showing
// up -- should be possible (though unlikely) for safepoint code
// to patch the return instruction of these methods and then
// later attempt to get an oop map for that instruction. For
// now, we warn if we find such a method.
boolean shouldSkipOopMaps = false;
if (curVFrame.isCompiledFrame()) {
CodeBlob cb = VM.getVM().getCodeCache().findBlob(curFrame.getPC());
OopMapSet maps = cb.getOopMaps();
if ((maps == null) || (maps.getSize() == 0)) {
shouldSkipOopMaps = true;
}
}
// Add signal information to annotation if necessary
SignalInfo sigInfo = (SignalInfo) interruptedFrameMap.get(curFrame);
if (sigInfo != null) {
// This frame took a signal and we need to report it.
anno = (anno + "\n*** INTERRUPTED BY SIGNAL " + Integer.toString(sigInfo.sigNum) +
" (" + sigInfo.sigName + ")");
}
JavaVFrame nextVFrame = curVFrame;
sun.jvm.hotspot.runtime.Frame nextFrame = curFrame;
do {
curVFrame = nextVFrame;
curFrame = nextFrame;
try {
Method method = curVFrame.getMethod();
if (interpreterFrameMethod == null && curVFrame.isInterpretedFrame()) {
interpreterFrameMethod = method;
}
int bci = curVFrame.getBCI();
String lineNumberAnno = "";
if (method.hasLineNumberTable()) {
if ((bci == DebugInformationRecorder.SYNCHRONIZATION_ENTRY_BCI) ||
(bci >= 0 && bci < method.getCodeSize())) {
lineNumberAnno = ", line " + method.getLineNumberFromBCI(bci);
} else {
lineNumberAnno = " (INVALID BCI)";
}
}
anno += "\n" + method.getMethodHolder().getName().asString() + "." +
method.getName().asString() + method.getSignature().asString() +
"\n@bci " + bci + lineNumberAnno;
} catch (Exception e) {
anno += "\n(ERROR while iterating vframes for frame " + curFrame + ")";
}
nextVFrame = curVFrame.javaSender();
if (nextVFrame != null) {
nextFrame = nextVFrame.getFrame();
}
} while (nextVFrame != null && nextFrame.equals(curFrame));
if (shouldSkipOopMaps) {
anno = anno + "\nNOTE: null or empty OopMapSet found for this CodeBlob";
}
if (curFrame.getFP() != null) {
annoPanel.addAnnotation(new Annotation(curFrame.getSP(),
curFrame.getFP(),
anno));
} else {
if (VM.getVM().getCPU().equals("x86") || VM.getVM().getCPU().equals("amd64")) {
// For C2, which has null frame pointers on x86/amd64
CodeBlob cb = VM.getVM().getCodeCache().findBlob(curFrame.getPC());
Address sp = curFrame.getSP();
if (Assert.ASSERTS_ENABLED) {
Assert.that(cb.getFrameSize() > 0, "CodeBlob must have non-zero frame size");
}
annoPanel.addAnnotation(new Annotation(sp,
sp.addOffsetTo(cb.getFrameSize()),
anno));
} else {
Assert.that(VM.getVM().getCPU().equals("ia64"), "only ia64 should reach here");
}
}
// Add interpreter frame annotations
if (curFrame.isInterpretedFrame()) {
annoPanel.addAnnotation(new Annotation(curFrame.addressOfInterpreterFrameExpressionStack(),
curFrame.addressOfInterpreterFrameTOS(),
"Interpreter expression stack"));
Address monBegin = curFrame.interpreterFrameMonitorBegin().address();
Address monEnd = curFrame.interpreterFrameMonitorEnd().address();
if (!monBegin.equals(monEnd)) {
annoPanel.addAnnotation(new Annotation(monBegin, monEnd,
"BasicObjectLocks"));
}
if (interpreterFrameMethod != null) {
// The offset is just to get the right stack slots highlighted in the output
int offset = 1;
annoPanel.addAnnotation(new Annotation(curFrame.addressOfInterpreterFrameLocal(offset),
curFrame.addressOfInterpreterFrameLocal((int) interpreterFrameMethod.getMaxLocals() + offset),
"Interpreter locals area for frame with SP = " + curFrame.getSP()));
}
String methodAnno = "Interpreter frame methodOop";
if (interpreterFrameMethod == null) {
methodAnno += " (BAD OOP)";
}
Address a = curFrame.addressOfInterpreterFrameMethod();
annoPanel.addAnnotation(new Annotation(a, a.addOffsetTo(addressSize), methodAnno));
a = curFrame.addressOfInterpreterFrameCPCache();
annoPanel.addAnnotation(new Annotation(a, a.addOffsetTo(addressSize), "Interpreter constant pool cache"));
}
RegisterMap rm = (RegisterMap) vf.getRegisterMap().clone();
if (!shouldSkipOopMaps) {
try {
curFrame.oopsDo(new AddressVisitor() {
public void visitAddress(Address addr) {
if (Assert.ASSERTS_ENABLED) {
Assert.that(addr.andWithMask(VM.getVM().getAddressSize() - 1) == null,
"Address " + addr + "should have been aligned");
}
OopHandle handle = addr.getOopHandleAt(0);
addAnnotation(addr, handle);
}
public void visitCompOopAddress(Address addr) {
if (Assert.ASSERTS_ENABLED) {
Assert.that(addr.andWithMask(VM.getVM().getAddressSize() - 1) == null,
"Address " + addr + "should have been aligned");
}
OopHandle handle = addr.getCompOopHandleAt(0);
addAnnotation(addr, handle);
}
public void addAnnotation(Address addr, OopHandle handle) {
// Check contents
String anno = "null oop";
if (handle != null) {
// Find location
CollectedHeap collHeap = VM.getVM().getUniverse().heap();
boolean bad = true;
anno = "BAD OOP";
if (collHeap instanceof GenCollectedHeap) {
GenCollectedHeap heap = (GenCollectedHeap) collHeap;
for (int i = 0; i < heap.nGens(); i++) {
if (heap.getGen(i).isIn(handle)) {
if (i == 0) {
anno = "NewGen ";
} else if (i == 1) {
anno = "OldGen ";
} else {
anno = "Gen " + i + " ";
}
bad = false;
break;
}
}
if (bad) {
// Try perm gen
if (heap.permGen().isIn(handle)) {
anno = "PermGen ";
bad = false;
}
}
} else if (collHeap instanceof ParallelScavengeHeap) {
ParallelScavengeHeap heap = (ParallelScavengeHeap) collHeap;
if (heap.youngGen().isIn(handle)) {
anno = "PSYoungGen ";
bad = false;
} else if (heap.oldGen().isIn(handle)) {
anno = "PSOldGen ";
bad = false;
} else if (heap.permGen().isIn(handle)) {
anno = "PSPermGen ";
bad = false;
}
} else {
// Optimistically assume the oop isn't bad
anno = "[Unknown generation] ";
bad = false;
}
if (!bad) {
try {
Oop oop = VM.getVM().getObjectHeap().newOop(handle);
if (oop instanceof Instance) {
// Java-level objects always have workable names
anno = anno + oop.getKlass().getName().asString();
} else {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
Oop.printOopValueOn(oop, new PrintStream(bos));
anno = anno + bos.toString();
}
}
catch (AddressException e) {
anno += "CORRUPT OOP";
}
catch (NullPointerException e) {
anno += "CORRUPT OOP (null pointer)";
}
}
}
annoPanel.addAnnotation(new Annotation(addr, addr.addOffsetTo(addressSize), anno));
}
}, rm);
} catch (Exception e) {
System.err.println("Error while performing oopsDo for frame " + curFrame);
e.printStackTrace();
}
}
vf = nextVFrame;
}
// This used to paint as we walked the frames. This caused the display to be refreshed
// enough to be annoying on remote displays. It also would cause the annotations to
// be displayed in varying order which caused some annotations to overwrite others
// depending on the races between painting and adding annotations. This latter problem
// still exists to some degree but moving this code here definitely seems to reduce it
annoPanel.makeVisible(startAddr);
annoPanel.repaint();
}
});
}
/** NOTE we are in a different thread here than either the main
thread or the Swing/AWT event handler thread, so we must be very
careful when creating or removing widgets */
private void attach(String pidText) {
try {
this.pidText = pidText;
pid = Integer.parseInt(pidText);
}
catch (NumberFormatException e) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
setMenuItemsEnabled(attachMenuItems, true);
JOptionPane.showInternalMessageDialog(desktop,
"Unable to parse process ID \"" + HSDB.this.pidText + "\".\nPlease enter a number.",
"Parse error",
JOptionPane.WARNING_MESSAGE);
}
});
return;
}
// Try to attach to this process
Runnable remover = new Runnable() {
public void run() {
attachWaitDialog.setVisible(false);
desktop.remove(attachWaitDialog);
attachWaitDialog = null;
}
};
try {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JOptionPane pane = new JOptionPane("Attaching to process " + pid + ", please wait...", JOptionPane.INFORMATION_MESSAGE);
pane.setOptions(new Object[] {});
attachWaitDialog = pane.createInternalFrame(desktop, "Attaching to Process");
attachWaitDialog.show();
}
});
// FIXME: display exec'd debugger's output messages during this
// lengthy call
agent.attach(pid);
if (agent.getDebugger().hasConsole()) {
showDbgConsoleMenuItem.setEnabled(true);
}
attached = true;
SwingUtilities.invokeLater(remover);
}
catch (DebuggerException e) {
SwingUtilities.invokeLater(remover);
final String errMsg = formatMessage(e.getMessage(), 80);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
setMenuItemsEnabled(attachMenuItems, true);
JOptionPane.showInternalMessageDialog(desktop,
"Unable to connect to process ID " + pid + ":\n\n" + errMsg,
"Unable to Connect",
JOptionPane.WARNING_MESSAGE);
}
});
agent.detach();
return;
}
// OK, the VM should be available. Create the Threads dialog.
showThreadsDialog();
}
/** NOTE we are in a different thread here than either the main
thread or the Swing/AWT event handler thread, so we must be very
careful when creating or removing widgets */
private void attach(final String executablePath, final String corePath) {
// Try to open this core file
Runnable remover = new Runnable() {
public void run() {
attachWaitDialog.setVisible(false);
desktop.remove(attachWaitDialog);
attachWaitDialog = null;
}
};
try {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JOptionPane pane = new JOptionPane("Opening core file, please wait...", JOptionPane.INFORMATION_MESSAGE);
pane.setOptions(new Object[] {});
attachWaitDialog = pane.createInternalFrame(desktop, "Opening Core File");
attachWaitDialog.show();
}
});
// FIXME: display exec'd debugger's output messages during this
// lengthy call
agent.attach(executablePath, corePath);
if (agent.getDebugger().hasConsole()) {
showDbgConsoleMenuItem.setEnabled(true);
}
attached = true;
SwingUtilities.invokeLater(remover);
}
catch (DebuggerException e) {
SwingUtilities.invokeLater(remover);
final String errMsg = formatMessage(e.getMessage(), 80);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
setMenuItemsEnabled(attachMenuItems, true);
JOptionPane.showInternalMessageDialog(desktop,
"Unable to open core file\n" + corePath + ":\n\n" + errMsg,
"Unable to Open Core File",
JOptionPane.WARNING_MESSAGE);
}
});
agent.detach();
return;
}
// OK, the VM should be available. Create the Threads dialog.
showThreadsDialog();
}
/** NOTE we are in a different thread here than either the main
thread or the Swing/AWT event handler thread, so we must be very
careful when creating or removing widgets */
private void connect(final String remoteMachineName) {
// Try to open this core file
Runnable remover = new Runnable() {
public void run() {
attachWaitDialog.setVisible(false);
desktop.remove(attachWaitDialog);
attachWaitDialog = null;
}
};
try {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JOptionPane pane = new JOptionPane("Connecting to debug server, please wait...", JOptionPane.INFORMATION_MESSAGE);
pane.setOptions(new Object[] {});
attachWaitDialog = pane.createInternalFrame(desktop, "Connecting to Debug Server");
attachWaitDialog.show();
}
});
agent.attach(remoteMachineName);
if (agent.getDebugger().hasConsole()) {
showDbgConsoleMenuItem.setEnabled(true);
}
attached = true;
SwingUtilities.invokeLater(remover);
}
catch (DebuggerException e) {
SwingUtilities.invokeLater(remover);
final String errMsg = formatMessage(e.getMessage(), 80);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
setMenuItemsEnabled(attachMenuItems, true);
JOptionPane.showInternalMessageDialog(desktop,
"Unable to connect to machine \"" + remoteMachineName + "\":\n\n" + errMsg,
"Unable to Connect",
JOptionPane.WARNING_MESSAGE);
}
});
agent.detach();
return;
}
// OK, the VM should be available. Create the Threads dialog.
showThreadsDialog();
}
private void detachDebugger() {
if (!attached) {
return;
}
agent.detach();
attached = false;
}
private void detach() {
detachDebugger();
attachWaitDialog = null;
threadsFrame = null;
consoleFrame = null;
setMenuItemsEnabled(attachMenuItems, true);
setMenuItemsEnabled(detachMenuItems, false);
toolsMenu.setEnabled(false);
showDbgConsoleMenuItem.setEnabled(false);
// FIXME: is this sufficient, or will I have to do anything else
// to the components to kill them off? What about WorkerThreads?
desktop.removeAll();
desktop.invalidate();
desktop.validate();
desktop.repaint();
}
/** NOTE that this is called from another thread than the main or
Swing thread and we have to be careful about synchronization */
private void showThreadsDialog() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
threadsFrame = new JInternalFrame("Java Threads");
threadsFrame.setResizable(true);
threadsFrame.setIconifiable(true);
JavaThreadsPanel threadsPanel = new JavaThreadsPanel();
threadsPanel.addPanelListener(HSDB.this);
threadsFrame.getContentPane().add(threadsPanel);
threadsFrame.setSize(500, 300);
threadsFrame.pack();
desktop.add(threadsFrame);
GraphicsUtilities.moveToInContainer(threadsFrame, 0.75f, 0.25f, 0, 20);
threadsFrame.show();
setMenuItemsEnabled(attachMenuItems, false);
setMenuItemsEnabled(detachMenuItems, true);
toolsMenu.setEnabled(true);
VM.registerVMInitializedObserver(new Observer() {
public void update(Observable o, Object data) {
computeRevPtrsMenuItem.setEnabled(true);
}
});
}
});
}
private void showObjectHistogram() {
sun.jvm.hotspot.oops.ObjectHistogram histo = new sun.jvm.hotspot.oops.ObjectHistogram();
ObjectHistogramCleanupThunk cleanup =
new ObjectHistogramCleanupThunk(histo);
doHeapIteration("Object Histogram",
"Generating histogram...",
histo,
cleanup);
}
class ObjectHistogramCleanupThunk implements CleanupThunk {
sun.jvm.hotspot.oops.ObjectHistogram histo;
ObjectHistogramCleanupThunk(sun.jvm.hotspot.oops.ObjectHistogram histo) {
this.histo = histo;
}
public void heapIterationComplete() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JInternalFrame histoFrame = new JInternalFrame("Object Histogram");
histoFrame.setResizable(true);
histoFrame.setClosable(true);
histoFrame.setIconifiable(true);
histoFrame.getContentPane().setLayout(new BorderLayout());
ObjectHistogramPanel panel = new ObjectHistogramPanel(histo);
panel.addPanelListener(HSDB.this);
histoFrame.getContentPane().add(panel);
desktop.add(histoFrame);
GraphicsUtilities.reshapeToAspectRatio(histoFrame, 4.0f / 3.0f, 0.6f,
histoFrame.getParent().getSize());
GraphicsUtilities.centerInContainer(histoFrame);
histoFrame.show();
}
});
}
}
public void showObjectsOfType(Klass type) {
FindObjectByType finder = new FindObjectByType(type);
FindObjectByTypeCleanupThunk cleanup =
new FindObjectByTypeCleanupThunk(finder);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
type.printValueOn(new PrintStream(bos));
String typeName = bos.toString();
doHeapIteration("Show Objects Of Type",
"Finding instances of \"" + typeName + "\"",
finder,
cleanup);
}
class FindObjectByTypeCleanupThunk implements CleanupThunk {
FindObjectByType finder;
FindObjectByTypeCleanupThunk(FindObjectByType finder) {
this.finder = finder;
}
public void heapIterationComplete() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JInternalFrame finderFrame = new JInternalFrame("Show Objects of Type");
finderFrame.getContentPane().setLayout(new BorderLayout());
finderFrame.setResizable(true);
finderFrame.setClosable(true);
finderFrame.setIconifiable(true);
ObjectListPanel panel = new ObjectListPanel(finder.getResults(),
new HeapProgress("Reverse Pointers Analysis"));
panel.addPanelListener(HSDB.this);
finderFrame.getContentPane().add(panel);
desktop.add(finderFrame);
GraphicsUtilities.reshapeToAspectRatio(finderFrame, 4.0f / 3.0f, 0.6f,
finderFrame.getParent().getSize());
GraphicsUtilities.centerInContainer(finderFrame);
finderFrame.show();
}
});
}
}
private void showDebuggerConsole() {
if (consoleFrame == null) {
consoleFrame = new JInternalFrame("Debugger Console");
consoleFrame.setResizable(true);
consoleFrame.setClosable(true);
consoleFrame.setIconifiable(true);
consoleFrame.getContentPane().setLayout(new BorderLayout());
consoleFrame.getContentPane().add(new DebuggerConsolePanel(agent.getDebugger()), BorderLayout.CENTER);
GraphicsUtilities.reshapeToAspectRatio(consoleFrame, 5.0f, 0.9f, desktop.getSize());
}
if (consoleFrame.getParent() == null) {
desktop.add(consoleFrame);
}
consoleFrame.setVisible(true);
consoleFrame.show();
consoleFrame.getContentPane().getComponent(0).requestFocus();
}
private void showConsole() {
CommandProcessor.DebuggerInterface di = new CommandProcessor.DebuggerInterface() {
public HotSpotAgent getAgent() {
return agent;
}
public boolean isAttached() {
return attached;
}
public void attach(String pid) {
attach(pid);
}
public void attach(String java, String core) {
}
public void detach() {
detachDebugger();
}
public void reattach() {
if (attached) {
detachDebugger();
}
if (pidText != null) {
attach(pidText);
} else {
attach(execPath, coreFilename);
}
}
};
showPanel("Command Line", new CommandProcessorPanel(new CommandProcessor(di, null, null, null)));
}
private void showFindByQueryPanel() {
showPanel("Find Object by Query", new FindByQueryPanel());
}
private void showFindPanel() {
showPanel("Find Pointer", new FindPanel());
}
private void showFindInHeapPanel() {
showPanel("Find Address In Heap", new FindInHeapPanel());
}
private void showFindInCodeCachePanel() {
showPanel("Find Address In Code Cache", new FindInCodeCachePanel());
}
private void showHeapParametersPanel() {
showPanel("Heap Parameters", new HeapParametersPanel());
}
public void showThreadInfo(final JavaThread thread) {
showPanel("Info for " + thread.getThreadName(), new ThreadInfoPanel(thread));
}
public void showJavaStackTrace(final JavaThread thread) {
JavaStackTracePanel jstp = new JavaStackTracePanel();
showPanel("Java stack trace for " + thread.getThreadName(), jstp);
jstp.setJavaThread(thread);
}
private void showDeadlockDetectionPanel() {
showPanel("Deadlock Detection", new DeadlockDetectionPanel());
}
private void showMonitorCacheDumpPanel() {
showPanel("Monitor Cache Dump", new MonitorCacheDumpPanel());
}
public void showClassBrowser() {
final JInternalFrame progressFrame = new JInternalFrame("Class Browser");
progressFrame.setResizable(true);
progressFrame.setClosable(true);
progressFrame.setIconifiable(true);
progressFrame.getContentPane().setLayout(new BorderLayout());
final ProgressBarPanel bar = new ProgressBarPanel("Generating class list ..");
bar.setIndeterminate(true);
progressFrame.getContentPane().add(bar, BorderLayout.CENTER);
desktop.add(progressFrame);
progressFrame.pack();
GraphicsUtilities.centerInContainer(progressFrame);
progressFrame.show();
workerThread.invokeLater(new Runnable() {
public void run() {
HTMLGenerator htmlGen = new HTMLGenerator();
InstanceKlass[] klasses = SystemDictionaryHelper.getAllInstanceKlasses();
final String htmlText = htmlGen.genHTMLForKlassNames(klasses);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JInternalFrame cbFrame = new JInternalFrame("Class Browser");
cbFrame.getContentPane().setLayout(new BorderLayout());
cbFrame.setResizable(true);
cbFrame.setClosable(true);
cbFrame.setIconifiable(true);
ClassBrowserPanel cbPanel = new ClassBrowserPanel();
cbFrame.getContentPane().add(cbPanel, BorderLayout.CENTER);
desktop.remove(progressFrame);
desktop.repaint();
desktop.add(cbFrame);
GraphicsUtilities.reshapeToAspectRatio(cbFrame, 1.25f, 0.85f,
cbFrame.getParent().getSize());
cbFrame.show();
cbPanel.setClassesText(htmlText);
}
});
}
});
}
public void showCodeViewer() {
showPanel("Code Viewer", new CodeViewerPanel(), 1.25f, 0.85f);
}
public void showCodeViewer(final Address address) {
final CodeViewerPanel panel = new CodeViewerPanel();
showPanel("Code Viewer", panel, 1.25f, 0.85f);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
panel.viewAddress(address);
}
});
}
public void showMemoryViewer() {
showPanel("Memory Viewer", new MemoryViewer(agent.getDebugger(), agent.getTypeDataBase().getAddressSize() == 8));
}
public void showCommandLineFlags() {
showPanel("Command Line Flags", new VMFlagsPanel());
}
public void showVMVersion() {
showPanel("VM Version Info", new VMVersionInfoPanel());
}
public void showSystemProperties() {
showPanel("System Properties", new SysPropsPanel());
}
private void showPanel(String name, JPanel panel) {
showPanel(name, panel, 5.0f / 3.0f, 0.4f);
}
private void showPanel(String name, JPanel panel, float aspectRatio, float fillRatio) {
JInternalFrame frame = new JInternalFrame(name);
frame.getContentPane().setLayout(new BorderLayout());
frame.setResizable(true);
frame.setClosable(true);
frame.setIconifiable(true);
frame.setMaximizable(true);
frame.getContentPane().add(panel, BorderLayout.CENTER);
desktop.add(frame);
GraphicsUtilities.reshapeToAspectRatio(frame, aspectRatio, fillRatio, frame.getParent().getSize());
GraphicsUtilities.randomLocation(frame);
frame.show();
if (panel instanceof SAPanel) {
((SAPanel)panel).addPanelListener(this);
}
}
//--------------------------------------------------------------------------------
// Framework for heap iteration with progress bar
//
interface CleanupThunk {
public void heapIterationComplete();
}
class HeapProgress implements HeapProgressThunk {
private JInternalFrame frame;
private ProgressBarPanel bar;
private String windowTitle;
private String progressBarTitle;
private CleanupThunk cleanup;
HeapProgress(String windowTitle) {
this(windowTitle, "Percentage of heap visited", null);
}
HeapProgress(String windowTitle, String progressBarTitle) {
this(windowTitle, progressBarTitle, null);
}
HeapProgress(String windowTitle, String progressBarTitle, CleanupThunk cleanup) {
this.windowTitle = windowTitle;
this.progressBarTitle = progressBarTitle;
this.cleanup = cleanup;
}
public void heapIterationFractionUpdate(final double fractionOfHeapVisited) {
if (frame == null) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
frame = new JInternalFrame(windowTitle);
frame.setResizable(true);
frame.setIconifiable(true);
frame.getContentPane().setLayout(new BorderLayout());
bar = new ProgressBarPanel(progressBarTitle);
frame.getContentPane().add(bar, BorderLayout.CENTER);
desktop.add(frame);
frame.pack();
GraphicsUtilities.constrainToSize(frame, frame.getParent().getSize());
GraphicsUtilities.centerInContainer(frame);
frame.show();
}
});
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
bar.setValue(fractionOfHeapVisited);
}
});
}
public void heapIterationComplete() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
desktop.remove(frame);
desktop.repaint();
if (VM.getVM().getRevPtrs() != null) {
// Ended up computing reverse pointers as a side-effect
computeRevPtrsMenuItem.setEnabled(false);
}
}
});
if (cleanup != null) {
cleanup.heapIterationComplete();
}
}
}
class VisitHeap implements Runnable {
HeapVisitor visitor;
VisitHeap(HeapVisitor visitor) {
this.visitor = visitor;
}
public void run() {
VM.getVM().getObjectHeap().iterate(visitor);
}
}
private void doHeapIteration(String frameTitle,
String progressBarText,
HeapVisitor visitor,
CleanupThunk cleanup) {
sun.jvm.hotspot.oops.ObjectHistogram histo = new sun.jvm.hotspot.oops.ObjectHistogram();
HeapProgress progress = new HeapProgress(frameTitle,
progressBarText,
cleanup);
HeapVisitor progVisitor = new ProgressiveHeapVisitor(visitor, progress);
workerThread.invokeLater(new VisitHeap(progVisitor));
}
//--------------------------------------------------------------------------------
// Stack trace helper
//
private static JavaVFrame getLastJavaVFrame(JavaThread cur) {
RegisterMap regMap = cur.newRegisterMap(true);
sun.jvm.hotspot.runtime.Frame f = cur.getCurrentFrameGuess();
if (f == null) return null;
boolean imprecise = true;
if (f.isInterpretedFrame() && !f.isInterpretedFrameValid()) {
System.err.println("Correcting for invalid interpreter frame");
f = f.sender(regMap);
imprecise = false;
}
VFrame vf = VFrame.newVFrame(f, regMap, cur, true, imprecise);
if (vf == null) {
System.err.println(" (Unable to create vframe for topmost frame guess)");
return null;
}
if (vf.isJavaFrame()) {
return (JavaVFrame) vf;
}
return (JavaVFrame) vf.javaSender();
}
// Internal routine for debugging
private static void dumpStack(JavaThread cur) {
RegisterMap regMap = cur.newRegisterMap(true);
sun.jvm.hotspot.runtime.Frame f = cur.getCurrentFrameGuess();
PrintStream tty = System.err;
while (f != null) {
tty.print("Found ");
if (f.isInterpretedFrame()) { tty.print("interpreted"); }
else if (f.isCompiledFrame()) { tty.print("compiled"); }
else if (f.isEntryFrame()) { tty.print("entry"); }
else if (f.isNativeFrame()) { tty.print("native"); }
else if (f.isGlueFrame()) { tty.print("glue"); }
else { tty.print("external"); }
tty.print(" frame with PC = " + f.getPC() + ", SP = " + f.getSP() + ", FP = " + f.getFP());
if (f.isSignalHandlerFrameDbg()) {
tty.print(" (SIGNAL HANDLER)");
}
tty.println();
if (!f.isFirstFrame()) {
f = f.sender(regMap);
} else {
f = null;
}
}
}
//--------------------------------------------------------------------------------
// Component utilities
//
private static JMenuItem createMenuItem(String name, ActionListener l) {
JMenuItem item = new JMenuItem(name);
item.addActionListener(l);
return item;
}
/** Punctuates the given string with \n's where necessary to not
exceed the given number of characters per line. Strips
extraneous whitespace. */
private String formatMessage(String message, int charsPerLine) {
StringBuffer buf = new StringBuffer(message.length());
StringTokenizer tokenizer = new StringTokenizer(message);
int curLineLength = 0;
while (tokenizer.hasMoreTokens()) {
String tok = tokenizer.nextToken();
if (curLineLength + tok.length() > charsPerLine) {
buf.append('\n');
curLineLength = 0;
} else {
if (curLineLength != 0) {
buf.append(' ');
++curLineLength;
}
}
buf.append(tok);
curLineLength += tok.length();
}
return buf.toString();
}
private void setMenuItemsEnabled(java.util.List items, boolean enabled) {
for (Iterator iter = items.iterator(); iter.hasNext(); ) {
((JMenuItem) iter.next()).setEnabled(enabled);
}
}
}
| 39.382435 | 149 | 0.560022 |
104c33b9a3386993dc6059b4d83b91dbf103a75a | 1,637 | package com.cart4j.auth.service.impl;
import com.cart4j.auth.Cart4jAuthApp;
import com.cart4j.auth.service.ClientService;
import com.cart4j.model.security.dto.v1.ClientDto;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {Cart4jAuthApp.class})
@ActiveProfiles("test")
public class ClientServiceImplTest {
@Test
public void test_persistFunction() {
ClientDto client = ClientDto.builder()
.clientUniqueId("TEST_1")
.clientSecret("12345")
.grantTypes("password")
.build();
client = clientService.addClient(client);
assertThat(client.getId()).isNotNull();
ClientDto updating = ClientDto.builder()
.clientUniqueId("TEST_2")
.build();
updating = clientService.editClient(client.getId(), updating);
// Does not allow to change the client unique id
assertThat(updating.getClientUniqueId()).isEqualTo("TEST_1");
clientService.deleteClient(updating.getId());
assertThat(clientService.getClient(updating.getId())).isNull();
}
@Autowired
PasswordEncoder passwordEncoder;
@Autowired
ClientService clientService;
}
| 33.408163 | 71 | 0.714111 |
a6c191fc203f27169ec9fc3186a23f827886b846 | 907 | package info.novatec.tr.websocket;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(myHandler(), "/webSocket").addInterceptors(new HttpSessionHandshakeInterceptor());
}
@Bean
public WebSocketHandler myHandler() {
return new TokenRunWebSocketHandler();
}
} | 36.28 | 104 | 0.848953 |
db718bdca9067787f7277972d7e8a833222c49b9 | 3,299 | /*
* Copyright (c) 2013, Cloudera, Inc. All Rights Reserved.
*
* Cloudera, Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* This software 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.cloudera.oryx.kmeans.computation.evaluate;
import com.cloudera.oryx.common.servcomp.Namespaces;
import com.cloudera.oryx.common.settings.ConfigUtils;
import com.cloudera.oryx.computation.common.JobStepConfig;
import com.cloudera.oryx.kmeans.computation.KMeansJobStep;
import com.cloudera.oryx.kmeans.computation.MLAvros;
import com.cloudera.oryx.kmeans.computation.cluster.ClusterSettings;
import com.cloudera.oryx.kmeans.computation.types.KMeansTypes;
import com.typesafe.config.Config;
import org.apache.commons.math3.linear.RealVector;
import org.apache.crunch.PCollection;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.lib.PTables;
import org.apache.crunch.types.avro.Avros;
import java.io.IOException;
public final class VoronoiPartitionStep extends KMeansJobStep {
@Override
protected MRPipeline createPipeline() throws IOException {
JobStepConfig stepConfig = getConfig();
Config config = ConfigUtils.getDefaultConfig();
ClusterSettings clusterSettings = ClusterSettings.create(config);
String instanceDir = stepConfig.getInstanceDir();
int generationID = stepConfig.getGenerationID();
String prefix = Namespaces.getInstanceGenerationPrefix(instanceDir, generationID);
String outputKey = prefix + "weighted/";
if (!validOutputPath(outputKey)) {
return null;
}
String indexKey = prefix + "sketch/" + clusterSettings.getSketchIterations();
String inputKey = prefix + "normalized/";
MRPipeline p = createBasicPipeline(ClosestSketchVectorFn.class);
// first I compute the weight of each k-sketch vector, i.e., Voronoi partition
// I aggregate all together and persist on disk
// PCollection<ClosestSketchVectorData> weights = inputPairs(p, inputKey, MLAvros.vector())
PCollection<ClosestSketchVectorData> weights = PTables.asPTable(inputPairs(p, inputKey, MLAvros.vector())
.parallelDo("computingSketchVectorWeights",
new ClosestSketchVectorFn<RealVector>(indexKey, clusterSettings),
Avros.pairs(Avros.ints(), Avros.reflects(ClosestSketchVectorData.class))))
.groupByKey(1)
.combineValues(new ClosestSketchVectorAggregator(clusterSettings))
.values()
.write(avroOutput(outputKey + "kSketchVectorWeights/"));
// this "pipeline" takes a single ClosestSketchVectorData and returns weighted vectors
// could be done outside MapReduce, but that would require me to materialize the ClosestSketchVectorData
weights.parallelDo(
"generatingWeightedSketchVectors",
new WeightVectorsFn(indexKey),
KMeansTypes.FOLD_WEIGHTED_VECTOR)
.write(avroOutput(outputKey + "weightedKSketchVectors/"));
return p;
}
}
| 42.844156 | 109 | 0.756896 |
f8cac5a1d2e05db441e59a62f2f1c89f51980221 | 5,685 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.jci2;
import java.io.File;
import org.apache.commons.jci2.classes.ExtendedDump;
import org.apache.commons.jci2.classes.SimpleDump;
import org.apache.commons.jci2.listeners.ReloadingListener;
import org.apache.commons.jci2.monitor.FilesystemAlterationMonitor;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
*
* @author tcurdt
*/
public final class ReloadingClassLoaderTestCase extends AbstractTestCase {
private final Log log = LogFactory.getLog(ReloadingClassLoaderTestCase.class);
private ReloadingClassLoader classloader;
private ReloadingListener listener;
private FilesystemAlterationMonitor fam;
private final byte[] clazzSimple1;
private final byte[] clazzSimple2;
private final byte[] clazzExtended;
public ReloadingClassLoaderTestCase() throws Exception {
clazzSimple1 = SimpleDump.dump("Simple1");
clazzSimple2 = SimpleDump.dump("Simple2");
clazzExtended = ExtendedDump.dump();
assertTrue(clazzSimple1.length > 0);
assertTrue(clazzSimple2.length > 0);
assertTrue(clazzExtended.length > 0);
}
@Override
protected void setUp() throws Exception {
super.setUp();
classloader = new ReloadingClassLoader(this.getClass().getClassLoader());
listener = new ReloadingListener();
listener.addReloadNotificationListener(classloader);
fam = new FilesystemAlterationMonitor();
fam.addListener(directory, listener);
fam.start();
}
public void testCreate() throws Exception {
listener.waitForFirstCheck();
log.debug("creating class");
writeFile("jci2/Simple.class", clazzSimple1);
listener.waitForCheck();
final Object simple = classloader.loadClass("jci2.Simple").newInstance();
assertEquals("Simple1", simple.toString());
}
public void testChange() throws Exception {
listener.waitForFirstCheck();
log.debug("creating class");
writeFile("jci2/Simple.class", clazzSimple1);
listener.waitForCheck();
final Object simple1 = classloader.loadClass("jci2.Simple").newInstance();
assertEquals("Simple1", simple1.toString());
log.debug("changing class");
writeFile("jci2/Simple.class", clazzSimple2);
listener.waitForEvent();
final Object simple2 = classloader.loadClass("jci2.Simple").newInstance();
assertEquals("Simple2", simple2.toString());
}
public void testDelete() throws Exception {
listener.waitForFirstCheck();
log.debug("creating class");
writeFile("jci2/Simple.class", clazzSimple1);
listener.waitForCheck();
final Object simple = classloader.loadClass("jci2.Simple").newInstance();
assertEquals("Simple1", simple.toString());
log.debug("deleting class");
assertTrue(new File(directory, "jci2/Simple.class").delete());
listener.waitForEvent();
try {
classloader.loadClass("jci2.Simple").newInstance();
fail();
} catch(final ClassNotFoundException e) {
assertEquals("jci2.Simple", e.getMessage());
}
}
public void testDeleteDependency() throws Exception {
listener.waitForFirstCheck();
log.debug("creating classes");
writeFile("jci2/Simple.class", clazzSimple1);
writeFile("jci2/Extended.class", clazzExtended);
listener.waitForCheck();
final Object simple = classloader.loadClass("jci2.Simple").newInstance();
assertEquals("Simple1", simple.toString());
final Object extended = classloader.loadClass("jci2.Extended").newInstance();
assertEquals("Extended:Simple1", extended.toString());
log.debug("deleting class dependency");
assertTrue(new File(directory, "jci2/Simple.class").delete());
listener.waitForEvent();
try {
classloader.loadClass("jci2.Extended").newInstance();
fail();
} catch(final NoClassDefFoundError e) {
assertEquals("jci2/Simple", e.getMessage());
}
}
public void testClassNotFound() {
try {
classloader.loadClass("bla");
fail();
} catch(final ClassNotFoundException e) {
}
}
public void testDelegation() {
classloader.clearAssertionStatus();
classloader.setClassAssertionStatus("org.apache.commons.jci2.ReloadingClassLoader", true);
classloader.setDefaultAssertionStatus(false);
classloader.setPackageAssertionStatus("org.apache.commons.jci2", true);
// FIXME: compare with delegation
}
@Override
protected void tearDown() throws Exception {
fam.removeListener(listener);
fam.stop();
super.tearDown();
}
}
| 33.639053 | 98 | 0.675989 |
5634c4808f445003756f325203d1c70b9457e05a | 10,865 | /*
* #%L
* OW2 Chameleon - Fuchsia Framework
* %%
* Copyright (C) 2009 - 2014 OW2 Chameleon
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
/*
Calimero - A library for KNX network access
Copyright (C) 2006-2008 B. Malinowsky
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or at your option any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under terms
of your choice, provided that you also meet, for each linked independent
module, the terms and conditions of the license of that module. An
independent module is a module which is not derived from or based on
this library. If you modify this library, you may extend this exception
to your version of the library, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from your
version.
*/
package tuwien.auto.calimero.log;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Calendar;
/**
* LogWriter using a {@link Writer} for output.
* <p>
* An existing output stream has to be supplied on creation of this LogWriter. All output
* will be checked against the internal log level, on logging permitted the output is
* formatted (optional) and handed to the underlying writer.<br>
* Output is not automatically flushed after each write by default.<br>
* Using <code>autoFlush = true</code> in the constructor ensures that no data buffering
* will delay the output. Note that this may degrade performance.<br>
* For occasional flushing use {@link #flush()} manually.
*
* @author B. Malinowsky
*/
public class LogStreamWriter extends LogWriter
{
/** Calendar used to generate date/time of logged output message. */
protected static final Calendar c = Calendar.getInstance();
/**
* Set the formatting behavior of <code>LogStreamWriter</code>.
* <p>
* Determines if <code>LogStreamWriter</code> should call
* {@link #formatOutput(String, LogLevel, String, Throwable) formatOutput(LogLevel,
* String, Throwable)} before writing out the log message. Defaults to
* <code>true</code>, but might be set to <code>false</code> by subtypes if
* message given to <code>write</code> is already formatted.
*/
protected boolean formatOutput = true;
/**
* Line separator, retrieved from the property "line.separator" and set in the
* constructor.
*/
protected String lineSep;
boolean autoFlush;
private Writer out;
/**
* Sets line separator; also called by subtypes creating the output stream on their
* own.
*/
protected LogStreamWriter()
{
try {
lineSep = System.getProperty("line.separator");
}
catch (final SecurityException e) {}
if (lineSep == null)
lineSep = "\n";
}
/**
* Creates a <code>LogStreamWriter</code> with specified output stream.
* <p>
* The output stream is wrapped by a BufferedWriter.
*
* @param os an OutputStream used by this LogStreamWriter
*/
public LogStreamWriter(OutputStream os)
{
this();
createWriter(os);
}
/**
* Creates a <code>LogStreamWriter</code> with specified log level and output
* stream.
*
* @param level log level assigned with this <code>LogStreamWriter</code>
* @param os an OutputStream used by this <code>LogStreamWriter</code>
* @see #LogStreamWriter(OutputStream)
*/
public LogStreamWriter(LogLevel level, OutputStream os)
{
this(os);
setLogLevel(level);
}
/**
* Creates a <code>LogStreamWriter</code> with specified log level and output
* stream. Parameter <code>autoFlush</code> sets flushing behavior on write() calls.
*
* @param level log level assigned with this <code>LogStreamWriter</code>
* @param os an OutputStream used by this <code>LogStreamWriter</code>
* @param autoFlush flush output after every successful call to write()
* @see #LogStreamWriter(LogLevel, OutputStream)
*/
public LogStreamWriter(LogLevel level, OutputStream os, boolean autoFlush)
{
this(level, os);
this.autoFlush = autoFlush;
}
/* (non-Javadoc)
* @see tuwien.auto.calimero.log.LogWriter#write
* (java.lang.String, tuwien.auto.calimero.log.LogLevel, java.lang.String)
*/
public void write(String logService, LogLevel level, String msg)
{
doWrite(logService, level, msg, null);
}
/* (non-Javadoc)
* @see tuwien.auto.calimero.log.LogWriter#write
* (java.lang.String, tuwien.auto.calimero.log.LogLevel, java.lang.String,
* java.lang.Throwable)
*/
public void write(String logService, LogLevel level, String msg, Throwable t)
{
doWrite(logService, level, msg, t);
}
/* (non-Javadoc)
* @see tuwien.auto.calimero.log.LogWriter#flush()
*/
public synchronized void flush()
{
if (out != null)
try {
out.flush();
}
catch (final IOException e) {
getErrorHandler().error(this, "on flush", e);
}
}
/* (non-Javadoc)
* @see tuwien.auto.calimero.log.LogWriter#close()
*/
public synchronized void close()
{
if (out != null) {
try {
out.close();
}
catch (final IOException e) {}
out = null;
}
}
/**
* Sets the underlying writer to use for logging output.
* <p>
* The log stream writer obtains ownership of the writer object.
*
* @param w the Writer
*/
protected final void setOutput(Writer w)
{
out = w;
}
/**
* Checks if logging output with log <code>level</code> is possible and would get
* accepted by this <code>LogStreamWriter</code>.
* <p>
* Therefore this method also checks that the underlying output stream is opened.
*
* @param level log level to check against
* @return true if log is permitted, false otherwise
*/
protected boolean logAllowed(LogLevel level)
{
if (out == null || level == LogLevel.OFF || level.higher(logLevel))
return false;
return true;
}
/**
* Creates a formatted output string from the input parameters.
* <p>
* Override this method to provide a different output format.<br>
* The output returned by default follows the shown format. The date/time format is
* according ISO 8601 representation, extended format with decimal fraction of second
* (milliseconds):<br>
* "YYYY-MM-DD hh:mm:ss,sss level=<code>level.toString()</code>,
* <code>logService</code>: <code>msg</code> (<code>t.getMessage()</code>)"<br>
* or, if throwable is <code>null</code> or throwable-message is <code>null</code><br>
* "YYYY-MM-DD hh:mm:ss,sss logService, LogLevel=<code>level.toString()</code>:
* <code>msg</code>".<br>
* If <code>logService</code> contains '.' in the name, only the part after the last
* '.' will be used. This way names like "package.subpackage.name" are shortened to
* "name". Nevertheless, if the first character after '.' is numeric, no truncation
* will be done to allow e.g. IP addresses in the log service name.
*
* @param svc name of the log service the message comes from
* @param l log level of message and throwable
* @param msg message to format
* @param t an optional throwable object to format, might be <code>null</code>
* @return the formatted output
*/
protected String formatOutput(String svc, LogLevel l, String msg, Throwable t)
{
// ??? for more severe output levels, a formatting routine which
// uses (part of) the throwable stack trace would be of advantage
final StringBuffer b = new StringBuffer(150);
synchronized (c) {
c.setTimeInMillis(System.currentTimeMillis());
b.append(c.get(Calendar.YEAR));
b.append('-').append(pad2Digits(c.get(Calendar.MONTH) + 1));
b.append('-').append(pad2Digits(c.get(Calendar.DAY_OF_MONTH)));
b.append(' ').append(pad2Digits(c.get(Calendar.HOUR_OF_DAY)));
b.append(':').append(pad2Digits(c.get(Calendar.MINUTE)));
b.append(':').append(pad2Digits(c.get(Calendar.SECOND)));
final int ms = c.get(Calendar.MILLISECOND);
b.append(',');
if (ms < 99)
b.append('0');
b.append(pad2Digits(ms));
}
b.append(" level=").append(l.toString());
b.append(", ");
final int dot = svc.lastIndexOf('.') + 1;
if (dot > 0 && dot < svc.length() && Character.isDigit(svc.charAt(dot)))
b.append(svc);
else
b.append(svc.substring(dot));
b.append(": ").append(msg);
if (t != null && t.getMessage() != null)
b.append(" (").append(t.getMessage()).append(")");
return b.toString();
}
void createWriter(OutputStream os)
{
setOutput(new BufferedWriter(new OutputStreamWriter(os), 512));
}
private synchronized void doWrite(String logService, LogLevel level, String msg,
Throwable t)
{
if (logAllowed(level))
try {
out.write(formatOutput ? formatOutput(logService, level, msg, t) : msg);
out.write(lineSep);
if (autoFlush)
out.flush();
}
catch (final Exception e) {
// IOException and RuntimeException
getErrorHandler().error(this, "on write", e);
}
}
private static String pad2Digits(int i)
{
return i > 9 ? Integer.toString(i) : "0" + Integer.toString(i);
}
}
| 34.492063 | 90 | 0.683111 |
442fbe7091e8f4552cb3c6cc75e784222d44020c | 14,589 | package tab_achievements;
import backend.MessageProcessing;
import backend.ModelDBConnection;
import general_classes.CheckBoxCellRenderer;
import general_classes.GUITableModel;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Vector;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.Box.Filler;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableColumn;
import tab_achievements.AcceptRejectEditor;
import tab_achievements.EditWatchRenderer;
public class IndividualAchievementsPanel extends JPanel {
private String currentAbit;
private JTable indAchivTable;
private JButton addNewAchievmentButton;
private JButton editAchievmentButton;
private JButton saveAchievmentButton;
private JButton deleteAchievmentButton;
private GUITableModel individAchivTM = new GUITableModel();
private String[] nameIndAchivTest;
private String[] individAchivColumnNames = new String[]{"Наименование", "Балл", "Подтверждающий документ"};
public IndividualAchievementsPanel() {
this.setLayout(new BorderLayout());
this.indAchivTable = new JTable(this.individAchivTM);
this.individAchivTM.setDataVector((Object[][])null, this.individAchivColumnNames);
this.indAchivTable.setAutoResizeMode(1);
JScrollPane scrPane = new JScrollPane(this.indAchivTable);
scrPane.setPreferredSize(new Dimension(300, 0));
this.indAchivTable.setMaximumSize(new Dimension(100, 100));
this.add(scrPane, "Center");
this.indAchivTable.setRowHeight(37);
this.individAchivTM.setDataVector((Object[][])null, this.individAchivColumnNames);
this.nameIndAchivTest = ModelDBConnection.getNamesFromTableOrderedById("IndividualAchievement");
this.createCheckboxTable(this.indAchivTable, 0, this.nameIndAchivTest);
EditWatchRenderer renderer = new EditWatchRenderer(this.indAchivTable);
this.indAchivTable.getColumnModel().getColumn(2).setCellRenderer(renderer);
this.indAchivTable.getColumnModel().getColumn(2).setCellEditor(new AcceptRejectEditor(this.indAchivTable));
this.indAchivTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
if(IndividualAchievementsPanel.this.indAchivTable.getSelectedRow() > -1 && IndividualAchievementsPanel.this.individAchivTM.getValueAt(IndividualAchievementsPanel.this.indAchivTable.getSelectedRow(), 0) != null) {
String[] values = new String[]{IndividualAchievementsPanel.this.currentAbit, "1", null};
String selectedIndAch = (String)IndividualAchievementsPanel.this.individAchivTM.getValueAt(IndividualAchievementsPanel.this.indAchivTable.getSelectedRow(), 0);
for(int j = 0; !selectedIndAch.equals(IndividualAchievementsPanel.this.nameIndAchivTest[j]); values[1] = String.valueOf(j + 1)) {
++j;
}
values[2] = (String)IndividualAchievementsPanel.this.individAchivTM.getValueAt(IndividualAchievementsPanel.this.indAchivTable.getSelectedRow(), 1);
((AcceptRejectEditor)IndividualAchievementsPanel.this.indAchivTable.getColumnModel().getColumn(2).getCellEditor()).setValues(values);
}
}
});
this.indAchivTable.getModel().addTableModelListener(new TableModelListener() {
public void tableChanged(TableModelEvent arg0) {
if(IndividualAchievementsPanel.this.indAchivTable.getSelectedRow() > -1 && IndividualAchievementsPanel.this.indAchivTable.getSelectedRow() < IndividualAchievementsPanel.this.indAchivTable.getRowCount() && IndividualAchievementsPanel.this.individAchivTM.getValueAt(IndividualAchievementsPanel.this.indAchivTable.getSelectedRow(), 0) != null) {
String[] values = new String[]{IndividualAchievementsPanel.this.currentAbit, "1", null};
String selectedIndAch = (String)IndividualAchievementsPanel.this.individAchivTM.getValueAt(IndividualAchievementsPanel.this.indAchivTable.getSelectedRow(), 0);
for(int j = 0; !selectedIndAch.equals(IndividualAchievementsPanel.this.nameIndAchivTest[j]); values[1] = String.valueOf(j + 1)) {
++j;
}
values[2] = (String)IndividualAchievementsPanel.this.individAchivTM.getValueAt(IndividualAchievementsPanel.this.indAchivTable.getSelectedRow(), 1);
((AcceptRejectEditor)IndividualAchievementsPanel.this.indAchivTable.getColumnModel().getColumn(2).getCellEditor()).setValues(values);
}
}
});
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, 1));
JPanel longButtonPanel = new JPanel();
longButtonPanel.setLayout(new GridLayout(0, 1));
this.addNewAchievmentButton = new JButton("Добавить новое достижение");
this.addNewAchievmentButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
IndividualAchievementsPanel.this.addNewAchievmentButtonActionPerformed(evt);
}
});
longButtonPanel.add(this.addNewAchievmentButton);
Dimension minSize = new Dimension(5, 10);
Dimension prefSize = new Dimension(5, 10);
Dimension maxSize = new Dimension(32767, 100);
buttonPanel.add(new Filler(minSize, prefSize, maxSize));
buttonPanel.add(longButtonPanel);
buttonPanel.add(Box.createRigidArea(new Dimension(0, 10)));
JPanel buttonEditSavePanel = new JPanel();
buttonEditSavePanel.setLayout(new FlowLayout(2));
this.editAchievmentButton = new JButton("Редактировать");
this.editAchievmentButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
IndividualAchievementsPanel.this.editAchievmentButtonActionPerformed(evt);
}
});
buttonEditSavePanel.add(this.editAchievmentButton);
this.saveAchievmentButton = new JButton("Сохранить");
this.saveAchievmentButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if(IndividualAchievementsPanel.this.indAchivTable.isEditing()) {
IndividualAchievementsPanel.this.indAchivTable.getCellEditor().stopCellEditing();
}
IndividualAchievementsPanel.this.saveAchievmentButtonActionPerformed(evt);
}
});
buttonEditSavePanel.add(this.saveAchievmentButton);
this.deleteAchievmentButton = new JButton("Удалить");
this.deleteAchievmentButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if(IndividualAchievementsPanel.this.indAchivTable.isEditing()) {
IndividualAchievementsPanel.this.indAchivTable.getCellEditor().stopCellEditing();
}
IndividualAchievementsPanel.this.deleteAchievmentButtonActionPerformed(evt);
}
});
buttonEditSavePanel.add(this.deleteAchievmentButton);
buttonPanel.add(buttonEditSavePanel);
this.add(buttonPanel, "Last");
this.setEditable(false);
}
private void addNewAchievmentButtonActionPerformed(ActionEvent evt) {
try {
this.individAchivTM.addRow(new String[this.individAchivColumnNames.length]);
} catch (Exception var3) {
MessageProcessing.displayErrorMessage(this, var3);
}
}
private void editAchievmentButtonActionPerformed(ActionEvent evt) {
try {
this.setEditable(true);
} catch (Exception var3) {
MessageProcessing.displayErrorMessage(this, var3);
}
}
private void deleteAchievmentButtonActionPerformed(ActionEvent evt) {
try {
if(this.indAchivTable.getSelectedRow() > -1) {
String[][] e = ModelDBConnection.getAllAchievmentsByAbiturientId(this.currentAbit, true);
if(e.length > this.indAchivTable.getSelectedRow()) {
Vector data = this.individAchivTM.getDataVector();
String currentIndAchievment = "1";
for(int data_delete = 0; !((Vector)data.elementAt(this.indAchivTable.getSelectedRow())).toArray()[0].toString().equals(this.nameIndAchivTest[data_delete]); currentIndAchievment = String.valueOf(data_delete + 1)) {
++data_delete;
}
String[] var7 = new String[]{this.currentAbit, currentIndAchievment};
ModelDBConnection.deleteElementInTableByIds("AbiturientIndividualAchievement", var7);
ModelDBConnection.updateCompetitiveBallsByID(this.currentAbit);
MessageProcessing.displaySuccessMessage(this, 5);
}
this.individAchivTM.removeRow(this.indAchivTable.getSelectedRow());
this.indAchivTable.clearSelection();
}
} catch (Exception var6) {
MessageProcessing.displayErrorMessage(this, var6);
}
}
private void saveAchievmentButtonActionPerformed(ActionEvent evt) {
try {
Vector e = this.individAchivTM.getDataVector();
String[][] data_new = new String[e.size()][8];
String[][] data_old = ModelDBConnection.getAllAchievmentsByAbiturientId(this.currentAbit, true);
int data_old_length = data_old == null?0:data_old.length;
ArrayList allUniqueAchievments = new ArrayList();
boolean isAcievmentNameNull = false;
boolean formatError = false;
int i;
int data_delete;
for(i = 0; i < e.size(); ++i) {
Object[] tmpdata = ((Vector)e.elementAt(i)).toArray();
if(tmpdata[0] == null) {
isAcievmentNameNull = true;
}
data_new[i][0] = this.currentAbit;
data_new[i][1] = "1";
for(data_delete = 0; !tmpdata[0].toString().equals(this.nameIndAchivTest[data_delete]); data_new[i][1] = String.valueOf(data_delete + 1)) {
++data_delete;
}
if(!allUniqueAchievments.contains(data_new[i][1])) {
allUniqueAchievments.add(data_new[i][1]);
}
if(tmpdata[1] != null) {
data_new[i][2] = tmpdata[1].toString().isEmpty()?null:tmpdata[1].toString();
if(data_new[i][2] != null && !data_new[i][2].matches("^[0-9]+$")) {
formatError = true;
}
}
for(data_delete = 3; data_delete < data_new[i].length; ++data_delete) {
data_new[i][data_delete] = null;
}
data_new[i][7] = null;
}
if(isAcievmentNameNull) {
MessageProcessing.displayErrorMessage((Component)null, 40);
} else if(formatError) {
MessageProcessing.displayErrorMessage((Component)null, 32);
} else if(allUniqueAchievments.size() != data_new.length) {
MessageProcessing.displayErrorMessage((Component)null, 41);
} else {
for(i = 0; i < (e.size() <= data_old_length?e.size():data_old_length); ++i) {
for(data_delete = 3; data_delete < data_new[i].length; ++data_delete) {
data_new[i][data_delete] = data_old[i][data_delete];
}
}
for(i = 0; i < data_old_length; ++i) {
String[] var13 = new String[]{data_old[i][0], data_old[i][1]};
ModelDBConnection.deleteElementInTableByIds("AbiturientIndividualAchievement", var13);
}
for(i = 0; i < e.size(); ++i) {
ModelDBConnection.updateAbiturientIndividualAchivementByID(data_new[i]);
}
ModelDBConnection.updateCompetitiveBallsByID(this.currentAbit);
MessageProcessing.displaySuccessMessage(this, 4);
this.indAchivTable.clearSelection();
this.setValues(this.currentAbit);
this.setEditable(false);
}
} catch (Exception var12) {
var12.printStackTrace();
MessageProcessing.displayErrorMessage(this, var12);
}
}
public void setValues(String aid) {
this.currentAbit = aid;
this.individAchivTM.setDataVector(ModelDBConnection.getAllAchievmentsByAbiturientId(aid, false), this.individAchivColumnNames);
String[] nameIndAchivTest = ModelDBConnection.getNamesFromTableOrderedById("IndividualAchievement");
this.createCheckboxTable(this.indAchivTable, 0, nameIndAchivTest);
EditWatchRenderer renderer = new EditWatchRenderer(this.indAchivTable);
this.indAchivTable.getColumnModel().getColumn(2).setCellRenderer(renderer);
this.indAchivTable.getColumnModel().getColumn(2).setCellEditor(new AcceptRejectEditor(this.indAchivTable));
this.setEditable(false);
}
public void setEditable(boolean state) {
this.indAchivTable.setEnabled(state);
this.saveAchievmentButton.setEnabled(state);
this.addNewAchievmentButton.setEnabled(state);
this.deleteAchievmentButton.setEnabled(state);
this.editAchievmentButton.setEnabled(!state);
if(this.currentAbit == null || this.currentAbit.equals("0")) {
this.editAchievmentButton.setEnabled(state);
}
}
private void createCheckboxTable(JTable table, int numColumn, String[] dataCheck) {
TableColumn tmpColumn = table.getColumnModel().getColumn(numColumn);
JComboBox comboBox = new JComboBox(dataCheck);
DefaultCellEditor defaultCellEditor = new DefaultCellEditor(comboBox);
tmpColumn.setCellEditor(defaultCellEditor);
tmpColumn.setCellRenderer(new CheckBoxCellRenderer(comboBox));
}
public String[][] getValues(boolean forDocs) {
String[][] indAchievments = ModelDBConnection.getAllAchievmentsByAbiturientId(this.currentAbit, true);
if(forDocs) {
Vector data = this.individAchivTM.getDataVector();
for(int i = 0; i < data.size(); ++i) {
indAchievments[i][1] = ((Vector)data.elementAt(i)).toArray()[0].toString();
}
}
return indAchievments;
}
}
| 46.461783 | 354 | 0.689629 |
5535c113a23241aaf82e61213dfb38d3516a8277 | 5,325 | package seedu.siasa.storage;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import seedu.siasa.commons.exceptions.IllegalValueException;
import seedu.siasa.model.contact.Contact;
import seedu.siasa.model.policy.Commission;
import seedu.siasa.model.policy.CoverageExpiryDate;
import seedu.siasa.model.policy.PaymentStructure;
import seedu.siasa.model.policy.Policy;
import seedu.siasa.model.policy.Title;
import seedu.siasa.model.tag.Tag;
/**
* Jackson-friendly version of {@link Policy}.
*/
public class JsonAdaptedPolicy {
public static final String MISSING_FIELD_MESSAGE_FORMAT = "Policy's %s field is missing!";
private final String title;
private final JsonAdaptedPaymentStructure paymentStructure;
private final String coverageExpiryDate;
private final JsonAdaptedCommission commission;
private final JsonAdaptedContact owner;
private final List<JsonAdaptedTag> tagged = new ArrayList<>();
/**
* Constructs a {@code JsonAdaptedPolicy} with the given policy details.
*/
@JsonCreator
public JsonAdaptedPolicy(@JsonProperty("title") String title,
@JsonProperty("paymentStructure") JsonAdaptedPaymentStructure paymentStructure,
@JsonProperty("coverageExpiryDate") String coverageExpiryDate,
@JsonProperty("commission") JsonAdaptedCommission commission,
@JsonProperty("owner") JsonAdaptedContact owner,
@JsonProperty("tagged") List<JsonAdaptedTag> tagged) {
this.title = title;
this.paymentStructure = paymentStructure;
this.coverageExpiryDate = coverageExpiryDate;
this.commission = commission;
this.owner = owner;
if (tagged != null) {
this.tagged.addAll(tagged);
}
}
/**
* Converts a given {@code Policy} into this class for Jackson use.
*/
public JsonAdaptedPolicy(Policy source) {
title = source.getTitle().toString();
paymentStructure = new JsonAdaptedPaymentStructure(source.getPaymentStructure());
coverageExpiryDate = source.getCoverageExpiryDate().toString();
commission = new JsonAdaptedCommission(source.getCommission());
owner = new JsonAdaptedContact(source.getOwner());
tagged.addAll(source.getTags().stream()
.map(JsonAdaptedTag::new)
.collect(Collectors.toList()));
}
public JsonAdaptedContact getOwner() {
return owner;
}
/**
* Converts this Jackson-friendly adapted policy object into the model's {@code Policy} object.
*
* @throws IllegalValueException if there were any data constraints violated in the adapted policy.
*/
public Policy toModelType(Contact policyOwner) throws IllegalValueException {
final List<Tag> policyTags = new ArrayList<>();
for (JsonAdaptedTag tag : tagged) {
policyTags.add(tag.toModelType());
}
if (title == null) {
throw new IllegalValueException(String.format(MISSING_FIELD_MESSAGE_FORMAT, Title.class.getSimpleName()));
}
if (!Title.isValidTitle(title)) {
throw new IllegalValueException(Title.MESSAGE_CONSTRAINTS);
}
final Title modelTitle = new Title(title);
if (paymentStructure == null) {
throw new IllegalValueException(
String.format(MISSING_FIELD_MESSAGE_FORMAT, PaymentStructure.class.getSimpleName()));
}
final PaymentStructure modelPaymentStructure = paymentStructure.toModelType();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
try {
if (coverageExpiryDate == null) {
throw new IllegalValueException(
String.format(MISSING_FIELD_MESSAGE_FORMAT, CoverageExpiryDate.class.getSimpleName()));
}
LocalDate date = LocalDate.parse(coverageExpiryDate, formatter);
} catch (IllegalValueException | DateTimeParseException e) {
throw new IllegalValueException(e.getMessage());
}
LocalDate date = LocalDate.parse(coverageExpiryDate, formatter);
final CoverageExpiryDate modelCoverageExpiryDate = new CoverageExpiryDate(date);
if (commission == null) {
throw new IllegalValueException(
String.format(MISSING_FIELD_MESSAGE_FORMAT, Commission.class.getSimpleName()));
}
final Commission modelCommission = commission.toModelType(modelPaymentStructure);
if (policyOwner == null) {
throw new IllegalValueException(
String.format(MISSING_FIELD_MESSAGE_FORMAT, Contact.class.getSimpleName()));
}
final Set<Tag> modelTags = new HashSet<>(policyTags);
return new Policy(modelTitle, modelPaymentStructure, modelCoverageExpiryDate, modelCommission, policyOwner,
modelTags);
}
}
| 39.154412 | 118 | 0.678873 |
393192092befb6096f503cd7ae7c3e84bdeae186 | 1,100 | package com.otcdlink.chiron.mockster;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Blocks until it gets a value from the {@link OperativeInvocation}.
*/
class ArgumentCapture extends ArgumentTrap {
private final CoreVerifier coreVerifier;
private final long invocationTimeoutMs ;
public ArgumentCapture(
final CoreVerifier coreVerifier,
final int methodCallIndex,
final int parameterIndex,
final long invocationTimeoutMs
) {
super( methodCallIndex, parameterIndex ) ;
this.coreVerifier = checkNotNull( coreVerifier ) ;
checkArgument( invocationTimeoutMs >= 0 ) ;
this.invocationTimeoutMs = invocationTimeoutMs ;
}
@Override
protected void toStringExtended( StringBuilder stringBuilder ) {
stringBuilder.append( ";invocationTimeoutMs=" ).append( invocationTimeoutMs ) ;
}
public < T > T waitForOperativeValue() {
return coreVerifier.waitForOperativeArgumentValue(
methodCallIndex, parameterIndex, invocationTimeoutMs ) ;
}
}
| 30.555556 | 83 | 0.754545 |
de87e0db8a167820f8d452d855c26b69f367bd9c | 630 | package com.herokuapp.budgetcontrolapi.service.revenue;
import com.herokuapp.budgetcontrolapi.dto.revenue.request.RevenueRequest;
import com.herokuapp.budgetcontrolapi.dto.revenue.response.RevenueResponse;
import java.util.List;
public interface RevenueService {
RevenueResponse createRevenue(RevenueRequest request);
RevenueResponse getRevenue(Long id);
List<RevenueResponse> getAllRevenueByDescription(String description);
List<RevenueResponse> getAllRevenueByYearMonth(Long year, Long month);
RevenueResponse updateRevenue(RevenueRequest requestDetails, Long id);
void deleteRevenue(Long id);
} | 30 | 75 | 0.81746 |
66a2f2188619cdb7d66e2656f0258a42aa386194 | 335 | package com.devlomi.record_view;
class RecordDurationBoundariesException extends IllegalArgumentException {
RecordDurationBoundariesException() {
super("Minimum Duration must have a positive value, and must be smaller than the Maximum duration value if and only if the Max duration is set (has positive value)");
}
}
| 37.222222 | 174 | 0.779104 |
924074e2bd371f5e2c9e0befec104f99c504bfac | 2,908 | package net.minecraft.client.gui;
import com.google.common.collect.Lists;
import java.util.Iterator;
import java.util.List;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ServerList;
import net.minecraft.client.network.LanServerDetector;
public class ServerSelectionList extends GuiListExtended
{
private final GuiMultiplayer field_148200_k;
private final List field_148198_l = Lists.newArrayList();
private final List field_148199_m = Lists.newArrayList();
private final GuiListExtended.IGuiListEntry field_148196_n = new ServerListEntryLanScan();
private int field_148197_o = -1;
private static final String __OBFID = "CL_00000819";
public ServerSelectionList(GuiMultiplayer p_i45049_1_, Minecraft p_i45049_2_, int p_i45049_3_, int p_i45049_4_, int p_i45049_5_, int p_i45049_6_, int p_i45049_7_)
{
super(p_i45049_2_, p_i45049_3_, p_i45049_4_, p_i45049_5_, p_i45049_6_, p_i45049_7_);
this.field_148200_k = p_i45049_1_;
}
public GuiListExtended.IGuiListEntry func_148180_b(int p_148180_1_)
{
if (p_148180_1_ < this.field_148198_l.size())
{
return (GuiListExtended.IGuiListEntry)this.field_148198_l.get(p_148180_1_);
}
else
{
p_148180_1_ -= this.field_148198_l.size();
if (p_148180_1_ == 0)
{
return this.field_148196_n;
}
else
{
--p_148180_1_;
return (GuiListExtended.IGuiListEntry)this.field_148199_m.get(p_148180_1_);
}
}
}
protected int getSize()
{
return this.field_148198_l.size() + 1 + this.field_148199_m.size();
}
public void func_148192_c(int p_148192_1_)
{
this.field_148197_o = p_148192_1_;
}
protected boolean isSelected(int p_148131_1_)
{
return p_148131_1_ == this.field_148197_o;
}
public int func_148193_k()
{
return this.field_148197_o;
}
public void func_148195_a(ServerList p_148195_1_)
{
this.field_148198_l.clear();
for (int var2 = 0; var2 < p_148195_1_.countServers(); ++var2)
{
this.field_148198_l.add(new ServerListEntryNormal(this.field_148200_k, p_148195_1_.getServerData(var2)));
}
}
public void func_148194_a(List p_148194_1_)
{
this.field_148199_m.clear();
Iterator var2 = p_148194_1_.iterator();
while (var2.hasNext())
{
LanServerDetector.LanServer var3 = (LanServerDetector.LanServer)var2.next();
this.field_148199_m.add(new ServerListEntryLanDetected(this.field_148200_k, var3));
}
}
protected int func_148137_d()
{
return super.func_148137_d() + 30;
}
public int func_148139_c()
{
return super.func_148139_c() + 85;
}
}
| 29.373737 | 166 | 0.659216 |
a94157bc5702dd57aa533c3766711b70dc054d9b | 890 | // Code written as part of the Java-Methods-Program-AP-Comp-A-2021-2022 repository on GitHub.
package com.company;
import java.util.Arrays;
public class Main {
public static void main(String[] args)
{
String testStatement = "<a>ThisIstheSequenceofCharacters</a>";
System.out.println(removeTag(testStatement));
}
public static String removeTag(String statementToCheck)
{
//Converts the string to an array of characters
char[] statementArray = statementToCheck.toCharArray();
//Arrays start at 0, and final is length - 1
for(int counter = 0; counter < statementArray.length; counter++)
{
if(statementArray[counter] == '>' || statementArray[counter] == '<')
{
statementArray[counter] = ' ';
}
}
return Arrays.toString(statementArray);
}
}
| 28.709677 | 93 | 0.621348 |
78bb20f542da78483f5fada31e2cb0c21e199066 | 2,694 | package com.yongzhi.library;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import com.kevin.tipview.TipItem;
import com.kevin.tipview.TipView;
import com.yongzhi.latlng.convert.LngLat;
import com.yongzhi.latlng.convert.LngLatUtil;
public class MainActivity extends AppCompatActivity {
private ConstraintLayout mConstraintLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mConstraintLayout = (ConstraintLayout) findViewById(R.id.root);
LngLat lngLat = new LngLat(121.431595, 31.276325);
LngLat wgs84ToBd09 = LngLatUtil.wgs84ToBd09(lngLat.getLongitude(), lngLat.getLatitude());
LngLat wgs84ToGcj02 = LngLatUtil.wgs84ToGcj02(lngLat.getLongitude(), lngLat.getLatitude());
LngLat gcj02ToBd09 = LngLatUtil.gcj02ToBd09(lngLat.getLongitude(), lngLat.getLatitude());
LngLat gcj02ToWgs84 = LngLatUtil.gcj02ToWgs84(lngLat.getLongitude(), lngLat.getLatitude());
LngLat bd09ToGcj02 = LngLatUtil.bd09ToGcj02(lngLat.getLongitude(), lngLat.getLatitude());
LngLat bd09ToWgs84 = LngLatUtil.bd09ToWgs84(lngLat.getLongitude(), lngLat.getLatitude());
final TextView textView = (TextView) findViewById(R.id.text);
String text = "";
text += "wgs84ToBd09:\n" + wgs84ToBd09 + "\n";
text += "wgs84ToGcj02:\n" + wgs84ToGcj02 + "\n";
text += "gcj02ToBd09:\n" + gcj02ToBd09 + "\n";
text += "gcj02ToWgs84:\n" + gcj02ToWgs84 + "\n";
text += "bd09ToGcj02:\n" + bd09ToGcj02 + "\n";
text += "bd09ToWgs84:\n" + bd09ToWgs84 + "\n";
textView.setText(text);
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new TipView.Builder(MainActivity.this, mConstraintLayout, 1200, 0)
.autoSize(true)
.setTextSize(12)
.padding(20, 10, 20, 10)
.addItem(new TipItem("一卡通麦粒消耗顺序为购买麦粒、赠品麦粒"))
.setOnItemClickListener(new TipView.OnItemClickListener() {
@Override
public void onItemClick(String name, int position) {
}
@Override
public void dismiss() {
}
})
.create();
}
});
}
}
| 40.818182 | 99 | 0.60876 |
d8438b3f0d03b29e5783016147280edcee979e53 | 1,585 | package diary.gui.EntryLog;
import java.awt.Color;
import diary.constants.Constants;
import diary.gui.GButton;
import diary.interfaces.GUIFunction;
import diary.methods.Methods;
public class EntryLogMapButton extends GButton implements GUIFunction
{
/**
*
*/
private static final long serialVersionUID = -873903782280068320L;
private Color defaultForeground, defaultBackground;
private boolean required;
public EntryLogMapButton(String text, boolean required)
{
super(required? Methods.createTextWithRequiredIdentifier(text): text);
//Initialization
this.required = required;
//Properties
// this.setOpaque(false);
// this.setBackground(Constants.COLOR_TRANSPARENT);
// this.setBorder(null);
// this.setFont(Constants.FONT_GENERAL);
this.defaultBackground = this.getBackground();
this.defaultForeground = this.getForeground();
this.resetDefaults();
}
//Public methods
public void setToHighlightedColor(boolean b)
{
if (b)
{
this.setForeground(Color.white);
this.setBackground(Constants.COLOR_HIGHLIGHT_BUTTON);
}
else
{
this.resetDefaults();
}
}
public boolean isRequired()
{
return this.required;
}
public void setRequired(boolean b)
{
this.required = b;
}
//Overridden Methods
@Override
public void setText(String text)
{
super.setText(this.isRequired()? Methods.createTextWithRequiredIdentifier(text) : text);
}
@Override
public void resetDefaults()
{
this.setForeground(this.defaultForeground);
this.setBackground(this.defaultBackground);
}
@Override
public void refresh() {}
}
| 20.320513 | 90 | 0.745741 |
ab8e274c2a449e7ec0fbe06e0f7b2281c617ffa1 | 1,017 | package com.ftfl.imageslidergallery;
import com.ftfl.imageslidergallery.adapter.FullScreenImageAdapter;
import com.ftfl.imageslidergallery.helper.Utils;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
public class FullScreenViewActivity extends Activity {
private Utils mUtils = null;
private FullScreenImageAdapter mAdapter = null;
private ViewPager mViewPager = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen_view);
mViewPager = (ViewPager) findViewById(R.id.pager);
mUtils = new Utils(getApplicationContext());
Intent intent = getIntent();
int position = intent.getIntExtra("position", 0);
mAdapter = new FullScreenImageAdapter(FullScreenViewActivity.this,
mUtils.getFilePaths());
mViewPager.setAdapter(mAdapter);
// displaying selected image first
mViewPager.setCurrentItem(position);
}
}
| 26.076923 | 68 | 0.79351 |
ffc0ab5aea4d0ca75000ea4d4f69762187a9936f | 5,688 | package demo.inventory.api.kafka;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.util.concurrent.Semaphore;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.context.ApplicationListener;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.kafka.core.KafkaOperations;
import org.springframework.kafka.support.SendResult;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.context.EmbeddedKafka;
import org.springframework.test.context.ActiveProfiles;
import demo.inventory.api.message.OrderCompletedNotice;
import demo.inventory.api.messaging.InvalidInventoryItemEvent;
import demo.inventory.api.messaging.InventoryUpdatedEvent;
@ActiveProfiles(profiles = "test")
@SpringBootTest(webEnvironment = WebEnvironment.NONE, properties = "opentracing.spring.web.enabled=false")
//@DirtiesContext(classMode = ClassMode.BEFORE_CLASS)
@EmbeddedKafka(topics={"${events.api.orders.topic}","${events.api.inventory.topic}"}, partitions=1)
@TestMethodOrder(OrderAnnotation.class)
public class OrderCompletionListenerTest {
private static final Logger log = LoggerFactory.getLogger(OrderCompletionListenerTest.class);
@Autowired
private KafkaOperations<String, OrderCompletedNotice> kafkaOperations;
@Autowired
private EmbeddedKafkaBroker kafkaBroker;
@Value("${spring.kafka.bootstrap-servers}")
private String bootstrapServers;
@Value(value = "${events.api.orders.topic}")
private String ordersTopicName;
@Value(value = "${events.api.inventory.topic}")
private String inventoryTopicName;
@Autowired
AbstractApplicationContext context;
static private Boolean isSubscribed = false;
static private Semaphore sutCompleteSignal = new Semaphore(0);
/*
* These listeners will be notified when the KafkaListener under test posts a ApplicationEvent.
*/
@BeforeEach
public void setupApplicationEventListeners() {
synchronized (isSubscribed) {
if( isSubscribed )
return;
context.addApplicationListener(new ApplicationListener<InventoryUpdatedEvent>() {
@Override
public void onApplicationEvent(InventoryUpdatedEvent event) {
log.info("Received InventoryUpdated ApplicationEvent");
signalSUTcomplete();
}});
context.addApplicationListener(new ApplicationListener<InvalidInventoryItemEvent>() {
@Override
public void onApplicationEvent(InvalidInventoryItemEvent event) {
log.info("Received InvalidInventoryItem ApplicationEvent");
signalSUTcomplete();
}});
isSubscribed = true;
}
}
@Test
@Order(1)
public void whenContextIsBootstrapped_thenOkReady() {
assertTrue(kafkaOperations != null, "Missing KafkaOperations bean");
assertTrue(kafkaBroker != null, "Missing KafkaBroker bean");
log.info("[CONFIG] spring.kafka.bootstrap.servers = " + bootstrapServers);
log.info("[CONFIG] events.api.orders.topic = " + ordersTopicName);
}
// Testcase: order placed for 10 units of some item in inventory
@Test
@Order(2)
public void whenOrderCompletedSent_thenFindInventoryUpdatedNotice() {
log.info("Posting an order notification");
// Send OrderCompletedNotice
OrderCompletedNotice message = new OrderCompletedNotice(3, 10);
kafkaOperations.send(ordersTopicName, message).addCallback(
this::onSendSuccess,
ex -> fail("Unable to send OrderCompleted notification due to : " + ex.getMessage()));
waitOnSUTcomplete();
return;
}
// Testcase: order placed for 10 units of some item not in inventory
@Test
@Order(3)
public void whenInvalidOrderCompletedSent_thenFindInvalidOrderNotice() {
log.info("Posting an order notification");
// Send invalid OrderCompletedNotice
OrderCompletedNotice message = new OrderCompletedNotice(1234, 10);
kafkaOperations.send(ordersTopicName, message).addCallback(
this::onSendSuccess,
ex -> fail("Unable to send OrderCompleted notification due to : " + ex.getMessage()));
waitOnSUTcomplete();
return;
}
private void onSendSuccess(SendResult<String, OrderCompletedNotice> result) {
ProducerRecord<String, OrderCompletedNotice> producerRecord = result.getProducerRecord();
// RecordMetadata recordMetadata = result.getRecordMetadata();
log.info("Delivered OrderCompleted notification on topic [{}]: {}",
producerRecord.topic(),
producerRecord.value().toString());
}
private void waitOnSUTcomplete() {
log.info("Begin wait on OrderCompletion Listener complete");
//log.info("Available permits: "+sutCompleteSignal.availablePermits());
try {
sutCompleteSignal.acquire();
}
catch (InterruptedException e) {
fail(e.toString());
}
log.info("End wait on OrderCompletion Listener complete");
}
private void signalSUTcomplete() {
sutCompleteSignal.release();
}
}
| 33.857143 | 106 | 0.743671 |
8d67495885d8ce660f5c49133b5445328882c1b3 | 10,335 | package extracells.part;
import appeng.api.config.Actionable;
import appeng.api.config.SecurityPermissions;
import appeng.api.networking.IGridNode;
import appeng.api.networking.security.MachineSource;
import appeng.api.networking.ticking.IGridTickable;
import appeng.api.networking.ticking.TickRateModulation;
import appeng.api.networking.ticking.TickingRequest;
import appeng.api.parts.IPart;
import appeng.api.parts.IPartCollisionHelper;
import appeng.api.parts.IPartHost;
import appeng.api.parts.IPartRenderHelper;
import appeng.api.storage.IMEMonitor;
import appeng.api.storage.data.IAEFluidStack;
import appeng.api.util.AEColor;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import extracells.container.ContainerFluidTerminal;
import extracells.gridblock.ECBaseGridBlock;
import extracells.gui.GuiFluidTerminal;
import extracells.network.packet.part.PacketFluidTerminal;
import extracells.render.TextureManager;
import extracells.util.FluidUtil;
import extracells.util.PermissionUtil;
import extracells.util.inventory.ECPrivateInventory;
import extracells.util.inventory.IInventoryUpdateReceiver;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.IIcon;
import net.minecraft.util.Vec3;
import net.minecraftforge.common.util.ForgeDirection;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidStack;
import org.apache.commons.lang3.tuple.MutablePair;
import java.util.ArrayList;
import java.util.List;
public class PartFluidTerminal extends PartECBase implements IGridTickable,
IInventoryUpdateReceiver {
protected Fluid currentFluid;
private List<Object> containers = new ArrayList<Object>();
protected ECPrivateInventory inventory = new ECPrivateInventory(
"extracells.part.fluid.terminal", 2, 64, this) {
@Override
public boolean isItemValidForSlot(int i, ItemStack itemStack) {
return isItemValidForInputSlot(i, itemStack);
}
};
protected boolean isItemValidForInputSlot(int i, ItemStack itemStack) {
return FluidUtil.isFluidContainer(itemStack);
}
protected MachineSource machineSource = new MachineSource(this);
@Override
public void getDrops( List<ItemStack> drops, boolean wrenched) {
for (ItemStack stack : inventory.slots) {
if (stack == null)
continue;
drops.add(stack);
}
}
@Override
public int getLightLevel() {
return this.isPowered() ? 9 : 0;
}
public void addContainer(ContainerFluidTerminal containerTerminalFluid) {
this.containers.add(containerTerminalFluid);
sendCurrentFluid();
}
@Override
public int cableConnectionRenderTo() {
return 1;
}
public void decreaseFirstSlot() {
ItemStack slot = this.inventory.getStackInSlot(0);
slot.stackSize--;
if (slot.stackSize <= 0)
this.inventory.setInventorySlotContents(0, null);
}
public void doWork() {
ItemStack secondSlot = this.inventory.getStackInSlot(1);
if (secondSlot != null && secondSlot.stackSize >= secondSlot.getMaxStackSize())
return;
ItemStack container = this.inventory.getStackInSlot(0);
if (!FluidUtil.isFluidContainer(container))
return;
container = container.copy();
container.stackSize = 1;
ECBaseGridBlock gridBlock = getGridBlock();
if (gridBlock == null)
return;
IMEMonitor<IAEFluidStack> monitor = gridBlock.getFluidMonitor();
if (monitor == null)
return;
if (FluidUtil.isEmpty(container)) {
if (this.currentFluid == null)
return;
int capacity = FluidUtil.getCapacity(container);
IAEFluidStack result = monitor.extractItems(FluidUtil.createAEFluidStack(this.currentFluid, capacity), Actionable.SIMULATE, this.machineSource);
int proposedAmount = result == null ? 0 : (int) Math.min(capacity, result.getStackSize());
if(proposedAmount == 0)
return;
MutablePair<Integer, ItemStack> filledContainer = FluidUtil.fillStack(container, new FluidStack(this.currentFluid, proposedAmount));
if(filledContainer.getLeft() > proposedAmount)
return;
if (fillSecondSlot(filledContainer.getRight())) {
monitor.extractItems(FluidUtil.createAEFluidStack(this.currentFluid, filledContainer.getLeft()), Actionable.MODULATE, this.machineSource);
decreaseFirstSlot();
}
} else {
FluidStack containerFluid = FluidUtil.getFluidFromContainer(container);
IAEFluidStack notInjected = monitor.injectItems(FluidUtil.createAEFluidStack(containerFluid), Actionable.SIMULATE, this.machineSource);
if (notInjected != null)
return;
MutablePair<Integer, ItemStack> drainedContainer = FluidUtil.drainStack(container, containerFluid);
ItemStack emptyContainer = drainedContainer.getRight();
if (emptyContainer == null || fillSecondSlot(emptyContainer)) {
monitor.injectItems(FluidUtil.createAEFluidStack(containerFluid), Actionable.MODULATE, this.machineSource);
decreaseFirstSlot();
}
}
}
public boolean fillSecondSlot(ItemStack itemStack) {
if (itemStack == null)
return false;
ItemStack secondSlot = this.inventory.getStackInSlot(1);
if (secondSlot == null) {
this.inventory.setInventorySlotContents(1, itemStack);
return true;
} else {
if (!secondSlot.isItemEqual(itemStack) || !ItemStack.areItemStackTagsEqual(itemStack, secondSlot))
return false;
this.inventory.incrStackSize(1, itemStack.stackSize);
return true;
}
}
@Override
public void getBoxes(IPartCollisionHelper bch) {
bch.addBox(2, 2, 14, 14, 14, 16);
bch.addBox(4, 4, 13, 12, 12, 14);
bch.addBox(5, 5, 12, 11, 11, 13);
}
public IInventory getInventory() {
return this.inventory;
}
@Override
public double getPowerUsage() {
return 0.5D;
}
@Override
public Object getServerGuiElement(EntityPlayer player) {
return new ContainerFluidTerminal(this, player);
}
@Override
public Object getClientGuiElement(EntityPlayer player) {
return new GuiFluidTerminal(this, player);
}
@Override
public TickingRequest getTickingRequest(IGridNode node) {
return new TickingRequest(1, 20, false, false);
}
@Override
public boolean onActivate(EntityPlayer player, Vec3 pos) {
if (isActive() && (PermissionUtil.hasPermission(player, SecurityPermissions.INJECT, (IPart) this) || PermissionUtil.hasPermission(player, SecurityPermissions.EXTRACT, (IPart) this)))
return super.onActivate(player, pos);
return false;
}
@Override
public void onInventoryChanged() {
saveData();
}
@Override
public void readFromNBT(NBTTagCompound data) {
super.readFromNBT(data);
this.inventory.readFromNBT(data.getTagList("inventory", 10));
}
public void removeContainer(ContainerFluidTerminal containerTerminalFluid) {
this.containers.remove(containerTerminalFluid);
}
@SideOnly(Side.CLIENT)
@Override
public void renderInventory(IPartRenderHelper rh, RenderBlocks renderer) {
Tessellator ts = Tessellator.instance;
IIcon side = TextureManager.TERMINAL_SIDE.getTexture();
rh.setTexture(side);
rh.setBounds(4, 4, 13, 12, 12, 14);
rh.renderInventoryBox(renderer);
rh.setTexture(side, side, side, TextureManager.BUS_BORDER.getTexture(),
side, side);
rh.setBounds(2, 2, 14, 14, 14, 16);
rh.renderInventoryBox(renderer);
ts.setBrightness(13 << 20 | 13 << 4);
rh.setInvColor(0xFFFFFF);
rh.renderInventoryFace(TextureManager.BUS_BORDER.getTexture(),
ForgeDirection.SOUTH, renderer);
rh.setBounds(3, 3, 15, 13, 13, 16);
rh.setInvColor(AEColor.Transparent.blackVariant);
rh.renderInventoryFace(TextureManager.TERMINAL_FRONT.getTextures()[0],
ForgeDirection.SOUTH, renderer);
rh.setInvColor(AEColor.Transparent.mediumVariant);
rh.renderInventoryFace(TextureManager.TERMINAL_FRONT.getTextures()[1],
ForgeDirection.SOUTH, renderer);
rh.setInvColor(AEColor.Transparent.whiteVariant);
rh.renderInventoryFace(TextureManager.TERMINAL_FRONT.getTextures()[2],
ForgeDirection.SOUTH, renderer);
rh.setBounds(5, 5, 12, 11, 11, 13);
renderInventoryBusLights(rh, renderer);
}
@SideOnly(Side.CLIENT)
@Override
public void renderStatic(int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer) {
Tessellator ts = Tessellator.instance;
IIcon side = TextureManager.TERMINAL_SIDE.getTexture();
rh.setTexture(side);
rh.setBounds(4, 4, 13, 12, 12, 14);
rh.renderBlock(x, y, z, renderer);
rh.setTexture(side, side, side, TextureManager.BUS_BORDER.getTexture(), side, side);
rh.setBounds(2, 2, 14, 14, 14, 16);
rh.renderBlock(x, y, z, renderer);
if (isActive())
Tessellator.instance.setBrightness(13 << 20 | 13 << 4);
ts.setColorOpaque_I(0xFFFFFF);
rh.renderFace(x, y, z, TextureManager.BUS_BORDER.getTexture(), ForgeDirection.SOUTH, renderer);
IPartHost host = getHost();
rh.setBounds(3, 3, 15, 13, 13, 16);
ts.setColorOpaque_I(host.getColor().blackVariant);
rh.renderFace(x, y, z, TextureManager.TERMINAL_FRONT.getTextures()[0], ForgeDirection.SOUTH, renderer);
ts.setColorOpaque_I(host.getColor().mediumVariant);
rh.renderFace(x, y, z, TextureManager.TERMINAL_FRONT.getTextures()[1], ForgeDirection.SOUTH, renderer);
ts.setColorOpaque_I(host.getColor().whiteVariant);
rh.renderFace(x, y, z, TextureManager.TERMINAL_FRONT.getTextures()[2], ForgeDirection.SOUTH, renderer);
rh.setBounds(5, 5, 12, 11, 11, 13);
renderStaticBusLights(x, y, z, rh, renderer);
}
public void sendCurrentFluid() {
for (Object containerFluidTerminal : this.containers) {
sendCurrentFluid(containerFluidTerminal);
}
}
public void sendCurrentFluid(Object container) {
if(container instanceof ContainerFluidTerminal){
ContainerFluidTerminal containerFluidTerminal = (ContainerFluidTerminal) container;
new PacketFluidTerminal(containerFluidTerminal.getPlayer(), this.currentFluid).sendPacketToPlayer(containerFluidTerminal.getPlayer());
}
}
public void setCurrentFluid(Fluid _currentFluid) {
this.currentFluid = _currentFluid;
sendCurrentFluid();
}
@Override
public TickRateModulation tickingRequest(IGridNode node,
int TicksSinceLastCall) {
doWork();
return TickRateModulation.FASTER;
}
@Override
public void writeToNBT(NBTTagCompound data) {
super.writeToNBT(data);
data.setTag("inventory", this.inventory.writeToNBT());
}
}
| 33.77451 | 184 | 0.766715 |
c5f3b50d1256f2087812742d983a5c7b4ce946aa | 3,186 | package com.lxy.mew.expandtextview.adapter;
import android.content.Context;
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.lxy.mew.expandtextview.R;
import java.util.ArrayList;
import java.util.List;
/**
*
* Created by master on 2017/4/29.
*/
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder>
{
private Context context;
private List<String> datas = new ArrayList<>();
public CustomAdapter(Context context)
{
this.context = context;
}
public void setDatas(List<String> datas)
{
this.datas = datas;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
return new ViewHolder(LayoutInflater.from(context).inflate(R.layout.item_expand, parent, false));
}
@Override
public void onBindViewHolder(final ViewHolder holder, int position)
{
String item = datas.get(position);
holder.tvContent.setText(item);
final View.OnClickListener listener = new View.OnClickListener()
{
boolean isExpand;//设置是否展开的标记
@Override
public void onClick(View v)
{
if (isExpand)
{
holder.tvContent.setMaxLines(2);//如果当前是展开的,则设置为闭合
holder.ivArrow.setRotation(0);//箭头重置为向下的状态
isExpand = false;
} else
{
holder.tvContent.setMaxLines(Integer.MAX_VALUE);//如果是闭合的,则展开
holder.ivArrow.setRotation(180);//箭头设置为向上
isExpand = true;
}
}
};
holder.tvContent.post(new Runnable()
{
@Override
public void run()
{
/**
* 在子线程中获取textview的行数,等页面加载完成之后才能取到行数
*/
int lineCount = holder.tvContent.getLineCount();
if (lineCount > 2)//如果行数大于2,就让textview闭合
{
holder.tvContent.setMaxLines(2);
holder.viewContainer.setOnClickListener(listener);//可以相应点击事件
holder.ivArrow.setVisibility(View.VISIBLE);
} else
{
holder.viewContainer.setOnClickListener(null);//行数没有超过两行,保持原状,无需改变
holder.ivArrow.setVisibility(View.GONE);//让箭头消失
}
}
});
}
@Override
public int getItemCount()
{
return datas.size();
}
class ViewHolder extends RecyclerView.ViewHolder
{
View viewContainer;
TextView tvContent;
ImageView ivArrow;
ViewHolder(View itemView)
{
super(itemView);
viewContainer = itemView.findViewById(R.id.view_item_container);
tvContent = (TextView) itemView.findViewById(R.id.tv_item_content);
ivArrow = (ImageView) itemView.findViewById(R.id.iv_item_arrow);
}
}
}
| 26.773109 | 105 | 0.576899 |
df1451e1dfbb3934094a1956466595f1faa5fb6b | 4,710 | package se.mah.elis.external.water.beans;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import org.joda.time.DateTime;
import se.mah.elis.data.WaterSample;
import se.mah.elis.external.beans.PeriodicityBean;
/**
* The WaterBeanFactory creates various water bean objects.
*
* @author "Johan Holmberg, Malmö University"
* @since 1.0
*/
public class WaterBeanFactory {
/**
* This constant is used to tell the factory to set the bean's user field.
*
* @since 1.0
*/
public static final int IS_USER = 1;
/**
* This constant is used to tell the factory to set the bean's device
* field.
*
* @since 1.0
*/
public static final int IS_DEVICE = 2;
/**
* This constant is used to tell the factory to set the bean's device set
* field.
*
* @since 1.0
*/
public static final int IS_DEVICESET = 3;
/**
* Creates a WaterBean object.
*
* @param samples The data samples to embed into the water bean.
* @param queryPeriod The periodicity, denoted as a string.
* @param uuid The UUID of the sampled object.
* @param mode Tells whether the sampled object is a user (by using
* WaterBeanFactory.IS_USER), a device (by using
* WaterBeanFactory.IS_DEVICE), or a device set (by using
* WaterBeanFactory.IS_DEVICESET).
* @return A WaterBean object.
* @since 1.0
*/
public static WaterBean create(Map<String, List<WaterSample>> samples,
String queryPeriod, UUID uuid, int mode) {
WaterBean bean = new WaterBean();
switch (mode) {
case IS_USER:
bean.user = uuid;
break;
case IS_DEVICE:
bean.device = uuid;
break;
case IS_DEVICESET:
bean.deviceset = uuid;
}
bean.period = new PeriodicityBean();
bean.period.periodicity = queryPeriod;
bean.samples = createDataListFromSamples(samples);
bean.summary = summarize(samples);
return bean;
}
/**
* Creates a WaterBean object.
*
* @param samples The data samples to embed into the water bean.
* @param queryPeriod The periodicity, denoted as a string.
* @param uuid The UUID of the sampled object.
* @param mode Tells whether the sampled object is a user (by using
* WaterBeanFactory.IS_USER), a device (by using
* WaterBeanFactory.IS_DEVICE), or a device set (by using
* WaterBeanFactory.IS_DEVICESET).
* @param from When the data sampling started.
* @param to When the data sampling ended.
* @return A WaterBean object.
* @since 1.0
*/
public static WaterBean create(Map<String, List<WaterSample>> samples,
String queryPeriod, UUID uuid, int mode,
DateTime from, DateTime to) {
WaterBean bean = create(samples, queryPeriod, uuid, mode);
bean.period.from = from;
bean.period.to = to;
return bean;
}
/**
* Creates a WaterBean object.
*
* @param samples The data samples to embed into the water bean.
* @param queryPeriod The periodicity, denoted as a string.
* @param uuid The UUID of the sampled object.
* @param mode Tells whether the sampled object is a user (by using
* WaterBeanFactory.IS_USER), a device (by using
* WaterBeanFactory.IS_DEVICE), or a device set (by using
* WaterBeanFactory.IS_DEVICESET).
* @param from When the data was sampled.
* @return A WaterBean object.
* @since 1.0
*/
public static WaterBean create(Map<String, List<WaterSample>> samples,
String queryPeriod, UUID uuid, int mode, DateTime when) {
WaterBean bean = create(samples, queryPeriod, uuid, mode);
bean.period.when = when;
return bean;
}
private static WaterSummaryBean summarize(
Map<String, List<WaterSample>> samples) {
WaterSummaryBean summary = new WaterSummaryBean();
float totalVolume = 0.0f;
for (String deviceName : samples.keySet()) {
for (WaterSample sample : samples.get(deviceName)) {
totalVolume += sample.getVolume();
}
}
summary.totalVolume = totalVolume;
return summary;
}
private static List<WaterDataPointBean> createDataListFromSamples(
Map<String, List<WaterSample>> waterSamples) {
List<WaterDataPointBean> points = new ArrayList<>();
WaterDataPointBean bean = null;
for (Entry<String, List<WaterSample>> entry : waterSamples.entrySet()) {
for (int i = 0; i < entry.getValue().size(); i++) {
try {
bean = points.get(i);
} catch (IndexOutOfBoundsException e) {
bean = new WaterDataPointBean();
bean.humanReadableTimestamp = entry.getValue().get(i).getSampleTimestamp().toString();
bean.timestamp = entry.getValue().get(i).getSampleTimestamp().getMillis();
points.add(i, bean);
}
bean.volume += entry.getValue().get(i).getVolume();
}
}
return points;
}
}
| 28.035714 | 91 | 0.691932 |
785499cffc1809e54a89879a0d0878492e063dbf | 5,865 | /*
* Copyright 2021-present Open Networking Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.kubevirtnetworking.api;
import com.google.common.collect.ImmutableSet;
import com.google.common.testing.EqualsTester;
import org.junit.Before;
import org.junit.Test;
import org.onlab.packet.IpPrefix;
import java.util.Set;
import static junit.framework.TestCase.assertEquals;
import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutable;
/**
* Unit tests for the default kubevirt security group class.
*/
public class DefaultKubevirtSecurityGroupTest {
private static final String ID_1 = "id-1";
private static final String ID_2 = "id-1";
private static final String NAME_1 = "sg-1";
private static final String NAME_2 = "sg-2";
private static final String DESCRIPTION_1 = "sg-1";
private static final String DESCRIPTION_2 = "sg-2";
private static final String RULE_ID_1 = "rule-1";
private static final String RULE_ID_2 = "rule-2";
private static final String DIRECTION_1 = "ingress";
private static final String DIRECTION_2 = "egress";
private static final String ETHER_TYPE_1 = "IPv4";
private static final String ETHER_TYPE_2 = "IPv4";
private static final Integer PORT_RANGE_MAX_1 = 80;
private static final Integer PORT_RANGE_MAX_2 = 8080;
private static final Integer PORT_RANGE_MIN_1 = 80;
private static final Integer PORT_RANGE_MIN_2 = 8080;
private static final String PROTOCOL_1 = "tcp";
private static final String PROTOCOL_2 = "udp";
private static final IpPrefix REMOTE_IP_PREFIX_1 = IpPrefix.valueOf("10.10.10.0/24");
private static final IpPrefix REMOTE_IP_PREFIX_2 = IpPrefix.valueOf("20.20.20.0/24");
private static final String REMOTE_GROUP_ID_1 = "rid-1";
private static final String REMOTE_GROUP_ID_2 = "rid-2";
private static final Set<KubevirtSecurityGroupRule> RULES_1 = ImmutableSet.of(
createRule(
RULE_ID_1,
ID_1,
DIRECTION_1,
ETHER_TYPE_1,
PORT_RANGE_MAX_1,
PORT_RANGE_MIN_1,
PROTOCOL_1,
REMOTE_IP_PREFIX_1,
REMOTE_GROUP_ID_1
)
);
private static final Set<KubevirtSecurityGroupRule> RULES_2 = ImmutableSet.of(
createRule(
RULE_ID_2,
ID_2,
DIRECTION_2,
ETHER_TYPE_2,
PORT_RANGE_MAX_2,
PORT_RANGE_MIN_2,
PROTOCOL_2,
REMOTE_IP_PREFIX_2,
REMOTE_GROUP_ID_2
)
);
private KubevirtSecurityGroup sg1;
private KubevirtSecurityGroup sameAsSg1;
private KubevirtSecurityGroup sg2;
/**
* Tests class immutability.
*/
@Test
public void testImmutability() {
assertThatClassIsImmutable(DefaultKubevirtSecurityGroup.class);
}
/**
* Initial setup for this unit test.
*/
@Before
public void setUp() {
sg1 = DefaultKubevirtSecurityGroup.builder()
.id(ID_1)
.name(NAME_1)
.description(DESCRIPTION_1)
.rules(RULES_1)
.build();
sameAsSg1 = DefaultKubevirtSecurityGroup.builder()
.id(ID_1)
.name(NAME_1)
.description(DESCRIPTION_1)
.rules(RULES_1)
.build();
sg2 = DefaultKubevirtSecurityGroup.builder()
.id(ID_2)
.name(NAME_2)
.description(DESCRIPTION_2)
.rules(RULES_2)
.build();
}
/**
* Tests object equality.
*/
@Test
public void testEquality() {
new EqualsTester().addEqualityGroup(sg1, sameAsSg1)
.addEqualityGroup(sg2)
.testEquals();
}
/**
* Test object construction.
*/
@Test
public void testConstruction() {
KubevirtSecurityGroup sg = sg1;
assertEquals(ID_1, sg.id());
assertEquals(NAME_1, sg.name());
assertEquals(DESCRIPTION_1, sg.description());
assertEquals(RULES_1, sg.rules());
}
private static KubevirtSecurityGroupRule createRule(String id, String sgId,
String direction, String etherType,
Integer portRangeMax,
Integer portRangeMin,
String protocol,
IpPrefix remoteIpPrefix,
String remoteGroupId) {
return DefaultKubevirtSecurityGroupRule.builder()
.id(id)
.securityGroupId(sgId)
.direction(direction)
.etherType(etherType)
.portRangeMax(portRangeMax)
.portRangeMin(portRangeMin)
.protocol(protocol)
.remoteIpPrefix(remoteIpPrefix)
.remoteGroupId(remoteGroupId)
.build();
}
}
| 35.331325 | 91 | 0.587383 |
4d6d8fdbcf7f761ebbac4e799a67bb2a9f7024db | 181 | package org.dishorg.dishorg;
class RecipeNotFoundException extends RuntimeException {
RecipeNotFoundException(Long id) {
super("Could not find recipe #" + id);
}
}
| 22.625 | 56 | 0.712707 |
26ff95e5cf26a314a8b4c058a94a22c6c16b70ec | 3,228 | /*
* Copyright (c) 2008-2022 The Aspectran Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.aspectran.core.component.session;
import com.aspectran.core.util.logging.Logger;
import com.aspectran.core.util.logging.LoggerFactory;
import java.security.SecureRandom;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;
/**
* The Session ID Generator.
*
* <p>Created: 2017. 6. 12.</p>
*/
public class SessionIdGenerator {
private static final Logger logger = LoggerFactory.getLogger(SessionIdGenerator.class);
private static final AtomicLong COUNTER = new AtomicLong();
private final String workerName;
private final Random random;
private boolean weakRandom;
public SessionIdGenerator() {
this(null);
}
public SessionIdGenerator(String workerName) {
if (workerName != null && workerName.contains(".")) {
throw new IllegalArgumentException("Worker name cannot contain '.'");
}
this.workerName = workerName;
this.random = initRandom();
}
/**
* Returns a new unique session id.
* @param seedTerm the seed for RNG
* @return a new unique session id
*/
public String createSessionId(long seedTerm) {
synchronized (random) {
long r0;
if (weakRandom) {
r0 = hashCode() ^ Runtime.getRuntime().freeMemory() ^ random.nextInt() ^ (seedTerm << 32);
} else {
r0 = random.nextLong();
}
if (r0 < 0) {
r0 = -r0;
}
long r1;
if (weakRandom) {
r1 = hashCode() ^ Runtime.getRuntime().freeMemory() ^ random.nextInt() ^ (seedTerm << 32);
} else {
r1 = random.nextLong();
}
if (r1 < 0) {
r1 = -r1;
}
StringBuilder id = new StringBuilder();
id.append(Long.toString(r0, Character.MAX_RADIX));
id.append(Long.toString(r1, Character.MAX_RADIX));
id.append(COUNTER.getAndIncrement());
if (workerName != null) {
id.append(".").append(workerName);
}
return id.toString();
}
}
/**
* Set up a random number generator for the session ids.
*
* By preference, use a SecureRandom but allow to be injected.
*/
private Random initRandom() {
try {
return new SecureRandom();
} catch (Exception e) {
logger.warn("Could not generate SecureRandom for session-id randomness", e);
weakRandom = true;
return new Random();
}
}
}
| 30.45283 | 106 | 0.596344 |
291ca7f18b4ff1f433141f7a30861d4dabb073c4 | 4,478 | package io.stanwood.analyticstest.analytics;
import android.app.Application;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.firebase.perf.FirebasePerformance;
import java.util.HashMap;
import java.util.Map;
import io.stanwood.framework.analytics.BaseAnalyticsTracker;
import io.stanwood.framework.analytics.adjust.AdjustTracker;
import io.stanwood.framework.analytics.adjust.AdjustTrackerImpl;
import io.stanwood.framework.analytics.fabric.FabricTracker;
import io.stanwood.framework.analytics.fabric.FabricTrackerImpl;
import io.stanwood.framework.analytics.firebase.FirebaseTracker;
import io.stanwood.framework.analytics.firebase.FirebaseTrackerImpl;
import io.stanwood.framework.analytics.ga.GoogleAnalyticsTrackerImpl;
import io.stanwood.framework.analytics.generic.Tracker;
import io.stanwood.framework.analytics.generic.TrackerParams;
import io.stanwood.framework.analytics.generic.TrackingEvent;
import io.stanwood.framework.analytics.mixpanel.MixpanelTracker;
import io.stanwood.framework.analytics.mixpanel.MixpanelTrackerImpl;
import timber.log.Timber;
public class AdvancedAppTracker extends BaseAnalyticsTracker {
private static AdvancedAppTracker instance;
private AdvancedAppTracker(@NonNull Context context, @NonNull FabricTracker fabricTracker, @NonNull FirebaseTracker firebaseTracker,
@Nullable Tracker... optional) {
super(context, fabricTracker, firebaseTracker, optional);
if (BuildConfig.DEBUG) {
Timber.plant(new Timber.DebugTree());
}
}
public static synchronized void init(Application application) {
if (instance == null) {
FirebaseTracker firebaseTracker = FirebaseTrackerImpl.builder(application)
.mapFunction(new FirebaseTracker.MapFunction() {
@Override
public TrackerParams map(TrackerParams params) {
return params.newBuilder("fbevent").build();
}
}).build();
Tracker adjustTracker = AdjustTrackerImpl.builder(application, "KEY")
.mapFunction(new AdjustTracker.MapFunction() {
@Override
public String mapContentToken(TrackerParams params) {
if (TrackingEvent.SCREEN_VIEW.equalsIgnoreCase(params.getEventName()) && params.getName().equals("home")) {
return "ADJUST_CONTENT_ID";
}
return null;
}
})
.build();
Tracker mixpanelTracker = MixpanelTrackerImpl.builder(application, "KEY")
.mapFunction(new MixpanelTracker.MapFunction() {
@Override
public TrackerParams map(TrackerParams params) {
return TrackerParams.builder(params.getEventName())
.addCustomProperty("category", params.getCategory())
.addCustomProperty("action", params.getName())
.addCustomProperty("label", params.getItemId()).build();
}
})
.build();
Tracker gaTracker = GoogleAnalyticsTrackerImpl.builder(application, "KEY")
.setExceptionTrackingEnabled(true)
.build();
FabricTrackerImpl fabricTracker = FabricTrackerImpl.builder(application).build();
instance = new AdvancedAppTracker(application, fabricTracker, firebaseTracker, mixpanelTracker, adjustTracker, gaTracker);
FirebasePerformance.getInstance().setPerformanceCollectionEnabled(!BuildConfig.DEBUG);
}
}
public static AdvancedAppTracker instance() {
if (instance == null) {
throw new IllegalArgumentException("Call init() first!");
}
return instance;
}
public void trackAdLoaded(String adId) {
trackEvent(TrackerParams.builder("ad").setName("loaded").setId(adId).build());
}
public void trackShowDetails(String id, String name) {
Map<String, Object> map = new HashMap<>(2);
map.put("id", id);
map.put("name", name);
trackScreenView("details", map);
}
} | 46.645833 | 136 | 0.635998 |
6d582bddbb710185a0bd045c630b6e90ce1c12dc | 4,557 | package de.ugoe.cs.smartshark.mutaSHARK.util;
import com.github.gumtreediff.actions.model.*;
import com.github.gumtreediff.tree.ITree;
import de.ugoe.cs.smartshark.mutaSHARK.util.defects4j.Defects4JBugFix;
import org.apache.commons.lang3.NotImplementedException;
import java.util.ArrayList;
public class ActionExecutor
{
public ActionExecutor()
{
}
public void executeAction(Action action)
{
if (action instanceof Insert)
{
executeInsert((Insert) action);
}
else if (action instanceof Addition)
{
executeAddition((Addition) action);
}
else if (action instanceof Move)
{
executeMove((Move) action);
}
else if (action instanceof Update)
{
executeUpdate((Update) action);
}
else if (action instanceof Delete)
{
executeDelete((Delete) action);
}
else if (action instanceof Replace)
{
executeReplace((Replace) action);
}
else
{
throw new UnsupportedOperationException("The action " + action.getName() + " is unsupported");
}
}
private void executeReplace(Replace action)
{
ITree parent = action.getOriginalNode().getParent();
assert parent == action.getNewNode().getParent();
ArrayList<ITree> newChildren = new ArrayList<>(parent.getChildren());
for (int i = 0; i < newChildren.size(); i++)
{
ITree oldChild = newChildren.get(i);
if (oldChild == action.getOriginalNode())
{
newChildren.remove(oldChild);
newChildren.add(i, action.getNewNode());
}
}
parent.setChildren(newChildren);
}
private void executeDelete(Delete action)
{
TreeNode parent = new TreeNode(action.getNode().getParent());
parent.removeChild(action.getNode());
}
private void executeUpdate(Update action)
{
throw new NotImplementedException("executeUpdate not implemented for " + action);
}
private void executeMove(Move action)
{
TreeNode treeNode = new TreeNode(action.getNode().getParent());
treeNode.removeChild(action.getNode());
action.getParent().insertChild(action.getNode(), action.getPosition());
}
private void executeAddition(Addition action)
{
throw new NotImplementedException("executeUpdate not implemented for " + action);
}
private void executeInsert(Insert action)
{
ITree node = action.getNode();
action.getParent().insertChild(node, action.getPosition());
}
public Move reassignTree(Move move, ITree clonedTree)
{
ITree originalParent = move.getParent();
ITree originalNode = move.getNode();
String originalParentUrl = TreeHelper.getUrl(originalParent, Integer.MAX_VALUE);
String originalNodeUrl = TreeHelper.getUrl(originalNode, Integer.MAX_VALUE);
ITree newParent = clonedTree.getChild(originalParentUrl);
ITree newNode = clonedTree.getChild(originalNodeUrl);
return new Move(newNode, newParent, move.getPosition());
}
public Replace reassignTree(Replace replace, ITree clonedTree)
{
ITree originalOriginalNode = replace.getOriginalNode();
ITree originalNewNode = replace.getNewNode();
String originalOriginalNodeUrl = TreeHelper.getUrl(originalOriginalNode, Integer.MAX_VALUE);
String originalNewNodeUrl = TreeHelper.getUrl(originalNewNode, Integer.MAX_VALUE);
ITree newOriginalNode = clonedTree.getChild(originalOriginalNodeUrl);
ITree newNewNode = clonedTree.getChild(originalNewNodeUrl);
return new Replace(newOriginalNode, newNewNode);
}
public Delete reassignTree(Delete delete, ITree clonedTree)
{
ITree originalNode = delete.getNode();
String originalNodeUrl = TreeHelper.getUrl(originalNode, Integer.MAX_VALUE);
ITree newNode = clonedTree.getChild(originalNodeUrl);
return new Delete(newNode);
}
public Insert reassignTree(Insert insert, ITree clonedTree)
{
ITree originalParent = insert.getParent();
ITree originalNode = insert.getNode().deepCopy();
String originalParentUrl = TreeHelper.getUrl(originalParent, Integer.MAX_VALUE);
ITree newParent = clonedTree.getChild(originalParentUrl);
return new Insert(originalNode, newParent, insert.getPosition());
}
}
| 33.755556 | 106 | 0.653939 |
4ba31ac8429dc6c39311280c7a4f77a4fda72e6c | 7,140 | package fr.faylixe.ekite.internal;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import org.eclipse.core.resources.IFile;
import org.eclipse.jface.text.IDocument;
import com.google.gson.Gson;
import fr.faylixe.ekite.EKitePlugin;
import fr.faylixe.ekite.model.ActionEvent.ErrorEvent;
import fr.faylixe.ekite.model.ActionEvent.FocusEvent;
import fr.faylixe.ekite.model.ActionEvent.LostFocusEvent;
import fr.faylixe.ekite.model.NotificationEvent.EditEvent;
import fr.faylixe.ekite.model.NotificationEvent.SelectionEvent;
import fr.faylixe.ekite.model.ActionEvent;
import fr.faylixe.ekite.model.Selection;
/**
* This class is in charge of dispatching event
* to Kite using UDP socket.
*
* @author fv
*/
public final class EventSender {
/** Exception thrown when no file name and document is set. **/
private static final IllegalStateException NO_CURRENT_FILE = new IllegalStateException("No current file / document settled.");
/** 2 MB buffer size. **/
private static final int BUFFER_SIZE = 2 << 20;
/** Gson instance for transforming event to JSON. **/
private final Gson gson;
/** Target socket to send data to. **/
private final DatagramSocket socket;
/** **/
private final EventReceiver receiver;
/** Plugin identifier to use for built event. **/
private final String pluginId;
/** Kite server hostname. **/
private String hostname;
/** Kite server port. **/
private int port;
/** Currently edited file name. **/
private String currentFilename;
/** Currently edited document model. **/
private IDocument currentDocument;
/**
* Default constructor.
*
* @param socket
* @param receiver
*/
private EventSender(final DatagramSocket socket, final EventReceiver receiver) {
this.socket = socket;
this.receiver = receiver;
this.pluginId = receiver.getPluginIdentifier();
if (EKitePlugin.DEBUG) {
EKitePlugin.log("Plugin identifier : " + pluginId);
}
this.gson = new Gson();
}
/**
* Current filename setter.
*
* @param filename Name of the currently edited file.
*/
public void setCurrentFilename(final String filename) {
this.currentFilename = filename;
}
/**
* Current file setter.
*
* @param file Currently edited file.
*/
public void setCurrentFile(final IFile file) {
receiver.setCurrentFile(file);
}
/**
* Current document setter.
*
* @param document Currently edited document.
*/
public void setCurrentDocument(final IDocument document) {
this.currentDocument = document;
receiver.setCurrentDocument(document);
}
/**
* Hostname setter.
*
* @param hostname Kite server hostname.
*/
public void setHostname(final String hostname) {
this.hostname = hostname;
}
/**
* Port setter.
*
* @param port Kite server port.
*/
public void setPort(final int port) {
this.port = port;
}
/**
* Sends an <tt>selection</tt> event to Kite.
*
* @param start Start position of the current edition.
* @param end End position of the current edition.
*
* @throws IOException If any error occurs while sending the event.
* @throws IllegalStateException If no current file or current document name is settled.
*/
public void sendSelection(final int start, final int end) throws IOException {
if (currentFilename == null || currentDocument == null) {
throw NO_CURRENT_FILE;
}
final String text = currentDocument.get();
final SelectionEvent event = new SelectionEvent(pluginId, currentFilename, text);
final Selection selection = new Selection(start, end);
event.addSelection(selection);
sendEvent(event);
}
/**
* Sends an <tt>edit</tt> event to Kite.
*
* @param start Start position of the current edition.
* @param end End position of the current edition.
*
* @throws IOException If any error occurs while sending the event.
* @throws IllegalStateException If no current file or current document name is settled.
*/
public void sendEdit(final int start, final int end) throws IOException {
if (currentFilename == null || currentDocument == null) {
throw NO_CURRENT_FILE;
}
final String text = currentDocument.get();
final EditEvent event = new EditEvent(pluginId, currentFilename, text);
final Selection selection = new Selection(start, end);
event.addSelection(selection);
sendEvent(event);
}
/**
* Sends an <tt>error</tt> event to Kite.
*
* @throws IOException If any error occurs while sending the event.
* @throws IllegalStateException If no current file name is settled.
*/
public void sendError(final String text) throws IOException {
if (currentFilename == null) {
throw NO_CURRENT_FILE;
}
final ErrorEvent event = new ErrorEvent(pluginId, currentFilename, text);
sendEvent(event);
}
/**
* Sends a <tt>focus</tt> event to Kite.
*
* @throws IOException If any error occurs while sending the event.
* @throws IllegalStateException If no current file name is settled.
*/
public void sendFocus() throws IOException {
if (currentFilename == null) {
throw NO_CURRENT_FILE;
}
final FocusEvent event;
if (currentDocument == null) {
event = new FocusEvent(pluginId, currentFilename);
}
else {
event = new FocusEvent(pluginId, currentFilename, currentDocument.get());
}
sendEvent(event);
}
/**
* Sends a <tt>lost_focus</tt> event to Kite.
*
* @throws IOException If any error occurs while sending the event.
* @throws IllegalStateException If no current file name is settled.
*/
public void sendLostFocus() throws IOException {
if (currentFilename == null) {
throw NO_CURRENT_FILE;
}
final LostFocusEvent event = new LostFocusEvent(pluginId, currentFilename);
sendEvent(event);
}
/**
* Sends the given <tt>event</tt> to Kite as
* a JSON blob to the target UDP socket.
*
* @param event Event to send.
* @throws IOException If any error occurs while sending the event.
*/
private synchronized void sendEvent(final ActionEvent event) throws IOException {
try {
final String json = gson.toJson(event);
if (EKitePlugin.DEBUG) {
EKitePlugin.log("Sending event : " + json);
}
final byte[] bytes = json.getBytes();
final DatagramPacket packet = new DatagramPacket(bytes,
bytes.length,
InetAddress.getByName(hostname),
port);
socket.send(packet);
}
catch (final IllegalStateException e) {
throw new IOException(e);
}
}
/**
* Creates and returns an {@link EventSender} instance.
*
* @param receiver Receiver instance this sender will be bound to.
* @param hostname Kite socket hostname.
* @param port Kite socket port.
* @return Created instance.
* @throws IOException If any error occurs while creating associated socket.
*/
public static EventSender create(final EventReceiver receiver, final String hostname, final int port) throws IOException {
final DatagramSocket socket = new DatagramSocket();
socket.setSendBufferSize(BUFFER_SIZE);
final EventSender instance = new EventSender(socket, receiver);
instance.setHostname(hostname);
instance.setPort(port);
return instance;
}
}
| 28.110236 | 127 | 0.717367 |
fe941477a08a37146ddcac4f0c59bd97d6587a84 | 374 | package com.chansuk.productservice.dao;
import com.chansuk.productservice.model.Music;
import com.chansuk.productservice.model.Product;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface MusicDao extends JpaRepository<Music, Integer> {
Music findById(int id);
List<Music> findByNomAlbumLike(String recherche);
}
| 28.769231 | 65 | 0.81016 |
614c1055df24fee977c49f0ac2d8fcae2bac1e5b | 4,130 | /*
* The MIT License (MIT)
*
* Copyright (c) 2021-2022 Yegor Bugayenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// @checkstyle PackageNameCheck (1 line)
package EOorg.EOeolang.EOfs;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.OpenOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Collection;
import java.util.LinkedList;
import org.eolang.AtComposite;
import org.eolang.AtFree;
import org.eolang.Data;
import org.eolang.Dataized;
import org.eolang.PhDefault;
import org.eolang.Phi;
/**
* File.as-output.
*
* @since 0.1
* @checkstyle TypeNameCheck (100 lines)
*/
@SuppressWarnings("PMD.AvoidDollarSigns")
public class EOfile$EOas_output extends PhDefault {
/**
* Ctor.
* @param sigma The \sigma
* @checkstyle BracketsStructureCheck (200 lines)
*/
@SuppressWarnings("PMD.ConstructorOnlyInitializesOrCallOtherConstructors")
public EOfile$EOas_output(final Phi sigma) {
this(sigma, null);
}
/**
* Ctor.
* @param sigma The \sigma
* @param out Output stream of NULL
* @checkstyle BracketsStructureCheck (200 lines)
*/
@SuppressWarnings("PMD.ConstructorOnlyInitializesOrCallOtherConstructors")
public EOfile$EOas_output(final Phi sigma, final OutputStream out) {
super(sigma);
this.add("mode", new AtFree());
this.add("φ", new AtComposite(this, rho -> new Data.ToPhi(true)));
this.add("write", new AtComposite(this, self -> {
OutputStream stream = out;
if (stream == null) {
final String mode = new Dataized(
self.attr("mode").get()
).take(String.class);
final Path path = Paths.get(
new Dataized(
self.attr("ρ").get()
).take(String.class)
);
stream = EOfile$EOas_output.stream(path, mode);
}
return new EOfile$EOas_output$EOwrite(self, stream);
}));
this.add("close", new AtComposite(this, self -> {
if (out != null) {
out.close();
}
return new Data.ToPhi(true);
}));
}
/**
* Make an output stream.
* @param path The path
* @param opts Opts
* @return Stream
* @throws IOException If fails
*/
private static OutputStream stream(final Path path, final String opts)
throws IOException {
final Collection<OpenOption> options = new LinkedList<>();
for (final char chr : opts.toCharArray()) {
if (chr == 'w') {
options.add(StandardOpenOption.WRITE);
}
if (chr == 'a') {
options.add(StandardOpenOption.APPEND);
}
}
if (opts.indexOf('+') < 0) {
options.add(StandardOpenOption.CREATE);
}
return Files.newOutputStream(path, options.toArray(new OpenOption[0]));
}
}
| 34.132231 | 80 | 0.637046 |
13fc858b1e24264396d138d9828d73065f935235 | 278 | public void copyFile(File in, File out) throws Exception {
FileChannel ic = new FileInputStream(in).getChannel();
FileChannel oc = new FileOutputStream(out).getChannel();
ic.transferTo(0, ic.size(), oc);
ic.close();
oc.close();
}
| 34.75 | 64 | 0.607914 |
fd2f54ab95b3719f8179cfe2b1bffde62bac6036 | 2,575 | package com.in726.app.e2e.test.chrome;
import com.in726.app.e2e.page.LoginPage;
import com.in726.app.e2e.page.MainPage;
import com.in726.app.e2e.page.UrlMonitorPage;
import com.in726.app.e2e.util.Util;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.util.Date;
import java.util.concurrent.TimeUnit;
public class UrlTest {
private static WebDriver driver;
private static LoginPage loginPage;
private static MainPage mainPage;
private static UrlMonitorPage urlMonitorPage;
@BeforeClass
public static void setup() {
System.setProperty("webdriver.chrome.driver", Util.getProperty("chromedriver"));
ChromeOptions options = new ChromeOptions();
options.addArguments("incognito");
driver = new ChromeDriver(options);
loginPage = new LoginPage(driver);
mainPage = new MainPage(driver);
urlMonitorPage = new UrlMonitorPage(driver);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get(Util.getProperty("homepage"));
}
@Test
public void createUrl() throws InterruptedException {
loginPage.setUsernameInput(Util.getProperty("login"));
loginPage.setPasswordInput(Util.getProperty("password"));
loginPage.clickLoginBtn();
Thread.sleep(2000);
mainPage.clickNewUrlBtn();
var urlName = "seleniumTest" + new Date().getTime();
var url = "https://t6.tss2020.site";
urlMonitorPage.setUrlNameInput(urlName);
urlMonitorPage.setUrlInput(url);
urlMonitorPage.setSelectSecondsToCheckByIndex("1800");
urlMonitorPage.setWordsTextArea("Log in");
Util.takeScreenShot(driver);
Thread.sleep(2000);
urlMonitorPage.clickUrlAddBtn();
Thread.sleep(2000);
var actualSingUpStatus = driver.switchTo().alert().getText();
driver.switchTo().alert().accept();
Assert.assertEquals("Link created successfully.", actualSingUpStatus);
driver.navigate().refresh();
Thread.sleep(2000);
urlMonitorPage.linkSelectByVisual(urlName);
Assert.assertTrue(urlMonitorPage.isDisplayedUrlsTable());
urlMonitorPage.clickMainPageBtn();
mainPage.clickLogoutBtn();
}
@AfterClass
public static void tearDown() {
driver.quit();
}
}
| 34.333333 | 88 | 0.695146 |
3b5bdd9d79db17817a855431c37c38c801b5ee72 | 2,506 | package hr.fer.zemris.jcms.desktop.satnica;
import hr.fer.zemris.jcms.parsers.TextService;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class StudentiBezSatnice {
/**
* @param args
*/
public static void main(String[] args) throws IOException {
if(args.length != 3) {
System.err.println("Ocekivao sam: isvu grupe_bez_satnice out/procisceniISVU");
System.exit(0);
}
InputStream is = new BufferedInputStream(new FileInputStream(args[1]));
List<String> satnicaLines = TextService.inputStreamToUTF8StringList(is);
Map<String,String> grupeBezSatnice = new HashMap<String, String>(100);
for(String line : satnicaLines) {
grupeBezSatnice.put(line, line);
//String[] elems = TextService.split(line, '/');
}
is = new BufferedInputStream(new FileInputStream(args[0]));
List<String> isvuLines = TextService.inputStreamToUTF8StringList(is);
Map<String,List<String>> studentiBezSatnice = new HashMap<String, List<String>>(100);
Map<String,String> kolegiji = new HashMap<String, String>(100);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(args[2])),"UTF-8"));
for(String line : isvuLines) {
String[] elems = TextService.split(line, '#');
String kljuc = elems[2]+"/"+elems[4];
kljuc = grupeBezSatnice.get(kljuc);
if(kljuc==null){
bw.write(line);
bw.write("\r\n");
continue;
}
List<String> list = studentiBezSatnice.get(kljuc);
if(list==null) {
list = new ArrayList<String>();
studentiBezSatnice.put(kljuc, list);
kolegiji.put(kljuc, elems[6]);
}
list.add(elems[0]);
elems[4]="";
bw.write(elems[0]);
for(int i = 1; i < elems.length; i++) {
bw.write('#');
bw.write(elems[i]);
}
bw.write("\r\n");
}
bw.flush();
bw.close();
List<String> keys = new ArrayList<String>(grupeBezSatnice.keySet());
Collections.sort(keys);
for(String kljuc : keys) {
List<String> studenti = studentiBezSatnice.get(kljuc);
if(studenti==null) {
System.out.println(kljuc+": 0");
} else {
System.out.println(kljuc+": "+studenti.size()+" ("+kolegiji.get(kljuc)+")");
}
}
}
}
| 30.192771 | 130 | 0.694733 |
ec299d93d5491177c61b8c52ae28d1ac70aa77b0 | 2,098 | package com.robin.algorithm.datastructures.unionfind;
public class UnionFind {
private int size;
private int[] rank;
private int[] father;
private int numComponents;
public UnionFind(int size) {
if (size <= 0) {
throw new IllegalArgumentException("Size <= 0 is not allowed");
}
this.size = numComponents = size;
rank = new int[size];
father = new int[size];
for (int i = 0; i < size; i++) {
father[i] = i;
rank[i] = 1;
}
}
public int find(int p) {
int root = p;
while (root != father[root]){
root = father[root];
}
while (p != root) {
int next = father[p];
father[p] = root;
p = next;
}
return root;
}
public int componentSize(int p) {
return rank[find(p)];
}
public int size() {
return size;
}
public int components() {
return numComponents;
}
public void union(int p, int q) {
int root1 = find(p);
int root2 = find(q);
if (rank[root1] < rank[root2]) {
rank[root2] += rank[root1];
father[root1] = root2;
} else {
rank[root1] += rank[root2];
father[root2] = root1;
}
numComponents--;
}
public boolean isConnected(int p, int q){
return find(p) == find(q);
}
public static void main(String[] args) {
int n = 10;
UnionFind union = new UnionFind(n);
System.out.println("初始:");
System.out.println("连接了5 6");
union.union(5, 6);
System.out.println("连接了1 2");
union.union(1, 2);
System.out.println("连接了2 3");
union.union(2, 3);
System.out.println("连接了1 4");
union.union(1, 4);
System.out.println("连接了1 5");
union.union(1, 5);
System.out.println("1 6 是否连接:" + union.isConnected(1, 6));
System.out.println("1 8 是否连接:" + union.isConnected(1, 8));
}
}
| 20.98 | 75 | 0.492374 |
9ea370bbf0580e7e480dd8f37847e7c53d4358ec | 1,011 | package com.redhat.quotegame.util;
import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.kafka.common.errors.SerializationException;
import org.apache.kafka.common.serialization.Deserializer;
/**
* Generic Kafka deserialiser for reading JSON to POJO.
* @param <T>
* @author laurent
*/
public class JsonPojoDeserializer<T> implements Deserializer<T> {
protected final static ObjectMapper OBJECT_MAPPER = new ObjectMapper();
protected Class<T> clazz;
@Override
public void configure(Map<String, ?> props, boolean data) { }
@Override
public T deserialize(String topic, byte[] bytes) {
if (bytes == null) {
return null;
}
T data;
try {
data = OBJECT_MAPPER.readValue(bytes, clazz);
} catch (Exception e) {
throw new SerializationException("Error deserializing JSON message", e);
}
return data;
}
@Override
public void close() { }
} | 25.275 | 84 | 0.657765 |
2f92215f4951c6281b55795c671798daafea6784 | 819 | package ren.crux.rainbow.runtime;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import ren.crux.rainbow.core.RequestGroupProvider;
@Configuration
@ConditionalOnWebApplication
public class RainbowAutoConfiguration {
@Bean
@ConditionalOnBean(RequestMappingHandlerMapping.class)
public RequestGroupProvider springBootRequestGroupProvider(RequestMappingHandlerMapping requestMappingHandlerMapping) {
return new SpringBootRequestGroupProvider(requestMappingHandlerMapping);
}
}
| 39 | 123 | 0.859585 |
9d2b3a278131af3a535225a8b3942f74d58b8381 | 468 | package com.wqt.springboot.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
/**
* @author iuShu
* @date Mar 29, 2018 6:35:15 PM
*/
@ComponentScan
@EnableAutoConfiguration
public class ExampleRunner {
public static void main(String[] args) {
SpringApplication.run(ExampleRunner.class, args);
}
}
| 23.4 | 71 | 0.760684 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.