text
stringlengths 10
2.72M
|
|---|
package kafka;//package kafka;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;
import java.util.Properties;
public class ConsumerKafkaByFlink {
public static void main(String[] args) throws Exception {
// StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(new Configuration());
//设置checkpoint时间
// env.enableCheckpointing(30000);
//设置时间语义
env.setStreamTimeCharacteristic(TimeCharacteristic.ProcessingTime);
//设置容错模式 默认
// env.getCheckpointConfig().setCheckpointingMode(CheckpointingMode.EXACTLY_ONCE);
// //设置重启策略
// env.setRestartStrategy(RestartStrategies.noRestart());
// //设置checkpoint保存地址
// env.setStateBackend(new FsStateBackend("hdfs://localhost:9000/fink/checkpoints"));
// //设置checkpoint的完成时间,超时则抛弃
// env.getCheckpointConfig().setCheckpointTimeout(500);
// //同一时间只能设置一个检查点
// env.getCheckpointConfig().setMaxConcurrentCheckpoints(1);
Properties pro = new Properties();
pro.setProperty("bootstrap.servers","10.0.12.254:18108");
pro.setProperty("zookeeper.connect","10.0.12.254:18127");
//flink1.11.1
//DataStreamSource<String> data = env.addSource(new FlinkKafkaConsumer011<String>("topic-test", new SimpleStringSchema(), pro));
//flink1.12.1
DataStreamSource<String> data = env.addSource(new FlinkKafkaConsumer<String>("r_source01", new SimpleStringSchema(), pro));
data.print();
env.execute("this is kafka_test");
}
}
|
package controller.command.impl;
import controller.command.Command;
import controller.constants.FrontConstants;
import controller.exception.ServiceLayerException;
import controller.service.DriverService;
import controller.service.ServiceFactory;
import controller.service.impl.ServiceFactoryImpl;
import controller.constants.PathJSP;
import domain.Driver;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class EditDriverCommand implements Command {
private ServiceFactory serviceFactory;
private DriverService driverService;
public EditDriverCommand() {
serviceFactory = ServiceFactoryImpl.getInstance();
driverService = serviceFactory.getDriverService();
}
@Override
public String execute(HttpServletRequest request, HttpServletResponse response) throws ServiceLayerException {
Integer idDriver = Integer.valueOf(request.getParameter(FrontConstants.DRIVER_ID));
Driver driver = driverService.getElementById(idDriver);
request.setAttribute(FrontConstants.DRIVER, driver);
return PathJSP.ADD_EDIT_DRIVER_PAGE;
}
}
|
package com.study.jpa.repository;
import com.study.jpa.entity.Parent;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* Created by francis on 2015. 12. 1..
*/
public interface ParentRepository extends JpaRepository<Parent, Long> {
}
|
package top.skyzc.juke.model;
public class ExamineRv {
private String username;
private String phoneNumber;
private String level;
private int imageUrl;
public ExamineRv(String username, String phoneNumber, String level, int imageUrl) {
this.username = username;
this.phoneNumber = phoneNumber;
this.level = level;
this.imageUrl = imageUrl;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
public int getImageUrl() {
return imageUrl;
}
public void setImageUrl(int imageUrl) {
this.imageUrl = imageUrl;
}
}
|
package com.fabio.dropbox.ftp;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.NoArgsConstructor;
import org.apache.commons.net.ftp.FTPClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.io.IOException;
@Service
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class FtpConnection {
private final Logger logger = LoggerFactory.getLogger(FtpConnection.class);
private String host = "ftp-server";
private String user = "java";
private String password = "abc123";
private FTPClient client;
public FTPClient createConnection() {
client = new FTPClient();
try {
client.connect(host);
client.login(user, password);
} catch (IOException e) {
logger.error(e.getMessage());
}
return this.client;
}
public void closeConnection() {
try {
client.disconnect();
} catch (IOException e) {
logger.error(e.getMessage());
}
}
}
|
package com.silver.mynews.api;
public interface Constants {
String BASE_URL = "https://newsapi.org/v2/";
String API_KEY = "YOUR_NEWS_API_API_KEY";
int DEFAULT_PAGE_SIZE = 20;
String NATIVE_AD_PLACEMENT_ID = "YOUR_NATIVE_AD_PLACEMENT_ID";
String INTERSTITIAL_AD_PLACEMENT_ID = "YOUR_INTERSTITIAL_AD_PLACEMENT_ID";
String BANNER_AD_PLACEMENT_ID = "YOUR_BANNER_AD_PLACEMENT_ID";
int NUM_ADS = 5;
}
|
package com.jp.photo.mapper;
import java.util.List;
import org.springframework.stereotype.Component;
import com.jp.photo.po.PhotoPo;
@Component("photoMapper")
public interface PhotoMapper {
public int addPhotoPo(PhotoPo po);
public int deletePhotoPoById(PhotoPo po);
public List<PhotoPo> getPhotoCretaeTimePageByAlbum_id(PhotoPo po);
public List<PhotoPo> getPhotoPoListByAlbum_idAndCreateTime(PhotoPo po);
public PhotoPo getPhotoPoById(PhotoPo po);
public int deletePhotoPoByAlbum_id(PhotoPo po);
}
|
package gdut.ff.utils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONObject;
import gdut.ff.domain.Ip;
@Service
public class IpUtil {
@Value("${api.mob.key}")
private String mobKey;
@Value("${api.mob.ip.address}")
private String mobIpAddress;
@Value("${api.mob.ip.method}")
private String mobIpMethod;
/**
* 查询的IP地址
* @param queryIpAddress
*/
public Ip queryIpDetail(String queryIpAddress) {
//http://apicloud.mob.com/ip/query?key=appkey&ip=222.73.199.34
String requestUrl = mobIpAddress + "?key=" + mobKey + "&ip="+queryIpAddress;
String result = HttpUtil.httpRequest(requestUrl);
JSONObject data = (JSONObject) JSONObject.parse(result);
String retCode = data.getString("retCode");
if("200".equals(retCode)) {
JSONObject detail = data.getJSONObject("result");
Ip ip = JSONObject.toJavaObject(detail, Ip.class);
return ip;
}
return null;
}
}
|
package com.pduleba.configuration;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.apache.commons.dbcp2.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.hibernate5.SpringSessionContext;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.support.SharedEntityManagerBean;
import org.springframework.orm.jpa.vendor.HibernateJpaSessionFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.pduleba.jpa.model.CarModel;
import com.pduleba.spring.data.SpringMarker;
import com.pduleba.spring.data.dao.SpringDataJpaMarker;
@Configuration
@ComponentScan(basePackageClasses=SpringMarker.class)
@EnableJpaRepositories(basePackageClasses = SpringDataJpaMarker.class)
@PropertySource("classpath:/config/application.properties")
@EnableTransactionManagement
public class SpringConfiguration implements ApplicationPropertiesConfiguration {
@Autowired
private Environment env;
@Bean // Trick (see doc of @PropertySource for more)
public static PropertySourcesPlaceholderConfigurer properties(Environment environment) {
PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
propertySourcesPlaceholderConfigurer.setEnvironment(environment);
return propertySourcesPlaceholderConfigurer;
}
@Bean DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(env.getProperty(KEY_DATASOURCE_DRIVER_CLASS));
dataSource.setUrl(env.getProperty(KEY_DATASOURCE_URL));
dataSource.setUsername(env.getProperty(KEY_DATASOURCE_USERNAME));
dataSource.setPassword(env.getProperty(KEY_DATASOURCE_PASSWORD));
return dataSource;
}
// EntityManagerFactory by dataSource
@Bean LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) throws IOException {
LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
entityManagerFactory.setDataSource(dataSource);
entityManagerFactory.setPackagesToScan(CarModel.class.getPackage().getName());
entityManagerFactory.setJpaProperties(getHibernateProperties());
entityManagerFactory.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
return entityManagerFactory;
}
// SessionFactory by EntityManagerFactory
@Bean public HibernateJpaSessionFactoryBean getSessionFactory(EntityManagerFactory emf) {
HibernateJpaSessionFactoryBean factory = new HibernateJpaSessionFactoryBean();
factory.setEntityManagerFactory(emf);
return factory;
}
// EntityManager by EntityMangerFactory
@Bean SharedEntityManagerBean entityManager(EntityManagerFactory emf) {
SharedEntityManagerBean entityManager = new SharedEntityManagerBean();
entityManager.setEntityManagerFactory(emf);
return entityManager;
}
// TransactionManager by EntityManagerFactory
@Bean PlatformTransactionManager transactionManager(EntityManagerFactory emf, DataSource dataSource) {
JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
jpaTransactionManager.setEntityManagerFactory(emf);
jpaTransactionManager.setDataSource(dataSource);
return jpaTransactionManager;
}
private Properties getHibernateProperties() throws IOException {
Properties prop = new Properties();
Resource resource = new ClassPathResource(env.getProperty(KEY_HIBERNATE_PROPERTIES_LOCATION));
if (resource.isReadable()) {
prop.load(resource.getInputStream());
// TRICK !!!
prop.put("hibernate.current_session_context_class", SpringSessionContext.class.getName());
} else {
throw new IllegalStateException(MessageFormat.format("{0} not readable", resource.getFilename()));
}
return prop;
}
}
|
package lame.data;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class IdentityBlockCodec implements BlockCodec {
@Override
public int encode(byte[] block, OutputStream output) throws IOException {
output.write(block);
return block.length;
}
@Override
public InputStream decode(InputStream input, int blockLength) throws IOException {
byte[] block = new byte[blockLength];
int bytesRead = input.read(block, 0, blockLength);
if (bytesRead != blockLength) {
throw new RuntimeException("Error reading block");
}
return new ByteArrayInputStream(block);
}
}
|
package assemAssist.model.scheduler.comparators;
import java.util.Comparator;
import assemAssist.model.order.order.Order;
/**
* The comparator which sorts the given {@link Order} according to a First Come
* First Served (FCFS) principle. The ordering is based on the ordered date,
* which must be effective.
*
* @author SWOP Group 3
* @version 2.0
*/
public final class OrderedDateComparator<T extends Order> implements
Comparator<T> {
/**
* {@inheritDoc}
*
* @pre The date of the Process is already set
*/
@Override
public int compare(Order o1, Order o2) {
if (o1 == null) {
if (o2 == null) {
return 0;
}
else {
return 1;
}
}
if (o2 == null) {
return -1;
}
if (o1.getAddedDate().isBefore(o2.getAddedDate())) {
return 1;
}
else if (o1.getAddedDate().isAfter(o2.getAddedDate())) {
return -1;
}
return 0;
}
}
|
package com.lin.paper.service;
import java.util.List;
import org.springframework.http.ResponseEntity;
import com.github.pagehelper.PageInfo;
import com.lin.paper.bean.UploadNotice;
import com.lin.paper.pojo.PNotice;
/**
* 公告信息业务逻辑接口
* @
* @date 2018年1月18日下午5:08:12
* @version 1.0
*/
public interface NoticeService {
/**
* 根据栏目ID查询前几条数据
* @param columnname
* @param i
* @return
*/
List<PNotice> getFaceNoticeByColumn(String columnid);
/**
* 后台分页查询公告列表
* @param page
* @return
*/
PageInfo<PNotice> getNoticeList(Integer page);
/**
* 尽可能同步上传的文件,返回存储数据对象
* @param uploadNotice
* @param path
* @return
*/
PNotice uploadFile(UploadNotice uploadNotice, String path);
/**
* 保存公告信息
* @param notice
*/
void saveNotice(PNotice notice);
/**
* 根据ID删除公告信息
* @param noticeid
*/
void deleteNoticeById(String noticeid);
/**
* 根据ID查询公告信息
* @param noticeid
* @return
*/
PNotice getNoticeById(String noticeid);
/**
* 更新公告信息
* @param notice
*/
void updateNotice(PNotice notice);
/**
* 根据栏目ID查询所有未删除公告信息
* @param columnid
* @return
*/
List<PNotice> getAllNoticeByColumn(String columnid);
/**
* 浏览公告信息
* @param noticeid
* @return
*/
PNotice showNoticeById(String noticeid);
/**
* 根据公告ID下载文件
* @param noticeid
* @return
*/
ResponseEntity<byte[]> downloadNoticeById(String noticeid, String path);
/**
* 根据关键字分页加载公告数据
* @param page
* @param kw
* @return
*/
PageInfo<PNotice> getNoticeListByTitle(Integer page, String kw);
}
|
package applyingjava.java.streams.collections;
import java.util.Optional;
import java.util.stream.Stream;
import applyingjava.java.streams.mapper.Mapper.Order;
import applyingjava.java.streams.util.FileUtil;
import applyingjava.java.streams.util.LOG;
public class OptionalFunctions {
public static void main(String[] args) {
Stream<Order> sampleOrder = FileUtil.getSampleOrders(1);
Optional<Order> order = sampleOrder.findFirst();
// ifPresent
order.ifPresent(LOG.print::log);
// get
LOG.print.log(order.get());
// orElse
order.orElse(new Order());
// orElseThrow
order = Optional.empty();
order.orElseThrow(() -> new NullPointerException("No Object Found."));
}
}
|
package org.firstinspires.ftc.teamcode;
import android.app.Activity;
import android.graphics.Color;
import android.view.View;
import com.qualcomm.ftcrobotcontroller.R;
import com.qualcomm.hardware.matrix.MatrixDcMotorController;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.hardware.CRServo;
import com.qualcomm.robotcore.hardware.ColorSensor;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.DcMotorSimple;
import com.qualcomm.robotcore.hardware.HardwareMap;
import com.qualcomm.robotcore.hardware.Servo;
import com.qualcomm.robotcore.hardware.ServoController;
import com.qualcomm.robotcore.util.ElapsedTime;
/**
* This is NOT an OpMode
* This class can be used to define all the specific hardware for a single robot.
* In this case that robot is a Pushbot, using Matrix Hardware.
* See PushbotTeleopTank_Iterative for a usage examples.
*
* This is coded as an Extension of HardwarePushbot to illustrate that the only additional
* action REQUIRED for a MATRIX controller is enabling the Servos.
*
* This hardware class assumes the following device names have been configured on the robot:
* Note: All names are lower case and some have single spaces between words.
*
* Matrix Controller has been assigned the name: "matrix controller"
*
* Motor channel: Left drive motor: "left_drive"
* Motor channel: Right drive motor: "right_drive"
* Motor channel: Manipulator drive motor: "left_arm"
* Servo channel: Servo to open left claw: "left_hand"
* Servo channel: Servo to open right claw: "right_hand"
*
* In addition, the Matrix Controller has been assigned the name: "matrix controller"
*/
public class teleop_hardware
{
/* Public OpMode members. */
public DcMotor leftMotor1 = null;
public DcMotor rightMotor1 = null;
public DcMotor leftMotor2 = null;
public DcMotor rightMotor2 = null;
//public DcMotor armMotor = null;
public CRServo beaconPusher = null;
public CRServo shovel = null;
public static final double OUT_OF_THE_WAY_SERVO = 0.56;
public static final double SHOVEL_FORWARD_POWER = 0.45;
public static final double SHOVEL_BACKWARD_POWER = -0.45;
// /* Private OpMode members. */
// private MatrixDcMotorController matrixMotorController = null;
// private ServoController matrixServoController = null;
/* Constructor */
public teleop_hardware(){
}
/* Initialize standard Hardware interfaces */
public void init(HardwareMap ahwMap) {
leftMotor1 = ahwMap.dcMotor.get("leftMotor1");
leftMotor2 = ahwMap.dcMotor.get("leftMotor2");
rightMotor1 = ahwMap.dcMotor.get("rightMotor1");
rightMotor2 = ahwMap.dcMotor.get("rightMotor2");
leftMotor1.setDirection(DcMotor.Direction.REVERSE);
leftMotor2.setDirection(DcMotor.Direction.REVERSE);
leftMotor1.setPower(0);
leftMotor2.setPower(0);
rightMotor1.setPower(0);
rightMotor2.setPower(0);
leftMotor1.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER);
leftMotor2.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER);
rightMotor1.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER);
rightMotor2.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER);
beaconPusher = ahwMap.crservo.get("beaconPusher");
shovel = ahwMap.crservo.get("shovel");
}
// Initialize base Motor and Servo objects
//super.init(ahwMap);
/*
* Matrix controllers are special.
*
* A Matrix controller is one controller with both motors and servos
* but software wants to treat it as two distinct controllers, one
* DcMotorController, and one ServoController.
*
* We accomplish this by initializing Motor and Servo controller with the same name
* given in the configuration. In the example below the name of the controller is
* "MatrixController"
*
* Normally we don't need to access the controllers themselves, we deal directly with
* the Motor and Servo objects, but the Matrix interface is different.
*
* In order to activate the servos, they need to be enabled on the controller with
* a call to pwmEnable() and disabled with a call to pwmDisable()
*
* Also, the Matrix Motor controller interface provides a call that enables all motors to
* updated simultaneously (with the same value).
*/
// // Initialize Matrix Motor and Servo objects
// matrixMotorController = (MatrixDcMotorController)ahwMap.dcMotorController.get("matrix controller");
// matrixServoController = ahwMap.servoController.get("matrix controller");
//
// // Enable Servos
// matrixServoController.pwmEnable(); // Don't forget to enable Matrix Output
}
// /*
// *
// * This is an example LinearOpMode that shows how to use
// * a legacy (NXT-compatible) Hitechnic Color Sensor v2.
// * It assumes that the color sensor is configured with a name of "sensor_color".
// *
// * You can use the X button on gamepad1 to toggle the LED on and off.
// *
// * Use Android Studio to Copy this Class, and Paste it into your team's code folder with a new name.
// * Remove or comment out the @Disabled line to add this opmode to the Driver Station OpMode list
// */
// @Autonomous(name = "Sensor: HT color", group = "Sensor")
// @Disabled
// public static class SensorHTColor extends LinearOpMode {
//
// ColorSensor colorSensor; // Hardware Device Object
//
//
// @Override
// public void runOpMode() {
//
// // hsvValues is an array that will hold the hue, saturation, and value information.
// float hsvValues[] = {0F, 0F, 0F};
//
// // values is a reference to the hsvValues array.
// final float values[] = hsvValues;
//
// // get a reference to the RelativeLayout so we can change the background
// // color of the Robot Controller app to match the hue detected by the RGB sensor.
// final View relativeLayout = ((Activity) hardwareMap.appContext).findViewById(R.id.RelativeLayout);
//
// // bPrevState and bCurrState represent the previous and current state of the button.
// boolean bPrevState = false;
// boolean bCurrState = false;
//
// // bLedOn represents the state of the LED.
// boolean bLedOn = true;
//
// // get a reference to our ColorSensor object.
// colorSensor = hardwareMap.colorSensor.get("sensor_color");
//
// // turn the LED on in the beginning, just so user will know that the sensor is active.
// colorSensor.enableLed(bLedOn);
//
// // wait for the start button to be pressed.
// waitForStart();
//
// // loop and read the RGB data.
// // Note we use opModeIsActive() as our loop condition because it is an interruptible method.
// while (opModeIsActive()) {
//
// // check the status of the x button on either gamepad.
// bCurrState = gamepad1.x;
//
// // check for button state transitions.
// if ((bCurrState == true) && (bCurrState != bPrevState)) {
//
// // button is transitioning to a pressed state. Toggle LED.
// // on button press, enable the LED.
// bLedOn = !bLedOn;
// colorSensor.enableLed(bLedOn);
// }
//
// // update previous state variable.
// bPrevState = bCurrState;
//
// // convert the RGB values to HSV values.
// Color.RGBToHSV(colorSensor.red(), colorSensor.green(), colorSensor.blue(), hsvValues);
//
// // send the info back to driver station using telemetry function.
// telemetry.addData("LED", bLedOn ? "On" : "Off");
// telemetry.addData("Clear", colorSensor.alpha());
// telemetry.addData("Red ", colorSensor.red());
// telemetry.addData("Green", colorSensor.green());
// telemetry.addData("Blue ", colorSensor.blue());
// telemetry.addData("Hue", hsvValues[0]);
//
// // change the background color to match the color detected by the RGB sensor.
// // pass a reference to the hue, saturation, and value array as an argument
// // to the HSVToColor method.
// relativeLayout.post(new Runnable() {
// public void run() {
// relativeLayout.setBackgroundColor(Color.HSVToColor(0xff, values));
// }
// });
//
// telemetry.update();
// }
// }
// /**
// * This is NOT an opmode.
// * <p>
// * This class can be used to define all the specific hardware for a single robot.
// * In this case that robot is a Pushbot.
// * See PushbotTeleopTank_Iterative and others classes starting with "Pushbot" for usage examples.
// * <p>
// * This hardware class assumes the following device names have been configured on the robot:
// * Note: All names are lower case and some have single spaces between words.
// * <p>
// * Motor channel: Left drive motor: "left_drive"
// * Motor channel: Right drive motor: "right_drive"
// * Motor channel: Manipulator drive motor: "left_arm"
// * Servo channel: Servo to open left claw: "left_hand"
// * Servo channel: Servo to open right claw: "right_hand"
// */
// public static class HardwarePushbot {
// /* Public OpMode members. */
// public DcMotor leftMotor1 = null;
// public DcMotor rightMotor1 = null;
// public DcMotor leftMotor2 = null;
// public DcMotor rightMotor2 = null;
// //public DcMotor armMotor = null;
// public Servo beaconPusher = null;
// public CRServo shovel = null;
//
// public static final double OUT_OF_THE_WAY_SERVO = 0.56;
// public static final double SHOVEL_FORWARD_POWER = 0.45;
// public static final double SHOVEL_BACKWARD_POWER = -0.45;
//
// /* local OpMode members. */
// HardwareMap hwMap = null;
// private ElapsedTime period = new ElapsedTime();
//
// /* Constructor */
// public HardwarePushbot() {
//
// }
//
// /* Initialize standard Hardware interfaces */
// public void init(HardwareMap ahwMap) {
// // Save reference to Hardware map
// hwMap = ahwMap;
//
// // Define and Initialize Motors
// leftMotor1 = hwMap.dcMotor.get("left_drive");
// rightMotor1 = hwMap.dcMotor.get("right_drive");
// leftMotor2 = hwMap.dcMotor.get("left_drive");
// rightMotor2 = hwMap.dcMotor.get("right_drive");
// //armMotor = hwMap.dcMotor.get("left_arm");
// leftMotor1.setDirection(DcMotor.Direction.FORWARD); // Set to REVERSE if using AndyMark motors
// rightMotor1.setDirection(DcMotor.Direction.REVERSE);// Set to FORWARD if using AndyMark motors
// leftMotor2.setDirection(DcMotor.Direction.FORWARD); // Set to REVERSE if using AndyMark motors
// rightMotor2.setDirection(DcMotor.Direction.REVERSE);// Set to FORWARD if using AndyMark motors
//
// // Set all motors to zero power
//
// leftMotor1.setPower(0);
// rightMotor1.setPower(0);
// leftMotor2.setPower(0);
// rightMotor2.setPower(0);
// //armMotor.setPower(0);
//
//
// // Set all motors to run without encoders.
// // May want to use RUN_USING_ENCODERS if encoders are installed.
// leftMotor1.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER);
// rightMotor1.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER);
// leftMotor2.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER);
// rightMotor2.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER);
// //armMotor.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER);
//
// // Define and initialize ALL installed servos.
// beaconPusher = hwMap.servo.get("left_hand");
// //shovel = hwMap.servo.get("right_hand");
// //beaconPusher.setPosition(MID_SERVO);
// //shovel;
// }
//
// /***
// * waitForTick implements a periodic delay. However, this acts like a metronome with a regular
// * periodic tick. This is used to compensate for varying processing times for each cycle.
// * The function looks at the elapsed cycle time, and sleeps for the remaining time interval.
// *
// * @param periodMs Length of wait cycle in mSec.
// */
// public void waitForTick(long periodMs) {
//
// long remaining = periodMs - (long) period.milliseconds();
//
// // sleep for the remaining portion of the regular cycle period.
// if (remaining > 0) {
// try {
// Thread.sleep(remaining);
// } catch (InterruptedException e) {
// Thread.currentThread().interrupt();
// }
// }
//
// // Reset the cycle clock for the next pass.
// period.reset();
// }
// }
//}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.commerceservices.order.dao.impl;
import static org.junit.Assert.assertEquals;
import de.hybris.platform.basecommerce.model.site.BaseSiteModel;
import de.hybris.platform.commerceservices.order.dao.SaveCartDao;
import de.hybris.platform.core.model.order.CartModel;
import de.hybris.platform.core.model.user.UserModel;
import de.hybris.platform.order.CartService;
import de.hybris.platform.servicelayer.ServicelayerTransactionalTest;
import de.hybris.platform.servicelayer.model.ModelService;
import de.hybris.platform.servicelayer.search.FlexibleSearchService;
import de.hybris.platform.servicelayer.time.TimeService;
import de.hybris.platform.servicelayer.user.UserService;
import de.hybris.platform.site.BaseSiteService;
import java.util.Date;
import javax.annotation.Resource;
import org.junit.Before;
import org.junit.Test;
public class DefaultSaveCartDaoIntegrationTest extends ServicelayerTransactionalTest
{
private static final String USER = "abrode";
private static final String CART_CODE = "abrodeCart";
private static final String TEST_BASESITE1_UID = "testSite";
private static final String TEST_BASESITE2_UID = "testSite2";
@Resource
private SaveCartDao saveCartDao;
@Resource
private UserService userService;
@Resource
private ModelService modelService;
@Resource
private BaseSiteService baseSiteService;
@Resource
private TimeService timeService;
@Resource
private FlexibleSearchService flexibleSearchService;
@Resource
private CartService cartService;
@Before
public void setUp() throws Exception
{
// importing test csv
importCsv("/commerceservices/test/testCommerceCart.csv", "utf-8");
}
@Test
public void getSavedCartsCountForSiteAndUserTest()
{
final UserModel user = userService.getUserForUID(USER);
final BaseSiteModel baseSite1 = baseSiteService.getBaseSiteForUID(TEST_BASESITE1_UID);
final BaseSiteModel baseSite2 = baseSiteService.getBaseSiteForUID(TEST_BASESITE2_UID);
final int originalCountWithNullBaseSite = saveCartDao.getSavedCartsCountForSiteAndUser(null, user).intValue();
final int originalCountWithBaseSite1 = saveCartDao.getSavedCartsCountForSiteAndUser(baseSite1, user).intValue();
final int originalCountWithBaseSite2 = saveCartDao.getSavedCartsCountForSiteAndUser(baseSite2, user).intValue();
final CartModel modelByExample = new CartModel();
modelByExample.setCode(CART_CODE);
CartModel cartToBeSaved = flexibleSearchService.getModelByExample(modelByExample);
populateCartModel(cartToBeSaved, user, null);
//save 1 cart with save time is null
cartToBeSaved.setSaveTime(null);
modelService.save(cartToBeSaved);
int countWithNullBaseSite = saveCartDao.getSavedCartsCountForSiteAndUser(null, user).intValue();
assertEquals(originalCountWithNullBaseSite, countWithNullBaseSite);
//save 1 cart with baseSite1
cartToBeSaved.setSaveTime(timeService.getCurrentTime());
cartToBeSaved.setSite(baseSite1);
modelService.save(cartToBeSaved);
countWithNullBaseSite = saveCartDao.getSavedCartsCountForSiteAndUser(null, user).intValue();
final int countWithBaseSite1 = saveCartDao.getSavedCartsCountForSiteAndUser(baseSite1, user).intValue();
assertEquals(originalCountWithBaseSite1 + 1, countWithBaseSite1);
assertEquals(originalCountWithNullBaseSite + 1, countWithNullBaseSite);
//save 1 session cart with baseSite2
userService.setCurrentUser(user);
cartToBeSaved = cartService.getSessionCart();
populateCartModel(cartToBeSaved, user, baseSite2);
modelService.save(cartToBeSaved);
countWithNullBaseSite = saveCartDao.getSavedCartsCountForSiteAndUser(null, user).intValue();
final int countWithBaseSite2 = saveCartDao.getSavedCartsCountForSiteAndUser(baseSite2, user).intValue();
assertEquals(originalCountWithBaseSite2 + 1, countWithBaseSite2);
assertEquals(originalCountWithNullBaseSite + 2, countWithNullBaseSite);
}
private void populateCartModel(final CartModel cart, final UserModel user, final BaseSiteModel baseSite)
{
cart.setName("name");
cart.setDescription("description");
cart.setSavedBy(user);
cart.setSite(baseSite);
final Date currentDate = timeService.getCurrentTime();
cart.setSaveTime(currentDate);
}
}
|
package ru.levelup.lesson03.lessonwork;
public class StringUtil {
//Стркока пустая если она
//null
//""
//(" ")
public static boolean isEmpty(String value){
//" dff " -> "dff"
//" as as " -> "as as"
return value == null || value.trim().isEmpty();//trim() убирает пробелы в начале и конце
}
}
|
package it.reply.tamangoteam.challenge.coding;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import it.reply.tamangoteam.utils.FileUtils;
public class WellsReadMain {
private static final Logger log = LogManager.getLogger();
public static void main(String[] args) {
List<String> wordsList = FileUtils.readFile("wellsread/words.txt");
Set<String> words = new HashSet<>(wordsList);
StringBuilder stringBuilder = new StringBuilder();
List<String> text = FileUtils.readFile("wellsread/The Time Machine by H. G. Wells.txt");
int n = 0;
for(Iterator<String> i = text.iterator(); i.hasNext(); n++) {
String line = i.next().replace(" ","");
for(String keyword: words) {
line = line.replaceAll(keyword, "");
}
if(!line.isBlank() ) {
stringBuilder.append(line);
}
if(n%100 == 0) {
log.info("{}/{}", n, text.size());
}
i.remove();
}
String lastLine = stringBuilder.toString();
for(String keyword: words) {
lastLine = lastLine.replaceAll(keyword, "");
}
log.info(lastLine);
}
}
|
package com.spring.domain;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author Naresh.P
*
*/
@Entity
@Table(name="bank_merchant")
public class BankMerchant implements Serializable{
private static final long serialVersionUID = 5267203409421089955L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;
private String merchantid;
private String issuedate;
private String bank_id;
private String branchcode;
private String chain_type_id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getMerchantid() {
return merchantid;
}
public void setMerchantid(String merchantid) {
this.merchantid = merchantid;
}
public String getIssuedate() {
return issuedate;
}
public void setIssuedate(String issuedate) {
this.issuedate = issuedate;
}
public String getBank_id() {
return bank_id;
}
public void setBank_id(String bank_id) {
this.bank_id = bank_id;
}
public String getBranchcode() {
return branchcode;
}
public void setBranchcode(String branchcode) {
this.branchcode = branchcode;
}
public String getChain_type_id() {
return chain_type_id;
}
public void setChain_type_id(String chain_type_id) {
this.chain_type_id = chain_type_id;
}
}
|
package com.tencent.mm.pluginsdk.ui.tools;
import android.text.Editable;
import android.text.TextWatcher;
import com.tencent.mm.ui.widget.MMEditText.b;
public class h$a implements TextWatcher {
public b qTc = null;
public final void afterTextChanged(Editable editable) {
}
public final void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
public final void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
if (this.qTc != null) {
this.qTc.Yr();
}
}
}
|
/*
* UniTime 3.2 - 3.5 (University Timetabling Application)
* Copyright (C) 2010 - 2013, UniTime LLC, and individual contributors
* as indicated by the @authors tag.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.unitime.timetable.gwt.shared;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.IsSerializable;
/**
* @author Tomas Muller
*/
public interface AcademicSessionProvider {
public Long getAcademicSessionId();
public String getAcademicSessionName();
public AcademicSessionInfo getAcademicSessionInfo();
public void addAcademicSessionChangeHandler(AcademicSessionChangeHandler handler);
public static interface AcademicSessionChangeEvent {
public Long getNewAcademicSessionId();
public Long getOldAcademicSessionId();
public boolean isChanged();
}
public static interface AcademicSessionChangeHandler {
public void onAcademicSessionChange(AcademicSessionChangeEvent event);
}
public void selectSession(Long sessionId, AsyncCallback<Boolean> callback);
public static class AcademicSessionInfo implements IsSerializable {
private Long iSessionId;
private String iYear, iTerm, iCampus, iName;
public AcademicSessionInfo() {}
public AcademicSessionInfo(Long sessionId, String year, String term, String campus, String name) {
iSessionId = sessionId;
iTerm = term;
iYear = year;
iCampus = campus;
iName = name;
}
public Long getSessionId() { return iSessionId; }
public void setSessionId(Long sessionId) { iSessionId = sessionId; }
public String getYear() { return iYear; }
public void setYear(String year) { iYear = year; }
public String getCampus() { return iCampus; }
public void setCampus(String campus) { iCampus = campus; }
public String getTerm() { return iTerm; }
public void setTerm(String term) { iTerm = term; }
public String getName() { return (iName == null || iName.isEmpty() ? iTerm + " " + iYear + " (" + iCampus + ")" : iName); }
public void setname(String name) { iName = name; }
@Override
public String toString() {
return getName();
}
@Override
public boolean equals(Object o) {
if (o == null || !(o instanceof AcademicSessionInfo)) return false;
return getSessionId().equals(((AcademicSessionInfo)o).getSessionId());
}
}
}
|
package ua.project.protester.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ProjectDto {
private Long projectId;
private String projectName;
private String projectWebsiteLink;
private Boolean projectActive;
private String creatorUsername;
private Long creatorId;
}
|
package net.thumbtack.mybatis.dao;
import net.thumbtack.mybatis.model.Address;
import net.thumbtack.mybatis.model.Author;
import java.sql.Date;
import java.util.List;
import java.util.Map;
public interface AuthorDAO {
public Author insert(Author author);
public Author getById(int id);
public List<Author> getAllLazy();
public List<Author> getAllUsingJoin();
public void deleteAll();
public void delete(Author author);
public void changeFirstName(Author author, String firstName);
public void batchInsert(List<Author> authorList);
public List<Author> getAllWithParams(Date date, String prefix);
public List<Author> getAllUsingSQLBuilder(Map<String, String> map);
public void changeFIO(Author author, String firstName, String lastName, String patronymic);
public void changeBirthDate(Author author, Date date);
public void addAddress(Author author, Address address);
public void deleteAllAddress(Author author);
public void changeAddress(Author author, Address address, String email);
public List<Author> getAuthorsByFirstName(String name);
}
|
package com.mes.old.meta;
// Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final
import java.math.BigDecimal;
import java.util.Date;
/**
* HWorkhourDetail generated by hbm2java
*/
public class HWorkhourDetail implements java.io.Serializable {
private String uniqueid;
private HWorkhourHeader HWorkhourHeader;
private String employeeid;
private String resuid;
private String worktype;
private Date workdate;
private String shiftid;
private String taskuid;
private String assnuid;
private String partNumber;
private String drawingid;
private String batchnum;
private String operationIddesc;
private BigDecimal preoptime;
private BigDecimal runtime;
private BigDecimal completeqty;
private BigDecimal completework;
private BigDecimal actualwork;
private BigDecimal optype;
private String creator;
private Date createtime;
private String notes;
private String sourceType;
private Long verifyState;
private BigDecimal overtimework;
private BigDecimal vacationwork;
private String opuid;
private String deptid;
private String deptname;
private String verifyReason;
private String verifyEmployee;
private Date verifyTime;
private String partname;
private String versionid;
private String operationname;
public HWorkhourDetail() {
}
public HWorkhourDetail(String uniqueid) {
this.uniqueid = uniqueid;
}
public HWorkhourDetail(String uniqueid, HWorkhourHeader HWorkhourHeader, String employeeid, String resuid,
String worktype, Date workdate, String shiftid, String taskuid, String assnuid, String partNumber,
String drawingid, String batchnum, String operationIddesc, BigDecimal preoptime, BigDecimal runtime,
BigDecimal completeqty, BigDecimal completework, BigDecimal actualwork, BigDecimal optype, String creator,
Date createtime, String notes, String sourceType, Long verifyState, BigDecimal overtimework,
BigDecimal vacationwork, String opuid, String deptid, String deptname, String verifyReason,
String verifyEmployee, Date verifyTime, String partname, String versionid, String operationname) {
this.uniqueid = uniqueid;
this.HWorkhourHeader = HWorkhourHeader;
this.employeeid = employeeid;
this.resuid = resuid;
this.worktype = worktype;
this.workdate = workdate;
this.shiftid = shiftid;
this.taskuid = taskuid;
this.assnuid = assnuid;
this.partNumber = partNumber;
this.drawingid = drawingid;
this.batchnum = batchnum;
this.operationIddesc = operationIddesc;
this.preoptime = preoptime;
this.runtime = runtime;
this.completeqty = completeqty;
this.completework = completework;
this.actualwork = actualwork;
this.optype = optype;
this.creator = creator;
this.createtime = createtime;
this.notes = notes;
this.sourceType = sourceType;
this.verifyState = verifyState;
this.overtimework = overtimework;
this.vacationwork = vacationwork;
this.opuid = opuid;
this.deptid = deptid;
this.deptname = deptname;
this.verifyReason = verifyReason;
this.verifyEmployee = verifyEmployee;
this.verifyTime = verifyTime;
this.partname = partname;
this.versionid = versionid;
this.operationname = operationname;
}
public String getUniqueid() {
return this.uniqueid;
}
public void setUniqueid(String uniqueid) {
this.uniqueid = uniqueid;
}
public HWorkhourHeader getHWorkhourHeader() {
return this.HWorkhourHeader;
}
public void setHWorkhourHeader(HWorkhourHeader HWorkhourHeader) {
this.HWorkhourHeader = HWorkhourHeader;
}
public String getEmployeeid() {
return this.employeeid;
}
public void setEmployeeid(String employeeid) {
this.employeeid = employeeid;
}
public String getResuid() {
return this.resuid;
}
public void setResuid(String resuid) {
this.resuid = resuid;
}
public String getWorktype() {
return this.worktype;
}
public void setWorktype(String worktype) {
this.worktype = worktype;
}
public Date getWorkdate() {
return this.workdate;
}
public void setWorkdate(Date workdate) {
this.workdate = workdate;
}
public String getShiftid() {
return this.shiftid;
}
public void setShiftid(String shiftid) {
this.shiftid = shiftid;
}
public String getTaskuid() {
return this.taskuid;
}
public void setTaskuid(String taskuid) {
this.taskuid = taskuid;
}
public String getAssnuid() {
return this.assnuid;
}
public void setAssnuid(String assnuid) {
this.assnuid = assnuid;
}
public String getPartNumber() {
return this.partNumber;
}
public void setPartNumber(String partNumber) {
this.partNumber = partNumber;
}
public String getDrawingid() {
return this.drawingid;
}
public void setDrawingid(String drawingid) {
this.drawingid = drawingid;
}
public String getBatchnum() {
return this.batchnum;
}
public void setBatchnum(String batchnum) {
this.batchnum = batchnum;
}
public String getOperationIddesc() {
return this.operationIddesc;
}
public void setOperationIddesc(String operationIddesc) {
this.operationIddesc = operationIddesc;
}
public BigDecimal getPreoptime() {
return this.preoptime;
}
public void setPreoptime(BigDecimal preoptime) {
this.preoptime = preoptime;
}
public BigDecimal getRuntime() {
return this.runtime;
}
public void setRuntime(BigDecimal runtime) {
this.runtime = runtime;
}
public BigDecimal getCompleteqty() {
return this.completeqty;
}
public void setCompleteqty(BigDecimal completeqty) {
this.completeqty = completeqty;
}
public BigDecimal getCompletework() {
return this.completework;
}
public void setCompletework(BigDecimal completework) {
this.completework = completework;
}
public BigDecimal getActualwork() {
return this.actualwork;
}
public void setActualwork(BigDecimal actualwork) {
this.actualwork = actualwork;
}
public BigDecimal getOptype() {
return this.optype;
}
public void setOptype(BigDecimal optype) {
this.optype = optype;
}
public String getCreator() {
return this.creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public Date getCreatetime() {
return this.createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
public String getNotes() {
return this.notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public String getSourceType() {
return this.sourceType;
}
public void setSourceType(String sourceType) {
this.sourceType = sourceType;
}
public Long getVerifyState() {
return this.verifyState;
}
public void setVerifyState(Long verifyState) {
this.verifyState = verifyState;
}
public BigDecimal getOvertimework() {
return this.overtimework;
}
public void setOvertimework(BigDecimal overtimework) {
this.overtimework = overtimework;
}
public BigDecimal getVacationwork() {
return this.vacationwork;
}
public void setVacationwork(BigDecimal vacationwork) {
this.vacationwork = vacationwork;
}
public String getOpuid() {
return this.opuid;
}
public void setOpuid(String opuid) {
this.opuid = opuid;
}
public String getDeptid() {
return this.deptid;
}
public void setDeptid(String deptid) {
this.deptid = deptid;
}
public String getDeptname() {
return this.deptname;
}
public void setDeptname(String deptname) {
this.deptname = deptname;
}
public String getVerifyReason() {
return this.verifyReason;
}
public void setVerifyReason(String verifyReason) {
this.verifyReason = verifyReason;
}
public String getVerifyEmployee() {
return this.verifyEmployee;
}
public void setVerifyEmployee(String verifyEmployee) {
this.verifyEmployee = verifyEmployee;
}
public Date getVerifyTime() {
return this.verifyTime;
}
public void setVerifyTime(Date verifyTime) {
this.verifyTime = verifyTime;
}
public String getPartname() {
return this.partname;
}
public void setPartname(String partname) {
this.partname = partname;
}
public String getVersionid() {
return this.versionid;
}
public void setVersionid(String versionid) {
this.versionid = versionid;
}
public String getOperationname() {
return this.operationname;
}
public void setOperationname(String operationname) {
this.operationname = operationname;
}
}
|
package com.wq.newcommunitygovern.mvp.ui.activity.signin;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.weique.commonres.core.RouterHub;
import com.weique.sdk.baidumap.MapShowPointsView;
import com.wq.newcommunitygovern.R;
import com.wq.newcommunitygovern.di.component.DaggerSigninComponent;
import com.wq.newcommunitygovern.mvp.contract.SigninContract;
import com.wq.newcommunitygovern.mvp.presenter.SigninPresenter;
import butterknife.BindView;
import static com.jess.arms.utils.Preconditions.checkNotNull;
/**
* ================================================
* Description:签到界面
* <p>
* ================================================
*
* @author Administrator
*/
@Route(path = RouterHub.APP_SIGNIN_ACTIVITY, name = "签到界面")
public class SigninActivity extends BaseActivity<SigninPresenter> implements SigninContract.View {
@BindView(R.id.map_view)
MapShowPointsView mapShowPointsView;
@Override
public void setupActivityComponent(@NonNull AppComponent appComponent) {
DaggerSigninComponent
.builder()
.appComponent(appComponent)
.view(this)
.build()
.inject(this);
}
@Override
protected void onResume() {
mapShowPointsView.onResume();
super.onResume();
}
@Override
protected void onPause() {
mapShowPointsView.onPause();
super.onPause();
}
@Override
protected void onDestroy() {
mapShowPointsView.onDestroy();
super.onDestroy();
}
@Override
public int initView(@Nullable Bundle savedInstanceState) {
return R.layout.app_activity_signin;
}
@Override
public void initData(@Nullable Bundle savedInstanceState) {
showLoading(true);
//单点
// LatLng point = new LatLng(39.163175, 116.100244);
// mapShowPointsView.setPointAndShow(point);
//路径 和 多点
// List<LatLng> points = new ArrayList<LatLng>();
// points.add(new LatLng(39.865, 116.444));
// points.add(new LatLng(39.825, 116.494));
// points.add(new LatLng(39.855, 116.534));
// points.add(new LatLng(39.805, 116.594));
// mapShowPointsView.setPointLineAndShow(points);
// mapShowPointsView.updateMapStatus(point, false);
mapShowPointsView.setListening(new MapShowPointsView.MapShowPointsViewListening() {
@Override
public void onTheCodingListener() {
hideLoading();
}
});
}
@Override
public void showLoading(boolean showLoading) {
showLoadingDialog();
}
@Override
public void hideLoading() {
dismissLoading();
}
@Override
public void showMessage(@NonNull String message) {
checkNotNull(message);
ArmsUtils.snackbarText(message);
}
@Override
public void launchActivity(@NonNull Intent intent) {
checkNotNull(intent);
ArmsUtils.startActivity(intent);
}
@Override
public void killMyself() {
finish();
}
}
|
package test_funzionali;
import static org.junit.Assert.*;
import java.util.Calendar;
import org.junit.Before;
import org.junit.Test;
import sistema.*;
public class SS5RimuovereUnCinemaDiUnGestoreCinema {
ApplicazioneAmministratoreSistema adminApp;
Calendar adminBirthday;
Calendar managerBirthday;
Cinema cinema;
@Before
public void setUp() throws Exception {
adminBirthday = Calendar.getInstance();
adminBirthday.set(1975, 2, 5);
managerBirthday = Calendar.getInstance();
managerBirthday.set(1980, 0, 1);
adminApp = new ApplicazioneAmministratoreSistema("Anna",
"Bianchi", "BNCNNA75C45D969Q", adminBirthday, "AnnaBianchi", "0000",
"anna.bianchi@gmail.com");
adminApp.login("AnnaBianchi", "0000");
adminApp.resetApplication();
// Registrazione di un nuovo gestore
adminApp.registraNuovoGestoreCinema("Luca", "Rossi", "RSSLCU80A01D969P",
managerBirthday, "luca.rossi@gmail.com");
cinema = new Cinema("Odeon", "Corso Buenos Aires, 83, 16129 Genova");
adminApp.addNewCinema("RSSLCU80A01D969P", cinema);
// Questo Scenario Secondario viene chiamato in seguito all'esecuzione
// dello use case UC13
// Scenario alternativo 6b di UC13:
// 2. L'Applicazione Amministratore Sistema chiede all'Amministratore Sistema
// lo username del Gestore Cinema
// 3. L'Amministratore Sistema inserisce i dati richiesti
// 4. L'Applicazione Amministratore Sistema valida i dati inseriti
assertNotNull(ApplicazioneAmministratoreSistema.getRegisteredGestoreCinema("RSSLCU80A01D969P"));
// 6a: L'Amministratore Sistema comunica di voler rimuovere un cinema dalla
// lista del Gestore Cinema
}
// Scenario Secondario: Rimuovere un cinema di un Gestore Cinema
@Test
public void SS5test1() {
// 1. L'Applicazione Amministratore Sistema chiede di inserire l’id del
// cinema da eliminare
// 2. L’Amministratore Sistema inserisce i dati richiesti
// 3. L'Applicazione Amministratore Sistema chiede conferma
// 4. L’Amministratore Sistema conferma di voler eliminare il cinema
// 5. L'Applicazione Amministratore Sistema effettua la cancellazione
assertTrue(adminApp.removeCinema("RSSLCU80A01D969P", cinema.getId()));
}
// Scenario alternativo 2a: L'Amministratore Sistema decide di annullare l'operazione
@Test
public void SS5test2() {
// 1. L'Applicazione Amministratore Sistema chiede di inserire l’id del
// cinema da eliminare
// 2a. Il Gestore Cinema decide di annullare l'operazione
return;
}
// Scenario alternativo 4a: L'Amministratore Sistema non conferma l'operazione
@Test
public void SS4test3() {
// 1. L'Applicazione Amministratore Sistema chiede di inserire l’id del
// cinema da eliminare
// 2. L’Amministratore Sistema inserisce i dati richiesti
// 3. L'Applicazione Amministratore Sistema chiede conferma
// 5a. L'Amministratore Sistema non conferma l'operazione
return;
}
// Scenario alternativo 5a: L’Applicazione Amministratore Sistema non riesce
// a cancellare il cinema perché l'id non è valido
@Test
public void SS5test4() {
// 1. L'Applicazione Amministratore Sistema chiede di inserire l’id del
// cinema da eliminare
// 2. L’Amministratore Sistema inserisce i dati richiesti
// 3. L'Applicazione Amministratore Sistema chiede conferma
// 4. L’Amministratore Sistema conferma di voler eliminare il cinema
// 5a. L'Applicazione Amministratore Sistema non effettua la cancellazione
int wrongId = -12234;
assertFalse(adminApp.removeCinema("RSSLCU80A01D969P", wrongId));
// Andare al passo 1 dello scenario secondario
}
}
|
package bl;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.List;
import library.common.tLeaveMobileData;
import library.dal.tLeaveMobileDA;
public class tLeaveMobileBL extends clsMainBL {
public void saveData(List<tLeaveMobileData> Listdata){
SQLiteDatabase db=getDb();
tLeaveMobileDA _tLeaveMobileDA=new tLeaveMobileDA(db);
for(tLeaveMobileData data:Listdata){
_tLeaveMobileDA.SaveDataMConfig(db, data);
}
}
public List<tLeaveMobileData> getData(String id){
List<tLeaveMobileData> listData=new ArrayList<tLeaveMobileData>();
tLeaveMobileDA _tLeaveMobileDA=new tLeaveMobileDA(db);
if(id.equals("")){
listData=_tLeaveMobileDA.getAllData(db);
}else{
tLeaveMobileData data=new tLeaveMobileData();
data=_tLeaveMobileDA.getData(db, id);
listData.add(data);
}
return listData;
}
public List<tLeaveMobileData> getAllDataToPushData(){
SQLiteDatabase db=getDb();
tLeaveMobileDA _tLeaveMobileDA=new tLeaveMobileDA(db);
List<tLeaveMobileData> ListData=new ArrayList<tLeaveMobileData>();
ListData=_tLeaveMobileDA.getAllDataPushData(db);
return ListData;
}
public int getContactsCount(){
SQLiteDatabase db=getDb();
tLeaveMobileDA _tLeaveMobileDA=new tLeaveMobileDA(db);
return _tLeaveMobileDA.getContactsCount(db);
}
}
|
package com.leo.service.grade;
import com.github.pagehelper.PageHelper;
import com.leo.entity.Grade;
import com.leo.mapper.GradeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Collections;
import java.util.List;
@Service
public class GradeServiceImpl implements GradeService {
@Autowired
private GradeMapper gradeMapper;
@Override
public int deleteByPrimaryKey(Short gid) {
return 0;
}
@Override
public int insert(Grade record) {
return 0;
}
@Override
public int insertSelective(Grade record) {
return 0;
}
@Override
public Grade selectByPrimaryKey(Short gid) {
return gradeMapper.selectByPrimaryKey(gid);
}
@Override
public List<Grade> selectGrades() {
PageHelper.startPage(1,10,"gname ASC");
List<Grade> grades = gradeMapper.selectGrades();
return grades;
}
@Override
public int updateByPrimaryKeySelective(Grade record) {
return 0;
}
@Override
public int updateByPrimaryKey(Grade record) {
return 0;
}
}
|
package com.mkyong.common.controller;
import com.mkyong.common.entities.User;
import com.mkyong.common.services.UserImpl;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class SubrisePackageController {
@Autowired
private UserImpl userImpl;
@RequestMapping(value = { "/subscribePackage" }, method = {
org.springframework.web.bind.annotation.RequestMethod.POST })
@ResponseBody
public final Map<Object, Object> doPost(@RequestBody String request) {
Map<Object, Object> data = new HashMap();
data.put("returnCode", Integer.valueOf(0));
JSONObject jsonObj = new JSONObject(request);
JSONArray activateList = jsonObj.getJSONArray("activateList");
JSONObject activate = activateList.getJSONObject(0);
String phoneNumber = activate.getString("phoneNumber");
User user = this.userImpl.getUserByPhoneNumber(phoneNumber);
if (user == null) {
JSONArray credits = activate.getJSONArray("credits");
JSONObject credit = credits.getJSONObject(0);
String creditId = credit.getString("creditID");
user = new User();
user.setPhoneNumber(phoneNumber);
user.setCreditId(creditId);
user.setBalance(Integer.valueOf(100));
this.userImpl.saveUser(user);
}
return data;
}
}
|
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.util.concurrent.TimeUnit;
public class TestClass {
public static void main(String[] args) throws InterruptedException {
//Rastgele bir mail çekmek için bu siteyi ziyeret ediyoruz.
WebDriver randommail = new FirefoxDriver();
randommail.get("http://www.yopmail.com/en/email-generator.php");
WebElement randommailElement = randommail.findElement(By.xpath("//*[@id=\"login\"]"));
String mail = randommailElement.getAttribute("value");
randommail.close();
WebDriver browser = new FirefoxDriver();
WebDriverWait wait = new WebDriverWait(browser, 30);
browser.get("https://connect-th.beinsports.com/en");
browser.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
Thread.sleep(1000);
//Ana Sayfadayken Subscribe Butonuna basılmadan önce
browser.findElement(By.xpath("/html/body/div[4]/div/nav/div[3]/ul/li[3]/a")).click();
Thread.sleep(2000);
//Subscribe Butonuna basıldıktan sonra
browser.findElement(By.xpath("/html/body/div[5]/div[1]/div[3]")).click();
Thread.sleep(2000);
//İkinci Subscribe butonuna basıldıktan sonra
browser.findElement(By.xpath("/html/body/div[5]/div[4]/div/div[2]/div[2]/div[2]/a")).click();
Thread.sleep(2000);
//Kayıt olma
CreateAccount createAccount = new CreateAccount(browser) ;
Thread.sleep(1000);
createAccount.typeName("Name");
Thread.sleep(1000);
createAccount.typeSurname("SurName");
Thread.sleep(1000);
createAccount.typeEmail(mail);
Thread.sleep(1000);
createAccount.typePassword("Asds123");
Thread.sleep(1000);
createAccount.button();
//Onay
OnaylamaSayfasi onaylamaSayfasi = new OnaylamaSayfasi(browser);
Thread.sleep(3000);
onaylamaSayfasi.pressX();
Thread.sleep(1000);
onaylamaSayfasi.markBox();
Thread.sleep(1000);
onaylamaSayfasi.pressButton();
//Kredi Kartı
KartBilgileri kartBilgileri = new KartBilgileri(browser);
Thread.sleep(5000);
kartBilgileri.KartAdi("KartAdı");
Thread.sleep(1000);
kartBilgileri.KartNumarasi("4532251641757362");
Thread.sleep(1000);
kartBilgileri.Exmm("02");
Thread.sleep(1000);
kartBilgileri.Exyy("2022");
Thread.sleep(1000);
kartBilgileri.OnayKodu("231");
Thread.sleep(1000);
kartBilgileri.Confirm();
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@id=\"ncol_cancel\"]")));
Thread.sleep(5000);
browser.close();
}
}
|
package com.vilio.plms.service.fundManagement;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.vilio.plms.dao.FundManagerDao;
import com.vilio.plms.dao.OperationManagerDao;
import com.vilio.plms.dao.QueryDao;
import com.vilio.plms.exception.ErrorException;
import com.vilio.plms.glob.Fields;
import com.vilio.plms.service.base.BaseService;
import com.vilio.plms.service.base.CommonService;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 类名: Plms100040<br>
* 功能:还款到账登记-手工登记初始化<br>
* 版本: 1.0<br>
* 日期: 2017年7月7日<br>
* 作者: xiezhilei<br>
* 版权:vilio<br>
* 说明:<br>
*/
@Service
public class Plms100040 extends BaseService {
private static final Logger logger = Logger.getLogger(Plms100040.class);
@Resource
FundManagerDao fundManagerDao;
@Resource
CommonService commonService;
/**
* 参数验证
*
* @param body
*/
public void checkParam(Map<String, Object> body) throws ErrorException {
}
/**
* 主业务流程空实现
*
* @param head
* @param body
*/
@Transactional(propagation = Propagation.REQUIRED,
isolation = Isolation.READ_COMMITTED,
rollbackFor = Exception.class)
public void busiService(Map<String, Object> head, Map<String, Object> body, Map<String, Object> resultMap) throws ErrorException, Exception {
String userNo = body.get(Fields.PARAM_USER_NO) == null ? "" : body.get(Fields.PARAM_USER_NO).toString();
String contractCode = body.get("contractCode").toString();
Map map = fundManagerDao.queryContractInfoForManualReceipts(contractCode);
if(map == null){
map = new HashMap();
}
resultMap.putAll(map);
//收款方列表
resultMap.put("accountTypeList", commonService.queryAccountTypeList());
//还款来源列表
resultMap.put("fundSourceList", commonService.querFundSourceList());
}
}
|
/*
* Copyright (C) 2017 JRummy Apps Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jrummyapps.android.colorpicker;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ComposeShader;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Paint.Style;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.Shader.TileMode;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
/**
* Displays a color picker to the user and allow them to select a color. A slider for the alpha channel is also available.
* Enable it by setting setAlphaSliderVisible(boolean) to true.
*/
public class ColorPickerView extends View {
private final static int DEFAULT_BORDER_COLOR = 0xFF6E6E6E;
private final static int DEFAULT_SLIDER_COLOR = 0xFFBDBDBD;
private final static int HUE_PANEL_WDITH_DP = 30;
private final static int ALPHA_PANEL_HEIGH_DP = 20;
private final static int PANEL_SPACING_DP = 10;
private final static int CIRCLE_TRACKER_RADIUS_DP = 5;
private final static int SLIDER_TRACKER_SIZE_DP = 4;
private final static int SLIDER_TRACKER_OFFSET_DP = 2;
/**
* The width in pixels of the border
* surrounding all color panels.
*/
private final static int BORDER_WIDTH_PX = 1;
/**
* The width in px of the hue panel.
*/
private int huePanelWidthPx;
/**
* The height in px of the alpha panel
*/
private int alphaPanelHeightPx;
/**
* The distance in px between the different
* color panels.
*/
private int panelSpacingPx;
/**
* The radius in px of the color palette tracker circle.
*/
private int circleTrackerRadiusPx;
/**
* The px which the tracker of the hue or alpha panel
* will extend outside of its bounds.
*/
private int sliderTrackerOffsetPx;
/**
* Height of slider tracker on hue panel,
* width of slider on alpha panel.
*/
private int sliderTrackerSizePx;
private Paint satValPaint;
private Paint satValTrackerPaint;
private Paint alphaPaint;
private Paint alphaTextPaint;
private Paint hueAlphaTrackerPaint;
private Paint borderPaint;
private Shader valShader;
private Shader satShader;
private Shader alphaShader;
/*
* We cache a bitmap of the sat/val panel which is expensive to draw each time.
* We can reuse it when the user is sliding the circle picker as long as the hue isn't changed.
*/
private BitmapCache satValBackgroundCache;
/* We cache the hue background to since its also very expensive now. */
private BitmapCache hueBackgroundCache;
/* Current values */
private int alpha = 0xff;
private float hue = 360f;
private float sat = 0f;
private float val = 0f;
private boolean showAlphaPanel = false;
private String alphaSliderText = null;
private int sliderTrackerColor = DEFAULT_SLIDER_COLOR;
private int borderColor = DEFAULT_BORDER_COLOR;
/**
* Minimum required padding. The offset from the
* edge we must have or else the finger tracker will
* get clipped when it's drawn outside of the view.
*/
private int mRequiredPadding;
/**
* The Rect in which we are allowed to draw.
* Trackers can extend outside slightly,
* due to the required padding we have set.
*/
private Rect drawingRect;
private Rect satValRect;
private Rect hueRect;
private Rect alphaRect;
private Point startTouchPoint = null;
private AlphaPatternDrawable alphaPatternDrawable;
private OnColorChangedListener onColorChangedListener;
public ColorPickerView( Context context ){
this( context, null );
}
public ColorPickerView( Context context, AttributeSet attrs ){
this( context, attrs, 0 );
}
public ColorPickerView( Context context, AttributeSet attrs, int defStyle ){
super( context, attrs, defStyle );
init( context, attrs );
}
@Override public Parcelable onSaveInstanceState(){
Bundle state = new Bundle();
state.putParcelable( "instanceState", super.onSaveInstanceState() );
state.putInt( "alpha", alpha );
state.putFloat( "hue", hue );
state.putFloat( "sat", sat );
state.putFloat( "val", val );
state.putBoolean( "show_alpha", showAlphaPanel );
state.putString( "alpha_text", alphaSliderText );
return state;
}
@Override public void onRestoreInstanceState( Parcelable state ){
if( state instanceof Bundle ){
Bundle bundle = (Bundle) state;
alpha = bundle.getInt( "alpha" );
hue = bundle.getFloat( "hue" );
sat = bundle.getFloat( "sat" );
val = bundle.getFloat( "val" );
showAlphaPanel = bundle.getBoolean( "show_alpha" );
alphaSliderText = bundle.getString( "alpha_text" );
state = bundle.getParcelable( "instanceState" );
}
super.onRestoreInstanceState( state );
}
private void init( Context context, AttributeSet attrs ){
//Load those if set in xml resource file.
TypedArray a = getContext().obtainStyledAttributes( attrs, R.styleable.ColorPickerView );
showAlphaPanel = a.getBoolean( R.styleable.ColorPickerView_cpv_alphaChannelVisible, false );
alphaSliderText = a.getString( R.styleable.ColorPickerView_cpv_alphaChannelText );
sliderTrackerColor = a.getColor( R.styleable.ColorPickerView_cpv_sliderColor, 0xFFBDBDBD );
borderColor = a.getColor( R.styleable.ColorPickerView_cpv_borderColor, 0xFF6E6E6E );
a.recycle();
applyThemeColors( context );
huePanelWidthPx = DrawingUtils.dpToPx( getContext(), HUE_PANEL_WDITH_DP );
alphaPanelHeightPx = DrawingUtils.dpToPx( getContext(), ALPHA_PANEL_HEIGH_DP );
panelSpacingPx = DrawingUtils.dpToPx( getContext(), PANEL_SPACING_DP );
circleTrackerRadiusPx = DrawingUtils.dpToPx( getContext(), CIRCLE_TRACKER_RADIUS_DP );
sliderTrackerSizePx = DrawingUtils.dpToPx( getContext(), SLIDER_TRACKER_SIZE_DP );
sliderTrackerOffsetPx = DrawingUtils.dpToPx( getContext(), SLIDER_TRACKER_OFFSET_DP );
mRequiredPadding = getResources().getDimensionPixelSize( R.dimen.cpv_required_padding );
initPaintTools();
//Needed for receiving trackball motion events.
setFocusable( true );
setFocusableInTouchMode( true );
}
private void applyThemeColors( Context c ){
// If no specific border/slider color has been
// set we take the default secondary text color
// as border/slider color. Thus it will adopt
// to theme changes automatically.
final TypedValue value = new TypedValue();
TypedArray a = c.obtainStyledAttributes( value.data, new int[]{ android.R.attr.textColorSecondary } );
if( borderColor == DEFAULT_BORDER_COLOR ){
borderColor = a.getColor( 0, DEFAULT_BORDER_COLOR );
}
if( sliderTrackerColor == DEFAULT_SLIDER_COLOR ){
sliderTrackerColor = a.getColor( 0, DEFAULT_SLIDER_COLOR );
}
a.recycle();
}
private void initPaintTools(){
satValPaint = new Paint();
satValTrackerPaint = new Paint();
hueAlphaTrackerPaint = new Paint();
alphaPaint = new Paint();
alphaTextPaint = new Paint();
borderPaint = new Paint();
satValTrackerPaint.setStyle( Style.STROKE );
satValTrackerPaint.setStrokeWidth( DrawingUtils.dpToPx( getContext(), 2 ) );
satValTrackerPaint.setAntiAlias( true );
hueAlphaTrackerPaint.setColor( sliderTrackerColor );
hueAlphaTrackerPaint.setStyle( Style.STROKE );
hueAlphaTrackerPaint.setStrokeWidth( DrawingUtils.dpToPx( getContext(), 2 ) );
hueAlphaTrackerPaint.setAntiAlias( true );
alphaTextPaint.setColor( 0xff1c1c1c );
alphaTextPaint.setTextSize( DrawingUtils.dpToPx( getContext(), 14 ) );
alphaTextPaint.setAntiAlias( true );
alphaTextPaint.setTextAlign( Align.CENTER );
alphaTextPaint.setFakeBoldText( true );
}
@Override protected void onDraw( Canvas canvas ){
if( drawingRect.width() <= 0 || drawingRect.height() <= 0 ){
return;
}
drawSatValPanel( canvas );
drawHuePanel( canvas );
drawAlphaPanel( canvas );
}
private void drawSatValPanel( Canvas canvas ){
final Rect rect = satValRect;
if( BORDER_WIDTH_PX > 0 ){
borderPaint.setColor( borderColor );
canvas.drawRect( drawingRect.left, drawingRect.top,
rect.right + BORDER_WIDTH_PX,
rect.bottom + BORDER_WIDTH_PX, borderPaint );
}
if( valShader == null ){
//Black gradient has either not been created or the view has been resized.
valShader = new LinearGradient( rect.left, rect.top, rect.left, rect.bottom, 0xffffffff, 0xff000000, TileMode.CLAMP );
}
//If the hue has changed we need to recreate the cache.
if( satValBackgroundCache == null || satValBackgroundCache.value != hue ){
if( satValBackgroundCache == null ){
satValBackgroundCache = new BitmapCache();
}
//We create our bitmap in the cache if it doesn't exist.
if( satValBackgroundCache.bitmap == null ){
satValBackgroundCache.bitmap = Bitmap
.createBitmap( rect.width(), rect.height(), Config.ARGB_8888 );
}
//We create the canvas once so we can draw on our bitmap and the hold on to it.
if( satValBackgroundCache.canvas == null ){
satValBackgroundCache.canvas = new Canvas( satValBackgroundCache.bitmap );
}
int rgb = Color.HSVToColor( new float[]{ hue, 1f, 1f } );
satShader = new LinearGradient( rect.left, rect.top, rect.right, rect.top, 0xffffffff, rgb, TileMode.CLAMP );
ComposeShader mShader = new ComposeShader(
valShader, satShader, PorterDuff.Mode.MULTIPLY );
satValPaint.setShader( mShader );
// Finally we draw on our canvas, the result will be
// stored in our bitmap which is already in the cache.
// Since this is drawn on a canvas not rendered on
// screen it will automatically not be using the
// hardware acceleration. And this was the code that
// wasn't supported by hardware acceleration which mean
// there is no need to turn it of anymore. The rest of
// the view will still be hw accelerated.
satValBackgroundCache.canvas.drawRect( 0, 0,
satValBackgroundCache.bitmap.getWidth(),
satValBackgroundCache.bitmap.getHeight(),
satValPaint );
//We set the hue value in our cache to which hue it was drawn with,
//then we know that if it hasn't changed we can reuse our cached bitmap.
satValBackgroundCache.value = hue;
}
// We draw our bitmap from the cached, if the hue has changed
// then it was just recreated otherwise the old one will be used.
canvas.drawBitmap( satValBackgroundCache.bitmap, null, rect, null );
Point p = satValToPoint( sat, val );
satValTrackerPaint.setColor( 0xff000000 );
canvas.drawCircle( p.x, p.y, circleTrackerRadiusPx - DrawingUtils.dpToPx( getContext(), 1 ), satValTrackerPaint );
satValTrackerPaint.setColor( 0xffdddddd );
canvas.drawCircle( p.x, p.y, circleTrackerRadiusPx, satValTrackerPaint );
}
private void drawHuePanel( Canvas canvas ){
final Rect rect = hueRect;
if( BORDER_WIDTH_PX > 0 ){
borderPaint.setColor( borderColor );
canvas.drawRect( rect.left - BORDER_WIDTH_PX,
rect.top - BORDER_WIDTH_PX,
rect.right + BORDER_WIDTH_PX,
rect.bottom + BORDER_WIDTH_PX,
borderPaint );
}
if( hueBackgroundCache == null ){
hueBackgroundCache = new BitmapCache();
hueBackgroundCache.bitmap = Bitmap.createBitmap( rect.width(), rect.height(), Config.ARGB_8888 );
hueBackgroundCache.canvas = new Canvas( hueBackgroundCache.bitmap );
int[] hueColors = new int[ (int) ( rect.height() + 0.5f ) ];
// Generate array of all colors, will be drawn as individual lines.
float h = 360f;
for( int i = 0 ; i < hueColors.length ; i++ ){
hueColors[ i ] = Color.HSVToColor( new float[]{ h, 1f, 1f } );
h -= 360f / hueColors.length;
}
// Time to draw the hue color gradient,
// its drawn as individual lines which
// will be quite many when the resolution is high
// and/or the panel is large.
Paint linePaint = new Paint();
linePaint.setStrokeWidth( 0 );
for( int i = 0 ; i < hueColors.length ; i++ ){
linePaint.setColor( hueColors[ i ] );
hueBackgroundCache.canvas.drawLine( 0, i, hueBackgroundCache.bitmap.getWidth(), i, linePaint );
}
}
canvas.drawBitmap( hueBackgroundCache.bitmap, null, rect, null );
Point p = hueToPoint( hue );
RectF r = new RectF();
r.left = rect.left - sliderTrackerOffsetPx;
r.right = rect.right + sliderTrackerOffsetPx;
r.top = p.y - ( sliderTrackerSizePx / 2 );
r.bottom = p.y + ( sliderTrackerSizePx / 2 );
canvas.drawRoundRect( r, 2, 2, hueAlphaTrackerPaint );
}
private void drawAlphaPanel( Canvas canvas ){
/*
* Will be drawn with hw acceleration, very fast.
* Also the AlphaPatternDrawable is backed by a bitmap
* generated only once if the size does not change.
*/
if( ! showAlphaPanel || alphaRect == null || alphaPatternDrawable == null ) return;
final Rect rect = alphaRect;
if( BORDER_WIDTH_PX > 0 ){
borderPaint.setColor( borderColor );
canvas.drawRect( rect.left - BORDER_WIDTH_PX,
rect.top - BORDER_WIDTH_PX,
rect.right + BORDER_WIDTH_PX,
rect.bottom + BORDER_WIDTH_PX,
borderPaint );
}
alphaPatternDrawable.draw( canvas );
float[] hsv = new float[]{ hue, sat, val };
int color = Color.HSVToColor( hsv );
int acolor = Color.HSVToColor( 0, hsv );
alphaShader = new LinearGradient( rect.left, rect.top, rect.right, rect.top,
color, acolor, TileMode.CLAMP );
alphaPaint.setShader( alphaShader );
canvas.drawRect( rect, alphaPaint );
if( alphaSliderText != null && ! alphaSliderText.equals( "" ) ){
canvas.drawText( alphaSliderText, rect.centerX(), rect.centerY() + DrawingUtils.dpToPx( getContext(), 4 ), alphaTextPaint );
}
Point p = alphaToPoint( alpha );
RectF r = new RectF();
r.left = p.x - ( sliderTrackerSizePx / 2 );
r.right = p.x + ( sliderTrackerSizePx / 2 );
r.top = rect.top - sliderTrackerOffsetPx;
r.bottom = rect.bottom + sliderTrackerOffsetPx;
canvas.drawRoundRect( r, 2, 2, hueAlphaTrackerPaint );
}
private Point hueToPoint( float hue ){
final Rect rect = hueRect;
final float height = rect.height();
Point p = new Point();
p.y = (int) ( height - ( hue * height / 360f ) + rect.top );
p.x = rect.left;
return p;
}
private Point satValToPoint( float sat, float val ){
final Rect rect = satValRect;
final float height = rect.height();
final float width = rect.width();
Point p = new Point();
p.x = (int) ( sat * width + rect.left );
p.y = (int) ( ( 1f - val ) * height + rect.top );
return p;
}
private Point alphaToPoint( int alpha ){
final Rect rect = alphaRect;
final float width = rect.width();
Point p = new Point();
p.x = (int) ( width - ( alpha * width / 0xff ) + rect.left );
p.y = rect.top;
return p;
}
private float[] pointToSatVal( float x, float y ){
final Rect rect = satValRect;
float[] result = new float[ 2 ];
float width = rect.width();
float height = rect.height();
if( x < rect.left ){
x = 0f;
}else if( x > rect.right ){
x = width;
}else{
x = x - rect.left;
}
if( y < rect.top ){
y = 0f;
}else if( y > rect.bottom ){
y = height;
}else{
y = y - rect.top;
}
result[ 0 ] = 1.f / width * x;
result[ 1 ] = 1.f - ( 1.f / height * y );
return result;
}
private float pointToHue( float y ){
final Rect rect = hueRect;
float height = rect.height();
if( y < rect.top ){
y = 0f;
}else if( y > rect.bottom ){
y = height;
}else{
y = y - rect.top;
}
return 360f - ( y * 360f / height );
}
private int pointToAlpha( int x ){
final Rect rect = alphaRect;
final int width = rect.width();
if( x < rect.left ){
x = 0;
}else if( x > rect.right ){
x = width;
}else{
x = x - rect.left;
}
return 0xff - ( x * 0xff / width );
}
@SuppressLint("ClickableViewAccessibility")
@Override public boolean onTouchEvent( MotionEvent event ){
try{
this.getParent().requestDisallowInterceptTouchEvent( true );
}catch( Throwable ignored ){
}
boolean update = false;
switch( event.getAction() ){
case MotionEvent.ACTION_DOWN:
startTouchPoint = new Point( (int) event.getX(), (int) event.getY() );
update = moveTrackersIfNeeded( event );
break;
case MotionEvent.ACTION_MOVE:
update = moveTrackersIfNeeded( event );
break;
case MotionEvent.ACTION_UP:
startTouchPoint = null;
update = moveTrackersIfNeeded( event );
break;
}
if( update ){
if( onColorChangedListener != null ){
onColorChangedListener.onColorChanged( Color.HSVToColor( alpha, new float[]{ hue, sat, val } ) );
}
invalidate();
return true;
}
return super.onTouchEvent( event );
}
private boolean moveTrackersIfNeeded( MotionEvent event ){
if( startTouchPoint == null ){
return false;
}
boolean update = false;
int startX = startTouchPoint.x;
int startY = startTouchPoint.y;
if( hueRect.contains( startX, startY ) ){
hue = pointToHue( event.getY() );
update = true;
}else if( satValRect.contains( startX, startY ) ){
float[] result = pointToSatVal( event.getX(), event.getY() );
sat = result[ 0 ];
val = result[ 1 ];
update = true;
}else if( alphaRect != null && alphaRect.contains( startX, startY ) ){
alpha = pointToAlpha( (int) event.getX() );
update = true;
}
return update;
}
@Override protected void onMeasure( int widthMeasureSpec, int heightMeasureSpec ){
int finalWidth;
int finalHeight;
int widthMode = MeasureSpec.getMode( widthMeasureSpec );
int heightMode = MeasureSpec.getMode( heightMeasureSpec );
int widthAllowed = MeasureSpec.getSize( widthMeasureSpec ) - getPaddingLeft() - getPaddingRight();
int heightAllowed =
MeasureSpec.getSize( heightMeasureSpec ) - getPaddingBottom() - getPaddingTop();
if( widthMode == MeasureSpec.EXACTLY || heightMode == MeasureSpec.EXACTLY ){
//A exact value has been set in either direction, we need to stay within this size.
if( widthMode == MeasureSpec.EXACTLY && heightMode != MeasureSpec.EXACTLY ){
//The with has been specified exactly, we need to adopt the height to fit.
int h = ( widthAllowed - panelSpacingPx - huePanelWidthPx );
if( showAlphaPanel ){
h += panelSpacingPx + alphaPanelHeightPx;
}
if( h > heightAllowed ){
//We can't fit the view in this container, set the size to whatever was allowed.
finalHeight = heightAllowed;
}else{
finalHeight = h;
}
finalWidth = widthAllowed;
}else if( widthMode != MeasureSpec.EXACTLY ){
//The height has been specified exactly, we need to stay within this height and adopt the width.
int w = ( heightAllowed + panelSpacingPx + huePanelWidthPx );
if( showAlphaPanel ){
w -= ( panelSpacingPx + alphaPanelHeightPx );
}
if( w > widthAllowed ){
//we can't fit within this container, set the size to whatever was allowed.
finalWidth = widthAllowed;
}else{
finalWidth = w;
}
finalHeight = heightAllowed;
}else{
//If we get here the dev has set the width and height to exact sizes. For example match_parent or 300dp.
//This will mean that the sat/val panel will not be square but it doesn't matter. It will work anyway.
//In all other senarios our goal is to make that panel square.
//We set the sizes to exactly what we were told.
finalWidth = widthAllowed;
finalHeight = heightAllowed;
}
}else{
//If no exact size has been set we try to make our view as big as possible
//within the allowed space.
//Calculate the needed width to layout using max allowed height.
int widthNeeded = ( heightAllowed + panelSpacingPx + huePanelWidthPx );
//Calculate the needed height to layout using max allowed width.
int heightNeeded = ( widthAllowed - panelSpacingPx - huePanelWidthPx );
if( showAlphaPanel ){
widthNeeded -= ( panelSpacingPx + alphaPanelHeightPx );
heightNeeded += panelSpacingPx + alphaPanelHeightPx;
}
boolean widthOk = false;
boolean heightOk = false;
if( widthNeeded <= widthAllowed ){
widthOk = true;
}
if( heightNeeded <= heightAllowed ){
heightOk = true;
}
if( widthOk && heightOk ){
finalWidth = widthAllowed;
finalHeight = heightNeeded;
}else if( widthOk ){
finalHeight = heightAllowed;
finalWidth = widthNeeded;
}else if( heightOk ){
finalHeight = heightNeeded;
finalWidth = widthAllowed;
}else{
finalHeight = heightAllowed;
finalWidth = widthAllowed;
}
}
setMeasuredDimension( finalWidth + getPaddingLeft() + getPaddingRight(),
finalHeight + getPaddingTop() + getPaddingBottom() );
}
// private int getPreferredWidth() {
// //Our preferred width and height is 200dp for the square sat / val rectangle.
// int width = DrawingUtils.dpToPx(getContext(), 200);
//
// return (width + huePanelWidthPx + panelSpacingPx);
// }
//
// private int getPreferredHeight() {
// int height = DrawingUtils.dpToPx(getContext(), 200);
//
// if (showAlphaPanel) {
// height += panelSpacingPx + alphaPanelHeightPx;
// }
// return height;
// }
@Override public int getPaddingTop(){
return Math.max( super.getPaddingTop(), mRequiredPadding );
}
@Override public int getPaddingBottom(){
return Math.max( super.getPaddingBottom(), mRequiredPadding );
}
@Override public int getPaddingLeft(){
return Math.max( super.getPaddingLeft(), mRequiredPadding );
}
@Override public int getPaddingRight(){
return Math.max( super.getPaddingRight(), mRequiredPadding );
}
@Override protected void onSizeChanged( int w, int h, int oldw, int oldh ){
super.onSizeChanged( w, h, oldw, oldh );
drawingRect = new Rect();
drawingRect.left = getPaddingLeft();
drawingRect.right = w - getPaddingRight();
drawingRect.top = getPaddingTop();
drawingRect.bottom = h - getPaddingBottom();
//The need to be recreated because they depend on the size of the view.
valShader = null;
satShader = null;
alphaShader = null;
// Clear those bitmap caches since the size may have changed.
satValBackgroundCache = null;
hueBackgroundCache = null;
setUpSatValRect();
setUpHueRect();
setUpAlphaRect();
}
private void setUpSatValRect(){
//Calculate the size for the big color rectangle.
final Rect dRect = drawingRect;
int left = dRect.left + BORDER_WIDTH_PX;
int top = dRect.top + BORDER_WIDTH_PX;
int bottom = dRect.bottom - BORDER_WIDTH_PX;
int right = dRect.right - BORDER_WIDTH_PX - panelSpacingPx - huePanelWidthPx;
if( showAlphaPanel ){
bottom -= ( alphaPanelHeightPx + panelSpacingPx );
}
satValRect = new Rect( left, top, right, bottom );
}
private void setUpHueRect(){
//Calculate the size for the hue slider on the left.
final Rect dRect = drawingRect;
int left = dRect.right - huePanelWidthPx + BORDER_WIDTH_PX;
int top = dRect.top + BORDER_WIDTH_PX;
int bottom = dRect.bottom - BORDER_WIDTH_PX -
( showAlphaPanel ? ( panelSpacingPx + alphaPanelHeightPx ) : 0 );
int right = dRect.right - BORDER_WIDTH_PX;
hueRect = new Rect( left, top, right, bottom );
}
private void setUpAlphaRect(){
if( ! showAlphaPanel ) return;
final Rect dRect = drawingRect;
int left = dRect.left + BORDER_WIDTH_PX;
int top = dRect.bottom - alphaPanelHeightPx + BORDER_WIDTH_PX;
int bottom = dRect.bottom - BORDER_WIDTH_PX;
int right = dRect.right - BORDER_WIDTH_PX;
alphaRect = new Rect( left, top, right, bottom );
alphaPatternDrawable = new AlphaPatternDrawable( DrawingUtils.dpToPx( getContext(), 4 ) );
alphaPatternDrawable.setBounds( Math.round( alphaRect.left ), Math
.round( alphaRect.top ), Math.round( alphaRect.right ), Math
.round( alphaRect.bottom ) );
}
/**
* Set a OnColorChangedListener to get notified when the color
* selected by the user has changed.
*
* @param listener the listener
*/
public void setOnColorChangedListener( OnColorChangedListener listener ){
onColorChangedListener = listener;
}
/**
* Get the current color this view is showing.
*
* @return the current color.
*/
public int getColor(){
return Color.HSVToColor( alpha, new float[]{ hue, sat, val } );
}
/**
* Set the color the view should show.
*
* @param color The color that should be selected. #argb
*/
public void setColor( int color ){
setColor( color, false );
}
/**
* Set the color this view should show.
*
* @param color The color that should be selected. #argb
* @param callback If you want to get a callback to your OnColorChangedListener.
*/
public void setColor( int color, boolean callback ){
int alpha = Color.alpha( color );
int red = Color.red( color );
int blue = Color.blue( color );
int green = Color.green( color );
float[] hsv = new float[ 3 ];
Color.RGBToHSV( red, green, blue, hsv );
this.alpha = alpha;
hue = hsv[ 0 ];
sat = hsv[ 1 ];
val = hsv[ 2 ];
if( callback && onColorChangedListener != null ){
onColorChangedListener
.onColorChanged( Color.HSVToColor( this.alpha, new float[]{ hue, sat, val } ) );
}
invalidate();
}
/**
* Set if the user is allowed to adjust the alpha panel. Default is false.
* If it is set to false no alpha will be set.
*
* @param visible {@code true} to show the alpha slider
*/
public void setAlphaSliderVisible( boolean visible ){
if( showAlphaPanel != visible ){
showAlphaPanel = visible;
/*
* Force recreation.
*/
valShader = null;
satShader = null;
alphaShader = null;
hueBackgroundCache = null;
satValBackgroundCache = null;
requestLayout();
}
}
/**
* Set the color of the tracker slider on the hue and alpha panel.
*
* @param color a color value
*/
@SuppressWarnings("unused")
public void setSliderTrackerColor( int color ){
sliderTrackerColor = color;
hueAlphaTrackerPaint.setColor( sliderTrackerColor );
invalidate();
}
/**
* Get color of the tracker slider on the hue and alpha panel.
*
* @return the color value
*/
@SuppressWarnings("unused")
public int getSliderTrackerColor(){
return sliderTrackerColor;
}
/**
* Set the color of the border surrounding all panels.
*
* @param color a color value
*/
@SuppressWarnings("unused")
public void setBorderColor( int color ){
borderColor = color;
invalidate();
}
/**
* Get the color of the border surrounding all panels.
*/
@SuppressWarnings("unused")
public int getBorderColor(){
return borderColor;
}
/**
* Set the text that should be shown in the
* alpha slider. Set to null to disable text.
*
* @param res string resource id.
*/
@SuppressWarnings("unused")
public void setAlphaSliderText( int res ){
String text = getContext().getString( res );
setAlphaSliderText( text );
}
/**
* Set the text that should be shown in the
* alpha slider. Set to null to disable text.
*
* @param text Text that should be shown.
*/
public void setAlphaSliderText( String text ){
alphaSliderText = text;
invalidate();
}
/**
* Get the current value of the text
* that will be shown in the alpha
* slider.
*
* @return the slider text
*/
@SuppressWarnings("unused")
public String getAlphaSliderText(){
return alphaSliderText;
}
private class BitmapCache {
public Canvas canvas;
public Bitmap bitmap;
public float value;
}
public interface OnColorChangedListener {
void onColorChanged( int newColor );
}
}
|
public class Main {
public static void main(String[] args) {
// create threads and start them using the class RunnableWorker
Thread worker1 = new Thread(new RunnableWorker());
worker1.setName("worker-1");
worker1.start();
Thread worker2 = new Thread(new RunnableWorker());
worker2.setName("worker-2");
worker2.start();
Thread worker3 = new Thread(new RunnableWorker());
worker3.setName("worker-3");
worker3.start();
}
}
|
package top.piao888.hbgc.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import top.piao888.hbgc.domain.Funs;
@Mapper
public interface FunsMapper {
int deleteByPrimaryKey(Long fid);
int insert(Funs record);
Funs selectByPrimaryKey(Long fid);
List<Funs> selectAll();
int updateByPrimaryKey(Funs record);
List<Funs> selectMenu();
}
|
package category.bitOperation;
public class CalCharacters {
}
|
package pl.ark.chr.buginator.client.sender;
/**
* Created by Arek on 2017-04-17.
*/
public interface HttpSender extends Sender {
void setEndpoint(String endpoint);
void setTimeout(int timeout);
void setTrustAllSsl(boolean trustAllSsl);
}
|
package laundry;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
public class DataStore {
static Connection conn = null;
public static boolean connectDB(String dbServer, int dbPort, String dbName, String userId, String userPwd) {
String dbURL = "jdbc:mariadb://" + dbServer + ":" + dbPort + "/" + dbName + "?useUnicode=yes&characterEncoding=UTF-8";
try {
Class.forName("org.mariadb.jdbc.Driver");
conn = DriverManager.getConnection(dbURL, userId, userPwd);
} catch(Exception e) {
String strMsg = "DB에 접속할 수 없습니다. 설정을 확인하여야 합니다.\r\n오류메시지는 다음과 같습니다.\r\n(" + e.getLocalizedMessage() + ")";
JOptionPane.showMessageDialog(null, strMsg);
return false;
}
return true;
}
public static boolean insertClothes(String strNickName, String strKind, int period) {
boolean bSuccess = false;
try {
int index = 1;
Calendar calendar = Calendar.getInstance();
Date regDate = calendar.getTime();
String sqlString = "INSERT INTO laundry.tb_laundry (NICKNAME, KIND, REGDATE, PERIOD, LASTDATE, NEXTDATE) VALUES (?, ?, ?, ?, ?, ?)";
PreparedStatement ps = conn.prepareStatement(sqlString);
ps.setString(index++, strNickName);
ps.setString(index++, strKind);
ps.setDate(index++, new java.sql.Date(regDate.getTime()));
ps.setInt(index++, period);
ps.setDate(index++, new java.sql.Date(regDate.getTime()));
calendar.add(Calendar.DATE, period);
Date nextDate = calendar.getTime();
ps.setDate(index++, new java.sql.Date(nextDate.getTime()));
ps.executeUpdate();
ps.close();
bSuccess = true;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
return bSuccess;
}
public static boolean updateLaundry(String strNickName, int year, int month, int day) {
boolean bSuccess = false;
int period = getPeriod(strNickName);
try {
int index = 1;
Calendar calendar = Calendar.getInstance();
calendar.set(year, month - 1, day);
Date laundryDate = calendar.getTime();
String sqlString = "UPDATE laundry.tb_laundry SET LASTDATE = ?, NEXTDATE = ? WHERE NICKNAME = ?";
PreparedStatement ps = conn.prepareStatement(sqlString);
ps.setDate(index++, new java.sql.Date(laundryDate.getTime()));
calendar.add(Calendar.DAY_OF_YEAR, period);
Date nextDate = calendar.getTime();
ps.setDate(index++, new java.sql.Date(nextDate.getTime()));
ps.setString(index++, strNickName);
ps.executeUpdate();
ps.close();
bSuccess = true;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
return bSuccess;
}
public static void deleteLaundry(String laundryName) {
}
public static int fillScheduleTableEntry(DefaultTableModel scheduleTableEntry, int year, int month, int day) {
scheduleTableEntry.setRowCount(0);
Calendar calendar = Calendar.getInstance();
calendar.set(year, month - 1, day);
String strDate = Integer.toString(year) + "-" + Integer.toString(month) + "-" + Integer.toString(day);
int rowCount = 0;
try {
String sqlString = "SELECT * FROM laundry.tb_laundry WHERE NEXTDATE = '" + strDate + "'";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sqlString);
while (rs.next()) {
Object[] rowData = new Object[5];
int rowIndex = 0;
rowData[rowIndex++] = rs.getString("NICKNAME");
rowData[rowIndex++] = rs.getString("KIND");
rowData[rowIndex++] = Integer.toString(rs.getInt("PERIOD"));
rowData[rowIndex++] = rs.getDate("LASTDATE").toLocalDate();
rowData[rowIndex++] = rs.getDate("NEXTDATE").toLocalDate();
scheduleTableEntry.addRow(rowData);
rowCount++;
}
rs.close();
stmt.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
return rowCount;
}
public static int listClothes(DefaultTableModel clothesTableEntry, String strCbKind) {
clothesTableEntry.setRowCount(0);
int rowCount = 0;
try {
String sqlString = "SELECT * FROM laundry.tb_laundry";
if (strCbKind.equalsIgnoreCase("전체") == false) {
sqlString += " WHERE KIND = '" + strCbKind + "'";
}
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sqlString);
while (rs.next()) {
Object[] rowData = new Object[6];
int rowIndex = 0;
rowData[rowIndex++] = rs.getString("NICKNAME");
rowData[rowIndex++] = rs.getString("KIND");
rowData[rowIndex++] = rs.getDate("REGDATE").toLocalDate();
rowData[rowIndex++] = Integer.toString(rs.getInt("PERIOD"));
rowData[rowIndex++] = rs.getDate("LASTDATE").toLocalDate();
rowData[rowIndex++] = rs.getDate("NEXTDATE").toLocalDate();
clothesTableEntry.addRow(rowData);
rowCount++;
}
rs.close();
stmt.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
return rowCount;
}
public static void flushTable() {
try {
Statement statement = conn.createStatement();
statement.executeUpdate("TRUNCATE laundry.tb_laundry");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
public static ArrayList<String> getNickNameList() {
ArrayList<String> strNickNameList = new ArrayList<>();
try {
String sqlString = "SELECT NICKNAME FROM laundry.tb_laundry";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sqlString);
while (rs.next()) {
strNickNameList.add(rs.getString("NICKNAME"));
}
rs.close();
stmt.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
return strNickNameList;
}
private static int getPeriod(String strNickName) {
int period = -1;
try {
String sqlString = "SELECT PERIOD FROM laundry.tb_laundry WHERE NICKNAME = '" + strNickName + "'";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sqlString);
if (rs.next()) {
period = rs.getInt("PERIOD");
}
rs.close();
stmt.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
return period;
}
}
|
package com.guli.order.feign.impl;
import com.guli.order.entity.Course;
import com.guli.order.feign.CourseFeign;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class CourseFeignImpl implements CourseFeign {
@Override
public Course getByIdCourseInfo(String courseId) {
return null;
}
}
|
package com.shopify.admin;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.servlet.LocaleResolver;
import com.shopify.admin.board.AdminBoardData;
import com.shopify.common.SpConstants;
import com.shopify.common.util.UtilFn;
import com.shopify.mapper.AdminMapper;
import com.shopify.shop.ShopData;
/**
* Admin 서비스
*
*/
@Service
@Transactional
public class AdminService {
private Logger LOGGER = LoggerFactory.getLogger(AdminService.class);
@Autowired private AdminMapper adminMapper;
@Autowired private MessageSource messageSource;
@Autowired LocaleResolver localeResolver;
@Autowired private UtilFn util;
public int insertAdmin(AdminData admin){
return adminMapper.insertAdmin(admin);
}
public int updateAdmin(AdminData admin){
return adminMapper.updateAdmin(admin);
}
public int selectAdminCount(AdminData admin){
return adminMapper.selectAdminCount(admin);
}
public int selectAdminPasswdCount(AdminData admin){
return adminMapper.selectAdminPasswdCount(admin);
}
public AdminData selectAdmin(AdminData admin){
return adminMapper.selectAdmin(admin);
}
public AdminData selectAdminPasswd(AdminData admin){
return adminMapper.selectAdminPasswd(admin);
}
/**
* 운영관리 > 관리자 목록 조회
* @return
*/
public Map<String, Object> selectAdminList(HttpSession sess , AdminData adminData) {
AdminData ad = (AdminData) sess.getAttribute(SpConstants.ADMIN_SESSION_KEY);
adminData.setLocale(ad.getLocale());
String searchWord = adminData.getSearchWord();
//검색조건 이름일 경우 암호화 처리
adminData.setSearchWordAese(util.getAESEncrypt(SpConstants.ENCRYPT_KEY, searchWord));
int dataCount = adminMapper.selectAllAdminCount(adminData);
int currentPage = adminData.getCurrentPage(); //현제 페이지
int pageSize = adminData.getPageSize(); // 페이지 당 데이터 수
int pageBlockSize = SpConstants.PAGE_BLOCK_SIZE; // 페이지 블럭 수
Map<String, Object> paging = new HashMap<String, Object>(); //페이징 정보 리스트 선언
List<AdminData> adminList = new ArrayList<AdminData>(); //데이터 리스트
List<AdminData> returnList = new ArrayList<AdminData>();//복호화처리한 데이터 리스트
if (dataCount > 0) {
paging = util.getPagingData(dataCount, pageSize, pageBlockSize, currentPage); //페이징 데이터 생성
adminData.setStartRow(Integer.parseInt(paging.get("startRow").toString())); // 데이터 시작 위치
adminData.setTotalPageNum(Integer.parseInt(paging.get("totalPageNum").toString())); // 최종데이터
adminList = adminMapper.selectAllAdmin(adminData);//데이터 리스트
for(AdminData item : adminList){
String adminName = util.getAESDecrypt(SpConstants.ENCRYPT_KEY, item.getAdminName());
String adminPhoneNumber = util.getAESDecrypt(SpConstants.ENCRYPT_KEY, item.getAdminPhoneNumber());
item.setAdminName(adminName);
item.setAdminPhoneNumber(adminPhoneNumber);
returnList.add(item);
}
}
// 리턴 변수 선언
Map<String, Object> map = new HashMap<String, Object>();
map.put("list", returnList);
map.put("paging", paging);
return map;
}
/**
* 운영관리 > 관리자 상세조회
* @return
*/
public List<AdminData> adminShow(AdminData admin, HttpSession sess) {
AdminData ad = (AdminData) sess.getAttribute(SpConstants.ADMIN_SESSION_KEY);
return adminMapper.adminShow(admin);
}
/**
* 운영관리 > 관리자 삭제
* @return
*/
public int deleteAdminList(AdminData adminData , HttpSession sess){
AdminData ad = (AdminData) sess.getAttribute(SpConstants.ADMIN_SESSION_KEY);
int result = 0;
String key = adminData.getCkBox();
String[] array = key.split(",");
ArrayList list = new ArrayList(Arrays.asList(array));
Iterator rootItr = list.iterator();
while (rootItr.hasNext()) {
String id = (String) rootItr.next();
adminMapper.deleteAdminList(id);
result++;
}
return result;
}
/**
* 운영관리 > 관리자 수정
* @return
*/
public int updateAdminList(AdminData admin , HttpSession sess){
AdminData ad = (AdminData) sess.getAttribute(SpConstants.ADMIN_SESSION_KEY);
String adminPhoneNumber = util.getAESEncrypt(SpConstants.ENCRYPT_KEY, admin.getAdminPhoneNumber());
//암호화 처리
admin.setAdminPhoneNumber(adminPhoneNumber);
String adminPasswd = admin.getAdminPasswd();
if(adminPasswd != null && !"".equals(adminPasswd)) {
admin.setAdminPasswd(util.getBCryptDecrypt(adminPasswd));
}
int result = adminMapper.updateAdminList(admin);
return result;
}
/**
* 운영관리 > 관리자 상세조회
* @return
*/
public AdminData selectAdminShow(AdminData adminData, HttpSession sess) {
AdminData ad = (AdminData) sess.getAttribute(SpConstants.ADMIN_SESSION_KEY);
AdminData adminList = adminMapper.selectAdminShow(adminData);
String adminName = "";
String adminPhoneNumber = "";
try {
adminName = util.getAESDecrypt(SpConstants.ENCRYPT_KEY, adminList.getAdminName());
} catch (Exception e) {
e.getStackTrace();
}
try {
adminPhoneNumber = util.getAESDecrypt(SpConstants.ENCRYPT_KEY, adminList.getAdminPhoneNumber());
} catch (Exception e) {
e.getStackTrace();
}
adminList.setAdminName(adminName);
adminList.setAdminPhoneNumber(adminPhoneNumber);
return adminMapper.selectAdminShow(adminData);
}
/**
* 관리자 로그인
* @return
*/
public AdminData selectAdminLogin(AdminData admin){
return adminMapper.selectAdminLogin(admin);
}
/**
* 관리자 권한 설정
* @return
*/
public List<AdminScopeData> selectAdminScope(AdminScopeData admin){
return adminMapper.selectAdminScope(admin);
}
/**
* 운영관리 > 관리자 등록
* @return
*/
public int insertAdminListPop(AdminData admin , HttpSession sess){
AdminData ad = (AdminData) sess.getAttribute(SpConstants.ADMIN_SESSION_KEY);
String adminPasswd = util.getBCryptDecrypt(admin.getAdminPasswd());
String adminName = util.getAESEncrypt(SpConstants.ENCRYPT_KEY, admin.getAdminName());
String adminPhoneNumber = util.getAESEncrypt(SpConstants.ENCRYPT_KEY, admin.getAdminPhoneNumber());
//암호화 처리
admin.setAdminPasswd(adminPasswd);
admin.setAdminName(adminName);
admin.setAdminPhoneNumber(adminPhoneNumber);
//id(email)중복확인
int chk = adminMapper.chkAdmin(admin);
if(chk > 0) {
return -1;
}else {
return adminMapper.insertAdminListPop(admin);
}
}
/**
* 운영관리 > 관리자 등록
* @return
*/
public int editAdminPassword(AdminData admin, HttpSession sess){
AdminData ad = (AdminData) sess.getAttribute(SpConstants.ADMIN_SESSION_KEY);
String passwd = util.getBCryptDecrypt(admin.getPasswd());
admin.setPasswd(passwd);
return adminMapper.updatePassword(admin);
}
}
|
package cn.czfshine.network.project.cs.bioclient;
import cn.czfshine.network.project.cs.config.Config;
import cn.czfshine.network.project.cs.dto.Message;
import io.datafx.controller.ViewController;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.Random;
/**
* 界面的控制器
*/
@ViewController(value = "/cs/sample.fxml")
public class ClientController {
/**
* 输出文本框
*/
@FXML
private TextArea output;
/**
* 断开连接按钮
*/
@FXML
private Button disconnectButton;
/**
* 端口文本框
*/
@FXML
private TextField serverport;
/**
* 消息文本框
*/
@FXML
private TextField messageTextBox;
/**
* 服务器ip文本框
*/
@FXML
private TextField severip;
/**
* 用户名
*/
@FXML
private TextField username;
/**
* 日志文本框
*/
@FXML
private TextArea logText;
/**
* 连接按钮
*/
@FXML
private Button connectButton;
/**
* 发送按钮
*/
@FXML
private Button sendButton;
/**
* 初始化函数,在载入界面前运行
*/
@PostConstruct
public void init() {
serverport.setText(String.valueOf(Config.DEFAULTSERVERPORT));
//随机用户名
username.setText("czfshine"+(new Random().nextInt(1000)));
disconnectButton.setDisable(true);
sendButton.setDisable(true);
}
/**
* 日志缓存
*/
private StringBuilder logcache =new StringBuilder();
public void log(String msg){
logcache.append(msg+"\n");
logText.setText(logcache.toString());
logText.setScrollLeft(Double.MAX_VALUE);
logText.setScrollTop(Double.MAX_VALUE);
}
private Client client;
@FXML
void Onconnect(ActionEvent event) {
String IP = severip.getText();
String text = serverport.getText();
int port=Integer.valueOf(text);
log("开始连接服务器"+IP+":"+port);
client = new Client();
try {
client.connect(IP,port);
log("连接成功");
String usernameText = username.getText();
client.sendLogin(usernameText);
connectButton.setDisable(true);
disconnectButton.setDisable(false);
sendButton.setDisable(false);
} catch (IOException e) {
log("连接失败");
log(e.getMessage());
e.printStackTrace();
}
Client.MessageHandler messageHandler = message -> {
log("收到消息"+message.toString());
receiveMessage(message);
return false;
};
client.setHandle(messageHandler);
Client.ErrorHandler errorHandler = () -> {
log("服务器已自动关闭");
connectButton.setDisable(false);
disconnectButton.setDisable(true);
sendButton.setDisable(true);
};
client.setErrorHandler(errorHandler);
System.out.println(1);
}
private void sendlogout(){
client.close(username.getText());
}
@FXML
void OnDisconnect(ActionEvent event) {
log("准备向服务器发送离线消息");
Thread thread = new Thread(this::sendlogout);
thread.setDaemon(true);
thread.start();
connectButton.setDisable(false);
disconnectButton.setDisable(true);
sendButton.setDisable(true);
}
private void receiveMessage(Message message){
String text = output.getText();
text+=(message.getWho()+":"+message.getContent()+"\n");
output.setText(text);
output.setScrollTop(Double.MAX_VALUE);
output.setScrollLeft(Double.MAX_VALUE);
}
private Message message;
private void sender(){
try {
client.sendMessage(message);
} catch (IOException e) {
log("向服务器发送消息失败");
e.printStackTrace();
return ;
}
log("向服务器发送消息成功");
}
@FXML
void OnSend(ActionEvent event) {
message = new Message();
String usernameText = username.getText();
String text = messageTextBox.getText();
message.setContent(text);
message.setWho(usernameText);
log("准备向服务器发送消息");
Thread thread = new Thread(this::sender);
thread.setDaemon(true);
thread.start();
}
}
|
package com.lbins.FruitsBusiness.bean;
import java.io.Serializable;
public class Response implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
public Response(int code){
Response.code = code;
}
public static int code;
public Response(){
super();
}
}
|
package com.codepath.nytimes.models;
import org.json.JSONArray;
import org.json.JSONException;
import java.util.ArrayList;
import java.util.List;
public class PopularArticle {
public String webUrl;
public String imageUrl;
public String title;
public static List<PopularArticle> fromJson(JSONArray movieJsonResults) {
ArrayList<PopularArticle> result = new ArrayList<>();
for(int i = 0; i < movieJsonResults.length(); i++ ) {
PopularArticle p = new PopularArticle();
try {
p.title = movieJsonResults.getJSONObject(i).getString("title");
p.webUrl = movieJsonResults.getJSONObject(i).getString("url");
JSONArray j = movieJsonResults.getJSONObject(i).getJSONArray("multimedia");
if(j !=null && j.length() > 0) {
p.imageUrl = j.getJSONObject(0).getString("url");
}
result.add(p);
} catch (JSONException e) {
e.printStackTrace();
}
}
return result;
}
}
|
/*
* 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 MultiClient;
import TokenizerUtils.VietTokenizerSingleton;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTextArea;
/**
*
* @author Admin
*/
public class ServerFrm extends javax.swing.JFrame {
/**
* Creates new form ServerFrm
*/
private VietTokenizerSingleton vietTokenizer;
private final int PORT = 1993;
private ServerSocket serverSocket = null;
private Socket socket = null;
private ClientService clientService;
public ServerFrm() {
super("Server tokenizer");
try {
initComponents();
vietTokenizer = VietTokenizerSingleton.getInstance();
clientService = new ClientService();
clientService.connectServer();
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
class multiClient implements Runnable {
private Socket clientSock = null;
private JTextArea room = null;
public multiClient(Socket clientSock, JTextArea room) {
this.clientSock = clientSock;
this.room = room;
}
@Override
public void run() {
DataInputStream dis = null;
DataOutputStream dos = null;
String msg = null;
try {
dis = new DataInputStream(clientSock.getInputStream());
dos = new DataOutputStream(clientSock.getOutputStream());
while (true) {
msg = dis.readUTF();
if (msg != null && !msg.isEmpty()) {
multiRequest mRequest = new multiRequest(dos, msg);
Thread requet = new Thread(mRequest);
requet.run();
}
}
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
class multiRequest implements Runnable {
private DataOutputStream dos = null;
private String msg = null;
public multiRequest(DataOutputStream dos, String msg) {
this.dos = dos;
this.msg = msg;
}
@Override
public void run() {
try {
msg = vietTokenizer.processTokenizer(msg);
RoomMain.append("Client: " + msg + "\n");
msg = requestTensorflow(msg);
dos.writeUTF(msg);
RoomMain.append("Client-token: " + msg + "\n");
// System.out.println("MSG-res:" + msg);
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
public String requestTensorflow(String s) {
String result = "";
try {
result = clientService.requestFromServer(s);
result=result.replace("_", " ");
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
return result;
}
public void ListenClient() {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
serverSocket = new ServerSocket(PORT);
while (true) {
multiClient mc;
mc = new multiClient(serverSocket.accept(), RoomMain);
System.out.println("connect ");
Thread tr = new Thread(mc);
tr.start();
}
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
});
thread.start();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
RoomMain = new javax.swing.JTextArea();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
RoomMain.setColumns(20);
RoomMain.setRows(5);
jScrollPane1.setViewportView(RoomMain);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 278, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ServerFrm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ServerFrm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ServerFrm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ServerFrm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
ServerFrm sfrm = new ServerFrm();
sfrm.setVisible(true);
sfrm.ListenClient();
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextArea RoomMain;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration//GEN-END:variables
}
|
// Sun Certified Java Programmer
// Chapter 8; P681_1
// Inner Classes
class BigOuter {
static class Nested { }
}
|
package de.adesso.gitstalker;
public class ApplicationTest {
}
|
package pl.gabinetynagodziny.officesforrent.provider.mailer;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
@Component
public class SignUpMailer {
private JavaMailSender emailSender;
private SignUpMailTextFactory signUpMailTextFactory;
public SignUpMailer(JavaMailSender emailSender, SignUpMailTextFactory signUpMailTextFactory){
this.emailSender = emailSender;
this.signUpMailTextFactory = signUpMailTextFactory;
}
public void sendConfirmationLink(String email, String token){
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(email);
message.setSubject(signUpMailTextFactory.getConfirmationMailSubject());
message.setText(signUpMailTextFactory.getConfirmationMailText(token));
emailSender.send(message);
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package datalayer.student;
import java.sql.ResultSet;
import java.sql.SQLException;
import model.student.Student;
import util.DBConnection;
import util.DBHandle;
/**
*
* @author Mampitiya
*/
public class StudentDA {
public static int addStudent(Student student) throws SQLException, ClassNotFoundException{
String sql = "Insert INTO student(studentID, first_name,last_name,address,telephone,guardian_name, guardian_number, gender) VALUES ('" + student.getStudentID() + "','" + student.getFirst_name() + "','" + student.getLast_name() + "','" + student.getAddress() + "','" + student.getTelephone() + "','" + student.getGuardian_name() + "','" + student.getGuardian_number() + "','" + student.getGender() + "')";
int res = DBHandle.setData(DBConnection.getConnection(), sql);
return res;
}
public static Student searchStudent(String studetnID) throws SQLException, ClassNotFoundException {
/*String sql = "Select * From student Where studentID='" + studetnID + "'";
ResultSet rst = DBHandle.getData(DBConnection.getConnection(), sql);
if (rst.next()) {
String first_name = rst.getString("first_name");
String last_name = rst.getString("last_name");
String address = rst.getString("address");
int telephone = rst.getInt("telephone");
String guardian_name = rst.getString("guardian_name");
int guardian_number = rst.getInt("guardian_number");
int bit = rst.getInt("gender");
boolean gender = false;
if(bit == 1)
gender = true;
Student student = new Student(studetnID, first_name, last_name, address, telephone, guardian_name, guardian_number, gender);
return student;
} else {
return null;
}*/
return null;
}
public static int deleteStudent(String studentID) throws SQLException, ClassNotFoundException {
String sql = "Delete From student Where studentID='" + studentID + "'";
int rst = DBHandle.setData(DBConnection.getConnection(), sql);
return rst;
}
public static int updateStudent(Student student) throws SQLException, ClassNotFoundException {
String sql = "Update student set first_name='" + student.getFirst_name() + "', last_name='" + student.getLast_name() + "',address='" + student.getAddress() + "',telephone='" + student.getTelephone() + "',guardian_name='" + student.getGuardian_name() + "', guardian_number='" + student.getGuardian_number() + "',gender='" + student.getGender() + "' Where studentID='" + student.getStudentID() + "'";
int rst = DBHandle.setData(DBConnection.getConnection(), sql);
return rst;
}
}
|
package com.link.admin.controller;
import com.jfinal.core.Controller;
import com.jfinal.core.JFinal;
import com.jfinal.kit.PathKit;
import com.jfinal.upload.UploadFile;
import com.link.common.util.ResultFile;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* Created by linkzz on 2017-07-13.
*/
public class FileController extends Controller {
public void upload() {
String path = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
//UploadFile file = getFile("imgFile", PathKit.getWebRootPath() + "/temp");
UploadFile file = getFile();
File source = file.getFile();
String fileName = file.getFileName();
String extension = fileName.substring(fileName.lastIndexOf("."));
String prefix;
if(".png".equals(extension) || ".jpg".equals(extension) || ".gif".equals(extension)){
prefix = "img";
fileName = generateWord() + extension;
}else{
prefix = "file";
}
ResultFile json = new ResultFile();
try {
FileInputStream fis = new FileInputStream(source);
File targetDir = new File(PathKit.getWebRootPath() + "/upload/" + prefix + "/u/" + path);
if (!targetDir.exists()) {
targetDir.mkdirs();
}
File target = new File(targetDir, fileName);
if (!target.exists()) {
target.createNewFile();
}
FileOutputStream fos = new FileOutputStream(target);
byte[] bts = new byte[300];
while (fis.read(bts, 0, 300) != -1) {
fos.write(bts, 0, 300);
}
fos.close();
fis.close();
json.setError(0);
//json.setMsg("上传成功");
json.setUrl(getRequest().getContextPath()+"/upload/" + prefix + "/u/" + path + "/" + fileName);
source.delete();
} catch (FileNotFoundException e) {
json.setError(1);
//json.setMsg("上传出现错误,请稍后再上传");
} catch (IOException e) {
json.setError(2);
//json.setMsg("文件写入服务器出现错误,请稍后再上传");
}
renderJson(json);
}
public void download(){
String path = getPara(0);
String img = PathKit.getWebRootPath() + "/upload/img/u/" + path.replaceAll("_", "/");
//ZipUtil.zip(img, PathKit.getWebRootPath() + "/img/temp/" + path);
renderFile("#(ctx)/upload/img/temp/" + path + ".zip");
}
private String generateWord() {
String[] beforeShuffle = new String[] { "2", "3", "4", "5", "6", "7",
"8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
"K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
"W", "X", "Y", "Z" };
List<String> list = Arrays.asList(beforeShuffle);
Collections.shuffle(list);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < list.size(); i++) {
sb.append(list.get(i));
}
String afterShuffle = sb.toString();
String result = afterShuffle.substring(5, 9);
return result;
}
/**
* 文件管理
*/
public void fileManager() {
String[] fileTypes = new String[] { "gif", "jpg", "jpeg", "png", "bmp" };
String currentPath = PathKit.getWebRootPath() + "/upload/";
File currentPathFile = new File(currentPath);
final List<Hashtable> fileList = new ArrayList<Hashtable>();
if (currentPathFile.listFiles() != null) {
for (File file : currentPathFile.listFiles()) {
Hashtable<String, Object> hash = new Hashtable<String, Object>();
String fileName = file.getName();
if (file.isDirectory()) {
hash.put("is_dir", true);
hash.put("has_file", (file.listFiles() != null));
hash.put("filesize", 0L);
hash.put("is_photo", false);
hash.put("filetype", "");
} else if (file.isFile()) {
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
hash.put("is_dir", false);
hash.put("has_file", false);
hash.put("filesize", file.length());
hash.put("is_photo", Arrays.<String> asList(fileTypes).contains(fileExt));
hash.put("filetype", fileExt);
}
hash.put("filename", fileName);
hash.put("datetime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(file.lastModified()));
fileList.add(hash);
}
}
// 排序形式,name or size or type
String order = getPara("order") != null ? getPara("order").toLowerCase() : "name";
if ("size".equals(order)) {
Collections.sort(fileList, new SizeComparator());
} else if ("type".equals(order)) {
Collections.sort(fileList, new TypeComparator());
} else {
Collections.sort(fileList, new NameComparator());
}
Map<String, Object> result = new HashMap<String, Object>() {
private static final long serialVersionUID = 1L;
{
put("moveup_dir_path", "");
put("current_dir_path", "");
put("current_url", JFinal.me().getContextPath() + "/upload/");
put("total_count", fileList.size());
put("file_list", fileList);
}
};
renderJson(result);
}
public class NameComparator implements Comparator {
@Override
public int compare(Object a, Object b) {
Hashtable hashA = (Hashtable) a;
Hashtable hashB = (Hashtable) b;
if (((Boolean) hashA.get("is_dir")) && !((Boolean) hashB.get("is_dir"))) {
return -1;
} else if (!((Boolean) hashA.get("is_dir")) && ((Boolean) hashB.get("is_dir"))) {
return 1;
} else {
return ((String) hashA.get("filename")).compareTo((String) hashB.get("filename"));
}
}
}
public class SizeComparator implements Comparator {
@Override
public int compare(Object a, Object b) {
Hashtable hashA = (Hashtable) a;
Hashtable hashB = (Hashtable) b;
if (((Boolean) hashA.get("is_dir")) && !((Boolean) hashB.get("is_dir"))) {
return -1;
} else if (!((Boolean) hashA.get("is_dir")) && ((Boolean) hashB.get("is_dir"))) {
return 1;
} else {
if (((Long) hashA.get("filesize")) > ((Long) hashB.get("filesize"))) {
return 1;
} else if (((Long) hashA.get("filesize")) < ((Long) hashB.get("filesize"))) {
return -1;
} else {
return 0;
}
}
}
}
public class TypeComparator implements Comparator {
@Override
public int compare(Object a, Object b) {
Hashtable hashA = (Hashtable) a;
Hashtable hashB = (Hashtable) b;
if (((Boolean) hashA.get("is_dir")) && !((Boolean) hashB.get("is_dir"))) {
return -1;
} else if (!((Boolean) hashA.get("is_dir")) && ((Boolean) hashB.get("is_dir"))) {
return 1;
} else {
return ((String) hashA.get("filetype")).compareTo((String) hashB.get("filetype"));
}
}
}
}
|
package Lesson19and20.task1;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class SerHorse {
public static void main(String[] args) {
Halter halter = new Halter(3);
Horse animal = new Horse("pigeon", halter);
System.out.println("Halter size before serialization: " + animal.getHalter().getSize());
try {
FileOutputStream fs = new FileOutputStream("testSer.ser");
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(animal);
os.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
FileInputStream fis = new FileInputStream("testSer.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
animal = (Horse) ois.readObject();
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Halter size after serialization: " + animal.getHalter());
}
}
|
package lesson30.hw2lastedition;
import java.util.HashSet;
import java.util.Set;
public class EmployeeDAO {
private static EmployeeDAO instance;
public static EmployeeDAO getInstance() {
if (instance == null) {
instance = new EmployeeDAO();
}
return instance;
}
private Set<Employee> employees = new HashSet<>();
public Employee add(Employee employee) {
employees.add(employee);
return employee;
}
public void remove(Employee employee) {
employees.remove(employee);
}
public Set<Employee> getAll() {
return employees;
}
public static Set<Employee> employeesByProject(String projectName) {
Set<Employee> result = new HashSet<>();
for (Employee employee : instance.getAll()) {
for (Project pro : employee.getProjects()) {
if (pro.getName().equals(projectName))
result.add(employee);
}
}
return result;
}
public static Set<Project> projectsByEmployee(Employee employee) {
return employee.getProjects();
}
public static Set<Employee> employeesByDepartmentWithoutProjects(DepartmentType departmentType) {
Set<Employee> result = new HashSet<>();
for (Department department : DepartmentDAO.getInstance().getAll()) {
if (department.getType().equals(departmentType)) {
for (Employee employee : instance.getAll()) {
if (employee.getProjects().isEmpty() &&
employee.getDepartment().getType().equals(departmentType))
result.add(employee);
}
}
}
return result;
}
public static Set<Employee> employeesByTeamLead(Employee lead) {
Set<Employee> result = new HashSet<>();
if (lead.getPosition().equals(Position.TEAM_LEAD))
result.addAll(employeesByProjectEmployee(lead));
return result;
}
public static Set<Employee> employeesByCustomerProjects(Customer customer) {
Set<Employee> result = new HashSet<>();
for (Employee employeeFromDAO : instance.getAll()) {
for (Project project : employeeFromDAO.getProjects()) {
if (project.getCustomer().equals(customer))
result.add(employeeFromDAO);
}
}
return result;
}
public static Set<Employee> employeesByProjectEmployee(Employee employee) {
Set<Employee> result = new HashSet<>();
for (Employee employeeFromDAO : instance.getAll()) {
for (Project project : employeeFromDAO.getProjects()) {
if (employee.getProjects().contains(project))
result.add(employeeFromDAO);
}
result.remove(employee);
}
return result;
}
public static Set<Employee> employeesWithoutProject() {
Set<Employee> result = new HashSet<>();
for (Employee employee : instance.getAll()) {
if (employee.getProjects().isEmpty()) {
result.add(employee);
}
}
return result;
}
public static Set<Employee> teamLeadsByEmployee(Employee employee) {
Set<Employee> result = new HashSet<>();
for (Project project : employee.getProjects()) {
if (identifyTeamLead(project) != null) {
result.add(identifyTeamLead(project));
}
}
return result;
}
private static Employee identifyTeamLead(Project project) {
for (Employee employee : instance.getAll()) {
if (employee.getProjects().contains(project) &&
employee.getPosition().equals(Position.TEAM_LEAD))
return employee;
}
return null;
}
}
|
package com.epam.bar.command.impl;
import com.epam.bar.command.*;
import com.epam.bar.command.marker.UserCommandMarker;
/**
* Moves an user to cocktail adding page
*
* @author Kirill Karalionak
* @version 1.0.0
*/
public class ToAddCocktailCommand implements Command, UserCommandMarker {
@Override
public CommandResult execute(RequestContext requestContext) {
return new CommandResult(new ForwardResponse(PagePath.ADD_COCKTAIL));
}
}
|
package com.example.kankan.adviewkankan;
import android.app.Dialog;
import android.media.Image;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class EmployeeAllProjectAcitivity extends AppCompatActivity implements View.OnClickListener {
private FirebaseAuth auth;
private FirebaseUser user;
private DatabaseReference myData;
private Toolbar toolbar;
private ImageView imgBack;
private RecyclerView recyclerView;
private String depertment="";
private Bundle bundle;
private List<Project> projectList;
private SwipeRefreshLayout swipeRefreshLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_employee_all_project_acitivity);
bundle=getIntent().getExtras();
depertment=bundle.getString("DEPT");
projectList=new ArrayList<>();
setTheToolbar();
imgBack=findViewById(R.id.imgEmployeeAllProjectActivityBack);
swipeRefreshLayout=findViewById(R.id.swipeRefreshLayoutEmployeeAllProjectActivity);
auth=FirebaseAuth.getInstance();
user=auth.getCurrentUser();
myData= FirebaseDatabase.getInstance().getReference();
swipeRefreshLayout.setRefreshing(true);
getTheProjectList();
imgBack.setOnClickListener(this);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(true);
getTheProjectList();
}
});
}
private void setTheRecyclerView(List<Project> list) {
recyclerView=findViewById(R.id.reViewEmployeeAllProjectActivity);
recyclerView.setLayoutManager(new LinearLayoutManager(EmployeeAllProjectAcitivity.this));
ProjectListAdapter adapter = new ProjectListAdapter(list, EmployeeAllProjectAcitivity.this);
recyclerView.setAdapter(adapter);
swipeRefreshLayout.setRefreshing(false);
}
private void getTheProjectList() {
myData.child("Project").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
projectList.clear();
for(DataSnapshot snapshot:dataSnapshot.getChildren())
{
Project project=snapshot.getValue(Project.class);
if(project.getDepertment().equalsIgnoreCase(depertment))
{
projectList.add(project);
}
setTheRecyclerView(projectList);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void setTheToolbar() {
toolbar=findViewById(R.id.toolbarEmployeeAllProjectActivity);
setSupportActionBar(toolbar);
}
@Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.imgEmployeeAllProjectActivityBack:
finish();
break;
}
}
}
|
package test;
import com.hp.hpl.jena.query.Dataset;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.tdb.TDBFactory;
import com.hp.hpl.jena.vocabulary.VCARD;
public class HelloWord {
public static void main(String[] args) {
// TODO Auto-generated method stub
// some definitions
String personURI = "http://somewhere/JohnSmith";
String givenName = "John";
String familyName = "Smith";
String fullName = givenName + " " + familyName;
// create an empty model
Model model = ModelFactory.createDefaultModel();
// create the resource
// and add the properties cascading style
Resource johnSmith
= model.createResource(personURI)
.addProperty(VCARD.FN, fullName)
.addProperty(VCARD.N,
model.createResource()
.addProperty(VCARD.Given, givenName)
.addProperty(VCARD.Family, familyName));
model.write(System.out);
System.out.println();
model.write(System.out, "RDF/XML-ABBREV");
System.out.println();
model.write(System.out, "N-TRIPLE");
String directory = "./TDB/testDb";
Dataset dataset = TDBFactory.createDataset(directory);
Model defaultModel = dataset.getDefaultModel();
defaultModel.add(model);
defaultModel.commit();
dataset.close();
}
}
|
package cn.edu.tju.http;
import cn.edu.tju.entity.MyException;
public class HttpException extends MyException {
private static final long serialVersionUID = 5824357504573919990L;
public HttpException(String msg) {
super(msg);
}
public HttpException(Throwable cause) {
super(cause);
}
public HttpException(String msg, Throwable cause) {
super(msg, cause);
}
}
|
/*
* 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 horarioescolar;
import ilog.concert.*;
import ilog.cplex.*;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
*
* @author a11030
*/
public class Modelo {
private int quantidadeProfessor;
private int quantidadeTurma;
private int quantidadeDias;
private int quantidadeHorario;
private Map<Integer, String> professores;
private Map<String, Integer> professoresNome;
private Map<Integer, String> turmas;
private Map<String, Integer> turmasNome;
private Map<Integer, String> dias;
private Map<String, Integer> diasNome;
private Map<Integer, String> horarios;
private Map<String, Integer> horariosNome;
private int[][] necessidade;
private int[][][] indisponibilidade;
public boolean readFile(String nomeArquivo) {
try {
FileReader fileReader = new FileReader(new File(nomeArquivo));
BufferedReader bufferedReader = new BufferedReader(fileReader);
if (bufferedReader.ready()) {
String linha = bufferedReader.readLine();
this.quantidadeProfessor = Integer.parseInt(linha);
}
if (bufferedReader.ready()) {
String[] linha = bufferedReader.readLine().split(", ");
professores = new HashMap<>(quantidadeProfessor);
professoresNome = new HashMap<>(quantidadeProfessor);
for (int i = 0; i < quantidadeProfessor; i++) {
professores.put(i, linha[i]);
professoresNome.put(linha[i], i);
}
}
if (bufferedReader.ready()) {
String linha = bufferedReader.readLine();
this.quantidadeTurma = Integer.parseInt(linha);
}
if (bufferedReader.ready()) {
String[] linha = bufferedReader.readLine().split(", ");
turmas = new HashMap<>(quantidadeTurma);
turmasNome = new HashMap<>(quantidadeTurma);
for (int i = 0; i < quantidadeTurma; i++) {
turmas.put(i, linha[i]);
turmasNome.put(linha[i], i);
}
}
if (bufferedReader.ready()) {
String linha = bufferedReader.readLine();
this.quantidadeDias = Integer.parseInt(linha);
}
if (bufferedReader.ready()) {
String[] linha = bufferedReader.readLine().split(", ");
dias = new HashMap<>(quantidadeDias);
diasNome = new HashMap<>(quantidadeDias);
for (int i = 0; i < quantidadeDias; i++) {
dias.put(i, linha[i]);
diasNome.put(linha[i], i);
}
}
if (bufferedReader.ready()) {
String linha = bufferedReader.readLine();
this.quantidadeHorario = Integer.parseInt(linha);
}
if (bufferedReader.ready()) {
String[] linha = bufferedReader.readLine().split(", ");
horarios = new HashMap<>(quantidadeHorario);
horariosNome = new HashMap<>(quantidadeHorario);
for (int i = 0; i < quantidadeHorario; i++) {
horarios.put(i, linha[i]);
horariosNome.put(linha[i], i);
}
}
necessidade = new int[quantidadeProfessor][quantidadeTurma];
if (bufferedReader.ready()) {
String linha = bufferedReader.readLine();
if (linha.equals("Necessidade")) {
while (bufferedReader.ready()) {
linha = bufferedReader.readLine();
if (linha.equals("Indisponibilidade")) {
break;
}
String[] necessidadeTempStrings = linha.split(" => ");
String[] necessidadeProfessorTurmaStrings = necessidadeTempStrings[0].split(", ");
int professor = professoresNome.get(necessidadeProfessorTurmaStrings[0]);
int turma = turmasNome.get(necessidadeProfessorTurmaStrings[1]);
necessidade[professor][turma] = Integer.parseInt(necessidadeTempStrings[1]);
}
}
}
indisponibilidade = new int[quantidadeDias][quantidadeHorario][quantidadeProfessor];
if (bufferedReader.ready()) {
while (bufferedReader.ready()) {
String linha = bufferedReader.readLine();
String[] indisponibilidadeTempStrings = linha.split(" => ");
String[] indisponibilidadeDiaAula = indisponibilidadeTempStrings[0].split(", ");
int dia = diasNome.get(indisponibilidadeDiaAula[0]);
int horario = horariosNome.get(indisponibilidadeDiaAula[1]);
int professor = professoresNome.get(indisponibilidadeTempStrings[1]);
indisponibilidade[dia][horario][professor] = 1;
}
}
bufferedReader.close();
fileReader.close();
return true;
} catch (IOException | NumberFormatException ex) {
System.out.println("Arquivo " + nomeArquivo + " não foi possível ler.");
System.err.print("Concert exception caught: " + ex);
return false;
}
}
public void modelo() {
try {
IloCplex model = new IloCplex();
/**
* Iniciando as variaveis booleanas
*/
IloNumVar[][][][] X = new IloNumVar[quantidadeDias][quantidadeHorario][quantidadeTurma][quantidadeProfessor];
for (int dia = 0; dia < quantidadeDias; dia++) {
for (int horario = 0; horario < quantidadeHorario; horario++) {
for (int turma = 0; turma < quantidadeTurma; turma++) {
for (int professor = 0; professor < quantidadeProfessor; professor++) {
X[dia][horario][turma][professor] = model.boolVar();
}
}
}
}
/**
* Função objetivo
*/
IloLinearNumExpr objective = model.linearNumExpr();
for (int dia = 0; dia < quantidadeDias; dia++) {
for (int horario = 0; horario < quantidadeHorario; horario++) {
for (int turma = 0; turma < quantidadeTurma; turma++) {
for (int professor = 0; professor < quantidadeProfessor; professor++) {
objective.addTerm(1.0, X[dia][horario][turma][professor]);
}
}
}
}
model.addMaximize(objective);
/**
* Necessidade t,p E Z+, para todo t,p
*/
for (int turma = 0; turma < quantidadeTurma; turma++) {
for (int professor = 0; professor < quantidadeProfessor; professor++) {
IloLinearNumExpr expr = model.linearNumExpr();
for (int dia = 0; dia < quantidadeDias; dia++) {
for (int horario = 0; horario < quantidadeHorario; horario++) {
expr.addTerm(1.0, X[dia][horario][turma][professor]);
}
}
model.addEq(expr, necessidade[professor][turma]);
}
}
/**
* Professor não pode estar em mais de uma turma ao mesmo tempo
*/
for (int professor = 0; professor < quantidadeProfessor; professor++) {
for (int horario = 0; horario < quantidadeHorario; horario++) {
for (int dia = 0; dia < quantidadeDias; dia++) {
IloLinearNumExpr expr = model.linearNumExpr();
for (int turma = 0; turma < quantidadeTurma; turma++) {
expr.addTerm(1.0, X[dia][horario][turma][professor]);
}
model.addLe(expr, 1.0);
}
}
}
/**
* Turma não pode ter o mesmo professor no mesmo dia e horario
*/
for (int turma = 0; turma < quantidadeTurma; turma++) {
for (int horario = 0; horario < quantidadeHorario; horario++) {
for (int dia = 0; dia < quantidadeDias; dia++) {
IloLinearNumExpr expr = model.linearNumExpr();
for (int professor = 0; professor < quantidadeProfessor; professor++) {
expr.addTerm(1.0, X[dia][horario][turma][professor]);
}
model.addLe(expr, 1.0);
}
}
}
/**
* Professor não da mais de duas horas aula por dia
*/
for (int turma = 0; turma < quantidadeTurma; turma++) {
for (int dia = 0; dia < quantidadeDias; dia++) {
for (int professor = 0; professor < quantidadeProfessor; professor++) {
IloLinearNumExpr expr = model.linearNumExpr();
for (int horario = 0; horario < quantidadeHorario; horario++) {
expr.addTerm(1.0, X[dia][horario][turma][professor]);
}
model.addLe(expr, 2.0);
}
}
}
/**
* Indisponibilidade dia x horario x professor E {0,1}, para todo
* dia,horario,professor 1 não pode dar aula 0 pode dar aula
*/
for (int dia = 0; dia < quantidadeDias; dia++) {
for (int horario = 0; horario < quantidadeHorario; horario++) {
for (int professor = 0; professor < quantidadeProfessor; professor++) {
if (indisponibilidade[dia][horario][professor] == 1) {
IloLinearNumExpr expr = model.linearNumExpr();
for (int turma = 0; turma < quantidadeTurma; turma++) {
expr.addTerm(1.0, X[dia][horario][turma][professor]);
}
model.addEq(expr, 0.0);
}
}
}
}
if (model.solve()) {
System.out.println("Status = " + model.getStatus());
System.out.println("Value = " + model.getBestObjValue());
//getRelatorioTurmas(model, X);
//getRelatorioProfessores(model, X);
} else {
System.out.println("A feasible solution may still be present, but IloCplex has not been able to prove its feasibility.");
}
} catch (IloException exception) {
System.err.print("Concert exception caught: " + exception);
}
}
private void getRelatorioTurmas(IloCplex model, IloNumVar[][][][] X) throws IloException {
try {
for (int turma = 0; turma < quantidadeTurma; turma++) {
String nomeArquivo = "turmas/" + turmas.get(turma) + ".txt";
FileWriter fileWriter = new FileWriter(new File(nomeArquivo));
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(turmas.get(turma));
bufferedWriter.newLine();
bufferedWriter.write("---------------------------------------------------------------------------------------------");
bufferedWriter.newLine();
bufferedWriter.write("\t\t");
for (int dia = 0; dia < quantidadeDias; dia++) {
bufferedWriter.write(dias.get(dia) + "\t\t");
}
bufferedWriter.newLine();
bufferedWriter.write("---------------------------------------------------------------------------------------------");
bufferedWriter.newLine();
for (int horario = 0; horario < quantidadeHorario; horario++) {
bufferedWriter.write("|" + horarios.get(horario) + "\t");
for (int dia = 0; dia < quantidadeDias; dia++) {
for (int professor = 0; professor < quantidadeProfessor; professor++) {
if (model.getValue(X[dia][horario][turma][professor]) == 1.0) {
bufferedWriter.write("|" + professores.get(professor) + "\t\t");
}
}
bufferedWriter.write("");
}
bufferedWriter.newLine();
bufferedWriter.write("---------------------------------------------------------------------------------------------");
bufferedWriter.newLine();
}
bufferedWriter.flush();
bufferedWriter.close();
fileWriter.close();
}
} catch (IOException ex) {
System.err.print("Concert exception caught: " + ex);
}
}
private void getRelatorioProfessores(IloCplex model, IloNumVar[][][][] X) throws IloException {
try {
for (int professor = 0; professor < quantidadeProfessor; professor++) {
String nomeArquivo = "professores/" + professores.get(professor) + ".txt";
FileWriter fileWriter = new FileWriter(new File(nomeArquivo));
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(professores.get(professor));
bufferedWriter.newLine();
bufferedWriter.write("---------------------------------------------------------------------------------------------");
bufferedWriter.newLine();
bufferedWriter.newLine();
bufferedWriter.write("---------------------------------------------------------------------------------------------");
bufferedWriter.newLine();
bufferedWriter.write("\t");
for (int dia = 0; dia < quantidadeDias; dia++) {
bufferedWriter.write("\t" + dias.get(dia) + "\t");
}
bufferedWriter.newLine();
bufferedWriter.write("---------------------------------------------------------------------------------------------");
bufferedWriter.newLine();
for (int horario = 0; horario < quantidadeHorario; horario++) {
bufferedWriter.write("|" + horarios.get(horario) + "\t");
for (int dia = 0; dia < quantidadeDias; dia++) {
for (int turma = 0; turma < quantidadeTurma; turma++) {
if (model.getValue(X[dia][horario][turma][professor]) == 1.0) {
bufferedWriter.write("|" + turmas.get(turma) + "\t");
}
}
}
bufferedWriter.newLine();
bufferedWriter.write("---------------------------------------------------------------------------------------------");
bufferedWriter.newLine();
}
bufferedWriter.flush();
bufferedWriter.close();
fileWriter.close();
}
} catch (IOException ex) {
System.err.print("Concert exception caught: " + ex);
}
}
}
|
package com.ejsfbu.app_main.DialogFragments;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Point;
import android.os.Bundle;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;
import com.ejsfbu.app_main.Activities.MainActivity;
import com.ejsfbu.app_main.Fragments.AddBankFragment;
import com.ejsfbu.app_main.Models.BankAccount;
import com.ejsfbu.app_main.Models.Goal;
import com.ejsfbu.app_main.Models.Reward;
import com.ejsfbu.app_main.Models.User;
import com.ejsfbu.app_main.R;
import java.util.ArrayList;
import java.util.List;
public class SetUpAutoPaymentDialogFragment extends DialogFragment {
Context context;
static User currentUser;
Button bSetUpAutoPaymentConfirm;
Button bSetUpAutoPaymentCancel;
EditText etAutoPaymentAmount;
Spinner spFrequency;
Spinner spTimesRepeated;
Spinner spAutoPayBanks;
String bankName;
Double amount;
String timesRepeated;
String frequency;
public SetUpAutoPaymentDialogFragment() {
}
public static SetUpAutoPaymentDialogFragment newInstance(Goal goal, User user) {
SetUpAutoPaymentDialogFragment setUpAutoPaymentDialogFragment = new SetUpAutoPaymentDialogFragment();
Bundle args = new Bundle();
args.putParcelable("goal", goal);
args.putParcelable("user", user);
setUpAutoPaymentDialogFragment.setArguments(args);
currentUser = user;
return setUpAutoPaymentDialogFragment;
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
context = getContext();
return inflater.inflate(R.layout.fragment_automatic_payment, container);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
bSetUpAutoPaymentConfirm = view.findViewById(R.id.bSetUpAutoPaymentConfirm);
bSetUpAutoPaymentCancel = view.findViewById(R.id.bSetUpAutoPaymentCancel);
spFrequency = view.findViewById(R.id.spFrequency);
spTimesRepeated = view.findViewById(R.id.spTimesRepeated);
spAutoPayBanks = view.findViewById(R.id.spAutoPayBanks);
etAutoPaymentAmount = view.findViewById(R.id.etAutoPaymentAmount);
setOnClickListeners();
setAdapters();
}
public void setOnClickListeners() {
bSetUpAutoPaymentConfirm.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
bankName = spAutoPayBanks.getSelectedItem().toString();
String amountString = etAutoPaymentAmount.getText().toString();
if (amountString.equals("")) {
Toast.makeText(context,"Please enter a value.", Toast.LENGTH_SHORT).show();
return;
} else {
amount = Double.valueOf(amountString);
}
timesRepeated = spTimesRepeated.getSelectedItem().toString();
frequency = spFrequency.getSelectedItem().toString();
if (Integer.valueOf(timesRepeated) != 1) {
frequency = frequency + "s";
}
sendBackResult();
return;
}
});
bSetUpAutoPaymentCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dismiss();
}
});
}
public void setAdapters(){
ArrayList<String> numArray = new ArrayList<>();
for (int i = 1; i < 100; i++) {
StringBuilder num = new StringBuilder();
num.append(i);
numArray.add(num.toString());
}
ArrayAdapter<String> numAdapter =
new ArrayAdapter<>(context, android.R.layout.simple_spinner_item, numArray);
numAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spTimesRepeated.setAdapter(numAdapter);
ArrayList<String> frequency = new ArrayList<>();
frequency.add("Day");
frequency.add("Week");
frequency.add("Month");
frequency.add("Year");
ArrayAdapter<String> frequencyAdapter =
new ArrayAdapter<>(context, android.R.layout.simple_spinner_item, frequency);
frequencyAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spFrequency.setAdapter(frequencyAdapter);
List<BankAccount> banks = new ArrayList<>();
banks = currentUser.getVerifiedBanks();
ArrayList<String> array = new ArrayList<>();
if (banks != null) {
for (BankAccount bank : banks) {
array.add(bank.getBankName());
}
}
if (array.size() == 0) {
array.add("No verified banks available");
}
ArrayAdapter<String> bankAdapter =
new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, array);
bankAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spAutoPayBanks.setAdapter(bankAdapter);
}
public void onResume() {
Window window = getDialog().getWindow();
Point size = new Point();
Display display = window.getWindowManager().getDefaultDisplay();
display.getSize(size);
window.setLayout((int) (size.x * 0.99), WindowManager.LayoutParams.WRAP_CONTENT);
window.setGravity(Gravity.CENTER);
super.onResume();
}
public interface SetUpAutoPaymentDialogListener {
void onFinishSetUpAutoPaymentDialog(String bankName, Double amount, String timesRepeated, String frequency);
}
public void sendBackResult() {
SetUpAutoPaymentDialogFragment.SetUpAutoPaymentDialogListener listener = (SetUpAutoPaymentDialogFragment.SetUpAutoPaymentDialogListener) getFragmentManager()
.findFragmentById(R.id.flMainContainer);
listener.onFinishSetUpAutoPaymentDialog(bankName, amount, timesRepeated, frequency);
Toast.makeText(context, "Automatic Recurring Payment Created", Toast.LENGTH_LONG).show();
dismiss();
return;
}
}
|
package com.example.nikkolasedip.fortnite.config;
public class Config {
public static final String PAYPAL_CLIENT_ID = "Abw2n3mMPksqI7CXBsr1rWiMb06Xu7iKJdCMjVI3H_VwbmeYIE7Ynt5e2wCOzv2cNHDXEbdNE-MOu8xV";
}
|
package com.marchuck.data.repository;
import com.marchuck.DataProvider;
import com.marchuck.NetworkResponse;
import javax.inject.Inject;
import io.reactivex.Observable;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import okhttp3.ResponseBody;
/**
* Project "AndroidInterview"
* <p>
* Created by Lukasz Marczak
* on 16.09.2017.
*/
public class DataProviderImpl implements DataProvider {
private RestApi restApi;
private DataMapper mapper;
private CacheManager<String, String> cacheManager;
@Inject public DataProviderImpl(RestApi api,
DataMapper mapper,
CacheManager<String, String> manager) {
this.restApi = api;
this.mapper = mapper;
this.cacheManager = manager;
}
@Override public Observable<NetworkResponse> provide() {
return restApi.requestData()
.map(new Function<ResponseBody, NetworkResponse>() {
@Override
public NetworkResponse apply(
@NonNull ResponseBody responseBody) throws Exception {
return mapper.transform(responseBody);
}
}).doOnNext(new Consumer<NetworkResponse>() {
@Override public void accept(NetworkResponse networkResponse) throws Exception {
if (networkResponse.isSuccessful()) {
cacheManager.put("", networkResponse.getResponse());
}
}
}).onErrorReturn(new Function<Throwable, NetworkResponse>() {
@Override
public NetworkResponse apply(@NonNull Throwable throwable) throws Exception {
return new NetworkResponse(cacheManager.get(""));
}
});
}
}
|
package net.cupmouse.minecraft.eplugin.database;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* @since 2016/02/16
*/
public interface ResultSetProcessor {
void accept(ResultSet resultSet) throws SQLException, NoResultNotAllowedException;
}
|
package timePhrase;
import static org.junit.Assert.*;
import java.util.Calendar;
import org.junit.Test;
/**
* Tests the {@link ChangeUnitTimePhrase} class.
*
* @author akauffman
*
*/
public class ChangeUnitTimePhraseTest {
/**
* Tests that Next or Last match the phrase.
*/
@Test
public void testQualifierMatches() {
final ChangeUnitTimePhrase timePhrase = new ChangeUnitTimePhrase();
assertTrue(timePhrase.matches("NEXT WEEK"));
assertTrue(timePhrase.matches("LAST WEEK"));
}
/**
* Tests that time units match the phrase.
*/
@Test
public void testTimeUnitMatches() {
final ChangeUnitTimePhrase timePhrase = new ChangeUnitTimePhrase();
assertTrue(timePhrase.matches("NEXT MILLISECOND"));
assertTrue(timePhrase.matches("NEXT SECOND"));
assertTrue(timePhrase.matches("NEXT MINUTE"));
assertTrue(timePhrase.matches("NEXT HOUR"));
assertTrue(timePhrase.matches("NEXT DAY"));
assertTrue(timePhrase.matches("NEXT WEEK"));
assertTrue(timePhrase.matches("NEXT MONTH"));
assertTrue(timePhrase.matches("NEXT YEAR"));
}
/**
* Tests that whitespace between qualifier and week is ignored.
*/
@Test
public void testWhitespaceMatches() {
final ChangeUnitTimePhrase timePhrase = new ChangeUnitTimePhrase();
assertTrue(timePhrase.matches("NEXTWEEK"));
assertTrue(timePhrase.matches("NEXT WEEK"));
assertTrue(timePhrase.matches("NEXT WEEK"));
assertTrue(timePhrase.matches("NEXT WEEK"));
}
/**
* Tests that phrase is case insensitive.
*/
@Test
public void testLowerCaseMatches(){
final ChangeUnitTimePhrase timePhrase = new ChangeUnitTimePhrase();
assertTrue(timePhrase.matches("NeXt WeEk"));
}
/**
* Tests that an invalid phrase does not match.
*/
@Test
public void testNoMatch(){
final ChangeUnitTimePhrase timePhrase = new ChangeUnitTimePhrase();
assertFalse(timePhrase.matches("DOES NOT MATCH"));
}
/**
* Tests the Next Millisecond returns a date 1 millisecond in the future.
*/
@Test
public void testNextMilli(){
final ChangeUnitTimePhrase timePhrase = new ChangeUnitTimePhrase();
final Calendar fromWhen = Calendar.getInstance();
fromWhen.set(2015, 3, 6, 1, 1, 1); //Monday, April 6th, 2015
fromWhen.set(Calendar.MILLISECOND, 1);
final Calendar nextMilli = Calendar.getInstance();
nextMilli.set(2015, 3, 6, 1, 1, 1); //Monday, April 6th, 2015
nextMilli.set(Calendar.MILLISECOND, 2);
timePhrase.matches("NEXT MILLISECOND");
assertEquals(nextMilli.getTime(), timePhrase.getTime(fromWhen));
}
/**
* Tests the Next Second returns a date 1 second in the future.
*/
@Test
public void testNextSecond(){
final ChangeUnitTimePhrase timePhrase = new ChangeUnitTimePhrase();
final Calendar fromWhen = Calendar.getInstance();
fromWhen.set(2015, 3, 6, 1, 1, 1); //Monday, April 6th, 2015
final Calendar nextSecond = Calendar.getInstance();
nextSecond.set(2015, 3, 6, 1, 1, 2); //Monday, April 6th, 2015
timePhrase.matches("NEXT SECOND");
assertEquals(nextSecond.getTime(), timePhrase.getTime(fromWhen));
}
/**
* Tests the Next Minute returns a date 1 minute in the future.
*/
@Test
public void testNextMinute(){
final ChangeUnitTimePhrase timePhrase = new ChangeUnitTimePhrase();
final Calendar fromWhen = Calendar.getInstance();
fromWhen.set(2015, 3, 6, 1, 1, 1); //Monday, April 6th, 2015
final Calendar nextMinute = Calendar.getInstance();
nextMinute.set(2015, 3, 6, 1, 2, 1); //Monday, April 6th, 2015
timePhrase.matches("NEXT MINUTE");
assertEquals(nextMinute.getTime(), timePhrase.getTime(fromWhen));
}
/**
* Tests the Next Hour returns a date 1 hour in the future.
*/
@Test
public void testNextHour(){
final ChangeUnitTimePhrase timePhrase = new ChangeUnitTimePhrase();
final Calendar fromWhen = Calendar.getInstance();
fromWhen.set(2015, 3, 6, 1, 1, 1); //Monday, April 6th, 2015
final Calendar nextHour = Calendar.getInstance();
nextHour.set(2015, 3, 6, 2, 1, 1); //Monday, April 6th, 2015
timePhrase.matches("NEXT HOUR");
assertEquals(nextHour.getTime(), timePhrase.getTime(fromWhen));
}
/**
* Tests the Next Day returns a date 1 day in the future.
*/
@Test
public void testNextDay(){
final ChangeUnitTimePhrase timePhrase = new ChangeUnitTimePhrase();
final Calendar fromWhen = Calendar.getInstance();
fromWhen.set(2015, 3, 6, 1, 1, 1); //Monday, April 6th, 2015
final Calendar nextDay = Calendar.getInstance();
nextDay.set(2015, 3, 7, 1, 1, 1); //Tuesday, April 7th, 2015
timePhrase.matches("NEXT DAY");
assertEquals(nextDay.getTime(), timePhrase.getTime(fromWhen));
}
/**
* Tests the Next Week phrase returns a date 7 days in the future.
*/
@Test
public void testNextWeek(){
final ChangeUnitTimePhrase timePhrase = new ChangeUnitTimePhrase();
final Calendar fromWhen = Calendar.getInstance();
fromWhen.set(2015, 3, 6, 1, 1, 1); //Monday, April 6th, 2015
final Calendar nextWeek = Calendar.getInstance();
nextWeek.set(2015, 3, 13, 1, 1, 1); //Monday, April 13th, 2015
timePhrase.matches("NEXT WEEK");
assertEquals(nextWeek.getTime(), timePhrase.getTime(fromWhen));
}
/**
* Tests the Next qualifier returns a date 7 days in the past.
*/
@Test
public void testLastWeek(){
final ChangeUnitTimePhrase timePhrase = new ChangeUnitTimePhrase();
final Calendar fromWhen = Calendar.getInstance();
fromWhen.set(2015, 3, 6, 1, 1, 1); //Monday, April 6th, 2015
final Calendar lastWeek = Calendar.getInstance();
lastWeek.set(2015, 2, 30, 1, 1, 1); //Monday, March 30th, 2015
timePhrase.matches("LAST WEEK");
assertEquals(lastWeek.getTime(), timePhrase.getTime(fromWhen));
}
/**
* Tests the Next Month phrase returns a date 1 month in the future.
*/
@Test
public void testNextMonth(){
final ChangeUnitTimePhrase timePhrase = new ChangeUnitTimePhrase();
final Calendar fromWhen = Calendar.getInstance();
fromWhen.set(2015, 3, 6, 1, 1, 1); //Monday, April 6th, 2015
final Calendar nextMonth = Calendar.getInstance();
nextMonth.set(2015, 4, 6, 1, 1, 1); //Wednesday, May 6th, 2015
timePhrase.matches("NEXT MONTH");
assertEquals(nextMonth.getTime(), timePhrase.getTime(fromWhen));
}
/**
* Tests the Next Year phrase returns a date 1 year in the future.
*/
@Test
public void testNextYear(){
final ChangeUnitTimePhrase timePhrase = new ChangeUnitTimePhrase();
final Calendar fromWhen = Calendar.getInstance();
fromWhen.set(2015, 3, 6, 1, 1, 1); //Monday, April 6th, 2015
final Calendar nextMonth = Calendar.getInstance();
nextMonth.set(2016, 3, 6, 1, 1, 1); //Wednesday, April 6th, 2016
timePhrase.matches("NEXT YEAR");
assertEquals(nextMonth.getTime(), timePhrase.getTime(fromWhen));
}
}
|
package com.oxycab.provider.ui.activity.notification;
import com.oxycab.provider.base.MvpPresenter;
public interface NotificationIPresenter<V extends NotificationIView> extends MvpPresenter<V> {
void notifications();
}
|
package com.pa.miniEip.controller;
import com.pa.miniEip.model.Supplier;
import com.pa.miniEip.service.SupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import java.util.List;
@Controller
public class SupplierController {
@Autowired
private SupplierService supplierService;
@GetMapping(value = "/suppliers")
public ResponseEntity<List<Supplier>> getAllSuppliers() {
List<Supplier> suppliers = supplierService.getAllSuppliers();
return ResponseEntity.status(HttpStatus.OK).body(suppliers);
}
}
|
package cn.smallclover.string;
public class StringReference {
public static void main(String[] args) {
String s = new String("HelloWorld");
String s1 = "HelloWorld";
System.out.println(s.intern() == s1);
}
}
|
package com.github.ezauton.core.simulator;
import com.github.ezauton.core.action.Action;
import com.github.ezauton.core.action.TimedPeriodicAction;
import com.github.ezauton.core.simulation.ModernSimulatedClock;
import org.junit.jupiter.api.Test;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicLong;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class InsantSimulatorTest {
@Test
public void testABC() throws TimeoutException {
AtomicLong sum = new AtomicLong();
Action actionA = new TimedPeriodicAction(20, TimeUnit.SECONDS)
.addRunnable(a -> () -> {
sum.addAndGet(a.getStopwatch().read());
});
Action actionB = new TimedPeriodicAction(20, TimeUnit.SECONDS)
.addRunnable(a -> () -> {
long l = sum.addAndGet(-a.getStopwatch().read(TimeUnit.MILLISECONDS));
assertEquals(0, l);
});
ModernSimulatedClock clock = new ModernSimulatedClock();
clock
.add(actionA)
.add(actionB)
.runSimulation(1000, TimeUnit.SECONDS);
assertEquals(0, sum.get());
}
}
|
package com.telyo.trainassistant.views;
import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.telyo.trainassistant.R;
/**
* Created by Administrator on 2017/7/5.
*/
public class MyLayoutWeatherView extends LinearLayout {
private LayoutInflater mInflater;
private TextView mTv_week;
private ImageView mImg_weather;
private TextView mTv_temperature;
private String mTv_weekString;
private int mTv_weekColor;
private float mTv_weekSize;
private String mTv_temperatureString;
private int mTv_temperatureColor;
private float mTv_temperatureSize;
private int weatherImageViewRes;
public MyLayoutWeatherView(Context context) {
this(context,null);
}
public MyLayoutWeatherView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs,0);
}
public MyLayoutWeatherView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView(context,attrs);
}
private void initView(Context context, AttributeSet attrs) {
TypedArray ta = context.obtainStyledAttributes(attrs,R.styleable.MyLayoutWeatherView);
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = mInflater.inflate(R.layout.weather_layout,this,false);
mTv_weekString = ta.getString(R.styleable.MyLayoutWeatherView_weekText);
mTv_weekColor = ta.getColor(R.styleable.MyLayoutWeatherView_weekColor,
ContextCompat.getColor(context,R.color.colorTv_black));
mTv_weekSize = ta.getDimension(R.styleable.MyLayoutWeatherView_weekSize,15);
mTv_temperatureString = ta.getString(R.styleable.MyLayoutWeatherView_week_temperatureText);
mTv_temperatureColor = ta.getColor(R.styleable.MyLayoutWeatherView_week_temperatureColor,
ContextCompat.getColor(context,R.color.colorTv_black));
mTv_temperatureSize = ta.getDimension(R.styleable.MyLayoutWeatherView_week_temperatureSize,15);
weatherImageViewRes = ta.getResourceId(R.styleable.MyLayoutWeatherView_week_weatherImageViewRes,0);
ta.recycle();
mTv_week = (TextView) view.findViewById(R.id.tv_week);
mImg_weather = (ImageView) view.findViewById(R.id.img_weather);
mTv_temperature = (TextView) view.findViewById(R.id.tv_temperature);
mTv_week.setText(mTv_weekString);
mTv_week.setTextSize(mTv_weekSize);
mTv_week.setTextColor(mTv_weekColor);
mTv_temperature.setText(mTv_temperatureString);
mTv_temperature.setTextSize(mTv_temperatureSize);
mTv_temperature.setTextColor(mTv_temperatureColor);
mImg_weather.setImageResource(weatherImageViewRes);
addView(view);
}
/*private TextView mTv_week;
private ImageView mImg_weather;
private TextView mTv_temperature;*/
public void setWeekText(String week){
mTv_week.setText(week);
}
public void setTemperatureText(String temperature){
mTv_temperature.setText(temperature);
}
public void setmImg_weatherRes(int srcId){
mImg_weather.setImageResource(srcId);
}
}
|
/**
* PlayerInteractEvent Listener
* @author Dartanman (Austin Dart)
*/
package main.dartanman.egghunt.events;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import main.dartanman.egghunt.Main;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.EquipmentSlot;
public class Interact implements Listener {
public Main plugin;
/**
* Constructs the PlayerInteractEvent Listener class with the Main class for access
* @param pl
* The Main class
*/
public Interact(Main pl) {
this.plugin = pl;
}
/**
* Listens to an event. In this case, the PlayerInteractEvent
* In this particular method, it is used for running code related to a Player finding an egg.
* @param event
* The event to listen to
*/
@EventHandler(priority = EventPriority.HIGHEST)
public void onInteract(PlayerInteractEvent event) {
Player player = event.getPlayer();
UUID uuid = player.getUniqueId();
String uuidStr = uuid.toString();
Action action = event.getAction();
// Prevents running twice due to the OFFHAND also being a thing.
if (event.getHand() != EquipmentSlot.HAND) {
return;
}
// Makes sure they are clicking a block - not the air
if (action == Action.LEFT_CLICK_BLOCK || action == Action.RIGHT_CLICK_BLOCK) {
Block block = event.getClickedBlock();
// Checks it is indeed a head (eggs are heads)
if (block.getType() == Material.PLAYER_HEAD || block.getType() == Material.PLAYER_WALL_HEAD) {
Location blockLoc = block.getLocation();
String locStr = String.valueOf(blockLoc.getWorld().getName()) + "/" + blockLoc.getBlockX() + "/"
+ blockLoc.getBlockY() + "/" + blockLoc.getBlockZ();
List<String> eggList = new ArrayList<>();
eggList = this.plugin.getEggDataFile().getStringList("EggLocations");
// Checks that there is indeed an egg where they clicked - not some other head
if (eggList.contains(locStr)) {
if (this.plugin.getEggDataFile().get("Players." + uuidStr + "." + locStr) == null) {
this.plugin.getEggDataFile().set("Players." + uuidStr + ".Count", Integer
.valueOf(this.plugin.getEggDataFile().getInt("Players." + uuidStr + ".Count") + 1));
player.sendMessage(ChatColor.BLUE + "You found an egg!");
player.sendMessage(ChatColor.BLUE + "You have found a total of " + ChatColor.GREEN
+ this.plugin.getEggDataFile().getInt("Players." + uuidStr + ".Count") + " Eggs.");
player.sendMessage(ChatColor.BLUE + "There are " + ChatColor.GREEN
+ this.plugin.getEggDataFile().getInt("EggCount") + " Eggs" + ChatColor.BLUE
+ " in all.");
String msg1 = ChatColor.translateAlternateColorCodes('&',
this.plugin.getConfig().getString("Messages.FoundEgg"));
String msg2 = msg1.replace("{found}",
this.plugin.getEggDataFile().getString("Players." + uuidStr + ".Count"));
String msg = msg2.replace("{total}", this.plugin.getEggDataFile().getString("EggCount"));
player.sendMessage(msg);
this.plugin.getEggDataFile().set("Players." + uuidStr + "." + locStr, Boolean.valueOf(true));
this.plugin.saveEggDataFile();
if (this.plugin.getEggDataFile().getInt("Players." + uuidStr + ".Count") == this.plugin
.getEggDataFile().getInt("EggCount")
&& this.plugin.getConfig().getBoolean("BroadcastWhenAllFound.Enabled"))
Bukkit.broadcastMessage(ChatColor.translateAlternateColorCodes('&', this.plugin.getConfig()
.getString("BroadcastWhenAllFound.Message").replace("{player}", player.getName())));
if (this.plugin.getEggDataFile().getInt("Players." + uuidStr + ".Count") == this.plugin
.getEggDataFile().getInt("EggCount")
&& this.plugin.getConfig().getBoolean("CommandRewardsForAllFound.Enabled"))
for (String cmd : this.plugin.getConfig()
.getStringList("CommandRewardsForAllFound.Commands"))
Bukkit.dispatchCommand((CommandSender) Bukkit.getConsoleSender(),
cmd.replace("{player}", player.getName()));
} else {
player.sendMessage(ChatColor.translateAlternateColorCodes('&',
this.plugin.getConfig().getString("Messages.AlreadyFound")));
}
this.plugin.saveEggDataFile();
}
}
}
}
}
|
package interpreter;
public class Instruction {
private final String instr;
private final String arg1;
private final int offset;
private final String arg2;
private final String arg3;
public Instruction(String instr, String arg1, int offset, String arg2, String arg3) {
this.instr = instr;
this.arg1 = arg1;
this.offset = offset;
this.arg2 = arg2;
this.arg3 = arg3;
}
public String getInstruction() {
return instr;
}
public String getArg1() {
return arg1;
}
public int getOffset() {
return offset;
}
public String getArg2() {
return arg2;
}
public String getArg3() {
return arg3;
}
public void printInstruction() {
System.out.println(instr + " " + arg1 + " " + offset + "("+arg2+")" + " " + arg3);
}
}
|
package com.gamemoim.demo.service;
import com.gamemoim.demo.account.AccountRepository;
import com.gamemoim.demo.domain.Account;
import com.gamemoim.demo.domain.Group;
import com.gamemoim.demo.domain.GroupManager;
import com.gamemoim.demo.group.GroupService;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;
import org.springframework.transaction.annotation.Transactional;
import static org.assertj.core.api.Assertions.*;
@SpringBootTest
@Transactional
@Rollback(false)
class GroupServiceTest {
@Autowired
GroupService service;
@Autowired
AccountRepository accountRepository;
@Test
public void 그룹생성() throws Exception {
//given
Account account = new Account("nick", "email", "password");
Group group = Group.createGroup("name","desc");
service.createGroup(group, account);
//when
accountRepository.save(account);
Group findGroup = service.searchGroupByName("name");
//then
assertThat(findGroup.getDescription()).isEqualTo(group.getDescription());
}
}
|
package com.rental.server.core.property;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import java.math.BigDecimal;
@Getter
@Builder
@AllArgsConstructor
public class Property {
private Long id;
private Double latitude;
private Double longitude;
private String type;
private String address;
private String neighbourhood;
private Integer size;
private Integer bedrooms;
private BigDecimal price;
private PropertyUrls urls;
}
|
package com.cognizant.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.cognizant.model.Department;
import com.cognizant.service.DeparmentService;
@RestController
@RequestMapping("/departments")
public class DepartmentController {
@Autowired
DeparmentService service;
/*
* Method -get http://localhost:9191/employees/allemp
*/
@GetMapping(value = "/alldept", produces = "application/json")
public List<Department> getAllDepartments() {
return service.getAllDepartments();
}
}
|
package pageobjects;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class PostagePage {
private WebDriver driver;
public PostagePage (WebDriver driver) {
this.driver = driver;
}
public String url() {
String postageUrl = "https://auspost.com.au/parcels-mail/calculate-postage-delivery-times#/";
return postageUrl;
}
public By fromPostcode() {
By postCode = By.cssSelector("input[id='domFrom_value']");
return postCode;
}
public By selectFromOne () {
return By.xpath("//div[@id=\'domFrom_dropdown\']/div[3]/div/div");
}
public By toPostcode() {
By postCode = By.cssSelector("input[id='domTo_value']");
return postCode;
}
public By selectToOne() {
return By.xpath("//div[@id=\'domTo_dropdown\']/div[3]/div/div");
}
public By goButton() {
By go = By.cssSelector("button[id='submit-domestic']");
return go;
}
public By settingSizeAndWeight() {
return By.xpath("//a[@class='size-weight__enter-weight-link ng-scope']");
}
public By length() {
return By.cssSelector("div[class='dimensions span-30p']>input");
}
public By width() {
return By.cssSelector("input[name='widthInput']");
}
public By height() {
return By.xpath("//input[@name='heightInput']");
}
public By weight() {
return By.xpath("//input[@name='weightInput']");
}
public By submitSizeAndWeight() {
return By.xpath("//button[@id='submit-set-dimensions']");
}
public By setDate() {
return By.xpath("//a[@class='delivery-times__enter-time-link']");
}
public By dateInput() {
return By.name("dateInput");
}
public By selectOneDate() {
return By.cssSelector(".delivery-times__input-field");
}
public By submitDate() {
return By.xpath("//button[@id='set-date']");
}
public String getExpressPostPrice() {
String Price = driver.findElement(By.xpath("//div[3]/span[2]")).getText();
return Price;
}
public String getParcelpostPrice () {
String Price = driver.findElement(By.xpath("//postage-service[2]/div/div/div/div/div[3]/span[2]")).getText();
return Price;
}
}
|
package com.nxtlife.mgs.view;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.nxtlife.mgs.entity.activity.Activity;
import com.nxtlife.mgs.entity.school.Grade;
import com.nxtlife.mgs.entity.user.Teacher;
import com.nxtlife.mgs.util.DateUtil;
@JsonInclude(value = Include.NON_ABSENT)
public class TeacherResponse {
private String id;
private String name;
private String username;
private String userId;
private String gender;
private String mobileNumber;
private String email;
private String dob;
private String qualification;
private List<GradeResponse> grades;
private List<String> activities;
private String schoolName;
private String schoolId;
private Boolean active;
private String designation;
private Boolean isManagmentMember;
private Boolean isCoach;
private Boolean isClassTeacher;
private String imagePath;
private String profileBrief;
private String yearOfEnrolment;
private List<ActivityRequestResponse> activityAndGrades;
private List<TeacherResponse> teachers;
private Set<String> roles;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getMobileNumber() {
return mobileNumber;
}
public void setMobileNumber(String mobileNumber) {
this.mobileNumber = mobileNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getQualification() {
return qualification;
}
public void setQualification(String qualification) {
this.qualification = qualification;
}
public List<GradeResponse> getGrades() {
return grades;
}
public void setGrades(List<GradeResponse> grades) {
this.grades = grades;
}
public List<String> getActivities() {
return activities;
}
public void setActivities(List<String> activities) {
this.activities = activities;
}
public String getSchoolName() {
return schoolName;
}
public void setSchoolName(String schoolName) {
this.schoolName = schoolName;
}
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public Boolean getIsManagmentMember() {
return isManagmentMember;
}
public void setIsManagmentMember(Boolean isManagmentMember) {
this.isManagmentMember = isManagmentMember;
}
public Boolean getIsCoach() {
return isCoach;
}
public void setIsCoach(Boolean isCoach) {
this.isCoach = isCoach;
}
public String getSchoolId() {
return schoolId;
}
public void setSchoolId(String schoolId) {
this.schoolId = schoolId;
}
public Boolean getIsClassTeacher() {
return isClassTeacher;
}
public void setIsClassTeacher(Boolean isClassTeacher) {
this.isClassTeacher = isClassTeacher;
}
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
public String getProfileBrief() {
return profileBrief;
}
public void setProfileBrief(String profileBrief) {
this.profileBrief = profileBrief;
}
public String getYearOfEnrolment() {
return yearOfEnrolment;
}
public void setYearOfEnrolment(String yearOfEnrolment) {
this.yearOfEnrolment = yearOfEnrolment;
}
public List<ActivityRequestResponse> getActivityAndGrades() {
return activityAndGrades;
}
public void setActivityAndGrades(List<ActivityRequestResponse> activityAndGrades) {
this.activityAndGrades = activityAndGrades;
}
public List<TeacherResponse> getTeachers() {
return teachers;
}
public void setTeachers(List<TeacherResponse> teachers) {
this.teachers = teachers;
}
public Set<String> getRoles() {
return roles;
}
public void setRoles(Set<String> roles) {
this.roles = roles;
}
public TeacherResponse() {
}
public TeacherResponse(Teacher teacher) {
this.id = teacher.getCid();
if (teacher.getUser() != null) {
this.userId = teacher.getUser().getCid();
roles = teacher.getUser().getUserRoles().stream().map(r -> r.getRole().getName()).distinct().collect(Collectors.toSet());
}
this.username = teacher.getUsername();
this.name = teacher.getName();
this.gender = teacher.getGender();
this.mobileNumber = teacher.getMobileNumber();
this.email = teacher.getEmail();
if (teacher.getDob() != null)
this.dob = DateUtil.formatDate(teacher.getDob());
this.qualification = teacher.getQualification();
this.active = teacher.getActive();
this.isManagmentMember = teacher.getIsManagmentMember();
this.designation = teacher.getDesignation();
this.isCoach = teacher.getIsCoach();
this.isClassTeacher = teacher.getIsClassTeacher();
this.imagePath = teacher.getImageUrl();
this.profileBrief = teacher.getProfileBrief();
if (teacher.getDob() != null)
this.dob = DateUtil.formatDate(teacher.getDob(), "yyyy-MM-dd");
if (teacher.getCreatedDate().get() != null)
this.yearOfEnrolment = Integer.toString(teacher.getCreatedDate().get().getYear());
if (teacher.getSchool() != null) {
this.schoolName = teacher.getSchool().getName();
this.schoolId = teacher.getSchool().getCid();
}
if (teacher.getGrades() != null && !teacher.getGrades().isEmpty()) {
// if (grades == null)
grades = new ArrayList<GradeResponse>();
for (Grade grade : teacher.getGrades()) {
grades.add(new GradeResponse(grade));
}
}
// change database for activity and then get all activity names and add
// to
// member list in the view
if (teacher.getTeacherActivityGrades() != null && !teacher.getTeacherActivityGrades().isEmpty()) {
if (activities == null)
activities = new ArrayList<String>();
if (activityAndGrades == null)
activityAndGrades = new ArrayList<ActivityRequestResponse>();
// Map<String,Set<String>> activityIdGradesIdMap = new
// HashMap<String, Set<String>>();
Map<Activity, Set<Grade>> activityGradesMap = new HashMap<Activity, Set<Grade>>();
teacher.getTeacherActivityGrades().stream().filter(i -> i.getActive()).forEach(item -> {
if (item.getActive()) {
if (!activities.contains(item.getActivity().getName()))
activities.add(item.getActivity().getName());
// if(!activityIdGradesIdMap.containsKey(item.getActivity().getCid()))
// activityIdGradesIdMap.put(item.getActivity().getCid(),
// new HashSet<String>());
if (!activityGradesMap.containsKey(item.getActivity()))
activityGradesMap.put(item.getActivity(), new HashSet<Grade>());
activityGradesMap.get(item.getActivity()).add(item.getGrade());
// activityIdGradesIdMap.get(item.getActivity().getCid()).add(item.getGrade().getCid());
}
});
if (!activityGradesMap.isEmpty()) {
for (Activity activity : activityGradesMap.keySet()) {
ActivityRequestResponse act = new ActivityRequestResponse(activity);
act.setGradeResponses(activityGradesMap.get(activity).stream().map(GradeResponse::new)
.collect(Collectors.toList()));
activityAndGrades.add(act);
}
}
// if(!activityGradesMap.isEmpty()) {
// for(String actId : activityGradesMap.keySet()) {
// ActivityRequestResponse activity = new ActivityRequestResponse();
// activity.setId(actId);
// activity.setGrades(new
// ArrayList<String>(activityGradesMap.get(actId)));
// activityAndGrades.add(activity);
// }
// }
// teacher.getActivities().stream().distinct().forEach(act ->
// {activities.add(act.getName());
// activityIds.add(act.getCid());});
// for (Activity activity : teacher.getActivities()) {
// activities.add(String.format("%s", activity.getName()));
// }
}
}
public TeacherResponse(Teacher teacher, Boolean teacherResponseForUser) {
this.id = teacher.getCid();
if (teacher.getUser() != null) {
this.userId = teacher.getUser().getCid();
roles = teacher.getUser().getUserRoles().stream().map(r -> r.getRole().getName()).distinct().collect(Collectors.toSet());
}
this.username = teacher.getUsername();
this.name = teacher.getName();
this.gender = teacher.getGender();
this.mobileNumber = teacher.getMobileNumber();
this.email = teacher.getEmail();
this.profileBrief = teacher.getProfileBrief();
if (teacher.getCreatedDate() != null)
this.yearOfEnrolment = Integer.toString(teacher.getCreatedDate().get().getYear());
if (teacher.getDob() != null)
this.dob = DateUtil.formatDate(teacher.getDob(), "yyyy-MM-dd");
this.qualification = teacher.getQualification();
this.active = teacher.getActive();
if (teacher.getSchool() != null) {
this.schoolName = teacher.getSchool().getName();
this.schoolId = teacher.getSchool().getCid();
}
this.isManagmentMember = teacher.getIsManagmentMember();
this.isCoach = teacher.getIsCoach();
this.isClassTeacher = teacher.getIsClassTeacher();
this.designation = teacher.getDesignation();
this.imagePath = teacher.getImageUrl();
if (teacher.getTeacherActivityGrades() != null && !teacher.getTeacherActivityGrades().isEmpty()) {
if (activities == null)
activities = new ArrayList<String>();
if (activityAndGrades == null)
activityAndGrades = new ArrayList<ActivityRequestResponse>();
// Map<String,Set<String>> activityIdGradesIdMap = new
// HashMap<String, Set<String>>();
Map<Activity, Set<Grade>> activityGradesMap = new HashMap<Activity, Set<Grade>>();
teacher.getTeacherActivityGrades().stream().filter(i -> i.getActive()).forEach(item -> {
if (item.getActive()) {
if (!activities.contains(item.getActivity().getName()))
activities.add(item.getActivity().getName());
// if(!activityIdGradesIdMap.containsKey(item.getActivity().getCid()))
// activityIdGradesIdMap.put(item.getActivity().getCid(),
// new HashSet<String>());
if (!activityGradesMap.containsKey(item.getActivity()))
activityGradesMap.put(item.getActivity(), new HashSet<Grade>());
activityGradesMap.get(item.getActivity()).add(item.getGrade());
// activityIdGradesIdMap.get(item.getActivity().getCid()).add(item.getGrade().getCid());
}
});
if (!activityGradesMap.isEmpty()) {
for (Activity activity : activityGradesMap.keySet()) {
ActivityRequestResponse act = new ActivityRequestResponse(activity);
act.setGradeResponses(activityGradesMap.get(activity).stream().map(GradeResponse::new)
.collect(Collectors.toList()));
activityAndGrades.add(act);
}
}
}
}
}
|
package com.rc.portal.webapp.filter;
import javax.servlet.ServletContext;
import com.opensymphony.webwork.views.freemarker.FreemarkerManager;
import com.rc.app.framework.webapp.util.CurrencyMethod;
import freemarker.template.Configuration;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
/**
* 货币处理
* @author 刘天灵
*
*/
public class ExtendFreemarkerManager extends FreemarkerManager{
protected Configuration createConfiguration(ServletContext servletContext)
throws TemplateException{
Configuration configuration = new Configuration();
configuration.setTemplateLoader(getTemplateLoader(servletContext));
configuration.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER);
configuration.setSharedVariable("currency", CurrencyMethod.getInstance());
configuration.setObjectWrapper(getObjectWrapper());
if(com.opensymphony.webwork.config.Configuration.isSet("webwork.i18n.encoding"))
configuration.setDefaultEncoding(com.opensymphony.webwork.config.Configuration.getString("webwork.i18n.encoding"));
loadSettings(servletContext, configuration);
return configuration;
}
}
|
package net.minecraft.world.gen.feature;
import java.util.Random;
import net.minecraft.init.Blocks;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.World;
public class WorldGenEndIsland extends WorldGenerator {
public boolean generate(World worldIn, Random rand, BlockPos position) {
float f = (rand.nextInt(3) + 4);
for (int i = 0; f > 0.5F; i--) {
for (int j = MathHelper.floor(-f); j <= MathHelper.ceil(f); j++) {
for (int k = MathHelper.floor(-f); k <= MathHelper.ceil(f); k++) {
if ((j * j + k * k) <= (f + 1.0F) * (f + 1.0F))
setBlockAndNotifyAdequately(worldIn, position.add(j, i, k), Blocks.END_STONE.getDefaultState());
}
}
f = (float)(f - rand.nextInt(2) + 0.5D);
}
return true;
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\world\gen\feature\WorldGenEndIsland.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
|
package com.czy.demos.springbootbetterretry.controllers;
import com.czy.demos.springbootbetterretry.Exception.CzyException;
import com.czy.demos.springbootbetterretry.NormalRetry.HelloService;
import com.czy.demos.springbootbetterretry.config.CustomAnnotationRetry.CustomRetryAnnotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@Controller
public class CustomAnnotationRetryController {
@Autowired
private HelloService helloService;
@ResponseBody
@RequestMapping(value = "/annotionRetry")
@CustomRetryAnnotation(retryTimes = 10)
public void customAnnotationRetry(){
this.helloService.saySth("12121212111");
}
@ResponseBody
@RequestMapping(value = "/test11")
public void testThrowException(){
throw new CzyException("rpc调用失败");
}
@ResponseBody
@RequestMapping(value = "/test22")
public void testThrowException2(){
this.helloService.saySth("12121212111");
}
@RequestMapping(value = "/test33")
public void testThrowException3() throws Exception {
throw new Exception("指向错误页面");
}
@RequestMapping(value = "/czyerror")
public String czyerror(){
return "czyerror";
}
}
|
package com.zhowin.miyou.recommend.dialog;
import android.os.Bundle;
import android.view.View;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.zhowin.base_library.base.BaseBottomSheetFragment;
import com.zhowin.base_library.utils.ConstantValue;
import com.zhowin.miyou.R;
import com.zhowin.miyou.recommend.adapter.LiveRoomSetAdapter;
import com.zhowin.miyou.recommend.callback.OnLiveRoomSettingItemListener;
import com.zhowin.miyou.recommend.model.LiveRoomSet;
import java.util.ArrayList;
import java.util.List;
/**
* 直播间设置的dialog
*/
public class LiveRoomSettingDialog extends BaseBottomSheetFragment {
private RecyclerView liveRoomSetRecyclerView;
private LiveRoomSetAdapter liveRoomSetAdapter;
private List<LiveRoomSet> liveRoomSetList = new ArrayList<>();
private OnLiveRoomSettingItemListener onLiveRoomSettingItemListener;
private int userIdentity;//用户身份
/**
* @param userIdentity 1:房主 2:主持人 3:接待管理 4:普通管理 5:普通用户
*/
public static LiveRoomSettingDialog newInstance(int userIdentity) {
LiveRoomSettingDialog settingDialog = new LiveRoomSettingDialog();
Bundle bundle = new Bundle();
bundle.putInt(ConstantValue.TYPE, userIdentity);
settingDialog.setArguments(bundle);
return settingDialog;
}
@Override
public int getLayoutResId() {
return R.layout.include_live_room_set_layout;
}
@Override
protected boolean isFixedHeight() {
return false;
}
public void setOnLiveRoomSettingItemListener(OnLiveRoomSettingItemListener onLiveRoomSettingItemListener) {
this.onLiveRoomSettingItemListener = onLiveRoomSettingItemListener;
}
@Override
public void initView() {
userIdentity = getArguments().getInt(ConstantValue.TYPE);
liveRoomSetRecyclerView = get(R.id.liveRoomSetRecyclerView);
get(R.id.tvCancel).setOnClickListener(this::onViewClick);
liveRoomSetRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
liveRoomSetAdapter = new LiveRoomSetAdapter(addSetDataList());
liveRoomSetRecyclerView.setAdapter(liveRoomSetAdapter);
liveRoomSetAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
@Override
public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
int itemID = liveRoomSetAdapter.getItem(position).getItemId();
String itemText = liveRoomSetAdapter.getItem(position).getItemTitle();
if (onLiveRoomSettingItemListener != null) {
onLiveRoomSettingItemListener.onLiveRoomItemClick(itemID, itemText);
}
}
});
}
/**
* 根据身份设置数据
*
* @return
*/
private List<LiveRoomSet> addSetDataList() {
List<LiveRoomSet> liveRoomSetList = new ArrayList<>();
if (!liveRoomSetList.isEmpty()) liveRoomSetList.clear();
switch (userIdentity) {
case 1:
liveRoomSetList.add(new LiveRoomSet(1, "房间流水"));
liveRoomSetList.add(new LiveRoomSet(2, "房间资料"));
liveRoomSetList.add(new LiveRoomSet(3, "房间加密"));
liveRoomSetList.add(new LiveRoomSet(4, "关闭公屏"));
liveRoomSetList.add(new LiveRoomSet(5, "清除公屏"));
liveRoomSetList.add(new LiveRoomSet(6, "开启魅力值统计"));
liveRoomSetList.add(new LiveRoomSet(7, "魅力值清零"));
liveRoomSetList.add(new LiveRoomSet(8, "设置管理员"));
liveRoomSetList.add(new LiveRoomSet(9, "禁言管理"));
liveRoomSetList.add(new LiveRoomSet(10, "禁麦管理"));
liveRoomSetList.add(new LiveRoomSet(11, "踢出房间"));
liveRoomSetList.add(new LiveRoomSet(12, "收藏房间"));
liveRoomSetList.add(new LiveRoomSet(13, "分享房间"));
liveRoomSetList.add(new LiveRoomSet(15, "退出房间"));
break;
case 2:
liveRoomSetList.add(new LiveRoomSet(1, "房间流水"));
liveRoomSetList.add(new LiveRoomSet(2, "房间资料"));
liveRoomSetList.add(new LiveRoomSet(3, "房间加密"));
liveRoomSetList.add(new LiveRoomSet(4, "关闭公屏"));
liveRoomSetList.add(new LiveRoomSet(5, "清除公屏"));
liveRoomSetList.add(new LiveRoomSet(6, "开启魅力值统计"));
liveRoomSetList.add(new LiveRoomSet(7, "魅力值清零"));
liveRoomSetList.add(new LiveRoomSet(9, "禁言管理"));
liveRoomSetList.add(new LiveRoomSet(10, "禁麦管理"));
liveRoomSetList.add(new LiveRoomSet(11, "踢出房间"));
liveRoomSetList.add(new LiveRoomSet(12, "收藏房间"));
liveRoomSetList.add(new LiveRoomSet(13, "分享房间"));
liveRoomSetList.add(new LiveRoomSet(14, "举报房间"));
liveRoomSetList.add(new LiveRoomSet(15, "退出房间"));
break;
case 3:
liveRoomSetList.add(new LiveRoomSet(2, "房间资料"));
liveRoomSetList.add(new LiveRoomSet(9, "禁言管理"));
liveRoomSetList.add(new LiveRoomSet(10, "禁麦管理"));
liveRoomSetList.add(new LiveRoomSet(11, "踢出房间"));
liveRoomSetList.add(new LiveRoomSet(12, "收藏房间"));
liveRoomSetList.add(new LiveRoomSet(13, "分享房间"));
liveRoomSetList.add(new LiveRoomSet(14, "举报房间"));
liveRoomSetList.add(new LiveRoomSet(15, "退出房间"));
break;
case 4:
case 5:
liveRoomSetList.add(new LiveRoomSet(12, "收藏房间"));
liveRoomSetList.add(new LiveRoomSet(13, "分享房间"));
liveRoomSetList.add(new LiveRoomSet(14, "举报房间"));
liveRoomSetList.add(new LiveRoomSet(15, "退出房间"));
break;
}
return liveRoomSetList;
}
@Override
public void onViewClick(View view) {
switch (view.getId()) {
case R.id.tvCancel:
dismiss();
break;
}
}
}
|
package model.pivot;
import java.util.ArrayList;
import java.util.List;
public class Record {
List<Member> values;
public Record(){
values=new ArrayList<Member>();
}
public List<Member> getValues() {
return values;
}
public void setValues(List<Member> values) {
this.values = values;
}
public Member getMemberByMeta(RecordMeta m) {
return values.get(m.getPos());
}
public Member getMemberByIndex(Integer idx) {
return values.get(idx);
}
public void print() {
String row="";
for(Member m: values){
row+=m+",";
}
// system.out.println(row);
}
}
|
//Copyright Hale [hale2000@163.com]
//
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
package tech.kiwa.engine.component.impl;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import tech.kiwa.engine.component.AbstractRuleReader;
import tech.kiwa.engine.entity.RuleItem;
import tech.kiwa.engine.exception.RuleEngineException;
import tech.kiwa.engine.utility.PropertyUtil;
/**
* @author Hale.Li
* @since 2018-01-28
* @version 0.1
*/
public class XMLRuleReader extends AbstractRuleReader {
private static Logger log = LoggerFactory.getLogger(XMLRuleReader.class);
private List<RuleItem> itemList = null;
@Override
public List<RuleItem> readRuleItemList() throws RuleEngineException {
//缓存加载
if(!ruleItemCache.isEmpty()){
return ruleItemCache;
}
itemList = new ArrayList<RuleItem>();
try {
// 创建DOM文档对象
DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dFactory.newDocumentBuilder();
Document doc;
String configFile = PropertyUtil.getProperty("xml.rule.filename");
if(!configFile.startsWith(File.separator)){
File dir = new File(PropertyUtil.class.getClassLoader().getResource("").getPath());
configFile = dir + File.separator + configFile;
}
doc = builder.parse(new File(configFile));
// 获取包含类名的文本节点
NodeList ruleList = doc.getElementsByTagName("rule");
for(int iLoop =0; iLoop < ruleList.getLength();iLoop++){
RuleItem item = new RuleItem();
Node rule = ruleList.item(iLoop);
NamedNodeMap attributes = rule.getAttributes();
if(null == attributes || attributes.getNamedItem("id") == null){
log.debug("rule id must not be null. rule.context = {}", rule.getTextContent());
return null;
}
String xmlRuleId = attributes.getNamedItem("id").getNodeValue();
item.setItemNo(xmlRuleId);
for(int jLoop =0 ; jLoop < attributes.getLength(); jLoop++){
Node node = attributes.item(jLoop);
item.setMappedValue(node.getNodeName(), node.getNodeValue());
}
// alias of attribute name.
if(attributes.getNamedItem("class") != null){
item.setExeClass(attributes.getNamedItem("class").getNodeValue());
}
if(attributes.getNamedItem("method") != null){
item.setExecutor(rule.getAttributes().getNamedItem("method").getNodeValue());
}
if(attributes.getNamedItem("parent") != null){
item.setParentItemNo(rule.getAttributes().getNamedItem("parent").getNodeValue());
}
if(rule.hasChildNodes()){
Node child = rule.getFirstChild();
while(child != null){
if("property".equalsIgnoreCase(child.getNodeName())){
NamedNodeMap childAttrs = child.getAttributes();
Node nameNode = childAttrs.getNamedItem("name");
Node valueNode = childAttrs.getNamedItem("value");
if(valueNode == null || nameNode == null){
throw new RuleEngineException("rule format error, attribute value or name must existed.");
}
Node typeNode = childAttrs.getNamedItem("type");
item.setMappedValue(nameNode.getNodeValue(), valueNode.getNodeValue());
if("param".equalsIgnoreCase(nameNode.getNodeValue())){
item.setParamName(valueNode.getNodeValue());
item.setParamType(typeNode.getNodeValue());
}
if("comparison".equalsIgnoreCase(nameNode.getNodeValue())){
Node codeNode = childAttrs.getNamedItem("code");
item.setComparisonCode(codeNode.getNodeValue());
item.setComparisonValue(valueNode.getNodeValue());
}
}
child = child.getNextSibling();
}
} // endif hasChildNodes.
if(!preCompile(item)){
log.debug("xml rule format error.");
throw new RuleEngineException("rule format error.");
//return null;
}
itemList.add(item);
} // end for
} catch (Exception e) {
log.debug(e.getMessage());
throw new RuleEngineException(e.getCause());
//return null;
}
synchronized(ruleItemCache){
ruleItemCache.addAll(itemList);
}
return ruleItemCache;
}
@Override
public Long getRuleItemCount() throws RuleEngineException {
if(itemList == null){
this.readRuleItemList();
return (long) itemList.size();
}
return 0L;
}
@Override
public RuleItem getRuleItem(String ruleId) throws RuleEngineException {
if(itemList == null){
this.readRuleItemList();
}
for(RuleItem rule: itemList){
if(rule.getItemNo().equalsIgnoreCase(ruleId)){
return rule;
}
}
RuleItem item = new RuleItem();
try {
// 创建DOM文档对象
DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dFactory.newDocumentBuilder();
Document doc;
String configFile = PropertyUtil.getProperty("xml.rule.filename");
if(!configFile.startsWith(File.separator)){
File dir = new File(PropertyUtil.class.getClassLoader().getResource("").getPath());
configFile = dir + File.separator + configFile;
}
doc = builder.parse(new File(configFile));
// 获取包含类名的文本节点
NodeList ruleList = doc.getElementsByTagName("rule");
for(int iLoop =0; iLoop < ruleList.getLength();iLoop++){
Node rule = ruleList.item(iLoop);
NamedNodeMap attributes = rule.getAttributes();
if(null == attributes || attributes.getNamedItem("id") == null){
log.debug("rule id must not be null.");
return null;
}
String xmlRuleId = attributes.getNamedItem("id").getNodeValue();
if(!ruleId.equalsIgnoreCase(xmlRuleId)){
continue;
}
item.setItemNo(xmlRuleId);
for(int jLoop =0 ; jLoop < attributes.getLength(); jLoop++){
Node node = attributes.item(jLoop);
item.setMappedValue(node.getNodeName(), node.getNodeValue());
}
// alias attribute name.
if(attributes.getNamedItem("class") != null){
item.setExeClass(attributes.getNamedItem("class").getNodeValue());
}
if(attributes.getNamedItem("method") != null){
item.setExecutor(rule.getAttributes().getNamedItem("method").getNodeValue());
}
if(attributes.getNamedItem("parent") != null){
item.setParentItemNo(rule.getAttributes().getNamedItem("parent").getNodeValue());
}
if(rule.hasChildNodes()){
Node child = rule.getFirstChild();
while(child != null){
if("property".equalsIgnoreCase(child.getNodeName())){
NamedNodeMap childAttrs = child.getAttributes();
Node nameNode = childAttrs.getNamedItem("name");
Node valueNode = childAttrs.getNamedItem("value");
item.setMappedValue(nameNode.getNodeValue(), valueNode.getNodeValue());
}
child = child.getNextSibling();
}
}
if(!preCompile(item)){
log.debug("xml rule format error.");
throw new RuleEngineException("rule format error.");
//return null;
}
// found , then return.
if(ruleId.equalsIgnoreCase(xmlRuleId)){
return item;
//break;
}
}
} catch (Exception e) {
log.debug(e.getMessage());
throw new RuleEngineException(e.getCause());
//return null;
}
return null;
}
public static void main(String[] args){
XMLRuleReader reader = new XMLRuleReader();
try {
reader.getRuleItem("blacklist");
} catch (RuleEngineException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package com.xiaoma.dd.pojo;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
public class CompanyExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public CompanyExample() {
oredCriteria = new ArrayList<Criteria>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
protected void addCriterionForJDBCDate(String condition, Date value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
addCriterion(condition, new java.sql.Date(value.getTime()), property);
}
protected void addCriterionForJDBCDate(String condition, List<Date> values, String property) {
if (values == null || values.size() == 0) {
throw new RuntimeException("Value list for " + property + " cannot be null or empty");
}
List<java.sql.Date> dateList = new ArrayList<java.sql.Date>();
Iterator<Date> iter = values.iterator();
while (iter.hasNext()) {
dateList.add(new java.sql.Date(iter.next().getTime()));
}
addCriterion(condition, dateList, property);
}
protected void addCriterionForJDBCDate(String condition, Date value1, Date value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
addCriterion(condition, new java.sql.Date(value1.getTime()), new java.sql.Date(value2.getTime()), property);
}
public Criteria andIdIsNull() {
addCriterion("id is null");
return (Criteria) this;
}
public Criteria andIdIsNotNull() {
addCriterion("id is not null");
return (Criteria) this;
}
public Criteria andIdEqualTo(Integer value) {
addCriterion("id =", value, "id");
return (Criteria) this;
}
public Criteria andIdNotEqualTo(Integer value) {
addCriterion("id <>", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThan(Integer value) {
addCriterion("id >", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThanOrEqualTo(Integer value) {
addCriterion("id >=", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThan(Integer value) {
addCriterion("id <", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThanOrEqualTo(Integer value) {
addCriterion("id <=", value, "id");
return (Criteria) this;
}
public Criteria andIdIn(List<Integer> values) {
addCriterion("id in", values, "id");
return (Criteria) this;
}
public Criteria andIdNotIn(List<Integer> values) {
addCriterion("id not in", values, "id");
return (Criteria) this;
}
public Criteria andIdBetween(Integer value1, Integer value2) {
addCriterion("id between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andIdNotBetween(Integer value1, Integer value2) {
addCriterion("id not between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andNameIsNull() {
addCriterion("name is null");
return (Criteria) this;
}
public Criteria andNameIsNotNull() {
addCriterion("name is not null");
return (Criteria) this;
}
public Criteria andNameEqualTo(String value) {
addCriterion("name =", value, "name");
return (Criteria) this;
}
public Criteria andNameNotEqualTo(String value) {
addCriterion("name <>", value, "name");
return (Criteria) this;
}
public Criteria andNameGreaterThan(String value) {
addCriterion("name >", value, "name");
return (Criteria) this;
}
public Criteria andNameGreaterThanOrEqualTo(String value) {
addCriterion("name >=", value, "name");
return (Criteria) this;
}
public Criteria andNameLessThan(String value) {
addCriterion("name <", value, "name");
return (Criteria) this;
}
public Criteria andNameLessThanOrEqualTo(String value) {
addCriterion("name <=", value, "name");
return (Criteria) this;
}
public Criteria andNameLike(String value) {
addCriterion("name like", value, "name");
return (Criteria) this;
}
public Criteria andNameNotLike(String value) {
addCriterion("name not like", value, "name");
return (Criteria) this;
}
public Criteria andNameIn(List<String> values) {
addCriterion("name in", values, "name");
return (Criteria) this;
}
public Criteria andNameNotIn(List<String> values) {
addCriterion("name not in", values, "name");
return (Criteria) this;
}
public Criteria andNameBetween(String value1, String value2) {
addCriterion("name between", value1, value2, "name");
return (Criteria) this;
}
public Criteria andNameNotBetween(String value1, String value2) {
addCriterion("name not between", value1, value2, "name");
return (Criteria) this;
}
public Criteria andRepNameIsNull() {
addCriterion("rep_name is null");
return (Criteria) this;
}
public Criteria andRepNameIsNotNull() {
addCriterion("rep_name is not null");
return (Criteria) this;
}
public Criteria andRepNameEqualTo(String value) {
addCriterion("rep_name =", value, "repName");
return (Criteria) this;
}
public Criteria andRepNameNotEqualTo(String value) {
addCriterion("rep_name <>", value, "repName");
return (Criteria) this;
}
public Criteria andRepNameGreaterThan(String value) {
addCriterion("rep_name >", value, "repName");
return (Criteria) this;
}
public Criteria andRepNameGreaterThanOrEqualTo(String value) {
addCriterion("rep_name >=", value, "repName");
return (Criteria) this;
}
public Criteria andRepNameLessThan(String value) {
addCriterion("rep_name <", value, "repName");
return (Criteria) this;
}
public Criteria andRepNameLessThanOrEqualTo(String value) {
addCriterion("rep_name <=", value, "repName");
return (Criteria) this;
}
public Criteria andRepNameLike(String value) {
addCriterion("rep_name like", value, "repName");
return (Criteria) this;
}
public Criteria andRepNameNotLike(String value) {
addCriterion("rep_name not like", value, "repName");
return (Criteria) this;
}
public Criteria andRepNameIn(List<String> values) {
addCriterion("rep_name in", values, "repName");
return (Criteria) this;
}
public Criteria andRepNameNotIn(List<String> values) {
addCriterion("rep_name not in", values, "repName");
return (Criteria) this;
}
public Criteria andRepNameBetween(String value1, String value2) {
addCriterion("rep_name between", value1, value2, "repName");
return (Criteria) this;
}
public Criteria andRepNameNotBetween(String value1, String value2) {
addCriterion("rep_name not between", value1, value2, "repName");
return (Criteria) this;
}
public Criteria andCreateMoneyIsNull() {
addCriterion("create_money is null");
return (Criteria) this;
}
public Criteria andCreateMoneyIsNotNull() {
addCriterion("create_money is not null");
return (Criteria) this;
}
public Criteria andCreateMoneyEqualTo(Double value) {
addCriterion("create_money =", value, "createMoney");
return (Criteria) this;
}
public Criteria andCreateMoneyNotEqualTo(Double value) {
addCriterion("create_money <>", value, "createMoney");
return (Criteria) this;
}
public Criteria andCreateMoneyGreaterThan(Double value) {
addCriterion("create_money >", value, "createMoney");
return (Criteria) this;
}
public Criteria andCreateMoneyGreaterThanOrEqualTo(Double value) {
addCriterion("create_money >=", value, "createMoney");
return (Criteria) this;
}
public Criteria andCreateMoneyLessThan(Double value) {
addCriterion("create_money <", value, "createMoney");
return (Criteria) this;
}
public Criteria andCreateMoneyLessThanOrEqualTo(Double value) {
addCriterion("create_money <=", value, "createMoney");
return (Criteria) this;
}
public Criteria andCreateMoneyIn(List<Double> values) {
addCriterion("create_money in", values, "createMoney");
return (Criteria) this;
}
public Criteria andCreateMoneyNotIn(List<Double> values) {
addCriterion("create_money not in", values, "createMoney");
return (Criteria) this;
}
public Criteria andCreateMoneyBetween(Double value1, Double value2) {
addCriterion("create_money between", value1, value2, "createMoney");
return (Criteria) this;
}
public Criteria andCreateMoneyNotBetween(Double value1, Double value2) {
addCriterion("create_money not between", value1, value2, "createMoney");
return (Criteria) this;
}
public Criteria andCreateTimeIsNull() {
addCriterion("create_time is null");
return (Criteria) this;
}
public Criteria andCreateTimeIsNotNull() {
addCriterion("create_time is not null");
return (Criteria) this;
}
public Criteria andCreateTimeEqualTo(Date value) {
addCriterionForJDBCDate("create_time =", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotEqualTo(Date value) {
addCriterionForJDBCDate("create_time <>", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeGreaterThan(Date value) {
addCriterionForJDBCDate("create_time >", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeGreaterThanOrEqualTo(Date value) {
addCriterionForJDBCDate("create_time >=", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeLessThan(Date value) {
addCriterionForJDBCDate("create_time <", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeLessThanOrEqualTo(Date value) {
addCriterionForJDBCDate("create_time <=", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeIn(List<Date> values) {
addCriterionForJDBCDate("create_time in", values, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotIn(List<Date> values) {
addCriterionForJDBCDate("create_time not in", values, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeBetween(Date value1, Date value2) {
addCriterionForJDBCDate("create_time between", value1, value2, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotBetween(Date value1, Date value2) {
addCriterionForJDBCDate("create_time not between", value1, value2, "createTime");
return (Criteria) this;
}
public Criteria andTelIsNull() {
addCriterion("tel is null");
return (Criteria) this;
}
public Criteria andTelIsNotNull() {
addCriterion("tel is not null");
return (Criteria) this;
}
public Criteria andTelEqualTo(String value) {
addCriterion("tel =", value, "tel");
return (Criteria) this;
}
public Criteria andTelNotEqualTo(String value) {
addCriterion("tel <>", value, "tel");
return (Criteria) this;
}
public Criteria andTelGreaterThan(String value) {
addCriterion("tel >", value, "tel");
return (Criteria) this;
}
public Criteria andTelGreaterThanOrEqualTo(String value) {
addCriterion("tel >=", value, "tel");
return (Criteria) this;
}
public Criteria andTelLessThan(String value) {
addCriterion("tel <", value, "tel");
return (Criteria) this;
}
public Criteria andTelLessThanOrEqualTo(String value) {
addCriterion("tel <=", value, "tel");
return (Criteria) this;
}
public Criteria andTelLike(String value) {
addCriterion("tel like", value, "tel");
return (Criteria) this;
}
public Criteria andTelNotLike(String value) {
addCriterion("tel not like", value, "tel");
return (Criteria) this;
}
public Criteria andTelIn(List<String> values) {
addCriterion("tel in", values, "tel");
return (Criteria) this;
}
public Criteria andTelNotIn(List<String> values) {
addCriterion("tel not in", values, "tel");
return (Criteria) this;
}
public Criteria andTelBetween(String value1, String value2) {
addCriterion("tel between", value1, value2, "tel");
return (Criteria) this;
}
public Criteria andTelNotBetween(String value1, String value2) {
addCriterion("tel not between", value1, value2, "tel");
return (Criteria) this;
}
public Criteria andAddressIsNull() {
addCriterion("address is null");
return (Criteria) this;
}
public Criteria andAddressIsNotNull() {
addCriterion("address is not null");
return (Criteria) this;
}
public Criteria andAddressEqualTo(String value) {
addCriterion("address =", value, "address");
return (Criteria) this;
}
public Criteria andAddressNotEqualTo(String value) {
addCriterion("address <>", value, "address");
return (Criteria) this;
}
public Criteria andAddressGreaterThan(String value) {
addCriterion("address >", value, "address");
return (Criteria) this;
}
public Criteria andAddressGreaterThanOrEqualTo(String value) {
addCriterion("address >=", value, "address");
return (Criteria) this;
}
public Criteria andAddressLessThan(String value) {
addCriterion("address <", value, "address");
return (Criteria) this;
}
public Criteria andAddressLessThanOrEqualTo(String value) {
addCriterion("address <=", value, "address");
return (Criteria) this;
}
public Criteria andAddressLike(String value) {
addCriterion("address like", value, "address");
return (Criteria) this;
}
public Criteria andAddressNotLike(String value) {
addCriterion("address not like", value, "address");
return (Criteria) this;
}
public Criteria andAddressIn(List<String> values) {
addCriterion("address in", values, "address");
return (Criteria) this;
}
public Criteria andAddressNotIn(List<String> values) {
addCriterion("address not in", values, "address");
return (Criteria) this;
}
public Criteria andAddressBetween(String value1, String value2) {
addCriterion("address between", value1, value2, "address");
return (Criteria) this;
}
public Criteria andAddressNotBetween(String value1, String value2) {
addCriterion("address not between", value1, value2, "address");
return (Criteria) this;
}
public Criteria andCreateUidIsNull() {
addCriterion("create_uid is null");
return (Criteria) this;
}
public Criteria andCreateUidIsNotNull() {
addCriterion("create_uid is not null");
return (Criteria) this;
}
public Criteria andCreateUidEqualTo(Integer value) {
addCriterion("create_uid =", value, "createUid");
return (Criteria) this;
}
public Criteria andCreateUidNotEqualTo(Integer value) {
addCriterion("create_uid <>", value, "createUid");
return (Criteria) this;
}
public Criteria andCreateUidGreaterThan(Integer value) {
addCriterion("create_uid >", value, "createUid");
return (Criteria) this;
}
public Criteria andCreateUidGreaterThanOrEqualTo(Integer value) {
addCriterion("create_uid >=", value, "createUid");
return (Criteria) this;
}
public Criteria andCreateUidLessThan(Integer value) {
addCriterion("create_uid <", value, "createUid");
return (Criteria) this;
}
public Criteria andCreateUidLessThanOrEqualTo(Integer value) {
addCriterion("create_uid <=", value, "createUid");
return (Criteria) this;
}
public Criteria andCreateUidIn(List<Integer> values) {
addCriterion("create_uid in", values, "createUid");
return (Criteria) this;
}
public Criteria andCreateUidNotIn(List<Integer> values) {
addCriterion("create_uid not in", values, "createUid");
return (Criteria) this;
}
public Criteria andCreateUidBetween(Integer value1, Integer value2) {
addCriterion("create_uid between", value1, value2, "createUid");
return (Criteria) this;
}
public Criteria andCreateUidNotBetween(Integer value1, Integer value2) {
addCriterion("create_uid not between", value1, value2, "createUid");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
}
|
package tutorialFX;
import org.jbox2d.dynamics.joints.RevoluteJointDef;
/**
* Created by ea on 17.05.15.
*/
public class FlappingJointDef extends RevoluteJointDef {
/**
* A flag to enable flapping.
*/
public boolean enableFlapping;
/**
* Angels for flapping: to change Motor direction
*/
public float upperFlapping;
public float lowerFlapping;
}
|
package com.lubarov.daniel.web.html;
public final class Xhtml5Document {
private final Element html;
public Xhtml5Document(Element html) {
this.html = html;
}
@Override
public String toString() {
return String.format("%s\n%s\n%s",
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
"<!DOCTYPE html>",
html);
}
}
|
package com.tencent.mm.plugin.voip.model;
import com.tencent.mm.ab.l;
import com.tencent.mm.compatible.util.g;
import com.tencent.mm.model.au;
import com.tencent.mm.model.q;
import com.tencent.mm.plugin.appbrand.s$l;
import com.tencent.mm.plugin.report.service.h;
import com.tencent.mm.plugin.voip.b.a;
import com.tencent.mm.plugin.voip.model.a.m;
import com.tencent.mm.protocal.c.bhy;
import com.tencent.mm.protocal.c.bzt;
import com.tencent.mm.protocal.c.bzu;
import com.tencent.mm.protocal.c.caf;
import com.tencent.mm.protocal.c.cak;
import com.tencent.mm.protocal.c.cav;
import com.tencent.mm.protocal.c.cax;
import com.tencent.mm.sdk.platformtools.x;
import java.util.LinkedList;
public final class t {
j oHa = null;
caf oNI = new caf();
private bzu oNJ = null;
private int oNK = 0;
public t(j jVar) {
this.oHa = jVar;
}
private void a(bzu bzu) {
if (bzu == null) {
a.eT("MicroMsg.Voip.VoipSyncHandle", "failed to pushVoipCmdList , VoipCmdList = null");
this.oNK++;
return;
}
if (this.oNJ == null) {
this.oNJ = new bzu();
}
int i = 0;
while (true) {
int i2 = i;
if (i2 < bzu.hbF) {
this.oNJ.hbG.add((bzt) bzu.hbG.get(i2));
i = i2 + 1;
} else {
this.oNJ.hbF = this.oNJ.hbG.size();
return;
}
}
}
private void b(bzu bzu) {
if (this.oNJ != null && this.oNJ.hbF > 0) {
int i = 0;
while (true) {
int i2 = i;
if (i2 < this.oNJ.hbF) {
bzu.hbG.add((bzt) this.oNJ.hbG.get(i2));
i = i2 + 1;
} else {
bzu.hbF = bzu.hbG.size();
bLl();
return;
}
}
}
}
public final void bLl() {
if (this.oNJ != null) {
this.oNJ.hbG.clear();
this.oNJ.hbF = 0;
this.oNJ = null;
this.oNK = 0;
}
}
public final int a(bzu bzu, boolean z, int i) {
if (this.oHa.oJX.kpo == 0) {
a.eT("MicroMsg.Voip.VoipSyncHandle", g.Ac() + "failed to do voip sync , roomid = 0");
} else if (this.oHa.oKd) {
a.eT("MicroMsg.Voip.VoipSyncHandle", g.Ac() + "voip syncing, push to cache...");
a(bzu);
} else {
bzu bzu2;
this.oHa.oKd = true;
if (bzu == null) {
bzu2 = new bzu();
bzu2.hbF = 0;
bzu2.hbG = new LinkedList();
} else {
bzu2 = bzu;
}
b(bzu2);
this.oNK = 0;
if (this.oHa.oKb == null) {
this.oHa.oKb = "".getBytes();
}
a.eU("MicroMsg.Voip.VoipSyncHandle", "____doVoipSync, fromjni:" + z + ",cmdList:" + bzu2.hbF + ",syncKey.length:" + this.oHa.oKb.length + ",selector:" + i);
new m(this.oHa.oJX.kpo, bzu2, this.oHa.oKb, this.oHa.oJX.kpp, i).bLp();
}
return 0;
}
public final void a(cav cav, int i) {
a.eU("MicroMsg.Voip.VoipSyncHandle", "onStatusChanged: status:" + cav.hcd);
if (cav.hcd == 1) {
m mVar;
this.oHa.oJw = true;
if (1 == i) {
mVar = this.oHa.oJX.oPS;
if (0 == mVar.oLs) {
mVar.oLs = System.currentTimeMillis();
a.eU("MicroMsg.VoipDailReport", "accept received timestamp:" + mVar.oLs);
}
}
if (3 == i) {
mVar = this.oHa.oJX.oPS;
if (0 == mVar.oLt) {
mVar.oLt = System.currentTimeMillis();
a.eU("MicroMsg.VoipDailReport", "sync accept received timestamp:" + mVar.oLt);
}
}
a.eU("MicroMsg.Voip.VoipSyncHandle", "zhengxue[DataAccept]onVoipSyncStatus:ACCEPTdata Flag: " + i);
this.oHa.oJY.aWJ();
i.bJI().oNa.bLk();
this.oHa.oJx = true;
if (this.oHa.oJz) {
this.oHa.oJz = false;
if (this.oHa.oJv) {
a.eU("MicroMsg.Voip.VoipSyncHandle", "onVoipSyncStatus:ACCEPT, pre-connect already success");
this.oHa.bJT();
} else if (this.oHa.oJy) {
a.eU("MicroMsg.Voip.VoipSyncHandle", "onVoipSyncStatus: ACCEPT, pre-connect already fail");
this.oHa.o(1, -9000, "");
} else {
a.eU("MicroMsg.Voip.VoipSyncHandle", "onVoipSyncStatus: ACCEPT, pre-connect still connecting...");
}
}
h.mEJ.h(11519, new Object[]{Integer.valueOf(i.bJI().bKS()), Long.valueOf(i.bJI().bKT()), Long.valueOf(i.bJI().bKU()), Integer.valueOf(2)});
this.oHa.bJZ();
this.oHa.bKb();
} else if (cav.hcd == 6) {
a.eU("MicroMsg.Voip.VoipSyncHandle", "onVoipSyncStatus: ACKED");
a.eU("MicroMsg.Voip.VoipSyncHandle", "onVoipSyncStatus: try use pre-connect");
this.oHa.oJz = true;
this.oHa.oJX.oON = 1;
this.oHa.bJZ();
} else if (cav.hcd == 8) {
a.eU("MicroMsg.Voip.VoipSyncHandle", "onVoipSyncStatus: ACK BUSY");
this.oHa.oJX.oPS.oKR = 211;
this.oHa.oJX.oPS.oKQ = 11;
this.oHa.oJX.oPS.oLc = 12;
h.mEJ.h(11519, new Object[]{Integer.valueOf(i.bJI().bKS()), Long.valueOf(i.bJI().bKT()), Long.valueOf(i.bJI().bKU()), Integer.valueOf(3)});
this.oHa.o(1, 211, "");
this.oHa.bKb();
} else if (cav.hcd == 2) {
a.eU("MicroMsg.Voip.VoipSyncHandle", "onVoipSyncStatus...MM_VOIP_SYNC_STATUS_REJECT");
this.oHa.oJX.oPS.oKQ = s$l.AppCompatTheme_checkedTextViewStyle;
this.oHa.oJX.oPS.oLc = 4;
this.oHa.oJX.oPS.oLj = (int) (System.currentTimeMillis() - this.oHa.oJX.oPS.beginTime);
h.mEJ.h(11519, new Object[]{Integer.valueOf(i.bJI().bKS()), Long.valueOf(i.bJI().bKT()), Long.valueOf(i.bJI().bKU()), Integer.valueOf(1)});
this.oHa.bKb();
this.oHa.o(4, 0, "");
} else if (cav.hcd == 3) {
this.oHa.oJX.oPS.oLc = 5;
} else if (cav.hcd == 4) {
a.eU("MicroMsg.Voip.VoipSyncHandle", "onVoipSyncStatus...MM_VOIP_SYNC_STATUS_SHUTDOWN");
if (this.oHa.mStatus < 6) {
this.oHa.oJX.oPS.oLd = 1;
}
this.oHa.oJX.oPS.oKQ = s$l.AppCompatTheme_spinnerStyle;
this.oHa.o(6, 0, "");
this.oHa.bKb();
} else {
a.eU("MicroMsg.Voip.VoipSyncHandle", "onStatusChanged: unknow status:" + cav.hcd);
}
}
public final void a(cak cak) {
au.Em().H(new 1(this, cak));
}
public final void b(cak cak) {
j jVar = this.oHa;
jVar.oJX.oOo = cak.rfy.siK.toByteArray();
jVar.bKa();
}
public final void c(bhy bhy) {
int aV = a.aV(bhy.siK.toByteArray());
a.eU("MicroMsg.Voip.VoipSyncHandle", "voipSync remote status changed, status = " + aV);
j jVar = this.oHa;
aV &= 255;
if (8 == aV || 9 == aV) {
jVar.oJP = aV;
} else {
jVar.oJN = aV;
jVar.oJL = aV;
}
if (1 == aV || 3 == aV) {
jVar.yw(2);
}
jVar.oJY.yF(aV);
}
public final void o(l lVar) {
x.i("MicroMsg.Voip.VoipSyncHandle", "____VoipSyncResp");
this.oHa.oKd = false;
cax cax = (cax) ((m) lVar).bLq();
this.oHa.oJX.parseSyncKeyBuff(this.oHa.oKb, this.oHa.oKb.length);
int i = this.oHa.oJX.field_statusSyncKey;
int i2 = this.oHa.oJX.field_relayDataSyncKey;
int i3 = this.oHa.oJX.field_connectingStatusKey;
this.oHa.oJX.parseSyncKeyBuff(cax.rny.siK.toByteArray(), cax.rny.siI);
int i4 = this.oHa.oJX.field_statusSyncKey;
int i5 = this.oHa.oJX.field_relayDataSyncKey;
int i6 = this.oHa.oJX.field_connectingStatusKey;
x.i("MicroMsg.Voip.VoipSyncHandle", "VoipSyncResp: oldStatusSyncKey:" + i + " oldRelayDataSyncKey:" + i2 + " oldConnectingStatusSyncKey:" + i3);
x.i("MicroMsg.Voip.VoipSyncHandle", "VoipSyncResp: newStatusSyncKey:" + i4 + " newRelayDataSyncKey:" + i5 + " newConnectingStatusSyncKey:" + i6);
this.oHa.oKb = cax.rny.siK.toByteArray();
x.i("MicroMsg.Voip.VoipSyncHandle", "voipSync response: continueflag=" + cax.rlm);
LinkedList linkedList = cax.sxi.hbG;
if (linkedList != null && linkedList.size() != 0) {
x.i("MicroMsg.Voip.VoipSyncHandle", " syncOnSceneEnd cmdlist size" + linkedList.size());
x.i("MicroMsg.Voip.VoipSyncHandle", " syncOnSceneEnd cmdlist size:" + linkedList.size() + ",selector = " + ((m) lVar).bLo());
int i7 = 0;
while (true) {
int i8 = i7;
if (i8 >= linkedList.size()) {
break;
}
bzt bzt = (bzt) linkedList.get(i8);
int i9 = bzt.rtM;
x.i("MicroMsg.Voip.VoipSyncHandle", "__parse sync resp, item cmdid:" + i9);
if (i9 == 1) {
if (i4 > i) {
if (this.oHa.oJX.kpo == 0) {
a.eT("MicroMsg.Voip.VoipSyncHandle", "voipSyncStatus ignored , roomid = 0");
} else {
try {
cav cav = (cav) new cav().aG(bzt.rtN.siK.toByteArray());
a.eU("MicroMsg.Voip.VoipSyncHandle", "onVoipSyncStatus in...from user=" + bzt.jTv + ",itemStatus = " + cav.hcd);
a(cav, 3);
} catch (Throwable e) {
x.printErrStackTrace("MicroMsg.Voip.VoipSyncHandle", e, "", new Object[0]);
}
}
}
} else if (i9 == 2) {
if (i5 > i2) {
if (this.oHa.oJX.kpo == 0) {
a.eT("MicroMsg.Voip.VoipSyncHandle", "RelayData ignored , roomid = 0");
} else {
try {
cak cak = (cak) new cak().aG(bzt.rtN.siK.toByteArray());
a.eU("MicroMsg.Voip.VoipSyncHandle", "onVoipSyncRelayData ...relayType = " + cak.hcE + ",from user = " + bzt.jTv);
if (cak.hcE == 5) {
a(cak);
} else if (cak.hcE == 3) {
this.oHa.aR(cak.rfy.siK.toByteArray());
if (!(cak.rfy == null || cak.rfy.siK == null)) {
this.oNI.suL = cak;
}
} else if (cak.hcE == 2) {
this.oHa.aQ(cak.rfy.siK.toByteArray());
if (!(cak.rfy == null || cak.rfy.siK == null)) {
this.oNI.suK = cak;
}
} else if (cak.hcE == 1) {
b(cak);
}
} catch (Throwable e2) {
x.printErrStackTrace("MicroMsg.Voip.VoipSyncHandle", e2, "", new Object[0]);
}
}
}
} else if (i9 == 3 && i6 > i3) {
if (this.oHa.oJX.kpo == 0) {
x.e("MicroMsg.Voip.VoipSyncHandle", "voipSync(ClientStatus) ignored , roomid = 0");
} else {
try {
bhy br = new bhy().br(bzt.rtN.siK.toByteArray());
if (bzt.jTv.equals(q.GF())) {
a.eT("MicroMsg.Voip.VoipSyncHandle", "svr response: local connecting status changed.");
} else {
c(br);
}
} catch (Throwable e22) {
x.printErrStackTrace("MicroMsg.Voip.VoipSyncHandle", e22, "", new Object[0]);
}
}
}
i7 = i8 + 1;
}
}
x.i("MicroMsg.Voip.VoipSyncHandle", "__parse sync resp end");
if ((this.oNJ != null && this.oNJ.hbF > 0) || this.oNK > 0) {
a(null, false, 7);
}
}
}
|
package net.minecraft.util.text;
public class TextComponentTranslationFormatException extends IllegalArgumentException {
public TextComponentTranslationFormatException(TextComponentTranslation component, String message) {
super(String.format("Error parsing: %s: %s", new Object[] { component, message }));
}
public TextComponentTranslationFormatException(TextComponentTranslation component, int index) {
super(String.format("Invalid index %d requested for %s", new Object[] { Integer.valueOf(index), component }));
}
public TextComponentTranslationFormatException(TextComponentTranslation component, Throwable cause) {
super(String.format("Error while parsing: %s", new Object[] { component }), cause);
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraf\\util\text\TextComponentTranslationFormatException.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
|
package io.ucia.login;
import android.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements StudentRegFragment.OnSaveStudentListener {
private EditText etXh;
private Button btnLogin;
private Button btnReg;
private FragmentManager fragmentManager;
private StudentRegFragment studentRegFragment;
private StudentInfoFragment studentInfoFragment;
private StudentListFragment studentListFragment;
private List<Student> stuList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentManager = this.getFragmentManager();
studentRegFragment = new StudentRegFragment();
studentRegFragment.setArguments(new Bundle());
fragmentManager.beginTransaction()
.add(R.id.leftContainer, studentRegFragment, "student_reg")
.hide(studentRegFragment)
.commit();
studentInfoFragment = new StudentInfoFragment();
studentInfoFragment.setArguments(new Bundle());
fragmentManager.beginTransaction()
.add(R.id.rightContainer, studentInfoFragment, "student_info")
.hide(studentInfoFragment)
.commit();
studentListFragment = new StudentListFragment();
studentListFragment.setArguments(new Bundle());
fragmentManager.beginTransaction()
.add(R.id.bottomContainer, studentListFragment, "student_list")
.hide(studentListFragment)
.commit();
stuList = new ArrayList<>();
etXh = findViewById(R.id.xh);
btnLogin = findViewById(R.id.login);
btnReg = findViewById(R.id.reg);
btnReg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String xh = etXh.getText().toString().trim();
if (xh.length()==0){
Toast.makeText(MainActivity.this, "请输入学号!", Toast.LENGTH_SHORT).show();
return;
}
etXh.setEnabled(false);
btnReg.setEnabled(false);
studentRegFragment.getArguments().putString("xh", xh);
Log.d("reg", ""+studentRegFragment.isHidden());
if (studentRegFragment.isHidden())
fragmentManager.beginTransaction().show(studentRegFragment).commit();
if (studentInfoFragment.isHidden())
fragmentManager.beginTransaction().show(studentInfoFragment).commit();
else
((TextView)studentInfoFragment.getView().findViewById(R.id.tv_info)).setText(null);
if (studentListFragment.isHidden())
fragmentManager.beginTransaction().show(studentListFragment).commit();
etXh.setEnabled(false);
btnLogin.setEnabled(false);
btnReg.setEnabled(false);
Button btnSave = studentRegFragment.getView().findViewById(R.id.save);
if (!btnSave.isEnabled())
btnSave.setEnabled(true);
EditText etXm = studentRegFragment.getView().findViewById(R.id.xm);
if (!etXm.isEnabled())
etXm.setEnabled(true);
etXm.requestFocus();
}
});
}
@Override
public void onSaveStudent(Student student) {
String info = "最近注册学生的信息:\n学号:" + student.getXh() + "\n姓名:" + student.getXm() +"\n性别:" + student.getXb();
StudentInfoFragment studentInfoFragment = (StudentInfoFragment) fragmentManager.findFragmentByTag("student_info");
TextView tvInfo = studentInfoFragment.getView().findViewById(R.id.tv_info);
tvInfo.setText(info);
stuList.add(student);
MyAdapter myAdapter = new MyAdapter(MainActivity.this, stuList);
ListView lvStu = fragmentManager.findFragmentByTag("student_list").getView().findViewById(R.id.lv_stu);
lvStu.setAdapter(myAdapter);
etXh.setEnabled(true);
etXh.setText("");
btnLogin.setEnabled(true);
btnReg.setEnabled(true);
}
}
|
package programmers;
public class IsItPrimeNumber {
public static void main(String[] args) {
// System.out.println(solution(new int[]{1,2,3,4}));
System.out.println(solution(new int[]{1,2,7,6,4}));
}
public static int solution(int[] nums) {
int answer = 0;
for(int i = 0; i<nums.length; i++){
for(int j = i; j<nums.length; j++){
if(i!=j){
for(int z = j; z<nums.length; z++){
if(i!=z && j!=z){
int number = nums[i] + nums[j] + nums[z];
if(isPrime(number)){
answer++;
}
}
}
}
}
}
return answer;
}
public static boolean isPrime(int num){
boolean value = true;
for(int i = 2; i<num; i++){
if(num%i==0){
value = false;
break;
}
}
return value;
}
}
|
package app.davecstillo.com.schoolapp;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.gson.JsonElement;
import app.davecstillo.com.schoolapp.Content.alumnosContent;
import app.davecstillo.com.schoolapp.Content.reportContent;
import app.davecstillo.com.schoolapp.dummy.DummyContent;
import app.davecstillo.com.schoolapp.dummy.DummyContent.DummyItem;
import java.util.List;
/**
* A fragment representing a list of Items.
* <p/>
* Activities containing this fragment MUST implement the {@link OnListFragmentInteractionListener}
* interface.
*/
public class reportfragment extends BaseFragment {
// TODO: Customize parameter argument names
private static final String ARG_COLUMN_COUNT = "column-count";
// TODO: Customize parameters
private int mColumnCount = 1;
private OnListFragmentInteractionListener mListener;
private alumnosContent.alumno alumno;
private reportContent content = new reportContent();
private ProgressDialog progressBar;
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public reportfragment() {
}
// TODO: Customize parameter initialization
@SuppressWarnings("unused")
public static reportfragment newInstance(int columnCount) {
reportfragment fragment = new reportfragment();
Bundle args = new Bundle();
args.putInt(ARG_COLUMN_COUNT, columnCount);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_report_list, container, false);
progressBar = new ProgressDialog(getContext());
progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressBar.setIndeterminate(true);
progressBar.setCancelable(false);
progressBar.setMessage("Cargando....");
progressBar.show();
// Set the adapter
if (view instanceof RecyclerView) {
Context context = view.getContext();
RecyclerView recyclerView = (RecyclerView) view;
if (mColumnCount <= 1) {
recyclerView.setLayoutManager(new LinearLayoutManager(context));
} else {
recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
}
StringBuilder url = new StringBuilder("reportados.php?codAlm=");
url.append(alumno.codigoAlumno);
content.cleanList();
callList(url.toString(), recyclerView);
}
return view;
}
public void callList(String path, RecyclerView recyclerView){
new BackgroundTask<JsonElement>(()-> httpHandler.instance.getJson(path), (json, exception)->{
if(exception!=null){
}
if(json!=null){
if(json.getAsJsonObject().get("Reporte_Alumno")!=null){
Toast toast = Toast.makeText(getContext(), "No hay notas disponibles", Toast.LENGTH_LONG);
toast.show();
progressBar.hide();
}else {
for (JsonElement res : json.getAsJsonObject().get("Reporte").getAsJsonArray()) {
int ID;
String Causal, Descripcion, Fecha;
JsonElement elm;
elm = res.getAsJsonObject().get("ID");ID = elm.getAsInt();
elm = res.getAsJsonObject().get("Causal");Causal = elm.getAsString();
elm = res.getAsJsonObject().get("Descripcion");Descripcion = elm.getAsString();
elm = res.getAsJsonObject().get("Fecha_reporte");Fecha = elm.getAsString();
Log.d("RES","Reportes result: " + res.toString());
content.addItem(content.createReporte(ID,Causal,Descripcion, Fecha));
}
onInfoFetched(content, recyclerView);
}
}
}).execute();
}
public void onInfoFetched(reportContent contenido, RecyclerView recyclerView){
progressBar.hide();
recyclerView.setAdapter(new reportItemRecyclerViewAdapter(contenido.ITEM, mListener));
}
public void setAlumno(alumnosContent.alumno alumno){
this.alumno = alumno;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnListFragmentInteractionListener) {
mListener = (OnListFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnListFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnListFragmentInteractionListener {
// TODO: Update argument type and name
void onListFragmentInteraction(reportContent.reporte item);
}
}
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.regex.Pattern;
public class NewLoader {
public static void main(String[] args) {
// lesson 4.5.1
String text = "Вася заработал 5000 рублей, Петя - 7563 рубля, а Маша - 30000 рублей";
String[] words = text.trim().split("\\s+");
// Pattern pattern = Pattern.compile("[0-9]+");
int sum = 0;
for (String word : words) {
if (Pattern.matches("[0-9]+", word)) {
sum += Integer.parseInt(word);
}
}
System.out.println(text);
System.out.println("Lesson 4.5.1 v1.0");
System.out.println("Общий зароботок: " + sum);
// Lesson 4.5.1
text = text.trim().replaceAll("[^0-9[\\s]]", "").trim();
String[] salaries = text.split("\\s+");
int sumSalaries = 0;
for (String salary : salaries
) {
sumSalaries += Integer.parseInt(salary);
}
System.out.println("Lesson 4.5.1 v2.0");
System.out.println("Общий зароботок друзей составил: " + sumSalaries);
// Lesson 4.5.2
String tragedy;
try {
// Path workingDirectory = Paths.get("").toAbsolutePath();
String root = System.getProperty("user.dir");
String sDirSeparator = System.getProperty("file.separator");
byte[] bytes = Files.readAllBytes(Paths.get(root + sDirSeparator + "04_NumbersStringsAndDates" + sDirSeparator +
"StringExperiments" + sDirSeparator + "src" + sDirSeparator + "shakespeare.txt"));
tragedy = new String(bytes);
} catch (IOException e) {
tragedy = "Romeo and Juliet William Shakespeare Romeo and Juliet is the world's most " +
"famous drama of tragic young love. Defying the feud which divides their families, " +
"Romeo and Juliet enjoy the fleeting rapture of courtship, marriage and sexual fulfillment; " +
"but a combination of old animosities and new coincidences brings them to suicidal deaths. " +
"This play offers a rich mixture of romantic lyricism, bawdy comedy, intimate harmony and " +
"sudden violence. Long successful in the theater, it has also generated numerous operas, " +
"ballets and films; and these have helped to make Romeo and Juliet perennially topical " +
"ROMEO AND JULIET by WILLIAM SHAKESPEARE";
}
String[] newWords = tragedy.replaceAll("[^\\s\\w]", "").trim().split("\\s+");
for (int i = 0; i < 20; i++) {
System.out.println(newWords[i]);
}
System.out.println("Lesson 4.5.2");
System.out.println("Выведено 20 слов из " + newWords.length);
// lesson 4.5.3
System.out.println("Введите данные в формате - Фамилия Имя Отчество");
String fio = "";
BufferedReader reader = (new BufferedReader(new InputStreamReader(System.in)));
try {
fio = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
String[] fullName = fio.trim().split("\\s+");
if (fullName.length == 3) {
System.out.printf("Фамилия: " + "%s" + System.lineSeparator() + "Имя: " + "%s" + System.lineSeparator()
+ "Отчество: " + "%s" + System.lineSeparator(), fullName[0], fullName[1], fullName[2]);
} else {
System.out.println("Неверный формат");
}
// lesson 4.5.4
System.out.println("Введите телефон в желательно в верном формате - 10 или 11 цифр");
String phone = "";
try {
phone = reader.readLine();
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
phone = phone.trim().replaceAll("[^0-9]", "").trim();
if (phone.length() > 11 || phone.length() < 10) {
System.out.println("Неверный формат");
} else if (phone.length() == 10) {
System.out.println("7" + phone);
} else {
if (phone.startsWith("8")) {
System.out.println("7" + phone.substring(1));
} else if (phone.startsWith("7")) {
System.out.println(phone);
} else {
System.out.println("Неверный формат");
}
}
// lesson 4.5.5
String safe = searchAndReplaceDiamonds("Номер кредитной карты <4008 1234 5678> 8912", "***");
System.out.println(safe);
String safe1 = searchAndReplaceDiamonds("Номер кредитной карты <4008 1234 5678>>> 8912", "***");
System.out.println(safe1);
String safe2 = searchAndReplaceDiamonds2("Номер кредитной карты <4008 1234 5678> 8912", "***");
System.out.println(safe2);
String s = "<hbt<<wrhb>tw4hbtw4 <HBT> 4hgw4h4w <> w4hw4h4wh <hbtwc>>wechdt svcwvcwe<1242532>mm<udkm";
System.out.println(s);
System.out.println(searchAndReplaceDiamonds(s, "!!!"));
System.out.println(searchAndReplaceDiamonds2(s, "!!!"));
}
// Настроен проглатывать повторы кавычек
static String searchAndReplaceDiamonds(String text, String placeholder) {
return text.replaceAll("<.*?>+", placeholder);
}
// Есть мнение, что RegEx это плохо
static String searchAndReplaceDiamonds2(String text, String placeholder) {
text = text.trim().replaceAll("<+", "<").replaceAll(">+", ">");
StringBuilder result = new StringBuilder();
int count = -1;
boolean isGood = true;
char ch;
for (int i = 0; i < text.length(); i++) {
ch = text.charAt(i);
if (isGood && ch != 60) {
result.append(ch);
} else if (ch == 60) {
count = i;
isGood = false;
} else if (ch == 62) {
result.append(placeholder);
isGood = true;
}
}
if (!isGood) {
result.append(text.substring(count));
}
return result.toString();
}
}
|
package LightProcessing.common.item;
import LightProcessing.common.lib.*;
import cpw.mods.fml.client.registry.RenderingRegistry;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.init.Blocks;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.EnumRarity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.world.ChunkCoordIntPair;
import net.minecraft.world.EnumSkyBlock;
import net.minecraft.world.World;
import net.minecraft.world.biome.WorldChunkManager;
import net.minecraftforge.event.world.ChunkWatchEvent;
public class ItemLightBall extends Item {
public ItemLightBall() {
super();
this.setUnlocalizedName("LightBall");
this.setCreativeTab(ItemTab.itemTab);
}
@Override
public boolean hasEffect(ItemStack par1ItemStack) {
return true;
}
@Override
@SideOnly(Side.CLIENT)
public EnumRarity getRarity(ItemStack par1ItemStack) {
return EnumRarity.epic;
}
@SideOnly(Side.CLIENT)
public void registerBlockIcons(IIconRegister iconRegister) {
itemIcon = iconRegister.registerIcon(Methods.textureName(this.getUnlocalizedName()));
}
public boolean onItemUse(ItemStack ItemStack, EntityPlayer Player, World world, int par4, int par5, int par6, int par7, float par8, float par9, float par10) {
if(Methods.useItem(Player, IDRef.LIGHT_BALL_ID)) {
if (world.getBlock(par4, par5, par6) != Blocks.air) {
world.setLightValue(EnumSkyBlock.Block, par4 + 1, par5, par6, 15);
world.setLightValue(EnumSkyBlock.Block, par4 - 1, par5, par6, 15);
world.setLightValue(EnumSkyBlock.Block, par4, par5 + 1, par6, 15);
world.setLightValue(EnumSkyBlock.Block, par4, par5 - 1, par6, 15);
world.setLightValue(EnumSkyBlock.Block, par4, par5, par6 + 1, 15);
world.setLightValue(EnumSkyBlock.Block, par4, par5, par6 - 1, 15);
world.setLightValue(EnumSkyBlock.Sky, par4 + 1, par5, par6, 15);
world.setLightValue(EnumSkyBlock.Sky, par4 - 1, par5, par6, 15);
world.setLightValue(EnumSkyBlock.Sky, par4, par5 + 1, par6, 15);
world.setLightValue(EnumSkyBlock.Sky, par4, par5 - 1, par6, 15);
world.setLightValue(EnumSkyBlock.Sky, par4, par5, par6 + 1, 15);
world.setLightValue(EnumSkyBlock.Sky, par4, par5, par6 - 1, 15);
return true;
}
}
return false;
}
}
|
package com.cartshare.Orders.controller;
import com.cartshare.User.dao.UserDAO;
import com.cartshare.models.*;
import com.cartshare.utils.MailController;
import com.cartshare.utils.OrderDetails;
import java.util.*;
import javax.validation.Valid;
import com.cartshare.RequestBody.*;
import com.cartshare.Store.dao.StoreDAO;
import com.cartshare.Orders.dao.OrdersDAO;
import com.cartshare.Pool.dao.PoolDAO;
import com.cartshare.Product.dao.ProductDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.*;
@CrossOrigin(origins = "*", allowedHeaders = "*")
@RestController
@RequestMapping("/orders")
public class OrdersController {
@Autowired
OrdersDAO ordersDAO;
@Autowired
UserDAO userDAO;
@Autowired
ProductDAO productDAO;
@Autowired
StoreDAO storeDAO;
@Autowired
PoolDAO poolDAO;
@Autowired
MailController mc;
@PostMapping(value = "/add/cart", produces = { "application/json", "application/xml" })
public ResponseEntity<?> addProductToCart(@RequestBody OrderRequest orderRequest) {
try {
Long userId = null;
try {
userId = Long.parseLong(orderRequest.getUserId());
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid user ID");
}
Long storeId = null;
try {
storeId = Long.parseLong(orderRequest.getStoreId());
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid store ID");
}
Long productId = null;
try {
productId = Long.parseLong(orderRequest.getProductId());
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid product ID");
}
Product product = productDAO.findById(productId);
if (product == null || product.getStore().getId() != storeId) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Product does not belong to the store");
} else if (product.isActive() == false) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Product has been deleted");
} else if (product.getStore().isActive() == false) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Store has been deleted");
}
Long quantity = null;
try {
quantity = Long.parseLong(orderRequest.getQuantity());
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid quantity");
}
if (quantity < 1) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid quantity");
}
User user = userDAO.findById(userId);
if (user == null) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid user ID");
}
Pool pool = null;
for (PoolMembers temp : user.getPoolMembers()) {
if (temp.getStatus().equals("Accepted")) {
pool = temp.getPool();
}
}
if (pool == null) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("User is not part of any pools");
}
Orders order = ordersDAO.findOrdersByUserAndStatus(user, "Cart");
if (order == null) {
order = new Orders();
order.setUser(user);
order.setPool(pool);
order.setStore(storeDAO.findById(storeId));
order.setStatus("Cart");
order = ordersDAO.saveOrderDetails(order);
} else if (order.getStore().getId() != storeId) {
return ResponseEntity.status(HttpStatus.CONFLICT)
.body("Cart cannot have products from multiple stores");
}
OrderItems orderItem = ordersDAO.findOrderItemsByOrdersAndProduct(order, product);
if (orderItem == null) {
orderItem = new OrderItems(order, product, quantity);
} else {
orderItem.setQuantity(orderItem.getQuantity() + quantity);
}
return ResponseEntity.status(HttpStatus.OK).body(ordersDAO.saveOrderItem(orderItem));
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}
@GetMapping(value = "/activeStoreInCart", produces = { "application/json", "application/xml" })
public ResponseEntity<?> getactiveStoreInCart(@RequestParam(value = "userId") String reqUserId) {
try {
Long userId = null;
try {
userId = Long.parseLong(reqUserId);
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid user ID");
}
User user = userDAO.findById(userId);
if (user == null) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid user ID");
}
Orders order = ordersDAO.findOrdersByUserAndStatus(user, "Cart");
if (order == null) {
return ResponseEntity.status(HttpStatus.CONFLICT).body("User does not have an active order in cart");
}
return ResponseEntity.status(HttpStatus.OK).body(order.getStore());
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}
@GetMapping(value = "/productsInCart", produces = { "application/json", "application/xml" })
public ResponseEntity<?> getProductsInCart(@RequestParam(value = "userId") String reqUserId) {
try {
Long userId = null;
try {
userId = Long.parseLong(reqUserId);
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid user ID");
}
User user = userDAO.findById(userId);
if (user == null) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid user ID");
}
Orders order = ordersDAO.findOrdersByUserAndStatus(user, "Cart");
if (order == null) {
return ResponseEntity.status(HttpStatus.CONFLICT).body("User does not have an active order in cart");
}
return ResponseEntity.status(HttpStatus.OK).body(order.getOrderItems());
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}
@GetMapping(value = "/pickUp/associatedOrders/{id}", produces = { "application/json", "application/xml" })
public ResponseEntity<?> pickUpAssociatedOrder(@Valid @PathVariable(name = "id") String id) {
try {
long l;
try {
l = Long.parseLong(id);
} catch (NumberFormatException e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid order ID");
}
Orders o = ordersDAO.findOrdersById(l);
List<Orders> list = ordersDAO.findAssociatedOrders(o);
if (list == null || list.size() == 0) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body("There are no associated orders for this order");
}
return ResponseEntity.status(HttpStatus.OK).body(list);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}
@GetMapping(value = "/pastOrders/{userId}", produces = { "application/json", "application/xml" })
public ResponseEntity<?> getPastOrdersOfUser(@Valid @PathVariable(name = "userId") String userId) {
try {
Long l;
try {
l = Long.parseLong(userId);
} catch (NumberFormatException e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid user id");
}
User u = userDAO.findById(l);
if (u == null) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("No user with given ID");
}
List<Orders> list = ordersDAO.findOrdersByUser(u);
if (list == null || list.size() == 0) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("No past orders");
}
List<Set<OrderItems>> listOfProductsInOrders = new ArrayList<>();
for (Orders order : list) {
listOfProductsInOrders.add(order.getOrderItems());
}
return ResponseEntity.status(HttpStatus.OK).body(listOfProductsInOrders);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}
@GetMapping(value = "/pickUp/{orderId}", produces = { "application/json", "application/xml" })
public ResponseEntity<?> pickUpOrder(@Valid @PathVariable(name = "orderId") String orderId) {
try {
ordersDAO.updateOrderStatus();
Long l;
try {
l = Long.parseLong(orderId);
} catch (NumberFormatException e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid order id or user id");
}
Orders order = ordersDAO.findOrdersById(l);
User user = order.getUser();
if (order == null || user == null) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body("order or user with the provided Id doesn't exist");
}
if (order.getStatus().compareTo("Confirmed") != 0) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body("This order and all it's associated orders have already been picked up");
}
order.setStatus("Delivered");
order.setFulfilled(true);
ordersDAO.saveOrderDetails(order);
mc.send(user.getEmail(), "Order #" + order.getId() + " picked up",
"You picked up your cartshare order #" + order.getId());
List<Orders> associated = ordersDAO.findAssociatedOrders(order); //
OrderDetails od = new OrderDetails();
String message = "";
if (associated != null) {
for (Orders o : associated) {
User u = o.getUser();
o.setPickupPooler(user);
o.setStatus("PickedUp");
o.setFulfilled(true);
ordersDAO.saveOrderDetails(o);
Address a = u.getAddress();
message += "<h1>User " + u.getNickName() + "'s order:</h1></br>Address: " + a.getStreet() + ", "
+ a.getCity() + ", " + a.getState() + ", " + a.getZipcode() + "</br>Order details: </br>"
+ od.GenerateProductTableWithoutPrice(o.getOrderItems()) + "</br></br>";
// hs.add(o.getUser());
mc.send(u.getEmail(), "Order #" + o.getId() + " picked up",
"Your cartshare order #" + o.getId() + " has been picked up by " + user.getScreenName());
}
mc.sendHTML(user.getEmail(), "Delivery Instructions for the associated orders", message);
return ResponseEntity.status(HttpStatus.OK).body("Associated");
}
return ResponseEntity.status(HttpStatus.OK).body("NoAssociated");
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}
@GetMapping(value = "/deliver/{userId}", produces = { "application/json", "application/xml" })
public ResponseEntity<?> ordersToDeliver(@Valid @PathVariable(name = "userId") String userId) {
try {
long l;
try {
l = Long.parseLong(userId);
} catch (NumberFormatException e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid user id");
}
User user = userDAO.findById(l);
if (user == null) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("User with ID doesn't exist");
}
List<Orders> list = ordersDAO.findOrdersToBeDeliveredByUser(user);
if (list == null || list.size() == 0) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("No orders to be delivered");
}
List<Set<OrderItems>> listOfProductsInOrders = new ArrayList<>();
for (Orders order : list) {
listOfProductsInOrders.add(order.getOrderItems());
}
return ResponseEntity.status(HttpStatus.OK).body(listOfProductsInOrders);
// return ResponseEntity.status(HttpStatus.OK).body(list);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}
@PutMapping(value = "/deliver/{id}", produces = { "application/json", "application/xml" })
public synchronized ResponseEntity<?> deliverOrder(@Valid @PathVariable(name = "id") String id) {
try {
Long l;
try {
l = Long.parseLong(id);
} catch (NumberFormatException e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid Order ID");
}
Orders order = ordersDAO.findOrdersById(l);
order.setStatus("Delivered");
ordersDAO.saveOrderDetails(order);
User u = order.getUser();
u.setContributionCredit(u.getContributionCredit() - 1);
userDAO.save(u);
User u1 = order.getPickupPooler();
u1.setContributionCredit(u1.getContributionCredit() + 1);
userDAO.save(u1);
String subject = "Order #" + order.getId() + " has been delivered";
String body = "Your order #" + order.getId() + " has been delivered by: "
+ order.getPickupPooler().getScreenName();
mc.send(u.getEmail(), subject, body);
return ResponseEntity.status(HttpStatus.OK).body("Order status set to delivered");
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}
@PutMapping(value = "/notDelivered/{id}", produces = { "application/json", "application/xml" })
public ResponseEntity<?> markAsNotDelivered(@Valid @PathVariable(name = "id") String id) {
try {
Long l;
try {
l = Long.parseLong(id);
} catch (NumberFormatException e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid Order ID");
}
Orders o = ordersDAO.findOrdersById(l);
if (o == null) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid Order ID");
}
User u = o.getUser();
u.setContributionCredit(u.getContributionCredit() + 1);
userDAO.save(u);
User u1 = o.getPickupPooler();
u1.setContributionCredit(u1.getContributionCredit() - 1);
userDAO.save(u1);
o.setStatus("NotDelivered");
ordersDAO.saveOrderDetails(o);
mc.send(o.getPickupPooler().getEmail(), "Update about one of the orders you delivered",
"User " + u.getScreenName() + " has marked order # " + o.getId() + " as Not Delivered");
return ResponseEntity.status(HttpStatus.OK).body("Order successfully marked as Not Delivered");
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}
@PostMapping(value = "/update/cart", produces = { "application/json", "application/xml" })
public ResponseEntity<?> updateQuantityOfProductInCart(@RequestBody OrderRequest orderRequest) {
try {
Long userId = null;
try {
userId = Long.parseLong(orderRequest.getUserId());
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid user ID");
}
Long quantity = null;
try {
quantity = Long.parseLong(orderRequest.getQuantity());
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid quantity");
}
if (quantity < 1) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid quantity");
}
Long orderItemId = null;
try {
orderItemId = Long.parseLong(orderRequest.getOrderItemId());
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid order item ID");
}
User user = userDAO.findById(userId);
if (user == null) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid user ID");
}
Orders order = ordersDAO.findOrdersByUserAndStatus(user, "Cart");
if (order == null) {
return ResponseEntity.status(HttpStatus.CONFLICT).body("User does not have an active order in cart");
}
OrderItems orderItem = ordersDAO.findOrderItemsById(orderItemId);
if (orderItem == null) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Product does not exist in order");
} else if (orderItem.getProduct().isActive() == false
|| orderItem.getProduct().getStore().isActive() == false) {
return ResponseEntity.status(HttpStatus.CONFLICT).body("Product or store has been deleted");
}
orderItem.setQuantity(quantity);
return ResponseEntity.status(HttpStatus.OK).body(ordersDAO.saveOrderItem(orderItem));
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}
@DeleteMapping(value = "/removeProductFromCart", produces = { "application/json", "application/xml" })
public ResponseEntity<?> removeProductFromCart(@RequestParam(value = "userId") String reqUserId,
@RequestParam(value = "orderItemId") String reqOrderItemId) {
try {
Long userId = null;
try {
userId = Long.parseLong(reqUserId);
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid user ID");
}
Long orderItemId = null;
try {
orderItemId = Long.parseLong(reqOrderItemId);
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid order item ID");
}
User user = userDAO.findById(userId);
if (user == null) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid user ID");
}
Orders order = ordersDAO.findOrdersByUserAndStatus(user, "Cart");
if (order == null) {
return ResponseEntity.status(HttpStatus.CONFLICT).body("User does not have an active order in cart");
}
OrderItems orderItem = ordersDAO.findOrderItemsById(orderItemId);
if (orderItem == null) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Product does not exist in order");
}
ordersDAO.removeProductFromCart(orderItemId);
List<OrderItems> itemsPresentInOrder = ordersDAO.findProductsInAOrder(order);
if (itemsPresentInOrder.size() == 0) {
ordersDAO.removeOrderFromCart(order.getId());
}
return ResponseEntity.status(HttpStatus.OK).body("Product removed from cart");
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}
@PostMapping(value = "/confirmOrder", produces = { "application/json", "application/xml" })
public ResponseEntity<?> confirmOrder(@RequestBody OrderRequest orderRequest) {
try {
Long userId = null;
try {
userId = Long.parseLong(orderRequest.getUserId());
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid user ID");
}
User user = userDAO.findById(userId);
if (user == null) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid user ID");
}
Orders order = ordersDAO.findOrdersByUserAndStatus(user, "Cart");
if (order == null) {
return ResponseEntity.status(HttpStatus.CONFLICT).body("User does not have an active order in cart");
} else if (order.getStore().isActive() == false) {
return ResponseEntity.status(HttpStatus.CONFLICT)
.body("Could not place order. Store has been deleted!");
}
for (OrderItems orderItem : order.getOrderItems()) {
if (orderItem.getProduct().isActive() == false) {
return ResponseEntity.status(HttpStatus.CONFLICT)
.body("Could not place order. Product " + orderItem.getProduct().getProductName()
+ " with SKU " + orderItem.getProduct().getSku() + " has been deleted!");
}
}
for (OrderItems orderItem : order.getOrderItems()) {
orderItem.setProductName(orderItem.getProduct().getProductName());
orderItem.setProductPrice(orderItem.getProduct().getPrice());
orderItem.setProductImage(orderItem.getProduct().getImageURL());
orderItem.setProductBrand(orderItem.getProduct().getBrand());
orderItem.setProductUnit(orderItem.getProduct().getUnit());
ordersDAO.saveOrderItem(orderItem);
}
if (orderRequest.getSelfPickup() == true) {
order.setPickupPooler(user);
order.setStatus("Confirmed");
} else {
order.setStatus("Ordered");
}
order.setTimestamp(new Date());
order = ordersDAO.saveOrderDetails(order);
OrderDetails od = new OrderDetails();
String heading = "Your order has been placed (#" + order.getId() + ")";
String message = od.GenerateProductTableWithPrice(order.getOrderItems());
// System.out.println(message);
mc.sendHTML(user.getEmail(), heading, message);
return ResponseEntity.status(HttpStatus.OK).body(order);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}
@GetMapping(value = "/pendingInPool", produces = { "application/json", "application/xml" })
public ResponseEntity<?> getPendingOrdersInPool(@RequestParam(value = "userId") String reqUserId,
@RequestParam(value = "storeId") String reqStoreId) {
try {
Long userId = null;
try {
userId = Long.parseLong(reqUserId);
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid user ID");
}
User user = userDAO.findById(userId);
if (user == null) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid user ID");
}
Long storeId = null;
try {
storeId = Long.parseLong(reqStoreId);
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid store ID");
}
Store store = storeDAO.findById(storeId);
if (store == null) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid store ID");
}
Pool pool = null;
for (PoolMembers temp : user.getPoolMembers()) {
if (temp.getStatus().equals("Accepted")) {
pool = temp.getPool();
}
}
if (pool == null) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("User is not part of any pools");
}
List<Orders> listOfOrders = ordersDAO.findOrdersWithNoPickup(pool, "Ordered", null, store);
Integer count = 0;
List<Set<OrderItems>> listOfProductsInOrders = new ArrayList<>();
for (Orders order : listOfOrders) {
if (order.getUser().getId() != userId) {
listOfProductsInOrders.add(order.getOrderItems());
count++;
if (count == 10) {
break;
}
}
}
return ResponseEntity.status(HttpStatus.OK).body(listOfProductsInOrders);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}
@PostMapping(value = "/pickupOtherOrders", produces = { "application/json", "application/xml" })
public ResponseEntity<?> pickupOtherOrders(@RequestBody OrderRequest orderRequest) {
try {
Long userId = null;
try {
userId = Long.parseLong(orderRequest.getUserId());
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid user ID");
}
User user = userDAO.findById(userId);
if (user == null) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid user ID");
}
Long storeId = null;
try {
storeId = Long.parseLong(orderRequest.getStoreId());
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid store ID");
}
Store store = storeDAO.findById(storeId);
if (store == null) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid store ID");
}
Long orderId = null;
try {
orderId = Long.parseLong(orderRequest.getOrderId());
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid order ID");
}
Orders originalOrder = ordersDAO.findOrdersById(orderId);
Integer numberOfOrders;
try {
numberOfOrders = Integer.parseInt(orderRequest.getNumberOfOrders());
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid number of orders");
}
if (numberOfOrders < 1 || numberOfOrders > 10) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid number of orders");
}
OrderDetails od = new OrderDetails();
Pool pool = null;
for (PoolMembers temp : user.getPoolMembers()) {
if (temp.getStatus().equals("Accepted")) {
pool = temp.getPool();
}
}
if (pool == null) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("User is not part of any pools");
}
List<Orders> listOfOrders = ordersDAO.findOrdersWithNoPickup(pool, "Ordered", null, store);
int count = 0;
String pickupUserMessage = "";
for (Orders order : listOfOrders) {
if (order.getUser().getId() != userId) {
pickupUserMessage += "<h2>Order " + (count + 1) + " details</h2>";
pickupUserMessage += od.GenerateProductTableWithoutPrice(order.getOrderItems());
String orderedUserHeading = "A fellow pooler will be picking up your order (# " + order.getId()
+ ")";
String orderedUserMessage = od.GenerateProductTableWithPrice(order.getOrderItems());
mc.sendHTML(order.getUser().getEmail(), orderedUserHeading, orderedUserMessage);
order.setStatus("Confirmed");
order.setPickupPooler(user);
ordersDAO.saveOrderDetails(order);
AssociatedOrders associatedOrders = new AssociatedOrders(originalOrder, order);
ordersDAO.saveAssociatedOrders(associatedOrders);
count++;
if (count == numberOfOrders) {
break;
}
}
}
String pickupUserHeading = "You have requested to pick up " + count + " orders";
mc.sendHTML(user.getEmail(), pickupUserHeading, pickupUserMessage);
return ResponseEntity.status(HttpStatus.OK).body(pickupUserHeading);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}
@GetMapping(value = "/ordersToPickup", produces = { "application/json", "application/xml" })
public ResponseEntity<?> getOrdersToPickup(@RequestParam(value = "userId", required = false) String reqUserId) {
try {
if (reqUserId == null) {
List<Orders> listOfOrders = ordersDAO.findAllOrdersToBePickedup();
List<Set<OrderItems>> listOfProductsInOrders = new ArrayList<>();
if (listOfOrders == null) {
return ResponseEntity.status(HttpStatus.OK).body(listOfProductsInOrders);
}
for (Orders order : listOfOrders) {
listOfProductsInOrders.add(order.getOrderItems());
}
return ResponseEntity.status(HttpStatus.OK).body(listOfProductsInOrders);
}
Long userId = null;
try {
userId = Long.parseLong(reqUserId);
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid user ID");
}
User user = userDAO.findById(userId);
if (user == null) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid user ID");
}
List<Orders> listOfOrders = ordersDAO.findOrdersToBePickedUpByUser(user);
List<Set<OrderItems>> listOfProductsInOrders = new ArrayList<>();
if (listOfOrders == null) {
return ResponseEntity.status(HttpStatus.OK).body(listOfProductsInOrders);
}
for (Orders order : listOfOrders) {
listOfProductsInOrders.add(order.getOrderItems());
}
return ResponseEntity.status(HttpStatus.OK).body(listOfProductsInOrders);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}
@GetMapping(value = "/associatedOrders", produces = { "application/json", "application/xml" })
public ResponseEntity<?> associatedOrdersDetails(@RequestParam("orderId") String reqOrderId) {
try {
Long orderId = null;
try {
orderId = Long.parseLong(reqOrderId);
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid order ID");
}
Orders order = ordersDAO.findOrdersById(orderId);
if (order == null) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid order ID");
}
List<Orders> listOfOrders = ordersDAO.findAssociatedOrders(order);
List<Set<OrderItems>> listOfProductsInOrders = new ArrayList<>();
if (listOfOrders == null) {
return ResponseEntity.status(HttpStatus.OK).body(listOfProductsInOrders);
}
for (Orders orderObj : listOfOrders) {
listOfProductsInOrders.add(orderObj.getOrderItems());
}
return ResponseEntity.status(HttpStatus.OK).body(listOfProductsInOrders);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}
}
|
package com.tencent.mm.plugin.voip.widget;
import android.content.Intent;
import com.tencent.mm.R;
import com.tencent.mm.plugin.voip.b.b;
import com.tencent.mm.plugin.voip.ui.a;
import com.tencent.mm.plugin.voip.ui.h;
import com.tencent.mm.sdk.platformtools.ad;
class b$5 implements a {
final /* synthetic */ b oWh;
b$5(b bVar) {
this.oWh = bVar;
}
public final boolean aWU() {
if (b.yW(b.e(this.oWh)) || b.yU(b.e(this.oWh))) {
return true;
}
return false;
}
public final void a(Intent intent, h hVar) {
if (intent.getBooleanExtra("Voip_Is_Talking", false)) {
hVar.OI(this.oWh.bMq());
} else {
hVar.OI(ad.getContext().getString(R.l.multitalk_waiting_wording));
}
}
}
|
package com.zhiyou.coprocessor;
import java.io.IOException;
import java.util.List;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Durability;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.coprocessor.BaseRegionObserver;
import org.apache.hadoop.hbase.coprocessor.ObserverContext;
import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
import org.apache.hadoop.hbase.regionserver.wal.WALEdit;
import org.apache.hadoop.hbase.util.Bytes;
//observer 的coprocessor 自动更新二级索引
//create 'order_item', 'i'
//create 'order_item_subtotal_index','r'
//协处理器 order_item, 索引自动更新到 order_item_subtotal_index
public class SecondaryIndexAutoUpdate extends BaseRegionObserver {
//索引表数据添加
@Override
public void prePut(ObserverContext<RegionCoprocessorEnvironment> e, Put put, WALEdit edit, Durability durability)
throws IOException {
List<Cell> subtotalCell =
put.get(Bytes.toBytes("i"), Bytes.toBytes("subtotal"));
if(subtotalCell != null && subtotalCell.size() > 0){
RegionCoprocessorEnvironment environment = e.getEnvironment();
Configuration configuration = environment.getConfiguration();
//与hbase建立连接
Connection connection =
ConnectionFactory.createConnection(configuration);
Table table =
connection.getTable(
TableName.valueOf(
"bd14:order_item_subtotal_index"));
//put对象
Put indexPut =
new Put(CellUtil.cloneValue(subtotalCell.get(0)));
indexPut.addColumn(Bytes.toBytes("r")
, put.getRow()
, null);
table.put(indexPut);
table.close();
}
}
}
|
/*
* 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 lru;
/**
*
* @author arles
*/
public class Lru {
private int [] array;
private int indexDead = 0;
private int size;
private int counter = 0;
private int miss;
private int hits;
public Lru(int size) {
this.size = size;
this.array = new int [size];
}
public int[] getArray() {
return array;
}
public int getIndexDead() {
return indexDead;
}
public int getSize() {
return size;
}
public int getMiss() {
return miss;
}
public int getHits() {
return hits;
}
public void setMiss(int miss) {
this.miss = miss;
}
public void setHits(int hits) {
this.hits = hits;
}
public void setArray(int[] array) {
this.array = array;
}
public void setIndexDead(int indexDead) {
this.indexDead = indexDead;
}
public void setSize(int size) {
this.size = size;
}
// Metodos de administracion
public void check (int x) {
if (this.counter == 0 ) {
this.array[counter] = x;
this.counter++;
this.miss++;
} else {
boolean exists = false;
for (int i = 0; i < this.array.length; i++) {
if (this.array[i] == x) {
exists = true;
break;
}
}
if (!exists) {
if (this.counter < size) {
this.array[this.counter] = x;
this.counter++;
this.miss++;
} else {
this.array[this.indexDead] = x;
this.indexDead = (this.indexDead + 1) % size;
this.miss++;
}
} else {
this.indexDead = (this.indexDead + 1) % size;
this.hits++;
}
}
}
public String printArray () {
String string = "[";
for (int i = 0; i < this.size; i++) {
if ( i == this.size - 1) {
string += this.array[i] + "]\n";
} else {
string += this.array[i] + ",";
}
}
return string;
}
}
|
package com.example.nadir.buddycheckalarm;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
import com.firebase.client.AuthData;
import com.firebase.client.ChildEventListener;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.GenericTypeIndicator;
import com.firebase.client.Query;
import com.firebase.client.ValueEventListener;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
/**
* Created by Nadir on 4/18/2016.
*/
public class UserProfileManager {
private static UserProfileManager instance = new UserProfileManager();
private Context context;
public static final Firebase firebaseRef = new Firebase(Globals.FIREBASE_REF);
private UserProfile currentUser;
private Firebase userRef;
private static final String TAG = "UserProfileManager";
public void setContext(Context context) {
this.context = context;
}
public static UserProfileManager getInstance() {
return instance;
}
public Firebase getUserRef() {
return userRef;
}
public UserProfile getCurrentUser() {
return currentUser;
}
public void loginOrRegister(final String username, final String password) {
Query queryRef = firebaseRef.child("users").orderByChild("username").equalTo(username);
queryRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
if (!snapshot.exists()) {
createUserAccountAndLogin(username, password);
}
else {
login(username, password);
}
}
@Override
public void onCancelled(FirebaseError firebaseError) {
System.out.println("The read failed: " + firebaseError.getMessage());
}
});
}
public void createUserAccountAndLogin(final String username, final String password) {
firebaseRef.createUser(username, password, new Firebase.ValueResultHandler<Map<String, Object>>() {
@Override
public void onSuccess(Map<String, Object> result) {
System.out.println("Successfully created user account with uid: " + result.get("uid"));
//add new user entry to firebase
userRef = firebaseRef.child("users").child((String) result.get("uid"));
Map<String, Object> userData = new HashMap<String, Object>();
userData.put("username", username);
userRef.updateChildren(userData);
//log in newly created user
login(username, password);
}
@Override
public void onError(FirebaseError firebaseError) {
System.out.println("Account Creation Error: " + firebaseError.getMessage());
}
});
}
public void login(final String username, final String password) {
firebaseRef.authWithPassword(username, password, new Firebase.AuthResultHandler() {
@Override
public void onAuthenticated(AuthData authData) {
System.out.println("User ID: " + authData.getUid() + ", Provider: " + authData.getProvider());
//set current user
currentUser = new UserProfile();
currentUser.uid = authData.getUid();
currentUser.email = username;
userRef = firebaseRef.child("users").child(currentUser.uid);
registerGcm();
}
@Override
public void onAuthenticationError(FirebaseError firebaseError) {
System.out.println(firebaseError.getMessage());
}
});
}
private void registerGcm() {
// Start IntentService to register this application with GCM.
Intent intent = new Intent(context, RegistrationIntentService.class);
context.startService(intent);
}
public void test() {
//instance.addAlarm(new Alarm(new Time(12, 42, 0)));
//instance.removeAlarm("-KHJ0O_08z6zjWRZH4Jn");
userRef.child("gcmToken").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
//GenericTypeIndicator needed to read firebase data as List<String>
//GenericTypeIndicator<List<String>> t = new GenericTypeIndicator<List<String>>() {};
String token = (String) snapshot.getValue();
String userEmail = UserProfileManager.getInstance().getCurrentUser().email;
String title = "Buddy Check Alarm";
String message = "User " + userEmail + " needs help waking up!";
try {
instance.sendNotification(token, title, message);
}
catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onCancelled(FirebaseError firebaseError) {
System.out.println("The read failed: " + firebaseError.getMessage());
}
});
}
public void sendNotification(String friendToken, String title, String msg) throws JSONException {
//HttpClient httpClient = HttpClientBuilder.create().build();
HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("Authorization", "key="+Globals.GCM_API_KEY); //REST API Key
JSONObject jGcmData = new JSONObject();
jGcmData.put("to", friendToken);
JSONObject jData = new JSONObject();
jData.put("title", title);
jData.put("message", msg);
jGcmData.put("data", jData);
System.out.println(jGcmData);
new HttpPostTask(Globals.GCM_POST_ENDPOINT_URL, headers, jGcmData).execute();
}
public void logout() {
firebaseRef.unauth();
currentUser = null;
userRef = null;
}
public boolean isLoggedIn() {
return currentUser != null;
}
private void startMainActivity() {
Intent i = new Intent();
i.setClassName("com.example.nadir.buddycheckalarm", "com.example.nadir.buddycheckalarm.MainActivity");
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
public void displayToast(CharSequence text) {
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
public void addFriend(final String friendUsername) {
//NOTE: friendsList is indexed by unique friendID, so we
// need to query by username to obtain friendID
final Query queryRef = firebaseRef.child("users").orderByChild("username").equalTo(friendUsername).limitToFirst(1);
queryRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.exists()) {
CharSequence text = "Username " + friendUsername + " does not exist";
displayToast(text);
System.out.println(text);
startMainActivity();
return;
}
queryRef.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot snapshot, String previousChild) {
//key of child username = friendUsername is friend's unique user ID
final String friendID = snapshot.getKey();
//now we need to add friendID to user's friendsList
final Firebase userFriendsRef = userRef.child("friends");
final Firebase usersRef = firebaseRef.child("users");
userFriendsRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
GenericTypeIndicator<List<String>> t = new GenericTypeIndicator<List<String>>() {};
List<String> friendsList = snapshot.getValue(t);
if (friendsList == null) {
friendsList = new ArrayList<>();
}
if (!friendsList.contains(friendID)) {
friendsList.add(friendID);
userFriendsRef.setValue(friendsList);
CharSequence text = "Friend " + friendUsername + " successfully added";
displayToast(text);
System.out.println(text);
}
else {
CharSequence text = friendUsername + " alraedy in your friends list";
displayToast(text);
System.out.println(text);
}
//go back to main activity after adding friend
startMainActivity();
}
@Override
public void onCancelled(FirebaseError firebaseError) {
System.out.println(firebaseError.getMessage());
}
});
}
//need to override these functions for ChildEventListener
@Override
public void onCancelled(FirebaseError firebaseError) {
System.out.println(firebaseError.getMessage());
}
@Override
public void onChildRemoved(DataSnapshot snapshot) {}
@Override
public void onChildChanged(DataSnapshot snapshot, String str) {}
@Override
public void onChildMoved(DataSnapshot snapshot, String str) {}
});
}
@Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
public void addAlarm(final Alarm a) {
//add alarm to general alarms list, push generates unique alarmID
Firebase alarmsRef = firebaseRef.child("alarms").push();
alarmsRef.setValue(a);
final String alarmID = alarmsRef.getKey();
final Firebase userAlarmsRef = userRef.child("activeAlarms");
userAlarmsRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
//GenericTypeIndicator needed to read firebase data as List<String>
GenericTypeIndicator<List<String>> t = new GenericTypeIndicator<List<String>>() {};
List<String> alarms = snapshot.getValue(t);
if (alarms == null) {
alarms = new ArrayList<String>();
}
alarms.add(alarmID);
userAlarmsRef.setValue(alarms);
}
@Override
public void onCancelled(FirebaseError firebaseError) {
System.out.println("The read failed: " + firebaseError.getMessage());
}
});
}
public void removeAlarm(final String alarmID) {
//Remove alarmID from user activeAlarms list
final Firebase userAlarmsRef = userRef.child("activeAlarms");
userAlarmsRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
//GenericTypeIndicator needed to read firebase data as List<String>
GenericTypeIndicator<List<String>> t = new GenericTypeIndicator<List<String>>() {};
List<String> alarms = snapshot.getValue(t);
//should not be null
if (alarms == null) {
System.out.println("User alarms list empty");
return;
}
alarms.remove(alarmID);
userAlarmsRef.setValue(alarms);
}
@Override
public void onCancelled(FirebaseError firebaseError) {
System.out.println("The read failed: " + firebaseError.getMessage());
}
});
//delete alarm from general alarms list
firebaseRef.child("alarms").child(alarmID).setValue(null);
}
public static class UserProfile {
public String uid;
public String email;
}
}
|
package br.com.fiap.healthtrack.entity;
import java.util.List;
public class MenuEntity {
private Long idMenu;
private String label;
private String url;
private String descricao;
private List<PerfilMenuEntity>perfilMenu;
public Long getIdMenu() {
return idMenu;
}
public void setIdMenu(Long idMenu) {
this.idMenu = idMenu;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
/**
* @return the perfilMenu
*/
public List<PerfilMenuEntity> getPerfilMenu() {
return perfilMenu;
}
/**
* @param perfilMenu the perfilMenu to set
*/
public void setPerfilMenu(List<PerfilMenuEntity> perfilMenu) {
this.perfilMenu = perfilMenu;
}
}
|
package cn.wzvtcsoft.validator.events;
import cn.wzvtcsoft.validator.anntations.*;
import cn.wzvtcsoft.validator.anntations.ValidSelect;
import cn.wzvtcsoft.validator.core.RuleParser;
import cn.wzvtcsoft.validator.exceptions.DomainRuleCheckException;
import cn.wzvtcsoft.validator.exceptions.ValidSelectCheckException;
import org.springframework.aop.support.AopUtils;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.stereotype.Component;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* 对所有的 @SelectValid 与 @DomainRule 的实例进行检查
*/
@Component
public class RuleValidCheckEvent implements ApplicationListener<ApplicationStartedEvent> {
private static final ParameterNameDiscoverer parameterNameDiscoverer =
new LocalVariableTableParameterNameDiscoverer();
@Override
public void onApplicationEvent(ApplicationStartedEvent event) {
validSelectCheck(event);
domainRuleCheck(event);
}
/**
* 针对 @RestController 注解的类下的方法下的包含 @DomainRule 的参数进行 rule 进行检查。
* 具体检查 rule 中的属性是否与 @DomainRule 注解的对象的属性是否匹配
*
* @throws DomainRuleCheckException @DomainRule 的实例的 rule 中的 property 与注解对应的 对象不匹配
*/
private static void domainRuleCheck(ApplicationStartedEvent event) throws DomainRuleCheckException {
event.getApplicationContext()
.getBeansWithAnnotation(MutationValidated.class)
.values()
.stream()
.map(AopUtils::getTargetClass)
.map(Class::getMethods)
.flatMap(methods -> Arrays.stream(methods))
.forEach(method -> {
Parameter[] parameters = method.getParameters();
Class<?>[] parameterTypes = method.getParameterTypes();
for (int i = 0; i < parameters.length; i++) {
//找到了有 @DomainRule 注解的参数
if (parameters[i].isAnnotationPresent(DomainRule.class)) {
String rule = parameters[i].getAnnotation(DomainRule.class).value();
Class target = parameterTypes[i];
List<String> properties = RuleParser.getProperties(rule);
List<String> fields = Arrays.stream(target.getDeclaredFields())
.map(Field::getName)
.collect(Collectors.toList());
if (!fields.containsAll(properties)) {
String message = "@DomainRule 中的属性与方法参数不匹配," + "\n" +
"rule :" + rule + "\n" +
" method : " + method.toString();
throw new DomainRuleCheckException(message);
}
}
}
});
}
/**
* 针对 @Validated 注解的类下的包含 @ValidSelect 的参数方法进行 rule 进行检查。
* 具体检查 rule 中的 参数是否与 方法中的参数名匹配。
*
* @throws ValidSelectCheckException @ValidSelect 中的 rule 与 中的参数名不匹配
*/
private static void validSelectCheck(ApplicationStartedEvent event) throws ValidSelectCheckException {
Optional<Method> errorMethod = event.getApplicationContext()
.getBeansWithAnnotation(MutationValidated.class)
.values()
.stream()
.map(AopUtils::getTargetClass)
.map(Class::getMethods)
.flatMap(methods -> Arrays.stream(methods))
.filter(method -> method.isAnnotationPresent(ValidSelect.class))
.filter(method -> {
List<String> params = Arrays.asList(parameterNameDiscoverer.getParameterNames(method));
return Arrays.stream(method.getAnnotationsByType(ValidSelect.class))
.noneMatch(validSelect -> {
String rule = validSelect.value();
List<String> properties = RuleParser.getProperties(rule);
return params.containsAll(properties);
});
}).findAny();
if (errorMethod.isPresent()) {
String message = "@ValidSelect 中的参数与方法中的参数不匹配 "
+ errorMethod.get().toString();
throw new ValidSelectCheckException(message);
}
}
}
|
package com.studentmanagement.controller;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.studentmanagement.api.Course;
import com.studentmanagement.api.Student;
import com.studentmanagement.api.Teacher;
import com.studentmanagement.service.CourseService;
@Controller
public class CourseController {
@Autowired
CourseService courseService;
@GetMapping("/test")
public String test(Model model) {
courseService.loadStudentsFromCourse(1);
return "hello";
}
@GetMapping("/courses")
public String showCourses(Model model, HttpSession session) {
Teacher login = (Teacher) session.getAttribute("login");
if (login == null)
return "redirect:/";
List<Course> courseList = courseService.loadCourses();
model.addAttribute("courses", courseList);
return "courses-list";
}
@GetMapping("/coursePage")
public String coursePage(@RequestParam("courseId") int id, Model model) {
Course course = courseService.getCourse(id);
model.addAttribute("course", course);
List<Student> courseStudents = courseService.loadStudentsFromCourse(id);
model.addAttribute("courseStudents", courseStudents);
List<Student> otherStudents = courseService.loadStudentsOutsideOfTheCourse(id);
model.addAttribute("otherStudents", otherStudents);
return "course-page";
}
@GetMapping("/addStudentToCourse")
public String addStudentToCourse(@RequestParam("courseId") int courseId, @RequestParam("studentId") int studentId) {
courseService.addStudentToCourse(courseId, studentId);
return "redirect:/coursePage?courseId=" + courseId;
}
@GetMapping("/deleteStudentFromCourse")
public String deleteStudentFromCourse(@RequestParam("courseId") int courseId,
@RequestParam("studentId") int studentId) {
courseService.deleteStudentFromCourse(courseId, studentId);
return "redirect:/coursePage?courseId=" + courseId;
}
}
|
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.NumberFormat;
public class GetData
{
public static void main(String args[])
{
NumberFormat currency=NumberFormat.getCurrencyInstance();
final String DRIVER="org.apache.derby.jdbc.EmbeddedDriver";
final String CONNECTION="jdbc:derby:AccountDatabase";
try
{
Class.forName(DRIVER).newInstance();
}catch (InstantiationException e)
{
e.printStackTrace();
}catch (IllegalAccessException e){
e.printStackTrace();
}catch (ClassNotFoundException e)
{
e.printStackTrace();
}
try (Connection connection=DriverManager.getConnection(CONNECTION);
Statement statement=connection.createStatement();
ResultSet resultset=statement.executeQuery("select * from ACCOUNTS"))
{
while(resultset.next())
{
System.out.print(resultset.getString("NAME"));
System.out.print(" , ");
System.out.print(resultset.getString("ADDRESS"));
System.out.print(" ");
System.out.println(currency.format(resultset.getFloat("BALANCE")));
}
}catch (SQLException e)
{
e.printStackTrace();
}
}
}
|
package com.example.session.androidversions;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
//Creating class by extending AppCompatActivity.
public class MainActivity extends AppCompatActivity
{
Toolbar toolbar; //Creating reference of the class Toolbar.
ImageView addBtn,deleteBtn; //Creating refereences of ImageView.
FloatingActionButton versionListOpenerBtn; //Creating reference of FloatingActionButton.
@Override
//onCreate method.
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //Setting content view.
//Setting toolbar reference to its ID.
toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar); //Setting toolbar as a support action bar.
toolbar.setTitle("Android Versions"); //Setting the title of toolbar.
toolbar.setTitleTextColor(getResources().getColor(R.color.toolbar_title)); //Setting the color of title.
//Getting opyion menu as overflow icon.
getSupportActionBar().openOptionsMenu();
//Setting references with their IDs.
addBtn=(ImageView)findViewById(R.id.add_icon);
deleteBtn=(ImageView)findViewById(R.id.delete_icon);
versionListOpenerBtn=(FloatingActionButton)findViewById(R.id.fab_btn);
//When ADD button on toolbar is clicked.
addBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
//Displaying toast.
Toast.makeText(getApplicationContext(),"ADD is Clicked",Toast.LENGTH_SHORT).show();
}
});
//When DELETE button on toolbar is clicked.
deleteBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
//Displaying toast.
Toast.makeText(getApplicationContext(),"DELETE is Clicked",Toast.LENGTH_SHORT).show();
}
});
//When Floating action button is clicked.
versionListOpenerBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Displaying toast.
Toast.makeText(getApplicationContext(),"Opening Versions.",Toast.LENGTH_SHORT).show();
//Creating Intent to change the activity.
Intent changePage = new Intent(MainActivity.this,VersionListActivity.class);
startActivity(changePage); //Starting Activity.
}
});
}
@Override
//Method which is creating option Menu.
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
//Adding elements to option menu.
menu.add("Search");
menu.add("Settings");
return true; //returning true.
}
@Override
//Method when item in the option menu is clicked.
public boolean onOptionsItemSelected(MenuItem item)
{
//Displaying Toast.
Toast.makeText(getApplicationContext(),item.getTitle()+" is Clicked",Toast.LENGTH_SHORT).show();
return true; //returning true.
}
}
|
/**
* nGrinder Recorder UIs.
*/
package org.ngrinder.recorder.ui;
|
package com.alanb.gesturecommon;
import android.content.Context;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
public class TaskPhraseLoader
{
private ArrayList<String> m_phrases;
private int m_pos = 0;
public TaskPhraseLoader(Context context)
{
m_phrases = new ArrayList<String>();
BufferedReader phrase_rdr = new BufferedReader(new InputStreamReader(
context.getResources().openRawResource(R.raw.phrases2)));
try
{
String line = phrase_rdr.readLine();
while (line != null)
{
m_phrases.add(line.toLowerCase());
line = phrase_rdr.readLine();
}
}
catch (java.io.IOException e)
{
e.printStackTrace();
}
Collections.shuffle(m_phrases);
}
public String next()
{
String phrase = m_phrases.get(m_pos);
m_pos = (m_pos + 1) % m_phrases.size();
return phrase;
}
}
|
package offer;
// 请实现一个函数用来匹配包括'.'和'*'的正则表达式。模式中的字符'.'表示任意一个字符,
// 而'*'表示它前面的字符可以出现任意次(包含0次)。
// 在本题中,匹配是指字符串的所有字符匹配整个模式。
// 例如,字符串"aaa"与模式"a.a"和"ab*ac*a"匹配,但是与"aa.a"和"ab*a"均不匹配
// 有个库函数 -- 试试
// return new String(str).matches(new String(pattern));
public class 正则表达式匹配 {
public static void main(String[] args) {
// String str = "aaa";
String str = "aaa";
char[] chs = str.toCharArray();
// String str1 = "ab*ac*a";
String str1 = "a*b";
char[] pattern = str1.toCharArray();
System.out.println(match(chs,pattern));
}
public static boolean match(char[] str, char[] pattern) {
int p = 0;
int q = 0;
boolean b = helper(str,pattern,p,q);
return b;
}
private static boolean helper(char[] str, char[] pattern, int p, int q) {
// 结束条件:都正常匹配到最后,或者pattern最后是a*(str=aaaaaa,pattern=aaa*)
if(p == str.length && (q == pattern.length || (q+2 == pattern.length && pattern[q+1]=='*')))
return true;
// 结束条件:str=ab pattern=abc*d*e*,后面的都需要*前面的出现0次 ; 或者pattern已经结束而str还没有结束
if(p == str.length || q == pattern.length){
if(p < str.length){
return false;
}else {
while(q+1 < pattern.length && pattern[q+1] == '*'){ // 循环将多余的x*都消除 【注意】 要判断下q+1
q = q+2;
}
if(q == pattern.length) return true;
else return false;
}
}
// q的后一个是*,q对应的字符可能出现0次也可能出现多次
if(q+1< pattern.length && pattern[q+1] == '*'){ // 【要判断下q+1,因为是跨越式使用该位置】
if(str[p] != pattern[q] && pattern[q] != '.'){ //不等(真正的不等,且pattern中不会是.),只可能出现0次
return helper(str,pattern,p,q+2);
}else {
return helper(str,pattern,p,q+2) || helper(str,pattern,p+1,q);
}
}
// 后一个字符不是*,正常比较是否匹配
if(str[p] == pattern[q] || pattern[q] == '.'){
return helper(str,pattern,p+1,q+1);
}
return false;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.