method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
b7d236b7-74b1-4822-801e-ce7c84a5d666 | 8 | public void backward(float delta, Level level, int currentRoom) {
float x,y,z,minX,maxX,minY,maxY;
List<Float> obsList = new ArrayList<Float>();
minY = level.getRoomList().get(currentRoom).getPos().getY();
maxY = level.getRoomList().get(currentRoom).getPos().getY() + level.getRoomList().get(currentRoom).getDy();
minX = level.getRoomList().get(currentRoom).getPos().getX();
maxX = level.getRoomList().get(currentRoom).getPos().getX() + level.getRoomList().get(currentRoom).getDx();
for (int i = 0; i < obsList.size(); i++) {
}
walking = true;
//Checking if the entity is inside the room boundery.
if(getPos().getX() - (float) ((getSpeed() * Math.cos(getOrientation()) * delta)) >= minX && getPos().getX() - (float) ((getSpeed() * Math.cos(getOrientation()) * delta)) <= maxX){
x = getPos().getX() - (float) ((getSpeed() * Math.cos(getOrientation()) * delta));
}else{
//Moving the payer 0.01f from the wall
if(getSpeed() * Math.cos(getOrientation()) * delta < 0){
x = level.getRoomList().get(currentRoom).getPos().getX() + level.getRoomList().get(currentRoom).getDx() - 0.01f;
}else{
x = level.getRoomList().get(currentRoom).getPos().getX() + 0.01f;
}
}
//Checking if the entity is inside the room boundery.
if(getPos().getY() - (float) ((getSpeed() * Math.sin(getOrientation()) * delta)) >= minY && getPos().getY() - (float) ((getSpeed() * Math.sin(getOrientation()) * delta)) <= maxY){
y = getPos().getY() - (float) ((getSpeed() * Math.sin(getOrientation()) * delta));
}else{
//Moving the payer 0.01f from the wall
if(getSpeed() * Math.sin(getOrientation()) * delta < 0){
y = level.getRoomList().get(currentRoom).getPos().getY() + level.getRoomList().get(currentRoom).getDy() - 0.01f;
}else{
y = level.getRoomList().get(currentRoom).getPos().getY() + 0.01f;
}
}
z = getPos().getZ() - 0.0f;
//Checking if the new X,Y,Z is equal to the old X,Y,Z. If so then object haven't be walking.
if(getPos().equals(new Point(x,y,z)) == true){
walking = false;
}
setPos(x, y, z);
} |
e68a31f7-d7e9-4490-bac1-ba53d29d9ac8 | 5 | public static void validateTour(Tour tour) throws TechnicalException {
if (tour == null) {
throw new TechnicalException(MSG_ERR_NULL_ENTITY);
}
if ( ! isValidDiscount(tour.getDiscount())) {
throw new TechnicalException(DISCOUNT_ERROR_MSG);
}
if ( ! isValidTotalSeats(tour.getTotalSeats())) {
throw new TechnicalException(TOTALSEATS_ERROR_MSG);
}
if ( ! isValidFreeSeats(tour.getTotalSeats(), tour.getFreeSeats())) {
throw new TechnicalException(FREESEATS_ERROR_MSG);
}
if ( ! isValidPrice(tour.getPrice())) {
throw new TechnicalException(PRICE_ERROR_MSG);
}
} |
743db422-330f-44e4-a48d-28dc458d76ef | 3 | protected String createJSON(List<String> values) {
final OutputStream out = new ByteArrayOutputStream();
final ObjectMapper mapper = new ObjectMapper();
String output = "";
try {
mapper.writeValue(out, values);
final byte[] data = ((ByteArrayOutputStream) out).toByteArray();
output = new String(data);
System.out.println(output);
} catch (JsonGenerationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return output;
} |
eed30b26-be57-4b72-b97c-e6fa3e5630bd | 5 | public String[] getFilteredCourses(boolean undergrad, boolean grad) {
ArrayList<String> filteredList = new ArrayList<String>();
for(Course course : courses.values()) {
String numWithNoX = course.getCatalogNumber().replaceAll("X", "0");
int courseNumber = getStringValue(numWithNoX);
if(undergrad && courseNumber <= 499) {
filteredList.add(course.getCourseName());
}
else if(grad && courseNumber >= 500) {
filteredList.add(course.getCourseName());
}
}
Collections.sort(filteredList, new CatalogNumberComparator());
String[] newArray = new String[filteredList.size()];
filteredList.toArray(newArray);
return newArray;
} |
be10fabb-b6fb-4fa7-a1be-c6782f3bc81c | 0 | protected String getRtnCode(int codeNum) {
return this.rtnCodes.get(codeNum);
} |
84072587-2e01-4e38-8737-8f010643390f | 1 | @Override
protected void logBindInfo(Method method) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("绑定" + getDescription() + "到方法[" + method + "]成功");
}
} |
fdab412c-e1f9-4391-a375-2bc4526a4cc9 | 2 | public static boolean insertar_nuevo(Producto x){
try{
BufferedWriter escribe=Files.newBufferedWriter(path,
java.nio.charset.StandardCharsets.UTF_8, java.nio.file.StandardOpenOption.APPEND);
escribe.write(x.getCod()+";"+x.getDesc()+";"+x.getStock()+";"+x.getPrecio());
escribe.newLine();
escribe.close();//si no no escribe pq?
return true;
}catch(InvalidPathException e){
System.out.println("Error en leer la ruta del fichero "+e);
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
} |
675af81b-6b6b-4128-9dbc-c880a103a4ee | 5 | @Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
String pathInfo = request.getServletPath();
if (StringUtil.isNullOrEmpty(pathInfo)) {
new IllegalArgumentException("该用户已经登陆.");
}
if (includeFilterPattern != null) {
Matcher matcher = includeFilterPattern.matcher(pathInfo.toLowerCase());
boolean iscontains = matcher.find();
if (iscontains) {
matcher = excludeFilterPattern.matcher(pathInfo.toLowerCase());
iscontains = matcher.find();
if (iscontains) {
filterChain.doFilter(req, resp);
return;
}
HttpSession session = request.getSession();
String sysAccessID = (String) session.getAttribute("sysAccessID");
// 判断是否登陆
if (StringUtil.isNullOrEmpty(sysAccessID)) {
} else {
}
} else {
filterChain.doFilter(req, resp);
}
}
} |
e8ea08d9-2f50-4d33-908e-cfb8ee816902 | 9 | public boolean isCompleteSubtree(PGridPath prefix) {
int prefixCount = 0;
int conjCount = 0;
for (String unsolved : unsolvedPaths_.keySet()) {
PGridPath unsolvedPath = new PGridPath(unsolved);
if (unsolvedPath.hasPrefix(prefix)) {
prefixCount++;
if (unsolvedPath.length() - prefix.length() == 1) {
conjCount++;
}
}
}
if (conjCount == 2) {
return true;
} else if (prefixCount == 1 && conjCount == 0) {
char last = prefix.value(prefix.length() - 1);
last = last == '0' ? '1' : '0';
PGridPath conjPath = new PGridPath(prefix.subPath(0, prefix.length() - 1) + last);
return isCompleteSubtree(conjPath);
} else if (prefixCount != conjCount) {
PGridPath zero = new PGridPath(prefix.toString() + '0');
PGridPath one = new PGridPath(prefix.toString() + '1');
boolean zeroResult = isCompleteSubtree(zero);
boolean oneResult = isCompleteSubtree(one);
return zeroResult && oneResult;
}
return false;
} |
9fb31aea-eee4-4c0b-a55e-d2073e67654f | 8 | private String useRbondVariables(String s, int frame) {
if (!(model instanceof MolecularModel))
return s;
MolecularModel m = (MolecularModel) model;
int n = m.bonds.size();
if (n <= 0)
return s;
int lb = s.indexOf("%rbond[");
int rb = s.indexOf("].", lb);
int lb0 = -1;
String v;
int i;
RadialBond bond;
while (lb != -1 && rb != -1) {
v = s.substring(lb + 7, rb);
double x = parseMathExpression(v);
if (Double.isNaN(x))
break;
i = (int) Math.round(x);
if (i < 0 || i >= n) {
out(ScriptEvent.FAILED, "Radial bond " + i + " does not exist.");
break;
}
v = escapeMetaCharacters(v);
bond = m.bonds.get(i);
s = replaceAll(s, "%rbond\\[" + v + "\\]\\.length", bond.getLength(frame) * R_CONVERTER);
s = replaceAll(s, "%rbond\\[" + v + "\\]\\.strength", bond.getBondStrength());
s = replaceAll(s, "%rbond\\[" + v + "\\]\\.bondlength", bond.getBondLength() * R_CONVERTER);
s = replaceAll(s, "%rbond\\[" + v + "\\]\\.atom1", bond.atom1.getIndex());
s = replaceAll(s, "%rbond\\[" + v + "\\]\\.atom2", bond.atom2.getIndex());
s = replaceAll(s, "%rbond\\[" + v + "\\]\\.custom", bond.custom);
lb0 = lb;
lb = s.indexOf("%rbond[");
if (lb0 == lb) // infinite loop
break;
rb = s.indexOf("].", lb);
}
return s;
} |
3d0828ee-2d9f-48e9-aca7-36a276efe071 | 7 | public boolean isTrip() {
boolean retBoo = false;
if (_cards.size() >= 3) {
if (!(isPair()))
return retBoo;
else {
for (int i = 0; i < _cards.size()-2; i++) {
for (int x = (i+1); x < _cards.size()-1; x++) {
if (_cards.get(i).compareTo(_cards.get(x)) == 0) {
for (int p = (x+1); p < _cards.size(); p++) {
if (_cards.get(i).compareTo(_cards.get(p)) == 0)
retBoo = true;
}
}
}
}
}
}
return retBoo;
} |
a99ff4bc-a33f-4d19-a408-10beb1683546 | 8 | public LearningEvaluation evalModel(InstanceStream trainStream, InstanceStream testStream, AbstractClassifier model) {
model = new SelfOzaBoostID();
InstanceStream stream = (InstanceStream)trainStream.copy();
ClassificationPerformanceEvaluator evaluator = new BasicClassificationPerformanceEvaluator();
Instance testInst = null;
int maxInstances = this.maxInstancesOption.getValue();
long instancesProcessed = 0;
System.out.println("Evaluating model...");
while (stream.hasMoreInstances()
&& ((maxInstances < 0) || (instancesProcessed < maxInstances))) {
testInst = (Instance) stream.nextInstance().copy();
int trueClass = (int) testInst.classValue();
testInst.setClassMissing();
double[] prediction = model.getVotesForInstance(testInst);
evaluator.addClassificationAttempt(trueClass, prediction, testInst
.weight());
instancesProcessed++;
if (instancesProcessed % INSTANCES_BETWEEN_MONITOR_UPDATES == 0) {
long estimatedRemainingInstances = stream
.estimatedRemainingInstances();
if (maxInstances > 0) {
long maxRemaining = maxInstances - instancesProcessed;
if ((estimatedRemainingInstances < 0)
|| (maxRemaining < estimatedRemainingInstances)) {
estimatedRemainingInstances = maxRemaining;
}
}
System.out.println(estimatedRemainingInstances < 0 ? -1.0
: (double) instancesProcessed
/ (double) (instancesProcessed + estimatedRemainingInstances));
}
}
System.out.println("Accuracy result before self-train: " + evaluator.getPerformanceMeasurements()[1]);
selfTrain(testInst);
int returnStatus = selfTest(testStream);
EvalActiveBoostingID.model.resetLearningImpl(); //Learning is completed so we can reset
return new LearningEvaluation(evaluator.getPerformanceMeasurements());
} |
70501615-0729-4604-aa3d-bb6289bbd5ce | 5 | private boolean askNodesorFinish() throws IOException
{
/* If >= CONCURRENCY nodes are in transit, don't do anything */
if (this.config.maxConcurrentMessagesTransiting() <= this.messagesTransiting.size())
{
return false;
}
/* Get unqueried nodes among the K closest seen that have not FAILED */
List<Node> unasked = this.closestNodesNotFailed(UNASKED);
if (unasked.isEmpty() && this.messagesTransiting.isEmpty())
{
/* We have no unasked nodes nor any messages in transit, we're finished! */
return true;
}
/**
* Send messages to nodes in the list;
* making sure than no more than CONCURRENCY messsages are in transit
*/
for (int i = 0; (this.messagesTransiting.size() < this.config.maxConcurrentMessagesTransiting()) && (i < unasked.size()); i++)
{
Node n = (Node) unasked.get(i);
int comm = server.sendMessage(n, lookupMessage, this);
this.nodes.put(n, AWAITING);
this.messagesTransiting.put(comm, n);
}
/* We're not finished as yet, return false */
return false;
} |
a855f75a-19cc-449e-a845-a174eb99fa39 | 0 | public void setGoTo(String []goTo) {
this.goTo=goTo[0];
} |
38280a7b-d911-4808-b9a0-b1957f31aa35 | 3 | public Actor remove(AdvancedLocation loc) {
switch (loc.getLayer()) {
case ActorLevel:
return super.remove(loc);
case FloorLevel:
return this.mapGrid.remove(loc);
case ObjectLevel:
return this.objectGrid.remove(loc);
default:
throw new IllegalArgumentException();
}
} |
3856e818-ab1a-45bd-bede-ab917faff543 | 8 | private static String escapeJSON(String text) {
StringBuilder builder = new StringBuilder();
builder.append('"');
for (int index = 0; index < text.length(); index++) {
char chr = text.charAt(index);
switch (chr) {
case '"':
case '\\':
builder.append('\\');
builder.append(chr);
break;
case '\b':
builder.append("\\b");
break;
case '\t':
builder.append("\\t");
break;
case '\n':
builder.append("\\n");
break;
case '\r':
builder.append("\\r");
break;
default:
if (chr < ' ') {
String t = "000" + Integer.toHexString(chr);
builder.append("\\u" + t.substring(t.length() - 4));
} else {
builder.append(chr);
}
break;
}
}
builder.append('"');
return builder.toString();
} |
f42bf744-b2bb-476d-a496-493b29dcb328 | 5 | static boolean agregarColeccion( Coleccion tipo ){
try{
if( tipo == Coleccion.CHAR)
cols[ cont ] = new ColeccionChar();
else if( tipo == Coleccion.DOUBLE )
cols[ cont ] = new ColeccionDouble();
else if( tipo == Coleccion.INTEGER )
cols[ cont ] = new ColeccionEntera();
else
cols[ cont ] = new ColeccionString();
cont++;
return true;
}
catch(ArrayIndexOutOfBoundsException a){
System.out.println("Ya no hay espacio");
}
catch(Exception e){
System.out.println("Error: " + e.getMessage());
}
return false;
} |
748d2581-11c9-4698-9345-873ae14def1d | 0 | public SaltAlgorithmIdentifierType getOtherSource() {
return otherSource;
} |
8305adb4-6b83-4c43-ab39-53b7e41e7e1d | 6 | @Override
public void consequent(CounterActionFactory CAF) {
// retrieve master name
String mName = (String) Serializer.deserialize(null, "mastername.dat");
String question = "What can I help you with?";
if (mName != null) {
question = "What can I help you with "+ mName +"?";
}
// show menu
CloudComment cc = CAF.createCloudComment(question);
SkinSwitch ss = CAF.createSkinSwitch(Emotion.happy.code);
RadioBtn menu = CAF.createRadioBtn();
menu.addOption("Would you read my comment?");
menu.addOption("Tell me something positive!");
menu.addOption("I'd like to talk with you!");
menu.addOption("Events in mind?");
cc.trigger();
ss.trigger();
menu.trigger();
int si = menu.getSelectedIndex();
if (si == -1) {
// cancelled
cc.setComment("Ohh.. ok.");
ss.setSkin(Emotion.sleepy.code);
cc.trigger();
ss.trigger();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
else if (si == 0) {
// read comment
this.readComment(CAF);
}
else if (si == 1) {
// something pos
this.somethingPositive(CAF);
}
else if (si == 2) {
// talking
this.someTalking(CAF);
}
else {
// events in mind
this.eventsInMind(CAF);
}
// get back to neutral
ss.setSkin(Emotion.neutral.code);
ss.trigger();
cc.hide();
} |
6039cde2-8059-42d0-bdc2-f59a7649198c | 9 | public static void main(String[] args){
int bufferSize=20;
Scheduler sched;
for(int iloscWatkow=10; iloscWatkow<51; iloscWatkow+=10)
{
watki++;
for(int czasMetody=0; czasMetody<101; czasMetody+=20)
{
czasy++;
System.out.println("WATKI "+ iloscWatkow + " CZAS " + czasMetody);
int howManyProducers =iloscWatkow/2, howManyConsumers=iloscWatkow/2;
int mt=czasMetody;
sched = new Scheduler(bufferSize, mt);
sched.start();
Proxy proxy = new Proxy(sched);
Thread producenci[] = new Thread[howManyProducers];
Thread konsumenci[] = new Thread[howManyConsumers];
for(int i=0; i<howManyProducers; ++i){
producenci[i] = new Producer(proxy, bufferSize/2);
}
for(int i=0; i<howManyConsumers; ++i){
konsumenci[i] = new Consumer(proxy, bufferSize/2);
}
for(int i=0; i<howManyProducers; ++i){
producenci[i].start();
}
for(int i=0; i<howManyConsumers; ++i){
konsumenci[i].start();
}
try{
if(mt==0) Thread.sleep(300);
Thread.sleep(50*mt*iloscWatkow);
}
catch(Exception e){}
for(int i=0; i<howManyProducers; ++i){
producenci[i].interrupt();
konsumenci[i].interrupt();
}
sched.interrupt();
wypisz2();
}
czasy=-1;
}
System.out.println();
System.out.println();
wypisz();
System.out.println();
wypisz2();
} |
33b238ff-58c4-4a84-a38d-34432a5a7737 | 0 | public double getSalary()
{
return salary;
} |
7d675ae9-d920-405b-b612-cfa66ce6c488 | 2 | public User findUser(String username, String password) {
String query = "SELECT * FROM user WHERE username = '%s' AND password = '%s'";
DBA dba = Helper.getDBA();
try {
ResultSet rs = dba.executeQuery(String.format(query, username, password));
while (rs.next()) {
this.ID = rs.getInt("userId");
this.userName = rs.getString("username");
this.password = rs.getString("password");
}
rs.close();
dba.closeConnections();
} catch (SQLException sqlEx) {
dba.closeConnections();
Helper.logException(sqlEx);
}
return this;
} |
0be31168-c8e6-4286-b6a0-c22e532d63f2 | 1 | protected void fireDocumentRemovedEvent(Document doc) {
removedEvent.setDocument(doc);
for (int i = 0, limit = documentRepositoryListeners.size(); i < limit; i++) {
((DocumentRepositoryListener) documentRepositoryListeners.get(i)).documentRemoved(removedEvent);
}
// Cleanup
removedEvent.setDocument(null);
} |
3c7cecd0-964c-4d4b-91dd-0e0d7d0b4d56 | 3 | public ItemSet GetUniqueItems() {
ItemSet uniqueItems = new ItemSet();/*uniquely constructed itemSet*/
for (int j = 0; j < transactionSet.size(); j++) {/*loop through the first transactionSet object*/
for (int i = 0; i < transactionSet.get(j).getTransaction().getItemSet().size(); i++) {/*doubly loop through each respective itemset in a transactionSet*/
Item item = transactionSet.get(j).getTransaction().getItemSet()
.get(i);
if (!uniqueItems.getItemSet().contains(item)) {/*Only add items if not already within the unique list. Otherwise do nothing.*/
uniqueItems.getItemSet().add(item);
}
}
}
return uniqueItems;
} |
431cb2c6-2f5a-45e7-a825-75c780958c20 | 0 | @Override
public Watcher addWatcher(String folderPath, int mask, boolean watchSubtree) throws IOException {
int watcherId = JNotify.addWatch(folderPath, mask, watchSubtree, jNotifyListener);
WatchKey watchKey = new JNotifyWatchKey(watcherId, folderPath);
Watcher watcher = new Watcher(watchKey, folderPath, mask, watchSubtree, jNotifyListener);
watcher.setWatchKey(watchKey);
LOG.info(StringUtil.concatenateStrings("A watcher was succeddfully registered. ", watcher.toString()));
return watcher;
} |
e892af2a-9922-437a-afb6-b6a4d9958e6c | 3 | private static byte[] deCrypt(byte[] cryptMsg, int Tabid){
PDU encryptedPDU = new PDU(cryptMsg, cryptMsg.length);
byte[] encryptedMsg = null;
try {
int algorithm = encryptedPDU.getByte(0);
int checksum = encryptedPDU.getByte(1);
int cryptLength = encryptedPDU.getShort(2);
int unCryptLength = encryptedPDU.getShort(4);
if(cryptLength <= encryptedPDU.length() - 8) {
encryptedMsg = encryptedPDU.getSubrange(8, cryptLength);
Crypt.decrypt(encryptedMsg, /*encryptedMsg.length*/ cryptMsg.length, catalogue.getKey(Tabid), catalogue.getKey(Tabid).length);
if (Message.div4(encryptedMsg.length) != Message.div4(unCryptLength)) {
//encryptedMsg = "INVALID KEY".getBytes();
System.out.println("Someone messed up the headers");
}
}else{
encryptedMsg = "INVALID ENCRYPTION".getBytes();
}
}catch(Exception e){
System.out.println("Someone decrypted a message wrong");
}
return encryptedMsg;
} |
31c35866-2da0-42e6-9417-7b9b5829cc4b | 6 | private Image getImage(String filename) {
// to read from file
ImageIcon icon = new ImageIcon(filename);
// try to read from URL
if ((icon == null) || (icon.getImageLoadStatus() != MediaTracker.COMPLETE)) {
try {
URL url = new URL(filename);
icon = new ImageIcon(url);
} catch (Exception e) { /* not a url */ }
}
// in case file is inside a .jar
if ((icon == null) || (icon.getImageLoadStatus() != MediaTracker.COMPLETE)) {
URL url = Draw.class.getResource(filename);
if (url == null) throw new RuntimeException("image " + filename + " not found");
icon = new ImageIcon(url);
}
return icon.getImage();
} |
55c7345a-22ff-4d4f-8e4f-a85bb83579e8 | 8 | public int convertNumber(List<String> input)
{
if(checkIfZero(input.get(0)) || input.size() < 1)
{
return 0;
}
int number = 0;
boolean negative = false;
while(!input.isEmpty())
{
if(checkIfNegative(input.get(0)))
{
negative = true;
input.remove("negative");
input.remove("minus");
}
else if(input.contains("million"))
{
number += million(input.subList(0, input.indexOf("million")));
input = input.subList(input.indexOf("million")+1, input.size());
}
else if(input.contains("thousand"))
{
number += thousand(input.subList(0, input.indexOf("thousand")));
input = input.subList(input.indexOf("thousand")+1, input.size());
}
else if(input.contains("hundred"))
{
number += hundred(input.subList(0, input.indexOf("hundred")));
input = input.subList(input.indexOf("hundred")+1, input.size());
}
else
{
number += twoDigitTypeCheck(input);
input = input.subList(0, 0);
}
}
if(negative == true)
{
number = -number;
}
return number;
} |
b3db87d4-b42b-485d-9a68-8146a0dc4130 | 8 | public Cell attackClosestUnit_(Queue<Cell> queue,
ArrayList<Cell> expandedNodes) {
Queue<Cell> newQueue = new LinkedList<Cell>();
Cell returnCell = null;
// if there are still nodes
while (!queue.isEmpty()) {
Cell currentNode = queue.poll();
Queue<Cell> nextNodes = currentNode.getSurroundingCells(map, false);
if (!expandedNodes.contains(currentNode)) {
expandedNodes.add(currentNode);
for (Cell c : nextNodes) {
if (!expandedNodes.contains(c)) {
// check cell is moveable
if (c.canMoveUnitTo(this)) {
c.setPreviousCell(currentNode);
newQueue.add(c);
} else if (c.canAttackCell(this)) {
c.setPreviousCell(currentNode);
returnCell = c;
return returnCell;
}
}
}
}
}
if (newQueue.size() == 0 || returnCell != null) {
return returnCell;
} else {
return attackClosestUnit_(newQueue, expandedNodes);
}
} |
995467d3-f87d-47a6-a09c-42fc26d04d10 | 9 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PlayerChoice other = (PlayerChoice) obj;
if (getCode() == null) {
if (other.getCode() != null)
return false;
} else if (!getCode().equals(other.getCode()))
return false;
if (getDescription() == null) {
if (other.getDescription() != null)
return false;
} else if (!getDescription().equals(other.getDescription()))
return false;
return true;
} |
dc399430-765c-4516-a93d-66830e2ad720 | 1 | public void addValidationMessage(BeamMeUpMQError errorMessage) {
if (validationErrorMessages == null) {
validationErrorMessages = new ArrayList<BeamMeUpMQError>();
}
validationErrorMessages.add(errorMessage);
} |
737be629-f2f5-43a8-a099-d9d5c6ab8fa8 | 2 | public Entity init(){
setVelocity(new Vector2f(-0.3f,0.2f));
try {
AddComponent( new ImageRenderComponent("BirdRender", new Image("assets/bird.png")) );
} catch (SlickException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Random rng = new Random(System.currentTimeMillis());
int r1 = rng.nextInt();
if(r1<0) r1*=-1;
this.setPosition(new Vector2f(SCREEN_WIDTH, Math.min(((int) r1 % SCREEN_HEIGHT) + GUI_HEIGHT + BIRD_HEIGHT, SCREEN_HEIGHT-BIRD_HEIGHT-64)));
return this;
} |
d6a9c228-7fed-422e-ad3e-d2c48821be39 | 2 | public final boolean onCommand(CommandSender sender, Command cmd,
String alias, String[] args) {
try {
Method method = this.getClass().getDeclaredMethod(cmd.getName(),
CommandSender.class, String[].class);
return (Boolean) method.invoke(this, sender, args);
} catch (InvocationTargetException e) {
plugin.error((Exception) e.getCause());
} catch (Exception e) {
plugin.error(e);
}
return false;
} |
216c925b-c534-48bd-89d5-69702a7b968d | 7 | public static String insertarRegistros( String nombreTabla, String[] camposTabla, String[] valoresTabla ) throws Exception
{
String query = "INSERT INTO " + nombreTabla;
if( camposTabla != null)
{
query += " (";
for( int i = 0; i < camposTabla.length; ++i ){
query += camposTabla[i];
if( i < camposTabla.length-1 )
query+=",";
}
query+=")";
}
query += " VALUES (";
for( int i = 0; i < valoresTabla.length; ++i ){
if(valoresTabla[i] == null||valoresTabla[i].equals("null"))
query += "NULL";
else
query += "'"+valoresTabla[i]+"'";
if(i<valoresTabla.length-1)
query+=",";
}
query += ");";
return query;
} |
5d425e1c-5e21-4516-a5a8-619de367d5af | 0 | private void jComboBoxVisiteurActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxVisiteurActionPerformed
((CtrlVisiteur)controleur).visiteurSelectionner();
}//GEN-LAST:event_jComboBoxVisiteurActionPerformed |
c9f96f4a-035b-4607-a83c-9f8987f91bd4 | 1 | private void init() {
for (int i=0; i< NUMBER_OF_EQUATION_PARAMETERS; i++) {
textFields[i] = new JTextField(TEXT_FIELD_MIN_WIDTH);
}
numberOfPointsTextField = new JTextField(TEXT_FIELD_MIN_WIDTH);
timeStepTextField = new JTextField(TEXT_FIELD_MIN_WIDTH);
timePeriodTextField = new JTextField(TEXT_FIELD_MIN_WIDTH);
numberOfSpheresTextField = new JTextField(TEXT_FIELD_MIN_WIDTH);
phiTextField = new JTextField(TEXT_FIELD_MIN_WIDTH);
psiTextField = new JTextField(TEXT_FIELD_MIN_WIDTH);
thetaTextField = new JTextField(TEXT_FIELD_MIN_WIDTH);
drawButton = new JButton("Draw!");
resetButton = new JButton("Reset");
resetButton.setToolTipText("Reset all values to default");
integrationMethodsComboBox = new JComboBox<>(IntegrationMethods.values());
integrationMethodsComboBox.setEditable(false);
angleComboBox = new JComboBox<>(Angle.values());
angleComboBox.setEditable(false);
} |
e8987dcd-7cf0-4335-b441-669b97e86526 | 8 | public static String propositiontoString(Proposition p){
switch(p){
case IS_FRONT_CLEAR: return "Front is Clear";
case IS_LEFT_CLEAR: return "Left is Clear";
case IS_RIGHT_CLEAR: return "Right is Clear";
case IS_FACING_NORTH: return "Facing North";
case IS_FACING_SOUTH: return "Facing South";
case IS_FACING_EAST: return "Facing East";
case IS_FACING_WEST: return "Facing West";
case NEXT_TO_BEEPER: return "Next to a Beeper";
}
return null;
} |
91c04c6f-4063-4b4f-957a-fe78fa2f3c1a | 9 | final public int writeVarLong (long value, boolean optimizePositive) throws KryoException {
if (!optimizePositive) value = (value << 1) ^ (value >> 63);
int varInt = 0;
varInt = (int)(value & 0x7F);
value >>>= 7;
if (value == 0) {
write(varInt);
return 1;
}
varInt |= 0x80;
varInt |= ((value & 0x7F) << 8);
value >>>= 7;
if (value == 0) {
writeLittleEndianInt(varInt);
position -= 2;
return 2;
}
varInt |= (0x80 << 8);
varInt |= ((value & 0x7F) << 16);
value >>>= 7;
if (value == 0) {
writeLittleEndianInt(varInt);
position -= 1;
return 3;
}
varInt |= (0x80 << 16);
varInt |= ((value & 0x7F) << 24);
value >>>= 7;
if (value == 0) {
writeLittleEndianInt(varInt);
position -= 0;
return 4;
}
varInt |= (0x80 << 24);
long varLong = (varInt & 0xFFFFFFFFL) | (((long)(value & 0x7F)) << 32);
value >>>= 7;
if (value == 0) {
writeLittleEndianLong(varLong);
position -= 3;
return 5;
}
varLong |= (0x80L << 32);
varLong |= (((long)(value & 0x7F)) << 40);
value >>>= 7;
if (value == 0) {
writeLittleEndianLong(varLong);
position -= 2;
return 6;
}
varLong |= (0x80L << 40);
varLong |= (((long)(value & 0x7F)) << 48);
value >>>= 7;
if (value == 0) {
writeLittleEndianLong(varLong);
position -= 1;
return 7;
}
varLong |= (0x80L << 48);
varLong |= (((long)(value & 0x7F)) << 56);
value >>>= 7;
if (value == 0) {
writeLittleEndianLong(varLong);
return 8;
}
varLong |= (0x80L << 56);
writeLittleEndianLong(varLong);
write((byte)((value & 0x7F)));
return 9;
} |
0f81bd4c-005d-4115-8963-5cdff6ad41bf | 2 | private String readAxiom(Document document) {
NodeList list = document.getDocumentElement().getElementsByTagName(
AXIOM_NAME);
if (list.getLength() < 1)
throw new ParseException("No axiom specified in the document!");
String axiom = containedText(list.item(list.getLength() - 1));
if (axiom == null)
axiom = "";
return axiom;
} |
632120cd-6096-4723-a8d6-7589660192b6 | 3 | private List<Entry<Integer, Object[]>> createQueryParametersList(E value) {
ClassInspect inspector = getClassInspector();
List<Entry<Integer,Object[]>> queryParameterValues = new LinkedList<Entry<Integer,Object[]>>();
List<Field> annotatedFields = inspector.findAllAnnotatedFields(Column.class);
int columnCount = 0;
for(Field field : annotatedFields) {
if(hasIgnoredAnnotation(field)) {
logger.debug("Field <" + field.getName() + "> has @Generated annotation. Ignoring for Insert Query");
continue;
}
Column annotation = field.getAnnotation(Column.class);
if(annotation == null) {
logger.debug("Field <" + field.getName() + "> has no @Column annotation. Ignoring for Insert Query");
continue;
}
columnCount++;
Method getMethod = inspector.findGetMethod(field);
Object getValue = inspector.executeGetMethod(value, getMethod);
Entry<Integer,Object[]> entry = new SimpleEntry<Integer,Object[]>(columnCount, new Object[] {field,getValue});
queryParameterValues.add(entry);
}
return queryParameterValues;
} |
1f596f58-57b5-4fac-b76d-cde9a9528f88 | 2 | private static String readFile(String filePath) {
Logger.log("Opening file " + filePath);
File file = new File(filePath);
assert file.exists();
assert file.isFile();
assert file.canRead();
Scanner s = null;
try {
s = new Scanner(file);
} catch (FileNotFoundException e) {
Logger.log("Error reading file " + filePath, Logger.ERROR);
e.printStackTrace();
}
assert s != null;
String out = "";
while (s.hasNextLine()) {
out += s.nextLine() + "\n";
}
return out;
} |
a17a7f43-1b54-462b-b27d-7320050922a5 | 9 | public boolean run() {
PrintStream original = System.out;
PrintStream noPrint = new PrintStream(new OutputStream() {
public void write(int b) {}
});
try {
Method m[] = this.getClass().getDeclaredMethods(); // Get all methods
for( Method i : m ) {
if( i.getName().startsWith("test") ) { // If it starts with the prefix test
currentTest = true;
Boolean thrown = false; // If the test threw an exception
try {
if( suppress_prints ) {
System.setOut(noPrint);
}
i.invoke(this);
System.setOut(original);
} catch( Throwable t ) {
System.setOut(original);
thrown = true;
System.out.print("E");
String new_message = "\t" + i.getName() + " threw an exception\n";
new_message += "\t\t" + t.toString() + "\n";
Throwable cause = t.getCause();
while( cause != null ) {
new_message += "\t\t\t" + cause.toString() + "\n";
cause = cause.getCause();
}
addMessage(new_message);
this.failCount++;
}
if( !this.currentTest ) { // If the current test failed
System.out.print("F");
this.failCount++;
} else if(!thrown) {
System.out.print(".");
}
this.finalizeMessages(i.getName());
}
}
System.out.println("");
if( this.failCount > 0 ) {
printMessages();
System.out.println("");
System.out.println("[FAILED COUNT=" + this.failCount + "]");
return false;
}
} catch (Exception e) {
e.printStackTrace();
}
return true;
} |
02050374-cf69-46d1-aa41-5681cb5f2c85 | 3 | private boolean isReady(Document doc)
throws Exception {
if (props.getProperty("checkPagePDFExists", "false").equalsIgnoreCase("true")) {
// check if PDF for the page exists
String strPagePDF = "";
NodeList nl = (NodeList) xp.evaluate("//NewsItem[NewsManagement/NewsItemType/@FormalName='Page']"
+ "/NewsComponent/NewsComponent/ContentItem/@Href",
doc, XPathConstants.NODESET);
if (nl.getLength() == 1)
strPagePDF = nl.item(0).getTextContent();
strPagePDF = props.getProperty("xslt.param.pagePDFPath") + strPagePDF;
File pagePDF = new File(strPagePDF);
if (!pagePDF.exists()) {
logger.warning("Page PDF " + strPagePDF + " does not exist. Page and its contents will not be exported.");
return false;
}
else
logger.finer("Page PDF " + strPagePDF + " exists.");
}
return true;
} |
d4a499ac-1484-41df-9f59-86a224d99305 | 8 | public static ArrayList<Double> firstXPrimeNumbers(double number) throws MathException{
ArrayList<Double> primes = new ArrayList<Double>();
boolean prime = true;
double sqRoot;
//Error detected
if(number < 1){
throw new MathException("Invalid input, minamum is 1");
}
primes.add(2.0);
//Logic exception: For single prime, must return here
if(number == 1){
return primes;
}
for(double potentialPrime = 3; primes.size() < number; potentialPrime++){
prime = true;
if((potentialPrime % 2) == 0){
continue;
}
sqRoot = Math.sqrt(potentialPrime);
for(int primeIndex = 1; primeIndex < primes.size(); primeIndex++){
if(primes.get(primeIndex) > sqRoot){
break;
}
if((potentialPrime % primes.get(primeIndex)) == 0){
prime = false;
break;
}
}
if(prime){
primes.add(potentialPrime);
}
}
return primes;
} |
ac51f33e-11b0-484b-8f2d-740bc2107c39 | 9 | public Equipa(String codigo,String nome,String Escalao, String cod_Escola) {
this.codEquipa = codigo;
this.nome = nome;
this.codEscola = cod_Escola;
this.DAOJogador = new DAOJogador();
switch (Escalao) {
case "Escalao.EscolaA":
escalao = new EscolaA();
break;
case "Escalao.EscolaB":
escalao = new EscolaB();
break;
case "Escalao.InfantisA":
escalao = new InfantisA();
break;
case "Escalao.InfantisB":
escalao = new InfantisB();
break;
case "Escalao.IniciadosA":
escalao = new IniciadosA();
break;
case "Escalao.IniciadosB":
escalao = new IniciadosB();
break;
case "Escalao.MinisA":
escalao = new MinisA();
break;
case "Escalao.MinisB":
escalao = new MinisB();
break;
case "Escalao.PreEscolaA":
escalao = new PreEscolaA();
break;
default:
//(Escalao.equals("Escalao.PreEscolaB")) {
escalao = new PreEscolaB();
break;
}
} |
4dc3889d-42d2-4eb4-8bc7-2c4e00fb7744 | 9 | public Instances transform(Instances train) throws Exception{
Attribute classAttribute = (Attribute) train.classAttribute().copy();
Attribute bagLabel = (Attribute) train.attribute(0);
double labelValue;
Instances newData = train.attribute(1).relation().stringFreeStructure();
//insert a bag label attribute at the begining
newData.insertAttributeAt(bagLabel, 0);
//insert a class attribute at the end
newData.insertAttributeAt(classAttribute, newData.numAttributes());
newData.setClassIndex(newData.numAttributes()-1);
Instances mini_data = newData.stringFreeStructure();
Instances max_data = newData.stringFreeStructure();
Instance newInst = new Instance (newData.numAttributes());
Instance mini_Inst = new Instance (mini_data.numAttributes());
Instance max_Inst = new Instance (max_data.numAttributes());
newInst.setDataset(newData);
mini_Inst.setDataset(mini_data);
max_Inst.setDataset(max_data);
double N= train.numInstances( );//number of bags
for(int i=0; i<N; i++){
int attIdx =1;
Instance bag = train.instance(i); //retrieve the bag instance
labelValue= bag.value(0);
if (m_TransformMethod != TRANSFORMMETHOD_MINIMAX)
newInst.setValue(0, labelValue);
else {
mini_Inst.setValue(0, labelValue);
max_Inst.setValue(0, labelValue);
}
Instances data = bag.relationalValue(1); // retrieve relational value for each bag
for(int j=0; j<data.numAttributes( ); j++){
double value;
if(m_TransformMethod == TRANSFORMMETHOD_ARITHMETIC){
value = data.meanOrMode(j);
newInst.setValue(attIdx++, value);
}
else if (m_TransformMethod == TRANSFORMMETHOD_GEOMETRIC){
double[] minimax = minimax(data, j);
value = (minimax[0]+minimax[1])/2.0;
newInst.setValue(attIdx++, value);
}
else { //m_TransformMethod == TRANSFORMMETHOD_MINIMAX
double[] minimax = minimax(data, j);
mini_Inst.setValue(attIdx, minimax[0]);//minima value
max_Inst.setValue(attIdx, minimax[1]);//maxima value
attIdx++;
}
}
if (m_TransformMethod == TRANSFORMMETHOD_MINIMAX) {
if (!bag.classIsMissing())
max_Inst.setClassValue(bag.classValue()); //set class value
mini_data.add(mini_Inst);
max_data.add(max_Inst);
}
else{
if (!bag.classIsMissing())
newInst.setClassValue(bag.classValue()); //set class value
newData.add(newInst);
}
}
if (m_TransformMethod == TRANSFORMMETHOD_MINIMAX) {
mini_data.setClassIndex(-1);
mini_data.deleteAttributeAt(mini_data.numAttributes()-1); //delete class attribute for the minima data
max_data.deleteAttributeAt(0); // delete the bag label attribute for the maxima data
newData = Instances.mergeInstances(mini_data, max_data); //merge minima and maxima data
newData.setClassIndex(newData.numAttributes()-1);
}
return newData;
} |
71d15b5f-b9c9-4f7b-96cc-8a8dbfaaaeae | 5 | public static void spielendeabrechnung() throws IOException {
if(punktespieler1 > punktespieler2 + 20) {
System.out.println("("+ausgabenummer+") "+spielername1+" gewinnt die Partie hochverdient!"); ausgabenummer += 1;
System.out.println("("+ausgabenummer+") "+"Er gewinnt mit "+punktespieler1+" zu "+punktespieler2+ " Punkten."); ausgabenummer += 1;
JOptionPane.showMessageDialog(null, "Das Spiel ist beendet!\n"+spielername1+" gewinnt deutlich mit "+punktespieler1+" zu "+punktespieler2+"\nHerzlichen Glückwunsch!", spielername1+" gewinnt", JOptionPane.INFORMATION_MESSAGE);
}
else if(punktespieler1 > punktespieler2) {
System.out.println("("+ausgabenummer+") "+spielername1+" gewinnt die Partie mit knappem Vorsprung!"); ausgabenummer += 1;
System.out.println("("+ausgabenummer+") "+"Er gewinnt mit "+punktespieler1+" zu "+punktespieler2+ " Punkten."); ausgabenummer += 1;
JOptionPane.showMessageDialog(null, "Das Spiel ist beendet!\n"+spielername1+" gewinnt knapp mit "+punktespieler1+" zu "+punktespieler2+"\nHerzlichen Glückwunsch!", spielername1+" gewinnt", JOptionPane.INFORMATION_MESSAGE);
}
else if(punktespieler1 == punktespieler2) {
System.out.println("("+ausgabenummer+") "+"Die Partie endet mit einem Remis."); ausgabenummer += 1;
System.out.println("("+ausgabenummer+") "+"Beide Spieler erreichten eine Punktzahl von "+punktespieler1+" Punkten."); ausgabenummer += 1;
}
else if(punktespieler1 + 20 < punktespieler2) {
System.out.println("("+ausgabenummer+") "+spielername2+" gewinnt die Partie hochverdient!"); ausgabenummer += 1;
System.out.println("("+ausgabenummer+") "+"Er gewinnt mit "+punktespieler2+" zu "+punktespieler1+ " Punkten."); ausgabenummer += 1;
JOptionPane.showMessageDialog(null, "Das Spiel ist beendet!\n"+spielername2+" gewinnt deutlich mit "+punktespieler2+" zu "+punktespieler1+"\nHerzlichen Glückwunsch!", spielername2+" gewinnt", JOptionPane.INFORMATION_MESSAGE);
}
else if(punktespieler1 < punktespieler2) {
System.out.println("("+ausgabenummer+") "+spielername2+" gewinnt die Partie mit knappem Vorsprung!"); ausgabenummer += 1;
System.out.println("("+ausgabenummer+") "+"Er gewinnt mit "+punktespieler2+" zu "+punktespieler1+ " Punkten."); ausgabenummer += 1;
JOptionPane.showMessageDialog(null, "Das Spiel ist beendet!\n"+spielername2+" gewinnt knapp mit "+punktespieler2+" zu "+punktespieler1+"\nHerzlichen Glückwunsch!", spielername2+" gewinnt", JOptionPane.INFORMATION_MESSAGE);
}
else{
System.out.println("("+ausgabenummer+") "+"Es ist etwas schiefgelaufen. Bitte starte das Spiel neu."); ausgabenummer += 1;
System.exit(0);
}
} |
258ac9d0-3ca9-4e78-a469-c6c9bfaeabb3 | 3 | public Integer getMatchName(String matchvalue) {
if (this.getMatchSring().equals(matchvalue)) {
return string_name;
}
if (this.getMatchNum().equals(matchvalue)) {
return num_name;
}
if (this.getMatchOperacion().equals(matchvalue)) {
return operador_name;
}
return begin;
} |
89ce4ca3-3aae-492f-9de0-501f38cbfe87 | 0 | @Test
public void testCalculateTotal() throws Exception {
BigDecimal bdRes;
this.terminal.scan("ABCDABA");
BigDecimal bd1 = BigDecimal.valueOf(13.25);
bd1 = bd1.setScale(2,BigDecimal.ROUND_HALF_DOWN);
bdRes = terminal.calculateTotal();
assertTrue(bd1.equals(bdRes));
this.terminal.scan("CCCCCCC");
BigDecimal bd2 = BigDecimal.valueOf(6.00);
bd2 = bd2.setScale(2,BigDecimal.ROUND_HALF_DOWN);
bdRes = terminal.calculateTotal();
assertTrue(bd2.equals(bdRes));
this.terminal.scan("ABCD");
BigDecimal bd3 = BigDecimal.valueOf(7.25);
bd3 = bd3.setScale(2,BigDecimal.ROUND_HALF_DOWN);
bdRes = terminal.calculateTotal();
assertTrue(bd3.equals(bdRes));
} |
9634d959-963f-4dcd-a64b-8dadb3eaa298 | 1 | public void setTipoPasajero(String tipoPasajero) {
if (tipoPasajero.length() <= 3) {
this.tipoPasajero = tipoPasajero.trim();
}else{
this.tipoPasajero = "ADT";
}
} |
d9950a70-453f-4f9a-9ab1-f11f9ace49b4 | 7 | public void add_all_features(String[] features_string){
for(int i=0;i<features_string.length;i++){
String[] feature_parsed= features_string[i].replace(":", " ").trim().split("\\s+");
int f_id= Integer.parseInt(feature_parsed[0]);
if(!index){
feat_present.add(f_id); // uncomment if not required
}
double f_val= Double.parseDouble(feature_parsed[1]);
feat_sum+=f_val;
// only during indexing step
if(index){
if(!f_points.containsKey(f_id)){
f_points.put(f_id,1); //Check this
invert_index.put(f_id, new HashMap<Integer,Double>());
}
else {
f_points.put(f_id,f_points.get(f_id)+1);
}
if(!mn_ft_allpts_infeat.containsKey(f_id)){
mn_ft_allpts_infeat.put(f_id, features_string.length);
mx_ft_allpts_infeat.put(f_id, features_string.length);
/***non-binary***/
if(non_bin){
min_ft_val.put(f_id, f_val);
max_ft_val.put(f_id, f_val);
}
/***/
}
else{
mn_ft_allpts_infeat.put(f_id, Math.min(features_string.length, mn_ft_allpts_infeat.get(f_id)));
mx_ft_allpts_infeat.put(f_id, Math.max(features_string.length, mx_ft_allpts_infeat.get(f_id)));
/***non-binary***/
if(non_bin){
min_ft_val.put(f_id, Math.min(f_val, min_ft_val.get(f_id)));
max_ft_val.put(f_id, Math.max(f_val, max_ft_val.get(f_id)));
}
/***/
}
invert_index.get(f_id).put(this.id, f_val);
}
/**/
feature_map.put(f_id, f_val);
/**/
}
this.feature_size=features_string.length;
//System.out.println(this.feature_size);
} |
c0d7821a-8090-49b1-ba91-48373db62ca1 | 0 | public int getMaxRound()
{
return maxRound;
} |
526a5130-a5de-4c66-9ee9-ebb43f96a917 | 8 | @Override
public void run() {
boolean error = false;
_shouldStop = false;
System.err.println("Sugar interpreter started");
if (null != _listener) {
_listener.interpreterStarted(this);
}
try {
Environment e = _rootEnvironment;
e.pushReader("bootstrap");
e.pushOp("read");
e.evaluateStack();
do {
e.pushReader("discriminator");
e.pushOp("read");
while(!_rootEnvironment.isStackEmpty()) {
if (_shouldStop) {
throw new Exception("The interpreter has been stopped");
}
IOp op = _rootEnvironment.evaluateStack();
if (null == op) {
break;
}
// TODO: Error should be a TYPE, not an op. There should be a "throw"
// op that does this itself
if (op instanceof org.sugarlang.op.Error) {
System.err.println("SUGAR STACK:");
_rootEnvironment.printStack(System.err);
error = true;
throw new Exception("A Sugar Error was thrown");
}
}
} while (true);
} catch (Exception e) {
System.err.println("The interpreter has terminated");
if (error) {
e.printStackTrace(System.err);
}
}
} |
0eec7c13-ae77-412c-9c81-64f1c0dbc09e | 4 | public static Attribute getSetting(PrintService service, PrintRequestAttributeSet set, Class<? extends Attribute> type, boolean tryDefaultIfNull) {
Attribute attribute = set.get(type);
if (tryDefaultIfNull && attribute == null && service != null) {
attribute = (Attribute) service.getDefaultAttributeValue(type);
}
return attribute;
} |
3aeeedcd-8048-4039-b066-75d858366020 | 8 | private final boolean tryReadPacket(final SelectionKey key, final T client, final ByteBuffer buf, final MMOConnection<T> con)
{
switch (buf.remaining())
{
case 0:
// buffer is full
// nothing to read
return false;
case 1:
// we don`t have enough data for header so we need to read
key.interestOps(key.interestOps() | SelectionKey.OP_READ);
// did we use the READ_BUFFER ?
if (buf == READ_BUFFER)
{
// move the pending byte to the connections READ_BUFFER
allocateReadBuffer(con);
}
else
{
// move the first byte to the beginning :)
buf.compact();
}
return false;
default:
// data size excluding header size :>
final int dataPending = (buf.getShort() & 0xFFFF) - HEADER_SIZE;
// do we got enough bytes for the packet?
if (dataPending <= buf.remaining())
{
// avoid parsing dummy packets (packets without body)
if (dataPending > 0)
{
final int pos = buf.position();
parseClientPacket(pos, buf, dataPending, client);
buf.position(pos + dataPending);
}
// if we are done with this buffer
if (!buf.hasRemaining())
{
if (buf != READ_BUFFER)
{
con.setReadBuffer(null);
recycleBuffer(buf);
}
else
{
READ_BUFFER.clear();
}
return false;
}
return true;
}
// we don`t have enough bytes for the dataPacket so we need
// to read
key.interestOps(key.interestOps() | SelectionKey.OP_READ);
// did we use the READ_BUFFER ?
if (buf == READ_BUFFER)
{
// move it`s position
buf.position(buf.position() - HEADER_SIZE);
// move the pending byte to the connections READ_BUFFER
allocateReadBuffer(con);
}
else
{
buf.position(buf.position() - HEADER_SIZE);
buf.compact();
}
return false;
}
} |
802b8676-64c3-4c0b-85a0-5788d4812b71 | 3 | private void copyPALtoRGBA(ByteBuffer buffer, byte[] curLine) {
if(paletteA != null) {
for(int i=1,n=curLine.length ; i<n ; i+=1) {
int idx = curLine[i] & 255;
byte r = palette[idx*3 + 0];
byte g = palette[idx*3 + 1];
byte b = palette[idx*3 + 2];
byte a = paletteA[idx];
buffer.put(r).put(g).put(b).put(a);
}
} else {
for(int i=1,n=curLine.length ; i<n ; i+=1) {
int idx = curLine[i] & 255;
byte r = palette[idx*3 + 0];
byte g = palette[idx*3 + 1];
byte b = palette[idx*3 + 2];
byte a = (byte)0xFF;
buffer.put(r).put(g).put(b).put(a);
}
}
} |
12d1d3b3-e5e2-4dce-a5f5-0ed11a978421 | 3 | @Override
public void draw(Graphics2D g2d) {
for (int i = 0; i < fireBalls.size(); i++)
fireBalls.get(i).render(g2d);
if (flinching) {
long elapsed = (System.nanoTime() - flinchTimer) / 1000000;
if (elapsed / 100 % 2 == 0) return;
}
} |
473e962d-c627-477c-a7f9-6eb6b8285709 | 0 | static void tune(Instrument i) {
// ...
i.play(Note.MIDDLE_C);
} |
7ec479fc-4c2b-4121-9d64-0f402e721c01 | 3 | @Override
public AbstractComponent parse(String string) throws BookParseException {
if (string == null) {
throw new BookParseException("String is null");
}
try {
TextComponent component = (TextComponent) factory
.newComponent(EComponentType.LISTING);
for (String s : string.split(LINE_REGEX)) {
component.addComponent(codeLineParser.parse(s));
}
return component;
} catch (ComponentException e) {
throw new BookParseException("Listing parse failed", e);
}
} |
2c849547-211d-40a9-960a-7a80465c0ea6 | 3 | public void insertSupplierAmount(supplier tempSupplier) throws SQLException{
try {
databaseConnector = myConnector.getConnection();
SQLQuery = "INSERT INTO familydoctor.supplier "+"VALUES(?,?,?,?)";
PreparedStatement preparedStatement = databaseConnector.prepareStatement(SQLQuery);
preparedStatement.setString(1, tempSupplier.getName());
preparedStatement.setString(2, tempSupplier.getContactDetails());
preparedStatement.setInt(3, tempSupplier.getPhnNo());
preparedStatement.setString(4, tempSupplier.getMail());
preparedStatement.executeUpdate();
}
catch (SQLException e) {
System.out.println(e.getMessage());
}
finally {
if (stmnt != null) {
stmnt.close();
}
if (databaseConnector != null) {
databaseConnector.close();
}
}
} |
0a8492ab-929e-458e-9be3-46e24952aa15 | 2 | public static boolean isNullOrEmpty(String input) {
return (input == null ? true : (input.length() <= 0 ? true : false));
} |
856c78c9-030a-4b2a-bec6-747abe33e90b | 8 | @Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
JTree tree = MainFrame.dataTree;
DefaultMutableTreeNode selectNode = (DefaultMutableTreeNode) tree
.getLastSelectedPathComponent();
int nodeLevel = selectNode.getLevel();
if (nodeLevel == 1) {
// 删除数据库
if (e.getActionCommand().equals(StringConstants.DELETE_DATABASE)) {
DefaultMutableTreeNode root = (DefaultMutableTreeNode) tree
.getModel().getRoot();
String dataName = (String) selectNode.getUserObject();
selectNode.removeAllChildren();
root.remove(selectNode);
tree.updateUI();
//删除本的地记录
String connInfo = MyUtils.readFile(FileString.FILEPATH + "connect_info.con");
if(!connInfo.equals("")){
String[] info = connInfo.split(",");
String result = "";
for(int i= 0;i<info.length;i++){
String[] infos = info[i].split("#");
if(infos[0].equals(dataName)){
continue;
}
result = result + info[i] + ",";
}
MyUtils.writeFile(result, "connect_info.con", FileString.FILEPATH);
}
} else if(e.getActionCommand().equals(StringConstants.REFRESH)) {
//刷新数据库
String dataName = (String)selectNode.getUserObject();
MainFrameManager mainFrameManager = MainFrameManager.getInstance();
mainFrameManager.refreshDataBase(dataName, selectNode);
} else if(e.getActionCommand().equals(StringConstants.BUILD_CODE)) {
OutputDialog dialog = new OutputDialog();
dialog.showDialog(MainFrame.mainFrame,(String)selectNode.getUserObject());
}
} else if(nodeLevel == 2){
}
} |
624af31d-a286-44b9-971a-394b1506bd6d | 0 | public static int hellingerDist(int color1, int color2) {
double dRed = Math.pow( Math.sqrt((color1 & RED_MASK) >> 16) - Math.sqrt((color2 & RED_MASK) >> 16),2);
double dGreen = Math.pow( Math.sqrt((color1 & GREEN_MASK) >> 8) - Math.sqrt((color2 & GREEN_MASK) >> 8),2);
double dBlue = Math.pow( Math.sqrt(color1 & BLUE_MASK) - Math.sqrt(color2 & BLUE_MASK),2);
double dist = (1/Math.sqrt(2))*Math.sqrt(dRed + dGreen + dBlue);
return (int)dist;
} |
04182226-2bbf-455d-9136-ff4f3a353a1f | 2 | public void visitIfCmpStmt(final IfCmpStmt stmt) {
if (stmt.right() == previous) {
check(stmt.left());
} else if (stmt.left() == previous) {
previous = stmt;
stmt.parent().visit(this);
}
} |
72962c88-16c4-4a4b-bf67-69baa36a614e | 8 | @Override
void insert() {
int ccid = -1; //1
int cphone = -1; //5
PreparedStatement ps;
BufferedReader in = new BufferedReader((new InputStreamReader(System.in)));
try {
Statement stmt = con.createStatement();
ResultSet rs;
System.out.println("Enter the Customer Id: ");
int cid = Integer.parseInt(in.readLine());
rs = stmt.executeQuery("SELECT customer_cid FROM Customer WHERE customer_cid = " + cid);
while (rs.next()) {
if (!rs.getString("customer_cid").isEmpty()){
System.out.println("Customer Id is taken. Please enter another one.");
this.insert();
}
}
} catch (SQLException e1) {
e1.printStackTrace();
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
ps = con.prepareStatement("INSERT INTO Customer VALUES (?,?,?,?,?)");
setNull(ps, askUser(in, "Customer ID: "), true, 1, ccid);
setNull(ps, askUser(in, "Customer Password: "), false, 2);
setNull(ps, askUser(in, "Customer Name: "), false, 3);
setNull(ps, askUser(in, "Customer Address: "), false, 4);
setNull(ps, askUser(in, "Customer Phone: "), false, 5, cphone);
ps.executeUpdate();
// commit work
con.commit();
ps.close();
} catch (IOException e) {
System.out.println("IOException!");
} catch (SQLException ex) {
System.out.println("Message: " + ex.getMessage());
try {
// undo the insert
con.rollback();
} catch (SQLException ex2) {
System.out.println("Message: " + ex2.getMessage());
System.exit(-1);
}
}
} |
13fca788-5e72-46c9-a09a-3ec8890e7691 | 0 | public String getSex() {
return sex;
} |
ff381ce0-244d-45f4-85d8-8a3ea39a6b0f | 9 | private void collectiveInstinctiveMovement() {
double[] m = new double[dimensions];
double totalFitness = 0;
// calculating m, the weighted average of individual movements
for (int i = 0; i < school.size(); i++) {
Fish _fish = school.get(i);
for (int j = 0; j < dimensions; j++) {
m[j] += _fish.getDeltaPosition()[j] * _fish.getDeltaFitness();
}
totalFitness += _fish.getDeltaFitness();
}
// avoid division by 0
if (totalFitness == 0) {
return;
}
for (int i = 0; i < dimensions; i++) {
m[i] /= totalFitness;
}
// applying m
for (int i = 0; i < school.size(); i++) {
Fish _fish = school.get(i);
double[] schoolInstinctivePosition = new double[dimensions];
for (int j = 0; j < dimensions; j++) {
schoolInstinctivePosition[j] = _fish.getPosition()[j] + m[j];
boolean collision = schoolInstinctivePosition[j] < -RANGE || schoolInstinctivePosition[j] > RANGE;
if (collision)
{
schoolInstinctivePosition[j] = schoolInstinctivePosition[j] > 0 ? RANGE : - RANGE;
}
}
_fish.setPosition(schoolInstinctivePosition);
}
} |
797199ee-ea32-49f5-ae41-232046c3867a | 6 | public void test() throws IOException {
FieldCache cache = FieldCache.DEFAULT;
double [] doubles = cache.getDoubles(reader, "theDouble");
assertSame("Second request to cache return same array", doubles, cache.getDoubles(reader, "theDouble"));
assertSame("Second request with explicit parser return same array", doubles, cache.getDoubles(reader, "theDouble", FieldCache.DEFAULT_DOUBLE_PARSER));
assertTrue("doubles Size: " + doubles.length + " is not: " + NUM_DOCS, doubles.length == NUM_DOCS);
for (int i = 0; i < doubles.length; i++) {
assertTrue(doubles[i] + " does not equal: " + (Double.MAX_VALUE - i), doubles[i] == (Double.MAX_VALUE - i));
}
long [] longs = cache.getLongs(reader, "theLong");
assertSame("Second request to cache return same array", longs, cache.getLongs(reader, "theLong"));
assertSame("Second request with explicit parser return same array", longs, cache.getLongs(reader, "theLong", FieldCache.DEFAULT_LONG_PARSER));
assertTrue("longs Size: " + longs.length + " is not: " + NUM_DOCS, longs.length == NUM_DOCS);
for (int i = 0; i < longs.length; i++) {
assertTrue(longs[i] + " does not equal: " + (Long.MAX_VALUE - i), longs[i] == (Long.MAX_VALUE - i));
}
byte [] bytes = cache.getBytes(reader, "theByte");
assertSame("Second request to cache return same array", bytes, cache.getBytes(reader, "theByte"));
assertSame("Second request with explicit parser return same array", bytes, cache.getBytes(reader, "theByte", FieldCache.DEFAULT_BYTE_PARSER));
assertTrue("bytes Size: " + bytes.length + " is not: " + NUM_DOCS, bytes.length == NUM_DOCS);
for (int i = 0; i < bytes.length; i++) {
assertTrue(bytes[i] + " does not equal: " + (Byte.MAX_VALUE - i), bytes[i] == (byte) (Byte.MAX_VALUE - i));
}
short [] shorts = cache.getShorts(reader, "theShort");
assertSame("Second request to cache return same array", shorts, cache.getShorts(reader, "theShort"));
assertSame("Second request with explicit parser return same array", shorts, cache.getShorts(reader, "theShort", FieldCache.DEFAULT_SHORT_PARSER));
assertTrue("shorts Size: " + shorts.length + " is not: " + NUM_DOCS, shorts.length == NUM_DOCS);
for (int i = 0; i < shorts.length; i++) {
assertTrue(shorts[i] + " does not equal: " + (Short.MAX_VALUE - i), shorts[i] == (short) (Short.MAX_VALUE - i));
}
int [] ints = cache.getInts(reader, "theInt");
assertSame("Second request to cache return same array", ints, cache.getInts(reader, "theInt"));
assertSame("Second request with explicit parser return same array", ints, cache.getInts(reader, "theInt", FieldCache.DEFAULT_INT_PARSER));
assertTrue("ints Size: " + ints.length + " is not: " + NUM_DOCS, ints.length == NUM_DOCS);
for (int i = 0; i < ints.length; i++) {
assertTrue(ints[i] + " does not equal: " + (Integer.MAX_VALUE - i), ints[i] == (Integer.MAX_VALUE - i));
}
float [] floats = cache.getFloats(reader, "theFloat");
assertSame("Second request to cache return same array", floats, cache.getFloats(reader, "theFloat"));
assertSame("Second request with explicit parser return same array", floats, cache.getFloats(reader, "theFloat", FieldCache.DEFAULT_FLOAT_PARSER));
assertTrue("floats Size: " + floats.length + " is not: " + NUM_DOCS, floats.length == NUM_DOCS);
for (int i = 0; i < floats.length; i++) {
assertTrue(floats[i] + " does not equal: " + (Float.MAX_VALUE - i), floats[i] == (Float.MAX_VALUE - i));
}
} |
1e195f3b-550f-426e-a1a0-94da0a37e7da | 9 | public boolean addComponentParts(World par1World, Random par2Random, StructureBoundingBox par3StructureBoundingBox)
{
if (isLiquidInStructureBoundingBox(par1World, par3StructureBoundingBox))
{
return false;
}
byte byte0 = 11;
if (!isLargeRoom)
{
byte0 = 6;
}
fillWithRandomizedBlocks(par1World, par3StructureBoundingBox, 0, 0, 0, 13, byte0 - 1, 14, true, par2Random, StructureStrongholdPieces.getStrongholdStones());
placeDoor(par1World, par2Random, par3StructureBoundingBox, doorType, 4, 1, 0);
randomlyFillWithBlocks(par1World, par3StructureBoundingBox, par2Random, 0.07F, 2, 1, 1, 11, 4, 13, Block.web.blockID, Block.web.blockID, false);
for (int i = 1; i <= 13; i++)
{
if ((i - 1) % 4 == 0)
{
fillWithBlocks(par1World, par3StructureBoundingBox, 1, 1, i, 1, 4, i, Block.planks.blockID, Block.planks.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 12, 1, i, 12, 4, i, Block.planks.blockID, Block.planks.blockID, false);
placeBlockAtCurrentPosition(par1World, Block.torchWood.blockID, 0, 2, 3, i, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.torchWood.blockID, 0, 11, 3, i, par3StructureBoundingBox);
if (isLargeRoom)
{
fillWithBlocks(par1World, par3StructureBoundingBox, 1, 6, i, 1, 9, i, Block.planks.blockID, Block.planks.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 12, 6, i, 12, 9, i, Block.planks.blockID, Block.planks.blockID, false);
}
continue;
}
fillWithBlocks(par1World, par3StructureBoundingBox, 1, 1, i, 1, 4, i, Block.bookShelf.blockID, Block.bookShelf.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 12, 1, i, 12, 4, i, Block.bookShelf.blockID, Block.bookShelf.blockID, false);
if (isLargeRoom)
{
fillWithBlocks(par1World, par3StructureBoundingBox, 1, 6, i, 1, 9, i, Block.bookShelf.blockID, Block.bookShelf.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 12, 6, i, 12, 9, i, Block.bookShelf.blockID, Block.bookShelf.blockID, false);
}
}
for (int j = 3; j < 12; j += 2)
{
fillWithBlocks(par1World, par3StructureBoundingBox, 3, 1, j, 4, 3, j, Block.bookShelf.blockID, Block.bookShelf.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 6, 1, j, 7, 3, j, Block.bookShelf.blockID, Block.bookShelf.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 9, 1, j, 10, 3, j, Block.bookShelf.blockID, Block.bookShelf.blockID, false);
}
if (isLargeRoom)
{
fillWithBlocks(par1World, par3StructureBoundingBox, 1, 5, 1, 3, 5, 13, Block.planks.blockID, Block.planks.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 10, 5, 1, 12, 5, 13, Block.planks.blockID, Block.planks.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 4, 5, 1, 9, 5, 2, Block.planks.blockID, Block.planks.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 4, 5, 12, 9, 5, 13, Block.planks.blockID, Block.planks.blockID, false);
placeBlockAtCurrentPosition(par1World, Block.planks.blockID, 0, 9, 5, 11, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.planks.blockID, 0, 8, 5, 11, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.planks.blockID, 0, 9, 5, 10, par3StructureBoundingBox);
fillWithBlocks(par1World, par3StructureBoundingBox, 3, 6, 2, 3, 6, 12, Block.fence.blockID, Block.fence.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 10, 6, 2, 10, 6, 10, Block.fence.blockID, Block.fence.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 4, 6, 2, 9, 6, 2, Block.fence.blockID, Block.fence.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 4, 6, 12, 8, 6, 12, Block.fence.blockID, Block.fence.blockID, false);
placeBlockAtCurrentPosition(par1World, Block.fence.blockID, 0, 9, 6, 11, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.fence.blockID, 0, 8, 6, 11, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.fence.blockID, 0, 9, 6, 10, par3StructureBoundingBox);
int k = getMetadataWithOffset(Block.ladder.blockID, 3);
placeBlockAtCurrentPosition(par1World, Block.ladder.blockID, k, 10, 1, 13, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.ladder.blockID, k, 10, 2, 13, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.ladder.blockID, k, 10, 3, 13, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.ladder.blockID, k, 10, 4, 13, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.ladder.blockID, k, 10, 5, 13, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.ladder.blockID, k, 10, 6, 13, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.ladder.blockID, k, 10, 7, 13, par3StructureBoundingBox);
byte byte1 = 7;
byte byte2 = 7;
placeBlockAtCurrentPosition(par1World, Block.fence.blockID, 0, byte1 - 1, 9, byte2, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.fence.blockID, 0, byte1, 9, byte2, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.fence.blockID, 0, byte1 - 1, 8, byte2, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.fence.blockID, 0, byte1, 8, byte2, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.fence.blockID, 0, byte1 - 1, 7, byte2, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.fence.blockID, 0, byte1, 7, byte2, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.fence.blockID, 0, byte1 - 2, 7, byte2, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.fence.blockID, 0, byte1 + 1, 7, byte2, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.fence.blockID, 0, byte1 - 1, 7, byte2 - 1, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.fence.blockID, 0, byte1 - 1, 7, byte2 + 1, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.fence.blockID, 0, byte1, 7, byte2 - 1, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.fence.blockID, 0, byte1, 7, byte2 + 1, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.torchWood.blockID, 0, byte1 - 2, 8, byte2, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.torchWood.blockID, 0, byte1 + 1, 8, byte2, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.torchWood.blockID, 0, byte1 - 1, 8, byte2 - 1, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.torchWood.blockID, 0, byte1 - 1, 8, byte2 + 1, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.torchWood.blockID, 0, byte1, 8, byte2 - 1, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.torchWood.blockID, 0, byte1, 8, byte2 + 1, par3StructureBoundingBox);
}
func_74879_a(par1World, par3StructureBoundingBox, par2Random, 3, 3, 5, field_75007_b, 1 + par2Random.nextInt(4));
if (isLargeRoom)
{
placeBlockAtCurrentPosition(par1World, 0, 0, 12, 9, 1, par3StructureBoundingBox);
func_74879_a(par1World, par3StructureBoundingBox, par2Random, 12, 8, 1, field_75007_b, 1 + par2Random.nextInt(4));
}
return true;
} |
e4bf7011-5904-4f47-a4da-ce029a3e123a | 5 | public void updateAsScheduled(int numUpdates) {
super.updateAsScheduled(numUpdates) ;
//
// TODO: Restore once building/salvage of vehicles is complete-
///if (! structure.intact()) return ;
base().intelMap.liftFogAround(this, 3.0f) ;
final FormerPlant plant = (FormerPlant) hangar() ;
final Target going = motion.target() ;
if (going == null || going == aboard()) {
if (plant == aboard()) {
for (Item sample : cargo.matches(SAMPLES)) {
final Tile t = (Tile) sample.refers ;
plant.soilSamples += (t.habitat().minerals() / 10f) + 0.5f ;
cargo.removeItem(sample) ;
}
if (plant.soilSamples < 10) {
motion.updateTarget(plant.pickSample()) ;
}
}
else {
cargo.addItem(Item.withReference(SAMPLES, origin())) ;
motion.updateTarget(plant) ;
}
toggleSoilDisplay() ;
}
} |
72024d69-c1d8-4a19-8353-c129b5506daf | 6 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TextReader other = (TextReader) obj;
if (content == null) {
if (other.content != null)
return false;
} else if (!content.equals(other.content))
return false;
return true;
} |
9d8353ad-0407-4718-bae8-40306072232c | 6 | public boolean needsCrypt() {
return ((this.sslMode == FTPConnection.AUTH_SSL_FTP_CONNECTION || this.sslMode == FTPConnection.AUTH_TLS_FTP_CONNECTION || this.sslMode == FTPConnection.IMPLICIT_SSL_WITH_CRYPTED_DATA_FTP_CONNECTION || this.sslMode == FTPConnection.IMPLICIT_TLS_WITH_CRYPTED_DATA_FTP_CONNECTION) && !isControllConnection())
|| this.sslMode != FTPConnection.FTP_CONNECTION
&& isControllConnection();
} |
77b92f6d-3145-4919-b28f-0fd71ff0d235 | 1 | public static void main(String[] args) {
String key = "ARVINBEHSHAD";
LinkedList<Character> word = new LinkedList<Character>();
for (int i = 0; i < key.length(); i++) {
word.append(key.charAt(i));
}
word.reverseList();
System.out.println("Reverse: " + word.toString());
word.reverseList();
System.out.println("Reverse back: " + word.toString());
word.append('_');
System.out.println("Append: " + word.toString());
word.insertAt(5, word, new Node<Character>(' ', null));
System.out.println("Insert space: " + word.toString());
word.replaceValue('T', 2);
System.out.println("Replace 'V': " + word.toString());
System.out.println("Length: " + word.length);
} |
fe1b3d21-828b-458f-a8e6-4d87828b52e6 | 2 | private Object convertRvalue(Object rvalue)
throws CannotCompileException
{
if (rvalue == null)
return null; // the return type is void.
String classname = rvalue.getClass().getName();
if (stubGen.isProxyClass(classname))
return new RemoteRef(exportObject(null, rvalue), classname);
else
return rvalue;
} |
503fedcc-70f3-427e-a9e4-b7353395cb87 | 3 | public synchronized void receive(Message m) {
String type = m.getType();
if (type.equals("heartbeat")) {
detector.receive(m);
} else if(type.equals("VAL")){
detector.addConsensusMessage(m);
} else if(type.equals("OUTCOME")){
detector.addOutcomeMessage(m);
}
} |
768ea482-c091-42f6-8cb9-abe44ca0f0d6 | 1 | public static void main(String[] args) {
int num1=0,num2=0;
// TODO Auto-generated method stub
try {
Scanner sc=new Scanner(System.in);
num1=sc.nextInt();
num2=sc.nextInt();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Sum1toN s=new Sum1toN();
System.out.println("Product of"+num1 +"and "+num2 +"is :"+s.multiply(num1,num2));
} |
d0b96f56-da13-4b2c-aacf-7a8db45c9c7a | 1 | public List<Double> getRPRowList(int index) {
List<Double> result= new ArrayList<Double>();
double[] values= this.getRPRowArray(index);
for (int i= 0; i< values.length; ++i) {
result.add(Double.valueOf(values[i]));
}
return result;
} |
d1cd87a8-4db7-4045-b69e-ab19d1941e8a | 0 | public void setDisplayImage (Image dispImage) {
displayImage = dispImage;
} |
691643ce-345e-4757-9711-c69ba21cc7c5 | 9 | public static void main(String[] args) throws IOException,
ClassNotFoundException
{
Driver d = new Driver();
Main.init();
TrigramProbGen t = new TrigramProbGen();
LevenshteinDistance LD = new LevenshteinDistance();
// What we essentially need to do is to take a particular phrase/
// sentence, and first detect
// if there is some misspelling. If there is no misspelling, we
// assume that the sentence is
// correct. We check the misspelling by searching against the default
// dictionary present in ubuntu
Scanner jin = new Scanner(System.in);
while (true)
{
String input = jin.nextLine();
String[] inputWords = input.split("[ .]");
int misspelt = -1;
for (int i = 0; i < inputWords.length; i++)
{
inputWords[i] = inputWords[i].toLowerCase();
if (!Dictionary.exists(inputWords[i]))
misspelt = i;
}
if (misspelt == -1)
{
System.out.println("All words are correctly spelt");
System.exit(0);
}
misspeltString = inputWords[misspelt];
// If there is a misspelling, we need to correct it. So for that, we
// first need to get a set
// of candidate replacements. In other words, the confusion set that
// we define is the list of
// words that are close to the misspelt word in terms of the results
// obtained from the first
// phase of the assignment.
// Once we have a confusion set, we can apply our method.
ArrayList<String> confusionSet = TrigramProbGen.cm
.getSuggestions(inputWords[misspelt]);
System.out.println(confusionSet);
// Suppose the original sentence was S = w1, w2, w3 ..... wn, and
// suppose the misspelt word was
// wi. Then we look at the confusion set of wi. We replace every
// word
// wi' from the confusion set
// and calculate the probability of the sentence P(S'). The word
// that
// is finally replaced/suggested
// is the word with the highest such probability.
// Now we need a method to calculate P(S). This is done using the
// trigrams in the following way.
// We have P(S) = Sigma P(S,T), where P(S,T) is the probability that
// blah balh and so on
String combined = "";
for (int i = 0; i < inputWords.length; i++)
combined += inputWords[i] + " ";
ArrayList<Tuple> corrections = TestData.correct(combined);
// for (Tuple cand : corrections)
// {
// System.out.println(cand.word + " " + cand.rank);
// }
for (String s : confusionSet)
{
// System.out.print(s + " : ");
inputWords[misspelt] = s;
Probab p = TrigramProbGen.probOfSentence(inputWords);
for (Tuple cand : corrections)
{
if (cand.word == s)
{
cand.trigram_rank = p.numerator;
cand.confusion_rank = bigInt(LD.getLDnoConfusion(misspeltString,
cand.word));
}
}
}
normalizeTuple(corrections);
for (Tuple cand : corrections)
{
System.out.println(cand.word + " : " + cand.overall_rank);
}
}
} |
692a2cf7-bd57-485e-bf1d-6c1be63218c8 | 5 | public AnnotationVisitor visitParameterAnnotation(
final int parameter,
final String desc,
final boolean visible)
{
AnnotationNode an = new AnnotationNode(desc);
if (visible) {
if (visibleParameterAnnotations == null) {
int params = Type.getArgumentTypes(this.desc).length;
visibleParameterAnnotations = new List[params];
}
if (visibleParameterAnnotations[parameter] == null) {
visibleParameterAnnotations[parameter] = new ArrayList(1);
}
visibleParameterAnnotations[parameter].add(an);
} else {
if (invisibleParameterAnnotations == null) {
int params = Type.getArgumentTypes(this.desc).length;
invisibleParameterAnnotations = new List[params];
}
if (invisibleParameterAnnotations[parameter] == null) {
invisibleParameterAnnotations[parameter] = new ArrayList(1);
}
invisibleParameterAnnotations[parameter].add(an);
}
return an;
} |
0af76fb7-d2ff-4d4b-84d7-9d11451c4a6e | 1 | static public Object deserializeArrayResource(String name, Class elemType, int length)
throws IOException
{
InputStream str = getResourceAsStream(name);
if (str==null)
throw new IOException("unable to load resource '"+name+"'");
Object obj = deserializeArray(str, elemType, length);
return obj;
} |
7a3748d7-f3bd-40c7-8f0f-f4d11755315f | 4 | private AFParser recursiveInvertedAFNEGenerate(RegularExpresionNode node) {
AFParser result = null;
if(node instanceof ConcatNode){
RegularExpresionNode left = ((ConcatNode)node).leftOperandNode;
RegularExpresionNode right = ((ConcatNode)node).rightOperandNode;
result = this.concatenateAutomatas(this.recursiveInvertedAFNEGenerate(right), this.recursiveInvertedAFNEGenerate(left));
}else if(node instanceof OrNode){
RegularExpresionNode left = ((OrNode)node).leftOperandNode;
RegularExpresionNode right = ((OrNode)node).rightOperandNode;
result = this.orAutomatas(this.recursiveInvertedAFNEGenerate(right), this.recursiveInvertedAFNEGenerate(left));
}else if(node instanceof CycleNode){
RegularExpresionNode unique = ((CycleNode)node).OperandNode;
result = this.asteriscAutomata(this.recursiveInvertedAFNEGenerate(unique));
}else if(node instanceof SymbolNode){
String value = "" + ((SymbolNode)node).Value;
result = this.generateLeafAutomata(value);
}
return result;
} |
aa5b49e9-cedc-46ed-8a53-a3571ba177e7 | 0 | @Basic
@Column(name = "name")
public String getName() {
return name;
} |
d2ffcb41-64ac-47ed-bf8e-e7de64367bb2 | 1 | @Override
public boolean isOpaque() {
return super.isOpaque() && !mDrawingDragImage;
} |
dba80112-d92d-47e7-948d-7a4ab8639691 | 4 | @EventHandler
public void RightClick(PlayerInteractEvent event) {
final Player p = event.getPlayer();
boolean mode = getConfig().getBoolean(p.getName().toLowerCase() + ".mode");
if(event.getAction().toString() == "RIGHT_CLICK_BLOCK") {
if(p.getItemInHand().getType().equals(Material.EMERALD)) {
p.openInventory(UIManager.Shop);
p.sendMessage(ChatColor.GREEN + "You opened the Shop!");
}else {
@SuppressWarnings("deprecation")
Block b = p.getTargetBlock(null, 200);
final Location loc = b.getLocation();
if(loc.getBlock().getType().equals(Material.BEACON) && mode) {
UIManager.giveItemName(p, Material.RAILS, 5, "Gold Mine", "Right click to place!");
loc.getBlock().setType(Material.AIR);
p.sendMessage(ChatColor.GREEN + "Building placed!");
getConfig().set(p.getName().toLowerCase() + ".mode", Boolean.valueOf(false));
String hand = p.getInventory().getItemInHand().getType().toString();
Build.BuildStructre(loc, p, hand);
p.sendMessage(ChatColor.GREEN + "Started build of... " + hand);
UIManager.giveItemName(p, Material.WOOL, 5, "No Structres Selected", "Go to the shop to add structres!");
return;
}else {
getConfig().set(p.getName().toLowerCase() + ".mode", Boolean.valueOf(false));
/** Need to set old.**/
return;
}
}
}
} |
b942e394-eea5-41d6-a60b-4a92acffa67d | 4 | @Override
public String buscarDocumentoPorConcepto(String concepto) {
ArrayList<Venta> geResult= new ArrayList<Venta>();
ArrayList<Venta> dbVentas = tablaVentas();
String result="";
try{
for (int i = 0; i < dbVentas.size() ; i++){
if(dbVentas.get(i).getConcepto().equalsIgnoreCase(concepto)){
geResult.add(dbVentas.get(i));
}
}
}catch (NullPointerException e) {
result="No existe la venta con ese concepto";
}
if (geResult.size()>0){
result=imprimir(geResult);
} else {
result="No se ha encontrado ningun registro";
}
return result;
} |
ca322f84-5326-4259-bc9d-3b75ec33fb44 | 5 | public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
System.out.println("This is my new Filter");
if (debug) {
log("testFilter:doFilter()");
}
doBeforeProcessing(request, response);
Throwable problem = null;
try {
chain.doFilter(request, response);
} catch (Throwable t) {
// If an exception is thrown somewhere down the filter chain,
// we still want to execute our after processing, and then
// rethrow the problem after that.
problem = t;
t.printStackTrace();
}
doAfterProcessing(request, response);
// If there was a problem, we want to rethrow it if it is
// a known type, otherwise log it.
if (problem != null) {
if (problem instanceof ServletException) {
throw (ServletException) problem;
}
if (problem instanceof IOException) {
throw (IOException) problem;
}
sendProcessingError(problem, response);
}
} |
c5e4a406-b62f-40ed-9bf5-fffcc8da3674 | 5 | @Override
protected ArrayList<PossibleTile> getLazyTiles(Board b) {
ArrayList<PossibleTile> lazyTiles = new ArrayList<PossibleTile>();
PossibleTile step1;
if (isWhite) {
Pawn clone = this.clone();
clone.setMoved();
step1 = new PossibleTile(clone.getX(), clone.getY() - 1, clone);
} else {
Pawn clone = this.clone();
clone.setMoved();
step1 = new PossibleTile(clone.getX(), clone.getY() + 1, clone);
}
boolean canMove = decideToAddTile(b, lazyTiles, step1);
if (!this.hasMoved && canMove) {
Pawn clone = this.clone();
PossibleTile step2;
clone.setMoved();
clone.setPossibleToPassant(true);
if (isWhite) {
step2 = new PossibleTile(clone.getX(), clone.getY() - 2, clone);
} else {
step2 = new PossibleTile(clone.getX(), clone.getY() + 2, clone);
}
decideToAddTile(b, lazyTiles, step2);
}
Pawn clone = this.clone();
clone.setMoved();
PossibleTile attack1;
PossibleTile attack2;
if (isWhite) {
attack1 = new PossibleTile(clone.getX() - 1, clone.getY() - 1, clone);
attack2 = new PossibleTile(clone.getX() + 1, clone.getY() - 1, clone);
} else {
attack1 = new PossibleTile(clone.getX() - 1, clone.getY() + 1, clone);
attack2 = new PossibleTile(clone.getX() + 1, clone.getY() + 1, clone);
}
decideToAddAttackTile(b, lazyTiles, attack1);
decideToAddAttackTile(b, lazyTiles, attack2);
PossibleTile passant1 = new PossibleTile(clone.getX() - 1, clone.getY(), clone);
PossibleTile passant2 = new PossibleTile(clone.getX() + 1, clone.getY(), clone);
decideToAddPassantTile(b, lazyTiles, passant1);
decideToAddPassantTile(b, lazyTiles, passant2);
return lazyTiles;
} |
5ad14fea-a242-4d82-b2fe-12c5dde27c28 | 9 | private void onAdd() {
try{
Double averageConsumption = Double.parseDouble(tfAverageConsumption.getText().replace(",", "."));
String fuelType = (String) cbFuelType.getSelectedItem();
int cargo = (int) Double.parseDouble(tfCargo.getText().replace(",", "."));
LinkedList<Route> routes = new LinkedList<>();
if(cbRoute.getSelectedIndex() == 0)
{
for(Route r : calculator.getRoutes())
{
for(int i = 1; i < cbRoute.getItemCount(); i++)
{
if(r.getCbString().equals(cbRoute.getItemAt(i)))
{
routes.add(r);
}
}
}
}
else
{
for(Route r : calculator.getRoutes())
{
if(r.getCbString().equals(cbRoute.getSelectedItem()))
{
routes.add(r);
}
}
}
Vehicle vehicle;
if(btCar.isSelected())
{
vehicle = new Car(cargo, fuelType, averageConsumption);
}
else
{
int axles = Integer.parseInt(tfAxles.getText().replace(",", "."));
boolean adBlue = cbBlue.isSelected();
vehicle = new Truck(cargo, fuelType, averageConsumption, adBlue, axles);
}
newTrip.setRoutes(routes);
newTrip.setVehicle(vehicle);
isOk = true;
dispose();
}catch(NumberFormatException ex)
{
JOptionPane.showMessageDialog(this, "Average Consumption, Cargo and Axles have to be a NUMBER!", "No Number", JOptionPane.ERROR_MESSAGE);
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(this, "Something went wrong...", "Ooops", JOptionPane.ERROR_MESSAGE);
}
} |
8d11d5c7-32d7-4672-b58d-fdfd026f2adb | 2 | private void buttonSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSaveActionPerformed
//Создаем новую кредитную программу по заполненным полям
CreditProgram crProg = new CreditProgram();
try {
crProg.setName(textFieldName.getText());
crProg.setMinAmount(Long.parseLong(textFieldMinAmount.getText()));
crProg.setMaxAmount(Long.parseLong(textFieldMaxAmount.getText()));
crProg.setDuration(Integer.parseInt(textFieldDuration.getText()));
crProg.setStartPay(Double.parseDouble(textFieldStartPay.getText()));
crProg.setPercent(Double.parseDouble(textFieldPercent.getText()));
crProg.setDescription(textAreaDescription.getText());
crProg.setCreditProgStatus(1);
} catch (NumberFormatException exc) {
JOptionPane.showMessageDialog(this, "Неверный формат данных!");
return;
}
//Обновляем или добавляем новую кредитную программу
if (crProgDAO.update(crProg) != true) {
crProgDAO.add(crProg);
}
JOptionPane.showMessageDialog(this, "Данные успешно сохранены");
//Обновляем таблицу
crProgDAO = new CreditProgramDAO();
crProgDAO.initTableModel(creditProgramTable, crProgDAO.listAll());
}//GEN-LAST:event_buttonSaveActionPerformed |
7a59b116-5cec-483f-b91d-9547609966f5 | 2 | public static void cleanMemory(){
byte[] trash = new byte[10240000];
File f = new File(Params.testFolder + java.io.File.separator + "trash.txt");
FileOutputStream fout = null;
try{
fout = new FileOutputStream(f);
for(int i = 0 ; i < 1000 ; i++) fout.write(trash);
fout.close();
}catch(IOException e){
//TODO: catch error
e.printStackTrace();
}finally{
}
} |
a17a326f-5c43-4b41-b3b3-7f504e306189 | 6 | @EventHandler
public void onPlayerDamagedByPlayer(EntityDamageByEntityEvent event) {
if (event.getEntity() instanceof Player && event.getDamager() instanceof Player) {
switch (HeroesHandler.inGamePlayers.get(event.getDamager())) {
case EARTH_SHAKER: {
break;
}
case ICE: {
((Player) event.getEntity()).addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 20, 5));
break;
}
case PYRO: {
((Player) event.getEntity()).setFireTicks(2);
break;
}
case VOIDLING: {
((Player) event.getEntity()).addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 20, 3));
break;
}
default: {
event.setCancelled(false);
break;
}
}
}
} |
b4d81216-38bf-410a-8f78-44d4d07cc55a | 1 | public void checkConsistent() {
if (!(outer instanceof SwitchBlock))
throw new jode.AssertError("Inconsistency");
super.checkConsistent();
} |
e027e94e-34a4-4cc3-b5a7-f410b2342fb4 | 0 | @Override
public String toString(){
return "Units " + name;
} |
74c17bab-8335-4846-8751-c8f3a3a05c08 | 9 | public static double evaluateNDCG(int k, HashMap<String, HashMap<Integer,Double>> relevance_judgments_2,
String path){
double NDCG = 0.0, IDCG=0.0;
List<Double> relevance = new ArrayList<Double>();
try {
BufferedReader reader = new BufferedReader(new FileReader(path));
double DCG = 0.0;
String readLineString = null;
for(int i=0; i<k; i++){
readLineString = reader.readLine();
Scanner s = new Scanner(readLineString).useDelimiter("\t");
String query = s.next();
int did = s.nextInt();
if(!relevance_judgments_2.containsKey(query)){
throw new IOException("query not found");
}
HashMap<Integer,Double> qr = relevance_judgments_2.get(query);
if(qr.containsKey(did)){
if (i==0) {
DCG = qr.get(did);
}
else {
DCG = DCG + qr.get(did) / Math.log(i + 1) / Math.log(2);
}
relevance.add(qr.get(did));
}
else {
relevance.add(0.0);
}
}
Collections.sort(relevance, Collections.reverseOrder());
for (int i=0; i<k; i++) {
if (i==0) {
IDCG = relevance.get(i);
}
else {
IDCG = IDCG + relevance.get(i) / Math.log(i + 1) / Math.log(2);
}
}
if (IDCG != 0.0)
NDCG = DCG / IDCG;
reader.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return NDCG;
} |
f00d942e-4226-44c8-ba1c-a3957de1ff32 | 8 | public Player getDamager(Entity damager, boolean allowPets)
{
// Check if the damager is a player
if (damager instanceof Player)
{
return (Player) damager;
}
// Check if the damager is a projectile from a player
else if (damager instanceof Projectile)
{
Projectile projectile = (Projectile) damager;
if (projectile.getShooter() instanceof Player)
{
return (Player) projectile.getShooter();
}
}
// Check if the damager is a pet tamed by a player
else if (allowPets && damager instanceof Tameable)
{
Tameable pet = (Tameable) damager;
if (pet.isTamed() && pet.getOwner() instanceof Player)
{
Player player = (Player) pet.getOwner();
// Only players with this permission can get bounty from their pets killing mobs
if (player.hasPermission("mobmanager.bounty.petreward"))
{
return player;
}
}
}
return null;
} |
9968bc0b-a1f5-499f-8099-61101db4ffa8 | 9 | public void readItems() {
while (custDataIn.hasNextLine()) {
String temp = custDataIn.nextLine();
if (checkDate(temp))
date = temp;
else {
throw new IllegalArgumentException();
}
System.out.println("DATE: " + date);
while (custDataIn.hasNextLine()) {
String line = custDataIn.next();
if (line.charAt(0) != '#') {
ReceiptItem rI = new ReceiptItem(line.substring(0,10));
switch (ItemDatabase.getFromUPC(rI.getUPC()).getType()) {
case 'F':
rI.setQuantity(1);
if (custDataIn.hasNextInt())
rI.setQuantity(custDataIn.nextInt());
break;
case 'P':
case 'Q':
}
receipt.addItem(rI);
} else {
printReceipt();
try {
custDataIn.nextLine();
} catch (NoSuchElementException e) {
}
receipt = new Receipt(date);
break;
}
}
}
} |
2c0d27ce-57e2-4561-b32b-953a7a556320 | 4 | private float min(ArrayList<Float> data) {
float min = Float.POSITIVE_INFINITY;
for (float f : data) {
if (f != f)
continue;
if (f < min)
min = f;
}
if (min == Float.POSITIVE_INFINITY)
min = -1e-7f;
return min;
} |
e9006eb5-e71b-471e-b2db-c33dc45b105b | 8 | public static void main(String[] args) {
EvolvingGlobalProblemSetInitialisation starter = new EvolvingGlobalProblemSetInitialisation();
starter.initLanguage(new char[] { '0', '1' }, 10, "(0|101|11(01)*(1|00)1|(100|11(01)*(1|00)0)(1|0(01)*(1|00)0)*0(01)*(1|00)1)*");
int solutionFoundCounter = 0;
int noSolutionFound = 0;
List<Long> cycleCount = new LinkedList<Long>();
long tmpCycle;
long timeStamp;
int[] problemCount = new int[25];
int[] candidatesCount = new int[1];
int[] noCycles = new int[2];
problemCount[0] = 3;
problemCount[1] = 6;
problemCount[2] = 9;
problemCount[3] = 12;
problemCount[4] = 15;
problemCount[5] = 18;
problemCount[6] = 21;
problemCount[7] = 24;
problemCount[8] = 27;
problemCount[9] = 30;
problemCount[10] = 33;
problemCount[11] = 36;
problemCount[12] = 39;
problemCount[13] = 42;
problemCount[14] = 45;
problemCount[15] = 48;
problemCount[16] = 51;
problemCount[17] = 54;
problemCount[18] = 57;
problemCount[19] = 60;
problemCount[20] = 63;
problemCount[21] = 66;
problemCount[22] = 69;
problemCount[23] = 72;
problemCount[24] = 75;
candidatesCount[0] = 50;
noCycles[0] = 250;
noCycles[1] = 500;
int pc = 0;
int cc = 0;
int nc = 0;
for (int x = 0; x < 10; x++) {
System.out.println("x:" + x);
for (int n = 0; n < 25; n++) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd_HH_mm_ss");
Logger l = new Logger("E_G_PS_" + df.format(new Date()) + ".log",
true);
pc = problemCount[n];
cc = candidatesCount[0];
nc = noCycles[1];
l.log("Problem Count: " + pc);
l.log("CandidatesCount: " + cc);
l.log("Max Cycles: " + nc);
solutionFoundCounter = 0;
noSolutionFound = 0;
cycleCount = new LinkedList<Long>();
for (int i = 0; i < 100; i++) {
timeStamp = System.currentTimeMillis();
starter.initProblems(pc);
starter.initCandidates(cc);
tmpCycle = starter.startEvolution(nc);
l.log(i + ": finished ("
+ (System.currentTimeMillis() - timeStamp) + "ms, "
+ tmpCycle + "cycles)");
if (starter.getWinner() != null) {
solutionFoundCounter++;
cycleCount.add(tmpCycle);
l.log(i + ": Solution found.");
// GraphvizRenderer.renderGraph(starter.getWinner().getObj(),
// "winner.svg");
} else {
noSolutionFound++;
l.log(i + ": No solution found.");
}
}
long max = 0;
long min = 10000;
long sum = 0;
for (long no : cycleCount) {
sum += no;
max = (no > max ? no : max);
min = (no < min ? no : min);
}
l.log("Solution Found: " + solutionFoundCounter);
l.log("Avg cycles: "
+ (cycleCount.size() > 0 ? sum / cycleCount.size()
: '0'));
l.log("Max cycles: " + max);
l.log("Min cycles: " + min);
l.log("No solution found: " + noSolutionFound);
l.finish();
}
}
} |
204d6630-04d2-4c6b-9f1f-7c5345564639 | 9 | private void getServersList(PrintWriter out) {
out.println("matchlist" + Utils.SEPARATOR + "beginning");
out.println(liste.size());
Iterator<Match> it = liste.iterator();
while ( it.hasNext() ){
Match m = ((Match) it.next());
String display = ( m.getType() == Utils.Types.ONEVSONE ? "1vs1" : ( m.getType() == Utils.Types.TWOVSTWO ? "2vs2" : "1vs2" ) );
if( m.getPlayer1() != null ){
display += " - " + m.getPlayer1().getLogin();
}else if( m.getPlayer2() != null ){
display += " - " + m.getPlayer2().getLogin();
}else if( m.getPlayer3() != null ){
display += " - " + m.getPlayer3().getLogin();
}else if( m.getPlayer4() != null ){
display += " - " + m.getPlayer4().getLogin();
}
display += " - " + m.countPlayers() + " joueur(s) / " + ( m.getType() == Utils.Types.ONEVSONE ? "2" : ( m.getType() == Utils.Types.TWOVSTWO ? "4" : "3" ) );
out.println(display);
}
out.println("matchlist" + Utils.SEPARATOR + "end");
out.flush();
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.