text
stringlengths 10
2.72M
|
|---|
package com.example.yamil.test.Models;
import com.parse.ParseClassName;
import com.parse.ParseFile;
import com.parse.ParseObject;
@ParseClassName("Hotel")
public class Hotel extends ParseObject {
private String objectId;
private String name;
private String description;
private Number score;
private String address;
private ParseFile photo;
public String getId() {
return getObjectId();
}
public String getName() {
return getString("name");
}
public void setName(String name) {
put("name", name);
}
public String getDescription() {
return getString("description");
}
public void setDescription(String description) {
put("description", description);
}
public Number getScore() {
return getNumber("score");
}
public void setScore(float score) {
put("score", score);
}
public String getAddress() {
return getString("address");
}
public void setAddress(String address) {
put("address", address);
}
public ParseFile getPhoto() {
return getParseFile("photo");
}
public void setPhoto(ParseFile photo) {
put("photo", photo);
}
}
|
package com.seleniumpom.tests.framework;
import org.apache.log4j.Logger;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import static org.testng.Assert.assertNotNull;
public class TestConfiguration {
protected Logger logger = Logger.getLogger(getClass());
private Properties properties;
private static TestConfiguration instance;
private TestConfiguration()
{
properties = System.getProperties();
//First load developer-specific settings, if any
merge(properties, propertiesFrom("local.properties"));
//Then load the global settings (used by Jenkins)
merge(properties, propertiesFrom("default.properties"));
}
public static TestConfiguration getInstance()
{
if (instance == null){
instance = new TestConfiguration();
}
return instance;
}
private Properties propertiesFrom(String propertyFileName) {
final Properties developerSpecific = new Properties();
loadPropertiesFile(developerSpecific, propertyFileName);
return developerSpecific;
}
private void loadPropertiesFile(Properties target, String propertyFileName) {
final InputStream stream = getClass().getClassLoader().getResourceAsStream(propertyFileName);
if (stream != null) {
try {
target.load(stream);
} catch (IOException e) {
logger.warn("Properties file ["+propertyFileName+"] not found - ignoring");
}
}
}
/**
* Merge properties according to Ant's precedence rules. That is, properties should be immutable, and once set, the values cannot be set again.
*
* @param original The original (immutable) set of properties
* @param additions Properties to be added to original. Any properties in this set that share a key with original will be discarded.
*/
private void merge(Properties original, Properties additions) {
for (Object keyToAdd : additions.keySet()) {
if (!original.containsKey(keyToAdd)) {
original.put(keyToAdd, additions.get(keyToAdd));
}
}
}
private String get(String key) {
String property = properties.getProperty(key);
assertNotNull(property, "Required property [" + key + "] not found");
return property;
}
// Public methods
public BrowserUtil.BrowserType getBrowser(){
String property = get("webdriver.browser");
return BrowserUtil.BrowserType.valueOf(property.toUpperCase());
}
public BrowserUtil.DriverType getDriverType(){
String property = get("webdriver.type");
return BrowserUtil.DriverType.valueOf(property.toUpperCase());
}
public String getSiteUrl(){
return get("site.url");
}
public String getSeleniumGridURL(){
return get("webdriver.seleniumgrid.url");
}
}
|
package ir.ceit.search.model;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Vector;
public class Dictionary {
private Node root;
private int size;
private Vector<HashMap<Node, Integer>> docList;
private int docSize;
private ArrayList<DocHeapElement> docHeap;
public Dictionary() {
this.root = null;
docList = new Vector<>();
docHeap = new ArrayList<>();
this.size = 0;
this.docSize = 0;
}
public void addWord(Node currentNode, String word, int docID, int position) {
if (this.root == null) {
Node newNode = new Node(word);
DocListElement doc = new DocListElement(docID);
doc.addToPositionList(position);
newNode.setDocHead(doc);
newNode.increaseDf();
this.root = newNode;
this.docList.get(docID).put(newNode, 1);
this.size++;
} else if (currentNode.getWord().equals(word)) {
if (!this.docList.get(docID).keySet().contains(currentNode)) {
this.docList.get(docID).put(currentNode, 1);
currentNode.increaseDf();
} else {
int tf = this.docList.get(docID).get(currentNode);
this.docList.get(docID).replace(currentNode, tf + 1);
}
DocListElement currentDoc = currentNode.getDocHead();
while (currentDoc.getNextDoc() != null && currentDoc.getNextDoc().getDocID() < docID) {
currentDoc = currentDoc.getNextDoc();
}
if (currentDoc.getNextDoc() == null) {
if (currentDoc.getDocID() == docID) {
currentDoc.addToPositionList(position);
} else {
DocListElement newDoc = new DocListElement(docID);
newDoc.addToPositionList(position);
currentDoc.setNextDoc(newDoc);
}
} else if (currentDoc.getNextDoc().getDocID() == docID) {
currentDoc = currentDoc.getNextDoc();
currentDoc.addToPositionList(position);
} else if (currentDoc.getNextDoc().getDocID() > docID) {
DocListElement newDoc = new DocListElement(docID);
newDoc.addToPositionList(position);
newDoc.setNextDoc(currentDoc.getNextDoc());
currentDoc.setNextDoc(newDoc);
}
} else if (currentNode.getWord().compareTo(word) < 0) {
if (currentNode.getRightNode() == null) {
Node newNode = new Node(word);
DocListElement doc = new DocListElement(docID);
doc.addToPositionList(position);
newNode.setDocHead(doc);
this.docList.get(docID).put(newNode, 1);
newNode.increaseDf();
currentNode.setRightNode(newNode);
this.size++;
} else {
addWord(currentNode.getRightNode(), word, docID, position);
}
} else {
if (currentNode.getLeftNode() == null) {
Node newNode = new Node(word);
DocListElement doc = new DocListElement(docID);
doc.addToPositionList(position);
newNode.setDocHead(doc);
newNode.increaseDf();
this.docList.get(docID).put(newNode, 1);
currentNode.setLeftNode(newNode);
this.size++;
} else {
addWord(currentNode.getLeftNode(), word, docID, position);
}
}
}
public Node searchWord(String word) {
return searchWord(this.root, word);
}
public Node searchWord(Node currentNode, String word) {
if (currentNode == null) {
return new Node("");
}
if (currentNode.getWord().equals(word)) {
return currentNode;
} else if (currentNode.getWord().compareTo(word) < 0) {
return searchWord(currentNode.getRightNode(), word);
} else {
return searchWord(currentNode.getLeftNode(), word);
}
}
public void printDictionary() {
printDictionary(this.root);
}
public void printDictionary(Node node) {
if (node == null) {
return;
} else {
printDictionary(node.getLeftNode());
System.out.println("word:" + node.getWord());
DocListElement docHead = node.getDocHead();
while (docHead != null) {
System.out.println("ID:" + docHead.getDocID() + docHead.getPositionList());
docHead = docHead.getNextDoc();
}
printDictionary(node.getRightNode());
}
}
public Vector<HashMap<Node, Integer>> getDocList() {
return docList;
}
public ArrayList<DocHeapElement> getDocHeap() {
return docHeap;
}
public void addDocHeapElement(int docID) {
this.docHeap.add(new DocHeapElement(docID));
}
public void addDocList() {
this.docList.add(new HashMap<>());
}
public Node getRoot() {
return root;
}
public void setRoot(Node root) {
this.root = root;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public int getDocSize() {
return docSize;
}
public void setDocSize(int docSize) {
this.docSize = docSize;
}
}
|
import net.webservicex.GeoIP;
import net.webservicex.GeoIPService;
import net.webservicex.GeoIPServiceSoap;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author nguyenhongphat0
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
GeoIPService ipservice = new GeoIPService();
GeoIPServiceSoap geoIPServiceSoap = ipservice.getGeoIPServiceSoap();
GeoIP geoip = geoIPServiceSoap.getGeoIP("222.255.236.148");
System.out.println(geoip.getCountryName());
System.out.println(geoip.getReturnCodeDetails());
}
}
|
package mydomain.needit;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* Created by Michal on 08/03/2016.
*/
public class InMemoryDB {
static List<UserLocation> userLocations = new LinkedList<>();
static List<Request> requests = new LinkedList<>();
static List<Response> responses = new LinkedList<>();
static Map<Type, List<Runnable>> runnableMap = new HashMap<>();
public static List<UserLocation> getUserLocations() {
return userLocations;
}
public static List<Request> getRequests() {
return requests;
}
public static List<Response> getResponses() {
return responses;
}
public static void setUserLocations(List<UserLocation> userLocations) {
if (InMemoryDB.userLocations.containsAll(userLocations) && userLocations.containsAll(InMemoryDB.userLocations)) {
return;
}
InMemoryDB.userLocations = userLocations;
updateRegistered(Type.USERS);
}
public static void setRequests(List<Request> requests) {
if (InMemoryDB.requests.containsAll(requests) && requests.containsAll(InMemoryDB.requests)) {
return;
}
InMemoryDB.requests = requests;
updateRegistered(Type.REQUESTS);
}
public static void setResponses(List<Response> responses) {
if (InMemoryDB.responses.containsAll(responses) && responses.containsAll(InMemoryDB.responses)) {
return;
}
InMemoryDB.responses = responses;
updateRegistered(Type.RESPONSES);
}
public static void registerUpdate(Type type, Runnable callback) {
List<Runnable> runnables = runnableMap.get(type);
if (runnables == null) {
runnables = new LinkedList<>();
runnableMap.put(type, runnables);
}
runnables.add(callback);
}
public static void updateRegistered(Type type) {
List<Runnable> runnables = runnableMap.get(type);
if (runnables == null)
return;
for (Runnable runnable : runnableMap.get(type)) {
runnable.run();
}
}
public static void update() {
new ServerUsersTask().execute();
new ServerRequestTask().execute();
new ServerResponderstTask().execute();
//new ServerPostUserTask().execute(new UserLocation("Michal", UserDetailsProvider.getUserDetailsProvider().getLocation())); //todo:access location etc.
}
public enum Type {
USERS,
RESPONSES,
REQUESTS
}
}
|
package com.flowedu.dto;
import lombok.Data;
@Data
public class PagingDto {
private int start;
private int end;
public PagingDto() {}
public PagingDto(int start, int end) {
this.start = start;
this.end = end;
}
}
|
package com.evan.graphics;
public interface CommandExcuteHandler {
public void onSuccess(String filePath);
public void onError(int code, String message);
}
|
package com.pointinside.android.app.util;
import android.os.AsyncTask;
import android.util.Log;
public abstract class DetachableAsyncTask<Params, Progress, Result>
extends AsyncTask<Params, Progress, Result>
{
private static final String TAG = DetachableAsyncTask.class.getSimpleName();
private TaskCallbacks<Result, Progress> mCallback;
public void clearCallback()
{
this.mCallback = null;
}
protected final void onCancelled()
{
if (this.mCallback != null) {
this.mCallback.onCancelled();
}
}
protected final void onPostExecute(Result paramResult)
{
if (this.mCallback != null)
{
this.mCallback.onPostExecute(paramResult);
return;
}
Log.w(TAG, "Dropping async task result on floor");
}
protected final void onPreExecute()
{
if (this.mCallback != null) {
this.mCallback.onPreExecute();
}
}
protected final void onProgressUpdate(Progress... paramVarArgs)
{
if (this.mCallback != null) {
this.mCallback.onProgressUpdate(paramVarArgs);
}
}
public void setCallback(TaskCallbacks<Result, Progress> paramTaskCallbacks)
{
this.mCallback = paramTaskCallbacks;
}
public static abstract class TaskCallbacks<R, P>
{
protected void onCancelled() {}
protected void onPostExecute(R paramR) {}
protected void onPreExecute() {}
protected void onProgressUpdate(P... paramVarArgs) {}
}
}
/* Location: D:\xinghai\dex2jar\classes-dex2jar.jar
* Qualified Name: com.pointinside.android.app.util.DetachableAsyncTask
* JD-Core Version: 0.7.0.1
*/
|
/******************************************************************************
* __ *
* <-----/@@\-----> *
* <-< < \\// > >-> *
* <-<-\ __ /->-> *
* Data / \ Crow *
* ^ ^ *
* info@datacrow.net *
* *
* This file is part of Data Crow. *
* Data Crow is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public *
* License as published by the Free Software Foundation; either *
* version 3 of the License, or any later version. *
* *
* Data Crow is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public *
* License along with this program. If not, see http://www.gnu.org/licenses *
* *
******************************************************************************/
package net.datacrow.util.svg;
import java.awt.Color;
import java.awt.image.BufferedImage;
import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.ImageTranscoder;
public class BufferedImageTranscoder extends ImageTranscoder {
private BufferedImage biLast = null;
/**
* Constructs a new transcoder that produces BufferedImage images.
*/
public BufferedImageTranscoder() {
hints.put(ImageTranscoder.KEY_BACKGROUND_COLOR, Color.white);
}
/**
* Creates a new ARGB image with the specified dimension.
* @param width the image width in pixels
* @param height the image height in pixels
*/
@Override
public BufferedImage createImage(int width, int height) {
return new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
}
/**
* Writes the specified image to the specified output.
* @param img the image to write
* @param output the output where to store the image
* @param TranscoderException if an error occurred while storing the image
*/
@Override
public void writeImage(BufferedImage img, TranscoderOutput output) throws TranscoderException {
biLast = img;
}
public BufferedImage getLastRendered(){
return biLast;
}
}
|
package io.spring.bookstore.exception;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class GlobalException {
@ExceptionHandler(value = RuntimeException.class)
public ResponseEntity<String> handleError() {
return new ResponseEntity<>("Something Were Wrong", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
|
/*
* Copyright 2017 Rundeck, Inc. (http://rundeck.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 org.rundeck.client.api.model.scheduler;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.rundeck.client.api.model.JobItem;
import java.util.*;
@JsonIgnoreProperties(ignoreUnknown = true)
public class ForecastJobItem extends JobItem {
private List<Date> futureScheduledExecutions;
public List<Date> getFutureScheduledExecutions() {
return futureScheduledExecutions;
}
}
|
package ru.mcfr.oxygen.framework.operations;
import ro.sync.ecss.extensions.api.*;
import ro.sync.ecss.extensions.api.node.AuthorDocumentFragment;
import ro.sync.ecss.extensions.api.node.AuthorElement;
import ro.sync.ecss.extensions.api.node.AuthorNode;
import ro.sync.util.URLUtil;
import javax.swing.*;
import javax.swing.text.BadLocationException;
import java.awt.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.URL;
/**
* Operation to save the Author node at caret in a separate document and refresh the new file path in the project.
*/
public class ExtractNodeToFileOperation implements AuthorOperation {
/**
* @see ro.sync.ecss.extensions.api.AuthorOperation#doOperation(ro.sync.ecss.extensions.api.AuthorAccess, ro.sync.ecss.extensions.api.ArgumentsMap)
*/
public void doOperation(AuthorAccess authorAccess, ArgumentsMap args) throws IllegalArgumentException,
AuthorOperationException {
// int caretOffset = authorAccess.getEditorAccess().getCaretOffset();
// String message = null;
// try {
// // Get node at caret
// AuthorNode nodeAtCaret = authorAccess.getDocumentController().getNodeAtOffset(caretOffset);
// JFileChooser fileChooser = new JFileChooser();
// fileChooser.setMultiSelectionEnabled(false);
//
// // Show Save Dialog
// if (fileChooser.showSaveDialog((Component) authorAccess.getWorkspaceAccess().getParentFrame())
// == JFileChooser.APPROVE_OPTION) {
// File outputFile = fileChooser.getSelectedFile();
// FileOutputStream fos = new FileOutputStream(outputFile);
// OutputStreamWriter writer = new OutputStreamWriter(fos, "UTF-8");
//
// // Write the node fragment
// AuthorDocumentFragment fragment = authorAccess.getDocumentController().createDocumentFragment(nodeAtCaret, true);
// String xmlFragment = authorAccess.getDocumentController().serializeFragmentToXML(fragment);
// writer.write(xmlFragment);
// writer.close();
//
// // Open file
// URL outputFileUrl = URLUtil.correct(outputFile);
// authorAccess.getWorkspaceAccess().open(outputFileUrl);
//
// // Refresh in project
// authorAccess.getWorkspaceAccess().refreshInProject(outputFileUrl);
// }
// } catch (BadLocationException e) {
// e.printStackTrace();
// } catch (IOException e) {
// e.printStackTrace();
// }
//
// if (message != null) {
// authorAccess.getWorkspaceAccess().getWorkspaceAccess().showErrorMessage(message);
// }
try{
AuthorNode[] nodes = authorAccess.getDocumentController().findNodesByXPath("//*", true, true, true);
authorAccess.getWorkspaceAccess().showErrorMessage("elements: " + nodes.length);
String ids = "value:\n";
int maxID = 0;
for (AuthorNode node : nodes){
try{
if (node.getType() == AuthorNode.NODE_TYPE_ELEMENT){
AuthorElement ae = (AuthorElement) node;
int id = Integer.valueOf(ae.getAttribute("id").getValue());
if (id > maxID)
maxID = id;
//ids += "name: " + ae.getXMLBaseURL().toString() + "id = " + ae.getAttribute("id") + "\n";
}
} catch (Exception e){
}
}
authorAccess.getWorkspaceAccess().showErrorMessage("maxID: " + maxID);
} catch (Exception e){
authorAccess.getWorkspaceAccess().showErrorMessage("error:" + e.getMessage());
}
}
/**
* @see ro.sync.ecss.extensions.api.AuthorOperation#getArguments()
*/
public ArgumentDescriptor[] getArguments() {
return null;
}
/**
* @see ro.sync.ecss.extensions.api.Extension#getDescription()
*/
public String getDescription() {
return "Save the Author node at caret in a separate document and refresh the new file path in the project";
}
}
|
package com.petpet.c3po.adaptor.rules;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import junit.framework.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import com.petpet.c3po.adaptor.AbstractAdaptor;
import com.petpet.c3po.datamodel.Element;
public class PostProcessingPriority {
@Test
public void shouldOrderProcessingRulesInAscendingOrder() throws Exception {
TestAdaptor a = new TestAdaptor();
PostProcessingRule ppr1 = Mockito.mock(PostProcessingRule.class);
PostProcessingRule ppr2 = Mockito.mock(PostProcessingRule.class);
Mockito.when(ppr1.getPriority()).thenReturn(42);
Mockito.when(ppr2.getPriority()).thenReturn(666);
List<ProcessingRule> rules = new ArrayList<ProcessingRule>();
rules.add(ppr1);
rules.add(ppr2);
a.setRules(rules);
Assert.assertEquals(42, rules.get(0).getPriority());
Assert.assertEquals(666, rules.get(1).getPriority());
rules = a.getRules();
Assert.assertEquals(666, rules.get(0).getPriority());
Assert.assertEquals(42, rules.get(1).getPriority());
}
@Test
public void shouldGetRulesOfType() throws Exception {
TestAdaptor a = new TestAdaptor();
PreProcessingRule ppr1 = new PreProcessingRule() {
@Override
public int getPriority() {
return 1;
}
@Override
public boolean shouldSkip(String property, String value, String status, String tool, String version) {
return false;
}
};
PostProcessingRule ppr2 = new PostProcessingRule() {
@Override
public int getPriority() {
return 1;
}
@Override
public Element process(Element e) {
return e;
}
};
List<ProcessingRule> rules = new ArrayList<ProcessingRule>();
rules.add(ppr1);
rules.add(ppr2);
a.setRules(rules);
List<PreProcessingRule> prerules = a.getPreProcessingRules();
Assert.assertEquals(1, prerules.size());
}
private class TestAdaptor extends AbstractAdaptor {
@Override
public void run() {
}
@Override
public void configure(Map<String, Object> config) {
}
public List<ProcessingRule> getRules() {
return super.getRules();
}
public List<PreProcessingRule> getPreProcessingRules() {
return super.getPreProcessingRules();
}
}
}
|
package com.trump.auction.trade.service.impl.bid;
public class bidFinishHandle {
}
|
package com.gaoshin.cloud.web.job.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
import com.gaoshin.cloud.web.job.bean.WorkStatus;
import common.util.Misc;
@Entity
@Table
public class TaskExecutionTryEntity {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
@Column
private Long taskExecutionId;
@Column(length = 64)
@Enumerated(EnumType.STRING)
private WorkStatus status = WorkStatus.Pending;
@Column
private Long startTime;
@Column
private Long finishTime;
@Column
@Lob
private String note;
@Column
@Lob
private String stdout;
@Column
private Integer nextTaskExecOrder;
@Column
@Lob
private String processInfo;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public void setStatus(WorkStatus status) {
this.status = status;
}
public WorkStatus getStatus() {
return status;
}
public Long getTaskExecutionId() {
return taskExecutionId;
}
public void setTaskExecutionId(Long taskExecutionId) {
this.taskExecutionId = taskExecutionId;
}
public Long getStartTime() {
return startTime;
}
public void setStartTime(Long startTime) {
this.startTime = startTime;
}
public Long getFinishTime() {
return finishTime;
}
public void setFinishTime(Long finishTime) {
this.finishTime = finishTime;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public void appendNote(Exception e) {
String trace = Misc.getStackTrace(e);
if(note == null) {
note = trace;
}
else {
note = note + "\n\n" + trace;
}
}
public void appendNote(String log) {
if(note == null) {
this.note = log;
}
else {
this.note = this.note + "\n\n" + log;
}
}
public String getStdout() {
return stdout;
}
public void setStdout(String stdout) {
this.stdout = stdout;
}
public void appendStdout(String log) {
if(stdout == null) {
this.stdout = log;
}
else {
this.stdout = this.stdout + "\n\n" + log;
}
}
public Integer getNextTaskExecOrder() {
return nextTaskExecOrder;
}
public void setNextTaskExecOrder(Integer nextTaskExecOrder) {
this.nextTaskExecOrder = nextTaskExecOrder;
}
public String getProcessInfo() {
return processInfo;
}
public void setProcessInfo(String processInfo) {
this.processInfo = processInfo;
}
}
|
package com.robin.springbootlearn.common.controller;
/**
* 公共控制器
*
* @author robin
* @version v0.0.1
* @since 2020-04-06 17:29
*/
public class SuperController {
}
|
/**
* Copyright (C) 2008 Atlassian
*
* 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.atlassian.connector.intellij.bamboo;
import static org.easymock.EasyMock.and;
import static org.easymock.EasyMock.createStrictMock;
import com.atlassian.theplugin.commons.bamboo.BuildStatus;
import org.easymock.EasyMock;
import org.easymock.IArgumentMatcher;
import java.util.Arrays;
import junit.framework.TestCase;
public class BambooStatusListenerTest extends TestCase {
private BambooStatusDisplay displayMock;
private BambooStatusTooltipListener tooltipListener;
@Override
protected void setUp() throws Exception {
super.setUp();
displayMock = createStrictMock(BambooStatusDisplay.class);
tooltipListener = new BambooStatusTooltipListener(displayMock, null);
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
displayMock = null;
tooltipListener = null;
}
public void testSingleBuildFailed() {
BambooBuildAdapter buildFail = HtmlBambooStatusListenerTest.generateBuildInfo(BuildStatus.FAILURE);
EasyMock.replay(displayMock);
tooltipListener.updateBuildStatuses(Arrays.asList(buildFail), null);
EasyMock.verify(displayMock);
}
public void testSingleBuildSucceed() {
BambooBuildAdapter build = HtmlBambooStatusListenerTest.generateBuildInfo(BuildStatus.SUCCESS);
EasyMock.replay(displayMock);
tooltipListener.updateBuildStatuses(Arrays.asList(build), null);
EasyMock.verify(displayMock);
}
public void testSingleBuildUnknown() {
BambooBuildAdapter build = HtmlBambooStatusListenerTest.generateBuildInfo(BuildStatus.UNKNOWN);
EasyMock.replay(displayMock);
tooltipListener.updateBuildStatuses(Arrays.asList(build), null);
EasyMock.verify(displayMock);
}
public static class PopupInfoHtmlContains implements IArgumentMatcher {
private final String expected;
public PopupInfoHtmlContains(String expected) {
this.expected = expected;
}
public boolean matches(Object actual) {
if (!(actual instanceof BambooPopupInfo)) {
return false;
}
String actualMessage = ((BambooPopupInfo) actual).toHtml();
return actualMessage.matches(expected);
}
public void appendTo(StringBuffer buffer) {
buffer.append("xxx (");
buffer.append(expected);
buffer.append(")");
}
}
public static BambooPopupInfo findPopupInfo(String pattern) {
EasyMock.reportMatcher(new PopupInfoHtmlContains(pattern));
return null;
}
public void testSingleBuildOK2Failed() {
BambooBuildAdapter buildOK = HtmlBambooStatusListenerTest.generateBuildInfo(BuildStatus.SUCCESS);
BambooBuildAdapter buildFail = HtmlBambooStatusListenerTest.generateBuildInfo(BuildStatus.FAILURE);
displayMock.updateBambooStatus(EasyMock.eq(BuildStatus.FAILURE), findPopupInfo(".*red.*failed.*"));
EasyMock.replay(displayMock);
tooltipListener.updateBuildStatuses(Arrays.asList(buildOK), null);
tooltipListener.updateBuildStatuses(Arrays.asList(buildFail), null);
EasyMock.verify(displayMock);
}
public void testSingleBuildFailed2OK() {
BambooBuildAdapter buildOK = HtmlBambooStatusListenerTest.generateBuildInfo(BuildStatus.SUCCESS);
BambooBuildAdapter buildFail = HtmlBambooStatusListenerTest.generateBuildInfo(BuildStatus.FAILURE);
displayMock.updateBambooStatus(EasyMock.eq(BuildStatus.SUCCESS), findPopupInfo(".*green.*succeed.*"));
EasyMock.replay(displayMock);
tooltipListener.updateBuildStatuses(Arrays.asList(buildFail), null);
tooltipListener.updateBuildStatuses(Arrays.asList(buildOK), null);
EasyMock.verify(displayMock);
}
public void testSingleBuildSequence() {
BambooBuildAdapter buildUnknown = HtmlBambooStatusListenerTest.generateBuildInfo(BuildStatus.UNKNOWN);
BambooBuildAdapter buildSucceeded = HtmlBambooStatusListenerTest.generateBuildInfo(BuildStatus.SUCCESS);
BambooBuildAdapter buildFailed = HtmlBambooStatusListenerTest.generateBuildInfo(BuildStatus.FAILURE);
EasyMock.replay(displayMock);
tooltipListener.updateBuildStatuses(Arrays.asList(buildUnknown), null);
tooltipListener.updateBuildStatuses(Arrays.asList(buildUnknown), null);
tooltipListener.updateBuildStatuses(Arrays.asList(buildUnknown), null);
tooltipListener.updateBuildStatuses(Arrays.asList(buildSucceeded), null);
tooltipListener.updateBuildStatuses(Arrays.asList(buildUnknown), null);
tooltipListener.updateBuildStatuses(Arrays.asList(buildSucceeded), null);
tooltipListener.updateBuildStatuses(Arrays.asList(buildSucceeded), null);
tooltipListener.updateBuildStatuses(Arrays.asList(buildSucceeded), null);
tooltipListener.updateBuildStatuses(Arrays.asList(buildSucceeded), null);
tooltipListener.updateBuildStatuses(Arrays.asList(buildUnknown), null);
tooltipListener.updateBuildStatuses(Arrays.asList(buildUnknown), null);
EasyMock.verify(displayMock);
EasyMock.reset(displayMock);
displayMock.updateBambooStatus(EasyMock.eq(BuildStatus.FAILURE), findPopupInfo(".*red.*failed.*"));
EasyMock.replay(displayMock);
tooltipListener.updateBuildStatuses(Arrays.asList(buildFailed), null);
EasyMock.verify(displayMock);
EasyMock.reset(displayMock);
EasyMock.replay(displayMock);
tooltipListener.updateBuildStatuses(Arrays.asList(buildFailed), null);
tooltipListener.updateBuildStatuses(Arrays.asList(buildFailed), null);
tooltipListener.updateBuildStatuses(Arrays.asList(buildUnknown), null);
tooltipListener.updateBuildStatuses(Arrays.asList(buildUnknown), null);
tooltipListener.updateBuildStatuses(Arrays.asList(buildFailed), null);
tooltipListener.updateBuildStatuses(Arrays.asList(buildUnknown), null);
EasyMock.verify(displayMock);
EasyMock.reset(displayMock);
displayMock.updateBambooStatus(EasyMock.eq(BuildStatus.SUCCESS), findPopupInfo(".*green.*succeed.*"));
EasyMock.replay(displayMock);
tooltipListener.updateBuildStatuses(Arrays.asList(buildSucceeded), null);
EasyMock.verify(displayMock);
EasyMock.reset(displayMock);
EasyMock.replay(displayMock);
tooltipListener.updateBuildStatuses(Arrays.asList(buildSucceeded), null);
tooltipListener.updateBuildStatuses(Arrays.asList(buildUnknown), null);
tooltipListener.updateBuildStatuses(Arrays.asList(buildSucceeded), null);
tooltipListener.updateBuildStatuses(Arrays.asList(buildUnknown), null);
EasyMock.verify(displayMock);
}
public void testMultipleOK2Failed() {
BambooBuildAdapter buildFirstUnknown = HtmlBambooStatusListenerTest.generateBuildInfo(BuildStatus.UNKNOWN);
BambooBuildAdapter buildFirstFailed = HtmlBambooStatusListenerTest.generateBuildInfo(BuildStatus.FAILURE);
BambooBuildAdapter buildFirstOK = HtmlBambooStatusListenerTest.generateBuildInfo(BuildStatus.SUCCESS);
BambooBuildAdapter buildSecondUnknown = HtmlBambooStatusListenerTest.generateBuildInfo2(BuildStatus.UNKNOWN);
BambooBuildAdapter buildSecondOK = HtmlBambooStatusListenerTest.generateBuildInfo2(BuildStatus.SUCCESS);
BambooBuildAdapter buildSecondFailed = HtmlBambooStatusListenerTest.generateBuildInfo2(BuildStatus.FAILURE);
displayMock.updateBambooStatus(EasyMock.eq(BuildStatus.FAILURE), findPopupInfo(".*red.*failed.*"));
EasyMock.replay(displayMock);
tooltipListener.updateBuildStatuses(Arrays.asList(buildFirstUnknown, buildSecondUnknown), null);
tooltipListener.updateBuildStatuses(Arrays.asList(buildFirstOK, buildSecondOK), null);
tooltipListener.updateBuildStatuses(Arrays.asList(buildFirstFailed, buildSecondFailed), null);
EasyMock.verify(displayMock);
}
public void testMultipleFailed2OK() {
BambooBuildAdapter buildFirstUnknown = HtmlBambooStatusListenerTest.generateBuildInfo(BuildStatus.UNKNOWN);
BambooBuildAdapter buildFirstFailed = HtmlBambooStatusListenerTest.generateBuildInfo(BuildStatus.FAILURE);
BambooBuildAdapter buildFirstOK = HtmlBambooStatusListenerTest.generateBuildInfo(BuildStatus.SUCCESS);
BambooBuildAdapter buildSecondUnknown = HtmlBambooStatusListenerTest.generateBuildInfo2(BuildStatus.UNKNOWN);
BambooBuildAdapter buildSecondOK = HtmlBambooStatusListenerTest.generateBuildInfo2(BuildStatus.SUCCESS);
BambooBuildAdapter buildSecondFailed = HtmlBambooStatusListenerTest.generateBuildInfo2(BuildStatus.FAILURE);
displayMock.updateBambooStatus(EasyMock.eq(BuildStatus.SUCCESS), findPopupInfo(".*green.*succeed.*"));
EasyMock.replay(displayMock);
tooltipListener.updateBuildStatuses(Arrays.asList(buildFirstUnknown, buildSecondUnknown), null);
tooltipListener.updateBuildStatuses(Arrays.asList(buildFirstFailed, buildSecondFailed), null);
tooltipListener.updateBuildStatuses(Arrays.asList(buildFirstOK, buildSecondOK), null);
EasyMock.verify(displayMock);
}
public void testMultiple() {
BambooBuildAdapter buildFirstUnknown = HtmlBambooStatusListenerTest.generateBuildInfo(BuildStatus.UNKNOWN);
BambooBuildAdapter buildFirstFailed = HtmlBambooStatusListenerTest.generateBuildInfo(BuildStatus.FAILURE);
BambooBuildAdapter buildFirstOK = HtmlBambooStatusListenerTest.generateBuildInfo(BuildStatus.SUCCESS);
BambooBuildAdapter buildSecondUnknown = HtmlBambooStatusListenerTest.generateBuildInfo2(BuildStatus.UNKNOWN);
BambooBuildAdapter buildSecondOK = HtmlBambooStatusListenerTest.generateBuildInfo2(BuildStatus.SUCCESS);
BambooBuildAdapter buildSecondFailed = HtmlBambooStatusListenerTest.generateBuildInfo2(BuildStatus.FAILURE);
displayMock.updateBambooStatus(EasyMock.eq(BuildStatus.FAILURE), and(findPopupInfo(".*green.*succeed.*"), findPopupInfo(".*red.*failed.*")));
EasyMock.replay(displayMock);
tooltipListener.updateBuildStatuses(Arrays.asList(buildFirstUnknown, buildSecondUnknown), null);
tooltipListener.updateBuildStatuses(Arrays.asList(buildFirstFailed, buildSecondOK), null);
tooltipListener.updateBuildStatuses(Arrays.asList(buildFirstOK, buildSecondFailed), null);
EasyMock.verify(displayMock);
EasyMock.reset(displayMock);
displayMock.updateBambooStatus(EasyMock.eq(BuildStatus.FAILURE), and(findPopupInfo(".*green.*succeed.*"), findPopupInfo(".*red.*failed.*")));
EasyMock.replay(displayMock);
tooltipListener.updateBuildStatuses(Arrays.asList(buildFirstUnknown, buildSecondUnknown), null);
tooltipListener.updateBuildStatuses(Arrays.asList(buildFirstOK, buildSecondFailed), null);
tooltipListener.updateBuildStatuses(Arrays.asList(buildFirstFailed, buildSecondOK), null);
EasyMock.verify(displayMock);
}
}
|
package me.devcom.pdrill;
public class Fuel {
public Integer block_id;
public Integer drillAirSpeed;
public Integer drillBlockSpeed;
public Integer fuelConsumptionBlockCount;
public Integer fuelConsumptionFuelCount;
public String configName;
public Fuel(Integer bid, Integer das, Integer dbs, Integer bc, Integer fc, String name){
block_id = bid;
drillAirSpeed = das;
drillBlockSpeed = dbs;
fuelConsumptionBlockCount = bc;
fuelConsumptionFuelCount = fc;
configName = name;
}
}
|
package hotelManagement;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.Scanner;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import fileio.Student;
public class ReadRoom extends Frame implements ActionListener{
private JLabel messageL;
public ReadRoom()
{
messageL=new JLabel("Select Which Room You want the details?");
GridLayout g = new GridLayout(5,2);
getFrame().setLayout(g);
getFrame().add(messageL);
getFrame().add(getRoomL());
getFrame().add(getRoom());
getFrame().add(getSubmit());
getFrame().add(getBack());
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==getSubmit())
{
//get info by room no. and show all info from file
Person [] persons = new Person [5];
Scanner s = new Scanner(System.in);
Person []data = new Person[100];
int index = 0;
//Person temp = new Person();
try {
File f = new File("data.txt");
Scanner x = new Scanner(f);
while(x.hasNextLine())
{
String name = x.nextLine();
String nid = x.nextLine();
String address = x.nextLine();
String phone = x.nextLine();
String daysToRentF = x.nextLine();
String coastF = x.nextLine();
// data is stored in file as String, even numbers
double daysToRent = Double.parseDouble(daysToRentF);
double coast = Double.parseDouble(coastF);
Person temp = new Person(name,nid,address,phone,daysToRent, coast);
data[index] = temp;
index++;
}
}catch (Exception e1) {
JOptionPane.showMessageDialog(null, e1.getMessage());
}
getFrame().setVisible(true);
//JOptionPane.showMessageDialog(null, "Mr X booked this room for 3 days \nHis Phone:\nHis Address");
}
else if(e.getSource()==getBack())
{
getFrame().setVisible(false);
new Menu();
}
}
}
|
import java.util.*;
public class testabel {
public double y(double x) {
double hasil = (x*x*x) - (2*(x*x) - x + 1);
return hasil;
}
public static void main(String[] args) {
testabel uji = new testabel();
Scanner input = new Scanner(System.in);
System.out.print("masukan batas xBawah :");
double xBawah = input.nextDouble();
System.out.print("masukan batas xAtas :");
double xAtas = input.nextDouble();
System.out.print("masukan jumlah pembagi N :");
int N = input.nextInt();
double h = (xAtas - xBawah) / N;
double x[] = new double[N + 1];
double y[] = new double[N + 1];
for (int i = 0; i <= N; i++) {
x[i] = xBawah + (i * h);
y[i] = y(x[i]);
System.out.println("nilai x[" + i + "]= " + x[i] + "& nilai y[" + i + "]=" + y[i]);
}
for (int j=0;j<=(N-1);j++) {
if(y[j] * y[j+1] < 0) {
System.out.println(" " + x[j] + " dan " + x[j + 1]);
if (Math.abs(y[j]) < Math.abs (y[j+1])) {
System.out.println("Jawabannya " + x[j]);
} else {
System.out.println("Jawabannya " + x[j+1]);
}
}
}
}
}
|
package example1.employee;
public class JsonExporter implements Employee.Exporter {
private String name;
@Override
public void storeName(String name) {
this.name = name;
}
@Override
public String toString() {
//json representation (low level details)
return "{\"name\":\"" + name + "\"}";
}
}
|
package net.davoleo.javagui.forms.controls;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
/*************************************************
* Author: Davoleo
* Date / Hour: 04/01/2019 / 15:18
* Class: JComboboxGui
* Project: JavaGUI
* Copyright - © - Davoleo - 2018
**************************************************/
public class JComboboxGui extends JFrame{
private JComboBox box;
private JLabel picture;
private static String[] filename = {"40x40.png", "ingot_blue.png"};
private Icon[] pics = {new ImageIcon(getClass().getResource(filename[0])), new ImageIcon(getClass().getResource(filename[1]))};
public JComboboxGui()
{
super("ComboBox!");
setLayout(new FlowLayout());
box = new JComboBox(filename);
box.addItemListener(
new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e)
{
if(e.getStateChange() == ItemEvent.SELECTED)
picture.setIcon(pics[box.getSelectedIndex()]);
}
}
);
add(box);
picture=new JLabel(pics[0]);
add(picture);
}
}
|
package blackjack;
public class Card {
private int val;
private int face;
private final int SPADES = 1;
private final int CLUBS = 4;
private final int HEARTS = 2;
private final int DIAMONDS = 3;
private final int ACE = 1;
private final int KING = 13;
private final int JACK = 11;
private final int QUEEN = 12;
private String str;
public Card(int suit, int value){
val = value;
face= suit;
}
public int getFace(){
return face;
}
public int getValue(){
if(val>=10)
return 10;
return val;
}
public boolean equals(Card a){
if(a.getValue() == this.getValue())
return true;
return false;
}
public String toString(){
if(val == 11)
str = "J";
else if(val == 12)
str = "Q";
else if(val == 13)
str = "K";
else if(val == 1)
str = "A";
else if(val > 0 && val < 14)
str = "" + val;
str += " ";
if(face == 2)
str += "♥";
else if(face == 4)
str += "♣";
else if(face == 1)
str+= "♠";
else if(face == 3)
str += "♦";
return str;
}
}
|
/*
* Copyright (C) 2021 Tenisheva N.I.
*/
package com.entrepreneurship.rest.webservices.restfulwebservices.model;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import java.util.Date;
import java.util.Objects;
/*
* {@ code Funds receipt} class represents properties and behaviours of funds receipt objects.
<br>
Each funds receipt has id, date, {@link Invoice invoice}, sum,
{@link Users user} and comment
<br>
@version 1.0
@author Tenisheva N.I.
*/
@Setter
@Getter
@Entity
@Table(name="FUNDS_RECEIPT")
public class FundsReceipt {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "date")
private Date date;
@Column(name = "sum")
private double sum;
@Column(name = "comment")
private String comment;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "id_username", nullable = false)
private Users user;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "id_invoice", nullable = false)
private Invoice invoice;
public FundsReceipt(Long id, Date date, double sum, String comment) {
super();
this.id = id;
this.date = date;
this.sum = sum;
this.comment = comment;
}
public FundsReceipt() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public double getSum() {
return sum;
}
public void setSum(double sum) {
this.sum = sum;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public Invoice getInvoice() {
return invoice;
}
public void setInvoice(Invoice invoice) {
this.invoice = invoice;
}
public Users getUser() {
return user;
}
public void setUser(Users user) {
this.user = user;
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!(obj instanceof FundsReceipt))
return false;
FundsReceipt other = (FundsReceipt) obj;
return this.id == other.id;
}
@Override
public String toString() {
return "FundsReceipt [date=" + date + ", sum=" + sum + "]";
}
}
|
public class Solution{
public static int conversion(int A,int B){
int num = A ^ B;
int count = 0;
while(num!=0){
num = num & (num-1);//this clears the rightmost 1 in bits.
count++;
}
return count;
}
}
|
package com.nfet.icare.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.nfet.icare.dao.ParseExcelMapper;
import com.nfet.icare.pojo.DeviceInfo;
@Service
public class ParseExcelServiceImpl implements ParseExcelService {
@Autowired
private ParseExcelMapper parseExcelMapper;
@Override
public int insertDeviceInfo(List<DeviceInfo> deviceInfos) {
// TODO Auto-generated method stub
return parseExcelMapper.insertDeviceInfo(deviceInfos);
}
}
|
package aiClass;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import deck.Card;
import deck.CardValue;
import deck.Suit;
/**
* Class that figures out what the ai-players cards are.
* @author Max Frennessen
* 17-05-25
* @version 2.0
*
* @author Henrik
* @version 3.0
* Added checks for finding and saving the best combination. Added checks for any existing flush.
*
* @version 3.1
* Fixed a small bug that prevented a straight from being detected. Fixed a bug that would
* overwrite the high-card as the best combination. Added a function to prevent all five
* table-cards from being used when prior to the river-round.
*/
public class AiCalculation {
private ArrayList<Card> aiHand = new ArrayList<Card>();
private ArrayList<Card> allCards = new ArrayList<Card>();
private ArrayList<Card> bestCombination = new ArrayList<Card>();
private int handStrength = 0;
private int pairs = 0, same = 0;
private boolean flush = false, straight = false, fullHouse = false;
/**
* Gets the cards that will be needed to calculate a respons that the ai will do.
* @param aiHand the current cards that are used by the ai.
*/
public AiCalculation(ArrayList<Card> aiHand, ArrayList<Card> tableCards) {
this.aiHand = aiHand;
allCards.addAll(aiHand);
allCards.addAll(tableCards);
doChecks();
}
public void doChecks() {
bestCombination = new ArrayList<Card>();
handStrength = 0; pairs = 0; same = 0;
flush = false; straight = false; fullHouse = false;
checkHighCards();
checkSuit();
checkPairAndMore();
checkStraight();
calcHandStrength();
}
/**
* Checks if ai-players has high cards or not.
* @return returns if the cards have a combined value of 17 or more.
*/
public boolean checkHighCards() {
boolean high = false;
int card1 = aiHand.get(0).getCardValue();
int card2 = aiHand.get(1).getCardValue();
if ((card1 + card2) >= 17) {
high = true;
}
if(bestCombination.isEmpty()) {
if(card1 > card2) {
bestCombination.add(aiHand.get(0));
} else {
bestCombination.add(aiHand.get(1));
}
}
return high;
}
/**
* calculates the number of same suits the ai players has.
* @return returns if the AI has a chance or has a flush
*/
public int checkSuit() {
int C = 0, S = 0, H = 0, D = 0;
int color = 0;
String suit = "";
for (Card card : allCards) {
String cardColor = card.getCardSuit().substring(0, 1);
if (cardColor.equals("S")) {
S++;
} else if (cardColor.equals("C")) {
C++;
} else if (cardColor.equals("D")) {
D++;
} else if (cardColor.equals("H")) {
H++;
}
}
if (S > color) {
color = S;
suit = "S";
}
if (H > color) {
color = H;
suit = "H";
}
if (D > color) {
color = D;
suit = "D";
}
if (C > color) {
color = C;
suit = "C";
}
if(color == 5) {
bestCombination.clear();
for(Card card : allCards) {
if(card.getCardSuit().substring(0, 1).equals(suit)) {
bestCombination.add(card);
}
}
flush = true;
}
return color;
}
/**
* calculates the amount of same cards that the ai-player has to use.
* @return returns how many pairs or more that the ai has.
*/
public int checkPairAndMore() {
int[] cardValuesOccurrences = new int[15];
for (int i = 0; i < allCards.size(); i++) {
cardValuesOccurrences[allCards.get(i).getCardValue()]++;
}
//Gets amount of pairs and the highest amount of cards with the same value
for(int i : cardValuesOccurrences) {
System.out.print(i);
if(i > same) {
same = i;
}
if(i >= 2) {
pairs++;
}
}
//Checks for full house
if(same >= 3 && pairs >= 2) {
fullHouse = true;
}
//Gets the best combination
if(fullHouse || pairs >= 1) {
if(fullHouse && same < 4) { //Gets the fullhouse combination
int pairValue = 0, threeOfAKindValue = 0;
for(int i = (cardValuesOccurrences.length-1); i >= 0; i--) {
if(cardValuesOccurrences[i] >= 3 && threeOfAKindValue == 0) {
threeOfAKindValue = i;
} else if(cardValuesOccurrences[i] >= 2 && pairValue == 0) {
pairValue = i;
}
}
bestCombination.clear();
for(Card card : allCards) {
if(card.getCardValue() == pairValue || card.getCardValue() == threeOfAKindValue) {
bestCombination.add(card);
}
}
} else if((same == 3 && !flush) || same == 4) { //Adds three of a kind or four of a kind to best combination
int tempValue = 0;
for(int i = (cardValuesOccurrences.length-1); i >= 0; i--) {
if(same == 4 && cardValuesOccurrences[i] == 4) {
tempValue = i;
} else if(same == 3 && cardValuesOccurrences[i] == 3 && tempValue == 0) {
tempValue = i;
}
}
bestCombination.clear();
for(Card card : allCards) {
if(card.getCardValue() == tempValue) {
bestCombination.add(card);
}
}
} else if(!flush){ //Adds one pair or two pair to the best combination
int pairOneValue = 0, pairTwoValue = 0, pairOneCount = 0, pairTwoCount = 0;
for(int i = (cardValuesOccurrences.length-1); i >= 0; i--) {
if(cardValuesOccurrences[i] >= 2) {
if(pairOneValue == 0) {
pairOneValue = i;
} else if(pairTwoValue == 0) {
pairTwoValue = i;
}
}
}
bestCombination.clear();
for(Card card : allCards) {
if(card.getCardValue() == pairOneValue && pairOneCount < 2) {
bestCombination.add(card);
pairOneCount++;
} else if(card.getCardValue() == pairTwoValue && pairTwoCount < 2) {
bestCombination.add(card);
pairTwoCount++;
}
}
}
}
return same;
}
//TODO Prioritize Straight Flush
/**
* calculates the number of cards that can be in a straight
* @return returns if the Ai has a chance or has a Straight.
*/
public int checkStraight() {
int treshold = 0;
ArrayList<Integer> cardValues = new ArrayList<Integer>();
for(Card card : allCards) { //Creates a sorted list with the values of all cards
cardValues.add(card.getCardValue());
if(card.getCardValue() == 14) {
cardValues.add(1);
}
}
Collections.sort(cardValues, Collections.reverseOrder());
for(int startValue : cardValues) {
ArrayList<Integer> tempList = new ArrayList<Integer>();
tempList.add(startValue);
for(int value : cardValues) { //Compares the start value with all other values to check for a straight
if(value == (tempList.get(tempList.size() - 1) - 1)) {
if(tempList.size() < 5) {
tempList.add(value);
}
}
}
if(tempList.size() == 5) { //Found a straight
if(same < 4 ) { //Only replace the best combination if there is no four of a kind
bestCombination.clear();
for(int partValue : tempList) { //Converts the values to cards and saves it in the best combination
//TODO Check for royal flush
for(Card card : allCards) {
if(partValue == 1) {
partValue = 14;
}
if(partValue == card.getCardValue()){
bestCombination.add(card);
}
}
}
}
straight = true;
return 5;
} else if(tempList.size() > treshold) {
treshold = tempList.size();
}
}
return treshold;
}
/**
* Sets the handStrenght of the ai-player.
* @return returns the ai-players current handStrenght.
*/
public int calcHandStrength(){
if(same==2){ //One pair
handStrength=1;
}
if(pairs>=2){ //Two pair
handStrength=2;
}
if(same==3){ //Three of a kind
handStrength=3;
}
if(straight){ //Straight
handStrength=4;
}
if(flush){ //Flush
handStrength=5;
}
if(fullHouse){ //Full house
handStrength=6;
}
if(same==4){ //Four of a kind
handStrength = 7;
}
if(flush && straight){ //Straight flush
handStrength = 8;
}
//Missing Royal Flush check?
return handStrength;
}
//TODO Move calculations of the best combination to this function or to new class
public ArrayList<Card> getWinningCards() {
doChecks();
return bestCombination;
}
/**
* If not last round, remove some of the cards from allCards
*/
public ArrayList<Card> getWinningCards(int round) {
if(round < 3) {
if(round == 0) { //Pre-flop
while(allCards.size() > 2) {
allCards.remove(allCards.size() - 1);
}
} else if(round == 1) { //Flop
while(allCards.size() > 5) {
allCards.remove(allCards.size() - 1);
}
} else { //Turn
while(allCards.size() > 6) {
allCards.remove(allCards.size() - 1);
}
}
}
doChecks();
return bestCombination;
}
public ArrayList<Card> getAIHand() {
return aiHand;
}
public ArrayList<Card> getAllCards() {
return allCards;
}
public int getHandStrength(int round) {
if(round < 3) {
if(round == 0) { //Pre-flop
while(allCards.size() > 2) {
allCards.remove(allCards.size() - 1);
}
} else if(round == 1) { //Flop
while(allCards.size() > 5) {
allCards.remove(allCards.size() - 1);
}
} else { //Turn
while(allCards.size() > 6) {
allCards.remove(allCards.size() - 1);
}
}
}
doChecks();
System.out.println(allCards + " - " + handStrength);
System.out.println(allCards + " - " + calcHandStrength());
return handStrength;
}
/*
//For testing different combinations
public static void main(String[] args) {
ArrayList<CardValue> values = new ArrayList<CardValue>();
values.add(CardValue.SIX);
values.add(CardValue.SIX);
values.add(CardValue.FIVE);
values.add(CardValue.QUEEN);
values.add(CardValue.FIVE);
values.add(CardValue.TEN);
values.add(CardValue.KING);
ArrayList<Suit> suits = new ArrayList<Suit>();
suits.add(Suit.SPADES);
suits.add(Suit.DIAMONDS);
suits.add(Suit.DIAMONDS);
suits.add(Suit.DIAMONDS);
suits.add(Suit.CLUBS);
suits.add(Suit.DIAMONDS);
suits.add(Suit.DIAMONDS);
ArrayList<Card> hand = new ArrayList<Card>();
ArrayList<Card> tableCards = new ArrayList<Card>();
hand.add(new Card(suits.get(0), values.get(0), null));
hand.add(new Card(suits.get(1), values.get(1), null));
hand.add(new Card(suits.get(2), values.get(2), null));
hand.add(new Card(suits.get(3), values.get(3), null));
hand.add(new Card(suits.get(4), values.get(4), null));
hand.add(new Card(suits.get(5), values.get(5), null));
hand.add(new Card(suits.get(6), values.get(6), null));
AiCalculation test = new AiCalculation(hand, tableCards);
System.out.println(test.flush);
System.out.println(test.getHandStrength(4));
System.out.println(test.getWinningCards());
}
*/
}
|
package sign.com.web.userGroup;
import java.util.List;
import java.util.Set;
/**
* create by luolong on 2018/5/16
*/
public class UserGroupFrom {
private Integer idGroup;
private String groupName;
private Integer createdBy;
private List<Integer> labelMember;
private List<Integer> uploadMember;
private List<Integer> auditMember;
public Integer getIdGroup() {
return idGroup;
}
public void setIdGroup(Integer idGroup) {
this.idGroup = idGroup;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public Integer getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Integer createdBy) {
this.createdBy = createdBy;
}
public List<Integer> getLabelMember() {
return labelMember;
}
public void setLabelMember(List<Integer> labelMember) {
this.labelMember = labelMember;
}
public List<Integer> getUploadMember() {
return uploadMember;
}
public void setUploadMember(List<Integer> uploadMember) {
this.uploadMember = uploadMember;
}
public List<Integer> getAuditMember() {
return auditMember;
}
public void setAuditMember(List<Integer> auditMember) {
this.auditMember = auditMember;
}
}
|
package com.handpay.obm.common.utils.csv;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import com.handpay.obm.common.utils.FileUtil;
public class CSVUtil{
private static final Logger logger = LoggerFactory.getLogger(CSVUtil.class);
public static void writeDataToFile(List<String[]> strData,
String fileName,boolean isAppend,String charset) throws Exception {
FileUtil.appendData(new File(fileName), strData,charset);
}
public static void writeDataToFile(String data,
String fileName,boolean isAppend,String charset) throws Exception {
FileUtil.writeWithTransferAppend(new File(fileName), data,charset,isAppend);
}
/*public static void writeDateToFile(String data, String fileName,
boolean isAppend,String charset) throws Exception {
FileUtil.writeData(new File(new String(fileName.getBytes(charset),charset)), data,charset);
}
*/
public static void deleteFileIfExsits(String fileName) throws Exception {
FileUtil.deleteFileIfExsits(fileName);
}
}
|
package jp.co.okato;
import java.io.PrintWriter;
import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloServlet extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("Hello World!");
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package tokomainankita;
/**
*
* @author windows10
*/
public class Owner {
private int id_user;
private String nama_lengkap;
private int no_telepon;
/**
* @return the id_user
*/
public int getId_user() {
return id_user;
}
/**
* @param id_user the id_user to set
*/
public void setId_user(int id_user) {
this.id_user = id_user;
}
/**
* @return the nama_lengkap
*/
public String getNama_lengkap() {
return nama_lengkap;
}
/**
* @param nama_lengkap the nama_lengkap to set
*/
public void setNama_lengkap(String nama_lengkap) {
this.nama_lengkap = nama_lengkap;
}
/**
* @return the no_telepon
*/
public int getNo_telepon() {
return no_telepon;
}
/**
* @param no_telepon the no_telepon to set
*/
public void setNo_telepon(int no_telepon) {
this.no_telepon = no_telepon;
}
}
|
package org.blogdemo.homeloan.processor;
import java.util.Map;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
public class MessageProcessor implements Processor{
@Override
public void process(Exchange exchange) throws Exception {
Map<String,Object> headers = exchange.getIn().getHeaders();
for(String headerName : headers.keySet()){
System.out.println("headerName:{"+headerName+"]");
}
Message originalMessage = exchange.getUnitOfWork().getOriginalInMessage();
System.out.println("Original Message:{"+originalMessage+"]");
exchange.getOut().setHeader("SchoolNum", exchange.getIn().getBody());
exchange.getOut().setBody(originalMessage.getBody());
}
}
|
package worker;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;
public class MatchingInstance {
public static Topic computeTopicAverage(List<Worker> workerList, Integer topicId) {
int successfulCalls = 0;
int totalCalls = 0;
int totalTime = 0;
for (int i = 0; i < workerList.size(); i++) {
Topic topic = workerList.get(i).topics.get(topicId);
successfulCalls += topic.numTaken;
totalCalls += topic.successRate != 0.0 ? topic.numTaken / topic.successRate : 0;
totalTime += topic.numTaken * topic.avgTime * 1.0;
}
double averageTime = (totalTime * 1.0) / successfulCalls;
double successRate = (1.0 * successfulCalls) / totalCalls;
return new Topic(topicId, averageTime, successfulCalls, successRate, 0, 0);
}
public static double computeTopicScore(Worker worker, int topicId, Map<Integer, Topic> topics) {
Topic t = worker.topics.get(topicId);
Topic tTotal = topics.get(topicId);
double numCallsMultiplier = Math.sqrt(1.0 * t.numTaken);
double numCallsScore = Math.cbrt(1.0 * t.numTaken);
double timeScore = Math.pow((tTotal.avgTime - t.avgTime) / tTotal.avgTime, 3);
double successScore = Math.pow((t.successRate - tTotal.successRate) / tTotal.successRate, 3);
double score = numCallsScore + numCallsMultiplier * (timeScore + successScore);
return score;
}
public static Map<Integer, Topic> computeAverageForAllTopics(List<Worker> workers, Integer numTopics) {
Map<Integer, Topic> t = new TreeMap<Integer, Topic>();
for (int i = 0; i < numTopics; i++) {
t.put(i, computeTopicAverage(workers, i));
}
return t;
}
public static void computeScores(List<Worker> workers, Integer numTopics, Map<Integer, Topic> topicAvg) {
for (int i = 0; i < workers.size(); i++) {
for (int j = 0; j < numTopics; j++) {
Worker w = workers.get(i);
w.topics.get(j).score = computeTopicScore(w, j, topicAvg);
if (w.topics.get(j).score > 2 * topicAvg.get(j).score) {
topicAvg.get(j).score = w.topics.get(j).score / 2.0;
}
}
}
}
public static void computePreferences(List<Worker> workers, Integer numTopics, Map<Integer, Topic> topicAvg) {
for (int j = 0; j < numTopics; j++) {
int numAbove = 0;
for (int i = 0; i < workers.size(); i++) {
if (workers.get(i).topics.get(j).score > topicAvg.get(j).score) {
numAbove++;
}
}
topicAvg.get(j).preference = workers.size() / (numAbove * 1.0);
}
for (int j = 0; j < numTopics; j++) {
for (int i = 0; i < workers.size(); i++) {
workers.get(i).topics.get(j).preference = workers.get(i).topics.get(j).score *
topicAvg.get(j).preference;
}
}
}
public static void createWorkers(List<Worker> workers, Integer numTopics, Integer numWorkers) {
Random rng = new Random();
List<Integer> topicTime = new ArrayList<Integer>();
for (int i = 0; i < numTopics; i++) {
int avgTimeMin = rng.nextInt(500) + 300;
topicTime.add(avgTimeMin);
}
for (int i = 0; i < numWorkers; i++) {
Map<Integer, Topic> t = new TreeMap<Integer, Topic>();
for (int j = 0; j < numTopics; j++) {
double successRate = rng.nextDouble() / 2;
int avgTime = topicTime.get(j) + rng.nextInt(300);
int numTaken = rng.nextInt(85);
if (numTaken > 15) {
successRate += .5;
}
t.put(j, new Topic(j, avgTime, numTaken, successRate, 0, 0));
}
workers.add(new Worker(t, i));
}
}
public static List<Worker> rankForCallTopic(List<Worker> workers, final Integer topicId, Map<Integer, Topic> topicAvg) {
List<Worker> candidatePool = new ArrayList<Worker>();
for (int i = 0; i < workers.size(); i++) {
if (workers.get(i).topics.get(topicId).score > topicAvg.get(topicId).score) {
candidatePool.add(workers.get(i));
}
}
candidatePool.sort(new Comparator<Worker>() {
public int compare(Worker worker1, Worker worker2) {
return Double.valueOf(worker1.topics.get(topicId).preference).compareTo(
Double.valueOf(worker2.topics.get(topicId).preference));
}
});
return candidatePool;
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package weixin;
/**
*
* @author jerry
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
//new AdminMain().setVisible(true);
new LoginMain().setVisible(true);
//new QFMain().setVisible(true);
}
}
|
package cn.xuetang.common.config;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Wizzer on 14-3-31.
*/
public class Dict {
//行政区划
public static final String DIVSION = "0008";
//接口类型
public static final String APP_TYPE = "0002";
//表单类型
public static final String FORM_TYPE = "0003";
//会员等级
public static final String USER_LEVEL = "0007";
}
|
package io.core9.plugin.widgets.datahandler;
import java.util.List;
import io.core9.plugin.widgets.Core9HiddenField;
import io.core9.plugin.widgets.datahandler.factories.CustomVariable;
public class DataHandlerDefaultConfig implements DataHandlerFactoryConfig {
@Core9HiddenField
private String componentName;
private List<CustomVariable> customVariables;
@Override
public void setComponentName(String componentName) {
this.componentName = componentName;
}
@Override
public String getComponentName() {
return componentName;
}
public List<CustomVariable> getCustomVariables() {
return customVariables;
}
public void setCustomVariables(List<CustomVariable> customVariables) {
this.customVariables = customVariables;
}
}
|
package org.digdata.swustoj.aop;
import java.io.IOException;
import java.sql.SQLException;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.digdata.swustoj.base.BasePointCut;
import org.digdata.swustoj.model.BusinessException;
import org.digdata.swustoj.model.JsonAndModel;
import org.digdata.swustoj.util.ClassUtil;
import org.springframework.core.annotation.Order;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Component;
import io.jsonwebtoken.ExpiredJwtException;
/**
*
* @author wwhhf
* @since 2016年6月1日
* @comment 缓存切面管理 order值越小,顺序越高
*/
@Order(1)
@Aspect
@Component
public class LogAspect extends BasePointCut {
private static Logger logger = Logger.getLogger(LogAspect.class);
/**
*
* @author wwhhf
* @since 2016年6月1日
* @comment service和Dao的日志记录,一切异常往controller层抛出,由controller捕获
* @param joinpoint
* @throws Throwable
*/
@AfterThrowing(value = "ServiceAndDaoPointCut()", throwing = "ex")
public void doServiceAndDaoAfterThrowing(JoinPoint joinpoint, Throwable ex) throws Throwable {
// 在这里判断异常,根据不同的异常返回错误。
if (ex.getClass().equals(DataAccessException.class)) {
throw new BusinessException("数据库操作失败!");
} else if (ex.getClass().toString().equals(NullPointerException.class.toString())) {
throw new BusinessException("调用了未经初始化的对象或者是不存在的对象!");
} else if (ex.getClass().equals(IOException.class)) {
throw new BusinessException("IO异常!");
} else if (ex.getClass().equals(ClassNotFoundException.class)) {
throw new BusinessException("指定的类不存在!");
} else if (ex.getClass().equals(ArithmeticException.class)) {
throw new BusinessException("数学运算异常!");
} else if (ex.getClass().equals(ArrayIndexOutOfBoundsException.class)) {
throw new BusinessException("数组下标越界!");
} else if (ex.getClass().equals(IllegalArgumentException.class)) {
throw new BusinessException("方法的参数错误!");
} else if (ex.getClass().equals(ClassCastException.class)) {
throw new BusinessException("类型强制转换错误!");
} else if (ex.getClass().equals(SecurityException.class)) {
throw new BusinessException("违背安全原则异常!");
} else if (ex.getClass().equals(SQLException.class)) {
throw new BusinessException("操作数据库异常!");
} else if (ex.getClass().equals(NoSuchMethodError.class)) {
throw new BusinessException("方法末找到异常!");
} else if (ex.getClass().equals(InternalError.class)) {
throw new BusinessException("Java虚拟机发生了内部错误");
} else {
throw new BusinessException("程序内部错误,操作失败!" + ex.getMessage());
}
}
/**
*
* @author wwhhff11
* @since 2016年6月21日
* @comment controller层异常捕获,记录日志
*/
@Around("ControllerPointCut()")
public Object around(ProceedingJoinPoint joinPoint) {
Class clazz = joinPoint.getTarget().getClass();
String clazzName = clazz.getName();
String methodName = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
Object result = null;
try {
result = joinPoint.proceed();
return result;
} catch (Throwable ex) {
ex.printStackTrace();
logger.error("**************************************************************");
logger.error("method info: " + ClassUtil.getMethodInfo(clazzName, methodName, args));
logger.error("Exception class: " + ex.getClass().getName());
logger.error("ex.getMessage():" + ex.getMessage());
logger.error("**************************************************************");
return new JsonAndModel(JsonAndModel.ERROR);
}
}
}
|
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.io.FileNotFoundException;
import javax.swing.JPanel;
public class Malowanko extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
try {
if (Zmienne.go == true) {
Graf graf = new Graf();
if (Zmienne.etykietyWierzcholkow == true) {
graf.drawEtykietyWierzcholkow(g);
}
if (Zmienne.nieSkierowana == true) {
graf.drawEdge(g);
}
if (Zmienne.skierowana == true) {
graf.drawSkierowane(g);
}
if (Zmienne.etykietyKrawedzi == true) {
graf.drawEtykietyKrawdzi(g);
}
graf.draw(g);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package com.jit.lembda10;
/*local variable referenced from lambda expression must be final or effectively final*/
public class Test {
int x = 10;
public void m2()
{
int y = 20;
Interf i = () -> {
x =888;
//y =999;
};
i.m1();
}
public static void main(String[] args) {
Test t = new Test();
t.m2();
}
}
|
package com.xue.trainingclass.event;
public class ChangePageEvent {
public int page;
public ChangePageEvent(int page) {
this.page = page;
}
}
|
/*
* Copyright 2002-2012 Drew Noakes
*
* 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.
*
* More information about this project is available at:
*
* http://drewnoakes.com/code/exif/
* http://code.google.com/p/metadata-extractor/
*/
package com.drew.metadata;
import com.drew.imaging.jpeg.JpegProcessingException;
import com.drew.imaging.jpeg.JpegSegmentData;
import com.drew.imaging.jpeg.JpegSegmentReader;
import java.io.*;
/** @author Drew Noakes http://drewnoakes.com */
public class ExtractAppSegmentBytesToFileUtility
{
public static void main(String[] args) throws IOException, JpegProcessingException
{
if (args.length < 2) {
System.err.println("Expects at least two arguments:\n\n <filename> <appSegmentNumber> [<segmentOccurrence>]");
System.exit(1);
}
byte segmentNumber = Byte.parseByte(args[1]);
if (segmentNumber > 0xF) {
System.err.println("Segment number must be between 0 (App0) and 15 (AppF).");
System.exit(1);
}
byte segment = (byte)(JpegSegmentReader.SEGMENT_APP0 + segmentNumber);
String filePath = args[0];
JpegSegmentData segmentData = new JpegSegmentReader(new File(filePath)).getSegmentData();
final int segmentCount = segmentData.getSegmentCount(segment);
if (segmentCount == 0) {
System.err.printf("No data was found in app segment %d.\n", segmentNumber);
System.exit(1);
}
if (segmentCount != 1 && args.length == 2) {
System.err.printf("%d occurrences of segment %d found. You must specify which index to use (zero based).\n", segmentCount, segmentNumber);
System.exit(1);
}
int occurrence = args.length > 2 ? Integer.parseInt(args[2]) : 0;
if (occurrence >= segmentCount) {
System.err.printf("Invalid occurrence number. Requested %d but only %d segments exist.\n", occurrence, segmentCount);
System.exit(1);
}
String outputFilePath = filePath + ".app" + segmentNumber + "bytes";
final byte[] bytes = segmentData.getSegment(segment, occurrence);
System.out.println("Writing output to: " + outputFilePath);
FileOutputStream stream = null;
try {
stream = new FileOutputStream(outputFilePath);
stream.write(bytes);
} finally {
if (stream != null)
stream.close();
}
}
public static byte[] read(File file) throws IOException
{
ByteArrayOutputStream ous = null;
InputStream ios = null;
try {
byte[] buffer = new byte[4096];
ous = new ByteArrayOutputStream();
ios = new FileInputStream(file);
int read;
while ((read = ios.read(buffer)) != -1)
ous.write(buffer, 0, read);
} finally {
if (ous != null)
ous.close();
if (ios != null)
ios.close();
}
return ous.toByteArray();
}
}
|
package testcases;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import pages.LoginPage;
import wdMethods.ProjectMethods;
public class TC005_DeleteLead extends ProjectMethods{
@BeforeTest
public void setData() {
testCaseName="TC005_DeleteLead";
testDescription="Delete user information";
testNodes="DeleteLead";
category="Smoke";
authors="Ramki";
browserName="chrome";
dataSheetName="DeleteLead";
}
@Test(dataProvider="fetchData")
public void DeleteLead(String uName,String pwd,String pNo) throws InterruptedException {
new LoginPage()
.enterUserName(uName)
.enterPassword(pwd)
.clickLogIn()
.clickCrmSfa()
.clickLead()
.clickFindLead()
.clickPhoneTap()
.typePhoneNumber(pNo)
.clickFindLeads()
.clickFirstCol()
.clickDeleteLead()
.clickFindLead()
.typeID()
.clickFindLeads() ;
}
}
|
/*
* Licensed to DuraSpace under one or more contributor license agreements.
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership.
*
* DuraSpace 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.fcrepo.client.integration;
import static javax.ws.rs.core.Response.Status.CREATED;
import static javax.ws.rs.core.Response.Status.FORBIDDEN;
import static javax.ws.rs.core.Response.Status.NO_CONTENT;
import static javax.ws.rs.core.Response.Status.OK;
import static org.fcrepo.client.TestUtils.TEXT_TURTLE;
import static org.fcrepo.client.TestUtils.rdfTtl;
import static org.fcrepo.client.TestUtils.sparqlUpdate;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URI;
import org.apache.commons.io.IOUtils;
import org.fcrepo.client.FcrepoClient;
import org.fcrepo.client.FcrepoResponse;
import org.junit.Ignore;
import org.junit.Test;
/**
* @author mohideen
*/
public class FcrepoAuthenticationIT extends AbstractResourceIT {
protected static FcrepoClient authClient;
public FcrepoAuthenticationIT() throws Exception {
super();
client = FcrepoClient.client().build();
authClient = FcrepoClient.client()
.credentials("fedoraAdmin", "password")
.authScope("localhost")
.build();
}
@Test
public void testAuthUserCanPut() throws Exception {
final InputStream body = new ByteArrayInputStream(rdfTtl.getBytes());
final FcrepoResponse response = authClient.put(new URI(serverAddress + "testobj1"))
.body(body, TEXT_TURTLE)
.perform();
final String content = IOUtils.toString(response.getBody(), "UTF-8");
final int status = response.getStatusCode();
assertEquals("Didn't get a CREATED response! Got content:\n" + content,
CREATED.getStatusCode(), status);
}
@Test
public void testUnAuthUserCannotPut() throws Exception {
final InputStream body = new ByteArrayInputStream(rdfTtl.getBytes());
final FcrepoResponse response = client.put(new URI(serverAddress + "testobj2"))
.body(body, TEXT_TURTLE)
.perform();
final String content = IOUtils.toString(response.getBody(), "UTF-8");
final int status = response.getStatusCode();
assertEquals("Unauthenticated user should be forbidden! Got content:\n" + content,
FORBIDDEN.getStatusCode(), status);
}
@Test
public void testAuthUserCanPatch() throws Exception {
final InputStream body = new ByteArrayInputStream(sparqlUpdate.getBytes());
final FcrepoResponse response = authClient.patch(new URI(serverAddress + "testobj1"))
.body(body)
.perform();
final int status = response.getStatusCode();
assertEquals("Didn't get a successful PATCH response! Got content:\n",
NO_CONTENT.getStatusCode(), status);
}
@Test
public void testUnAuthUserCannotPatch() throws Exception {
final InputStream body = new ByteArrayInputStream(sparqlUpdate.getBytes());
final FcrepoResponse response = client.patch(new URI(serverAddress + "testobj1"))
.body(body)
.perform();
final String content = IOUtils.toString(response.getBody(), "UTF-8");
final int status = response.getStatusCode();
assertEquals("Unauthenticated user should be forbidden! Got content:\n" + content,
FORBIDDEN.getStatusCode(), status);
}
@Test
public void testAuthUserCanPost() throws Exception {
final InputStream body = new ByteArrayInputStream(rdfTtl.getBytes());
final FcrepoResponse response = authClient.post(new URI(serverAddress))
.body(body, TEXT_TURTLE)
.perform();
final String content = IOUtils.toString(response.getBody(), "UTF-8");
final int status = response.getStatusCode();
assertEquals("Didn't get a CREATED response! Got content:\n" + content,
CREATED.getStatusCode(), status);
}
@Test
public void testUnAuthUserCannotPost() throws Exception {
final InputStream body = new ByteArrayInputStream(rdfTtl.getBytes());
final FcrepoResponse response = client.post(new URI(serverAddress))
.body(body, TEXT_TURTLE)
.perform();
final String content = IOUtils.toString(response.getBody(), "UTF-8");
final int status = response.getStatusCode();
assertEquals("Unauthenticated user should be forbidden! Got content:\n" + content,
FORBIDDEN.getStatusCode(), status);
}
@Test
public void testAuthUserCanGet()
throws Exception {
final FcrepoResponse response = authClient.get(new URI(serverAddress)).perform();
final int status = response.getStatusCode();
assertEquals("Authenticated user can not read root!", OK
.getStatusCode(), status);
}
@Ignore("Pending alignment with WebAC in FCREPO-2952")
@Test
public void testUnAuthUserCannotGet()
throws Exception {
final FcrepoResponse response = client.get(new URI(serverAddress)).perform();
final int status = response.getStatusCode();
assertEquals("Unauthenticated user should be forbidden!", FORBIDDEN
.getStatusCode(), status);
}
}
|
package controller;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.DAO.UserDAO;
import model.object.User;
import model.utils.Convert;
@WebServlet( "/login")
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// set up response
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
PrintWriter printWriter = response.getWriter();
// get user
Integer libraryCardId = Convert.convertStringToInt(request.getParameter("libraryCardId"));
String password = request.getParameter("password");
User user = null;
if (libraryCardId != null && password.length() != 0) {
user = UserDAO.getUserByLogin(libraryCardId, password);
}
// processing
if (user == null) {
printWriter.print("error");
} else {
HttpSession session = request.getSession(true);
session.setAttribute("user", user);
if (user.getRoleId() == 1) {
printWriter.print("default?page=home");
} else {
printWriter.print("default?page=adminHome");
}
}
}
}
|
package jire.network;
import java.util.Set;
import jire.packet.PacketService;
import jire.packet.translate.PacketTranslator;
public interface Server {
int getPort();
Set<Client> getClients();
boolean start();
boolean stop();
PacketService getPacketService();
PacketTranslator getPacketTranslator();
Server configurePacketService(PacketService packetService);
Server configurePacketTranslator(PacketTranslator packetTranslator);
}
|
package dev.liambloom.softwareEngineering.chapter17.rightWrong;
/**
* * Mr. Marques
*
* Tree_Building_RIGHT_WRONG_CLIENT: This program will build a tree w/ the values in
* 'nums'. When completed, the Tree will look like:
*
* 8
/ \
/ \
/ \
4 12
/ \ / \
/ \ / \
2 6 10 14
/ \ / \ / \ / \
1 3 5 7 9 11 13 15
*
*
* OutPut:
* Print tree 'InOrder':
* 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 ,
* Print tree 'PreOrder':
* 8 , 4 , 2 , 1 , 3 , 6 , 5 , 7 , 12 , 10 , 9 , 11 , 14 , 13 , 15 ,
* Print tree 'PostOrder':
* 1 , 3 , 2 , 5 , 7 , 6 , 4 , 9 , 11 , 10 , 13 , 15 , 14 , 12 , 8 ,
*
*
*/
import java.util.*;
public class CLIENT
{
public static void main()
{
ArrayList nums = new ArrayList();
TreeNode root=null;
int i;
// Put the numbers into the Arraylist 'nums'
getNumbers(nums);
// RIGHT!!!
// You MUST set the root outside of the method or it will be NULL.
root = new TreeNode(nums.get(0),null,null); // Set root w/ 1st value.
//--------------------WRONG!!!-----------------
// makeTreeTest(root,nums); // WRONG!!!
for(i=1; i<nums.size(); i++) // Make the rest of the tree w/ 1 value at a time.
placeNodeInTree(root,new TreeNode(nums.get(i),null,null));
// ---------------------------- Printing the tree ----------------------------
// NOTE: there are 3 ways to print a tree. PreOrder, InOrder, and PostOrder.
// Trace thru each and understand for the AP test.
//
// -- InOrder -- // This IS the one we use and makes the most sense!!!
System.out.println(" Print tree 'InOrder': -- This IS the one we regularly use! -- ");
printTreeInOrder(root);
System.out.println("\n\n");
// -- PreOrder --
System.out.println(" Print tree 'PreOrder':");
printTreePreOrder(root);
System.out.println("\n\n");
// -- PostOrder --
System.out.println(" Print tree 'PostOrder':");
printTreePostOrder(root);
System.out.println("\n\n");
} // main
// --------------------WRONG!!!-----------------
// This method will NOT work because root2 from here will not stay in memory when we
// return back to main(). Thus, the whole tree is lost. :(
public static void makeTreeTest(TreeNode root2, ArrayList nums)
{
int i;
for(i=0; i<nums.size(); i++) // Make the tree STARTING at 0. WRONG!!!
placeNodeInTree(root2,new TreeNode(nums.get(i),null,null));
}
// --------------------WRONG!!!-----------------
// -----------------------------------------------------------------------------
public static void getNumbers(ArrayList nums)
{
nums.add(new Integer(8)); nums.add(new Integer(4));
nums.add(new Integer(12)); nums.add(new Integer(2));
nums.add(new Integer(6)); nums.add(new Integer(10));
nums.add(new Integer(14)); nums.add(new Integer(1));
nums.add(new Integer(3)); nums.add(new Integer(5));
nums.add(new Integer(7)); nums.add(new Integer(9));
nums.add(new Integer(11)); nums.add(new Integer(13));
nums.add(new Integer(15));
}
// -----------------------------------------------------------------------------
public static void placeNodeInTree(TreeNode t, TreeNode n)
{
// ---- used for makeTreeTest() ----
// if (t==null)
// t = n;
if ( ((Integer)n.getValue()).intValue() < ((Integer)t.getValue()).intValue()) {
if (t.getLeft()==null)
t.setLeft(n);
else
placeNodeInTree(t.getLeft(),n);
}else {
if (t.getRight()==null)
t.setRight(n);
else
placeNodeInTree(t.getRight(),n);
}
} // buildTree
// --------------------------------------------------------------------------------
// "Traversal": Exhaust left side, then print node, then exhaust right side
// output : 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13, 14 , 15 ,
public static void printTreeInOrder(TreeNode t)
{
if (t != null) {
printTreeInOrder(t.getLeft());
System.out.print(t.getValue() + " , ");
printTreeInOrder(t.getRight());
}
}
// --------------------------------------------------------------------------------
// "Traversal": Print the node as each occurs.
// output : 8 , 4 , 2 , 1 , 3 , 6 , 5 , 7 , 12 , 10 , 9 , 11 , 14, 13 , 15 ,
public static void printTreePreOrder(TreeNode t)
{
if (t != null) {
System.out.print(t.getValue() + " , ");
printTreePreOrder(t.getLeft());
printTreePreOrder(t.getRight());
}
}
// --------------------------------------------------------------------------------
// "Traversal": Exhaust left then right side printing the 'root' of each subtree last.
// output : 1 , 3 , 2 , 5 , 7 , 6 , 4 , 9 , 11 , 10 , 15 , 14 , 13, 12 , 8 ,
public static void printTreePostOrder(TreeNode t)
{
if (t != null) {
printTreePostOrder(t.getLeft());
printTreePostOrder(t.getRight());
System.out.print(t.getValue() + " , ");
}
}
} // Tree_Building_CLIENT
|
/*
* @(#) IEbmsContainerLogDAO.java
* Copyright (c) 2007 eSumTech Co., Ltd. All Rights Reserved.
*/
package com.esum.wp.ebms.ebmscontainerlog.dao;
import java.util.List;
import org.springframework.dao.DataAccessException;
import com.esum.appframework.dao.IBaseDAO;
import com.esum.appframework.exception.ApplicationException;
/**
*
* @author heowon@esumtech.com
* @version $Revision: 1.1 $ $Date: 2007/06/20 00:46:00 $
*/
public interface IEbmsContainerLogDAO extends IBaseDAO {
List selectPageList(Object object) throws ApplicationException;
}
|
package com.oxymore.practice.controller;
public class ControllerInitException extends Exception {
public ControllerInitException(String controller, String message) {
super(String.format("Initialization of controller '%s' failed with error '%s'", controller, message));
}
public ControllerInitException(Throwable throwable) {
super(throwable);
}
}
|
/**
* Sencha GXT 3.0.1 - Sencha for GWT
* Copyright(c) 2007-2012, Sencha, Inc.
* licensing@sencha.com
*
* http://www.sencha.com/products/gxt/license/
*/
package com.sencha.gxt.examples.resources.shared;
import com.google.web.bindery.requestfactory.shared.EntityProxy;
import com.google.web.bindery.requestfactory.shared.EntityProxyId;
public interface NamedProxy extends EntityProxy {
Integer getId();
String getName();
@Override
public EntityProxyId<? extends NamedProxy> stableId();
}
|
package com.stackflow.testCases;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import com.stackflow.pageObjects.GmailLogin;
import com.stackflow.pageObjects.StackFlowEmailSentPage;
import com.stackflow.pageObjects.StackFlowHomePage;
import com.stackflow.pageObjects.StackFlowSignUpPage;
public class TC01_RegistrationCheck extends BaseClass {
@Test
public void userSignUpCheck() throws Exception {
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
StackFlowHomePage homepage = new StackFlowHomePage(driver);
StackFlowSignUpPage signup = homepage.signUpButtonClick();
logger.info("User Click on the Sign Up button");
signup.getDisplayName(displayname);
logger.info("User enter the display name");
signup.emailId(signUpEmID);
logger.info("User enter the email Id");
signup.passwordKey(password);
logger.info("User entered password");
StackFlowEmailSentPage emailst = new StackFlowEmailSentPage(driver);
logger.info("Waiting for the user to finish the recaptcha. Once done Please click on sign up button ");
if (emailst.getSuccessEmailSent() == true) {
AssertJUnit.assertTrue(true);
logger.info("Email sent successfully....");
logger.info("Test Case Passed....");
} else {
logger.info("Email sent is failed...");
logger.info("Test Case Failed....");
captureScreen(driver, "userSignUpCheck");
AssertJUnit.assertTrue(false);
}
}
@Test(groups = { "A" }, dependsOnMethods = { "userSignUpCheck" })
public void gmailUserActivate() throws Exception {
driver.get(gmUrl);
logger.info("Gmail url opened.");
GmailLogin gmail = new GmailLogin(driver);
// logging into gmail using the parent email ID.
gmail.enterEmailID(gmailParent);
gmail.enterPassword(password);
logger.info(signUpEmID + " is the email");
logger.info("User Logged in to the Gmail");
// Searching for the email based on the child mail id and text of the mail
// subject
gmail.searchEmail(signUpEmID);
logger.info("User searched email");
gmail.clickEmail(emailSub);
logger.info("User clicked on the mail");
try {
StackFlowHomePage everified = gmail.openLink();
logger.info("User clicked on the activate link");
Thread.sleep(500);
String MainWindow = driver.getWindowHandle();
// To handle all new opened window.
Set<String> s1 = driver.getWindowHandles();
Iterator<String> i1 = s1.iterator();
while (i1.hasNext()) {
String ChildWindow = i1.next();
if (!MainWindow.equalsIgnoreCase(ChildWindow)) {
// Switching to Child window
driver.switchTo().window(ChildWindow);
boolean result = everified.askQuestion();
if (result == true) {
AssertJUnit.assertTrue(true);
logger.info("Successfully user account is activated");
logger.info("Test Case Passed....");
} else {
logger.info("Email sent is failed...");
logger.info("Test Case Failed....");
captureScreen(driver, "gmailUserActivate");
AssertJUnit.assertTrue(false);
}
}
}
} catch (org.openqa.selenium.StaleElementReferenceException ex) {
StackFlowHomePage everified1 = gmail.openLink();
logger.info("User clicked on the activate link");
String MainWindow = driver.getWindowHandle();
// To handle all new opened window.
Set<String> s1 = driver.getWindowHandles();
Iterator<String> i1 = s1.iterator();
while (i1.hasNext()) {
String ChildWindow = i1.next();
if (!MainWindow.equalsIgnoreCase(ChildWindow)) {
// Switching to Child window
driver.switchTo().window(ChildWindow);
boolean result = everified1.askQuestion();
if (result == true) {
AssertJUnit.assertTrue(true);
logger.info("Successfully user account is activated");
logger.info("Test Case Passed....");
} else {
logger.info("Email sent is failed...");
logger.info("Test Case Failed....");
captureScreen(driver, "gmailUserActivate");
AssertJUnit.assertTrue(false);
}
}
}
}
}
}
|
package de.doridian.yiffbukkit.chatcomponent;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.mojang.api.profiles.HttpProfileRepository;
import com.mojang.api.profiles.Profile;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
public class FishBansResolver {
private static final HttpProfileRepository HTTP_PROFILE_REPOSITORY = new HttpProfileRepository("minecraft");
private static final Cache<String, UUID> playerUUIDMap = CacheBuilder.newBuilder().expireAfterAccess(10, TimeUnit.MINUTES).softValues().build(new CacheLoader<String, UUID>() {
@Override
public UUID load(String username) throws Exception {
Profile[] profiles = HTTP_PROFILE_REPOSITORY.findProfilesByNames(username);
if(profiles.length == 1) {
String uuidStr = profiles[0].getId();
if(uuidStr.indexOf('-') < 1)
uuidStr = uuidStr.substring(0, 8) + "-" + uuidStr.substring(8, 12) + "-" + uuidStr.substring(12, 16) + "-" + uuidStr.substring(16, 20) + "-" + uuidStr.substring(20);
return UUID.fromString(uuidStr);
}
return null;
}
});
public static UUID getUUID(String username) {
try {
return playerUUIDMap.get(username.toLowerCase());
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
|
/**
*
*/
package com.application.ui.activity;
import java.util.List;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.application.ui.calligraphy.CalligraphyContextWrapper;
import com.application.ui.view.BottomSheet;
import com.application.ui.view.MaterialRippleLayout;
import com.application.ui.view.SwipeBackActivityBase;
import com.application.ui.view.SwipeBackActivityHelper;
import com.application.ui.view.SwipeBackLayout;
import com.application.ui.view.SwipeBackUtils;
import com.application.utils.AndroidUtilities;
import com.application.utils.AppConstants;
import com.application.utils.FileLog;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.mobcast.R;
/**
* @author Vikalp Patel(VikalpPatelCE)
*
*/
public abstract class YouTubeFailureRecoveryActivity extends
YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener,
SwipeBackActivityBase {
private static final String TAG = YouTubeFailureRecoveryActivity.class
.getSimpleName();
private static final int RECOVERY_DIALOG_REQUEST = 1;
@Override
protected void attachBaseContext(Context newBase) {
try {
if (AndroidUtilities.isAppLanguageIsEnglish()) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
} else {
super.attachBaseContext(newBase);
}
} catch (Exception e) {
FileLog.e(TAG, e.toString());
}
}
@Override
public void onInitializationFailure(YouTubePlayer.Provider provider,
YouTubeInitializationResult errorReason) {
if (errorReason.isUserRecoverableError()) {
errorReason.getErrorDialog(this, RECOVERY_DIALOG_REQUEST).show();
} else {
String errorMessage = String.format(
getString(R.string.error_player), errorReason.toString());
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECOVERY_DIALOG_REQUEST) {
// Retry initialization if user performed a recovery action
getYouTubePlayerProvider().initialize(AppConstants.YOUTUBE.API_KEY,
this);
}
}
protected abstract YouTubePlayer.Provider getYouTubePlayerProvider();
private SwipeBackActivityHelper mHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mHelper = new SwipeBackActivityHelper(this);
mHelper.onActivityCreate();
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mHelper.onPostCreate();
}
@Override
public View findViewById(int id) {
View v = super.findViewById(id);
if (v == null && mHelper != null)
return mHelper.findViewById(id);
return v;
}
@Override
public SwipeBackLayout getSwipeBackLayout() {
return mHelper.getSwipeBackLayout();
}
@Override
public void setSwipeBackEnable(boolean enable) {
getSwipeBackLayout().setEnableGesture(enable);
}
@Override
public void scrollToFinishActivity() {
SwipeBackUtils.convertActivityToTranslucent(this);
getSwipeBackLayout().scrollToFinishActivity();
}
protected BottomSheet.Builder getShareActions(BottomSheet.Builder builder,
String text) {
PackageManager pm = this.getPackageManager();
final Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, text);
final List<ResolveInfo> list = pm.queryIntentActivities(shareIntent, 0);
for (int i = 0; i < list.size(); i++) {
builder.sheet(i, list.get(i).loadIcon(pm), list.get(i)
.loadLabel(pm));
}
builder.listener(new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ActivityInfo activity = list.get(which).activityInfo;
ComponentName name = new ComponentName(
activity.applicationInfo.packageName, activity.name);
Intent newIntent = (Intent) shareIntent.clone();
newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
newIntent.setComponent(name);
startActivity(newIntent);
}
});
return builder;
}
protected void setMaterialRippleWithGrayOnView(View mView) {
MaterialRippleLayout.on(mView).rippleColor(Color.parseColor("#aaaaaa"))
.rippleAlpha(0.2f).rippleHover(true).rippleOverlay(true)
.rippleBackground(Color.parseColor("#00000000")).create();
}
protected void setMaterialRippleOnView(View mView) {
MaterialRippleLayout.on(mView).rippleColor(Color.parseColor("#ffffff"))
.rippleAlpha(0.2f).rippleHover(true).rippleOverlay(true)
.rippleBackground(Color.parseColor("#00000000")).create();
}
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
AndroidUtilities.exitWindowAnimation(YouTubeFailureRecoveryActivity.this);
}
}
|
package com.jl.extract;
import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.XPath;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import com.jl.domain.Polarity;
import com.jl.polaritySql.polarityService;
public class judgeP {
public String[] getXinneng(String str){
String[] xinneng=new String[2];
try{
SAXReader reader=new SAXReader();
File file=new File("setConfig/sim.xml");
Document doc;
doc = reader.read(file);
Element list=(Element) doc.selectSingleNode("/words/performance[word='"+str+"']/word");
if(list!=null){
Element p=list.getParent();
String t=p.attributeValue("name");
String table=p.attributeValue("table");
xinneng[0]=t;
xinneng[1]=table;
}
}catch(Exception e){
e.printStackTrace();
}
return xinneng;
}
public void judgeS1(String brand,String type,String tag,String des,int number,double fo_quan){
try{
String[] tt=this.getXinneng(tag);
if(tt!=null){
String newtag=tt[0];//得到评价性能名
String table=tt[1];//得到极性表名
polarityService ps=new polarityService();
int count= ps.queryForTotalRows(table, des);
if(count!=0){
Polarity po=ps.queryForOneProduct(table, des);
double value=po.getPolarity()*fo_quan;
System.out.println("词极性度:"+value);
ps.Close();
if(value<-0.05)
{
SAXReader reader=new SAXReader();
File file=new File("setConfig/result.xml");
Document doc;
doc = reader.read(file);
Node node=doc.selectSingleNode("/tree/brand[@name='"+brand+"']");
if(node==null){
Element newStu=DocumentHelper.createElement("brand");
//如何给元素添加属性
newStu.addAttribute("name", brand);
Element newStu_type=DocumentHelper.createElement("type");
newStu_type.addAttribute("name",type);
Element newP=DocumentHelper.createElement("performance");
newP.addAttribute("name", newtag);
newP.addAttribute("weight", number+";");
newP.setText("1");
newStu_type.add(newP);
newStu.add(newStu_type);
doc.getRootElement().add(newStu);
OutputFormat output=OutputFormat.createPrettyPrint();
output.setEncoding("utf-8");//输出的编码utf-8
XMLWriter writer = new XMLWriter(
new FileOutputStream(file),output);
writer.write( doc );
writer.flush();
writer.close();
}else{
Node node_t=node.selectSingleNode("/tree/brand[@name='"+brand+"']/type[@name='"+type+"']");
if(node_t!=null){
Node node_xin=node_t.selectSingleNode("/tree/brand[@name='"+brand+"']/type[@name='"+type+"']/performance[@name='"+newtag+"']");
if(node_xin!=null){
String num=node_xin.getText();
String weight=((Element) node_xin).attributeValue("weight");
int t=Integer.parseInt(num);
t=t+1;
node_xin.setText(t+"");
weight=weight+number+";";
((Element)node_xin).setAttributeValue("weight", weight);
OutputFormat output=OutputFormat.createPrettyPrint();
output.setEncoding("utf-8");
XMLWriter writer=new XMLWriter(new FileOutputStream(file),output);
writer.write(doc);
writer.flush();
writer.close();
}else{
Element newCar_per=((Element)node_t).addElement("performance");
newCar_per.addAttribute("name", newtag);
newCar_per.addAttribute("weight",number+";");
newCar_per.setText("1");
OutputFormat output=OutputFormat.createPrettyPrint();
output.setEncoding("utf-8");//输出的编码utf-8
XMLWriter writer = new XMLWriter(
new FileOutputStream(file),output);
writer.write( doc );
writer.flush();
writer.close();
}
}else{
Element newCar_type=((Element)node).addElement("type");
newCar_type.addAttribute("name", type);
Element newXinneng=newCar_type.addElement("performance");
newXinneng.addAttribute("name", newtag);
newXinneng.addAttribute("weight", number+";");
newXinneng.setText("1");
OutputFormat output=OutputFormat.createPrettyPrint();
output.setEncoding("utf-8");//输出的编码utf-8
XMLWriter writer = new XMLWriter(
new FileOutputStream(file),output);
writer.write( doc );
writer.flush();
writer.close();
}
}
}
}
}
}catch(Exception e){
e.printStackTrace();
}
}
public void judgeS2(String brand,String tag,String des,int number,double fo_quan){
try{
String[] tt=this.getXinneng(tag);
if(tt!=null){
String newtag=tt[0];//得到评价性能名
String table=tt[1];//得到极性表名
polarityService ps=new polarityService();
int count=ps.queryForTotalRows(table, des);
if(count!=0){
Polarity po=ps.queryForOneProduct(table, des);
double value=po.getPolarity()*fo_quan;
System.out.println("词极性度:"+value);
ps.Close();
if(value<-0.05)
{
SAXReader reader=new SAXReader();
File file=new File("setConfig/result.xml");
Document doc;
doc = reader.read(file);
Node node=doc.selectSingleNode("/tree/brand[@name='"+brand+"']");
if(node==null){
Element newStu=DocumentHelper.createElement("brand");
//如何给元素添加属性
newStu.addAttribute("name", brand);
newStu.addAttribute("xmlns", "http://www.inktomi.com/"); //增加命名空间
Element newP=DocumentHelper.createElement("performance");
newP.addAttribute("name", newtag);
newP.addAttribute("weight", number+";");
newP.setText("1");
newStu.add(newP);
doc.getRootElement().add(newStu);
OutputFormat output=OutputFormat.createPrettyPrint();
output.setEncoding("utf-8");//输出的编码utf-8
XMLWriter writer = new XMLWriter(
new FileOutputStream(file),output);
writer.write( doc );
writer.flush();
writer.close();
}else{
Node node_xin=node.selectSingleNode("/tree/brand[@name='"+brand+"']/performance[@name='"+newtag+"']");
if(node_xin!=null){
String num=node_xin.getText();
String weight=((Element) node_xin).attributeValue("weight");
int t=Integer.parseInt(num);
t=t+1;
node_xin.setText(t+"");
weight=weight+number+";";
((Element)node_xin).setAttributeValue("weight", weight);
OutputFormat output=OutputFormat.createPrettyPrint();
output.setEncoding("utf-8");
XMLWriter writer=new XMLWriter(new FileOutputStream(file),output);
writer.write(doc);
writer.flush();
writer.close();
}else{
Element newCar_per=((Element)node).addElement("performance");
newCar_per.addAttribute("name", newtag);
newCar_per.addAttribute("weight",number+";");
newCar_per.setText("1");
OutputFormat output=OutputFormat.createPrettyPrint();
output.setEncoding("utf-8");//输出的编码utf-8
XMLWriter writer = new XMLWriter(
new FileOutputStream(file),output);
writer.write( doc );
writer.flush();
writer.close();
}
}
}
}
}
}catch(Exception e){
e.printStackTrace();
}
}
public static List<Element> searchNodes(String xpath,Node node){
xpath=xpath.replace("/", "/boss:");
HashMap xmlMap = new HashMap();
xmlMap.put("boss","http://www.inktomi.com/");
XPath x = node.createXPath(xpath);
x.setNamespaceURIs(xmlMap);
return x.selectNodes(node);
}
public static Node searchSingleNode(String xpath,Node node){
xpath=xpath.replace("/", "/boss:");
HashMap xmlMap = new HashMap();
xmlMap.put("boss","http://www.inktomi.com/");
XPath x = node.createXPath(xpath);
x.setNamespaceURIs(xmlMap);
return x.selectSingleNode(node);
}
}
|
package ch.so.agi.cadastre.webservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CadastreWebServiceApplication {
public static void main(String[] args) {
SpringApplication.run(CadastreWebServiceApplication.class, args);
}
}
|
package com.example.hdxy.baseproject.Http.subscriber;
import android.util.Log;
import com.example.hdxy.baseproject.Base.BaseImpl;
import com.example.hdxy.baseproject.Http.exception.ApiException;
import com.example.hdxy.baseproject.Util.StringUtil;
import com.google.gson.stream.MalformedJsonException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.exceptions.CompositeException;
public abstract class BaseObserver<T> implements Observer<T> {
private BaseImpl mBaseImpl;
protected abstract void onBaseError(int code, String msg);
protected abstract void onBaseNext(T data);
public BaseObserver(BaseImpl baseImpl) {
mBaseImpl = baseImpl;
}
@Override
public void onSubscribe(Disposable d) {
if (mBaseImpl !=null){
if (d!=null){
mBaseImpl.addDisposable(d);
}
}
}
@Override
public void onNext(T t) {
if (t!=null){
onBaseNext(t);
}
}
@Override
public void onError(Throwable e) {
if (e instanceof CompositeException) {
CompositeException compositeE=(CompositeException)e;
for (Throwable throwable : compositeE.getExceptions()) {
if (throwable instanceof SocketTimeoutException) {
onBaseError(ApiException.Code_TimeOut,ApiException.SOCKET_TIMEOUT_EXCEPTION);
} else if (throwable instanceof ConnectException) {
onBaseError(ApiException.Code_UnConnected,ApiException.CONNECT_EXCEPTION);
} else if (throwable instanceof UnknownHostException) {
onBaseError(ApiException.Code_UnConnected,ApiException.CONNECT_EXCEPTION);
} else if (throwable instanceof MalformedJsonException) {
onBaseError(ApiException.Code_MalformedJson,ApiException.MALFORMED_JSON_EXCEPTION);
}
}
}else {
String message = e.getMessage();
onBaseError(ApiException.Code_Default, StringUtil.judgeString(message));
}
Log.d("AAA", "onError: " + e.getMessage());
}
@Override
public void onComplete() {
}
}
|
public interface Heuristic {
double calculate(Pair fromPos, Pair endPos);
}
|
package com.marcos.inicio;
import com.marcos.biblioteca.negocio.beans.AutorBean;
import com.marcos.biblioteca.negocio.beans.EjemplarBean;
import com.marcos.biblioteca.negocio.beans.LibroBean;
import com.marcos.biblioteca.negocio.beans.PrestamoBean;
import com.marcos.biblioteca.negocio.beans.UsuarioBean;
import com.marcos.bibloteca.negocio.CreateAutor;
import com.marcos.bibloteca.negocio.CreateLibro;
public class Start {
public static void main(String[] args) {
EjemplarBean eje1 = new EjemplarBean();
eje1.setLocalizacion("oviedo");
EjemplarBean eje2 = new EjemplarBean();
eje2.setLocalizacion("Gijon");
UsuarioBean jose = new UsuarioBean();
jose.setNombre("jose");
jose.setDireccion("oviedo");
jose.setTelefono("650251425");
UsuarioBean carlos = new UsuarioBean();
carlos.setNombre("carlos");
carlos.setDireccion("gijon");
carlos.setTelefono("650275635");
PrestamoBean prestamo1=new PrestamoBean();
prestamo1.setFechaDevolucion("21/1/2000");
prestamo1.setFechaPrestamo("17/1/2000");
PrestamoBean prestamo2=new PrestamoBean();
prestamo2.setFechaDevolucion("11/1/2000");
prestamo2.setFechaPrestamo("07/1/2000");
AutorBean autor1 = new AutorBean();
autor1.setNombre("Ken Follet");
AutorBean autor2 = new AutorBean();
autor2.setNombre("JK Rowling");
LibroBean libro1 = new LibroBean();
libro1.setEditorial("SM");
libro1.setIsbn("34567M");
libro1.setPaginas(182);
libro1.setTitulo("Harry Potter I");
LibroBean libro2 = new LibroBean();
libro2.setEditorial("SM");
libro2.setIsbn("3466567M");
libro2.setPaginas(242);
libro2.setTitulo("Harry Potter II");
LibroBean libro3 = new LibroBean();
libro3.setEditorial("Anaya");
libro3.setIsbn("346sfes6567M");
libro3.setPaginas(842);
libro3.setTitulo("Los pilares de la tierra");
/*aņadir*/
autor2.addLibros(libro1);
autor2.addLibros(libro2);
autor1.addLibros(libro3);
/*persistir*/
CreateAutor createAutor = new CreateAutor();
createAutor.create(autor1);
createAutor.create(autor2);
CreateLibro createLibro = new CreateLibro();
createLibro.create(libro1);
createLibro.create(libro2);
createLibro.create(libro3);
}
}
|
package test_private;
import io.IO;
import io.ImageReader;
import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;
import java.io.IOException;
import logic.huffman.HuffmanCode;
import logic.huffman.HuffmanTree;
import org.junit.Before;
import org.junit.Test;
import datamodel.huffman.tree.Tree;
public class HuffmanCodeTest {
private Tree tree;
private HuffmanCode code;
@Before
public void init() throws FileNotFoundException, IOException {
tree = HuffmanTree.getHuffmanTree("test.png");
code = new HuffmanCode(tree);
}
private void createBinaryString() throws FileNotFoundException,
IOException {
ImageReader reader = new ImageReader("test2.png");
String binaryStringFileName = "target/binaryStringRGB";
IO.writeImageBinaryString(binaryStringFileName, reader);
String binaryStringFileName2 = "target/binaryStringHuffman";
tree = HuffmanTree.getHuffmanTree("test2.png");
code = new HuffmanCode(tree);
IO.writeBinaryString(binaryStringFileName2, code.encryptImage(reader));
}
private void compressTolevel(int level) throws FileNotFoundException,
IOException {
tree = HuffmanTree.getHuffmanTree("test2.png");
code = new HuffmanCode(tree);
String compressedFileName = "target/compLevel" + level;
String compressedFileName2 = "target/compLevel" + level + "_2";
ImageReader reader = new ImageReader("test2.png");
String encryptedString = code.encryptImage(reader);
code.compress(level);
BufferedImage compressedFile = code.decryptImage(encryptedString,
reader.getWidth(), reader.getHeight());
IO.saveImage(compressedFileName, compressedFile);
reader = new ImageReader(compressedFileName + ".png");
encryptedString = code.encryptImage(reader);
BufferedImage compressedFile2 = code.decryptImage(encryptedString,
reader.getWidth(), reader.getHeight());
IO.saveImage(compressedFileName2, compressedFile2);
}
@Test
public void compressionLevel1Test() throws FileNotFoundException,
IOException {
compressTolevel(1);
createBinaryString();
}
}
|
package antworld.client;
/**
* Created by Dominic on 12/9/2016.
*/
import java.awt.*;
import antworld.common.Util;
import antworld.common.AntAction;
import antworld.common.AntAction.AntActionType;
import antworld.common.AntData;
import antworld.common.CommData;
import antworld.common.Direction;
import antworld.common.FoodData;
import antworld.common.FoodType;
import java.awt.Point;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
/**
* Ant wrapper class to wrap the AntData given by the server and perform operations and commands
*/
public class AntBrain
{
/**
* Nest Position
*/
int centerX, centerY;
/**
* data linked to this ant
*/
AntData data;
/**
* current commData
*/
CommData commData;
/**
* Food to gather
*/
FoodData closeFood;
/**
* map representation
*/
WorldMap map;
/**
* Current command
*/
Command command = Command.EMPTY;
/**
* Known closest water
*/
Tiles waterPosition;
/**
* Explore targets to choose from
*/
LinkedList<Tiles> exploreDeque;
/**
* Current Target (where the ant is going)
*/
Tiles target = null;
/**
* Current position
*/
Tiles tile;
/**
* Enemy ant is next to
*/
AntData enemy;
// Debug flags
public static final boolean DEBUG_HOME = false;
public static final boolean DEBUG_FOOD = false;
public static final boolean DEBUG_MOVE = false;
public static final boolean DEBUG_BLOCKED = false;
public boolean isAntLeader = false;
public boolean inGroup = false;
public Tiles antLeader;
// Moves to avoid
public final HashSet<Tiles> blockedMoves;
public final HashSet<Tiles> plannedMoves;
/**
* Distance to count near food
*/
public final int NEAR_DISTANCE;
/**
* Commands to control the ant with, some unimplemented
*/
enum Command
{
EXPLORE,
WATER,
DEFEND,
GATHER,
ATTACK,
HOME,
ESCAPE,
EMPTY,
HEAL
}
/**
* Create a new Ant
*
* @param ant ant data for this ant
* @param commData current comm data
* @param map map representation
* @param exploreDeque explore tiles
* @param blockedMoves current blocked moves set
* @param plannedMoves current planned moves set
* @param centerX nest x
* @param centerY nest y
* @param waterPosition best known water position
*/
public AntBrain(AntData ant, CommData commData, WorldMap map, LinkedList<Tiles> exploreDeque,
HashSet<Tiles> blockedMoves, HashSet<Tiles> plannedMoves, int centerX, int centerY,
Tiles waterPosition)
{
this.data = ant;
this.commData = commData;
this.map = map;
this.exploreDeque = exploreDeque;
this.blockedMoves = blockedMoves;
this.plannedMoves = plannedMoves;
tile = map.getTile(data.gridX, data.gridY);
this.centerX = centerX;
this.centerY = centerY;
this.waterPosition = waterPosition;
NEAR_DISTANCE = (int) (ant.antType.getVisionRadius() * 1.5);
}
/**
* This is the main logic of the ant
*
* Uses a switch based on command setting (which is an enum) for what action the ant should take
* Works in conjunction with the client to make a strategy
*/
void continueCommand()
{
if (DEBUG_BLOCKED)
{
System.out.println("Blocked size = " + blockedMoves.size() + " plannedSize = " + plannedMoves.size());
}
//System.out.println("Command = " + command + " ant = " + data.id);
switch (command)
{
case ATTACK:
if (enemy == null && !nextToEnemy())
{
command = Command.EXPLORE;
continueCommand();
}
else
{
attack(moveToDirection(enemy.gridX - tile.xPos, enemy.gridY - tile.yPos));
}
break;
case EXPLORE:
if (target == null || (target.xPos == data.gridX && target.yPos == data.gridY))
{
target = exploreDeque.pop();
exploreDeque.addLast(target);
}
moveTowardsTarget();
break;
case GATHER:
if (commData.foodSet == null || (!commData.foodSet.contains(closeFood)))
{
target = null;
command = Command.EXPLORE;
continueCommand();
return;
}
if (target == null)
{
target = map.getTile(closeFood.gridX, closeFood.gridY);
}
if (nextTo(target.xPos, target.yPos))
{
pickup(moveToDirection(target.xPos - data.gridX, target.yPos - data.gridY));
target = null;
command = Command.HOME;
return;
}
moveTowardsTarget();
break;
case HOME:
if (tile.nest && tile.distance(centerX, centerY) < 20)
{
if (!underground())
{
enterNest();
return;
}
if (data.carryUnits > 0)
{
if (DEBUG_FOOD)
{
System.out.println("DROPPING FOOD");
}
drop();
target = null;
command = Command.HEAL;
return;
}
command = Command.HEAL;
target = null;
continueCommand();
break;
}
target = map.getTile(centerX, centerY);
moveTowardsTarget();
break;
case HEAL:
if (data.health < data.antType.getMaxHealth())
{
if (commData.foodStockPile[FoodType.WATER.ordinal()] > 0)
{
heal();
}
else
{
stasis();
}
}
else
{
command = Command.EMPTY;
target = null;
}
break;
case WATER:
if (target == null)
{
target = waterPosition;
}
if (nextToWater())
{
pickup(moveToDirection(target.xPos - data.gridX, target.yPos - data.gridY));
target = null;
command = Command.HOME;
return;
}
moveTowardsTarget();
break;
case EMPTY:
default:
command = Command.EXPLORE;
continueCommand();
break;
}
}
/**
* Current tile
*
* @return position tile
*/
Tiles getTile()
{
return tile;
}
/**
* Calculate the tile that is direction away
*
* @param dir direction
* @return tile at direction
*/
public Tiles getTileOffset(Direction dir)
{
return map.getTile(tile.xPos + dir.deltaX(), tile.yPos + dir.deltaY());
}
/**
* ant data
*
* @return data
*/
public AntData getData()
{
return data;
}
/**
* If ant is in stasis
*
* @return true if can move false otherwise
*/
public boolean canMove()
{
return data.ticksUntilNextAction == 0;
}
/**
* Set ant action to stasis
*/
public void stasis()
{
data.myAction = new AntAction(AntActionType.STASIS);
}
/**
* Unsupported, meant to flee from a direction
*
* @param dir direction to go away from
*/
public void flee(Direction dir)
{
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Set action to attack
*
* @param dir direction to attack
*/
public void attack(Direction dir)
{
data.myAction = new AntAction(AntActionType.ATTACK, dir);
}
/**
* Pickup maximum amount
*
* @param dir direction to pickup from
*/
public void pickup(Direction dir)
{
data.myAction = new AntAction(AntActionType.PICKUP, dir, data.antType.getCarryCapacity());
}
/**
* Pickup
*
* @param dir direction to pickup from
* @param quantity amount to pickup
*/
public void pickup(Direction dir, int quantity)
{
data.myAction = new AntAction(AntActionType.PICKUP, dir, quantity);
}
/**
* Set action to drop Drop logic, tries to find the best direction to drop in
*/
public void drop()
{
Direction bestDir = Direction.getRandomDir();
for (Direction dir : Direction.values())
{
Tiles tile = getTileOffset(dir);
if (blockedMoves.contains(tile) || plannedMoves.contains(dir))
{
continue;
}
else
{
bestDir = dir;
break;
}
}
data.myAction = new AntAction(AntActionType.DROP, bestDir, data.carryUnits);
}
/**
* Set action to heal for underground ants
*/
public void heal()
{
data.myAction = new AntAction(AntActionType.HEAL);
}
/**
* Move in direction
*
* @param dir which direction to move
*/
public void move(Direction dir)
{
plannedMoves.add(getTileOffset(dir));
data.myAction = new AntAction(AntActionType.MOVE, dir);
}
/**
* Normalize number to magnitude of 1 (or 0 if x is 0)
*
* @param x number to normalize
* @return normalized number
*/
public int normalize(int x)
{
if (x != 0)
{
return x / Math.abs(x);
}
return 0;
}
/**
* Basic logic to move towards a target, does not account for path
*
* Tries to find greedy best move first and then moves near that if that is blocked
*/
public void moveTowardsTarget()
{
if (target == null)
{
if (DEBUG_MOVE)
{
System.out.println("Null target in move towards target.");
}
stasis();
return;
}
// find best non blocked move
int xTo = target.xPos - tile.xPos;
if (xTo != 0)
{
xTo = xTo / Math.abs(xTo);
}
int yTo = target.yPos - tile.yPos;
if (yTo != 0)
{
yTo = yTo / Math.abs(yTo);
}
Direction closest = moveToDirection(xTo, yTo);
Direction bestDir = closest;
Tiles best = getTileOffset(closest);
if (blockedMoves.contains(best) || plannedMoves.contains(best) || best.isBlocked())
{
bestDir = Direction.getLeftDir(bestDir);
best = getTileOffset(bestDir);
}
if (blockedMoves.contains(best) || plannedMoves.contains(best) || best.isBlocked())
{
bestDir = Direction.getRightDir(closest);
best = getTileOffset(bestDir);
}
if (blockedMoves.contains(best) || plannedMoves.contains(best) || best.isBlocked())
{
bestDir = Direction.getLeftDir(Direction.getLeftDir(closest));
best = getTileOffset(bestDir);
}
if (blockedMoves.contains(best) || plannedMoves.contains(best) || best.isBlocked())
{
bestDir = Direction.getRightDir(Direction.getRightDir(closest));
best = getTileOffset(bestDir);
}
if (best.isBlocked())
{
if (DEBUG_BLOCKED)
{
System.out.println("Best is blocked");
}
moveRandom();
}
else
{
move(bestDir);
}
if (DEBUG_HOME)
{
if (command == Command.HOME)
{
System.out.println("Ant(" + data.id + ") Command home move = " + data.myAction.direction + " from " + "(" + tile.xPos + "," + tile.yPos + ")");
}
}
}
/**
* Expects delta of magnitude 1, will find correct direction Enum value to return based on deltas
*
* @param deltaX x delta of move
* @param deltaY y delta of move
* @return direction of to move corresponding delta
*/
public Direction moveToDirection(int deltaX, int deltaY)
{
for (Direction dir : Direction.values())
{
if (dir.deltaX() == deltaX && dir.deltaY() == deltaY)
{
return dir;
}
}
System.out.println("Bad move in moveToDirection " + data.id + " x = " + deltaX + " y = " + deltaY);
return Direction.getRandomDir();
}
/**
* Check if ant is next to a position
*
* @param x x position
* @param y y position
* @return true if next to otherwise false
*/
public boolean nextTo(int x, int y)
{
return Math.abs(data.gridX - x) == 1 && Math.abs(data.gridY - y) == 1;
}
/**
* Check to see if ant is next to enemy
*
* @return true if enemy is one square away
*/
boolean nextToEnemy()
{
this.enemy = null;
if (commData.enemyAntSet == null || commData.enemyAntSet.isEmpty())
{
return false;
}
for (AntData enemy : commData.enemyAntSet)
{
if (nextTo(enemy.gridX, enemy.gridY))
{
this.enemy = enemy;
return true;
}
}
return false;
}
/**
* If ant is near food set closeFood and return true
*
* @return false if not near food in foodset true if near food
*/
public boolean nearFood()
{
if (closeFood != null)
{
if (commData.foodSet.contains(closeFood))
{
return true;
}
}
for (FoodData food : commData.foodSet)
{
if (nearPoint(food.gridX, food.gridY))
{
closeFood = food;
return true;
}
}
closeFood = null;
return false;
}
public boolean nextToWater()
{
for (Tiles neighbor : map.getNeighbors(tile.xPos, tile.yPos))
{
if (neighbor.water)
{
waterPosition = neighbor;
target = neighbor;
return true;
}
}
return false;
}
/**
* Determines if ant is near point using the NEAR_DISTANCE constant
*
* @param x position
* @param y position
* @return true if Manhattan distance is < NEAR_DISTANCE false otherwise
*/
public boolean nearPoint(int x, int y)
{
return Util.manhattanDistance(data.gridX, data.gridY, x, y) < NEAR_DISTANCE;
}
/**
* Set action to move to a random direction
*/
public void moveRandom()
{
data.myAction = new AntAction(AntActionType.MOVE, Direction.getRandomDir());
}
/**
* Set action to enter the nest
*/
public void enterNest()
{
data.myAction = new AntAction(AntActionType.ENTER_NEST);
}
/**
* Set action to exit the nest
*
* @param p point to exit at
*/
public void exitNest(Point p)
{
data.myAction = new AntAction(AntActionType.EXIT_NEST, p.x, p.y);
}
/**
* Set action to exit nest
*
* @param x x position to exit at
* @param y y position to exit at
*/
public void exitNest(int x, int y)
{
data.myAction = new AntAction(AntActionType.EXIT_NEST, x, y);
}
/**
* Boolean check to see if ant is at home nest
*
* @return true if at home nest false otherwise
*/
public boolean atNest()
{
if (Util.manhattanDistance(data.gridX, data.gridY, centerX, centerX) < 20
&& map.getTile(data.gridX, data.gridY).nest)
{
return true;
}
return false;
}
/**
* If ant is 1 move away from food (so it can pickup food)
*
* @return true if next to any food, false otherwise
*/
private boolean nextToFood()
{
for (FoodData food : commData.foodSet)
{
if (nextTo(food.gridX, food.gridY))
{
return true;
}
}
return false;
}
/**
* Set the ant data
*
* @param ant data to set to
*/
public void setData(AntData ant)
{
data = ant;
}
/**
* Check if ant is underground
*
* @return true if underground false otherwise
*/
public boolean underground()
{
return data.underground;
}
/**
* Update needed ant data on communication update
*
* @param ant new ant data
* @param commData new comm data
*/
public void updateData(AntData ant, CommData commData)
{
data = ant;
tile = map.getTile(data.gridX, data.gridY);
this.commData = commData;
}
/**
* Compare ant to another ant by id's
*
* @param ant other ant
* @return true if other ant has same id
*/
public boolean equals(AntData ant)
{
return data.id == ant.id;
}
/**
* Hashcode for Hash structures, uses ant id
*
* @return int for hashcode which is just the ant id
*/
public int hashCode()
{
return data.id;
}
/**
* Compare ant to another object
*
* @param obj object to compare to
* @return true if other object is an ant and has the same id
*/
public boolean equals(Object obj)
{
if (obj == null)
{
return false;
}
if (getClass() != obj.getClass())
{
return false;
}
final AntBrain other = (AntBrain) obj;
if (this.data.id != other.data.id)
{
return false;
}
return true;
}
/**
* Check if health is low
*
* @return true if health is less than or equal to half false otherwise
*/
public boolean lowHealth()
{
return data.health <= data.antType.getMaxHealth() / 2;
}
/**
* Set the current ant command
*
* @param command command to be set to
*/
public void setCommand(Command command)
{
this.command = command;
}
/**
* Set the current ant target
*
* @param target new target for ant
*/
public void setTarget(Tiles target)
{
this.target = target;
}
/**
* Set target based on coordinates
*
* @param x x coord
* @param y y coord
*/
public void setTarget(int x, int y)
{
target = map.getTile(x, y);
}
/**
* Use AStar to find a path, very slow
*
* @param goal path to this target from current position
* @return list of maptiles representing the path
*/
public java.util.List<Tiles> findPath(Tiles goal)
{
return map.generatePath(map.getTile(data.gridX, data.gridY), goal);
}
}
|
import java.util.Scanner;
public class Determinant{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String[] eh = sc.nextLine().split(" ");
int[] ar = new int[eh.length];
for(int i = 0; i < eh.length; i++) {
ar[i] = Integer.parseInt(eh[i]);
}
int[][] z = new int[ar.length][ar.length];
z[0] = ar;
for(int i = 1; i < z.length; i++){
String[] e = sc.nextLine().split(" ");
for(int j = 0; j < eh.length; j++) {
z[i][j] = Integer.parseInt(e[j]);
}
}
sc.close();
System.out.println(determine(z));
}
public static int determine(int[][] x){
int[] g = new int[]{1, -1};
if(x.length == 1){
return x[0][0];
}
int z = 0;
for(int i = 0; i < x.length; i++){
z = z + determine(create(x, i)) * x[0][i] * g[i % 2];
}
return z;
}
public static int[][] create(int[][] x, int i){
int[][] a = new int[x.length - 1][x.length - 1];
for(int j = 1; j < x.length; j++){
int f = 0;
for(int k = 0; k < x.length; k++){
if(k == i){
f = -1;
continue;
}
a[j - 1][k + f] = x[j][k];
}
}
return a;
}
}
|
package com.test.base;
import java.util.Arrays;
import java.util.List;
import com.test.SolutionA;
import junit.framework.TestCase;
public class Example extends TestCase
{
private Solution solution;
@Override
protected void setUp()
throws Exception
{
super.setUp();
}
public void testSolutionA()
{
solution = new SolutionA();
assertSolution();
}
private void assertSolution()
{
int[] arrayA = {1, 2, 3};
List<List<Integer>> resultA = solution.permute(arrayA);
log(resultA);
}
private void log(List<List<Integer>> result)
{
for (int i = 0; i < result.size(); i++)
{
System.out.println(Arrays.toString(result.get(i).toArray()));
}
}
@Override
protected void tearDown()
throws Exception
{
solution = null;
super.tearDown();
}
}
|
package com.springlearn.spring.springcore.propertyplaceholder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("com/springlearn/spring/springcore/propertyplaceholder/config.xml");
myDAO dao=(myDAO)context.getBean("myDAO");
System.out.println(dao);
}
}
|
package com.karya.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="stkrepageing001mb")
public class StkRepAgeing001MB implements Serializable{
private static final long serialVersionUID = -723583058586873479L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "stageId")
private int stageId;
@Column(name="itemCode")
private String itemCode;
@Column(name="description")
private String description;
@Column(name="itemGroup")
private String itemGroup;
@Column(name="brand")
private String brand;
@Column(name="averageAge")
private String averageAge;
@Column(name="earliest")
private String earliest;
@Column(name="latest")
private String latest;
@Column(name="UOM")
private String UOM;
public int getStageId() {
return stageId;
}
public void setStageId(int stageId) {
this.stageId = stageId;
}
public String getItemCode() {
return itemCode;
}
public void setItemCode(String itemCode) {
this.itemCode = itemCode;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getItemGroup() {
return itemGroup;
}
public void setItemGroup(String itemGroup) {
this.itemGroup = itemGroup;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getAverageAge() {
return averageAge;
}
public void setAverageAge(String averageAge) {
this.averageAge = averageAge;
}
public String getEarliest() {
return earliest;
}
public void setEarliest(String earliest) {
this.earliest = earliest;
}
public String getLatest() {
return latest;
}
public void setLatest(String latest) {
this.latest = latest;
}
public String getUOM() {
return UOM;
}
public void setUOM(String uOM) {
UOM = uOM;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
|
package ru.avokin.uidiff.common.view.actions;
import java.util.List;
/**
* User: Andrey Vokin
* Date: 14.09.2010
*/
public interface ActionManager {
public void registerAction(BaseAction action);
public BaseAction getAction(String actionName);
public List<BaseAction> getAllActions();
}
|
package com.project.daicuongbachkhoa.teacher.algebrateacher;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.project.daicuongbachkhoa.MainActivity;
import com.project.daicuongbachkhoa.R;
import com.project.daicuongbachkhoa.teacher.TeacherHelp;
import com.project.daicuongbachkhoa.teacher.lawteacher.OptionLawTeacher;
public class OptionAlgebraTeacher extends AppCompatActivity {
private TextView txtAlgeblaTeacherLogout, txtAlgebraTeacherHelp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_option_algebra_teacher);
txtAlgeblaTeacherLogout = findViewById(R.id.txtAlgebraTeacherLogout);
txtAlgebraTeacherHelp = findViewById(R.id.txtAlgebraTeacherHelp);
txtAlgeblaTeacherLogout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
algebraTeacherLogout();
}
});
txtAlgebraTeacherHelp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
txtAlgebraTeacherHelp();
}
});
}
private void txtAlgebraTeacherHelp() {
startActivity(new Intent(OptionAlgebraTeacher.this, TeacherHelp.class));
}
private void algebraTeacherLogout() {
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(OptionAlgebraTeacher.this, MainActivity.class));
finish();
}
}
|
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
Socket client;
DataOutputStream out;
DataInputStream in;
ServerSocket server=null;
try {
server = new ServerSocket(1313);
}
catch(IOException ex)
{
ex.getMessage();
}
try{
System.out.print("Connection accepted.");
while(true) {
client = server.accept();
out = new DataOutputStream(client.getOutputStream());
in = new DataInputStream(client.getInputStream());
int N = in.readInt();
int M = in.readInt();
System.out.println();
Matrix A = new Matrix(N, M);
// Запись матрицы A
for (int i = 0; i < A.getN(); i++) {
for (int j = 0; j < A.getM(); j++) {
A.changeElement(i, j, in.readDouble());
System.out.print(A.getElement(i,j)+" ");
}
System.out.println();
}
N = in.readInt();
M = in.readInt();
Matrix B = new Matrix(N, M);
// Запись матрицы B
for (int i = 0; i < B.getN(); i++) {
for (int j = 0; j < B.getM(); j++) {
B.changeElement(i, j, in.readDouble());
}
}
if ((A.getM()) != (B.getN())) {
out.writeBoolean(true);
} else {
out.writeBoolean(false);
Matrix rezult = Matrix.rezult(A, B);
// Отправляем результат
out.writeInt(rezult.getN());
out.writeInt(rezult.getM());
for (int i = 0; i < rezult.getN(); i++) {
for (int j = 0; j < rezult.getM(); j++) {
out.writeDouble(rezult.getElement(i, j));
}
}
}
in.close();
out.close();
client.close();
}
}
catch(IOException ex)
{
}
catch(OutOfMemoryError ex){
}
}
}
|
package algorithms.strings.tries.practice;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.google.common.collect.Sets;
import org.apache.commons.lang3.StringUtils;
import org.junit.Assert;
import org.junit.Test;
/**
* Created by Chen Li on 2018/6/17.
*/
public class TernaryTrieTest {
@Test
public void put() {
TernaryTrie<Integer> trie = new TernaryTrie<>();
String key = "abcd";
Integer value = 100;
trie.put(key, value);
Integer v = trie.get(key);
Assert.assertEquals("", value, v);
}
@Test
public void deleteTest() {
TernaryTrie<Integer> trie = new TernaryTrie<>();
List<String> keys = Arrays.asList("sea", "abcd", "tea", "seaa", "seab", "seac", "seabde");
for (String key : keys) {
trie.put(key, 1);
}
Assert.assertEquals("", keys.size(), trie.size());
for (String key : keys) {
Assert.assertEquals("", 1, trie.get(key).intValue());
}
int count = keys.size();
for (String key : keys) {
trie.delete(key);
count--;
Assert.assertEquals("", count, trie.size());
}
Assert.assertTrue(trie.isEmpty());
}
@Test
public void withPrefixTest() {
TernaryTrie<Integer> trie = new TernaryTrie<>();
Set<String> expectedKeysPrefixA = Sets.newHashSet("a", "ab", "abc", "abcd", "abef", "abefg", "abfg");
Collection<String> keys = null;
for (String key : expectedKeysPrefixA) {
trie.put(key, 1);
}
keys = trie.keysWithPrefix("a");
System.out.println(StringUtils.join(keys, ", "));
Assert.assertEquals("", expectedKeysPrefixA, new HashSet<>(keys));
Collection<String> keys2 = trie.keysWithPrefix("ab");
System.out.println(StringUtils.join(keys2, ", "));
trie.clear();
trie.put("a", 1);
keys = trie.keysWithPrefix("a");
Assert.assertEquals("", 1, keys.size());
}
@Test
public void longestPrefixOf() {
TernaryTrie<Integer> trie = new TernaryTrie<>();
trie.put("a", 1);
trie.put("ab", 1);
trie.put("abc", 1);
trie.put("abcd", 1);
trie.put("abef", 1);
trie.put("abefg", 1);
trie.put("abfg", 1);
System.out.println(trie.longestPrefixOf("abefgh"));
System.out.println(trie.longestPrefixOf("cd"));
}
}
|
package vo.WebPromotionVO;
import java.util.Vector;
/**
* Created by Qin Liu on 2016/12/8.
*/
/**
* circle 0商圈
* discount 1折扣
* @author Qin Liu
*/
public class CircleVO extends Vector<String> {
public CircleVO(String circle, double discount) {
this.add(circle);
this.add(String.valueOf(discount));
}
public String getCircle() {
return this.get(0);
}
public double getDiscount() {
return Double.parseDouble(this.get(1));
}
}
|
/**
* Copyright (C), 1995-2018, XXX有限公司
* FileName: MyException
* Author: wens.
* Date: 2018/6/4 下午7:16
* Description: 我的通用异常类
* History:
* <author> <time> <version> <desc>
* 作者姓名 修改时间 版本号 描述
*/
package com.phantom.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.View;
import com.phantom.dto.ErrorInfo;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.net.ssl.HttpsURLConnection;
import javax.servlet.http.HttpServletRequest;
/**
* 〈一句话功能简述〉<br>
* 〈我的通用异常处理类〉
*
* @author wens.
* @create 2018/6/4
* @since 1.0.0
*/
@ControllerAdvice
public class GlobalExceptionHandler {
/**默认错误视图*/
public static final String DEFAULT_ERROR_VIEW = "error";
@ExceptionHandler( Exception.class)
public ModelAndView defaultErrorHandler(HttpServletRequest httpServletRequest,Exception e) throws Exception{
ModelAndView mav = new ModelAndView();
mav.addObject("exception",e);
mav.addObject("url",httpServletRequest.getRequestURL());
mav.addObject("auditor","BUGBUGSHERE_爸爸在这儿");
mav.setViewName(DEFAULT_ERROR_VIEW);
return mav;
}
@ExceptionHandler(MyException.class)
@ResponseBody
public ErrorInfo<String> jsonErrorHandle(HttpServletRequest httpServletRequest, MyException e) throws Exception{
ErrorInfo<String> r = new ErrorInfo<>();
r.setCode(ErrorInfo.ERROR);
r.setData(String.valueOf(Math.PI));
r.setMessage("发生错误啦,赶紧检查检查");
r.setUrl("www.bilibili.com");
return r;
}
}
|
package service;
import java.util.HashMap;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import model.Emp;
import model.MemberDataBean;
import mybatis.MybatisConnector;
@Service //���� Ŭ������ ���������� �����ϴ� service bean���� ���
public class MemberService {
private final String namespace = "mybatis.Member";
@Autowired
public MybatisConnector mybatisConnentor;
public List getAllNodeDiv2() throws Exception {
SqlSession sqlSession = mybatisConnentor.sqlSession();
try {
return sqlSession.selectList(namespace + ".getAllNodeDiv2");
} finally {
sqlSession.close();
}
}
public void insertMember(MemberDataBean member) throws Exception {
SqlSession sqlSession = mybatisConnentor.sqlSession();
try {
System.out.println(member);
sqlSession.insert(namespace + ".insertMember", member);
} finally {
sqlSession.commit();
sqlSession.close();
}
}
public int getMaxNum() {
SqlSession sqlSession = mybatisConnentor.sqlSession();
try {
return sqlSession.selectOne(namespace + ".getMaxNum");
} finally {
sqlSession.close();
}
}
public MemberDataBean user_login(String m_id, String m_pw) throws Exception {
SqlSession sqlSession = mybatisConnentor.sqlSession();
HashMap map = new HashMap();
map.put("m_id", m_id);
map.put("m_pw", m_pw);
System.out.println("---------service_login");
try {
return sqlSession.selectOne(namespace + ".user_login", map);
} finally {
sqlSession.close();
}
}
public int user_meminformation(MemberDataBean member) throws Exception {
SqlSession sqlSession = mybatisConnentor.sqlSession();
System.out.println("---------service_user_meminformation");
try {
return sqlSession.update(namespace + ".user_meminformation", member);
} finally {
sqlSession.commit();
sqlSession.close();
}
}
public int isMember(String id) {
SqlSession sqlSession = mybatisConnentor.sqlSession();
try {
return sqlSession.selectOne(namespace + ".isMem", id);
} finally {
sqlSession.close();
}
}
public Emp empLogin(String id, String pw) {
SqlSession sqlSession = mybatisConnentor.sqlSession();
HashMap map = new HashMap();
map.put("id", id);
map.put("pw", pw);
try {
System.out.println("service: "+id+","+pw);
return sqlSession.selectOne(namespace + ".empLogin", map);
} finally {
sqlSession.close();
}
}
}
|
package global.coda.hospitalmanagement.exceptionMapper;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import global.coda.hospitalmanagement.exception.BusinessException;
// TODO: Auto-generated Javadoc
/**
* The Class BusinessExceptionMapper.
*/
@Provider
public class BusinessExceptionMapper implements ExceptionMapper<BusinessException> {
/**
* To response.
*
* @param exception the exception
* @return the response
*/
@Override
@Produces(MediaType.APPLICATION_JSON)
public Response toResponse(BusinessException exception) {
return Response.status(400).entity("Invalid Input").build();
}
}
|
package graphics_control.event_handling.game;
import graphics_control.drawables.GameCell;
import javafx.event.EventHandler;
import javafx.scene.paint.Color;
public class MouseExitsAvailableMove implements EventHandler<javafx.scene.input.MouseEvent> {
private GameCell gameCell;
public MouseExitsAvailableMove(GameCell gC) {
this.gameCell = gC;
}
public void handle(javafx.scene.input.MouseEvent event) {
gameCell.getRect().setFill(Color.DARKGRAY);
}
}
|
package Vistas;
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.List;
import java.util.Vector;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import Controlador.AreaAdministracion;
import ViewModels.VistaClase;
public class Cronograma extends JFrame {
/**
*
*/
private static final long serialVersionUID = -7305690017978747952L;
private JPanel pnlContenedor;
private JPanel pnlInferior;
private JTable tblItems;
private DefaultTableModel dataModel;
private JLabel lblTitulo;
List<VistaClase> items;
public Cronograma() {
// Establecer el titulo de la ventana
this.setTitle("CRONOGRAMA");
// Establecer la dimension de la ventana (ancho, alto)
this.setSize(750, 400);
// Establecer NO dimensionable la ventana
this.setResizable(false);
// Ubicar la ventana en el centro de la pantalla
this.setLocationRelativeTo(null);
// Agregar el panel al JFrame
this.getContentPane().add(this.getPanelContenedor());
// Mostrar la ventana
this.setVisible(true);
}
private JPanel getPanelContenedor() {
pnlContenedor = new JPanel();
pnlInferior = new JPanel();
pnlContenedor.setLayout(new BorderLayout());
lblTitulo = new JLabel("Cronograma");
lblTitulo.setFont(new Font("Serif", Font.BOLD, 20));
lblTitulo.setHorizontalAlignment(JLabel.CENTER);
pnlContenedor.add(lblTitulo, BorderLayout.PAGE_START);
pnlContenedor.add(getJTable(), BorderLayout.CENTER);
pnlContenedor.add(getPanelInferior(), BorderLayout.PAGE_END);
return pnlContenedor;
}
private JPanel getPanelInferior() {
pnlInferior.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0; // n�mero columna
gbc.gridy = 0; // n�mero fila
gbc.gridwidth = 1; // numero de columnas de ancho
gbc.gridheight = 1; // numero de filas de ancho
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.VERTICAL; // rellenar la celda en ambos sentidos (horizontal y vertical)
gbc.insets = new Insets(3, 3, 3, 3); // definir el relleno exterior
return pnlInferior;
}
private JScrollPane getJTable() {
tblItems = new JTable();
JScrollPane scrollPane = new JScrollPane(tblItems);
fillTable();
return scrollPane;
}
public void fillTable() {
items = getItems();
Vector<String> aux;
String[] cabecera = { "Deporte", "Día", "Hora" };
dataModel = new DefaultTableModel();
dataModel.setColumnCount(5);
dataModel.setColumnIdentifiers(cabecera);
tblItems.setModel(dataModel);
tblItems.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
// List<Socio> items = AreaAdministracion.getInstancia().obtenerSocios();
for (VistaClase item : items) {
aux = new Vector<String>();
aux.add(item.getDeporte().toString());
aux.add(item.getDia().toString());
aux.add(item.getHora().toString());
dataModel.addRow(aux);
}
if (tblItems == null)
tblItems = new JTable();
}
private List<VistaClase> getItems() {
return AreaAdministracion.getInstancia().obtenerClases();
}
}
|
/**
*
*/
package selection_Sort;
/**
* @author Aloy
*
*/
public class selection {
/**
* @param args
* @return args
*
*/
private static Integer excel_sort(Integer args) {
// TODO Auto-generated method stub
int i,j,small,tmp,pos;
for (i = 0; i< args.length; i++) {
small=args[i];
pos=i;
for ( j = i+1; j < args.length-1; j++) {
if (args[j]<small) {
small=args[j];
pos=j;
}
}
tmp=args[i];
args[i]=args[pos];
args[pos]=tmp;
}
//now the array has been sorted in ascending order
/*
* now we require to return the value to the integer array shell
*/
return args;
}
}
|
package com.notabilia.mycards.models.entities;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.time.LocalDate;
@Entity
public class Card implements EntityModel<Integer> {
@JsonIgnore
private static final Double MODEL_VERSION = 1.0;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String description;
private LocalDate purchaseDate;
private String merchant;
private Double price;
// For JSON deserialisation
public Card() {}
public Card(Integer id) {
this(id, null, null, null, null);
}
public Card(
Integer id,
String description,
LocalDate purchaseDate,
String merchant,
Double price
) {
this.id = id;
this.description = description;
this.purchaseDate = purchaseDate;
this.merchant = merchant;
this.price = price;
}
@Override
public Integer getId() {
return this.id;
}
public String getDescription() {
return description;
}
public void setDescription(String descrption) {
this.description = descrption;
}
public LocalDate getPurchaseDate() {
return purchaseDate;
}
public void setPurchaseDate(LocalDate purchaseDate) {
this.purchaseDate = purchaseDate;
}
public String getMerchant() {
return merchant;
}
public void setMerchant(String merchant) {
this.merchant = merchant;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
@Override
public Double getModelVersion() {
return MODEL_VERSION;
}
}
|
package org.example.openweatherapi;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonIgnoreProperties(ignoreUnknown = true)
public class OpenWeather {
@JsonProperty("name")
private String name;
@JsonProperty("main")
public Weather weather;
@JsonProperty("wind")
public Wind wind;
public String getName() {
return name;
}
public Double getFeelsLikeTemp() {
return weather.getFeelsLike();
}
public Integer getHumidity() {
return weather.getHumidity();
}
public Double getTemp() {
return weather.getTemp();
}
public Integer getPressure() {
return weather.getPressure();
}
public Double getSpeed() {
return wind.getSpeed();
}
//пізніше створити файл *.properties та винести в нього дані
private static String url = "https://openweathermap.org/data/2.5/weather?id=";
private static String api_key = "&appid=b6907d289e10d714a6e88b30761fae22";
public static OpenWeather getWeather(String sity_id) {
RestTemplate restTemplate = new RestTemplate();
return restTemplate.getForObject(url + sity_id + api_key, OpenWeather.class);
}
}
|
package examples;
public class MaximumTest {
public static void main(String[] args) {
System.out.printf("Maximum of %d, %d and %d is %d%n", 3, 4, 5, maximum(3, 4, 5));
System.out.printf("Maximum of %.2f, %.2f, and %.2f is %.2f", 6.6, 8.8, 7.7, maximum(6.6, 8.8, 7.7));
//the output expects a type integer and double respectively
//therefore the compiler explicitly cast method maximum to it respective type
}
public static <T extends Comparable<T>> T maximum(T x, T y, T z) {
//The upper bound of this method is interface comparable
//therefore at run time the type of the generic is Comparable and this method returns a comparable object
T max = x;
if(y.compareTo(max) > 0)
max = y;
if(z.compareTo(max) > 0)
max = z;
return max;
}
}
|
package DataStructures.arrays;
/**
* Given a m * n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
* 1 1 1 0
* 1 1 1 0
* 1 1 0 0
* 1 0 0 0
*/
public class MatrixZeros {
public static void setZeroes(int[][] A) {
if (A == null) return;
int rowLen = A.length;
int colLen = A[0].length;
//set flag for zeroth row/col
boolean firstRowZero = false;
boolean firstColZero = false;
for (int i = 0; i < colLen; i++) {
if (A[0][i] == 0)
firstRowZero = true;
}
for (int i = 0; i < rowLen; i++) {
if (A[i][0] == 0)
firstColZero = true;
}
//traverse all row/col
for (int i = 1; i < rowLen; i++) {
for (int j = 1; j < colLen; j++) {
if (A[i][j] == 0) {
A[i][0] = 0;
A[0][j] = 0;
}
}
}
//mark resp row/col to zero
for (int i = 1; i < rowLen; i++) {
for (int j = 1; j < colLen; j++) {
if (A[i][0] == 0 || A[0][j] == 0) {
A[i][j] = 0;
}
}
}
//finally make first row/col to zero
for (int i = 0; i < colLen; i++) {
if (firstColZero)
A[0][i] = 0;
}
for (int i = 0; i < rowLen; i++) {
if (firstRowZero)
A[i][0] = 0;
}
}
public static void main(String args[]) {
int[][] A = new int[][]{
{1, 1, 1, 0},
{1, 1, 1, 0},
{1, 1, 0, 0},
{1, 0, 0, 0}
};
MatrixZeros.setZeroes(A);
System.out.println(A);
}
}
|
/**
* Created by Владислав on 23.09.2016.
*/
import JUnitTest1.Calculate;
import junit.framework.TestCase;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Stories;
import static junit.framework.Assert.*;
public class CalculateTest extends TestCase {
private Calculate calculate = null;
public CalculateTest(String name){
super(name);
}
protected void setUp() throws Exception{
super.setUp();
calculate = new Calculate();
}
protected void tearDown() throws Exception{
calculate = null;
super.tearDown();
}
@Features("addition")
@Stories("+")
public void testCalcA() throws Exception{
int a = 2;
int b = 1;
int expectedReturn = 3;
int actualReturn = calculate.addition(a,b);
assertEquals("return: ", expectedReturn, actualReturn);
}
@Features("subtraction")
@Stories("-")
public void testCalcS() throws Exception{
int a = 10;
int b = 3;
int expectedReturn = 7;
int actualReturn = calculate.subtraction(a,b);
assertEquals("return: ", expectedReturn, actualReturn);
}
@Features("multiplication")
@Stories("*")
public void testCalcM() throws Exception{
int a = 2;
int b = 3;
int expectedReturn = 6;
int actualReturn = calculate.multiplication(a,b);
assertEquals("return: ", expectedReturn, actualReturn);
}
@Features("division")
@Stories("/")
public void testCalcD() throws Exception{
int a = 15;
int b = 3;
int expectedReturn = 5;
int actualReturn = calculate.division(a,b);
assertEquals("return: ", expectedReturn, actualReturn);
}
}
|
package exchange_match_engine;
public class CancelElement implements RequestElement{
int transactionID;
public CancelElement(int transactionID){
this.transactionID = transactionID;
}
}
|
package ir.ceit.search.nlp.stemming.global.utils;
import global.utils.PatriciaTrie.KeyAnalyzer;
/**
*
* @author htaghizadeh
*/
public class IntegerKeyCreator implements KeyAnalyzer<Integer> {
public static int[] createIntBitMask(final int bitCount) {
int[] bits = new int[bitCount];
for (int i = 0; i < bitCount; i++) {
bits[i] = 1 << (bitCount - i - 1);
}
return bits;
}
private static final int[] BITS = createIntBitMask(32);
@Override
public int length(Integer key) {
return 32;
}
@Override
public boolean isBitSet(Integer key, int keyLength, int bitIndex) {
return (key & BITS[bitIndex]) != 0;
}
@Override
public int bitIndex(Integer key, int keyOff, int keyLength,
Integer found, int foundOff, int foundKeyLength) {
if (found == null)
found = 0;
if(keyOff != 0 || foundOff != 0)
throw new IllegalArgumentException("offsets must be 0 for fixed-size keys");
boolean allNull = true;
int length = Math.max(keyLength, foundKeyLength);
for (int i = 0; i < length; i++) {
int a = key & BITS[i];
int b = found & BITS[i];
if (allNull && a != 0) {
allNull = false;
}
if (a != b) {
return i;
}
}
if (allNull) {
return KeyAnalyzer.NULL_BIT_KEY;
}
return KeyAnalyzer.EQUAL_BIT_KEY;
}
@Override
public int compare(Integer o1, Integer o2) {
return o1.compareTo(o2);
}
@Override
public int bitsPerElement() {
return 1;
}
@Override
public boolean isPrefix(Integer prefix, int offset, int length, Integer key) {
int addr1 = prefix.intValue();
int addr2 = key.intValue();
addr1 = addr1 << offset;
int mask = 0;
for(int i = 0; i < length; i++) {
mask |= (0x1 << i);
}
addr1 &= mask;
addr2 &= mask;
return addr1 == addr2;
}
}
|
package com.hcl.neo.eloader.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "business_group_master")
public class BusinessGroupMaster {
@Id
public String id;
public String name;
public String displayName;
public String kmGroup;
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the displayName
*/
public String getDisplayName() {
return displayName;
}
/**
* @param displayName the displayName to set
*/
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
/**
* @return the kmGroup
*/
public String getKmGroup() {
return kmGroup;
}
/**
* @param kmGroup the kmGroup to set
*/
public void setKmGroup(String kmGroup) {
this.kmGroup = kmGroup;
}
@Override
public String toString() {
return "BusinessGroupMaster [name=" + name + ", displayName=" + displayName + ", kmGroup=" + kmGroup + "]";
}
}
|
package com.lenovohit.ssm.treat.model;
public class AssayItem {
private String id; //检查项目ID
private int index; // 0,
private String item; //检查项目 "游离三碘甲状腺氨酸",
private String result; //检查结果 "1.53",
private String state; //状态指标 "3",
private String range; //参考范围 "1.80 - 4.10",
private String unit; //单位 "pg/ml"
private String assayId; //检查单ID
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getRange() {
return range;
}
public void setRange(String range) {
this.range = range;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
public String getAssayId() {
return assayId;
}
public void setAssayId(String assayId) {
this.assayId = assayId;
}
}
|
package crushstudio.crush_studio.entity;
import crushstudio.crush_studio.config.anototion.CrushAnotation;
import javax.persistence.*;
import java.time.LocalDate;
@Entity
@Table(name = "user")
public class User extends BaseEntity {
@CrushAnotation
@Column(name = "fullname")
private String fullname;
@CrushAnotation
@Column(name = "age")
private int age;
@CrushAnotation
@Column(name = "nick")
private String nickname;
@CrushAnotation
@Column(name = "phone_number")
private String numberPhone;
@CrushAnotation
@Column(name = "email")
private String email;
@CrushAnotation
@Column(name = "main_city")
private String mainCity;
@Column(name = " day_when_you_create")
private LocalDate localDate;
//There must be information about you, hobby or who you are
@CrushAnotation
@Column(name = "info", columnDefinition = "TEXT")
private String specialInfoForYou;
@OneToOne(mappedBy = "user")
@JoinColumn(name = "id")
private UserAuthentification authentification;
// @ManyToOne
// @JoinColumn(name = "user_id")
// private HoHeIs hoHeIs;
}
|
package peter8icestone.concurrency.chapter5;
public class ThreadJoin4 {
public static void main(String[] args) {
long startTimeStamp = System.currentTimeMillis();
Thread t1 = new Thread(new CaptureRunnable("M1", 10_000L));
Thread t2 = new Thread(new CaptureRunnable("M2", 5_000L));
Thread t3 = new Thread(new CaptureRunnable("M3", 15_000L));
t1.start();
t2.start();
t3.start();
try {
t1.join();
t2.join();
t3.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
long endTimeStamp = System.currentTimeMillis();
System.out.printf("capture is done, startTimeStamp=%s, endTimeStamp=%s\n", startTimeStamp, endTimeStamp);
}
}
class CaptureRunnable implements Runnable {
private String machineName;
private long spendTime;
CaptureRunnable(String machineName, long spendTime) {
this.machineName = machineName;
this.spendTime = spendTime;
}
@Override
public void run() {
try {
Thread.sleep(spendTime);
System.out.printf("%s capture completed and successfully at [%s]\n",
machineName, System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
|
package com.spring.service.domain;
import java.util.*;
import java.io.*;
public class WordLadder {
private static Set<String> dict;//�ֵ�
private static Set<String> record;//��¼�滻����µ��ʣ������������ѭ��
private static Stack<String> result; //WordLadder�Ľ��
private static Queue<Stack<String>> ladder;//���ڴ洢ladder�Ķ���
private static String word1;
private static String word2;
public WordLadder(){
this.dict = new HashSet<>();//�ֵ�
this.record = new HashSet<>();//��¼�滻����µ��ʣ������������ѭ��
this.result = new Stack<>(); //WordLadder�Ľ��
this.ladder = new LinkedList<>();//���ڴ洢ladder�Ķ��
this.word1 = "";
this.word2 = "";
}
public String setWord(String w1, String w2){
word1 = w1;
word2 = w2;
return w1+w2;
}
public String getLadder(){
String ss;
if(result.empty()){
ss = "No ladder found from " + word2 + " back to " + word1 + "\n";
return ss;
}
ss = "A ladder from " + word2 + " back to " + word1 + ":\n";
while(!result.empty()){
ss += result.pop() ;
ss += " ";
}
ss += "\n";
return ss;
}
public String run() {
if(!setDict("D:\\罗宇辰\\作业\\大二下\\软工后端\\hw2\\src\\main\\java\\com\\spring\\service\\text\\dictionary.txt")){
return "open file error\n";
};
Stack<String> ss = new Stack<>();
ss.push(word1);
ladder.offer(ss);
record.add(word1);
if(!findLadder(word2)){
return "no ladder\n";
};
ladder = new LinkedList<>();
record = new HashSet<>();
return "ok";
}
private static boolean findLadder(String word2) {
//System.out.println("ladder size "+ladder.size());
while (ladder.size() > 0) {
int size = ladder.size();
for (int i = 0; i < size; i++) {
Stack<String> temp = ladder.poll();
String word = temp.peek();
String ww1 = "";
String ww2 = "";
String ww3 = "";
//��������ʷֱ�������ֱ仯������ɾ����
int len = word.length();
for (int j = 0; j <= len; j++) {
if (j != len)
ww3 = word.substring(0, j) + word.substring(j + 1);
;//ɾ����ĸ
boolean cc = check(ww3, word2, temp);
for (char ch = 'a'; ch <= 'z'; ch++) {
ww2 = word.substring(0, j) + ch + word.substring(j);//�����ĸ
if (j != len)
ww1 = word.substring(0, j) + ch + word.substring(j + 1); //�ı���ĸ
if (check(ww1, word2, temp) ||
check(ww2, word2, temp) ||
cc)
return true;
}
}
}
}
//System.out.println("false!");
return false;
}
public static boolean check(String word, String target, Stack<String> temp) {
//System.out.println(word + " " +target);
if (record.contains(word))
return false;
if (word.equals(target)) {
result = (Stack<String>)temp.clone();
result.push(word);
//ladder = queue<stack<string>>();//����
return true;
} else if (dict.contains(word)) //�µ�����û���ֹ�����Ч����
//���ⲿ��wordladder��ӵ�ladder������
{
record.add(word);
Stack<String> save = (Stack<String>)temp.clone();
save.push(word);
ladder.offer(save);
}
return false;
}
private static boolean setDict(String fileName) {
File file = new File(fileName);
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String tempString;
// һ�ζ���һ�У�ֱ������nullΪ�ļ�����
while ((tempString = reader.readLine()) != null) {
dict.add(tempString);
}
reader.close();
return true;
} catch (IOException e) {
//e.printStackTrace();
return false;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.*;
import java.net.*;
import javax.swing.*;
import java.util.*;
import java.text.*;
/**
*
* @author Cham
*/
class ServerThread extends Thread {
String message, whisperTo, invalid;
int i, j, k;
MyConnection[] conn;
MyConnection user;
public ServerThread(MyConnection[] c, MyConnection u){
conn = c;
user = u;
}
public void run(){
try{
for(i = 1; conn[i] != null; i++){
for(j =1; j <= user.userNo; j++){
conn[j].sendMessage("/status" + user.userNo + " " + conn[i].userNo + " " +conn[i].name + " " + conn[i].status + "\nEND");
}
}
for(j = 1; j <= user.userNo; j++){
conn[j].sendMessage("Server message: " + user.name + " has connected" + ".\nEND");
}
while(true){
message = user.getMessage();
if (message.startsWith("/")){
/* /changename */ if(message.startsWith("/changename ")){
for(k = 1; conn[k] != null; k++){}
for(i = 1; conn[i] != null; i++){
for(j =1; j <= user.userNo; j++){
conn[j].sendMessage("/status" + (k-1) + " " + conn[i].userNo + " " +conn[i].name + " " + conn[i].status + "\nEND");
}
}
for(j = 1; conn[j] != null; j++){
conn[j].sendMessage("Server message: " + user.name + " has changed name to " + message.substring(12) + "." + "\nEND");
conn[j].sendMessage("/changename" + user.userNo + " " + message.substring(12));
}
user.name = message.substring(12);
/* /changestatus */ }else if(message.startsWith("/changestatus ")){
for(k = 1; conn[k] != null; k++){}
for(i = 1; conn[i] != null; i++){
for(j =1; j <= user.userNo; j++){
conn[j].sendMessage("/status" + (k-1) + " " + conn[i].userNo + " " +conn[i].name + " " + conn[i].status + "\nEND");
}
}
for(j = 1; conn[j] != null; j++){
conn[j].sendMessage("Server message: " + user.name + " has changed status to " + message.substring(14) + "." + "\nEND");
conn[j].sendMessage("/changestatus" + user.userNo + " " + message.substring(14));
}
user.status = message.substring(14);
/* /whisper */ }else if(message.startsWith("/whisper ")){
whisperTo = message.substring(9, (message.indexOf(" ", 9)));
for(j = 1; conn[j] != null; j++){
if(conn[j].name.equals(whisperTo)) break;
}
System.out.println(j + " " + whisperTo);
if(conn[j] != null && conn[j].name.equals(whisperTo) ) conn[j].sendMessage("[" + user.name + " whispers]: " + message.substring ((message.indexOf(" ", 9) + 1)));
else user.sendMessage("Server message: " + whisperTo + " is not available.");
/* /quit */ }else if(message.startsWith("/quit")){
for(i = 1; !conn[i].name.equals(user.name); i++){}
for(j = 1; conn[j] != null; j++){
conn[j].sendMessage(user.name + " has disconnected" + "\nEND");
}for(k = 1; conn[k] != null; k++){
conn[k].sendMessage("/disconnect" + i + " " + j + " \nEND" );
}
conn[i].sendMessage(message);
conn[j-1].userNo = conn[i].userNo;
conn[i] = conn[j-1];
conn[j-1] = null;
break;
/* invalid */ }else{
if(message.contains(" ")){
invalid = message.substring(0, (message.indexOf(" ")));
user.sendMessage("Invalid command \""+ invalid + "\".\nEND");
}else user.sendMessage("Invalid command \""+ message + "\".\nEND");
}
}
/*messages*/ else{
for(j = 1; conn[j] != null; j++){
conn[j].sendMessage(user.name + ": "+ message + "\nEND");
}
}
}
} catch (Exception e){
e.printStackTrace();
}
}
}
|
package io.jrevolt.sysmon.client.ui.model;
import io.jrevolt.sysmon.model.NetworkInfo;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
/**
* @author <a href="mailto:patrikbeno@gmail.com">Patrik Beno</a>
*/
public class NetworkItem {
private StringProperty cluster = new SimpleStringProperty();
private StringProperty server = new SimpleStringProperty();
private StringProperty destination = new SimpleStringProperty();
private IntegerProperty port = new SimpleIntegerProperty();
private StringProperty sourceIP = new SimpleStringProperty();
private StringProperty destinationIP = new SimpleStringProperty();
private SimpleObjectProperty<Long> time = new SimpleObjectProperty<>();
private ObjectProperty<NetworkInfo.Status> status = new SimpleObjectProperty<>();
private StringProperty comment = new SimpleStringProperty();
public String getCluster() {
return cluster.get();
}
public StringProperty clusterProperty() {
return cluster;
}
public void setCluster(String cluster) {
this.cluster.set(cluster);
}
public String getServer() {
return server.get();
}
public StringProperty serverProperty() {
return server;
}
public void setServer(String server) {
this.server.set(server);
}
public String getSourceIP() {
return sourceIP.get();
}
public StringProperty sourceIPProperty() {
return sourceIP;
}
public void setSourceIP(String sourceIP) {
this.sourceIP.set(sourceIP);
}
public String getDestination() {
return destination.get();
}
public StringProperty destinationProperty() {
return destination;
}
public void setDestination(String destination) {
this.destination.set(destination);
}
public String getDestinationIP() {
return destinationIP.get();
}
public StringProperty destinationIPProperty() {
return destinationIP;
}
public void setDestinationIP(String destinationIP) {
this.destinationIP.set(destinationIP);
}
public int getPort() {
return port.get();
}
public IntegerProperty portProperty() {
return port;
}
public void setPort(int port) {
this.port.set(port);
}
public Long getTime() {
return time.get();
}
public SimpleObjectProperty<Long> timeProperty() {
return time;
}
public void setTime(Long time) {
this.time.set(time);
}
public NetworkInfo.Status getStatus() {
return status.get();
}
public ObjectProperty<NetworkInfo.Status> statusProperty() {
return status;
}
public void setStatus(NetworkInfo.Status status) {
this.status.set(status);
}
public String getComment() {
return comment.get();
}
public StringProperty commentProperty() {
return comment;
}
public void setComment(String comment) {
this.comment.set(comment);
}
}
|
package org.juxtasoftware.diff.util;
import java.io.IOException;
import java.net.URI;
import java.util.List;
import java.util.Set;
import org.juxtasoftware.diff.Token;
import org.juxtasoftware.diff.TokenSource;
import org.juxtasoftware.diff.impl.SimpleToken;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import eu.interedition.text.Name;
import eu.interedition.text.Range;
import eu.interedition.text.Text;
import eu.interedition.text.mem.SimpleAnnotation;
import eu.interedition.text.mem.SimpleName;
import eu.interedition.text.mem.SimpleText;
/**
* @author <a href="http://gregor.middell.net/" title="Homepage">Gregor Middell</a>
*/
public class SimpleTokenSource implements TokenSource {
private static final Name TEST_TOKEN_NAME = new SimpleName((URI) null, "testToken");
@Override
public List<Token> tokensOf(Text text, Set<Range> ranges) throws IOException {
Preconditions.checkArgument(text instanceof SimpleText);
final String textContent = ((SimpleText) text).getContent();
final List<Token> tokens = Lists.newArrayList();
int start = -1;
StringBuffer token = new StringBuffer();
for ( int offset=0; offset<textContent.length(); offset++) {
char read = textContent.charAt(offset);
if ( isTokenChar( read )) {
if ( start == -1 ) {
start = offset;
}
token.append( read );
} else {
if ( start != -1 ) {
Range tokenRange = new Range(start, offset);
final SimpleAnnotation a = new SimpleAnnotation(text, TEST_TOKEN_NAME, tokenRange, null);
tokens.add(new SimpleToken(a, token.toString()));
token = new StringBuffer();
start = -1;
}
}
}
if (start > -1 ) {
Range tokenRange = new Range(start, textContent.length()-1);
final SimpleAnnotation a = new SimpleAnnotation(text, TEST_TOKEN_NAME, tokenRange, null);
tokens.add(new SimpleToken(a, token.toString()));
}
return tokens;
}
private boolean isTokenChar(int c) {
if (Character.isWhitespace(c)) {
return false;
}
if (Character.isLetter(c) || Character.isDigit(c)) {
return true;
}
return false;
}
}
|
package src.modulo4.complementos;
/**
*
* @author uel
*/
public class Face {
int nVerts;
VertexID[] vert;
public Face() {
nVerts = 0;
vert = null;
}
public Face(int nVerts, VertexID[] vert) {
this.nVerts = nVerts;
this.vert = new VertexID[nVerts];
}
public int getNVerts() {
return nVerts;
}
public void setNVerts(int nVerts) {
this.nVerts = nVerts;
}
}
|
package utility;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ReadFile {
private String path;
private boolean res;
public ReadFile(String filePath, boolean res) {
this.path = filePath;
this.res = res;
}
public String[] openFile() throws IOException {
BufferedReader reader = null;
if (res) {
reader = new BufferedReader(new InputStreamReader(getClass().getResource(path).openStream()));
} else {
FileReader fr = new FileReader(path);
reader = new BufferedReader(fr);
}
int numberOfLines = readLines(path);
String[] out = new String[numberOfLines];
for (int i = 0; i < numberOfLines; i++) {
out[i] = reader.readLine();
}
reader.close();
return out;
}
public int readLines(String filePath) throws IOException{
BufferedReader reader = null;
if (res) {
reader = new BufferedReader(new InputStreamReader(getClass().getResource(path).openStream()));
} else {
FileReader fr = new FileReader(path);
reader = new BufferedReader(fr);
}
int out = 0;
while (reader.readLine() != null) {
out++;
}
reader.close();
return out;
}
}
|
package com.Servlet;
import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.Service.OrderService;
import com.al.dao.OrderDao;
import com.al.dao.OrderDaoImpl;
import com.al.model.Order;
/**
* Servlet implementation class PlaceOrder
*/
@WebServlet("/PlaceOrder")
public class PlaceOrder extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public PlaceOrder() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
HttpSession session=request.getSession(true);
Object count = session.getAttribute("Count");
Object clientIdObj=session.getAttribute("clientId");
Integer clientId = (Integer) clientIdObj;
Object productIdObj = session.getAttribute("productId");
Integer productId = (Integer) productIdObj;
OrderService orderService=new OrderService();
Integer countInt=(Integer)count;
System.out.println(countInt);
String parameter = request.getParameter("quantity1");
System.out.println("quantity1"+ parameter);
for(int i=1;i<=countInt;i++)
{
String quantity="quantity"+i;
String OrderPlacedDate="OrderPlacedDate"+i;
String DeadLine="deadLine"+i;
//System.out.println("orderId"+OrderId);
String quantityRequired = request.getParameter(quantity);
String orderPlacedDate = request.getParameter(OrderPlacedDate);
String deadline = request.getParameter(DeadLine);
System.out.println(quantityRequired+orderPlacedDate+deadline);
List<Order> allOrders = orderService.getAllOrders();
int size = allOrders.size()-1;
int orderId = allOrders.get(size).getOrderId();
orderId++;
orderService.getOrderFromUser(orderId, clientId,productId, Integer.parseInt(quantityRequired),orderPlacedDate, deadline);
}
List<Order> orderOfParticularClient = orderService.getOrderOfParticularClient(clientId);
request.setAttribute("allOrders",orderOfParticularClient);
RequestDispatcher requestDispatcher=request.getRequestDispatcher("ViewOrders.jsp");
requestDispatcher.include(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
|
package com.chinasoft.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.chinasoft.dao.CkDao;
import com.chinasoft.domain.Ck;
import com.chinasoft.service.CkService;
@Service("ckService")
@Transactional
public class CkServiceImpl implements CkService{
@Resource(name="ckDao")
private CkDao ckDao;
public void save(Ck ck) throws Exception {
this.ckDao.save(ck);
}
public List<Ck> findAllCk(Ck ck) throws Exception {
if(ck.getNum() == null && ck.getName()==null){
List<Ck> cks = this.ckDao.findAll();
return cks;
}else{
List<Ck> cks = this.ckDao.findAll(ck);
return cks;
}
}
public void deleteCkById(Integer id) throws Exception {
if(id!=null){
this.ckDao.delete(id);
}else{
throw new RuntimeException("id不能为空");
}
}
public Ck getCkById(Integer id) throws Exception {
return this.ckDao.getById(id);
}
public void updateCk(Ck ck1, Integer id) throws Exception {
// 校验...
// 根据id查找仓库
Ck ck = this.ckDao.getById(id);
if(ck!=null){
ck.setDh(ck1.getDh());
ck.setKcl(ck1.getKcl());
ck.setLxr(ck1.getLxr());
ck.setName(ck1.getName());
this.ckDao.update(ck);
}
}
// 根据name查找仓库
public Ck getCkByName(String ckName) throws Exception {
if(ckName != null){
return this.ckDao.getCkByName(ckName);
}else{
throw new RuntimeException("仓库名不能为空!!");
}
}
// 查找所有仓库
public List<Ck> findAllCk() throws Exception {
return this.ckDao.findAll();
}
}
|
package com.paces.game.others;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.VertexAttributes;
import com.badlogic.gdx.graphics.g3d.Material;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.TextureAttribute;
import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder;
public class BG {
public Model bg;
public ModelInstance bgI;
public Texture fondo;
public BG(float prof, float alto, float ancho, float posX){
fondo = new Texture(Gdx.files.internal("TexturasLunas/bg.jpg"));
ModelBuilder modelBuilder = new ModelBuilder();
bg = modelBuilder.createBox(prof, alto, ancho, new Material(TextureAttribute.createDiffuse(fondo)),
VertexAttributes.Usage.Position | VertexAttributes.Usage.Normal | VertexAttributes.Usage.TextureCoordinates);
bgI = new ModelInstance(bg, posX, 0f, 0f);
}
}
|
package negocio.apresentacao;
import java.util.Date;
import negocio.basica.Computador;
import negocio.basica.Hardware;
import negocio.controlador.ControladorHardware;
public class ApresentacaoHardware {
public static void main (String [] args){
ControladorHardware contHard = new ControladorHardware();
Hardware hard = new Hardware();
Computador computador = new Computador();
computador.setId(1);
hard.setId(1);
hard.setMarca("seagate");
hard.setModelo("st001");
hard.setGarantia("1 ano");
hard.setDtcompra(new Date());
hard.setComputador(computador);
contHard.incluir(hard);
}
}
|
package elainpeli;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Minna
*/
import java.util.Random;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.HashMap;
public class Kayttoliittyma {
private Scanner lukija;
private HashMap<Integer, Elain> elaimet = new HashMap<>();
private ArrayList<Pelaaja> pelaajat = new ArrayList<>();
private int pelivuorossa;
public Kayttoliittyma(Scanner lukija, HashMap<Integer, Elain> elaimet) {
this.lukija = lukija;
this.elaimet = elaimet;
this.pelaajat = pelaajat;
this.pelivuorossa = 0;
}
public void kaynnista() {
pelaajienLisays();
while (!peliLoppu()) {
System.out.println("\nPelivuorossa " + pelaajat.get(pelivuorossa).nimi());
System.out.println("1: Heitä noppaa\n" +
"2: Näytä pistetilanne");
tulostaElainlista();
System.out.print("> ");
int valinta = Integer.valueOf(lukija.nextLine());
switch(valinta) {
case 1: nopanheitto(); break;
case 2: pistetilanne(); break;
}
pelivuoro();
}
System.out.println("*~*~* " + voittaja() + " voitti! *~*~*");
}
private void pelaajienLisays() {
/* Annetaan pelaajien nimet, max 4 */
for (int i = 0; i < 4; i++) {
System.out.println("Anna pelaajan nimi (paina Enter, jos haluat lopettaa):");
String pelaaja = lukija.nextLine();
if (pelaaja.isBlank()) {
break;
}
pelaajat.add(new Pelaaja(pelaaja));
}
}
private void nopanheitto() {
/* Nopanheitto, nopan luku vastaa eläimen osien määrää. 6 = mikä vain */
Random arpa = new Random();
int luku = arpa.nextInt(6) + 1;
switch (luku) {
case 1: System.out.print(luku + " - Sammakko! ");
kasvataElainta(elaimet.get(luku));
break;
case 2: System.out.print(luku + " - Ankka! ");
kasvataElainta(elaimet.get(luku));
break;
case 3: System.out.print(luku + " - Possu! ");
kasvataElainta(elaimet.get(luku));
break;
case 4: System.out.print(luku + " - Lehmä! ");
kasvataElainta(elaimet.get(luku));
break;
case 5: System.out.print(luku + " - Hevonen! ");
kasvataElainta(elaimet.get(luku));
break;
case 6: System.out.print(luku + " - Valitse mikä vain eläin!\n");
tulostaElainvalinta();
int valinta = Integer.valueOf(lukija.nextLine());
kasvataElainta(elaimet.get(valinta));
break;
}
System.out.println("");
}
private void pistetilanne() {
// "piste(ttä)" nätimmäksi
for (Pelaaja pelaaja : pelaajat) {
System.out.println(pelaaja.nimi() + ": " + pelaaja.pisteet() + " piste(ttä)");
}
System.out.println("");
}
private void pelivuoro() {
this.pelivuorossa++;
if (this.pelivuorossa == pelaajat.size()) {
this.pelivuorossa = 0;
}
}
public void tulostaElainlista() {
for (int luku : this.elaimet.keySet()) {
System.out.println(" " + elaimet.get(luku).getOsat()
+ "/"
+ elaimet.get(luku).getKoko()
+ " "
+ elaimet.get(luku).getNimi()
);
}
}
public void tulostaElainvalinta() {
for (int luku : this.elaimet.keySet()) {
System.out.println(" " + luku + ": " + elaimet.get(luku).getNimi() + "\t"
+ elaimet.get(luku).getOsat() + "/" + elaimet.get(luku).getKoko());
}
}
private void kasvataElainta(Elain elain) {
if (elain.kasvata()) {
System.out.print("Onnea! Sait pisteen.");
pelaajat.get(this.pelivuorossa).lisaaPisteita();
}
}
private boolean peliLoppu() {
for (int i : elaimet.keySet()) {
if (elaimet.get(i).onkoValmis() == false) {
return false;
}
}
return true;
}
// KORJAA ARRAYINDEXOUTOFBOUNDS
private String voittaja() {
int paras = pelaajat.get(0).pisteet();
Pelaaja voittaja = pelaajat.get(0);
for (Pelaaja pelaaja : pelaajat) {
if (pelaaja.pisteet() > paras) {
paras = pelaaja.pisteet();
voittaja = pelaaja;
}
}
return voittaja.nimi();
}
}
|
import java.util.ArrayList;
public class Registro {
private ArrayList<Socio> listado;
private int cupo;
private boolean descuento;
public ArrayList<Socio> getListado() {
return listado;
}
public void setListado(ArrayList<Socio> listado) {
if(listado.size()<=cupo){
this.listado = listado;
System.out.println("Socios asignados correctamente");
}
else {
int resto=listado.size()-cupo;
System.out.println("Cupo exedido: "+resto);
}
}
public int getCupo() {
return cupo;
}
public void setCupo(int cupo) {
this.cupo = cupo;
}
public boolean isDescuento() {
return descuento;
}
public void setDescuento(boolean descuento) {
this.descuento = descuento;
}
}
|
package com.tpg.brks.ms.expenses.integration.web;
import org.apache.http.HttpStatus;
public interface HttpResponseFixture {
default int isOk() {
return HttpStatus.SC_OK;
}
}
|
package com._520it._01_preparedstatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import org.junit.Test;
import com._520it.util.JdbcUtil;
public class PreparedStatementTest {
@Test
public void testName() throws Exception {
//¼ÖçöÓûÖ´ÊÂ
String sql="INSERT INTO t_student(name,age) VALUES(?,?)";
Connection conn=JdbcUtil.getConnection();
PreparedStatement preparedStatement=conn.prepareStatement(sql);
preparedStatement.setString(1, "AA");
preparedStatement.setInt(2, 12);
preparedStatement.executeUpdate();
JdbcUtil.close(null, preparedStatement, conn);
}
}
|
package com.yc.education.model.account;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.*;
@Table(name = "account_payable_info")
public class AccountPayableInfo {
/**
* 应付账款冲账--收款方式详情
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
/**
* 应付账款冲账id
*/
private Long otherid;
/**
* 付款方式
*/
@Column(name = "payment_method")
private String paymentMethod;
/**
* 付款金额
*/
@Column(name = "payment_money")
private BigDecimal paymentMoney;
/**
* 供应商
*/
private String supplier;
/**
* 发票号码
*/
@Column(name = "invoice_no")
private String invoiceNo;
/**
* 备注
*/
private String remark;
/**
* 创建时间
*/
private Date createtime;
/**
* 添加时间
*/
private Date addtime;
/**
* 获取应付账款冲账--收款方式详情
*
* @return id - 应付账款冲账--收款方式详情
*/
public Long getId() {
return id;
}
/**
* 设置应付账款冲账--收款方式详情
*
* @param id 应付账款冲账--收款方式详情
*/
public void setId(Long id) {
this.id = id;
}
/**
* 获取应付账款冲账id
*
* @return otherid - 应付账款冲账id
*/
public Long getOtherid() {
return otherid;
}
/**
* 设置应付账款冲账id
*
* @param otherid 应付账款冲账id
*/
public void setOtherid(Long otherid) {
this.otherid = otherid;
}
/**
* 获取付款方式
*
* @return payment_method - 付款方式
*/
public String getPaymentMethod() {
return paymentMethod;
}
/**
* 设置付款方式
*
* @param paymentMethod 付款方式
*/
public void setPaymentMethod(String paymentMethod) {
this.paymentMethod = paymentMethod;
}
/**
* 获取付款金额
*
* @return payment_money - 付款金额
*/
public BigDecimal getPaymentMoney() {
return paymentMoney;
}
/**
* 设置付款金额
*
* @param paymentMoney 付款金额
*/
public void setPaymentMoney(BigDecimal paymentMoney) {
this.paymentMoney = paymentMoney;
}
/**
* 获取供应商
*
* @return supplier - 供应商
*/
public String getSupplier() {
return supplier;
}
/**
* 设置供应商
*
* @param supplier 供应商
*/
public void setSupplier(String supplier) {
this.supplier = supplier;
}
/**
* 获取发票号码
*
* @return invoice_no - 发票号码
*/
public String getInvoiceNo() {
return invoiceNo;
}
/**
* 设置发票号码
*
* @param invoiceNo 发票号码
*/
public void setInvoiceNo(String invoiceNo) {
this.invoiceNo = invoiceNo;
}
/**
* 获取备注
*
* @return remark - 备注
*/
public String getRemark() {
return remark;
}
/**
* 设置备注
*
* @param remark 备注
*/
public void setRemark(String remark) {
this.remark = remark;
}
/**
* 获取创建时间
*
* @return createtime - 创建时间
*/
public Date getCreatetime() {
return createtime;
}
/**
* 设置创建时间
*
* @param createtime 创建时间
*/
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
/**
* 获取添加时间
*
* @return addtime - 添加时间
*/
public Date getAddtime() {
return addtime;
}
/**
* 设置添加时间
*
* @param addtime 添加时间
*/
public void setAddtime(Date addtime) {
this.addtime = addtime;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.