repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
lucasdavid/Dust-cleaner | projects/assignment-player-2/src/gatech/mmpm/sensor/builtin/DistanceEC.java | 3921 | /* Copyright 2010 Santiago Ontanon and Ashwin Ram */
package gatech.mmpm.sensor.builtin;
import gatech.mmpm.ActionParameterType;
import gatech.mmpm.Context;
import gatech.mmpm.Entity;
import gatech.mmpm.GameState;
import gatech.mmpm.PhysicalEntity;
import gatech.mmpm.sensor.Sensor;
import gatech.mmpm.util.Pair;
/**
* Distance between a coordinate and an entity. Both
* parameters must be specified.
*
* @author David Llanso
* @organization: Georgia Institute of Technology
* @date 06-November-2009
*
*/
public class DistanceEC extends Sensor
{
public DistanceEC()
{
} // Constructor
//---------------------------------------------------------------
public DistanceEC(DistanceEC dec)
{
super(dec);
} // Copy constructor
//---------------------------------------------------------------
public Object clone()
{
return new DistanceEC();
} // clone
//---------------------------------------------------------------
/**
* Return the type of the sensor.
*
* Keep in mind that this is <em>not</em> the real Java type,
* but the MMPM type. See the
* gatech.mmpm.ActionParameterType.getJavaType() method
* for more information.
*
* @return Type of the sensor.
*/
public ActionParameterType getType()
{
return ActionParameterType.FLOAT;
} // getType
//---------------------------------------------------------------
public Object evaluate(int cycle, GameState gs, String player, Context parameters)
{
Entity e = getEntityParam(parameters,"entity");
float[] coor = getCoorParam(parameters,"coor");
float d = 0;
if(coor != null && e!=null && e instanceof PhysicalEntity)
d = (float)gs.getMap().distance(coor,
((PhysicalEntity)e).get_Coords());
else
d = Float.MAX_VALUE;
// System.out.println("DistanceEC: " + d);
return d;
} // evaluate
//---------------------------------------------------------------
/**
* Public method that provides the parameters that
* this sensor uses to be evaluated. This method provides
* all the parameters that can be used in the evaluation,
* nevertheless some sensor can be evaluated with only
* some of them.
*
* @return The list of needed parameters this sensor needs
* to be evaluated.
*/
public java.util.List<Pair<String,ActionParameterType>> getNeededParameters() {
return _listOfNeededParameters;
} // getNeededParameters
//---------------------------------------------------------------
/**
* Public static method that provides the parameters that
* this sensor uses to be evaluated. This method provides
* all the parameters that can be used in the evaluation,
* nevertheless some sensor can be evaluated with only
* some of them.
*
* @return The list of needed parameters this sensor needs
* to be evaluated.
*/
public static java.util.List<Pair<String,ActionParameterType>> getStaticNeededParameters() {
return _listOfNeededParameters;
} // getStaticNeededParameters
//---------------------------------------------------------------
// Static fields
//---------------------------------------------------------------
static java.util.List<Pair<String,ActionParameterType>> _listOfNeededParameters;
//---------------------------------------------------------------
// Static initializers
//---------------------------------------------------------------
static {
// Add parameters to _listOfNeededParameters.
_listOfNeededParameters = new java.util.LinkedList<Pair<String,ActionParameterType>>(gatech.mmpm.sensor.Sensor.getStaticNeededParameters());
_listOfNeededParameters.add(new Pair<String,ActionParameterType>("entity", ActionParameterType.ENTITY_ID));
_listOfNeededParameters.add(new Pair<String,ActionParameterType>("coor", ActionParameterType.COORDINATE));
} // static initializer
} // Class DistanceEC
| mit |
UCSB-CS56-W15/W15-lab04 | src/edu/ucsb/cs56/w15/drawings/brentkirkland/advanced/WritePictureToFile.java | 3139 | package edu.ucsb.cs56.w15.drawings.brentkirkland.advanced;
import java.awt.image.BufferedImage;
import java.awt.Graphics2D;
import java.awt.Color;
import java.io.File;
import javax.imageio.ImageIO;
import java.io.IOException;
import edu.ucsb.cs56.w15.drawings.utilities.ShapeTransforms;
import edu.ucsb.cs56.w15.drawings.utilities.GeneralPathWrapper;
/**
* A class with a main method that can write a drawing to a graphics file.
*
* @author P. Conrad,
* @version for CS56, W11 UCSB
*/
public class WritePictureToFile
{
public static void usage()
{
System.out.println("Usage: java WritePictureToFile whichImage mypic");
// @@@ modify the next line to describe your picture
System.out.println(" whichImage should be 1,2 or 3");
System.out.println(" whichImage chooses from drawPicture1, 2 or 3");
System.out.println(" .png gets added to the filename");
System.out.println(" e.g. if you pass mypic, filename is mypic.png");
System.out.println("Example: java WritePictureToFile 3 foo");
System.out.println(" produces foo.png from drawPicture3");
}
/** Write the drawFourCoffeeCups picture to a file.
*
* @param args The first command line argument is the file to write to. We leave off the extension
* because that gets put on automatically.
*/
public static void main(String[] args)
{
// make sure we have exactly one command line argument
if (args.length != 2)
{
usage();
System.exit(1);
}
String whichPicture = args[0]; // first command line arg is 1, 2, 3
String outputfileName = args[1]; // second command line arg is which pic
final int WIDTH = 640;
final int HEIGHT = 480;
// create a new image
// TYPE_INT_ARGB is "RGB image" with transparency (A = alpha channel)
BufferedImage bi =
new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_ARGB);
// g2 is a Graphics2D object that will draw into the BufferedImage object
Graphics2D g2 = bi.createGraphics();
if (whichPicture.equals("1")) {
AllMyDrawings.drawPicture1(g2);
} else if (whichPicture.equals("2")) {
AllMyDrawings.drawPicture2(g2);
} else if (whichPicture.equals("3")) {
AllMyDrawings.drawPicture3(g2);
}
final String imageType = "png"; // choices: "gif", "png", "jpg"
// We must declare this variable outside the try block,
// so we can see it inside the catch block
String fullFileName = "";
try
{
fullFileName = outputfileName + "." + imageType; // make the file name
File outputfile = new File(fullFileName); // the file we will try to write
ImageIO.write(bi, imageType, outputfile); // actually write it
System.out.println("I created " + fullFileName); // tell the user
}
catch (IOException e)
{
System.err.println("Sorry, an error occurred--I could not create "+ fullFileName +"\n The error was: "+ e.toString());
}
}
}
| mit |
OlegShatin/Politics_project | src/ru/kpfu/itis/group11501/shatin/politics_web_project/repositories/impls/UserRepositoryImpl.java | 6955 | package ru.kpfu.itis.group11501.shatin.politics_web_project.repositories.impls;
import com.sun.xml.internal.bind.v2.TODO;
import ru.kpfu.itis.group11501.shatin.politics_web_project.helpers.ConnectionSingleton;
import ru.kpfu.itis.group11501.shatin.politics_web_project.models.Role;
import ru.kpfu.itis.group11501.shatin.politics_web_project.models.User;
import ru.kpfu.itis.group11501.shatin.politics_web_project.repositories.UserRepository;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneOffset;
/**
* @author Oleg Shatin
* 11-501
*/
public class UserRepositoryImpl implements UserRepository {
@Override
public User getUserByEmail(String email) {
PreparedStatement statement = null;
User result = null;
try {
statement = ConnectionSingleton.getConnection().prepareStatement(
"select * FROM users WHERE users.email LIKE ?");
statement.setString(1, email.toLowerCase());
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()){
result = createUserLikeResultSet(resultSet);
}
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
@Override
public boolean userExists(String email, String hashed_password) {
try {
PreparedStatement statement = ConnectionSingleton.getConnection().prepareStatement(
"select * FROM users WHERE users.email LIKE ? AND users.password_hash LIKE ?");
statement.setString(1, email.toLowerCase());
statement.setString(2, hashed_password);
ResultSet resultSet = statement.executeQuery();
return resultSet.next();
} catch (SQLException e){
e.printStackTrace();
}
return false;
}
@Override
public boolean containsThisEmail(String email) {
try {
PreparedStatement statement = ConnectionSingleton.getConnection().prepareStatement(
"select * FROM users WHERE users.email LIKE ?");
statement.setString(1, email.toLowerCase());
ResultSet resultSet = statement.executeQuery();
return resultSet.next();
} catch (SQLException e){
e.printStackTrace();
}
return false;
}
@Override
public boolean samePassportExists(String passportSeries, String passportNum) {
try {
PreparedStatement statement = ConnectionSingleton.getConnection().prepareStatement(
"select * FROM users WHERE users.passport_series LIKE ? AND users.passport_number LIKE ?");
statement.setString(1, passportSeries);
statement.setString(2, passportNum);
ResultSet resultSet = statement.executeQuery();
return resultSet.next();
} catch (SQLException e){
e.printStackTrace();
}
return false;
}
@Override
public boolean addNewUser(String password, String email, Role role, int timezoneOffset, String passportSeries, String passportNum, String name, String surname, String patronymic, LocalDate birthdayDate) {
try {
PreparedStatement statement = ConnectionSingleton.getConnection().prepareStatement(
"INSERT INTO users(password_hash, email, role, timezone, passport_series, passport_number," +
"name, surname, patronymic, birthday) VALUES (?,?,?,?,?,?,?,?,?,?)");
statement.setString(1, password);
statement.setString(2, email.toLowerCase());
statement.setString(3, role.name());
statement.setInt(4, timezoneOffset);
statement.setString(5, passportSeries);
statement.setString(6, passportNum);
statement.setString(7, name);
statement.setString(8, surname);
statement.setString(9, patronymic);
statement.setDate(10, Date.valueOf(birthdayDate.toString()));
return 0 < statement.executeUpdate();
} catch (SQLException e){
e.printStackTrace();
}
return false;
}
@Override
public User getUserById(long userId) {
PreparedStatement statement = null;
User result = null;
try {
statement = ConnectionSingleton.getConnection().prepareStatement(
"select * FROM users WHERE users.id = ?");
statement.setLong(1, userId);
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()){
result = createUserLikeResultSet(resultSet);
}
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
@Override
public boolean updateEmail(long userId, String email) {
try {
PreparedStatement statement
= ConnectionSingleton.getConnection()
.prepareStatement("UPDATE users SET email = ? WHERE id = ?");
statement.setString(1, email.toLowerCase());
statement.setLong(2, userId);
return statement.executeUpdate() > 0;
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
@Override
public boolean updatePassword(long userId, String hashedPassword) {
try {
PreparedStatement statement
= ConnectionSingleton.getConnection()
.prepareStatement("UPDATE users SET password_hash = ? WHERE id = ?");
statement.setString(1, hashedPassword);
statement.setLong(2, userId);
return statement.executeUpdate() > 0;
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
private User createUserLikeResultSet(ResultSet resultSet) throws SQLException {
return createUserLikeResultSetWithCustomIdColumnName(resultSet, "id");
}
User createUserLikeResultSetWithCustomIdColumnName(ResultSet resultSet, String idColumnName) throws SQLException {
return new User(resultSet.getString("password_hash"),
resultSet.getString("email"),
resultSet.getLong(idColumnName),
Role.valueOf(resultSet.getString("role")),
ZoneOffset.ofHours(resultSet.getInt("timezone")),
LocalDate.of(resultSet.getDate("birthday").getYear(),resultSet.getDate("birthday").getMonth() + 1,resultSet.getDate("birthday").getDay()),
resultSet.getString("name"),
resultSet.getString("surname"),
resultSet.getString("patronymic"));
}
}
| mit |
Craftolution/CraftoPlugin | modules/fly/src/main/java/de/craftolution/craftoplugin/module/fly/FlyTime.java | 4823 | /*
* This file is part of CraftoPlugin, licensed under the MIT License (MIT).
*
* Copyright (c) 2020 CraftolutionDE <https://craftolution.de>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* Website: https://craftolution.de/
* Contact: support@craftolution.de
*/
package de.craftolution.craftoplugin.module.fly;
import de.craftolution.craftoplugin.core.utils.Check;
import de.craftolution.craftoplugin.service.playerstorage.StoredPlayer;
import java.time.Duration;
import java.time.Instant;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Optional;
public class FlyTime {
public static final Duration INFINITE = Duration.ofSeconds(-1);
private final int id;
private final int playerId;
private final Instant createdAt;
private Duration duration;
private Optional<Instant> activatedAt;
private Optional<Instant> expiredAt;
private Optional<Instant> revokedAt;
FlyTime(int id, int playerId, Instant createdAt, Duration duration, Optional<Instant> activatedAt,
Optional<Instant> expiredAt, Optional<Instant> revokedAt) {
Check.nonNulls("createdAt/duration/activatedAt/expiredAt/revokedAt",
createdAt, duration, activatedAt, expiredAt, revokedAt);
Check.min(id, 0);
Check.min(playerId, 0);
if (duration.isNegative() && !duration.equals(INFINITE)) {
throw new IllegalArgumentException("negative duration: " + duration);
}
this.id = id;
this.playerId = playerId;
this.createdAt = createdAt;
this.duration = duration;
this.activatedAt = activatedAt;
this.expiredAt = expiredAt;
this.revokedAt = revokedAt;
}
FlyTime(int id, int playerId, Duration duration) {
this(id, playerId, Instant.now(), duration, Optional.empty(), Optional.empty(), Optional.empty());
}
void updateDuration(Duration newDuration) {
this.duration = newDuration;
}
void activate() {
this.activatedAt = Optional.of(Instant.now());
}
void expire() {
this.expiredAt = Optional.of(Instant.now());
}
void revoke() {
this.revokedAt = Optional.of(Instant.now());
}
public int getId() {
return id;
}
public StoredPlayer getPlayer() throws NoSuchElementException {
return StoredPlayer.getOrThrow(this.playerId);
}
public Instant getCreatedAt() {
return createdAt;
}
public Duration getDuration() {
return duration;
}
public Optional<Instant> getActivatedAt() {
return activatedAt;
}
public Optional<Instant> getExpiredAt() {
return expiredAt;
}
public Optional<Instant> getRevokedAt() {
return revokedAt;
}
public Optional<Instant> getPlannedExpiration() {
if (this.duration.equals(INFINITE)) { return Optional.empty(); }
return getActivatedAt().map(instant -> instant.plus(this.duration));
}
public boolean hasBeenActivated() {
return this.getActivatedAt().isPresent();
}
public boolean hasExpired() {
return this.getExpiredAt().isPresent();
}
public boolean hasBeenRevoked() {
return this.getRevokedAt().isPresent();
}
public boolean isInfinite() {
return this.getDuration().equals(INFINITE);
}
public Optional<Duration> getTimeLeft() {
return getPlannedExpiration()
.map(planned -> Duration.between(Instant.now(), planned))
.map(dur -> dur.isNegative() ? Duration.ZERO : dur);
}
@Override
public String toString() {
return "FlyTime{" +
"id=" + id +
", playerId=" + playerId +
", createdAt=" + createdAt +
", duration=" + duration +
", activatedAt=" + activatedAt +
", expiredAt=" + expiredAt +
", revokedAt=" + revokedAt +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
FlyTime flyTime = (FlyTime) o;
return id == flyTime.id;
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}
| mit |
bladestery/Sapphire | example_apps/AndroidStudioMinnie/sapphire/src/main/java/boofcv/alg/feature/detect/intensity/impl/ImplFastIntensity12.java | 25408 | /*
* Copyright (c) 2011-2016, Peter Abeles. All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.org).
*
* 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 boofcv.alg.feature.detect.intensity.impl;
import boofcv.alg.feature.detect.intensity.FastCornerIntensity;
import boofcv.struct.image.ImageGray;
/**
* <p>
* Contains logic for detecting fast corners. Pixels are sampled such that they can eliminate the most
* number of possible corners, reducing the number of samples required.
* </p>
*
* <p>
* DO NOT MODIFY. Generated by {@link GenerateImplFastIntensity}.
* </p>
*
* @author Peter Abeles
*/
public class ImplFastIntensity12<T extends ImageGray> extends FastCornerIntensity<T>
{
/**
* @param helper Provide the image type specific helper.
*/
public ImplFastIntensity12(FastHelper<T> helper) {
super(helper);
}
@Override
protected boolean checkLower( int index )
{
if( helper.checkPixelLower(index + offsets[0]) ) {
if( helper.checkPixelLower(index + offsets[1]) ) {
if( helper.checkPixelLower(index + offsets[2]) ) {
if( helper.checkPixelLower(index + offsets[3]) ) {
if( helper.checkPixelLower(index + offsets[4]) ) {
if( helper.checkPixelLower(index + offsets[5]) ) {
if( helper.checkPixelLower(index + offsets[6]) ) {
if( helper.checkPixelLower(index + offsets[7]) ) {
if( helper.checkPixelLower(index + offsets[8]) ) {
if( helper.checkPixelLower(index + offsets[9]) ) {
if( helper.checkPixelLower(index + offsets[10]) ) {
if( helper.checkPixelLower(index + offsets[11]) ) {
return true;
} else if( helper.checkPixelLower(index + offsets[15]) ) {
return true;
} else {
return false;
}
} else if( helper.checkPixelLower(index + offsets[14]) ) {
if( helper.checkPixelLower(index + offsets[15]) ) {
return true;
} else {
return false;
}
} else {
return false;
}
} else if( helper.checkPixelLower(index + offsets[13]) ) {
if( helper.checkPixelLower(index + offsets[14]) ) {
if( helper.checkPixelLower(index + offsets[15]) ) {
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else if( helper.checkPixelLower(index + offsets[12]) ) {
if( helper.checkPixelLower(index + offsets[13]) ) {
if( helper.checkPixelLower(index + offsets[14]) ) {
if( helper.checkPixelLower(index + offsets[15]) ) {
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else if( helper.checkPixelLower(index + offsets[11]) ) {
if( helper.checkPixelLower(index + offsets[12]) ) {
if( helper.checkPixelLower(index + offsets[13]) ) {
if( helper.checkPixelLower(index + offsets[14]) ) {
if( helper.checkPixelLower(index + offsets[15]) ) {
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else if( helper.checkPixelLower(index + offsets[10]) ) {
if( helper.checkPixelLower(index + offsets[11]) ) {
if( helper.checkPixelLower(index + offsets[12]) ) {
if( helper.checkPixelLower(index + offsets[13]) ) {
if( helper.checkPixelLower(index + offsets[14]) ) {
if( helper.checkPixelLower(index + offsets[15]) ) {
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else if( helper.checkPixelLower(index + offsets[9]) ) {
if( helper.checkPixelLower(index + offsets[10]) ) {
if( helper.checkPixelLower(index + offsets[11]) ) {
if( helper.checkPixelLower(index + offsets[12]) ) {
if( helper.checkPixelLower(index + offsets[13]) ) {
if( helper.checkPixelLower(index + offsets[14]) ) {
if( helper.checkPixelLower(index + offsets[15]) ) {
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else if( helper.checkPixelLower(index + offsets[8]) ) {
if( helper.checkPixelLower(index + offsets[9]) ) {
if( helper.checkPixelLower(index + offsets[10]) ) {
if( helper.checkPixelLower(index + offsets[11]) ) {
if( helper.checkPixelLower(index + offsets[12]) ) {
if( helper.checkPixelLower(index + offsets[13]) ) {
if( helper.checkPixelLower(index + offsets[14]) ) {
if( helper.checkPixelLower(index + offsets[15]) ) {
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else if( helper.checkPixelLower(index + offsets[7]) ) {
if( helper.checkPixelLower(index + offsets[8]) ) {
if( helper.checkPixelLower(index + offsets[9]) ) {
if( helper.checkPixelLower(index + offsets[10]) ) {
if( helper.checkPixelLower(index + offsets[11]) ) {
if( helper.checkPixelLower(index + offsets[12]) ) {
if( helper.checkPixelLower(index + offsets[13]) ) {
if( helper.checkPixelLower(index + offsets[14]) ) {
if( helper.checkPixelLower(index + offsets[15]) ) {
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else if( helper.checkPixelLower(index + offsets[6]) ) {
if( helper.checkPixelLower(index + offsets[7]) ) {
if( helper.checkPixelLower(index + offsets[8]) ) {
if( helper.checkPixelLower(index + offsets[9]) ) {
if( helper.checkPixelLower(index + offsets[10]) ) {
if( helper.checkPixelLower(index + offsets[11]) ) {
if( helper.checkPixelLower(index + offsets[12]) ) {
if( helper.checkPixelLower(index + offsets[13]) ) {
if( helper.checkPixelLower(index + offsets[14]) ) {
if( helper.checkPixelLower(index + offsets[5]) ) {
if( helper.checkPixelLower(index + offsets[15]) ) {
return true;
} else if( helper.checkPixelLower(index + offsets[3]) ) {
if( helper.checkPixelLower(index + offsets[4]) ) {
return true;
} else {
return false;
}
} else {
return false;
}
} else if( helper.checkPixelLower(index + offsets[15]) ) {
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else if( helper.checkPixelLower(index + offsets[5]) ) {
if( helper.checkPixelLower(index + offsets[6]) ) {
if( helper.checkPixelLower(index + offsets[7]) ) {
if( helper.checkPixelLower(index + offsets[8]) ) {
if( helper.checkPixelLower(index + offsets[9]) ) {
if( helper.checkPixelLower(index + offsets[10]) ) {
if( helper.checkPixelLower(index + offsets[11]) ) {
if( helper.checkPixelLower(index + offsets[12]) ) {
if( helper.checkPixelLower(index + offsets[13]) ) {
if( helper.checkPixelLower(index + offsets[4]) ) {
if( helper.checkPixelLower(index + offsets[14]) ) {
if( helper.checkPixelLower(index + offsets[3]) ) {
return true;
} else if( helper.checkPixelLower(index + offsets[15]) ) {
return true;
} else {
return false;
}
} else if( helper.checkPixelLower(index + offsets[2]) ) {
if( helper.checkPixelLower(index + offsets[3]) ) {
return true;
} else {
return false;
}
} else {
return false;
}
} else if( helper.checkPixelLower(index + offsets[14]) ) {
if( helper.checkPixelLower(index + offsets[15]) ) {
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else if( helper.checkPixelLower(index + offsets[4]) ) {
if( helper.checkPixelLower(index + offsets[5]) ) {
if( helper.checkPixelLower(index + offsets[6]) ) {
if( helper.checkPixelLower(index + offsets[7]) ) {
if( helper.checkPixelLower(index + offsets[8]) ) {
if( helper.checkPixelLower(index + offsets[9]) ) {
if( helper.checkPixelLower(index + offsets[10]) ) {
if( helper.checkPixelLower(index + offsets[11]) ) {
if( helper.checkPixelLower(index + offsets[12]) ) {
if( helper.checkPixelLower(index + offsets[3]) ) {
if( helper.checkPixelLower(index + offsets[13]) ) {
if( helper.checkPixelLower(index + offsets[2]) ) {
return true;
} else if( helper.checkPixelLower(index + offsets[14]) ) {
return true;
} else {
return false;
}
} else if( helper.checkPixelLower(index + offsets[1]) ) {
if( helper.checkPixelLower(index + offsets[2]) ) {
return true;
} else {
return false;
}
} else {
return false;
}
} else if( helper.checkPixelLower(index + offsets[13]) ) {
if( helper.checkPixelLower(index + offsets[14]) ) {
if( helper.checkPixelLower(index + offsets[15]) ) {
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
}
@Override
protected boolean checkUpper( int index )
{
if( helper.checkPixelUpper(index + offsets[0]) ) {
if( helper.checkPixelUpper(index + offsets[1]) ) {
if( helper.checkPixelUpper(index + offsets[2]) ) {
if( helper.checkPixelUpper(index + offsets[3]) ) {
if( helper.checkPixelUpper(index + offsets[4]) ) {
if( helper.checkPixelUpper(index + offsets[5]) ) {
if( helper.checkPixelUpper(index + offsets[6]) ) {
if( helper.checkPixelUpper(index + offsets[7]) ) {
if( helper.checkPixelUpper(index + offsets[8]) ) {
if( helper.checkPixelUpper(index + offsets[9]) ) {
if( helper.checkPixelUpper(index + offsets[10]) ) {
if( helper.checkPixelUpper(index + offsets[11]) ) {
return true;
} else if( helper.checkPixelUpper(index + offsets[15]) ) {
return true;
} else {
return false;
}
} else if( helper.checkPixelUpper(index + offsets[14]) ) {
if( helper.checkPixelUpper(index + offsets[15]) ) {
return true;
} else {
return false;
}
} else {
return false;
}
} else if( helper.checkPixelUpper(index + offsets[13]) ) {
if( helper.checkPixelUpper(index + offsets[14]) ) {
if( helper.checkPixelUpper(index + offsets[15]) ) {
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else if( helper.checkPixelUpper(index + offsets[12]) ) {
if( helper.checkPixelUpper(index + offsets[13]) ) {
if( helper.checkPixelUpper(index + offsets[14]) ) {
if( helper.checkPixelUpper(index + offsets[15]) ) {
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else if( helper.checkPixelUpper(index + offsets[11]) ) {
if( helper.checkPixelUpper(index + offsets[12]) ) {
if( helper.checkPixelUpper(index + offsets[13]) ) {
if( helper.checkPixelUpper(index + offsets[14]) ) {
if( helper.checkPixelUpper(index + offsets[15]) ) {
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else if( helper.checkPixelUpper(index + offsets[10]) ) {
if( helper.checkPixelUpper(index + offsets[11]) ) {
if( helper.checkPixelUpper(index + offsets[12]) ) {
if( helper.checkPixelUpper(index + offsets[13]) ) {
if( helper.checkPixelUpper(index + offsets[14]) ) {
if( helper.checkPixelUpper(index + offsets[15]) ) {
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else if( helper.checkPixelUpper(index + offsets[9]) ) {
if( helper.checkPixelUpper(index + offsets[10]) ) {
if( helper.checkPixelUpper(index + offsets[11]) ) {
if( helper.checkPixelUpper(index + offsets[12]) ) {
if( helper.checkPixelUpper(index + offsets[13]) ) {
if( helper.checkPixelUpper(index + offsets[14]) ) {
if( helper.checkPixelUpper(index + offsets[15]) ) {
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else if( helper.checkPixelUpper(index + offsets[8]) ) {
if( helper.checkPixelUpper(index + offsets[9]) ) {
if( helper.checkPixelUpper(index + offsets[10]) ) {
if( helper.checkPixelUpper(index + offsets[11]) ) {
if( helper.checkPixelUpper(index + offsets[12]) ) {
if( helper.checkPixelUpper(index + offsets[13]) ) {
if( helper.checkPixelUpper(index + offsets[14]) ) {
if( helper.checkPixelUpper(index + offsets[15]) ) {
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else if( helper.checkPixelUpper(index + offsets[7]) ) {
if( helper.checkPixelUpper(index + offsets[8]) ) {
if( helper.checkPixelUpper(index + offsets[9]) ) {
if( helper.checkPixelUpper(index + offsets[10]) ) {
if( helper.checkPixelUpper(index + offsets[11]) ) {
if( helper.checkPixelUpper(index + offsets[12]) ) {
if( helper.checkPixelUpper(index + offsets[13]) ) {
if( helper.checkPixelUpper(index + offsets[14]) ) {
if( helper.checkPixelUpper(index + offsets[15]) ) {
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else if( helper.checkPixelUpper(index + offsets[6]) ) {
if( helper.checkPixelUpper(index + offsets[7]) ) {
if( helper.checkPixelUpper(index + offsets[8]) ) {
if( helper.checkPixelUpper(index + offsets[9]) ) {
if( helper.checkPixelUpper(index + offsets[10]) ) {
if( helper.checkPixelUpper(index + offsets[11]) ) {
if( helper.checkPixelUpper(index + offsets[12]) ) {
if( helper.checkPixelUpper(index + offsets[13]) ) {
if( helper.checkPixelUpper(index + offsets[14]) ) {
if( helper.checkPixelUpper(index + offsets[5]) ) {
if( helper.checkPixelUpper(index + offsets[15]) ) {
return true;
} else if( helper.checkPixelUpper(index + offsets[3]) ) {
if( helper.checkPixelUpper(index + offsets[4]) ) {
return true;
} else {
return false;
}
} else {
return false;
}
} else if( helper.checkPixelUpper(index + offsets[15]) ) {
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else if( helper.checkPixelUpper(index + offsets[5]) ) {
if( helper.checkPixelUpper(index + offsets[6]) ) {
if( helper.checkPixelUpper(index + offsets[7]) ) {
if( helper.checkPixelUpper(index + offsets[8]) ) {
if( helper.checkPixelUpper(index + offsets[9]) ) {
if( helper.checkPixelUpper(index + offsets[10]) ) {
if( helper.checkPixelUpper(index + offsets[11]) ) {
if( helper.checkPixelUpper(index + offsets[12]) ) {
if( helper.checkPixelUpper(index + offsets[13]) ) {
if( helper.checkPixelUpper(index + offsets[4]) ) {
if( helper.checkPixelUpper(index + offsets[14]) ) {
if( helper.checkPixelUpper(index + offsets[3]) ) {
return true;
} else if( helper.checkPixelUpper(index + offsets[15]) ) {
return true;
} else {
return false;
}
} else if( helper.checkPixelUpper(index + offsets[2]) ) {
if( helper.checkPixelUpper(index + offsets[3]) ) {
return true;
} else {
return false;
}
} else {
return false;
}
} else if( helper.checkPixelUpper(index + offsets[14]) ) {
if( helper.checkPixelUpper(index + offsets[15]) ) {
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else if( helper.checkPixelUpper(index + offsets[4]) ) {
if( helper.checkPixelUpper(index + offsets[5]) ) {
if( helper.checkPixelUpper(index + offsets[6]) ) {
if( helper.checkPixelUpper(index + offsets[7]) ) {
if( helper.checkPixelUpper(index + offsets[8]) ) {
if( helper.checkPixelUpper(index + offsets[9]) ) {
if( helper.checkPixelUpper(index + offsets[10]) ) {
if( helper.checkPixelUpper(index + offsets[11]) ) {
if( helper.checkPixelUpper(index + offsets[12]) ) {
if( helper.checkPixelUpper(index + offsets[3]) ) {
if( helper.checkPixelUpper(index + offsets[13]) ) {
if( helper.checkPixelUpper(index + offsets[2]) ) {
return true;
} else if( helper.checkPixelUpper(index + offsets[14]) ) {
return true;
} else {
return false;
}
} else if( helper.checkPixelUpper(index + offsets[1]) ) {
if( helper.checkPixelUpper(index + offsets[2]) ) {
return true;
} else {
return false;
}
} else {
return false;
}
} else if( helper.checkPixelUpper(index + offsets[13]) ) {
if( helper.checkPixelUpper(index + offsets[14]) ) {
if( helper.checkPixelUpper(index + offsets[15]) ) {
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
}
}
| mit |
jenkinsci/analysis-runner | src/main/java/edu/hm/hafner/ParameterAssignment.java | 1565 | package edu.hm.hafner;
import java.util.Date;
/**
* Useless class - only for test-cases.
*
* @author Christian Möstl
*/
public class ParameterAssignment {
private Date date;
private int number;
private final String text;
/**
* Creates a new instance of {@link ParameterAssignment}.
*
* @param date
* Date
* @param number
* number
* @param text
* Text
*/
public ParameterAssignment(final Date date, final int number, final String text) {
this.date = date;
this.number = number;
this.text = text;
}
/**
* Do sth...
* @param a number
*/
public void doSth(int a) {
int b = 0;
if (a > 0) {
System.out.println(">0");
if (a == 1) {
++b;
System.out.println("a=1");
a = b;
if (a == 2) {
System.out.println("a=2");
}
}
}
System.out.println(b);
}
/**
* Returns the date.
*
* @return the date
*/
public Date getDate() {
return date;
}
/**
* Returns the number.
*
* @return the number
*/
public int getNumber() {
return number;
}
/**
* Returns the text.
*
* @return the text
*/
public String getText() {
return text;
}
} | mit |
tbepler/JProbe | src/util/xmlserializer/XMLSerializerUtil.java | 35207 | package util.xmlserializer;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.lang.reflect.*;
import java.util.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.*;
import org.xml.sax.InputSource;
import com.sun.org.apache.xerces.internal.parsers.DOMParser;
/**
* This class can be used to serialize objects as XML to files or OutputStreams and deserialize objects from those XML
* files or InputStreams, in a manner similar to how java serialization works. Objects you wish to serialize should implement
* the {@link Serializable} interface. There are also a few objects that cannot be instantiated due to java's internal security.
* I included a work around for instantiating Class objects, but there may be others that can not be deserialized properly.
* Furthermore, if your object contains objects that do not implement Serializable, those objects must have a public or protected
* default constructor available to initialize their state. I would advise making all contents serializable,
* not serializing objects with those components, using the @{@link XMLIgnore} annotation to ignore those fields, or defining
* custom read and write methods for your object.
* <p>
* I have also added support for implementing custom read and write methods to objects. They must follow this exact
* signature:
* <p>
* private void writeObjectXML(WriteField writer) throws ObjectWriteException;
* <p>
* private void readObjectXML(ReadField reader) throws ObjectReadException;
* <p>
* The write object method is responsible for writing out the fields you wish to save. The read object method
* is responsible for restoring the object's state from the xml written by your write method. These methods are only responsible
* for your object's fields, not any superclass's fields. The Write- and ReadField objects provide methods for writing out
* or reading in your data fields. Note that if you implement write object, you should also implement read object or there is
* a good chance that the default reading behavior will not be able to successfully restore your object's fields.
* <p>
* Furthermore, while I have tried to test this these methods on a variety of classes, I cannot guarantee that it
* will work in all cases. If bugs come up, you can try to fix them or let me know, and I will try to fix them. As
* a further note, I am aware that this class does not contain elegant code. The read and write algorithms are complicated
* and functionality is the priority.
* <p>
* This class relies on the SilentObjectCreator to get the SerializationConstructor that is used to construct
* the read objects without invoking their constructors. This means that the SilentObjectCreator must use the sun.reflect
* package and, therefore, could be broken in future Java versions. It also means that each object you wish to serialize
* to XML using this class should implement the Serializable interface or inherit it from a superclass. Any objects it
* contains and its superclasses should also implement Serializable whenever possible. Output may be unpredictable
* if this is not the case.
* <p>
* To allow subtypes of non-serializable classes to be serialized, the subtype may assume responsibility for saving and
* restoring the state of the supertype's public, protected, and (if accessible) package fields. The subtype may assume
* this responsibility only if the class it extends has an accessible no-arg constructor to initialize the class's state.
* It is an error to declare a class Serializable in this case. The error will be detected at runtime. During deserialization,
* the fields of non-serializable classes will be initialized using the public or protected no-arg constructor of the class.
* A no-arg constructor must be accessible to the subclass that is serializable. The fields of serializable subclasses will
* be restored from the stream
* <p>
* Finally, several objects are constructed using special cases, this is either to prevent security exceptions, as is
* the case for the Class class, or to make their outputs less verbose, as is the case for Strings and Maps. I have
* included test cases in {@link TestXMLObjectSerializer} that should help illustrate the usage of this class.
* {@author Tristan Bepler}
* <p>
* The method formatXML has been added to create indentations for better readability, and also to omit the XML declaration
* at the beginning of the file. {@author Alex Song}
* <p>
* Happy serializing.
*
* @author Tristan Bepler
* @author Alex Song
* @version 1.1
*
* @see Serializable
* @see TestXMLObjectSerializer
* @see XMLIgnore
*
*/
public class XMLSerializerUtil {
private static final String DOM_WILDCARD = "*";
private static final String MODIFIERS = "modifiers";
private static final String CUSTOM_READ = "readObjectXML";
private static final String CUSTOM_WRITE = "writeObjectXML";
private static final String VALUE = "value";
private static final String KEY = "key";
private static final String INDEX = "index";
private static final String ENTRY = "entry";
private static final String CLASSPATH = "classpath";
private static final String SUPERCLASS = "superclass";
private static final String CLASSFIELDS = "fields";
private static final String REF_ID = "refId";
private static final String SEE_REF_ID = "seeRefId";
private static final Map<Class<?>, Class<?>> WRAPPER_TYPES = getWrapperTypes();
private static final Map<Character, Character> REPLACEMENT_MAP = replacementMap();
private static final Map<String, Class<?>> PRIMITIVE_CLASSES = primitiveClasses();
public static boolean isWrapperType(Class<?> clazz){
return WRAPPER_TYPES.values().contains(clazz);
}
public static Class<?> getWrapper(Class<?> clazz){
return WRAPPER_TYPES.get(clazz);
}
private static Map<Character, Character> replacementMap(){
Map<Character, Character> map = new HashMap<Character, Character>();
map.put('$', '.');
map.put('.', '$');
return map;
}
private static Map<String, Class<?>> primitiveClasses(){
Map<String, Class<?>> map = new HashMap<String, Class<?>>();
map.put("boolean", boolean.class);
map.put("byte", byte.class);
map.put("short", short.class);
map.put("int", int.class);
map.put("long", long.class);
map.put("char", char.class);
map.put("float", float.class);
map.put("double", double.class);
map.put("void", void.class);
return map;
}
private static Map<Class<?>, Class<?>> getWrapperTypes(){
Map<Class<?>, Class<?>> ret = new HashMap<Class<?>, Class<?>>();
ret.put(Boolean.TYPE, Boolean.class);
ret.put(Character.TYPE, Character.class);
ret.put(Byte.TYPE, Byte.class);
ret.put(Short.TYPE, Short.class);
ret.put(Integer.TYPE, Integer.class);
ret.put(Long.TYPE, Long.class);
ret.put(Float.TYPE, Float.class);
ret.put(Double.TYPE, Double.class);
ret.put(Void.TYPE, Void.class);
return ret;
}
/**
* This method parses the given value into the specified primitive or wrapper class.
* @param clazz - primitive or wrapper class used to parse
* @param value - string to be parsed
* @return object of type clazz parsed from the string
* @author Trisan Bepler
*/
public static Object toObject( Class<?> clazz, String value ) {
if( Boolean.TYPE == clazz ) return Boolean.parseBoolean( value );
if( Byte.TYPE == clazz ) return Byte.parseByte( value );
if( Short.TYPE == clazz ) return Short.parseShort( value );
if( Integer.TYPE == clazz ) return Integer.parseInt( value );
if( Long.TYPE == clazz ) return Long.parseLong( value );
if( Float.TYPE == clazz ) return Float.parseFloat( value );
if( Double.TYPE == clazz ) return Double.parseDouble( value );
if( Boolean.class == clazz ) return Boolean.parseBoolean( value );
if( Byte.class == clazz ) return Byte.parseByte( value );
if( Short.class == clazz ) return Short.parseShort( value );
if( Integer.class == clazz ) return Integer.parseInt( value );
if( Long.class == clazz ) return Long.parseLong( value );
if( Float.class == clazz ) return Float.parseFloat( value );
if( Double.class == clazz ) return Double.parseDouble( value );
if( Character.class == clazz) return value.charAt(0);
if( Character.TYPE == clazz) return value.charAt(0);
return value;
}
/**
* This class is used to put fields on the element it is initialized with.
*
* @author Tristan Bepler
*
*/
public static class WriteField{
private Element cur;
private Document doc;
private List<Object> written;
private WriteField(Element cur, Document doc, List<Object> written){
this.cur = cur;
this.doc = doc;
this.written = written;
}
private void newChildText(String name, String content){
Element e = doc.createElement(name);
cur.appendChild(e);
e.setTextContent(content);
}
public void write(String name, boolean value){
newChildText(name, String.valueOf(value));
}
public void write(String name, char value){
newChildText(name, String.valueOf(value));
}
public void write(String name, byte value){
newChildText(name, String.valueOf(value));
}
public void write(String name, short value){
newChildText(name, String.valueOf(value));
}
public void write(String name, int value){
newChildText(name, String.valueOf(value));
}
public void write(String name, long value){
newChildText(name, String.valueOf(value));
}
public void write(String name, float value){
newChildText(name, String.valueOf(value));
}
public void write(String name, double value){
newChildText(name, String.valueOf(value));
}
/**
* Creates a new child node with the given name and uses it to write the given object.
* @param name - name of new child node
* @param value - object to be written
* @throws ObjectWriteException
*/
public void write(String name, Object value) throws ObjectWriteException{
Element child = doc.createElement(name);
cur.appendChild(child);
fillTreeRecurse(value, child, doc, written);
}
}
/**
* This class is used to read fields from the element it is initialized with.
*
* @author Tristan Bepler
*
*/
public static class ReadField{
private Element cur;
private List<Element> children;
private ClassLoader loader;
private Map<Integer, Object> references;
private ReadField(Element cur, ClassLoader loader, Map<Integer, Object> references){
this.cur = cur;
this.loader = loader;
this.references = references;
this.children = getDirectChildElementsByTag(cur, DOM_WILDCARD);
}
private Element getChild(String tag){
for(Element e : children){
if(e.getNodeName().equals(tag)){
return e;
}
}
return null;
}
/**
* Returns the class of this object
* @return class of object
* @throws ClassNotFoundException
*/
public Class<?> getObjectClass() throws ClassNotFoundException{
if(cur.hasAttribute(CLASSPATH)){
try{
return loader.loadClass(cur.getAttribute(CLASSPATH));
} catch(Exception e){
return Class.forName(cur.getAttribute(CLASSPATH));
}
}
return null;
}
public boolean read(String name, boolean def){
Element e = getChild(name);
if(e!=null){
return Boolean.parseBoolean(e.getTextContent());
}
return def;
}
public char read(String name, char def){
Element e = getChild(name);
if(e!=null){
return e.getTextContent().charAt(0);
}
return def;
}
public byte read(String name, byte def){
Element e = getChild(name);
if(e!=null){
return Byte.parseByte(e.getTextContent());
}
return def;
}
public short read(String name, short def){
Element e = getChild(name);
if(e!=null){
return Short.parseShort(e.getTextContent());
}
return def;
}
public int read(String name, int def){
Element e = getChild(name);
if(e!=null){
return Integer.parseInt(e.getTextContent());
}
return def;
}
public long read(String name, long def){
Element e = getChild(name);
if(e!=null){
return Long.parseLong(e.getTextContent());
}
return def;
}
public float read(String name, float def){
Element e = getChild(name);
if(e!=null){
return Float.parseFloat(e.getTextContent());
}
return def;
}
public double read(String name, double def){
Element e = getChild(name);
if(e!=null){
return Double.parseDouble(e.getTextContent());
}
return def;
}
/**
* Reads the specified node name for an object, returns the default object if no such node exists.
* @param name - name of child node to search
* @param def - default object to return
* @return - the object read from the child node with the given name or the default object if there
* was none
* @throws ObjectReadException
*/
public Object read(String name, Object def) throws ObjectReadException{
Element e = getChild(name);
if(e!=null){
return readTreeRecurse(e, loader, references);
}
return def;
}
}
/**
* This method is used to serialize the given object as XML to the given OutputStream. Objects should implement
* the Serializable interface or inherit it from a superclass. Furthermore, as many superclasses and contained
* classes should implement Serializable as possible. If they do not, behavior may be unpredictable. See this
* classes description for more information. {@link XMLSerializerUtil}
* @param o - object to be serialized to XML
* @param out - OutputStream this object will be written to
* @throws ObjectWriteException
* @author Tristan Bepler
*/
public static void serialize(Object o, OutputStream out) throws ObjectWriteException{
try{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
fillTreeRecurse(o, null, doc, new ArrayList<Object>());
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setAttribute("indent-number", 2);
Transformer transformer = formatXML(transformerFactory.newTransformer());
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(out);
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(source, result);
}catch(Exception e){
throw new ObjectWriteException(e);
}
}
/**
* This method is used to serialize the given object to XML. The object XML will be written to a file at the path
* specified by the given string. Objects should implement the Serializable interface or inherit it from a superclass.
* Furthermore, as many superclasses and contained classes should implement Serializable as possible. If they do not,
* behavior may be unpredictable. See this classes description for more information. {@link XMLSerializerUtil}
* @param o - object to be serialized to XML
* @param file - file the object XML should be written to
* @throws ObjectWriteException
* @author Tristan Bepler
*/
public static void write(Object o, String file) throws ObjectWriteException{
try{
serialize(o, new BufferedOutputStream(new FileOutputStream(file)));
} catch (Exception e){
throw new ObjectWriteException(e);
}
}
/**
* This method recursively serializes objects.
* @author Tristan Bepler
*/
private static void fillTreeRecurse(Object o, Element parent, Document doc, List<Object> written) throws ObjectWriteException{
try{
// write nothing if o is null
if(o == null){
return;
}
//initialize parent node if uninitialized
if(parent == null){
parent = doc.createElement(o.getClass().getSimpleName());
doc.appendChild(parent);
}
//set the classpath of this object as an attribute of the node
parent.setAttribute(CLASSPATH, o.getClass().getName());
//simply write the objects value if it is a primitive wrapper
if(XMLSerializerUtil.isWrapperType(o.getClass())){
parent.setTextContent(String.valueOf(o));
return;
}
//if the object references an object that has already been written, tag it's refId
if(written.contains(o)){
parent.setAttribute(SEE_REF_ID, String.valueOf(written.indexOf(o)));
return;
}
//add this object to the written object array and set its refId
written.add(o);
parent.setAttribute(REF_ID, String.valueOf(written.indexOf(o)));
//special cases
if(writeSpecialCaseObjectIsString(o, parent, doc, written)){
return;
}
if(writeSpecialCaseObjectIsClass(o, parent, doc, written)){
return;
}
if(writeSpecialCaseObjectIsMap(o, parent, doc, written)){
return;
}
//if object is an array, have to handle it specially, recursively write array elements
if(o.getClass().isArray()){
writeArray(o, parent, doc, written);
return;
}
//object is a proper object, check and write its superclass and fill all fields
writeObject(o, parent, doc, written);
} catch (IllegalArgumentException e){
throw new ObjectWriteException(e);
} catch (IllegalAccessException e){
throw new ObjectWriteException();
}
}
/**
* Writes the object by recursively iterating over its class and superclass fields
*
* @author Tristan Bepler
*/
private static void writeObject(Object o, Element parent, Document doc, List<Object> written) throws IllegalAccessException, ObjectWriteException {
//init class
Class<?> clazz = o.getClass();
//now write the class and superclass fields recursively
writeFieldsRecurse(o, parent, doc, written, clazz);
}
/**
* Recursively writes the fields of this class and its superclasses
*
* @author Tristan Bepler
*/
private static void writeFieldsRecurse(Object o, Element parent, Document doc, List<Object> written, Class<?> clazz) throws IllegalAccessException, ObjectWriteException {
if(!Serializable.class.isAssignableFrom(clazz)){
try {
Constructor con = clazz.getDeclaredConstructor();
if(con.getModifiers() != Modifier.PUBLIC && con.getModifiers() != Modifier.PROTECTED){
throw new ObjectWriteException("Non-serializable class \""+clazz+"\" does not have a public or protected default constructor.");
}
} catch (Exception e){
throw new ObjectWriteException("Non-serializable class \""+clazz+"\" does not have a public or protected default constructor.");
}
return;
}
Element classNode = doc.createElement(CLASSFIELDS);
parent.appendChild(classNode);
WriteField writer = new WriteField(classNode, doc, written);
//check if custom write method defined
try {
Method write = clazz.getDeclaredMethod(CUSTOM_WRITE, WriteField.class);
if(write.getExceptionTypes()[0] == ObjectWriteException.class){
write.setAccessible(true);
write.invoke(o, writer);
}
}catch (InvocationTargetException e){
throw new ObjectWriteException(e);
} catch (Exception e){
writeFieldDefault(o, clazz, writer);
}
if(!classNode.hasChildNodes()){
parent.removeChild(classNode);
}
clazz = clazz.getSuperclass();
if(clazz == null){
return;
}
Element superNode = doc.createElement(SUPERCLASS);
parent.appendChild(superNode);
superNode.setAttribute(CLASSPATH, clazz.getName());
writeFieldsRecurse(o, superNode, doc, written, clazz);
}
/**
* The default field writing method
*
* @author Tristan Bepler
*/
private static void writeFieldDefault(Object o, Class<?> clazz, WriteField writer) throws IllegalAccessException, ObjectWriteException {
for(Field f : clazz.getDeclaredFields()){
f.setAccessible(true);
Object value = f.get(o);
//ignore this field if it is null or static and final or annotated by @XMLIgnore
if(value==null){
continue;
}
if(f.isAnnotationPresent(XMLIgnore.class)){
continue;
}
if(Modifier.isStatic(f.getModifiers())&&Modifier.isFinal(f.getModifiers())){
continue;
}
String name = f.getName();
name = name.replace('$', REPLACEMENT_MAP.get('$'));
writer.write(name, value);
}
}
/**
* Writes array by iterating over the elements
*
* @author Tristan Bepler
*/
private static void writeArray(Object o, Element parent, Document doc, List<Object> written) throws IllegalAccessException, ArrayIndexOutOfBoundsException, IllegalArgumentException, ObjectWriteException {
for(int i=0; i<Array.getLength(o); i++){
Element entry = doc.createElement(ENTRY);
parent.appendChild(entry);
entry.setAttribute(INDEX, String.valueOf(i));
fillTreeRecurse(Array.get(o, i), entry, doc, written);
}
}
/**
* Returns all the unique fields of the classes in the given list.
* @author Tristan Bepler
*/
private static Field[] getAllFields(List<Class<?>> classes){
Set<Field> fields = new HashSet<Field>();
for(Class<?> clazz : classes){
fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
}
return fields.toArray(new Field[fields.size()]);
}
/**
* Method for handling serialization of String objects.
* @author Tristan Bepler
*/
private static boolean writeSpecialCaseObjectIsString(Object o, Element cur, Document doc, List<Object> written){
if(o instanceof String){
cur.setTextContent((String) o);
return true;
}
return false;
}
/**
* Method for handling deserialization of String objects.
* @author Tristan Bepler
*/
private static String readSpecialCaseObjectIsString(Class<?> clazz, Element cur){
if(clazz == String.class){
return cur.getTextContent();
}
return null;
}
/**
* Method for handling serialization of class objects.
* @author Tristan Bepler
*/
private static boolean writeSpecialCaseObjectIsClass(Object o, Element cur, Document doc, List<Object> written){
if(o instanceof Class){
cur.setTextContent(((Class)o).getName());
return true;
}
return false;
}
/**
* Method for handling deserialization of class objects.
* @author Tristan Bepler
*/
private static Object readSpecialCaseObjectIsClass(Class<?> clazz, Element cur, ClassLoader loader) throws ClassNotFoundException{
if(Class.class == clazz){
if(PRIMITIVE_CLASSES.containsKey(cur.getTextContent())){
return PRIMITIVE_CLASSES.get(cur.getTextContent());
}
try{
return loader.loadClass(cur.getTextContent());
} catch (Exception e){
return Class.forName(cur.getTextContent());
}
}
return null;
}
/**
* Method for handling serialization of map objects. Maps were very verbose before.
* @author Tristan Bepler
*/
private static boolean writeSpecialCaseObjectIsMap(Object o, Element cur, Document doc, List<Object> written) throws IllegalArgumentException, IllegalAccessException, ObjectWriteException {
if(o instanceof Map){
Map map = (Map) o;
for(Object key : map.keySet()){
Element entry = doc.createElement(ENTRY);
cur.appendChild(entry);
WriteField writer = new WriteField(entry, doc, written);
writer.write(KEY, key);
writer.write(VALUE, map.get(key));
}
return true;
}
return false;
}
/**
* This method handled deserialization of map objects.
* @author Tristan Bepler
*/
private static Map readSpecialCaseObjectIsMap(Class<?> clazz, Element cur, ClassLoader loader, Map<Integer, Object> references) throws Exception{
if(Map.class.isAssignableFrom(clazz)){
try{
Constructor con = clazz.getConstructor();
con.setAccessible(true);
Map map = (Map) con.newInstance();
addReference(cur, references, map);
List<Element> entries = getDirectChildElementsByTag(cur, ENTRY);
for(Element entry: entries){
ReadField reader = new ReadField(entry, loader, references);
Object key = reader.read(KEY, null);
Object value = reader.read(VALUE, null);
map.put(key, value);
}
return map;
}catch (Exception e){
throw new Exception(e);
}
}
return null;
}
/**
* This method is used to deserialize a previously XML serialized object from the given InputStream. The ClassLoader
* will be used to retrieve the classes required for object instantiation. This is to allow loading of classes
* from external sources if necessary. See this classes description for more information on object serialization
* and deserialization.{@link XMLSerializerUtil}
* @param in - the InputStream the object will be deserialized from
* @param loader - a ClassLoader that will be used to load Class objects
* @return - the deserialized object
* @throws ObjectReadException
* @author Tristan Bepler
*/
public static Object deserialize(InputStream in, ClassLoader loader) throws ObjectReadException{
try {
DOMParser parser = new DOMParser();
parser.parse(new InputSource(in));
Document doc = parser.getDocument();
doc.getDocumentElement().normalize();
return readTreeRecurse(doc.getDocumentElement(), loader, new HashMap<Integer, Object>());
} catch (Exception e) {
throw new ObjectReadException(e);
}
}
/**
* This method is used to deserialize a previously XML serialized object from the given InputStream. See this
* classes description for more information on object serialization and deserialization.{@link XMLSerializerUtil}
* @param in - the InputStream the object will be deserialized from
* @return - the deserialized object
* @throws ObjectReadException
* @author Trisan Bepler
*/
public static Object deserialize(InputStream in) throws ObjectReadException{
return deserialize(in, ClassLoader.getSystemClassLoader());
}
/**
* This method is used to deserialize a previously serialized object from the XML file it was written to. The
* ClassLoader will be used to retrieve the classes required for object instantiation. This is to allow loading
* of classes from external sources if necessary. See this classes description for more information on object
* serialization and deserialization.{@link XMLSerializerUtil}
* @param file - the file containing the object XML
* @param loader - a ClassLoader that will be used to load Class objects.
* @return - the deserialized object
* @throws ObjectReadException
* @author Tristan Bepler
*/
public static Object read(String file, ClassLoader loader) throws ObjectReadException{
try {
return deserialize(new BufferedInputStream(new FileInputStream(file)), loader);
} catch (Exception e) {
throw new ObjectReadException(e);
}
}
/**
* This method is used to deserialize and object from its serialized object XML. The path of the file the object
* should be deserialized from is specified by the file parameter. See this classes description for more
* information about object serialization and deserialization.{@link XMLSerializerUtil}
* @param file - the file containing the object XML
* @return - the deserialized object
* @throws ObjectReadException
* @author Tristan Bepler
*/
public static Object read(String file) throws ObjectReadException{
return read(file, ClassLoader.getSystemClassLoader());
}
/**
* This method recursively deserializes objects
* @author Tristan Bepler
*/
private static Object readTreeRecurse(Element cur, ClassLoader loader, Map<Integer, Object> references) throws ObjectReadException{
try{
//if cur is null return null
if(cur == null){
return null;
}
//if cur is already written elswhere, read it from it's reference
if(cur.hasAttribute(SEE_REF_ID)){
int refId = Integer.parseInt(cur.getAttribute(SEE_REF_ID));
try{
return references.get(refId);
} catch(Exception e){
throw new ObjectReadException("Error: could find reference object");
}
}
//if cur has no classpath specified, return null
if(!cur.hasAttribute(CLASSPATH)){
return null;
}
//get the class of cur
Class<?> c;
try{
c = (Class<?>) loader.loadClass(cur.getAttribute(CLASSPATH));
} catch(Exception e){
c = (Class<?>) Class.forName(cur.getAttribute(CLASSPATH));
}
//if cur is a wrapper type, parse and return it
if(isWrapperType(c)){
return toObject(c, cur.getTextContent().trim());
}
//if cur is an instance of the Class class
Object isClass = readSpecialCaseObjectIsClass(c, cur, loader);
if(isClass != null){
addReference(cur, references, isClass);
return isClass;
}
//special case, if cur is a string return it
Object isString = readSpecialCaseObjectIsString(c, cur);
if(isString != null){
addReference(cur, references, isString);
return isString;
}
//special case, if cur is a map return it
Object isMap = readSpecialCaseObjectIsMap(c, cur, loader, references);
if(isMap != null){
return isMap;
}
//if cur is an array, instantiate it and recursively build its elements
if(c.isArray()){
return readArray(c, cur, loader, references);
}
//get first non-serializable superclass
Class nonSerial = c;
while(Serializable.class.isAssignableFrom(nonSerial)){
nonSerial = nonSerial.getSuperclass();
}
//create object using constructor of its highest level superclass not implementing serializable
Object readObject = SilentObjectCreator.create(c, nonSerial);
//add object to the references map
addReference(cur, references, readObject);
readFieldsRecurse(readObject, cur, loader, references, c);
return readObject;
} catch (Exception e) {
throw new ObjectReadException(e);
}
}
/**
* Fills this class and super classes' fields recursively.
*
* @author Tristan Bepler
*/
private static void readFieldsRecurse(Object readObject, Element cur, ClassLoader loader, Map<Integer, Object> references, Class<?> clazz) throws ObjectReadException, NoSuchFieldException, IllegalAccessException {
if(!Serializable.class.isAssignableFrom(clazz)){
return;
}
if(hasChild(cur, CLASSFIELDS)){
Element classNode = getDirectChildElementsByTag(cur, CLASSFIELDS).get(0);
//check if custom read method defined
try {
Method read = clazz.getDeclaredMethod(CUSTOM_READ, ReadField.class);
if(read.getExceptionTypes()[0] == ObjectReadException.class){
ReadField reader = new ReadField(classNode, loader, references);
read.setAccessible(true);
read.invoke(readObject, reader);
}
} catch (InvocationTargetException e){
throw new ObjectReadException(e);
} catch (Exception e){
//try default
readFieldsDefault(classNode, loader, references, readObject, clazz);
}
}
//fill superclass fields recursively
clazz = clazz.getSuperclass();
if(clazz == null){
return;
}
Element superNode = getDirectChildElementsByTag(cur, SUPERCLASS).get(0);
readFieldsRecurse(readObject, superNode, loader, references, clazz);
}
/**
* Iterates over and fills all the object's fields
*
* @author Tristan Bepler
*/
private static void readFieldsDefault(Element cur, ClassLoader loader, Map<Integer, Object> references, Object readObject, Class<?> clazz) throws NoSuchFieldException, IllegalAccessException, ObjectReadException {
for(Field f : clazz.getDeclaredFields()){
f.setAccessible(true);
//if field is final static or transient, ignore
if(Modifier.isStatic(f.getModifiers())&&Modifier.isFinal(f.getModifiers())){
continue;
}
//if field is annoted with @XMLIgnore, ignore
if(f.isAnnotationPresent(XMLIgnore.class)){
continue;
}
//if field is final, remove final modifier
if(Modifier.isFinal(f.getModifiers())){
Field mods = Field.class.getDeclaredField(MODIFIERS);
mods.setAccessible(true);
mods.setInt(f, f.getModifiers() & ~Modifier.FINAL);
}
String name = f.getName();
name = name.replace('$', REPLACEMENT_MAP.get('$'));
ReadField reader = new ReadField(cur, loader, references);
f.set(readObject, reader.read(name, null));
}
}
/**
* Returns a list of classes containing the class of the object and all its super classes
*
* @author Tristan Bepler
*/
private static List<Class<?>> getSupers(Object o) {
List<Class<?>> classes = new ArrayList<Class<?>>();
Class<?> curClass = o.getClass();
while(curClass != null){
classes.add(curClass);
curClass = curClass.getSuperclass();
}
return classes;
}
/**
* Builds the array by iterating over its elements
*
* @author Tristan Bepler
*/
private static Object readArray(Class<?> c, Element cur, ClassLoader loader, Map<Integer, Object> references) throws ObjectReadException {
List<Element> children = getDirectChildElementsByTag(cur, ENTRY);
Object readArray = Array.newInstance(c.getComponentType(), children.size());
addReference(cur, references, readArray);
for(Element entry : children){
int index = Integer.parseInt(entry.getAttribute(INDEX));
Array.set(readArray, index, readTreeRecurse(entry, loader, references));
}
return readArray;
}
/**
* Adds a reference for the given object to the references map if it has a refId
*
* @author Tristan Bepler
*/
private static void addReference(Element cur, Map<Integer, Object> references, Object o) {
if(cur.hasAttribute(REF_ID)){
int id = Integer.parseInt(cur.getAttribute(REF_ID));
references.put(id, o);
}
}
/**
* This method returns a list of the direct element node children of this element node with the specified tag.
* @param node - parent node
* @param tag - tag of direct children to be returned
* @return a list containing the direct element children with the given tag
* @author Tristan Bepler
*/
public static List<Element> getDirectChildElementsByTag(Element node, String tag){
List<Element> children = new ArrayList<Element>();
Node child = node.getFirstChild();
while(child!=null){
if(child.getNodeType() == Node.ELEMENT_NODE && (child.getNodeName().equals(tag) || tag.equals(DOM_WILDCARD))){
children.add((Element) child);
}
child = child.getNextSibling();
}
return children;
}
/**
* This method checks whether the given element node has a child element with the given name.
* @param node - parent to check
* @param name - name of child
* @return - true if parent has a child with the given name, false otherwise
*/
public static boolean hasChild(Element node, String name){
List<Element> children = getDirectChildElementsByTag(node, DOM_WILDCARD);
for(Element e : children){
if(e.getNodeName().equals(name)){
return true;
}
}
return false;
}
/**
* This method formats the XML file by omitting the XML Declaration and
* creating indentations
* @param transformer - transformer that is used to process XML
* @return a transformer that omits the XML declaration and performs indentations
* @author Alex Song
*/
private static Transformer formatXML(Transformer transformer) {
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
return transformer;
}
}
| mit |
mayconbordin/boardhood | mobile_app/BoardHood/src/com/boardhood/mobile/activity/SignupActivity.java | 8401 | package com.boardhood.mobile.activity;
import org.apache.http.conn.HttpHostConnectException;
import com.boardhood.api.exception.ValidationError;
import com.boardhood.api.exception.ValidationException;
import com.boardhood.api.model.User;
import com.boardhood.mobile.BoardHoodClientManager;
import com.boardhood.mobile.BoardHoodWebCacheClient;
import com.boardhood.mobile.CredentialManager;
import com.boardhood.mobile.R;
import com.boardhood.mobile.activity.base.BoardHoodActivity;
import com.boardhood.mobile.loader.UserCreateTask;
import com.boardhood.mobile.utils.NetworkUtil;
import com.boardhood.mobile.utils.TaskLoader;
import com.boardhood.mobile.utils.Validator;
import com.boardhood.mobile.utils.Validator.Field;
import com.boardhood.mobile.widget.Button;
import com.boardhood.mobile.widget.LoadingButton;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
public class SignupActivity extends BoardHoodActivity {
private EditText usernameEditText;
private EditText emailEditText;
private EditText passwordEditText;
private LoadingButton createButton;
private Button cancelButton;
private User user;
private Validator validator;
private Field fieldUsername;
private Field fieldEmail;
private Field fieldPassword;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
initAttrs();
initListeners();
// for a better gradient background
// not sure if it works
getWindow().setFormat(PixelFormat.RGBA_8888);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DITHER);
getWindow().getDecorView().getBackground().setDither(true);
}
public void initAttrs() {
usernameEditText = (EditText) findViewById(R.id.signup_username);
emailEditText = (EditText) findViewById(R.id.signup_email);
passwordEditText = (EditText) findViewById(R.id.signup_password);
createButton = (LoadingButton) findViewById(R.id.signup_create);
cancelButton = (Button) findViewById(R.id.signup_cancel);
createButton.setText(getString(R.string.create));
cancelButton.toGray();
validator = new Validator(this);
fieldUsername = validator.addField("name", usernameEditText);
fieldEmail = validator.addField("email", emailEditText);
fieldPassword = validator.addField("password", passwordEditText);
}
public void initListeners() {
createButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
validator.clearErrors();
String username = usernameEditText.getText().toString();
String email = emailEditText.getText().toString();
String password = passwordEditText.getText().toString();
if (TextUtils.isEmpty(username)) {
fieldUsername.addError(validator.getErrorMessage(fieldUsername.getName(), ValidationError.EMPTY_FIELD));
} else if (username.length() > 80) {
fieldUsername.addError(validator.getErrorMessage(fieldUsername.getName(), ValidationError.ABOVE_MAX_LENGTH));
}
if (TextUtils.isEmpty(email)) {
fieldEmail.addError(validator.getErrorMessage(fieldEmail.getName(), ValidationError.EMPTY_FIELD));
} else if (email.length() > 120) {
fieldEmail.addError(validator.getErrorMessage(fieldEmail.getName(), ValidationError.ABOVE_MAX_LENGTH));
}
if (TextUtils.isEmpty(password)) {
fieldPassword.addError(validator.getErrorMessage(fieldPassword.getName(), ValidationError.EMPTY_FIELD));
} else if (password.length() < 3) {
fieldPassword.addError(validator.getErrorMessage(fieldPassword.getName(), ValidationError.BELOW_MIN_LENGTH));
}
if (!validator.validate(null)) {
return;
}
user = new User();
user.setName(username);
user.setEmail(email);
user.setPassword(password);
new UserCreateTask(client, new TaskLoader.TaskListener<User>() {
@Override
public void onPreExecute() {
setAllEnabled(false);
createButton.showLoader();
}
@Override
public void onTaskSuccess(User result) {
Log.i("SignupActivity", "user registered");
CredentialManager.setAuthUser(SignupActivity.this, user);
startFeedActivity();
finish();
}
@Override
public void onTaskFailed(Exception error) {
Log.e("SignupActivity", error.getMessage());
if (error instanceof ValidationException) {
validator.validate((ValidationException) error);
} else if (!NetworkUtil.isOnline(SignupActivity.this)) {
showErrorDialog(R.string.connection_error, R.string.connection_error_internet);
} else if (error instanceof HttpHostConnectException) {
showErrorDialog(R.string.connection_error, R.string.connection_error_host);
} else {
showErrorDialog(R.string.signup_error, R.string.signup_error_unknown);
}
createButton.hideLoader();
setAllEnabled(true);
}
}).execute(user);
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(LoginActivity.createIntent(SignupActivity.this));
finish();
}
});
usernameEditText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged(CharSequence s, int start, int before, int count){
if(s != null && s.length() > 0 && usernameEditText.getError() != null) {
usernameEditText.setError(null);
}
}
});
emailEditText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged(CharSequence s, int start, int before, int count){
if(s != null && s.length() > 0 && emailEditText.getError() != null) {
emailEditText.setError(null);
}
}
});
passwordEditText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged(CharSequence s, int start, int before, int count){
if(s != null && s.length() > 0 && passwordEditText.getError() != null) {
passwordEditText.setError(null);
}
}
});
}
public void startFeedActivity() {
BoardHoodClientManager.setClient(
new BoardHoodWebCacheClient(this, BoardHoodClientManager.URL));
BoardHoodClientManager.setCredentials(user);
Intent intent = FeedActivity.createIntent(SignupActivity.this);
startActivity(intent);
}
public void showErrorDialog(int titleId, int messageId) {
String title = getString(titleId);
String message = getString(messageId);
AlertDialog.Builder builder = new AlertDialog.Builder(SignupActivity.this);
builder.setMessage(message)
.setTitle(title)
.setNeutralButton(getString(R.string.close), new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int which) {
dialog.cancel();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
public void setAllEnabled(boolean enable) {
usernameEditText.setEnabled(enable);
passwordEditText.setEnabled(enable);
createButton.setEnabled(enable);
cancelButton.setEnabled(enable);
}
public static Intent createIntent(Context context) {
Intent i = new Intent(context, SignupActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
return i;
}
}
| mit |
JonCole/SampleCode | Redis/Java/RedisClientTests/src/Program.java | 3969 | import java.io.*;
import java.lang.management.ManagementFactory;
import java.nio.file.*;
import java.util.Date;
public class Program {
public static String AppName = ManagementFactory.getRuntimeMXBean().getName();
public static void main(String[] args) {
try {
printSystemInfo();
Path filePath = Paths.get(System.getProperty("user.dir"), "RedisInstances.txt");
RedisInstance.loadFromFile(filePath);
CommandLineArgs options = CommandLineArgs.parse(args);
IRedisClient client = options.getClient();
Redis.initialize(client);
Logging.writeLine("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
Logging.writeLine("Starting Scenario: %s, threads=%d, iterations=%d, host=%s",
options.getScenario(),
options.getThreadCount(),
options.getIterationCount(),
client.getHostName());
Logging.writeLine("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
ITestScenario scenario = getTestScenario(options.getScenario());
scenario.run(options);
}
catch( Exception ex)
{
Logging.logException(ex);
}
}
private static void printSystemInfo() {
Logging.writeLine("Working Dir: %s", System.getProperty("user.dir"));
Logging.writeLine("Available Processors: %d", Runtime.getRuntime().availableProcessors());
}
public static ITestScenario getTestScenario(String scenarioName)
{
ITestScenario result;
switch(scenarioName.toLowerCase()) {
case "load":
result = new LoadTests();
break;
case "latency":
result = new LatencyPercentileTests();
break;
default:
throw new IllegalArgumentException("Unknown Scenario: " + scenarioName);
}
//IdleConnectionTests.run(11*60);
//simpleGetTest();
//RedisConsole();
return result;
}
public static void simpleGetTest(){
Logging.writeLine("Connecting...");
Redis.getClient();
String value = new Date().toString();
Logging.writeLine("Setting initial value=" + value);
Redis.getClient().set("foo", value);
Logging.writeLine("done");
String result = Redis.getClient().get("foo");
Logging.writeLine("Returned from cache: " + result);
}
private static void RedisConsole() {
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
try {
while (true) {
Logging.writeLine("");
Logging.write(".> ");
String line = console.readLine();
String[] tokens = line.split(" ");
if (tokens.length < 1)
return;
switch (tokens[0].toLowerCase()) {
case "set":
if (tokens.length != 3)
continue;
Redis.getClient().set(tokens[1], tokens[2]);
break;
case "get":
if (tokens.length < 2)
continue;
Logging.writeLine( " " + Redis.getClient().get(tokens[1]));
break;
case "info":
if (tokens.length > 1)
continue;
Logging.writeLine( " " + Redis.getClient().info());
break;
default:
Logging.writeLine(String.format("Unknown command %s", tokens[0]));
}
}
} catch ( IOException ex) {
Logging.logException(ex);
}
}
}
| mit |
dledzinski/graphfinder | GraphFinder2/src/graphfinder2/typedGraph/degree6/Chr6EdivOdivEdivOdiv.java | 1920 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package graphfinder2.typedGraph.degree6;
import graphfinder2.graph.Graph;
import graphfinder2.graph.RingGraph;
import graphfinder2.typedGraph.AbstractTypedGraph;
import graphfinder2.typedGraph.AbstractTypedGraphCreator;
import graphfinder2.typedGraph.TypedGraph;
/**
*
* @author damian
*/
public class Chr6EdivOdivEdivOdiv extends AbstractTypedGraphCreator {
// jedyny obiekt
private static Chr6EdivOdivEdivOdiv instance = null;
private Chr6EdivOdivEdivOdiv() {
super(2, 4);
}
public synchronized static Chr6EdivOdivEdivOdiv getInstance() {
if (instance == null) {
instance = new Chr6EdivOdivEdivOdiv();
}
return instance;
}
public TypedGraph create(int nodeNumber, int... params) {
return new AbstractTypedGraph(this, nodeNumber, params) {
@Override
protected Graph createGraph(int nodeNUmber, int[] params) {
// tworzenie grafu
RingGraph ringGraph = new RingGraph(nodeNumber);
// dodawanie cieciw
ringGraph.createDivisible(params[0], complexity, 0);
ringGraph.createDivisible(params[1], complexity, 1);
ringGraph.createDivisible(params[2], complexity, 0);
ringGraph.createDivisible(params[3], complexity, 1);
return ringGraph;
}
};
}
public boolean isValidNodeNumber(int nodeNumber) {
return nodeNumber % (complexity) == 0;
}
public boolean isValidParams(int nodeNumber, int[] params) {
return params[0] != params[2] && params[1] != params[3] && RingGraph.isValidDivisibleLength(nodeNumber, params[0], complexity) && RingGraph.isValidDivisibleLength(nodeNumber, params[1], complexity) && RingGraph.isValidDivisibleLength(nodeNumber, params[2], complexity) && RingGraph.isValidDivisibleLength(nodeNumber, params[3], complexity);
}
public boolean isOptimalParams(int nodeNumber, int[] params) {
return params[0] < params[1];
}
}
| mit |
Flaxbeard/Sprockets | src/main/java/flaxbeard/sprockets/api/IMultiblockComparator.java | 217 | package flaxbeard.sprockets.api;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
public interface IMultiblockComparator
{
public boolean isEqual(IBlockAccess iba, BlockPos pos);
}
| mit |
mbuzdalov/non-dominated-sorting | implementations/src/test/java/ru/ifmo/nds/tests/JensenFortinBuzdalovRedBlackHybridENSParallelTest.java | 374 | package ru.ifmo.nds.tests;
import ru.ifmo.nds.JensenFortinBuzdalov;
import ru.ifmo.nds.NonDominatedSortingFactory;
public class JensenFortinBuzdalovRedBlackHybridENSParallelTest extends CorrectnessTestsBase {
@Override
protected NonDominatedSortingFactory getFactory() {
return JensenFortinBuzdalov.getRedBlackTreeSweepHybridENSImplementation(-1);
}
}
| mit |
InspireNXE/Pulse | src/main/java/org/inspirenxe/pulse/network/pc/PCConnectionListener.java | 8164 | /**
* This file is part of Pulse, licensed under the MIT License (MIT).
*
* Copyright (c) 2014-2015 InspireNXE <http://inspirenxe.org/>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.inspirenxe.pulse.network.pc;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.concurrent.Future;
import org.inspirenxe.pulse.SpongeGame;
import org.inspirenxe.pulse.network.pc.protocol.PCProtocol;
import org.spacehq.packetlib.ConnectionListener;
import org.spacehq.packetlib.Server;
import org.spacehq.packetlib.tcp.TcpPacketCodec;
import org.spacehq.packetlib.tcp.TcpPacketEncryptor;
import org.spacehq.packetlib.tcp.TcpPacketSizer;
import java.net.BindException;
import java.net.InetSocketAddress;
public final class PCConnectionListener implements ConnectionListener {
private final Server server;
private final String host;
private final int port;
private Channel channel;
private EventLoopGroup group;
public PCConnectionListener(Server server, String host, int port) {
this.server = server;
this.host = host;
this.port = port;
}
@Override
public String getHost() {
return this.host;
}
@Override
public int getPort() {
return this.port;
}
@Override
public boolean isListening() {
return this.channel != null && this.channel.isOpen();
}
@Override
public void bind() {
this.bind(true);
}
@Override
public void bind(boolean wait) {
this.bind(wait, null);
}
@Override
public void bind(boolean wait, Runnable callback) {
if (this.group == null && this.channel == null) {
this.group = new NioEventLoopGroup();
final ChannelFuture future = (new ServerBootstrap()).channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer() {
public void initChannel(Channel channel) throws Exception {
final InetSocketAddress address = (InetSocketAddress) channel.remoteAddress();
final PCProtocol protocol = (PCProtocol) PCConnectionListener.this.server.createPacketProtocol();
// TODO PE Support
final PCSession session = new PCSession(PCConnectionListener.this.server, address.getHostName(), address
.getPort(), protocol);
session.getPacketProtocol().newServerSession(PCConnectionListener.this.server, session);
channel.config().setOption(ChannelOption.IP_TOS, 24);
channel.config().setOption(ChannelOption.TCP_NODELAY, false);
final ChannelPipeline pipeline = channel.pipeline();
session.refreshReadTimeoutHandler(channel);
session.refreshWriteTimeoutHandler(channel);
pipeline.addLast("encryption", new TcpPacketEncryptor(session));
pipeline.addLast("sizer", new TcpPacketSizer(session));
pipeline.addLast("codec", new TcpPacketCodec(session));
pipeline.addLast("manager", session);
}
}).group(this.group).localAddress(this.host, this.port).bind();
if (future != null) {
if (wait) {
try {
future.sync();
} catch (Exception ex) {
if (ex instanceof BindException) {
SpongeGame.logger.error("Failed to bind to [{}:{}]! Is there another server running on this port?", host, port);
}
return;
}
this.channel = future.channel();
if (callback != null) {
callback.run();
}
} else {
future.addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()) {
PCConnectionListener.this.channel = future.channel();
if (callback != null) {
callback.run();
}
} else {
SpongeGame.logger.error("Failed to bind to [{}:{}]! Is there another server running on this port?", host, port);
}
}
});
}
}
}
}
@Override
public void close() {
this.close(false);
}
@Override
public void close(boolean wait) {
this.close(false, null);
}
@Override
public void close(boolean wait, Runnable callback) {
if (this.channel != null) {
if (this.channel.isOpen()) {
final ChannelFuture future = this.channel.close();
if (wait) {
try {
future.sync();
} catch (InterruptedException ignored) {
}
if (callback != null) {
callback.run();
}
} else {
future.addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()) {
if (callback != null) {
callback.run();
}
} else {
SpongeGame.logger.error("Failed to asynchronously close connection listener!", future.cause());
}
}
});
}
}
this.channel = null;
}
if (this.group != null) {
final Future<?> future1 = this.group.shutdownGracefully();
if (wait) {
try {
future1.sync();
} catch (InterruptedException ignored) {}
} else {
future1.addListener(future -> {
if (!future.isSuccess()) {
SpongeGame.logger.error("Failed to asynchronously close connection listener!", future.cause());
}
});
}
this.group = null;
}
}
}
| mit |
romildo/eplan | src/main/java/types/UNIT.java | 193 | package types;
public class UNIT extends Type {
public static final UNIT T = new UNIT();
private UNIT() {
}
@Override
public String toString() {
return "unit";
}
}
| mit |
dreamhead/moco | moco-core/src/main/java/com/github/dreamhead/moco/handler/CollectionHandler.java | 1256 | package com.github.dreamhead.moco.handler;
import com.github.dreamhead.moco.MocoConfig;
import com.github.dreamhead.moco.ResponseHandler;
import com.github.dreamhead.moco.internal.SessionContext;
import com.google.common.collect.ImmutableList;
import java.util.stream.Collectors;
import static com.google.common.collect.ImmutableList.copyOf;
public abstract class CollectionHandler extends AbstractResponseHandler {
private final ImmutableList<ResponseHandler> handlers;
private int index;
protected CollectionHandler(final Iterable<ResponseHandler> handlers) {
this.handlers = copyOf(handlers);
}
@Override
public final void writeToResponse(final SessionContext context) {
int current = index;
this.index = next(index, this.handlers.size());
handlers.get(current).writeToResponse(context);
}
@Override
public final ResponseHandler doApply(final MocoConfig config) {
return newCollectionHandler(handlers.stream()
.map(input -> input.apply(config))
.collect(Collectors.toList()));
}
protected abstract int next(int index, int size);
protected abstract ResponseHandler newCollectionHandler(Iterable<ResponseHandler> handlers);
}
| mit |
rvep/dev_backend | src/main/java/io/abnd/rvep/security/model/intf/AuthVerificationResponse.java | 163 | package io.abnd.rvep.security.model.intf;
public interface AuthVerificationResponse {
boolean getIsVerified();
void setIsVerified(boolean verified);
}
| mit |
jheinnic/reactor-readnums | readnums-app/src/main/java/info/jchein/apps/nr/codetest/ingest/app/SpringMain.java | 1517 | package info.jchein.apps.nr.codetest.ingest.app;
import info.jchein.apps.nr.codetest.ingest.config.IngestConfiguration;
import info.jchein.apps.nr.codetest.ingest.config.ParametersConfiguration;
import info.jchein.apps.nr.codetest.ingest.messages.EventConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
public class SpringMain
implements CommandLineRunner
{
// private static final Logger LOG = LoggerFactory.getLogger(SpringMain.class);
public static void main(String[] args) throws InterruptedException {
SpringApplication app =
new SpringApplicationBuilder(
SpringMain.class, IngestConfiguration.class, EventConfiguration.class, ParametersConfiguration.class)
.headless(true)
.main(SpringMain.class).application();
app.run(args);
}
@Autowired
ApplicationWatchdog applicationWatchdog;
@Autowired
ConfigurableApplicationContext applicationContext;
// CTXT.registerShutdownHook();
// Thread.sleep(2000);
// CTXT.stop();
@Override
public void run(String... args) throws Exception {
applicationContext.registerShutdownHook();
applicationContext.start();
applicationWatchdog.blockUntilTerminatedOrInterrupted();
}
} | mit |
Theyssen/LinguAdde | src/main/java/linguadde/exception/NoTranslationException.java | 412 | package linguadde.exception;
import java.util.LinkedHashSet;
import java.util.Set;
public class NoTranslationException extends Exception {
private static final Set<String> messages = new LinkedHashSet<String>();
public NoTranslationException(String message) {
super(message);
messages.add(message);
}
public static Set<String> getMessages() {
return messages;
}
}
| mit |
robzenn92/introsde | assignment_3_client/src/introsde/document/ws/Measure.java | 3546 |
package introsde.document.ws;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for measure complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="measure">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="dateRegistered" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="measureType" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="measureValue" type="{http://www.w3.org/2001/XMLSchema}double"/>
* <element name="measureValueType" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="mid" type="{http://www.w3.org/2001/XMLSchema}int"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "measure", propOrder = {
"dateRegistered",
"measureType",
"measureValue",
"measureValueType",
"mid"
})
public class Measure {
protected String dateRegistered;
protected String measureType;
protected double measureValue;
protected String measureValueType;
protected int mid;
/**
* Gets the value of the dateRegistered property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDateRegistered() {
return dateRegistered;
}
/**
* Sets the value of the dateRegistered property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDateRegistered(String value) {
this.dateRegistered = value;
}
/**
* Gets the value of the measureType property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMeasureType() {
return measureType;
}
/**
* Sets the value of the measureType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMeasureType(String value) {
this.measureType = value;
}
/**
* Gets the value of the measureValue property.
*
*/
public double getMeasureValue() {
return measureValue;
}
/**
* Sets the value of the measureValue property.
*
*/
public void setMeasureValue(double value) {
this.measureValue = value;
}
/**
* Gets the value of the measureValueType property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMeasureValueType() {
return measureValueType;
}
/**
* Sets the value of the measureValueType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMeasureValueType(String value) {
this.measureValueType = value;
}
/**
* Gets the value of the mid property.
*
*/
public int getMid() {
return mid;
}
/**
* Sets the value of the mid property.
*
*/
public void setMid(int value) {
this.mid = value;
}
}
| mit |
HaHaBird/JavaLearinigProject | src/annotation/MyAnno.java | 287 | package annotation;
import java.lang.annotation.*;
/**
* Desc:
* 创建自定义注解
* Created by WangGuoku on 2017/9/27 16:05.
*/
@Documented
@Target(ElementType.FIELD)
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnno{
String getName() default "";
}
| mit |
Brians200/KSP-Module-Adder | src/KspModuleEditor.java | 1792 | import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import config.io.FolderManager;
import config.misc.GlobalIgnoreList;
import config.misc.GlobalSettings;
public class KspModuleEditor {
public static void main(String[] args){
try {
Scanner scanner = new Scanner(new File("GlobalSettings.txt"));
while(scanner.hasNext())
{
String inLine = scanner.next().replaceAll("\\s", "");
if(inLine.startsWith("AddMechJeb="))
{
GlobalSettings.addMechjeb = Boolean.parseBoolean(inLine.replace("AddMechJeb=", ""));
}
else if(inLine.startsWith("AddProtractor="))
{
GlobalSettings.addProtractor = Boolean.parseBoolean(inLine.replace("AddProtractor=", ""));
}
else if(inLine.startsWith("AddDeadlyReentry="))
{
GlobalSettings.addDeadlyReentry = Boolean.parseBoolean(inLine.replace("AddDeadlyReentry=", ""));
}
}
scanner.close();
} catch (FileNotFoundException e) {
// TODO proper error handling
// we'll just keep the defaults for now...
e.printStackTrace();
}
try{
Scanner scanner = new Scanner(new File("FilesAndFoldersToIgnore.txt"));
boolean fileMode = true;
while(scanner.hasNext())
{
String inLine = scanner.next().trim();
if(inLine.equals(""))
{
continue;
}
else if(inLine.equals("#Folders"))
{
fileMode = false;
}
else if(inLine.equals("#Files"))
{
fileMode = true;
}
else if(fileMode)
{
GlobalIgnoreList.filesToIgnore.add(inLine);
}
else
{
GlobalIgnoreList.foldersToIgnore.add(inLine);
}
}
scanner.close();
} catch (FileNotFoundException e) {
// TODO proper error handling
e.printStackTrace();
}
FolderManager.applyChanges();
}
}
| mit |
Azure/azure-sdk-for-java | sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/HealthcareEntity.java | 2567 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.ai.textanalytics.implementation.models;
import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
/** The HealthcareEntity model. */
@Fluent
public final class HealthcareEntity extends HealthcareEntityProperties {
/*
* The assertion property.
*/
@JsonProperty(value = "assertion")
private HealthcareAssertion assertion;
/*
* Preferred name for the entity. Example: 'histologically' would have a
* 'name' of 'histologic'.
*/
@JsonProperty(value = "name")
private String name;
/*
* Entity references in known data sources.
*/
@JsonProperty(value = "links")
private List<HealthcareEntityLink> links;
/**
* Get the assertion property: The assertion property.
*
* @return the assertion value.
*/
public HealthcareAssertion getAssertion() {
return this.assertion;
}
/**
* Set the assertion property: The assertion property.
*
* @param assertion the assertion value to set.
* @return the HealthcareEntity object itself.
*/
public HealthcareEntity setAssertion(HealthcareAssertion assertion) {
this.assertion = assertion;
return this;
}
/**
* Get the name property: Preferred name for the entity. Example: 'histologically' would have a 'name' of
* 'histologic'.
*
* @return the name value.
*/
public String getName() {
return this.name;
}
/**
* Set the name property: Preferred name for the entity. Example: 'histologically' would have a 'name' of
* 'histologic'.
*
* @param name the name value to set.
* @return the HealthcareEntity object itself.
*/
public HealthcareEntity setName(String name) {
this.name = name;
return this;
}
/**
* Get the links property: Entity references in known data sources.
*
* @return the links value.
*/
public List<HealthcareEntityLink> getLinks() {
return this.links;
}
/**
* Set the links property: Entity references in known data sources.
*
* @param links the links value to set.
* @return the HealthcareEntity object itself.
*/
public HealthcareEntity setLinks(List<HealthcareEntityLink> links) {
this.links = links;
return this;
}
}
| mit |
newmann/shop | src/main/java/com/iwc/shop/modules/act/web/ActProcessController.java | 7103 | /**
* Copyright © 2012-2014 <a href="http://www.iwantclick.com">iWantClick</a>iwc.shop All rights reserved.
*/
package com.iwc.shop.modules.act.web;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.stream.XMLStreamException;
import com.iwc.shop.common.utils.StringUtils;
import com.iwc.shop.common.web.BaseController;
import org.activiti.engine.runtime.ProcessInstance;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.iwc.shop.common.persistence.Page;
import com.iwc.shop.modules.act.service.ActProcessService;
/**
* 流程定义相关Controller
* @author Tony Wong
* @version 2013-11-03
*/
@Controller
@RequestMapping(value = "${adminPath}/act/process")
public class ActProcessController extends BaseController {
@Autowired
private ActProcessService actProcessService;
/**
* 流程定义列表
*/
@RequiresPermissions("act:process:edit")
@RequestMapping(value = {"list", ""})
public String processList(String category, HttpServletRequest request, HttpServletResponse response, Model model) {
/*
* 保存两个对象,一个是ProcessDefinition(流程定义),一个是Deployment(流程部署)
*/
Page<Object[]> page = actProcessService.processList(new Page<Object[]>(request, response), category);
model.addAttribute("page", page);
model.addAttribute("category", category);
return "modules/act/actProcessList";
}
/**
* 运行中的实例列表
*/
@RequiresPermissions("act:process:edit")
@RequestMapping(value = "running")
public String runningList(String procInsId, String procDefKey, HttpServletRequest request, HttpServletResponse response, Model model) {
Page<ProcessInstance> page = actProcessService.runningList(new Page<ProcessInstance>(request, response), procInsId, procDefKey);
model.addAttribute("page", page);
model.addAttribute("procInsId", procInsId);
model.addAttribute("procDefKey", procDefKey);
return "modules/act/actProcessRunningList";
}
/**
* 读取资源,通过部署ID
* @param processDefinitionId 流程定义ID
* @param processInstanceId 流程实例ID
* @param resourceType 资源类型(xml|image)
* @param response
* @throws Exception
*/
@RequiresPermissions("act:process:edit")
@RequestMapping(value = "resource/read")
public void resourceRead(String procDefId, String proInsId, String resType, HttpServletResponse response) throws Exception {
InputStream resourceAsStream = actProcessService.resourceRead(procDefId, proInsId, resType);
byte[] b = new byte[1024];
int len = -1;
while ((len = resourceAsStream.read(b, 0, 1024)) != -1) {
response.getOutputStream().write(b, 0, len);
}
}
/**
* 部署流程
*/
@RequiresPermissions("act:process:edit")
@RequestMapping(value = "/deploy", method=RequestMethod.GET)
public String deploy(Model model) {
return "modules/act/actProcessDeploy";
}
/**
* 部署流程 - 保存
* @param file
* @return
*/
@RequiresPermissions("act:process:edit")
@RequestMapping(value = "/deploy", method=RequestMethod.POST)
public String deploy(@Value("#{APP_PROP['activiti.export.diagram.path']}") String exportDir,
String category, MultipartFile file, RedirectAttributes redirectAttributes) {
String fileName = file.getOriginalFilename();
if (StringUtils.isBlank(fileName)){
redirectAttributes.addFlashAttribute("message", "请选择要部署的流程文件");
}else{
String message = actProcessService.deploy(exportDir, category, file);
redirectAttributes.addFlashAttribute("message", message);
}
return "redirect:" + adminPath + "/act/process";
}
/**
* 设置流程分类
*/
@RequiresPermissions("act:process:edit")
@RequestMapping(value = "updateCategory")
public String updateCategory(String procDefId, String category, RedirectAttributes redirectAttributes) {
actProcessService.updateCategory(procDefId, category);
return "redirect:" + adminPath + "/act/process";
}
/**
* 挂起、激活流程实例
*/
@RequiresPermissions("act:process:edit")
@RequestMapping(value = "update/{state}")
public String updateState(@PathVariable("state") String state, String procDefId, RedirectAttributes redirectAttributes) {
String message = actProcessService.updateState(state, procDefId);
redirectAttributes.addFlashAttribute("message", message);
return "redirect:" + adminPath + "/act/process";
}
/**
* 将部署的流程转换为模型
* @param procDefId
* @param redirectAttributes
* @return
* @throws UnsupportedEncodingException
* @throws XMLStreamException
*/
@RequiresPermissions("act:process:edit")
@RequestMapping(value = "convert/toModel")
public String convertToModel(String procDefId, RedirectAttributes redirectAttributes) throws UnsupportedEncodingException, XMLStreamException {
org.activiti.engine.repository.Model modelData = actProcessService.convertToModel(procDefId);
redirectAttributes.addFlashAttribute("message", "转换模型成功,模型ID="+modelData.getId());
return "redirect:" + adminPath + "/act/model";
}
/**
* 导出图片文件到硬盘
*/
@RequiresPermissions("act:process:edit")
@RequestMapping(value = "export/diagrams")
@ResponseBody
public List<String> exportDiagrams(@Value("#{APP_PROP['activiti.export.diagram.path']}") String exportDir) throws IOException {
List<String> files = actProcessService.exportDiagrams(exportDir);;
return files;
}
/**
* 删除部署的流程,级联删除流程实例
* @param deploymentId 流程部署ID
*/
@RequiresPermissions("act:process:edit")
@RequestMapping(value = "delete")
public String delete(String deploymentId) {
actProcessService.deleteDeployment(deploymentId);
return "redirect:" + adminPath + "/act/process";
}
/**
* 删除流程实例
* @param procInsId 流程实例ID
* @param reason 删除原因
*/
@RequiresPermissions("act:process:edit")
@RequestMapping(value = "deleteProcIns")
public String deleteProcIns(String procInsId, String reason, RedirectAttributes redirectAttributes) {
if (StringUtils.isBlank(reason)){
addMessage(redirectAttributes, "请填写删除原因");
}else{
actProcessService.deleteProcIns(procInsId, reason);
addMessage(redirectAttributes, "删除流程实例成功,实例ID=" + procInsId);
}
return "redirect:" + adminPath + "/act/process/running/";
}
}
| mit |
dckg/daogenerator | src/main/java/net/dckg/daogenerator/Column.java | 743 | package net.dckg.daogenerator;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.sql.Types;
/**
* Denotes a column in database.
* <p>
* Every DAO property must be public and have this annotation;
* <br> - name is it's column name in database
* <br> - type is it's column type in database
* <br>
* <b>The order of properties must be the same as in database table create script.</b>
*
* @see java.sql.Types
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface Column {
String name() default "";
/**
* the SQL type (as defined in java.sql.Types) to be sent to the database
* <br>
* Defaults to INTEGER
*
* @return java.sql.Types
*/
int type() default Types.INTEGER;
}
| mit |
rtatol/recipes | src/main/java/com/recipes/controller/HomeController.java | 515 | package com.recipes.controller;
import com.recipes.configuration.security.Auth;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class HomeController {
@PreAuthorize(Auth.ROLE_QUEEN)
@GetMapping("/")
public String home(final Model model) {
model.addAttribute("message", "hello");
return "home";
}
}
| mit |
android-samples/loading-show-hide | src/com/example/myloading/MainActivity.java | 705 | package com.example.myloading;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void buttonMethod(View v){
ProgressBar p = (ProgressBar)
findViewById(R.id.progressBar1);
p.setVisibility(View.VISIBLE); // 表示
}
public void buttonMethod2(View v){
ProgressBar p = (ProgressBar)
findViewById(R.id.progressBar1);
p.setVisibility(View.GONE); // 非表示
}
}
| mit |
zitudu/scala-like-collection-and-sort | src/main/java/collection/mutable/HashMultimap.java | 2578 | package collection.mutable;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
public class HashMultimap<K,V> {
Map<K, List<V>> map = new HashMap<K, List<V>>();
int total = 0;
public HashMultimap() { }
/**
* Returns the total number of entries in the multimap.
* @return
*/
public int size() { return total; }
/**
* Tests whether if the multimap is empty.
* @return
*/
public boolean isEmpty() { return size() == 0; }
/**
* Returns a (possibly empty) iteration of all values associated wiht the key.
* @param key
* @return
*/
Iterable<V> get(K key) {
List<V> secondary = map.get(key);
if (secondary != null)
return secondary;
return new ArrayList<V>();
}
/**
* Adds a new entry associating key with value.
* @param key
* @param value
*/
public void put(K key, V value) {
List<V> secondary = map.get(key);
if (secondary == null) {
secondary = new ArrayList<V>();
map.put(key, secondary);
}
secondary.add(value);
total++;
}
/**
* Removes the (key, value) entry, if exists.
* @param key
* @param value
* @return
*/
public boolean remove(K key, V value) {
boolean wasRemoved = false;
List<V> secondary = map.get(key);
if (secondary != null) {
wasRemoved = secondary.remove(value);
if (wasRemoved) {
total--;
if (secondary.isEmpty())
map.remove(key);
}
}
return wasRemoved;
}
/**
* Removes all entries with given key.
* @param key
* @return
*/
Iterable<V> removeAll(K key) {
List<V> secondary = map.get(key);
if (secondary != null) {
total -= secondary.size();
map.remove(key);
} else
secondary = new ArrayList<V>();
return secondary;
}
/**
* Returns an iteration of all entries in the multimap.
* @return
*/
Iterable<Map.Entry<K,V>> entries() {
List<Map.Entry<K,V>> result = new ArrayList<Map.Entry<K, V>>();
for (Map.Entry<K,List<V>> secondary: map.entrySet()) {
K key = secondary.getKey();
for (V value: secondary.getValue())
result.add(new AbstractMap.SimpleEntry<K, V>(key, value));
}
return result;
}
}
| mit |
duke-compsci344-spring2015/jogl_jars | src/framework/Pixmap.java | 2891 | package framework;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
/**
* Convenience class for dealing with images.
*
* Creating a pixmap requires a filename that should be a gif, png, or jpg image.
*
* @author Robert C. Duvall
* @author Owen Astrachan
* @author Syam Gadde
*/
public class Pixmap {
public static final Dimension DEFAULT_SIZE = new Dimension(300, 300);
public static final Color DEFAULT_COLOR = Color.BLACK;
public static final String DEFAULT_NAME = "Default";
private String myFileName;
private BufferedImage myImage;
private Dimension mySize;
/**
* Create a pixmap with given width and height and filled with given initial color
*/
public Pixmap (int width, int height, Color color) {
createImage(width, height, color);
}
/**
* Create a pixmap from the given local file
*/
public Pixmap (String fileName) throws IOException {
if (fileName == null) {
createImage(DEFAULT_SIZE.width, DEFAULT_SIZE.height, DEFAULT_COLOR);
} else {
read(fileName);
}
}
/**
* Returns the file name of this Pixmap (if it exists)
*/
public String getName () {
int index = myFileName.lastIndexOf(File.separator);
if (index >= 0) {
return myFileName.substring(index + 1);
} else {
return myFileName;
}
}
/**
* Returns the dimensions of the Pixmap.
*/
public Dimension getSize () {
return new Dimension(mySize);
}
/**
* Returns the color of the pixel at the given point in the pixmap.
*/
public Color getColor (int x, int y) {
if (isInBounds(x, y)) {
return new Color(myImage.getRGB(x, y));
} else {
return DEFAULT_COLOR;
}
}
/**
* Paint the image on the canvas
*/
public void paint (Graphics pen) {
pen.drawImage(myImage, 0, 0, mySize.width, mySize.height, null);
}
// returns true if the given point is a valid Pixmap value.
private boolean isInBounds (int x, int y) {
return (0 <= x && x < mySize.width) && (0 <= y && y < mySize.height);
}
// Read the pixmap from the given file.
private void read (String fileName) throws IOException {
myFileName = fileName;
myImage = ImageIO.read(new File(myFileName));
mySize = new Dimension(myImage.getWidth(), myImage.getHeight());
}
// convenience function
private void createImage (int width, int height, Color color) {
myFileName = color.toString();
myImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
mySize = new Dimension(width, height);
}
}
| mit |
boubre/BayouBot | Workspace/src/workspace/typeblocking/FocusTraversalManager.java | 26961 | package workspace.typeblocking;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.List;
import renderable.RenderableBlock;
import workspace.Page;
import workspace.WorkspaceEvent;
import workspace.WorkspaceListener;
import workspace.BlockCanvas.Canvas;
import codeblocks.Block;
import codeblocks.BlockConnector;
/**
* The FocusTraversalManager has two function. First, it
* maintains a pointer to the block, if any, that has
* focus and the corresponding focus point on that block.
* If the focus is not on the block, then it must be set
* to some point of the block canvas.
*
* The second primary function of the FocusTraversalManager
* is to redirect the focus to the next appropriate block
* in a particular stack. One could "traverse" the stack
* by moving the focus to one of the following:
* 1. the block after
* 2. the block before
* 3. the next block
* 4. the previous block
*
* The exact definition of what "next", "previous",
* "after", and "before" is described in details in
* their corresponding method summary.
* As a focus manager of the entire system, the class
* must maintain particular invariants at all time.
* Clients of this module may obtain the focus through
* three observer (getter) methods. Clients may also
* manualy mutate the focus through three modifier (setter)
* methods.
*
* However, BOTH the value returned in the observer
* methods and the value passed in the modifier methods
* MUST maintain particular invariants described below.
*
* These invariants must hold at all time and check reps
* should be imposed to ensure that any changes to the
* system still holds these crucial invariants. Clients
* of this module may assume that the invariants mentioned
* below will always hold.
*
* INVARIANT I.
* If the canvas has focus, then the block does not. Thus
* 1. focusBlock == Block.null
* 2. canvasFocusPoint != null
* 3. blockFocusPoint == null
*
* INVARIANT II.
* If the block has focus, then the canvas does not. Thus
* 1. focusBlock != Block.null
* 2. canvasFocusPoint == null
* 3. blockFocusPoint != null
*
* @specfield focusBlock : Long //block with focus
* @specfield canvasFocusPoint : Point //focus point on canvas relative to canvas
* @specfield blockFocusPoint : Point //focus point on block relative to block
*
*/
public class FocusTraversalManager implements MouseListener, KeyListener, WorkspaceListener{
/** this.focuspoint: the point on the block with focus */
private Point blockFocusPoint = null;
/** this.focuspoint: the point on the block canvas's last mosue click */
private Point canvasFocusPoint = new Point(0,0);
/** this.focusblock: the Block ID that currently has focus */
private Long focusBlock = Block.NULL;
/////////////////
// Constructor //
/////////////////
public FocusTraversalManager(){}
///////////////
// Observers //
///////////////
/**
* @return the block that has focus, if any.
*
* TODO: finish method documentation
*/
public Long getFocusBlockID() {
//DO NOT REMOVE CHECK REP BELOW!!!
//Many client classes depend on this invariant
if(invalidBlock(focusBlock)){
//If block is null then, focus should be on block on canvas.
//To test this, we must recall that when focus is on block,
//the canvas focus point is set to null.
if (canvasFocusPoint == null) throw new RuntimeException(
"Focus has not yet been set to block");
if (blockFocusPoint != null) throw new RuntimeException(
"Focus should be set to block");
}else{
//if block is not null, then we need to make sure the
//focus is on the block. To test this, we recall
//that when the focus is on the block, the
//canvas focus point is set to null
if (canvasFocusPoint != null) throw new RuntimeException(
"Focus has not yet been set to canvas");
if (blockFocusPoint == null) throw new RuntimeException(
"Focus has not been removed from block");
}
return focusBlock;
}
/**
* @return point of focus on canvas
*
* TODO: finish method documentation
*/
public Point getCanvasPoint(){
//DO NOT REMOVE CHECK REP BELOW!!!
//Many client classes depend on this invariant
//If focus block is not null, then the focus is
//currently set on that instance of the block.
//As a result, you may not request the canvas's
//focus point because it DOES NOT have focus
if(!invalidBlock(focusBlock)) throw new RuntimeException(
"May not request canvas's focus point if " +
"canvas does not have focus. Focus at: "+focusBlock);
if(blockFocusPoint != null ) throw new RuntimeException(
"May not request canvas's focus point if " +
"canvas does not have focus. Focus at: "+blockFocusPoint);
if(canvasFocusPoint == null ) throw new RuntimeException(
"May not request canvas's focus point if " +
"canvas does not have focus. Canvas focus is null.");
//Okay, invariant holds. So return point of focus on canvas.
return canvasFocusPoint;
}
/**
* @return point of focus on block
*
* TODO: finish method documentation
*/
public Point getBlockPoint(){
//DO NOT REMOVE CHECK REP BELOW!!!
//Many client classes depend on this invariant
//If focus block is null, then the focus is
//currently set on canvas. You may not request
//the block's focus point because it DOES NOT have focus
if(invalidBlock(focusBlock)) throw new RuntimeException(
"May not request block's focus point if " +
"block does not have focus. Focus at: "+focusBlock);
if(blockFocusPoint == null ) throw new RuntimeException(
"May not request block's focus point if " +
"block does not have focus. Focus at: "+blockFocusPoint);
if(canvasFocusPoint != null ) throw new RuntimeException(
"Canvas focus is still valid. May not request" +
"block's focus point if block does not have focus.");
//Okay, invariant holds. So return point of focus on canvas.
return blockFocusPoint;
}
//////////////////
// Focus Set Up //
//////////////////
/**
* Sets focus to block
* @parem block
*
* TODO: finish method documentation
*/
public void setFocus(Block block){
if(block == null){
throw new RuntimeException("Invariant Violated:" +
"may not set focus to a null Block instance");
//Please do not remove exception above. This class
//and many other classes within the typeblocking
//package requires that the following invariant(s) must hold:
// MAY NOT SET FOCUS TO NULL BLOCK INSTANCES
}else{
setFocus(block.getBlockID());
}
}
public void setFocus(Long blockID){
if(blockID == null || blockID == Block.NULL || blockID == -1 || Block.getBlock(blockID) == null ){
throw new RuntimeException("Invariant Violated:" +
"may not set focus to a null Block instance");
//Please do not remove exception above. This class
//and many other classes within the typeblocking
//package requires that the following invariant(s) must hold:
// MAY NOT SET FOCUS TO NULL BLOCK INSTANCES
}
//remove focus from old block if one existed
if(!invalidBlock(this.focusBlock)){
getBlock(this.focusBlock).setFocus(false);
RenderableBlock.getRenderableBlock(this.focusBlock).repaintBlock();
}
//set focus block to blockID
getBlock(blockID).setFocus(true);
RenderableBlock.getRenderableBlock(blockID).requestFocus();
RenderableBlock.getRenderableBlock(blockID).repaintBlock();
//set canvas focus point to be null; canvas no longer has focus
this.canvasFocusPoint = null;
//set blockfocus point to new value
this.blockFocusPoint = new Point(0,0);
//set focusblock
this.focusBlock = blockID;
//System.out.println("FocusManager: Setting focus to block: " + this.focusBlock+", "+this.blockFocusPoint+", "+this.canvasFocusPoint);
}
/**
* Set Focus to canvas at canvasPoint. THE BLOCKID MUST BE BLOCK.NULL!!!
* @param canvasPoint
* @param blockID
*
* TODO: finish method documentation
*/
public void setFocus(Point canvasPoint, Long blockID) {
if(blockID == null || blockID == Block.NULL || blockID == -1 || Block.getBlock(blockID) == null ){
//remove focus form old block if one existed
if(!invalidBlock(this.focusBlock)){
getBlock(this.focusBlock).setFocus(false);
RenderableBlock.getRenderableBlock(this.focusBlock).repaintBlock();
}
//set block ID to null
this.focusBlock=Block.NULL;
//set canvas focus point to canvasPoint
this.canvasFocusPoint = canvasPoint;
//set block focus point to null
this.blockFocusPoint = null;
//System.out.println("FocusManager: Setting focus to canvas: " + this.focusBlock+", "+this.blockFocusPoint+", "+this.canvasFocusPoint);
}else{
throw new RuntimeException("Invariant Violated:" +
"may not set new focus point if focus is on a block");
//Please do not remove exception above. This class
//and many other classes within the typeblocking
//package requires that the following invariant(s) must hold:
// CANVAS POINT MAY NOT BE SET UNLESS BLOCK IS NULL
// CANVAS POINT MAY NOT BE SET IF FOCUS IS ON BLOCK
}
}
void setFocus(Point location){
//please do not remove this method or try to
//create a method this takes only a point as an argument.
//The thing is, it's too tricky to create such a method
//and I want to let users who use this method know that
//this is a fundalmentally wrong method to invoke.
//may not use this method as it does not ensure class invariant will hold
throw new RuntimeException("The use of this method is FORBIDDEN");
}
//////////////////////////////////////
// Focus Traversal Handling Methods //
//////////////////////////////////////
/**
* Reassigns the focus to the "next block" of the current focusBlock.
* If the current focusblock is at location n of the flatten linear vector
* of the block tree structure, then the "next block" is located at n+1.
* In other words, the previous block is the parent block of the next
* socket of the parent block of the focusblock.
*
* @requires pointFocusOwner != null &&
* focusblock.getSockets() != null &&
* focusblock.getSockets() is not empty
* @modifies this.focusblock
* @effects this.focusblock now points to the "next block"
* as described in method overview;
* @returns true if the new focus is on a block that isn't null
*/
public boolean focusNextBlock() {
//return focus to canvas if no focusblock does not exist
if(invalidBlock(focusBlock) || !RenderableBlock.getRenderableBlock(focusBlock).isVisible()){
setFocus(canvasFocusPoint, Block.NULL);
return false;
}
//give focus to any preceeding socket of current block
Block currentBlock = getBlock(focusBlock);
for(BlockConnector socket : currentBlock.getSockets()){
if(socket != null && !invalidBlock(socket.getBlockID())){
//give focus to socket block
setFocus(socket.getBlockID());
return true;
}
}
//give focus to after block of current block
Long afterBlock = currentBlock.getAfterBlockID();
if(!invalidBlock(afterBlock)){
setFocus(afterBlock);
return true;
}
//current block != null.....invariant checke in getNextNode()
Block nextBlock = this.getNextNode(currentBlock);
//check invariant
if(nextBlock == null) throw new RuntimeException ("Invariant Violated: return value of getNextNode() may not be null");
//set focus
setFocus(nextBlock.getBlockID());
return true;
}
/**
* Reassigns the focus to the "previous block" of the current focusBlock.
* If the current focusblock is at location n of the flatten linear vector
* of the block tree structure, then the "previous block" is located at n-1.
* In other words, the previous block is the innermost block of the previous
* socket of the parent block of the focusblock.
*
* @requires pointFocusOwner != null &&
* focusblock.getSockets() != null &&
* focusblock.getSockets() is not empty
* @modifies this.focusblock
* @effects this.focusblock now points to the "previous block"
* as described in method overview;
* @returns true if the new focus is on a block that isn't null
*/
public boolean focusPrevBlock() {
//return focus to canvas if no focusblock does not exist
if(invalidBlock(focusBlock) || !RenderableBlock.getRenderableBlock(focusBlock).isVisible()){
setFocus(canvasFocusPoint, Block.NULL);
return false;
}
Block currentBlock = getBlock(focusBlock);
//set plug to be previous block
Block previousBlock = getPlugBlock(currentBlock);
//if plug is null, set before to be previous block
if(previousBlock == null ) previousBlock = getBeforeBlock(currentBlock);
//If before is ALSO null, jump to bottom of the stack;
if(previousBlock == null){
previousBlock = getBottomRightBlock(currentBlock);
}else{
//If at least a plug block OR (but not both) before block exist,
//then get innermost block of the previous socket of the previous block
//assumes previousBlock.getSockets is not empty, not null
Block beforeBlock = previousBlock;
//ASSUMPTION BEING MADE: assume that the list below is constructed to
//have all the sockets FOLLOWED by FOLLOWED by the after connector
//THE ORDER MUST BE KEPT TO WORK CORRECTLY! We cannot use
//BlockLinkChecker.getSocketEquivalents because the specification does
//not guarantee this precise ordering. Futhermore, an interable
//has no defined order. However, as of this writing, the current implementation
//of that method does seem to produce this ordering. But we're still not using it.
List<BlockConnector> connections = new ArrayList<BlockConnector>();
for(BlockConnector socket : previousBlock.getSockets()){
connections.add(socket); //add sockets
}
connections.add(previousBlock.getAfterConnector()); //add after connector
//now traverse the connections
for(BlockConnector connector : connections){
if(connector == null || connector.getBlockID() == Block.NULL || getBlock(connector.getBlockID()) == null){
continue; //if null socket, move on to next socket
}
if(connector.getBlockID().equals(currentBlock.getBlockID())){ //reached back to current block
if(!beforeBlock.getBlockID().equals(previousBlock.getBlockID())){
//if previous block was never updated, go to bottom of stack
previousBlock = getBottomRightBlock(previousBlock);
}
setFocus(previousBlock.getBlockID());
return true;
}
//update previous block
previousBlock = getBlock(connector.getBlockID());
}
//so it seems liek all sockets are null (or sockets exist),
//so just get the bottom of the stack
previousBlock = getBottomRightBlock(previousBlock);
}
setFocus(previousBlock.getBlockID());
return true;
}
/**
* Gives focus to the first after block down the tree,
* that is, the next control block in the stack.
* If next control block does not exist, then give
* focus to current focusblock. Otherwise, give
* focus to block canvas.
* @requires focusblock.isMinimized() == false
* @modifies this.focusblock
* @effects sets this.focusblock to be the first
* after block if possible. Otherwise, keep
* the focus on the current focusblock.
* If focus block is an invalid block,
* return focus to the default (block canvas)
* @returns true if and only if focus was set to new after block
* @expects no wrapping to TopOfStack block, do not use this method for infix blocks
*/
public boolean focusAfterBlock() {
if(invalidBlock(focusBlock) || !RenderableBlock.getRenderableBlock(focusBlock).isVisible()){
//return focus to canvas if no focusblock does not exist
setFocus(canvasFocusPoint, Block.NULL);
return false;
}
Block currentBlock = getBlock(focusBlock);
while(currentBlock != null){
if(getAfterBlock(currentBlock) != null){
//return focus to before block
setFocus(getAfterBlock(currentBlock));
return true;
}
currentBlock = getPlugBlock(currentBlock);
if(currentBlock == null){
//return focus to old block
setFocus(focusBlock);
return true;
}
}
return true;
}
/**
* Gives focus to the first beforeblock up the tree,
* that is, the previous control block in the stack.
* If no previous control block exists, then give
* focus to current focusblock. Otherwise, give
* focus to block canvas.
* @requires focusblock.isMinimized() == false
* @modifies this.focusblock
* @effects sets this.focusblock to be the first
* before block if possible. Otherwise, keep
* the focus on the current focusblock.
* If focus block is an invalid block,
* return focus to the default (block canvas)
* @returns true if and only if focus was set to new before block
* @expects no wrapping to bottom block, do not use this method for infix blocks
*/
public boolean focusBeforeBlock() {
if(invalidBlock(focusBlock) || !RenderableBlock.getRenderableBlock(focusBlock).isVisible()){
//return focus to canvas if no focusblock does not exist
setFocus(canvasFocusPoint, Block.NULL);
return false;
}
Block currentBlock = getBlock(focusBlock);
while(currentBlock != null){
if(getBeforeBlock(currentBlock) != null){
//return focus to before block
setFocus(getBeforeBlock(currentBlock));
return true;
}
currentBlock = getPlugBlock(currentBlock);
if(currentBlock == null){
//return focus to old block
setFocus(focusBlock);
return false;
}
}
return false;
}
///////////////////////
// TRAVERSING STACKS //
///////////////////////
/**
* @requires currentBlock != null
* @param currentBlock
* @return currentBlock or NON-NULL block that is the next node of currentBlock
*/
private Block getNextNode(Block currentBlock){
//check invarient
if(invalidBlock(currentBlock)) throw new RuntimeException("Invariant Violated: may not resurve over a null instance of currentBlock");
//if plug not null, then let plug be parent of current block
Block parentBlock = getBlock(currentBlock.getPlugBlockID());
//otherwise if after not null, then let after be parent of current block
if (invalidBlock(parentBlock)) parentBlock = getBlock(currentBlock.getBeforeBlockID());
//if plug and after are both null, then return currentBlock
if(invalidBlock(parentBlock)) return currentBlock;
//socket index of current block with respect to its parent
int i = parentBlock.getSocketIndex(parentBlock.getConnectorTo(currentBlock.getBlockID()));
//return socket block of parent if one exist
//int i == 0 if not current block not a socket of parent
if(i != -1 && i>=0){
for(BlockConnector parentSocket : parentBlock.getSockets()){
if(parentSocket == null || invalidBlock(parentSocket.getBlockID()) || parentBlock.getSocketIndex(parentSocket)<=i){
continue;
}else{
return getBlock(parentSocket.getBlockID());
}
}
}
//return afterblock of parent
if(invalidBlock(parentBlock.getAfterBlockID())){
return getNextNode(parentBlock);
}
if(parentBlock.getAfterBlockID().equals(currentBlock.getBlockID())){
return getNextNode(parentBlock);
}
//This is top of the block, so return currentBlock
return getBlock(parentBlock.getAfterBlockID());
}
/**
* For a given block, returns the outermost (top-leftmost)
* block in the stack.
* @requires block represented by blockID != null
* @param blockID any block in a stack.
* @return the outermost block (or Top-of-Stack)
* such that the outermost block != null
*/
Long getTopOfStack(Long blockID) {
//check invariant
if (blockID == null || blockID == Block.NULL || Block.getBlock(blockID) == null)
throw new RuntimeException("Invariant Violated: may not" +
"iterate for outermost block over a null instance of Block");
//parentBlock is the topmost block in stack
Block parentBlock = null;
//go the top most block
parentBlock = getBeforeBlock(blockID);
if (parentBlock !=null ) return getTopOfStack(parentBlock.getBlockID());
//go to the left most block
parentBlock = getPlugBlock(blockID);
if(parentBlock != null ) return getTopOfStack(parentBlock.getBlockID());
//check invariant
assert parentBlock != null : "Invariant Violated: may not " +
"return a null instance of block as the outermost block";
//If we can't traverse any deeper, then this is innermost Block.
return blockID;
}
/**
* For a given block, returns the innermost (bottom-rightmost)
* block in the substack.
* @requires block !=null block.getBlockID != Block.NULL
* @param block the top block of the substack.
* @return the innermost block in the substack.
* such that the innermost block != null
*/
private Block getBottomRightBlock (Block block) {
//check invariant
if (block == null || block.getBlockID() == Block.NULL )
throw new RuntimeException("Invariant Violated: may not" +
"iterate for innermost block over a null instance of Block");
//returnblock = next deepest node on far right
Block returnBlock = null;
// find deepest node, that is, bottom most block in stack.
returnBlock = getAfterBlock(block);
if(returnBlock != null) return getBottomRightBlock(returnBlock);
// move to the next socket in line:
for(BlockConnector socket : block.getSockets()){//assumes socket!=null
Block socketBlock = getBlock(socket.getBlockID());
if(socketBlock !=null ) returnBlock = socketBlock;
}
if(returnBlock !=null ) return getBottomRightBlock(returnBlock);
//check invariant
assert returnBlock != null : "Invariant Violated: may not " +
"return a null instance of block as the innermost block";
//If we can't traverse any deeper, then this is innermost Block.
return block;
}
//////////////////////
//Convienence Method//
//////////////////////
/**
* @param block
* @return true if and only if block ==null ||
* block.getBlockID == null &&
* block.getBLockID == Block.NULL
*/
private boolean invalidBlock(Block block){
if (block == null) return true;
if (block.getBlockID() == null) return true;
if (block.getBlockID() == Block.NULL) return true;
return false;
}
private boolean invalidBlock(Long blockID){
if (blockID == null) return true;
if (blockID == Block.NULL) return true;
if (getBlock(blockID) == null) return true;
return false;
}
/**
* All the private methods below follow a similar
* specification. They all require that the block
* referanced by blockID (or block.getBlockID) is
* non-null. If getting a socket block, they
* additionally require that 0<socket< # of sockets in block.
* All the methods before return a block located
* at a block connector corresponding to the name
* of the obserser method.
*
* @requires blockID != Block.Null && block !=null
* @returns Block instance located at corresponding
* connection or null if non exists
*/
private Block getBlock(Long blockID) {
return Block.getBlock(blockID);
}
private Block getBeforeBlock(Long blockID) {
return getBeforeBlock(getBlock(blockID));
}
private Block getBeforeBlock(Block block) {
return getBlock(block.getBeforeBlockID());
}
private Block getAfterBlock(Block block) {
return getBlock(block.getAfterBlockID());
}
private Block getPlugBlock(Long blockID) {
return getPlugBlock(getBlock(blockID));
}
private Block getPlugBlock(Block block) {
return getBlock(block.getPlugBlockID());
}
///////////////////
// MOUSE METHODS //
///////////////////
/**
* Action: removes the focus current focused block
* and places new focus on e.getSource
* @requires e != null
* @modifies this.blockFocusOwner && e.getSource
* @effects removes focus from this.blockFocusOwner
* adds focus to e.getSource iff e.getSource
* is instance of BlockCanvas and RenderableBlock
*/
private void grabFocus(MouseEvent e){
//System.out.println("FocusManager: Mouse Event at ("+ e.getX()+", "+e.getY()+") on "+e.getSource());
if(e.getSource() instanceof Canvas){
//get canvas point
Point canvasPoint = e.getPoint();
/* SwingUtilities.convertPoint(
(BlockCanvas)e.getSource(),
e.getPoint(),
((BlockCanvas)e.getSource()).getCanvas());*/
setFocus(canvasPoint, Block.NULL);
((Canvas)e.getSource()).grabFocus();
}else if(e.getSource() instanceof RenderableBlock){
setFocus(((RenderableBlock)e.getSource()).getBlockID());
((RenderableBlock)e.getSource()).grabFocus();
}
}
public void mousePressed(MouseEvent e) {grabFocus(e);}
public void mouseReleased(MouseEvent e) {grabFocus(e);}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {}
///////////////////////////////
// Key Listeners Method //
///////////////////////////////
public void keyPressed(KeyEvent e){
KeyInputMap.processKeyChar(e);}
public void keyReleased(KeyEvent e){}
public void keyTyped(KeyEvent e){}
///////////////////////////////
// WORKSPACE LISTENER METHOD //
///////////////////////////////
/**
* Subscription: BLOCK_ADDED events.
* Action: add this.mouselistener to the block referanced by event
* @requires block reference in event is not null
* @modifies this.blockFocusOwner && event.block
* @effects Add this.mouselistener to this.blockFocusOwner
* removes focus from this.blockFocusOwner
* adds focus to e.getSource iff e.getSource
* is instance of BlockCanvas and RenderableBlock
*/
public void workspaceEventOccurred(WorkspaceEvent event) {
switch(event.getEventType()){
case WorkspaceEvent.BLOCK_ADDED:
//System.out.println("FocusManager: Block_Added Event at of "+event.getSourceBlockID()+" on "+event.getSourceWidget());
//only add focus manager as listener to blocks added to pages
if(!(event.getSourceWidget() instanceof Page)) break;
RenderableBlock rb = RenderableBlock.getRenderableBlock(event.getSourceBlockID());
if(rb == null) break;
//only add once
for(MouseListener l : rb.getMouseListeners()){
if(l.equals(this)){
return;
//TODO: this shouldn't return, it should break
//but you can't double break in java
}
}
rb.addMouseListener(this);
rb.addKeyListener(this);
setFocus(event.getSourceBlockID());
rb.grabFocus();
break;
}
}
public String toString() {
return "FocusManager: "+blockFocusPoint+" of "+Block.getBlock(focusBlock);
}
} | mit |
bkahlert/api-usability-analyzer | de.fu_berlin.imp.apiua.groundedtheory/test/de/fu_berlin/imp/apiua/groundedtheory/storage/impl/AllTests.java | 264 | package de.fu_berlin.imp.apiua.groundedtheory.storage.impl;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class)
@SuiteClasses({ CodeStoreSaveTest.class })
public class AllTests {
}
| mit |
w1ndy/tripping-dangerzone | nachos/ag/ThreadGrader2.java | 3254 | package nachos.ag;
import java.util.Vector;
import nachos.machine.Lib;
import nachos.machine.Machine;
import nachos.threads.Communicator;
import nachos.threads.KThread;
import nachos.threads.RoundRobinScheduler;
import nachos.threads.ThreadedKernel;
/**
* <li>ThreadGrader2: <b>Communicator</b><br>
* <ol type=a>
* <li>Test ThreadGrader2.a: Tests your communicator
* <li>Test ThreadGrader2.b: Tests your communicator, with more
* speakers/listeners
* <li>Test ThreadGrader2.c: Tests your communicator, with more
* speakers/listneers, and transmits more messages
* </ol>
* </li>
*
* @author Isaac
*
*/
public class ThreadGrader2 extends BasicTestGrader
{
static int total = 0;
static int totalMax = 100;
static int count = 0;
static Vector<Integer> list = new Vector<Integer>();
public void run ()
{
assertTrue(ThreadedKernel.scheduler instanceof RoundRobinScheduler,
"this test requires roundrobin scheduler");
com = new Communicator();
/* Test ThreadGrader2.a: Tests your communicator */
total = 1;
count = 0;
list.clear();
forkNewThread(new a(111));
forkNewThread(new b());
while (count != total)
{
assertTrue(Machine.timer().getTime() < 2000,
"Too many ticks wasted on \nTest ThreadGrader2.a");
KThread.yield();
}
/*
* Test ThreadGrader2.b: Tests your communicator, with more
* speakers/listeners
*/
total = 2;
count = 0;
forkNewThread(new a(111));
forkNewThread(new a(222));
forkNewThread(new b());
forkNewThread(new b());
while (count != total)
{
assertTrue(Machine.timer().getTime() < 2000,
"Too many ticks wasted on \nTest ThreadGrader2.b");
KThread.yield();
}
/*
* Test ThreadGrader2.c: Tests your communicator, with more
* speakers/listneers, and transmits more messages
*/
total = 50;
count = 0;
int na = 0, nb = 0;
for (int i = 0; i < total * 2; ++i)
{
int tmp = Lib.random(2);
if (tmp == 0)
{
++na;
forkNewThread(new a(i));
}
else
{
++nb;
forkNewThread(new b());
}
}
if (na < nb)
{
for (int i = 0; i < nb - na; ++i)
forkNewThread(new a(i + total * 2));
}
else if (na > nb)
{
for (int i = 0; i < na - nb; ++i)
forkNewThread(new b());
}
while (count != total)
{
assertTrue(Machine.timer().getTime() < 10000,
"Too many ticks wasted on \nTest ThreadGrader2.c");
KThread.yield();
}
done();
}
private Communicator com = null;
private class a implements Runnable
{
int word;
public a (int word)
{
this.word = word;
}
public void run ()
{
list.add(word);
com.speak(word);
// System.out.println(KThread.currentThread() + " say " + word);
}
}
private class b implements Runnable
{
public void run ()
{
int w = com.listen();
assertTrue(list.contains(new Integer(w)), "unknown message received");
list.remove(new Integer(w));
// System.out.println(KThread.currentThread() + " listened "
// + com.listen());
++count;
}
}
}
| mit |
RodrigoQuesadaDev/XGen4J | xgen4j/src/main/java/com/rodrigodev/xgen4j/generators/ErrorClassesGenerator.java | 4876 | /*
* The MIT License (MIT)
*
* Copyright (c) 2015 Rodrigo Quesada <rodrigoquesada.dev@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.rodrigodev.xgen4j.generators;
import com.rodrigodev.xgen4j.GenerationOptions;
import com.rodrigodev.xgen4j.model.common.clazz.ErrorExceptionClassFilePair;
import com.rodrigodev.xgen4j.model.error.ErrorClassFile;
import com.rodrigodev.xgen4j.model.error.ErrorClassWriter;
import com.rodrigodev.xgen4j.model.error.configuration.definition.ErrorDefinition;
import com.rodrigodev.xgen4j.model.error.configuration.definition.RootErrorDefinition;
import com.rodrigodev.xgen4j.model.error.exception.ExceptionClassFile;
import com.rodrigodev.xgen4j.model.error.exception.ExceptionClassWriter;
import lombok.Getter;
import lombok.NonNull;
import lombok.experimental.Accessors;
import lombok.experimental.FieldDefaults;
import lombok.experimental.NonFinal;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/**
* Created by Rodrigo Quesada on 13/07/15.
*/
@FieldDefaults(makeFinal = true)
@Accessors(fluent = true)
public class ErrorClassesGenerator extends ClassesGenerator {
public static class InjectedFields {
@Inject ErrorClassWriter errorClassWriter;
@Inject ExceptionClassWriter exceptionClassWriter;
@Inject
public InjectedFields() {
}
}
private InjectedFields inj;
private RootErrorDefinition rootError;
@NonFinal private Optional<ErrorClassFile> rootErrorClassFile;
@NonFinal private Optional<ExceptionClassFile> rootExceptionClassFile;
@Getter private List<ErrorExceptionClassFilePair> errorExceptionPairs;
private GenerationOptions options;
protected ErrorClassesGenerator(
@NonNull InjectedFields injectedFields,
String sourceDirPath,
@NonNull RootErrorDefinition rootError,
@NonNull GenerationOptions options
) {
super(sourceDirPath);
this.inj = injectedFields;
this.rootError = rootError;
this.rootErrorClassFile = Optional.empty();
this.rootExceptionClassFile = Optional.empty();
this.errorExceptionPairs = new ArrayList<>();
this.options = options;
}
public ErrorClassFile rootErrorClassFile() {
return rootErrorClassFile.get();
}
public ExceptionClassFile rootExceptionClassFile() {
return rootExceptionClassFile.get();
}
@Override
public void generate() {
generate(rootError, Optional.empty(), Optional.empty());
}
private void generate(
ErrorDefinition error,
Optional<ErrorClassFile> parentErrorClassFile,
Optional<ExceptionClassFile> parentExceptionClassFile
) {
ExceptionClassFile exceptionClassFile = inj.exceptionClassWriter.write(
sourceDirPath, rootExceptionClassFile, error, parentExceptionClassFile, options
);
ErrorClassFile errorClassFile = inj.errorClassWriter.write(
sourceDirPath,
rootErrorClassFile,
rootExceptionClassFile,
error,
exceptionClassFile,
parentErrorClassFile
);
if (!rootErrorClassFile.isPresent()) {
rootErrorClassFile = Optional.of(errorClassFile);
rootExceptionClassFile = Optional.of(exceptionClassFile);
}
errorExceptionPairs.add(new ErrorExceptionClassFilePair(errorClassFile, exceptionClassFile));
ErrorDefinition[] subErrors = error.errors();
for (ErrorDefinition subError : subErrors) {
generate(
subError,
Optional.of(errorClassFile),
Optional.of(exceptionClassFile)
);
}
}
}
| mit |
tysjiang/displaysize | src/android/DisplaySize.java | 1630 | //package com.darktalker.cordova.webviewsetting;
package com.bluechatbox.android.displaysize;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CallbackContext;
import org.json.JSONArray;
import org.json.JSONException;
import android.os.Build;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;
import android.content.Context;
import android.graphics.Point;
public class DisplaySize extends CordovaPlugin {
private CordovaWebView webView;
private static final String LOG_TAG = "DisplaySize";
@Override
public void initialize(final CordovaInterface cordova, CordovaWebView webView) {
this.webView = webView;
super.initialize(cordova, webView);
}
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if ("get".equals(action)) {
Context ctx = this.cordova.getActivity().getApplicationContext();
Display display = ((WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
callbackContext.success(Integer.toString(width) + '-' + Integer.toString(height));
return true;
}
return false; // Returning false results in a "MethodNotFound" error.
}
}
| mit |
horrorho/InflatableDonkey | src/main/java/com/github/horrorho/inflatabledonkey/cloud/clients/DeviceClient.java | 3000 | /*
* The MIT License
*
* Copyright 2016 Ahseya.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.horrorho.inflatabledonkey.cloud.clients;
import com.github.horrorho.inflatabledonkey.cloudkitty.CloudKitty;
import com.github.horrorho.inflatabledonkey.cloudkitty.operations.RecordRetrieveRequestOperations;
import com.github.horrorho.inflatabledonkey.data.backup.Device;
import com.github.horrorho.inflatabledonkey.data.backup.DeviceID;
import com.github.horrorho.inflatabledonkey.data.backup.DeviceFactory;
import com.github.horrorho.inflatabledonkey.protobuf.CloudKit;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.annotation.concurrent.Immutable;
import org.apache.http.client.HttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author Ahseya
*/
@Immutable
public final class DeviceClient {
private static final Logger logger = LoggerFactory.getLogger(DeviceClient.class);
public static List<Device>
apply(HttpClient httpClient, CloudKitty kitty, Collection<DeviceID> devices)
throws IOException {
List<String> deviceList = devices.stream()
.map(Object::toString)
.collect(Collectors.toList());
List<CloudKit.RecordRetrieveResponse> responses
= RecordRetrieveRequestOperations.get(kitty, httpClient, "mbksync", deviceList);
return devices(responses);
}
static List<Device> devices(List<CloudKit.RecordRetrieveResponse> responses) {
logger.debug("-- devices() - responses: {}", responses);
return responses
.stream()
.map(CloudKit.RecordRetrieveResponse::getRecord)
.map(DeviceFactory::from)
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toList());
}
}
| mit |
Jesus-Gonzalez/jeecommerce | src/jeecommerce modelos/src/modelos/Banco.java | 383 | package modelos;
/**
*
* Clase contenedora para un banco
*
* @author jesus
*
*/
public class Banco
{
public long bid;
public String nombre,
numero;
public boolean activo;
public Banco() {}
public Banco(long bid, String nombre, String numero, boolean activo)
{
this.bid = bid;
this.nombre = nombre;
this.numero = numero;
this.activo = activo;
}
}
| mit |
sancas/JAVA-UDB | Practica 1/ejemplo2.java | 418 | import java.util.*;
public class ejemplo2 {
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
int n1;
int n2;
int suma;
System.out.print("Ingrese el 1er numero: ");
n1 = reader.nextInt();
System.out.print("Ingrese el 2do numero: ");
n2 = reader.nextInt();
suma = n1 + n2;
System.out.println("suma de " + n1 + " y " + n2 + " es " + suma);
System.exit(0);
}
} | mit |
jwfwessels/AFK | src/afk/bot/Robot.java | 2745 | /*
* Copyright (c) 2013 Triforce - in association with the University of Pretoria and Epi-Use <Advance/>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package afk.bot;
import afk.bot.london.RobotEvent;
import java.util.UUID;
/**
* This is the interface to all user-written Robot classes.
*
* @author Daniel
*/
public interface Robot
{
/**
* Sets all flags to there default "false" position.
*/
public void clearActions();
/**
* Gets a copy of the action array.
* @return
*/
public boolean[] getActions();
/**
* Sets the events for this tick.
* @param events the events.
*/
public void setEvents(RobotEvent events);
/**
* Gets the robot's unique ID.
* @return
*/
public UUID getId();
/**
* Get the robot's number.
* @return the robot's number.
*/
public int getBotNum();
/**
* Main execution method of the robot implemented by the user. This is
* called once every game tick to calculate the actions to take for that
* game tick.
*/
public void run();
/**
* Initialisation code is implemented by the user here. This is where any
* robot configuration properties may be set.
*/
public void init();
/**
* Gets the RobotConfigManager associated with this robot.
* @return the RobotConfigManager associated with this robot.
*/
public RobotConfigManager getConfigManager();
/**
* Sets the RobotConfigManager to associate with this robot.
* @return the RobotConfigManager to associate with this robot.
*/
public void setConfigManager(RobotConfigManager config);
}
| mit |
yuriytkach/spring-basics-course-project | src/main/java/com/yet/spring/core/loggers/CacheFileEventLogger.java | 748 | package com.yet.spring.core.loggers;
import java.util.ArrayList;
import java.util.List;
import com.yet.spring.core.beans.Event;
public class CacheFileEventLogger extends FileEventLogger {
private int cacheSize;
private List<Event> cache;
public CacheFileEventLogger(String filename, int cacheSize) {
super(filename);
this.cacheSize = cacheSize;
this.cache = new ArrayList<Event>(cacheSize);
}
public void destroy() {
if ( ! cache.isEmpty()) {
writeEventsFromCache();
}
}
@Override
public void logEvent(Event event) {
cache.add(event);
if (cache.size() == cacheSize) {
writeEventsFromCache();
cache.clear();
}
}
private void writeEventsFromCache() {
cache.stream().forEach(super::logEvent);
}
}
| mit |
mickleness/pumpernickel | src/main/java/com/pump/plaf/PulsingCirclesThrobberUI.java | 2926 | /**
* This software is released as part of the Pumpernickel project.
*
* All com.pump resources in the Pumpernickel project are distributed under the
* MIT License:
* https://raw.githubusercontent.com/mickleness/pumpernickel/master/License.txt
*
* More information about the Pumpernickel project is available here:
* https://mickleness.github.io/pumpernickel/
*/
package com.pump.plaf;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import javax.swing.JComponent;
/**
* A <code>ThrobberUI</code> showing 3 circles pulsing outward that also move in
* a clockwise rotation.
* <p>
* <table summary="Sample Animations of PulsingCirclesThrobberUI" cellpadding="10">
* <tr>
* <td><img src=
* "https://raw.githubusercontent.com/mickleness/pumpernickel/master/resources/throbber/PulsingCirclesThrobberUI.gif"
* alt="PulsingCirclesThrobberUI"></td>
* <td><img src=
* "https://raw.githubusercontent.com/mickleness/pumpernickel/master/resources/throbber/PulsingCirclesThrobberUIx2.gif"
* alt="PulsingCirclesThrobberUI, Magnified 2x"></td>
* <td><img src=
* "https://raw.githubusercontent.com/mickleness/pumpernickel/master/resources/throbber/PulsingCirclesThrobberUIx4.gif"
* alt="PulsingCirclesThrobberUI, Magnified 4x"></td>
* </tr>
* </table>
* <p>
* On installation: the component's foreground is set to dark gray, but if that
* is changed then that color is used to render this animation.
* <P>
* The default period for this animation is 750, but you can modify this with
* the period client properties {@link ThrobberUI#PERIOD_KEY} or
* {@link ThrobberUI#PERIOD_MULTIPLIER_KEY}.
*
*/
public class PulsingCirclesThrobberUI extends ThrobberUI {
/**
* The default duration (in ms) it takes to complete a cycle.
*/
public static final int DEFAULT_PERIOD = 750;
public PulsingCirclesThrobberUI() {
super(1000 / 24);
}
@Override
protected synchronized void paintForeground(Graphics2D g, JComponent jc,
Dimension size, Float fixedFraction) {
float f;
if (fixedFraction != null) {
f = fixedFraction;
} else {
int p = getPeriod(jc, DEFAULT_PERIOD);
float t = System.currentTimeMillis() % p;
f = t / p;
}
boolean spiral = false;
double maxDotSize = spiral ? 2 : 2.2;
Color color = jc == null ? getDefaultForeground() : jc.getForeground();
g.setColor(color);
for (int a = 0; a < 8; a++) {
double z = a / 8.0;
double r = spiral ? 6 * ((z - f + 1) % 1) : 6;
double x = size.width / 2 + r * Math.cos(Math.PI * 2 * z);
double y = size.width / 2 + r * Math.sin(Math.PI * 2 * z);
double k = maxDotSize * ((z - f + 1) % 1);
Ellipse2D dot = new Ellipse2D.Double(x - k, y - k, 2 * k, 2 * k);
g.fill(dot);
}
}
@Override
public Dimension getPreferredSize() {
return new Dimension(16, 16);
}
@Override
public Color getDefaultForeground() {
return Color.darkGray;
}
} | mit |
oguzbilgener/cs319-project | src/main/java/util/TimerListener.java | 193 | package util;
import java.util.Timer;
/**
* Created by asusss on 11.12.2015.
*/
public interface TimerListener {
public void onTimeOut();
public void onTick (int elapsedTime);
}
| mit |
aviolette/foodtrucklocator | main/src/main/java/foodtruck/geolocation/GoogleServerApiKey.java | 537 | package foodtruck.geolocation;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import com.google.inject.BindingAnnotation;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* @author aviolette
* @since 5/19/16
*/
@BindingAnnotation
@Target({FIELD, PARAMETER, METHOD}) @Retention(RUNTIME)
@interface GoogleServerApiKey {
}
| mit |
acidghost/algorithms-data-structures-java | src/it/uniba/di/itps/asd/exams/Lab20101117/pila/PilaDoubling.java | 944 | package it.uniba.di.itps.asd.exams.Lab20101117.pila;
/**
* Created by acidghost on 27/08/14.
*/
public class PilaDoubling<T> implements Pila<T> {
private T[] pila = (T[]) new Object[1];
private int n = 0;
@Override
public boolean isEmpty() {
return n == 0;
}
@Override
public void push(T e) {
if(n == pila.length) {
T[] tmp = (T[]) new Object[n * 2];
System.arraycopy(pila, 0, tmp, 0, n);
pila = tmp;
}
pila[n] = e;
n++;
}
@Override
public T top() {
if(isEmpty()) {
throw new EccezioneStrutturaVuota("Pila vuota");
} else {
return pila[n-1];
}
}
@Override
public void pop() {
if(n <= pila.length/4) {
T[] tmp = (T[]) new Object[n / 2];
System.arraycopy(pila, 0, tmp, 0, n);
pila = tmp;
}
n--;
}
}
| mit |
ivailopankow/Android-Learning-Projects | UIRadioGroup/app/build/generated/source/buildConfig/debug/course/examples/ui/radiogroup/BuildConfig.java | 465 | /**
* Automatically generated file. DO NOT MODIFY
*/
package course.examples.ui.radiogroup;
public final class BuildConfig {
public static final boolean DEBUG = Boolean.parseBoolean("true");
public static final String APPLICATION_ID = "course.examples.ui.radiogroup";
public static final String BUILD_TYPE = "debug";
public static final String FLAVOR = "";
public static final int VERSION_CODE = 1;
public static final String VERSION_NAME = "1.0";
}
| mit |
timur86/console-downloader | src/main/java/com/github/itimur/downloader/AsyncDownloader.java | 1331 | package com.github.itimur.downloader;
import com.github.itimur.callbacks.FutureDownloadCallback;
import com.google.common.collect.ImmutableList;
import com.google.common.eventbus.EventBus;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
/**
* @author Timur
*/
public class AsyncDownloader implements Downloader {
@Override
public void startAllAsync(ImmutableList<DownloadTask> tasks,
ListeningExecutorService executor,
EventBus evenBus) {
FutureDownloadCallback downloadCallback = new FutureDownloadCallback(evenBus);
for (ListenableFuture<Download> future : submitTasks(tasks, executor)) {
Futures.addCallback(future, downloadCallback, executor);
}
}
private ImmutableList<ListenableFuture<Download>> submitTasks(ImmutableList<DownloadTask> tasks,
ListeningExecutorService executor) {
ImmutableList.Builder<ListenableFuture<Download>> futures = ImmutableList.builder();
for (DownloadTask task : tasks) {
futures.add(executor.submit(task));
}
return futures.build();
}
}
| mit |
justacoder/mica | src/parts/MiBasicPropertyPanel.java | 5741 |
/*
***************************************************************************
* Mica - the Java(tm) Graphics Framework *
***************************************************************************
* NOTICE: Permission to use, copy, and modify this software and its *
* documentation is hereby granted provided that this notice appears in *
* all copies. *
* *
* Permission to distribute un-modified copies of this software and its *
* documentation is hereby granted provided that no fee is charged and *
* that this notice appears in all copies. *
* *
* SOFTWARE FARM MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE *
* SUITABILITY OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT *
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR *
* A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SOFTWARE FARM SHALL NOT BE *
* LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR *
* CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE, MODIFICATION OR *
* DISTRIBUTION OF THIS SOFTWARE OR ITS DERIVATIVES. *
* *
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND *
* DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, *
* UPDATES, ENHANCEMENTS, OR MODIFICATIONS. *
* *
***************************************************************************
* Copyright (c) 1997-2004 Software Farm, Inc. All Rights Reserved. *
***************************************************************************
*/
package com.swfm.mica;
import com.swfm.mica.util.Strings;
/**
* @version %I% %G%
* @author Michael L. Davis
* @release 1.4.1
* @module %M%
* @language Java (JDK 1.4)
*/
public class MiBasicPropertyPanel extends MiPropertyPanel
{
private MiTable table;
private MiScrolledBox scrolledBox;
public MiBasicPropertyPanel(boolean scrollable)
{
this(scrollable, 1);
}
public MiBasicPropertyPanel(boolean scrollable, int numberOfColumns)
{
MiColumnLayout layout = new MiColumnLayout();
layout.setElementHSizing(Mi_EXPAND_TO_FILL);
layout.setUniqueElementIndex(0);
layout.setUniqueElementSizing(Mi_EXPAND_TO_FILL);
setLayout(layout);
MiParts scrolledBoxReturn = new MiParts();
table = makePropertyPanelTable(this, scrollable, numberOfColumns, scrolledBoxReturn);
scrolledBox = scrolledBoxReturn.size() > 0 ? (MiScrolledBox )scrolledBoxReturn.get(0) : null;
}
public int getInspectedObjectIndex()
{
return(-1);
}
public MiTable getTable()
{
return(table);
}
public MiScrolledBox getScrolledBox()
{
return(scrolledBox);
}
protected void generatePanel()
{
makePropertyPanelWidgets(this, table);
}
public static MiTable makePropertyPanelTable(MiPart container, boolean scrollable)
{
return(makePropertyPanelTable(container, scrollable, 1));
}
public static MiTable makePropertyPanelTable(
MiPart container, boolean scrollable, int numberOfColumns)
{
return(makePropertyPanelTable(container, scrollable, numberOfColumns));
}
public static MiTable makePropertyPanelTable(
MiPart container, boolean scrollable, int numberOfColumns, MiParts scrolledBoxReturn)
{
MiTable table = new MiTable();
table.getTableWideDefaults().setHorizontalJustification(Mi_LEFT_JUSTIFIED);
table.getTableWideDefaults().setHorizontalSizing(Mi_SAME_SIZE);
table.setTotalNumberOfColumns(numberOfColumns * 2);
table.setHasFixedTotalNumberOfColumns(true);
table.setMinimumNumberOfVisibleColumns(numberOfColumns * 2);
table.setMaximumNumberOfVisibleColumns(numberOfColumns * 2);
table.getSectionMargins().setMargins(0);
table.getTableWideDefaults().insetMargins.setMargins(4, 2, 4, 2);
table.getMadeColumnDefaults(1).setColumnHorizontalSizing(Mi_EXPAND_TO_FILL);
MiRectangle cellBackgroundRect = new MiRectangle();
cellBackgroundRect.setBorderLook(Mi_RAISED_BORDER_LOOK);
table.getBackgroundManager().appendCellBackgrounds(cellBackgroundRect);
table.setPropertyValue(MiTable.Mi_CELL_BG_PROPERTY_NAME + ".backgroundColor",
MiColorManager.getColorName(table.getBackgroundColor()));
table.getSelectionManager().setMaximumNumberSelected(0);
table.getSelectionManager().setBrowsable(false);
if (scrollable)
{
MiScrolledBox scrolledBox = new MiScrolledBox(table);
container.appendPart(scrolledBox);
scrolledBoxReturn.add(scrolledBox);
}
else
{
table.setPreferredNumberOfVisibleRows(-1);
container.appendPart(table);
}
return(table);
}
public static void makePropertyPanelWidgets(MiPropertyPanel panel, MiTable table)
{
table.removeAllCells();
MiPropertyWidgets properties = panel.getPropertyWidgets();
if (properties.size() < table.getPreferredNumberOfVisibleRows())
{
table.setPreferredNumberOfVisibleRows(properties.size());
}
MiParts parts = new MiParts();
for (int i = 0; i < properties.size(); ++i)
{
MiText label = new MiText(properties.elementAt(i).getDisplayName());
MiWidget widget = properties.elementAt(i).getWidget();
label.setStatusHelp(widget.getStatusHelp(widget.getCenter()));
label.setDialogHelp(widget.getDialogHelp(null));
parts.addElement(label);
parts.addElement(widget);
}
table.appendItems(parts);
}
}
| mit |
fcduarte/simple-todo | src/com/fcduarte/todoapp/activity/TodoActivity.java | 5147 | package com.fcduarte.todoapp.activity;
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.widget.CursorAdapter;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import com.fcduarte.todoapp.R;
import com.fcduarte.todoapp.database.TodoContract.TodoItem;
import com.fcduarte.todoapp.database.TodoItemDataSource;
import com.fcduarte.todoapp.util.SwipeDismissListViewTouchListener;
public class TodoActivity extends Activity {
public static int RESULT_OK = 200;
public static int RESULT_NOT_MODIFIED = 304;
private static int REQUEST_EDIT_ITEM = 0;
private static TodoItemDataSource datasource;
private static SimpleCursorAdapter itemsAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_todo);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction().add(R.id.container, new MainFragment()).commit();
}
datasource = new TodoItemDataSource(this);
datasource.open();
itemsAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1,
datasource.getAll(), new String[] { TodoItem.COLUMN_NAME_ITEM_DESCRIPTION },
new int[] { android.R.id.text1 }, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.todo, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == REQUEST_EDIT_ITEM) {
Long itemId = data.getLongExtra(EditItemActivity.ITEM_ID, -1);
String newItemDescription = data.getStringExtra(EditItemActivity.ITEM_DESCRIPTION);
updateItem(itemId, newItemDescription);
}
}
public static class MainFragment extends Fragment {
private ListView lvItems;
private View rootView;
private Button btnAddItem;
private EditText etNewItem;
public MainFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_todo, container, false);
etNewItem = (EditText) rootView.findViewById(R.id.etNewItem);
lvItems = (ListView) rootView.findViewById(R.id.lvItems);
lvItems.setAdapter(itemsAdapter);
SwipeDismissListViewTouchListener touchListener = new SwipeDismissListViewTouchListener(
lvItems,
new SwipeDismissListViewTouchListener.DismissCallbacks() {
@Override
public boolean canDismiss(int position) {
return true;
}
@Override
public void onDismiss(ListView listView, int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
removeTodoItem(position);
}
}
});
lvItems.setOnTouchListener(touchListener);
lvItems.setOnScrollListener(touchListener.makeScrollListener());
lvItems.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Cursor cursor = itemsAdapter.getCursor();
Intent intent = new Intent(getActivity(), EditItemActivity.class);
intent.putExtra(EditItemActivity.ITEM_ID,
cursor.getLong(TodoItem.COLUMN_NAME_ID_POSITION));
intent.putExtra(EditItemActivity.ITEM_DESCRIPTION,
cursor.getString(TodoItem.COLUMN_NAME_ITEM_DESCRIPTION_POSITION));
getActivity().startActivityForResult(intent, TodoActivity.REQUEST_EDIT_ITEM);
}
});
btnAddItem = (Button) rootView.findViewById(R.id.btnAddItem);
btnAddItem.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
addTodoItem();
etNewItem.setText("");
lvItems.smoothScrollToPosition(itemsAdapter.getCount());
}
});
return rootView;
}
private void addTodoItem() {
datasource.create(etNewItem.getText().toString());
itemsAdapter.changeCursor(datasource.getAll());
}
private void removeTodoItem(int position) {
Cursor cursor = itemsAdapter.getCursor();
cursor.moveToPosition(position);
datasource.delete(cursor.getLong(TodoItem.COLUMN_NAME_ID_POSITION));
itemsAdapter.changeCursor(datasource.getAll());
}
}
private void updateItem(Long itemId, String newItemDescription) {
datasource.update(itemId, newItemDescription);
itemsAdapter.changeCursor(datasource.getAll());
}
}
| mit |
Epsilon2/Memetic-Algorithm-for-TSP | jfreechart-1.0.16/source/org/jfree/data/xy/XYIntervalSeriesCollection.java | 11638 | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2013, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library 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 Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.]
*
* -------------------------------
* XYIntervalSeriesCollection.java
* -------------------------------
* (C) Copyright 2006-2013, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 20-Oct-2006 : Version 1 (DG);
* 13-Feb-2007 : Provided a number of method overrides that enhance
* performance, and added a proper clone()
* implementation (DG);
* 18-Jan-2008 : Added removeSeries() and removeAllSeries() methods (DG);
* 22-Apr-2008 : Implemented PublicCloneable (DG);
* 02-Jul-2013 : Use ParamChecks (DG);
*
*/
package org.jfree.data.xy;
import java.io.Serializable;
import java.util.List;
import org.jfree.chart.util.ParamChecks;
import org.jfree.data.general.DatasetChangeEvent;
import org.jfree.util.ObjectUtilities;
import org.jfree.util.PublicCloneable;
/**
* A collection of {@link XYIntervalSeries} objects.
*
* @since 1.0.3
*
* @see XYIntervalSeries
*/
public class XYIntervalSeriesCollection extends AbstractIntervalXYDataset
implements IntervalXYDataset, PublicCloneable, Serializable {
/** Storage for the data series. */
private List data;
/**
* Creates a new instance of <code>XIntervalSeriesCollection</code>.
*/
public XYIntervalSeriesCollection() {
this.data = new java.util.ArrayList();
}
/**
* Adds a series to the collection and sends a {@link DatasetChangeEvent}
* to all registered listeners.
*
* @param series the series (<code>null</code> not permitted).
*/
public void addSeries(XYIntervalSeries series) {
ParamChecks.nullNotPermitted(series, "series");
this.data.add(series);
series.addChangeListener(this);
fireDatasetChanged();
}
/**
* Returns the number of series in the collection.
*
* @return The series count.
*/
public int getSeriesCount() {
return this.data.size();
}
/**
* Returns a series from the collection.
*
* @param series the series index (zero-based).
*
* @return The series.
*
* @throws IllegalArgumentException if <code>series</code> is not in the
* range <code>0</code> to <code>getSeriesCount() - 1</code>.
*/
public XYIntervalSeries getSeries(int series) {
if ((series < 0) || (series >= getSeriesCount())) {
throw new IllegalArgumentException("Series index out of bounds");
}
return (XYIntervalSeries) this.data.get(series);
}
/**
* Returns the key for a series.
*
* @param series the series index (in the range <code>0</code> to
* <code>getSeriesCount() - 1</code>).
*
* @return The key for a series.
*
* @throws IllegalArgumentException if <code>series</code> is not in the
* specified range.
*/
public Comparable getSeriesKey(int series) {
// defer argument checking
return getSeries(series).getKey();
}
/**
* Returns the number of items in the specified series.
*
* @param series the series (zero-based index).
*
* @return The item count.
*
* @throws IllegalArgumentException if <code>series</code> is not in the
* range <code>0</code> to <code>getSeriesCount() - 1</code>.
*/
public int getItemCount(int series) {
// defer argument checking
return getSeries(series).getItemCount();
}
/**
* Returns the x-value for an item within a series.
*
* @param series the series index.
* @param item the item index.
*
* @return The x-value.
*/
public Number getX(int series, int item) {
XYIntervalSeries s = (XYIntervalSeries) this.data.get(series);
return s.getX(item);
}
/**
* Returns the start x-value (as a double primitive) for an item within a
* series.
*
* @param series the series index (zero-based).
* @param item the item index (zero-based).
*
* @return The value.
*/
public double getStartXValue(int series, int item) {
XYIntervalSeries s = (XYIntervalSeries) this.data.get(series);
return s.getXLowValue(item);
}
/**
* Returns the end x-value (as a double primitive) for an item within a
* series.
*
* @param series the series index (zero-based).
* @param item the item index (zero-based).
*
* @return The value.
*/
public double getEndXValue(int series, int item) {
XYIntervalSeries s = (XYIntervalSeries) this.data.get(series);
return s.getXHighValue(item);
}
/**
* Returns the y-value (as a double primitive) for an item within a
* series.
*
* @param series the series index (zero-based).
* @param item the item index (zero-based).
*
* @return The value.
*/
public double getYValue(int series, int item) {
XYIntervalSeries s = (XYIntervalSeries) this.data.get(series);
return s.getYValue(item);
}
/**
* Returns the start y-value (as a double primitive) for an item within a
* series.
*
* @param series the series index (zero-based).
* @param item the item index (zero-based).
*
* @return The value.
*/
public double getStartYValue(int series, int item) {
XYIntervalSeries s = (XYIntervalSeries) this.data.get(series);
return s.getYLowValue(item);
}
/**
* Returns the end y-value (as a double primitive) for an item within a
* series.
*
* @param series the series (zero-based index).
* @param item the item (zero-based index).
*
* @return The value.
*/
public double getEndYValue(int series, int item) {
XYIntervalSeries s = (XYIntervalSeries) this.data.get(series);
return s.getYHighValue(item);
}
/**
* Returns the y-value for an item within a series.
*
* @param series the series index.
* @param item the item index.
*
* @return The y-value.
*/
public Number getY(int series, int item) {
return new Double(getYValue(series, item));
}
/**
* Returns the start x-value for an item within a series.
*
* @param series the series index.
* @param item the item index.
*
* @return The x-value.
*/
public Number getStartX(int series, int item) {
return new Double(getStartXValue(series, item));
}
/**
* Returns the end x-value for an item within a series.
*
* @param series the series index.
* @param item the item index.
*
* @return The x-value.
*/
public Number getEndX(int series, int item) {
return new Double(getEndXValue(series, item));
}
/**
* Returns the start y-value for an item within a series. This method
* maps directly to {@link #getY(int, int)}.
*
* @param series the series index.
* @param item the item index.
*
* @return The start y-value.
*/
public Number getStartY(int series, int item) {
return new Double(getStartYValue(series, item));
}
/**
* Returns the end y-value for an item within a series. This method
* maps directly to {@link #getY(int, int)}.
*
* @param series the series index.
* @param item the item index.
*
* @return The end y-value.
*/
public Number getEndY(int series, int item) {
return new Double(getEndYValue(series, item));
}
/**
* Removes a series from the collection and sends a
* {@link DatasetChangeEvent} to all registered listeners.
*
* @param series the series index (zero-based).
*
* @since 1.0.10
*/
public void removeSeries(int series) {
if ((series < 0) || (series >= getSeriesCount())) {
throw new IllegalArgumentException("Series index out of bounds.");
}
XYIntervalSeries ts = (XYIntervalSeries) this.data.get(series);
ts.removeChangeListener(this);
this.data.remove(series);
fireDatasetChanged();
}
/**
* Removes a series from the collection and sends a
* {@link DatasetChangeEvent} to all registered listeners.
*
* @param series the series (<code>null</code> not permitted).
*
* @since 1.0.10
*/
public void removeSeries(XYIntervalSeries series) {
ParamChecks.nullNotPermitted(series, "series");
if (this.data.contains(series)) {
series.removeChangeListener(this);
this.data.remove(series);
fireDatasetChanged();
}
}
/**
* Removes all the series from the collection and sends a
* {@link DatasetChangeEvent} to all registered listeners.
*
* @since 1.0.10
*/
public void removeAllSeries() {
// Unregister the collection as a change listener to each series in
// the collection.
for (int i = 0; i < this.data.size(); i++) {
XYIntervalSeries series = (XYIntervalSeries) this.data.get(i);
series.removeChangeListener(this);
}
this.data.clear();
fireDatasetChanged();
}
/**
* Tests this instance for equality with an arbitrary object.
*
* @param obj the object (<code>null</code> permitted).
*
* @return A boolean.
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof XYIntervalSeriesCollection)) {
return false;
}
XYIntervalSeriesCollection that = (XYIntervalSeriesCollection) obj;
return ObjectUtilities.equal(this.data, that.data);
}
/**
* Returns a clone of this dataset.
*
* @return A clone of this dataset.
*
* @throws CloneNotSupportedException if there is a problem cloning.
*/
public Object clone() throws CloneNotSupportedException {
XYIntervalSeriesCollection clone
= (XYIntervalSeriesCollection) super.clone();
int seriesCount = getSeriesCount();
clone.data = new java.util.ArrayList(seriesCount);
for (int i = 0; i < this.data.size(); i++) {
clone.data.set(i, getSeries(i).clone());
}
return clone;
}
}
| mit |
digitalheir/java-legislation-gov-uk-library | src/main/java/org/w3/_1998/math/mathml/NamedSpace.java | 2257 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.08.07 at 06:17:52 PM CEST
//
package org.w3._1998.math.mathml;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for named-space.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="named-space">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="veryverythinmathspace"/>
* <enumeration value="verythinmathspace"/>
* <enumeration value="thinmathspace"/>
* <enumeration value="mediummathspace"/>
* <enumeration value="thickmathspace"/>
* <enumeration value="verythickmathspace"/>
* <enumeration value="veryverythickmathspace"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "named-space")
@XmlEnum
public enum NamedSpace {
@XmlEnumValue("veryverythinmathspace")
VERYVERYTHINMATHSPACE("veryverythinmathspace"),
@XmlEnumValue("verythinmathspace")
VERYTHINMATHSPACE("verythinmathspace"),
@XmlEnumValue("thinmathspace")
THINMATHSPACE("thinmathspace"),
@XmlEnumValue("mediummathspace")
MEDIUMMATHSPACE("mediummathspace"),
@XmlEnumValue("thickmathspace")
THICKMATHSPACE("thickmathspace"),
@XmlEnumValue("verythickmathspace")
VERYTHICKMATHSPACE("verythickmathspace"),
@XmlEnumValue("veryverythickmathspace")
VERYVERYTHICKMATHSPACE("veryverythickmathspace");
private final String value;
NamedSpace(String v) {
value = v;
}
public static NamedSpace fromValue(String v) {
for (NamedSpace c: NamedSpace.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
public String value() {
return value;
}
}
| mit |
novirael/school-codebase | java/algorithms/src/stacks3/Zad3.java | 1100 | package stacks3;
import java.io.*;
// Todo
public class Zad3 {
public static void main(String[] args) {
Stos stos = new Stos();
while (true) {
System.out.println("Podaj napis do odwrócenia (Puste konczy program)");
String napis = "";
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
napis = br.readLine();
System.out.println(napis);
}
catch (IOException e){
e.printStackTrace();
}
if (napis.isEmpty()) {
break;
}
for (String litera : napis.split("")) {
stos.dodajDoStosu(litera);
}
String napisDoWypisania = "";
while (true){
try{
napisDoWypisania += stos.pobierzZeStosu();
}
catch (PustyStosException e){
break;
}
}
System.out.println(napisDoWypisania);
}
}
} | mit |
limpoxe/Android-Plugin-Framework | Samples/PluginTest/src/main/java/com/example/plugintest/manymethods/f/c/A5.java | 8249 | package com.example.plugintest.manymethods.f.c;
public class A5 {
public static void a0(String msg) { System.out.println("msg=" + msg + 0); }
public static void a1(String msg) { System.out.println("msg=" + msg + 1); }
public static void a2(String msg) { System.out.println("msg=" + msg + 2); }
public static void a3(String msg) { System.out.println("msg=" + msg + 3); }
public static void a4(String msg) { System.out.println("msg=" + msg + 4); }
public static void a5(String msg) { System.out.println("msg=" + msg + 5); }
public static void a6(String msg) { System.out.println("msg=" + msg + 6); }
public static void a7(String msg) { System.out.println("msg=" + msg + 7); }
public static void a8(String msg) { System.out.println("msg=" + msg + 8); }
public static void a9(String msg) { System.out.println("msg=" + msg + 9); }
public static void a10(String msg) { System.out.println("msg=" + msg + 10); }
public static void a11(String msg) { System.out.println("msg=" + msg + 11); }
public static void a12(String msg) { System.out.println("msg=" + msg + 12); }
public static void a13(String msg) { System.out.println("msg=" + msg + 13); }
public static void a14(String msg) { System.out.println("msg=" + msg + 14); }
public static void a15(String msg) { System.out.println("msg=" + msg + 15); }
public static void a16(String msg) { System.out.println("msg=" + msg + 16); }
public static void a17(String msg) { System.out.println("msg=" + msg + 17); }
public static void a18(String msg) { System.out.println("msg=" + msg + 18); }
public static void a19(String msg) { System.out.println("msg=" + msg + 19); }
public static void a20(String msg) { System.out.println("msg=" + msg + 20); }
public static void a21(String msg) { System.out.println("msg=" + msg + 21); }
public static void a22(String msg) { System.out.println("msg=" + msg + 22); }
public static void a23(String msg) { System.out.println("msg=" + msg + 23); }
public static void a24(String msg) { System.out.println("msg=" + msg + 24); }
public static void a25(String msg) { System.out.println("msg=" + msg + 25); }
public static void a26(String msg) { System.out.println("msg=" + msg + 26); }
public static void a27(String msg) { System.out.println("msg=" + msg + 27); }
public static void a28(String msg) { System.out.println("msg=" + msg + 28); }
public static void a29(String msg) { System.out.println("msg=" + msg + 29); }
public static void a30(String msg) { System.out.println("msg=" + msg + 30); }
public static void a31(String msg) { System.out.println("msg=" + msg + 31); }
public static void a32(String msg) { System.out.println("msg=" + msg + 32); }
public static void a33(String msg) { System.out.println("msg=" + msg + 33); }
public static void a34(String msg) { System.out.println("msg=" + msg + 34); }
public static void a35(String msg) { System.out.println("msg=" + msg + 35); }
public static void a36(String msg) { System.out.println("msg=" + msg + 36); }
public static void a37(String msg) { System.out.println("msg=" + msg + 37); }
public static void a38(String msg) { System.out.println("msg=" + msg + 38); }
public static void a39(String msg) { System.out.println("msg=" + msg + 39); }
public static void a40(String msg) { System.out.println("msg=" + msg + 40); }
public static void a41(String msg) { System.out.println("msg=" + msg + 41); }
public static void a42(String msg) { System.out.println("msg=" + msg + 42); }
public static void a43(String msg) { System.out.println("msg=" + msg + 43); }
public static void a44(String msg) { System.out.println("msg=" + msg + 44); }
public static void a45(String msg) { System.out.println("msg=" + msg + 45); }
public static void a46(String msg) { System.out.println("msg=" + msg + 46); }
public static void a47(String msg) { System.out.println("msg=" + msg + 47); }
public static void a48(String msg) { System.out.println("msg=" + msg + 48); }
public static void a49(String msg) { System.out.println("msg=" + msg + 49); }
public static void a50(String msg) { System.out.println("msg=" + msg + 50); }
public static void a51(String msg) { System.out.println("msg=" + msg + 51); }
public static void a52(String msg) { System.out.println("msg=" + msg + 52); }
public static void a53(String msg) { System.out.println("msg=" + msg + 53); }
public static void a54(String msg) { System.out.println("msg=" + msg + 54); }
public static void a55(String msg) { System.out.println("msg=" + msg + 55); }
public static void a56(String msg) { System.out.println("msg=" + msg + 56); }
public static void a57(String msg) { System.out.println("msg=" + msg + 57); }
public static void a58(String msg) { System.out.println("msg=" + msg + 58); }
public static void a59(String msg) { System.out.println("msg=" + msg + 59); }
public static void a60(String msg) { System.out.println("msg=" + msg + 60); }
public static void a61(String msg) { System.out.println("msg=" + msg + 61); }
public static void a62(String msg) { System.out.println("msg=" + msg + 62); }
public static void a63(String msg) { System.out.println("msg=" + msg + 63); }
public static void a64(String msg) { System.out.println("msg=" + msg + 64); }
public static void a65(String msg) { System.out.println("msg=" + msg + 65); }
public static void a66(String msg) { System.out.println("msg=" + msg + 66); }
public static void a67(String msg) { System.out.println("msg=" + msg + 67); }
public static void a68(String msg) { System.out.println("msg=" + msg + 68); }
public static void a69(String msg) { System.out.println("msg=" + msg + 69); }
public static void a70(String msg) { System.out.println("msg=" + msg + 70); }
public static void a71(String msg) { System.out.println("msg=" + msg + 71); }
public static void a72(String msg) { System.out.println("msg=" + msg + 72); }
public static void a73(String msg) { System.out.println("msg=" + msg + 73); }
public static void a74(String msg) { System.out.println("msg=" + msg + 74); }
public static void a75(String msg) { System.out.println("msg=" + msg + 75); }
public static void a76(String msg) { System.out.println("msg=" + msg + 76); }
public static void a77(String msg) { System.out.println("msg=" + msg + 77); }
public static void a78(String msg) { System.out.println("msg=" + msg + 78); }
public static void a79(String msg) { System.out.println("msg=" + msg + 79); }
public static void a80(String msg) { System.out.println("msg=" + msg + 80); }
public static void a81(String msg) { System.out.println("msg=" + msg + 81); }
public static void a82(String msg) { System.out.println("msg=" + msg + 82); }
public static void a83(String msg) { System.out.println("msg=" + msg + 83); }
public static void a84(String msg) { System.out.println("msg=" + msg + 84); }
public static void a85(String msg) { System.out.println("msg=" + msg + 85); }
public static void a86(String msg) { System.out.println("msg=" + msg + 86); }
public static void a87(String msg) { System.out.println("msg=" + msg + 87); }
public static void a88(String msg) { System.out.println("msg=" + msg + 88); }
public static void a89(String msg) { System.out.println("msg=" + msg + 89); }
public static void a90(String msg) { System.out.println("msg=" + msg + 90); }
public static void a91(String msg) { System.out.println("msg=" + msg + 91); }
public static void a92(String msg) { System.out.println("msg=" + msg + 92); }
public static void a93(String msg) { System.out.println("msg=" + msg + 93); }
public static void a94(String msg) { System.out.println("msg=" + msg + 94); }
public static void a95(String msg) { System.out.println("msg=" + msg + 95); }
public static void a96(String msg) { System.out.println("msg=" + msg + 96); }
public static void a97(String msg) { System.out.println("msg=" + msg + 97); }
public static void a98(String msg) { System.out.println("msg=" + msg + 98); }
public static void a99(String msg) { System.out.println("msg=" + msg + 99); }
}
| mit |
nphau/Android-VFindWeek | yostajsc-style/src/main/java/com/yostajsc/style/designs/animations/sliders/SlideOutUpAnimator.java | 1754 | package com.yostajsc.style.designs.animations.sliders;
/*
* The MIT License (MIT)
*
* Copyright (c) 2014 daimajia
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import android.view.View;
import android.view.ViewGroup;
import com.nineoldandroids.animation.ObjectAnimator;
import com.yostajsc.style.designs.animations.BaseViewAnimator;
public class SlideOutUpAnimator extends BaseViewAnimator {
@Override
public void prepare(View target) {
ViewGroup parent = (ViewGroup) target.getParent();
getAnimatorAgent().playTogether(
ObjectAnimator.ofFloat(target, "alpha", 1, 0),
ObjectAnimator.ofFloat(target, "translationY", 0, -target.getBottom())
);
}
}
| mit |
callstats-io/callstats.java | callstats-java-sdk/src/test/java/io/callstats/sdk/CallStatsAuthenticatorTest.java | 1690 | package io.callstats.sdk;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import io.callstats.sdk.httpclient.CallStatsHttp2Client;
import io.callstats.sdk.internal.CallStatsAuthenticator;
import io.callstats.sdk.internal.CallStatsConst;
import io.callstats.sdk.listeners.CallStatsInitListener;
public class CallStatsAuthenticatorTest {
/** The listener. */
CallStatsInitListener listener;
CallStatsHttp2Client httpClient;
CallStatsAuthenticator authenticator;
/** The app id. */
int appId = CallStatsTest.appId;
/** The app secret. */
String appSecret = CallStatsTest.appSecret;
String bridgeId = CallStatsTest.bridgeId;
@Before
public void setUp() {
listener = Mockito.mock(CallStatsInitListener.class);
httpClient = new CallStatsHttp2Client(CallStatsConst.CONNECTION_TIMEOUT);
authenticator = new CallStatsAuthenticator(appId, appSecret, bridgeId, httpClient, listener);
}
@Test
public void doAuthenticationTest() {
authenticator.doAuthentication();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
String msg = "SDK authentication successful";
Mockito.verify(listener).onInitialized(msg);
}
@Test
public void doAuthenticationTestInvalidAppId() {
authenticator =
new CallStatsAuthenticator(appId + 1, appSecret, bridgeId, httpClient, listener);
authenticator.doAuthentication();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
String errMsg = "SDK Authentication Error";
Mockito.verify(listener).onError(CallStatsErrors.HTTP_ERROR, errMsg);
}
}
| mit |
selvasingh/azure-sdk-for-java | sdk/appconfiguration/mgmt-v2019_11_01_preview/src/main/java/com/microsoft/azure/management/appconfiguration/v2019_11_01_preview/implementation/KeyValueImpl.java | 1616 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.appconfiguration.v2019_11_01_preview.implementation;
import com.microsoft.azure.management.appconfiguration.v2019_11_01_preview.KeyValue;
import com.microsoft.azure.arm.model.implementation.WrapperImpl;
import org.joda.time.DateTime;
import java.util.Map;
class KeyValueImpl extends WrapperImpl<KeyValueInner> implements KeyValue {
private final AppConfigurationManager manager;
KeyValueImpl(KeyValueInner inner, AppConfigurationManager manager) {
super(inner);
this.manager = manager;
}
@Override
public AppConfigurationManager manager() {
return this.manager;
}
@Override
public String contentType() {
return this.inner().contentType();
}
@Override
public String eTag() {
return this.inner().eTag();
}
@Override
public String keyVal() {
return this.inner().key();
}
@Override
public String label() {
return this.inner().label();
}
@Override
public DateTime lastModified() {
return this.inner().lastModified();
}
@Override
public Boolean locked() {
return this.inner().locked();
}
@Override
public Map<String, String> tags() {
return this.inner().tags();
}
@Override
public String value() {
return this.inner().value();
}
}
| mit |
micheljung/downlords-faf-client | src/main/java/com/faforever/client/leaderboard/RatingStat.java | 206 | package com.faforever.client.leaderboard;
import lombok.Data;
@Data
public class RatingStat {
private final int rating;
private final int totalCount;
private final int countWithEnoughGamesPlayed;
}
| mit |
jlinn/stripe-api-java | src/main/java/net/joelinn/stripe/response/transfers/ListTransfersResponse.java | 253 | package net.joelinn.stripe.response.transfers;
import net.joelinn.stripe.response.AbstractListResponse;
/**
* User: Joe Linn
* Date: 5/26/2014
* Time: 9:06 PM
*/
public class ListTransfersResponse extends AbstractListResponse<TransferResponse>{
}
| mit |
0359xiaodong/serenity-android | serenity-app/src/main/java/us/nineworlds/serenity/volley/VolleyUtils.java | 2183 | /**
* The MIT License (MIT)
* Copyright (c) 2012 David Carver
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
* OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
* OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package us.nineworlds.serenity.volley;
import us.nineworlds.plex.rest.model.impl.MediaContainer;
import us.nineworlds.serenity.core.OkHttpStack;
import android.content.Context;
import android.util.Log;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
/**
* @author dcarver
*
*/
public class VolleyUtils {
private static RequestQueue queue;
public static RequestQueue getRequestQueueInstance(Context context) {
if (queue == null) {
queue = Volley.newRequestQueue(context, new OkHttpStack());
}
return queue;
}
public static Request volleyXmlGetRequest(String url,
Response.Listener response, Response.ErrorListener error) {
SimpleXmlRequest<MediaContainer> request = new SimpleXmlRequest<MediaContainer>(
Request.Method.GET, url, MediaContainer.class, response, error);
if (queue == null) {
Log.e("VolleyUtils", "Initialize Request Queue!");
return null;
}
return queue.add(request);
}
}
| mit |
mozi22/ImageUploadAndroidExample | app/src/main/java/com/main/junaidstore/activities/MainActivity.java | 14871 | package com.main.junaidstore.activities;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Parcelable;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.Toast;
import com.main.junaidstore.R;
import com.main.junaidstore.adapters.CategoriesAdapter;
import com.main.junaidstore.adapters.MainGridAdapter;
import com.main.junaidstore.interfaces.AsyncCallback;
import com.main.junaidstore.libraries.GeneralFunctions;
import com.main.junaidstore.libraries.NetworkInterface;
import com.mikepenz.materialdrawer.AccountHeader;
import com.mikepenz.materialdrawer.AccountHeaderBuilder;
import com.mikepenz.materialdrawer.Drawer;
import com.mikepenz.materialdrawer.DrawerBuilder;
import com.mikepenz.materialdrawer.model.DividerDrawerItem;
import com.mikepenz.materialdrawer.model.PrimaryDrawerItem;
import com.mikepenz.materialdrawer.model.ProfileDrawerItem;
import com.mikepenz.materialdrawer.model.SecondaryDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem;
import org.parceler.Parcels;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
public class MainActivity extends FragmentActivity implements AsyncCallback {
@BindView(R.id.activity_main) RelativeLayout main_activity_view;
@BindView(R.id.main_image_grid) GridView image_grid;
@BindView(R.id.main_header_tags) LinearLayout main_header_tags;
@BindView(R.id.main_header_date) Spinner main_header_date;
@BindView(R.id.main_header_category) Spinner main_header_category;
private final String GET_POSTS_ALL_CATEGORIES = "All";
private final String GET_POSTS_FIRST_TIME = "firstTime";
public static final int CODE_POST_CATEGORIES = 291;
public static final int CODE_POST_DATES = 292;
public static final int CODE_POSTS = 293;
public NetworkInterface networkInterface;
public boolean initialDataLoadedCat = false;
public boolean initialDataLoadedDates = false;
public List<com.main.junaidstore.models.Categories> categoriesList;
public List<com.main.junaidstore.models.Posts> datesList;
public List<com.main.junaidstore.models.Posts> postsList;
ProgressDialog progress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
networkInterface = new NetworkInterface(this);
progress = new ProgressDialog(this);
progress.setTitle("Loading");
progress.setMessage("loading more records...");
progress.show();
main_header_date.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if(initialDataLoadedCat && initialDataLoadedDates && datesList.size()!=0 && categoriesList.size()!=0){
loadBasedOnNewCategories();
}
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
main_header_category.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if(initialDataLoadedCat && initialDataLoadedDates && datesList.size()!=0 && categoriesList.size()!=0){
loadBasedOnNewCategories();
}
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
if(GeneralFunctions.getSessionValue(this,getResources().getString(R.string.usertype)).equals("2")) {
createDrawerForEmployee();
}
else{
createDrawer();
}
}
private void loadBasedOnNewCategories(){
progress.show();
String categoryid = GET_POSTS_ALL_CATEGORIES;
for(int i=0;i<this.categoriesList.size();i++){
if(this.categoriesList.get(i).getCategory().equals(main_header_category.getSelectedItem().toString())){
categoryid = this.categoriesList.get(i).getID();
}
}
MainActivity.this.networkInterface.getPosts(GeneralFunctions.getSessionValue(MainActivity.this,getResources().getString(R.string.userid)),
GeneralFunctions.getSessionValue(MainActivity.this,getResources().getString(R.string.access_token)),
categoryid,
main_header_date.getSelectedItem().toString(),
CODE_POSTS);
}
@Override
protected void onResume(){
super.onResume();
initialDataLoadedCat = false;
initialDataLoadedDates = false;
this.networkInterface.getCategories(GeneralFunctions.getSessionValue(this,getResources().getString(R.string.userid)),
GeneralFunctions.getSessionValue(this,getResources().getString(R.string.access_token)),
CODE_POST_CATEGORIES);
this.networkInterface.getPostDates(GeneralFunctions.getSessionValue(this,getResources().getString(R.string.userid)),
GeneralFunctions.getSessionValue(this,getResources().getString(R.string.access_token)),
CODE_POST_DATES);
this.networkInterface.getPosts(GeneralFunctions.getSessionValue(this,getResources().getString(R.string.userid)),
GeneralFunctions.getSessionValue(this,getResources().getString(R.string.access_token)),
GET_POSTS_FIRST_TIME,
"",
CODE_POSTS);
}
private void createDrawerForEmployee(){
AccountHeader headerResult = new AccountHeaderBuilder()
.withActivity(this)
.withHeaderBackground(R.drawable.cover)
.addProfiles(
new ProfileDrawerItem().withName(getResources().getString(R.string.app_name)).withIcon(ContextCompat.getDrawable(getApplicationContext(),R.drawable.app_cover))
)
.build();
//Now create your drawer and pass the AccountHeader.Result
Drawer result = new DrawerBuilder()
.withAccountHeader(headerResult)
.withActivity(this)
.withTranslucentStatusBar(false)
.withActionBarDrawerToggle(true)
.withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
@Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
// do something with the clicked item :D
if(position == 3){
startActivity(new Intent(MainActivity.this,Categories.class));
}
else if(position == 1){
startActivity(new Intent(MainActivity.this,AddNewItem.class));
}
else if(position == -1 ){
new AlertDialog.Builder(MainActivity.this)
.setTitle("Logout")
.setMessage("Are you sure you want to logout ?")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
GeneralFunctions.addSessionValue(MainActivity.this,getResources().getString(R.string.access_token),"");
GeneralFunctions.addSessionValue(MainActivity.this,getResources().getString(R.string.usertype),"");
GeneralFunctions.addSessionValue(MainActivity.this,getResources().getString(R.string.userid),"");
Intent intent = new Intent(MainActivity.this,login.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}})
.setNegativeButton(android.R.string.no, null).show();
}
return false;
}
})
.build();
result.addStickyFooterItem(new PrimaryDrawerItem().withName("Logout"));
}
private void createDrawer(){
////if you want to update the items at a later time it is recommended to keep it in a variable
SecondaryDrawerItem item1 = new SecondaryDrawerItem ().withIdentifier(1).withName(R.string.add_item).withSelectable(true);
SecondaryDrawerItem item2 = new SecondaryDrawerItem().withIdentifier(2).withName(R.string.category).withSelectable(true);
AccountHeader headerResult = new AccountHeaderBuilder()
.withActivity(this)
.withHeaderBackground(R.drawable.cover)
.addProfiles(
new ProfileDrawerItem().withName(getResources().getString(R.string.app_name)).withIcon(ContextCompat.getDrawable(getApplicationContext(),R.drawable.app_cover))
)
.build();
//Now create your drawer and pass the AccountHeader.Result
Drawer result = new DrawerBuilder()
.withAccountHeader(headerResult)
.withActivity(this)
.withTranslucentStatusBar(false)
.withActionBarDrawerToggle(true)
.addDrawerItems(
item1,
new DividerDrawerItem(),
item2
)
.withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
@Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
// do something with the clicked item :D
if(position == 3){
startActivity(new Intent(MainActivity.this,Categories.class));
}
else if(position == 1){
startActivity(new Intent(MainActivity.this,AddNewItem.class));
}
else if(position == -1 ){
new AlertDialog.Builder(MainActivity.this)
.setTitle("Logout")
.setMessage("Are you sure you want to logout ?")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
GeneralFunctions.addSessionValue(MainActivity.this,getResources().getString(R.string.access_token),"");
GeneralFunctions.addSessionValue(MainActivity.this,getResources().getString(R.string.usertype),"");
GeneralFunctions.addSessionValue(MainActivity.this,getResources().getString(R.string.userid),"");
Intent intent = new Intent(MainActivity.this,login.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}})
.setNegativeButton(android.R.string.no, null).show();
}
return false;
}
})
.build();
result.addStickyFooterItem(new PrimaryDrawerItem().withName("Logout"));
}
@Override
public void AsyncCallback(int resultCode, Parcelable rf) {
com.main.junaidstore.models.Response response = Parcels.unwrap(rf);
if(CODE_POST_CATEGORIES == resultCode){
categoriesList = response.getCategories();
populateCategoriesDropdown(categoriesList);
initialDataLoadedCat = true;
}
else if(CODE_POST_DATES == resultCode){
datesList = response.getPosts();
populateDatesDropdown(datesList);
initialDataLoadedDates = true;
}
else if(CODE_POSTS == resultCode){
this.postsList = response.getPosts();
if(this.postsList.size() == 0){
Toast.makeText(getApplicationContext(),"No Records in this category",Toast.LENGTH_SHORT).show();
progress.dismiss();
return;
}
image_grid.setAdapter(new MainGridAdapter(getApplicationContext(),this.postsList,this));
}
progress.dismiss();
}
private void populateCategoriesDropdown(List<com.main.junaidstore.models.Categories> categories){
List<String> str = new ArrayList<>();
str.add("All");
for(com.main.junaidstore.models.Categories cat: categoriesList){
str.add(cat.getCategory());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, str);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
main_header_category.setAdapter(adapter);
}
private void populateDatesDropdown(List<com.main.junaidstore.models.Posts> posts){
List<String> str = new ArrayList<>();
for(int i=posts.size() -1 ;i>=0;i--){
str.add(posts.get(i).getCreatedAt());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, str);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
main_header_date.setAdapter(adapter);
}
}
| mit |
bentodev/bentolang | src/bento/runtime/Holder.java | 2076 | /* Bento
*
* $Id: Holder.java,v 1.14 2014/01/14 14:42:45 sthippo Exp $
*
* Copyright (c) 2002-2014 by bentodev.org
*
* Use of this code in source or compiled form is subject to the
* Bento Poetic License at http://www.bentodev.org/poetic-license.html
*/
package bento.runtime;
import bento.lang.Definition;
import bento.lang.ArgumentList;
import bento.lang.ResolvedInstance;
/**
* A simple container for associating a definition with an instantiated
* object. A Holder is useful for lazy instantiation (avoiding instantiation
* till the last possible moment) and for providing name, type, source code
* and other metadata about the object that can be obtained from the
* definition
*
*
* @author mash
*
*/
public class Holder {
public Definition nominalDef;
public ArgumentList nominalArgs;
public Definition def;
public ArgumentList args;
public Object data;
public ResolvedInstance resolvedInstance;
public Holder() {
this(null, null, null, null, null, null, null);
}
public Holder(Definition nominalDef, ArgumentList nominalArgs, Definition def, ArgumentList args, Context context, Object data, ResolvedInstance resolvedInstance) {
this.nominalDef = nominalDef;
this.nominalArgs = nominalArgs;
this.def = def;
this.args = args;
this.data = data;
this.resolvedInstance = resolvedInstance;
}
public String toString() {
return "{ nominalDef: "
+ (nominalDef == null ? "(null)" : nominalDef.getName())
+ "\n nominalArgs: "
+ (nominalArgs == null ? "(null)" : nominalArgs.toString())
+ "\n def: "
+ (def == null ? "(null)" : def.getName())
+ "\n args: "
+ (args == null ? "(null)" : args.toString())
+ "\n data: "
+ (data == null ? "(null)" : data.toString())
+ "\n resolvedInstance: "
+ (resolvedInstance == null ? "(null)" : resolvedInstance.getName())
+ "\n}";
}
} | mit |
BlackJar72/ClimaticBiomePlacement | main/java/jaredbgreat/climaticbiome/blocks/BlockBushBase.java | 434 | package jaredbgreat.climaticbiome.blocks;
import jaredbgreat.climaticbiome.ClimaticBiomes;
import jaredbgreat.climaticbiome.util.IHaveModel;
import net.minecraft.block.BlockBush;
import net.minecraft.item.Item;
abstract public class BlockBushBase extends BlockBush implements IHaveModel {
@Override
public void registerModel() {
ClimaticBiomes.proxy.registerItemRender(Item
.getItemFromBlock(this), 0, "inventory");
}
}
| mit |
blyk/BlackCode-Fuse | AndroidUI/.build/Simulator/Android/src/com/Android_UI/XliCppThreadHandler.java | 1601 | package com.Android_UI;
import java.util.ArrayList;
import android.os.Handler;
import android.os.Message;
public class XliCppThreadHandler extends Handler {
public static final int REPEATING_MESSAGE = 10;
private int repeatCount = 0;
private ArrayList<Integer> repeatingMessageIndex;
private int xliCallbackIndex = -2;
public XliCppThreadHandler()
{
super();
repeatingMessageIndex = new ArrayList<Integer>();
xliCallbackIndex = registerRepeating(50);
}
@Override
public void handleMessage(Message msg)
{
switch (msg.what) {
case REPEATING_MESSAGE:
handleRepeating(msg);
break;
default:
break;
}
}
private void handleRepeating(Message msg)
{
if (msg.arg1 == xliCallbackIndex) {
com.Android_UI.ActivityNativeEntryPoints.cppTimerCallback(msg.arg1); // {TODO} this should own callback
Message newMsg = Message.obtain();
newMsg.what = msg.what;
newMsg.arg1 = msg.arg1;
newMsg.arg2 = msg.arg2;
this.sendMessageDelayed(newMsg, msg.arg2);
} else if (repeatingMessageIndex.contains((Integer)msg.arg1)) {
com.Android_UI.ActivityNativeEntryPoints.cppTimerCallback(msg.arg1);
this.sendMessageDelayed(msg, msg.arg2);
}
}
public void unregisterRepeating(int repeater_id)
{
repeatingMessageIndex.remove((Integer)repeater_id);
}
public int registerRepeating(int millisecondsDelay)
{
int i = repeatCount+=1;
repeatingMessageIndex.add(i);
Message msg = Message.obtain();
msg.what = REPEATING_MESSAGE;
msg.arg1 = i;
msg.arg2 = millisecondsDelay;
this.sendMessageDelayed(msg, millisecondsDelay);
return i;
}
}
| mit |
kazuhira-r/lucene-examples | lucene-classic-query-parser/src/main/java/QueryParserEscape.java | 233 | import org.apache.lucene.queryparser.classic.QueryParser;
public class QueryParserEscape {
public static void main(String[] args) {
String input = "(1+1):2";
System.out.println(QueryParser.escape(input));
}
} | mit |
30days-tech/android | 公共组件/pushservice/src/main/java/com/thirtydays/pushservice/receiver/XMMessageReceiver.java | 5685 | package com.thirtydays.pushservice.receiver;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.thirtydays.pushservice.PushManager;
import com.thirtydays.pushservice.constant.PushConstant;
import com.thirtydays.pushservice.entity.PushMessage;
import com.xiaomi.mipush.sdk.ErrorCode;
import com.xiaomi.mipush.sdk.MiPushClient;
import com.xiaomi.mipush.sdk.MiPushCommandMessage;
import com.xiaomi.mipush.sdk.MiPushMessage;
import com.xiaomi.mipush.sdk.PushMessageReceiver;
import com.xiaomi.push.service.XMJobService;
import java.util.List;
/**
* Created by yanchengmeng on 2016/12/14.
* 小米推送消息接收器
*/
public class XMMessageReceiver extends PushMessageReceiver {
private final static String TAG = XMMessageReceiver.class.getSimpleName();
@Override
public void onNotificationMessageClicked(Context context, MiPushMessage miPushMessage) {
Log.e(TAG, "onNotificationMessageClicked");
PushMessage pushMessage = new PushMessage();
pushMessage.setExtras(miPushMessage.getExtra());
pushMessage.setTitle(miPushMessage.getTitle());
// 传输数据从content取
pushMessage.setDesc(miPushMessage.getDescription());
pushMessage.setMsgId(miPushMessage.getMessageId());
if (PushManager.getInstance().getMessageHandler() != null) {
PushManager.getInstance().getMessageHandler().setOriginalMessage(miPushMessage.toBundle().toString());
PushManager.getInstance().getMessageHandler().onNotificationClicked(context, pushMessage);
}
}
/**
* 推送消息收到后立即触发
* @param context
* @param miPushMessage
*/
@Override
public void onNotificationMessageArrived(Context context, MiPushMessage miPushMessage) {
Log.e(TAG, "onNotificationMessageArrived.");
super.onNotificationMessageArrived(context, miPushMessage);
// PushMessage pushMessage = new PushMessage();
// pushMessage.setExtras(miPushMessage.getExtra());
// pushMessage.setTitle(miPushMessage.getTitle());
// // 传输数据从content取
// pushMessage.setDesc(miPushMessage.getDescription());
// pushMessage.setMsgId(miPushMessage.getMessageId());
// pushMessage.setNotifyId(miPushMessage.getNotifyId());
//
// if (PushManager.getInstance().getMessageHandler() != null) {
// PushManager.getInstance().getMessageHandler().setOriginalMessage(miPushMessage.toBundle().toString());
// PushManager.getInstance().getMessageHandler().onNotificationClicked(context, pushMessage);
// }
}
@Override
public void onReceiveRegisterResult(Context context, MiPushCommandMessage miPushCommandMessage) {
String command = miPushCommandMessage.getCommand();
Log.e(TAG, "onReceiveRegisterResult:" + command);
List<String> arguments = miPushCommandMessage.getCommandArguments();
String cmdArg1 = ((arguments != null && arguments.size() > 0) ? arguments.get(0) : null);
String cmdArg2 = ((arguments != null && arguments.size() > 1) ? arguments.get(1) : null);
if (MiPushClient.COMMAND_REGISTER.equals(command)) {
if (miPushCommandMessage.getResultCode() == ErrorCode.SUCCESS) {
Log.i(TAG, "Regist XIAOMI push token success. token:" + cmdArg1);
// 通知推送token
Intent intent = new Intent (PushConstant.PUSH_TOKEN_CHANGED);
intent.putExtra(PushConstant.PUSH_TOKEN, cmdArg1);
context.sendBroadcast(intent);
} else {
// 注册失败就用友盟推送:小米推送会因为系统时间错误导致注册失败
Intent intent = new Intent(PushConstant.PUSH_SERVICE_INIT_FAIL_ACTION);
context.sendBroadcast(intent);
// TODO 上报bugly
// CrashReport.postCatchedException(new Exception(miPushCommandMessage.getReason()));
}
}
}
/**
* 处理透传消息
*
* @param context
* @param miPushMessage
*/
@Override
public void onReceivePassThroughMessage(Context context, MiPushMessage miPushMessage) {
Log.e(TAG, "onReceivePassThroughMessage-----");
Log.e(TAG, "miPushMessage:" + miPushMessage.toString());
// 取自定义消息内容
PushMessage pushMessage = new PushMessage();
pushMessage.setMsgId(miPushMessage.getMessageId());
pushMessage.setDesc(miPushMessage.getDescription());
pushMessage.setCustom(miPushMessage.getContent());
pushMessage.setExtras(miPushMessage.getExtra());
// 处理消息
if (null != pushMessage && PushManager.getInstance().getMessageHandler() != null) {
PushManager.getInstance().getMessageHandler().setOriginalMessage(miPushMessage.toBundle().toString());
PushManager.getInstance().getMessageHandler().onReceiveMessage(context, pushMessage);
}
pushMessage.setExtras(miPushMessage.getExtra());
}
@Override
public void onCommandResult(Context context, MiPushCommandMessage miPushCommandMessage) {
String command = miPushCommandMessage.getCommand();
Log.e(TAG, "onCommandResult:" + command + ", resultCode:" + miPushCommandMessage.getResultCode()
+ ", reason:" + miPushCommandMessage.getReason());
}
@Override
public void onReceiveMessage(Context context, MiPushMessage miPushMessage) {
Log.e(TAG, "onReceiveMessage");
super.onReceiveMessage(context, miPushMessage);
}
}
| mit |
tornaia/hr2 | hr2-java-parent/hr2-backend-api/src/test/java/test/matcher/SzabadsagFelhasznalasResponseDTOMatcher.java | 2803 | package test.matcher;
import static hu.interconnect.util.DateUtils.parseNap;
import java.util.Date;
import org.hamcrest.CoreMatchers;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.core.IsAnything;
import hu.interconnect.hr.backend.api.dto.SzabadsagFelhasznalasResponseDTO;
import hu.interconnect.hr.backend.api.enumeration.FelhasznaltSzabadnapJelleg;
import test.matcher.AbstractTypeSafeDiagnosingMatcher;
public class SzabadsagFelhasznalasResponseDTOMatcher extends AbstractTypeSafeDiagnosingMatcher<SzabadsagFelhasznalasResponseDTO> {
private Matcher<Integer> tsz = new IsAnything<>();
private Matcher<Date> kezdet = new IsAnything<>();
private Matcher<Date> veg = new IsAnything<>();
private Matcher<FelhasznaltSzabadnapJelleg> jelleg = new IsAnything<>();
private Matcher<Integer> munkanapokSzama = new IsAnything<>();
public SzabadsagFelhasznalasResponseDTOMatcher tsz(Integer tsz) {
this.tsz = CoreMatchers.is(tsz);
return this;
}
public SzabadsagFelhasznalasResponseDTOMatcher kezdet(Matcher<Date> kezdet) {
this.kezdet = kezdet;
return this;
}
public SzabadsagFelhasznalasResponseDTOMatcher kezdet(String kezdetStr) {
this.kezdet = CoreMatchers.is(parseNap(kezdetStr));
return this;
}
public SzabadsagFelhasznalasResponseDTOMatcher veg(Matcher<Date> veg) {
this.veg = veg;
return this;
}
public SzabadsagFelhasznalasResponseDTOMatcher veg(String vegStr) {
this.veg = CoreMatchers.is(parseNap(vegStr));
return this;
}
public SzabadsagFelhasznalasResponseDTOMatcher jelleg(FelhasznaltSzabadnapJelleg jelleg) {
this.jelleg = CoreMatchers.is(jelleg);
return this;
}
public SzabadsagFelhasznalasResponseDTOMatcher munkanapokSzama(Integer munkanapokSzama) {
this.munkanapokSzama = CoreMatchers.is(munkanapokSzama);
return this;
}
@Override
protected boolean matchesSafely(SzabadsagFelhasznalasResponseDTO item, Description mismatchDescription) {
return matches(tsz, item.tsz, "tsz value: ", mismatchDescription) &&
matches(kezdet, item.kezdet, "kezdet value: ", mismatchDescription) &&
matches(veg, item.veg, "veg value: ", mismatchDescription) &&
matches(jelleg, item.jelleg, "jelleg value: ", mismatchDescription) &&
matches(munkanapokSzama, item.munkanapokSzama, "munkanapokSzama value: ", mismatchDescription);
}
@Override
public void describeTo(Description description) {
description.appendText(SzabadsagFelhasznalasResponseDTO.class.getSimpleName())
.appendText(", tsz: ").appendDescriptionOf(tsz)
.appendText(", kezdet: ").appendDescriptionOf(kezdet)
.appendText(", veg: ").appendDescriptionOf(veg)
.appendText(", jelleg: ").appendDescriptionOf(jelleg)
.appendText(", munkanapokSzama: ").appendDescriptionOf(munkanapokSzama);
}
} | mit |
rsegismont/Androlife | mobile/src/main/java/com/rsegismont/androlife/details/ProgrammesDetailActivity.java | 7606 | package com.rsegismont.androlife.details;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.view.PagerTabStrip;
import android.support.v4.view.ViewPager;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.MenuItem;
import com.rsegismont.androlife.R;
import com.rsegismont.androlife.activities.ProgrammeAbstract;
import com.rsegismont.androlife.common.Constantes;
import com.rsegismont.androlife.common.SharedInformation;
import com.rsegismont.androlife.common.SharedInformation.DatabaseColumn;
import com.rsegismont.androlife.common.api.AndrolifeApi9;
import com.rsegismont.androlife.common.utils.Utils;
import com.rsegismont.androlife.core.utils.AndrolifeUtils;
import com.rsegismont.androlife.home.HomeActivity;
import java.util.Calendar;
public class ProgrammesDetailActivity extends ProgrammeAbstract implements LoaderManager.LoaderCallbacks<Cursor> {
@Override
public int getActivityOrientation() {
if(Utils.hasGingerbread()){
return AndrolifeApi9.getSensorPortraitAttribute();
}
return ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
}
public static final String commonDate = SharedInformation.DatabaseColumn.DATE_UTC.stringValue + " BETWEEN ? AND ?";
private ViewPager myPager;
public PagerTabStrip tabTitle;
public boolean firstInit = true;
private int getCurrentIndex() {
if (this.mCursor == null) {
return -1;
}
if (this.mCursor.getCount() <= 0) {
return -1;
}
for (int position = Math.max(0, mCursor.getPosition()); position < mCursor.getCount(); position++) {
if (mCursor.moveToPosition(position)) {
long dateUtc = this.mCursor.getLong(this.mCursor
.getColumnIndex(SharedInformation.DatabaseColumn.DATE_UTC.stringValue));
if (System.currentTimeMillis() - dateUtc >= 0) {
return position;
}
} else {
break;
}
}
return -1;
}
private int getTonightIndex() {
if (this.mCursor == null) {
return -1;
}
if (this.mCursor.getCount() <= 0) {
return -1;
}
final long currentDateUtc = this.mCursor.getLong(this.mCursor
.getColumnIndex(SharedInformation.DatabaseColumn.DATE_UTC.stringValue));
final Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(currentDateUtc);
calendar.set(Calendar.HOUR_OF_DAY, 19);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
for (int position = Math.max(0, mCursor.getPosition()); position < mCursor.getCount(); position++) {
if (mCursor.moveToPosition(position)) {
long candidateDateUtc = this.mCursor.getLong(this.mCursor
.getColumnIndex(SharedInformation.DatabaseColumn.DATE_UTC.stringValue));
if (calendar.getTime().getTime() - candidateDateUtc >= 0L) {
return position;
}
} else {
break;
}
}
return -1;
}
public void onCreate(Bundle paramBundle) {
super.onCreate(paramBundle);
final int type = getIntent().getIntExtra(Constantes.TYPE, Constantes.CURSOR_FULL);
getSupportLoaderManager().initLoader(type, null, this);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_HOME_AS_UP, ActionBar.DISPLAY_HOME_AS_UP);
setContentView(R.layout.host_activity);
setTitle(getResources().getString(R.string.app_name));
switch (type) {
case Constantes.CURSOR_FULL:
getSupportActionBar().setSubtitle(getResources().getString(R.string.subtitle_all));
break;
case Constantes.CURSOR_QUERY:
getSupportActionBar().setSubtitle(getResources().getString(R.string.subtitle_query));
break;
case Constantes.CURSOR_NEWS:
getSupportActionBar().setSubtitle(getResources().getString(R.string.subtitle_news));
break;
case Constantes.CURSOR_SELECTION:
getSupportActionBar().setSubtitle(getResources().getString(R.string.subtitle_selection));
break;
default:
break;
}
myPager = (ViewPager) findViewById(R.id.host_tab_viewpager);
tabTitle = (PagerTabStrip) findViewById(R.id.host_tab_title);
if (tabTitle != null) {
this.tabTitle.setTabIndicatorColor(getResources().getColor(R.color.androlife_programs_hint_underline));
this.tabTitle.setTextColor(getResources().getColor(R.color.androlife_programs_hint_text));
}
}
public Loader<Cursor> onCreateLoader(int paramInt, Bundle paramBundle) {
Calendar morningCalendar = Calendar.getInstance();
morningCalendar.setTimeInMillis(getIntent().getLongExtra("DETAIL_DATE_INDEX", 0L));
morningCalendar.add(Calendar.HOUR_OF_DAY, -24);
Calendar eveningCalendar = Calendar.getInstance();
eveningCalendar.setTimeInMillis(getIntent().getLongExtra("DETAIL_DATE_INDEX", 0L));
eveningCalendar.add(Calendar.HOUR_OF_DAY, 24);
switch (paramInt) {
default:
return AndrolifeUtils.getAndrolifeLoader(getApplicationContext(), paramInt, null, new Calendar[] {
morningCalendar, eveningCalendar });
case Constantes.CURSOR_QUERY:
return new CursorLoader(this, SharedInformation.CONTENT_URI_PROGRAMMES, null,
SharedInformation.DatabaseColumn.DESCRIPTION.stringValue + " LIKE ?", new String[] { "%"
+ getIntent().getExtras().getString("DETAIL_QUERY") + "%" },
SharedInformation.DatabaseColumn.DATE_UTC.stringValue + " ASC");
case Constantes.CURSOR_QUERY_VIEW:
String str = SharedInformation.DatabaseColumn.DATE_UTC.stringValue + " BETWEEN ? AND ?";
String[] arrayOfString = new String[2];
arrayOfString[0] = "" + morningCalendar.getTime().getTime();
arrayOfString[1] = "" + eveningCalendar.getTime().getTime();
return new CursorLoader(this, SharedInformation.CONTENT_URI_PROGRAMMES, null, str, arrayOfString,
SharedInformation.DatabaseColumn.DATE_UTC.stringValue + " ASC");
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
}
public void onLoadFinished(Loader<Cursor> paramLoader, Cursor cursor) {
this.mCursor = cursor;
adapterDetails = new DetailsAdapter(this);
myPager.setOnPageChangeListener(adapterDetails);
myPager.setAdapter(adapterDetails);
final String intentDate = getIntent().getDataString();
if (intentDate == null) {
final long initialTime = getIntent().getLongExtra(Constantes.DETAIL_DATE_TIME, 0);
setPagerSelection(initialTime);
} else {
setPagerSelection(Long.valueOf(intentDate));
}
}
public void onLoaderReset(Loader<Cursor> paramLoader) {
}
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.menu_list_programmes_now:
setPagerSelection(getCurrentIndex());
return true;
case R.id.menu_list_programmes_tonight:
setPagerSelection(getTonightIndex());
return true;
case android.R.id.home:
// ProjectsActivity is my 'home' activity
startActivityAfterCleanup(HomeActivity.class);
return true;
}
return (super.onOptionsItemSelected(menuItem));
}
public void setPagerSelection(long initialTime) {
final int initialPosition = mCursor.getPosition();
for (int i = 0; i < mCursor.getCount(); i++) {
mCursor.moveToPosition(i);
final long value = mCursor.getLong(mCursor.getColumnIndex(DatabaseColumn.DATE_UTC.stringValue));
final int index = i;
if (initialTime == value) {
if (myPager.getCurrentItem() == index) {
if (firstInit == true) {
firstInit = false;
adapterDetails.onPageSelected(index);
}
} else {
myPager.setCurrentItem(index, false);
}
break;
}
}
if (initialPosition >= 0) {
mCursor.moveToPosition(initialPosition);
}
}
} | mit |
mahdiarn/OOPJava | test/Cages/CagesTest.java | 6210 | /*
* 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 Cages;
import cages.Cages;
import cage.Cage;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Rizky Faramita <13515055 @ std.stei.itb.ac.id>
* @version 1.1 (current version number of program)
* @since 1.1 (the version of the package this class was first added to)
*/
public class CagesTest {
public CagesTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of GetArrayCage method of class Cages.
*/
@Test
public void testGetArrayCage() {
System.out.println("getArrayCage");
//test case pada ctor tanpa parameter
Cages instanceNoParam = new Cages();
Cage[] expArrayNoParam = new Cage[0];
Cage[] resultArrayNoParam = instanceNoParam.getArrayCage();
assertArrayEquals(expArrayNoParam, resultArrayNoParam);
//test case pada ctor dengan parameter
Cages instanceParam = new Cages(1);
Cage[] expArrayParam = new Cage[1];
Cage[] resultArrayParam = instanceParam.getArrayCage();
assertArrayEquals(expArrayParam, resultArrayParam);
//test case pada cctor
Cages instanceCctor = new Cages(2);
Cages itemCctor = new Cages(instanceCctor);
Cage[] expArrayCctor = instanceCctor.getArrayCage();
Cage[] resultArrayCctor = itemCctor.getArrayCage();
assertArrayEquals(expArrayCctor, resultArrayCctor);
}
/**
* Test of getCage method of class Cages.
*/
@Test
public void testGetCage() {
System.out.println("getCage");
//test case dengan Cage tanpa parameter
Cage itemNoParam = new Cage();
Cages instanceNoParam = new Cages(2);
instanceNoParam.setArrayCage(itemNoParam, 1);
int expCageIdNoParam = itemNoParam.getCageId();
int resultCageIdNoParam = instanceNoParam.getCage(1).getCageId();
assertEquals(expCageIdNoParam, resultCageIdNoParam);
}
/**
* Test of setArrayCages method of class Cages.
*/
@Test
public void testSetArrayCages() {
System.out.println("setArrayCages");
//test case pada i=1 dan ctor Cage tanpa parameter
Cages instanceNoParam = new Cages(2);
Cage itemNoParam = new Cage();
instanceNoParam.setArrayCage(itemNoParam, 1);
Cage expCageNoParam = itemNoParam;
Cage resultCageNoParam = instanceNoParam.getCage(1);
assertEquals(expCageNoParam, resultCageNoParam);
//test case pada i=1 dan ctor dengan param x=1, y=1, id=1,
//animal_id=1
Cages instanceParam = new Cages(2);
Cage itemParam = new Cage(1,1,1,1);
instanceParam.setArrayCage(itemParam, 1);
//test case untuk animal_id 1
int expAnimalId = 1;
//test case mengambil elemen pertama
int resultAnimalId = instanceParam.getCage(1).getAnimalId();
assertEquals(expAnimalId, resultAnimalId);
//test case pada cctor
Cages sample = new Cages(3);
Cages instanceCctor = new Cages(sample);
Cage itemCctor = new Cage (2,2,2,2);
instanceCctor.setArrayCage(itemCctor,2);
//test case untuk cage_id 2
int expCageId = 2;
//test case diambil elemen ketiga
int resultCageId = instanceCctor.getCage(2).getCageId();
assertEquals(expCageId, resultCageId);
}
/**
* Test of GetNeff method of class Cages.
*/
@Test
public void testGetNeff() {
System.out.println("getNeff");
//test case pada ctor tanpa parameter
Cages instanceNoParam = new Cages();
int expNeffNoParam = 0;
int resultNeffNoParam = instanceNoParam.getNeff();
assertEquals(expNeffNoParam, resultNeffNoParam);
//test case pada ctor dengan parameter
Cages instanceParam = new Cages(1);
int expNeffParam = 1;
int resultNeffParam = instanceParam.getNeff();
assertEquals(expNeffParam, resultNeffParam);
//test case pada cctor
Cages instanceCctor = new Cages(2);
Cages itemCctor = new Cages(instanceCctor);
int expNeffCctor = instanceCctor.getNeff();
int resultNeffCctor = itemCctor.getNeff();
assertEquals(expNeffCctor, resultNeffCctor);
}
/**
* Test of SetIdx method of class Cages.
*/
@Test
public void testSetIdx() {
System.out.println("setIdx");
//test case pada neff=1 dan ctor Cage tanpa parameter
Cages instanceNoParam = new Cages(1);
Cage itemNoParam = new Cage();
instanceNoParam.setIdx(itemNoParam);
Cage expCageNoParam = itemNoParam;
Cage resultCageNoParam = instanceNoParam.getCage(0);
assertEquals(expCageNoParam, resultCageNoParam);
//test case pada neff=2 dan ctor dengan param x=1, y=1, id=1,
//animal_id=1
Cages instanceParam = new Cages(2);
Cage itemParam = new Cage(1,1,1,1);
instanceParam.setIdx(itemParam);
//test case untuk animal_id 1
int expAnimalId = 1;
//test case diambil elemen kedua
int resultAnimalId = instanceParam.getCage(1).getAnimalId();
assertEquals(expAnimalId, resultAnimalId);
//test case pada cctor
Cages sample = new Cages(3);
Cages instanceCctor = new Cages(sample);
Cage itemCctor = new Cage (2,2,2,2);
instanceCctor.setIdx(itemCctor);
//test case untuk cage_id 2
int expCageId = 2;
//test case diambil elemen ketiga
int resultCageId = instanceCctor.getCage(2).getCageId();
assertEquals(expCageId, resultCageId);
}
}
| mit |
microsoftgraph/msgraph-sdk-java | src/main/java/com/microsoft/graph/requests/WorkbookFunctionsOddFPriceRequest.java | 3002 | // Template Source: BaseMethodRequest.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.requests;
import com.microsoft.graph.models.WorkbookFunctionResult;
import com.microsoft.graph.models.WorkbookFunctions;
import com.microsoft.graph.requests.WorkbookFunctionsOddFPriceRequest;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;
import com.microsoft.graph.http.BaseRequest;
import com.microsoft.graph.http.HttpMethod;
import com.microsoft.graph.core.ClientException;
import com.microsoft.graph.core.IBaseClient;
import com.microsoft.graph.models.WorkbookFunctionsOddFPriceParameterSet;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The class for the Workbook Functions Odd FPrice Request.
*/
public class WorkbookFunctionsOddFPriceRequest extends BaseRequest<WorkbookFunctionResult> {
/**
* The request for this WorkbookFunctionsOddFPrice
*
* @param requestUrl the request URL
* @param client the service client
* @param requestOptions the options for this request
*/
public WorkbookFunctionsOddFPriceRequest(@Nonnull final String requestUrl, @Nonnull final IBaseClient<?> client, @Nullable final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) {
super(requestUrl, client, requestOptions, WorkbookFunctionResult.class);
}
/** The body for the method */
@Nullable
public WorkbookFunctionsOddFPriceParameterSet body;
/**
* Invokes the method and returns a future with the result
* @return a future with the result
*/
@Nonnull
public java.util.concurrent.CompletableFuture<WorkbookFunctionResult> postAsync() {
return sendAsync(HttpMethod.POST, body);
}
/**
* Invokes the method and returns the result
* @return result of the method invocation
* @throws ClientException an exception occurs if there was an error while the request was sent
*/
@Nullable
public WorkbookFunctionResult post() throws ClientException {
return send(HttpMethod.POST, body);
}
/**
* Sets the select clause for the request
*
* @param value the select clause
* @return the updated request
*/
@Nonnull
public WorkbookFunctionsOddFPriceRequest select(@Nonnull final String value) {
addSelectOption(value);
return this;
}
/**
* Sets the expand clause for the request
*
* @param value the expand clause
* @return the updated request
*/
@Nonnull
public WorkbookFunctionsOddFPriceRequest expand(@Nonnull final String value) {
addExpandOption(value);
return this;
}
}
| mit |
jangesz/java-action | tic-vertx/src/main/java/org/tic/vertx/MainVerticle.java | 734 | package org.tic.vertx;
import io.vertx.rxjava.core.AbstractVerticle;
import io.vertx.rxjava.core.http.HttpServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MainVerticle extends AbstractVerticle {
private static final Logger logger = LoggerFactory.getLogger(MainVerticle.class);
@Override
public void start() throws Exception {
HttpServer server = vertx.createHttpServer();
server.requestStream().toObservable()
.subscribe(req -> {
logger.debug("first server verticle!");
req.response().end("Hello from " + Thread.currentThread().getName());
});
server.rxListen(3456).subscribe();
}
}
| mit |
Orion-F/Utilitools | src/log/LogType.java | 175 | package log;
public enum LogType {
ERROR(true),
UTILITOOLS(false),
INFO(true),
CUSTOM(true);
private LogType(boolean defaultShow) {
}
}
| mit |
BrainDoctor/clusterbrake | src/main/java/net/chrigel/clusterbrake/transcode/ffmpeg/FfmpegCLI.java | 4174 | package net.chrigel.clusterbrake.transcode.ffmpeg;
import com.google.inject.Inject;
import com.google.inject.Provider;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import net.chrigel.clusterbrake.process.ExternalProcess;
import net.chrigel.clusterbrake.transcode.Transcoder;
import net.chrigel.clusterbrake.transcode.TranscoderSettings;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
*
*/
public class FfmpegCLI
implements Transcoder {
private File source;
private File output;
private List<String> arguments;
private final Logger logger;
private TranscoderSettings settings;
private final Provider<ExternalProcess> processProvider;
private ExternalProcess process;
@Inject
FfmpegCLI(
TranscoderSettings settings,
Provider<ExternalProcess> processProvider
) throws FileNotFoundException {
if (!new File(settings.getCLIPath()).exists()) {
throw new FileNotFoundException(settings.getCLIPath());
}
this.settings = settings;
this.logger = LogManager.getLogger(getClass());
this.processProvider = processProvider;
}
@Override
public Transcoder from(File source) throws FileNotFoundException {
if (source.exists()) {
this.source = source;
return this;
} else {
throw new FileNotFoundException(String.format("Source does not exist: %1$s", source.getAbsolutePath()));
}
}
@Override
public Transcoder to(File output) {
validateOutput(output);
this.output = output;
return this;
}
@Override
public Transcoder withOptions(List<String> options) throws IllegalArgumentException {
validateArguments(options);
this.arguments = options;
return this;
}
@Override
public int transcode() throws InterruptedException, IOException {
Objects.requireNonNull(source, "Input is not specified");
Objects.requireNonNull(output, "Output is not specified");
Objects.requireNonNull(arguments, "Arguments not specified");
this.process = processProvider.get();
return process
.withIORedirected(settings.isIORedirected())
.withPath(settings.getCLIPath())
.withArguments(addOptionsToArguments(arguments))
.start();
}
@Override
public void abort() {
if (process != null) {
try {
process.destroy(1, TimeUnit.MINUTES);
} catch (InterruptedException ex) {
logger.warn(ex);
}
}
}
private void validateArguments(List<String> arguments) {
logger.debug("Validating arguments...");
arguments.forEach(arg -> {
if (arg.startsWith("--help") || arg.equals("-h ") || arg.equals("-?") || arg.equals("-help")) {
throw new IllegalArgumentException("Help option is specified in arguments");
}
if (arg.startsWith("-version")) {
throw new IllegalArgumentException("Update option is specified in arguments");
}
});
}
private void validateOutput(File file) {
if (file.getParentFile() != null && !file.getParentFile().exists()) {
throw new IllegalArgumentException("Parent folder of output does not exist.");
}
}
private List<String> addOptionsToArguments(List<String> options) {
List<String> list = new LinkedList<>();
options.forEach(arg -> {
if (arg.contains(" ")) {
if (arg.contains("${INPUT}")) {
arg = arg.replace("${INPUT}", source.getAbsolutePath());
}
list.addAll(Arrays.asList(arg.split(" ", 2)));
} else {
list.add(arg);
}
});
list.add(output.getAbsolutePath());
return list;
}
}
| mit |
uomsystemsbiology/LMMEL-miR-miner | MATLAB_functions/infodynamics/infodynamics-dist-0.1.3/java/source/infodynamics/measures/discrete/ContextOfPastMeasureCalculator.java | 4293 | package infodynamics.measures.discrete;
import infodynamics.utils.MathsUtils;
import infodynamics.utils.MatrixUtils;
/**
* @author Joseph Lizier
*
* Info theoretic measure calculator base class for
* measures which require the context of the past
* history of the destination variable.
*
* Usage:
* 1. Continuous accumulation of observations before computing :
* Call: a. initialise()
* b. addObservations() several times over
* c. computeLocalFromPreviousObservations() or computeAverageLocalOfObservations()
* 2. Standalone computation from a single set of observations:
* Call: computeLocal() or computeAverageLocal()
*
* @author Joseph Lizier
* joseph.lizier at gmail.com
* http://lizier.me/joseph/
*
*/
public abstract class ContextOfPastMeasureCalculator extends
InfoMeasureCalculator {
protected int k = 0; // history length k.
protected boolean noObservationStorage = false;
protected int[][] nextPastCount = null; // Count for (i[t+1], i[t]) tuples
protected int[] pastCount = null; // Count for i[t]
protected int[] nextCount = null; // count for i[t+1]
protected int[] maxShiftedValue = null; // states * (base^(k-1))
protected int base_power_k = 0;
/**
* @param base
*/
public ContextOfPastMeasureCalculator(int base, int history) {
this(base, history, false);
}
/**
* Constructor to be used by child classes only.
* In general, only needs to be explicitly called if child classes
* do not wish to create the observation arrays.
*
* @param base
* @param history
* @param dontCreateObsStorage
*/
protected ContextOfPastMeasureCalculator(int base, int history, boolean dontCreateObsStorage) {
super(base);
k = history;
base_power_k = MathsUtils.power(base, k);
// Relax the requirement that k >= 1, so that we can
// eliminate considering the history at will ...
//if (k < 1) {
// throw new RuntimeException("History k " + history + " is not >= 1 a ContextOfPastMeasureCalculator");
//}
// Check that we can convert the history value into an integer ok:
if (k > Math.log(Integer.MAX_VALUE) / log_base) {
throw new RuntimeException("Base and history combination too large");
}
// Create constants for tracking prevValues
maxShiftedValue = new int[base];
for (int v = 0; v < base; v++) {
maxShiftedValue[v] = v * MathsUtils.power(base, k-1);
}
noObservationStorage = dontCreateObsStorage;
if (!dontCreateObsStorage) {
// Create storage for counts of observations
nextPastCount = new int[base][base_power_k];
pastCount = new int[base_power_k];
nextCount = new int[base];
}
}
/**
* Initialise calculator, preparing to take observation sets in
* Should be called prior to any of the addObservations() methods.
* You can reinitialise without needing to create a new object.
*
*/
public void initialise() {
super.initialise();
if (!noObservationStorage) {
MatrixUtils.fill(nextPastCount, 0);
MatrixUtils.fill(pastCount, 0);
MatrixUtils.fill(nextCount, 0);
}
}
/**
* Utility function to compute the combined past values of x up to and including time step t
* (i.e. (x_{t-k+1}, ... ,x_{t-1},x_{t}))
*
* @param x
* @param t
* @return
*/
public int computePastValue(int[] x, int t) {
int pastVal = 0;
for (int p = 0; p < k; p++) {
pastVal *= base;
pastVal += x[t - k + 1 + p];
}
return pastVal;
}
/**
* Utility function to compute the combined past values of x up to and including time step t
* (i.e. (x_{t-k+1}, ... ,x_{t-1},x_{t}))
*
* @param x
* @param agentNumber
* @param t
* @return
*/
public int computePastValue(int[][] x, int agentNumber, int t) {
int pastVal = 0;
for (int p = 0; p < k; p++) {
pastVal *= base;
pastVal += x[t - k + 1 + p][agentNumber];
}
return pastVal;
}
/**
* Utility function to compute the combined past values of x up to and including time step t
* (i.e. (x_{t-k+1}, ... ,x_{t-1},x_{t}))
*
* @param x
* @param agentNumber
* @param t
* @return
*/
public int computePastValue(int[][][] x, int agentRow, int agentColumn, int t) {
int pastVal = 0;
for (int p = 0; p < k; p++) {
pastVal *= base;
pastVal += x[t - k + 1 + p][agentRow][agentColumn];
}
return pastVal;
}
}
| mit |
TorchPowered/Thallium | src/main/java/net/minecraft/entity/passive/EntityHorse.java | 54229 | package net.minecraft.entity.passive;
import com.google.common.base.Predicate;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityAgeable;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.IEntityLivingData;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.ai.EntityAIFollowParent;
import net.minecraft.entity.ai.EntityAILookIdle;
import net.minecraft.entity.ai.EntityAIMate;
import net.minecraft.entity.ai.EntityAIPanic;
import net.minecraft.entity.ai.EntityAIRunAroundLikeCrazy;
import net.minecraft.entity.ai.EntityAISwimming;
import net.minecraft.entity.ai.EntityAIWander;
import net.minecraft.entity.ai.EntityAIWatchClosest;
import net.minecraft.entity.ai.attributes.IAttribute;
import net.minecraft.entity.ai.attributes.IAttributeInstance;
import net.minecraft.entity.ai.attributes.RangedAttribute;
import net.minecraft.entity.player.Player;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.inventory.AnimalChest;
import net.minecraft.inventory.IInvBasic;
import net.minecraft.inventory.InventoryBasic;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.pathfinding.PathNavigateGround;
import net.minecraft.potion.Potion;
import net.minecraft.server.management.PreYggdrasilConverter;
import net.minecraft.util.BlockPos;
import net.minecraft.util.DamageSource;
import net.minecraft.util.MathHelper;
import net.minecraft.util.StatCollector;
import net.minecraft.world.DifficultyInstance;
import net.minecraft.world.World;
public class EntityHorse extends EntityAnimal implements IInvBasic
{
private static final Predicate<Entity> horseBreedingSelector = new Predicate<Entity>()
{
public boolean apply(Entity p_apply_1_)
{
return p_apply_1_ instanceof EntityHorse && ((EntityHorse)p_apply_1_).isBreeding();
}
};
private static final IAttribute horseJumpStrength = (new RangedAttribute((IAttribute)null, "horse.jumpStrength", 0.7D, 0.0D, 2.0D)).setDescription("Jump Strength").setShouldWatch(true);
private static final String[] horseArmorTextures = new String[] {null, "textures/entity/horse/armor/horse_armor_iron.png", "textures/entity/horse/armor/horse_armor_gold.png", "textures/entity/horse/armor/horse_armor_diamond.png"};
private static final String[] HORSE_ARMOR_TEXTURES_ABBR = new String[] {"", "meo", "goo", "dio"};
private static final int[] armorValues = new int[] {0, 5, 7, 11};
private static final String[] horseTextures = new String[] {"textures/entity/horse/horse_white.png", "textures/entity/horse/horse_creamy.png", "textures/entity/horse/horse_chestnut.png", "textures/entity/horse/horse_brown.png", "textures/entity/horse/horse_black.png", "textures/entity/horse/horse_gray.png", "textures/entity/horse/horse_darkbrown.png"};
private static final String[] HORSE_TEXTURES_ABBR = new String[] {"hwh", "hcr", "hch", "hbr", "hbl", "hgr", "hdb"};
private static final String[] horseMarkingTextures = new String[] {null, "textures/entity/horse/horse_markings_white.png", "textures/entity/horse/horse_markings_whitefield.png", "textures/entity/horse/horse_markings_whitedots.png", "textures/entity/horse/horse_markings_blackdots.png"};
private static final String[] HORSE_MARKING_TEXTURES_ABBR = new String[] {"", "wo_", "wmo", "wdo", "bdo"};
private int eatingHaystackCounter;
private int openMouthCounter;
private int jumpRearingCounter;
public int field_110278_bp;
public int field_110279_bq;
protected boolean horseJumping;
private AnimalChest horseChest;
private boolean hasReproduced;
/**
* "The higher this value, the more likely the horse is to be tamed next time a player rides it."
*/
protected int temper;
protected float jumpPower;
private boolean field_110294_bI;
private float headLean;
private float prevHeadLean;
private float rearingAmount;
private float prevRearingAmount;
private float mouthOpenness;
private float prevMouthOpenness;
/** Used to determine the sound that the horse should make when it steps */
private int gallopTime;
private String texturePrefix;
private String[] horseTexturesArray = new String[3];
private boolean field_175508_bO = false;
public EntityHorse(World worldIn)
{
super(worldIn);
this.setSize(1.4F, 1.6F);
this.isImmuneToFire = false;
this.setChested(false);
((PathNavigateGround)this.getNavigator()).setAvoidsWater(true);
this.tasks.addTask(0, new EntityAISwimming(this));
this.tasks.addTask(1, new EntityAIPanic(this, 1.2D));
this.tasks.addTask(1, new EntityAIRunAroundLikeCrazy(this, 1.2D));
this.tasks.addTask(2, new EntityAIMate(this, 1.0D));
this.tasks.addTask(4, new EntityAIFollowParent(this, 1.0D));
this.tasks.addTask(6, new EntityAIWander(this, 0.7D));
this.tasks.addTask(7, new EntityAIWatchClosest(this, Player.class, 6.0F));
this.tasks.addTask(8, new EntityAILookIdle(this));
this.initHorseChest();
}
protected void entityInit()
{
super.entityInit();
this.dataWatcher.addObject(16, Integer.valueOf(0));
this.dataWatcher.addObject(19, Byte.valueOf((byte)0));
this.dataWatcher.addObject(20, Integer.valueOf(0));
this.dataWatcher.addObject(21, String.valueOf((Object)""));
this.dataWatcher.addObject(22, Integer.valueOf(0));
}
public void setHorseType(int type)
{
this.dataWatcher.updateObject(19, Byte.valueOf((byte)type));
this.resetTexturePrefix();
}
/**
* Returns the horse type. 0 = Normal, 1 = Donkey, 2 = Mule, 3 = Undead Horse, 4 = Skeleton Horse
*/
public int getHorseType()
{
return this.dataWatcher.getWatchableObjectByte(19);
}
public void setHorseVariant(int variant)
{
this.dataWatcher.updateObject(20, Integer.valueOf(variant));
this.resetTexturePrefix();
}
public int getHorseVariant()
{
return this.dataWatcher.getWatchableObjectInt(20);
}
/**
* Gets the name of this command sender (usually username, but possibly "Rcon")
*/
public String getName()
{
if (this.hasCustomName())
{
return this.getCustomNameTag();
}
else
{
int i = this.getHorseType();
switch (i)
{
case 0:
default:
return StatCollector.translateToLocal("entity.horse.name");
case 1:
return StatCollector.translateToLocal("entity.donkey.name");
case 2:
return StatCollector.translateToLocal("entity.mule.name");
case 3:
return StatCollector.translateToLocal("entity.zombiehorse.name");
case 4:
return StatCollector.translateToLocal("entity.skeletonhorse.name");
}
}
}
private boolean getHorseWatchableBoolean(int p_110233_1_)
{
return (this.dataWatcher.getWatchableObjectInt(16) & p_110233_1_) != 0;
}
private void setHorseWatchableBoolean(int p_110208_1_, boolean p_110208_2_)
{
int i = this.dataWatcher.getWatchableObjectInt(16);
if (p_110208_2_)
{
this.dataWatcher.updateObject(16, Integer.valueOf(i | p_110208_1_));
}
else
{
this.dataWatcher.updateObject(16, Integer.valueOf(i & ~p_110208_1_));
}
}
public boolean isAdultHorse()
{
return !this.isChild();
}
public boolean isTame()
{
return this.getHorseWatchableBoolean(2);
}
public boolean func_110253_bW()
{
return this.isAdultHorse();
}
/**
* Gets the horse's owner
*/
public String getOwnerId()
{
return this.dataWatcher.getWatchableObjectString(21);
}
public void setOwnerId(String id)
{
this.dataWatcher.updateObject(21, id);
}
public float getHorseSize()
{
return 0.5F;
}
/**
* "Sets the scale for an ageable entity according to the boolean parameter, which says if it's a child."
*/
public void setScaleForAge(boolean p_98054_1_)
{
if (p_98054_1_)
{
this.setScale(this.getHorseSize());
}
else
{
this.setScale(1.0F);
}
}
public boolean isHorseJumping()
{
return this.horseJumping;
}
public void setHorseTamed(boolean tamed)
{
this.setHorseWatchableBoolean(2, tamed);
}
public void setHorseJumping(boolean jumping)
{
this.horseJumping = jumping;
}
public boolean allowLeashing()
{
return !this.isUndead() && super.allowLeashing();
}
protected void func_142017_o(float p_142017_1_)
{
if (p_142017_1_ > 6.0F && this.isEatingHaystack())
{
this.setEatingHaystack(false);
}
}
public boolean isChested()
{
return this.getHorseWatchableBoolean(8);
}
/**
* Returns type of armor from DataWatcher (0 = iron, 1 = gold, 2 = diamond)
*/
public int getHorseArmorIndexSynced()
{
return this.dataWatcher.getWatchableObjectInt(22);
}
/**
* 0 = iron, 1 = gold, 2 = diamond
*/
private int getHorseArmorIndex(ItemStack itemStackIn)
{
if (itemStackIn == null)
{
return 0;
}
else
{
Item item = itemStackIn.getItem();
return item == Items.iron_horse_armor ? 1 : (item == Items.golden_horse_armor ? 2 : (item == Items.diamond_horse_armor ? 3 : 0));
}
}
public boolean isEatingHaystack()
{
return this.getHorseWatchableBoolean(32);
}
public boolean isRearing()
{
return this.getHorseWatchableBoolean(64);
}
public boolean isBreeding()
{
return this.getHorseWatchableBoolean(16);
}
public boolean getHasReproduced()
{
return this.hasReproduced;
}
/**
* Set horse armor stack (for example: new ItemStack(Items.iron_horse_armor))
*/
public void setHorseArmorStack(ItemStack itemStackIn)
{
this.dataWatcher.updateObject(22, Integer.valueOf(this.getHorseArmorIndex(itemStackIn)));
this.resetTexturePrefix();
}
public void setBreeding(boolean breeding)
{
this.setHorseWatchableBoolean(16, breeding);
}
public void setChested(boolean chested)
{
this.setHorseWatchableBoolean(8, chested);
}
public void setHasReproduced(boolean hasReproducedIn)
{
this.hasReproduced = hasReproducedIn;
}
public void setHorseSaddled(boolean saddled)
{
this.setHorseWatchableBoolean(4, saddled);
}
public int getTemper()
{
return this.temper;
}
public void setTemper(int temperIn)
{
this.temper = temperIn;
}
public int increaseTemper(int p_110198_1_)
{
int i = MathHelper.clamp_int(this.getTemper() + p_110198_1_, 0, this.getMaxTemper());
this.setTemper(i);
return i;
}
/**
* Called when the entity is attacked.
*/
public boolean attackEntityFrom(DamageSource source, float amount)
{
Entity entity = source.getEntity();
return this.riddenByEntity != null && this.riddenByEntity.equals(entity) ? false : super.attackEntityFrom(source, amount);
}
/**
* Returns the current armor value as determined by a call to InventoryPlayer.getTotalArmorValue
*/
public int getTotalArmorValue()
{
return armorValues[this.getHorseArmorIndexSynced()];
}
/**
* Returns true if this entity should push and be pushed by other entities when colliding.
*/
public boolean canBePushed()
{
return this.riddenByEntity == null;
}
public boolean prepareChunkForSpawn()
{
int i = MathHelper.floor_double(this.posX);
int j = MathHelper.floor_double(this.posZ);
this.worldObj.getBiomeGenForCoords(new BlockPos(i, 0, j));
return true;
}
public void dropChests()
{
if (!this.worldObj.isRemote && this.isChested())
{
this.dropItem(Item.getItemFromBlock(Blocks.chest), 1);
this.setChested(false);
}
}
private void func_110266_cB()
{
this.openHorseMouth();
if (!this.isSilent())
{
this.worldObj.playSoundAtEntity(this, "eating", 1.0F, 1.0F + (this.rand.nextFloat() - this.rand.nextFloat()) * 0.2F);
}
}
public void fall(float distance, float damageMultiplier)
{
if (distance > 1.0F)
{
this.playSound("mob.horse.land", 0.4F, 1.0F);
}
int i = MathHelper.ceiling_float_int((distance * 0.5F - 3.0F) * damageMultiplier);
if (i > 0)
{
this.attackEntityFrom(DamageSource.fall, (float)i);
if (this.riddenByEntity != null)
{
this.riddenByEntity.attackEntityFrom(DamageSource.fall, (float)i);
}
Block block = this.worldObj.getBlockState(new BlockPos(this.posX, this.posY - 0.2D - (double)this.prevRotationYaw, this.posZ)).getBlock();
if (block.getMaterial() != Material.air && !this.isSilent())
{
Block.SoundType block$soundtype = block.stepSound;
this.worldObj.playSoundAtEntity(this, block$soundtype.getStepSound(), block$soundtype.getVolume() * 0.5F, block$soundtype.getFrequency() * 0.75F);
}
}
}
/**
* Returns number of slots depending horse type
*/
private int getChestSize()
{
int i = this.getHorseType();
return !this.isChested() || i != 1 && i != 2 ? 2 : 17;
}
private void initHorseChest()
{
AnimalChest animalchest = this.horseChest;
this.horseChest = new AnimalChest("HorseChest", this.getChestSize());
this.horseChest.setCustomName(this.getName());
if (animalchest != null)
{
animalchest.func_110132_b(this);
int i = Math.min(animalchest.getSizeInventory(), this.horseChest.getSizeInventory());
for (int j = 0; j < i; ++j)
{
ItemStack itemstack = animalchest.getStackInSlot(j);
if (itemstack != null)
{
this.horseChest.setInventorySlotContents(j, itemstack.copy());
}
}
}
this.horseChest.func_110134_a(this);
this.updateHorseSlots();
}
/**
* Updates the items in the saddle and armor slots of the horse's inventory.
*/
private void updateHorseSlots()
{
if (!this.worldObj.isRemote)
{
this.setHorseSaddled(this.horseChest.getStackInSlot(0) != null);
if (this.canWearArmor())
{
this.setHorseArmorStack(this.horseChest.getStackInSlot(1));
}
}
}
/**
* Called by InventoryBasic.onInventoryChanged() on a array that is never filled.
*/
public void onInventoryChanged(InventoryBasic p_76316_1_)
{
int i = this.getHorseArmorIndexSynced();
boolean flag = this.isHorseSaddled();
this.updateHorseSlots();
if (this.ticksExisted > 20)
{
if (i == 0 && i != this.getHorseArmorIndexSynced())
{
this.playSound("mob.horse.armor", 0.5F, 1.0F);
}
else if (i != this.getHorseArmorIndexSynced())
{
this.playSound("mob.horse.armor", 0.5F, 1.0F);
}
if (!flag && this.isHorseSaddled())
{
this.playSound("mob.horse.leather", 0.5F, 1.0F);
}
}
}
/**
* Checks if the entity's current position is a valid location to spawn this entity.
*/
public boolean getCanSpawnHere()
{
this.prepareChunkForSpawn();
return super.getCanSpawnHere();
}
protected EntityHorse getClosestHorse(Entity entityIn, double distance)
{
double d0 = Double.MAX_VALUE;
Entity entity = null;
for (Entity entity1 : this.worldObj.getEntitiesInAABBexcluding(entityIn, entityIn.getEntityBoundingBox().addCoord(distance, distance, distance), horseBreedingSelector))
{
double d1 = entity1.getDistanceSq(entityIn.posX, entityIn.posY, entityIn.posZ);
if (d1 < d0)
{
entity = entity1;
d0 = d1;
}
}
return (EntityHorse)entity;
}
public double getHorseJumpStrength()
{
return this.getEntityAttribute(horseJumpStrength).getAttributeValue();
}
/**
* Returns the sound this mob makes on death.
*/
protected String getDeathSound()
{
this.openHorseMouth();
int i = this.getHorseType();
return i == 3 ? "mob.horse.zombie.death" : (i == 4 ? "mob.horse.skeleton.death" : (i != 1 && i != 2 ? "mob.horse.death" : "mob.horse.donkey.death"));
}
protected Item getDropItem()
{
boolean flag = this.rand.nextInt(4) == 0;
int i = this.getHorseType();
return i == 4 ? Items.bone : (i == 3 ? (flag ? null : Items.rotten_flesh) : Items.leather);
}
/**
* Returns the sound this mob makes when it is hurt.
*/
protected String getHurtSound()
{
this.openHorseMouth();
if (this.rand.nextInt(3) == 0)
{
this.makeHorseRear();
}
int i = this.getHorseType();
return i == 3 ? "mob.horse.zombie.hit" : (i == 4 ? "mob.horse.skeleton.hit" : (i != 1 && i != 2 ? "mob.horse.hit" : "mob.horse.donkey.hit"));
}
public boolean isHorseSaddled()
{
return this.getHorseWatchableBoolean(4);
}
/**
* Returns the sound this mob makes while it's alive.
*/
protected String getLivingSound()
{
this.openHorseMouth();
if (this.rand.nextInt(10) == 0 && !this.isMovementBlocked())
{
this.makeHorseRear();
}
int i = this.getHorseType();
return i == 3 ? "mob.horse.zombie.idle" : (i == 4 ? "mob.horse.skeleton.idle" : (i != 1 && i != 2 ? "mob.horse.idle" : "mob.horse.donkey.idle"));
}
protected String getAngrySoundName()
{
this.openHorseMouth();
this.makeHorseRear();
int i = this.getHorseType();
return i != 3 && i != 4 ? (i != 1 && i != 2 ? "mob.horse.angry" : "mob.horse.donkey.angry") : null;
}
protected void playStepSound(BlockPos pos, Block blockIn)
{
Block.SoundType block$soundtype = blockIn.stepSound;
if (this.worldObj.getBlockState(pos.up()).getBlock() == Blocks.snow_layer)
{
block$soundtype = Blocks.snow_layer.stepSound;
}
if (!blockIn.getMaterial().isLiquid())
{
int i = this.getHorseType();
if (this.riddenByEntity != null && i != 1 && i != 2)
{
++this.gallopTime;
if (this.gallopTime > 5 && this.gallopTime % 3 == 0)
{
this.playSound("mob.horse.gallop", block$soundtype.getVolume() * 0.15F, block$soundtype.getFrequency());
if (i == 0 && this.rand.nextInt(10) == 0)
{
this.playSound("mob.horse.breathe", block$soundtype.getVolume() * 0.6F, block$soundtype.getFrequency());
}
}
else if (this.gallopTime <= 5)
{
this.playSound("mob.horse.wood", block$soundtype.getVolume() * 0.15F, block$soundtype.getFrequency());
}
}
else if (block$soundtype == Block.soundTypeWood)
{
this.playSound("mob.horse.wood", block$soundtype.getVolume() * 0.15F, block$soundtype.getFrequency());
}
else
{
this.playSound("mob.horse.soft", block$soundtype.getVolume() * 0.15F, block$soundtype.getFrequency());
}
}
}
protected void applyEntityAttributes()
{
super.applyEntityAttributes();
this.getAttributeMap().registerAttribute(horseJumpStrength);
this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(53.0D);
this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.22499999403953552D);
}
/**
* Will return how many at most can spawn in a chunk at once.
*/
public int getMaxSpawnedInChunk()
{
return 6;
}
public int getMaxTemper()
{
return 100;
}
/**
* Returns the volume for the sounds this mob makes.
*/
protected float getSoundVolume()
{
return 0.8F;
}
/**
* Get number of ticks, at least during which the living entity will be silent.
*/
public int getTalkInterval()
{
return 400;
}
private void resetTexturePrefix()
{
this.texturePrefix = null;
}
public void openGUI(Player playerEntity)
{
if (!this.worldObj.isRemote && (this.riddenByEntity == null || this.riddenByEntity == playerEntity) && this.isTame())
{
this.horseChest.setCustomName(this.getName());
playerEntity.displayGUIHorse(this, this.horseChest);
}
}
/**
* Called when a player interacts with a mob. e.g. gets milk from a cow, gets into the saddle on a pig.
*/
public boolean interact(Player player)
{
ItemStack itemstack = player.inventory.getCurrentItem();
if (itemstack != null && itemstack.getItem() == Items.spawn_egg)
{
return super.interact(player);
}
else if (!this.isTame() && this.isUndead())
{
return false;
}
else if (this.isTame() && this.isAdultHorse() && player.isSneaking())
{
this.openGUI(player);
return true;
}
else if (this.func_110253_bW() && this.riddenByEntity != null)
{
return super.interact(player);
}
else
{
if (itemstack != null)
{
boolean flag = false;
if (this.canWearArmor())
{
int i = -1;
if (itemstack.getItem() == Items.iron_horse_armor)
{
i = 1;
}
else if (itemstack.getItem() == Items.golden_horse_armor)
{
i = 2;
}
else if (itemstack.getItem() == Items.diamond_horse_armor)
{
i = 3;
}
if (i >= 0)
{
if (!this.isTame())
{
this.makeHorseRearWithSound();
return true;
}
this.openGUI(player);
return true;
}
}
if (!flag && !this.isUndead())
{
float f = 0.0F;
int j = 0;
int k = 0;
if (itemstack.getItem() == Items.wheat)
{
f = 2.0F;
j = 20;
k = 3;
}
else if (itemstack.getItem() == Items.sugar)
{
f = 1.0F;
j = 30;
k = 3;
}
else if (Block.getBlockFromItem(itemstack.getItem()) == Blocks.hay_block)
{
f = 20.0F;
j = 180;
}
else if (itemstack.getItem() == Items.apple)
{
f = 3.0F;
j = 60;
k = 3;
}
else if (itemstack.getItem() == Items.golden_carrot)
{
f = 4.0F;
j = 60;
k = 5;
if (this.isTame() && this.getGrowingAge() == 0)
{
flag = true;
this.setInLove(player);
}
}
else if (itemstack.getItem() == Items.golden_apple)
{
f = 10.0F;
j = 240;
k = 10;
if (this.isTame() && this.getGrowingAge() == 0)
{
flag = true;
this.setInLove(player);
}
}
if (this.getHealth() < this.getMaxHealth() && f > 0.0F)
{
this.heal(f);
flag = true;
}
if (!this.isAdultHorse() && j > 0)
{
this.addGrowth(j);
flag = true;
}
if (k > 0 && (flag || !this.isTame()) && k < this.getMaxTemper())
{
flag = true;
this.increaseTemper(k);
}
if (flag)
{
this.func_110266_cB();
}
}
if (!this.isTame() && !flag)
{
if (itemstack != null && itemstack.interactWithEntity(player, this))
{
return true;
}
this.makeHorseRearWithSound();
return true;
}
if (!flag && this.canCarryChest() && !this.isChested() && itemstack.getItem() == Item.getItemFromBlock(Blocks.chest))
{
this.setChested(true);
this.playSound("mob.chickenplop", 1.0F, (this.rand.nextFloat() - this.rand.nextFloat()) * 0.2F + 1.0F);
flag = true;
this.initHorseChest();
}
if (!flag && this.func_110253_bW() && !this.isHorseSaddled() && itemstack.getItem() == Items.saddle)
{
this.openGUI(player);
return true;
}
if (flag)
{
if (!player.capabilities.isCreativeMode && --itemstack.stackSize == 0)
{
player.inventory.setInventorySlotContents(player.inventory.currentItem, (ItemStack)null);
}
return true;
}
}
if (this.func_110253_bW() && this.riddenByEntity == null)
{
if (itemstack != null && itemstack.interactWithEntity(player, this))
{
return true;
}
else
{
this.mountTo(player);
return true;
}
}
else
{
return super.interact(player);
}
}
}
private void mountTo(Player player)
{
player.rotationYaw = this.rotationYaw;
player.rotationPitch = this.rotationPitch;
this.setEatingHaystack(false);
this.setRearing(false);
if (!this.worldObj.isRemote)
{
player.mountEntity(this);
}
}
/**
* Return true if the horse entity can wear an armor
*/
public boolean canWearArmor()
{
return this.getHorseType() == 0;
}
/**
* Return true if the horse entity can carry a chest.
*/
public boolean canCarryChest()
{
int i = this.getHorseType();
return i == 2 || i == 1;
}
/**
* Dead and sleeping entities cannot move
*/
protected boolean isMovementBlocked()
{
return this.riddenByEntity != null && this.isHorseSaddled() ? true : this.isEatingHaystack() || this.isRearing();
}
/**
* Used to know if the horse can be leashed, if he can mate, or if we can interact with him
*/
public boolean isUndead()
{
int i = this.getHorseType();
return i == 3 || i == 4;
}
/**
* Return true if the horse entity is sterile (Undead || Mule)
*/
public boolean isSterile()
{
return this.isUndead() || this.getHorseType() == 2;
}
/**
* Checks if the parameter is an item which this animal can be fed to breed it (wheat, carrots or seeds depending on
* the animal type)
*/
public boolean isBreedingItem(ItemStack stack)
{
return false;
}
private void func_110210_cH()
{
this.field_110278_bp = 1;
}
/**
* Called when the mob's health reaches 0.
*/
public void onDeath(DamageSource cause)
{
super.onDeath(cause);
if (!this.worldObj.isRemote)
{
this.dropChestItems();
}
}
/**
* Called frequently so the entity can update its state every tick as required. For example, zombies and skeletons
* use this to react to sunlight and start to burn.
*/
public void onLivingUpdate()
{
if (this.rand.nextInt(200) == 0)
{
this.func_110210_cH();
}
super.onLivingUpdate();
if (!this.worldObj.isRemote)
{
if (this.rand.nextInt(900) == 0 && this.deathTime == 0)
{
this.heal(1.0F);
}
if (!this.isEatingHaystack() && this.riddenByEntity == null && this.rand.nextInt(300) == 0 && this.worldObj.getBlockState(new BlockPos(MathHelper.floor_double(this.posX), MathHelper.floor_double(this.posY) - 1, MathHelper.floor_double(this.posZ))).getBlock() == Blocks.grass)
{
this.setEatingHaystack(true);
}
if (this.isEatingHaystack() && ++this.eatingHaystackCounter > 50)
{
this.eatingHaystackCounter = 0;
this.setEatingHaystack(false);
}
if (this.isBreeding() && !this.isAdultHorse() && !this.isEatingHaystack())
{
EntityHorse entityhorse = this.getClosestHorse(this, 16.0D);
if (entityhorse != null && this.getDistanceSqToEntity(entityhorse) > 4.0D)
{
this.navigator.getPathToEntityLiving(entityhorse);
}
}
}
}
/**
* Called to update the entity's position/logic.
*/
public void onUpdate()
{
super.onUpdate();
if (this.worldObj.isRemote && this.dataWatcher.hasObjectChanged())
{
this.dataWatcher.func_111144_e();
this.resetTexturePrefix();
}
if (this.openMouthCounter > 0 && ++this.openMouthCounter > 30)
{
this.openMouthCounter = 0;
this.setHorseWatchableBoolean(128, false);
}
if (!this.worldObj.isRemote && this.jumpRearingCounter > 0 && ++this.jumpRearingCounter > 20)
{
this.jumpRearingCounter = 0;
this.setRearing(false);
}
if (this.field_110278_bp > 0 && ++this.field_110278_bp > 8)
{
this.field_110278_bp = 0;
}
if (this.field_110279_bq > 0)
{
++this.field_110279_bq;
if (this.field_110279_bq > 300)
{
this.field_110279_bq = 0;
}
}
this.prevHeadLean = this.headLean;
if (this.isEatingHaystack())
{
this.headLean += (1.0F - this.headLean) * 0.4F + 0.05F;
if (this.headLean > 1.0F)
{
this.headLean = 1.0F;
}
}
else
{
this.headLean += (0.0F - this.headLean) * 0.4F - 0.05F;
if (this.headLean < 0.0F)
{
this.headLean = 0.0F;
}
}
this.prevRearingAmount = this.rearingAmount;
if (this.isRearing())
{
this.prevHeadLean = this.headLean = 0.0F;
this.rearingAmount += (1.0F - this.rearingAmount) * 0.4F + 0.05F;
if (this.rearingAmount > 1.0F)
{
this.rearingAmount = 1.0F;
}
}
else
{
this.field_110294_bI = false;
this.rearingAmount += (0.8F * this.rearingAmount * this.rearingAmount * this.rearingAmount - this.rearingAmount) * 0.6F - 0.05F;
if (this.rearingAmount < 0.0F)
{
this.rearingAmount = 0.0F;
}
}
this.prevMouthOpenness = this.mouthOpenness;
if (this.getHorseWatchableBoolean(128))
{
this.mouthOpenness += (1.0F - this.mouthOpenness) * 0.7F + 0.05F;
if (this.mouthOpenness > 1.0F)
{
this.mouthOpenness = 1.0F;
}
}
else
{
this.mouthOpenness += (0.0F - this.mouthOpenness) * 0.7F - 0.05F;
if (this.mouthOpenness < 0.0F)
{
this.mouthOpenness = 0.0F;
}
}
}
private void openHorseMouth()
{
if (!this.worldObj.isRemote)
{
this.openMouthCounter = 1;
this.setHorseWatchableBoolean(128, true);
}
}
/**
* Return true if the horse entity ready to mate. (no rider, not riding, tame, adult, not steril...)
*/
private boolean canMate()
{
return this.riddenByEntity == null && this.ridingEntity == null && this.isTame() && this.isAdultHorse() && !this.isSterile() && this.getHealth() >= this.getMaxHealth() && this.isInLove();
}
public void setEating(boolean eating)
{
this.setHorseWatchableBoolean(32, eating);
}
public void setEatingHaystack(boolean p_110227_1_)
{
this.setEating(p_110227_1_);
}
public void setRearing(boolean rearing)
{
if (rearing)
{
this.setEatingHaystack(false);
}
this.setHorseWatchableBoolean(64, rearing);
}
private void makeHorseRear()
{
if (!this.worldObj.isRemote)
{
this.jumpRearingCounter = 1;
this.setRearing(true);
}
}
public void makeHorseRearWithSound()
{
this.makeHorseRear();
String s = this.getAngrySoundName();
if (s != null)
{
this.playSound(s, this.getSoundVolume(), this.getSoundPitch());
}
}
public void dropChestItems()
{
this.dropItemsInChest(this, this.horseChest);
this.dropChests();
}
private void dropItemsInChest(Entity entityIn, AnimalChest animalChestIn)
{
if (animalChestIn != null && !this.worldObj.isRemote)
{
for (int i = 0; i < animalChestIn.getSizeInventory(); ++i)
{
ItemStack itemstack = animalChestIn.getStackInSlot(i);
if (itemstack != null)
{
this.entityDropItem(itemstack, 0.0F);
}
}
}
}
public boolean setTamedBy(Player player)
{
this.setOwnerId(player.getUniqueID().toString());
this.setHorseTamed(true);
return true;
}
/**
* Moves the entity based on the specified heading. Args: strafe, forward
*/
public void moveEntityWithHeading(float strafe, float forward)
{
if (this.riddenByEntity != null && this.riddenByEntity instanceof EntityLivingBase && this.isHorseSaddled())
{
this.prevRotationYaw = this.rotationYaw = this.riddenByEntity.rotationYaw;
this.rotationPitch = this.riddenByEntity.rotationPitch * 0.5F;
this.setRotation(this.rotationYaw, this.rotationPitch);
this.rotationYawHead = this.renderYawOffset = this.rotationYaw;
strafe = ((EntityLivingBase)this.riddenByEntity).moveStrafing * 0.5F;
forward = ((EntityLivingBase)this.riddenByEntity).moveForward;
if (forward <= 0.0F)
{
forward *= 0.25F;
this.gallopTime = 0;
}
if (this.onGround && this.jumpPower == 0.0F && this.isRearing() && !this.field_110294_bI)
{
strafe = 0.0F;
forward = 0.0F;
}
if (this.jumpPower > 0.0F && !this.isHorseJumping() && this.onGround)
{
this.motionY = this.getHorseJumpStrength() * (double)this.jumpPower;
if (this.isPotionActive(Potion.jump))
{
this.motionY += (double)((float)(this.getActivePotionEffect(Potion.jump).getAmplifier() + 1) * 0.1F);
}
this.setHorseJumping(true);
this.isAirBorne = true;
if (forward > 0.0F)
{
float f = MathHelper.sin(this.rotationYaw * (float)Math.PI / 180.0F);
float f1 = MathHelper.cos(this.rotationYaw * (float)Math.PI / 180.0F);
this.motionX += (double)(-0.4F * f * this.jumpPower);
this.motionZ += (double)(0.4F * f1 * this.jumpPower);
this.playSound("mob.horse.jump", 0.4F, 1.0F);
}
this.jumpPower = 0.0F;
}
this.stepHeight = 1.0F;
this.jumpMovementFactor = this.getAIMoveSpeed() * 0.1F;
if (!this.worldObj.isRemote)
{
this.setAIMoveSpeed((float)this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).getAttributeValue());
super.moveEntityWithHeading(strafe, forward);
}
if (this.onGround)
{
this.jumpPower = 0.0F;
this.setHorseJumping(false);
}
this.prevLimbSwingAmount = this.limbSwingAmount;
double d1 = this.posX - this.prevPosX;
double d0 = this.posZ - this.prevPosZ;
float f2 = MathHelper.sqrt_double(d1 * d1 + d0 * d0) * 4.0F;
if (f2 > 1.0F)
{
f2 = 1.0F;
}
this.limbSwingAmount += (f2 - this.limbSwingAmount) * 0.4F;
this.limbSwing += this.limbSwingAmount;
}
else
{
this.stepHeight = 0.5F;
this.jumpMovementFactor = 0.02F;
super.moveEntityWithHeading(strafe, forward);
}
}
/**
* (abstract) Protected helper method to write subclass entity data to NBT.
*/
public void writeEntityToNBT(NBTTagCompound tagCompound)
{
super.writeEntityToNBT(tagCompound);
tagCompound.setBoolean("EatingHaystack", this.isEatingHaystack());
tagCompound.setBoolean("ChestedHorse", this.isChested());
tagCompound.setBoolean("HasReproduced", this.getHasReproduced());
tagCompound.setBoolean("Bred", this.isBreeding());
tagCompound.setInteger("Type", this.getHorseType());
tagCompound.setInteger("Variant", this.getHorseVariant());
tagCompound.setInteger("Temper", this.getTemper());
tagCompound.setBoolean("Tame", this.isTame());
tagCompound.setString("OwnerUUID", this.getOwnerId());
if (this.isChested())
{
NBTTagList nbttaglist = new NBTTagList();
for (int i = 2; i < this.horseChest.getSizeInventory(); ++i)
{
ItemStack itemstack = this.horseChest.getStackInSlot(i);
if (itemstack != null)
{
NBTTagCompound nbttagcompound = new NBTTagCompound();
nbttagcompound.setByte("Slot", (byte)i);
itemstack.writeToNBT(nbttagcompound);
nbttaglist.appendTag(nbttagcompound);
}
}
tagCompound.setTag("Items", nbttaglist);
}
if (this.horseChest.getStackInSlot(1) != null)
{
tagCompound.setTag("ArmorItem", this.horseChest.getStackInSlot(1).writeToNBT(new NBTTagCompound()));
}
if (this.horseChest.getStackInSlot(0) != null)
{
tagCompound.setTag("SaddleItem", this.horseChest.getStackInSlot(0).writeToNBT(new NBTTagCompound()));
}
}
/**
* (abstract) Protected helper method to read subclass entity data from NBT.
*/
public void readEntityFromNBT(NBTTagCompound tagCompund)
{
super.readEntityFromNBT(tagCompund);
this.setEatingHaystack(tagCompund.getBoolean("EatingHaystack"));
this.setBreeding(tagCompund.getBoolean("Bred"));
this.setChested(tagCompund.getBoolean("ChestedHorse"));
this.setHasReproduced(tagCompund.getBoolean("HasReproduced"));
this.setHorseType(tagCompund.getInteger("Type"));
this.setHorseVariant(tagCompund.getInteger("Variant"));
this.setTemper(tagCompund.getInteger("Temper"));
this.setHorseTamed(tagCompund.getBoolean("Tame"));
String s = "";
if (tagCompund.hasKey("OwnerUUID", 8))
{
s = tagCompund.getString("OwnerUUID");
}
else
{
String s1 = tagCompund.getString("Owner");
s = PreYggdrasilConverter.getStringUUIDFromName(s1);
}
if (s.length() > 0)
{
this.setOwnerId(s);
}
IAttributeInstance iattributeinstance = this.getAttributeMap().getAttributeInstanceByName("Speed");
if (iattributeinstance != null)
{
this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(iattributeinstance.getBaseValue() * 0.25D);
}
if (this.isChested())
{
NBTTagList nbttaglist = tagCompund.getTagList("Items", 10);
this.initHorseChest();
for (int i = 0; i < nbttaglist.tagCount(); ++i)
{
NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i);
int j = nbttagcompound.getByte("Slot") & 255;
if (j >= 2 && j < this.horseChest.getSizeInventory())
{
this.horseChest.setInventorySlotContents(j, ItemStack.loadItemStackFromNBT(nbttagcompound));
}
}
}
if (tagCompund.hasKey("ArmorItem", 10))
{
ItemStack itemstack = ItemStack.loadItemStackFromNBT(tagCompund.getCompoundTag("ArmorItem"));
if (itemstack != null && isArmorItem(itemstack.getItem()))
{
this.horseChest.setInventorySlotContents(1, itemstack);
}
}
if (tagCompund.hasKey("SaddleItem", 10))
{
ItemStack itemstack1 = ItemStack.loadItemStackFromNBT(tagCompund.getCompoundTag("SaddleItem"));
if (itemstack1 != null && itemstack1.getItem() == Items.saddle)
{
this.horseChest.setInventorySlotContents(0, itemstack1);
}
}
else if (tagCompund.getBoolean("Saddle"))
{
this.horseChest.setInventorySlotContents(0, new ItemStack(Items.saddle));
}
this.updateHorseSlots();
}
/**
* Returns true if the mob is currently able to mate with the specified mob.
*/
public boolean canMateWith(EntityAnimal otherAnimal)
{
if (otherAnimal == this)
{
return false;
}
else if (otherAnimal.getClass() != this.getClass())
{
return false;
}
else
{
EntityHorse entityhorse = (EntityHorse)otherAnimal;
if (this.canMate() && entityhorse.canMate())
{
int i = this.getHorseType();
int j = entityhorse.getHorseType();
return i == j || i == 0 && j == 1 || i == 1 && j == 0;
}
else
{
return false;
}
}
}
public EntityAgeable createChild(EntityAgeable ageable)
{
EntityHorse entityhorse = (EntityHorse)ageable;
EntityHorse entityhorse1 = new EntityHorse(this.worldObj);
int i = this.getHorseType();
int j = entityhorse.getHorseType();
int k = 0;
if (i == j)
{
k = i;
}
else if (i == 0 && j == 1 || i == 1 && j == 0)
{
k = 2;
}
if (k == 0)
{
int i1 = this.rand.nextInt(9);
int l;
if (i1 < 4)
{
l = this.getHorseVariant() & 255;
}
else if (i1 < 8)
{
l = entityhorse.getHorseVariant() & 255;
}
else
{
l = this.rand.nextInt(7);
}
int j1 = this.rand.nextInt(5);
if (j1 < 2)
{
l = l | this.getHorseVariant() & 65280;
}
else if (j1 < 4)
{
l = l | entityhorse.getHorseVariant() & 65280;
}
else
{
l = l | this.rand.nextInt(5) << 8 & 65280;
}
entityhorse1.setHorseVariant(l);
}
entityhorse1.setHorseType(k);
double d1 = this.getEntityAttribute(SharedMonsterAttributes.maxHealth).getBaseValue() + ageable.getEntityAttribute(SharedMonsterAttributes.maxHealth).getBaseValue() + (double)this.getModifiedMaxHealth();
entityhorse1.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(d1 / 3.0D);
double d2 = this.getEntityAttribute(horseJumpStrength).getBaseValue() + ageable.getEntityAttribute(horseJumpStrength).getBaseValue() + this.getModifiedJumpStrength();
entityhorse1.getEntityAttribute(horseJumpStrength).setBaseValue(d2 / 3.0D);
double d0 = this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).getBaseValue() + ageable.getEntityAttribute(SharedMonsterAttributes.movementSpeed).getBaseValue() + this.getModifiedMovementSpeed();
entityhorse1.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(d0 / 3.0D);
return entityhorse1;
}
/**
* Called only once on an entity when first time spawned, via egg, mob spawner, natural spawning etc, but not called
* when entity is reloaded from nbt. Mainly used for initializing attributes and inventory
*/
public IEntityLivingData onInitialSpawn(DifficultyInstance difficulty, IEntityLivingData livingdata)
{
livingdata = super.onInitialSpawn(difficulty, livingdata);
int i = 0;
int j = 0;
if (livingdata instanceof EntityHorse.GroupData)
{
i = ((EntityHorse.GroupData)livingdata).horseType;
j = ((EntityHorse.GroupData)livingdata).horseVariant & 255 | this.rand.nextInt(5) << 8;
}
else
{
if (this.rand.nextInt(10) == 0)
{
i = 1;
}
else
{
int k = this.rand.nextInt(7);
int l = this.rand.nextInt(5);
i = 0;
j = k | l << 8;
}
livingdata = new EntityHorse.GroupData(i, j);
}
this.setHorseType(i);
this.setHorseVariant(j);
if (this.rand.nextInt(5) == 0)
{
this.setGrowingAge(-24000);
}
if (i != 4 && i != 3)
{
this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue((double)this.getModifiedMaxHealth());
if (i == 0)
{
this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(this.getModifiedMovementSpeed());
}
else
{
this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.17499999701976776D);
}
}
else
{
this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(15.0D);
this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.20000000298023224D);
}
if (i != 2 && i != 1)
{
this.getEntityAttribute(horseJumpStrength).setBaseValue(this.getModifiedJumpStrength());
}
else
{
this.getEntityAttribute(horseJumpStrength).setBaseValue(0.5D);
}
this.setHealth(this.getMaxHealth());
return livingdata;
}
public void setJumpPower(int jumpPowerIn)
{
if (this.isHorseSaddled())
{
if (jumpPowerIn < 0)
{
jumpPowerIn = 0;
}
else
{
this.field_110294_bI = true;
this.makeHorseRear();
}
if (jumpPowerIn >= 90)
{
this.jumpPower = 1.0F;
}
else
{
this.jumpPower = 0.4F + 0.4F * (float)jumpPowerIn / 90.0F;
}
}
}
public void updateRiderPosition()
{
super.updateRiderPosition();
if (this.prevRearingAmount > 0.0F)
{
float f = MathHelper.sin(this.renderYawOffset * (float)Math.PI / 180.0F);
float f1 = MathHelper.cos(this.renderYawOffset * (float)Math.PI / 180.0F);
float f2 = 0.7F * this.prevRearingAmount;
float f3 = 0.15F * this.prevRearingAmount;
this.riddenByEntity.setPosition(this.posX + (double)(f2 * f), this.posY + this.getMountedYOffset() + this.riddenByEntity.getYOffset() + (double)f3, this.posZ - (double)(f2 * f1));
if (this.riddenByEntity instanceof EntityLivingBase)
{
((EntityLivingBase)this.riddenByEntity).renderYawOffset = this.renderYawOffset;
}
}
}
/**
* Returns randomized max health
*/
private float getModifiedMaxHealth()
{
return 15.0F + (float)this.rand.nextInt(8) + (float)this.rand.nextInt(9);
}
/**
* Returns randomized jump strength
*/
private double getModifiedJumpStrength()
{
return 0.4000000059604645D + this.rand.nextDouble() * 0.2D + this.rand.nextDouble() * 0.2D + this.rand.nextDouble() * 0.2D;
}
/**
* Returns randomized movement speed
*/
private double getModifiedMovementSpeed()
{
return (0.44999998807907104D + this.rand.nextDouble() * 0.3D + this.rand.nextDouble() * 0.3D + this.rand.nextDouble() * 0.3D) * 0.25D;
}
/**
* Returns true if given item is horse armor
*/
public static boolean isArmorItem(Item p_146085_0_)
{
return p_146085_0_ == Items.iron_horse_armor || p_146085_0_ == Items.golden_horse_armor || p_146085_0_ == Items.diamond_horse_armor;
}
/**
* returns true if this entity is by a ladder, false otherwise
*/
public boolean isOnLadder()
{
return false;
}
public float getEyeHeight()
{
return this.height;
}
public boolean replaceItemInInventory(int inventorySlot, ItemStack itemStackIn)
{
if (inventorySlot == 499 && this.canCarryChest())
{
if (itemStackIn == null && this.isChested())
{
this.setChested(false);
this.initHorseChest();
return true;
}
if (itemStackIn != null && itemStackIn.getItem() == Item.getItemFromBlock(Blocks.chest) && !this.isChested())
{
this.setChested(true);
this.initHorseChest();
return true;
}
}
int i = inventorySlot - 400;
if (i >= 0 && i < 2 && i < this.horseChest.getSizeInventory())
{
if (i == 0 && itemStackIn != null && itemStackIn.getItem() != Items.saddle)
{
return false;
}
else if (i != 1 || (itemStackIn == null || isArmorItem(itemStackIn.getItem())) && this.canWearArmor())
{
this.horseChest.setInventorySlotContents(i, itemStackIn);
this.updateHorseSlots();
return true;
}
else
{
return false;
}
}
else
{
int j = inventorySlot - 500 + 2;
if (j >= 2 && j < this.horseChest.getSizeInventory())
{
this.horseChest.setInventorySlotContents(j, itemStackIn);
return true;
}
else
{
return false;
}
}
}
public static class GroupData implements IEntityLivingData
{
public int horseType;
public int horseVariant;
public GroupData(int type, int variant)
{
this.horseType = type;
this.horseVariant = variant;
}
}
}
| mit |
dvsa/mot | mot-selenium/src/main/java/uk/gov/dvsa/ui/pages/mot/TestAbandonedPage.java | 317 | package uk.gov.dvsa.ui.pages.mot;
import uk.gov.dvsa.framework.config.webdriver.MotAppDriver;
public class TestAbandonedPage extends TestCancelledPage{
private static final String PAGE_TITLE = "MOT test cancelled";
public TestAbandonedPage(MotAppDriver driver) {
super(driver, PAGE_TITLE);
}
}
| mit |
stryng/JQuaternion | src/main/java/com/jquaternion/jqsa/repository/PersistentTokenRepository.java | 541 | package com.jquaternion.jqsa.repository;
import com.jquaternion.jqsa.domain.PersistentToken;
import com.jquaternion.jqsa.domain.User;
import org.joda.time.LocalDate;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
/**
* Spring Data JPA repository for the PersistentToken entity.
*/
public interface PersistentTokenRepository extends JpaRepository<PersistentToken, String> {
List<PersistentToken> findByUser(User user);
List<PersistentToken> findByTokenDateBefore(LocalDate localDate);
}
| mit |
crlsndrsjmnz/GotIt | app/src/main/java/co/carlosandresjimenez/android/gotit/api/GotItSvcApi.java | 3932 | /*
* The MIT License (MIT)
*
* Copyright (c) 2015 Carlos Andres Jimenez <apps@carlosandresjimenez.co>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package co.carlosandresjimenez.android.gotit.api;
import java.util.ArrayList;
import co.carlosandresjimenez.android.gotit.beans.Answer;
import co.carlosandresjimenez.android.gotit.beans.Checkin;
import co.carlosandresjimenez.android.gotit.beans.Question;
import co.carlosandresjimenez.android.gotit.beans.User;
import retrofit.http.Body;
import retrofit.http.GET;
import retrofit.http.POST;
import retrofit.http.Query;
/**
* This interface defines an API for a GotItSvc. The
* interface is used to provide a contract for client/server
* interactions. The interface is annotated with Retrofit
* annotations so that clients can automatically convert the
* results into objects.
*
* @author Carlos Andres Jimenez
*/
public interface GotItSvcApi {
String ID_PARAMETER = "id";
String USER_PATH = "/user";
String REGISTER_PATH = USER_PATH + "/register";
String CHECKIN_BASE_PATH = "/checkin";
String CHECKIN_HISTORY_PATH = CHECKIN_BASE_PATH + "/history";
String CHECKIN_GRAPH_PATH = CHECKIN_BASE_PATH + "/graph";
String QUESTION_PATH = CHECKIN_BASE_PATH + "/question";
String ANSWER_PATH = CHECKIN_BASE_PATH + "/answer";
String FOLLOWING_BASE_PATH = "/following";
String FOLLOWING_LIST_PATH = FOLLOWING_BASE_PATH + "/list";
String FOLLOWING_TIMELINE_PATH = FOLLOWING_BASE_PATH + "/timeline";
String APPROVE_PARAMETER = "approved";
String FOLLOWBACK_PARAMETER = "followback";
String FOLLOW_BASE_PATH = "/follow";
String FOLLOW_REQUESTS_PATH = FOLLOW_BASE_PATH + "/requests";
String FOLLOW_APPROVE_PATH = FOLLOW_BASE_PATH + "/approve";
@GET(USER_PATH)
User getUserDetails(
@Query(ID_PARAMETER) String userId);
@POST(REGISTER_PATH)
String registerUser(@Body User u);
@GET(QUESTION_PATH)
ArrayList<Question> getAllQuestions();
@POST(ANSWER_PATH)
int saveAnswers(@Body ArrayList<Answer> answers);
@GET(CHECKIN_HISTORY_PATH)
ArrayList<Checkin> getCheckinHistory();
@GET(CHECKIN_BASE_PATH)
ArrayList<Question> getCheckinAnswers(@Query(ID_PARAMETER) String checkinId);
@GET(FOLLOWING_LIST_PATH)
ArrayList<User> getFollowingList();
@GET(FOLLOW_REQUESTS_PATH)
ArrayList<User> getFollowRequestsList();
@GET(FOLLOWING_TIMELINE_PATH)
ArrayList<Checkin> getFollowingTimeline();
@GET(FOLLOW_BASE_PATH)
int follow(@Query(ID_PARAMETER) String followEmail);
@GET(FOLLOW_APPROVE_PATH)
int changeFollowerStatus(@Query(ID_PARAMETER) String followerEmail,
@Query(APPROVE_PARAMETER) boolean approve,
@Query(FOLLOWBACK_PARAMETER) boolean followBack);
@GET(CHECKIN_GRAPH_PATH)
ArrayList<Answer> getGraphData(@Query(ID_PARAMETER) String email);
}
| mit |
stelian56/geometria | archive/3.2/src/net/geocentral/geometria/action/GPrismAction.java | 4565 | /**
* Copyright 2000-2013 Geometria Contributors
* http://geocentral.net/geometria
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License
* http://www.gnu.org/licenses
*/
package net.geocentral.geometria.action;
import net.geocentral.geometria.model.GDocument;
import net.geocentral.geometria.model.GFigure;
import net.geocentral.geometria.model.GSolid;
import net.geocentral.geometria.model.GSolidFactory;
import net.geocentral.geometria.util.GDictionary;
import net.geocentral.geometria.util.GGraphicsFactory;
import net.geocentral.geometria.util.GStringUtils;
import org.apache.log4j.Logger;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class GPrismAction implements GLoggable, GFigureAction {
private String figureName;
private Integer sideCount;
private String comments;
private static Logger logger = Logger.getLogger("net.geocentral.geometria");
public GPrismAction() {
}
public GPrismAction(String parameter) {
sideCount = Integer.valueOf(parameter);
}
public boolean execute() {
return execute(false);
}
public boolean execute(boolean silent) {
logger.info(silent + ", " + sideCount);
GDocumentHandler documentHandler = GDocumentHandler.getInstance();
if (!silent && sideCount == null) {
String input = GGraphicsFactory.getInstance().showInputDialog(GDictionary.get("EnterNumberOfSides"));
if (input == null) {
return false;
}
try {
sideCount = Integer.parseInt(input);
}
catch (Exception exception) {
documentHandler.error(GDictionary.get("BadSideCount", input));
return false;
}
if (sideCount < 3) {
documentHandler.error(GDictionary.get("BadSideCount", input));
return false;
}
}
GSolid solid = GSolidFactory.getInstance().newPrism(sideCount);
GFigure figure = documentHandler.newFigure(solid);
figureName = figure.getName();
if (!silent) {
documentHandler.setDocumentModified(true);
}
documentHandler.notepadChanged();
logger.info(figureName);
return true;
}
public void undo(GDocumentHandler documentHandler) {
logger.info("");
GDocument document = documentHandler.getActiveDocument();
document.removeFigure(figureName);
documentHandler.removeFigure(figureName);
documentHandler.notepadChanged();
logger.info(figureName);
}
public GLoggable clone() {
GPrismAction action = new GPrismAction();
action.figureName = figureName;
action.sideCount = sideCount;
return action;
}
public String toLogString() {
String figureType = GDictionary.get("prism");
return GDictionary.get("Create", figureType, figureName);
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public void make(Element node) throws Exception {
logger.info("");
NodeList ns = node.getElementsByTagName("sideCount");
if (ns.getLength() < 1) {
logger.error("No side count");
throw new Exception();
}
sideCount = Integer.valueOf(ns.item(0).getTextContent());
ns = node.getElementsByTagName("comments");
if (ns.getLength() > 0) {
String s = ns.item(0).getTextContent();
comments = GStringUtils.fromXml(s);
}
}
public void serialize(StringBuffer buf) {
logger.info("");
buf.append("\n<action>")
.append("\n<className>")
.append(this.getClass().getSimpleName())
.append("</className>")
.append("\n<sideCount>")
.append(String.valueOf(sideCount))
.append("</sideCount>");
if (comments != null) {
String s = GStringUtils.toXml(comments);
buf.append("\n<comments>")
.append(s)
.append("</comments>");
}
buf.append("\n</action>");
}
public String getShortDescription() {
String figureType = GDictionary.get("prism");
return GDictionary.get("create", figureType, figureName);
}
public String getFigureName() {
return figureName;
}
}
| mit |
jenniferlarsson/KD405A_Jennifer_L | KD405A_Larsson_J_uppgift4B/src/Snake.java | 599 |
/** A class describing a Snake */
public class Snake extends Animal{
private boolean poisonous;
/** Constructor */
public Snake(String latinName, boolean poisonous) {
super(latinName);
this.poisonous = poisonous;
setFriendlyName("no name");
}
public boolean isPoisonous(){
return poisonous;
}
@Override
public String getInfo() {
String poisonousStatus;
if (poisonous){
poisonousStatus = "poisonous";
} else{
poisonousStatus = "not poisonous";
}
return " the snake named " + getFriendlyName() + " lat " + getLatinName() + " is "+ poisonousStatus;
}
}
| mit |
midhunhk/trip-o-meter | app/src/main/java/com/ae/apps/tripmeter/listeners/FloatingActionButtonClickListener.java | 267 | package com.ae.apps.tripmeter.listeners;
/**
* Implement to get notified when the FAB is clicked
*/
public interface FloatingActionButtonClickListener {
/**
* Invoked when the Floating Action Button is clicked
*/
void onFloatingActionClick();
}
| mit |
sonots/embulk-parser-none | src/main/java/org/embulk/parser/NoneParserPlugin.java | 2153 | package org.embulk.parser;
import org.embulk.config.Config;
import org.embulk.config.ConfigDefault;
import org.embulk.config.ConfigDiff;
import org.embulk.config.ConfigSource;
import org.embulk.config.Task;
import org.embulk.config.TaskSource;
import org.embulk.spi.ParserPlugin;
import org.embulk.spi.FileInput;
import org.embulk.spi.PageOutput;
import org.embulk.spi.Schema;
import org.embulk.spi.SchemaConfig;
import org.embulk.spi.Exec;
import org.embulk.spi.PageBuilder;
import org.embulk.spi.util.LineDecoder;
import org.embulk.spi.ColumnConfig;
import java.util.ArrayList;
import static org.embulk.spi.type.Types.STRING;
public class NoneParserPlugin
implements ParserPlugin
{
public interface PluginTask
extends Task, LineDecoder.DecoderTask //, TimestampParser.Task
{
@Config("column_name")
@ConfigDefault("\"payload\"")
public String getColumnName();
}
@Override
public void transaction(ConfigSource config, ParserPlugin.Control control)
{
PluginTask task = config.loadConfig(PluginTask.class);
ArrayList<ColumnConfig> columns = new ArrayList<ColumnConfig>();
final String columnName = task.getColumnName();
columns.add(new ColumnConfig(columnName, STRING ,config));
Schema schema = new SchemaConfig(columns).toSchema();
control.run(task.dump(), schema);
}
@Override
public void run(TaskSource taskSource, Schema schema,
FileInput input, PageOutput output)
{
PluginTask task = taskSource.loadTask(PluginTask.class);
LineDecoder lineDecoder = new LineDecoder(input,task);
PageBuilder pageBuilder = new PageBuilder(Exec.getBufferAllocator(), schema, output);
String line = null;
final String columnName = task.getColumnName();
while( input.nextFile() ){
while(true){
line = lineDecoder.poll();
if( line == null ){
break;
}
pageBuilder.setString(0, line);
pageBuilder.addRecord();
}
}
pageBuilder.finish();
}
}
| mit |
zhoukekestar/drafts | _~2017/hellojni/app/src/main/jni/NdkTest.java | 302 | /**
* Created by Administrator on 8/8/2017.
*/
public class NdkTest {
static {
System.loadLibrary("NdkTest");//加载要使用的so文件
}
//生命native方法
public static native String getString();
public static native int doAdd(int param1,int param2);
}
| mit |
ev34j/ev34j | ev34j-mindstorms/src/main/java/com/ev34j/mindstorms/sensor/NxtUltrasonicSensor.java | 500 | package com.ev34j.mindstorms.sensor;
import com.ev34j.core.sensor.SensorPort;
import com.ev34j.core.sensor.SensorSetting;
import com.ev34j.core.sensor.UltrasonicSensor;
public class NxtUltrasonicSensor
extends AbstractUltrasonicSensor {
public NxtUltrasonicSensor(final int portNum) {
this("" + portNum);
}
public NxtUltrasonicSensor(final String portName) {
super((new UltrasonicSensor(NxtUltrasonicSensor.class, SensorPort.findByPort(portName), SensorSetting.NXT_US)));
}
}
| mit |
MX-Futhark/hook-any-text | src/main/java/hextostring/debug/DebuggableHexSelectionsContent.java | 3023 | package hextostring.debug;
import java.util.List;
import hexcapture.HexSelectionsContentSnapshot;
import hextostring.format.DecorableList;
/**
* Wraps the content of hex selections into an object containing the necessary
* information for debugging
*
* @author Maxime PIA
*/
public class DebuggableHexSelectionsContent implements DebuggableStrings,
DecorableList {
private HexSelectionsContentSnapshot snapshot;
private List<DebuggableStrings> orderedResults;
private String decorationBefore = "";
private String decorationBetween = "";
private String decorationAfter = "";
public DebuggableHexSelectionsContent(
HexSelectionsContentSnapshot snapshot,
List<DebuggableStrings> orderedResults) {
this.snapshot = snapshot;
this.orderedResults = orderedResults;
if (snapshot.getSize() != orderedResults.size()) {
throw new IllegalArgumentException("Incompatible sizes");
}
}
@Override
public void setDecorationBefore(String decorationBefore) {
this.decorationBefore = decorationBefore;
}
@Override
public void setDecorationBetween(String decorationBetween) {
this.decorationBetween = decorationBetween;
}
@Override
public void setDecorationAfter(String decorationAfter) {
this.decorationAfter = decorationAfter;
}
@Override
public void setLinesDecorations(String before, String after) {}
@Override
public DecorableList getDecorableList() {
return this;
}
@Override
public String toString(long debuggingFlags, int converterStrictness) {
StringBuilder sb = new StringBuilder();
int index = 0;
boolean selectionsBoundsFlagOn =
(debuggingFlags & DebuggingFlags.HEX_SELECTIONS_BOUNDS) > 0;
boolean selectionsContentFlagOn =
(debuggingFlags & DebuggingFlags.HEX_SELECTIONS_CONTENT) > 0;
boolean selectionDebuggingOn =
selectionsBoundsFlagOn || selectionsContentFlagOn;
sb.append(decorationBefore);
for (DebuggableStrings ds : orderedResults) {
if (selectionDebuggingOn) {
sb.append("[");
}
if (selectionsBoundsFlagOn) {
sb.append(
"#" + snapshot.getSelectionIdAt(index) +
(snapshot.getActiveSelectionIndex() == index
? " (active)"
: "") +
", from " +
formatToHexString(snapshot.getSelectionStartAt(index)) +
" to " +
formatToHexString(snapshot.getSelectionEndAt(index))
);
}
if (selectionsContentFlagOn) {
sb.append(
" (selected as: \"" + snapshot.getValueAt(index) + "\")"
);
}
if (selectionDebuggingOn) {
sb.append(":\n");
}
if (ds != null) {
sb.append(ds.toString(debuggingFlags, converterStrictness));
} else if (selectionDebuggingOn) {
sb.append("<null>");
}
if (selectionDebuggingOn) {
sb.append("]");
}
if (index != orderedResults.size() - 1) {
sb.append(decorationBetween);
}
++index;
}
sb.append(decorationAfter);
if (selectionDebuggingOn) {
sb.append("\n");
}
return sb.toString();
}
private String formatToHexString(Number n) {
return "0x" + String.format("%02X", n);
}
}
| mit |
RallySoftware/jarvis-core | src/main/java/com/rallydev/jarvis/Bot.java | 1334 | package com.rallydev.jarvis;
import clojure.lang.RT;
import clojure.lang.Symbol;
import clojure.lang.Var;
import groovy.lang.Closure;
import java.util.HashMap;
import java.util.Map;
public abstract class Bot {
public static void addPlugin(Object plugin, Map metadata) {
ADD_PLUGIN.invoke(plugin, metadata);
}
public static void addCommand(String commandName, String description, String author, final Closure callback) {
HashMap<String, String> map = new HashMap<String,String>();
map.put("command", commandName);
map.put("description", description);
map.put("author", author);
addPlugin(new GroovyCommand(callback, commandName), map);
}
private static final Var REQUIRE = RT.var("clojure.core", "require");
static {
REQUIRE.invoke(Symbol.intern("jarvis.plugins"));
}
private static final Var ADD_PLUGIN = RT.var("jarvis.plugins", "add-plugin");
private static class GroovyCommand implements Plugin {
private final Closure callback;
private final String command;
private GroovyCommand(Closure callback, String command) {
this.callback = callback;
this.command = command;
}
public Object invoke(Map message) {
return callback.call(message);
}
}
}
| mit |
SirGandal/Percolation | Percolation/src/PercolationQF.java | 3956 | import edu.princeton.cs.algs4.QuickUnionUF;
public class PercolationQF {
private int[][] directions = new int[][] { { 1, 0 }, // BOTTOM
{ -1, 0 }, // TOP
{ 0, -1 }, // LEFT
{ 0, 1 } // RIGHT
};
private int size;
private int[] grid;
// Main union find data structure used to determine if the system percolates
private QuickUnionUF ufMain;
// Support union find data structure used to discover if a site is full or not
// and avoid backwash.
private QuickUnionUF ufSupport;
public PercolationQF(int n) {
if (n <= 0) {
throw new java.lang.IllegalArgumentException();
}
this.size = n;
// add two virtual sites, one connected to all the elements of the top row,
// and one connected to all the ones at the bottom row.
ufMain = new QuickUnionUF((n * n) + 2);
// add one virtual site connected to all the elements of the top row.
ufSupport = new QuickUnionUF((n * n) + 1);
// connect top row sites to virtual top site
for (int i = 1; i < n + 1; i++) {
ufMain.union(i, 0);
ufSupport.union(i, 0);
}
// connect bottom row sites to virtual bottom site
for (int i = n * n; i > n * n - n; i--) {
ufMain.union(i, (n * n) + 1);
}
// create n-by-n grid, with all sites blocked
// No need to keep a multidimensional array
grid = new int[n * n];
// Initialize all to full
for (int i = 0; i < n * n; i++) {
grid[i] = 0;
}
}
// open site (row i, column j) if it is not open already
public void open(int i, int j) {
if (!isValidCoordinate(i, j)) {
throw new java.lang.IndexOutOfBoundsException();
}
int tmpi = i;
int tmpj = j;
if (isBlocked(i, j)) {
// it is indeed blocked, let's open it
grid[getIndex(i, j)] = 1;
for (int d = 0; d < directions.length; d++) {
i = tmpi + directions[d][0];
j = tmpj + directions[d][1];
// if a site in one of the allowed directions is open we can perform a
// connection
if (isValidCoordinate(i, j) && isOpen(i, j)) {
// shift by one because of the virtual top site
int siteA = getIndex(i, j) + 1;
int siteB = getIndex(tmpi, tmpj) + 1;
ufMain.union(siteA, siteB);
ufSupport.union(siteA, siteB);
}
}
}
}
// is site (row i, column j) open?
public boolean isOpen(int i, int j) {
if (isValidCoordinate(i, j)) {
return grid[getIndex(i, j)] == 1;
}
throw new java.lang.IndexOutOfBoundsException();
}
// is site (row i, column j) full?
public boolean isFull(int i, int j) {
if (isValidCoordinate(i, j)) {
if (isOpen(i, j)) {
// index is shifted by one due to the virtual top site
int index = getIndex(i, j) + 1;
if (index < size) {
// by definition an open site at the first row is full
return true;
}
return ufSupport.connected(index, 0);
}
} else {
throw new java.lang.IndexOutOfBoundsException();
}
return false;
}
// is site (row i, column j) blocked?
private boolean isBlocked(int i, int j) {
if (isValidCoordinate(i, j)) {
return grid[getIndex(i, j)] == 0;
}
return false;
}
// does the system percolate?
public boolean percolates() {
// we don't use the isFull definition
int virtualTop = 0;
int virtualBottom = size * size + 1;
// corner case: 1 site
if (virtualBottom == 2) {
return isOpen(1, 1);
}
// corner case: no sites
if (virtualBottom == 0) {
return false;
}
return ufMain.connected(virtualTop, virtualBottom);
}
// get single index from row and column
private int getIndex(int i, int j) {
return (i - 1) * size + (j - 1);
}
private boolean isValidCoordinate(int i, int j) {
if (i > 0 && i <= size && j > 0 && j <= size) {
return true;
}
return false;
}
} | mit |
mohitbnsl/BANSAL | jadler-core/src/main/java/net/jadler/matchers/ParameterRequestMatcher.java | 2285 | /*
* Copyright (c) 2013 Jadler contributors
* This program is made available under the terms of the MIT License.
*/
package net.jadler.matchers;
import java.util.List;
import net.jadler.Request;
import org.apache.commons.lang.Validate;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;
/**
* A {@link RequestMatcher} used for matching a request parameter.
*/
public class ParameterRequestMatcher extends RequestMatcher<List<String>> {
private final String paramName;
private final String desc;
/**
* Protected constructor useful only when subtyping. For creating instances of this class use
* {@link #requestParameter(java.lang.String, org.hamcrest.Matcher)} instead.
* @param pred a predicate to be applied on the given request parameter
* @param paramName name of a request parameter (case sensitive)
*/
public ParameterRequestMatcher(final Matcher<? super List<String>> pred, final String paramName) {
super(pred);
Validate.notEmpty(paramName, "paramName cannot be empty");
this.paramName = paramName;
this.desc = "parameter \"" + paramName + "\" is";
}
/**
* Retrieves a parameter (defined in {@link #ParameterRequestMatcher(org.hamcrest.Matcher, java.lang.String)})
* of the given request. The values are percent-encoded.
* @param req request to retrieve the parameter from
* @return the request parameter as a list of values or {@code null} if there is no such a parameter in the request
*/
@Override
protected List<String> retrieveValue(final Request req) {
return req.getParameters().getValues(this.paramName);
}
/**
* {@inheritDoc}
*/
@Override
protected String provideDescription() {
return this.desc;
}
/**
* Factory method to create new instance of this matcher.
* @param paramName name of a request parameter
* @param pred a predicate to be applied on the request parameter
* @return new instance of this matcher
*/
@Factory
public static ParameterRequestMatcher requestParameter(final String paramName,
final Matcher<? super List<String>> pred) {
return new ParameterRequestMatcher(pred, paramName);
}
} | mit |
emacslisp/Java | JavaN/src/javan/util/function/IntBinaryOperator.java | 944 | /*
* Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package javan.util.function;
/**
* Represents an operation upon two {@code int}-valued operands and producing an
* {@code int}-valued result. This is the primitive type specialization of
* {@link BinaryOperator} for {@code int}.
*
* <p>This is a <a href="package-summary.html">functional interface</a>
* whose functional method is {@link #applyAsInt(int, int)}.
*
* @see BinaryOperator
* @see IntUnaryOperator
* @since 1.8
*/
@FunctionalInterface
public interface IntBinaryOperator {
/**
* Applies this operator to the given operands.
*
* @param left the first operand
* @param right the second operand
* @return the operator result
*/
int applyAsInt(int left, int right);
}
| mit |
tcdl/msb-java | core/src/test/java/io/github/tcdl/msb/ProducerTest.java | 4788 | package io.github.tcdl.msb;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.typesafe.config.ConfigFactory;
import io.github.tcdl.msb.adapters.ProducerAdapter;
import io.github.tcdl.msb.api.Callback;
import io.github.tcdl.msb.api.exception.ChannelException;
import io.github.tcdl.msb.api.exception.JsonConversionException;
import io.github.tcdl.msb.api.message.Message;
import io.github.tcdl.msb.api.message.MetaMessage;
import io.github.tcdl.msb.api.message.Topics;
import io.github.tcdl.msb.api.message.payload.RestPayload;
import io.github.tcdl.msb.config.MsbConfig;
import io.github.tcdl.msb.support.TestUtils;
import io.github.tcdl.msb.support.Utils;
import org.apache.commons.lang3.StringUtils;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import java.time.Clock;
import java.util.HashMap;
import java.util.Map;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
/**
* Created by rdro on 4/28/2015.
*/
@RunWith(MockitoJUnitRunner.class)
public class ProducerTest {
private static final String TOPIC = "test:producer";
@Mock
private ProducerAdapter adapterMock;
@Mock
private Callback<Message> handlerMock;
private ObjectMapper messageMapper = TestUtils.createMessageMapper();
@Test(expected = NullPointerException.class)
public void testCreateConsumerProducerNullAdapter() {
new Producer(null, "testTopic", messageMapper);
}
@Test(expected = NullPointerException.class)
public void testCreateProducerNullTopic() {
new Producer(adapterMock, null, messageMapper);
}
@Test(expected = NullPointerException.class)
public void testCreateProducerNullMapper() {
new Producer(adapterMock, "testTopic", null);
}
@Test
public void testPublishWithDefaultRoutingKey() throws Exception {
Message originaMessage = TestUtils.createSimpleRequestMessage(TOPIC);
Producer producer = new Producer(adapterMock, TOPIC, messageMapper);
producer.publish(originaMessage);
verify(adapterMock).publish(anyString(), eq(StringUtils.EMPTY));
}
@Test(expected = ChannelException.class)
@SuppressWarnings("unchecked")
public void testPublishRawAdapterThrowChannelException() throws ChannelException {
Message originaMessage = TestUtils.createSimpleRequestMessage(TOPIC);
Mockito.doThrow(ChannelException.class).when(adapterMock).publish(anyString(), anyString());
Producer producer = new Producer(adapterMock, TOPIC, messageMapper);
producer.publish(originaMessage);
verify(handlerMock, never()).call(any(Message.class));
}
@Test(expected = JsonConversionException.class)
@Ignore("Need to create message that when parse to JSON will cause JsonProcessingException in Utils.toJson or use PowerMock")
@SuppressWarnings("unchecked")
public void testPublishThrowExceptionVerifyCallbackNotSetNotCalled() throws ChannelException {
Message brokenMessage = createBrokenRequestMessageWithAndTopicTo(TOPIC);
Producer producer = new Producer(adapterMock, TOPIC, messageMapper);
producer.publish(brokenMessage);
verify(adapterMock, never()).publish(anyString());
verify(handlerMock, never()).call(any(Message.class));
}
private Message createBrokenRequestMessageWithAndTopicTo(String topicTo) {
MsbConfig msbConf = new MsbConfig(ConfigFactory.load());
Clock clock = Clock.systemDefaultZone();
ObjectMapper payloadMapper = TestUtils.createMessageMapper();
Topics topic = new Topics(topicTo, topicTo + ":response:" + msbConf.getServiceDetails().getInstanceId(), null);
Map<String, String> body = new HashMap<>();
body.put("body", "{\\\"x\\\" : 3} garbage");
RestPayload<?, ?, ?, Map<String, String>> payload = new RestPayload.Builder<Object, Object, Object, Map<String, String>>()
.withBody(body)
.build();
JsonNode payloadNode = Utils.convert(payload, JsonNode.class, payloadMapper);
MetaMessage.Builder metaBuilder = new MetaMessage.Builder(null, clock.instant(), msbConf.getServiceDetails(), clock);
return new Message.Builder()
.withCorrelationId(Utils.generateId())
.withId(Utils.generateId())
.withTopics(topic)
.withMetaBuilder(metaBuilder)
.withPayload(payloadNode)
.build();
}
} | mit |
ianli-sc/website | study/node/hsfTest/messenger-common-1.3.3-sources/com/taobao/messenger/service/common/Period.java | 402 | package com.taobao.messenger.service.common;
/**
* Æ£ÀͶÈÖÜÆÚ
* @author huohu
* @since 1.0, 2009-5-7 ÏÂÎç05:30:35
*/
public enum Period {
/**
* Ìì
*/
ONEDAY(1),
/**
* ÖÜ£¨ÆßÌ죩
*/
ONEWEEK(7),
/**
* Ô£¨31Ì죩
*/
ONEMONTH(31);
private int value;
private Period(int value){
this.value = value;
}
public int getValue(){
return value;
}
}
| mit |
seratch/jslack | slack-api-client/src/main/java/com/slack/api/methods/response/admin/conversations/restrict_access/AdminConversationsRestrictAccessListGroupsResponse.java | 543 | package com.slack.api.methods.response.admin.conversations.restrict_access;
import com.slack.api.methods.SlackApiResponse;
import com.slack.api.model.ErrorResponseMetadata;
import lombok.Data;
import java.util.List;
@Data
public class AdminConversationsRestrictAccessListGroupsResponse implements SlackApiResponse {
private boolean ok;
private String warning;
private String error;
private String needed;
private String provided;
private List<String> groupIds;
private ErrorResponseMetadata responseMetadata;
} | mit |
MHS-FIRSTrobotics/TeamClutch-FTC2016 | I2cLibrary/src/main/java/org/ftccommunity/i2clibrary/interfaces/IBNO055IMU.java | 21574 | /*
* Copyright © 2016 David Sargent
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.ftccommunity.i2clibrary.interfaces;
import com.qualcomm.robotcore.eventloop.opmode.OpMode;
import com.qualcomm.robotcore.hardware.I2cDevice;
import org.ftccommunity.i2clibrary.ClassFactory;
import org.ftccommunity.i2clibrary.navigation.Acceleration;
import org.ftccommunity.i2clibrary.navigation.AngularVelocity;
import org.ftccommunity.i2clibrary.navigation.EulerAngles;
import org.ftccommunity.i2clibrary.navigation.MagneticFlux;
import org.ftccommunity.i2clibrary.navigation.Position;
import org.ftccommunity.i2clibrary.navigation.Quaternion;
import org.ftccommunity.i2clibrary.navigation.Velocity;
/**
* Interface API to the Adafruit 9-DOF Absolute Orientation IMU Fusion Breakout - BNO055 sensor. You
* can create an implementation of this interface for a given sensor using {@link
* ClassFactory#createAdaFruitBNO055IMU(OpMode, I2cDevice) ClassFactory.createAdaFruitBNO055IMU()}.
*
* @see IAccelerationIntegrator
* @see ClassFactory#createAdaFruitBNO055IMU(OpMode, I2cDevice)
* @see <a href="http://www.adafruit.com/products/2472">http://www.adafruit.com/products/2472</a>
* @see <a href="http://www.bosch-sensortec.com/en/homepage/products_3/9_axis_sensors_5/ecompass_2/bno055_3/bno055_4">http://www.bosch-sensortec.com/en/homepage/products_3/9_axis_sensors_5/ecompass_2/bno055_3/bno055_4</a>
*/
public interface IBNO055IMU {
//----------------------------------------------------------------------------------------------
// Construction
//----------------------------------------------------------------------------------------------
/**
* The size of the calibration data, starting at ACCEL_OFFSET_X_LSB, is 22 bytes.
*/
int cbCalibrationData = 22;
/**
* Initialize the sensor using the indicated set of parameters. Note that the execution of this
* method can take a fairly long while, possibly several tens of milliseconds.
*
* @param parameters the parameters with which to initialize the IMU
*/
void initialize(Parameters parameters);
/**
* Shut down the sensor. This doesn't do anything in the hardware device itself, but rather
* shuts down any resources (threads, etc) that we use to communicate with it.
*/
void close();
//----------------------------------------------------------------------------------------------
// Reading sensor output
//----------------------------------------------------------------------------------------------
/**
* Returns the current temperature. Units are as configured during initialization.
*
* @return the current temperature
*/
double getTemperature();
/**
* Returns the magnetic field strength experienced by the sensor. See Section 3.6.5.2 of the
* BNO055 specification.
*
* @return the magnetic field strength experienced by the sensor, in units of tesla
* @see <a href="https://en.wikipedia.org/wiki/Tesla_(unit)">https://en.wikipedia.org/wiki/Tesla_(unit)</a>
*/
MagneticFlux getMagneticFieldStrength();
/**
* Returns the overall acceleration experienced by the sensor. This is composed of a component
* due to the movement of the sensor and a component due to the force of gravity.
*
* @return the overall acceleration vector experienced by the sensor
*/
Acceleration getOverallAcceleration();
/**
* Returns the acceleration experienced by the sensor due to the movement of the sensor.
*
* @return the acceleration vector of the sensor due to its movement
*/
Acceleration getLinearAcceleration();
/**
* Returns the direction of the force of gravity relative to the sensor.
*
* @return the acceleration vector of gravity relative to the sensor
*/
Acceleration getGravity();
/**
* Returns the rate of change of the absolute orientation of the sensor.
*
* @return the rate at which the orientation of the sensor is changing.
* @see #getAngularOrientation()
*/
AngularVelocity getAngularVelocity();
/**
* Returns the absolute orientation of the sensor as a set of Euler angles.
*
* @return the absolute orientation of the sensor
* @see #getQuaternionOrientation()
*/
EulerAngles getAngularOrientation();
/**
* Returns the absolute orientation of the sensor as a quaternion.
*
* @return the absolute orientation of the sensor
* @see #getAngularOrientation()
*/
Quaternion getQuaternionOrientation();
//----------------------------------------------------------------------------------------------
// Position and velocity management
//----------------------------------------------------------------------------------------------
/**
* Returns the current position of the sensor as calculated by doubly integrating the observed
* sensor accelerations.
*
* @return the current position of the sensor.
*/
Position getPosition();
/**
* Returns the current velocity of the sensor as calculated by integrating the observed sensor
* accelerations.
*
* @return the current velocity of the sensor
*/
Velocity getVelocity();
/**
* Returns the last observed acceleration of the sensor. Note that this does not communicate
* with the sensor, but rather returns the most recent value reported to the acceleration
* integration algorithm.
*
* @return the last observed acceleration of the sensor
*/
Acceleration getAcceleration();
/**
* Start (or re-start) a thread that continuously at intervals polls the current linear
* acceleration of the sensor and integrates it to provide velocity and position information. A
* default polling interval of 100ms is used.
*
* @param initalPosition If non-null, the current sensor position is set to this value. If
* null, the current sensor position is unchanged.
* @param initialVelocity If non-null, the current sensor velocity is set to this value. If
* null, the current sensor velocity is unchanged.
* @see #startAccelerationIntegration(Position, Velocity)
* @see #getLinearAcceleration()
*/
void startAccelerationIntegration(Position initalPosition, Velocity initialVelocity);
/**
* As in {@link #startAccelerationIntegration(Position, Velocity)}, but provides control over
* the frequency which which the acceleration is polled.
*
* @param initalPosition If non-null, the current sensor position is set to this value. If
* null, the current sensor position is unchanged.
* @param initialVelocity If non-null, the current sensor velocity is set to this value. If
* null, the current sensor velocity is unchanged.
* @param msPollInterval the interval to use, in milliseconds, between successive calls to
* {@link #getLinearAcceleration()}
* @see #startAccelerationIntegration(Position, Velocity, int)
*/
void startAccelerationIntegration(Position initalPosition, Velocity initialVelocity, int msPollInterval);
/**
* Stop the integration thread if it is currently running.
*/
void stopAccelerationIntegration();
//----------------------------------------------------------------------------------------------
// Status inquiry
//----------------------------------------------------------------------------------------------
/**
* Returns the current status of the system.
*
* @return the current status of the system <p> See section 4.3.58 of the BNO055 specification.
* @see #getSystemError() <p> <table summary="System Status Codes">
* <tr><td>Result</td><td>Meaning</td></tr> <tr><td>0</td><td>idle</td></tr>
* <tr><td>1</td><td>system error</td></tr> <tr><td>2</td><td>initializing peripherals</td></tr>
* <tr><td>3</td><td>system initialization</td></tr> <tr><td>4</td><td>executing
* self-test</td></tr> <tr><td>5</td><td>sensor fusion algorithm running</td></tr>
* <tr><td>6</td><td>system running without fusion algorithms</td></tr> </table>
*/
byte getSystemStatus();
/**
* If {@link #getSystemStatus()} is 'system error' (1), returns particulars regarding that
* error. <p> See section 4.3.58 of the BNO055 specification.
*
* @return the current error status
* @see #getSystemStatus() <p> <table summary="System Error Codes">
* <tr><td>Result</td><td>Meaning</td></tr> <tr><td>0</td><td>no error</td></tr>
* <tr><td>1</td><td>peripheral initialization error</td></tr> <tr><td>2</td><td>system
* initialization error</td></tr> <tr><td>3</td><td>self test result failed</td></tr>
* <tr><td>4</td><td>register map value out of range</td></tr> <tr><td>5</td><td>register map
* address out of range</td></tr> <tr><td>6</td><td>register map write error</td></tr>
* <tr><td>7</td><td>BNO low power mode not available for selected operation mode</td></tr>
* <tr><td>8</td><td>acceleromoeter power mode not available</td></tr> <tr><td>9</td><td>fusion
* algorithm configuration error</td></tr> <tr><td>A</td><td>sensor configuraton error</td></tr>
* </table>
*/
byte getSystemError();
boolean isSystemCalibrated();
boolean isGyroCalibrated();
boolean isAccelerometerCalibrated();
boolean isMagnetometerCalibrated();
/**
* Read calibration data from the IMU which later can be restored with writeCalibrationData().
* This might be persistently stored, and reapplied at a later power-on. <p> For greatest
* utility, full calibration should be achieved before reading the calibration data
*
* @return the calibration data
* @see #writeCalibrationData(byte[])
*/
byte[] readCalibrationData();
/**
* Write calibration data previously retrieved.
*
* @param data the calibration data to write
* @see #readCalibrationData()
*/
void writeCalibrationData(byte[] data);
/**
* Low level: read the byte starting at the indicated register
*
* @param register the location from which to read the data
* @return the data that was read
*/
byte read8(REGISTER register);
//----------------------------------------------------------------------------------------------
// Low level reading and writing
//----------------------------------------------------------------------------------------------
/**
* Low level: read data starting at the indicated register
*
* @param register the location from which to read the data
* @param cb the number of bytes to read
* @return the data that was read
*/
byte[] read(REGISTER register, int cb);
/**
* Low level: write a byte to the indicated register
*
* @param register the location at which to write the data
* @param bVal the data to write
*/
void write8(REGISTER register, int bVal);
/**
* Low level: write data starting at the indicated register
*
* @param register the location at which to write the data
* @param data the data to write
*/
void write(REGISTER register, byte[] data);
enum I2CADDR {
UNSPECIFIED(-1), DEFAULT(0x28 * 2), ALTERNATE(0x29 * 2);
public final byte bVal;
I2CADDR(int i) {
bVal = (byte) i;
}
}
//----------------------------------------------------------------------------------------------
// Enumerations to make all of the above work
//----------------------------------------------------------------------------------------------
enum TEMPUNIT {
CELSIUS(0), FARENHEIT(1);
public final byte bVal;
TEMPUNIT(int i) {
bVal = (byte) i;
}
}
enum ANGLEUNIT {
DEGREES(0), RADIANS(1);
public final byte bVal;
ANGLEUNIT(int i) {
bVal = (byte) i;
}
}
enum ACCELUNIT {
METERS_PERSEC_PERSEC(0), MILLIGALS(1);
public final byte bVal;
ACCELUNIT(int i) {
bVal = (byte) i;
}
}
enum PITCHMODE {
WINDOWS(0), ANDROID(1);
public final byte bVal;
PITCHMODE(int i) {
bVal = (byte) i;
}
}
/**
* Sensor modes are described in Table 3-5 (p21) of the BNO055 specification, where they are
* termed "operation modes".
*/
enum SENSOR_MODE {
CONFIG(0X00), ACCONLY(0X01), MAGONLY(0X02),
GYRONLY(0X03), ACCMAG(0X04), ACCGYRO(0X05),
MAGGYRO(0X06), AMG(0X07), IMU(0X08),
COMPASS(0X09), M4G(0X0A), NDOF_FMC_OFF(0X0B),
NDOF(0X0C);
//------------------------------------------------------------------------------------------
public final byte bVal;
SENSOR_MODE(int i) {
this.bVal = (byte) i;
}
}
/**
* REGISTER provides symbolic names for each of the BNO055 device registers
*/
enum REGISTER {
/**
* Controls which of the two register pages are visible
*/
PAGE_ID(0X07),
CHIP_ID(0x00),
ACCEL_REV_ID(0x01),
MAG_REV_ID(0x02),
GYRO_REV_ID(0x03),
SW_REV_ID_LSB(0x04),
SW_REV_ID_MSB(0x05),
BL_REV_ID(0X06),
/**
* Acceleration data register
*/
ACCEL_DATA_X_LSB(0X08),
ACCEL_DATA_X_MSB(0X09),
ACCEL_DATA_Y_LSB(0X0A),
ACCEL_DATA_Y_MSB(0X0B),
ACCEL_DATA_Z_LSB(0X0C),
ACCEL_DATA_Z_MSB(0X0D),
/**
* Magnetometer data register
*/
MAG_DATA_X_LSB(0X0E),
MAG_DATA_X_MSB(0X0F),
MAG_DATA_Y_LSB(0X10),
MAG_DATA_Y_MSB(0X11),
MAG_DATA_Z_LSB(0X12),
MAG_DATA_Z_MSB(0X13),
/**
* Gyro data registers
*/
GYRO_DATA_X_LSB(0X14),
GYRO_DATA_X_MSB(0X15),
GYRO_DATA_Y_LSB(0X16),
GYRO_DATA_Y_MSB(0X17),
GYRO_DATA_Z_LSB(0X18),
GYRO_DATA_Z_MSB(0X19),
/**
* Euler data registers
*/
EULER_H_LSB(0X1A),
EULER_H_MSB(0X1B),
EULER_R_LSB(0X1C),
EULER_R_MSB(0X1D),
EULER_P_LSB(0X1E),
EULER_P_MSB(0X1F),
/**
* Quaternion data registers
*/
QUATERNION_DATA_W_LSB(0X20),
QUATERNION_DATA_W_MSB(0X21),
QUATERNION_DATA_X_LSB(0X22),
QUATERNION_DATA_X_MSB(0X23),
QUATERNION_DATA_Y_LSB(0X24),
QUATERNION_DATA_Y_MSB(0X25),
QUATERNION_DATA_Z_LSB(0X26),
QUATERNION_DATA_Z_MSB(0X27),
/**
* Linear acceleration data registers
*/
LINEAR_ACCEL_DATA_X_LSB(0X28),
LINEAR_ACCEL_DATA_X_MSB(0X29),
LINEAR_ACCEL_DATA_Y_LSB(0X2A),
LINEAR_ACCEL_DATA_Y_MSB(0X2B),
LINEAR_ACCEL_DATA_Z_LSB(0X2C),
LINEAR_ACCEL_DATA_Z_MSB(0X2D),
/**
* Gravity data registers
*/
GRAVITY_DATA_X_LSB(0X2E),
GRAVITY_DATA_X_MSB(0X2F),
GRAVITY_DATA_Y_LSB(0X30),
GRAVITY_DATA_Y_MSB(0X31),
GRAVITY_DATA_Z_LSB(0X32),
GRAVITY_DATA_Z_MSB(0X33),
/**
* Temperature data register
*/
TEMP(0X34),
/**
* Status registers
*/
CALIB_STAT(0X35),
SELFTEST_RESULT(0X36),
INTR_STAT(0X37),
SYS_CLK_STAT(0X38),
SYS_STAT(0X39),
SYS_ERR(0X3A),
/**
* Unit selection register
*/
UNIT_SEL(0X3B),
DATA_SELECT(0X3C),
/**
* Mode registers
*/
OPR_MODE(0X3D),
PWR_MODE(0X3E),
SYS_TRIGGER(0X3F),
TEMP_SOURCE(0X40),
/**
* Axis remap registers
*/
AXIS_MAP_CONFIG(0X41),
AXIS_MAP_SIGN(0X42),
/**
* SIC registers
*/
SIC_MATRIX_0_LSB(0X43),
SIC_MATRIX_0_MSB(0X44),
SIC_MATRIX_1_LSB(0X45),
SIC_MATRIX_1_MSB(0X46),
SIC_MATRIX_2_LSB(0X47),
SIC_MATRIX_2_MSB(0X48),
SIC_MATRIX_3_LSB(0X49),
SIC_MATRIX_3_MSB(0X4A),
SIC_MATRIX_4_LSB(0X4B),
SIC_MATRIX_4_MSB(0X4C),
SIC_MATRIX_5_LSB(0X4D),
SIC_MATRIX_5_MSB(0X4E),
SIC_MATRIX_6_LSB(0X4F),
SIC_MATRIX_6_MSB(0X50),
SIC_MATRIX_7_LSB(0X51),
SIC_MATRIX_7_MSB(0X52),
SIC_MATRIX_8_LSB(0X53),
SIC_MATRIX_8_MSB(0X54),
/**
* Accelerometer Offset registers
*/
ACCEL_OFFSET_X_LSB(0X55),
ACCEL_OFFSET_X_MSB(0X56),
ACCEL_OFFSET_Y_LSB(0X57),
ACCEL_OFFSET_Y_MSB(0X58),
ACCEL_OFFSET_Z_LSB(0X59),
ACCEL_OFFSET_Z_MSB(0X5A),
/**
* Magnetometer Offset registers
*/
MAG_OFFSET_X_LSB(0X5B),
MAG_OFFSET_X_MSB(0X5C),
MAG_OFFSET_Y_LSB(0X5D),
MAG_OFFSET_Y_MSB(0X5E),
MAG_OFFSET_Z_LSB(0X5F),
MAG_OFFSET_Z_MSB(0X60),
/**
* Gyroscope Offset register s
*/
GYRO_OFFSET_X_LSB(0X61),
GYRO_OFFSET_X_MSB(0X62),
GYRO_OFFSET_Y_LSB(0X63),
GYRO_OFFSET_Y_MSB(0X64),
GYRO_OFFSET_Z_LSB(0X65),
GYRO_OFFSET_Z_MSB(0X66),
/**
* Radius registers
*/
ACCEL_RADIUS_LSB(0X67),
ACCEL_RADIUS_MSB(0X68),
MAG_RADIUS_LSB(0X69),
MAG_RADIUS_MSB(0X6A);
//------------------------------------------------------------------------------------------
public final byte bVal;
REGISTER(int i) {
this.bVal = (byte) i;
}
}
/**
* Instances of Parameters contain data indicating how a BNO055 absolute orientation sensor is
* to be initialized.
*
* @see #initialize(Parameters)
*/
class Parameters {
/**
* the address at which the sensor resides on the I2C bus.
*/
public I2CADDR i2cAddr8Bit = I2CADDR.DEFAULT;
/**
* the mode we wish to use the sensor in
*/
public SENSOR_MODE mode = SENSOR_MODE.IMU;
/**
* whether to use the external or internal 32.768khz crystal. External crystal use is
* recommended by the BNO055 specification.
*/
public boolean useExternalCrystal = true;
/**
* units in which temperature are measured. See Section 3.6.1 (p31) of the BNO055
* specification
*/
public TEMPUNIT temperatureUnit = TEMPUNIT.CELSIUS;
/**
* units in which angles and angular rates are measured. See Section 3.6.1 (p31) of the
* BNO055 specification
*/
public ANGLEUNIT angleunit = ANGLEUNIT.RADIANS;
/**
* units in which accelerations are measured. See Section 3.6.1 (p31) of the BNO055
* specification
*/
public ACCELUNIT accelunit = ACCELUNIT.METERS_PERSEC_PERSEC;
/**
* directional convention for measureing pitch angles. See Section 3.6.1 (p31) of the BNO055
* specification
*/
public PITCHMODE pitchmode = PITCHMODE.ANDROID; // Section 3.6.2
/**
* calibration data with which the BNO055 should be initialized
*/
public byte[] calibrationData = null;
/**
* the algorithm to use for integrating acceleration to produce velocity and position. If
* not specified, a simple but not especially effective internal algorithm will be used.
*/
public IAccelerationIntegrator accelerationIntegrationAlgorithm = null;
/**
* the boost in thread priority to use for data acquisition. A small increase in the thread
* priority can help reduce timestamping jitter and improve acceleration integration at only
* a small detriment to other parts of the system.
*/
public int threadPriorityBoost = 0;
/**
* debugging aid: enable logging for this device?
*/
public boolean loggingEnabled = false;
/**
* debugging aid: the logging tag to use when logging
*/
public String loggingTag = "AdaFruitIMU";
}
}
| mit |
McMasterGo/MacGo_Android | app/src/main/java/com/example/MacGo/Item.java | 1892 | package com.example.MacGo;
import com.parse.Parse;
import com.parse.ParseObject;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
/**
* Created by KD on 1/12/2015.
*/
public class Item {
String itemId;
String itemName;
Number itemPrice;
int calories;
Number itemQuantity;
private static ParseObject category;
public final String getItemId() {
return itemId;
}
public Number getPurchaseItemQuantity() {
return itemQuantity;
}
public final String getItemName() {
return itemName;
}
public final Number getItemPrice() {
return itemPrice;
}
public final int getItemCalories() {
return calories;
}
public final ParseObject getItemCategory() {
return category;
}
public static String covertDataFormat(Date date, String format) {
String formatDate = "00 MMMMM YYYY";
Format sdf = new SimpleDateFormat(format, Locale.US);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int hours = calendar.get(Calendar.HOUR);
if (calendar.get(Calendar.AM_PM) == Calendar.PM) {
formatDate = sdf.format(date).toString() + " @"+hours+"pm";
}
else {
formatDate = sdf.format(date).toString() + " @"+hours+"am";
}
return formatDate;
}
public Item(String itemId, String itemName, Number itemPrice,
int calories, Number itemQuantity,ParseObject category) {
this.itemId = itemId;
this.itemName = itemName;
this.itemPrice = itemPrice;
this.itemQuantity = itemQuantity;
this.calories = calories;
this.category = category;
}
}
| mit |
morgano5/mail_web_client | src/main/java/au/id/villar/email/webClient/users/UserDao.java | 214 | package au.id.villar.email.webClient.users;
public interface UserDao {
User find(String username);
User find(int id);
User create(String username, String password);
void remove(int userId);
}
| mit |
Faos7/ekey_backend_java | src/main/java/com/ekey/service/impl/TransactionServiceImpl.java | 2722 | package com.ekey.service.impl;
import com.ekey.repository.BooksRepository;
import com.ekey.repository.UserRepository;
import com.ekey.models.Book;
import com.ekey.models.Transaction;
import com.ekey.models.User;
import com.ekey.models.out.UserOut;
import com.ekey.service.TransactionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Collection;
/**
* Created by faos7 on 12.11.16.
*/
@Service
public class TransactionServiceImpl implements TransactionService {
private static final Logger LOGGER = LoggerFactory.getLogger(TransactionServiceImpl.class);
private UserRepository userRepository;
private BooksRepository booksRepository;
@Autowired
public TransactionServiceImpl(UserRepository userRepository, BooksRepository booksRepository) {
this.userRepository = userRepository;
this.booksRepository = booksRepository;
}
@Override
public Collection<Book> getAllBooksStudentEverHad(Long studentCardId) {
User user = userRepository.findOneByStudentCardId(studentCardId);
Collection<Transaction> transactions = user.getStTransactions();
Collection<Book> res = new ArrayList<>();
for (Transaction tx:transactions) {
res.add(tx.getBook());
}
return res;
}
@Override
public Collection<Book> getAllBooksLibrarianEverGiven(Long studentCardId) {
User user = userRepository.findOneByStudentCardId(studentCardId);
Collection<Transaction> transactions = user.getLbTransactions();
Collection<Book> res = new ArrayList<>();
for (Transaction tx:transactions) {
res.add(tx.getBook());
}
return res;
}
@Override
public Collection<UserOut> getAllBookOwners(String number) {
Book book = booksRepository.findOneByNumber(number).get();
Collection<Transaction> transactions = book.getTransactions();
Collection<UserOut> res = new ArrayList<>();
for (Transaction tx:transactions) {
res.add(new UserOut(tx.getStudent()));
}
return res;
}
@Override
public Transaction getTransactionByBookAndStudent(User student, Book book) {
Collection<Transaction> transactions = student.getStTransactions();
Transaction tx = new Transaction();
for (Transaction transaction:transactions) {
if (tx.isFinished() == false){
if (transaction.getBook() == book){
tx = transaction;
}
}
}
return tx;
}
}
| mit |
petuhovskiy/task-packager | src/main/java/com/petukhovsky/tpack/task/judge/JudgeTestInfo.java | 1002 | package com.petukhovsky.tpack.task.judge;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.petukhovsky.jvaluer.commons.checker.CheckResult;
import com.petukhovsky.jvaluer.commons.run.InvocationResult;
import com.petukhovsky.tpack.task.tests.Test;
/**
* Created by arthur on 21.10.16.
*/
public class JudgeTestInfo {
private final Test test;
private final InvocationResult result;
private final CheckResult check;
@JsonCreator
public JudgeTestInfo(@JsonProperty("test") Test test,
@JsonProperty("result") InvocationResult result,
@JsonProperty("check") CheckResult check) {
this.test = test;
this.result = result;
this.check = check;
}
public Test getTest() {
return test;
}
public InvocationResult getResult() {
return result;
}
public CheckResult getCheck() {
return check;
}
}
| mit |
Lab603/PicEncyclopedias | app/src/main/java/com/lab603/picencyclopedias/SplashActivity.java | 2001 | package com.lab603.picencyclopedias;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import com.lab603.picencyclopedias.MainActivity;
import com.lab603.picencyclopedias.R;
/**
* Created by FutureApe on 2017/9/26.
*/
public class SplashActivity extends Activity {
private final int SPLASH_DISPLAY_LENGTH = 3000;
private Handler hander;
private TextView textView;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// getWindow().requestFeature(Window.FEATURE_NO_TITLE);
//透明状态栏
// getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
Window window = getWindow();
//定义全屏参数
int flag = WindowManager.LayoutParams.FLAG_FULLSCREEN;
//设置当前窗体为全屏显示
window.setFlags(flag, flag);
setContentView(R.layout.activity_splash);
textView = (TextView)findViewById(R.id.textView2);
textView.setText("<Picencyclopedias/>");
hander = new Handler();
//延迟SPLASH_DISPLAY_LENGTH时间然后跳转到MainActivity
hander.postDelayed(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(SplashActivity.this,MainActivity.class);
startActivity(intent);
SplashActivity.this.finish();
}
},SPLASH_DISPLAY_LENGTH);
}
/**
* 禁用返回键
* @param keyCode
* @param event
* @return
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK)
return true;
return super.onKeyDown(keyCode, event);
}
}
| mit |
jsquared21/Intro-to-Java-Programming | Exercise_11/Exercise_11_13/Exercise_11_13.java | 1749 | /*********************************************************************************
* (Remove duplicates) Write a method that removes the duplicate elements from *
* an array list of integers using the following header: *
* *
* public static void removeDuplicate(ArrayList<Integer> list) *
* *
* Write a test program that prompts the user to enter 10 integers to a list and *
* displays the distinct integers separated by exactly one space. *
*********************************************************************************/
import java.util.Scanner;
import java.util.ArrayList;
public class Exercise_11_13 {
/** Main method */
public static void main(String[] args) {
// Create a scanner
Scanner input = new Scanner(System.in);
// Create an ArrayList
ArrayList<Integer> list = new ArrayList<Integer>();
// Prompt ther user to enter 10 integers
System.out.print("Enter 10 integers: ");
for (int i = 0; i < 10; i++) {
list.add(input.nextInt());
}
// Invoke removeDuplicate method
removeDuplicate(list);
// Display the distinct integers
System.out.print("The distinct integers are ");
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i) + " ");
}
System.out.println();
}
/** Removes the duplicate elements from an array list of integers */
public static void removeDuplicate(ArrayList<Integer> list) {
for (int i = 0; i < list.size() - 1; i++) {
for (int j = i + 1; j < list.size(); j++) {
if (list.get(i) == list.get(j))
list.remove(j);
}
}
}
} | mit |
jenkinsci/testcomplete-plugin | src/main/java/com/smartbear/jenkins/plugins/testcomplete/TcSummaryAction.java | 3844 | /*
* The MIT License
*
* Copyright (c) 2015, SmartBear Software
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.smartbear.jenkins.plugins.testcomplete;
import hudson.model.Action;
import hudson.model.Api;
import hudson.model.Run;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import java.io.File;
import java.util.*;
/**
* @author Igor Filin
*/
@ExportedBean
public class TcSummaryAction implements Action {
private final Run<?, ?> build;
private LinkedHashMap<String, TcReportAction> reports = new LinkedHashMap<>();
private ArrayList<TcReportAction> reportsOrder = new ArrayList<>();
private final TcDynamicReportAction dynamic;
TcSummaryAction(Run<?, ?> build) {
this.build = build;
String buildDir = build.getRootDir().getAbsolutePath();
String reportsPath = buildDir + File.separator + Constants.REPORTS_DIRECTORY_NAME + File.separator;
dynamic = new TcDynamicReportAction(reportsPath);
}
public String getIconFileName() {
return "/plugin/" + Constants.PLUGIN_NAME + "/images/tc-48x48.png";
}
public String getDisplayName() {
return Messages.TcSummaryAction_DisplayName();
}
public String getUrlName() {
return Constants.PLUGIN_NAME;
}
public Run<?, ?> getBuild() {
return build;
}
public void addReport(TcReportAction report) {
if (!reports.containsValue(report)) {
report.setParent(this);
reports.put(report.getId(), report);
reportsOrder.add(report);
}
}
@Exported(name="reports", inline = true)
public ArrayList<TcReportAction> getReportsOrder() {
return reportsOrder;
}
public HashMap<String, TcReportAction> getReports() {
return reports;
}
@SuppressWarnings("unused")
public TcReportAction getNextReport(TcReportAction report) {
if (report == null || !reportsOrder.contains(report)) {
return null;
}
int index = reportsOrder.indexOf(report);
if (index + 1 >= reportsOrder.size()) {
return null;
}
return reportsOrder.get(index + 1);
}
@SuppressWarnings("unused")
public TcReportAction getPreviousReport(TcReportAction report) {
if (report == null || !reportsOrder.contains(report)) {
return null;
}
int index = reportsOrder.indexOf(report);
if (index <= 0) {
return null;
}
return reportsOrder.get(index - 1);
}
public TcDynamicReportAction getDynamic() {
return dynamic;
}
public String getPluginName() {
return Constants.PLUGIN_NAME;
}
public Api getApi() {
return new Api(this);
}
} | mit |
datetimeformat/datetimeformat-java | src/test/java/com/gh/datetimeformat/DateTimeControllerIT.java | 1255 | package com.gh.datetimeformat;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import java.net.URL;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.embedded.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class DateTimeControllerIT {
@LocalServerPort
private int port;
private URL base;
@Autowired
private TestRestTemplate template;
@Before
public void setUp() throws Exception {
this.base = new URL("http://localhost:" + port + "/");
}
@Ignore
@Test
public void getHello() throws Exception {
ResponseEntity<String> response = template.getForEntity(base.toString(), String.class);
assertThat(response.getBody(), equalTo("Greetings from Spring Boot!"));
}
} | mit |
synapticloop/linode-api | src/main/java/synapticloop/linode/api/response/AvailDatacentersResponse.java | 3584 | package synapticloop.linode.api.response;
/*
* Copyright (c) 2016-2017 Synapticloop.
*
* All rights reserved.
*
* This code may contain contributions from other parties which, where
* applicable, will be listed in the default build file for the project
* ~and/or~ in a file named CONTRIBUTORS.txt in the root of the project.
*
* This source code and any derived binaries are covered by the terms and
* conditions of the Licence agreement ("the Licence"). You may not use this
* source code or any derived binaries except in compliance with the Licence.
* A copy of the Licence is available in the file named LICENSE.txt shipped with
* this source code or binaries.
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import synapticloop.linode.api.helper.ResponseHelper;
import synapticloop.linode.api.response.bean.Datacenter;
public class AvailDatacentersResponse extends BaseResponse {
private static final Logger LOGGER = LoggerFactory.getLogger(AvailDatacentersResponse.class);
private List<Datacenter> datacenters = new ArrayList<Datacenter>();
private Map<Long, Datacenter> datacenterIdLookup = new HashMap<Long, Datacenter>();
private Map<String, Datacenter> datacenterAbbreviationLookup = new HashMap<String, Datacenter>();
/**
*
* The json should have been formed by the following:
*
* <pre>
* {
* "ERRORARRAY":[],
* "ACTION":"avail.datacenters",
* "DATA":[
* {
* "DATACENTERID":2,
* "LOCATION":"Dallas, TX, USA",
* "ABBR":"dallas"
* },
* {
* "DATACENTERID":3,
* "LOCATION":"Fremont, CA, USA",
* "ABBR":"fremont"
* },
* {
* "DATACENTERID":4,
* "LOCATION":"Atlanta, GA, USA",
* "ABBR":"atlanta"
* },
* {
* "DATACENTERID":6,
* "LOCATION":"Newark, NJ, USA",
* "ABBR":"newark"
* },
* {
* "DATACENTERID":7,
* "LOCATION":"London, England, UK",
* "ABBR":"london"
* },
* {
* "DATACENTERID":8,
* "LOCATION":"Tokyo, JP",
* "ABBR":"tokyo"
* },
* {
* "DATACENTERID":9,
* "LOCATION":"Singapore, SG",
* "ABBR":"singapore"
* },
* {
* "DATACENTERID":10,
* "LOCATION":"Frankfurt, DE",
* "ABBR":"frankfurt"
* }
* ]
* }
* </pre>
*
* @param jsonObject the json object to parse
*/
public AvailDatacentersResponse(JSONObject jsonObject) {
super(jsonObject);
if(!hasErrors()) {
JSONArray dataArray = jsonObject.getJSONArray(JSON_KEY_DATA);
for (Object datacentreObject : dataArray) {
Datacenter datacenter = new Datacenter((JSONObject)datacentreObject);
datacenters.add(datacenter);
datacenterIdLookup.put(datacenter.getDatacenterId(), datacenter);
datacenterAbbreviationLookup.put(datacenter.getAbbreviation(), datacenter);
}
}
jsonObject.remove(JSON_KEY_DATA);
ResponseHelper.warnOnMissedKeys(LOGGER, jsonObject);
}
public List<Datacenter> getDatacenters() {
return(datacenters);
}
public Datacenter getDatacenterById(Long id) {
return(datacenterIdLookup.get(id));
}
public Datacenter getDatacenterByAbbreviation(String abbreviation) {
return(datacenterAbbreviationLookup.get(abbreviation));
}
}
| mit |
NikitaKozlov/Pury | example/src/main/java/com/nikitakozlov/pury_example/profilers/StartApp.java | 1006 | package com.nikitakozlov.pury_example.profilers;
public final class StartApp {
public static final String PROFILER_NAME = "App Start";
public static final String TOP_STAGE ="App Start";
public static final int TOP_STAGE_ORDER = 0;
public static final String SPLASH_SCREEN = "Splash Screen";
public static final int SPLASH_SCREEN_ORDER = TOP_STAGE_ORDER + 1;
public static final String SPLASH_LOAD_DATA = "Splash Load Data";
public static final int SPLASH_LOAD_DATA_ORDER = SPLASH_SCREEN_ORDER + 1;
public static final String MAIN_ACTIVITY_LAUNCH = "Main Activity Launch";
public static final int MAIN_ACTIVITY_LAUNCH_ORDER = SPLASH_SCREEN_ORDER + 1;
public static final String MAIN_ACTIVITY_CREATE = "onCreate()";
public static final int MAIN_ACTIVITY_CREATE_ORDER = MAIN_ACTIVITY_LAUNCH_ORDER + 1;
public static final String MAIN_ACTIVITY_START = "onStart()";
public static final int MAIN_ACTIVITY_START_ORDER = MAIN_ACTIVITY_LAUNCH_ORDER + 1;
}
| mit |
piperchester/petrichor | src/petrichor/Petrichor.java | 1021 | package petrichor;
import behavior.Aggressive;
import behavior.Behavior;
import robocode.*;
import java.awt.Color;
/**
* Petrichor - a robot by Piper Chester and Michael Timbrook
*/
public class Petrichor extends AdvancedRobot
{
private Behavior active;
/**
* Petrichor's default behavior. Initialization of robot occurs here.
*/
public void run() {
setColors(Color.blue, Color.cyan, Color.green); // Body, gun, radar
// Set behavior
active = new Aggressive(this);
// Sit in the behaviors run loop
while (active.runLoop());
}
/**
* What to do when you see another robot.
*/
public void onScannedRobot(ScannedRobotEvent e) {
active.onScannedRobot(e);
}
/**
* What to do when you're hit by a bullet.
*/
public void onHitByBullet(HitByBulletEvent e) {
active.onHitByBullet(e);
}
/**
* onHitWall: What to do when you hit a wall
*/
public void onHitWall(HitWallEvent e) {
active.onHitWall(e);
}
}
| mit |