blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 7
332
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
50
| license_type
stringclasses 2
values | repo_name
stringlengths 7
115
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 557
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.85k
684M
⌀ | star_events_count
int64 0
77.7k
| fork_events_count
int64 0
48k
| gha_license_id
stringclasses 17
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 82
values | src_encoding
stringclasses 28
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 7
5.41M
| extension
stringclasses 11
values | content
stringlengths 7
5.41M
| authors
sequencelengths 1
1
| author
stringlengths 0
161
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
895834b55e663c820faf329f2502e1b59c811fc8 | bf4e5ce01d5db32f95400e9e1a79d69c0c760e5e | /app/src/main/java/com/xhly/godutch/utility/DateTools.java | fe4cb40e5062d8fa2319375fbc8bf680261c4aaf | [] | no_license | xhly521/AAHelper | cef8f61b90b6d42bcccb4f1a07ffc0f407217a83 | 5079de7254753cf21d54be5e518cae7ad72c1c4f | refs/heads/master | 2020-04-03T19:08:02.936008 | 2016-06-24T01:20:40 | 2016-06-24T01:20:40 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 46,411 | java | package com.xhly.godutch.utility;
import java.io.Serializable;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
/**
* 日期操作工具类,主要实现了日期的常用操作。
* <p>
* 在工具类中经常使用到工具类的格式化描述,这个主要是一个日期的操作类,所以日志格式主要使用 SimpleDateFormat的定义格式.
* <p>
* 格式的意义如下: 日期和时间模式 <br>
* 日期和时间格式由日期和时间模式字符串指定。在日期和时间模式字符串中,未加引号的字母 'A' 到 'Z' 和 'a' 到 'z'
* 被解释为模式字母,用来表示日期或时间字符串元素。文本可以使用单引号 (') 引起来,以免进行解释。"''"
* 表示单引号。所有其他字符均不解释;只是在格式化时将它们简单复制到输出字符串,或者在分析时与输入字符串进行匹配。
* <p>
* 定义了以下模式字母(所有其他字符 'A' 到 'Z' 和 'a' 到 'z' 都被保留): <br>
* <table>
* <tr>
* <td>字母</td>
* <td>日期或时间元素</td>
* <td>表示</td>
* <td>示例</td>
* <td>
* </tr>
* <tr>
* <td>G</td>
* <td>Era</td>
* <td>标志符</td>
* <td>Text</td>
* <td>AD</td>
* <td>
* </tr>
* <tr>
* <td>y</td>
* <td>年</td>
* <td>Year</td>
* <td>1996;</td>
* <td>96</td>
* <td>
* </tr>
* <tr>
* <td>M</td>
* <td>年中的月份</td>
* <td>Month</td>
* <td>July;</td>
* <td>Jul;</td>
* <td>07
* </tr>
* <tr>
* <td>w</td>
* <td>年中的周数</td>
* <td>Number</td>
* <td>27</td>
* <td>
* </tr>
* <tr>
* <td>W</td>
* <td>月份中的周数</td>
* <td>Number</td>
* <td>2</td>
* <td>
* </tr>
* <tr>
* <td>D</td>
* <td>年中的天数</td>
* <td>Number</td>
* <td>189</td>
* <td>
* </tr>
* <tr>
* <td>d</td>
* <td>月份中的天数</td>
* <td>Number</td>
* <td>10</td>
* <td>
* </tr>
* <tr>
* <td>F</td>
* <td>月份中的星期</td>
* <td>Number</td>
* <td>2</td>
* <td>
* </tr>
* <tr>
* <td>E</td>
* <td>星期中的天数</td>
* <td>Text</td>
* <td>Tuesday;</td>
* <td>Tue
* </tr>
* <tr>
* <td>a</td>
* <td>Am/pm</td>
* <td>标记</td>
* <td>Text</td>
* <td>PM</td>
* <td>
* </tr>
* <tr>
* <td>H</td>
* <td>一天中的小时数(0-23)</td>
* <td>Number</td>
* <td>0
* </tr>
* <tr>
* <td>k</td>
* <td>一天中的小时数(1-24)</td>
* <td>Number</td>
* <td>24</td>
* <td>
* </tr>
* <tr>
* <td>K</td>
* <td>am/pm</td>
* <td>中的小时数(0-11)</td>
* <td>Number</td>
* <td>0</td>
* <td>
* </tr>
* <tr>
* <td>h</td>
* <td>am/pm</td>
* <td>中的小时数(1-12)</td>
* <td>Number</td>
* <td>12</td>
* <td>
* </tr>
* <tr>
* <td>m</td>
* <td>小时中的分钟数</td>
* <td>Number</td>
* <td>30</td>
* <td>
* </tr>
* <tr>
* <td>s</td>
* <td>分钟中的秒数</td>
* <td>Number</td>
* <td>55</td>
* <td>
* </tr>
* <tr>
* <td>S</td>
* <td>毫秒数</td>
* <td>Number</td>
* <td>978</td>
* <td>
* </tr>
* <tr>
* <td>z</td>
* <td>时区</td>
* <td>General</td>
* <td>time</td>
* <td>zone</td>
* <td>Pacific</td>
* <td>Standard</td>
* <td>Time;</td>
* <td>PST;</td>
* <td>GMT-08:00
* </tr>
* <tr>
* <td>Z</td>
* <td>时区</td>
* <td>RFC</td>
* <td>822</td>
* <td>time</td>
* <td>zone</td>
* <td>-0800</td>
* <td>
* </tr>
* </table>
*
* 模式字母通常是重复的,其数量确定其精确表示:
*
*/
public final class DateTools implements Serializable {
/**
*
*/
private static final long serialVersionUID = -3098985139095632110L;
private DateTools() {
}
/**
* 格式化日期显示格式
*
* @param sdate
* 原始日期格式 s - 表示 "yyyy-mm-dd" 形式的日期的 String 对象
* @param format
* 格式化后日期格式
* @return 格式化后的日期显示
*/
public static String dateFormat(String sdate, String format) {
SimpleDateFormat formatter = new SimpleDateFormat(format);
java.sql.Date date = java.sql.Date.valueOf(sdate);
String dateString = formatter.format(date);
return dateString;
}
/**
* 求两个日期相差天数
*
* @param sd
* 起始日期,格式yyyy-MM-dd
* @param ed
* 终止日期,格式yyyy-MM-dd
* @return 两个日期相差天数
*/
public static long getIntervalDays(String sd, String ed) {
return ((java.sql.Date.valueOf(ed)).getTime() - (java.sql.Date
.valueOf(sd)).getTime()) / (3600 * 24 * 1000);
}
/**
* 起始年月yyyy-MM与终止月yyyy-MM之间跨度的月数。
*
* @param beginMonth
* 格式为yyyy-MM
* @param endMonth
* 格式为yyyy-MM
* @return 整数。
*/
public static int getInterval(String beginMonth, String endMonth) {
int intBeginYear = Integer.parseInt(beginMonth.substring(0, 4));
int intBeginMonth = Integer.parseInt(beginMonth.substring(beginMonth
.indexOf("-") + 1));
int intEndYear = Integer.parseInt(endMonth.substring(0, 4));
int intEndMonth = Integer.parseInt(endMonth.substring(endMonth
.indexOf("-") + 1));
return ((intEndYear - intBeginYear) * 12)
+ (intEndMonth - intBeginMonth) + 1;
}
/**
* 根据给定的分析位置开始分析日期/时间字符串。例如,时间文本 "07/10/96 4:5 PM, PDT" 会分析成等同于
* Date(837039928046) 的 Date。
*
* @param sDate
* @param dateFormat
* @return
*/
public static Date getDate(String sDate, String dateFormat) {
SimpleDateFormat fmt = new SimpleDateFormat(dateFormat);
ParsePosition pos = new ParsePosition(0);
return fmt.parse(sDate, pos);
}
/**
* 取得当前日期的年份,以yyyy格式返回.
*
* @return 当年 yyyy
*/
public static String getCurrentYear() {
return getFormatCurrentTime("yyyy");
}
/**
* 自动返回上一年。例如当前年份是2007年,那么就自动返回2006
*
* @return 返回结果的格式为 yyyy
*/
public static String getBeforeYear() {
String currentYear = getFormatCurrentTime("yyyy");
int beforeYear = Integer.parseInt(currentYear) - 1;
return "" + beforeYear;
}
/**
* 取得当前日期的月份,以MM格式返回.
*
* @return 当前月份 MM
*/
public static String getCurrentMonth() {
return getFormatCurrentTime("MM");
}
/**
* 取得当前日期的天数,以格式"dd"返回.
*
* @return 当前月中的某天dd
*/
public static String getCurrentDay() {
return getFormatCurrentTime("dd");
}
/**
* 返回当前时间字符串。
* <p>
* 格式:yyyy-MM-dd
*
* @return String 指定格式的日期字符串.
*/
public static String getCurrentDate() {
return getFormatDateTime(new Date(), "yyyy-MM-dd");
}
/**
* 返回当前指定的时间戳。格式为yyyy-MM-dd HH:mm:ss
*
* @return 格式为yyyy-MM-dd HH:mm:ss,总共19位。
*/
public static String getCurrentDateTime() {
return getFormatDateTime(new Date(), "yyyy-MM-dd HH:mm:ss");
}
/**
* 返回给定时间字符串。
* <p>
* 格式:yyyy-MM-dd
*
* @param date
* 日期
* @return String 指定格式的日期字符串.
*/
public static String getFormatDate(Date date) {
return getFormatDateTime(date, "yyyy-MM-dd");
}
/**
* 根据制定的格式,返回日期字符串。例如2007-05-05
*
* @param format
* "yyyy-MM-dd" 或者 "yyyy/MM/dd",当然也可以是别的形式。
* @return 指定格式的日期字符串。
*/
public static String getFormatDate(String format) {
return getFormatDateTime(new Date(), format);
}
/**
* 返回当前时间字符串。
* <p>
* 格式:yyyy-MM-dd HH:mm:ss
*
* @return String 指定格式的日期字符串.
*/
public static String getCurrentTime() {
return getFormatDateTime(new Date(), "yyyy-MM-dd HH:mm:ss");
}
/**
* 返回给定时间字符串。
* <p>
* 格式:yyyy-MM-dd HH:mm:ss
*
* @param date
* 日期
* @return String 指定格式的日期字符串.
*/
public static String getFormatTime(Date date) {
return getFormatDateTime(date, "yyyy-MM-dd HH:mm:ss");
}
/**
* 返回给短时间字符串。
* <p>
* 格式:yyyy-MM-dd
*
* @param date
* 日期
* @return String 指定格式的日期字符串.
*/
public static String getFormatShortTime(Date date) {
return getFormatDateTime(date, "yyyy-MM-dd");
}
/**
* 根据给定的格式,返回时间字符串。
* <p>
* 格式参照类描绘中说明.和方法getFormatDate是一样的。
*
* @param format
* 日期格式字符串
* @return String 指定格式的日期字符串.
*/
public static String getFormatCurrentTime(String format) {
return getFormatDateTime(new Date(), format);
}
/**
* 根据给定的格式与时间(Date类型的),返回时间字符串。最为通用。<br>
*
* @param date
* 指定的日期
* @param format
* 日期格式字符串
* @return String 指定格式的日期字符串.
*/
public static String getFormatDateTime(Date date, String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(date);
}
/**
* 取得指定年月日的日期对象.
*
* @param year
* 年
* @param month
* 月注意是从1到12
* @param day
* 日
* @return 一个java.util.Date()类型的对象
*/
public static Date getDateObj(int year, int month, int day) {
Calendar c = new GregorianCalendar();
c.set(year, month - 1, day);
return c.getTime();
}
/**
* 获取指定日期的下一天。
*
* @param date
* yyyy/MM/dd
* @return yyyy/MM/dd
*/
public static String getDateTomorrow(String date) {
Date tempDate = null;
if (date.indexOf("/") > 0)
tempDate = getDateObj(date, "[/]");
if (date.indexOf("-") > 0)
tempDate = getDateObj(date, "[-]");
tempDate = getDateAdd(tempDate, 1);
return getFormatDateTime(tempDate, "yyyy/MM/dd");
}
/**
* 获取与指定日期相差指定天数的日期。
*
* @param date
* yyyy/MM/dd
* @param offset
* 正整数
* @return yyyy/MM/dd
*/
public static String getDateOffset(String date, int offset) {
// Date tempDate = getDateObj(date, "[/]");
Date tempDate = null;
if (date.indexOf("/") > 0)
tempDate = getDateObj(date, "[/]");
if (date.indexOf("-") > 0)
tempDate = getDateObj(date, "[-]");
tempDate = getDateAdd(tempDate, offset);
return getFormatDateTime(tempDate, "yyyy/MM/dd");
}
/**
* 取得指定分隔符分割的年月日的日期对象.
*
* @param argsDate
* 格式为"yyyy-MM-dd"
* @param split
* 时间格式的间隔符,例如“-”,“/”,要和时间一致起来。
* @return 一个java.util.Date()类型的对象
*/
public static Date getDateObj(String argsDate, String split) {
String[] temp = argsDate.split(split);
int year = new Integer(temp[0]).intValue();
int month = new Integer(temp[1]).intValue();
int day = new Integer(temp[2]).intValue();
return getDateObj(year, month, day);
}
/**
* 取得给定字符串描述的日期对象,描述模式采用pattern指定的格式.
*
* @param dateStr
* 日期描述 从给定字符串的开始分析文本,以生成一个日期。该方法不使用给定字符串的整个文本。 有关日期分析的更多信息,请参阅
* parse(String, ParsePosition) 方法。一个 String,应从其开始处进行分析
*
* @param pattern
* 日期模式
* @return 给定字符串描述的日期对象。
*/
public static Date getDateFromString(String dateStr, String pattern) {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
Date resDate = null;
try {
resDate = sdf.parse(dateStr);
} catch (Exception e) {
e.printStackTrace();
}
return resDate;
}
/**
* 取得当前Date对象.
*
* @return Date 当前Date对象.
*/
public static Date getDateObj() {
Calendar c = new GregorianCalendar();
return c.getTime();
}
/**
*
* @return 当前月份有多少天;
*/
public static int getDaysOfCurMonth() {
int curyear = new Integer(getCurrentYear()).intValue(); // 当前年份
int curMonth = new Integer(getCurrentMonth()).intValue();// 当前月份
int mArray[] = new int[] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30,
31 };
// 判断闰年的情况 ,2月份有29天;
if ((curyear % 400 == 0)
|| ((curyear % 100 != 0) && (curyear % 4 == 0))) {
mArray[1] = 29;
}
return mArray[curMonth - 1];
// 如果要返回下个月的天数,注意处理月份12的情况,防止数组越界;
// 如果要返回上个月的天数,注意处理月份1的情况,防止数组越界;
}
/**
* 根据指定的年月 返回指定月份(yyyy-MM)有多少天。
*
* @param time
* yyyy-MM
* @return 天数,指定月份的天数。
*/
public static int getDaysOfCurMonth(final String time) {
if (time.length() != 7) {
throw new NullPointerException("参数的格式必须是yyyy-MM");
}
String[] timeArray = time.split("-");
int curyear = new Integer(timeArray[0]).intValue(); // 当前年份
int curMonth = new Integer(timeArray[1]).intValue();// 当前月份
if (curMonth > 12) {
throw new NullPointerException("参数的格式必须是yyyy-MM,而且月份必须小于等于12。");
}
int mArray[] = new int[] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30,
31 };
// 判断闰年的情况 ,2月份有29天;
if ((curyear % 400 == 0)
|| ((curyear % 100 != 0) && (curyear % 4 == 0))) {
mArray[1] = 29;
}
if (curMonth == 12) {
return mArray[0];
}
return mArray[curMonth - 1];
// 如果要返回下个月的天数,注意处理月份12的情况,防止数组越界;
// 如果要返回上个月的天数,注意处理月份1的情况,防止数组越界;
}
/**
* 返回指定为年度为year月度month的月份内,第weekOfMonth个星期的第dayOfWeek天是当月的几号。<br>
* 00 00 00 01 02 03 04 <br>
* 05 06 07 08 09 10 11<br>
* 12 13 14 15 16 17 18<br>
* 19 20 21 22 23 24 25<br>
* 26 27 28 29 30 31 <br>
* 2006年的第一个周的1到7天为:05 06 07 01 02 03 04 <br>
* 2006年的第二个周的1到7天为:12 13 14 08 09 10 11 <br>
* 2006年的第三个周的1到7天为:19 20 21 15 16 17 18 <br>
* 2006年的第四个周的1到7天为:26 27 28 22 23 24 25 <br>
* 2006年的第五个周的1到7天为:02 03 04 29 30 31 01 。本月没有就自动转到下个月了。
*
* @param year
* 形式为yyyy <br>
* @param month
* 形式为MM,参数值在[1-12]。<br>
* @param weekOfMonth
* 在[1-6],因为一个月最多有6个周。<br>
* @param dayOfWeek
* 数字在1到7之间,包括1和7。1表示星期天,7表示星期六<br>
* -6为星期日-1为星期五,0为星期六 <br>
* @return <type>int</type>
*/
public static int getDayofWeekInMonth(String year, String month,
String weekOfMonth, String dayOfWeek) {
Calendar cal = new GregorianCalendar();
// 在具有默认语言环境的默认时区内使用当前时间构造一个默认的 GregorianCalendar。
int y = new Integer(year).intValue();
int m = new Integer(month).intValue();
cal.clear();// 不保留以前的设置
cal.set(y, m - 1, 1);// 将日期设置为本月的第一天。
cal.set(Calendar.DAY_OF_WEEK_IN_MONTH,
new Integer(weekOfMonth).intValue());
cal.set(Calendar.DAY_OF_WEEK, new Integer(dayOfWeek).intValue());
// System.out.print(cal.get(Calendar.MONTH)+" ");
// System.out.print("当"+cal.get(Calendar.WEEK_OF_MONTH)+"\t");
// WEEK_OF_MONTH表示当天在本月的第几个周。不管1号是星期几,都表示在本月的第一个周
return cal.get(Calendar.DAY_OF_MONTH);
}
/**
* 根据指定的年月日小时分秒,返回一个java.Util.Date对象。
*
* @param year
* 年
* @param month
* 月 0-11
* @param date
* 日
* @param hourOfDay
* 小时 0-23
* @param minute
* 分 0-59
* @param second
* 秒 0-59
* @return 一个Date对象。
*/
public static Date getDate(int year, int month, int date, int hourOfDay,
int minute, int second) {
Calendar cal = new GregorianCalendar();
cal.set(year, month, date, hourOfDay, minute, second);
return cal.getTime();
}
/**
* 根据指定的年、月、日返回当前是星期几。1表示星期天、2表示星期一、7表示星期六。
*
* @param year
* @param month
* month是从1开始的12结束
* @param day
* @return 返回一个代表当期日期是星期几的数字。1表示星期天、2表示星期一、7表示星期六。
*/
public static int getDayOfWeek(String year, String month, String day) {
Calendar cal = new GregorianCalendar(new Integer(year).intValue(),
new Integer(month).intValue() - 1, new Integer(day).intValue());
return cal.get(Calendar.DAY_OF_WEEK);
}
/**
* 根据指定的年、月、日返回当前是星期几。1表示星期天、2表示星期一、7表示星期六。
*
* @param date
* "yyyy/MM/dd",或者"yyyy-MM-dd"
* @return 返回一个代表当期日期是星期几的数字。1表示星期天、2表示星期一、7表示星期六。
*/
public static int getDayOfWeek(String date) {
String[] temp = null;
if (date.indexOf("/") > 0) {
temp = date.split("/");
}
if (date.indexOf("-") > 0) {
temp = date.split("-");
}
return getDayOfWeek(temp[0], temp[1], temp[2]);
}
/**
* 返回当前日期是星期几。例如:星期日、星期一、星期六等等。
*
* @param date
* 格式为 yyyy/MM/dd 或者 yyyy-MM-dd
* @return 返回当前日期是星期几
*/
public static String getChinaDayOfWeek(String date) {
String[] weeks = new String[] { "星期日", "星期一", "星期二", "星期三", "星期四",
"星期五", "星期六" };
int week = getDayOfWeek(date);
return weeks[week - 1];
}
/**
* 根据指定的年、月、日返回当前是星期几。1表示星期天、2表示星期一、7表示星期六。
*
* @param date
*
* @return 返回一个代表当期日期是星期几的数字。1表示星期天、2表示星期一、7表示星期六。
*/
public static int getDayOfWeek(Date date) {
Calendar cal = new GregorianCalendar();
cal.setTime(date);
return cal.get(Calendar.DAY_OF_WEEK);
}
/**
* 返回制定日期所在的周是一年中的第几个周。<br>
* created by wangmj at 20060324.<br>
*
* @param year
* @param month
* 范围1-12<br>
* @param day
* @return int
*/
public static int getWeekOfYear(String year, String month, String day) {
Calendar cal = new GregorianCalendar();
cal.clear();
cal.set(new Integer(year).intValue(),
new Integer(month).intValue() - 1, new Integer(day).intValue());
return cal.get(Calendar.WEEK_OF_YEAR);
}
/**
* 取得给定日期加上一定天数后的日期对象.
*
* @param date
* 给定的日期对象
* @param amount
* 需要添加的天数,如果是向前的天数,使用负数就可以.
* @return Date 加上一定天数以后的Date对象.
*/
public static Date getDateAdd(Date date, int amount) {
Calendar cal = new GregorianCalendar();
cal.setTime(date);
cal.add(GregorianCalendar.DATE, amount);
return cal.getTime();
}
/**
* 取得给定日期加上一定天数后的日期对象.
*
* @param date
* 给定的日期对象
* @param amount
* 需要添加的天数,如果是向前的天数,使用负数就可以.
* @param format
* 输出格式.
* @return Date 加上一定天数以后的Date对象.
*/
public static String getFormatDateAdd(Date date, int amount, String format) {
Calendar cal = new GregorianCalendar();
cal.setTime(date);
cal.add(GregorianCalendar.DATE, amount);
return getFormatDateTime(cal.getTime(), format);
}
/**
* 获得当前日期固定间隔天数的日期,如前60天dateAdd(-60)
*
* @param amount
* 距今天的间隔日期长度,向前为负,向后为正
* @param format
* 输出日期的格式.
* @return java.lang.String 按照格式输出的间隔的日期字符串.
*/
public static String getFormatCurrentAdd(int amount, String format) {
Date d = getDateAdd(new Date(), amount);
return getFormatDateTime(d, format);
}
/**
* 取得给定格式的昨天的日期输出
*
* @param format
* 日期输出的格式
* @return String 给定格式的日期字符串.
*/
public static String getFormatYestoday(String format) {
return getFormatCurrentAdd(-1, format);
}
/**
* 返回指定日期的前一天。<br>
*
* @param sourceDate
* @param format
* yyyy MM dd hh mm ss
* @return 返回日期字符串,形式和formcat一致。
*/
public static String getYestoday(String sourceDate, String format) {
return getFormatDateAdd(getDateFromString(sourceDate, format), -1,
format);
}
/**
* 返回明天的日期,<br>
*
* @param format
* @return 返回日期字符串,形式和formcat一致。
*/
public static String getFormatTomorrow(String format) {
return getFormatCurrentAdd(1, format);
}
/**
* 返回指定日期的后一天。<br>
*
* @param sourceDate
* @param format
* @return 返回日期字符串,形式和formcat一致。
*/
public static String getFormatDateTommorrow(String sourceDate, String format) {
return getFormatDateAdd(getDateFromString(sourceDate, format), 1,
format);
}
/**
* 根据主机的默认 TimeZone,来获得指定形式的时间字符串。
*
* @param dateFormat
* @return 返回日期字符串,形式和formcat一致。
*/
public static String getCurrentDateString(String dateFormat) {
Calendar cal = Calendar.getInstance(TimeZone.getDefault());
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
sdf.setTimeZone(TimeZone.getDefault());
return sdf.format(cal.getTime());
}
// /**
// * @deprecated 不鼓励使用。 返回当前时间串 格式:yyMMddhhmmss,在上传附件时使用
// *
// * @return String
// */
// public static String getCurDate() {
// GregorianCalendar gcDate = new GregorianCalendar();
// int year = gcDate.get(GregorianCalendar.YEAR);
// int month = gcDate.get(GregorianCalendar.MONTH) + 1;
// int day = gcDate.get(GregorianCalendar.DAY_OF_MONTH);
// int hour = gcDate.get(GregorianCalendar.HOUR_OF_DAY);
// int minute = gcDate.get(GregorianCalendar.MINUTE);
// int sen = gcDate.get(GregorianCalendar.SECOND);
// String y;
// String m;
// String d;
// String h;
// String n;
// String s;
// y = new Integer(year).toString();
//
// if (month < 10) {
// m = "0" + new Integer(month).toString();
// } else {
// m = new Integer(month).toString();
// }
//
// if (day < 10) {
// d = "0" + new Integer(day).toString();
// } else {
// d = new Integer(day).toString();
// }
//
// if (hour < 10) {
// h = "0" + new Integer(hour).toString();
// } else {
// h = new Integer(hour).toString();
// }
//
// if (minute < 10) {
// n = "0" + new Integer(minute).toString();
// } else {
// n = new Integer(minute).toString();
// }
//
// if (sen < 10) {
// s = "0" + new Integer(sen).toString();
// } else {
// s = new Integer(sen).toString();
// }
//
// return "" + y + m + d + h + n + s;
// }
/**
* 根据给定的格式,返回时间字符串。 和getFormatDate(String format)相似。
*
* @param format
* yyyy MM dd hh mm ss
* @return 返回一个时间字符串
*/
public static String getCurTimeByFormat(String format) {
Date newdate = new Date(System.currentTimeMillis());
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(newdate);
}
/**
* 获取两个时间串时间的差值,单位为秒
*
* @param startTime
* 开始时间 yyyy-MM-dd HH:mm:ss
* @param endTime
* 结束时间 yyyy-MM-dd HH:mm:ss
* @return 两个时间的差值(秒)
*/
public static long getDiff(String startTime, String endTime) {
long diff = 0;
SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date startDate = ft.parse(startTime);
Date endDate = ft.parse(endTime);
diff = startDate.getTime() - endDate.getTime();
diff = diff / 1000;
} catch (ParseException e) {
e.printStackTrace();
}
return diff;
}
/**
* 获取小时/分钟/秒
*
* @param second
* 秒
* @return 包含小时、分钟、秒的时间字符串,例如3小时23分钟13秒。
*/
public static String getHour(long second) {
long hour = second / 60 / 60;
long minute = (second - hour * 60 * 60) / 60;
long sec = (second - hour * 60 * 60) - minute * 60;
return hour + "小时" + minute + "分钟" + sec + "秒";
}
/**
* 返回指定时间字符串。
* <p>
* 格式:yyyy-MM-dd HH:mm:ss
*
* @return String 指定格式的日期字符串.
*/
public static String getDateTime(long microsecond) {
return getFormatDateTime(new Date(microsecond), "yyyy-MM-dd HH:mm:ss");
}
/**
* 返回当前时间加实数小时后的日期时间。
* <p>
* 格式:yyyy-MM-dd HH:mm:ss
*
* @return Float 加几实数小时.
*/
public static String getDateByAddFltHour(float flt) {
int addMinute = (int) (flt * 60);
Calendar cal = new GregorianCalendar();
cal.setTime(new Date());
cal.add(GregorianCalendar.MINUTE, addMinute);
return getFormatDateTime(cal.getTime(), "yyyy-MM-dd HH:mm:ss");
}
/**
* 返回指定时间加指定小时数后的日期时间。
* <p>
* 格式:yyyy-MM-dd HH:mm:ss
*
* @return 时间.
*/
public static String getDateByAddHour(String datetime, int minute) {
String returnTime = null;
Calendar cal = new GregorianCalendar();
SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date;
try {
date = ft.parse(datetime);
cal.setTime(date);
cal.add(GregorianCalendar.MINUTE, minute);
returnTime = getFormatDateTime(cal.getTime(), "yyyy-MM-dd HH:mm:ss");
} catch (ParseException e) {
e.printStackTrace();
}
return returnTime;
}
/**
* 获取两个时间串时间的差值,单位为小时
*
* @param startTime
* 开始时间 yyyy-MM-dd HH:mm:ss
* @param endTime
* 结束时间 yyyy-MM-dd HH:mm:ss
* @return 两个时间的差值(秒)
*/
public static int getDiffHour(String startTime, String endTime) {
long diff = 0;
SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date startDate = ft.parse(startTime);
Date endDate = ft.parse(endTime);
diff = startDate.getTime() - endDate.getTime();
diff = diff / (1000 * 60 * 60);
} catch (ParseException e) {
e.printStackTrace();
}
return new Long(diff).intValue();
}
/**
* 返回年份的下拉框。
*
* @param selectName
* 下拉框名称
* @param value
* 当前下拉框的值
* @param startYear
* 开始年份
* @param endYear
* 结束年份
* @return 年份下拉框的html
*/
public static String getYearSelect(String selectName, String value,
int startYear, int endYear) {
int start = startYear;
int end = endYear;
if (startYear > endYear) {
start = endYear;
end = startYear;
}
StringBuffer sb = new StringBuffer("");
sb.append("<select name=\"" + selectName + "\">");
for (int i = start; i <= end; i++) {
if (!value.trim().equals("") && i == Integer.parseInt(value)) {
sb.append("<option value=\"" + i + "\" selected>" + i
+ "</option>");
} else {
sb.append("<option value=\"" + i + "\">" + i + "</option>");
}
}
sb.append("</select>");
return sb.toString();
}
/**
* 返回年份的下拉框。
*
* @param selectName
* 下拉框名称
* @param value
* 当前下拉框的值
* @param startYear
* 开始年份
* @param endYear
* 结束年份
* 例如开始年份为2001结束年份为2005那么下拉框就有五个值。(2001、2002、2003、2004、2005)。
* @return 返回年份的下拉框的html。
*/
public static String getYearSelect(String selectName, String value,
int startYear, int endYear, boolean hasBlank) {
int start = startYear;
int end = endYear;
if (startYear > endYear) {
start = endYear;
end = startYear;
}
StringBuffer sb = new StringBuffer("");
sb.append("<select name=\"" + selectName + "\">");
if (hasBlank) {
sb.append("<option value=\"\"></option>");
}
for (int i = start; i <= end; i++) {
if (!value.trim().equals("") && i == Integer.parseInt(value)) {
sb.append("<option value=\"" + i + "\" selected>" + i
+ "</option>");
} else {
sb.append("<option value=\"" + i + "\">" + i + "</option>");
}
}
sb.append("</select>");
return sb.toString();
}
/**
* 返回年份的下拉框。
*
* @param selectName
* 下拉框名称
* @param value
* 当前下拉框的值
* @param startYear
* 开始年份
* @param endYear
* 结束年份
* @param js
* 这里的js为js字符串。例如 " onchange=\"changeYear()\" "
* ,这样任何js的方法就可以在jsp页面中编写,方便引入。
* @return 返回年份的下拉框。
*/
public static String getYearSelect(String selectName, String value,
int startYear, int endYear, boolean hasBlank, String js) {
int start = startYear;
int end = endYear;
if (startYear > endYear) {
start = endYear;
end = startYear;
}
StringBuffer sb = new StringBuffer("");
sb.append("<select name=\"" + selectName + "\" " + js + ">");
if (hasBlank) {
sb.append("<option value=\"\"></option>");
}
for (int i = start; i <= end; i++) {
if (!value.trim().equals("") && i == Integer.parseInt(value)) {
sb.append("<option value=\"" + i + "\" selected>" + i
+ "</option>");
} else {
sb.append("<option value=\"" + i + "\">" + i + "</option>");
}
}
sb.append("</select>");
return sb.toString();
}
/**
* 返回年份的下拉框。
*
* @param selectName
* 下拉框名称
* @param value
* 当前下拉框的值
* @param startYear
* 开始年份
* @param endYear
* 结束年份
* @param js
* 这里的js为js字符串。例如 " onchange=\"changeYear()\" "
* ,这样任何js的方法就可以在jsp页面中编写,方便引入。
* @return 返回年份的下拉框。
*/
public static String getYearSelect(String selectName, String value,
int startYear, int endYear, String js) {
int start = startYear;
int end = endYear;
if (startYear > endYear) {
start = endYear;
end = startYear;
}
StringBuffer sb = new StringBuffer("");
sb.append("<select name=\"" + selectName + "\" " + js + ">");
for (int i = start; i <= end; i++) {
if (!value.trim().equals("") && i == Integer.parseInt(value)) {
sb.append("<option value=\"" + i + "\" selected>" + i
+ "</option>");
} else {
sb.append("<option value=\"" + i + "\">" + i + "</option>");
}
}
sb.append("</select>");
return sb.toString();
}
/**
* 获取月份的下拉框
*
* @param selectName
* @param value
* @param hasBlank
* @return 返回月份的下拉框。
*/
public static String getMonthSelect(String selectName, String value,
boolean hasBlank) {
StringBuffer sb = new StringBuffer("");
sb.append("<select name=\"" + selectName + "\">");
if (hasBlank) {
sb.append("<option value=\"\"></option>");
}
for (int i = 1; i <= 12; i++) {
if (!value.trim().equals("") && i == Integer.parseInt(value)) {
sb.append("<option value=\"" + i + "\" selected>" + i
+ "</option>");
} else {
sb.append("<option value=\"" + i + "\">" + i + "</option>");
}
}
sb.append("</select>");
return sb.toString();
}
/**
* 获取月份的下拉框
*
* @param selectName
* @param value
* @param hasBlank
* @param js
* @return 返回月份的下拉框。
*/
public static String getMonthSelect(String selectName, String value,
boolean hasBlank, String js) {
StringBuffer sb = new StringBuffer("");
sb.append("<select name=\"" + selectName + "\" " + js + ">");
if (hasBlank) {
sb.append("<option value=\"\"></option>");
}
for (int i = 1; i <= 12; i++) {
if (!value.trim().equals("") && i == Integer.parseInt(value)) {
sb.append("<option value=\"" + i + "\" selected>" + i
+ "</option>");
} else {
sb.append("<option value=\"" + i + "\">" + i + "</option>");
}
}
sb.append("</select>");
return sb.toString();
}
/**
* 获取天的下拉框,默认的为1-31。 注意:此方法不能够和月份下拉框进行联动。
*
* @param selectName
* @param value
* @param hasBlank
* @return 获得天的下拉框
*/
public static String getDaySelect(String selectName, String value,
boolean hasBlank) {
StringBuffer sb = new StringBuffer("");
sb.append("<select name=\"" + selectName + "\">");
if (hasBlank) {
sb.append("<option value=\"\"></option>");
}
for (int i = 1; i <= 31; i++) {
if (!value.trim().equals("") && i == Integer.parseInt(value)) {
sb.append("<option value=\"" + i + "\" selected>" + i
+ "</option>");
} else {
sb.append("<option value=\"" + i + "\">" + i + "</option>");
}
}
sb.append("</select>");
return sb.toString();
}
/**
* 获取天的下拉框,默认的为1-31
*
* @param selectName
* @param value
* @param hasBlank
* @param js
* @return 获取天的下拉框
*/
public static String getDaySelect(String selectName, String value,
boolean hasBlank, String js) {
StringBuffer sb = new StringBuffer("");
sb.append("<select name=\"" + selectName + "\" " + js + ">");
if (hasBlank) {
sb.append("<option value=\"\"></option>");
}
for (int i = 1; i <= 31; i++) {
if (!value.trim().equals("") && i == Integer.parseInt(value)) {
sb.append("<option value=\"" + i + "\" selected>" + i
+ "</option>");
} else {
sb.append("<option value=\"" + i + "\">" + i + "</option>");
}
}
sb.append("</select>");
return sb.toString();
}
/**
* 计算两天之间有多少个周末(这个周末,指星期六和星期天,一个周末返回结果为2,两个为4,以此类推。) (此方法目前用于统计司机用车记录。)
* 注意开始日期和结束日期要统一起来。
*
* @param startDate
* 开始日期 ,格式"yyyy/MM/dd" 或者"yyyy-MM-dd"
* @param endDate
* 结束日期 ,格式"yyyy/MM/dd"或者"yyyy-MM-dd"
* @return int
*/
public static int countWeekend(String startDate, String endDate) {
int result = 0;
Date sdate = null;
Date edate = null;
if (startDate.indexOf("/") > 0 && endDate.indexOf("/") > 0) {
sdate = getDateObj(startDate, "/"); // 开始日期
edate = getDateObj(endDate, "/");// 结束日期
}
if (startDate.indexOf("-") > 0 && endDate.indexOf("-") > 0) {
sdate = getDateObj(startDate, "-"); // 开始日期
edate = getDateObj(endDate, "-");// 结束日期
}
// 首先计算出都有那些日期,然后找出星期六星期天的日期
int sumDays = Math.abs(getDiffDays(startDate, endDate));
int dayOfWeek = 0;
for (int i = 0; i <= sumDays; i++) {
dayOfWeek = getDayOfWeek(getDateAdd(sdate, i)); // 计算每过一天的日期
if (dayOfWeek == 1 || dayOfWeek == 7) { // 1 星期天 7星期六
result++;
}
}
return result;
}
/**
* 返回两个日期之间相差多少天。 注意开始日期和结束日期要统一起来。
*
* @param startDate
* 格式"yyyy/MM/dd" 或者"yyyy-MM-dd"
* @param endDate
* 格式"yyyy/MM/dd" 或者"yyyy-MM-dd"
* @return 整数。
*/
public static int getDiffDays(String startDate, String endDate) {
long diff = 0;
SimpleDateFormat ft = null;
if (startDate.indexOf("/") > 0 && endDate.indexOf("/") > 0) {
ft = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
}
if (startDate.indexOf("-") > 0 && endDate.indexOf("-") > 0) {
ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
try {
Date sDate = ft.parse(startDate + " 00:00:00");
Date eDate = ft.parse(endDate + " 00:00:00");
diff = eDate.getTime() - sDate.getTime();
diff = diff / 86400000;// 1000*60*60*24;
} catch (ParseException e) {
e.printStackTrace();
}
return (int) diff;
}
/**
* 返回两个日期之间的详细日期数组(包括开始日期和结束日期)。 例如:2007/07/01 到2007/07/03 ,那么返回数组
* {"2007/07/01","2007/07/02","2007/07/03"} 注意开始日期和结束日期要统一起来。
*
* @param startDate
* 格式"yyyy/MM/dd"或者 yyyy-MM-dd
* @param endDate
* 格式"yyyy/MM/dd"或者 yyyy-MM-dd
* @return 返回一个字符串数组对象
*/
public static String[] getArrayDiffDays(String startDate, String endDate) {
int LEN = 0; // 用来计算两天之间总共有多少天
// 如果结束日期和开始日期相同
if (startDate.equals(endDate)) {
return new String[] { startDate };
}
Date sdate = null;
if (startDate.indexOf("/") > 0 && endDate.indexOf("/") > 0) {
sdate = getDateObj(startDate, "/"); // 开始日期
}
if (startDate.indexOf("-") > 0 && endDate.indexOf("-") > 0) {
sdate = getDateObj(startDate, "-"); // 开始日期
}
LEN = getDiffDays(startDate, endDate);
String[] dateResult = new String[LEN + 1];
dateResult[0] = startDate;
for (int i = 1; i < LEN + 1; i++) {
if (startDate.indexOf("/") > 0 && endDate.indexOf("/") > 0) {
dateResult[i] = getFormatDateTime(getDateAdd(sdate, i),
"yyyy/MM/dd");
}
if (startDate.indexOf("-") > 0 && endDate.indexOf("-") > 0) {
dateResult[i] = getFormatDateTime(getDateAdd(sdate, i),
"yyyy-MM-dd");
}
}
return dateResult;
}
/**
* 判断一个日期是否在开始日期和结束日期之间。
*
* @param srcDate
* 目标日期 yyyy/MM/dd 或者 yyyy-MM-dd
* @param startDate
* 开始日期 yyyy/MM/dd 或者 yyyy-MM-dd
* @param endDate
* 结束日期 yyyy/MM/dd 或者 yyyy-MM-dd
* @return 大于等于开始日期小于等于结束日期,那么返回true,否则返回false
*/
public static boolean isInStartEnd(String srcDate, String startDate,
String endDate) {
if (startDate.compareTo(srcDate) <= 0
&& endDate.compareTo(srcDate) >= 0) {
return true;
} else {
return false;
}
}
/**
* 获取天的下拉框,默认的为1-4。 注意:此方法不能够和月份下拉框进行联动。
*
* @param selectName
* @param value
* @param hasBlank
* @return 获得季度的下拉框
*/
public static String getQuarterSelect(String selectName, String value,
boolean hasBlank) {
StringBuffer sb = new StringBuffer("");
sb.append("<select name=\"" + selectName + "\">");
if (hasBlank) {
sb.append("<option value=\"\"></option>");
}
for (int i = 1; i <= 4; i++) {
if (!value.trim().equals("") && i == Integer.parseInt(value)) {
sb.append("<option value=\"" + i + "\" selected>" + i
+ "</option>");
} else {
sb.append("<option value=\"" + i + "\">" + i + "</option>");
}
}
sb.append("</select>");
return sb.toString();
}
/**
* 获取季度的下拉框,默认的为1-4
*
* @param selectName
* @param value
* @param hasBlank
* @param js
* @return 获取季度的下拉框
*/
public static String getQuarterSelect(String selectName, String value,
boolean hasBlank, String js) {
StringBuffer sb = new StringBuffer("");
sb.append("<select name=\"" + selectName + "\" " + js + ">");
if (hasBlank) {
sb.append("<option value=\"\"></option>");
}
for (int i = 1; i <= 4; i++) {
if (!value.trim().equals("") && i == Integer.parseInt(value)) {
sb.append("<option value=\"" + i + "\" selected>" + i
+ "</option>");
} else {
sb.append("<option value=\"" + i + "\">" + i + "</option>");
}
}
sb.append("</select>");
return sb.toString();
}
/**
* 将格式为yyyy或者yyyy.MM或者yyyy.MM.dd的日期转换为yyyy/MM/dd的格式。位数不足的,都补01。<br>
* 例如.1999 = 1999/01/01 再如:1989.02=1989/02/01
*
* @param argDate
* 需要进行转换的日期。格式可能为yyyy或者yyyy.MM或者yyyy.MM.dd
* @return 返回格式为yyyy/MM/dd的字符串
*/
public static String changeDate(String argDate) {
if (argDate == null || argDate.trim().equals("")) {
return "";
}
String result = "";
// 如果是格式为yyyy/MM/dd的就直接返回
if (argDate.length() == 10 && argDate.indexOf("/") > 0) {
return argDate;
}
String[] str = argDate.split("[.]"); // .比较特殊
int LEN = str.length;
for (int i = 0; i < LEN; i++) {
if (str[i].length() == 1) {
if (str[i].equals("0")) {
str[i] = "01";
} else {
str[i] = "0" + str[i];
}
}
}
if (LEN == 1) {
result = argDate + "/01/01";
}
if (LEN == 2) {
result = str[0] + "/" + str[1] + "/01";
}
if (LEN == 3) {
result = str[0] + "/" + str[1] + "/" + str[2];
}
return result;
}
/**
* 将格式为yyyy或者yyyy.MM或者yyyy.MM.dd的日期转换为yyyy/MM/dd的格式。位数不足的,都补01。<br>
* 例如.1999 = 1999/01/01 再如:1989.02=1989/02/01
*
* @param argDate
* 需要进行转换的日期。格式可能为yyyy或者yyyy.MM或者yyyy.MM.dd
* @return 返回格式为yyyy/MM/dd的字符串
*/
public static String changeDateWithSplit(String argDate, String split) {
if (argDate == null || argDate.trim().equals("")) {
return "";
}
if (split == null || split.trim().equals("")) {
split = "-";
}
String result = "";
// 如果是格式为yyyy/MM/dd的就直接返回
if (argDate.length() == 10 && argDate.indexOf("/") > 0) {
return argDate;
}
// 如果是格式为yyyy-MM-dd的就直接返回
if (argDate.length() == 10 && argDate.indexOf("-") > 0) {
return argDate;
}
String[] str = argDate.split("[.]"); // .比较特殊
int LEN = str.length;
for (int i = 0; i < LEN; i++) {
if (str[i].length() == 1) {
if (str[i].equals("0")) {
str[i] = "01";
} else {
str[i] = "0" + str[i];
}
}
}
if (LEN == 1) {
result = argDate + split + "01" + split + "01";
}
if (LEN == 2) {
result = str[0] + split + str[1] + split + "01";
}
if (LEN == 3) {
result = str[0] + split + str[1] + split + str[2];
}
return result;
}
/**
* 返回指定日期的的下一个月的天数。
*
* @param argDate
* 格式为yyyy-MM-dd或者yyyy/MM/dd
* @return 下一个月的天数。
*/
public static int getNextMonthDays(String argDate) {
String[] temp = null;
if (argDate.indexOf("/") > 0) {
temp = argDate.split("/");
}
if (argDate.indexOf("-") > 0) {
temp = argDate.split("-");
}
Calendar cal = new GregorianCalendar(new Integer(temp[0]).intValue(),
new Integer(temp[1]).intValue() - 1,
new Integer(temp[2]).intValue());
int curMonth = cal.get(Calendar.MONTH);
cal.set(Calendar.MONTH, curMonth + 1);
int curyear = cal.get(Calendar.YEAR);// 当前年份
curMonth = cal.get(Calendar.MONTH);// 当前月份,0-11
int mArray[] = new int[] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30,
31 };
// 判断闰年的情况 ,2月份有29天;
if ((curyear % 400 == 0)
|| ((curyear % 100 != 0) && (curyear % 4 == 0))) {
mArray[1] = 29;
}
return mArray[curMonth];
}
public static void main(String[] args) {
System.out.println(DateTools.getCurrentDateTime());
System.out.println("first=" + changeDateWithSplit("2000.1", ""));
System.out.println("second=" + changeDateWithSplit("2000.1", "/"));
String[] t = getArrayDiffDays("2008/02/15", "2008/02/19");
for (int i = 0; i < t.length; i++) {
System.out.println(t[i]);
}
t = getArrayDiffDays("2008-02-15", "2008-02-19");
for (int i = 0; i < t.length; i++) {
System.out.println(t[i]);
}
System.out.println(getNextMonthDays("2008/02/15") + "||"
+ getCurrentMonth() + "||" + DateTools.changeDate("1999"));
System.out.println(DateTools.changeDate("1999.1"));
System.out.println(DateTools.changeDate("1999.11"));
System.out.println(DateTools.changeDate("1999.1.2"));
System.out.println(DateTools.changeDate("1999.11.12"));
}
} | [
"[email protected]"
] | |
60e692a31034dd32a0a0a708ab771046b5fa2c20 | fffcf946aab37b73ac74bb445ddeda3c6fc2838b | /core/src/com/gaskarov/teerain/core/VisitorOrganoid.java | 2a4b5a6ef0c20ffc070cccb8ef163d469c88c00d | [] | no_license | Barricade/TeeRain | cafc630fc5905ba39dd77d9b8365f9c5a2e8698a | 0e44448fb707934d69a767d02549ea88031646dc | refs/heads/master | 2021-01-20T03:06:56.221206 | 2019-07-09T22:46:10 | 2019-07-09T22:46:10 | 51,308,989 | 3 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,433 | java | package com.gaskarov.teerain.core;
import com.badlogic.gdx.math.Vector2;
import com.gaskarov.teerain.core.cellularity.Cellularity;
import com.gaskarov.teerain.resource.Settings;
import com.gaskarov.util.common.MathUtils;
import com.gaskarov.util.constants.GlobalConstants;
import com.gaskarov.util.container.Array;
/**
* Copyright (c) 2016 Ayrat Gaskarov <br>
* All rights reserved.
*
* @author Ayrat Gaskarov
*/
public class VisitorOrganoid {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static final Array sPool = Array.obtain();
private boolean mIsEnabled;
private boolean mIsVisitor;
private int mVisitorX;
private int mVisitorY;
private int mVisitorWidth;
private int mVisitorHeight;
// ===========================================================
// Constructors
// ===========================================================
private VisitorOrganoid() {
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
private static VisitorOrganoid obtainPure() {
if (GlobalConstants.POOL)
synchronized (VisitorOrganoid.class) {
return sPool.size() == 0 ? new VisitorOrganoid()
: (VisitorOrganoid) sPool.pop();
}
return new VisitorOrganoid();
}
private static void recyclePure(VisitorOrganoid pObj) {
if (GlobalConstants.POOL)
synchronized (VisitorOrganoid.class) {
sPool.push(pObj);
}
}
public static VisitorOrganoid obtain(boolean pIsEnabled) {
VisitorOrganoid obj = obtainPure();
obj.mIsEnabled = pIsEnabled;
obj.mIsVisitor = false;
obj.mVisitorX = 0;
obj.mVisitorY = 0;
obj.mVisitorWidth = 0;
obj.mVisitorHeight = 0;
return obj;
}
public static void recycle(VisitorOrganoid pObj) {
recyclePure(pObj);
}
public void attach(Cellularity pCellularity, int pX, int pY, int pZ) {
if (mIsEnabled) {
if (!pCellularity.isChunk())
pCellularity.tickEnable(pX, pY, pZ);
}
}
public void detach(Cellularity pCellularity, int pX, int pY, int pZ) {
if (mIsEnabled) {
if (!pCellularity.isChunk())
pCellularity.tickDisable(pX, pY, pZ);
}
}
public void tissularedAttach(Cellularity pCellularity, int pX, int pY,
int pZ) {
if (mIsEnabled)
pushVisitor(pCellularity, pX, pY, pZ);
}
public void tissularedDetach(Cellularity pCellularity, int pX, int pY,
int pZ) {
if (mIsEnabled)
removeVisitor(pCellularity.getTissularity());
}
public void tick(Cellularity pCellularity, int pX, int pY, int pZ) {
if (mIsEnabled && !pCellularity.isChunk())
pushVisitor(pCellularity, pX, pY, pZ);
}
public boolean getIsEnabled() {
return mIsEnabled;
}
public void setIsEnabled(Cellularity pCellularity, int pX, int pY, int pZ,
boolean pIsEnabled) {
if (mIsEnabled == pIsEnabled)
return;
mIsEnabled = pIsEnabled;
if (pCellularity == null)
return;
Tissularity tissularity = pCellularity.getTissularity();
if (mIsEnabled) {
if (tissularity != null)
pushVisitor(pCellularity, pX, pY, pZ);
if (!pCellularity.isChunk())
pCellularity.tickEnable(pX, pY, pZ);
} else {
if (!pCellularity.isChunk())
pCellularity.tickDisable(pX, pY, pZ);
if (tissularity != null)
removeVisitor(tissularity);
}
}
private void pushVisitor(Cellularity pCellularity, int pX, int pY, int pZ) {
Tissularity tissularity = pCellularity.getTissularity();
Vector2 p = pCellularity.localToChunk(pX + 0.5f, pY + 0.5f);
float x = p.x;
float y = p.y;
int lx = pCellularity.localToGlobalX(MathUtils.floor(x)
- (Settings.VISITOR_WIDTH + 1) / 2);
int ly = pCellularity.localToGlobalY(MathUtils.floor(y)
- (Settings.VISITOR_HEIGHT + 1) / 2);
int rx = pCellularity.localToGlobalX(MathUtils.ceil(x)
+ (Settings.VISITOR_WIDTH - 1) / 2);
int ry = pCellularity.localToGlobalY(MathUtils.ceil(y)
+ (Settings.VISITOR_HEIGHT - 1) / 2);
int width = rx - lx + 1;
int height = ry - ly + 1;
if (mIsVisitor)
tissularity.moveVisitor(mVisitorX, mVisitorY, mVisitorWidth,
mVisitorHeight, lx, ly, width, height);
else {
tissularity.addVisitor(lx, ly, width, height);
tissularity.pushVisitor(this, pCellularity, pX, pY, pZ);
}
mIsVisitor = true;
mVisitorX = lx;
mVisitorY = ly;
mVisitorWidth = width;
mVisitorHeight = height;
}
private void removeVisitor(Tissularity pTissularity) {
if (mIsVisitor) {
pTissularity.removeVisitor(this);
pTissularity.removeVisitor(mVisitorX, mVisitorY, mVisitorWidth,
mVisitorHeight);
mIsVisitor = false;
}
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| [
"[email protected]"
] | |
5cc8ee3cd7e71af8aabbc2b7948698e4d4e0f493 | 22ee19c86602e3f2de45b59f4e4d1b872f8a1e27 | /custom-log4j2-appender/appender/src/main/java/org/wso2/sample/custom/log4j2/appender/CustomLog4j2Appender.java | 0b8b2b5e656fa1b29071fdb3913160b92d0460ec | [
"Apache-2.0"
] | permissive | wso2-incubator/samples-is | b7f5aca5d8c595f180546e011410cc27563d7891 | 19d13bd10d1744572080926b438aacaff1484ad0 | refs/heads/master | 2022-08-31T06:49:18.082720 | 2022-08-17T14:35:15 | 2022-08-17T14:35:15 | 147,661,973 | 4 | 17 | Apache-2.0 | 2022-08-17T14:35:16 | 2018-09-06T11:13:35 | Java | UTF-8 | Java | false | false | 4,627 | java | /*
* Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.sample.custom.log4j2.appender;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.logging.log4j.core.Filter;
import org.apache.logging.log4j.core.Layout;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.appender.AbstractAppender;
import org.apache.logging.log4j.core.config.Property;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
import org.apache.logging.log4j.core.config.plugins.PluginElement;
import org.apache.logging.log4j.core.config.plugins.PluginFactory;
import org.wso2.sample.custom.service.manager.CustomServiceManager;
import java.io.Serializable;
@Plugin(name = "CustomLog4j2LogAppender", category = "Core", elementType = "appender", printObject = false)
public class CustomLog4j2Appender extends AbstractAppender {
private static final Log log = LogFactory.getLog(CustomLog4j2Appender.class);
private CustomLog4j2Appender(String name, Filter filter, final Layout<? extends Serializable> layout,
boolean ignoreExceptions) {
super(name, filter, layout, ignoreExceptions, Property.EMPTY_ARRAY);
}
@PluginFactory
public static CustomLog4j2Appender createAppender(
@PluginAttribute(value = "name") String name,
@PluginElement("Layout") Layout<? extends Serializable> layout,
@PluginElement("Filter") Filter filter,
@PluginAttribute(value = "ignoreExceptions", defaultBoolean = true) boolean ignoreExceptions) {
return new CustomLog4j2Appender(name, filter, layout, ignoreExceptions);
}
@Override
public void start() {
super.start();
// Do initiate something here.
}
@Override
public void stop() {
super.stop();
// Do stop something here.
}
@Override
public void append(LogEvent logEvent) {
log.info("Log event: " + logEvent.getMessage().getFormattedMessage() + ", received.");
/*
Here we can do something with the received log event. Following example demonstrate that.
In this example, we are using the information from the log event and perform some logic in the Identity
Server runtime. Keep in mind that this log appender is deployed under the fragmented host: 'org.ops4j.pax
.logging.pax-logging-log4j2'. Because of that, we cannot use the OSGi services from the Identity Server
default OSGi runtime.
So this sample project keep a different OSGi bundle called 'org.wso2.sample.service.manager' deployed in the
Identity Server runtime, and consume a singleton instance from it. It's also important that we are not using
any classes loaded by the fragmented host, and pass that to the service manager to avoid class loading
errors. This is the reason to use a separate model class to represent the logEvent.
*/
boolean isUserExists = CustomServiceManager.getInstance().isUserAvailable(new org.wso2.sample.custom.service
.manager.model.Log(logEvent.getMessage().getFormattedMessage(), logEvent.getContextData().toMap()));
// Now we have obtained the user existence from identity Server runtime. We will invoke an API endpoint with
// this information.
invokeUserExistenceEndpoint(logEvent.getMessage().getFormattedMessage(), isUserExists);
}
private void invokeUserExistenceEndpoint(String formattedLogMessage, boolean isUserExists) {
// We could call an external endpoint here. Keep in mind that this log appender is not async operation.
// Therefore, the client used to invoke the endpoint needs to invoke the endpoint asynchronously to avoid
// performance issues.
log.info("Invoking external APIs to notify user existence");
return;
}
}
| [
"[email protected]"
] | |
a74fff7eb54e2ee62437a87dd40c5fb2c71a8238 | c99ecaf5692a5dd3c4b6c5af8960b958ef61d22f | /excelClassExceptionDebug/src/jxl/Workbook.java | d03660e3c8238823bbaf89fb5c8f5e6ac5745109 | [] | no_license | bloomer024/Mobile-Development | afc00c65c7b3ae98ac93a2d2ab3e5b629a8e124f | d68fb0a556702e172f327ab3bc0da8d4be37034a | refs/heads/master | 2020-12-27T09:34:47.148817 | 2013-09-03T16:40:22 | 2013-09-03T16:40:22 | 37,514,253 | 1 | 0 | null | 2015-06-16T07:12:33 | 2015-06-16T07:12:32 | null | UTF-8 | Java | false | false | 12,899 | java | /*********************************************************************
*
* Copyright (C) 2002 Andrew Khan
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
***************************************************************************/
package jxl;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import src.jxl.read.biff.BiffException;
import src.jxl.read.biff.PasswordException;
import src.jxl.read.biff.WorkbookParser;
import src.jxl.write.WritableWorkbook;
import src.jxl.write.biff.WritableWorkbookImpl;
/**
* Represents a Workbook. Contains the various factory methods and provides
* a variety of accessors which provide access to the work sheets.
*/
public abstract class Workbook
{
/**
* The current version of the software
*/
private static final String VERSION = "2.6.12";
/**
* The constructor
*/
protected Workbook()
{
}
/**
* Gets the sheets within this workbook. Use of this method for
* large worksheets can cause performance problems.
*
* @return an array of the individual sheets
*/
public abstract Sheet[] getSheets();
/**
* Gets the sheet names
*
* @return an array of strings containing the sheet names
*/
public abstract String[] getSheetNames();
/**
* Gets the specified sheet within this workbook
* As described in the accompanying technical notes, each call
* to getSheet forces a reread of the sheet (for memory reasons).
* Therefore, do not make unnecessary calls to this method. Furthermore,
* do not hold unnecessary references to Sheets in client code, as
* this will prevent the garbage collector from freeing the memory
*
* @param index the zero based index of the reQuired sheet
* @return The sheet specified by the index
* @exception IndexOutOfBoundException when index refers to a non-existent
* sheet
*/
public abstract Sheet getSheet(int index)
throws IndexOutOfBoundsException;
/**
* Gets the sheet with the specified name from within this workbook.
* As described in the accompanying technical notes, each call
* to getSheet forces a reread of the sheet (for memory reasons).
* Therefore, do not make unnecessary calls to this method. Furthermore,
* do not hold unnecessary references to Sheets in client code, as
* this will prevent the garbage collector from freeing the memory
*
* @param name the sheet name
* @return The sheet with the specified name, or null if it is not found
*/
public abstract Sheet getSheet(String name);
/**
* Accessor for the software version
*
* @return the version
*/
public static String getVersion()
{
return VERSION;
}
/**
* Returns the number of sheets in this workbook
*
* @return the number of sheets in this workbook
*/
public abstract int getNumberOfSheets();
/**
* Gets the named cell from this workbook. If the name refers to a
* range of cells, then the cell on the top left is returned. If
* the name cannot be found, null is returned.
* This is a convenience function to quickly access the contents
* of a single cell. If you need further information (such as the
* sheet or adjacent cells in the range) use the functionally
* richer method, findByName which returns a list of ranges
*
* @param name the name of the cell/range to search for
* @return the cell in the top left of the range if found, NULL
* otherwise
*/
public abstract Cell findCellByName(String name);
/**
* Returns the cell for the specified location eg. "Sheet1!A4".
* This is identical to using the CellReferenceHelper with its
* associated performance overheads, consequently it should
* be use sparingly
*
* @param loc the cell to retrieve
* @return the cell at the specified location
*/
public abstract Cell getCell(String loc);
/**
* Gets the named range from this workbook. The Range object returns
* contains all the cells from the top left to the bottom right
* of the range.
* If the named range comprises an adjacent range,
* the Range[] will contain one object; for non-adjacent
* ranges, it is necessary to return an array of length greater than
* one.
* If the named range contains a single cell, the top left and
* bottom right cell will be the same cell
*
* @param name the name of the cell/range to search for
* @return the range of cells, or NULL if the range does not exist
*/
public abstract Range[] findByName(String name);
/**
* Gets the named ranges
*
* @return the list of named cells within the workbook
*/
public abstract String[] getRangeNames();
/**
* Determines whether the sheet is protected
*
* @return TRUE if the workbook is protected, FALSE otherwise
*/
public abstract boolean isProtected();
/**
* Parses the excel file.
* If the workbook is password protected a PasswordException is thrown
* in case consumers of the API wish to handle this in a particular way
*
* @exception BiffException
* @exception PasswordException
*/
protected abstract void parse() throws BiffException, PasswordException;
/**
* Closes this workbook, and frees makes any memory allocated available
* for garbage collection
*/
public abstract void close();
/**
* A factory method which takes in an excel file and reads in the contents.
*
* @exception IOException
* @exception BiffException
* @param file the excel 97 spreadsheet to parse
* @return a workbook instance
*/
public static Workbook getWorkbook(java.io.File file)
throws IOException, BiffException
{
return getWorkbook(file, new WorkbookSettings());
}
/**
* A factory method which takes in an excel file and reads in the contents.
*
* @exception IOException
* @exception BiffException
* @param file the excel 97 spreadsheet to parse
* @param ws the settings for the workbook
* @return a workbook instance
*/
public static Workbook getWorkbook(java.io.File file, WorkbookSettings ws)
throws IOException, BiffException
{
FileInputStream fis = new FileInputStream(file);
// Always close down the input stream, regardless of whether or not the
// file can be parsed. Thanks to Steve Hahn for this
File dataFile = null;
try
{
dataFile = new File(fis, ws);
}
catch (IOException e)
{
fis.close();
throw e;
}
catch (BiffException e)
{
fis.close();
throw e;
}
fis.close();
Workbook workbook = new WorkbookParser(dataFile, ws);
workbook.parse();
return workbook;
}
/**
* A factory method which takes in an excel file and reads in the contents.
*
* @param is an open stream which is the the excel 97 spreadsheet to parse
* @return a workbook instance
* @exception IOException
* @exception BiffException
*/
public static Workbook getWorkbook(InputStream is)
throws IOException, BiffException
{
return getWorkbook(is, new WorkbookSettings());
}
/**
* A factory method which takes in an excel file and reads in the contents.
*
* @param is an open stream which is the the excel 97 spreadsheet to parse
* @param ws the settings for the workbook
* @return a workbook instance
* @exception IOException
* @exception BiffException
*/
public static Workbook getWorkbook(InputStream is, WorkbookSettings ws)
throws IOException, BiffException
{
File dataFile = new File(is, ws);
Workbook workbook = new WorkbookParser(dataFile, ws);
workbook.parse();
return workbook;
}
/**
* Creates a writable workbook with the given file name
*
* @param file the workbook to copy
* @return a writable workbook
* @exception IOException
*/
public static WritableWorkbook createWorkbook(java.io.File file)
throws IOException
{
return createWorkbook(file, new WorkbookSettings());
}
/**
* Creates a writable workbook with the given file name
*
* @param file the file to copy from
* @param ws the global workbook settings
* @return a writable workbook
* @exception IOException
*/
public static WritableWorkbook createWorkbook(java.io.File file,
WorkbookSettings ws)
throws IOException
{
FileOutputStream fos = new FileOutputStream(file);
WritableWorkbook w = new WritableWorkbookImpl(fos, true, ws);
return w;
}
/**
* Creates a writable workbook with the given filename as a copy of
* the workbook passed in. Once created, the contents of the writable
* workbook may be modified
*
* @param file the output file for the copy
* @param in the workbook to copy
* @return a writable workbook
* @exception IOException
*/
public static WritableWorkbook createWorkbook(java.io.File file,
Workbook in)
throws IOException
{
return createWorkbook(file, in, new WorkbookSettings());
}
/**
* Creates a writable workbook with the given filename as a copy of
* the workbook passed in. Once created, the contents of the writable
* workbook may be modified
*
* @param file the output file for the copy
* @param in the workbook to copy
* @param ws the configuration for this workbook
* @return a writable workbook
*/
public static WritableWorkbook createWorkbook(java.io.File file,
Workbook in,
WorkbookSettings ws)
throws IOException
{
FileOutputStream fos = new FileOutputStream(file);
WritableWorkbook w = new WritableWorkbookImpl(fos, in, true, ws);
return w;
}
/**
* Creates a writable workbook as a copy of
* the workbook passed in. Once created, the contents of the writable
* workbook may be modified
*
* @param os the stream to write to
* @param in the workbook to copy
* @return a writable workbook
* @exception IOException
*/
public static WritableWorkbook createWorkbook(OutputStream os,
Workbook in)
throws IOException
{
return createWorkbook(os, in, ((WorkbookParser) in).getSettings());
}
/**
* Creates a writable workbook as a copy of
* the workbook passed in. Once created, the contents of the writable
* workbook may be modified
*
* @param os the output stream to write to
* @param in the workbook to copy
* @param ws the configuration for this workbook
* @return a writable workbook
* @exception IOException
*/
public static WritableWorkbook createWorkbook(OutputStream os,
Workbook in,
WorkbookSettings ws)
throws IOException
{
WritableWorkbook w = new WritableWorkbookImpl(os, in, false, ws);
return w;
}
/**
* Creates a writable workbook. When the workbook is closed,
* it will be streamed directly to the output stream. In this
* manner, a generated excel spreadsheet can be passed from
* a servlet to the browser over HTTP
*
* @param os the output stream
* @return the writable workbook
* @exception IOException
*/
public static WritableWorkbook createWorkbook(OutputStream os)
throws IOException
{
return createWorkbook(os, new WorkbookSettings());
}
/**
* Creates a writable workbook. When the workbook is closed,
* it will be streamed directly to the output stream. In this
* manner, a generated excel spreadsheet can be passed from
* a servlet to the browser over HTTP
*
* @param os the output stream
* @param ws the configuration for this workbook
* @return the writable workbook
* @exception IOException
*/
public static WritableWorkbook createWorkbook(OutputStream os,
WorkbookSettings ws)
throws IOException
{
WritableWorkbook w = new WritableWorkbookImpl(os, false, ws);
return w;
}
}
| [
"[email protected]"
] | |
323069234e746e85dbb240857effb2653bcef44e | 7e80069f4ba764c4e94055869f9a80aa3ac63a9e | /src/main/java/cn/cindy/quote/Employee.java | 3c69a67300a11d62b28e125a105f3c2b1444f71c | [] | no_license | caowenyan/cwy | 31030c25ab9134e521d7ccbd8f52d869a7b789d3 | 56ae6f9fc6c504df9912815c4eeed94665282889 | refs/heads/master | 2020-12-29T02:39:16.406230 | 2018-07-07T15:52:30 | 2018-07-07T15:52:30 | 30,817,275 | 2 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,006 | java | package cn.cindy.quote;
import org.apache.commons.lang3.StringUtils;
import java.lang.reflect.Field;
public class Employee {
private String name=null;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public Employee(){}
public Employee(String n){
this.name=n;
}
//将两个Employee对象交换
public static void swap(Employee e1,Employee e2){
Employee temp=e1;
e1=e2;
e2=temp;
System.out.println(e1.name+" "+e2.name); //打印结果:李四 张三
}
//主函数
public static void main(String[] args) throws Exception{
System.out.println(StringUtils.leftPad("1", 5, '0'));
Employee worker=new Employee("张三");
Employee manager=new Employee("李四");
swap(worker,manager);
System.out.println(worker.name+" "+manager.name); //打印结果仍然是: 张三 李四
}
}
| [
"[email protected]"
] | |
8bc68cef8c5caace263bc5fb978994a767e49c66 | 76f16f829caac1435a8c58b6b564e05db65f12dd | /src/main/java/org/frc2851/data/type/PlaceholderType.java | f72094d35684a8995ad9085d59bcf034ae962512 | [] | no_license | CrevolutionRoboticsProgramming/VisionCommunicatorPlugin | 2e74956594ca8288ccc9c61d22c33610ab1cb791 | e4cbff9187736ac516531a3eeb6ffc715786df94 | refs/heads/master | 2020-07-22T11:27:15.670230 | 2019-09-22T18:45:45 | 2019-09-22T18:45:45 | 207,184,343 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 816 | java | package org.frc2851.data.type;
import edu.wpi.first.shuffleboard.api.data.ComplexDataType;
import org.frc2851.data.PlaceholderData;
import java.util.Map;
import java.util.function.Function;
/**
* Represents data of the {@link PlaceholderData} type.
*/
public final class PlaceholderType extends ComplexDataType<PlaceholderData>
{
public static final PlaceholderType Instance = new PlaceholderType();
private static final String TYPE_NAME = "PlaceholderData";
private PlaceholderType()
{
super(TYPE_NAME, PlaceholderData.class);
}
@Override
public Function<Map<String, Object>, PlaceholderData> fromMap()
{
return map -> new PlaceholderData();
}
@Override
public PlaceholderData getDefaultValue()
{
return new PlaceholderData();
}
}
| [
"[email protected]"
] | |
eb995597b4f4a3b644c4911a574485543e2bd688 | 1eaf9e35aa9fd2464f32cfa818a260ab97a6a078 | /src/main/java/shop/book/PaperBook.java | 3de9b3b149a59839f57e3d64ae1332b0ac147c24 | [] | no_license | kacperdob/Empikv2 | 44b360d8176e47be4d7afed82fc7fc0cf98f8bc5 | 7d23b2f2c016e049b77f714ebbb3c42972b3648d | refs/heads/master | 2022-04-03T22:22:04.317634 | 2020-02-17T12:27:47 | 2020-02-17T12:27:47 | 237,267,888 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 274 | java | package shop.book;
import lombok.Getter;
import java.math.BigDecimal;
@Getter
public class PaperBook extends Book{
public PaperBook(long id, String name, BigDecimal price, String author, int pageCounter) {
super(id, name, price, author, pageCounter);
}
}
| [
"[email protected]"
] | |
029751361bb047bb3ad8d91ef43b60698cc629da | 4e1759b604516c067875f1254b6d67216efa1bbb | /weixinpojo/src/main/java/com/yinkai/entities/ImageExample.java | 770508a9c59caca4019eb176bbd11cdd2858337c | [] | no_license | suoyiguke/weixinparent | 92a16922993cf682115f23802e81143a68eb2971 | d374b2a02ac0ee341969030a05fc4de3d3e2180b | refs/heads/master | 2021-05-08T12:41:18.691106 | 2018-02-02T13:07:33 | 2018-02-02T13:07:33 | 119,958,912 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 11,845 | java | package com.yinkai.entities;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class ImageExample implements Serializable {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public ImageExample() {
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));
}
public Criteria andImageIdIsNull() {
addCriterion("image_id is null");
return (Criteria) this;
}
public Criteria andImageIdIsNotNull() {
addCriterion("image_id is not null");
return (Criteria) this;
}
public Criteria andImageIdEqualTo(Integer value) {
addCriterion("image_id =", value, "imageId");
return (Criteria) this;
}
public Criteria andImageIdNotEqualTo(Integer value) {
addCriterion("image_id <>", value, "imageId");
return (Criteria) this;
}
public Criteria andImageIdGreaterThan(Integer value) {
addCriterion("image_id >", value, "imageId");
return (Criteria) this;
}
public Criteria andImageIdGreaterThanOrEqualTo(Integer value) {
addCriterion("image_id >=", value, "imageId");
return (Criteria) this;
}
public Criteria andImageIdLessThan(Integer value) {
addCriterion("image_id <", value, "imageId");
return (Criteria) this;
}
public Criteria andImageIdLessThanOrEqualTo(Integer value) {
addCriterion("image_id <=", value, "imageId");
return (Criteria) this;
}
public Criteria andImageIdIn(List<Integer> values) {
addCriterion("image_id in", values, "imageId");
return (Criteria) this;
}
public Criteria andImageIdNotIn(List<Integer> values) {
addCriterion("image_id not in", values, "imageId");
return (Criteria) this;
}
public Criteria andImageIdBetween(Integer value1, Integer value2) {
addCriterion("image_id between", value1, value2, "imageId");
return (Criteria) this;
}
public Criteria andImageIdNotBetween(Integer value1, Integer value2) {
addCriterion("image_id not between", value1, value2, "imageId");
return (Criteria) this;
}
public Criteria andTopicIdIsNull() {
addCriterion("topic_id is null");
return (Criteria) this;
}
public Criteria andTopicIdIsNotNull() {
addCriterion("topic_id is not null");
return (Criteria) this;
}
public Criteria andTopicIdEqualTo(Integer value) {
addCriterion("topic_id =", value, "topicId");
return (Criteria) this;
}
public Criteria andTopicIdNotEqualTo(Integer value) {
addCriterion("topic_id <>", value, "topicId");
return (Criteria) this;
}
public Criteria andTopicIdGreaterThan(Integer value) {
addCriterion("topic_id >", value, "topicId");
return (Criteria) this;
}
public Criteria andTopicIdGreaterThanOrEqualTo(Integer value) {
addCriterion("topic_id >=", value, "topicId");
return (Criteria) this;
}
public Criteria andTopicIdLessThan(Integer value) {
addCriterion("topic_id <", value, "topicId");
return (Criteria) this;
}
public Criteria andTopicIdLessThanOrEqualTo(Integer value) {
addCriterion("topic_id <=", value, "topicId");
return (Criteria) this;
}
public Criteria andTopicIdIn(List<Integer> values) {
addCriterion("topic_id in", values, "topicId");
return (Criteria) this;
}
public Criteria andTopicIdNotIn(List<Integer> values) {
addCriterion("topic_id not in", values, "topicId");
return (Criteria) this;
}
public Criteria andTopicIdBetween(Integer value1, Integer value2) {
addCriterion("topic_id between", value1, value2, "topicId");
return (Criteria) this;
}
public Criteria andTopicIdNotBetween(Integer value1, Integer value2) {
addCriterion("topic_id not between", value1, value2, "topicId");
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 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);
}
}
} | [
"[email protected]"
] | |
07bbfb0e073dd50a2ed77194e3d0726357ba2180 | df15108a3563a0a2ec5b063762b30f351f067c35 | /glossator/src/main/java/com/kritarie/glossator/binder/FactoryBinder.java | d4d42c4708e6da31b482c583a9d71d928c866793 | [] | no_license | Kritarie/Glossator | d0804f221a1772bc04a4b6fdd245380febbc81d8 | 10f3cbbeacfbad69340e2848e0fb6b498b752060 | refs/heads/master | 2021-01-10T16:44:18.794113 | 2016-01-10T04:36:05 | 2016-01-10T04:36:05 | 47,955,569 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 522 | java | package com.kritarie.glossator.binder;
import android.view.ViewGroup;
import com.kritarie.glossator.GlossaryViewHolder;
/**
* Created by Sean on 12/11/2015.
*/
public class FactoryBinder<T> extends GlossaryBinder<T> {
private HolderFactory<T> mFactory;
public FactoryBinder(Class<T> modelClass, HolderFactory<T> factory) {
super(modelClass);
mFactory = factory;
}
@Override
public GlossaryViewHolder<T> create(ViewGroup parent) {
return mFactory.create(parent);
}
}
| [
"[email protected]"
] | |
14101c527519f0c54a6796e283284ec63a875aa3 | dde3de70797c28ae0548460cb94ee0006ff0aaf2 | /Build/Android/src/com/epicgames/ue4/DownloadShim.java | 0ce75dea42ce86c5ca0fec6b14f3be0f76dafcac | [] | no_license | APTist/ProjectShooter | ae02d12b65452ff6686647087389c415841b9fc6 | 49de18fe081738caaf654e8e9bddfd44997878ea | refs/heads/main | 2023-07-28T02:04:43.552967 | 2021-09-13T08:19:46 | 2021-09-13T08:19:46 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,432 | java | package com.epicgames.ue4;
import com.Artist.ShooterSecond.OBBDownloaderService;
import com.Artist.ShooterSecond.DownloaderActivity;
import android.app.Activity;
import com.google.android.vending.expansion.downloader.Helpers;
import com.Artist.ShooterSecond.OBBData;
public class DownloadShim
{
public static OBBDownloaderService DownloaderService;
public static DownloaderActivity DownloadActivity;
public static Class<DownloaderActivity> GetDownloaderType() { return DownloaderActivity.class; }
public static boolean expansionFilesDelivered(Activity activity, int version) {
for (OBBData.XAPKFile xf : OBBData.xAPKS) {
String fileName = Helpers.getExpansionAPKFileName(activity, xf.mIsMain, Integer.toString(version), OBBData.AppType);
GameActivity.Log.debug("Checking for file : " + fileName);
String fileForNewFile = Helpers.generateSaveFileName(activity, fileName);
String fileForDevFile = Helpers.generateSaveFileNameDevelopment(activity, fileName);
GameActivity.Log.debug("which is really being resolved to : " + fileForNewFile + "\n Or : " + fileForDevFile);
if (Helpers.doesFileExist(activity, fileName, xf.mFileSize, false)) {
GameActivity.Log.debug("Found OBB here: " + fileForNewFile);
}
else if (Helpers.doesFileExistDev(activity, fileName, xf.mFileSize, false)) {
GameActivity.Log.debug("Found OBB here: " + fileForDevFile);
}
else return false;
}
return true;
}
}
| [
"[email protected]"
] | |
575b25a3a897a0437dc095b3f4ad0ae1e63324a9 | 240b0a05e4c63e6557bf603450bb2f8287d87e00 | /project/src/main/java/repository/impl/EmployeeRepositoryImpl.java | 29cfc389ac1e56107bf306c08db1607995cb209d | [
"MIT"
] | permissive | nasrmohammad4804/hw15-console-Bank-Application | 5b4ac474af69576615331260bdfb3a2341202b02 | 310a95d1234b3ae6b4809306ccb96b5b61de6100 | refs/heads/master | 2023-08-10T20:20:23.791335 | 2021-10-01T17:32:06 | 2021-10-01T17:32:06 | 408,320,231 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 491 | java | package repository.impl;
import base.repository.impl.BaseRepositoryImpl;
import domain.Employee;
import repository.EmployeeRepository;
import javax.persistence.EntityManager;
public class EmployeeRepositoryImpl extends BaseRepositoryImpl<Employee,Long>
implements EmployeeRepository {
public EmployeeRepositoryImpl(EntityManager entityManager) {
super(entityManager);
}
@Override
public Class<Employee> getEntityClass() {
return Employee.class;
}
}
| [
"[email protected]"
] | |
c1febae4696db03c4982e812ddb3011b58cebccb | 208ba847cec642cdf7b77cff26bdc4f30a97e795 | /di/da/src/main/java/org.wp.da/models/ReaderPost.java | 52cf1928dbb4b416aff3fcc4e9a4c19727a763e6 | [] | no_license | kageiit/perf-android-large | ec7c291de9cde2f813ed6573f706a8593be7ac88 | 2cbd6e74837a14ae87c1c4d1d62ac3c35df9e6f8 | refs/heads/master | 2021-01-12T14:00:19.468063 | 2016-09-27T13:10:42 | 2016-09-27T13:10:42 | 69,685,305 | 0 | 0 | null | 2016-09-30T16:59:49 | 2016-09-30T16:59:48 | null | UTF-8 | Java | false | false | 23,617 | java | package org.wp.da.models;
import android.text.TextUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.wp.da.ui.reader.ReaderConstants;
import org.wp.da.ui.reader.models.ReaderBlogIdPostId;
import org.wp.da.ui.reader.utils.ImageSizeMap;
import org.wp.da.ui.reader.utils.ReaderImageScanner;
import org.wp.da.ui.reader.utils.ReaderUtils;
import org.wp.da.util.DateTimeUtils;
import org.wp.da.util.GravatarUtils;
import org.wp.da.util.HtmlUtils;
import org.wp.da.util.JSONUtils;
import org.wp.da.util.StringUtils;
import java.text.BreakIterator;
import java.util.Iterator;
public class ReaderPost {
private String pseudoId;
public long postId;
public long blogId;
public long feedId;
public long feedItemId;
public long authorId;
private String title;
private String text;
private String excerpt;
private String authorName;
private String authorFirstName;
private String blogName;
private String blogUrl;
private String postAvatar;
private String primaryTag; // most popular tag on this post based on usage in blog
private String secondaryTag; // second most popular tag on this post based on usage in blog
public double sortIndex;
private String published;
private String url;
private String shortUrl;
private String featuredImage;
private String featuredVideo;
public int numReplies; // includes comments, trackbacks & pingbacks
public int numLikes;
public boolean isLikedByCurrentUser;
public boolean isFollowedByCurrentUser;
public boolean isCommentsOpen;
public boolean isExternal;
public boolean isPrivate;
public boolean isVideoPress;
public boolean isJetpack;
private String attachmentsJson;
private String discoverJson;
private String format;
public long xpostPostId;
public long xpostBlogId;
public static ReaderPost fromJson(JSONObject json) {
if (json == null) {
throw new IllegalArgumentException("null json post");
}
ReaderPost post = new ReaderPost();
post.postId = json.optLong("ID");
post.blogId = json.optLong("site_ID");
post.feedId = json.optLong("feed_ID");
post.feedItemId = json.optLong("feed_item_ID");
if (json.has("pseudo_ID")) {
post.pseudoId = JSONUtils.getString(json, "pseudo_ID"); // read/ endpoint
} else {
post.pseudoId = JSONUtils.getString(json, "global_ID"); // sites/ endpoint
}
// remove HTML from the excerpt
post.excerpt = HtmlUtils.fastStripHtml(JSONUtils.getString(json, "excerpt")).trim();
post.text = JSONUtils.getString(json, "content");
post.title = JSONUtils.getStringDecoded(json, "title");
post.format = JSONUtils.getString(json, "format");
post.url = JSONUtils.getString(json, "URL");
post.shortUrl = JSONUtils.getString(json, "short_URL");
post.setBlogUrl(JSONUtils.getString(json, "site_URL"));
post.numLikes = json.optInt("like_count");
post.isLikedByCurrentUser = JSONUtils.getBool(json, "i_like");
post.isFollowedByCurrentUser = JSONUtils.getBool(json, "is_following");
post.isExternal = JSONUtils.getBool(json, "is_external");
post.isPrivate = JSONUtils.getBool(json, "site_is_private");
post.isJetpack = JSONUtils.getBool(json, "is_jetpack");
JSONObject jsonDiscussion = json.optJSONObject("discussion");
if (jsonDiscussion != null) {
post.isCommentsOpen = JSONUtils.getBool(jsonDiscussion, "comments_open");
post.numReplies = jsonDiscussion.optInt("comment_count");
} else {
post.isCommentsOpen = JSONUtils.getBool(json, "comments_open");
post.numReplies = json.optInt("comment_count");
}
// parse the author section
assignAuthorFromJson(post, json.optJSONObject("author"));
post.featuredImage = JSONUtils.getString(json, "featured_image");
post.blogName = JSONUtils.getStringDecoded(json, "site_name");
post.published = JSONUtils.getString(json, "date");
// sort index determines how posts are sorted - this is a "score" for search results,
// liked date for liked posts, and published date for all others
if (json.has("score")) {
post.sortIndex = json.optDouble("score");
} else if (json.has("date_liked")) {
String likeDate = JSONUtils.getString(json, "date_liked");
post.sortIndex = DateTimeUtils.iso8601ToTimestamp(likeDate);
} else {
post.sortIndex = DateTimeUtils.iso8601ToTimestamp(post.published);
}
// if the post is untitled, make up a title from the excerpt
if (!post.hasTitle() && post.hasExcerpt()) {
post.title = extractTitle(post.excerpt, 50);
}
// remove html from title (rare, but does happen)
if (post.hasTitle() && post.title.contains("<") && post.title.contains(">")) {
post.title = HtmlUtils.stripHtml(post.title);
}
// parse the tags section
assignTagsFromJson(post, json.optJSONObject("tags"));
// parse the attachments
JSONObject jsonAttachments = json.optJSONObject("attachments");
if (jsonAttachments != null && jsonAttachments.length() > 0) {
post.attachmentsJson = jsonAttachments.toString();
}
// site metadata - returned when ?meta=site was added to the request
JSONObject jsonSite = JSONUtils.getJSONChild(json, "meta/data/site");
if (jsonSite != null) {
post.blogId = jsonSite.optInt("ID");
post.blogName = JSONUtils.getString(jsonSite, "name");
post.setBlogUrl(JSONUtils.getString(jsonSite, "URL"));
post.isPrivate = JSONUtils.getBool(jsonSite, "is_private");
// TODO: as of 29-Sept-2014, this is broken - endpoint returns false when it should be true
post.isJetpack = JSONUtils.getBool(jsonSite, "jetpack");
}
// "discover" posts
JSONObject jsonDiscover = json.optJSONObject("discover_metadata");
if (jsonDiscover != null) {
post.setDiscoverJson(jsonDiscover.toString());
}
// xpost info
assignXpostIdsFromJson(post, json.optJSONArray("metadata"));
// if there's no featured image, check if featured media has been set - this is sometimes
// a YouTube or Vimeo video, in which case store it as the featured video so we can treat
// it as a video
if (!post.hasFeaturedImage()) {
JSONObject jsonMedia = json.optJSONObject("featured_media");
if (jsonMedia != null && jsonMedia.length() > 0) {
String mediaUrl = JSONUtils.getString(jsonMedia, "uri");
if (!TextUtils.isEmpty(mediaUrl)) {
String type = JSONUtils.getString(jsonMedia, "type");
boolean isVideo = (type != null && type.equals("video"));
if (isVideo) {
post.featuredVideo = mediaUrl;
} else {
post.featuredImage = mediaUrl;
}
}
}
}
// if the post still doesn't have a featured image but we have attachment data, check whether
// we can find a suitable featured image from the attachments
if (!post.hasFeaturedImage() && post.hasAttachments()) {
post.featuredImage = new ImageSizeMap(post.attachmentsJson)
.getLargestImageUrl(ReaderConstants.MIN_FEATURED_IMAGE_WIDTH);
}
// if we *still* don't have a featured image but the text contains an IMG tag, check whether
// we can find a suitable image from the text
if (!post.hasFeaturedImage() && post.hasText() && post.text.contains("<img")) {
post.featuredImage = new ReaderImageScanner(post.text, post.isPrivate)
.getLargestImage(ReaderConstants.MIN_FEATURED_IMAGE_WIDTH);
}
return post;
}
/*
* assigns cross post blog & post IDs from post's metadata section
* "metadata": [
* {
* "id": "21192",
* "key": "xpost_origin",
* "value": "11326809:18427"
* }
* ],
*/
private static void assignXpostIdsFromJson(ReaderPost post, JSONArray jsonMetadata) {
if (jsonMetadata == null) return;
for (int i = 0; i < jsonMetadata.length(); i++) {
JSONObject jsonMetaItem = jsonMetadata.optJSONObject(i);
String metaKey = jsonMetaItem.optString("key");
if (!TextUtils.isEmpty(metaKey) && metaKey.equals("xpost_origin")) {
String value = jsonMetaItem.optString("value");
if (!TextUtils.isEmpty(value) && value.contains(":")) {
String[] valuePair = value.split(":");
if (valuePair.length == 2) {
post.xpostBlogId = StringUtils.stringToLong(valuePair[0]);
post.xpostPostId = StringUtils.stringToLong(valuePair[1]);
return;
}
}
}
}
}
/*
* assigns author-related info to the passed post from the passed JSON "author" object
*/
private static void assignAuthorFromJson(ReaderPost post, JSONObject jsonAuthor) {
if (jsonAuthor == null) return;
post.authorName = JSONUtils.getStringDecoded(jsonAuthor, "name");
post.authorFirstName = JSONUtils.getStringDecoded(jsonAuthor, "first_name");
post.postAvatar = JSONUtils.getString(jsonAuthor, "avatar_URL");
post.authorId = jsonAuthor.optLong("ID");
// site_URL doesn't exist for /sites/ endpoints, so get it from the author
if (TextUtils.isEmpty(post.blogUrl)) {
post.setBlogUrl(JSONUtils.getString(jsonAuthor, "URL"));
}
}
/*
* assigns primary/secondary tags to the passed post from the passed JSON "tags" object
*/
private static void assignTagsFromJson(ReaderPost post, JSONObject jsonTags) {
if (jsonTags == null) {
return;
}
Iterator<String> it = jsonTags.keys();
if (!it.hasNext()) {
return;
}
// most popular tag & second most popular tag, based on usage count on this blog
String mostPopularTag = null;
String nextMostPopularTag = null;
int popularCount = 0;
while (it.hasNext()) {
JSONObject jsonThisTag = jsonTags.optJSONObject(it.next());
// if the number of posts on this blog that use this tag is higher than previous,
// set this as the most popular tag, and set the second most popular tag to
// the current most popular tag
int postCount = jsonThisTag.optInt("post_count");
if (postCount > popularCount) {
nextMostPopularTag = mostPopularTag;
mostPopularTag = JSONUtils.getStringDecoded(jsonThisTag, "slug");
popularCount = postCount;
}
}
// don't set primary tag if one is already set
if (!post.hasPrimaryTag()) {
post.setPrimaryTag(mostPopularTag);
}
post.setSecondaryTag(nextMostPopularTag);
}
/*
* extracts a title from a post's excerpt - used when the post has no title
*/
private static String extractTitle(final String excerpt, int maxLen) {
if (TextUtils.isEmpty(excerpt))
return null;
if (excerpt.length() < maxLen)
return excerpt.trim();
StringBuilder result = new StringBuilder();
BreakIterator wordIterator = BreakIterator.getWordInstance();
wordIterator.setText(excerpt);
int start = wordIterator.first();
int end = wordIterator.next();
int totalLen = 0;
while (end != BreakIterator.DONE) {
String word = excerpt.substring(start, end);
result.append(word);
totalLen += word.length();
if (totalLen >= maxLen)
break;
start = end;
end = wordIterator.next();
}
if (totalLen==0)
return null;
return result.toString().trim() + "...";
}
// --------------------------------------------------------------------------------------------
public String getAuthorName() {
return StringUtils.notNullStr(authorName);
}
public void setAuthorName(String name) {
this.authorName = StringUtils.notNullStr(name);
}
public String getAuthorFirstName() {
return StringUtils.notNullStr(authorFirstName);
}
public void setAuthorFirstName(String name) {
this.authorFirstName = StringUtils.notNullStr(name);
}
public String getTitle() {
return StringUtils.notNullStr(title);
}
public void setTitle(String title) {
this.title = StringUtils.notNullStr(title);
}
public String getText() {
return StringUtils.notNullStr(text);
}
public void setText(String text) {
this.text = StringUtils.notNullStr(text);
}
public String getExcerpt() {
return StringUtils.notNullStr(excerpt);
}
public void setExcerpt(String excerpt) {
this.excerpt = StringUtils.notNullStr(excerpt);
}
// https://codex.wordpress.org/Post_Formats
public String getFormat() {
return StringUtils.notNullStr(format);
}
public void setFormat(String format) {
this.format = StringUtils.notNullStr(format);
}
public boolean isGallery() {
return format != null && format.equals("gallery");
}
public String getUrl() {
return StringUtils.notNullStr(url);
}
public void setUrl(String url) {
this.url = StringUtils.notNullStr(url);
}
public String getShortUrl() {
return StringUtils.notNullStr(shortUrl);
}
public void setShortUrl(String url) {
this.shortUrl = StringUtils.notNullStr(url);
}
public boolean hasShortUrl() {
return !TextUtils.isEmpty(shortUrl);
}
public String getFeaturedImage() {
return StringUtils.notNullStr(featuredImage);
}
public void setFeaturedImage(String featuredImage) {
this.featuredImage = StringUtils.notNullStr(featuredImage);
}
public String getFeaturedVideo() {
return StringUtils.notNullStr(featuredVideo);
}
public void setFeaturedVideo(String featuredVideo) {
this.featuredVideo = StringUtils.notNullStr(featuredVideo);
}
public String getBlogName() {
return StringUtils.notNullStr(blogName);
}
public void setBlogName(String blogName) {
this.blogName = StringUtils.notNullStr(blogName);
}
public String getBlogUrl() {
return StringUtils.notNullStr(blogUrl);
}
public void setBlogUrl(String blogUrl) {
this.blogUrl = StringUtils.notNullStr(blogUrl);
}
public String getPostAvatar() {
return StringUtils.notNullStr(postAvatar);
}
public void setPostAvatar(String postAvatar) {
this.postAvatar = StringUtils.notNullStr(postAvatar);
}
public String getPseudoId() {
return StringUtils.notNullStr(pseudoId);
}
public void setPseudoId(String pseudoId) {
this.pseudoId = StringUtils.notNullStr(pseudoId);
}
public String getPublished() {
return StringUtils.notNullStr(published);
}
public void setPublished(String published) {
this.published = StringUtils.notNullStr(published);
}
public String getPrimaryTag() {
return StringUtils.notNullStr(primaryTag);
}
public void setPrimaryTag(String tagName) {
// this is a bit of a hack to avoid setting the primary tag to one of the defaults
if (!ReaderTag.isDefaultTagTitle(tagName)) {
this.primaryTag = StringUtils.notNullStr(tagName);
}
}
boolean hasPrimaryTag() {
return !TextUtils.isEmpty(primaryTag);
}
public String getSecondaryTag() {
return StringUtils.notNullStr(secondaryTag);
}
public void setSecondaryTag(String tagName) {
if (!ReaderTag.isDefaultTagTitle(tagName)) {
this.secondaryTag = StringUtils.notNullStr(tagName);
}
}
/*
* attachments are stored as the actual JSON to avoid having a separate table for
* them, may need to revisit this if/when attachments become more important
*/
public String getAttachmentsJson() {
return StringUtils.notNullStr(attachmentsJson);
}
public void setAttachmentsJson(String json) {
attachmentsJson = StringUtils.notNullStr(json);
}
public boolean hasAttachments() {
return !TextUtils.isEmpty(attachmentsJson);
}
/*
* "discover" posts also store the actual JSON
*/
public String getDiscoverJson() {
return StringUtils.notNullStr(discoverJson);
}
public void setDiscoverJson(String json) {
discoverJson = StringUtils.notNullStr(json);
}
public boolean isDiscoverPost() {
return !TextUtils.isEmpty(discoverJson);
}
private transient ReaderPostDiscoverData discoverData;
public ReaderPostDiscoverData getDiscoverData() {
if (discoverData == null && !TextUtils.isEmpty(discoverJson)) {
try {
discoverData = new ReaderPostDiscoverData(new JSONObject(discoverJson));
} catch (JSONException e) {
return null;
}
}
return discoverData;
}
public boolean hasText() {
return !TextUtils.isEmpty(text);
}
public boolean hasUrl() {
return !TextUtils.isEmpty(url);
}
public boolean hasExcerpt() {
return !TextUtils.isEmpty(excerpt);
}
public boolean hasFeaturedImage() {
return !TextUtils.isEmpty(featuredImage);
}
public boolean hasFeaturedVideo() {
return !TextUtils.isEmpty(featuredVideo);
}
public boolean hasPostAvatar() {
return !TextUtils.isEmpty(postAvatar);
}
public boolean hasBlogName() {
return !TextUtils.isEmpty(blogName);
}
public boolean hasAuthorName() {
return !TextUtils.isEmpty(authorName);
}
public boolean hasAuthorFirstName() {
return !TextUtils.isEmpty(authorFirstName);
}
public boolean hasTitle() {
return !TextUtils.isEmpty(title);
}
public boolean hasBlogUrl() {
return !TextUtils.isEmpty(blogUrl);
}
/*
* returns true if this post is from a WordPress blog
*/
public boolean isWP() {
return !isExternal;
}
/*
* returns true if this is a cross-post
*/
public boolean isXpost() {
return xpostBlogId != 0 && xpostPostId != 0;
}
/*
* returns true if the passed post appears to be the same as this one - used when posts are
* retrieved to determine which ones are new/changed/unchanged
*/
public boolean isSamePost(ReaderPost post) {
return post != null
&& post.blogId == this.blogId
&& post.postId == this.postId
&& post.feedId == this.feedId
&& post.feedItemId == this.feedItemId
&& post.numLikes == this.numLikes
&& post.numReplies == this.numReplies
&& post.isFollowedByCurrentUser == this.isFollowedByCurrentUser
&& post.isLikedByCurrentUser == this.isLikedByCurrentUser
&& post.isCommentsOpen == this.isCommentsOpen
&& post.getTitle().equals(this.getTitle())
&& post.getExcerpt().equals(this.getExcerpt())
&& post.getText().equals(this.getText());
}
public boolean hasIds(ReaderBlogIdPostId ids) {
return ids != null
&& ids.getBlogId() == this.blogId
&& ids.getPostId() == this.postId;
}
/*
* liking is enabled for all wp.com and jp posts with the exception of discover posts
*/
public boolean canLikePost() {
return (isWP() || isJetpack) && (!isDiscoverPost());
}
/****
* the following are transient variables - not stored in the db or returned in the json - whose
* sole purpose is to cache commonly-used values for the post that speeds up using them inside
* adapters
****/
/*
* returns the featured image url as a photon url set to the passed width/height
*/
private transient String featuredImageForDisplay;
public String getFeaturedImageForDisplay(int width, int height) {
if (featuredImageForDisplay == null) {
if (!hasFeaturedImage()) {
featuredImageForDisplay = "";
} else {
featuredImageForDisplay = ReaderUtils.getResizedImageUrl(featuredImage, width, height, isPrivate);
}
}
return featuredImageForDisplay;
}
/*
* returns the avatar url as a photon url set to the passed size
*/
private transient String avatarForDisplay;
public String getPostAvatarForDisplay(int size) {
if (avatarForDisplay == null) {
if (!hasPostAvatar()) {
return "";
}
avatarForDisplay = GravatarUtils.fixGravatarUrl(postAvatar, size);
}
return avatarForDisplay;
}
/*
* returns the blog's blavatar url as a photon url set to the passed size
*/
private transient String blavatarForDisplay;
public String getPostBlavatarForDisplay(int size) {
if (blavatarForDisplay == null) {
if (!hasBlogUrl()) {
return "";
}
blavatarForDisplay = GravatarUtils.blavatarFromUrl(getBlogUrl(), size);
}
return blavatarForDisplay;
}
/*
* converts iso8601 published date to an actual java date
*/
private transient java.util.Date dtPublished;
public java.util.Date getDatePublished() {
if (dtPublished == null) {
dtPublished = DateTimeUtils.iso8601ToJavaDate(published);
}
return dtPublished;
}
/*
* determine which tag to display for this post
* - no tag if this is a private blog or there is no primary tag for this post
* - primary tag, unless it's the same as the currently selected tag
* - secondary tag if primary tag is the same as the currently selected tag
*/
private transient String tagForDisplay;
public String getTagForDisplay(final String currentTagName) {
if (tagForDisplay == null) {
if (!isPrivate && hasPrimaryTag()) {
if (getPrimaryTag().equalsIgnoreCase(currentTagName)) {
tagForDisplay = getSecondaryTag();
} else {
tagForDisplay = getPrimaryTag();
}
} else {
tagForDisplay = "";
}
}
return tagForDisplay;
}
/*
* used when a unique numeric id is required by an adapter (when hasStableIds() = true)
*/
private transient long stableId;
public long getStableId() {
if (stableId == 0) {
stableId = (pseudoId != null ? pseudoId.hashCode() : 0);
}
return stableId;
}
}
| [
"[email protected]"
] | |
439364346170cacbe71491ca90f5dfa54774bb58 | 89efe8e875762e5823c1ae7e5eb5937004c7fcc1 | /src/main/java/ge/ka/pwrserver/HelloController.java | ccfa08e45f2ab450fbed0da8b4bf62a8c749cec5 | [] | no_license | gehka/pwr-server | a1e9da8a971a1abb41c88763d56fcbe2175532de | 977b9a7ca60199d5395aef6504b8b19b273146da | refs/heads/master | 2023-07-18T23:59:55.178472 | 2021-09-06T18:55:20 | 2021-09-06T18:55:20 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,194 | java | package ge.ka.pwrserver;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import ge.ka.pwrserver.model.Accelerator;
import ge.ka.pwrserver.service.RestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.sql.Timestamp;
@RestController
public class HelloController {
@Autowired
private RestService restService;
@RequestMapping(value="/", method = RequestMethod.GET)
public String home() {
return new Timestamp(System.currentTimeMillis()).toString();
}
@RequestMapping(value="/hello", method = RequestMethod.GET)
public String Hello() throws JsonProcessingException {
Accelerator acc = new Accelerator(0, 11, 22, 33);
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.writeValueAsString(acc);
}
@RequestMapping(value="/acc", method = RequestMethod.GET)
public void getAccs(){
this.restService.doPost();
}
}
| [
"Ns8TZyUbNR8JKFiWyP0A"
] | Ns8TZyUbNR8JKFiWyP0A |
292778f468e22b8cd23811d76082e5e014581b07 | 86647ab1dce23875b27988750c23b8455829f489 | /commonlib/src/main/java/com/dudu/commonlib/xml/JDomXmlDocument.java | 56458c4864084d4583fcf978c1182669003de3fd | [] | no_license | BAT6188/DuDuHome_Home | 1fab41f8fd0456c6fdecb901dc2ee94c269ec516 | 08fa399406a1e19e7738c6767260db4153593f38 | refs/heads/master | 2023-05-28T18:38:36.377138 | 2016-07-25T06:48:06 | 2016-07-25T06:48:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 692 | java | package com.dudu.commonlib.xml;
/**
* Created by Administrator on 2016/2/15.
*/
import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by Eaway on 2016/2/15.
*/
public class JDomXmlDocument {
public Document parserXml(InputStream inputStream) {
Document document = null;
SAXBuilder builder = new SAXBuilder();
try {
document = builder.build(inputStream);
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return document;
}
}
| [
"[email protected]"
] | |
a9e5f49074ec4f0431387a57e568c730b39bab11 | ab513fbacf6f85853cccaa04e295cc8083f51482 | /4th Semester/Systems for Design and Implementation/Laboratory/Book App First/oscar-web/src/main/java/oscar/web/converter/ConverterBaseEntity.java | c36f3034ba024b663f65c1c6a1ff02ab20ff2275 | [] | no_license | galoscar07/college2k16-2k19 | 1ee23e6690e4e5ac3ab9a8ed9792ebbeaecddbf6 | a944bdbc13977aa6782e9eb83a97000aa58a9a93 | refs/heads/master | 2023-01-09T15:59:07.882933 | 2019-06-24T12:06:32 | 2019-06-24T12:06:32 | 167,170,983 | 1 | 1 | null | 2023-01-04T18:21:31 | 2019-01-23T11:22:29 | Python | UTF-8 | Java | false | false | 225 | java | package oscar.web.converter;
import oscar.core.model.BaseEntity;
import oscar.web.dto.BaseDto;
interface ConverterBaseEntity<Model extends BaseEntity<Long>, Dto extends BaseDto>
extends Converter<Model, Dto> {
}
| [
"[email protected]"
] | |
a0c2aa62437cf6233a0042b310642b6143873575 | 1c965c1b1ccdd4d87828472d439f0dc18b8d8314 | /appProyectoFinal/src/java/Model/Ejercicio.java | bf91d7f43daff0a26f23c547a1defb4836ce3249 | [] | no_license | BayronJPR/appProyectoFinal | 5cbd4e61fe4589e1558c28bcfbb0a4fb48d452e0 | c03768af06fa47a2f106089741a61a6107d7c0e3 | refs/heads/master | 2022-03-07T12:32:10.134693 | 2019-08-02T21:21:36 | 2019-08-02T21:21:36 | 198,127,517 | 0 | 0 | null | 2019-08-02T21:22:15 | 2019-07-22T01:53:23 | CSS | UTF-8 | Java | false | false | 1,063 | java | /*
* 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 Model;
/**
*
* @author MrHaksh
*/
public class Ejercicio {
int idEjercicio;
String descripcion;
int log;
public Ejercicio(int idEjercicio, String descripcion, int log) {
this.setIdEjercicio(idEjercicio);
this.setDescripcion(descripcion);
this.setLog(log);
}
public Ejercicio() {
}
public int getIdEjercicio() {
return idEjercicio;
}
public void setIdEjercicio(int idEjercicio) {
this.idEjercicio = idEjercicio;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public int getLog() {
return log;
}
public void setLog(int log) {
this.log = log;
}
}
| [
"MrHaksh@MrHaksh"
] | MrHaksh@MrHaksh |
1cf5a4f0954badee59a8c13eeabe8f47fc06aa71 | 8534ea766585cfbd6986fd845e59a68877ecb15b | /p006b/p007a/p008a/p009a/p010a/p012b/C0215n.java | 09ca10f970e1b8f3561e7b26dc0eaad16c2758c6 | [] | no_license | Shanzid01/NanoTouch | d7af94f2de686f76c2934b9777a92b9949b48e10 | 6d51a44ff8f719f36b880dd8d1112b31ba75bfb4 | refs/heads/master | 2020-04-26T17:39:53.196133 | 2019-03-04T10:23:51 | 2019-03-04T10:23:51 | 173,720,526 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 444 | java | package p006b.p007a.p008a.p009a.p010a.p012b;
import java.io.File;
import java.util.Comparator;
/* compiled from: CommonUtils */
final class C0215n implements Comparator<File> {
C0215n() {
}
public /* synthetic */ int compare(Object obj, Object obj2) {
return m1938a((File) obj, (File) obj2);
}
public int m1938a(File file, File file2) {
return (int) (file.lastModified() - file2.lastModified());
}
}
| [
"[email protected]"
] | |
31cf9b6ad5eed658a42426b2f73456bc42636b05 | e154ba6d0515774b07fd1af979f55efd58e7891c | /src/main/java/org/mdev/revolution/communication/packets/outgoing/newnavigator/SearchResultSet.java | 39891f0f709dd400bffb526cb7bc25c6d31a0bef | [] | no_license | jadenmitchell/Revolution | 1d7e8779a660eb868c8090a7c16c5bdfcaea631d | 82e014d2c794c29de5d7b5d52125fd45f30efa19 | refs/heads/master | 2020-12-11T09:30:02.593119 | 2016-07-31T07:52:25 | 2016-07-31T07:52:25 | 59,269,527 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,220 | java | package org.mdev.revolution.communication.packets.outgoing.newnavigator;
import org.mdev.revolution.communication.packets.outgoing.ServerPacket;
import org.mdev.revolution.communication.packets.outgoing.ServerPacketHeader;
import org.mdev.revolution.database.domain.navigator.FlatCat;
import org.mdev.revolution.game.navigator.NavigatorSearchAllowance;
import org.mdev.revolution.game.navigator.NavigatorViewMode;
import java.util.List;
public class SearchResultSet extends ServerPacket {
public SearchResultSet(String category, String data, List<FlatCat> categories) {
super(ServerPacketHeader.SearchResultSet);
super.writeString(category);
super.writeString(data);
super.writeInt(categories.size());
categories.forEach((c) -> {
super.writeString("lol"); // Category Identifier
super.writeString(c.getPublicName());
super.writeInt(NavigatorSearchAllowance.getIntValue(c.getSearchAllowance()));
super.writeBoolean(false);
super.writeInt(c.getViewMode() == NavigatorViewMode.REGULAR ? 0 : c.getViewMode() == NavigatorViewMode.THUMBNAIL ? 1 : 0);
// TODO: Send the rest of the shit.
});
}
}
| [
"[email protected]"
] | |
3b2234828ae250563add053f44db2bf2599373d0 | 120e8dad2d78043f66423fb2fe714b3b39f68a15 | /java_programming/src/day41_arraylist/practiceGit.java | 11e498188180eccd5f6ee181298cf0d237302304 | [] | no_license | AleksandarBacko/API | 5a7627eea40e4962adc2f7207ebcdd0a0fcf3cae | f28f472a383370d0201ab7b01ed28c4ca8e11a56 | refs/heads/master | 2023-07-11T07:10:53.231922 | 2021-07-28T22:34:07 | 2021-07-28T22:34:07 | 397,413,742 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 191 | java | package day41_arraylist;
public class practiceGit {
public static void main(String[] args) {
System.out.println("git works");
System.out.println("sdaasdasdasd");
}
}
| [
"[email protected]"
] | |
0b2747914e7550ad47f1504d10c232bac668438b | 530e3daf0896f2b8b3deca6483e3b893d0bb5483 | /foodBox/api/src/main/java/org/yokekhei/fsd/capstone/api/repository/OrderRepository.java | d16e7214182c08032cbb69a164de6fe097af9fc7 | [] | no_license | s94shweta/FSDSimplilearnShweta | 37a780ff2e1196c4b7213493141d43c0e4aadef8 | 6f58b54db77886607dd6f7b89d2b6f464e619bd4 | refs/heads/master | 2023-07-07T06:38:43.204002 | 2021-08-08T19:51:09 | 2021-08-08T19:51:09 | 309,680,235 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 633 | java | package org.yokekhei.fsd.capstone.api.repository;
import java.time.LocalDateTime;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.yokekhei.fsd.capstone.api.entity.Order;
import org.yokekhei.fsd.capstone.api.entity.User;
public interface OrderRepository extends JpaRepository<Order, Long> {
List<Order> findAllByCreatedDateTimeBetween(LocalDateTime createdDateTimeStart, LocalDateTime createdDateTimeEnd);
List<Order> findByUser(User user);
List<Order> findByUserAndCreatedDateTimeBetween(User user, LocalDateTime createdDateTimeStart,
LocalDateTime createdDateTimeEnd);
}
| [
"[email protected]"
] | |
2efd4ab4bcef4416d48223f54962c21dd3b980a3 | 01fbb3b01bee6db9e923e0a30174eff165265031 | /COUPON-API-SERVICE/src/main/java/com/easytobuy/CouponApiServiceApplication.java | 1d0e1d1d5705089ea717d54fc8b7ece4176370f4 | [] | no_license | MaruthamSatish/EASYTOBUY_VERSION_0.01 | bdc2adb27d86a2e73fcc81802c426292cf942fde | c71d05d723c5a6d91af1c727fd607bb685384231 | refs/heads/main | 2023-02-09T00:29:50.765235 | 2021-01-01T13:42:34 | 2021-01-01T13:42:34 | 300,364,271 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 414 | java | package com.easytobuy;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
public class CouponApiServiceApplication {
public static void main(String[] args) {
SpringApplication.run(CouponApiServiceApplication.class, args);
}
}
| [
"[email protected]"
] | |
31f8a7f20c55acda2b1cb8de62d192a72762373e | 3a20b07e2f1e148a14782d412d5e05ec82ff209e | /groupeH/trunk/IAgo/src/main/java/myPack/App.java | 59916ca8082ff02309c8028fb42cb033ba354fe6 | [] | no_license | sunye/alma-go | 5683c2cd998112fd2cbadc2b17679adce041832e | 8cffdc3f89f1a4c103b175a58c9b26c41d7e7bb9 | refs/heads/master | 2021-05-25T11:47:26.523567 | 2020-10-14T12:29:05 | 2020-10-14T12:29:05 | 32,451,651 | 0 | 0 | null | 2020-10-14T12:29:07 | 2015-03-18T10:12:34 | HTML | UTF-8 | Java | false | false | 169 | java | package myPack;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
}
}
| [
"mouezapeter@fe6e65f2-260b-11df-8e73-9931e1e0996c"
] | mouezapeter@fe6e65f2-260b-11df-8e73-9931e1e0996c |
e8d870709c1e753891043a9f45a035cd97474c3d | 0718470c4d1ae82e0ea8ac39ea2ce051d60b09f1 | /src/test/java/StringCalculatorTest.java | fbed69e44151297ad14a985ccccf9438a8921bbb | [] | no_license | fahad-israr/TDD-Kata-String-Calculator | e74c8702b4f7f13f34092e8dbe674ed45e02d39c | 0eb3a25598cce5137c2b85a797ce24b8111a08fb | refs/heads/master | 2023-02-01T22:46:50.310071 | 2020-12-21T05:00:01 | 2020-12-21T05:00:01 | 320,345,981 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,422 | java | import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class StringCalculatorTest {
@Test
public void testAddShouldReturn0() {
StringCalculator calculator = new StringCalculator();
assertEquals(0, calculator.add(""));
}
@Test
public void testAddShouldReturn1() {
StringCalculator calculator = new StringCalculator();
assertEquals(1, calculator.add("1"));
}
@Test
public void testAddShouldReturn3() {
StringCalculator calculator = new StringCalculator();
assertEquals(3, calculator.add("1,2"));
}
@Test
public void testAddShouldReturnNegativeInfinity() {
StringCalculator calculator = new StringCalculator();
assertEquals(Integer.MIN_VALUE, calculator.add("1,2,sometext"));
}
@Test
public void testAddShouldReturn6() {
StringCalculator calculator = new StringCalculator();
assertEquals(6, calculator.add("1\n2,3"));
}
@Test
public void testAddShouldReturn3withCustomDelimiter() {
StringCalculator calculator = new StringCalculator();
assertEquals(3, calculator.add("//;\n1;2"));
}
@Test
public void testAddShouldReturnException(){
StringCalculator calculator = new StringCalculator();
try {
calculator.add("-1,2");
}
catch (IllegalArgumentException e){
assertEquals(e.getMessage(), "Negatives not allowed: -1");
}
try {
calculator.add("2,-4,3,-5");
}
catch (IllegalArgumentException e){
assertEquals(e.getMessage(), "Negatives not allowed: -4,-5");
}
}
@Test
public void testAddShouldReturn2() {
StringCalculator calculator = new StringCalculator();
assertEquals(2, calculator.add("1001,2"));
}
@Test
public void testAddShouldReturn6withAnyDelimiterLength() {
StringCalculator calculator = new StringCalculator();
assertEquals(6, calculator.add("//[***]\n1***2***3"));
}
@Test
public void testAddShouldReturn6withMutipleDelimiter() {
StringCalculator calculator = new StringCalculator();
assertEquals(6, calculator.add("//[*][%]\n1*2%3"));
}
@Test
public void testAddShouldReturn6withMutipleDelimiterofAnyLength() {
StringCalculator calculator = new StringCalculator();
assertEquals(6, calculator.add("//[***][%%%]\n1***2%%%3"));
}
}
| [
"[email protected]"
] | |
ca76e8d3faba1acdc281b3f97322c219fd0b9ff1 | bf3a091d350d8ff1ecebb761b299a294ec031c53 | /stock-management-automation/src/main/java/io/github/ydhekim/stock_management_automation/controller/GetAllWarehouseAttendantsController.java | cfbdd3debaaf5639b35475eae0dd9d967dfd6f92 | [] | no_license | ydhekim/stock-management-automation | e7d0c29fe6d1181b6f89b98e3e78704eb3843fe9 | a9d3a641fba240969d546865181a25d8bec365c2 | refs/heads/master | 2020-04-10T00:17:11.485470 | 2018-12-17T19:15:27 | 2018-12-17T19:15:27 | 160,681,022 | 0 | 5 | null | 2018-12-14T13:37:40 | 2018-12-06T13:47:45 | JavaScript | UTF-8 | Java | false | false | 1,824 | java | package io.github.ydhekim.stock_management_automation.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import io.github.ydhekim.stock_management_automation.dao.WarehouseAttendantDAO;
import io.github.ydhekim.stock_management_automation.dao.WarehouseAttendantDAOImpl;
import io.github.ydhekim.stock_management_automation.model.Employee;
@WebServlet("/GetAllWarehouseAttendantsController")
public class GetAllWarehouseAttendantsController extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
WarehouseAttendantDAO warehouseAttendantDAO = new WarehouseAttendantDAOImpl();
ArrayList<Employee> employees;
employees = warehouseAttendantDAO.getAllWarehouseAttendants();
out.println("Personel ID - Personel PW - Personel Adi - Personel Soyadi - Departman ID <br/>");
for (Employee employee : employees) {
int employeeId = employee.getId();
int employeePw = employee.getPassword();
String firstName = employee.getFirstName();
String lastName = employee.getLastName();
int departmentId = employee.getDepartment().getId();
out.println(employeeId + " ---------- " + employeePw + " ---------- " + firstName + " ---------- "
+ lastName + " ---------- " + departmentId + "<br/>");
}
out.println("<a href='index-mng.jsp'>Geri Don!</a>");
out.close();
}
}
| [
"[email protected]"
] | |
7cf758ba6d43d2d78856d1ce4583904f6c211c44 | 67789e4c8d45819105bb39efaa00eec6943ab42c | /src/main/java/br/com/prontuariounico/security/SpringSecurityAuditorAware.java | 7725459d7ca93b7ed117d7fbda0632b2920bdf29 | [] | no_license | emaruya/prontuario_unico | 06fa9581f21a26dab8d1fcb85983ad64b7442433 | 815625ed9ba124db4d71ec097ab1bd1ddc9f3f2d | refs/heads/main | 2023-01-28T00:14:48.242192 | 2020-12-07T01:49:08 | 2020-12-07T01:49:08 | 319,147,298 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 552 | java | package br.com.prontuariounico.security;
import br.com.prontuariounico.config.Constants;
import java.util.Optional;
import org.springframework.data.domain.AuditorAware;
import org.springframework.stereotype.Component;
/**
* Implementation of {@link AuditorAware} based on Spring Security.
*/
@Component
public class SpringSecurityAuditorAware implements AuditorAware<String> {
@Override
public Optional<String> getCurrentAuditor() {
return Optional.of(SecurityUtils.getCurrentUserLogin().orElse(Constants.SYSTEM_ACCOUNT));
}
}
| [
"[email protected]"
] | |
0e2af2467ffc6783927ab1926ea2531b75a3e3e0 | c8bace3885addf0ed59adb3a643e6fcb53e3487e | /news-jsp-mysql/src/java/com/news/util/DaiCaThang.java | f5b392333e6b399085a60e34015bacac06398286 | [] | no_license | quandt162/Jsp_Servlet | 25d1b0ca0c63d0b87cc57ff3b790f0fef4004cdf | e527f24546ad85375639cf7fc222627416ac0c7c | refs/heads/master | 2021-01-10T04:47:01.704295 | 2015-12-04T13:53:04 | 2015-12-04T13:53:04 | 47,406,180 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,371 | java | package com.news.util;
import java.util.Arrays;
public class DaiCaThang {
private static char[] SPECIAL_CHARACTERS = { ' ', '!', '"', '#', '$', '%',
'*', '+', ',', ':', '<', '=', '>', '?', '@', '[', '\\', ']', '^',
'`', '|', '~', 'À', 'Á', 'Â', 'Ã', 'È', 'É', 'Ê', 'Ì', 'Í', 'Ò',
'Ó', 'Ô', 'Õ', 'Ù', 'Ú', 'Ý', 'à', 'á', 'â', 'ã', 'è', 'é', 'ê',
'ì', 'í', 'ò', 'ó', 'ô', 'õ', 'ù', 'ú', 'ý', 'Ă', 'ă', 'Đ', 'đ',
'Ĩ', 'ĩ', 'Ũ', 'ũ', 'Ơ', 'ơ', 'Ư', 'ư', 'Ạ', 'ạ', 'Ả', 'ả', 'Ấ',
'ấ', 'Ầ', 'ầ', 'Ẩ', 'ẩ', 'Ẫ', 'ẫ', 'Ậ', 'ậ', 'Ắ', 'ắ', 'Ằ', 'ằ',
'Ẳ', 'ẳ', 'Ẵ', 'ẵ', 'Ặ', 'ặ', 'Ẹ', 'ẹ', 'Ẻ', 'ẻ', 'Ẽ', 'ẽ', 'Ế',
'ế', 'Ề', 'ề', 'Ể', 'ể', 'Ễ', 'ễ', 'Ệ', 'ệ', 'Ỉ', 'ỉ', 'Ị', 'ị',
'Ọ', 'ọ', 'Ỏ', 'ỏ', 'Ố', 'ố', 'Ồ', 'ồ', 'Ổ', 'ổ', 'Ỗ', 'ỗ', 'Ộ',
'ộ', 'Ớ', 'ớ', 'Ờ', 'ờ', 'Ở', 'ở', 'Ỡ', 'ỡ', 'Ợ', 'ợ', 'Ụ', 'ụ',
'Ủ', 'ủ', 'Ứ', 'ứ', 'Ừ', 'ừ', 'Ử', 'ử', 'Ữ', 'ữ', 'Ự', 'ự', };
private static char[] REPLACEMENTS = { '-', '\0', '\0', '\0', '\0', '\0',
'\0', '_', '\0', '_', '\0', '\0', '\0', '\0', '\0', '\0', '_',
'\0', '\0', '\0', '\0', '\0', 'A', 'A', 'A', 'A', 'E', 'E', 'E',
'I', 'I', 'O', 'O', 'O', 'O', 'U', 'U', 'Y', 'a', 'a', 'a', 'a',
'e', 'e', 'e', 'i', 'i', 'o', 'o', 'o', 'o', 'u', 'u', 'y', 'A',
'a', 'D', 'd', 'I', 'i', 'U', 'u', 'O', 'o', 'U', 'u', 'A', 'a',
'A', 'a', 'A', 'a', 'A', 'a', 'A', 'a', 'A', 'a', 'A', 'a', 'A',
'a', 'A', 'a', 'A', 'a', 'A', 'a', 'A', 'a', 'E', 'e', 'E', 'e',
'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'I',
'i', 'I', 'i', 'O', 'o', 'O', 'o', 'O', 'o', 'O', 'o', 'O', 'o',
'O', 'o', 'O', 'o', 'O', 'o', 'O', 'o', 'O', 'o', 'O', 'o', 'O',
'o', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u',
'U', 'u', };
public static String toUrlFriendly(String s) {
int maxLength = Math.min(s.length(), 236);
char[] buffer = new char[maxLength];
int n = 0;
for (int i = 0; i < maxLength; i++) {
char ch = s.charAt(i);
buffer[n] = removeAccent(ch);
// skip not printable characters
if (buffer[n] > 31) {
n++;
}
}
// skip trailing slashes
while (n > 0 && buffer[n - 1] == '/') {
n--;
}
return String.valueOf(buffer, 0, n);
}
public static char removeAccent(char ch) {
int index = Arrays.binarySearch(SPECIAL_CHARACTERS, ch);
if (index >= 0) {
ch = REPLACEMENTS[index];
}
return ch;
}
public static String removeAccent(String s) {
StringBuilder sb = new StringBuilder(s);
for (int i = 0; i < sb.length(); i++) {
sb.setCharAt(i, removeAccent(sb.charAt(i)));
}
return sb.toString();
}
public static String[] fuck69(String source){
if(source == null || "".equals(source)) return null;
String tmp = toUrlFriendly(source).replace("-", "").toUpperCase();
String[] rs = new String[tmp.length()];
for(int i=0; i<tmp.length(); i++){
rs[i] = tmp.charAt(i)+" ";
}
return rs;
}
public static void main(String[] args) {
// String rs[] = DaiCaThang.fuck69("Trịnh Lê Tú");
// System.out.println(DaiCaThang.fuck69("Trịnh Lê Tú").length);
// for(String s : rs){
// System.out.print(s);
// }
System.out.println(toUrlFriendly("Trời mưa quá rồi").toLowerCase());
}
}
| [
"[email protected]"
] | |
94d89507c1d3d25b02ffb0ec5b349caddc12dd4b | 6fe6e726bc5959593201127cd8975ae7ab0d39da | /config-server-git/src/main/java/spring/config/ConfigServerGitApplication.java | 8f85f2cbff07692444fef42357e343d5eeee03b4 | [] | no_license | lcodyto/springcloud-study | 3d77ee61e0d4d77e746e434f077c896cde76109a | 7412efe39e65e56799037180b40901f9c5fb076c | refs/heads/master | 2023-05-06T02:02:17.946975 | 2021-05-04T15:52:00 | 2021-05-04T15:52:00 | 372,820,373 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 410 | java | package spring.config;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;
@EnableConfigServer
@SpringBootApplication
public class ConfigServerGitApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigServerGitApplication.class, args);
}
}
| [
"[email protected]"
] | |
b6cad4625411d7ef1fdfe4f28f2a9cb9f47ae839 | 3d65929e1d1b37cf2807b5f45a145fbc10cc073b | /Module4/20_case_study/case_study/src/main/java/vn/codegym/model/Position.java | 1d1300f7775d2e061b5f081b254926424ce10a74 | [] | no_license | MAIDOAN2302/A1020I1-DoanThiMai | 336f111335ac42794fb00824764685b923becf62 | 2383398c1009f48d81c50ce2f4d3d4984110c215 | refs/heads/master | 2023-08-13T21:57:04.841504 | 2021-10-04T16:36:26 | 2021-10-04T16:36:26 | 312,744,327 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 845 | java | package vn.codegym.model;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import java.util.Set;
@Entity
public class Position {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@NotBlank(message = "Không được để trống")
private String name;
@OneToMany(mappedBy = "position")
private Set<Employee> employees;
public Position() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Employee> getEmployees() {
return employees;
}
public void setEmployees(Set<Employee> employees) {
this.employees = employees;
}
}
| [
"[email protected]"
] | |
24c190ac4905fc5ec5b55da4a9ed3449873ec1f1 | fc7dbc55c28514a48629184383c808d348b8425c | /300. Longest Increasing Subsequence/src/Solution2.java | 8347195e0cca92c51c9d09c11a58b75dfeba915f | [] | no_license | novRay/leetcode_solution | afbb4b905aeb5040957ea0a817043bd85eb1dbcd | aa6844cc10ca0177b5753678bec19ca144c96671 | refs/heads/master | 2023-08-19T02:05:59.819837 | 2021-10-16T07:16:51 | 2021-10-16T07:16:51 | 408,674,456 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 779 | java | import java.util.Arrays;
// Greedy + Binary Search (Patience Sort)
public class Solution2 {
public int lengthOfLIS(int[] nums) {
int n = nums.length;
int[] tails = new int[n];
int res = 0;
for (int num : nums) {
int lo = 0;
int hi = res;
if (res == 0 || num > tails[res - 1]) {
tails[res] = num;
res ++;
} else {
while (lo < hi) {
int mid = (lo + hi) / 2;
if (tails[mid] < num) {
lo = mid + 1;
} else {
hi = mid;
}
}
tails[lo] = num;
}
}
return res;
}
}
| [
"[email protected]"
] | |
5ef182d65e8a0708d7e594643abe9c97cdc1bef5 | e0c8d4b3c1fdfb0f8469b7de23ffb9ca471052bb | /Week12-BankAccount/src/BankAccountTester.java | 4617de7e98ff7199f01fd10b5ac90afaa45c244e | [] | no_license | tranric/Java_2015_stuff | d8848a4a783777a37b8ea9b37e3073d0341865f0 | 4f0069b01e6d946cadfdda91e1c1256d7c02ca31 | refs/heads/main | 2023-02-04T09:51:12.965424 | 2020-12-18T02:05:41 | 2020-12-18T02:05:41 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 668 | java | import BankAccountClasses.*;
public class BankAccountTester {
public BankAccountTester(){
//BankAccount myAccount = new BankAccount(4000);
SavingsAccount savings = new SavingsAccount(5000 , 0.02);
ChequingAccount chq = new ChequingAccount(400);
savings.addInterest();
System.out.println(savings.toString());
System.out.println(chq.toString());
chq.deposit(100);
chq.withdraw(50);
chq.withdraw(100);
chq.withdraw(50);
System.out.println(chq.toString());
chq.deductFees();
System.out.println(chq.toString());
}
public static void main(String[] args) {
new BankAccountTester();
}
}
| [
"[email protected]"
] | |
95a9dfefb3d9c68ece698dd4cbf4878a5a7636ca | d71e879b3517cf4fccde29f7bf82cff69856cfcd | /ExtractedJars/iRobot_com.irobot.home/javafiles/android/support/v4/media/MediaBrowserServiceCompat$d$7.java | 9d5e19ba1a8bb8d727889cf5775d26becb1897b3 | [
"MIT"
] | permissive | Andreas237/AndroidPolicyAutomation | b8e949e072d08cf6c6166c3f15c9c63379b8f6ce | c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a | refs/heads/master | 2020-04-10T02:14:08.789751 | 2019-05-16T19:29:11 | 2019-05-16T19:29:11 | 160,739,088 | 5 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,801 | java | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package android.support.v4.media;
import android.support.v4.f.a;
// Referenced classes of package android.support.v4.media:
// MediaBrowserServiceCompat
class MediaBrowserServiceCompat$d$7
implements Runnable
{
public void run()
{
android.os.IBinder ibinder = a.a();
// 0 0:aload_0
// 1 1:getfield #23 <Field MediaBrowserServiceCompat$e a>
// 2 4:invokeinterface #33 <Method android.os.IBinder android.support.v4.media.MediaBrowserServiceCompat$e.a()>
// 3 9:astore_1
b.a.b.remove(((Object) (ibinder)));
// 4 10:aload_0
// 5 11:getfield #21 <Field MediaBrowserServiceCompat$d b>
// 6 14:getfield #36 <Field MediaBrowserServiceCompat android.support.v4.media.MediaBrowserServiceCompat$d.a>
// 7 17:getfield #39 <Field a MediaBrowserServiceCompat.b>
// 8 20:aload_1
// 9 21:invokevirtual #45 <Method Object a.remove(Object)>
// 10 24:pop
// 11 25:return
}
final MediaBrowserServiceCompat.e a;
final MediaBrowserServiceCompat.d b;
MediaBrowserServiceCompat$d$7(MediaBrowserServiceCompat.d d1, MediaBrowserServiceCompat.e e)
{
b = d1;
// 0 0:aload_0
// 1 1:aload_1
// 2 2:putfield #21 <Field MediaBrowserServiceCompat$d b>
a = e;
// 3 5:aload_0
// 4 6:aload_2
// 5 7:putfield #23 <Field MediaBrowserServiceCompat$e a>
super();
// 6 10:aload_0
// 7 11:invokespecial #26 <Method void Object()>
// 8 14:return
}
}
| [
"[email protected]"
] | |
c60d94fe485a598a78c4f040ce0727f890ce4589 | 606d7911da535e25c34bac9778bd83322052950e | /src/main/java/tech/ouyu/quickResponder/back/QuickResponderApplication.java | 424639aac8fb172625f37c4590c4b03289f5c614 | [] | no_license | Ouyuone/quick-responder-back | b31a0cf4cc11fdcfe763d71bb92fac96cf5668e4 | 6e4bf63289138f235ec9871a414e1c7c5db0fc0b | refs/heads/main | 2023-02-23T01:44:19.739372 | 2021-01-30T13:04:27 | 2021-01-30T13:04:27 | 320,580,067 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 468 | java | package tech.ouyu.quickResponder.back;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@MapperScan(basePackages = {"tech.ouyu.quickResponder.back.mapper"})
@SpringBootApplication
public class QuickResponderApplication {
public static void main(String[] args) {
SpringApplication.run(QuickResponderApplication.class, args);
}
}
| [
"[email protected]"
] | |
38a1636f54f3f202a9b00f73f6bb66e2137f8ab6 | 8d7010fc64c8c91c028f2bb5e11550cbce7244b2 | /src/main/java/services/impl/UserSecurityServiceImpl.java | 9467f9b3d2718423310b4cffbd299ddbeb274143 | [] | no_license | Typersun/quiz-engine-servlets | c6c927af59fb9f132ddfbd861f665f32ef31b73d | a9f4a0e4fecd690a60260eb1a7033fff8ae25d3c | refs/heads/master | 2023-05-08T04:45:14.648728 | 2021-05-27T18:19:43 | 2021-05-27T18:19:43 | 360,391,358 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,731 | java | package services.impl;
import dto.LoginDto;
import dto.RegistrationDto;
import dto.TokenDto;
import dto.errors.ErrorEntity;
import exceptions.QuizEngineException;
import lombok.AllArgsConstructor;
import models.Profile;
import models.User;
import repositories.UserRepository;
import services.UserSecurityService;
import utils.JwtHelper;
import java.util.Optional;
@AllArgsConstructor
public class UserSecurityServiceImpl implements UserSecurityService {
private final UserRepository userRepository;
private final JwtHelper jwtHelper;
private final Validator validator;
@Override
public TokenDto save(RegistrationDto entity) throws QuizEngineException {
Optional<ErrorEntity> optionalError = validator.getUserRegisterFormError(entity);
if (optionalError.isPresent()) {
throw new QuizEngineException(optionalError.get());
}
User user = User.builder()
.username(entity.getUsername())
.email(entity.getEmail())
.password(entity.getPassword())
.profile(new Profile())
.build();
userRepository.save(user);
return new TokenDto(jwtHelper.generateToken(user));
}
@Override
public TokenDto auth(LoginDto entity) throws QuizEngineException {
Optional<ErrorEntity> optionalError = validator.getLoginFormError(entity);
if (optionalError.isPresent()) {
throw new QuizEngineException(optionalError.get());
}
User user = User.builder()
.username(entity.getUsername())
.password(entity.getPassword())
.build();
return new TokenDto(jwtHelper.generateToken(user));
}
}
| [
"[email protected]"
] | |
5585e22b77985af4b0b307282b80663283ea0f15 | 4b787007b59c2e575082a37584ef0a88a5628df0 | /app/src/main/java/com/adamapps/coursealert/HomeActivity.java | bb5f12c0b8de37d963e0aeb989df40c20f59d2fb | [] | no_license | adamfils/SchoolAssistant | 12a117206e954d5ab624e2b2afe2c32bb2d8d0e3 | 5a757de3a3f3b5ff765f9c2552ebcd83c577f69c | refs/heads/master | 2021-01-20T16:10:02.437775 | 2017-08-18T07:10:21 | 2017-08-18T07:10:21 | 90,822,185 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 24,399 | java | package com.adamapps.coursealert;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.adamapps.coursealert.GettingStarted.Welcome;
import com.adamapps.coursealert.model.SinglePostModel;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.github.clans.fab.FloatingActionButton;
import com.github.clans.fab.FloatingActionMenu;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
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.Query;
import com.google.firebase.database.ValueEventListener;
import com.like.LikeButton;
import com.like.OnLikeListener;
import com.miguelcatalan.materialsearchview.MaterialSearchView;
import com.squareup.picasso.Callback;
import com.squareup.picasso.NetworkPolicy;
import com.squareup.picasso.Picasso;
import jp.co.recruit_lifestyle.android.widget.WaveSwipeRefreshLayout;
public class HomeActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener {
DatabaseReference reference;
RecyclerView recyclerView;
FirebaseAuth auth;
FirebaseUser user;
GoogleApiClient mGoogleApiClient;
private boolean mProcessLike = false;
DatabaseReference like_ref;
DatabaseReference comment_ref;
WaveSwipeRefreshLayout waveSwipeRefreshLayout;
ImageButton deleteButton;
private Query mQuery;
MaterialSearchView search_view;
FloatingActionButton post;
FloatingActionMenu fab_menu;
DatabaseReference postRef;
private MediaPlayer mp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_activty);
//Toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle(R.string.app_name);
toolbar.setTitleTextColor(Color.WHITE);
toolbar.showOverflowMenu();
mp = new MediaPlayer();
post = (FloatingActionButton) findViewById(R.id.new_post);
fab_menu = (FloatingActionMenu) findViewById(R.id.fab_menu);
postRef = FirebaseDatabase.getInstance().getReference().child("post");
auth = FirebaseAuth.getInstance();
user = auth.getCurrentUser();
search_view = (MaterialSearchView) findViewById(R.id.search_view);
search_view.setOnSearchViewListener(new MaterialSearchView.SearchViewListener() {
@Override
public void onSearchViewShown() {
}
@Override
public void onSearchViewClosed() {
firebaseRecycler();
}
});
search_view.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
if (newText != null && !newText.isEmpty()) {
mQuery = postRef.orderByChild("name").startAt(newText);
FirebaseRecyclerAdapter<SinglePostModel, PostViewHolder> adapter =
new FirebaseRecyclerAdapter<SinglePostModel, PostViewHolder>
(SinglePostModel.class, R.layout.single_post_layout, PostViewHolder.class, mQuery) {
@Override
protected void populateViewHolder(PostViewHolder viewHolder, SinglePostModel model, int position) {
final String post_key = getRef(position).getKey();
viewHolder.setImage(HomeActivity.this, model.getImage());
viewHolder.setTitle(model.getTitle());
viewHolder.setDesc(model.getDesc());
viewHolder.setUid(model.getName());
viewHolder.setLikeBtn(post_key);
viewHolder.setUsersLike(post_key);
viewHolder.like_btn.setOnLikeListener(new OnLikeListener() {
@Override
public void liked(final LikeButton likeButton) {
mProcessLike = true;
like_ref = reference.child("Likes");
like_ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (mProcessLike) {
like_ref.child(post_key).child(auth.getCurrentUser().getUid())
.setValue(auth.getCurrentUser().getDisplayName())
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Toast.makeText(HomeActivity.this, "Liked", Toast.LENGTH_SHORT).show();
mp.reset();
mp = MediaPlayer.create(getApplicationContext(), R.raw.snd_like_story);
mp.start();
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(HomeActivity.this, "Could Not Like", Toast.LENGTH_SHORT).show();
}
});
likeButton.setAnimationScaleFactor(3);
mProcessLike = false;
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
@Override
public void unLiked(LikeButton likeButton) {
like_ref = reference.child("Likes");
like_ref.child(post_key).child(auth.getCurrentUser().getUid()).removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Toast.makeText(HomeActivity.this, "DisLiked", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(HomeActivity.this, "Could Not Dislike \n" + e, Toast.LENGTH_SHORT).show();
}
});
likeButton.setAnimationScaleFactor(3);
mProcessLike = false;
}
});
}
};
recyclerView.setLayoutManager(new LinearLayoutManager(HomeActivity.this));
recyclerView.setAdapter(adapter);
} else {
firebaseRecycler();
}
return true;
}
});
reference = FirebaseDatabase.getInstance().getReference();
postRef = reference.child("post");
recyclerView = (RecyclerView) findViewById(R.id.post_preview);
postRef.keepSynced(true);
houseKeeping();
like_ref.keepSynced(true);
firebaseRecycler();
}
private void firebaseRecycler() {
FirebaseRecyclerAdapter<SinglePostModel, PostViewHolder> adapter =
new FirebaseRecyclerAdapter<SinglePostModel, PostViewHolder>
(SinglePostModel.class, R.layout.single_post_layout, PostViewHolder.class, postRef) {
@Override
protected void populateViewHolder(PostViewHolder viewHolder, SinglePostModel model, int position) {
final String post_key = getRef(position).getKey();
viewHolder.setImage(HomeActivity.this, model.getImage());
viewHolder.setTitle(model.getTitle());
viewHolder.setDesc(model.getDesc());
viewHolder.setUid(model.getName());
viewHolder.setLikeBtn(post_key);
viewHolder.setUsersLike(post_key);
viewHolder.like_btn.setOnLikeListener(new OnLikeListener() {
@Override
public void liked(final LikeButton likeButton) {
mProcessLike = true;
like_ref = reference.child("Likes");
like_ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (mProcessLike) {
like_ref.child(post_key).child(auth.getCurrentUser().getUid())
.setValue(auth.getCurrentUser().getDisplayName())
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Toast.makeText(HomeActivity.this, "Liked", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(HomeActivity.this, "Could Not Like", Toast.LENGTH_SHORT).show();
}
});
likeButton.setAnimationScaleFactor(3);
mProcessLike = false;
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
@Override
public void unLiked(LikeButton likeButton) {
like_ref = reference.child("Likes");
like_ref.child(post_key).child(auth.getCurrentUser().getUid()).removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Toast.makeText(HomeActivity.this, "DisLiked", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(HomeActivity.this, "Could Not Dislike \n" + e, Toast.LENGTH_SHORT).show();
}
});
likeButton.setAnimationScaleFactor(3);
mProcessLike = false;
}
});
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
return;
}
});
}
};
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
}
private void houseKeeping() {
final DatabaseReference connectedRef = FirebaseDatabase.getInstance().getReference(".info/connected");
waveSwipeRefreshLayout = (WaveSwipeRefreshLayout) findViewById(R.id.refresh_layout);
waveSwipeRefreshLayout.setWaveColor(Color.parseColor("#c85a54"));
waveSwipeRefreshLayout.setOnRefreshListener(new WaveSwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
connectedRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
boolean connected = dataSnapshot.getValue(Boolean.class);
if (connected) {
Toast.makeText(HomeActivity.this, "You Are Connected", Toast.LENGTH_SHORT).show();
new Task().execute();
} else {
Toast.makeText(HomeActivity.this, "You Seem Not To Be Connected", Toast.LENGTH_SHORT).show();
new Task().execute();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
like_ref = reference.child("Likes");
comment_ref = reference.child("Comments");
}
public void NewPost(View v) {
fab_menu.close(true);
startActivity(new Intent(this, NewPostActivity.class));
}
public void SearchUser(View v) {
fab_menu.close(true);
startActivity(new Intent(this, SearchUserActivity.class));
}
public void Profile(View v) {
fab_menu.close(true);
startActivity(new Intent(this, CurrentUserProfile.class));
}
public void Logout(View v) {
fab_menu.close(true);
FirebaseAuth.getInstance().signOut();
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(new ResultCallback<Status>() {
@Override
public void onResult(@NonNull Status status) {
Toast.makeText(HomeActivity.this, "Signed Out Hope To See You Soon", Toast.LENGTH_SHORT).show();
}
});
finish();
startActivity(new Intent(HomeActivity.this, Welcome.class));
}
private class Task extends AsyncTask<Void, Void, String[]> {
@Override
protected String[] doInBackground(Void... voids) {
return new String[0];
}
@Override
protected void onPostExecute(String[] strings) {
waveSwipeRefreshLayout.setRefreshing(false);
super.onPostExecute(strings);
}
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
public static class PostViewHolder extends RecyclerView.ViewHolder {
View mView;
LikeButton like_btn;
ImageButton comment_btn;
TextView usersLike;
DatabaseReference like_ref;
FirebaseAuth auth;
public PostViewHolder(View itemView) {
super(itemView);
mView = itemView;
like_btn = (LikeButton) mView.findViewById(R.id.like_button);
comment_btn = (ImageButton) mView.findViewById(R.id.comment_btn);
usersLike = (TextView) mView.findViewById(R.id.usersWhoLike);
like_ref = FirebaseDatabase.getInstance().getReference().child("Likes");
auth = FirebaseAuth.getInstance();
like_ref.keepSynced(true);
}
public void setComment(String post_key) {
}
public void setUsersLike(String post_key) {
like_ref.child(post_key).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
long userNumber = dataSnapshot.getChildrenCount();
/*for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()){
String users = dataSnapshot1.getValue(String.class);
StringBuilder buffer = new StringBuilder();
for (int i=0;i<userNumber;i++){
if(i>0){
buffer.append(",");
}
buffer.append(users);
}
usersLike.setText(buffer);
}*/
usersLike.setText(String.valueOf(userNumber));
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public void setLikeBtn(final String post_key) {
like_ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.child(post_key).hasChild(auth.getCurrentUser().getUid())) {
//like_btn.setImageResource(R.drawable.ic_like_blue);
like_btn.setLiked(true);
like_btn.setAnimationScaleFactor(4);
} else {
//like_btn.setImageResource(R.drawable.ic_like_grey);
like_btn.setLiked(false);
like_btn.setAnimationScaleFactor(3);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
void setImage(final Context context, final String image) {
final ImageView postImage = (ImageView) mView.findViewById(R.id.singlePostImage);
Picasso.with(context).load(image).
placeholder(R.drawable.ic_image).error(R.drawable.ic_image_coloured).networkPolicy(NetworkPolicy.OFFLINE).into(postImage, new Callback() {
@Override
public void onSuccess() {
}
@Override
public void onError() {
Picasso.with(context).load(image).
placeholder(R.drawable.ic_image).error(R.drawable.ic_image_coloured).into(postImage);
}
});
}
public void setTitle(String title) {
TextView titleNew = (TextView) mView.findViewById(R.id.singlePostTitle);
titleNew.setText(title);
}
void setDesc(String desc) {
TextView description = (TextView) mView.findViewById(R.id.singlePostDescription);
description.setText(desc);
}
void setUid(String uid) {
TextView userId = (TextView) mView.findViewById(R.id.singleUserId);
userId.setText(uid);
}
void setName(String name) {
TextView userId = (TextView) mView.findViewById(R.id.singleUserId);
userId.setText(name);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem item = menu.findItem(R.id.action_search);
search_view.setMenuItem(item);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.logout) {
FirebaseAuth.getInstance().signOut();
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(new ResultCallback<Status>() {
@Override
public void onResult(@NonNull Status status) {
Toast.makeText(HomeActivity.this, "Signed Out", Toast.LENGTH_SHORT).show();
}
});
finish();
startActivity(new Intent(HomeActivity.this, Welcome.class));
}
if (id == R.id.explore) {
fab_menu.close(true);
startActivity(new Intent(this, ExploreCategories.class));
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
if (search_view.isSearchOpen()) {
search_view.closeSearch();
} else {
super.onBackPressed();
}
}
}
| [
"[email protected]"
] | |
c5f5e61ea9e88ee79ad2ae61bd8f13ecc1360d8d | 7188a41b6ecdef00cfbf03cc662a631eeb7e2f18 | /DaiCuongFirstApp - v1.1/app/src/main/java/com/project/daicuongbachkhoa/ui/vatly1/VatLy1QuizDbHelper.java | e156edeb902dfdd7b58bf5e8004152c7f36976ac | [] | no_license | DongPhamBK/DaiCuongBachKhoa2 | e78a45f809c1b16f55d5a2f82c86fa2c6e04dfdd | ad6b20a130af22bdd20bd1e28d6331d1d75f7081 | refs/heads/master | 2023-01-18T20:19:28.045856 | 2020-12-01T02:13:00 | 2020-12-01T02:13:00 | 317,399,061 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 15,220 | java | package com.project.daicuongbachkhoa.ui.vatly1;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Build;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import com.project.daicuongbachkhoa.R;
import com.project.daicuongbachkhoa.ui.vatly1.VatLy1QuizContract.*;
import java.util.ArrayList;
import java.util.List;
// sử dụng class với SQLite
public class VatLy1QuizDbHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "VatLy1OnTapQuiz.db";// tạo database
private static final int DATABASE_VERSION = 1;// PHIÊN BẢN
private static VatLy1QuizDbHelper instace;
private SQLiteDatabase db;// tạo database sqlite
private VatLy1QuizDbHelper(@Nullable Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static synchronized VatLy1QuizDbHelper getInstace(Context context){
if(instace == null){
instace = new VatLy1QuizDbHelper(context.getApplicationContext());
}
return instace;
}
@Override
public void onCreate(SQLiteDatabase db) {
this.db = db;
final String SQL_CREATE_CATEGORIES_TABLE = "CREATE TABLE " +
CategoriesTable.TABLE_NAME + "( " +
CategoriesTable._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
CategoriesTable.COLUMN_NAME + " TEXT " +
")";
final String SQL_CREATE_QUESTIONS_TABLE = "CREATE TABLE " +
QuestionTable.TABLE_NAME + " ( " +
QuestionTable._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
QuestionTable.COLUMN_QUESTION + " TEXT, " +
QuestionTable.COLUMN_OPTION1 + " TEXT, " +
QuestionTable.COLUMN_OPTION2 + " TEXT, " +
QuestionTable.COLUMN_OPTION3 + " TEXT, " +
QuestionTable.COLUMN_ANSWER_NUM + " INTEGER, " +
QuestionTable.COLUMN_DIFFICULTY + " TEXT, " +
QuestionTable.COLUMN_CATEGORY_ID + " INTEGER," +
"FOREIGN KEY(" + QuestionTable.COLUMN_CATEGORY_ID + ") REFERENCES " +
CategoriesTable.TABLE_NAME + "(" + CategoriesTable._ID + ")" + "ON DELETE CASCADE" +
")";
db.execSQL(SQL_CREATE_CATEGORIES_TABLE);
db.execSQL(SQL_CREATE_QUESTIONS_TABLE);
fillCategoriesTable();
fillQuestionsTable();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// chú ý lệnh sql cần chính xác
db.execSQL("DROP TABLE IF EXISTS " + CategoriesTable.TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + QuestionTable.TABLE_NAME);
onCreate(db);
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onConfigure(SQLiteDatabase db) {
super.onConfigure(db);
db.setForeignKeyConstraintsEnabled(true);
// cái này nó bắt api cái trên, khi nào lỗi thì cần xem lại !
/*
***********************************
NHỚ KIỂM TRA LẠI CHỖ NÀY NHÉ !
********************************
*/
}
//bảng chương học
private void fillCategoriesTable() {
VatLy1Category c1 = new VatLy1Category("Động học chất điểm");
insertCategory(c1);
VatLy1Category c2 = new VatLy1Category("Động lực học chất điểm");
insertCategory(c2);
VatLy1Category c3 = new VatLy1Category("Động lực học vật rắn");
insertCategory(c3);
}
public void addCategory(VatLy1Category category){
db = getWritableDatabase();
insertCategory(category);
}
public void addCategories(List<VatLy1Category> categories ){
db = getWritableDatabase();
for(VatLy1Category category:categories){
insertCategory(category);
}
}
private void insertCategory(VatLy1Category category) {
ContentValues cv = new ContentValues();
cv.put(CategoriesTable.COLUMN_NAME, category.getName());
db.insert(CategoriesTable.TABLE_NAME, null, cv);
}
// bảng phương án
private void fillQuestionsTable() {
VatLy1Question q1 = new VatLy1Question("Trường hợp nào dưới đây có thể coi vật chuyển động như một chất điểm ?", "A.Chiếc ô tô trong bến xe.", "B.Mặt Trăng quanh Trái Đất", "C.Con cá trong chậu", 2, VatLy1Question.DIFFICULTY_EASY, VatLy1Category.CHUONG1);
insertQuestion(q1);
VatLy1Question q2 = new VatLy1Question("Nếu nói \"Trái Đất quay quanh Mặt Trời\" thì trong câu nói này vật nào được chọn làm vật mốc?", "A.Trái Đất", "B.Mặt Trăng", "C.Mặt Trời", 3, VatLy1Question.DIFFICULTY_EASY, VatLy1Category.CHUONG1);
insertQuestion(q2);
VatLy1Question q3 = new VatLy1Question("Hệ quy chiếu gồm:", "A.Vật làm mốc, hệ toạ độ, mốc thời gian.", "B.Hệ toạ độ, mốc thời gian, đồng hồ.", "C.Vật làm mốc, hệ toạ độ, mốc thời gian và đồng hồ.", 3, VatLy1Question.DIFFICULTY_EASY, VatLy1Category.CHUONG1);
insertQuestion(q3);
VatLy1Question q4 = new VatLy1Question("Công thức tính vận tốc", "A. v = s/t", "B. v = t/s", "C. v = s*t", 1, VatLy1Question.DIFFICULTY_EASY, VatLy1Category.CHUONG1);
insertQuestion(q4);
VatLy1Question q5 = new VatLy1Question("Công thức quãng đường đi được của chuyển động thẳng nhanh dần đều là:", "A. s = v0t + at2/2 (a và v0 cùng dấu).", "B. s = v0t + at2/2 (a và v0 trái dấu).", "C. x = x0 + v0t + at2/2 (a và v0 trái dấu).", 1, VatLy1Question.DIFFICULTY_MEDIUM, VatLy1Category.CHUONG1);
insertQuestion(q5);
VatLy1Question q6 = new VatLy1Question("Tại một nơi nhất định trên Trái Đất và ở gần mặt đất, các vật đều rơi tự do với:", "A.Cùng một gia tốc g.", "B.Gia tốc khác nhau.", "C.Gia tốc bằng 0", 1, VatLy1Question.DIFFICULTY_MEDIUM, VatLy1Category.CHUONG1);
insertQuestion(q6);
VatLy1Question q7 = new VatLy1Question("Trường hợp nào dưới đây có thể coi vật chuyển động như một chất điểm ?", "A.Chiếc ô tô trong bến xe.", "B.Mặt Trăng quanh Trái Đất", "C.Con cá trong chậu", 2, VatLy1Question.DIFFICULTY_MEDIUM, VatLy1Category.CHUONG1);
insertQuestion(q7);
VatLy1Question q8 = new VatLy1Question("Nếu nói \"Trái Đất quay quanh Mặt Trời\" thì trong câu nói này vật nào được chọn làm vật mốc?", "A.Trái Đất", "B.Mặt Trăng", "C.Mặt Trời", 3, VatLy1Question.DIFFICULTY_MEDIUM, VatLy1Category.CHUONG1);
insertQuestion(q8);
VatLy1Question q9 = new VatLy1Question("Hệ quy chiếu gồm:", "A.Vật làm mốc, hệ toạ độ, mốc thời gian.", "B.Hệ toạ độ, mốc thời gian, đồng hồ.", "C.Vật làm mốc, hệ toạ độ, mốc thời gian và đồng hồ.", 3, VatLy1Question.DIFFICULTY_MEDIUM, VatLy1Category.CHUONG1);
insertQuestion(q9);
VatLy1Question q10 = new VatLy1Question("Công thức tính vận tốc", "A. v = s/t", "B. v = t/s", "C. v = s*t", 1, VatLy1Question.DIFFICULTY_MEDIUM, VatLy1Category.CHUONG1);
insertQuestion(q10);
VatLy1Question q11 = new VatLy1Question("Công thức quãng đường đi được của chuyển động thẳng nhanh dần đều là:", "A. s = v0t + at2/2 (a và v0 cùng dấu).", "B. s = v0t + at2/2 (a và v0 trái dấu).", "C. x = x0 + v0t + at2/2 (a và v0 trái dấu).", 1, VatLy1Question.DIFFICULTY_MEDIUM, VatLy1Category.CHUONG1);
insertQuestion(q11);
VatLy1Question q12 = new VatLy1Question("Tại một nơi nhất định trên Trái Đất và ở gần mặt đất, các vật đều rơi tự do với:", "A.Cùng một gia tốc g.", "B.Gia tốc khác nhau.", "C.Gia tốc bằng 0", 1, VatLy1Question.DIFFICULTY_MEDIUM, VatLy1Category.CHUONG1);
insertQuestion(q12);
VatLy1Question q13 = new VatLy1Question("Trường hợp nào dưới đây có thể coi vật chuyển động như một chất điểm ?", "A.Chiếc ô tô trong bến xe.", "B.Mặt Trăng quanh Trái Đất", "C.Con cá trong chậu", 2, VatLy1Question.DIFFICULTY_HARD, VatLy1Category.CHUONG1);
insertQuestion(q13);
VatLy1Question q14 = new VatLy1Question("Nếu nói \"Trái Đất quay quanh Mặt Trời\" thì trong câu nói này vật nào được chọn làm vật mốc?", "A.Trái Đất", "B.Mặt Trăng", "C.Mặt Trời", 3, VatLy1Question.DIFFICULTY_HARD, VatLy1Category.CHUONG1);
insertQuestion(q14);
VatLy1Question q15 = new VatLy1Question("Hệ quy chiếu gồm:", "A.Vật làm mốc, hệ toạ độ, mốc thời gian.", "B.Hệ toạ độ, mốc thời gian, đồng hồ.", "C.Vật làm mốc, hệ toạ độ, mốc thời gian và đồng hồ.", 3, VatLy1Question.DIFFICULTY_HARD, VatLy1Category.CHUONG1);
insertQuestion(q15);
VatLy1Question q16 = new VatLy1Question("Công thức tính vận tốc", "A. v = s/t", "B. v = t/s", "C. v = s*t", 1, VatLy1Question.DIFFICULTY_HARD, VatLy1Category.CHUONG1);
insertQuestion(q16);
VatLy1Question q17 = new VatLy1Question("Công thức quãng đường đi được của chuyển động thẳng nhanh dần đều là:", "A. s = v0t + at2/2 (a và v0 cùng dấu).", "B. s = v0t + at2/2 (a và v0 trái dấu).", "C. x = x0 + v0t + at2/2 (a và v0 trái dấu).", 1, VatLy1Question.DIFFICULTY_HARD, VatLy1Category.CHUONG1);
insertQuestion(q17);
VatLy1Question q18 = new VatLy1Question("Tại một nơi nhất định trên Trái Đất và ở gần mặt đất, các vật đều rơi tự do với:", "A.Cùng một gia tốc g.", "B.Gia tốc khác nhau.", "C.Gia tốc bằng 0", 1, VatLy1Question.DIFFICULTY_HARD, VatLy1Category.CHUONG1);
insertQuestion(q18);
}
public void addQuestion(VatLy1Question question){
db = getWritableDatabase();
insertQuestion(question);
}
public void addQuestions(List<VatLy1Question> questions){
db = getWritableDatabase();
for(VatLy1Question question:questions){
insertQuestion(question);
}
}
private void insertQuestion(VatLy1Question question) {
ContentValues cv = new ContentValues();
cv.put(QuestionTable.COLUMN_QUESTION, question.getQuestion());
cv.put(QuestionTable.COLUMN_OPTION1, question.getOption1());
cv.put(QuestionTable.COLUMN_OPTION2, question.getOption2());
cv.put(QuestionTable.COLUMN_OPTION3, question.getOption3());
cv.put(QuestionTable.COLUMN_ANSWER_NUM, question.getAnswerNum());
cv.put(QuestionTable.COLUMN_DIFFICULTY, question.getDifficulty());
cv.put(QuestionTable.COLUMN_CATEGORY_ID, question.getCategoryId());
db.insert(QuestionTable.TABLE_NAME, null, cv);
}
public List<VatLy1Category> getAllCategories() {
List<VatLy1Category> categoryList = new ArrayList<>();
db = getReadableDatabase();
Cursor c = db.rawQuery("SELECT * FROM " + CategoriesTable.TABLE_NAME, null);
if (c.moveToFirst()) {
do {
VatLy1Category category = new VatLy1Category();
category.setId(c.getInt(c.getColumnIndex(CategoriesTable._ID)));
category.setName(c.getString(c.getColumnIndex(CategoriesTable.COLUMN_NAME)));
categoryList.add(category);
} while (c.moveToNext());
}
c.close();
return categoryList;
}
// nhập list câu hỏi
public ArrayList<VatLy1Question> getAllQuestions() {
ArrayList<VatLy1Question> questionList = new ArrayList<>();
db = getReadableDatabase();
Cursor c = db.rawQuery("SELECT * FROM " + QuestionTable.TABLE_NAME, null);
if (c.moveToFirst()) {
do {
VatLy1Question question = new VatLy1Question();
question.setId(c.getInt(c.getColumnIndex(QuestionTable._ID)));
question.setQuestion(c.getString(c.getColumnIndex(QuestionTable.COLUMN_QUESTION)));
question.setOption1(c.getString(c.getColumnIndex(QuestionTable.COLUMN_OPTION1)));
question.setOption2(c.getString(c.getColumnIndex(QuestionTable.COLUMN_OPTION2)));
question.setOption3(c.getString(c.getColumnIndex(QuestionTable.COLUMN_OPTION3)));
question.setAnswerNum(c.getInt(c.getColumnIndex(QuestionTable.COLUMN_ANSWER_NUM)));
question.setDifficulty(c.getString(c.getColumnIndex(QuestionTable.COLUMN_DIFFICULTY)));
question.setCategoryId(c.getInt(c.getColumnIndex(QuestionTable.COLUMN_CATEGORY_ID)));
questionList.add(question);
} while (c.moveToNext());
}
c.close();// đừng quên khoá lại !
return questionList;
}
public ArrayList<VatLy1Question> getQuestions(int categoryId, String difficulty) {
ArrayList<VatLy1Question> questionList = new ArrayList<>();
db = getReadableDatabase();
String selection = QuestionTable.COLUMN_CATEGORY_ID + " = ? " +
" AND " + QuestionTable.COLUMN_DIFFICULTY + " = ? ";
String[] selectionArgs = new String[]{String.valueOf(categoryId),difficulty};
Cursor c = db.query(
QuestionTable.TABLE_NAME,
null,
selection,
selectionArgs,
null,
null,
null
);
/* String[] selectionArgs = new String[]{difficulty};
Cursor c = db.rawQuery("SELECT * FROM " + QuestionTable.TABLE_NAME +
" WHERE " + QuestionTable.COLUMN_DIFFICULTY + " = ?", selectionArgs);
*/
if (c.moveToFirst()) {
do {
VatLy1Question question = new VatLy1Question();
question.setId(c.getInt(c.getColumnIndex(QuestionTable._ID)));
question.setQuestion(c.getString(c.getColumnIndex(QuestionTable.COLUMN_QUESTION)));
question.setOption1(c.getString(c.getColumnIndex(QuestionTable.COLUMN_OPTION1)));
question.setOption2(c.getString(c.getColumnIndex(QuestionTable.COLUMN_OPTION2)));
question.setOption3(c.getString(c.getColumnIndex(QuestionTable.COLUMN_OPTION3)));
question.setAnswerNum(c.getInt(c.getColumnIndex(QuestionTable.COLUMN_ANSWER_NUM)));
question.setDifficulty(c.getString(c.getColumnIndex(QuestionTable.COLUMN_DIFFICULTY)));
question.setCategoryId(c.getInt(c.getColumnIndex(QuestionTable.COLUMN_CATEGORY_ID)));
questionList.add(question);
} while (c.moveToNext());
}
c.close();// đừng quên khoá lại !
return questionList;
}
}
| [
"[email protected]"
] | |
e1c5833fbd74e3ed594768dc21a1e7da11ad1ed2 | 45d1e88d4275045417b1128b1978bb277de4136c | /A04.Netty/B01.Netty_Book/doc/nettybook2-master/src/com/phei/netty/frame/correct/TimeServer.java | 054d21c33f672d04db4956b944325cec23e27826 | [
"Apache-2.0"
] | permissive | huaxueyihao/NoteOfStudy | 2c1f95ef30e264776d0bbf72fb724b0fe9aceee4 | 061e62c97f4fa04fa417fd08ecf1dab361c20b87 | refs/heads/master | 2022-07-12T04:11:02.960324 | 2021-01-24T02:47:54 | 2021-01-24T02:47:54 | 228,293,820 | 0 | 0 | Apache-2.0 | 2022-06-21T03:49:20 | 2019-12-16T03:19:50 | Java | UTF-8 | Java | false | false | 2,617 | java | /*
* Copyright 2013-2018 Lilinfeng.
*
* 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.phei.netty.frame.correct;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
/**
* @author lilinfeng
* @date 2014年2月14日
* @version 1.0
*/
public class TimeServer {
public void bind(int port) throws Exception {
// 配置服务端的NIO线程组
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 1024)
.childHandler(new ChildChannelHandler());
// 绑定端口,同步等待成功
ChannelFuture f = b.bind(port).sync();
// 等待服务端监听端口关闭
f.channel().closeFuture().sync();
} finally {
// 优雅退出,释放线程池资源
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel arg0) throws Exception {
arg0.pipeline().addLast(new LineBasedFrameDecoder(1024));
arg0.pipeline().addLast(new StringDecoder());
arg0.pipeline().addLast(new TimeServerHandler());
}
}
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
int port = 8080;
if (args != null && args.length > 0) {
try {
port = Integer.valueOf(args[0]);
} catch (NumberFormatException e) {
// 采用默认值
}
}
new TimeServer().bind(port);
}
}
| [
"[email protected]"
] | |
abef9fd16b4828299457a0bb91e7eaa383163a29 | 7887568d9fc991bd0c062398013cffc681127123 | /src/com/web/daos/ScheduleDao.java | 034658a0ce29453294d4b3e98b6738b9b4978ce2 | [] | no_license | yoonsil/jee-soccer | fbb09c790032ab5f413b7a1514ece2310e0ebb27 | 08654b73e8073e97d2b147e255b7620cee8d9b31 | refs/heads/master | 2020-07-31T08:16:10.281990 | 2019-10-01T01:40:15 | 2019-10-01T01:40:15 | 210,541,908 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 57 | java | package com.web.daos;
public interface ScheduleDao {
}
| [
"[email protected]"
] | |
c713e65f857b8dc109f5a78d3c9869f22152cdbf | a1da428be70cf8d8d3e3519985eb0c37707a8243 | /fastapi/src/main/java/org/pulp/fastapi/extension/SequenceObservable.java | 48726bcf5f19ade1eb6251d261ca79062daefca8 | [] | no_license | huxinjun/fastapi | 088fef57760ec4088e006f7763455caa9fee7f08 | 6b6d395ce54ec3ef6b96ec794504724233669c44 | refs/heads/master | 2023-02-03T14:40:42.305750 | 2020-12-23T11:40:20 | 2020-12-23T11:40:20 | 273,634,312 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,798 | java | package org.pulp.fastapi.extension;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import org.pulp.fastapi.model.Error;
import org.pulp.fastapi.model.IModel;
import org.pulp.fastapi.util.Log;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import io.reactivex.Observable;
import retrofit2.Retrofit;
/**
* 单接口多url顺序请求,直到成功为止
* Created by xinjun on 2019/12/12 21:47
*/
public class SequenceObservable<T extends IModel> extends SimpleObservable<T> {
/**
* 配置的path无法访问回调
* Created by xinjun on 2019/12/13 10:35
*/
public interface Unreachable {
void onUnreachable(Error error, String path);
}
private String[] paths;
private int currIndex = 0;
private Unreachable unreachableCallback;//url无法访问回调
private Faild faild;
SequenceObservable(Observable<T> upstream, Type observableType, Annotation[] annotations, Retrofit retrofit, Class<?> apiClass) {
super(upstream, observableType, annotations, retrofit, apiClass);
}
@Override
public SequenceObservable<T> refresh() {
setExtraParam(null);
setCurrData(null);
super.success(new Success<T>() {
@Override
public void onSuccess(@NonNull T data) {
dispose();
}
});
super.faild(new Faild() {
@Override
public void onFaild(@NonNull Error error) {
Log.out("success.faild hash=" + this.hashCode());
if (unreachableCallback != null)
unreachableCallback.onUnreachable(error, getCurrPath());
nextUrl();
}
});
return this;
}
@Override
public SequenceObservable<T> success(final Success<T> success) {
super.success(new Success<T>() {
@Override
public void onSuccess(@NonNull T data) {
if (success != null)
success.onSuccess(data);
dispose();
}
});
super.faild(new Faild() {
@Override
public void onFaild(@NonNull Error error) {
Log.out("success.faild hash=" + this.hashCode());
if (unreachableCallback != null)
unreachableCallback.onUnreachable(error, getCurrPath());
nextUrl();
}
});
return this;
}
@Override
public SequenceObservable<T> faild(Faild faild) {
this.faild = faild;
return this;
}
@Override
public SequenceObservable<T> toastError() {
return (SequenceObservable<T>) super.toastError();
}
public SequenceObservable<T> unreachable(Unreachable unreachable) {
this.unreachableCallback = unreachable;
return this;
}
private void nextUrl() {
if (currIndex >= paths.length - 1) {
Error error = new Error();
error.setCode(Error.Code.ALL_URLS_INVALID.code);
error.setMsg("all path is unreachable");
if (this.faild != null)
this.faild.onFaild(error);
toastErrorIfNeed(error);
dispose();
return;
}
currIndex++;
refresh();
}
String getCurrPath() {
if (paths == null || paths.length == 0)
throw new RuntimeException("not found paths,please use @MultiPath annotation above api method");
String currPath = paths[currIndex];
if (TextUtils.isEmpty(currPath))
throw new RuntimeException("@MultiPath value item must not be null or emtpy");
return currPath;
}
void setPaths(String[] paths) {
this.paths = paths;
}
}
| [
"[email protected]"
] | |
22cb80af646c0db82ef4d38b5a7a3b8d26fadcbb | 5fa205de1d8e5cfcd45170c1f8e8a0b095763241 | /src/view/LoaningsFrame.java | 4620263a35b2d81cdcf842b540fc3be9d189c123 | [] | no_license | duongbx288/QuanlyThuvien | aa6746fbeb37b5f5944c45822821cc9d6eea70d0 | 0ce2652ec8c8df93a1244caef9e67ad58880c763 | refs/heads/main | 2023-08-02T09:14:01.840176 | 2021-10-04T10:23:27 | 2021-10-04T10:23:27 | 413,369,641 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 13,424 | java | package view;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.table.DefaultTableModel;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFCreationHelper;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import controller.BooksController;
import controller.LoaningsController;
import controller.ReadersController;
import input.LoaningInputFrame;
import model.Loanings;
import net.proteanit.sql.DbUtils;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import java.awt.Color;
import java.awt.Font;
public class LoaningsFrame extends JFrame {
private JPanel contentPane;
private JTable table;
DefaultTableModel model;
public ArrayList<Loanings> list;
private JTextField mamt;
private JTextField madg;
private JTextField matt;
public void showTable() {
for (Loanings s : list) {
model.addRow(new Object[]{
s.getmamt1(), s.getmadg1(), s.getmatt1(), s.getnmuon(), s.getnhentra(), s.gettiencoc()
});
}
}
public static void MuonsachExcel() throws Exception {
Connection connect = DriverManager.getConnection("jdbc:sqlserver://127.0.0.1:1433;databaseName=Thư_viện_trg3901;username=sa;password=thuvienXD"
);
Statement statement = connect.createStatement();
ResultSet resultSet = statement.executeQuery("select * from Muontra_XD3901");
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet spreadsheet = workbook.createSheet("Đơn mượn sách");
XSSFCreationHelper createHelper = workbook.getCreationHelper();
XSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.setDataFormat(
createHelper.createDataFormat().getFormat("MMMM dd, yyyy"));
spreadsheet.setDefaultColumnWidth(20);
XSSFRow row = spreadsheet.createRow(1);
XSSFCell cell;
cell = row.createCell(1);
cell.setCellValue("Mã đơn mượn trả");
cell = row.createCell(2);
cell.setCellValue("Mã độc giả");
cell = row.createCell(3);
cell.setCellValue("Mã thủ thư");
cell = row.createCell(4);
cell.setCellValue("Ngày mượn");
cell = row.createCell(5);
cell.setCellValue("Ngày hẹn trả");
cell = row.createCell(6);
cell.setCellValue("Tiền cọc");
int i = 2;
while(resultSet.next()) {
row = spreadsheet.createRow(i);
cell = row.createCell(1);
cell.setCellValue(resultSet.getString("Ma_muon_tra"));
cell = row.createCell(2);
cell.setCellValue(resultSet.getString("Ma_doc_gia"));
cell = row.createCell(3);
cell.setCellValue(resultSet.getString("Ma_thu_thu"));
cell = row.createCell(4);
cell.setCellValue(resultSet.getDate("Ngay_muon"));
cell.setCellStyle(cellStyle);
cell = row.createCell(5);
cell.setCellValue(resultSet.getDate("Ngay_hen_tra"));
cell.setCellStyle(cellStyle);
cell = row.createCell(6);
cell.setCellValue(resultSet.getString("Tien_coc"));
i++;
}
FileOutputStream out = new FileOutputStream(new File("ThongtinMuontra.xlsx"));
workbook.write(out);
out.close();
System.out.println("ThongtinMuontra.xlsx written successfully");
workbook.close();
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("com.jtattoo.plaf.graphite.GraphiteLookAndFeel");
} catch (Throwable e) {
e.printStackTrace();
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
LoaningsFrame frame = new LoaningsFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public LoaningsFrame() {
setTitle("Mượn_trảXD3901");
list = new LoaningsController().getListMuontra();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 1264, 603);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(25, 115, 977, 441);
contentPane.add(scrollPane);
table = new JTable();
table.setModel(new DefaultTableModel(
new Object[][] {
},
new String[] {
"M\u00E3 \u0111\u01A1n cho m\u01B0\u1EE3n s\u00E1ch", "M\u00E3 \u0111\u1ED9c gi\u1EA3", "M\u00E3 th\u1EE7 th\u01B0", "Ng\u00E0y m\u01B0\u1EE3n", "Ng\u00E0y h\u1EB9n tr\u1EA3", "Ti\u1EC1n c\u1ECDc"
}
));
scrollPane.setViewportView(table);
table.setFillsViewportHeight(true);
table.setRowHeight(table.getRowHeight()+20);
JButton btnNewButton = new JButton("Thêm");
btnNewButton.setFont(new Font("Dialog", Font.PLAIN, 14));
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
LoaningInputFrame inputfrm = new LoaningInputFrame();
inputfrm.setVisible(true);
}
});
btnNewButton.setBounds(26, 69, 115, 36);
contentPane.add(btnNewButton);
JButton btnNewButton_1 = new JButton("Làm mới");
btnNewButton_1.setFont(new Font("Dialog", Font.PLAIN, 14));
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
Connection conn = DriverManager.getConnection("jdbc:sqlserver://127.0.0.1:1433;databaseName=Thư_viện_trg3901;username=sa;password=thuvienXD");
String query = "SELECT * FROM Muontra_XD3901";
PreparedStatement st = conn.prepareStatement(query);
ResultSet rs = st.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
} catch (SQLException e1) {
e1.printStackTrace();
}
}
});
btnNewButton_1.setBounds(170, 69, 115, 36);
contentPane.add(btnNewButton_1);
JButton btnNewButton_2 = new JButton("Xóa");
btnNewButton_2.setFont(new Font("Dialog", Font.PLAIN, 14));
btnNewButton_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int row1 = table.getSelectedRow();
if(row1 == -1) {
} else {
int opt = JOptionPane.showConfirmDialog(null,"Are u sure to delete the chosen information","Xóa thông tin đơn mượn sách",JOptionPane.YES_NO_OPTION);
if(opt == 0) {
try {
Connection conn = DriverManager.getConnection("jdbc:sqlserver://127.0.0.1:1433;databaseName=Thư_viện_trg3901;username=sa;password=thuvienXD");
int row = table.getSelectedRow();
String value = (table.getModel().getValueAt(row, 0).toString());
String query = "DELETE FROM Muontra_XD3901 WHERE [Ma_muon_tra] = '"+value+"'";
PreparedStatement pst = conn.prepareStatement(query);
pst.executeUpdate();
String query1 = "SELECT * FROM Muontra_XD3901 ";
PreparedStatement st = conn.prepareStatement(query1);
ResultSet rs = st.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
} catch (SQLException e1) {e1.printStackTrace();}
}
}
}
});
btnNewButton_2.setBounds(308, 69, 115, 36);
contentPane.add(btnNewButton_2);
JButton btnNewButton_5 = new JButton("Sửa");
btnNewButton_5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
Connection conn = DriverManager.getConnection("jdbc:sqlserver://127.0.0.1:1433;databaseName=Thư_viện_trg3901;username=sa;password=thuvienXD");
int row = table.getSelectedRow();
String value0 = (table.getModel().getValueAt(row, 0).toString());
String value1 = (table.getModel().getValueAt(row, 1).toString());
String value2 = (table.getModel().getValueAt(row, 2).toString());
String value3 = (table.getModel().getValueAt(row, 3).toString());
String value4 = (table.getModel().getValueAt(row, 4).toString());
int value5 = Integer.parseInt( table.getValueAt(row, 5).toString());
String query = "UPDATE Muontra_XD3901 SET Ma_muon_tra = '"+value0+"', Ma_doc_gia = '"+value1+"', Ma_thu_thu = '"+value2+"', Ngay_muon = '"+value3+"', Ngay_hen_tra = '"+value4+"', Tien_coc = '"+value5+"' WHERE [Ma_muon_tra] = '"+value0+"'";
PreparedStatement pst = conn.prepareStatement(query);
pst.executeUpdate();
String query1 = "SELECT * FROM Muontra_XD3901 ";
PreparedStatement st = conn.prepareStatement(query1);
ResultSet rs = st.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
} catch (SQLException e1) {e1.printStackTrace();}
}
});
btnNewButton_5.setFont(new Font("Dialog", Font.PLAIN, 14));
btnNewButton_5.setBounds(444, 69, 115, 36);
contentPane.add(btnNewButton_5);
JButton btnNewButton_3 = new JButton("Tìm kiếm");
btnNewButton_3.setFont(new Font("Dialog", Font.PLAIN, 14));
btnNewButton_3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
Connection conn = DriverManager.getConnection("jdbc:sqlserver://127.0.0.1:1433;databaseName=Thư_viện_trg3901;username=sa;password=thuvienXD");
String query = "SELECT * FROM Muontra_XD3901 WHERE Ma_muon_tra LIKE '%" + mamt.getText() + "%' AND Ma_doc_gia LIKE N\'%" + madg.getText() + "%' AND Ma_thu_thu LIKE N\'%" + matt.getText() + "%'";
PreparedStatement st = conn.prepareStatement(query);
ResultSet rs = st.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
} catch (SQLException e1) {
e1.printStackTrace();
}
}
});
btnNewButton_3.setBounds(1026, 127, 115, 36);
contentPane.add(btnNewButton_3);
JButton btnNewButton_3_1 = new JButton("Xuất file Excel");
btnNewButton_3_1.setFont(new Font("Dialog", Font.PLAIN, 14));
btnNewButton_3_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
MuonsachExcel();
Process process = Runtime.getRuntime().exec("cmd /c start ThongtinMuontra.xlsx ");
} catch (Exception e1) {
JOptionPane.showMessageDialog(rootPane,"Có lỗi khi xuất file Excel");
e1.printStackTrace();
}
}
});
btnNewButton_3_1.setBounds(1026, 388, 115, 36);
contentPane.add(btnNewButton_3_1);
mamt = new JTextField();
mamt.setColumns(10);
mamt.setBounds(1095, 195, 115, 36);
contentPane.add(mamt);
madg = new JTextField();
madg.setColumns(10);
madg.setBounds(1095, 258, 115, 36);
contentPane.add(madg);
matt = new JTextField();
matt.setColumns(10);
matt.setBounds(1095, 322, 115, 36);
contentPane.add(matt);
JLabel lblMnCho = new JLabel("Mã đơn cho");
lblMnCho.setBounds(1018, 195, 67, 18);
contentPane.add(lblMnCho);
JLabel lblMcGi_1 = new JLabel("Mã độc giả");
lblMcGi_1.setBounds(1018, 258, 67, 26);
contentPane.add(lblMcGi_1);
JLabel lblMThTh = new JLabel("Mã thủ thư");
lblMThTh.setBounds(1018, 322, 67, 26);
contentPane.add(lblMThTh);
JLabel lblMnSch = new JLabel("mượn sách");
lblMnSch.setBounds(1018, 213, 67, 18);
contentPane.add(lblMnSch);
JButton btnNewButton_2_1 = new JButton("Trở lại");
btnNewButton_2_1.setFont(new Font("Dialog", Font.PLAIN, 14));
btnNewButton_2_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
HomeFrame hmfrm = new HomeFrame();
hmfrm.setVisible(true);
contentPane.setVisible(false);
dispose();
}
});
btnNewButton_2_1.setBounds(582, 69, 115, 36);
contentPane.add(btnNewButton_2_1);
JLabel lblNewLabel_3 = new JLabel("Thông tin mượn sách");
lblNewLabel_3.setForeground(Color.WHITE);
lblNewLabel_3.setFont(new Font("Corbel Light", Font.PLAIN, 25));
lblNewLabel_3.setBounds(40, 10, 241, 55);
contentPane.add(lblNewLabel_3);
JLabel Nen1 = new JLabel("");
Nen1.setBackground(new Color(210, 105, 30));
Nen1.setBounds(27, 10, 1200, 95);
Nen1.setOpaque(true);
contentPane.add(Nen1);
JLabel Nen2 = new JLabel("");
Nen2.setBackground(new Color(184, 134, 11));
Nen2.setBounds(1012, 116, 215, 346);
Nen2.setOpaque(true);
contentPane.add(Nen2);
JLabel Nen0 = new JLabel("");
Nen0.setBounds(0, 0, 1254, 569);
ImageIcon icon = new ImageIcon("icontoUse/Huge-Library-Wallpaper.jpg");
Nen0.setIcon(icon);
contentPane.add(Nen0);
JButton btnNewButton_2_1_1 = new JButton("Sửa");
btnNewButton_2_1_1.setFont(new Font("Dialog", Font.PLAIN, 14));
btnNewButton_2_1_1.setBounds(582, 69, 115, 36);
contentPane.add(btnNewButton_2_1_1);
model = (DefaultTableModel) table.getModel();
showTable();
}
}
| [
"[email protected]"
] | |
f55844b95dfc18d258d2e25557b246c32e4cd8e5 | b52cf581d7637563d148bddc9d226bbf654a474e | /src/main/java/com/rainple/weChatRobot/pojo/BaseMessage.java | bfa3f3a894f21c5467569a1514e6d6496a0a493c | [] | no_license | rainple1860/robot | 453675dad590dac3456ea94099ac4b7fb5e2e0e3 | e31d8f692226db8c1d2127034316567279f0f4a4 | refs/heads/master | 2023-08-23T00:27:44.477293 | 2021-10-20T15:12:30 | 2021-10-20T15:12:30 | 191,574,506 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 949 | java | package com.rainple.weChatRobot.pojo;
/**
* 消息父类
* @author Stephen
*
*/
public class BaseMessage {
//接收方微信号
private String ToUserName;
//发送方微信号
private String FromUserName;
//创建时间
private long CreateTime;
//消息类型
private String MsgType;
public String getToUserName() {
return ToUserName;
}
public void setToUserName(String toUserName) {
ToUserName = toUserName;
}
public String getFromUserName() {
return FromUserName;
}
public void setFromUserName(String fromUserName) {
FromUserName = fromUserName;
}
public long getCreateTime() {
return CreateTime;
}
public void setCreateTime(long createTime) {
CreateTime = createTime;
}
public String getMsgType() {
return MsgType;
}
public void setMsgType(String msgType) {
MsgType = msgType;
}
}
| [
"[email protected]"
] | |
d487451296254e9c3ccf561b4ef83aea80c12372 | 7b7c0f0b98a2993f0107e6f8fa7036e6e90db2c9 | /app/src/main/java/com/example/jsonparsingwithglideandvolley/Class/AboutMovies.java | 14d6523759b70345c2ecb2762885dab99a6f72a8 | [] | no_license | humayu96/JsonParsingWithGlideAndVolley | 4ef394676ddd03abd973ed9f5306d750653086fb | 9a2dd2e22d7bdb6b8cdabbc21898f2966177a1e0 | refs/heads/master | 2020-04-28T22:05:46.958569 | 2019-03-14T11:09:03 | 2019-03-14T11:09:03 | 175,605,732 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,706 | java | package com.example.jsonparsingwithglideandvolley.Class;
// Anime
public class AboutMovies {
public String name;
public String description;
public String rating;
public String img;
public String categories;
public String studio;
public int episode;
public AboutMovies() {
}
public AboutMovies(String name, String description, String rating, String img, String categories, String studio, int episode) {
this.name = name;
this.description = description;
this.rating = rating;
this.img = img;
this.categories = categories;
this.studio = studio;
this.episode = episode;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getRating() {
return rating;
}
public void setRating(String rating) {
this.rating = rating;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public String getCategories() {
return categories;
}
public void setCategories(String categories) {
this.categories = categories;
}
public String getStudio() {
return studio;
}
public void setStudio(String studio) {
this.studio = studio;
}
public int getEpisode() {
return episode;
}
public void setEpisode(int episode) {
this.episode = episode;
}
}
| [
"[email protected]"
] | |
8ba9145fe404252a9ef1e00234a44c1ba4dbc1b7 | 2d328561c7d4a96ee5c8612ccebdef7c978fae77 | /RestfulClient/src/main/java/com/restfulclient/impl/RequestBody.java | db2be545e2aab125240581f9a8f4f4fc25e341da | [
"Apache-2.0"
] | permissive | osvaldogh85/rest_tinny | acb634c73cb2ac3481c548832d4b85c46e2a9580 | 6122e65b3550cbaddb0dfb1145b32daee9cd56d9 | refs/heads/main | 2023-07-28T05:30:04.301660 | 2021-09-14T20:58:05 | 2021-09-14T20:58:05 | 364,962,499 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,621 | java | package com.restfulclient.impl;
import com.restfulclient.interfaces.IRequestBody;
public class RequestBody implements IRequestBody {
public static final int ZERO_LENGTH = 0;
private byte[] body;
private BodyType bodyType;
private Object content=null;
private RequestBody(final BodyType bodyType, Object content,final byte[] body) {
this.body = body;
this.bodyType = bodyType;
this.content=content;
}
public static IRequestBody build(final BodyType bodyType,String body) {
return new RequestBody(bodyType, body, body.getBytes());
}
public static IRequestBody build(final BodyType bodyType) {
return new RequestBody(bodyType, null, null);
}
public static IRequestBody buildDefault() {
return new RequestBody(BodyType.NONE, null, null);
}
public static IRequestBody build(final BodyType bodyType,Object content,final byte[] body) {
return new RequestBody(bodyType, content , body);
}
@Override
public byte[] getBody() {
return body;
}
@Override
public void setBody(byte[] body) {
this.body = body;
}
@Override
public BodyType getBodyType() {
return bodyType;
}
@Override
public void clean() {
body=null;
bodyType=null;
}
@Override
public long getBodyLength() {
return this.body.length;
}
@Override
public Object getBodyContent() {
return content;
}
@Override
public void setBodyContent(Object content) {
this.content=content;
}
}
| [
"[email protected]"
] | |
8479575b52bad789557b605639536752dfc7c597 | 8c3742a2ca655a649a31d6e60224bea5647495bf | /src/main/java/com/hdjd/grit/model/pojo/VO/TemplateData.java | 2803af22c3bf99a55032f2bab8b7965f10fd6b2b | [] | no_license | unsnow/grit | fe2c60f1d3c78ed76a704e18b6fe7d94c2dffa9f | a26b9c03f052ad37c7c310b4f8215b776bb51e5a | refs/heads/master | 2022-12-28T11:08:17.323258 | 2020-10-14T02:55:35 | 2020-10-14T02:55:35 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 622 | java | package com.hdjd.grit.model.pojo.VO;
import lombok.Data;
/**
* @description 设置推送的文字和颜色
*/
@Data
public class TemplateData {
//keyword1:订单类型,keyword2:下单金额,keyword3:配送地址,keyword4:取件地址,keyword5备注
private String value;//,,依次排下去
public TemplateData(String value){
this.value = value;
}
// private String time6; //订单预约时间
// private String thing4; //订单金额
// private String date5; //支付时间
// private String color;//字段颜色(微信官方已废弃,设置没有效果)
} | [
"[email protected]"
] | |
b198e20f55f7c9b0641c7d97c9d68c356471f9ab | e7e497b20442a4220296dea1550091a457df5a38 | /main_project/search/ExternalSearcher/src/externalsearch/ExternalSearcherI.java | 680c9fb58c89f358776e449d1d45069eb8e4c83a | [] | no_license | gunner14/old_rr_code | cf17a2dedf8dfcdcf441d49139adaadc770c0eea | bb047dc88fa7243ded61d840af0f8bad22d68dee | refs/heads/master | 2021-01-17T18:23:28.154228 | 2013-12-02T23:45:33 | 2013-12-02T23:45:33 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,410 | java | // **********************************************************************
//
// Copyright (c) 2003-2009 ZeroC, Inc. All rights reserved.
//
// This copy of Ice is licensed to you under the terms described in the
// ICE_LICENSE file included in this distribution.
//
// **********************************************************************
// Ice version 3.3.1
package externalsearch;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.util.concurrent.atomic.AtomicInteger;
import com.xiaonei.search2.Config;
import com.xiaonei.search2.model.IndexResult;
import com.xiaonei.search2.model.IndexResultItem;
import com.xiaonei.search2.model.IndexType;
import engine.search.BooleanQuery;
import engine.search.ConditionToQuery;
import engine.search.IndexReader;
import engine.search.IndexSearcher;
import engine.search.TermQuery;
import engine.search.TransformCondition;
public final class ExternalSearcherI extends _ExternalSearcherDisp {
private static Map<String, String> keymap = new HashMap<String, String>();
private IndexSearcher[] searchers = new IndexSearcher[2];
private AtomicInteger cur = new AtomicInteger(-1);
private String curIndex = "";
private static String dir = "/data/xce/XiaoNeiSearch/index3";
private CheckThread thread = new CheckThread(dir, this);
public void reloadIndex(String path) throws IOException,
InterruptedException {
if (path.equals(curIndex)) {
return;
}
long start = System.currentTimeMillis();
System.out.println("加载索引 " + dir);
File file = new File(dir + "/" + path);
String[] indexs = file.list();
System.out.println(indexs[0]);
List<IndexReader> readers = new ArrayList<IndexReader>();
for (int i = 0; i < indexs.length; i++) {
readers.add(i, new IndexReader(dir + "/" + path + "/" + indexs[i]));
}
int pos = (cur.get() + 1) % 2;
if (readers.size() == 0) {
searchers[pos] = null;
} else {
searchers[pos] = new IndexSearcher(
readers.toArray(new IndexReader[readers.size()]));
}
cur.incrementAndGet();
curIndex = path;
long end = System.currentTimeMillis();
long cost = end - start;
System.out.println("加载结束:cost:" + cost);
System.out.println("keymap size:" + keymap.size());
for (Map.Entry<String, String> entry : keymap.entrySet()) {
System.out.println("keymap key:" + entry.getKey() + " value:"
+ entry.getValue());
}
Thread.sleep(10000);
searchers[1 - pos] = null;
System.gc();
}
public ExternalSearcherI() {
thread.start();
}
static {
keymap.put("GENERAL.gender", "gender");
keymap.put("GENERAL.range.age", "age");
keymap.put("WORKPLACE_INFO.workplace_name", "workplace");
keymap.put("JS_INFO.junior_high_school_info.junior_high_school_year",
"junior.year");
keymap.put("JS_INFO.junior_high_school_info.junior_high_school_name",
"junior.name");
keymap.put("UNIVERSITY_INFO.enroll_year", "univ.year");
keymap.put("UNIVERSITY_INFO.university_id", "univ.name");
keymap.put("GENERAL.home_province", "homeprovince");
keymap.put("GENERAL.home_city", "homecity");
keymap.put("HIGH_SCHOOL_INFO.high_school_name", "high.name");
keymap.put("HIGH_SCHOOL_INFO.enroll_year", "high.year");
}
public static class Result implements Serializable {
public int resultHits = 0;
public int totalHits = 0;
public Vector<IndexResultItem> hitsResult = new Vector<IndexResultItem>();
}
@SuppressWarnings("unused")
public IndexResult search(
java.util.Map<java.lang.String, java.lang.String> condition,
int begin, int limit, Ice.Current __current) {
if (cur.get() < 0) {
System.out.println("Index is Not ready");
return null;
}
IndexSearcher searcher = searchers[cur.get() % 2];
if (searcher == null) {
System.out.println("Index is Not ready");
return null;
}
SimpleDateFormat dateFm = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String dateTime = dateFm.format(new java.util.Date());
System.out.println(dateTime);
long start = System.currentTimeMillis();
int realBegin = Math.min(Config.HARD_LIMIT, begin);
if (realBegin + limit > Config.HARD_LIMIT) {
realBegin = Config.HARD_LIMIT - limit;
}
System.out.println("begin:" + begin + " limit:" + limit + " realBegin:"
+ realBegin);
int needsTotal = realBegin + limit;
TransformCondition transformer = new TransformCondition(condition,
keymap);
Map<String, String> query = transformer.transform();
for (Map.Entry<String, String> entry : query.entrySet()) {
System.out.println("AFTER TRANSFORM key:" + entry.getKey()
+ " value:" + entry.getValue());
}
Result result_user = new Result();
IndexResult indexResult = new IndexResult();
indexResult.typedCount = new HashMap<IndexType, Integer>();
long getQueryStart = System.currentTimeMillis();
ConditionToQuery termQuery = new ConditionToQuery(
searcher.getReaders()[0]);
BooleanQuery booleanQuery = new BooleanQuery();
try {
booleanQuery = termQuery.getQuery(query);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
long getQueryEnd = System.currentTimeMillis();
long searchStart = System.currentTimeMillis();
ArrayList<Integer> ids = null;
try {
ids = searcher.search(booleanQuery, needsTotal);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long searchEnd = System.currentTimeMillis();
long getUserIdStart = System.currentTimeMillis();
if (ids == null || realBegin >= ids.size() || realBegin < 0) {
System.out.println("result is null, return");
return indexResult;
}
for (int id : ids) {
System.out.println("id:" + id);
}
long getUserIdEnd = System.currentTimeMillis();
long getIndexResultStart = System.currentTimeMillis();
for (int id : ids) {
HashMap<String, String> content = new HashMap<String, String>();
// content.put("is_friend", "0");
result_user.hitsResult.add(new IndexResultItem(IndexType.User, id,
content));
}
System.out.println("Searcher: " + cur.get() + " begin:" + realBegin
+ " limit:" + limit + " result_user.size:"
+ result_user.hitsResult.size());
result_user.resultHits = result_user.hitsResult.size();
result_user.totalHits = ids.size();
List<IndexResultItem> result_app = null;
List<IndexResultItem> result_page = null;
int result_app_size = 0;
int result_page_size = 0;
int result_app_totalsize = 0;
int result_page_totalsize = 0;
List<IndexResultItem> hitsResult = new Vector<IndexResultItem>(
needsTotal);
hitsResult.addAll(result_user.hitsResult);
long getIndexResultEnd = System.currentTimeMillis();
long end = System.currentTimeMillis();
indexResult.currentPos = realBegin;
indexResult.timeCost = end - start;
indexResult.totalCount = result_user.totalHits;
indexResult.typedCount.put(IndexType.User, result_user.totalHits);
indexResult.contents = hitsResult
.toArray(new IndexResultItem[hitsResult.size()]);
StringBuilder builder = new StringBuilder();
builder.append("KEY:");
for (Map.Entry<String, String> entry : condition.entrySet()) {
// System.out.println("AFTER TRANSFORM key:" + entry.getKey()
// + " value:" + entry.getValue());
builder.append(entry.getKey() + ":" + entry.getValue() + ",");
}
// System.out.println("hitsResult.size:" + hitsResult.size()
// + " contents.size:" + indexResult.contents.length);
builder.append("; hitsResult.size:" + hitsResult.size()
+ "; contents.size:" + indexResult.contents.length);
// System.out.println("totalCount:" + indexResult.totalCount);
// System.out.println("totalCost:" + (end - start) + "ms; getQueryCost:"
// + (getQueryEnd - getQueryStart) + "ms; searchCost:"
// + (searchEnd - searchStart) + "ms; getUserIdCost:"
// + (getUserIdEnd - getUserIdStart) + "ms; getIndexResultCost:"
// + (getIndexResultEnd - getIndexResultStart));
builder.append("; totalCost:" + (end - start) + "; getQueryCost:"
+ (getQueryEnd - getQueryStart) + "; searchCost:"
+ (searchEnd - searchStart) + "; getUserIdCost:"
+ (getUserIdEnd - getUserIdStart) + "; getIndexResultCost:"
+ (getIndexResultEnd - getIndexResultStart));
System.out.println(builder.toString());
return indexResult;
}
}
| [
"[email protected]"
] | |
82349d8cb884df78c599ba8fc78b577fc2df6fb8 | 49778f2f41b83ab783c04cec96b6b386c33bdf88 | /Remove_Nth_Node_From_End_of_List.java | 7c7290645e7c65f6df98b90c4443dc668bdad816 | [] | no_license | cqx83/Leetcode | b8521154bc8cf1e5ee10e94ea3a6707a0d272b15 | 850562066937be04f881131f22c76677446f2f3f | refs/heads/master | 2016-09-03T06:38:28.582489 | 2014-08-22T06:09:57 | 2014-08-22T06:09:57 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 386 | java | public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode d = new ListNode(0);
d.next = head;
ListNode s = d, f = d;
while(n-- > 0) {
f = f.next;
}
while(f.next != null) {
s = s.next;
f = f.next;
}
s.next = s.next.next;
return d.next;
}
} | [
"[email protected]"
] | |
610fbdb6e1f6290a07ccd370b4746d8ea3a590e6 | 60b39cfa29cee07d052ce07093aff567fe1d789a | /src/main/java/com/bootdo/mia/service/impl/ExperevaluateServiceImpl.java | f6d1fba83395aeb7051055d15cc4a80013b2628a | [] | no_license | iamfine099/mia | 05ecb7d8b98871797b30de8250e68fe46f665efa | 4c7469e1d8918269e9a6b0cc2a90a7ffc1b9a05d | refs/heads/master | 2022-09-11T09:39:11.970942 | 2020-04-03T05:25:07 | 2020-04-03T05:25:07 | 180,247,196 | 0 | 0 | null | 2022-09-01T23:06:57 | 2019-04-08T23:18:11 | JavaScript | UTF-8 | Java | false | false | 4,210 | java | package com.bootdo.mia.service.impl;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.bootdo.mia.dao.ExperevaluateDao;
import com.bootdo.mia.domain.ExperevaluateDO;
import com.bootdo.mia.service.ExperevaluateService;
import com.bootdo.common.utils.excel.ImportExcel;
import org.springframework.web.multipart.MultipartFile;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
@Service
public class ExperevaluateServiceImpl implements ExperevaluateService {
@Autowired
private ExperevaluateDao experevaluateDao;
@Override
public ExperevaluateDO get(Integer eetId){
return experevaluateDao.get(eetId);
}
@Override
public List<ExperevaluateDO> list(Map<String, Object> map){
return experevaluateDao.list(map);
}
@Override
public List<ExperevaluateDO> detailList(Map<String, Object> map){
return experevaluateDao.detailList(map);
}
@Override
public int count(Map<String, Object> map){
return experevaluateDao.count(map);
}
@Override
public int detailCount(Map<String, Object> map){
return experevaluateDao.detailCount(map);
}
@Override
public int save(ExperevaluateDO experevaluate){
return experevaluateDao.save(experevaluate);
}
@Override
public int update(ExperevaluateDO experevaluate){
return experevaluateDao.update(experevaluate);
}
@Override
public int remove(Integer eetId){
return experevaluateDao.remove(eetId);
}
@Override
public int batchRemove(Integer[] eetIds){
return experevaluateDao.batchRemove(eetIds);
}
/**
* 职位类别导出EXCEL
* @param request
* @param response
* @param out
*/
public void exportExcel(HttpServletRequest request,
HttpServletResponse response, Map<String, Object> map,
ServletOutputStream out) {
TemplateExportParams params = new TemplateExportParams("templates/doc/Experevaluate.xls");
List<ExperevaluateDO> list = experevaluateDao.list(map);
Map<String, Object> map1 = new HashMap<String, Object>();
map1.put("maplist", list);
Workbook workbook = ExcelExportUtil.exportExcel(params,map1);
try {
String fileName = "Experevaluate"+new Date().getTime()/1000+".xls";
response.setContentType("application/octet-stream");
response.setHeader("name", fileName);
response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
response.setHeader("Pragma", "public");
response.setDateHeader("Expires", 0);
response.setHeader("Content-disposition","attachment; filename=\""+URLEncoder.encode(fileName, "UTF-8")+ "\"");
workbook.write(out);
workbook.close();
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 导入excel
* @param fileName
* @param file
* @return
* @throws IOException
* @throws InvalidFormatException
*/
public void importExcel(String fileName, MultipartFile file) throws Exception {
ImportExcel ei = new ImportExcel(file, 1, 0);
List<ExperevaluateDO> list = ei.getDataList(ExperevaluateDO.class);
//
for (ExperevaluateDO experevaluate : list) {
if(experevaluate != null) {
experevaluateDao.save( experevaluate);
}
}
}
@Override
public int notCompleteCount(Map<String,Object> map) {
return experevaluateDao.notCompleteCount(map);
}
@Override
public String avgScore(Integer articleId) {
return experevaluateDao.avgScore(articleId);
}
@Override
public Integer recommendNum(Integer articleId) {
return experevaluateDao.recommendNum(articleId);
}
@Override
public Integer likeNum(Integer articleId) {
return experevaluateDao.likeNum(articleId);
}
@Override
public int deleteByArticleId(Integer articleId){
return experevaluateDao.deleteByArticleId(articleId);
}
}
| [
"[email protected]"
] | |
cebb661be362dc1de29d0c6e170bb43250bf3e6e | 7a3ad8a883d2a7cf1a46c9d713b0dafeb4126601 | /src/main/java/com/tnsoft/web/service/impl/ExportServiceImpl.java | 4484598f58a26fd87ad10d7bb407ae7a8b799aa3 | [] | no_license | TheOneChina/znll | b45546b69a71aeef5b6257634fff6e45cd73d34a | 2970d1e16beacd0cbaa44be21c1c27e36c55e94e | refs/heads/master | 2020-04-27T20:19:30.049617 | 2019-03-18T12:25:19 | 2019-03-18T12:25:19 | 174,340,693 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 29,793 | java | package com.tnsoft.web.service.impl;
import com.expertise.common.util.StringUtils;
import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.border.Border;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.TextAlignment;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.tnsoft.hibernate.model.Express;
import com.tnsoft.hibernate.model.Tag;
import com.tnsoft.hibernate.model.TagExpress;
import com.tnsoft.hibernate.model.TempExpress;
import com.tnsoft.web.dao.ExpressDAO;
import com.tnsoft.web.dao.TagDAO;
import com.tnsoft.web.dao.TagExpressDAO;
import com.tnsoft.web.dao.TempExpressDAO;
import com.tnsoft.web.model.Constants;
import com.tnsoft.web.service.ExportService;
import com.tnsoft.web.util.ChartUtil;
import com.tnsoft.web.util.Utils;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;
@Service("exportService")
public class ExportServiceImpl implements ExportService {
@Resource(name = "tempExpressDAO")
private TempExpressDAO tempExpressDAO;
@Resource(name = "expressDAO")
private ExpressDAO expressDAO;
@Resource(name = "tagExpressDAO")
private TagExpressDAO tagExpressDAO;
@Resource(name = "tagDAO")
private TagDAO tagDAO;
@Override
public void exportToPDF(int expressId, Date start, Date end, int flag, HttpServletRequest request,
HttpServletResponse response) {
try {
ServletOutputStream outputStream = response.getOutputStream();
response.reset();
response.setContentType("application/pdf");
List<TempExpress> tempExpressList = tempExpressDAO.getByExpressIdWithTimeLimit(expressId,
start, end);
Express express = expressDAO.getById(expressId);
TagExpress tagExpress = tagExpressDAO.getLastTagExpressByEId(expressId);
Tag tag = tagDAO.getById(tagExpress.getTagNo());
String fileName = express.getExpressNo();
if (StringUtils.isEmpty(fileName)) {
fileName = expressId + ".pdf";
} else {
fileName += ".pdf";
}
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
//Initialize PDF writer
PdfWriter writer = new PdfWriter(outputStream);
//Initialize PDF document
PdfDocument pdf = new PdfDocument(writer);
// Initialize document
Document document = new Document(pdf);
PdfFont helvetica = PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
//不同版本名称
String expressNo, statusActive, statusFinish;
if (flag == Constants.Version.EXPRESS) {
//物流版
expressNo = "订单号";
statusActive = "配送中";
statusFinish = "已签收";
} else {
//医药/标准版
expressNo = "监测点名称";
statusActive = "监测中";
statusFinish = "已结束";
}
Float maxAlertTemperature, minAlertTemperature;
if (express.getTemperatureMax() != null) {
maxAlertTemperature = express.getTemperatureMax();
} else {
if (tag.getTemperatureMax() != null) {
maxAlertTemperature = tag.getTemperatureMax();
} else {
maxAlertTemperature = null;
}
}
if (express.getTemperatureMin() != null) {
minAlertTemperature = express.getTemperatureMin();
} else {
if (tag.getTemperatureMin() != null) {
minAlertTemperature = tag.getTemperatureMin();
} else {
minAlertTemperature = null;
}
}
String maxAlertTemperatureStr, minAlertTemperatureStr;
if (null != maxAlertTemperature) {
maxAlertTemperatureStr = maxAlertTemperature + "";
} else {
maxAlertTemperatureStr = "无";
}
if (null != minAlertTemperature) {
minAlertTemperatureStr = minAlertTemperature + "";
} else {
minAlertTemperatureStr = "无";
}
float[] briefTableWidths = {90, 90, 90, 90, 90, 90};
Table briefTable = new Table(briefTableWidths);
briefTable.addCell(new Paragraph(expressNo).setFont(helvetica)).addCell(new Cell(1, 3).add(new
Paragraph(express.getExpressNo()).setFont(helvetica)));
if (express.getStatus() == Constants.ExpressState.STATE_FINISHED) {
briefTable.addCell(new Paragraph("状态").setFont(helvetica)).addCell(new Paragraph(statusFinish)
.setFont(helvetica));
} else {
briefTable.addCell(new Paragraph("状态").setFont(helvetica)).addCell(new Paragraph(statusActive)
.setFont(helvetica));
}
String creationTimeStr = "";
String finishedTimeStr = "";
if (null != express.getCreationTime()) {
creationTimeStr = Utils.SF.format(express.getCreationTime());
}
if (null != express.getCheckOutTime()) {
finishedTimeStr = Utils.SF.format(express.getCheckOutTime());
}
briefTable.addCell(new Paragraph("开始时间").setFont(helvetica)).addCell(new Cell(1, 2).add(new Paragraph
(creationTimeStr).setFont(helvetica)));
briefTable.addCell(new Paragraph("结束时间").setFont(helvetica)).addCell(new Cell(1, 2).add(new Paragraph
(finishedTimeStr).setFont(helvetica)));
briefTable.addCell(new Paragraph("低温阈值").setFont(helvetica)).addCell(new Paragraph
(minAlertTemperatureStr).setFont(helvetica));
briefTable.addCell(new Paragraph("高温阈值").setFont(helvetica)).addCell(new Paragraph
(maxAlertTemperatureStr).setFont(helvetica));
//温湿度曲线获得
BufferedImage bufferedImage = ChartUtil.getChart(tempExpressList, maxAlertTemperature,
minAlertTemperature, flag);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(byteArrayOutputStream);
encoder.encode(bufferedImage);
ImageData imageData = ImageDataFactory.create(byteArrayOutputStream.toByteArray());
Image image = new Image(imageData);
float[] widths = {200, 150, 150};
Table originalDataTable = new Table(widths);
originalDataTable.addCell(new Paragraph("时间").setFont(helvetica)).addCell(new Paragraph("温度(℃)")
.setFont(helvetica)).addCell(new Paragraph("湿度(%)").setFont(helvetica));
int alertCount = 0;
Float averageTemp = null, minTemp = null, maxTemp = null, averageHumidity = null, minHumidity = null,
maxHumidity = null;
if (tempExpressList.size() > 0) {
minTemp = tempExpressList.get(0).getTemperature();
maxTemp = tempExpressList.get(0).getTemperature();
averageTemp = 0F;
minHumidity = tempExpressList.get(0).getHumidity();
maxHumidity = tempExpressList.get(0).getHumidity();
averageHumidity = 0F;
int size = tempExpressList.size();
for (TempExpress tempExpress : tempExpressList) {
if (tempExpress.getHumidity() == 0) {
originalDataTable.addCell(Utils.SF.format(tempExpress.getCreationTime())).addCell(tempExpress
.getTemperature() + "").addCell("-");
} else {
originalDataTable.addCell(Utils.SF.format(tempExpress.getCreationTime())).addCell(tempExpress
.getTemperature() + "").addCell(tempExpress.getHumidity() + "");
}
if (null != maxAlertTemperature && tempExpress.getTemperature() >= maxAlertTemperature) {
alertCount++;
}
if (null != minAlertTemperature && tempExpress.getTemperature() <= minAlertTemperature) {
alertCount++;
}
if (minTemp > tempExpress.getTemperature()) {
minTemp = tempExpress.getTemperature();
}
if (maxTemp < tempExpress.getTemperature()) {
maxTemp = tempExpress.getTemperature();
}
if (minHumidity > tempExpress.getHumidity()) {
minHumidity = tempExpress.getHumidity();
}
if (maxHumidity < tempExpress.getHumidity()) {
maxHumidity = tempExpress.getHumidity();
}
averageTemp += tempExpress.getTemperature() / size;
averageHumidity += tempExpress.getHumidity() / size;
}
}
//将统计数据添加到报表
briefTable.addCell(new Paragraph("报警次数").setFont(helvetica)).addCell(new Paragraph
(alertCount + "").setFont(helvetica));
if (null != averageTemp) {
briefTable.addCell(new Paragraph("平均温度").setFont(helvetica)).addCell(new Paragraph
(averageTemp + "").setFont(helvetica));
} else {
briefTable.addCell(new Paragraph("平均温度").setFont(helvetica)).addCell(new Paragraph
("无").setFont(helvetica));
}
if (null != maxTemp) {
briefTable.addCell(new Paragraph("最高温度").setFont(helvetica)).addCell(new Paragraph
(maxTemp + "").setFont(helvetica));
} else {
briefTable.addCell(new Paragraph("最高温度").setFont(helvetica)).addCell(new Paragraph
("无").setFont(helvetica));
}
if (null != minTemp) {
briefTable.addCell(new Paragraph("最低温度").setFont(helvetica)).addCell(new Paragraph
(minTemp + "").setFont(helvetica));
} else {
briefTable.addCell(new Paragraph("最低温度").setFont(helvetica)).addCell(new Paragraph
("无").setFont(helvetica));
}
if (null != averageHumidity && averageHumidity > 0) {
briefTable.addCell(new Paragraph("平均湿度").setFont(helvetica)).addCell(new Paragraph
(averageHumidity + "").setFont(helvetica));
} else {
// briefTable.addCell(new Paragraph("平均湿度").setFont(helvetica)).addCell(new Paragraph
// ("无").setFont(helvetica));
}
if (null != maxHumidity && maxHumidity > 0) {
briefTable.addCell(new Paragraph("最高湿度").setFont(helvetica)).addCell(new Paragraph
(maxHumidity + "").setFont(helvetica));
} else {
// briefTable.addCell(new Paragraph("最高湿度").setFont(helvetica)).addCell(new Paragraph
// ("无").setFont(helvetica));
}
if (null != minHumidity && minHumidity > 0) {
briefTable.addCell(new Paragraph("最低湿度").setFont(helvetica)).addCell(new Paragraph
(minHumidity + "").setFont(helvetica));
} else {
// briefTable.addCell(new Paragraph("最低湿度").setFont(helvetica)).addCell(new Paragraph
// ("无").setFont(helvetica));
}
briefTable.addCell(new Paragraph("设备识别号").setFont(helvetica)).addCell(new Cell(1, 5).add(new Paragraph
(tag.getTagNo()).setFont(helvetica)));
//添加到pdf
document.add(new Paragraph("数据曲线").setFont(helvetica).setFontSize(24));
document.add(image);
document.add(new Paragraph("数据报表").setFont(helvetica).setFontSize(24));
document.add(briefTable);
document.add(new Paragraph("原始数据").setFont(helvetica).setFontSize(24));
document.add(originalDataTable);
//Close document
document.close();
pdf.close();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void exportToXLS(int expressId, Date start, Date end, int flag, HttpServletRequest request,
HttpServletResponse response) {
try {
ServletOutputStream outputStream = response.getOutputStream();
response.reset();//清空输出流
response.setContentType("application/msexcel");
List<TempExpress> tempExpressList = tempExpressDAO.getByExpressIdWithTimeLimit(expressId,
start, end);
Express express = expressDAO.getById(expressId);
// TagExpress tagExpress = tagExpressDAO.getLastTagExpressByEId(expressId);
// Tag tag = tagDAO.getById(tagExpress.getTagNo());
String fileName = express.getExpressNo();
if (StringUtils.isEmpty(fileName)) {
fileName = expressId + ".xls";
} else {
fileName += ".xls";
}
//不同版本名称
String expressNo;
if (flag == Constants.Version.EXPRESS) {
//物流版
expressNo = "订单号";
} else {
//医药/标准版
expressNo = "监测点名称";
}
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
WritableWorkbook wwb = Workbook.createWorkbook(outputStream);
WritableSheet ws = wwb.createSheet("sheet1", 0);
ws.addCell(new Label(0, 0, expressNo)); //将生成的单元格添加到工作表中
ws.addCell(new Label(1, 0, express.getExpressNo()));
ws.addCell(new Label(0, 1, "时间"));
ws.addCell(new Label(1, 1, "温度(℃)"));
int row = 2;
if (tempExpressList.size() > 0 && tempExpressList.get(0).getHumidity() > 0) {
for (TempExpress tempExpress : tempExpressList) {
ws.addCell(new Label(2, 1, "湿度(%)"));
ws.addCell(new Label(0, row, Utils.SF.format(tempExpress.getCreationTime())));
ws.addCell(new Label(1, row, tempExpress.getTemperature() + ""));
ws.addCell(new Label(2, row, tempExpress.getHumidity() + ""));
row++;
}
} else {
for (TempExpress tempExpress : tempExpressList) {
ws.addCell(new Label(0, row, Utils.SF.format(tempExpress.getCreationTime())));
ws.addCell(new Label(1, row, tempExpress.getTemperature() + ""));
row++;
}
}
wwb.write();
wwb.close();
} catch (IOException | WriteException e) {
e.printStackTrace();
}
}
@Override
public void exportCalibrationToPDF(String tagNo, HttpServletRequest request, HttpServletResponse response) {
try {
ServletOutputStream outputStream = response.getOutputStream();
response.reset();
response.setContentType("application/pdf");
Tag tag = tagDAO.getById(tagNo);
if (null == tag) {
return;
}
String fileName = tag.getTagNo() + ".pdf";
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
//Initialize PDF writer
PdfWriter writer = new PdfWriter(outputStream);
//Initialize PDF document
PdfDocument pdf = new PdfDocument(writer);
// Initialize document
Document document = new Document(pdf);
PdfFont helvetica = PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
String rangeCN, rangeEN, rangeHCN, rangHEN, model;
if (tag.getCalibrationType() == Constants.Calibrate.TM20) {
rangeCN = "测温范围:-20 ~ 50℃";
rangeEN = "Temp Range:-20 ~ 50℃";
rangeHCN = "";
rangHEN = "";
model = "TM20";
} else if (tag.getCalibrationType() == Constants.Calibrate.TM20E) {
rangeCN = "测温范围:-100 ~ 50℃";
rangeEN = "Temp Range:-100 ~ 50℃";
rangeHCN = "";
rangHEN = "";
model = "TM20E";
} else if (tag.getCalibrationType() == Constants.Calibrate.THM20) {
rangeCN = "测温范围:-20 ~ 60℃";
rangeEN = "Temp Range:-20 ~ 60℃";
rangeHCN = "测湿范围:0-100%RH";
rangHEN = "Humidity Range:0-100%RH";
model = "THM20";
} else if (tag.getCalibrationType() == Constants.Calibrate.THM20E) {
rangeCN = "测温范围:-40 ~ 85℃";
rangeEN = "Temp Range:-40 ~ 85℃";
rangeHCN = "测湿范围:0-100%RH";
rangHEN = "Humidity Range:0-100%RH";
model = "THM20E";
} else {
rangeCN = "";
rangeEN = "";
rangeHCN = "";
rangHEN = "";
model = "";
}
//设置默认字体
document.setFont(helvetica);
document.setFontSize(10.5f);
document.add(new Paragraph(""));
document.add(new Paragraph(""));
document.add(new Paragraph(""));
document.add(new Paragraph(""));
document.add(new Paragraph(""));
document.add(new Paragraph(""));
document.add(new Paragraph(""));
document.add(new Paragraph(""));
float[] widths = {170, 180, 180};
Table infoTable = new Table(widths);
infoTable.addCell(new Paragraph("设备名称:智能温湿度监测仪")).addCell(new Paragraph(rangeCN)).addCell(new Paragraph
(rangeHCN));
infoTable.addCell(new Paragraph("Name:Intelligent temperature and humidity monitor")).addCell(new
Paragraph(rangeEN)).addCell(new
Paragraph(rangHEN));
infoTable.addCell(new Cell(1, 3).add(new Paragraph("")));
infoTable.addCell(new Paragraph("型号规格:" + model)).addCell(new Cell(1, 2).add(new Paragraph("设备识别码:" + tag
.getTagNo())));
infoTable.addCell(new Paragraph("Model:" + model)).addCell(new Cell(1, 2).add(new Paragraph("Instrument " +
"ID:" + tag.getTagNo())));
infoTable.addCell(new Cell(1, 3).add(new Paragraph("")));
infoTable.addCell(new Cell(1, 3).add(new Paragraph("校准日期:" + Utils.SF.format(tag.getCalibrationTime()))));
infoTable.addCell(new Cell(1, 3).add(new Paragraph("Calibration Date:" + Utils.SF.format(tag
.getCalibrationTime()))));
infoTable.getCell(0, 0).setBorder(Border.NO_BORDER);
infoTable.getCell(0, 1).setBorder(Border.NO_BORDER);
infoTable.getCell(0, 2).setBorder(Border.NO_BORDER);
infoTable.getCell(1, 0).setBorder(Border.NO_BORDER);
infoTable.getCell(1, 1).setBorder(Border.NO_BORDER);
infoTable.getCell(1, 2).setBorder(Border.NO_BORDER);
infoTable.getCell(2, 0).setBorder(Border.NO_BORDER);
infoTable.getCell(3, 0).setBorder(Border.NO_BORDER);
infoTable.getCell(3, 1).setBorder(Border.NO_BORDER);
infoTable.getCell(4, 0).setBorder(Border.NO_BORDER);
infoTable.getCell(4, 1).setBorder(Border.NO_BORDER);
infoTable.getCell(5, 0).setBorder(Border.NO_BORDER);
infoTable.getCell(6, 0).setBorder(Border.NO_BORDER);
infoTable.getCell(7, 0).setBorder(Border.NO_BORDER);
document.add(infoTable);
DecimalFormat decimalFormat = new DecimalFormat("##0.00");
float[] widths1 = {145, 145, 145, 145};
document.add(new Paragraph(""));
document.add(new Paragraph("一、温度示值校准 Temperature:(℃)"));
Table tempTable = new Table(widths1);
tempTable.addCell(new Paragraph("标准温度值(℃)\n Reference Value"))
.addCell(new Paragraph("被校仪器示值(℃)\n Measured Value"))
.addCell(new Paragraph("示值误差(℃)\n Indication Error"))
.addCell(new Paragraph("允许误差(℃)\n Permissible Error"));
if (tag.getCalibrationType() == Constants.Calibrate.TM20 || tag.getCalibrationType() == Constants
.Calibrate.TM20E) {
tempTable.addCell(new Paragraph(tag.getStandardLowTemp() + ""))
.addCell(new Paragraph(tag.getCalibrationLowTemp() + ""))
.addCell(new Paragraph(decimalFormat.format(tag.getCalibrationLowTemp() - tag
.getStandardLowTemp())))
.addCell(new Paragraph(Constants.Calibrate.PERMISSIBLE_ERROR_TEMP + ""));
tempTable.addCell(new Paragraph(tag.getStandardMediumTemp() + ""))
.addCell(new Paragraph(tag.getCalibrationMediumTemp() + ""))
.addCell(new Paragraph(decimalFormat.format(tag.getCalibrationMediumTemp() - tag
.getStandardMediumTemp())))
.addCell(new Paragraph(Constants.Calibrate.PERMISSIBLE_ERROR_TEMP + ""));
tempTable.addCell(new Paragraph(tag.getStandardHighTemp() + ""))
.addCell(new Paragraph(tag.getCalibrationHighTemp() + ""))
.addCell(new Paragraph(decimalFormat.format(tag.getCalibrationHighTemp() - tag
.getStandardHighTemp())))
.addCell(new Paragraph(Constants.Calibrate.PERMISSIBLE_ERROR_TEMP + ""));
document.add(tempTable);
document.add(new Paragraph(""));
document.add(new Paragraph(""));
document.add(new Paragraph(""));
document.add(new Paragraph(""));
} else {
if (tag.getStandardLowTemp() > 0) {
tempTable.addCell(new Paragraph(tag.getStandardLowTemp() + ""))
.addCell(new Paragraph(tag.getCalibrationLowTemp() + ""))
.addCell(new Paragraph(decimalFormat.format(tag.getCalibrationLowTemp() - tag
.getStandardLowTemp())))
.addCell(new Paragraph(Constants.Calibrate.PERMISSIBLE_ERROR_TEMP + ""));
} else {
tempTable.addCell(new Paragraph(tag.getStandardLowTemp() + ""))
.addCell(new Paragraph(tag.getCalibrationLowTemp() + ""))
.addCell(new Paragraph(decimalFormat.format(tag.getCalibrationLowTemp() - tag
.getStandardLowTemp())))
.addCell(new Paragraph("1"));
}
if (tag.getStandardMediumTemp() > 0) {
tempTable.addCell(new Paragraph(tag.getStandardMediumTemp() + ""))
.addCell(new Paragraph(tag.getCalibrationMediumTemp() + ""))
.addCell(new Paragraph(decimalFormat.format(tag.getCalibrationMediumTemp() - tag
.getStandardMediumTemp())))
.addCell(new Paragraph(Constants.Calibrate.PERMISSIBLE_ERROR_TEMP + ""));
} else {
tempTable.addCell(new Paragraph(tag.getStandardMediumTemp() + ""))
.addCell(new Paragraph(tag.getCalibrationMediumTemp() + ""))
.addCell(new Paragraph(decimalFormat.format(tag.getCalibrationMediumTemp() - tag
.getStandardMediumTemp())))
.addCell(new Paragraph("1"));
}
if (tag.getStandardHighTemp() > 0) {
tempTable.addCell(new Paragraph(tag.getStandardHighTemp() + ""))
.addCell(new Paragraph(tag.getCalibrationHighTemp() + ""))
.addCell(new Paragraph(decimalFormat.format(tag.getCalibrationHighTemp() - tag
.getStandardHighTemp())))
.addCell(new Paragraph(Constants.Calibrate.PERMISSIBLE_ERROR_TEMP + ""));
document.add(tempTable);
} else {
tempTable.addCell(new Paragraph(tag.getStandardHighTemp() + ""))
.addCell(new Paragraph(tag.getCalibrationHighTemp() + ""))
.addCell(new Paragraph(decimalFormat.format(tag.getCalibrationHighTemp() - tag
.getStandardHighTemp())))
.addCell(new Paragraph("1"));
document.add(tempTable);
}
document.add(new Paragraph(""));
document.add(new Paragraph("二、相对湿度示值校准 Relative Humidity:(%RH)"));
Table humidityTable = new Table(widths1);
humidityTable.addCell(new Paragraph("标准湿度值(%RH)\n Reference Value"))
.addCell(new Paragraph("被校仪器示值(%RH)\n Measured Value"))
.addCell(new Paragraph("示值误差(%RH)\n Indication Error"))
.addCell(new Paragraph("允许误差(%RH)\n Permissible Error"));
humidityTable.addCell(new Paragraph(tag.getStandardHumidity() + ""))
.addCell(new Paragraph(tag.getCalibrationHumidity() + ""))
.addCell(new Paragraph(decimalFormat.format(tag.getCalibrationHumidity() - tag
.getStandardHumidity())))
.addCell(new Paragraph(Constants.Calibrate.PERMISSIBLE_ERROR_HUMIDITY + ""));
document.add(humidityTable);
}
document.add(new Paragraph(""));
document.add(new Paragraph("Note:"));
document.add(new Paragraph("1.本次校准依据的技术规范:JJG205-2005 机械式温湿度计检定规程\nReference documents for the " +
"calibration: JJG205-2005 Mechanical " +
"Thermo-hygrometers\n2.本次校准地点及其环境:物华通信及环境试验实验室,25℃,75%RH\nEnvironment Used in Calibration : WUVA " +
"Communications and Environmental test laboratory,25℃," +
"75%RH\n3.本证书仅对所检的器具有效,该证书未经本公司许可不得翻录,本设备校准周期为12 个月\nThis certificate only for the inspection " +
"instruments effectively, the certificate shall not be copied without permission of the company, " +
"the equipment calibration cycle is 12 months\n"));
document.add(new Paragraph(""));
document.add(new Paragraph(""));
document.add(new Paragraph("校 准 员 核 验 员 " +
" 批 准 人\nOperator Inspector " +
" Approver").setTextAlignment(TextAlignment.CENTER));
//Close document
document.close();
pdf.close();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| [
"[email protected]"
] | |
cbf4592d37ac7b546eb545a6b4101a05fd9168ef | 56c068ac8118fbc3e15e37e538935a283b9f908d | /src/com/WaveCreator/TarsosWrapper/TarsosRunner.java | fb45adf23298b6988e2fb6ce2bc40d9e1c254a72 | [] | no_license | nietoperz809/wavecreator | 8944cd630288b234388a0a9cf812ab425541178e | 64f3456208fc891f9a2a5250a564c19bec471a1a | refs/heads/master | 2021-01-17T09:11:52.268778 | 2018-08-26T23:52:21 | 2018-08-26T23:52:21 | 28,629,861 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,605 | java | package com.WaveCreator.TarsosWrapper;
import be.tarsos.dsp.AudioDispatcher;
import be.tarsos.dsp.AudioEvent;
import be.tarsos.dsp.AudioProcessor;
import be.tarsos.dsp.io.jvm.JVMAudioInputStream;
import be.tarsos.dsp.io.jvm.WaveformWriter;
import com.WaveCreator.Wave16;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import java.io.ByteArrayInputStream;
import java.util.ArrayList;
/**
* Created by Administrator on 3/7/2017.
*/
public class TarsosRunner
{
static class Wave16Creator extends WaveformWriter
{
final ArrayList<Wave16> waves = new ArrayList<>();
Wave16 result;
final float sampleRate;
final AudioFormat format;
public Wave16Creator (AudioFormat format)
{
super(format, "tarsosCreated");
sampleRate = format.getSampleRate();
this.format = format;
}
@Override
public boolean process (AudioEvent audioEvent)
{
int byteOverlap = audioEvent.getOverlap() * format.getFrameSize();
int byteStepSize = audioEvent.getBufferSize() * format.getFrameSize() - byteOverlap;
if(audioEvent.getTimeStamp() == 0)
{
byteOverlap = 0;
byteStepSize = audioEvent.getBufferSize() * format.getFrameSize();
}
byte[] fb = audioEvent.getByteBuffer();
Wave16 wv = new Wave16 (fb, (int) sampleRate, byteOverlap, byteStepSize);
waves.add(wv);
return true;
}
@Override
public void processingFinished ()
{
Wave16[] arr = new Wave16[waves.size()];
waves.toArray(arr);
result = Wave16.combineAppend(arr);
//System.out.println("finished");
}
}
public static Wave16 execute (Wave16 in, AudioProcessor proc, int buffsize)
{
byte[] arr = in.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream(arr);
AudioInputStream inputStream = new AudioInputStream(bais, in.getAudioFormat(), arr.length);
int overlap = buffsize-128;
AudioFormat format = inputStream.getFormat(); //new AudioFormat(44100,16,1,true,false); ;
JVMAudioInputStream i2 = new JVMAudioInputStream(inputStream);
AudioDispatcher dispatcher = new AudioDispatcher(i2, buffsize, overlap);
dispatcher.addAudioProcessor(proc);
Wave16Creator wc = new Wave16Creator(format);
dispatcher.addAudioProcessor(wc);
dispatcher.run();
return wc.result;
}
}
| [
"[email protected]"
] | |
a59fe8e47e73c4f5b0c25b4d30fad14bdd15be12 | f91bcd71b19e9a7159816c16a889861b56330a20 | /RemoteMonitor/src/Server/ServerProcess.java | 5792852ddb8b412d6bed992031258b3d115f98bc | [] | no_license | luoxinglian/Lolita | 8b2e9b219a8821ee89d6a814c068cc87934a2325 | 7c5afe3725765f9a71b9f2ec25208e86dd8c5111 | refs/heads/master | 2021-01-12T11:22:34.347625 | 2016-11-06T12:38:06 | 2016-11-06T12:38:06 | 72,906,904 | 0 | 0 | null | 2016-11-05T05:22:55 | 2016-11-05T05:22:54 | null | UTF-8 | Java | false | false | 1,450 | java | package Server;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class ServerProcess extends ArrayList {
private SocketManager socketMan = new SocketManager();
public void getServer() {
try {
ServerSocket serverSocket = new ServerSocket(7788);
System.out.println("�����������Ѿ�����");
while (true) {
Socket socket = serverSocket.accept();
new write_Thread(socket).start();
socketMan.add(socket);
// socketMan.sendClientCount();
}
} catch (Exception e) {
e.printStackTrace();
}
}
class write_Thread extends Thread {
Socket socket = null;
private BufferedReader reader;
private PrintWriter writer;
public write_Thread(Socket socket) {
this.socket = socket;
}
public void run() {
try {
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new PrintWriter(socket.getOutputStream(), true);
String msgArea;
while ((msgArea = reader.readLine()) != null) {
System.out.println(msgArea);
socketMan.sendToAll(msgArea);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String args[]) {
ServerProcess server = new ServerProcess();
server.getServer();
}
public void open() {
// TODO Auto-generated method stub
}
}
| [
"[email protected]"
] | |
d4706556107dffcb0edee8cc9b8f423e5fb3a780 | 525dd1ab6c6ec23fbbfc58a3213c6947bfcf55e4 | /src/TreeVector/NewickParser.java | 009d7f5fac9cd8b5acc296340a09c16891b40a76 | [] | no_license | gatechatl/STRAW | 312f92f0f8c4bd70b5f5422e612ef8762cbda85a | f2f054ba51bcf4be937c17c70c9fc4f82690ad03 | refs/heads/master | 2021-06-26T12:36:00.754838 | 2020-12-25T20:20:05 | 2020-12-25T20:20:05 | 75,668,076 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 10,385 | java | package TreeVector;
import java.util.Stack;
import java.io.*;
/**
* A Parser for the Newick format of tree topologies.
* Contains methods to parse to internal format or output as XML.
* Uses Node objects for internal data structure.
*
* @author Ralph Pethica
* @version 11/08/2006
*/
public class NewickParser
{
private String newick;
private Stack <Node> currentnode;
private Node node;
private int position;
private boolean firstpass;
/**
* Constructor for objects of class NewickParser
*/
public NewickParser()
{
newick = new String();
position = 0;
currentnode = new Stack<Node>();
node = new Node();
currentnode.push(node);
firstpass = true;
}
/**
* Main parser, should be used once the newick string is loaded.
* Can be loaded using readFile or setString methods.
* Possibly change this to several constructors later.
* @param void
* @return void(for now)
*/
public void parseTree()
{
if (newick == null || newick.equals("")){ //Check tree variable has been filled
System.out.println("Please load a tree before using the parsetree method");
System.exit(1);
}
if (checkBrackets() == false){ //Check brackets for pre loaded newick tree
System.out.println("There is a ')' in the wrong place in this tree");
System.exit(1);
}
String noblanks = newick.replace(" ", "");
newick = noblanks; //Get rid of blanks between chars for easier parsing
int i=newick.length();
char c = newick.charAt(i-1);
if(c != ';'){
System.out.println("Tree does not end in a ';'");
System.exit(1);
}
scanNode();
}
/**
* Reads the next node in the newick string
*
* @param void
* @return void
*/
private void scanNode()
{
if (getCurrentChar() == '('){ //if the char is a ( then we must have hit an internal node
scanInternalNode();
//System.out.println("Internal Node Found");
}
else if (getCurrentChar() != ';'){ //if char is anything else, then it must be a leaf node label
getLeafLabel();
//System.out.println("Leaf Label Found");
}
else { //Else must be a ; so report error
System.out.println("Found a ; in the wrong place in tree");
System.exit(1);
}
}
/**
* Reads an internal node of the newick string
*
* @param void
* @return void
*/
private void scanInternalNode()
{
position++;
if (firstpass == true){ //This statement is here to make sure a node is not added as a descendant first time round
firstpass = false; //Once set to false a child node is always added to the stack
}
else{
Node node = new Node(); //We now make a new node
Node topnode = currentnode.pop(); //get the last node from stack
topnode.addChild(node); //add new node as child of last node
currentnode.push(topnode); //push lastnode back
currentnode.push(node); //push new node back
}
scanNode(); //Read the first node
while (getCurrentChar() != ')'){
if (getCurrentChar() == ','){ //if character is a , then move to next char
position++;
//System.out.println("Found a , in while loop and incremented position to: " + position + " char at pos = " + newick.charAt(position));
}
scanNode();
}
position++;
if (getCurrentChar() != ',' && getCurrentChar() != ')' && getCurrentChar() != ';'){ //label found
//System.out.println("About to get label in scanInternalNode method");
Node tempnode = currentnode.pop();
tempnode.setName(getLabel());
currentnode.push(tempnode);
}
if (getCurrentChar() == ':'){ //length found
position++;
Node lengthnode = currentnode.pop(); //pop last node
lengthnode.setLength(getLength()); //set the length to double from getlength method
currentnode.push(lengthnode); //push back on stack
}
currentnode.pop();
}
/**
* Gets the label from a string using the next end character as a mark
*
* @param void
* @return String
*/
private String getLabel()
{
String label = new String();
int end = getNodeEnd(); //find the next end character
int colon = newick.indexOf( ':',position);
if (colon >=0 && colon < end){ //activate when length calculator sorted
end = colon;
}
label = newick.substring(position, end); // get all characters between current position and located end char
position = end; // once done, set the position to end
return label;
}
private void getLeafLabel()
{
String label = getLabel();
Node childnode = new Node();
childnode.setName(label);
childnode.setType("leaf");
if (getCurrentChar() == ':'){
position++;
childnode.setLength(getLength()); //set the length to double from getlength method
}
Node tempnode = currentnode.pop();
tempnode.addChild(childnode);
currentnode.push(tempnode);
//System.out.println("Leaf label found looks like: " + label);
//System.out.println("Char at position now is: " + newick.charAt(position));
}
private double getLength()
{
int end = getNodeEnd();
double length = 0;
String stringlength = newick.substring(position, end);
try {
length = Double.valueOf(stringlength);
}
catch (Exception e){
System.out.println("Error reading branch length");
System.exit(1);
}
position = end; ///May want to add check that end is valid before doing this
//System.out.println("Length found is: " + length);
return length;
}
/**
* Uses the position int to calculate the int location in the newick char array(string) of a end of label character such as ,
*
* @param void
* @return int location
*/
public int getNodeEnd()
{
int comma = newick.indexOf(',',position); //if nothing found a -1 value is returned, and must be checked for later
int semicolon = newick.indexOf(';',position);
int rightbracket = newick.indexOf(')',position);
int leftbracket = newick.indexOf('(',position);
int location = newick.length(); //position of current end char
if (comma >= 0){ //if there is a comma coming up
location = comma; //location of the comma is the current position in string plus distance of comma
}
if(semicolon >= 0 && semicolon < location){ //if there is a semicolon before comma, then use that as end
location = semicolon;
}
if (rightbracket >= 0 && rightbracket < location){ //if there is a right bracket before semicolon, then use that as end
location = rightbracket;
}
if (leftbracket >= 0 && leftbracket < location) {
System.out.println("Found opening bracket in wrong place when detecting node end");
System.exit(1);
}
return location;
}
/**
* Gets the char in the newick string at the location of the position counter int
*
* @param void
* @return char
*/
private char getCurrentChar()
{
if (position>newick.length()){
System.out.println("Position counter off scale of tree string");
System.exit(1);
}
char c = newick.charAt(position);
return c;
}
/**
* Reads a Newick Tree from a file and loads to main string variable
*
* @param String filename
* @return void(for now)
*/
public void readFile(String filename)
{
try
{
BufferedReader in= new BufferedReader(new FileReader(filename));
String line;
String tree = new String();
while ((line = in.readLine()) != null) {
tree = tree + line;
}
in.close();
newick = tree;
//System.out.println(tree);
}
catch (Exception e)
{
System.err.println("File input error, please make sure file name is the first arguement");
}
}
/**
* Loads main variable directly a with newick string
*
* @param String tree
* @return void(for now)
*/
public void setString(String tree)
{
newick = tree;
}
private boolean checkBrackets() //Checks the bracket numbers for a string returns true if OK
{
int bracketcounter = 0;
for (int i=0; i<newick.length();i++){
char c = newick.charAt(i);
if(c == '('){
bracketcounter++;
}
else if(c==')'){
bracketcounter--;
}
if (bracketcounter < 0){ //If there is an closing bracket before the next opening
return false;
}
}
if (bracketcounter > 0){ //If the number of brackets of each type is not equal
return false;
}
return true;
}
/**
* Returns the main (parsed) node of the root of tree
*
* @param void
* @return Node node
*/
public Node getNode()
{
return node;
}
}
| [
"[email protected]"
] | |
2d2ce2bc1585a0e43a1278bd4b7e2fc7a18bb095 | 57f6ad86a4959a7aad2fe609d667ec5ddf081ab8 | /Day1123/src/net/tis/day23/AAA.java | 595e580f8074d7a9a75a100ad5a927751e67b5c7 | [] | no_license | leejj0221/apple | a04426fcfcd46773112357c307fa5cda146160f4 | 847e48daeee700dd60d7d1d8a18fdcde8214c469 | refs/heads/master | 2023-04-07T09:16:54.077075 | 2021-04-06T00:55:41 | 2021-04-06T00:55:41 | 354,688,008 | 0 | 0 | null | null | null | null | WINDOWS-1252 | Java | false | false | 300 | java | package net.tis.day23;
public class AAA {
public int my;
public static void apple() {
System.out.println("\nstatic apple¸Þ¼Òµå");
}//apple END
public void color() {
System.out.println("\nnon-static color");
}//color END
public static void main(String[]args) {
}
}//class AAA END
| [
"[email protected]"
] | |
c24680efbc3f51f3c7d2a283f5da343744fb4596 | 7b9cb42995cd6d61560c8c0e67f3c7ef3cdeb3bc | /src/com/cody/service/sys/ItemService.java | dceba595c825a5f25cdd07c817c9593b5806ce88 | [] | no_license | visket/xmsb | 28fbe7ca490f32798ef6a209729821470d601399 | 17ec00e439f6a9c853ae091fa4c5891718c338f2 | refs/heads/master | 2021-01-18T04:44:20.741738 | 2017-03-08T13:58:32 | 2017-03-08T13:58:32 | 84,274,237 | 0 | 0 | null | 2017-03-08T13:58:32 | 2017-03-08T03:28:34 | JavaScript | UTF-8 | Java | false | false | 1,291 | java | package com.cody.service.sys;
import java.util.List;
import com.cody.common.utils.PageInfo;
import com.cody.entity.sys.Item;
public interface ItemService {
/**
* 删除
*
* @param id
* @return
*/
int deleteByPrimaryKey(String id);
/**
* 添加
*
* @param record
* @return
*/
int insert(Item record);
/**
* 添加
*
* @param record
* @return
*/
int insertSelective(Item record);
/**
* 查找
*
* @param id
* @return
*/
Item selectByPrimaryKey(String id);
/**
* 修改
*
* @param record
* @return
*/
int updateByPrimaryKeySelective(Item record);
/**
* 修改
*
* @param record
* @return
*/
int updateByPrimaryKey(Item record);
/**
* 分页
*
* @param pageInfo
*/
void find(PageInfo pageInfo);
/**
* 通过父字典的 代号 找出所有的子字典项
*
* @param dictionarycode
* @return
*/
List<Item> findByDictionarycode(String dictionarycode);
/**
* 通过子字典的代号查询子字典对象
*
* @param itemcode
* @return
*/
Item findByCode(String itemcode);
/**
* 用来过滤查询 单位等级的
*
* @return
*/
List<Item> findToGradetype();
/**
* 批量删除
*
* @param ids
* @return
*/
int deleteByPrimaryKeys(String[] ids);
}
| [
"[email protected]"
] | |
0ad7337ed80647391080208b1b32e6d121c420f4 | e2c9c5041db56f6ca85733da44e6f82bb3696da5 | /src/broadreach/Clinician/ViewPatientMedHistory.java | e2af0342ff495226ffa4bc5c49ef259c9ffb38c5 | [] | no_license | GullianvdWalt/BroadReach | 32ad1c13ad1fe93a1016253691da9a85e2540d8e | b28f529cc210559e0f822aa5a6d438c5418c9889 | refs/heads/master | 2023-01-10T12:34:06.612700 | 2020-11-10T10:14:11 | 2020-11-10T10:14:11 | 264,821,970 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 19,998 | java | /**
*
* @author Gullian Van Der Walt
* H5G8YT7X3
* ITDA301 - Project 2020
* Pearson Pretoria
* BSC IT Level 3
*
*
*
* This Is The Patient Medical History View
*
*
*/
package broadreach.Clinician;
public class ViewPatientMedHistory extends javax.swing.JFrame {
/**
* Creates new form ViewPatientMedHistory
*/
public ViewPatientMedHistory() {
initComponents();
}
/**
* 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() {
patientMedHistPanel = new javax.swing.JPanel();
headPanel1 = new javax.swing.JPanel();
headSubPanel2 = new javax.swing.JPanel();
homeBtnDiagnosis1 = new javax.swing.JButton();
headSubPanel3 = new javax.swing.JPanel();
medHistoryIcon = new javax.swing.JLabel();
patientMedHistoryLbl = new javax.swing.JLabel();
subheadingLbl = new javax.swing.JLabel();
headSubPanel4 = new javax.swing.JPanel();
exitBtn = new javax.swing.JButton();
bodyPanel = new javax.swing.JPanel();
subBodyPanel = new javax.swing.JPanel();
filterPanel = new javax.swing.JPanel();
filterIcon = new javax.swing.JLabel();
pNameLbl = new javax.swing.JLabel();
pNameTxtFld = new javax.swing.JTextField();
pSurnameLbl = new javax.swing.JLabel();
pSurnameTxtFld = new javax.swing.JTextField();
saIDLbl = new javax.swing.JLabel();
saIDTxtFld = new javax.swing.JTextField();
pastTestDBPane = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
patientMedHistTbl = new javax.swing.JTable();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("BroadReach - Patient Medical History");
setName("patientMedHistoryFrame"); // NOI18N
patientMedHistPanel.setBackground(new java.awt.Color(255, 255, 255));
patientMedHistPanel.setMaximumSize(new java.awt.Dimension(1920, 1080));
patientMedHistPanel.setMinimumSize(new java.awt.Dimension(1920, 1080));
patientMedHistPanel.setPreferredSize(new java.awt.Dimension(1920, 1080));
headPanel1.setBackground(new java.awt.Color(0, 46, 93));
headPanel1.setMaximumSize(new java.awt.Dimension(1920, 227));
headPanel1.setMinimumSize(new java.awt.Dimension(1440, 227));
headPanel1.setPreferredSize(new java.awt.Dimension(1920, 225));
headPanel1.setLayout(new java.awt.GridLayout(1, 1));
headSubPanel2.setBackground(new java.awt.Color(0, 46, 93));
headSubPanel2.setPreferredSize(new java.awt.Dimension(640, 227));
homeBtnDiagnosis1.setBackground(new java.awt.Color(0, 46, 93));
homeBtnDiagnosis1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/home.png"))); // NOI18N
homeBtnDiagnosis1.setBorderPainted(false);
homeBtnDiagnosis1.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
homeBtnDiagnosis1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
homeBtnDiagnosis1ActionPerformed(evt);
}
});
javax.swing.GroupLayout headSubPanel2Layout = new javax.swing.GroupLayout(headSubPanel2);
headSubPanel2.setLayout(headSubPanel2Layout);
headSubPanel2Layout.setHorizontalGroup(
headSubPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(headSubPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(homeBtnDiagnosis1, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(524, Short.MAX_VALUE))
);
headSubPanel2Layout.setVerticalGroup(
headSubPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, headSubPanel2Layout.createSequentialGroup()
.addContainerGap(109, Short.MAX_VALUE)
.addComponent(homeBtnDiagnosis1)
.addContainerGap())
);
headPanel1.add(headSubPanel2);
headSubPanel3.setBackground(new java.awt.Color(0, 46, 93));
headSubPanel3.setPreferredSize(new java.awt.Dimension(640, 227));
medHistoryIcon.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/clinic_Logo.png"))); // NOI18N
patientMedHistoryLbl.setFont(new java.awt.Font("Constantia", 1, 36)); // NOI18N
patientMedHistoryLbl.setForeground(new java.awt.Color(255, 255, 255));
patientMedHistoryLbl.setText("Patient Medical History");
patientMedHistoryLbl.setToolTipText("");
patientMedHistoryLbl.setVerticalAlignment(javax.swing.SwingConstants.TOP);
subheadingLbl.setFont(new java.awt.Font("Constantia", 1, 36)); // NOI18N
subheadingLbl.setForeground(new java.awt.Color(255, 255, 255));
subheadingLbl.setText("BroadReach Clinic");
subheadingLbl.setToolTipText("");
subheadingLbl.setVerticalAlignment(javax.swing.SwingConstants.TOP);
javax.swing.GroupLayout headSubPanel3Layout = new javax.swing.GroupLayout(headSubPanel3);
headSubPanel3.setLayout(headSubPanel3Layout);
headSubPanel3Layout.setHorizontalGroup(
headSubPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(headSubPanel3Layout.createSequentialGroup()
.addContainerGap(66, Short.MAX_VALUE)
.addComponent(medHistoryIcon)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(headSubPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(patientMedHistoryLbl)
.addComponent(subheadingLbl, javax.swing.GroupLayout.PREFERRED_SIZE, 334, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(67, 67, 67))
);
headSubPanel3Layout.setVerticalGroup(
headSubPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(headSubPanel3Layout.createSequentialGroup()
.addGap(34, 34, 34)
.addComponent(subheadingLbl)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 40, Short.MAX_VALUE)
.addGroup(headSubPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, headSubPanel3Layout.createSequentialGroup()
.addComponent(medHistoryIcon)
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, headSubPanel3Layout.createSequentialGroup()
.addComponent(patientMedHistoryLbl)
.addGap(27, 27, 27))))
);
headPanel1.add(headSubPanel3);
headSubPanel4.setBackground(new java.awt.Color(0, 46, 93));
headSubPanel4.setPreferredSize(new java.awt.Dimension(640, 227));
exitBtn.setBackground(new java.awt.Color(0, 46, 93));
exitBtn.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/exit_icon.png"))); // NOI18N
exitBtn.setToolTipText("Exit BroadReach");
exitBtn.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
exitBtn.setBorderPainted(false);
exitBtn.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
exitBtn.setDefaultCapable(false);
exitBtn.setPreferredSize(new java.awt.Dimension(97, 97));
exitBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exitBtnActionPerformed(evt);
}
});
javax.swing.GroupLayout headSubPanel4Layout = new javax.swing.GroupLayout(headSubPanel4);
headSubPanel4.setLayout(headSubPanel4Layout);
headSubPanel4Layout.setHorizontalGroup(
headSubPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, headSubPanel4Layout.createSequentialGroup()
.addContainerGap(533, Short.MAX_VALUE)
.addComponent(exitBtn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
headSubPanel4Layout.setVerticalGroup(
headSubPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, headSubPanel4Layout.createSequentialGroup()
.addContainerGap(117, Short.MAX_VALUE)
.addComponent(exitBtn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
headPanel1.add(headSubPanel4);
patientMedHistPanel.add(headPanel1);
bodyPanel.setBackground(new java.awt.Color(255, 255, 255));
bodyPanel.setForeground(new java.awt.Color(0, 46, 93));
bodyPanel.setMinimumSize(new java.awt.Dimension(1920, 853));
bodyPanel.setPreferredSize(new java.awt.Dimension(1920, 853));
subBodyPanel.setBackground(new java.awt.Color(255, 255, 255));
subBodyPanel.setMinimumSize(new java.awt.Dimension(900, 853));
subBodyPanel.setPreferredSize(new java.awt.Dimension(1650, 750));
filterPanel.setBackground(new java.awt.Color(255, 255, 255));
filterPanel.setPreferredSize(new java.awt.Dimension(1625, 160));
java.awt.FlowLayout flowLayout1 = new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 20, 5);
flowLayout1.setAlignOnBaseline(true);
filterPanel.setLayout(flowLayout1);
filterIcon.setFont(new java.awt.Font("Constantia", 0, 24)); // NOI18N
filterIcon.setForeground(new java.awt.Color(0, 46, 93));
filterIcon.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/filter.png"))); // NOI18N
filterPanel.add(filterIcon);
pNameLbl.setFont(new java.awt.Font("Constantia", 0, 24)); // NOI18N
pNameLbl.setForeground(new java.awt.Color(0, 46, 93));
pNameLbl.setText("Patient Name:");
filterPanel.add(pNameLbl);
pNameTxtFld.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
pNameTxtFld.setToolTipText("");
pNameTxtFld.setActionCommand("<Not Set>");
pNameTxtFld.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 46, 93), 2, true));
pNameTxtFld.setPreferredSize(new java.awt.Dimension(232, 45));
pNameTxtFld.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
pNameTxtFldActionPerformed(evt);
}
});
filterPanel.add(pNameTxtFld);
pSurnameLbl.setFont(new java.awt.Font("Constantia", 0, 24)); // NOI18N
pSurnameLbl.setForeground(new java.awt.Color(0, 46, 93));
pSurnameLbl.setText("Patient Surname:");
filterPanel.add(pSurnameLbl);
pSurnameTxtFld.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
pSurnameTxtFld.setToolTipText("");
pSurnameTxtFld.setActionCommand("<Not Set>");
pSurnameTxtFld.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 46, 93), 2, true));
pSurnameTxtFld.setPreferredSize(new java.awt.Dimension(232, 45));
pSurnameTxtFld.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
pSurnameTxtFldActionPerformed(evt);
}
});
filterPanel.add(pSurnameTxtFld);
saIDLbl.setFont(new java.awt.Font("Constantia", 0, 24)); // NOI18N
saIDLbl.setForeground(new java.awt.Color(0, 46, 93));
saIDLbl.setText("SA ID:");
filterPanel.add(saIDLbl);
saIDTxtFld.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
saIDTxtFld.setToolTipText("");
saIDTxtFld.setActionCommand("<Not Set>");
saIDTxtFld.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 46, 93), 2, true));
saIDTxtFld.setPreferredSize(new java.awt.Dimension(232, 45));
saIDTxtFld.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
saIDTxtFldActionPerformed(evt);
}
});
filterPanel.add(saIDTxtFld);
subBodyPanel.add(filterPanel);
pastTestDBPane.setBackground(new java.awt.Color(255, 255, 255));
pastTestDBPane.setPreferredSize(new java.awt.Dimension(1625, 570));
patientMedHistTbl.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4", "Title 5", "Title 6", "Title 7", "Title 8", "Title 9", "Title 10", "Title 11", "Title 12"
}
));
jScrollPane1.setViewportView(patientMedHistTbl);
javax.swing.GroupLayout pastTestDBPaneLayout = new javax.swing.GroupLayout(pastTestDBPane);
pastTestDBPane.setLayout(pastTestDBPaneLayout);
pastTestDBPaneLayout.setHorizontalGroup(
pastTestDBPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pastTestDBPaneLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 1605, Short.MAX_VALUE)
.addContainerGap())
);
pastTestDBPaneLayout.setVerticalGroup(
pastTestDBPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pastTestDBPaneLayout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 559, Short.MAX_VALUE)
.addContainerGap())
);
subBodyPanel.add(pastTestDBPane);
bodyPanel.add(subBodyPanel);
patientMedHistPanel.add(bodyPanel);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(patientMedHistPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(patientMedHistPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 1028, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
//Home Button
private void homeBtnDiagnosis1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_homeBtnDiagnosis1ActionPerformed
new ClinicianHome().setVisible(true);
this.setVisible(false);
}//GEN-LAST:event_homeBtnDiagnosis1ActionPerformed
//Exit Button
private void exitBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitBtnActionPerformed
System.exit(0);
}//GEN-LAST:event_exitBtnActionPerformed
private void pNameTxtFldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pNameTxtFldActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_pNameTxtFldActionPerformed
private void pSurnameTxtFldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pSurnameTxtFldActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_pSurnameTxtFldActionPerformed
private void saIDTxtFldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saIDTxtFldActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_saIDTxtFldActionPerformed
/**
* @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(ViewPatientMedHistory.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ViewPatientMedHistory.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ViewPatientMedHistory.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ViewPatientMedHistory.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() {
new ViewPatientMedHistory().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel bodyPanel;
private javax.swing.JButton exitBtn;
private javax.swing.JLabel filterIcon;
private javax.swing.JPanel filterPanel;
private javax.swing.JPanel headPanel1;
private javax.swing.JPanel headSubPanel2;
private javax.swing.JPanel headSubPanel3;
private javax.swing.JPanel headSubPanel4;
private javax.swing.JButton homeBtnDiagnosis1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel medHistoryIcon;
private javax.swing.JLabel pNameLbl;
private javax.swing.JTextField pNameTxtFld;
private javax.swing.JLabel pSurnameLbl;
private javax.swing.JTextField pSurnameTxtFld;
private javax.swing.JPanel pastTestDBPane;
private javax.swing.JPanel patientMedHistPanel;
private javax.swing.JTable patientMedHistTbl;
private javax.swing.JLabel patientMedHistoryLbl;
private javax.swing.JLabel saIDLbl;
private javax.swing.JTextField saIDTxtFld;
private javax.swing.JPanel subBodyPanel;
private javax.swing.JLabel subheadingLbl;
// End of variables declaration//GEN-END:variables
}
| [
"[email protected]"
] | |
7992e136da5e3bed413ef11c9017e504ae92a951 | 1b02b3a179e2bdd2a6d2805373e4b3e8e8f3ae9c | /src/Student.java | 5c179f6467fb7ce6e3c176d6e240f6f2f651a2cd | [] | no_license | Lucihpet/Lab9 | 075cd7b5dcac4a4a6a6762454865d52b6c1b405c | 8f1cb0287abfcfe106a841bd59a52884719bb3f3 | refs/heads/master | 2021-02-26T00:33:32.924838 | 2020-03-11T03:14:49 | 2020-03-11T03:14:49 | 245,480,778 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,476 | java | import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class Student /*implements Comparable<Student>*/ /*implements Cloneable*/ implements Serializable {
protected String name;
protected double GPA;
public Student (String n, double gpa) {
this.name = n;
this. GPA = gpa;
}
public Student (Student other) {
this.name = other.name;
this.GPA = other.GPA;
}
public void setName(String n) {
this.name = n;
}
public void setGPA(double gpa) {
this.GPA = gpa;
}
public String getName() {
return this.name;
}
public double getGPA() {
return this.GPA;
}
public int compareTo(Student other) {
return (int)(this.GPA - other.GPA);
}
@Override
public Student clone() {
return new Student(this);
}
public static void main (String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student("Tim", 3.4));
students.add(new Student("Allison", 3.7));
students.add(new Student("Matt", 3.2));
students.add(new Student("Fred", 2.7));
students.add(new Student("Beth", 3.9));
students.add(new Student("Heather", 4.0));
students.add(new Student("Jake", 3.2));
students.add(new Student("Zack", 2.9));
students.add(new Student("Chris", 3.0));
students.add(new Student("Melody", 3.7));
}
}
| [
"[email protected]"
] | |
c1cc3623291ff5aee7d7d4bf5c97f2f1ad332e5f | 23827633298df1569d2e64e623c0e5a6d97cdfa6 | /observer/src/main/java/cn/ep/dp/observer/impl/Watcher.java | 9032deac8a49fefab84bd5e6c042a5b0dcb15ab1 | [] | no_license | dark-ep/design-patterns | e556ede3f1e9ccb78c1a3057c5f6226a1eafef04 | a54720b648c513462f20f43c140edbb15284ae8c | refs/heads/master | 2020-03-25T11:32:50.792419 | 2018-01-12T07:39:08 | 2018-01-12T07:39:08 | 143,736,976 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 629 | java | package cn.ep.dp.observer.impl;
import cn.ep.dp.observer.WatcherObserver;
import cn.ep.dp.observer.subject.BaseWaterQuality;
/**
* @author lhl
*/
public class Watcher implements WatcherObserver {
/**
* 职务
*/
private String job;
@Override
public String getJob() {
return job;
}
@Override
public void setJob(String job) {
this.job = job;
}
@Override
public void update(BaseWaterQuality subject) {
// 这里是采用拉的方式
System.out.println(job + "获取到通知,当前污染级别为:" + subject.getPolluteLevel());
}
}
| [
"[email protected]"
] | |
cd8ea3318bceab1785267d20b7e730d02916af13 | 0d163e2b966ee5959554610951ecf3c85bc77a13 | /src/main/java/com/jctp/md/JCTPMdSpiAdapter.java | 5dcb602bc492bcafb4b4be6e6c386fa1f48a0d3e | [] | no_license | jiangcuilan/JCTP | 46dda8f84c44ad5765f9a7a5073515677615c991 | 62863c1f157047b9a87eaaf3c7fa16f36eb1c2ee | refs/heads/master | 2021-01-20T20:36:21.325448 | 2016-08-07T04:01:33 | 2016-08-07T04:01:33 | 64,987,317 | 5 | 5 | null | null | null | null | UTF-8 | Java | false | false | 3,082 | java | package com.jctp.md;
import static com.jctp.util.JCTPStructUtil.getStructObject;
import org.bridj.BridJ;
import org.bridj.Pointer;
import org.bridj.StructObject;
import org.bridj.ann.Virtual;
import com.ctp.thostftdcmdapi.CThostFtdcMdSpi;
import com.ctp.thostftdcuserapistruct.CThostFtdcDepthMarketDataField;
import com.ctp.thostftdcuserapistruct.CThostFtdcRspInfoField;
import com.ctp.thostftdcuserapistruct.CThostFtdcRspUserLoginField;
import com.ctp.thostftdcuserapistruct.CThostFtdcSpecificInstrumentField;
import com.ctp.thostftdcuserapistruct.CThostFtdcUserLogoutField;
/**
* MdSpi适配器类
*
* @author Hraink E-mail:[email protected]
* @version 2013-1-27 上午11:31:12
*/
public final class JCTPMdSpiAdapter extends CThostFtdcMdSpi{
JCTPMdSpi mdSpi;
public JCTPMdSpiAdapter(JCTPMdSpi mdSpi) {
BridJ.protectFromGC(this);
this.mdSpi = mdSpi;
}
@Override
@Virtual(0)
public void OnFrontConnected() {
mdSpi.onFrontConnected();
}
@Override
@Virtual(1)
public void OnFrontDisconnected(int nReason) {
mdSpi.onFrontDisconnected(nReason);
}
@Override
@Virtual(2)
public void OnHeartBeatWarning(int nTimeLapse) {
mdSpi.onHeartBeatWarning(nTimeLapse);
}
@Override
@Virtual(3)
public void OnRspUserLogin(
Pointer<CThostFtdcRspUserLoginField> pRspUserLogin,
Pointer<CThostFtdcRspInfoField> pRspInfo, int nRequestID,
boolean bIsLast) {
mdSpi.onRspUserLogin(getStructObject(pRspUserLogin), getStructObject(pRspInfo), nRequestID, bIsLast);
}
@Override
@Virtual(4)
public void OnRspUserLogout(Pointer<CThostFtdcUserLogoutField> pUserLogout,
Pointer<CThostFtdcRspInfoField> pRspInfo, int nRequestID,
boolean bIsLast) {
mdSpi.onRspUserLogout(getStructObject(pUserLogout), getStructObject(pRspInfo), nRequestID, bIsLast);
}
@Override
@Virtual(5)
public void OnRspError(Pointer<CThostFtdcRspInfoField> pRspInfo,
int nRequestID, boolean bIsLast) {
mdSpi.onRspError(getStructObject(pRspInfo), nRequestID, bIsLast);
}
@Override
@Virtual(6)
public void OnRspSubMarketData(
Pointer<CThostFtdcSpecificInstrumentField> pSpecificInstrument,
Pointer<CThostFtdcRspInfoField> pRspInfo, int nRequestID,
boolean bIsLast) {
mdSpi.onRspSubMarketData(getStructObject(pSpecificInstrument), getStructObject(pRspInfo), nRequestID, bIsLast);
}
@Override
@Virtual(7)
public void OnRspUnSubMarketData(
Pointer<CThostFtdcSpecificInstrumentField> pSpecificInstrument,
Pointer<CThostFtdcRspInfoField> pRspInfo, int nRequestID,
boolean bIsLast) {
mdSpi.onRspUnSubMarketData(getStructObject(pSpecificInstrument), getStructObject(pRspInfo), nRequestID, bIsLast);
}
@Override
@Virtual(8)
public void OnRtnDepthMarketData(
Pointer<CThostFtdcDepthMarketDataField> pDepthMarketData) {
mdSpi.onRtnDepthMarketData(getStructObject(pDepthMarketData));
}
/**
* 获得Field
*
* 对可能出现的null值做处理
* @param <T>
* @param field field的指针对象
* @return
*/
private <T extends StructObject> T getField(Pointer<T> field) {
return field == null ? null : field.get();
}
}
| [
"[email protected]"
] | |
a635638b46e1cfb7518cf05d055366a3e60a54b4 | eadd59d4d3755818f76ce344109345a95cf3c001 | /src/Endoscopy/EndoscopyExtractorOld.java | 3dbbdd79b10841e65b0185c4951b547d9a8c017d | [] | no_license | sebastiz/Physipopv2.0.3 | 129728fcf24c56afc1e97bb206c7d93dec54b902 | 86184120deb321afd1e04e2eda4d866fca07b922 | refs/heads/master | 2021-09-24T08:11:44.695007 | 2018-10-05T12:10:59 | 2018-10-05T12:10:59 | 105,247,903 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,974 | java |
package Endoscopy;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import Overview.Checkers;
import Overview.DBConnectorForAll;
import org.pmw.tinylog.Logger;
public class EndoscopyExtractorOld {
public EndoscopyExtractorOld() {
}
public static void Endoscopy_mane(String filepath) throws IOException, SQLException {
String first="";
String second="";
Statement st;
String tab="";
String FName=null;
String SName=null;
String HospNum=null;
String DOB=null;
String VisitDate=null;
String ResultPerformed=null;
//Take the spreadsheet and look at the visitDate
//Then take the pathology spreadsheet and look at the sample taken date
//Then add the array togather for the ones where the Hospital NUmber and VisitDate match
//Then you need to add the pathology reports together and the endoscopies together so that the next iteration of endoscopies have no loose ends of pathology
////System.out.println("Yes I am over here in the Endoscopy Section");
Map<String,String> mapEndoscBarr= new LinkedHashMap<String,String>();
FileInputStream fis = new FileInputStream(new File(filepath));
HSSFWorkbook workBook = new HSSFWorkbook (fis);
HSSFSheet sheet = workBook.getSheetAt (0);
List<HSSFRow> filteredRows = new ArrayList<HSSFRow>();
//Filter by pathology from what I am given
Iterator<Row> rows= sheet.rowIterator();
while (rows.hasNext ()){
HSSFRow row = (HSSFRow) rows.next ();
Iterator<Cell> cells = row.cellIterator ();
while (cells.hasNext ()){
HSSFCell cell = (HSSFCell) cells.next ();
if (cell.toString().contains("Barrett")) {
filteredRows.add(row);
break;
}
}
}
////System.out.println("filteredRowsSIZE"+filteredRows.size());
ArrayList<List<String>> out = new ArrayList<List<String>>();
for (HSSFRow n:filteredRows){
Iterator<Cell> cells = n.cellIterator ();
ArrayList<String> in =new ArrayList<String>();
while (cells.hasNext ()){
HSSFCell cell = (HSSFCell) cells.next ();
in.add(cell.toString());
}
out.add(in);
}
workBook.close();
//Add each array to a HashMap
////System.out.println("OUTSIZE"+out.size());
int adder=0;
for (List<String> n:out){
adder++;
if(adder % 5 == 0){
//System.out.println("Divisible by 2");
try {
//System.gc();
Thread.sleep(500);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
mapEndoscBarr.clear();
////System.out.println("NNNNNNNNNNN"+n);
try {
HospNum=n.get(0).trim();
mapEndoscBarr.put("HospNum_Id", n.get(1).trim());
} catch (Exception e10) {
e10.printStackTrace();
}
try {
FName=n.get(2).trim();
mapEndoscBarr.put("FIRSTNAME", n.get(2).trim().replaceAll("'", ""));
} catch (Exception e9) {
e9.printStackTrace();
}
try {
SName=n.get(3).trim();
mapEndoscBarr.put("LASTNAME", n.get(3).trim().replaceAll("'", ""));
} catch (Exception e8) {
e8.printStackTrace();
}
try {
mapEndoscBarr.put("ENDOSCOPIST", n.get(4).trim().replaceAll("'", ""));
} catch (Exception e7) {
e7.printStackTrace();
}
try {
mapEndoscBarr.put("ENDOTWO", n.get(5).trim());
} catch (Exception e6) {
e6.printStackTrace();
}
try {
mapEndoscBarr.put("TRAINEE", n.get(6).trim());
} catch (Exception e5) {
e5.printStackTrace();
}
try {
mapEndoscBarr.put("ER_PROCEDUREPERFORMED", n.get(7).trim());
} catch (Exception e) {
e.printStackTrace();
}
try {
mapEndoscBarr.put("VisitDate", n.get(8).trim());
VisitDate=n.get(8).trim();
} catch (Exception e4) {
e4.printStackTrace();
}
try {
mapEndoscBarr.put("ROOM", n.get(9).trim().replaceAll("'", ""));
} catch (Exception e3) {
e3.printStackTrace();
}
try {
mapEndoscBarr.put("INDICATIONS", n.get(10).trim().replaceAll("'", ""));
} catch (Exception e2) {
e2.printStackTrace();
}
try {
mapEndoscBarr.put("ER_EXTENTOFEXAM", n.get(11).trim().replaceAll("'", ""));
} catch (Exception e1) {
e1.printStackTrace();
}
try {
mapEndoscBarr.put("ER_FINDINGS_STR", n.get(12).trim().replaceAll("'", ""));
} catch (Exception e) {
e.printStackTrace();
}
try {
mapEndoscBarr.put("ER_DIAGNOSIS_STR", n.get(13).trim().replaceAll("'", ""));
} catch (Exception e) {
e.printStackTrace();
}
try {
mapEndoscBarr.put("ER_RECOMMENDATIONS", n.get(14).trim().replaceAll("'", ""));
} catch (Exception e) {
e.printStackTrace();
}
try {
mapEndoscBarr.put("ER_RECALLREASON1", n.get(15).trim().replaceAll("'", ""));
} catch (Exception e) {
e.printStackTrace();
}
try {
Pattern CStage_pattern = Pattern.compile("(C(\\s|=)*\\d+)",Pattern.DOTALL);
Matcher matcherC12Stage_pattern = CStage_pattern.matcher(n.get(12).toString().trim());
Matcher matcherC13Stage_pattern = CStage_pattern.matcher(n.get(13).toString().trim());
if (matcherC12Stage_pattern.find()) {
mapEndoscBarr.put("C_Stage",matcherC12Stage_pattern.group(1).replaceAll("\\n^$", "").replaceAll(" ", "").replaceAll("\n", "").replaceAll("\\t", "").replaceAll("=", "").replaceAll("C", ""));
//System.out.println("GOT THE C 12");
}
else if (matcherC13Stage_pattern.find()) {
mapEndoscBarr.put("C_Stage",matcherC13Stage_pattern.group(1).replaceAll("\\n^$", "").replaceAll(" ", "").replaceAll("\n", "").replaceAll("\\t", "").replaceAll("=", "").replaceAll("M", ""));
//System.out.println("GOT THE C 13");
}
} catch (Exception e) {
e.printStackTrace();
}
try {
Pattern MStage_pattern = Pattern.compile("(M(\\s|=)*\\d+)",Pattern.DOTALL);
Matcher matcherM12Stage_pattern = MStage_pattern.matcher(n.get(12).toString().trim());
Matcher matcherM13Stage_pattern = MStage_pattern.matcher(n.get(13).toString().trim());
if (matcherM12Stage_pattern.find()) {
mapEndoscBarr.put("M_Stage",matcherM12Stage_pattern.group(1).replaceAll("\\n^$", "").replaceAll(" ", "").replaceAll("\n", "").replaceAll("\\t", "").replaceAll("C", ""));
//System.out.println("GOT THE M 12");
}
else if (matcherM13Stage_pattern.find()) {
//System.out.println("GOT THE M 13");
mapEndoscBarr.put("M_Stage",matcherM13Stage_pattern.group(1).replaceAll("\\n^$", "").replaceAll(" ", "").replaceAll("\n", "").replaceAll("\\t", "").replaceAll("C", ""));
}
} catch (Exception e) {
e.printStackTrace();
}
try {
DBConnectorForAll ConnectMeUp = new DBConnectorForAll();
tab="Endoscopy";
st=ConnectMeUp.Connector(HospNum,FName,SName,DOB);
first=ConnectMeUp.StringInsertKeyPreparer(st,mapEndoscBarr,tab);
second=ConnectMeUp.StringInsertValuePreparer(st,mapEndoscBarr,tab);
VisitDate=ResultPerformed;
if (!Checkers.VisitDateChecker(st,tab,HospNum).contains(VisitDate)){
ConnectMeUp.Inserter(st,HospNum,first,second,tab,filepath);
}
System.gc();
} catch (Exception e) {
Logger.error(e+HospNum+"->From EndoscopyOld"+filepath);
}
}
}
}
| [
"[email protected]"
] | |
09570baa2ad2fa78bb8d0ecdaddf0d90bb93e617 | d1d8b0885c964b647c8ac0451ea7f0dc3726f847 | /ServletHtml/ServletHtml/src/com/jspservletcookbook/bean/WorkReportBean.java | 82732330881be8e71dc6c400e21bed63a3e560b2 | [] | no_license | fhlkm/WebProject | 8595d84e6abb86a16430e372c55a18a474c4229b | 5336855d6a9c353cf4ac51108ccf028d0f76b0f5 | refs/heads/master | 2020-04-15T12:51:04.692902 | 2015-03-20T22:39:25 | 2015-03-20T22:39:25 | 32,610,551 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 597 | java | package com.jspservletcookbook.bean;
public class WorkReportBean {
public static final String SNO ="Number";
public static final String Time="Time";
public static final String Name="Name";
public static final String Date="Date";
public static final String SCHECKLIST="Checklists";
public static final String Image="Image";
public static final String DESCRIPTION ="DESCRIPTION";
public static final String IMG_REPORT_PICTURE ="IMG_REPORT_PICTURE";
public static final String PICTURE="PICTURE";
public static final String PICTURES ="PICTURES";
public static final String PART="PART";
}
| [
"[email protected]"
] | |
50f63aaa2afdc97e778ed67ebc68705bc310cc45 | f48c04532f155c30a040e03237cffdde586e96fb | /src/main/java/com/hu/fenxiao/controller/front/CartController.java | 2e0ae60f17e8b5f16e5c7226fdbdbd1c0c444588 | [] | no_license | Metathinking/fenxiao | 7d649e37303d77755fd14a40cb1313d37de89096 | 5c14e99773b75f33ba7cb29742fe245fe6573141 | refs/heads/master | 2020-03-07T21:20:04.097037 | 2018-05-07T03:48:37 | 2018-05-07T03:48:37 | 127,723,560 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,775 | java | package com.hu.fenxiao.controller.front;
import com.hu.fenxiao.controller.admin.AdminTuiGuangSettingController;
import com.hu.fenxiao.domain.CartItem;
import com.hu.fenxiao.domain.Member;
import com.hu.fenxiao.exception.ServiceException;
import com.hu.fenxiao.service.CartItemService;
import com.hu.fenxiao.util.ExceptionTipHandler;
import com.hu.fenxiao.util.Tip;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import java.util.List;
@Controller
@RequestMapping("member/cart")
public class CartController {
private Logger logger = LogManager.getLogger(AdminTuiGuangSettingController.class);
@Autowired
private CartItemService cartItemService;
@RequestMapping(value = "list", method = RequestMethod.GET)
public String list(Model model) {
model.addAttribute("sign", "cart");
return "front/cart";
}
@RequestMapping(value = "list", method = RequestMethod.POST)
@ResponseBody
public Tip getList(HttpSession session) {
List<CartItem> list = null;
try {
Member member = (Member) session.getAttribute("MEMBER");
list = cartItemService.list(member.getId());
return new Tip(true, 100, "", list);
} catch (ServiceException e) {
e.printStackTrace();
return ExceptionTipHandler.handler(e);
} catch (Exception e) {
logger.error(e.getMessage(), e);
e.printStackTrace();
return ExceptionTipHandler.handler(e);
}
}
/**
* 商品加入购物车
*
* @param productId
* @return
*/
@RequestMapping(value = "add", method = RequestMethod.POST)
@ResponseBody
public Tip addItem(@RequestParam String productId,
@RequestParam(required = false) Integer quantity,
HttpSession session) {
try {
if (quantity == null || quantity == 0) {
quantity = 1;
}
Member member = (Member) session.getAttribute("MEMBER");
cartItemService.edit(member.getId(), productId, quantity);
return new Tip(true, 100, "成功");
} catch (ServiceException e) {
e.printStackTrace();
return ExceptionTipHandler.handler(e);
} catch (Exception e) {
logger.error(e.getMessage(), e);
return ExceptionTipHandler.handler(e);
}
}
/**
* 购物车商品增加一个
*
* @param productId
* @return
*/
@RequestMapping(value = "raise", method = RequestMethod.POST)
@ResponseBody
public Tip raise(@RequestParam String productId, HttpSession session) {
try {
Member member = (Member) session.getAttribute("MEMBER");
int quantity = cartItemService.raise(member.getId(), productId);
return new Tip(true, 100, quantity + "", quantity);
} catch (ServiceException e) {
e.printStackTrace();
return ExceptionTipHandler.handler(e);
} catch (Exception e) {
e.printStackTrace();
logger.error(e.getMessage(), e);
return ExceptionTipHandler.handler(e);
}
}
@RequestMapping(value = "reduce", method = RequestMethod.POST)
@ResponseBody
public Tip reduce(@RequestParam String productId, HttpSession session) {
try {
Member member = (Member) session.getAttribute("MEMBER");
int quantity = cartItemService.reduce(member.getId(), productId);
return new Tip(true, 100, quantity + "", quantity);
} catch (ServiceException e) {
e.printStackTrace();
return ExceptionTipHandler.handler(e);
} catch (Exception e) {
e.printStackTrace();
logger.error(e.getMessage(), e);
return ExceptionTipHandler.handler(e);
}
}
/**
* 删除购物车商品
*
* @param cartItemId
* @return
*/
@RequestMapping(value = "delete", method = RequestMethod.POST)
@ResponseBody
public Tip delete(@RequestParam String cartItemId) {
try {
cartItemService.delete(cartItemId);
return new Tip(true, 100, "成功");
} catch (ServiceException e) {
e.printStackTrace();
return ExceptionTipHandler.handler(e);
} catch (Exception e) {
logger.error(e.getMessage(), e);
return ExceptionTipHandler.handler(e);
}
}
}
| [
"[email protected]"
] | |
f03daaa72f2786f0c30bd70db5fd45b6ae75f32b | e3cdf168fd96b1512fdd57bfba6abfb81d76f162 | /Jam.Guess/src/main/Jam/Guess/Jam/Guess/rmi/ClientManager.java | 073ff918725c32b8f44ed664ffcfeb606c0abab0 | [] | no_license | Heikum/Jam.Guess | 59686a05cef6173bfc008647301ac31cfba0f8ea | 3a0821eb0bb2e5d41c42681e69e6e053b955fb75 | refs/heads/master | 2021-09-04T04:38:48.038600 | 2018-01-15T23:00:33 | 2018-01-15T23:00:33 | 114,888,440 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,771 | java | package main.Jam.Guess.Jam.Guess.rmi;
import main.Jam.Guess.IGUIController;
import main.Jam.Guess.Jam.Guess.IGameManager;
import main.Jam.Guess.Jam.Guess.User;
import main.Jam.Guess.Jam.Guess.audioplayer.AudioPlayer ;
import main.Jam.Guess.Jam.Guess.fontyspublisher.IRemotePropertyListener ;
import main.Jam.Guess.Jam.Guess.fontyspublisher.IRemotePublisherForListener ;
import main.Jam.Guess.Jam.Guess.log.Logger ;
import uk.co.caprica.vlcj.component.AudioMediaPlayerComponent;
import uk.co.caprica.vlcj.discovery.NativeDiscovery;
import main.Jam.Guess.IPlayer;
import java.beans.PropertyChangeEvent;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
public class ClientManager extends UnicastRemoteObject implements IRemotePropertyListener {
private IRemotePublisherForListener publisher;
private IGameManager server;
private IGUIController guiController;
private User registeredUser;
private static IPlayer player;
private static ExecutorService pool = Executors.newFixedThreadPool(3);
private Logger logger;
private static final String MSG_NOT_IN_PARTY = "You're not in a party";
private static final String MSG_NOT_LOGGED_IN = "You're not logged in";
private static final String MSG_ALREADY_LOGGED_IN = "You're already logged in";
public ClientManager(IRemotePublisherForListener publisher, IGameManager server) throws RemoteException {
logger = new Logger("ClientManager", Level.ALL, Level.SEVERE);
this.publisher = publisher;
this.server = server;
(new NativeDiscovery()).discover();
player = new AudioPlayer(pool, new AudioMediaPlayerComponent());
}
@Override
public synchronized void propertyChange(PropertyChangeEvent evt) throws RemoteException {
// System.out.println(currentParty.getPartyMessage());
if (guiController != null){
guiController.update();
}
}
public void setGuiController(IGUIController controller){
guiController = controller;
}
public User login(String username, String password) throws RemoteException {
if (getUser() != null) {
//return MSG_ALREADY_LOGGED_IN;
return null;
}
User user = server.login(username, password);
if (user == null) {
logger.log(Level.WARNING, String.format("%s tried to login", username));
//return "Incorrect username or password.";
return null;
}
registeredUser = (User) user;
logger.log(Level.INFO, String.format("%s logged in", user.getUsername()));
return registeredUser;
//return String.format("You logged in as: %s", user.getNickname());
}
public String logout() throws RemoteException {
if (getUser() == null) {
return MSG_NOT_LOGGED_IN;
}
String partyKey = "";
User u = getUser();
server.logout(u);
logger.log(Level.INFO, String.format("%s logged out", u.getUsername()));
return "You logged out.";
}
public void resumePlaying(){
player.play();
}
public void pause(){
player.pause();
}
public void stop(){
player.stop();
}
public String play() throws RemoteException {
User user = getUser();
if (user == null) {
return MSG_NOT_LOGGED_IN;
}
return "This action is not allowed.";
}
public User getUser() {
if (registeredUser != null) {
return registeredUser;
} else return null;
}
}
| [
"[email protected]"
] | |
b71274cb925a02638507f0769d42357ef9ec7264 | 52b967c6ae1ec8e40d395de03b7a493a3351a4fc | /lee338_CountBits_medium.java | d5d65280556d65987c4ac038e02be21ae05a6de3 | [] | no_license | abcdddxy/LeetCode | bec0c1dfbee11937d18e8f62a7eb3ce1a73ec500 | b9c1f7282fdd6976df40308eb0df35fbca501f72 | refs/heads/master | 2020-03-28T07:18:56.727578 | 2019-03-29T08:33:22 | 2019-03-29T08:33:22 | 147,455,214 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 693 | java | public class lee338_CountBits_medium {
//暴力搜索
public int[] countBits(int num) {
int[] res = new int[num + 1];
for (int i = 1; i <= num; i++) {
res[i] = numOfOne(i);
}
return res;
}
private int numOfOne(int num) {
int res = 0;
while (num >= 1) {
if (num % 2 == 1) res += 1;
num /= 2;
}
return res;
}
//dp
public int[] countBits2(int num) {
int[] res = new int[num + 1];
int idx = 1;
for (int i = 0; i <= num; i++) {
if(i == idx * 2) idx *= 2;
res[i] = res[i - idx] + 1;
}
return res;
}
}
| [
"[email protected]"
] | |
1fb2956f88ed6da884b045a771fe6205195ec391 | c885ef92397be9d54b87741f01557f61d3f794f3 | /tests-without-trycatch/Jsoup-84/org.jsoup.helper.W3CDom/default/11/org/jsoup/helper/W3CDom_ESTest.java | d3bc32c781fdc27a713fea868ecfb77e10827481 | [
"CC-BY-4.0",
"MIT"
] | permissive | pderakhshanfar/EMSE-BBC-experiment | f60ac5f7664dd9a85f755a00a57ec12c7551e8c6 | fea1a92c2e7ba7080b8529e2052259c9b697bbda | refs/heads/main | 2022-11-25T00:39:58.983828 | 2022-04-12T16:04:26 | 2022-04-12T16:04:26 | 309,335,889 | 0 | 1 | null | 2021-11-05T11:18:43 | 2020-11-02T10:30:38 | null | UTF-8 | Java | false | false | 9,970 | java | /*
* This file was automatically generated by EvoSuite
* Fri Jul 30 09:19:25 GMT 2021
*/
package org.jsoup.helper;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.evosuite.runtime.EvoAssertions.*;
import org.evosuite.runtime.EvoRunner;
import org.evosuite.runtime.EvoRunnerParameters;
import org.jsoup.helper.W3CDom;
import org.jsoup.nodes.DataNode;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.XmlDeclaration;
import org.jsoup.parser.Parser;
import org.junit.runner.RunWith;
import org.w3c.dom.DOMException;
@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true)
public class W3CDom_ESTest extends W3CDom_ESTest_scaffolding {
@Test(timeout = 4000)
public void test00() throws Throwable {
Document document0 = new Document(":nh-last-of-typ(");
Element element0 = document0.tagName(":nh-last-of-typ(");
document0.prependChild(element0);
W3CDom w3CDom0 = new W3CDom();
// Undeclared exception!
// try {
w3CDom0.fromJsoup(document0);
// fail("Expecting exception: DOMException");
// } catch(DOMException e) {
// }
}
@Test(timeout = 4000)
public void test01() throws Throwable {
W3CDom w3CDom0 = new W3CDom();
Document document0 = Parser.parse("xmlns", "j4");
org.w3c.dom.Document document1 = w3CDom0.fromJsoup(document0);
W3CDom.W3CBuilder w3CDom_W3CBuilder0 = new W3CDom.W3CBuilder(document1);
// Undeclared exception!
// try {
w3CDom_W3CBuilder0.tail(document0, 749);
// fail("Expecting exception: NullPointerException");
// } catch(NullPointerException e) {
// //
// // no message in exception (getMessage() returned null)
// //
// verifyException("org.jsoup.helper.W3CDom$W3CBuilder", e);
// }
}
@Test(timeout = 4000)
public void test02() throws Throwable {
Document document0 = Parser.parse("org.jsoup.helper.W3CDom", "org.jsoup.helper.W3CDom");
Element element0 = document0.tagName("org.jsoup.helper.W3CDom");
document0.prependChild(element0);
W3CDom w3CDom0 = new W3CDom();
// Undeclared exception!
w3CDom0.fromJsoup(document0);
}
@Test(timeout = 4000)
public void test03() throws Throwable {
Document document0 = new Document("smalO");
W3CDom w3CDom0 = new W3CDom();
w3CDom0.factory = null;
// Undeclared exception!
// try {
w3CDom0.fromJsoup(document0);
// fail("Expecting exception: NullPointerException");
// } catch(NullPointerException e) {
// //
// // no message in exception (getMessage() returned null)
// //
// verifyException("org.jsoup.helper.W3CDom", e);
// }
}
@Test(timeout = 4000)
public void test04() throws Throwable {
W3CDom w3CDom0 = new W3CDom();
Document document0 = new Document("$6|_T~");
// Undeclared exception!
// try {
w3CDom0.fromJsoup(document0);
// fail("Expecting exception: IndexOutOfBoundsException");
// } catch(IndexOutOfBoundsException e) {
// //
// // Index: 0, Size: 0
// //
// verifyException("java.util.ArrayList", e);
// }
}
@Test(timeout = 4000)
public void test05() throws Throwable {
W3CDom w3CDom0 = new W3CDom();
// Undeclared exception!
// try {
w3CDom0.fromJsoup((Document) null);
// fail("Expecting exception: IllegalArgumentException");
// } catch(IllegalArgumentException e) {
// //
// // Object must not be null
// //
// verifyException("org.jsoup.helper.Validate", e);
// }
}
@Test(timeout = 4000)
public void test06() throws Throwable {
W3CDom w3CDom0 = new W3CDom();
Document document0 = Parser.parse("~&%fsQ71hr9", "~&%fsQ71hr9");
org.w3c.dom.Document document1 = w3CDom0.fromJsoup(document0);
// Undeclared exception!
// try {
w3CDom0.convert(document0, document1);
// fail("Expecting exception: DOMException");
// } catch(DOMException e) {
// }
}
@Test(timeout = 4000)
public void test07() throws Throwable {
W3CDom w3CDom0 = new W3CDom();
Document document0 = Document.createShell("");
Element element0 = document0.attr("", "xmlns:|pb-^&");
document0.prependChild(element0);
// Undeclared exception!
// try {
w3CDom0.convert(document0, (org.w3c.dom.Document) null);
// fail("Expecting exception: IllegalArgumentException");
// } catch(IllegalArgumentException e) {
// //
// // String must not be empty
// //
// verifyException("org.jsoup.helper.Validate", e);
// }
}
@Test(timeout = 4000)
public void test08() throws Throwable {
Document document0 = new Document(".Kd$@N2q_lG93W");
W3CDom w3CDom0 = new W3CDom();
Document document1 = Parser.parseBodyFragment(".Kd$@N2q_lG93W", ".Kd$@N2q_lG93W");
org.w3c.dom.Document document2 = w3CDom0.fromJsoup(document1);
// Undeclared exception!
// try {
w3CDom0.convert(document0, document2);
// fail("Expecting exception: IndexOutOfBoundsException");
// } catch(IndexOutOfBoundsException e) {
// //
// // Index: 0, Size: 0
// //
// verifyException("java.util.ArrayList", e);
// }
}
@Test(timeout = 4000)
public void test09() throws Throwable {
W3CDom w3CDom0 = new W3CDom();
Document document0 = Parser.parse("n&/<r:R9pLRe>$vv =", "n&/<r:R9pLRe>$vv =");
// Undeclared exception!
// try {
w3CDom0.fromJsoup(document0);
// fail("Expecting exception: DOMException");
// } catch(DOMException e) {
// }
}
@Test(timeout = 4000)
public void test10() throws Throwable {
Document document0 = Parser.parseBodyFragment("xmlns:xjemlm:i|s\"", "xmlns:xjemlm:i|s\"");
Element element0 = document0.attr("xmlns:xjemlm:i|s\"", "xmlns:xjemlm:i|s\"");
document0.prependChild(element0);
W3CDom w3CDom0 = new W3CDom();
// Undeclared exception!
// try {
w3CDom0.fromJsoup(document0);
// fail("Expecting exception: DOMException");
// } catch(DOMException e) {
// }
}
@Test(timeout = 4000)
public void test11() throws Throwable {
Document document0 = Parser.parseBodyFragment("xmlns", "xmlns");
Element element0 = document0.attr("xmlns", "xmlns");
document0.prependChild(element0);
W3CDom w3CDom0 = new W3CDom();
// Undeclared exception!
// try {
w3CDom0.fromJsoup(document0);
// fail("Expecting exception: DOMException");
// } catch(DOMException e) {
// }
}
@Test(timeout = 4000)
public void test12() throws Throwable {
W3CDom w3CDom0 = new W3CDom();
Document document0 = Parser.parseBodyFragment("\";)d')7~", "\";)d')7~");
org.w3c.dom.Document document1 = w3CDom0.fromJsoup(document0);
W3CDom.W3CBuilder w3CDom_W3CBuilder0 = new W3CDom.W3CBuilder(document1);
XmlDeclaration xmlDeclaration0 = new XmlDeclaration("\";)d')7~", "f-P;x74j-tO=", true);
w3CDom_W3CBuilder0.head(xmlDeclaration0, (-1));
assertFalse(xmlDeclaration0.hasParent());
}
@Test(timeout = 4000)
public void test13() throws Throwable {
W3CDom w3CDom0 = new W3CDom();
Document document0 = Document.createShell("{\u0001d'S");
org.w3c.dom.Document document1 = w3CDom0.fromJsoup(document0);
W3CDom.W3CBuilder w3CDom_W3CBuilder0 = new W3CDom.W3CBuilder(document1);
DataNode dataNode0 = new DataNode("{\u0001d'S");
// Undeclared exception!
// try {
w3CDom_W3CBuilder0.head(dataNode0, (-234));
// fail("Expecting exception: NullPointerException");
// } catch(NullPointerException e) {
// //
// // no message in exception (getMessage() returned null)
// //
// }
}
@Test(timeout = 4000)
public void test14() throws Throwable {
W3CDom w3CDom0 = new W3CDom();
Document document0 = Parser.parseBodyFragment("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>", "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>");
org.w3c.dom.Document document1 = w3CDom0.fromJsoup(document0);
assertNotNull(document1);
}
@Test(timeout = 4000)
public void test15() throws Throwable {
W3CDom w3CDom0 = new W3CDom();
Document document0 = Document.createShell("");
// Undeclared exception!
// try {
w3CDom0.convert(document0, (org.w3c.dom.Document) null);
// fail("Expecting exception: NullPointerException");
// } catch(NullPointerException e) {
// //
// // no message in exception (getMessage() returned null)
// //
// }
}
@Test(timeout = 4000)
public void test16() throws Throwable {
W3CDom w3CDom0 = new W3CDom();
Document document0 = Parser.parse("command", "command");
org.w3c.dom.Document document1 = w3CDom0.fromJsoup(document0);
String string0 = w3CDom0.asString(document1);
assertEquals("<html>\n<head>\n<META http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n</head>\n<body>command</body>\n</html>\n", string0);
}
@Test(timeout = 4000)
public void test17() throws Throwable {
Document document0 = Parser.parseBodyFragment("xmlns:xmlns:<html>\n<head>\n<met htt-equiv\"cwntent-type\" conten=\"text/html; charset=ut-8\"\n9/head\n<bod></body\n<yhtml>", "xmlns:xmlns:<html>\n<head>\n<met htt-equiv\"cwntent-type\" conten=\"text/html; charset=ut-8\"\n9/head\n<bod></body\n<yhtml>");
W3CDom w3CDom0 = new W3CDom();
w3CDom0.fromJsoup(document0);
}
}
| [
"[email protected]"
] | |
46e9066ccb561876c4a7e3d480d4a3be2cf78ad0 | dff2417b6d1281c5d287c888d58bbe7aea163e8c | /core/src/com/mygdx/game/GameOrganize/Controller.java | 40244792a9c15d7cedfb5b8be8080b90ef715a4f | [] | no_license | 913x100/Flyer | c8dd47fd7b8c9821e8fa75a13d63d3cc6d0c94f1 | eaf7d1f5c0c183437bddffd03137e505f3afdc17 | refs/heads/master | 2021-08-30T12:47:58.092474 | 2017-12-18T01:52:04 | 2017-12-18T01:52:04 | 112,700,592 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,246 | java | package com.mygdx.game.GameOrganize;
import com.badlogic.gdx.InputProcessor;
import com.mygdx.game.GameObjects.Player;
import com.mygdx.game.GameWorld.GameWorld;
public class Controller implements InputProcessor {
private Player player;
private GameWorld world;
public Controller(GameWorld world) {
this.world = world;
player = world.getPlayer();
}
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
if (world.isReady()) {
world.start();
}
player.onTap();
if (world.isGameOver()) {
world.restart();
}
return true;
}
public boolean keyDown(int keycode) {
return false;
}
public boolean keyUp(int keycode) {
return false;
}
public boolean keyTyped(char character) {
return false;
}
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
return false;
}
public boolean touchDragged(int screenX, int screenY, int pointer) {
return false;
}
public boolean mouseMoved(int screenX, int screenY) {
return false;
}
public boolean scrolled(int amount) {
return false;
}
}
| [
"[email protected]"
] | |
4b8099e08bfd0d71128cd9b5823ffe219f91e5f0 | 3e1f10035045bab9b2022e222f420cc0ddae34e2 | /src/UI/UIImageButton.java | a58394f96effe978500d252c30f68d8caff1cc8d | [] | no_license | jaimemiranda1/Frogger | f8b974d5d704c5ea262d01da326360b958c000a9 | f76a746d1ae1b912dcac9e136cd16bfd94948514 | refs/heads/master | 2020-04-27T01:45:31.812459 | 2019-03-01T03:41:33 | 2019-03-01T03:41:33 | 173,974,356 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,023 | java | package UI;
import java.awt.*;
import java.awt.image.BufferedImage;
/**
* Created by AlexVR on 7/1/2018.
*/
public class UIImageButton extends UIObject{
private BufferedImage[] images;
private ClickListlener clicker;
public UIImageButton(float x, float y, int width, int height, BufferedImage[] images,ClickListlener clicker ) {
super(x, y, width, height);
this.images=images;
this.clicker=clicker;
}
@Override
public void tick() {
}
@Override
public void render(Graphics g) {
if(active){
if(images.length==3) {
g.drawImage(images[2], (int) x, (int) y, width, heith, null);
}
}
else if(hovering){
g.drawImage(images[1],(int)x,(int)y,width,heith,null);
}else{
g.drawImage(images[0],(int)x,(int)y,width,heith,null);
}
}
@Override
public void onClick()
{
clicker.onClick();
}
}
| [
"[email protected]"
] | |
d4e00a9ac93598a92eb4cc74c950fa8369fd4d7e | 9d35ff2cffd6af816953b8b4ec9e5a7944a3c2e0 | /Numero.java | af71a4088868dff1db18ed4ab2eeac2ff33db0b9 | [] | no_license | SebastianCP95/Pr-ctica_ENDES_GIT | 119abfe9d9d8b1865d53e580c8c11ea4863709f2 | 7d386170ebc944da0b0825087dc5c9c8c678e94a | refs/heads/main | 2023-04-02T16:30:40.882770 | 2021-04-14T10:42:47 | 2021-04-14T10:42:47 | 357,859,535 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 606 | java | /*
* 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 tareajunit;
/**
*
* @author sebastian
*/
public class Numero {
private int num;
public Numero() {
}
public Numero(int num) {
this.num = num;
}
public boolean NumeoPrimo(){
int cont = 0;
for (int i = 1; i <= num; i++) {
if (num % i == 0) {
cont++;
}
}
return cont == 2;
}
}
| [
"[email protected]"
] | |
a2c858687aab0a7d914897afb73ee93f607b5d83 | 7ad5a3ceb5b28e31d54269515e35232fbc87fd21 | /core/src/main/java/org/jpedal/jbig2/decoders/JBIG2StreamDecoder.java | 749ef2dd8a594b01fe0869c788012446601acaed | [
"Apache-2.0"
] | permissive | demetbolata/icepdf4 | 966a4a8eea50cb4bf82100180f72189f589b09c3 | e8dfcb5c03502f1e38d077a730761de945153cd7 | refs/heads/master | 2023-03-15T16:02:51.443928 | 2016-05-29T09:02:30 | 2016-05-29T09:02:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 18,812 | java | /*
* Copyright 2006-2012 ICEsoft Technologies 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 org.jpedal.jbig2.decoders;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.jpedal.jbig2.JBIG2Exception;
import org.jpedal.jbig2.image.JBIG2Bitmap;
import org.jpedal.jbig2.io.StreamReader;
import org.jpedal.jbig2.segment.Segment;
import org.jpedal.jbig2.segment.SegmentHeader;
import org.jpedal.jbig2.segment.extensions.ExtensionSegment;
import org.jpedal.jbig2.segment.pageinformation.PageInformationSegment;
import org.jpedal.jbig2.segment.pattern.PatternDictionarySegment;
import org.jpedal.jbig2.segment.region.generic.GenericRegionSegment;
import org.jpedal.jbig2.segment.region.halftone.HalftoneRegionSegment;
import org.jpedal.jbig2.segment.region.refinement.RefinementRegionSegment;
import org.jpedal.jbig2.segment.region.text.TextRegionSegment;
import org.jpedal.jbig2.segment.stripes.EndOfStripeSegment;
import org.jpedal.jbig2.segment.symboldictionary.SymbolDictionarySegment;
import org.jpedal.jbig2.util.BinaryOperation;
public class JBIG2StreamDecoder {
private StreamReader reader;
private boolean noOfPagesKnown;
private boolean randomAccessOrganisation;
private int noOfPages = -1;
private List segments = new ArrayList();
private List bitmaps = new ArrayList();
private byte[] globalData;
private ArithmeticDecoder arithmeticDecoder;
private HuffmanDecoder huffmanDecoder;
private MMRDecoder mmrDecoder;
public static boolean debug = false;
public void movePointer(int i){
reader.movePointer(i);
}
public void setGlobalData(byte[] data) {
globalData = data;
}
public void decodeJBIG2(byte[] data) throws IOException, JBIG2Exception {
reader = new StreamReader(data);
resetDecoder();
boolean validFile = checkHeader();
if (JBIG2StreamDecoder.debug)
System.out.println("validFile = " + validFile);
if (!validFile) {
/**
* Assume this is a stream from a PDF so there is no file header,
* end of page segments, or end of file segments. Organisation must
* be sequential, and the number of pages is assumed to be 1.
*/
noOfPagesKnown = true;
randomAccessOrganisation = false;
noOfPages = 1;
/** check to see if there is any global data to be read */
if (globalData != null) {
/** set the reader to read from the global data */
reader = new StreamReader(globalData);
huffmanDecoder = new HuffmanDecoder(reader);
mmrDecoder = new MMRDecoder(reader);
arithmeticDecoder = new ArithmeticDecoder(reader);
/** read in the global data segments */
readSegments();
/** set the reader back to the main data */
reader = new StreamReader(data);
} else {
/**
* There's no global data, so move the file pointer back to the
* start of the stream
*/
reader.movePointer(-8);
}
} else {
/**
* We have the file header, so assume it is a valid stand-alone
* file.
*/
if (JBIG2StreamDecoder.debug)
System.out.println("==== File Header ====");
setFileHeaderFlags();
if (JBIG2StreamDecoder.debug) {
System.out.println("randomAccessOrganisation = " + randomAccessOrganisation);
System.out.println("noOfPagesKnown = " + noOfPagesKnown);
}
if (noOfPagesKnown) {
noOfPages = getNoOfPages();
if (JBIG2StreamDecoder.debug)
System.out.println("noOfPages = " + noOfPages);
}
}
huffmanDecoder = new HuffmanDecoder(reader);
mmrDecoder = new MMRDecoder(reader);
arithmeticDecoder = new ArithmeticDecoder(reader);
/** read in the main segment data */
readSegments();
}
public HuffmanDecoder getHuffmanDecoder() {
return huffmanDecoder;
}
public MMRDecoder getMMRDecoder() {
return mmrDecoder;
}
public ArithmeticDecoder getArithmeticDecoder() {
return arithmeticDecoder;
}
private void resetDecoder() {
noOfPagesKnown = false;
randomAccessOrganisation = false;
noOfPages = -1;
segments.clear();
bitmaps.clear();
}
public void cleanupPostDecode() {
// Clear away everything but the page segments
for (Iterator it = segments.iterator(); it.hasNext();) {
Segment segment = (Segment) it.next();
SegmentHeader segmentHeader = segment.getSegmentHeader();
if (segmentHeader.getSegmentType() != segment.PAGE_INFORMATION) {
it.remove();
}
}
bitmaps.clear();
}
private void readSegments() throws IOException, JBIG2Exception {
if (JBIG2StreamDecoder.debug)
System.out.println("==== Segments ====");
boolean finished = false;
while (!reader.isFinished() && !finished) {
SegmentHeader segmentHeader = new SegmentHeader();
if (JBIG2StreamDecoder.debug)
System.out.println("==== Segment Header ====");
readSegmentHeader(segmentHeader);
// read the Segment data
Segment segment = null;
int segmentType = segmentHeader.getSegmentType();
int[] referredToSegments = segmentHeader.getReferredToSegments();
int noOfReferredToSegments = segmentHeader.getReferredToSegmentCount();
switch (segmentType) {
case Segment.SYMBOL_DICTIONARY:
if (JBIG2StreamDecoder.debug)
System.out.println("==== Segment Symbol Dictionary ====");
segment = new SymbolDictionarySegment(this);
segment.setSegmentHeader(segmentHeader);
break;
case Segment.INTERMEDIATE_TEXT_REGION:
if (JBIG2StreamDecoder.debug)
System.out.println("==== Intermediate Text Region ====");
segment = new TextRegionSegment(this, false);
segment.setSegmentHeader(segmentHeader);
break;
case Segment.IMMEDIATE_TEXT_REGION:
if (JBIG2StreamDecoder.debug)
System.out.println("==== Immediate Text Region ====");
segment = new TextRegionSegment(this, true);
segment.setSegmentHeader(segmentHeader);
break;
case Segment.IMMEDIATE_LOSSLESS_TEXT_REGION:
if (JBIG2StreamDecoder.debug)
System.out.println("==== Immediate Lossless Text Region ====");
segment = new TextRegionSegment(this, true);
segment.setSegmentHeader(segmentHeader);
break;
case Segment.PATTERN_DICTIONARY:
if (JBIG2StreamDecoder.debug)
System.out.println("==== Pattern Dictionary ====");
segment = new PatternDictionarySegment(this);
segment.setSegmentHeader(segmentHeader);
break;
case Segment.INTERMEDIATE_HALFTONE_REGION:
if (JBIG2StreamDecoder.debug)
System.out.println("==== Intermediate Halftone Region ====");
segment = new HalftoneRegionSegment(this, false);
segment.setSegmentHeader(segmentHeader);
break;
case Segment.IMMEDIATE_HALFTONE_REGION:
if (JBIG2StreamDecoder.debug)
System.out.println("==== Immediate Halftone Region ====");
segment = new HalftoneRegionSegment(this, true);
segment.setSegmentHeader(segmentHeader);
break;
case Segment.IMMEDIATE_LOSSLESS_HALFTONE_REGION:
if (JBIG2StreamDecoder.debug)
System.out.println("==== Immediate Lossless Halftone Region ====");
segment = new HalftoneRegionSegment(this, true);
segment.setSegmentHeader(segmentHeader);
break;
case Segment.INTERMEDIATE_GENERIC_REGION:
if (JBIG2StreamDecoder.debug)
System.out.println("==== Intermediate Generic Region ====");
segment = new GenericRegionSegment(this, false);
segment.setSegmentHeader(segmentHeader);
break;
case Segment.IMMEDIATE_GENERIC_REGION:
if (JBIG2StreamDecoder.debug)
System.out.println("==== Immediate Generic Region ====");
segment = new GenericRegionSegment(this, true);
segment.setSegmentHeader(segmentHeader);
break;
case Segment.IMMEDIATE_LOSSLESS_GENERIC_REGION:
if (JBIG2StreamDecoder.debug)
System.out.println("==== Immediate Lossless Generic Region ====");
segment = new GenericRegionSegment(this, true);
segment.setSegmentHeader(segmentHeader);
break;
case Segment.INTERMEDIATE_GENERIC_REFINEMENT_REGION:
if (JBIG2StreamDecoder.debug)
System.out.println("==== Intermediate Generic Refinement Region ====");
segment = new RefinementRegionSegment(this, false, referredToSegments, noOfReferredToSegments);
segment.setSegmentHeader(segmentHeader);
break;
case Segment.IMMEDIATE_GENERIC_REFINEMENT_REGION:
if (JBIG2StreamDecoder.debug)
System.out.println("==== Immediate Generic Refinement Region ====");
segment = new RefinementRegionSegment(this, true, referredToSegments, noOfReferredToSegments);
segment.setSegmentHeader(segmentHeader);
break;
case Segment.IMMEDIATE_LOSSLESS_GENERIC_REFINEMENT_REGION:
if (JBIG2StreamDecoder.debug)
System.out.println("==== Immediate lossless Generic Refinement Region ====");
segment = new RefinementRegionSegment(this, true, referredToSegments, noOfReferredToSegments);
segment.setSegmentHeader(segmentHeader);
break;
case Segment.PAGE_INFORMATION:
if (JBIG2StreamDecoder.debug)
System.out.println("==== Page Information Dictionary ====");
segment = new PageInformationSegment(this);
segment.setSegmentHeader(segmentHeader);
break;
case Segment.END_OF_PAGE:
continue;
case Segment.END_OF_STRIPE:
if (JBIG2StreamDecoder.debug)
System.out.println("==== End of Stripes ====");
segment = new EndOfStripeSegment(this);
segment.setSegmentHeader(segmentHeader);
break;
case Segment.END_OF_FILE:
if (JBIG2StreamDecoder.debug)
System.out.println("==== End of File ====");
finished = true;
continue;
case Segment.PROFILES:
if (JBIG2StreamDecoder.debug)
System.out.println("PROFILES UNIMPLEMENTED");
break;
case Segment.TABLES:
if (JBIG2StreamDecoder.debug)
System.out.println("TABLES UNIMPLEMENTED");
break;
case Segment.EXTENSION:
if (JBIG2StreamDecoder.debug)
System.out.println("==== Extensions ====");
segment = new ExtensionSegment(this);
segment.setSegmentHeader(segmentHeader);
break;
default:
System.out.println("Unknown Segment type in JBIG2 stream");
break;
}
if (!randomAccessOrganisation) {
segment.readSegment();
}
segments.add(segment);
}
if (randomAccessOrganisation) {
for (Iterator it = segments.iterator(); it.hasNext();) {
Segment segment = (Segment) it.next();
segment.readSegment();
}
}
}
public PageInformationSegment findPageSegement(int page) {
for (Iterator it = segments.iterator(); it.hasNext();) {
Segment segment = (Segment) it.next();
SegmentHeader segmentHeader = segment.getSegmentHeader();
if (segmentHeader.getSegmentType() == segment.PAGE_INFORMATION && segmentHeader.getPageAssociation() == page) {
return (PageInformationSegment) segment;
}
}
return null;
}
public Segment findSegment(int segmentNumber) {
for (Iterator it = segments.iterator(); it.hasNext();) {
Segment segment = (Segment) it.next();
if (segment.getSegmentHeader().getSegmentNumber() == segmentNumber) {
return segment;
}
}
return null;
}
private void readSegmentHeader(SegmentHeader segmentHeader) throws IOException, JBIG2Exception {
handleSegmentNumber(segmentHeader);
handleSegmentHeaderFlags(segmentHeader);
handleSegmentReferredToCountAndRententionFlags(segmentHeader);
handleReferedToSegmentNumbers(segmentHeader);
handlePageAssociation(segmentHeader);
if (segmentHeader.getSegmentType() != Segment.END_OF_FILE)
handleSegmentDataLength(segmentHeader);
}
private void handlePageAssociation(SegmentHeader segmentHeader) throws IOException {
int pageAssociation;
boolean isPageAssociationSizeSet = segmentHeader.isPageAssociationSizeSet();
if (isPageAssociationSizeSet) { // field is 4 bytes long
short[] buf = new short[4];
reader.readByte(buf);
pageAssociation = BinaryOperation.getInt32(buf);
} else { // field is 1 byte long
pageAssociation = reader.readByte();
}
segmentHeader.setPageAssociation(pageAssociation);
if (JBIG2StreamDecoder.debug)
System.out.println("pageAssociation = " + pageAssociation);
}
private void handleSegmentNumber(SegmentHeader segmentHeader) throws IOException {
short[] segmentBytes = new short[4];
reader.readByte(segmentBytes);
int segmentNumber = BinaryOperation.getInt32(segmentBytes);
if (JBIG2StreamDecoder.debug)
System.out.println("SegmentNumber = " + segmentNumber);
segmentHeader.setSegmentNumber(segmentNumber);
}
private void handleSegmentHeaderFlags(SegmentHeader segmentHeader) throws IOException {
short segmentHeaderFlags = reader.readByte();
// System.out.println("SegmentHeaderFlags = " + SegmentHeaderFlags);
segmentHeader.setSegmentHeaderFlags(segmentHeaderFlags);
}
private void handleSegmentReferredToCountAndRententionFlags(SegmentHeader segmentHeader) throws IOException, JBIG2Exception {
short referedToSegmentCountAndRetentionFlags = reader.readByte();
int referredToSegmentCount = (referedToSegmentCountAndRetentionFlags & 224) >> 5; // 224
// =
// 11100000
short[] retentionFlags = null;
/** take off the first three bits of the first byte */
short firstByte = (short) (referedToSegmentCountAndRetentionFlags & 31); // 31 =
// 00011111
if (referredToSegmentCount <= 4) { // short form
retentionFlags = new short[1];
retentionFlags[0] = firstByte;
} else if (referredToSegmentCount == 7) { // long form
short[] longFormCountAndFlags = new short[4];
/** add the first byte of the four */
longFormCountAndFlags[0] = firstByte;
for (int i = 1; i < 4; i++)
// add the next 3 bytes to the array
longFormCountAndFlags[i] = reader.readByte();
/** get the count of the referred to Segments */
referredToSegmentCount = BinaryOperation.getInt32(longFormCountAndFlags);
/** calculate the number of bytes in this field */
int noOfBytesInField = (int) Math.ceil(4 + ((referredToSegmentCount + 1) / 8d));
// System.out.println("noOfBytesInField = " + noOfBytesInField);
int noOfRententionFlagBytes = noOfBytesInField - 4;
retentionFlags = new short[noOfRententionFlagBytes];
reader.readByte(retentionFlags);
} else { // error
throw new JBIG2Exception("Error, 3 bit Segment count field = " + referredToSegmentCount);
}
segmentHeader.setReferredToSegmentCount(referredToSegmentCount);
if (JBIG2StreamDecoder.debug)
System.out.println("referredToSegmentCount = " + referredToSegmentCount);
segmentHeader.setRententionFlags(retentionFlags);
if (JBIG2StreamDecoder.debug)
System.out.print("retentionFlags = ");
if (JBIG2StreamDecoder.debug) {
for (int i = 0; i < retentionFlags.length; i++)
System.out.print(retentionFlags[i] + " ");
System.out.println("");
}
}
private void handleReferedToSegmentNumbers(SegmentHeader segmentHeader) throws IOException {
int referredToSegmentCount = segmentHeader.getReferredToSegmentCount();
int[] referredToSegments = new int[referredToSegmentCount];
int segmentNumber = segmentHeader.getSegmentNumber();
if (segmentNumber <= 256) {
for (int i = 0; i < referredToSegmentCount; i++)
referredToSegments[i] = reader.readByte();
} else if (segmentNumber <= 65536) {
short[] buf = new short[2];
for (int i = 0; i < referredToSegmentCount; i++) {
reader.readByte(buf);
referredToSegments[i] = BinaryOperation.getInt16(buf);
}
} else {
short[] buf = new short[4];
for (int i = 0; i < referredToSegmentCount; i++) {
reader.readByte(buf);
referredToSegments[i] = BinaryOperation.getInt32(buf);
}
}
segmentHeader.setReferredToSegments(referredToSegments);
if (JBIG2StreamDecoder.debug) {
System.out.print("referredToSegments = ");
for (int i = 0; i < referredToSegments.length; i++)
System.out.print(referredToSegments[i] + " ");
System.out.println("");
}
}
private int getNoOfPages() throws IOException {
short[] noOfPages = new short[4];
reader.readByte(noOfPages);
return BinaryOperation.getInt32(noOfPages);
}
private void handleSegmentDataLength(SegmentHeader segmentHeader) throws IOException {
short[] buf = new short[4];
reader.readByte(buf);
int dateLength = BinaryOperation.getInt32(buf);
segmentHeader.setDataLength(dateLength);
if (JBIG2StreamDecoder.debug)
System.out.println("dateLength = " + dateLength);
}
private void setFileHeaderFlags() throws IOException {
short headerFlags = reader.readByte();
if ((headerFlags & 0xfc) != 0) {
System.out.println("Warning, reserved bits (2-7) of file header flags are not zero " + headerFlags);
}
int fileOrganisation = headerFlags & 1;
randomAccessOrganisation = fileOrganisation == 0;
int pagesKnown = headerFlags & 2;
noOfPagesKnown = pagesKnown == 0;
}
private boolean checkHeader() throws IOException {
short[] controlHeader = new short[] { 151, 74, 66, 50, 13, 10, 26, 10 };
short[] actualHeader = new short[8];
reader.readByte(actualHeader);
return Arrays.equals(controlHeader, actualHeader);
}
public int readBits(int num) throws IOException {
return reader.readBits(num);
}
public int readBit() throws IOException {
return reader.readBit();
}
public void readByte(short[] buff) throws IOException {
reader.readByte(buff);
}
public void consumeRemainingBits() throws IOException {
reader.consumeRemainingBits();
}
public short readByte() throws java.io.IOException {
return reader.readByte();
}
public void appendBitmap(JBIG2Bitmap bitmap) {
bitmaps.add(bitmap);
}
public JBIG2Bitmap findBitmap(int bitmapNumber) {
for (Iterator it = bitmaps.iterator(); it.hasNext();) {
JBIG2Bitmap bitmap = (JBIG2Bitmap) it.next();
if (bitmap.getBitmapNumber() == bitmapNumber) {
return bitmap;
}
}
return null;
}
public JBIG2Bitmap getPageAsJBIG2Bitmap(int i) {
JBIG2Bitmap pageBitmap = findPageSegement(1).getPageBitmap();
return pageBitmap;
}
public boolean isNumberOfPagesKnown() {
return noOfPagesKnown;
}
public int getNumberOfPages() {
return noOfPages;
}
public boolean isRandomAccessOrganisationUsed() {
return randomAccessOrganisation;
}
public List getAllSegments() {
return segments;
}
}
| [
"[email protected]"
] | |
329c917c74b992ba708184b68772837f8de19aa1 | e5327b5c93e3fad9f3382724b7f4075648e90696 | /app/src/main/java/com/lab4u/hannahchen/teacherlogin/ServiceGenerator.java | 346d40740d28d75e58a96fb0cd21eff0c276c12c | [] | no_license | hannahmei15/login | 1133aed9658ebb70c755ac09539d74fa1b45083e | e4e8b1710bf164afff764444e4d88526c699befc | refs/heads/master | 2021-01-20T22:14:49.782884 | 2016-07-01T19:57:27 | 2016-07-01T19:57:27 | 61,892,274 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,559 | java | package com.lab4u.hannahchen.teacherlogin;
import android.util.Base64;
import com.squareup.okhttp.OkHttpClient;
import retrofit.Callback;
import retrofit.RequestInterceptor;
import retrofit.RestAdapter;
import retrofit.client.OkClient;
/**
* Created by hannahchen on 6/24/16.
*/
public class ServiceGenerator {
public static final String API_BASE_URL = "http://10.0.1.18:9001";
private static RestAdapter.Builder builder = new RestAdapter.Builder()
.setEndpoint(API_BASE_URL)
.setLogLevel(RestAdapter.LogLevel.FULL)
.setClient(new OkClient(new OkHttpClient()));
public static <S> S createService(Class<S> serviceClass) {
builder.setRequestInterceptor(new RequestInterceptor() {
@Override
public void intercept(RequestFacade request) {
request.addHeader("X-ZUMO-APPLICATION", "XzqZNtYMEpTSljpfGytdLootHaOhvG73");
}
});
RestAdapter adapter = builder.build();
return adapter.create(serviceClass);
}
public static <S> S createService(Class<S> serviceClass, final String authToken) {
if (authToken != null) {
builder.setRequestInterceptor(new RequestInterceptor() {
@Override
public void intercept(RequestFacade request) {
request.addHeader("Authorization", authToken);
}
});
}
RestAdapter adapter = builder.build();
return adapter.create(serviceClass);
}
}
| [
"[email protected]"
] | |
013615f9c4ae26accea39704a1715e001ed68ad8 | 7c1430c53b4d66ad0e96dd9fc7465a5826fdfb77 | /uims-support/src/cn/edu/sdu/uims/itms/task/ITaskBase.java | c2c64adf1c97819a10ed90a56f450fa4ca131cbc | [] | no_license | wang3624270/online-learning-server | ef97fb676485f2bfdd4b479235b05a95ad62f841 | 2d81920fef594a2d0ac482efd76669c8d95561f1 | refs/heads/master | 2020-03-20T04:33:38.305236 | 2019-05-22T06:31:05 | 2019-05-22T06:31:05 | 137,187,026 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,037 | java | package cn.edu.sdu.uims.itms.task;
import java.awt.Graphics;
import java.util.EventObject;
import cn.edu.sdu.uims.itms.def.ITaskTemplate;
import cn.edu.sdu.uims.itms.handler.IHandler;
import cn.edu.sdu.uims.trans.UFPoint;
public class ITaskBase {
protected ITaskTemplate taskTemplate;
protected IHandler handler;
protected ISubTask owner;
public ITaskBase() {
}
public void init() {
}
// public void start() {
//
// }
public void start(String enterStatusFlag, UFPoint firstP) {
}
public void setTemplate(ITaskTemplate temp) {
taskTemplate = temp;
}
public ITaskTemplate getTemplate() {
return taskTemplate;
}
public void setHandler(IHandler handler) {
this.handler = handler;
}
public IHandler getHandler() {
return handler;
}
public int processEvent(String eventName, EventObject e) {
return -1;
}
public void setParaData(Object data) {
}
public void setCurrentPoint(UFPoint p) {
//
}
public void setOwner(ISubTask o) {
owner = o;
}
public void drawCursor(Graphics dc) {
}
}
| [
"[email protected]"
] | |
ee0658ccf7ac0460cab526273ffff8e32f51c476 | 060d61cb219eb20a7b11abaa914def74d4605c50 | /onlineMall-dev-pojo/src/main/java/com/heweixing/pojo/bo/SubmitOrderBO.java | 7d02e0652ba048d9f3663095528e3525c078d1f4 | [] | no_license | starheweixing/onlineMall | 410e2269bd5967578c0382235ce5e933a173c82c | bee9b6919d674719226b6d85aea8100b12c0785d | refs/heads/master | 2023-05-15T02:30:57.941287 | 2021-05-31T15:17:32 | 2021-05-31T15:17:32 | 353,915,791 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,405 | java | package com.heweixing.pojo.bo;
public class SubmitOrderBO {
/**
* 用于创建订单的bo对象
*/
private String userId;
private String ItemSpecIds;
private String addressId;
private Integer payMethod;
private String leftMsg;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getItemSpecIds() {
return ItemSpecIds;
}
public void setItemSpecIds(String itemSpecIds) {
ItemSpecIds = itemSpecIds;
}
public String getAddressId() {
return addressId;
}
public void setAddressId(String addressId) {
this.addressId = addressId;
}
public Integer getPayMethod() {
return payMethod;
}
public void setPayMethod(Integer payMethod) {
this.payMethod = payMethod;
}
public String getLeftMsg() {
return leftMsg;
}
public void setLeftMsg(String leftMsg) {
this.leftMsg = leftMsg;
}
@Override
public String toString() {
return "SubmitOrderBO{" +
"userId='" + userId + '\'' +
", ItemSpecIds='" + ItemSpecIds + '\'' +
", addressId='" + addressId + '\'' +
", payMethod=" + payMethod +
", leftMsg='" + leftMsg + '\'' +
'}';
}
}
| [
"[email protected]"
] | |
9f04930cea39aaf2b1cbd0275a6ae057ac0ef70c | 58cd5a5c2ac064f6117bcc0b9241a96fa213adf3 | /src/main/java/net/madicorp/smartinvestplus/stockexchange/domain/StockExchangeWithSecurities.java | 7912a419e45dc0cb6e7aebcb3e1a02be4f41d2d0 | [] | no_license | madicorp/smartinvestplus-back | 98dc1c960d34db6bbd8a395fd8799a260f9cd7df | d0a9c76db97b7a321df62a507ff792b4f1bee0f0 | refs/heads/master | 2021-01-17T19:00:45.484868 | 2016-08-07T09:58:37 | 2016-08-07T20:17:03 | 62,477,335 | 0 | 0 | null | 2016-08-03T00:01:49 | 2016-07-03T02:02:00 | Java | UTF-8 | Java | false | false | 1,215 | java | package net.madicorp.smartinvestplus.stockexchange.domain;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.*;
import org.jongo.marshall.jackson.oid.MongoId;
import org.springframework.cloud.cloudfoundry.com.fasterxml.jackson.annotation.JsonProperty;
import org.springframework.data.mongodb.core.mapping.Document;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;
/**
* User: sennen
* Date: 02/07/2016
* Time: 00:08
*/
@Document(collection = "stock_exchanges")
@Getter
@Setter
@NoArgsConstructor
@EqualsAndHashCode(of = {"stockExchange"})
@ToString(of = {"stockExchange"})
public class StockExchangeWithSecurities {
@JsonIgnore
private StockExchange stockExchange = new StockExchange();
private List<Security> securities = new ArrayList<>();
public void setSymbol(String symbol) {
stockExchange.setSymbol(symbol);
}
@NotNull
@MongoId
public String getSymbol() {
return stockExchange.getSymbol();
}
public void setName(String name) {
stockExchange.setName(name);
}
@NotNull
@JsonProperty
public String getName() {
return stockExchange.getName();
}
}
| [
"[email protected]"
] | |
46427d973725aeefa5687f75107eedc9213a6377 | 20c4818f027187f98c18176f79de90239615ced7 | /src/practica2/arrays/src/practica2/arrays/ejercicio5.java | 81fb73a12ff4c794b9d187ed59e8501cb94bc6fc | [] | no_license | rosarioValero/Programacion | 0369dbd3ef9867cd46dcb064b71e17d49203280c | 14685ecff9e4c44fc3d836f27c3faee2dc581637 | refs/heads/master | 2021-04-26T01:59:47.700904 | 2018-05-31T14:43:07 | 2018-05-31T14:43:07 | 107,447,165 | 0 | 0 | null | 2018-01-31T18:14:27 | 2017-10-18T18:27:19 | Python | UTF-8 | Java | false | false | 1,110 | java | /*
* 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 practica2.arrays;
/**
*
* @author Rosario
* 5. Crear una matriz “marco” de tamaño 8x6: todos sus elementos
* deben ser 0 salvo los de los bordes que deben ser 1.
* Mostrar la matriz.
*/
public class ejercicio5 {
public static void main(String[] args) {
int[][] matriz = new int[8][6];
//llena la matriz
for(int i=0; i < matriz.length; i++){
for(int j=0; j < matriz[0].length; j++){
//muestra primera o ultima columna o fila
if(i==0 || i==7 || j==0 || j==5){
matriz[i][j]=1;
}
}
}
//imprime el array
for(int i=0; i < matriz.length; i++){
for(int j=0; j < matriz[0].length; j++){
System.out.print(matriz[i][j]);
}
System.out.println();
}
}
}
| [
"[email protected]"
] | |
06ada0e2831785d3d0d023f55cba2bf44b6c1c27 | 285396012d8bc255da379de7d9a153b576480c1f | /app/src/main/java/com/hani/android/retrofitexample/adapter/RecyclerviewAdapter.java | 2f62ad56b5c6ee9e80d5c6e2508c5711f8f24874 | [] | no_license | Hani-Patel/Retrofitexample | 16b1b5e84ddd3e41047f3d80e187b25b70e2986e | b5ead4a8685f345e06371a7a13e7d4b71342b3e8 | refs/heads/master | 2021-01-20T14:42:46.360435 | 2017-05-08T16:50:06 | 2017-05-08T16:50:06 | 90,651,421 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,271 | java | package com.hani.android.retrofitexample.adapter;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.hani.android.retrofitexample.R;
import com.hani.android.retrofitexample.model.User;
import com.hani.android.retrofitexample.viewholder.RecyclerViewholder;
import java.util.List;
/**
* Created by SURBHI PATEL on 09-04-2017.
*/
public class RecyclerviewAdapter extends RecyclerView.Adapter<RecyclerViewholder> {
private List<User> itemlist;
public RecyclerviewAdapter(List<User> itemlist) {
this.itemlist = itemlist;
}
@Override
public RecyclerViewholder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_row,null);
RecyclerViewholder recyclerViewholder=new RecyclerViewholder(view);
return recyclerViewholder;
}
@Override
public void onBindViewHolder(RecyclerViewholder holder, int position) {
holder.name.setText(itemlist.get(position).getName());
holder.hobby.setText(itemlist.get(position).getHobby());
}
@Override
public int getItemCount() {
return itemlist.size();
}
}
| [
"Honey"
] | Honey |
0d51f0c405f2dd093cd4a8cbe93643219f466066 | 1a6411754950de9eb8c3d8e3f75b6a8470829b16 | /SpringTemplate/src/test/java/com/fesco/SpringTemplate/AppTest.java | d4af23a50abd2e25b35c65ee48e8a361ee65af8c | [] | no_license | ijfessey/tester | b3533c7a54c725e9071a9042ec5e21f7d7890bcd | 5e313e7e8cec9301a49ee8ecfa9e3d828230e58d | refs/heads/master | 2020-11-25T13:24:58.946180 | 2016-09-06T20:09:57 | 2016-09-06T20:09:57 | 67,541,521 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 692 | java | package com.fesco.SpringTemplate;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
}
}
| [
"[email protected]"
] | |
cc4e949c2424db37affde6d1cb83e214b129420b | b5de44cfce82705858e71f95b51c85d955156c6f | /src/main/java/edu/stanford/crypto/cs251/miners/CompliantMiner.java | 51700a1e7d6bdac7f7010150c1927c23ff23a769 | [] | no_license | fordneild/mining-strats | 924686c245e6e14e0646f0813af645f892c7f17f | 494b4e9294b0adbb513bae3074414316de673536 | refs/heads/main | 2023-03-26T07:29:14.744533 | 2021-03-24T00:42:28 | 2021-03-24T00:42:28 | 348,377,043 | 0 | 0 | null | 2021-03-23T19:46:37 | 2021-03-16T14:24:24 | Java | UTF-8 | Java | false | false | 1,250 | java | package edu.stanford.crypto.cs251.miners;
import edu.stanford.crypto.cs251.blockchain.Block;
import edu.stanford.crypto.cs251.blockchain.NetworkStatistics;
public class CompliantMiner extends BaseMiner implements Miner {
private Block currentHead;
public CompliantMiner(String id, int hashRate, int connectivity) {
super(id, hashRate, connectivity);
}
@Override
public Block currentlyMiningAt() {
return currentHead;
}
@Override
public Block currentHead() {
return currentHead;
}
@Override
public void blockMined(Block block, boolean isMinerMe) {
if(isMinerMe) {
if (block.getHeight() > currentHead.getHeight()) {
this.currentHead = block;
}
}
else{
if (currentHead == null) {
currentHead = block;
} else if (block != null && block.getHeight() > currentHead.getHeight()) {
this.currentHead = block;
}
}
}
@Override
public void initialize(Block genesis, NetworkStatistics networkStatistics) {
this.currentHead = genesis;
}
@Override
public void networkUpdate(NetworkStatistics statistics) {
}
}
| [
"[email protected]"
] | |
107bfb78abb4ef90a07ae6c4ce43d9d4c6f429e7 | 49104ac40fc4b9839a076a28462e6130b3de00c3 | /src/main/java/pages/ElementsPage.java | c6bd60f8c2f69eb56163e1c826eb12efe5d963f3 | [] | no_license | sholm73/demoqa | b6195bf50f61d290031fe06d67f2d79e7c39ec03 | 9cafeed28e1d8072bb9c1f111e429534b1eb9cbd | refs/heads/master | 2023-07-18T04:51:38.195980 | 2021-09-06T22:07:12 | 2021-09-06T22:07:12 | 401,426,697 | 0 | 0 | null | 2021-09-06T22:07:13 | 2021-08-30T17:18:03 | Java | UTF-8 | Java | false | false | 655 | java | package pages;
import org.junit.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class ElementsPage extends ParentPage{
public ElementsPage(WebDriver webDriver) {
super(webDriver);
}
public ElementsPage openElementsPage(){
try {
webDriver.get(baseURL);
webDriver.findElement(By.xpath(".//*/h5[text()='Elements']")).click();
logger.info("Elements Page was opened");
} catch (Exception e){
logger.error("Can`t work with Elements Page");
Assert.fail("Can`t work with Elements Page");
}
return this;
}
}
| [
"[email protected]"
] | |
c6bd60ca6d3af197a335ddf913adb93dc73dd29c | 9af7ff6b77b9e1aac67d7cf9f49b695511d94310 | /MultiProcessSysWebService_Thread_Online_1.3/src/ServiceInterface/ServiceImpl.java | 2d697466ac035b78ce725308d15a4315ae6d55dc | [] | no_license | zjmeixinyanzhi/MultipleDatacenterCollaborativeProcessSystem | bc5e30d27d23b0d1455207eddf90b63f1b2c9939 | 36e28e145eff16d9f7c80c5c5af684aac4f5370a | refs/heads/master | 2021-01-09T21:55:31.022679 | 2017-04-05T14:00:26 | 2017-04-05T14:00:26 | 54,820,368 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,719 | java | /**
* ServiceImpl.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
*/
package ServiceInterface;
public interface ServiceImpl extends java.rmi.Remote {
public java.lang.String orderRSDataPlan(java.lang.String strRequesXML) throws java.rmi.RemoteException;
public java.lang.String systemMonitorInfo(java.lang.String strRequesIP) throws java.rmi.RemoteException;
public java.lang.String commonProductRequireSubmit(java.lang.String strRequestXML) throws java.rmi.RemoteException;
public java.lang.String rnDataService(java.lang.String strRequestXML, java.lang.String serviceType) throws java.rmi.RemoteException;
public java.lang.String validationOrderSubmit(java.lang.String strRequestXML) throws java.rmi.RemoteException;
public java.lang.String dataProductSubmit(java.lang.String strRequestXML) throws java.rmi.RemoteException;
public java.lang.String commonProductOrderSubmit(java.lang.String strRequestXML) throws java.rmi.RemoteException;
public java.lang.String faProducRequireSubmit(java.lang.String strRequestXML) throws java.rmi.RemoteException;
public java.lang.String dataProductQuery(java.lang.String strRequestXML) throws java.rmi.RemoteException;
public java.lang.String faProductRequireSubmit(java.lang.String strRequestXML) throws java.rmi.RemoteException;
public java.lang.String dataProductViewDetail(java.lang.String strRequestXML) throws java.rmi.RemoteException;
public java.lang.String dataPrdouctQuery(java.lang.String strRequestXML) throws java.rmi.RemoteException;
public java.lang.String taskStatus(java.lang.String strRequestXML) throws java.rmi.RemoteException;
}
| [
"[email protected]"
] | |
55f90c3dbf340dd659864b987ad3a67d1d975f09 | 9289419e7980d2d668fad259cec88317f4696e54 | /maven-confluence-core/src/main/java/org/bsc/confluence/ConfluenceServiceFactory.java | f2199e354aa48fb1ae8924abf60f5f75569ca203 | [
"NTP",
"RSA-MD",
"LicenseRef-scancode-pcre",
"Apache-2.0",
"MIT",
"LicenseRef-scancode-rsa-1990",
"Beerware",
"LicenseRef-scancode-other-permissive",
"Spencer-94",
"BSD-3-Clause",
"LicenseRef-scancode-rsa-md4",
"metamail",
"HPND-sell-variant",
"LicenseRef-scancode-zeusbench"
] | permissive | dmytro-sydorenko/maven-confluence-plugin | 084cd5aec41e6ca91c48476be7e41045c6edbc25 | 79285dd8030766c7cbefd98df7f6159d2030d221 | refs/heads/master | 2020-08-07T20:03:48.397743 | 2019-10-01T09:43:29 | 2019-10-01T09:43:29 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,689 | java | /*
* 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 org.bsc.confluence;
import static java.lang.String.format;
import static org.bsc.confluence.xmlrpc.XMLRPCConfluenceServiceImpl.createInstanceDetectingVersion;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import javax.json.JsonObjectBuilder;
import org.bsc.confluence.ConfluenceService.Credentials;
import org.bsc.confluence.rest.RESTConfluenceServiceImpl;
import org.bsc.confluence.rest.model.Page;
import org.bsc.confluence.xmlrpc.XMLRPCConfluenceServiceImpl;
import org.bsc.ssl.SSLCertificateInfo;
/**
*
* @author bsorrentino
*/
public class ConfluenceServiceFactory {
private static class MixedConfluenceService implements ConfluenceService {
final XMLRPCConfluenceServiceImpl xmlrpcService;
final RESTConfluenceServiceImpl restService;
public MixedConfluenceService(String endpoint, Credentials credentials, ConfluenceProxy proxyInfo, SSLCertificateInfo sslInfo) throws Exception {
this.xmlrpcService = createInstanceDetectingVersion(endpoint, credentials, proxyInfo, sslInfo);
final String restEndpoint = new StringBuilder()
.append(ConfluenceService.Protocol.XMLRPC.removeFrom(endpoint))
.append(ConfluenceService.Protocol.REST.path())
.toString();
this.restService = new RESTConfluenceServiceImpl(restEndpoint, credentials, sslInfo);
}
@Override
public Credentials getCredentials() {
return xmlrpcService.getCredentials();
}
@Override
public Model.PageSummary findPageByTitle(String parentPageId, String title) throws Exception {
return xmlrpcService.findPageByTitle(parentPageId, title);
}
@Override
public CompletableFuture<Boolean> removePage(Model.Page parentPage, String title) {
return xmlrpcService.removePage(parentPage, title);
}
@Override
public CompletableFuture<Model.Page> createPage(Model.Page parentPage, String title) {
return xmlrpcService.createPage(parentPage, title);
}
@Override
public CompletableFuture<Model.Attachment> addAttachment(Model.Page page, Model.Attachment attachment, InputStream source) {
return xmlrpcService.addAttachment(page, attachment, source);
}
@Override
public CompletableFuture<Model.Page> storePage(Model.Page page) {
return xmlrpcService.storePage(page);
}
@Override
public CompletableFuture<Model.Page> storePage(Model.Page page, Storage content) {
if( Storage.Representation.STORAGE == content.rapresentation ) {
if( page.getId()==null ) {
final JsonObjectBuilder inputData =
restService.jsonForCreatingPage(page.getSpace(),
Integer.valueOf(page.getParentId()),
page.getTitle());
restService.jsonAddBody(inputData, content);
return CompletableFuture.supplyAsync( () ->
restService.createPage(inputData.build()).map(Page::new).get() );
}
return restService.storePage(page, content);
}
return xmlrpcService.storePage(page, content);
}
@Override
public boolean addLabelByName(String label, long id) throws Exception {
return xmlrpcService.addLabelByName(label, id);
}
@Override
public Model.Attachment createAttachment() {
return xmlrpcService.createAttachment();
}
@Override
public CompletableFuture<Optional<Model.Attachment>> getAttachment(String pageId, String name, String version) {
return xmlrpcService.getAttachment(pageId, name, version);
}
@Override
public CompletableFuture<Optional<Model.Page>> getPage(String spaceKey, String pageTitle) {
return xmlrpcService.getPage(spaceKey, pageTitle);
}
@Override
public CompletableFuture<Optional<Model.Page>> getPage(String pageId) {
return xmlrpcService.getPage(pageId);
}
@Override
public String toString() {
return xmlrpcService.toString();
}
@Override
public List<Model.PageSummary> getDescendents(String pageId) throws Exception {
return xmlrpcService.getDescendents(pageId);
}
@Override
public void removePage(String pageId) throws Exception {
xmlrpcService.removePage(pageId);
}
@Override
public void exportPage(String url, String spaceKey, String pageTitle, ExportFormat exfmt, File outputFile) throws Exception {
xmlrpcService.exportPage(url, spaceKey, pageTitle, exfmt, outputFile);
}
/* (non-Javadoc)
* @see java.io.Closeable#close()
*/
@Override
public void close() throws IOException {
xmlrpcService.logout();
}
}
/**
* return XMLRPC based Confluence services
*
* @param endpoint
* @param credentials
* @param proxyInfo
* @param sslInfo
* @return XMLRPC based Confluence services
* @throws Exception
*/
public static ConfluenceService createInstance( String endpoint,
Credentials credentials,
ConfluenceProxy proxyInfo,
SSLCertificateInfo sslInfo) throws Exception
{
if( ConfluenceService.Protocol.XMLRPC.match(endpoint)) {
return new MixedConfluenceService(endpoint, credentials, proxyInfo, sslInfo);
}
if( ConfluenceService.Protocol.REST.match(endpoint)) {
return new RESTConfluenceServiceImpl(endpoint, credentials /*, proxyInfo*/, sslInfo);
}
throw new IllegalArgumentException(
format("endpoint doesn't contain a valid API protocol\nIt must be '%s' or '%s'",
ConfluenceService.Protocol.XMLRPC.path(),
ConfluenceService.Protocol.REST.path())
);
}
}
| [
"[email protected]"
] | |
f6adcc95f148c2dcde4370bac6004a4886166e94 | a251d4d36b0e296866be8f0cc4d66d97dbdfdbec | /app/src/main/java/so/wih/android/jjewatch/ui/fragment/ContactFragment.java | 68228a2211b3cf567ddaebe6beccf0985b19fdbb | [] | no_license | GoldenStrawberry/JJEWatch | f02b606c664fe49a77985ad48d5c16458a407139 | bff87a71693984c85b17e4b0e26e993a89d14cd2 | refs/heads/master | 2021-01-20T00:53:19.647242 | 2017-04-24T06:40:29 | 2017-04-24T06:40:57 | 89,206,524 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,281 | java | package so.wih.android.jjewatch.ui.fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import so.wih.android.jjewatch.R;
import so.wih.android.jjewatch.ui.activity.ContactsActivity;
/**
* 联系人主界面
* Created by Administrator on 2016/11/22.
*/
public class ContactFragment extends Fragment {
private View view;
private ImageView contactImageView;
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.contact_fragment, null);
//初始化控件
initView();
return view;
}
/**
* 初始化控件
*/
private void initView() {
contactImageView = (ImageView) view.findViewById(R.id.contact_image);
contactImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), ContactsActivity.class);
startActivity(intent);
}
});
}
}
| [
"[email protected]"
] | |
9aa5e96e8810c75174146da47e6e9b7edb5244d6 | 764cd47e9a2ce2c02835a18481cffb0ed5f905db | /server/src/main/java/server/service/FollowerServiceImpl.java | 00d0a44226b8b10d0a75f9e18d8e43a4909d8bd5 | [] | no_license | MortalMachine/Tweeter | 4c14c319f2ea4fdc97eab0142a9b3e59dab61893 | 610692b35b1a8c4836d5238b491c094354372ea3 | refs/heads/master | 2022-04-22T05:31:59.161019 | 2020-04-16T22:18:28 | 2020-04-16T22:18:28 | 256,341,048 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,946 | java | package server.service;
import java.util.ArrayList;
import java.util.List;
import server.dto.FollowsDTO;
import model.domain.User;
import model.service.FollowerService;
import request.FollowersRequest;
import response.FollowersResponse;
import server.dao.follows.FollowsDynamoDAO;
import server.dao.follows.IFollowsDAO;
import server.dao.user.IUserDAO;
import server.dao.user.UserDynamoDAO;
import server.dto.UserDTO;
import server.s3.S3AO;
public class FollowerServiceImpl implements FollowerService {
@Override
public FollowersResponse getFollowers(FollowersRequest request) {
IFollowsDAO followsDAO = new FollowsDynamoDAO();
IUserDAO userDAO = new UserDynamoDAO();
S3AO s3AO = new S3AO();
User followee = request.getFollowee();
/* Query user's followers from follows table */
try {
FollowsDTO followsDTO = followsDAO.getFollowers(followee.getAlias(), request.getLastFollower());
List<User> followers = followsDTO.getUsers();
/* Fill list of followers for page */
for (User follower : followers) {
UserDTO userDTO = userDAO.getUserItem(follower.getAlias(), follower.getFirstName());
User followerFromUserTable = userDTO.getUser();
String imageUrl = s3AO.getProfilePicFromS3(followerFromUserTable.getImageUrl());
/* follower has a null lastname and imageurl needs to change the s3 file path
to a client-friendly url */
follower.setLastName(followerFromUserTable.getLastName());
follower.setImageUrl(imageUrl);
}
System.out.println("Sending followers response");
return new FollowersResponse(followers, followsDTO.hasMorePages());
} catch (Exception e) {
System.err.println(e.getMessage());
return new FollowersResponse(e.getMessage());
}
}
}
| [
"[email protected]"
] | |
61688891e969cbb456c19707437fbf6e38213e91 | d1d45741205fa19e92e58404533e0d28228d9fd5 | /src/main/java/onedarray/Solution.java | 8af0486a33ac36e3478b434c03b9c446f78ac966 | [] | no_license | federico-ravagli/hackerrank-java | 898901cf95eef63ea0510246f029a6e0f41f12bc | 69f9e848ac0a5ea6a08b61870cfb1c14c6ec98e2 | refs/heads/master | 2022-02-21T03:27:45.297837 | 2019-09-20T17:55:45 | 2019-09-20T17:55:45 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,088 | java | package onedarray;
import java.util.Scanner;
public class Solution {
private static int leap;
private static int[] game;
private static boolean canWin(int leap, int[] game) {
Solution.leap = leap;
Solution.game = game;
return canMove(0);
}
private static boolean canMove(int start) {
if (start < 0 || game[start] == 1)
return false;
else if (start == game.length - 1 || start + leap >= game.length)
return true;
game[start] = 1;
return canMove(start + 1) || canMove(start - 1) || canMove(start + leap);
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int q = scan.nextInt();
while (q-- > 0) {
int n = scan.nextInt();
int leap = scan.nextInt();
int[] game = new int[n];
for (int i = 0; i < n; i++) {
game[i] = scan.nextInt();
}
System.out.println( (canWin(leap, game)) ? "YES" : "NO" );
}
scan.close();
}
} | [
"[email protected]"
] | |
62b7828c21b9adc82379e91395182bda188c817c | 4ea1c43893200c86cc9dbaaa311ae052568e84fa | /src/exAula49/Ex01.java | a330302f3d494d14c8474e3660f7f76acf81598b | [] | no_license | uluizeduardo/exerciciosJava | b0a97c1c133fa5d948de972cedf0135b0b519972 | c1dcaa122ed1cb24f8bdb9c47cd41fbe28229614 | refs/heads/main | 2023-06-02T19:11:27.614983 | 2021-06-21T18:56:02 | 2021-06-21T18:56:02 | 373,830,547 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,082 | java | /*Escreva um programa que repita a leitura de uma senha até que ela seja válida. Para cada leitura de senha
incorreta informada, escrever a mensagem "Senha Invalida". Quando a senha for informada corretamente deve ser
impressa a mensagem "Acesso Permitido" e o algoritmo encerrado. Considere que a senha correta é o valor 2002.
Exemplo:
Entrada: Saída
2200 Senha Invalida
1020 Senha Invalida
2022 Senha Invalida
2002 Acesso Permitido
*/
package exAula49;
import java.util.Scanner;
public class Ex01 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
//Variável
double senha;
//Entrada de dados
System.out.println("Informe a senha: ");
senha = scan.nextInt();
//Condicional
while (senha != 2002){
System.out.println("Senha inválida ");
System.out.println("Informe a senha: ");
senha = scan.nextInt();
}
System.out.println("Acesso permitido");
}
}
| [
"[email protected]"
] | |
a9a2ccd15ed3b3167f20163923173f17888d4f33 | 63488e907632b2ab39edcf8d1ffc6db9658d6794 | /src/com/mercury/flows/Flow_Passengers.java | 509ad9795f9644a55ce25470a87b3c4d7000a26b | [] | no_license | Irwog19/Demo2 | b6cd7f6111651e7ac8a5e2823c5a539fef0f4999 | 311215b1e49fa8c49aaf69ced83f32fa9901365b | refs/heads/master | 2022-11-08T10:19:41.668519 | 2020-07-03T10:29:04 | 2020-07-03T10:29:04 | 276,871,945 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 361 | java | package com.mercury.flows;
import java.io.IOException;
import com.mercury.basedriver.Basedriver;
import com.mercury.pages.Page_Passengers;
public class Flow_Passengers extends Basedriver {
Page_Passengers pp = new Page_Passengers();
public void passengers_flow() throws IOException, InterruptedException {
pp.passenger1();
pp.passenger2();
}
}
| [
"[email protected]"
] | |
72c614ecae4b1338125f9e7dfca7c168d8b0dada | 6e8fd46f50e2ba8a59d8cd1fb8830f1dbeb3e02e | /src/com/kant/design/patterns/state/StateToggle.java | e5b6858171c50fcc7c16b9e57216dfdfc8c4e5dd | [
"MIT"
] | permissive | thekant/myCodeRepo | f41bfa1e0901536714517a831e95148507d882a8 | 41f53a11a07b0e0eaa849fe8119e5c21960e7593 | refs/heads/master | 2020-05-21T17:54:53.149716 | 2017-07-05T16:11:58 | 2017-07-05T16:11:58 | 65,477,480 | 3 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,392 | java | package com.kant.design.patterns.state;
/**
*
* @author shaskant
*
*/
import java.io.*;
class Button {
// stores context
private State current;
public Button() {
current = OFF.instance();
}
public void setCurrent(State s) {
current = s;
}
public void push() {
current.push(this);
}
}
// 4. The "wrappee" hierarchy
abstract class State {
// 5. Default behavior can go in the base class
public abstract void push(Button b);
}
class ON extends State {
private static ON inst = new ON();
private ON() {
}
public static State instance() {
return inst;
}
/**
* Current state is ON , so set state to OFF.
*/
public void push(Button b) {
b.setCurrent(OFF.instance());
System.out.println(" turning OFF");
}
}
class OFF extends State {
private static OFF inst = new OFF();
private OFF() {
}
public static State instance() {
return inst;
}
/**
* Current state is OFF , so set state to ON.
*/
public void push(Button b) {
b.setCurrent(ON.instance());
System.out.println(" turning ON");
}
}
/**
*
* @author shaskant
*
*/
public class StateToggle {
public static void main(String[] args) throws IOException {
InputStreamReader is = new InputStreamReader(System.in);
int ch;
Button btn = new Button();
while (true) {
System.out.print("Press 'Enter'");
ch = is.read();
ch = is.read();
btn.push();
}
}
}
| [
"[email protected]"
] | |
c7c2efdc5faaee6666df8f3778ec7fa1b288ec72 | 1b3b77970bca925f3e5c4d510a03ad5f64e0681c | /http/src/main/java/io/cantor/http/BoundHttpResponseEncoder.java | bf3216dbdf3b16452b5f8b96283a1b2ff8d2c7a6 | [
"Apache-2.0"
] | permissive | zhiwuya/cantor | dec78776065c5424ae85c0a21fea2a7e0918bd88 | 0fce472b419c35d387557dcc5acb0f787c3b0627 | refs/heads/master | 2020-03-30T05:38:47.477626 | 2018-09-26T07:54:40 | 2018-09-26T07:54:40 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 643 | java | package io.cantor.http;
import java.util.List;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.HttpResponseEncoder;
class BoundHttpResponseEncoder extends HttpResponseEncoder {
private ChannelHandlerContext context;
@Override
protected void encode(ChannelHandlerContext ctx, Object msg, List<Object> out)
throws Exception {
super.encode(context, msg, out);
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
context = PooledDirectByteBufAllocator.forceDirectAllocator(ctx);
super.handlerAdded(context);
}
}
| [
"[email protected]"
] | |
c9e34a1b2bf51ec6e3012444d7720cdcce3d5562 | f3c21a8d125f72498687f5ff24af0d7dafe74d5b | /09/src/Test3.java | 5d7970b88addf69e1a66ff1c1530d39730900a5d | [] | no_license | Saxphone1/Java_BigData | ccbd89ef4f1922144095eb91160034f4faba26b4 | fe560d1de3d5a48d46242f799c452fe60d1e72bc | refs/heads/master | 2020-05-24T19:24:54.456678 | 2019-03-31T03:20:27 | 2019-03-31T03:20:27 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,165 | java | import java.util.*;
//import java.util.function.Consumer;
public class Test3 {
public static void main(String[] args) {
Vector<String> v = new Vector<>();
v.add("Tom");
v.add("jack");
v.add("lose");
v.add("lily");
// iterator(v);
// enumeration(v);
foreach1(v);
}
public static void foreach1(Collection<String> c){
// Consumer<String> cc = (String str)->{
// System.out.println(str);
// };
// c.forEach(str-> System.out.println(str));
// c.forEach(System.out::println);
}
public static void foreach(Collection<String> c){
for(String s:c){
System.out.println(s);
}
}
public static void enumeration(Vector<String> v){
Enumeration<String> e = v.elements();
while (e.hasMoreElements()){
System.out.println(e.nextElement());
}
}
public static void iterator(Collection<String> c){
Iterator<String> it = c.iterator();
while (it.hasNext()){
System.out.println(it.next());
}
}
}
| [
"[email protected]"
] | |
e2e568bad75f3a06729b6a96ed55c64519a5f05c | faec30ec90321902f33049ba0c5441daaebed387 | /ManyToMany/src/main/java/com/manytomany/JoinedEntity/unidirectional/compositeprimary/Entity/USCBookPublisher.java | 9193848877995ef9241d84098e09887ec4e77cf8 | [] | no_license | chiraglucky/jpa-hibernate | cc94b5936d3496ce3f4f6f24829860cbcdcfca9f | 1750c7e54b9a6adf7f986b4bb789b15baf05f3df | refs/heads/main | 2023-07-13T16:10:23.386621 | 2021-08-24T14:06:09 | 2021-08-24T14:06:09 | 399,360,914 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,003 | java | package com.manytomany.JoinedEntity.unidirectional.compositeprimary.Entity;
import lombok.*;
import javax.persistence.*;
import java.util.Date;
//create bookpublisher as JoinedEntity with Composite primary key as BSCBookPublisherId
@Data
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@Entity
public class USCBookPublisher {
@EmbeddedId
private USCBookPublisherId id;
private Date publisherDate;
@ManyToOne(cascade = CascadeType.ALL)
@MapsId("uscBookId")
@JoinColumn(name = "book_id")
private USCBook USCBook;
@ManyToOne(cascade = CascadeType.ALL)
@MapsId("uscPublisherId")
@JoinColumn(name = "publisher_id")
private USCPublisher USCPublisher;
public USCBookPublisher(Date publisherDate, USCBook USCBook, USCPublisher USCPublisher) {
this.id=new USCBookPublisherId(USCBook.getId(), USCPublisher.getId());
this.publisherDate = publisherDate;
this.USCBook = USCBook;
this.USCPublisher = USCPublisher;
}
}
| [
"[email protected]"
] | |
3e1ebd56a9ef1db47ccbdadb96e9ebf01fc2233d | 64cc0c69946d673cd6c9624a009dde8213de06e3 | /src/test/java/com/aidriveall/cms/web/rest/AuthorityResourceIT.java | bcfc1ff470530442889021459ac65dbc86c2fac5 | [
"MIT"
] | permissive | luhai1/jhi-ant-vue | 5d46a5dbf0f1133edb63a049909e960f7053c66c | e0aba8370ea1f9c8804bf1e3cfb319ee2ed29666 | refs/heads/master | 2023-03-21T11:42:40.672265 | 2020-10-09T08:51:15 | 2020-10-09T08:51:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 35,046 | java | package com.aidriveall.cms.web.rest;
import com.aidriveall.cms.JhiAntVueApp;
import com.aidriveall.cms.domain.Authority;
import com.aidriveall.cms.domain.Authority;
import com.aidriveall.cms.domain.User;
import com.aidriveall.cms.domain.ViewPermission;
import com.aidriveall.cms.repository.AuthorityRepository;
import com.aidriveall.cms.service.AuthorityService;
import com.aidriveall.cms.service.dto.AuthorityDTO;
import com.aidriveall.cms.service.mapper.AuthorityMapper;
import com.aidriveall.cms.web.rest.errors.ExceptionTranslator;
import com.aidriveall.cms.service.dto.AuthorityCriteria;
import com.aidriveall.cms.service.AuthorityQueryService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.Validator;
import javax.persistence.EntityManager;
import java.util.ArrayList;
import java.util.List;
import static com.aidriveall.cms.web.rest.TestUtil.createFormattingConversionService;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Integration tests for the {@link AuthorityResource} REST controller.
*/
@SpringBootTest(classes = JhiAntVueApp.class)
public class AuthorityResourceIT {
private static final String DEFAULT_NAME = "AAAAAAAAAA";
private static final String UPDATED_NAME = "BBBBBBBBBB";
private static final String DEFAULT_CODE = "AAAAAAAAAA";
private static final String UPDATED_CODE = "BBBBBBBBBB";
private static final String DEFAULT_INFO = "AAAAAAAAAA";
private static final String UPDATED_INFO = "BBBBBBBBBB";
private static final Integer DEFAULT_ORDER = 1;
private static final Integer UPDATED_ORDER = 2;
private static final Integer SMALLER_ORDER = 1 - 1;
private static final Boolean DEFAULT_DISPLAY = false;
private static final Boolean UPDATED_DISPLAY = true;
@Autowired
private AuthorityRepository authorityRepository;
@Mock
private AuthorityRepository authorityRepositoryMock;
@Autowired
private AuthorityMapper authorityMapper;
@Mock
private AuthorityService authorityServiceMock;
@Autowired
private AuthorityService authorityService;
@Autowired
private AuthorityQueryService authorityQueryService;
@Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
@Autowired
private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
@Autowired
private ExceptionTranslator exceptionTranslator;
@Autowired
private EntityManager em;
@Autowired
private Validator validator;
private MockMvc restAuthorityMockMvc;
private Authority authority;
@BeforeEach
public void setup() {
MockitoAnnotations.initMocks(this);
final AuthorityResource authorityResource = new AuthorityResource(authorityService, authorityQueryService);
this.restAuthorityMockMvc = MockMvcBuilders.standaloneSetup(authorityResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setConversionService(createFormattingConversionService())
.setMessageConverters(jacksonMessageConverter)
.setValidator(validator).build();
}
/**
* Create an entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static Authority createEntity(EntityManager em) {
Authority authority = new Authority()
.name(DEFAULT_NAME)
.code(DEFAULT_CODE)
.info(DEFAULT_INFO)
.order(DEFAULT_ORDER)
.display(DEFAULT_DISPLAY);
return authority;
}
/**
* Create an updated entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static Authority createUpdatedEntity(EntityManager em) {
Authority authority = new Authority()
.name(UPDATED_NAME)
.code(UPDATED_CODE)
.info(UPDATED_INFO)
.order(UPDATED_ORDER)
.display(UPDATED_DISPLAY);
return authority;
}
@BeforeEach
public void initTest() {
authority = createEntity(em);
}
@Test
@Transactional
public void createAuthority() throws Exception {
int databaseSizeBeforeCreate = authorityRepository.findAll().size();
// Create the Authority
AuthorityDTO authorityDTO = authorityMapper.toDto(authority);
restAuthorityMockMvc.perform(post("/api/authorities")
.contentType(TestUtil.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(authorityDTO)))
.andExpect(status().isCreated());
// Validate the Authority in the database
List<Authority> authorityList = authorityRepository.findAll();
assertThat(authorityList).hasSize(databaseSizeBeforeCreate + 1);
Authority testAuthority = authorityList.get(authorityList.size() - 1);
assertThat(testAuthority.getName()).isEqualTo(DEFAULT_NAME);
assertThat(testAuthority.getCode()).isEqualTo(DEFAULT_CODE);
assertThat(testAuthority.getInfo()).isEqualTo(DEFAULT_INFO);
assertThat(testAuthority.getOrder()).isEqualTo(DEFAULT_ORDER);
assertThat(testAuthority.isDisplay()).isEqualTo(DEFAULT_DISPLAY);
}
@Test
@Transactional
public void createAuthorityWithExistingId() throws Exception {
int databaseSizeBeforeCreate = authorityRepository.findAll().size();
// Create the Authority with an existing ID
authority.setId(1L);
AuthorityDTO authorityDTO = authorityMapper.toDto(authority);
// An entity with an existing ID cannot be created, so this API call must fail
restAuthorityMockMvc.perform(post("/api/authorities")
.contentType(TestUtil.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(authorityDTO)))
.andExpect(status().isBadRequest());
// Validate the Authority in the database
List<Authority> authorityList = authorityRepository.findAll();
assertThat(authorityList).hasSize(databaseSizeBeforeCreate);
}
@Test
@Transactional
public void getAllAuthorities() throws Exception {
// Initialize the database
authorityRepository.saveAndFlush(authority);
// Get all the authorityList
restAuthorityMockMvc.perform(get("/api/authorities?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(authority.getId().intValue())))
.andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME)))
.andExpect(jsonPath("$.[*].code").value(hasItem(DEFAULT_CODE)))
.andExpect(jsonPath("$.[*].info").value(hasItem(DEFAULT_INFO)))
.andExpect(jsonPath("$.[*].order").value(hasItem(DEFAULT_ORDER)))
.andExpect(jsonPath("$.[*].display").value(hasItem(DEFAULT_DISPLAY.booleanValue())));
}
@SuppressWarnings({"unchecked"})
public void getAllAuthoritiesWithEagerRelationshipsIsEnabled() throws Exception {
AuthorityResource authorityResource = new AuthorityResource(authorityServiceMock, authorityQueryService);
when(authorityServiceMock.findAllWithEagerRelationships(any())).thenReturn(new PageImpl(new ArrayList<>()));
MockMvc restAuthorityMockMvc = MockMvcBuilders.standaloneSetup(authorityResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setConversionService(createFormattingConversionService())
.setMessageConverters(jacksonMessageConverter).build();
restAuthorityMockMvc.perform(get("/api/authorities?eagerload=true"))
.andExpect(status().isOk());
verify(authorityServiceMock, times(1)).findAllWithEagerRelationships(any());
}
@SuppressWarnings({"unchecked"})
public void getAllAuthoritiesWithEagerRelationshipsIsNotEnabled() throws Exception {
AuthorityResource authorityResource = new AuthorityResource(authorityServiceMock, authorityQueryService);
when(authorityServiceMock.findAllWithEagerRelationships(any())).thenReturn(new PageImpl(new ArrayList<>()));
MockMvc restAuthorityMockMvc = MockMvcBuilders.standaloneSetup(authorityResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setConversionService(createFormattingConversionService())
.setMessageConverters(jacksonMessageConverter).build();
restAuthorityMockMvc.perform(get("/api/authorities?eagerload=true"))
.andExpect(status().isOk());
verify(authorityServiceMock, times(1)).findAllWithEagerRelationships(any());
}
@Test
@Transactional
public void getAuthority() throws Exception {
// Initialize the database
authorityRepository.saveAndFlush(authority);
// Get the authority
restAuthorityMockMvc.perform(get("/api/authorities/{id}", authority.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$.id").value(authority.getId().intValue()))
.andExpect(jsonPath("$.name").value(DEFAULT_NAME))
.andExpect(jsonPath("$.code").value(DEFAULT_CODE))
.andExpect(jsonPath("$.info").value(DEFAULT_INFO))
.andExpect(jsonPath("$.order").value(DEFAULT_ORDER))
.andExpect(jsonPath("$.display").value(DEFAULT_DISPLAY.booleanValue()));
}
@Test
@Transactional
public void getAuthoritiesByIdFiltering() throws Exception {
// Initialize the database
authorityRepository.saveAndFlush(authority);
Long id = authority.getId();
defaultAuthorityShouldBeFound("id.equals=" + id);
defaultAuthorityShouldNotBeFound("id.notEquals=" + id);
defaultAuthorityShouldBeFound("id.greaterThanOrEqual=" + id);
defaultAuthorityShouldNotBeFound("id.greaterThan=" + id);
defaultAuthorityShouldBeFound("id.lessThanOrEqual=" + id);
defaultAuthorityShouldNotBeFound("id.lessThan=" + id);
}
@Test
@Transactional
public void getAllAuthoritiesByNameIsEqualToSomething() throws Exception {
// Initialize the database
authorityRepository.saveAndFlush(authority);
// Get all the authorityList where name equals to DEFAULT_NAME
defaultAuthorityShouldBeFound("name.equals=" + DEFAULT_NAME);
// Get all the authorityList where name equals to UPDATED_NAME
defaultAuthorityShouldNotBeFound("name.equals=" + UPDATED_NAME);
}
@Test
@Transactional
public void getAllAuthoritiesByNameIsNotEqualToSomething() throws Exception {
// Initialize the database
authorityRepository.saveAndFlush(authority);
// Get all the authorityList where name not equals to DEFAULT_NAME
defaultAuthorityShouldNotBeFound("name.notEquals=" + DEFAULT_NAME);
// Get all the authorityList where name not equals to UPDATED_NAME
defaultAuthorityShouldBeFound("name.notEquals=" + UPDATED_NAME);
}
@Test
@Transactional
public void getAllAuthoritiesByNameIsInShouldWork() throws Exception {
// Initialize the database
authorityRepository.saveAndFlush(authority);
// Get all the authorityList where name in DEFAULT_NAME or UPDATED_NAME
defaultAuthorityShouldBeFound("name.in=" + DEFAULT_NAME + "," + UPDATED_NAME);
// Get all the authorityList where name equals to UPDATED_NAME
defaultAuthorityShouldNotBeFound("name.in=" + UPDATED_NAME);
}
@Test
@Transactional
public void getAllAuthoritiesByNameIsNullOrNotNull() throws Exception {
// Initialize the database
authorityRepository.saveAndFlush(authority);
// Get all the authorityList where name is not null
defaultAuthorityShouldBeFound("name.specified=true");
// Get all the authorityList where name is null
defaultAuthorityShouldNotBeFound("name.specified=false");
}
@Test
@Transactional
public void getAllAuthoritiesByNameContainsSomething() throws Exception {
// Initialize the database
authorityRepository.saveAndFlush(authority);
// Get all the authorityList where name contains DEFAULT_NAME
defaultAuthorityShouldBeFound("name.contains=" + DEFAULT_NAME);
// Get all the authorityList where name contains UPDATED_NAME
defaultAuthorityShouldNotBeFound("name.contains=" + UPDATED_NAME);
}
@Test
@Transactional
public void getAllAuthoritiesByNameNotContainsSomething() throws Exception {
// Initialize the database
authorityRepository.saveAndFlush(authority);
// Get all the authorityList where name does not contain DEFAULT_NAME
defaultAuthorityShouldNotBeFound("name.doesNotContain=" + DEFAULT_NAME);
// Get all the authorityList where name does not contain UPDATED_NAME
defaultAuthorityShouldBeFound("name.doesNotContain=" + UPDATED_NAME);
}
@Test
@Transactional
public void getAllAuthoritiesByCodeIsEqualToSomething() throws Exception {
// Initialize the database
authorityRepository.saveAndFlush(authority);
// Get all the authorityList where code equals to DEFAULT_CODE
defaultAuthorityShouldBeFound("code.equals=" + DEFAULT_CODE);
// Get all the authorityList where code equals to UPDATED_CODE
defaultAuthorityShouldNotBeFound("code.equals=" + UPDATED_CODE);
}
@Test
@Transactional
public void getAllAuthoritiesByCodeIsNotEqualToSomething() throws Exception {
// Initialize the database
authorityRepository.saveAndFlush(authority);
// Get all the authorityList where code not equals to DEFAULT_CODE
defaultAuthorityShouldNotBeFound("code.notEquals=" + DEFAULT_CODE);
// Get all the authorityList where code not equals to UPDATED_CODE
defaultAuthorityShouldBeFound("code.notEquals=" + UPDATED_CODE);
}
@Test
@Transactional
public void getAllAuthoritiesByCodeIsInShouldWork() throws Exception {
// Initialize the database
authorityRepository.saveAndFlush(authority);
// Get all the authorityList where code in DEFAULT_CODE or UPDATED_CODE
defaultAuthorityShouldBeFound("code.in=" + DEFAULT_CODE + "," + UPDATED_CODE);
// Get all the authorityList where code equals to UPDATED_CODE
defaultAuthorityShouldNotBeFound("code.in=" + UPDATED_CODE);
}
@Test
@Transactional
public void getAllAuthoritiesByCodeIsNullOrNotNull() throws Exception {
// Initialize the database
authorityRepository.saveAndFlush(authority);
// Get all the authorityList where code is not null
defaultAuthorityShouldBeFound("code.specified=true");
// Get all the authorityList where code is null
defaultAuthorityShouldNotBeFound("code.specified=false");
}
@Test
@Transactional
public void getAllAuthoritiesByCodeContainsSomething() throws Exception {
// Initialize the database
authorityRepository.saveAndFlush(authority);
// Get all the authorityList where code contains DEFAULT_CODE
defaultAuthorityShouldBeFound("code.contains=" + DEFAULT_CODE);
// Get all the authorityList where code contains UPDATED_CODE
defaultAuthorityShouldNotBeFound("code.contains=" + UPDATED_CODE);
}
@Test
@Transactional
public void getAllAuthoritiesByCodeNotContainsSomething() throws Exception {
// Initialize the database
authorityRepository.saveAndFlush(authority);
// Get all the authorityList where code does not contain DEFAULT_CODE
defaultAuthorityShouldNotBeFound("code.doesNotContain=" + DEFAULT_CODE);
// Get all the authorityList where code does not contain UPDATED_CODE
defaultAuthorityShouldBeFound("code.doesNotContain=" + UPDATED_CODE);
}
@Test
@Transactional
public void getAllAuthoritiesByInfoIsEqualToSomething() throws Exception {
// Initialize the database
authorityRepository.saveAndFlush(authority);
// Get all the authorityList where info equals to DEFAULT_INFO
defaultAuthorityShouldBeFound("info.equals=" + DEFAULT_INFO);
// Get all the authorityList where info equals to UPDATED_INFO
defaultAuthorityShouldNotBeFound("info.equals=" + UPDATED_INFO);
}
@Test
@Transactional
public void getAllAuthoritiesByInfoIsNotEqualToSomething() throws Exception {
// Initialize the database
authorityRepository.saveAndFlush(authority);
// Get all the authorityList where info not equals to DEFAULT_INFO
defaultAuthorityShouldNotBeFound("info.notEquals=" + DEFAULT_INFO);
// Get all the authorityList where info not equals to UPDATED_INFO
defaultAuthorityShouldBeFound("info.notEquals=" + UPDATED_INFO);
}
@Test
@Transactional
public void getAllAuthoritiesByInfoIsInShouldWork() throws Exception {
// Initialize the database
authorityRepository.saveAndFlush(authority);
// Get all the authorityList where info in DEFAULT_INFO or UPDATED_INFO
defaultAuthorityShouldBeFound("info.in=" + DEFAULT_INFO + "," + UPDATED_INFO);
// Get all the authorityList where info equals to UPDATED_INFO
defaultAuthorityShouldNotBeFound("info.in=" + UPDATED_INFO);
}
@Test
@Transactional
public void getAllAuthoritiesByInfoIsNullOrNotNull() throws Exception {
// Initialize the database
authorityRepository.saveAndFlush(authority);
// Get all the authorityList where info is not null
defaultAuthorityShouldBeFound("info.specified=true");
// Get all the authorityList where info is null
defaultAuthorityShouldNotBeFound("info.specified=false");
}
@Test
@Transactional
public void getAllAuthoritiesByInfoContainsSomething() throws Exception {
// Initialize the database
authorityRepository.saveAndFlush(authority);
// Get all the authorityList where info contains DEFAULT_INFO
defaultAuthorityShouldBeFound("info.contains=" + DEFAULT_INFO);
// Get all the authorityList where info contains UPDATED_INFO
defaultAuthorityShouldNotBeFound("info.contains=" + UPDATED_INFO);
}
@Test
@Transactional
public void getAllAuthoritiesByInfoNotContainsSomething() throws Exception {
// Initialize the database
authorityRepository.saveAndFlush(authority);
// Get all the authorityList where info does not contain DEFAULT_INFO
defaultAuthorityShouldNotBeFound("info.doesNotContain=" + DEFAULT_INFO);
// Get all the authorityList where info does not contain UPDATED_INFO
defaultAuthorityShouldBeFound("info.doesNotContain=" + UPDATED_INFO);
}
@Test
@Transactional
public void getAllAuthoritiesByOrderIsEqualToSomething() throws Exception {
// Initialize the database
authorityRepository.saveAndFlush(authority);
// Get all the authorityList where order equals to DEFAULT_ORDER
defaultAuthorityShouldBeFound("order.equals=" + DEFAULT_ORDER);
// Get all the authorityList where order equals to UPDATED_ORDER
defaultAuthorityShouldNotBeFound("order.equals=" + UPDATED_ORDER);
}
@Test
@Transactional
public void getAllAuthoritiesByOrderIsNotEqualToSomething() throws Exception {
// Initialize the database
authorityRepository.saveAndFlush(authority);
// Get all the authorityList where order not equals to DEFAULT_ORDER
defaultAuthorityShouldNotBeFound("order.notEquals=" + DEFAULT_ORDER);
// Get all the authorityList where order not equals to UPDATED_ORDER
defaultAuthorityShouldBeFound("order.notEquals=" + UPDATED_ORDER);
}
@Test
@Transactional
public void getAllAuthoritiesByOrderIsInShouldWork() throws Exception {
// Initialize the database
authorityRepository.saveAndFlush(authority);
// Get all the authorityList where order in DEFAULT_ORDER or UPDATED_ORDER
defaultAuthorityShouldBeFound("order.in=" + DEFAULT_ORDER + "," + UPDATED_ORDER);
// Get all the authorityList where order equals to UPDATED_ORDER
defaultAuthorityShouldNotBeFound("order.in=" + UPDATED_ORDER);
}
@Test
@Transactional
public void getAllAuthoritiesByOrderIsNullOrNotNull() throws Exception {
// Initialize the database
authorityRepository.saveAndFlush(authority);
// Get all the authorityList where order is not null
defaultAuthorityShouldBeFound("order.specified=true");
// Get all the authorityList where order is null
defaultAuthorityShouldNotBeFound("order.specified=false");
}
@Test
@Transactional
public void getAllAuthoritiesByOrderIsGreaterThanOrEqualToSomething() throws Exception {
// Initialize the database
authorityRepository.saveAndFlush(authority);
// Get all the authorityList where order is greater than or equal to DEFAULT_ORDER
defaultAuthorityShouldBeFound("order.greaterThanOrEqual=" + DEFAULT_ORDER);
// Get all the authorityList where order is greater than or equal to UPDATED_ORDER
defaultAuthorityShouldNotBeFound("order.greaterThanOrEqual=" + UPDATED_ORDER);
}
@Test
@Transactional
public void getAllAuthoritiesByOrderIsLessThanOrEqualToSomething() throws Exception {
// Initialize the database
authorityRepository.saveAndFlush(authority);
// Get all the authorityList where order is less than or equal to DEFAULT_ORDER
defaultAuthorityShouldBeFound("order.lessThanOrEqual=" + DEFAULT_ORDER);
// Get all the authorityList where order is less than or equal to SMALLER_ORDER
defaultAuthorityShouldNotBeFound("order.lessThanOrEqual=" + SMALLER_ORDER);
}
@Test
@Transactional
public void getAllAuthoritiesByOrderIsLessThanSomething() throws Exception {
// Initialize the database
authorityRepository.saveAndFlush(authority);
// Get all the authorityList where order is less than DEFAULT_ORDER
defaultAuthorityShouldNotBeFound("order.lessThan=" + DEFAULT_ORDER);
// Get all the authorityList where order is less than UPDATED_ORDER
defaultAuthorityShouldBeFound("order.lessThan=" + UPDATED_ORDER);
}
@Test
@Transactional
public void getAllAuthoritiesByOrderIsGreaterThanSomething() throws Exception {
// Initialize the database
authorityRepository.saveAndFlush(authority);
// Get all the authorityList where order is greater than DEFAULT_ORDER
defaultAuthorityShouldNotBeFound("order.greaterThan=" + DEFAULT_ORDER);
// Get all the authorityList where order is greater than SMALLER_ORDER
defaultAuthorityShouldBeFound("order.greaterThan=" + SMALLER_ORDER);
}
@Test
@Transactional
public void getAllAuthoritiesByDisplayIsEqualToSomething() throws Exception {
// Initialize the database
authorityRepository.saveAndFlush(authority);
// Get all the authorityList where display equals to DEFAULT_DISPLAY
defaultAuthorityShouldBeFound("display.equals=" + DEFAULT_DISPLAY);
// Get all the authorityList where display equals to UPDATED_DISPLAY
defaultAuthorityShouldNotBeFound("display.equals=" + UPDATED_DISPLAY);
}
@Test
@Transactional
public void getAllAuthoritiesByDisplayIsNotEqualToSomething() throws Exception {
// Initialize the database
authorityRepository.saveAndFlush(authority);
// Get all the authorityList where display not equals to DEFAULT_DISPLAY
defaultAuthorityShouldNotBeFound("display.notEquals=" + DEFAULT_DISPLAY);
// Get all the authorityList where display not equals to UPDATED_DISPLAY
defaultAuthorityShouldBeFound("display.notEquals=" + UPDATED_DISPLAY);
}
@Test
@Transactional
public void getAllAuthoritiesByDisplayIsInShouldWork() throws Exception {
// Initialize the database
authorityRepository.saveAndFlush(authority);
// Get all the authorityList where display in DEFAULT_DISPLAY or UPDATED_DISPLAY
defaultAuthorityShouldBeFound("display.in=" + DEFAULT_DISPLAY + "," + UPDATED_DISPLAY);
// Get all the authorityList where display equals to UPDATED_DISPLAY
defaultAuthorityShouldNotBeFound("display.in=" + UPDATED_DISPLAY);
}
@Test
@Transactional
public void getAllAuthoritiesByDisplayIsNullOrNotNull() throws Exception {
// Initialize the database
authorityRepository.saveAndFlush(authority);
// Get all the authorityList where display is not null
defaultAuthorityShouldBeFound("display.specified=true");
// Get all the authorityList where display is null
defaultAuthorityShouldNotBeFound("display.specified=false");
}
@Test
@Transactional
public void getAllAuthoritiesByChildrenIsEqualToSomething() throws Exception {
// Initialize the database
authorityRepository.saveAndFlush(authority);
Authority children = AuthorityResourceIT.createEntity(em);
em.persist(children);
em.flush();
authority.addChildren(children);
authorityRepository.saveAndFlush(authority);
Long childrenId = children.getId();
// Get all the authorityList where children equals to childrenId
defaultAuthorityShouldBeFound("childrenId.equals=" + childrenId);
// Get all the authorityList where children equals to childrenId + 1
defaultAuthorityShouldNotBeFound("childrenId.equals=" + (childrenId + 1));
}
@Test
@Transactional
public void getAllAuthoritiesByUsersIsEqualToSomething() throws Exception {
// Initialize the database
authorityRepository.saveAndFlush(authority);
User users = UserResourceIT.createEntity(em);
em.persist(users);
em.flush();
authority.addUsers(users);
authorityRepository.saveAndFlush(authority);
Long usersId = users.getId();
// Get all the authorityList where users equals to usersId
defaultAuthorityShouldBeFound("usersId.equals=" + usersId);
// Get all the authorityList where users equals to usersId + 1
defaultAuthorityShouldNotBeFound("usersId.equals=" + (usersId + 1));
}
@Test
@Transactional
public void getAllAuthoritiesByViewPermissionIsEqualToSomething() throws Exception {
// Initialize the database
authorityRepository.saveAndFlush(authority);
ViewPermission viewPermission = ViewPermissionResourceIT.createEntity(em);
em.persist(viewPermission);
em.flush();
authority.addViewPermission(viewPermission);
authorityRepository.saveAndFlush(authority);
Long viewPermissionId = viewPermission.getId();
// Get all the authorityList where viewPermission equals to viewPermissionId
defaultAuthorityShouldBeFound("viewPermissionId.equals=" + viewPermissionId);
// Get all the authorityList where viewPermission equals to viewPermissionId + 1
defaultAuthorityShouldNotBeFound("viewPermissionId.equals=" + (viewPermissionId + 1));
}
@Test
@Transactional
public void getAllAuthoritiesByParentIsEqualToSomething() throws Exception {
// Initialize the database
authorityRepository.saveAndFlush(authority);
Authority parent = AuthorityResourceIT.createEntity(em);
em.persist(parent);
em.flush();
authority.setParent(parent);
authorityRepository.saveAndFlush(authority);
Long parentId = parent.getId();
// Get all the authorityList where parent equals to parentId
defaultAuthorityShouldBeFound("parentId.equals=" + parentId);
// Get all the authorityList where parent equals to parentId + 1
defaultAuthorityShouldNotBeFound("parentId.equals=" + (parentId + 1));
}
/**
* Executes the search, and checks that the default entity is returned.
*/
private void defaultAuthorityShouldBeFound(String filter) throws Exception {
restAuthorityMockMvc.perform(get("/api/authorities?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(authority.getId().intValue())))
.andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME)))
.andExpect(jsonPath("$.[*].code").value(hasItem(DEFAULT_CODE)))
.andExpect(jsonPath("$.[*].info").value(hasItem(DEFAULT_INFO)))
.andExpect(jsonPath("$.[*].order").value(hasItem(DEFAULT_ORDER)))
.andExpect(jsonPath("$.[*].display").value(hasItem(DEFAULT_DISPLAY.booleanValue())));
// Check, that the count call also returns 1
restAuthorityMockMvc.perform(get("/api/authorities/count?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(content().string("1"));
}
/**
* Executes the search, and checks that the default entity is not returned.
*/
private void defaultAuthorityShouldNotBeFound(String filter) throws Exception {
restAuthorityMockMvc.perform(get("/api/authorities?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$").isArray())
.andExpect(jsonPath("$").isEmpty());
// Check, that the count call also returns 0
restAuthorityMockMvc.perform(get("/api/authorities/count?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(content().string("0"));
}
@Test
@Transactional
public void getNonExistingAuthority() throws Exception {
// Get the authority
restAuthorityMockMvc.perform(get("/api/authorities/{id}", Long.MAX_VALUE))
.andExpect(status().isNotFound());
}
@Test
@Transactional
public void updateAuthority() throws Exception {
// Initialize the database
authorityRepository.saveAndFlush(authority);
int databaseSizeBeforeUpdate = authorityRepository.findAll().size();
// Update the authority
Authority updatedAuthority = authorityRepository.findById(authority.getId()).get();
// Disconnect from session so that the updates on updatedAuthority are not directly saved in db
em.detach(updatedAuthority);
updatedAuthority
.name(UPDATED_NAME)
.code(UPDATED_CODE)
.info(UPDATED_INFO)
.order(UPDATED_ORDER)
.display(UPDATED_DISPLAY);
AuthorityDTO authorityDTO = authorityMapper.toDto(updatedAuthority);
restAuthorityMockMvc.perform(put("/api/authorities")
.contentType(TestUtil.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(authorityDTO)))
.andExpect(status().isOk());
// Validate the Authority in the database
List<Authority> authorityList = authorityRepository.findAll();
assertThat(authorityList).hasSize(databaseSizeBeforeUpdate);
Authority testAuthority = authorityList.get(authorityList.size() - 1);
assertThat(testAuthority.getName()).isEqualTo(UPDATED_NAME);
assertThat(testAuthority.getCode()).isEqualTo(UPDATED_CODE);
assertThat(testAuthority.getInfo()).isEqualTo(UPDATED_INFO);
assertThat(testAuthority.getOrder()).isEqualTo(UPDATED_ORDER);
assertThat(testAuthority.isDisplay()).isEqualTo(UPDATED_DISPLAY);
}
@Test
@Transactional
public void updateNonExistingAuthority() throws Exception {
int databaseSizeBeforeUpdate = authorityRepository.findAll().size();
// Create the Authority
AuthorityDTO authorityDTO = authorityMapper.toDto(authority);
// If the entity doesn't have an ID, it will throw BadRequestAlertException
restAuthorityMockMvc.perform(put("/api/authorities")
.contentType(TestUtil.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(authorityDTO)))
.andExpect(status().isBadRequest());
// Validate the Authority in the database
List<Authority> authorityList = authorityRepository.findAll();
assertThat(authorityList).hasSize(databaseSizeBeforeUpdate);
}
@Test
@Transactional
public void deleteAuthority() throws Exception {
// Initialize the database
authorityRepository.saveAndFlush(authority);
int databaseSizeBeforeDelete = authorityRepository.findAll().size();
// Delete the authority
restAuthorityMockMvc.perform(delete("/api/authorities/{id}", authority.getId())
.accept(TestUtil.APPLICATION_JSON))
.andExpect(status().isNoContent());
// Validate the database contains one less item
List<Authority> authorityList = authorityRepository.findAll();
assertThat(authorityList).hasSize(databaseSizeBeforeDelete - 1);
}
}
| [
"[email protected]"
] | |
08a7719598f92d96749efd28c090fe939ccd251e | 9fb02ba460aaad7040a792f79825e5b89b4451d3 | /app/src/test/java/com/lifeistech/android/myapplication/ExampleUnitTest.java | a1cae6d650442de7fc8d8713d61aa4b2dd63d25a | [] | no_license | TsukasaMaruyama/app426 | 0ef95d98b50cb6232357a4b072338276099db513 | a44cb7d700f0ff034498d497e53e934ab2aed85d | refs/heads/master | 2020-03-13T08:13:48.565016 | 2018-04-25T17:03:34 | 2018-04-25T17:03:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 414 | java | package com.lifeistech.android.myapplication;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | [
"[email protected]"
] | |
6f56b68e33a9b6dc9327c3f01232318a3548c78a | 7d8236d87119493601f83d93ae4a36c29be3f8bc | /src/test/java/io/github/jhipster/application/web/rest/AuditResourceIntTest.java | 004ad669c89004ea9a55a0334ca804ea6dfdb268 | [] | no_license | scarabetta/jhipsterSample2 | e4808cdbeda4482aa507814e406d36bdef1ae8e2 | f5155176eb5b6c334dec9ab94728addea3c9c470 | refs/heads/master | 2021-04-28T13:34:14.329505 | 2018-02-19T19:03:34 | 2018-02-19T19:03:34 | 122,107,341 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,053 | java | package io.github.jhipster.application.web.rest;
import io.github.jhipster.application.JhipsterSample2App;
import io.github.jhipster.application.config.audit.AuditEventConverter;
import io.github.jhipster.application.domain.PersistentAuditEvent;
import io.github.jhipster.application.repository.PersistenceAuditEventRepository;
import io.github.jhipster.application.service.AuditEventService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.format.support.FormattingConversionService;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Test class for the AuditResource REST controller.
*
* @see AuditResource
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = JhipsterSample2App.class)
@Transactional
public class AuditResourceIntTest {
private static final String SAMPLE_PRINCIPAL = "SAMPLE_PRINCIPAL";
private static final String SAMPLE_TYPE = "SAMPLE_TYPE";
private static final Instant SAMPLE_TIMESTAMP = Instant.parse("2015-08-04T10:11:30Z");
private static final long SECONDS_PER_DAY = 60 * 60 * 24;
@Autowired
private PersistenceAuditEventRepository auditEventRepository;
@Autowired
private AuditEventConverter auditEventConverter;
@Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
@Autowired
private FormattingConversionService formattingConversionService;
@Autowired
private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
private PersistentAuditEvent auditEvent;
private MockMvc restAuditMockMvc;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
AuditEventService auditEventService =
new AuditEventService(auditEventRepository, auditEventConverter);
AuditResource auditResource = new AuditResource(auditEventService);
this.restAuditMockMvc = MockMvcBuilders.standaloneSetup(auditResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setConversionService(formattingConversionService)
.setMessageConverters(jacksonMessageConverter).build();
}
@Before
public void initTest() {
auditEventRepository.deleteAll();
auditEvent = new PersistentAuditEvent();
auditEvent.setAuditEventType(SAMPLE_TYPE);
auditEvent.setPrincipal(SAMPLE_PRINCIPAL);
auditEvent.setAuditEventDate(SAMPLE_TIMESTAMP);
}
@Test
public void getAllAudits() throws Exception {
// Initialize the database
auditEventRepository.save(auditEvent);
// Get all the audits
restAuditMockMvc.perform(get("/management/audits"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].principal").value(hasItem(SAMPLE_PRINCIPAL)));
}
@Test
public void getAudit() throws Exception {
// Initialize the database
auditEventRepository.save(auditEvent);
// Get the audit
restAuditMockMvc.perform(get("/management/audits/{id}", auditEvent.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.principal").value(SAMPLE_PRINCIPAL));
}
@Test
public void getAuditsByDate() throws Exception {
// Initialize the database
auditEventRepository.save(auditEvent);
// Generate dates for selecting audits by date, making sure the period will contain the audit
String fromDate = SAMPLE_TIMESTAMP.minusSeconds(SECONDS_PER_DAY).toString().substring(0,10);
String toDate = SAMPLE_TIMESTAMP.plusSeconds(SECONDS_PER_DAY).toString().substring(0,10);
// Get the audit
restAuditMockMvc.perform(get("/management/audits?fromDate="+fromDate+"&toDate="+toDate))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].principal").value(hasItem(SAMPLE_PRINCIPAL)));
}
@Test
public void getNonExistingAuditsByDate() throws Exception {
// Initialize the database
auditEventRepository.save(auditEvent);
// Generate dates for selecting audits by date, making sure the period will not contain the sample audit
String fromDate = SAMPLE_TIMESTAMP.minusSeconds(2*SECONDS_PER_DAY).toString().substring(0,10);
String toDate = SAMPLE_TIMESTAMP.minusSeconds(SECONDS_PER_DAY).toString().substring(0,10);
// Query audits but expect no results
restAuditMockMvc.perform(get("/management/audits?fromDate=" + fromDate + "&toDate=" + toDate))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(header().string("X-Total-Count", "0"));
}
@Test
public void getNonExistingAudit() throws Exception {
// Get the audit
restAuditMockMvc.perform(get("/management/audits/{id}", Long.MAX_VALUE))
.andExpect(status().isNotFound());
}
}
| [
"[email protected]"
] | |
cdfae2beaa053fcd46852f3df9e262ff3a9acccb | 56ef36eb19786046b42ea0ec78dc47d2c17df7d5 | /EDD/practica4/src/mx/unam/ciencias/edd/ArbolBinario.java | fdca2c9dbde4bc84f1da6beeaa5a779b27e687dc | [] | no_license | acasanova009/UNAM | b05be40834615b03742b5fe5c5c99eb7df11e964 | 9e628aebe601098ecb8d786991f17685018f6bb5 | refs/heads/master | 2021-05-29T11:10:04.847601 | 2015-09-03T02:14:20 | 2015-09-03T02:14:20 | 41,837,786 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 11,535 | java | package mx.unam.ciencias.edd;
import java.util.NoSuchElementException;
import java.lang.Math;
/**
* <p>Clase abstracta para árboles binarios genéricos.</p>
*
* <p>La clase proporciona las operaciones básicas para árboles
* binarios, pero deja la implementación de varios en manos de las
* clases concretas.</p>
*/
public abstract class ArbolBinario<T> implements Iterable<T> {
/**
* Clase interna protegida para vértices.
*/
protected class Vertice<T> implements VerticeArbolBinario<T> {
/** El elemento del vértice. */
public T elemento;
/** El padre del vértice. */
public Vertice<T> padre;
/** El izquierdo del vértice. */
public Vertice<T> izquierdo;
/** El derecho del vértice. */
public Vertice<T> derecho;
/**
* Constructor único que recibe un elemento.
* @param elemento el elemento del vértice.
*/
public Vertice(T elem) {
//Aquí va su código.
padre = izquierdo = derecho = null;
this.elemento = elem;
}
/**
* Regresa una representación en cadena del vértice.
* @return una representación en cadena del vértice.
*/
public String toString() {
// Aquí va su código.
return elemento.toString();
}
/**
* Nos dice si el vértice tiene un padre.
* @return <tt>true</tt> si el vértice tiene padre,
* <tt>false</tt> en otro caso.
*/
@Override public boolean hayPadre() {
// Aquí va su código.
// Aquí va su código.
boolean hayDichoElemento = false;
if (padre != null)
hayDichoElemento = true;
return hayDichoElemento;
}
/**
* Nos dice si el vértice tiene un izquierdo.
* @return <tt>true</tt> si el vértice tiene izquierdo,
* <tt>false</tt> en otro caso.
*/
@Override public boolean hayIzquierdo() {
// Aquí va su código.
// Aquí va su código.
boolean hayDichoElemento = false;
if (izquierdo!= null)
hayDichoElemento = true;
return hayDichoElemento;
}
/**
* Nos dice si el vértice tiene un derecho.
* @return <tt>true</tt> si el vértice tiene derecho,
* <tt>false</tt> en otro caso.
*/
@Override public boolean hayDerecho() {
// Aquí va su código.
boolean hayDichoElemento = false;
if (derecho != null)
hayDichoElemento = true;
return hayDichoElemento;
}
/**
* Regresa el padre del vértice.
* @return el padre del vértice.
* @throws NoSuchElementException si el vértice no tiene padre.
*/
@Override public VerticeArbolBinario<T> getPadre() {
// Aquí va su código.
if (hayPadre())
return padre;
else throw new NoSuchElementException("No hay padre");
}
/**
* Regresa el izquierdo del vértice.
* @return el izquierdo del vértice.
* @throws NoSuchElementException si el vértice no tiene izquierdo.
*/
@Override public VerticeArbolBinario<T> getIzquierdo() {
if (hayIzquierdo())
return izquierdo;
else throw new NoSuchElementException("No hay elemnto izquierdo");
// Aquí va su código.
}
/**
* Regresa el derecho del vértice.
* @return el derecho del vértice.
* @throws NoSuchElementException si el vértice no tiene derecho.
*/
@Override public VerticeArbolBinario<T> getDerecho() {
if (hayDerecho())
return derecho;
else throw new NoSuchElementException("No hay elemnto derecho");
// Aquí va su código.
}
/**
* Regresa el elemento al que apunta el vértice.
* @return el elemento al que apunta el vértice.
*/
@Override public T get() {
return elemento;
// Aquí va su código.
}
}
/** La raíz del árbol. */
protected Vertice<T> raiz;
/** El número de elementos */
protected int elementos;
/**
* Construye un árbol con cero elementos.
*/
public ArbolBinario() {
// Aquí va su código.
raiz = null;
elementos = 0;
}
/**
* Regresa la profundidad del árbol. La profundidad de un árbol
* es la longitud de la ruta más larga entre la raíz y una hoja.
* @return la profundidad del árbol.
*/
public int profundidad() {
return profundidad(raiz);
}
private int profundidad(Vertice<T> ver )
{
if (ver == null || (!ver.hayIzquierdo() && !ver.hayDerecho()))
return 0;
return (1 + Math.max(profundidad(ver.izquierdo), profundidad(ver.derecho)));
}
/**
* Regresa el número de elementos en el árbol. El número de
* elementos es el número de elementos que se han agregado al
* árbol.
* @return el número de elementos en el árbol.
*/
public int getElementos() {
return getElementos(raiz);
}
private int getElementos(Vertice<T> ver)
{
if (ver == null)
return 0;
else
return (1 + getElementos(ver.izquierdo) + getElementos(ver.derecho));
}
/**
* Agrega un elemento al árbol.
* @param elemento el elemento a agregar al árbol.
* @return el vértice agregado al árbol que contiene el
* elemento.
*/
public abstract VerticeArbolBinario<T> agrega(T elemento);
/**
* Elimina un elemento del árbol.
* @param elemento el elemento a eliminar.
*/
public abstract void elimina(T elemento);
/**
* Busca un elemento en el árbol. Si lo encuentra, regresa el
* vértice que lo contiene; si no, regresa <tt>null</tt>.
* @param elemento el elemento a buscar.
* @return un vértice que contiene el elemento buscado si lo
* encuentra; <tt>null</tt> en otro caso.
*/
public VerticeArbolBinario<T> busca(T elemento) {
// return null;
return busquedaDFS(raiz, elemento);
}
private VerticeArbolBinario<T> busquedaDFS(Vertice<T> v, T e)
{
VerticeArbolBinario<T> verticeEncontrado = null;
if (v != null)
if (v.elemento.equals(e))
verticeEncontrado = v;
else
{
verticeEncontrado = busquedaDFS(v.izquierdo, e);
if (verticeEncontrado == null)
verticeEncontrado = busquedaDFS(v.derecho, e);
}
return verticeEncontrado;
}
/**
* Regresa el vértice que contiene la raíz del árbol.
* @return el vértice que contiene la raíz del árbol.
* @throws NoSuchElementException si el árbol es vacío.
*/
public VerticeArbolBinario<T> raiz() {
return raiz;
// Aquí va su código.
}
/**
* Regresa una representación en cadena del árbol.
* @return una representación en cadena del árbol.
*/
@Override public String toString() {
/* Necesitamos la profundidad para saber cuántas ramas puede
haber. */
if (elementos == 0)
return "";
int p = profundidad() + 1;
/* true == dibuja rama, false == dibuja espacio. */
boolean[] rama = new boolean[p];
for (int i = 0; i < p; i++)
/* Al inicio, no dibujamos ninguna rama. */
rama[i] = false;
String s = aCadena(raiz, 0, rama);
return s.substring(0, s.length()-1);
}
/* Método auxiliar recursivo que hace todo el trabajo. */
private String aCadena(Vertice<T> vertice, int nivel, boolean[] rama) {
/* Primero que nada agregamos el vertice a la cadena. */
String s = vertice + "\n";
/* A partir de aquí, dibujamos rama en este nivel. */
rama[nivel] = true;
if (vertice.izquierdo != null && vertice.derecho != null) {
/* Si hay vertice izquierdo Y derecho, dibujamos ramas o
* espacios. */
s += espacios(nivel, rama);
/* Dibujamos el conector al hijo izquierdo. */
s += "├─›";
/* Recursivamente dibujamos el hijo izquierdo y sus
descendientes. */
s += aCadena(vertice.izquierdo, nivel+1, rama);
/* Dibujamos ramas o espacios. */
s += espacios(nivel, rama);
/* Dibujamos el conector al hijo derecho. */
s += "└─»";
/* Como ya dibujamos el último hijo, ya no hay rama en
este nivel. */
rama[nivel] = false;
/* Recursivamente dibujamos el hijo derecho y sus
descendientes. */
s += aCadena(vertice.derecho, nivel+1, rama);
} else if (vertice.izquierdo != null) {
/* Dibujamos ramas o espacios. */
s += espacios(nivel, rama);
/* Dibujamos el conector al hijo izquierdo. */
s += "└─›";
/* Como ya dibujamos el último hijo, ya no hay rama en
este nivel. */
rama[nivel] = false;
/* Recursivamente dibujamos el hijo izquierdo y sus
descendientes. */
s += aCadena(vertice.izquierdo, nivel+1, rama);
} else if (vertice.derecho != null) {
/* Dibujamos ramas o espacios. */
s += espacios(nivel, rama);
/* Dibujamos el conector al hijo derecho. */
s += "└─»";
/* Como ya dibujamos el último hijo, ya no hay rama en
este nivel. */
rama[nivel] = false;
/* Recursivamente dibujamos el hijo derecho y sus
descendientes. */
s += aCadena(vertice.derecho, nivel+1, rama);
}
return s;
}
/* Dibuja los espacios (incluidas las ramas, de ser necesarias)
que van antes de un vértice. */
private String espacios(int n, boolean[] rama) {
String s = "";
for (int i = 0; i < n; i++)
if (rama[i])
/* Rama: dibújala. */
s += "│ ";
else
/* No rama: dibuja espacio. */
s += " ";
return s;
}
/**
* Convierte el vértice (visto como instancia de {@link
* VerticeArbolBinario}) en vértice (visto como instancia de
* {@link Vertice}). Método auxililar para hacer esta audición
* en un único lugar.
* @param verticeArbolBinario el vértice de árbol binario que queremos
* como vértice.
* @return el vértice recibido visto como vértice.
* @throws ClassCastException si el vértice no es instancia de
* {@link Vertice}.
*/
protected Vertice<T> vertice(VerticeArbolBinario<T> verticeArbolBinario) {
/* Tenemos que suprimir advertencias. */
@SuppressWarnings("unchecked") Vertice<T> n = (Vertice<T>)verticeArbolBinario;
return n;
}
}
| [
"[email protected]"
] | |
8437baaae762c098c8c4b5a8650616c8f58669e1 | 092d184b84865e942ed0d00779faa1deca0252e8 | /app/src/main/java/com/example/chatapp/FriendsActivity.java | d34adce7356535f4a218a8441d89fc4bf94c7337 | [] | no_license | KaranParwani1116/ChatApp | 9f23c8eb43721e8135353b586f9a73be60a18216 | df0e05a6e817817798a572bb6b400652e7524073 | refs/heads/master | 2020-07-16T03:54:17.295125 | 2019-12-30T14:58:31 | 2019-12-30T14:58:31 | 205,713,007 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 3,791 | java | package com.example.chatapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.appcompat.widget.Toolbar;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.squareup.picasso.Picasso;
import de.hdodenhof.circleimageview.CircleImageView;
public class FriendsActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private DatabaseReference usersref;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_friends);
recyclerView=(RecyclerView)findViewById(R.id.find_friends_recyclerlist);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
usersref= FirebaseDatabase.getInstance().getReference().child("User");
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("Find Friends");
}
@Override
protected void onStart() {
super.onStart();
FirebaseRecyclerOptions<Contacts> options=
new FirebaseRecyclerOptions.Builder<Contacts>()
.setQuery(usersref,Contacts.class)
.build();
FirebaseRecyclerAdapter<Contacts,FindFriendViewHolder>adapter=new FirebaseRecyclerAdapter<Contacts, FindFriendViewHolder>(options) {
@Override
protected void onBindViewHolder(@NonNull FindFriendViewHolder findFriendViewHolder, final int i, @NonNull Contacts contacts) {
findFriendViewHolder.username.setText(contacts.getName());
findFriendViewHolder.userstatus.setText(contacts.getStatus());
Picasso.get().load(contacts.getImage()).placeholder(R.drawable.profile_image).fit().into(findFriendViewHolder.userprofilephoto);
findFriendViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String visit_user_id=getRef(i).getKey();
Intent intent=new Intent(FriendsActivity.this,ProfileActivity.class);
intent.putExtra("visit_user_id",visit_user_id);
startActivity(intent);
}
});
}
@NonNull
@Override
public FindFriendViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.users_view,parent,false);
FindFriendViewHolder viewHolder=new FindFriendViewHolder(view);
return viewHolder;
}
};
recyclerView.setAdapter(adapter);
adapter.startListening();
}
public static class FindFriendViewHolder extends RecyclerView.ViewHolder{
TextView username,userstatus;
CircleImageView userprofilephoto;
public FindFriendViewHolder(@NonNull View itemView) {
super(itemView);
username=(itemView).findViewById(R.id.user_name);
userstatus=(itemView).findViewById(R.id.user_status);
userprofilephoto=(itemView).findViewById(R.id.users_profile_image);
}
}
}
| [
"[email protected]"
] | |
f239c6b09b2eaeecb0535e6121e938810ee11e98 | d2288b31f82408f9251a4a851802916e1da0c7b1 | /src/main/java/net/lshift/lee/jaxb/pojo/Grandchild.java | 018a3fbbc32da04b6dda72b3b2b3271f78aa4be5 | [] | no_license | ljcoomber/jaxb-nested-adapters | e9c4656528486a1fd317565101e3b084ac35a259 | 0d97378392b7368813d42426e81dac0c5222173a | refs/heads/master | 2020-06-04T22:23:50.335953 | 2012-12-14T13:55:56 | 2012-12-14T13:55:56 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 432 | java | package net.lshift.lee.jaxb.pojo;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import net.lshift.lee.jaxb.xml.adapter.GrandchildAdapter;
@XmlJavaTypeAdapter(GrandchildAdapter.class)
public class Grandchild {
private final String grandchildName;
public Grandchild(String grandchildName) {
this.grandchildName = grandchildName;
}
public String getGrandchildName() {
return grandchildName;
}
}
| [
"[email protected]"
] | |
02f4ff768c241ee8a57cbc4cff9d5f7808254c9b | 5b790baa6d8d3d4fa6dcb5e0d74ee40987a6ab75 | /dao/src/main/java/com/eghm/dao/model/UserInviteLog.java | add01ebaab91605ed339f61532edf948c64eceff | [] | no_license | ergehenmeng/base-project | 7c4ece5da25f5ecb42e7b84fbb5ced8e88c462e2 | 508cca3c1e033b6c37a1303ccfe6775f6ab1e074 | refs/heads/master | 2022-07-12T12:53:33.032225 | 2021-07-24T11:04:48 | 2021-07-24T11:04:48 | 201,187,861 | 1 | 0 | null | 2022-06-17T02:21:24 | 2019-08-08T05:55:33 | Java | UTF-8 | Java | false | false | 779 | java | package com.eghm.dao.model;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* @author 二哥很猛
*/
@Data
public class UserInviteLog implements Serializable {
/**
* 主键<br>
* 表 : user_invite_log<br>
* 对应字段 : id<br>
*/
private Long id;
/**
* 用户id<br>
* 表 : user_invite_log<br>
* 对应字段 : user_id<br>
*/
private Long userId;
/**
* 被邀请人id<br>
* 表 : user_invite_log<br>
* 对应字段 : invite_user_id<br>
*/
private Long inviteUserId;
/**
* 添加时间<br>
* 表 : user_invite_log<br>
* 对应字段 : add_time<br>
*/
private Date addTime;
private static final long serialVersionUID = 1L;
} | [
"[email protected]"
] | |
779c4dc8cf802fa4a3ee5b9d8e07f5c9f6d423ef | 7cf147fa4269cc3fb5465ebf351a4d5bd24188e6 | /app/src/main/java/com/future_melody/net/request/AddFollowRequest.java | 7f5608154a20ae3a98516983bdd57569095fe165 | [] | no_license | gyingg/music | 1528dc08960e50963ee88dafd2899f15e49d122e | 547f819fd42d092d10837ed60c4142f34de49edc | refs/heads/master | 2020-04-11T21:33:36.696393 | 2018-12-17T10:06:41 | 2018-12-17T10:06:41 | 162,093,105 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 367 | java | package com.future_melody.net.request;
/**
* Created by Y on 2018/5/30.
*/
public class AddFollowRequest {
private String bg_userid;// 被关注人的id
private String g_userid;// 关注人的id
public AddFollowRequest(String bg_userid, String g_userid) {
this.bg_userid = bg_userid;
this.g_userid = g_userid;
}
}
| [
"gyingg"
] | gyingg |
d8e3f76e3128175e262e5cf22f3bbcea5bd5102c | 28234ced7a13cc6ebae3252eb51bed3af91349c3 | /src/test/java/de/essig/adventofcode/aoc2019/Day11.java | ee1f2b3830323343fbe7e3025d913ab531d63d27 | [] | no_license | essigt/aoc-2019 | 6b335aea51ebf2b17cdf4455f8567d71df3ccdff | 6501096cf0e297997fac68010a52f20ed2737948 | refs/heads/master | 2020-09-28T03:14:51.020400 | 2019-12-26T07:54:47 | 2019-12-26T07:54:47 | 226,674,858 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 19,041 | java | package de.essig.adventofcode.aoc2019;
import org.junit.jupiter.api.Test;
import java.util.*;
import java.util.stream.Collectors;
import static de.essig.adventofcode.aoc2019.Day11Data.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
public class Day11 {
private long relativeBase = 0;
private Map<Tile, Long> hull = new HashMap<>();
private enum Direction {LEFT, UP, RIGHT, DOWN};
@Test
void partOne() {
int posX = 0;
int posY = 0;
Direction currentDirection = Direction.UP;
boolean halt = false;
long instructionPointer = 0;
Map<Long, Long> programmAsInt = parseProgramm(PROGRAM);
while(!halt) {
ArrayList<Long> input = new ArrayList<>();
input.add(getColor(posX, posY));
Context context = runProgramm(programmAsInt, instructionPointer, input);
System.out.println("Output: " + context.getOutput());
if(context.isHalted()) {
break;
}
long color = context.getOutput().get(0);
long direction = context.getOutput().get(1);
// Paint
hull.put(new Tile(posX, posY), color);
// Turne
if(direction == 0) { //Turn left
if(currentDirection == Direction.UP) {
currentDirection = Direction.LEFT;
} else if(currentDirection == Direction.LEFT) {
currentDirection = Direction.DOWN;
} else if(currentDirection == Direction.DOWN) {
currentDirection = Direction.RIGHT;
} else {
currentDirection = Direction.UP;
}
} else { //Turn right
if(currentDirection == Direction.UP) {
currentDirection = Direction.RIGHT;
} else if(currentDirection == Direction.LEFT) {
currentDirection = Direction.UP;
} else if(currentDirection == Direction.DOWN) {
currentDirection = Direction.LEFT;
} else {
currentDirection = Direction.DOWN;
}
}
// Move
if(currentDirection == Direction.UP) {
posY++;
} else if(currentDirection == Direction.LEFT) {
posX--;
} else if(currentDirection == Direction.DOWN) {
posY--;
} else {
posX++;
}
halt = context.isHalted();
programmAsInt = context.getProgrammAsIntEnd();
instructionPointer = context.getInstructionPointer();
//System.out.println("Painted at leased once: " + hull.size());
}
System.out.println("Painted at leased once: " + hull.size());
assertThat(hull.size(), is(1985));
paintHull();
}
@Test
void partTwo() {
int posX = 0;
int posY = 0;
Direction currentDirection = Direction.UP;
boolean halt = false;
long instructionPointer = 0;
Map<Long, Long> programmAsInt = parseProgramm(PROGRAM);
hull.put(new Tile(posX,posY), 1L);
while(!halt) {
ArrayList<Long> input = new ArrayList<>();
input.add(getColor(posX, posY));
Context context = runProgramm(programmAsInt, instructionPointer, input);
if(context.isHalted()) {
System.out.println("Output: " + context.getOutput());
break;
}
if(context.getOutput().size() < 2) {
System.out.println("Output: " + context.getOutput());
System.out.println("Unexpected No Output");
break;
}
long color = context.getOutput().get(0);
long direction = context.getOutput().get(1);
// Paint
hull.remove(new Tile(posX,posY));
hull.put(new Tile(posX, posY), color);
// Turn
if(direction == 0) { //Turn left
if(currentDirection == Direction.UP) {
currentDirection = Direction.LEFT;
} else if(currentDirection == Direction.LEFT) {
currentDirection = Direction.DOWN;
} else if(currentDirection == Direction.DOWN) {
currentDirection = Direction.RIGHT;
} else {
currentDirection = Direction.UP;
}
} else { //Turn right
if(currentDirection == Direction.UP) {
currentDirection = Direction.RIGHT;
} else if(currentDirection == Direction.LEFT) {
currentDirection = Direction.UP;
} else if(currentDirection == Direction.DOWN) {
currentDirection = Direction.LEFT;
} else {
currentDirection = Direction.DOWN;
}
}
// Move
if(currentDirection == Direction.UP) {
posY++;
} else if(currentDirection == Direction.LEFT) {
posX--;
} else if(currentDirection == Direction.DOWN) {
posY--;
} else {
posX++;
}
halt = context.isHalted();
programmAsInt = context.getProgrammAsIntEnd();
instructionPointer = context.getInstructionPointer();
}
paintHull(); // Answer = BLCZCJLZ
}
private void paintHull() {
int xMin = hull.keySet().stream().mapToInt(Tile::getX).min().orElse(0);
int xMax = hull.keySet().stream().mapToInt(Tile::getX).max().orElse(0);
int yMin = hull.keySet().stream().mapToInt(Tile::getY).min().orElse(0);
int yMax = hull.keySet().stream().mapToInt(Tile::getY).max().orElse(0);
for(int y = yMax; y >= yMin; y--) {
for(int x = xMin; x <= xMax; x++) {
System.out.print(getColor(x,y) == 1 ? "X" : " ");
}
System.out.println();
}
}
private Long getColor(int x, int y) {
return hull.getOrDefault(new Tile(x,y), 0L);
}
private Context runProgramm(Map<Long, Long> programmAsInt, long instructionPointer, List<Long> inputs) {
Context context = new Context(programmAsInt, inputs);
boolean stop = false;
while (!stop) {
int instruction = getOpCode(programmAsInt.get(instructionPointer));
if (instruction == 99) {
context.setHalted(true);
stop = true;
} else if (instruction == 1) { // ADD
printCommand(programmAsInt, instructionPointer, 4);
long value1 = getParamAccordingToMode(programmAsInt, instructionPointer, 0);
long value2 = getParamAccordingToMode(programmAsInt, instructionPointer, 1);
long destination = getJumpGoalAccordingToMode(programmAsInt, instructionPointer, 2);
long sum = value1 + value2;
programmAsInt.put(destination, sum);
instructionPointer += 4;
} else if (instruction == 2) { // MUL
printCommand(programmAsInt, instructionPointer, 4);
long value1 = getParamAccordingToMode(programmAsInt, instructionPointer, 0);
long value2 = getParamAccordingToMode(programmAsInt, instructionPointer, 1);
long destination = getJumpGoalAccordingToMode(programmAsInt, instructionPointer, 2);
long sum = value1 * value2;
programmAsInt.put(destination, sum);
instructionPointer += 4;
} else if (instruction == 3) { // INPUT
printCommand(programmAsInt, instructionPointer, 2);
long destination = getJumpGoalAccordingToMode(programmAsInt, instructionPointer, 0);
long input = inputs.remove(0);
//System.out.println("Input Value " + input + " at " + destination);
programmAsInt.put(destination, input);
instructionPointer += 2;
} else if (instruction == 4) { // OUTPUT
printCommand(programmAsInt, instructionPointer, 2);
long output = getParamAccordingToMode(programmAsInt, instructionPointer, 0);
context.getOutput().add(output);
// Finish when two outputs are collected
if(context.getOutput().size() == 2) {
stop=true;
}
instructionPointer += 2;
} else if (instruction == 5) { // jump-if-true
printCommand(programmAsInt, instructionPointer, 3);
long value1 = getParamAccordingToMode(programmAsInt, instructionPointer, 0);
long jumpGoal = getParamAccordingToMode(programmAsInt, instructionPointer, 1);
if (value1 != 0) {
instructionPointer = jumpGoal;
} else {
instructionPointer += 3;
}
} else if (instruction == 6) { // jump-if-false
printCommand(programmAsInt, instructionPointer, 3);
long value1 = getParamAccordingToMode(programmAsInt, instructionPointer, 0);
long jumpGoal = getParamAccordingToMode(programmAsInt, instructionPointer, 1);
if (value1 == 0) {
instructionPointer = jumpGoal;
} else {
instructionPointer += 3;
}
} else if (instruction == 7) { // less-then
printCommand(programmAsInt, instructionPointer, 4);
long value1 = getParamAccordingToMode(programmAsInt, instructionPointer, 0);
long value2 = getParamAccordingToMode(programmAsInt, instructionPointer, 1);
long resultGoal = getJumpGoalAccordingToMode(programmAsInt, instructionPointer, 2);
if (value1 < value2) {
programmAsInt.put(resultGoal, 1L);
} else {
programmAsInt.put(resultGoal, 0L);
}
instructionPointer += 4;
} else if (instruction == 8) { // equals
printCommand(programmAsInt, instructionPointer, 4);
long value1 = getParamAccordingToMode(programmAsInt, instructionPointer, 0);
long value2 = getParamAccordingToMode(programmAsInt, instructionPointer, 1);
long resultGoal = getJumpGoalAccordingToMode(programmAsInt, instructionPointer, 2);
if (value1 == value2) {
programmAsInt.put(resultGoal, 1L);
} else {
programmAsInt.put(resultGoal, 0L);
}
instructionPointer += 4;
} else if (instruction == 9) { // set relative base
printCommand(programmAsInt, instructionPointer, 2);
relativeBase += getParamAccordingToMode(programmAsInt, instructionPointer, 0);
//System.out.println("Relativ Base=" + relativeBase);
instructionPointer += 2;
} else {
System.err.println("FATAL: Unknown Instruction " + instruction + "@" + instructionPointer);
break;
}
}
context.setProgrammAsIntEnd(programmAsInt);
context.setInstructionPointer(instructionPointer);
return context;
}
private void printCommand(Map<Long, Long> programmAsInt, long instructionPointer, int length) {
for(int i = 0; i< length; i++) {
System.out.print(programmAsInt.getOrDefault(instructionPointer+i, 0L) + ",");
}
System.out.println();
}
long getJumpGoalAccordingToMode(Map<Long, Long> programmAsInt, long instructionPointer, int param) {
if (param == 0) {
if (getFirstParamMode(programmAsInt.get(instructionPointer)) == 2) { // Relative MODE
long relativPart = programmAsInt.getOrDefault(instructionPointer + 1, 0L);
return relativeBase + relativPart;
//throw new IllegalArgumentException("Relative mode not implemented");
} else {
return programmAsInt.get(instructionPointer + 1 );
}
} else if (param == 1) {
if (getSecondParamMode(programmAsInt.get(instructionPointer)) == 2) { // Relative MODE
long relativPart = programmAsInt.getOrDefault(instructionPointer + 2, 0L);
return relativeBase + relativPart;
} else {
return programmAsInt.get(instructionPointer + 2 );
}
} else if (param == 2) {
if (getThirdParamMode(programmAsInt.get(instructionPointer)) == 2) { // Relative MODE
long relativPart = programmAsInt.getOrDefault(instructionPointer + 3, 0L);
return relativeBase + relativPart;
} else {
return programmAsInt.get(instructionPointer + 3 );
}
} else {
throw new IllegalArgumentException("Not implemented");
}
}
long getParamAccordingToMode(Map<Long, Long> programmAsInt, long instructionPointer, int param) {
if (param == 0) {
if (getFirstParamMode(programmAsInt.get(instructionPointer)) == 0) { // POSITION MODE
return programmAsInt.getOrDefault(programmAsInt.get(instructionPointer + 1), 0L);
} else if (getFirstParamMode(programmAsInt.get(instructionPointer)) == 2) { // Relative MODE
long relativPart = programmAsInt.getOrDefault(instructionPointer + 1,0L);
return programmAsInt.getOrDefault( relativeBase + relativPart, 0L);
} else {
return programmAsInt.getOrDefault(instructionPointer + 1, 0L);
}
} else if (param == 1) {
if (getSecondParamMode(programmAsInt.get(instructionPointer)) == 0) { // POSITION MODE
return programmAsInt.getOrDefault(programmAsInt.get(instructionPointer + 2),0L );
} else if (getSecondParamMode(programmAsInt.get(instructionPointer)) == 2) { // Relative MODE
long relativPart = programmAsInt.getOrDefault(instructionPointer + 2, 0L);
return programmAsInt.getOrDefault( relativeBase + relativPart, 0L);
} else {
return programmAsInt.getOrDefault(instructionPointer + 2, 0L);
}
} else if (param == 2) {
if (getThirdParamMode(programmAsInt.get(instructionPointer)) == 0) { // POSITION MODE
return programmAsInt.getOrDefault(programmAsInt.get(instructionPointer + 3),0L );
} else if (getThirdParamMode(programmAsInt.get(instructionPointer)) == 2) { // Relative MODE
long relativPart = programmAsInt.getOrDefault(instructionPointer + 3, 0L);
return programmAsInt.getOrDefault( relativeBase + relativPart, 0L);
} else {
return programmAsInt.getOrDefault(instructionPointer + 3, 0L);
}
} else {
throw new IllegalArgumentException("Not implemented");
}
}
@Test
void testOps() {
assertThat(getOpCode(10002), is(2));
assertThat(getFirstParamMode(11022), is(0));
assertThat(getFirstParamMode(20122), is(1));
assertThat(getSecondParamMode(21022), is(1));
assertThat(getSecondParamMode(10122), is(0));
assertThat(getThirdParamMode(11022), is(1));
assertThat(getThirdParamMode(1122), is(0));
assertThat(getFirstParamMode(21202), is(2));
assertThat(getSecondParamMode(2022), is(2));
assertThat(getThirdParamMode(21122), is(2));
}
int getOpCode(long instruction) {
return (int) instruction % 100;
}
int getFirstParamMode(long instruction) {
return (int) (instruction / 100L) % 10;
}
int getSecondParamMode(long instruction) {
return (int) (instruction / 1000L) % 10;
}
int getThirdParamMode(long instruction) {
return (int)(instruction / 10000L) % 10;
}
private Map<Long, Long> parseProgramm(String input) {
Map<Long, Long> programm = new HashMap<>();
String[] split = input.split(",");
long pos = 0;
for (String instruction : split) {
programm.put(pos, Long.valueOf(instruction));
pos++;
}
return programm;
}
private String prettyPrint(Context context) {
return context.getProgrammAsIntEnd().values().stream().map(String::valueOf).collect(Collectors.joining(","));
}
private class Context {
Map<Long, Long> programmAsIntOriginal;
Map<Long, Long> programmAsIntEnd;
List<Long> input;
List<Long> output;
private boolean halted;
private long instructionPointer;
public Context(Map<Long, Long> programmAsIntOriginal, List<Long> input) {
this.programmAsIntOriginal = new HashMap<>(programmAsIntOriginal);
this.input = input;
this.output = new ArrayList<>();
}
public boolean isHalted() {
return halted;
}
public void setHalted(boolean halted) {
this.halted = halted;
}
public long getInstructionPointer() {
return instructionPointer;
}
public void setInstructionPointer(long instructionPointer) {
this.instructionPointer = instructionPointer;
}
public Map<Long, Long> getProgrammAsIntEnd() {
return programmAsIntEnd;
}
public void setProgrammAsIntEnd(Map<Long, Long> programmAsIntEnd) {
this.programmAsIntEnd = new HashMap<>(programmAsIntEnd);
}
public Map<Long, Long> getProgrammAsIntOriginal() {
return programmAsIntOriginal;
}
public List<Long> getInputs() {
return input;
}
public List<Long> getOutput() {
return output;
}
}
private static class Tile{
private int x;
private int y;
public Tile(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Tile tile = (Tile) o;
return x == tile.x &&
y == tile.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
}
}
| [
"[email protected]"
] | |
28527d3a24fb9cf9f6d524e0bec0508e31464638 | f14d53fc595fb264ff99de428c6db3e25609f677 | /src/main/java/com/tidi/restaurant/domain/Table.java | 6e751ec1adf0a2419c07803c209b1c59d4e306bf | [] | no_license | daniel-1321/restaurant | efbf0c7b10f8d1b7e8a5777d05fc71ff3a0f572d | 84144caabebf4feb41f4a6fe066f85ba7911917e | refs/heads/master | 2021-07-21T03:07:58.118068 | 2019-11-04T11:23:26 | 2019-11-04T11:23:26 | 219,399,048 | 0 | 0 | null | 2020-10-13T17:11:26 | 2019-11-04T02:15:20 | Java | UTF-8 | Java | false | false | 963 | java | package com.tidi.restaurant.domain;
/**
* @author HO_TRONG_DAI
* @date Oct 30, 2019
* @tag
*/
public class Table {
private int table_id;
private String table_name;
private String table_type;
public Table(int table_id, String table_name, String table_type) {
super();
this.table_id = table_id;
this.table_name = table_name;
this.table_type = table_type;
}
public Table() {
super();
}
public int getTable_id() {
return table_id;
}
public void setTable_id(int table_id) {
this.table_id = table_id;
}
public String getTable_name() {
return table_name;
}
public void setTable_name(String table_name) {
this.table_name = table_name;
}
public String getTable_type() {
return table_type;
}
public void setTable_type(String table_type) {
this.table_type = table_type;
}
@Override
public String toString() {
return "Table [table_id=" + table_id + ", table_name=" + table_name + ", table_type=" + table_type + "]";
}
}
| [
"[email protected]"
] | |
97c2a5ddf0bc75c36db85d3c75179fabdf373587 | 6385b72cf9d68587c63677d46fa431bc33f2f44f | /src/main/java/com/ph/lease/converter/DateConverter.java | 887fc5f4f5915674b6f67c9662f419f029029a42 | [] | no_license | wowpH/Lease | eef4ce2acb17d1c15c23d58365a90ce1dc9a9911 | a3054dde909c8ce54f4ae6e9157599010ebf73cc | refs/heads/master | 2023-03-08T20:14:47.651725 | 2022-08-30T17:20:21 | 2022-08-30T17:20:21 | 261,090,160 | 24 | 8 | null | 2023-02-22T08:28:52 | 2020-05-04T05:41:50 | Java | UTF-8 | Java | false | false | 614 | java | package com.ph.lease.converter;
import org.springframework.core.convert.converter.Converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author PengHao
*/
public class DateConverter implements Converter<String, Date> {
private static final SimpleDateFormat DEFAULT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Override
public Date convert(String s) {
Date date = null;
try {
date = DEFAULT.parse(s);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
}
| [
"[email protected]"
] | |
0bdd7c7930bab07890f9df815bd9dcf371d61037 | 0f0e5747898e74e20274ef5fd5b30a981b18b96c | /JPAOneToOne-Bi/src/com/lti/model/Student.java | 946ea0ec7ce36939cf9c4b2a8d1283d7d1bc1f5e | [] | no_license | anerishah1997/JPA_Day3 | ac6b6b4c7a82dfc686670a5d2f1197281d731a00 | 61179e0ab6420b62b92b509e9c8fddd8bba0b1d3 | refs/heads/master | 2020-09-06T15:29:50.077800 | 2019-11-08T12:51:34 | 2019-11-08T12:51:34 | 220,465,775 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,644 | java | package com.lti.model;
import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Transient;
@Entity
@Table(name="student")
@SequenceGenerator(name="seq", sequenceName="seq_student", initialValue=1, allocationSize=1)
public class Student implements Serializable{
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE,generator="seq")
private int studentId;
private int rollNumber;
private String studentName;
private double avgScore;
@Transient
private String dob;
@OneToOne(cascade=CascadeType.ALL,fetch=FetchType.EAGER) // Bidirectional reln (Owner side) as Student's reference is created in Address.
// cascadeType indicates when owner enitty is persisted then automatically child entity is persisted
//when type is ALL,which do all things(persist,merge,find,remove) in child auto.
@JoinColumn(name="addressId")
private Address address;
public Student(int rollNumber, String studentName, double avgScore) {
super();
this.rollNumber = rollNumber;
this.studentName = studentName;
this.avgScore = avgScore;
}
public Student() {
super();
}
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public int getRollNumber() {
return rollNumber;
}
public void setRollNumber(int rollNumber) {
this.rollNumber = rollNumber;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public double getAvgScore() {
return avgScore;
}
public void setAvgScore(double avgScore) {
this.avgScore = avgScore;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public Address getAddress() {
return address;
}
/*@Override
public String toString() {
return "Student [studentId=" + studentId + ", rollNumber=" + rollNumber + ", studentName=" + studentName
+ ", avgScore=" + avgScore + ", dob=" + dob + ", address=" + address + "]";
}*/
public void setAddress(Address address) {
this.address = address;
}
@Override
public String toString() {
return "Student [studentId=" + studentId + ", rollNumber=" + rollNumber + ", studentName=" + studentName
+ ", avgScore=" + avgScore + ", dob=" + dob + "]";
}
}
| [
"[email protected]"
] | |
b7dec27881bb66741afe98b43bf1a966cfb7dfcf | 5f64ef2e3d2a99f0ea2a3eeed116d9d89f8bc6ec | /java/android/GantiTab/src/aini/nur/TabSatu.java | 6f8d5243d93a58e5ef85c5d22f4375e68141dba9 | [] | no_license | nurainir/nuraini | 3f77a22b6161065e34e3d16d9d0dfa5c21caa6e1 | 59704616c4a289da0a3ef39cad26376cfbb29c65 | refs/heads/master | 2021-01-10T19:13:28.999029 | 2011-04-13T13:40:36 | 2011-04-13T13:40:36 | 32,705,621 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,269 | java | package aini.nur;
/**
* TabSatu menampilkan rating di android
* @author : Nur Aini Rakhmawati
* @since : March 18, 2011
* @license : GPL
*/
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RatingBar;
import android.widget.Toast;
import android.widget.RatingBar.OnRatingBarChangeListener;
public class TabSatu extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab1);
final RatingBar rb = (RatingBar)findViewById(R.id.RatingBar01);
rb.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
Toast.makeText(TabSatu.this, "Rating Sekarang: " + rating, Toast.LENGTH_SHORT).show();
}
});
Button button = (Button) findViewById(R.id.Button01);
button.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
}
});
}
}
| [
"[email protected]@f4ffccde-388a-575a-2cd9-47a10c9617cc"
] | [email protected]@f4ffccde-388a-575a-2cd9-47a10c9617cc |
a2c0bbaa0a35cf3ad59e56c046fac6fef895d3f4 | 4dc51eda244cba50be874a288245b5d44ca5f161 | /web/src/test/java/rabbitmq/Recv.java | db626429d5d7f480cfb8f54fc19dffee508e3124 | [] | no_license | easonlian/blind | da50ceb3bffb0a350d502d096404a6f5376548e9 | 5b1c699ebf902b0cf540d980b0109d5cce0b51ac | refs/heads/master | 2021-01-20T20:45:09.120043 | 2016-10-31T09:36:16 | 2016-10-31T09:36:16 | 65,655,356 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,345 | java | /*
* Copyright (c) 2016 Qunar.com. All Rights Reserved.
*/
package rabbitmq;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import java.io.IOException;
public class Recv {
private final static String QUEUE_NAME = "hello";
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
Consumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
throws IOException {
String message = new String(body, "UTF-8");
System.out.println(" [x] Received '" + message + "'");
}
};
channel.basicConsume(QUEUE_NAME, true, consumer);
}
} | [
"[email protected]"
] |