method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
02b6d0ce-674f-4064-b9a4-907f30518e44 | 1 | public Constant newUTF8(final String value) {
key1.set('s', value, null, null);
Constant result = get(key1);
if (result == null) {
result = new Constant(key1);
put(result);
}
return result;
} |
e64140f1-3915-4998-a9fa-c31b92088f21 | 7 | private static void requestAndParseAllMeasurementsBelongingToExactGSMCells() {
String fileName = "/Users/Johan/Documents/CellTowers/cell_towers_GSM_exact.csv";
try(BufferedReader br = new BufferedReader(new FileReader(fileName));){
String line = "";
int totalCount = 0;
int count = 0;
JSONFile jsonFile = new JSONFile(JSONFile.filePathCellTowers+"cells_exact_samples67-80"+JSONFile.fileFormat);
jsonFile.iWannaStartAnArray("cells");
long startTime = System.currentTimeMillis();
System.out.println("Starting to read from file..");
while((line = br.readLine()) != null) {
totalCount++;
if(totalCount%30000==0)
System.out.println("Read "+totalCount+" lines..");
String[] fields = line.split(",");
int samples = Integer.parseInt(fields[9]);
if(samples >= 67 && samples <=80) {
Request request = new Request(fields[1], fields[2], fields[3], fields[4]);
OpenCellIdCell openCellIdCell = request.getData();
jsonFile.writeThisOpenCellIdCell(openCellIdCell);
count++;
if(count%100==0)
System.out.println("Parsed "+count+" cells..");
}
}
jsonFile.theArrayIsDone();
jsonFile.iAmDoneWriting();
System.out.println("Done reading from file..\n");
double timeElapsed = (System.currentTimeMillis()-startTime)/(double)1000;
System.out.println("Read "+totalCount+" lines..\n");
System.out.println("Count is "+count);
System.out.println("Time elapsed: "+timeElapsed+" seconds");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} |
89763307-ff7e-4807-88bd-7362f3a55320 | 3 | public Command recv (long timeout_)
{
Command cmd_ = null;
// Try to get the command straight away.
if (active) {
cmd_ = cpipe.read ();
if (cmd_ != null) {
return cmd_;
}
// If there are no more commands available, switch into passive state.
active = false;
signaler.recv ();
}
// Wait for signal from the command sender.
boolean rc = signaler.wait_event (timeout_);
if (!rc)
return null;
// We've got the signal. Now we can switch into active state.
active = true;
// Get a command.
cmd_ = cpipe.read ();
assert (cmd_ != null);
return cmd_;
} |
a7566a6b-622f-408e-b0cb-cdad642ec60e | 0 | private Set<Card> sevenFlush() {
return convertToCardSet("2S,6S,8S,3S,9S,KS,JS");
} |
2eeeeb7a-1e56-4ae6-94d5-6f0ffbe59f2a | 7 | public void render(){
BufferStrategy bs = getBufferStrategy();
if(bs == null){
createBufferStrategy(3);
return;
}
int xOffset = player.x-screen.width/2;
int yOffset = player.y-screen.height/2;
level.renderTiles(screen, xOffset, yOffset);
for(int x=0; x<level.width;x++){
int color = Colors.get(-1,-1,-1,000);
if(x%10==0&&x!=0){
color = Colors.get(-1, -1,-1,500);
}
//Font.render(x%10+"", screen, x*8, 0, color);
}
level.renderEntities(screen);
for(int y=0;y<screen.height;y++){
for(int x=0; x<screen.width; x++){
int colorCode = screen.pixels[x+y*screen.width];
if(colorCode<255) pixels[x+y*WIDTH] = colors[colorCode];
}
}
Graphics g = bs.getDrawGraphics();
g.drawImage(image,0,0,getWidth(),getHeight(),null);
g.dispose();
bs.show();
} |
4f80eacc-bf81-48f3-a121-9e82dd8a618f | 7 | public void prepare(Dish dish) {
LinkedList<Material> materials = dish.getMaterials();
for (Material tmp : materials) {
for (StorageAdapter storage : storageList) {
if (tmp.getName().equals(storage.getName())) {
storage.setAmount(storage.getAmount() - tmp.getAmount());
}
}
}
LinkedList<Ingredient> ingredients = dish.getIngredients();
for (Ingredient tmp : ingredients) {
for (StorageAdapter storage : storageList) {
if (tmp.getName().equals(storage.getName()) && storage.getAmount() > 0) {
storage.setAmount(storage.getAmount() - 1);
}
}
}
nodifyObserver();
} |
847b12e2-9a0f-4f63-866c-786527e295ee | 9 | public void getInput()
{
while (Keyboard.next())
{
//if(!chatMode){
if(getStats().isAlive())
{
if(Keyboard.isKeyDown(Keyboard.KEY_A))
{
movx = MOVE_LEFT;
spr.setAnimation(1);
}
else if(Keyboard.isKeyDown(Keyboard.KEY_D))
{
movx = MOVE_RIGHT;
spr.setAnimation(0);
}
else
{
movx = MOVE_NULL;
}
if(Keyboard.isKeyDown(Keyboard.KEY_SPACE))
justJump = true;
}
else
{
Main.spawnGUI(0);
movx = MOVE_NULL;
}
//}
//else{
//}
}
while (Mouse.next())
{
if (Mouse.getEventButtonState()) {
if (Mouse.getEventButton() == 0) {
click(Mouse.getX()/16 + Camera.getX()/16, Mouse.getY()/16 + Camera.getY()/16);
}
}else {
if (Mouse.getEventButton() == 0) {
}
}
}
} |
27aef7a7-e633-4248-8194-b1a129a4ef46 | 7 | public static boolean testPropertyP(Stella_Object self, Surrogate relation) {
{ MemoizationTable memoTable000 = null;
Cons memoizedEntry000 = null;
Stella_Object memoizedValue000 = null;
if (Stella.$MEMOIZATION_ENABLEDp$) {
memoTable000 = ((MemoizationTable)(Logic.SGT_LOGIC_F_TEST_PROPERTYp_MEMO_TABLE_000.surrogateValue));
if (memoTable000 == null) {
Surrogate.initializeMemoizationTable(Logic.SGT_LOGIC_F_TEST_PROPERTYp_MEMO_TABLE_000, "(:MAX-VALUES 500 :TIMESTAMPS (:KB-UPDATE))");
memoTable000 = ((MemoizationTable)(Logic.SGT_LOGIC_F_TEST_PROPERTYp_MEMO_TABLE_000.surrogateValue));
}
memoizedEntry000 = MruMemoizationTable.lookupMruMemoizedValue(((MruMemoizationTable)(memoTable000)), self, relation, ((Context)(Stella.$CONTEXT$.get())), Stella.MEMOIZED_NULL_VALUE, 6);
memoizedValue000 = memoizedEntry000.value;
}
if (memoizedValue000 != null) {
if (memoizedValue000 == Stella.MEMOIZED_NULL_VALUE) {
memoizedValue000 = null;
}
}
else {
memoizedValue000 = (Logic.helpMemoizeTestPropertyP(self, relation) ? Stella.TRUE_WRAPPER : Stella.FALSE_WRAPPER);
if (Stella.$MEMOIZATION_ENABLEDp$) {
memoizedEntry000.value = ((memoizedValue000 == null) ? Stella.MEMOIZED_NULL_VALUE : memoizedValue000);
}
}
{ BooleanWrapper value000 = ((BooleanWrapper)(memoizedValue000));
return (BooleanWrapper.coerceWrappedBooleanToBoolean(value000));
}
}
} |
4d1a8577-f623-424c-a0aa-8a4e42c69f48 | 9 | private void searchGoodWord(List<String> words) {
if(words != null && !words.isEmpty()) {
List<Keyword> keywordList = dictionary.getKeywordList();
int priority = -1;
float distance = 1;
int elementId = -1;
int elementIdRegardingDistance = 0;
for(int i = 0; i < words.size(); i++) {
String[] possibleWords = words.get(i).split(";");
for(int j = 0; j < keywordList.size(); j++) {
if(possibleWords[1].equals(keywordList.get(j).getWord())
&& keywordList.get(j).getKeywordData().getPriority() > priority
&& (float)Integer.parseInt(possibleWords[2]) / possibleWords[1].length() < 0.3) {
priority = keywordList.get(j).getKeywordData().getPriority();
elementId = i;
} else if ((float)Integer.parseInt(possibleWords[2]) / possibleWords[1].length() < distance) {
distance = (float)Integer.parseInt(possibleWords[2]) / possibleWords[1].length();
elementIdRegardingDistance = i;
}
}
}
if(elementId >= 0) {
String[] possibleWord = words.get(elementId).split(";");
this.questionableWord = possibleWord[1];
words.remove(elementId);
this.possibleWords = words;
} else {
String[] possibleWord = words.get(elementIdRegardingDistance).split(";");
this.questionableWord = possibleWord[1];
words.remove(elementIdRegardingDistance);
this.possibleWords = words;
}
} else {
this.possibleWords = null;
}
} |
272c6ee8-3911-4bac-8201-e8e1692f8424 | 7 | public void move() throws Exception {
rightPressed = false;
View.count++;
int timer = 100;
int result = 0;
int divider = 0;
System.out.println("Dragged method running");
OpenCVFrameGrabber grabber = new OpenCVFrameGrabber(0);
grabber.start();
//Create canvas frame for displaying webcam.
//CanvasFrame canvasW = new CanvasFrame("Webcam");
//Set Canvas frame to close on exit
IplImage orgImg = grabber.grab();
//Set canvas size as per dimentions of video frame.
//canvasW.setCanvasSize(grabber.getImageWidth(), grabber.getImageHeight());
// threshold the captured image using the lower and upper thresholds
// defined above
// see end of the code for explanation on contours
outerloop:
while ((orgImg = grabber.grab()) != null) {
timer --;
if(timer == 0) {
break outerloop;
}
// threshold the captured image using the lower and upper thresholds
IplImage thresholdImage = hsvThreshold(orgImg);
CvMemStorage mem = CvMemStorage.create();
CvSeq contours = new CvSeq(orgImg);
contours = cvCreateSeq(0, sizeof(CvContour.class),
sizeof(CvSeq.class), mem);
cvFindContours(thresholdImage.clone(), mem, contours,
Loader.sizeof(CvContour.class), CV_RETR_CCOMP,
CV_CHAIN_APPROX_SIMPLE, cvPoint(0, 0));
while (contours != null && !contours.isNull()) {
divider++;
System.out.println(divider);
// define a 2D rectangle structure that will be the bounding box of the contour of the object
CvRect br = cvBoundingRect(contours, 1);
// draw a GREEN rectangle around the contour (of the object detected)
cvRectangle(orgImg, cvPoint(br.x(), br.y()),
cvPoint(br.x() + br.width(), br.y() + br.height()),
CvScalar.GREEN, 3, CV_AA, 0);
if(divider%2==0)
{
result = result - br.x();
if(result > 0)
{
clockViewCard.displayedTime.add(Calendar.HOUR_OF_DAY, 3);
System.out.println("add 3");
break outerloop;
}
else if(result < 0)
{
clockViewCard.displayedTime.add(Calendar.HOUR_OF_DAY, -3);
System.out.println("minus 3");
result = 0;
break outerloop;
}
//else if(result ==0) System.out.println("Nothing");
}
else result = br.x();
cvWaitKey(2);
// do all of the above for the next contour
contours = contours.h_next();
}
// show the detected 'coloured' objects with rectangles drawn on on the initially captured image
//canvasW.showImage(orgImg);
}
grabber.stop();
//canvasW.dispose();
clockViewCard.repaint();
} |
2f41cedd-9876-4572-8278-f8722809179e | 5 | public Instruction findMatchingPop() {
int poppush[] = new int[2];
getStackPopPush(poppush);
int count = poppush[1];
Instruction instr = this;
while (true) {
if (instr.succs != null || instr.doesAlwaysJump())
return null;
instr = instr.nextByAddr;
if (instr.preds != null)
return null;
instr.getStackPopPush(poppush);
if (count == poppush[0])
return instr;
count += poppush[1] - poppush[0];
}
} |
875671cf-ef0c-4a37-9be9-8bf231ff82f2 | 9 | public int compareTo(Object b)
{
if (getClass() == b.getClass())
{
EventModel a = (EventModel) b;
if (year > a.year)
{
return 1;
}
if (year < a.year)
{
return -1;
}
if (month > a.month)
{
return 1;
}
if (month < a.month)
{
return -1;
}
if (day > a.day)
{
return 1;
}
if (day < a.day)
{
return -1;
}
if (hour > a.hour)
{
return 1;
}
if (hour < a.hour)
{
return -1;
}
return 0;
}
return 0;
} |
e345be4c-fb66-423a-8ce3-1a9df5855944 | 9 | private TransformNode createNode(String className)
throws ClassNotFoundException {
TransformNode tr = null;
if (ConnectNode.class.getName().equals(className)) {
tr = soundProcessor.createConnectNode();
} else if (EchoNode.class.getName().equals(className)) {
tr = soundProcessor.createEchoNode();
} else if (AutoMuteNode.class.getName().equals(className)) {
tr = soundProcessor.createAutoMuteNode();
} else if (ModulateNode.class.getName().equals(className)) {
tr = soundProcessor.createModulateNode();
} else if (VolumeNode.class.getName().equals(className)) {
tr = soundProcessor.createVolumeNode();
} else if (LevelMeterNode.class.getName().equals(className)) {
tr = soundProcessor.createLevelMeterNode();
} else if (SequenceNode.class.getName().equals(className)) {
tr = soundProcessor.createSequenceNode();
} else if (MixerNode.class.getName().equals(className)) {
tr = soundProcessor.createMixerNode();
} else if (ToneShiftNode.class.getName().equals(className)) {
tr = soundProcessor.createToneShiftNode();
} else {
throw new ClassNotFoundException(className);
}
return tr;
} |
ffb6b2e2-74b4-4ec6-8165-6a85551d4063 | 8 | public static void main(String[] args) {
boolean timeToExit = false;
do {
System.out.println("Выберите действие: ");
System.out.println("1. Create");
System.out.println("2. Link");
System.out.println("3. Unlink");
System.out.println("4. Message");
System.out.println("5. Print");
System.out.println("6. Exit");
try {
int choice = Integer.parseInt(jin.nextLine());
switch (choice) {
case 1: {
create();
break;
}
case 2: {
link();
break;
}
case 3: {
unlink();
break;
}
case 4: {
message();
break;
}
case 5: {
print();
break;
}
case 6: {
timeToExit = true;
break;
}
}
} catch (NumberFormatException e) {
System.out.println("Неверный ввод");
}
} while (!timeToExit);
} |
accd44f6-e3c5-4ad8-ac9d-2734c604fe39 | 3 | public static boolean checkRoot(String filename) {
File[] roots = File.listRoots();
for (File root : roots) {
try {
String canonicalRoot = root.getCanonicalPath().toLowerCase();
if (filename.toLowerCase().startsWith(canonicalRoot)) {
return true;
}
} catch (IOException e) {
// Do we care?
}
}
return false;
} |
f61a14c4-2dbd-40f2-906b-59db244b2c81 | 0 | public static void main(String... args)
{
ConstructorReferenceSAM<ConstructorReference> constructorReference = ConstructorReference::new;
System.out.println(constructorReference.whatEverMethodIs().getContent());
ConstructorReferenceSAMWithArgs<ConstructorReference,String> constructorReferenceSAMWithArgs = ConstructorReference::new;
System.out.println(constructorReferenceSAMWithArgs.specifiedMethod("Yo").getContent());
ConstructorReferenceSAMWithParameterizedArg<ConstructorReference,String> constructorReferenceSAMWithArgs1 = ConstructorReference::<String>new;
List<String> stringList = new ArrayList<>();
stringList.add("Yo1");
stringList.add("Yo2");
stringList.add("Yo3");
System.out.println( constructorReferenceSAMWithArgs1.specifiedList(stringList).getContents().size());
} |
54e3c17a-9bd6-48ef-9a9b-139ac788967a | 5 | private boolean isEnpassant(Position checkedPos, Position beside) {
if(!(isValidPos(checkedPos)||isEmptyPlace(checkedPos))) return false;
if(!isEmptyPlace(beside)&&!isSameTeam(beside)&&Board.chessBoard.get(beside).moveCount==1) return true;
return false;
} |
973b0fd8-fe88-4e04-ab9d-469e42c1678a | 5 | public static String generateCard() {
String temp = new String();
String newCard = new String();
int tmp;
Random rand = new Random();
int cardDigits[] = new int[16];
// For AmericanExpress 1st digit is always 3, 2nd digit is 7
cardDigits[0] = 3;
cardDigits[1] = 4+3*rand.nextInt(2);
newCard += cardDigits[0];
newCard += cardDigits[1];
// Initialize the 3rd-14th digit to a random number
for (int i = 2; i < 14; i++) {
cardDigits[i] = rand.nextInt(10);
newCard += cardDigits[i];
}
String luhnString = new String();
for (int i = 13; i >= 0; i--) {
if (i%2 == 1) {
tmp = cardDigits[i] * 2;
}
else
tmp = cardDigits[i];
luhnString += tmp;
}
int luhnSum = 0;
for (int i = 0; i < luhnString.length(); i++) {
temp = Character.toString(luhnString.charAt(i));
luhnSum += Integer.parseInt(temp);
}
// Calculate the check digit based on the luhnSum
int checkDigit = 10 - (luhnSum%10);
if (checkDigit == 10)
checkDigit = 0;
cardDigits[14] = checkDigit;
newCard += cardDigits[14];
return newCard;
} |
5595c679-f819-47f6-9fa5-a3415c9e6c6d | 2 | @Override
public String execute(SessionRequestContent request) throws ServletLogicException {
String page = ConfigurationManager.getProperty("path.page.hotels");
String prevPage = (String) request.getSessionAttribute(JSP_PAGE);
resaveParamsShowHotel(request);
formHotelList(request);
showSelectedHotel(request);
if (page == null ? prevPage != null : ! page.equals(prevPage)) {
request.setSessionAttribute(JSP_PAGE, page);
cleanSessionShowHotel(request);
}
return page;
} |
202fb4f4-f66f-4f92-99a1-b00b03a747e0 | 5 | public MainFrame() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
User user = Service.getCurrentUser();
this.setTitle("Carletti Production Manager - " + user.getUsername()
+ " (" + user.getGroup() + ")");
this.setResizable(true);
this.setSize(600, 500);
this.setMinimumSize(new Dimension(500, 450));
this.setLocationRelativeTo(this.getRootPane());
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
mntmDashboard = new JMenuItem("Dashboard");
mntmProducts = new JMenuItem("Products");
JMenu mnStatistics = new JMenu("Statistics");
mntmPercentageOfWaste = new JMenuItem("Percentage of Waste");
mntmCreateTrays = new JMenuItem("Create Trays");
mntmAveragePickingTimes = new JMenuItem("Average Picking Times");
mntmLogout = new JMenuItem("Logout");
if (user.canAccess("Dashboard")) {
mntmDashboard.setMnemonic('D');
mntmDashboard.addActionListener(controller);
menuBar.add(mntmDashboard);
}
if (user.canAccess("Products")) {
mntmProducts.setMnemonic('P');
mntmProducts.addActionListener(controller);
menuBar.add(mntmProducts);
}
if (user.canAccess("Statistics")) {
mnStatistics.setMnemonic('S');
// menuBar.add(mnStatistics);
mntmPercentageOfWaste.setMnemonic('W');
mntmPercentageOfWaste.addActionListener(controller);
// mnStatistics.add(mntmPercentageOfWaste);
mntmAveragePickingTimes.setMnemonic('A');
mntmAveragePickingTimes.addActionListener(controller);
// mnStatistics.add(mntmAveragePickingTimes);
}
if (user.canAccess("Create Trays")) {
mntmCreateTrays.setMnemonic('T');
mntmCreateTrays.addActionListener(controller);
menuBar.add(mntmCreateTrays);
}
if (user.canAccess("Logout")) {
mntmLogout.setMnemonic('L');
mntmLogout.addActionListener(controller);
menuBar.add(mntmLogout);
}
this.add(pnlNotifications, BorderLayout.NORTH);
this.navigateTo(pnlDashboard);
} |
96d0c64c-4913-4fe4-92dd-3117ca5725ee | 4 | public boolean getGenericPortMappingEntry(int index,
final PortMappingEntry portMappingEntry)
throws IOException, SAXException {
Map<String, String> args = new HashMap<String, String>();
args.put("NewPortMappingIndex", Integer.toString(index));
Map<String, String> nameValue = simpleUPnPcommand(controlURL,
serviceType, "GetGenericPortMappingEntry", args);
if (nameValue.isEmpty() || nameValue.containsKey("errorCode"))
return false;
portMappingEntry.setRemoteHost(nameValue.get("NewRemoteHost"));
portMappingEntry.setInternalClient(nameValue.get("NewInternalClient"));
portMappingEntry.setProtocol(nameValue.get("NewProtocol"));
portMappingEntry.setEnabled(nameValue.get("NewEnabled"));
portMappingEntry.setPortMappingDescription(
nameValue.get("NewPortMappingDescription"));
try {
portMappingEntry.setInternalPort(
Integer.parseInt(nameValue.get("NewInternalPort")));
} catch (Exception e) {
}
try {
portMappingEntry.setExternalPort(
Integer.parseInt(nameValue.get("NewExternalPort")));
} catch (Exception e) {
}
return true;
} |
1f7b7722-44cb-470c-9e82-9f38b7b13781 | 1 | public void addToStart(String value) throws AlreadyExist {
ListElement current = new ListElement(value);
if (count == 0) {
head = current;
tail = current;
} else {
current.connectNext(head);
head = current;
}
count++;
} |
0f1f4ff7-19ef-43e7-982c-95f7e1426afc | 2 | public static void main(String[] args) {
// wap to take input from user and display the pattern according to value
/*
2 **
3 ***
9 *********
1 *
*/
int[] arInt=new int[]{2,7,9,11};
for (int j = 0; j < arInt.length; j++) {
int i=arInt[j];
for(int l=1;l<=i;l++)
{
System.out.print("*");
}
System.out.println("");
}
} |
aae5cbc8-2063-4980-a161-e05d2a0df1c0 | 8 | protected void loadAllManufacturers()
{
final String filename=getManufacturersFilename();
CMFile xmlFile=new CMFile(filename, null, CMFile.FLAG_FORCEALLOW);
if((!xmlFile.exists())||(!xmlFile.canRead()))
xmlFile=new CMFile("/resources/examples/manufacturers.xml", null, CMFile.FLAG_FORCEALLOW);
manufacturers.clear();
if(xmlFile.exists() && xmlFile.canRead())
{
final List<XMLLibrary.XMLTag> xDoc=CMLib.xml().parseAllXML(xmlFile.text());
final List<XMLLibrary.XMLTag> xMans=new SLinkedList<XMLLibrary.XMLTag>();
for(final XMLLibrary.XMLTag x : xDoc)
{
if(x.tag().equalsIgnoreCase("MANUFACTURER"))
xMans.add(x);
else
if(x.tag().equalsIgnoreCase("MANUFACTURERS"))
xMans.addAll(x.contents());
}
for(final XMLTag x : xMans)
{
final Manufacturer man =(Manufacturer)CMClass.getCommon("DefaultManufacturer");
man.setXml(x.value());
addManufacturer(man);
}
}
} |
b3555791-3ba4-4013-b820-9aafdacbe124 | 3 | @Override
public void run() {
while (n < 2000) {
try {
// this will load the MySQL driver, each DB has its own driver
Class.forName("com.mysql.jdbc.Driver");
// setup the connection with the DB.
connect = DriverManager.getConnection("jdbc:mysql://localhost/cdr_data?user=root&password=root");
// preparedStatements can use variables and are more efficient
preparedStatement = connect.prepareStatement("insert into cdr_inbound "
+ "(CallingPeerAddress,CalledPeerAddress,SetupTime,STMS,ConnectTime,"
+ "CTMS,DisconnectTime,DTMS,IsMissed,DateAdded,TypeAppel) values (?, ?, ?, ?, ? ,? ,? ,?, ?, ?, ?)");
//"myuser, webpage, datum, summary, COMMENTS from FEEDBACK.COMMENTS");
// parameters start with 1
preparedStatement.setString(1, CallingPeerAddress);
preparedStatement.setString(2, CalledPeerAddress);
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
java.util.Date dateSTMS = sdf.parse(SetupTime);
java.sql.Timestamp tstmp = new java.sql.Timestamp(dateSTMS.getTime());
preparedStatement.setTimestamp(3, tstmp);
preparedStatement.setInt(4, Integer.valueOf(STMS));
java.util.Date dateCTMS = sdf.parse(ConnectTime);
java.sql.Timestamp tCtmp = new java.sql.Timestamp(dateCTMS.getTime());
preparedStatement.setTimestamp(5, tCtmp);
preparedStatement.setInt(6, Integer.valueOf(CTMS));
java.util.Date dateDTMS = sdf.parse(DisconnectTime);
java.sql.Timestamp tDtmp = new java.sql.Timestamp(dateDTMS.getTime());
preparedStatement.setTimestamp(7, tDtmp);
preparedStatement.setInt(8, Integer.valueOf(DTMS));
preparedStatement.setBoolean(9, IsMissed);
long timeNow = Calendar.getInstance().getTimeInMillis();
java.sql.Timestamp ts = new java.sql.Timestamp(timeNow);
preparedStatement.setTimestamp(10, ts);
preparedStatement.setInt(11, TypeAppel);
preparedStatement.executeUpdate();
} catch (SQLException e) {
Logger.getLogger(ConcurrentDataInsertTest.class.getName()).log(Level.SEVERE, null, e);
} catch (ParseException | ClassNotFoundException ex) {
Logger.getLogger(ConcurrentDataInsertTest.class.getName()).log(Level.SEVERE, null, ex);
} finally {
n++;
//System.out.println(n + " " + Thread.currentThread().getName());
}
}
} |
94c2c8b4-ed41-4170-836e-8ec04930c363 | 8 | public RockEntity(double x, double y, double dx, double dy, int width, int height, int size, int type, double gridSize, double spawnTimer) {
this.x = x;
this.y = y;
this.dx = dx;
this.dy = dy;
this.width = width;
this.height = height;
this.size = size;
this.spawnTimer = spawnTimer;
startTime = spawnTimer < 0 ? 1000 : spawnTimer;
switch (size) {
case RockEntity.BIG:
this.grid = gridSize;
break;
case RockEntity.MEDIUM:
this.grid = 3.0 * gridSize / 4;
break;
case RockEntity.SMALL:
this.grid = gridSize / 2;
break;
}
this.radius = 3 * grid;
bounds = new BoundingShape(BoundingShape.CIRCLE, RockEntity.this.radius);
fakeRocks = new RockMockupEntity[4];
for (int i = 0; i < 4; ++i) {
fakeRocks[i] = new RockMockupEntity(i);
}
switch (type % 3) {
case 0: {
double[] xs = {0 * grid, 1 * grid, 3 * grid, 2 * grid, 4 * grid, 3 * grid, 1 * grid, -1 * grid, -2 * grid, -3 * grid, -2 * grid};
double[] ys = {-2 * grid, -3 * grid, -1 * grid, 0 * grid, 1 * grid, 3 * grid, 2 * grid, 3 * grid, 1 * grid, 0 * grid, -2 * grid};
xCoords = xs;
yCoords = ys;
break;
}
case 1: {
double[] xs = {-1 * grid, 2 * grid, 3 * grid, 3 * grid, 1 * grid, -0.5 * grid, -0.5 * grid, -2 * grid, -3 * grid, -2 * grid, -3 * grid};
double[] ys = {-3 * grid, -3 * grid, -1 * grid, 0 * grid, 3 * grid, 3 * grid, 0 * grid, 3 * grid, 0.5 * grid, 0 * grid, -0.5 * grid};
xCoords = xs;
yCoords = ys;
break;
}
case 2: {
double[] xs = {-1.5 * grid, 1 * grid, 3 * grid, 0 * grid, 3 * grid, 1 * grid, 0 * grid, -2 * grid, -3 * grid, -3 * grid, -1 * grid};
double[] ys = {-3 * grid, -3 * grid, -1.5 * grid, -0.5 * grid, 1 * grid, 3 * grid, 2 * grid, 3 * grid, 0.5 * grid, -1.5 * grid, -1.5 * grid};
xCoords = xs;
yCoords = ys;
break;
}
}
} |
413500cb-56bc-45e1-9863-de0eb9a84bfe | 1 | private static boolean canSearch(Object o) {
return o != null && !(o instanceof Reference);
} |
7407eebb-3eb1-4621-aee9-02c8ee5b1c87 | 3 | private void writeOut(String output) {
String myName = dir.getName();
File out = new File(output + File.separator + myName);
if (!out.exists()) {
out.mkdir();
}
for (DirManager manager : subDirs) {
manager.writeOut(output + File.separator + myName);
}
for (Clazz clazz : classes.values()) {
clazz.writeOut(output + File.separator + myName);
}
} |
62d2928d-3b1b-4684-a4e7-5102e2a8803b | 0 | String getSlip() {
return id;
} |
a5e967e2-1f21-4aae-950b-837e97c2918d | 6 | private Set<TKey<?, ?>> setupPortalKeys() {
Set<TKey<?, ?>> portalKeys = new LinkedHashSet<>();
portalKeys.add(ProviderKeys.PORTAL_STATUS);
portalKeys.add(ProviderKeys.COORDINATE);
portalKeys.add(ProviderKeys.LINK);
validQualifiers.put(ProviderKeys.LINK, new LinkedHashSet<Class<? extends Enum<?>>>() {
{
add(ProviderQualifiers.LINK_TYPE);
}
});
qualifiers.add(ProviderQualifiers.LINK_TYPE);
uniqueKeys.add(ProviderKeys.PORTAL_STATUS);
uniqueKeys.add(ProviderKeys.COORDINATE);
return portalKeys;
} |
f6fe2d91-0e61-43bf-a233-96ef8c3d6bf8 | 0 | public String getPostalCode() {
return Address.getPostalCode();
} |
59af6cc7-4250-4435-b4c9-91e000deb02c | 9 | @Override
public void setMiscText(String text)
{
super.setMiscText("");
slots = new Item[0];
slotProps = new Ability[0];
String itemXml = "";
int x=text.indexOf(';');
if(x >=0)
{
itemXml = text.substring(x+1).trim();
text = text.substring(0,x).trim();
}
int numSlots = CMParms.getParmInt(text, "NUM", 1);
if(numSlots > 0)
{
slots = new Item[numSlots];
slotProps = new Ability[numSlots];
}
slotType= CMParms.getParmStr(text, "TYPE", "");
removeable = CMParms.getParmBool(text, "REMOVEABLE", true);
if(itemXml.length()>0)
{
if(itemXml.startsWith("<ITEM>"))
itemXml="<ITEMS>"+itemXml+"</ITEMS>";
final List<Item> items = new LinkedList<Item>();
CMLib.coffeeMaker().addItemsFromXML(itemXml, items, null);
int islot = 0;
int aslot = 0;
for(Item I : items)
{
final Ability A=I.fetchEffect("Prop_ItemSlotFiller");
if(A!=null)
{
int aSlotNumbs= CMParms.getParmInt(A.text(), "NUM", 1);
for(int a=0; (a<aSlotNumbs) && (islot<slots.length);a++)
slots[islot++]=I;
if(aslot < slotProps.length)
{
slotProps[aslot++]=A;
}
}
}
}
setAffected = true;
} |
d9706069-1ea0-42e0-bc6c-bf9eac1e0b16 | 6 | private void loadState() throws IOException
{
try
{
String path = CA_PERSISTENCE_PATH + File.separator + CA_ID;
File nodeFile = new File(path);
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(nodeFile));
CA ca = (CA) ois.readObject();
if (ca.getUserId() != null && ca.getSecurityAgent() != null
&& ca.getRegisteredNodeData() != null
&& ca.getNode() != null
&& ca.getContactList() != null)
{
this.securityAgent.setKeyPair(ca.getSecurityAgent().getKeyPair());
this.registeredNodesData = ca.getRegisteredNodeData();
//this.node.loadState(ca.getNode());
this.contactList = ca.getContactList();
}
else
{
throw new IOException("Can't load CA data");
}
}
catch (ClassNotFoundException cnfe)
{
throw new IOException("Corrupted file, can't load CA state");
}
} |
53e6686b-a3c0-4b28-baf9-eb98c04a7a93 | 9 | public void renderAddonsTile()
{
for(Interactable i: addons)
{
if(i.isVisible())
{
int [] image = i.getCurrentPixelArray();
for(int xx=0;xx<i.getWidth();xx++)
{
for(int yy=0;yy<i.getHeight();yy++)
{
if(i.getY()+yy>=0 && i.getY()+yy<height && i.getX()+xx>=0 && i.getX()+xx<width && (int)image[i.getWidth()* yy + xx] != -65328)
{
pixels[(i.getX()+xx)+(i.getY()+yy)*width]= image[xx + yy* i.getWidth()];
}
}
}
}
}
} |
29570b3c-13f5-432b-b23e-5dda583cb46f | 5 | @Override
public O train(I input) throws Exception {
Object i = input;
for(final Processor p : processors){
p.setContext(context);
context.getProgressReporter().reportProgress(p.getClass().getSimpleName() + " train: ", 0);
long t0 = System.currentTimeMillis();
if (p instanceof ParallelProcessor) {
final ParallelProcessor pp = (ParallelProcessor) p;
pp.setChunks(cores);
final Object o = pp.initTrain(i);
Queue<Future> futures = new LinkedList<Future>();
for(int c=0; c<cores; c++){
final Object finalI = i;
final int finalC = c;
futures.add(executorService.submit(new Callable<Object>() {
@Override
public Object call() throws Exception {
pp.train(finalI, o, finalC);
return null;
}
}));
while(futures.size() > cores * 2) {
futures.poll().get();
}
}
while(futures.size() > 0) {
futures.poll().get();
}
i = o;
} else {
System.err.println(p + " ( " + i.getClass() + " )");
i = p.train(i);
}
long t1 = System.currentTimeMillis();
context.getProgressReporter().reportProgress(p.getClass().getSimpleName() + " train complete. Time spent " + (t1-t0), 1);
}
return (O) i;
} |
25b3239a-80c4-420b-b824-c85a8e15fdd9 | 6 | private boolean isPassableFromTo(int fromx,int fromy, int tox,int toy) {
int tileFrom = mapSteps[fromx][fromy];
int tileTo= mapSteps[tox][toy];
int curTileSet = curGb.readMemory(curGb.pokemon.curTilesetAddress);
for(int c = curGb.pokemon.tilePairCollisionsLandAddress; memory[c] != 0xFF; c+=3) {
if(memory[c] != curTileSet)
continue;
if(memory[c+1] == tileFrom && memory[c+2] == tileTo)
return false;
if(memory[c+2] == tileFrom && memory[c+1] == tileTo)
return false;
}
return true;
} |
40ca29dc-1f5b-41bb-8940-c2b1c3225359 | 2 | public void readResults() {
String saveFile = saveFileName + ".xrsbxl2x";
ReadFile read = new ReadFile("./Results/" + saveFile);
List<String> readLines = new ArrayList<>();
try {
Collections.addAll(readLines, read.OpenFile());
} catch (IOException ex) {
System.out.println(ex.getMessage());
System.exit(-1);
}
String[] lines = readLines.toArray(new String[readLines.size()]);
for (int i = 0; i < 5; i++) {
System.out.println(lines[i]);
}
} |
28f9ac34-7e31-4e3e-984d-b6bfbf07c47a | 4 | public synchronized static String inputNotation(int move) {
// Gather the information from the move int
int fromIndex = fromIndex(move);
int toIndex = toIndex(move);
int moveType = moveType(move);
StringBuilder inputNotation = new StringBuilder();
positionToString(fromIndex, inputNotation);
positionToString(toIndex, inputNotation);
// Check for promotion
switch (moveType) {
case PROMOTION_QUEEN:
inputNotation.append("q");
break;
case PROMOTION_ROOK:
inputNotation.append("r");
break;
case PROMOTION_BISHOP:
inputNotation.append("b");
break;
case PROMOTION_KNIGHT:
inputNotation.append("n");
break;
}
return inputNotation.toString();
} |
81c3e1be-dbc1-4385-85e3-6c0c54e221fc | 8 | @Override
public void valueChanged(TreeSelectionEvent arg0) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
if (node == null) return;
if (node.isLeaf()) {
if (prevNode != null) {
detectChange();
}
tabbedPane.removeAll();
listOfColumns.clear();
GridBagLayout gbl_temp = new GridBagLayout();
gbl_temp.columnWeights = new double[] { 0, 1.0, Double.MIN_VALUE };
gbl_temp.rowWeights = new double[] { 1.0, Double.MIN_VALUE };
GridBagConstraints textFieldConstraints = new GridBagConstraints();
GridBagConstraints labelConstraints = new GridBagConstraints();
textFieldConstraints.anchor = GridBagConstraints.FIRST_LINE_START;
textFieldConstraints.fill = GridBagConstraints.HORIZONTAL;
textFieldConstraints.insets = new Insets(5, 0, 0, 0);
textFieldConstraints.gridx = 1;
textFieldConstraints.gridy = 0;
textFieldConstraints.weightx = 1.0;
textFieldConstraints.weightx = 1.0;
textFieldConstraints.gridwidth = 4;
labelConstraints.insets = new Insets(5, 0, 0, 10);
labelConstraints.anchor = GridBagConstraints.FIRST_LINE_START;
labelConstraints.gridx = 0;
labelConstraints.gridy = 0;
labelConstraints.weightx = 0.0;
for (ModNode columnNode : xmlParser.modList.getChild(node.getParent().getParent().toString()).getChild(node.getParent().toString()).getChild(node.toString()).getChildren()) {
if (columnNode.getName().contains("Conditions")) {
listOfColumns.put(new JLabel(columnNode.getName()), createConditionsList(columnNode));
} else if (columnNode.getName().contains("Properties")) {
listOfColumns.put(new JLabel(columnNode.getName()), createItemPropsList(columnNode));
} else {
JTextPane columnData = new JTextPane();
columnData.setText(columnNode.getData());
columnData.setEditable(true);
listOfColumns.put(new JLabel(columnNode.getName()), columnData);
}
}
for (JLabel label : listOfColumns.keySet()) {
if (listOfColumns.get(label).getClass().equals(JSplitPane.class)) {
textFieldConstraints.fill = GridBagConstraints.BOTH;
} else {
textFieldConstraints.fill = GridBagConstraints.NONE;
}
JPanel tempPanel = new JPanel(gbl_temp);
tempPanel.add(label, labelConstraints);
tempPanel.add(listOfColumns.get(label), textFieldConstraints);
tabbedPane.addTab(label.getText(), tempPanel);
}
tabbedPane.updateUI();
prevNode = node;
}
} |
a1e15c01-7e11-459f-869d-ee78dd986649 | 8 | public void moveEnemy(int x, int y, Point enemyToMove) {
Point newLocation = new Point((int) (enemyToMove.getX() + x), (int) (enemyToMove.getY() + y));
GridSpace gs = grid.get(enemyToMove);
GridSpace gs2 = grid.get(newLocation);
if (gs.returnLivingThings().get(0).isFrozen()) {
return;
}
// if (this.characterLocation.getX() - this.enemyLocation.getX() >=
// 0) {
// newLocation.translate(1, 0);
// } else {
// newLocation.translate(-1, 0);
// }
if (gs2.returnThings().size() > 0) {
if (gs2.hasSolid()) {
if (gs2.returnWeapons().size() == 0) {
return;
} else {
for (LivingThing e : gs2.returnLivingThings()) {
if (e.getSolid()) {
return;
}
}
for (Terrain t : gs2.returnTerrain()) {
if (t.getSolid()) {
return;
}
}
}
}
}
Thing t = gs.remove(gs.returnThings().get(0));
gs2.add(t);
gs.sortArrayOfThings();
gs2.sortArrayOfThings();
grid.put(enemyToMove, gs);
grid.put(newLocation, gs2);
setEnemyLocation(newLocation, enemyToMove);
enemyToMove.translate(x, y);
} |
ac32b488-f10c-40ae-8b14-e24667afbbc2 | 5 | @Override
public void mouseClicked(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON3 && label.getOnCanvas()) {
label.erase(canvas.getCurrentLayer());
} else if (e.getButton() == MouseEvent.BUTTON1 && label.getOnCanvas()) {
label.drawTile(canvas.getCurrentTile(), canvas.getCurrentLayer());
}
if(!label.getOnCanvas()){
canvas.changeCurrentTile(label.id);
}
} |
f5f085e6-33cb-4f8f-907e-15a3133bd795 | 0 | public Environment(Strategy strategy){
this.strategy = strategy;
} |
7f86015e-0924-431a-9ce3-e0c424cd5d0c | 7 | public int getBonusScore (int numOfFrame){
int bonusFirst;
int bonusSecond;
if(numOfFrame==currentFrame-1)
return 0;
if(scoreBoard[numOfFrame].checkStrike()){
if(numOfFrame==currentFrame-2 && currentRoll%2==1)
return 0;
bonusFirst = scoreBoard[numOfFrame+1].getFirstPoint();
if(bonusFirst==10){
if(numOfFrame==currentFrame-2)
return 0;
bonusSecond=scoreBoard[numOfFrame+2].getFirstPoint();
return bonusFirst+bonusSecond;
}
bonusSecond=scoreBoard[numOfFrame+1].getSecondPoint();
return bonusFirst+bonusSecond;
}
if(scoreBoard[numOfFrame].checkSpare()){
return scoreBoard[numOfFrame+1].getFirstPoint();
}
return 0;
} |
0724efa2-4a5c-46b3-9be6-2384a95fd40e | 7 | private boolean blockBlocksFlow(World par1World, int par2, int par3, int par4)
{
int var5 = par1World.getBlockId(par2, par3, par4);
if (var5 != Block.doorWood.blockID && var5 != Block.doorSteel.blockID && var5 != Block.signPost.blockID && var5 != Block.ladder.blockID && var5 != Block.reed.blockID)
{
if (var5 == 0)
{
return false;
}
else
{
Material var6 = Block.blocksList[var5].blockMaterial;
return var6 == Material.portal ? true : var6.blocksMovement();
}
}
else
{
return true;
}
} |
28a4b755-32d6-4a7d-87d8-8ef02540dcaa | 9 | private void parser(final Element e) {
// Extract the information according to the question's type
switch ((String) e.getAttributeValue("type")) {
case "truefalse":
TrueFalse tf = new TrueFalse(e.getChild("name")
.getChildText("text"), e.getChild("questiontext")
.getChildText("text"), e.getChild("questiontext")
.getAttributeValue("format"), e.getChild("image")
.getValue(), e.getChild("generalfeedback").getTextTrim(), e
.getChild("defaultgrade").getText(), e.getChild("penalty")
.getTextTrim(), e.getChild("hidden").getText(), e.getChild(
"shuffleanswers").getText());
Iterator<?> ite = e.getChildren("answer").iterator();
while (ite.hasNext()) {
Element parcour = (Element) ite.next();
if (parcour.getName().equals("answer")) {
tf.ajoutAnswer(new Answer(parcour.getChildText("text"),
parcour.getAttributeValue("fraction"), parcour
.getChild("feedback").getTextTrim()));
}
}
listQuestion.add(tf);
break;
case "shortanswer":
ShortAnswer sa = new ShortAnswer(e.getChild("name").getChildText(
"text"), e.getChild("questiontext").getChildText("text"), e
.getChild("questiontext").getAttributeValue("format"), e
.getChild("image").getValue(), e
.getChild("generalfeedback").getTextTrim(), e.getChild(
"defaultgrade").getText(), e.getChild("penalty")
.getTextTrim(), e.getChild("hidden").getText(), e.getChild(
"shuffleanswers").getText(), e.getChild("usecase")
.getText());
ite = e.getChildren("answer").iterator();
while (ite.hasNext()) {
Element parcour = (Element) ite.next();
if (parcour.getName().equals("answer")) {
sa.ajoutAnswer(new Answer(parcour.getChildTextTrim("text"),
parcour.getAttributeValue("fraction"), parcour
.getChild("feedback").getChildTextTrim(
"text")));
}
}
listQuestion.add(sa);
break;
case "essay":
Essay es = new Essay(e.getChild("name").getChildText("text"), e
.getChild("questiontext").getChildText("text"), e.getChild(
"questiontext").getAttributeValue("format"), e.getChild(
"image").getValue(), e.getChild("generalfeedback")
.getTextTrim(), e.getChild("defaultgrade").getText(), e
.getChild("penalty").getTextTrim(), e.getChild("hidden")
.getText(), e.getChild("shuffleanswers").getText(),
new Answer(e.getChild("answer").getChildText("text"), e
.getChild("answer").getAttributeValue("fraction"),
e.getChild("answer").getChild("feedback")
.getTextTrim()));
listQuestion.add(es);
break;
case "numerical":
Answer a = new Answer(e.getChild("answer").getChildText("text"), e
.getChild("answer").getAttributeValue("fraction"), e
.getChild("answer").getChild("feedback").getTextTrim());
a.setTolerance(e.getChild("answer").getChildText("tolerance"));
NumericalAnswer na = new NumericalAnswer(e.getChild("name")
.getChildText("text"), e.getChild("questiontext")
.getChildText("text"), e.getChild("questiontext")
.getAttributeValue("format"), e.getChild("image")
.getValue(), e.getChild("generalfeedback").getTextTrim(), e
.getChild("defaultgrade").getText(), e.getChild("penalty")
.getTextTrim(), e.getChild("hidden").getText(), e.getChild(
"shuffleanswers").getText(), a);
listQuestion.add(na);
break;
default:
Logger logger = Logger.getLogger("app");
logger.info(e.getAttributeValue("type"));
}
} |
47ab3b40-0742-4f10-96ff-2d7fcc9cf87b | 6 | public void update(double deltaTime){
// If the display has been resized, move all elements belonging to this CompositeElement into the same relative position.
// i.e. if CompositeElement is at bottom right of screen, after resizing will still be at bottom right of screen.
if(Display.wasResized()){
for (GUIElement element : compositeElements.values()) {
element.setX(element.getAnchorX()+(x-anchorX));
element.setY(element.getAnchorY()+(y-anchorY));
}
}
if(render){
for (GUIElement element : compositeElements.values()) {
element.update(deltaTime);
}
}
// Perform a scale operation:
if(performScaling){
setScale(scaleTarget);
for (GUIElement element : compositeElements.values()) {
element.performScale(scaleTarget, timeToScale);
//If you want the scaling to be done from x,y of this CompositeElement, not the centre of each object:
//element.setX(element.getAnchorX()*getScale());
//element.setY(element.getAnchorY()*getScale());
}
performScaling=false;
}
} |
3aa00820-0feb-4338-8faa-23b25ec684eb | 7 | private void initialize() {
gameFrame = new JFrame();
gameFrame.setTitle("Hand and Foot");
gameFrame.setBounds(0, 0, 800, 500);
gameFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
gameFrame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
exit();
}
});
JMenuBar menuBar = new JMenuBar();
gameFrame.setJMenuBar(menuBar);
JMenu mnGame = new JMenu("Game");
menuBar.add(mnGame);
JMenuItem mntmConnect = new JMenuItem("Connect to IP Game");
mntmConnect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
InetAddress address;
String ip = JOptionPane.showInputDialog(gameFrame, "IP: ",
"Connect", JOptionPane.QUESTION_MESSAGE);
try {
address = InetAddress.getByName(ip);
} catch (UnknownHostException ex) {
JOptionPane.showMessageDialog(gameFrame,
"That IP Address is not valid.");
return;
}
connect(address);
}
});
JMenuItem mntmConnectToLocal = new JMenuItem("Connect to Local Game");
mntmConnectToLocal.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new LocalGame(Main.this).setVisible(true);
}
});
mnGame.add(mntmConnectToLocal);
mnGame.add(mntmConnect);
JMenuItem mntmOptions = new JMenuItem("Options");
mntmOptions.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String[] values = new String[4];
for (int i = 0; i < 4; i++) {
values[Sorting.values()[i].order] = Sorting.values()[i].str;
}
OptionsDialog cs = new OptionsDialog(Main.this, values);
cs.setVisible(true);
cs.setLocationRelativeTo(gameFrame);
}
});
JMenuItem mntmHostGame = new JMenuItem("Host Game");
mntmHostGame.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new NumPlayers(Main.this).setVisible(true);
}
});
mnGame.add(mntmHostGame);
mnGame.add(mntmOptions);
mnGame.add(new JPopupMenu.Separator());
JMenuItem mntmExit = new JMenuItem("Exit");
mntmExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
exit();
}
});
mnGame.add(mntmExit);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[] { 0, 0, 0 };
gridBagLayout.rowWeights = new double[] { 0.0, 0.0, 0.0, 0.0 };
gridBagLayout.columnWeights = new double[] { 0.0, 0.0, 0.0 };
gameFrame.getContentPane().setLayout(gridBagLayout);
btnDraw7Cards = new JButton("Draw 7 Cards from Discard");
btnDraw7Cards.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
network.send(PacketCreator.draw7());
hasDrawn = true;
setButtons(false);
}
});
GridBagConstraints gbc_btnDrawCards_1 = new GridBagConstraints();
gbc_btnDrawCards_1.insets = new Insets(5, 0, 5, 0);
gbc_btnDrawCards_1.anchor = GridBagConstraints.EAST;
gbc_btnDrawCards_1.fill = GridBagConstraints.VERTICAL;
gbc_btnDrawCards_1.gridx = 2;
gbc_btnDrawCards_1.gridy = 0;
gameFrame.getContentPane().add(btnDraw7Cards, gbc_btnDrawCards_1);
btnDraw7Cards.setEnabled(false);
btnDraw2Cards = new JButton("Draw 2 Cards");
btnDraw2Cards.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
network.send(PacketCreator.draw());
hasDrawn = true;
setButtons(false);
}
});
GridBagConstraints gbc_btnDrawCards = new GridBagConstraints();
gbc_btnDrawCards.insets = new Insets(5, 0, 5, 5);
gbc_btnDrawCards.anchor = GridBagConstraints.WEST;
gbc_btnDrawCards.fill = GridBagConstraints.VERTICAL;
gbc_btnDrawCards.gridx = 1;
gbc_btnDrawCards.gridy = 0;
gameFrame.getContentPane().add(btnDraw2Cards, gbc_btnDrawCards);
btnDraw2Cards.setEnabled(false);
JButton btnPlayGroup = new JButton("Play Group");
btnPlayGroup.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (staging != null)
network.send(PacketCreator.play(staging));
}
});
GridBagConstraints gbc_btnPlayGroup = new GridBagConstraints();
gbc_btnPlayGroup.fill = GridBagConstraints.HORIZONTAL;
gbc_btnPlayGroup.weighty = 1.0;
gbc_btnPlayGroup.anchor = GridBagConstraints.SOUTH;
gbc_btnPlayGroup.insets = new Insets(0, 5, 5, 5);
gbc_btnPlayGroup.gridx = 0;
gbc_btnPlayGroup.gridy = 1;
gameFrame.getContentPane().add(btnPlayGroup, gbc_btnPlayGroup);
surface = new Surface(this);
GridBagConstraints gbc_surface = new GridBagConstraints();
gbc_surface.gridheight = 3;
gbc_surface.weightx = 1.0;
gbc_surface.weighty = 1.0;
gbc_surface.gridwidth = 2;
gbc_surface.fill = GridBagConstraints.BOTH;
gbc_surface.gridx = 1;
gbc_surface.gridy = 1;
gameFrame.getContentPane().add(surface, gbc_surface);
JButton btnRemoveGroup = new JButton("Remove Group");
btnRemoveGroup.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (staging != null) {
for (Card c : staging) {
hand.add(c);
}
staging = null;
redraw();
}
}
});
GridBagConstraints gbc_btnRemoveGroup = new GridBagConstraints();
gbc_btnRemoveGroup.weighty = 1.0;
gbc_btnRemoveGroup.anchor = GridBagConstraints.NORTH;
gbc_btnRemoveGroup.insets = new Insets(0, 5, 5, 5);
gbc_btnRemoveGroup.gridx = 0;
gbc_btnRemoveGroup.gridy = 2;
gameFrame.getContentPane().add(btnRemoveGroup, gbc_btnRemoveGroup);
JButton btnSortHand = new JButton("Sort Hand");
btnSortHand.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Don't want sort to affect hand indexes while floating a card
// or waiting on discard.
// We use absolute index for those calculations
if (!surface.isFloating() && toDiscard == -1) {
Collections.sort(hand);
redraw();
}
}
});
GridBagConstraints gbc_btnSortHand = new GridBagConstraints();
gbc_btnSortHand.fill = GridBagConstraints.HORIZONTAL;
gbc_btnSortHand.insets = new Insets(0, 5, 60, 5);
gbc_btnSortHand.gridx = 0;
gbc_btnSortHand.gridy = 3;
gameFrame.getContentPane().add(btnSortHand, gbc_btnSortHand);
} |
ae8bc026-8db1-43cf-946e-56a660f86289 | 4 | protected static void addFileNameToList(DocumentInfo docInfo) {
// check to see if this file is in frameInfoList
int position = NOT_THERE;
String filename = PropertyContainerUtil.getPropertyAsString(docInfo, DocumentInfo.KEY_PATH);
for (int i = 0, limit = frameInfoList.size(); i < limit; i++) {
if (PropertyContainerUtil.propertyEqualsAsString(((DocumentInfo) frameInfoList.get(i)), DocumentInfo.KEY_PATH, filename)) {
position = i;
}
}
// if it's not in frameInfoList ...
if (position == NOT_THERE) {
// if the frameInfoList is too long ...
if (frameInfoList.size() >= Preferences.getPreferenceInt(Preferences.FRAME_INFO_LIST_SIZE).cur) {
frameInfoList.remove(0);
}
// add the file's docInfo to frameInfoList
frameInfoList.add(docInfo);
} else {
// update its doc info
frameInfoList.set(position, docInfo);
// move that to the top of the list
StanVectorTools.moveElementToTail(frameInfoList, position);
}
// sync
recentFilesList.syncTreeSet();
recentFilesList.syncMenuItems();
} |
eee7f3d7-e30f-48a4-b9d3-3e60d8e5bf9d | 7 | private JMenuItem getPatternLengthItem() {
if (patternLengthItem == null) {
patternLengthItem = new JMenuItem();
patternLengthItem.setText("Set Pattern Length...");
patternLengthItem.setMnemonic(KeyEvent.VK_L);
patternLengthItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
MonomeConfiguration monomeConfig = MonomeConfigurationFactory.getMonomeConfiguration(index);
if (monomeConfig.pages.size() > 0) {
int curLength = monomeConfig.patternBanks.get(monomeConfig.curPage).getPatternLength();
String length = (String)JOptionPane.showInputDialog(
(JMenuItem) e.getSource(),
"Enter new pattern length (1-16 measures)",
"Set Pattern Length",
JOptionPane.PLAIN_MESSAGE,
null,
null,
curLength);
if (length == null || length.compareTo("") == 0) {
return;
}
try {
int iLength = Integer.parseInt(length);
if (iLength > 0 && iLength <= 16) {
monomeConfig.setPatternLength(monomeConfig.curPage, iLength);
}
} catch (NumberFormatException ex) {
return;
}
}
}
});
}
return patternLengthItem;
} |
5d515f9c-9f08-4553-8e54-ff89e2a5da0b | 0 | @Override
public void documentRemoved(DocumentRepositoryEvent e) {} |
5aa411fd-5978-4dcb-9810-69c615efd8f2 | 1 | @Override
public void execute(VirtualMachine vm) {
for (int i = 0; i < levelsOfStackToPop; i++) {
vm.popRunTimeStack();
}
} |
adcf3514-6801-45b2-b54a-907e63847c30 | 7 | private static int[] readHeuristics(int h, String fileName) {
// Our corners heuristics array will have 88179840
// elements, but not all of them will have a value
// as we only calculated heuristics for valid corner
// positions starting at the goal state rather than
// all possible permutations of corners.
int[] heuristics = new int[h];
FileReader file = null;
String line;
try {
file = new FileReader(fileName);
BufferedReader reader = new BufferedReader(file);
while ((line = reader.readLine()) != null) {
// For each line, split by the comma
String[] lineData = line.split(",");
// lineData[0] will be the encoded corner value
// lineData[1] will be the calculated heuristic
if (!(lineData[0].equals("") || lineData[1].equals(""))) {
heuristics[Integer.parseInt(lineData[0])] = Integer.parseInt(lineData[1]);
}
}
} catch (FileNotFoundException e) {
throw new RuntimeException("File not found");
} catch (IOException e) {
throw new RuntimeException("IO error occurred");
} finally {
if (file != null) {
try {
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return heuristics;
} |
6bdaae51-ea0f-457c-868e-5b30966057e2 | 9 | @SuppressWarnings("unchecked")
void setLineBits(float dx, float dy) {
slope = (dx != 0 ? dy / dx : dy >= 0 ? Float.MAX_VALUE : -Float.MAX_VALUE);
lineTypeX = (slope <=1 && slope >= -1);
lineDirection = (slope < 0 ? -1 : 1);
if (getCachedLine())
return;
nBits = (lineTypeX ? g3d.width : g3d.height);
lineBits = new BitSet(nBits);
dy = Math.abs(dy);
dx = Math.abs(dx);
if (dy > dx) {
float t = dx;
dx = dy;
dy = t;
}
int twoDError = 0;
float twoDx = dx + dx, twoDy = dy + dy;
for (int i = 0; i < nBits; i++) {
twoDError += twoDy;
if (twoDError > dx) {
lineBits.set(i);
twoDError -= twoDx;
}
}
lineCache.put(slopeKey, lineBits);
nCached++;
//if (--test > 0 || ((100-test) % 100 == 0)) System.out.println(test+" "+dx + " " + dy + " " + lineBits);
} |
52f15359-ec4e-4c2c-996c-5251af4cfacb | 1 | public void inicio(FonteFinanciamento fontefinanciamento) throws Exception
{
salvar = new JButton("Salvar");
id = new JTextInt(fontefinanciamento.getId());
id.setEditable(false);
id.setEnabled(false);
nome = new JTextField(fontefinanciamento.getNome() == null ? ""
: fontefinanciamento.getNome());
JPanel pp = new JPanel();
DesignGridLayout layout = new DesignGridLayout(pp);
layout.row().grid(new JLabel("ID:")).add(id);
layout.row().grid(new JLabel("Nome:")).add(nome);
layout.row().grid().add(salvar, 1);
getContentPane().add(new JScrollPane(pp));
pack();
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
setSize(400, 150);
setVisible(true);
} |
0341f3ee-c7a6-4910-91d4-6942d25f48ea | 3 | public void kill() {
if (killState.compareAndSet(false, true)) {
try {
socket.close();
} catch (IOException e) {/*NOP*/}
threadGroup.interrupt();
try {
deathQueue.put(name);
} catch (InterruptedException e) {/*NOP*/}
}
} |
4c32d466-8acb-43b7-bbc4-c91d1288ef97 | 7 | public void show() {
int choice;
boolean tryAgain;
do{
System.out.print("Enter Username: ");
username = ConsoleReader.readString();
System.out.print("Enter Password: ");
password = ConsoleReader.readString();
tryAgain = !staffBL.isValid(username, password);
if(tryAgain) {
System.out.println("Login Invalid! Please try again.");
}
}
while(tryAgain);
System.out.println();
do {
System.out.println("1) Create/ Update/ Remove movie listing");
System.out.println("2) Create/ Update/ Remove cinema showtimes and the movies to be shown");
System.out.println("3) Print sale revenue report by movie, cinema and period");
System.out.println("4) Configure system settings");
System.out.println("5) Back");
System.out.print("Please enter choice: ");
choice = ConsoleReader.readIntInput();
System.out.println();
switch(choice) {
case 1:
movieListingView.show();
System.out.println();
break;
case 2:
manageShowTimes.showMenu();
System.out.println();
break;
case 3:
view.printReport();
System.out.println();
break;
case 4:
systemSetting.show();
System.out.println();
break;
default:
break;
}
}while(choice < 5);
} |
0b8567af-bfad-44eb-8f76-4dfa028cbf8e | 3 | private static void setLookAndFeel() {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) { // Windows
javax.swing.UIManager.setLookAndFeel(info.getClassName()); break;
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex){}
} |
23064690-d209-4279-bbcf-247f3e77979a | 4 | @Override
public void update()
{
yy++;
if(yy < 60) {
y += 0.2632;
}
else if(yy > 60 && yy < 120) {
y -= 0.2632;
}
if(yy > 120) {
yy = 0;
}
} |
b56a1e08-93fe-4cf9-b1d0-734fe2e55251 | 8 | private static SAMFileHeader mergeHeaders(List<RecordSource> sources) {
SAMFileHeader header = new SAMFileHeader();
for (RecordSource source : sources) {
SAMFileHeader h = source.reader.getFileHeader();
for (SAMSequenceRecord seq : h.getSequenceDictionary().getSequences()) {
if (header.getSequenceDictionary().getSequence(seq.getSequenceName()) == null)
header.addSequence(seq);
}
for (SAMProgramRecord pro : h.getProgramRecords()) {
if (header.getProgramRecord(pro.getProgramGroupId()) == null)
header.addProgramRecord(pro);
}
for (String comment : h.getComments())
header.addComment(comment);
for (SAMReadGroupRecord rg : h.getReadGroups()) {
if (header.getReadGroup(rg.getReadGroupId()) == null)
header.addReadGroup(rg);
}
}
return header;
} |
447e784c-46a8-44a3-8da3-759303e25726 | 4 | private static int toIndex(Direction dir) {
switch(dir) {
case SOUTH: return 0;
case NORTH: return 1;
case WEST: return 2;
case EAST: return 3;
}
return 0;
} |
04e06ff9-028e-4e17-9daf-aa864f60d390 | 4 | public boolean equals(Object obj) {
if (obj == this)
return true;
if (obj != null && obj instanceof Reference) {
Reference tmp = (Reference) obj;
return (tmp.objf == objf) && (tmp.genf == genf);
}
return false;
} |
b419a724-9cca-485a-a9c3-17335a17ced2 | 0 | public Capture nextCapture (Position position){
FactoryOfCapturingsForCpuForPiece factory = new FactoryOfCapturingsForCpuForPiece(position,this,largestCapture);
return (Capture) factory.getBest();
} |
6705cbb7-6c1e-4730-a92c-93feab05ee04 | 3 | public void reset() {
try {
// reseting non cached byte stream
if (byteArrayInputStream != null) {
byteArrayInputStream.reset();
}
// reseting cached byte stream
if (fileInputStream != null) {
fileInputStream.close();
fileInputStream = null;
fileInputStream = new FileInputStream(tempFile);
}
} catch (IOException e) {
logger.log(Level.FINE, "Error closing file streams.", e);
}
} |
1a74032b-ffb2-4e26-a5b5-de76f6ea84a9 | 0 | public OpenFileMenuItem(FileProtocol protocol) {
setProtocol(protocol);
addActionListener(this);
} |
1ff016d9-2a9b-40f1-8bfd-e2227124038e | 4 | public static void ellipse(double x, double y, double semiMajorAxis, double semiMinorAxis) {
if (semiMajorAxis < 0) throw new RuntimeException("ellipse semimajor axis can't be negative");
if (semiMinorAxis < 0) throw new RuntimeException("ellipse semiminor axis can't be negative");
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(2*semiMajorAxis);
double hs = factorY(2*semiMinorAxis);
if (ws <= 1 && hs <= 1) pixel(x, y);
else offscreen.draw(new Ellipse2D.Double(xs - ws/2, ys - hs/2, ws, hs));
draw();
} |
ae64e4cc-2aa6-4f17-b5dd-4672618d360e | 7 | String checkSecurity(int iLevel, javax.servlet.http.HttpSession session, javax.servlet.http.HttpServletResponse response, javax.servlet.http.HttpServletRequest request){
try {
Object o1 = session.getAttribute("UserID");
Object o2 = session.getAttribute("UserRights");
boolean bRedirect = false;
if ( o1 == null || o2 == null ) { bRedirect = true; }
if ( ! bRedirect ) {
if ( (o1.toString()).equals("")) { bRedirect = true; }
else if ( (new Integer(o2.toString())).intValue() < iLevel) { bRedirect = true; }
}
if ( bRedirect ) {
response.sendRedirect("Login.jsp?querystring=" + toURL(request.getQueryString()) + "&ret_page=" + toURL(request.getRequestURI()));
return "sendRedirect";
}
}
catch(Exception e){};
return "";
} |
db1f9eec-06c8-4f0a-9e4b-58bf862fd3b8 | 8 | private void setPrecision() {
int firstPos = pos;
precisionSet = false;
if (pos<fmt.length()&&fmt.charAt(pos)=='.') {
pos++;
if ((pos < fmt.length())
&& (fmt.charAt(pos)=='*')) {
pos++;
if (!setPrecisionArgPosition()) {
variablePrecision = true;
precisionSet = true;
}
return;
}
else {
while (pos < fmt.length()) {
char c = fmt.charAt(pos);
if (Character.isDigit(c)) pos++;
else break;
}
if (pos > firstPos+1) {
String sz = fmt.substring(firstPos+1,pos);
precision = Integer.parseInt(sz);
precisionSet = true;
}
}
}
} |
f59573fd-6783-4ccb-85e2-2c89c2456299 | 5 | public static void main(String[] args) throws RemoteException {
if (System.getSecurityManager() == null) {
System.setSecurityManager(new SecurityManager());
}
System.out.println("Hello World! salut didier\n");
// EntityManager em = Persistence.createEntityManagerFactory("legedePU").createEntityManager();
//ServeurLegede sl=new ServeurLegede();
try {
//demarre le serveur sur le port 1099
LocateRegistry.createRegistry(1099);
} catch (RemoteException ex) {
ex.printStackTrace();
}
ServeurLegede sl = null;
try {
sl = new ServeurLegede();
} catch (RemoteException ex) {
ex.detail.printStackTrace();
}
try {
Naming.rebind("InterServeur", sl);
} catch (MalformedURLException ex) {
} catch (RemoteException ex) {
}
} |
f7368d1f-4e89-4a67-a605-cb0a5cedaed7 | 1 | private void initMenu()
{
JPanel titlePanel = new JPanel();
this.add(titlePanel);
JLabel title = new JLabel("Card Counting Training");
titlePanel.add(title);
JPanel inputPanel = new JPanel();
this.add(inputPanel);
input = new JTextField(2);
input.setText("6");
inputPanel.add(input);
JPanel startPanel = new JPanel();
this.add(startPanel);
JButton startBtn = new JButton("START");
getRootPane().setDefaultButton(startBtn);
startPanel.add(startBtn);
startBtn.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
game.runGame(Byte.parseByte(input.getText()));
}
catch (Exception ex)
{
game.runGame((byte) 6);
}
finally
{
initGameForm();
}
}
});
this.pack();
setInTheMiddle();
} |
614502f5-1337-4544-9a32-b7f84f3ef8c8 | 0 | public void ajoutNiemeListeMetadonnee(int n, Metadonnee m) {
listeMetaDonnees.add(n, m);
} |
49b552c4-6fab-4027-9437-f100de482eb8 | 7 | private boolean r_case_other() {
int among_var;
// (, line 123
// [, line 124
ket = cursor;
// substring, line 124
among_var = find_among_b(a_6, 6);
if (among_var == 0) {
return false;
}
// ], line 124
bra = cursor;
// call R1, line 124
if (!r_R1()) {
return false;
}
switch (among_var) {
case 0:
return false;
case 1:
// (, line 125
// delete, line 125
slice_del();
break;
case 2:
// (, line 126
// delete, line 126
slice_del();
break;
case 3:
// (, line 127
// <-, line 127
slice_from("a");
break;
case 4:
// (, line 128
// <-, line 128
slice_from("e");
break;
}
return true;
} |
6aa5c890-57d5-43a1-b00f-b8d4f4282292 | 3 | private void createSysTrayIcon()
{
sysTrayIconVisible=true;
//Check the SystemTray is supported
if (!SystemTray.isSupported()) {
log("SystemTray is not supported."); //$NON-NLS-1$
return;
}
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e1) {
e1.printStackTrace();
}
popup = new PopupMenu();
trayIcon = new TrayIcon( iconSystrayOffline ); //$NON-NLS-1$
trayIcon.setImageAutoSize(true);
final SystemTray tray = SystemTray.getSystemTray();
// Create a pop-up menu components
showMain = new MenuItem(Messages.MainWin_7);
hideMain = new MenuItem(Messages.MainWin_8);
exitApp = new MenuItem(Messages.MainWin_19);
showMain.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Display.getDefault().syncExec( new Runnable(){
public void run()
{
showFromTray();
}
} );
}
});
hideMain.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Display.getDefault().syncExec( new Runnable(){
public void run()
{
hideToTray();
}
} );
}
});
exitApp.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Display.getDefault().asyncExec( new Runnable(){
public void run()
{
shutDownApp();
}
} );
}
});
trayIcon.setPopupMenu(popup);
try {
tray.add(trayIcon);
} catch (AWTException e) {
log("TrayIcon could not be added."); //$NON-NLS-1$
}
} |
70241c54-f20b-49ac-a224-add6167af08a | 2 | public static synchronized boolean allowcateUser(Object instance,
Object[] users) {
for (int i = 0; i < users.length; i++) {
if (users[i] == null) {
users[i] = instance;
return true;
}
}
// could not allocate space for user
return false;
} |
0410053e-0e76-4088-b1c9-845adcfcca1f | 8 | public static void main(String[] args) {
RandomSearchInitialisation starter = new RandomSearchInitialisation();
starter.initLanguage(new char[] { 'a', 'b' }, 10, "[ab]*abab");
int solutionFoundCounter = 0;
int noSolutionFound = 0;
List<Long> cycleCount = new LinkedList<Long>();
long tmpCycle;
long timeStamp;
int[] problemCount = new int[5];
int[] candidatesCount = new int[5];
int[] noCycles = new int[2];
problemCount[0] = 50;
problemCount[1] = 100;
problemCount[2] = 150;
problemCount[3] = 200;
problemCount[4] = 250;
candidatesCount[0] = 50;
candidatesCount[1] = 100;
candidatesCount[2] = 150;
candidatesCount[3] = 200;
candidatesCount[4] = 250;
noCycles[0] = 250;
noCycles[1] = 500;
int pc = 0;
int cc = 0;
int nc = 0;
for (int x = 0; x < 10; x++) {
System.out.println("x:" + x);
for (int n = 0; n < 25; n++) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd_HH_mm_ss");
Logger l = new Logger("RAND_ABAB_"+ df.format(new Date()) + ".log",
true);
pc = 0;
cc = candidatesCount[(int) Math.floor(n / 5)];
nc = noCycles[1];
l.log("Problem Count: " + pc);
l.log("CandidatesCount: " + cc);
l.log("Max Cycles: " + nc);
solutionFoundCounter = 0;
noSolutionFound = 0;
cycleCount = new LinkedList<Long>();
for (int i = 0; i < 100; i++) {
timeStamp = System.currentTimeMillis();
starter.initCandidates(cc);
tmpCycle = starter.startEvolution(nc);
l.log(i + ": finished ("
+ (System.currentTimeMillis() - timeStamp) + "ms, "
+ tmpCycle + "cycles)");
if (starter.getWinner() != null) {
solutionFoundCounter++;
cycleCount.add(tmpCycle);
l.log(i + ": Solution found.");
} else {
noSolutionFound++;
l.log(i + ": No solution found.");
}
}
long max = 0;
long min = 10000;
long sum = 0;
for (long no : cycleCount) {
sum += no;
max = (no > max ? no : max);
min = (no < min ? no : min);
}
l.log("Solution Found: " + solutionFoundCounter);
l.log("Avg cycles: "
+ (cycleCount.size() > 0 ? sum / cycleCount.size()
: '0'));
l.log("Max cycles: " + max);
l.log("Min cycles: " + min);
l.log("No solution found: " + noSolutionFound);
l.finish();
}
}
} |
de60dd9d-251a-4d14-93d5-8d75a780df26 | 8 | @Subscribe
public void logout(PlayerDisconnectEvent event) throws SQLException {
if(!plugin.chatEnabled)return;
String name = event.getPlayer().getName();
if(name==null){
for(String data:plugin.onlinePlayers.keySet()){
if(plugin.getProxy().getPlayer(data)==null){
plugin.onlinePlayers.remove(data);
return;
}
}
}
plugin.getUtilities().updateLastSeen(name);
if (plugin.onlinePlayers.containsKey(name)) {
ChatPlayer cp = plugin.getChatPlayer(name);
if (cp == null){
return;
}
// remove from all channels
for (String data : cp.getChannels()) {
ChatChannel cc = plugin.getChannel(data);
cc.offlineMember(cp);
}
plugin.getChannel(cp.getCurrentServer()).removeMember(cp.getName());
if (plugin.chatSpying.contains(cp.getName())) {
plugin.chatSpying.remove(cp.getName());
}
plugin.onlinePlayers.remove(event.getPlayer().getName());
}
} |
ac2a413a-aef5-4e90-90bc-5dcff36a4b45 | 6 | protected ChunkManager(Plots p)
{
this.p = p;
chunkFile = new File(p.getDataFolder(), File.separator+"chunks.yml");
memberFile = new File(p.getDataFolder(), File.separator+"member.yml");
if(!chunkFile.exists())
{
try
{
if(!chunkFile.createNewFile())
{
p.getLogger().warning("Failed to create the save file for chunks");
}
}
catch(IOException ex)
{
ex.printStackTrace();
}
}
if(!memberFile.exists())
{
try
{
if(!memberFile.createNewFile())
{
p.getLogger().warning("Failed to create the save file for member rights");
}
}
catch(IOException ex)
{
ex.printStackTrace();
}
}
log = p.getLogger();
noclaim = new HashSet<String>(p.getConfig().getStringList("noclaim-chunks"));
} |
c59d8ce2-bdfd-4afe-b33f-bbf2271e7c5c | 6 | static public String encode(final byte[] bytes) {
int i = 0, index = 0, digit = 0;
int currByte, nextByte;
StringBuffer base32 = new StringBuffer((bytes.length + 7) * 8 / 5);
while (i < bytes.length) {
currByte = (bytes[i] >= 0) ? bytes[i] : (bytes[i] + 256); // unsign
/* Is the current digit going to span a byte boundary? */
if (index > 3) {
if ((i + 1) < bytes.length) {
nextByte =
(bytes[i + 1] >= 0) ? bytes[i + 1] : (bytes[i + 1] + 256);
} else {
nextByte = 0;
}
digit = currByte & (0xFF >> index);
index = (index + 5) % 8;
digit <<= index;
digit |= nextByte >> (8 - index);
i++;
} else {
digit = (currByte >> (8 - (index + 5))) & 0x1F;
index = (index + 5) % 8;
if (index == 0)
i++;
}
base32.append(base32Chars.charAt(digit));
}
return base32.toString();
} |
7c0f075a-1804-4d1d-ae55-c89d0e790019 | 0 | public employee(String id) {
super(id);
} |
596b1462-7dc7-4dd7-ba89-a322f742b39e | 5 | public JSONObject increment(String key) throws JSONException {
Object value = this.opt(key);
if (value == null) {
this.put(key, 1);
} else if (value instanceof Integer) {
this.put(key, ((Integer) value).intValue() + 1);
} else if (value instanceof Long) {
this.put(key, ((Long) value).longValue() + 1);
} else if (value instanceof Double) {
this.put(key, ((Double) value).doubleValue() + 1);
} else if (value instanceof Float) {
this.put(key, ((Float) value).floatValue() + 1);
} else {
throw new JSONException("Unable to increment [" + quote(key) + "].");
}
return this;
} |
b468aa1a-229b-4a40-a485-c735f703a6c2 | 6 | public void title() {
switch(titleMenu.select()) {
case(-1):
break;
// Starting a new game
case(0):
if(Theater.saveFile.matches("New")) {
Theater.get().loadStage();
} else {
System.out.println("This shoudn't happen");
}
closeMenu();
titleMenu = null;
break;
// Loading a previous save game
case(1):
titleMenuType = TitleMenuType.LOADGAME;
buildTitleMenu();
break;
// Checking the Options
case(2):
titleMenuType = TitleMenuType.OPTIONS;
buildTitleMenu();
break;
// Exiting the game
case(3):
Theater.toBeClosed = true;
closeMenu();
titleMenu = null;
break;
}
} |
04913278-705d-4b8c-bc2b-a8e702c4d62c | 1 | public boolean canHaveAsCreditLimit(BigInteger creditLimit) {
return (creditLimit != null) && (creditLimit.compareTo(BigInteger.ZERO) <= 0);
} |
cc160c31-ca96-4bef-b22d-6d9edef0801d | 4 | public BulkAdd(java.awt.Frame parent, String currVersion, List<String> versions, String currCategory) {
super(parent);
initComponents();
files = new ArrayList<File>();
new FileDrop(jList1, new FileDrop.Listener() {
public void filesDropped(File[] f ) {
for(int i=0; i<f.length; i++) {
files.add(f[i]);
}
updateList();
} // end filesDropped
}); // end FileDrop.Listener
for(int i=0; i<jComboBox1.getItemCount(); i++) {
String cat = ((String) jComboBox1.getItemAt(i)).toLowerCase().replaceAll(" ", "_");
if(cat.equals(currCategory)) {
jComboBox1.setSelectedIndex(i);
break;
}
}
version = currVersion;
for(int i=0; i<versions.size(); i++) {
jComboBox2.addItem("webOS " + versions.get(i));
}
jComboBox2.setSelectedItem("webOS " + version);
getContentPane().requestFocus();
} |
3b2a7116-a61f-4fc9-bd2a-6c1c985b2fdf | 2 | public static int floatAlphaToIntAlpha(float alpha) {
if(alpha < 0f || alpha > 1f) {
throw new IllegalArgumentException("alpha must be between 0f and 1f. value: " + alpha);
}
return (int) (255 * alpha);
} |
c3d09681-c877-4e96-b7ee-bdb57e8b278b | 8 | private void fileTransfertServer()
{
Socket l_newClient = null;
this.ctrl_fileServerActivation = true;
while( this.ctrl_fileServerActivation )
{
try
{
l_newClient = this.ctrl_srvSock.accept();
l_newClient.setSoTimeout( (int) this.ctrl_tcpTransfertTimeout );
ctrl_downloader.ReSet( l_newClient,
this.ctrl_fileBoxDirectory );
if( ctrl_downloader.getHeader() ) // a timeout can occur
{
//ASK TO USER !!
String ll_clientName = addrToName( l_newClient.getInetAddress() );
String ll_fileName = ctrl_downloader.getFilenameFromHeader();
String ll_fileSize = Long.toString( ctrl_downloader.getFileSizeFromHeader());
Logger.notify("New File Transfert Request from " + ll_clientName + " (" + ll_fileName + "," + ll_fileSize + " Bytes )");
if( UserInteract.askuser( "<html><strong>" + ll_clientName + "</strong> wants to send you a file : </html>\n\n" +
"<html>Name\t : <strong><i>\"" + ll_fileName + "\"</i></strong>.</html>\n" +
"<html>Size\t : <strong>" + ll_fileSize + "</strong> octets.</html>\n\n" +
"<html><center>Will you accept this request ?</center></html>","New request !") )
{
ctrl_downloader.accept();
ctrl_trayinter.InformationMessage("Download of " + ll_fileName + " started.");
if( ctrl_downloader.getData() ) // a timeout can occur
{
// SUCCESS DOWNLOAD
Logger.notify("Download is ok !");
ctrl_trayinter.InformationMessage("Download of " + ll_fileName + " successful !");
}
else
{
// FAILURE DOWNLOAD
Logger.error("Download failed...");
ctrl_trayinter.ErrorMessage("Download of " + ll_fileName + " failed...");
}
}
else
{
ctrl_downloader.refuse();
}
}
else
{
Logger.error("Cannot read the header...");
}
l_newClient.close();
}
catch ( SocketTimeoutException e)
{
//Logger.exception(e.toString());;
// No answer from client
Logger.error("Client timed out...");
}
catch (SocketException e)
{
if( this.ctrl_fileServerActivation)
{
Logger.exception(e.toString());;
Logger.error("Socket error...");
}
else
{
/* Nothing to do : server was intentionally closed */
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
Logger.exception(e.toString());;
Logger.error("I/O Fatal error...");
}
finally
{
// Closing the socket is not compulsory, thanks to garbage collector
}
}
} |
6d73b8f2-f56a-4be5-8ea1-5c87637e4a32 | 7 | public boolean loadFixMessage( String aFixMessage )
{
logger.debug("Loading FIX string " + aFixMessage);
if ( ( getAtdl4jOptions().getInputAndFilterData() != null ) &&
( getAtdl4jOptions().getInputAndFilterData().getInputSelectStrategyName() != null ) )
{
logger.debug("getAtdl4jOptions().getInputAndFilterData().getInputSelectStrategyName(): " + getAtdl4jOptions().getInputAndFilterData().getInputSelectStrategyName());
logger.debug("Invoking selectDropDownStrategy: " + getAtdl4jOptions().getInputAndFilterData().getInputSelectStrategyName() );
getStrategySelectionPanel().selectDropDownStrategyByStrategyName( getAtdl4jOptions().getInputAndFilterData().getInputSelectStrategyName() );
}
else // Match getWireValue() and then use getUiRep() if avail, otherwise getName()
{
if ( ( getStrategies() != null ) && ( getStrategies().getStrategyIdentifierTag() != null ) )
{
String strategyWireValue = FIXMessageParser.extractFieldValueFromFIXMessage( aFixMessage, getStrategies().getStrategyIdentifierTag().intValue() );
logger.debug("strategyWireValue: " + strategyWireValue);
if ( strategyWireValue != null )
{
logger.debug("Invoking selectDropDownStrategy for strategyWireValue: " + strategyWireValue );
getStrategySelectionPanel().selectDropDownStrategyByStrategyWireValue( strategyWireValue );
}
}
}
if (getSelectedStrategy() == null)
{
// -- Notify StrategyEventListener (eg Atdl4jTesterPanel) --
fireStrategyEventListenerStrategyNotValidated( null, "Please select a strategy" );
return false;
}
// -- (aReinitPanelFlag=true) --
StrategyUI ui = getStrategiesUI().getStrategyUI( getSelectedStrategy(), true );
// -- Note available getStrategies() may be filtered due to SecurityTypes, Markets, or Region/Country rules --
if ( ui != null )
{
logger.debug( "Invoking ui.setFIXMessage() for: " + ui.getStrategy().getName() + " with FIX Message: " + aFixMessage );
ui.setFIXMessage(aFixMessage);
logger.debug( "FIX string loaded successfully!" );
// -- Notify StrategyEventListener (eg Atdl4jTesterPanel), aSelectedViaInputFixMsg=true --
fireStrategyEventListenerStrategySelected( getSelectedStrategy(), true );
return true;
}
else
{
// -- Notify StrategyEventListener (eg Atdl4jTesterPanel) --
fireStrategyEventListenerStrategyNotValidated( getSelectedStrategy(), getSelectedStrategy().getName() + " is not available." );
return false;
}
// catch (ValidationException ex)
// {
// getAtdl4jUserMessageHandler().displayException( "Validation Exception", "", ex );
// logger.debug( "Validation Exception:", ex );
//
// // -- Notify StrategyEventListener (eg Atdl4jTesterPanel) --
// fireStrategyEventListenerStrategyValidationFailed( getSelectedStrategy(), ex );
// return false;
// }
// catch (Exception ex)
// {
// getAtdl4jUserMessageHandler().displayException( "Exception", "", ex );
// logger.warn( "Generic Exception", ex );
//
// // -- Notify StrategyEventListener (eg Atdl4jTesterPanel) --
// fireStrategyEventListenerStrategyNotValidated( getSelectedStrategy(), "" );
// return false;
// }
} |
008d53a5-5d36-4e0c-bb94-40c3e2712f80 | 9 | @Test
public void testInstance() throws Exception {
SmilesParser sp = new SmilesParser(DefaultChemObjectBuilder.getInstance());
IAtomContainer ac = sp.parseSmiles("Nc1ccccc1");
IAtomContainer g1 = new AtomContainer(ac);
AdjacencyList adj = new AdjacencyList();
List<Node> nodes = new ArrayList<Node>();
int counter = 0;
for (IAtom atom0 : g1.atoms()) {
nodes.add(counter++, new Node(atom0));
}
for (Node atom0 : nodes) {
for (Node atom1 : nodes) {
IBond bond = g1.getBond(atom0.getAtom(), atom1.getAtom());
if (bond != null) {
adj.addEdge(atom0, atom1, bond);
}
}
}
for (int i = 0; i < nodes.size(); i++) {
for (int j = 0; j < nodes.size(); j++) {
if (i < j) {
IBond bond = g1.getBond(nodes.get(i).getAtom(), nodes.get(j).getAtom());
if (bond != null) {
adj.addEdge(nodes.get(i), nodes.get(j), bond);
}
}
}
}
for (Node node : nodes) {
AdjacencyList minBranching = new EdmondsChuLiu().getMinBranching(node, adj);
Assert.assertEquals(6, minBranching.getAllEdges().size());
}
} |
7a34048d-f7c4-4b28-abe4-1cae82adafb8 | 4 | public void checkForUpdate() throws IOException {
new Thread(new Runnable() {
@Override
public void run() {
try {
int retval = updater.DownloadUrlPool("Files/Version/Serverversion", "Serverversion", null);
if (retval == 1) {
BufferedReader Server = new BufferedReader(new FileReader("Files/Version/Serverversion"));
String zeile1 = Server.readLine();
label_3.setText(zeile1.replace(" Completeupdate", ""));
label_2.setText(Gui.Version);
String ClientVersion = Gui.Version.replace(".", "");
int INTClientVersion = Integer.parseInt(ClientVersion);
String ServerVersion = zeile1.replace(".", "").replace(" Completeupdate", "");
System.out.println("- Client-Version is: " + Gui.Version);
System.out.println("- Server-Version is: " + zeile1.replace(" Completeupdate", ""));
int INTServerVersion = Integer.parseInt(ServerVersion);
if (INTServerVersion > INTClientVersion) {
Update.button.setEnabled(true);
} else {
Update.button.setEnabled(false);
}
if (zeile1.contains(" Completeupdate") == true) {
System.out.println("Complete Update needed!");
Update.button.setEnabled(false);
Update.message();
}
} else {
}
} catch (IOException IOException) {
button.setEnabled(false);
}
}
}).start();
} |
3031e200-5c20-43d6-8df2-3ec0e6839c4b | 7 | @Override
public V put(K key, V value) {
int code=key.hashCode();
int hash =hash(code);
hash &=mask;
int hash2 =hash2(code);
hash2 &=mask;
int hash3 =hash3(code);
hash3 &=mask;
Object tk =table[hash];
if (key.equals(tk)) {
V old =(V) table[hash + 1];
table[hash + 1] =value;
return old;
}
tk =table[hash2];
if (key.equals(tk)) {
V old =(V) table[hash2 + 1];
table[hash2 + 1] =value;
return old;
}
tk =table[hash3];
if (key.equals(tk)) {
V old =(V) table[hash3 + 1];
table[hash3 + 1] =value;
return old;
}
tk =table[hash];
if (tk == null) {
table[hash] =key;
table[hash + 1] =value;
size++;
return null;
}
tk =table[hash2];
if (tk == null) {
table[hash2] =key;
table[hash2 + 1] =value;
size++;
return null;
}
tk =table[hash3];
if (tk == null) {
table[hash3] =key;
table[hash3 + 1] =value;
size++;
return null;
}
// System.out.println(Integer.toHexString(hash)+"\t"+Integer.toHexString(hash2)+"\t"+Integer.toHexString(hash3));
// fail. This is generally very rare.
// evict key value pair...
Object pushKey =table[hash];
Object pushValue =table[hash + 1];
table[hash] =key;
table[hash + 1] =value;
// System.out.println("Key:"+key+"\t"+hash);
assert !key.equals(pushKey);
pushInsert(pushKey, pushValue);
size++;
if (size > threshold)
rehash();
return null;
} |
e483d438-7caa-4316-81dd-152a37814fde | 8 | public CLIController() {
Action exitAction = new Action() {
@Override
public void execute(ArgSet args) {
stopped = true;
}
};
Action debugAction = new Action() {
@Override
public void execute(ArgSet args) {
int i = args.fetchInteger();
Debugger.setLevel(i);
}
};
Action debugTrackAddAction = new Action() {
@Override
public void execute(ArgSet args) {
String tag = args.pop();
Debugger.trackAdd(tag);
}
};
Action debugTrackRemoveAction = new Action() {
@Override
public void execute(ArgSet args) {
String tag = args.pop();
Debugger.trackRemove(tag);
}
};
Action debugTrackListAction = new Action() {
@Override
public void execute(ArgSet args) {
Set<String> tags = Debugger.seenTags();
System.out.println("Seen tags:");
for(String s: tags) {
System.out.println("\t " + s);
}
}
};
Action scriptAction = new Action() {
@Override
public void execute(ArgSet args) {
while(args.hasArg()) {
String path = args.pop();
try {
File f = new File(path);
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
String s;
do {
s = br.readLine();
if(s != null) {
controller.handle(new ArgSet(s));
}
} while(s != null);
br.close();
} catch(FileNotFoundException e) {
System.out.println("[CommandLineInterface] The file " + path + " does not exist.");
} catch(IOException e) {
System.out.println("[CommandLineInterface] An error occurred while reading from file " + path);
e.printStackTrace();
return;
}
}
}
};
Action echoAction = new Action() {
@Override
public void execute(ArgSet args) {
if(args.hasStringArg()) {
System.out.println(args.fetchString());
} else if(args.hasArg()) {
System.out.println(args.pop());
} else {
System.out.println("[CommandLineInterface] the command \"echo\" requires an argument enclosed by quotation marks");
}
}
};
Action innerAction = new CommandAction(innerController);
mapCommand("exit", exitAction);
getContext("debug").mapCommand("level", debugAction);
getContext("debug").getContext("track").mapCommand("add", debugTrackAddAction);
getContext("debug").getContext("track").mapCommand("remove", debugTrackRemoveAction);
getContext("debug").getContext("track").mapCommand("list", debugTrackListAction);
mapAbbreviation('r', scriptAction);
mapCommand("run", scriptAction);
mapCommand("echo", echoAction);
setDefaultAction(innerAction);
} |
559d1e69-26a7-4dfd-ae65-1b3f93e53395 | 2 | public void renameAndHide() {
CPArtwork artwork = controller.getArtwork();
if (layerNb >= 0 && layerNb < artwork.getLayersNb()) {
artwork.setLayerName(layerNb, getText());
}
layerNb = -1;
setVisible(false);
setEnabled(false);
} |
6b51f36a-76d5-4f5f-b3fb-19eeb4b79c45 | 2 | public JSONObject putOpt(String key, Object value) throws JSONException {
if (key != null && value != null) {
this.put(key, value);
}
return this;
} |
127c5cf3-6a03-4a2e-b027-1c93932a78fa | 4 | public static int recuClimbStairs(int n){
if(n==1)
return 1;
if(n==2)
return 2;
int left = 0, right = 0;
if(tmpResult[n-1] == 0)
tmpResult[n-1] = recuClimbStairs(n-1);
left = tmpResult[n-1];
if(tmpResult[n-2] == 0)
tmpResult[n-2] = recuClimbStairs(n-2);
right = tmpResult[n-2];
return left + right;
} |
dfdc4c92-2249-43c8-973d-00e85e5ae0ad | 9 | private double calculateScore(ArrayList<seed> seedlist) {
double total = 0.0;
for (int i = 0; i < seedlist.size(); i++) {
double score = 0.0;
double chance = 0.0;
double totaldis = 0.0;
double difdis = 0.0;
for (int j = 0; j < seedlist.size(); j++) {
if (j != i) {
totaldis = totaldis
+ Math.pow(
distance(seedlist.get(i), seedlist.get(j)),
-2);
}
}
for (int j = 0; j < seedlist.size(); j++) {
if (j != i
&& ((seedlist.get(i).tetraploid && !seedlist.get(j).tetraploid) || (!seedlist
.get(i).tetraploid && seedlist.get(j).tetraploid))) {
difdis = difdis
+ Math.pow(
distance(seedlist.get(i), seedlist.get(j)),
-2);
}
}
chance = difdis / totaldis;
score = chance + (1 - chance) * s;
total = total + score;
}
return total;
} |
f308f7da-3838-49bc-985e-dc083f2b7120 | 4 | @Override
public void mouseDragged(MouseEvent e) {
Graphics graphics = d.getGraphics();
if(this.p.getCurrentTool() == -1){
if(working_layer != -1){
if(now_resizing){
p.resizeFigureUsingCorner(working_layer, active_corner, e.getX(), e.getY());
}else{
p.moveFiguresOnLayer(this.working_layer, e.getX()-delta_x, e.getY()-delta_y);
}
}
}else{
try{
Thread.sleep(15);
d.paint(d.getGraphics());
delta_x = e.getX() - oringin_x ;
delta_y = e.getY() - origin_y ;
d.paintDrawable(p.buildDrawable(p.getCurrentTool(), oringin_x, origin_y, delta_x, delta_y), graphics);
}catch(Exception ex){
}
}
dragged = true;
} |
2e4d4c50-0f25-4884-b09e-07ce5bb31463 | 6 | public void update(double time) {
switch (enemyState) {
case MOVING:
updateMovement(time);
break;
case SHOOTING:
break;
case SEARCHING:
updateSearch(time);
break;
}
if (Collision.canEnemySeePlayer(this)) {
enterSightMode();
lastKnownPlayerLoc = Game.getWorld().getPlayer().location;
} else {
if (enemyState == EnemyState.SHOOTING) {
enemyState = EnemyState.SEARCHING;
createPathToPlayer();
}
}
if (Collision.isEnemyIntersectingBullet(this)) {
destroyed = true;
}
} |
91061795-922e-4822-8e2b-cbd077b15ab1 | 2 | public static boolean needsUpdate(EntityType type) {
boolean b = false;
switch (type) {
case OBJ_TREE:
break;
case OBJ_DOOR_WOOD:
break;
}
return b;
} |
62e7c378-6739-4ffd-bf9d-aaba66c1b419 | 5 | public static void main(String[] args) throws IOException, NumberFormatException {
if (args.length < 1) {
System.out.println("Please use command \n"
+"java -jar yc173.jar \"tilepuzyc173\" \"tilepuzinput.txt\"\n"
+"or\n"
+"java -jar yc173.jar \"queensyc173\" n \n"
+"to run the jar file");
return;
}
if (args[0].equals("tilepuzyc173")) {
if (args.length < 2) {
System.out.println("Please input the input file name: tilepuzinput.txt");
return;
}
String filename = args[1];
int[][] intialState = FifteenState.parseInitialState(filename);
AStarSearch.search(FifteenSearchNode.generateRoot(intialState));
} else if (args[0].equals("queensyc173")) {
if (args.length < 2) {
System.out.println("Please input an int n for the number of queens");
return;
}
int nQueens = Integer.parseInt(args[1]);
AStarSearch.search(SuperqueensSearchNode.generateRoot(nQueens));
} else {
System.out.println("Unknown problem name: " + args[0]);
}
} |
8b9824f9-0665-44b1-bb51-34a32e6a2240 | 2 | public static Punktbewegung findPunktbewegungById(ArrayList<Punktbewegung> punktbewegungs, int id) {
for(Punktbewegung punktbewegung:punktbewegungs) {
if(punktbewegung.getId()==id) {
return punktbewegung;
}
}
return new Punktbewegung();
} |
806c50ae-d81f-4751-b4d6-e975ad78eda8 | 8 | public void setData(String title, String yleg, final TimeSeriesCollection tsc) {
JFreeChart chart = ChartFactory.createTimeSeriesChart(
title, "Date", yleg, tsc, true, true, false);
XYPlot plot = (XYPlot) chart.getPlot();
XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(){
private static final long serialVersionUID = 1L;
@Override
public Paint getItemPaint(int row, int column) {
Paint col;
if (row == 0) {
col = Color.pink;
} else {
col = Color.cyan;
}
long x = (long)tsc.getXValue(row, column);
// Ha az adott idpont egy tarts rendszerkimarads intervallumba esik, akkor a jell pont fekete lesz.
for (int i = 0; i < (sysdown.size() - 1); i += 2) {
if ((x >= sysdown.get(i)) && (x <= sysdown.get(i+1))) {
return Color.black;
}
}
// Ha az adott idpont beleesik a szenzor tarts kimaradsa intervallumba a jell pont szine lecserldik.
for (int i = 0; i < (sensor.getHeavyLoss().size() - 1); i += 2) {
if ((x > sensor.getHeavyLoss().get(i)) && (x < sensor.getHeavyLoss().get(i+1))) {
return col;
}
}
return super.getItemPaint(row, column);
}
@Override
public boolean getItemLineVisible(int series, int item) {
if (series == 0) return false;
else return true;
}
};
renderer.setSeriesShape(0, circle);
renderer.setSeriesShape(1, circle);
renderer.setBaseStroke(new BasicStroke(1));
plot.setRenderer(renderer);
chart_panel.setChart(chart);
} |
77ac706a-45b0-4ec9-b54f-09da1b53e653 | 0 | @Test
public void testReadField_protected()
{
Assert.assertEquals(
"protected",
ReflectUtils.readField(new Bean(), "_field3")
);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.