hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
---|---|---|---|---|---|
a394f817416332d0f96fa410e989f5a39c128012 | 642 | /*
* Created on Oct 25, 2004
*
*/
package de.renew.gui.logging;
import org.apache.log4j.Appender;
import org.apache.log4j.Logger;
/**
* @author Sven Offermann
*
*/
public class TreeNodeAppenderWrapper {
private Logger logger;
private Appender appender;
public TreeNodeAppenderWrapper(Logger logger, Appender appender) {
this.logger = logger;
this.appender = appender;
}
public Logger getLogger() {
return this.logger;
}
public Appender getAppender() {
return this.appender;
}
public String toString() {
return this.appender.getClass().getName();
}
} | 18.342857 | 70 | 0.649533 |
aa0b228944024371d88529697ae7346c241040df | 23,569 | package com.example.demo.controller;
import com.example.demo.bean.*;
import com.example.demo.entity.*;
import com.example.demo.rule.*;
import com.example.demo.service.*;
import com.example.demo.util.DateUtil;
import com.example.demo.util.FileUtil;
import org.apache.ibatis.binding.BindingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpSession;
import javax.xml.crypto.Data;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Controller
@RequestMapping(value = "/index-manage-parking")
public class ParkingManageController {
ParkingRecordService parkingRecordService;
CarService carService;
OrderService orderService;
StaffTaskService staffTaskService;
StaffDutyService staffDutyService;
StaffService staffService;
ParkingLotSettingService parkingLotSettingService;
ParkingSpaceService parkingSpaceService;
RuleCommonBasicService ruleCommonBasicService;
RulePersonService rulePersonService;
RuleCustomService ruleCustomService;
RuleCustomInterimService ruleCustomInterimService;
RuleFixedParkingService ruleFixedParkingService;
//计费
FixedRule fixedRule;
Rule rule;
PersonRule personRule;
CustomRule customRule;
BasicCharge basicCharge;
InterimCharge interimCharge;
List<InterimRule> interimRuleList;
@RequestMapping(value = "/addParkingRecordEnter", method = RequestMethod.POST)
public String addParkingRecordEnter(Model model, @RequestBody Map<String, String> map, HttpSession session) {
String car_type = map.get("car_type");
String car_type_model = map.get("car_type_model");
String car_user = map.get("car_user");
String car_plate_num_head = map.get("car_plate_num_head");
String car_plate_num = map.get("car_plate_num");
String car_color = map.get("car_color");
System.out.println(map.toString());
String car_plate_number = car_plate_num_head + car_plate_num;
carService.addRowByInfo(car_type, car_plate_number, car_color, car_type_model, processCarUser(car_user));
parkingRecordService.addRowByInfo(car_plate_number, new Date());
String starting_date = staffDutyService.selectStartingTime();
model.addAttribute("EnterResult", parkingRecordService.selectEnter(starting_date, 10, 0));
return "index-manage-parking::EnterResult";
}
public int processCarUser(String car_user) {
if (car_user.equals("临时车主")) {
return 0;
}
return Integer.parseInt(car_user);
}
@RequestMapping(value = "/addParkingOrderOuter", method = RequestMethod.POST)
public String addParkingOrderOuter(Model model, @RequestBody Map<String, String> map, HttpSession session) {
String order_car_number = map.get("order_car_number");
String order_pay_type = map.get("order_pay_type");
String order_payer = map.get("order_payer");
String order_receiver = map.get("order_receiver");
String money = map.get("money");
System.out.println(map.toString());
TbOrder tbOrder = new TbOrder();
tbOrder.setOrderAmount(Float.parseFloat(money));
tbOrder.setOrderPayer(order_payer);
tbOrder.setOrderReceiver(order_receiver);
tbOrder.setOrderState("已完成");
tbOrder.setOrderPayType(order_pay_type);
tbOrder.setOrderPurchaseType("停车场支付");
orderService.addRowByInfo(tbOrder);
String starting_date = staffDutyService.selectStartingTime();
System.out.println(parkingRecordService.updateByOuter(order_car_number, starting_date, new Date(), tbOrder.getOrderId()));
model.addAttribute("OuterResult", parkingRecordService.selectOuter(starting_date, 10, 0));
return "index-manage-parking::OuterResult";
}
@RequestMapping(value = "/updateDutyOffWork", method = RequestMethod.GET)
public String updateDutyOffWork(Model model, HttpSession session) {
String startTime = (String) session.getAttribute("startTime");
model.addAttribute("ending_time", DateUtil.getNowDate());
model.addAttribute("enterCount", parkingRecordService.selectCountEnter(startTime));
model.addAttribute("outerCount", parkingRecordService.selectCountOuter(startTime));
model.addAttribute("orderCount", orderService.selectRowCount(startTime));
try {
model.addAttribute("TotalCount", orderService.selectTotalCount(startTime));
} catch (BindingException e) {
model.addAttribute("TotalCount", 0);
}
model.addAttribute("OffWorkResult", parkingRecordService.selectDutyAll(startTime, 10, 0));
return "index-manage-parking::OffWorkResult";
}
@RequestMapping(value = "/commitDutyOffWork", method = RequestMethod.POST)
public String commitDutyOffWork(Model model, @RequestBody Map<String, String> map, HttpSession session) {
String startTime = (String) session.getAttribute("startTime");
String endTime = DateUtil.getNowDate();
staffDutyService.updateRowByInf0(endTime);
TbStaffDuty tbStaffDuty = staffDutyService.selectLastRow();
String enterCount = String.valueOf(parkingRecordService.selectCountEnter(startTime));
String outerCount = String.valueOf(parkingRecordService.selectCountOuter(startTime));
String orderCount;
String TotalCount;
try {
orderCount = String.valueOf(orderService.selectRowCount(startTime));
TotalCount = String.valueOf(orderService.selectTotalCount(startTime));
} catch (Exception e) {
orderCount = "0";
TotalCount = "0";
}
Integer staffId = (Integer) session.getAttribute("staffId");//职员编号
String staffName = (String) session.getAttribute("staffName");//职员姓名
session.removeAttribute("nowStaff");
session.removeAttribute("startTime");
FileUtil.exportExcel(parkingRecordService.selectDutyAll(startTime, 10, 0), enterCount, outerCount, orderCount, TotalCount, new TbStaffDuty(), staffId, staffName);
return "index-manage-parking";
}
@RequestMapping(value = "/addDutyRow", method = RequestMethod.GET)
public String addDutyRow(Model model, HttpSession session) {
String date = DateUtil.getNowDate();
//获取当前操作员信息
Integer staffId = (Integer) session.getAttribute("staffId");
Integer staff_task_id = staffTaskService.selectTaskToday(staffId, date);
if (staff_task_id != null) {
staffDutyService.addRowByInfo(staffId, date, staff_task_id);
model.addAttribute("info", "1");
session.setAttribute("startTime", staffDutyService.selectStartingTime());
session.setAttribute("staffId", staffId);
session.setAttribute("nowStaff", staffService.selectNameById(staffId));
} else {
model.addAttribute("info", "0");
}
return "index-manage-parking";
}
@RequestMapping(value = "/selectRecordAndOrderByPage", method = RequestMethod.POST)
public String selectRecordAndOrderByPage(Model model, @RequestBody Map<String, String> map) {
System.out.println(map.toString());
String starting_date = staffDutyService.selectStartingTime();
String search_car_plate_type = map.get("search_car_plate_type");
String search_car_type = map.get("search_car_type");
String search_pay_type = map.get("search_pay_type");
String search_Keyword_title = map.get("search_Keyword_title");
String search_Keyword = map.get("search_Keyword");
int page = Integer.parseInt(map.get("page"));
int pageNum = Integer.parseInt(map.get("search_number"));
model.addAttribute("RecordAndOrderResult", parkingRecordService.selectAllByInfo(starting_date, search_car_plate_type, search_car_type, search_pay_type, search_Keyword_title, search_Keyword, pageNum, (page - 1) * pageNum));
List<TbParkingRecord> list = parkingRecordService.selectAllByInfo(starting_date, search_car_plate_type, search_car_type, search_pay_type, search_Keyword_title, search_Keyword, 0, 0);
model.addAttribute("NowPage", page );
model.addAttribute("TotalPage", (list.size() / pageNum)+1);
return "index-manage-parking::RecordAndOrderResult";
}
@Async
@RequestMapping(value = "/countCharge", method = RequestMethod.POST)
public String countCharge(Model model, @RequestBody Map<String, String> map, HttpSession session) {
String order_car_number = map.get("order_car_number");
Date ending_time = new Date();
TbParkingRecord tbParkingRecord = parkingRecordService.selectRowByCarNum(order_car_number).get(0);
Date starting_time = tbParkingRecord.getEnterTime();
TbParkingLot tbParkingLot = parkingLotSettingService.selectRowById(2).get(0);
String car_type = tbParkingRecord.getTbCar().getCarTypeModel();
String rule = processRuleType(tbParkingLot.getRuleSetting().substring(0, 3));
String interimRule = tbParkingLot.getRuleSetting().substring(3, 4);
processCharge(rule, car_type, tbParkingLot.getParkingLotLevel());
if (interimRule.equals("1")) {
processInterimRule(starting_time, ending_time, car_type);
}
processFixRule(ending_time, order_car_number, car_type);
processRule(starting_time, ending_time, interimRule);//加载规则
switch (rule) {
case "基本规则":
model.addAttribute("Amount", this.rule.total);
break;
case "自定义规则":
model.addAttribute("Amount", this.customRule.total);
break;
case "私人规则":
model.addAttribute("Amount", this.personRule.total);
break;
}
return "index-manage-parking::chargeResult";
}
public void processRule(Date starting_time, Date ending_time, String interim_rule) {
if (interim_rule.equals("1")) {
switch (basicCharge.getNow_rule()) {
case "私人规则":
personRule = new PersonRule(starting_time, ending_time, (PersonCharge) basicCharge, interimRuleList, fixedRule);
break;
case "基本规则":
rule = new Rule(starting_time, ending_time, (CommonCharge) basicCharge, interimRuleList, fixedRule);
break;
case "自定义规则":
customRule = new CustomRule(starting_time, ending_time, (CustomCharge) basicCharge, interimRuleList, fixedRule);
break;
}
} else {
switch (basicCharge.getNow_rule()) {
case "私人规则":
personRule = new PersonRule(starting_time, ending_time, (PersonCharge) basicCharge, fixedRule);
break;
case "基本规则":
rule = new Rule(starting_time, ending_time, (CommonCharge) basicCharge, fixedRule);
break;
case "自定义规则":
customRule = new CustomRule(starting_time, ending_time, (CustomCharge) basicCharge, fixedRule);
break;
}
}
}
public String processRuleType(String rule) {
switch (rule) {
case "100":
return "基本规则";
case "010":
return "自定义规则";
case "001":
return "私人规则";
}
return "";
}
@Async
public void processInterimRule(Date starting_time, Date ending_time, String car_type) {
this.interimRuleList = new ArrayList<>();
while (starting_time.getTime() < ending_time.getTime()) {
String d = DateUtil.getNowDate(starting_time);
if (searchInterimList(starting_time) == -1) {
if (ruleCustomInterimService.selectRuleExist(d) != 0) {
if (ruleCustomInterimService.selectAllExist(d) == 1) {
this.interimCharge = new InterimCharge(car_type, "临时规则", "全天制度",
DateUtil.process(d),
ruleCustomInterimService.selectMoneyByInfo(d, "全天", "小车") == null ? 0
: ruleCustomInterimService.selectMoneyByInfo(d, "全天", "小车"));
} else {
this.interimCharge = new InterimCharge(car_type, "临时规则",
"小时制度", DateUtil.process(d),
ruleCustomInterimService.selectMoneyByPeakFirst(d, "小车"),
ruleCustomInterimService.selectMoneyByPeak(d, "小车"),
ruleCustomInterimService.selectMoneyByPlain(d, "小车"),
ruleCustomInterimService.selectMoneyByAll(d, "小车")
);
}
addInterimRuleList(DateUtil.getNowDate(d));
}
}
starting_time = DateUtil.addDay(starting_time, ending_time);
}
}
@Async
public int searchInterimList(Date date) {
for (int i = 0; i < interimRuleList.size(); i++) {
if (interimRuleList.get(i).getUse_date().getTime() == date.getTime()) {
return i;
}
}
return -1;
}
@Async
public void addInterimRuleList(Date date) {
if (searchInterimList(date) == -1) {
this.interimRuleList.add(new InterimRule(this.interimCharge, date));
}
}
@Async
public void processFixRule(Date ending_time, String plate_type, String car_type) {
try {
TbParkingSpace tbParkingSpace = parkingSpaceService.selectExpireDateByCar(plate_type).get(0);
Date date = tbParkingSpace.getExpireDate();
fixedRule = new FixedRule(date, new BasicCharge(car_type, "固定车位规则"));
} catch (Exception e) {
fixedRule = null;
}
}
public void processCharge(String rule, String car_type, String zone_type) {
switch (rule) {
case "基本规则":
processCommonCharge(car_type, zone_type);
break;
case "自定义规则":
processCustomCharge(car_type);
break;
case "私人规则":
processPersonCharge(car_type);
break;
}
}
public void processCommonCharge(String car_type, String zone_type) {
if (car_type.equals("小车")) {
switch (zone_type) {
case "一类地区":
basicCharge = new CommonCharge("小车", "基本规则", ruleCommonBasicService.selectRowById("1").getMoney(),
ruleCommonBasicService.selectRowById("2").getMoney(), ruleCommonBasicService.selectRowById("3").getMoney(),
ruleCommonBasicService.selectRowById("4").getMoney(), ruleCommonBasicService.selectRowById("5").getMoney());
break;
case "二类地区":
basicCharge = new CommonCharge("小车", "基本规则", ruleCommonBasicService.selectRowById("6").getMoney(),
ruleCommonBasicService.selectRowById("7").getMoney(), ruleCommonBasicService.selectRowById("8").getMoney(),
ruleCommonBasicService.selectRowById("9").getMoney(), ruleCommonBasicService.selectRowById("10").getMoney());
break;
case "三类地区":
basicCharge = new CommonCharge("小车", "基本规则", ruleCommonBasicService.selectRowById("11").getMoney());
break;
}
}
if (car_type.equals("大型车")) {
switch (zone_type) {
case "一类地区":
basicCharge = new CommonCharge("大型车", "基本规则", ruleCommonBasicService.selectRowById("12").getMoney(),
ruleCommonBasicService.selectRowById("13").getMoney(), ruleCommonBasicService.selectRowById("14").getMoney(),
ruleCommonBasicService.selectRowById("15").getMoney(), ruleCommonBasicService.selectRowById("16").getMoney());
break;
case "二类地区":
basicCharge = new CommonCharge("大型车", "基本规则", ruleCommonBasicService.selectRowById("17").getMoney(),
ruleCommonBasicService.selectRowById("18").getMoney(), ruleCommonBasicService.selectRowById("19").getMoney(),
ruleCommonBasicService.selectRowById("20").getMoney(), ruleCommonBasicService.selectRowById("21").getMoney());
break;
case "三类地区":
basicCharge = new CommonCharge("大型车", "基本规则", ruleCommonBasicService.selectRowById("22").getMoney());
break;
}
}
if (car_type.equals("超大型车")) {
switch (zone_type) {
case "一类地区":
basicCharge = new CommonCharge("超大型车", "基本规则", ruleCommonBasicService.selectRowById("23").getMoney(),
ruleCommonBasicService.selectRowById("24").getMoney(), ruleCommonBasicService.selectRowById("25").getMoney(),
ruleCommonBasicService.selectRowById("26").getMoney(), ruleCommonBasicService.selectRowById("27").getMoney());
break;
case "二类地区":
basicCharge = new CommonCharge("超大型车", "基本规则", ruleCommonBasicService.selectRowById("28").getMoney(),
ruleCommonBasicService.selectRowById("29").getMoney(), ruleCommonBasicService.selectRowById("30").getMoney(),
ruleCommonBasicService.selectRowById("31").getMoney(), ruleCommonBasicService.selectRowById("32").getMoney());
break;
case "三类地区":
basicCharge = new CommonCharge("超大型车", "基本规则", ruleCommonBasicService.selectRowById("33").getMoney());
break;
}
}
if (car_type.equals("其他车")) {
switch (zone_type) {
case "一类地区":
basicCharge = new CommonCharge("其他车", "基本规则", ruleCommonBasicService.selectRowById("34").getMoney());
break;
case "二类地区":
basicCharge = new CommonCharge("其他车", "基本规则", ruleCommonBasicService.selectRowById("35").getMoney());
break;
case "三类地区":
basicCharge = new CommonCharge("其他车", "基本规则", ruleCommonBasicService.selectRowById("36").getMoney());
break;
}
}
}
public void processCustomCharge(String car_type) {
switch (car_type) {
case "小车":
this.basicCharge = new CustomCharge("小车", "自定义规则",
ruleCustomService.selectMoneyByInfo("高峰前一个小时", "小车"),
ruleCustomService.selectMoneyByInfo("高峰普通时段", "小车"),
ruleCustomService.selectMoneyByInfo("非高峰时段", "小车"),
ruleCustomService.selectMoneyByInfo("全天最高上限", "小车"));
break;
case "大型车":
this.basicCharge = new CustomCharge("大型车", "自定义规则",
ruleCustomService.selectMoneyByInfo("高峰前一个小时", "大型车"),
ruleCustomService.selectMoneyByInfo("高峰普通时段", "大型车"),
ruleCustomService.selectMoneyByInfo("非高峰时段", "大型车"),
ruleCustomService.selectMoneyByInfo("全天最高上限", "大型车"));
break;
case "超大型车":
this.basicCharge = new CustomCharge("超大型车", "自定义规则",
ruleCustomService.selectMoneyByInfo("高峰前一个小时", "超大型车"),
ruleCustomService.selectMoneyByInfo("高峰普通时段", "超大型车"),
ruleCustomService.selectMoneyByInfo("非高峰时段", "超大型车"),
ruleCustomService.selectMoneyByInfo("全天最高上限", "超大型车"));
break;
case "其他车":
this.basicCharge = new CustomCharge("其他车", "自定义规则",
ruleCustomService.selectMoneyByInfo("高峰前一个小时", "其他车"),
ruleCustomService.selectMoneyByInfo("高峰普通时段", "其他车"),
ruleCustomService.selectMoneyByInfo("非高峰时段", "其他车"),
ruleCustomService.selectMoneyByInfo("全天最高上限", "其他车"));
break;
}
}
public void processPersonCharge(String car_type) {
switch (car_type) {
case "小车":
basicCharge = new PersonCharge("小车", "私人规则", rulePersonService.selectMoneyByCarType("小车"));
break;
case "大车":
basicCharge = new PersonCharge("小车", "私人规则", rulePersonService.selectMoneyByCarType("大车"));
break;
case "超大型车":
basicCharge = new PersonCharge("小车", "私人规则", rulePersonService.selectMoneyByCarType("超大型车"));
break;
case "其他车":
basicCharge = new PersonCharge("小车", "私人规则", rulePersonService.selectMoneyByCarType("其他车"));
break;
}
}
@Autowired
public void setParkingRecordService(ParkingRecordService parkingRecordService) {
this.parkingRecordService = parkingRecordService;
}
@Autowired
public void setCarService(CarService carService) {
this.carService = carService;
}
@Autowired
public void setOrderService(OrderService orderService) {
this.orderService = orderService;
}
@Autowired
public void setStaffTaskService(StaffTaskService staffTaskService) {
this.staffTaskService = staffTaskService;
}
@Autowired
public void setStaffDutyService(StaffDutyService staffDutyService) {
this.staffDutyService = staffDutyService;
}
@Autowired
public void setStaffService(StaffService staffService) {
this.staffService = staffService;
}
@Autowired
public void setRuleCommonBasicService(RuleCommonBasicService ruleCommonBasicService) {
this.ruleCommonBasicService = ruleCommonBasicService;
}
@Autowired
public void setRulePersonService(RulePersonService rulePersonService) {
this.rulePersonService = rulePersonService;
}
@Autowired
public void setRuleCustomService(RuleCustomService ruleCustomService) {
this.ruleCustomService = ruleCustomService;
}
@Autowired
public void setRuleCustomInterimService(RuleCustomInterimService ruleCustomInterimService) {
this.ruleCustomInterimService = ruleCustomInterimService;
}
@Autowired
public void setRuleFixedParkingService(RuleFixedParkingService ruleFixedParkingService) {
this.ruleFixedParkingService = ruleFixedParkingService;
}
@Autowired
public void setParkingLotSettingService(ParkingLotSettingService parkingLotSettingService) {
this.parkingLotSettingService = parkingLotSettingService;
}
@Autowired
public void setParkingSpaceService(ParkingSpaceService parkingSpaceService) {
this.parkingSpaceService = parkingSpaceService;
}
}
| 47.043912 | 230 | 0.62998 |
768e364beafcc2c33802fa479500de8e198f2f4a | 424 | //package com.pal.rest;
//
//import org.springframework.web.bind.annotation.GetMapping;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RestController;
//
//@RestController
//@RequestMapping("/test")
//public class Travel {
//
// @GetMapping("/hello")
// public String sethello() {
// System.out.println("hello from test");
// return "hello";
// }
//
//}
| 23.555556 | 64 | 0.712264 |
f9f291d5ce56b36e081e3a3c7733e575e9f264b1 | 18,210 | package net.opendatadev.odensample;
import android.content.res.Resources;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import org.liquidplayer.javascript.JSContext;
import org.liquidplayer.javascript.JSException;
import org.liquidplayer.javascript.JSValue;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import static net.opendatadev.odensample.ManifestEntry.Download;
import static net.opendatadev.odensample.ManifestEntry.Download.Extract;
public class ManifestDownloader
{
private final Set<ManifestDownloaderListener> listeners;
private final File rootFolder;
private int toDownloadCount;
private AtomicInteger downloadedCount;
private boolean allFilesAdded;
{
listeners = new CopyOnWriteArraySet<>();
}
public ManifestDownloader(@NonNull final File folder)
{
rootFolder = folder;
}
public void addManifestDownloaderListener(@NonNull final ManifestDownloaderListener listener)
{
listeners.add(listener);
}
public void removeManifestDownloaderListener(@NonNull final ManifestDownloaderListener listener)
{
listeners.remove(listener);
}
public void download(final int resId,
@NonNull final Resources resources,
final boolean overwrite)
throws
IOException
{
final ManifestEntry[] entries;
entries = Manifest.getManifestEntries(resId,
resources);
download(entries,
overwrite);
}
public void download(@NonNull final ManifestEntry entry,
final boolean overwrite)
{
download(new ManifestEntry[]{entry},
overwrite);
}
public void download(@NonNull final ManifestEntry[] entries,
final boolean overwrite)
{
toDownloadCount = 0;
downloadedCount = new AtomicInteger(0);
allFilesAdded = false;
for(@NonNull final ManifestEntry entry : entries)
{
try
{
downloadEntry(entry,
overwrite,
() -> convert(entries));
}
catch(final IOException ex)
{
for(final ManifestDownloaderListener listener : listeners)
{
listener.downloadError(entry,
ex);
}
}
}
allFilesAdded = true;
// nothing downloaded
if(toDownloadCount == 0)
{
for(final ManifestDownloaderListener listener : listeners)
{
listener.conversionCompleted(entries);
}
}
}
private void downloadEntry(@NonNull final ManifestEntry entry,
final boolean overwrite,
@NonNull final Runnable callback)
throws
IOException
{
final File localityFolder;
localityFolder = Manifest.getLocalFolderFor(entry,
rootFolder);
if(overwrite)
{
FileUtils.deleteFolder(localityFolder);
}
FileUtils.createFolder(localityFolder);
downloadProvider(overwrite,
localityFolder,
entry,
callback);
}
private void downloadProvider(final boolean overwrite,
@NonNull final File localityFolder,
@NonNull final ManifestEntry entry,
@NonNull final Runnable callback)
throws
IOException
{
final File providerFolder;
final String provider;
final Download[] downloads;
provider = entry.getProvider();
providerFolder = new File(localityFolder,
provider);
FileUtils.createFolder(providerFolder);
if(entry.getConverter() != null)
{
final String converter;
converter = entry.getConverter();
downloadConverter(converter,
entry,
providerFolder,
overwrite,
callback);
}
downloads = entry.getDownloads();
for(int i = 0; i < downloads.length; i++)
{
final File downloadFolder;
final Download download;
final String path;
final String src;
final Extract[] extract;
path = Integer.toString(i);
downloadFolder = new File(providerFolder,
path);
FileUtils.createFolder(downloadFolder);
download = entry.getDownloads()[i];
src = download.getSrc();
extract = download.getExtract();
downloadDataset(src,
entry,
downloadFolder,
overwrite,
extract,
callback);
}
}
private void downloadConverter(@NonNull final String url,
@NonNull final ManifestEntry entry,
@NonNull final File toFolder,
final boolean overwrite,
@NonNull final Runnable callback)
{
final File localConverterFile;
localConverterFile = new File(toFolder,
"converter.js");
download(url,
entry,
localConverterFile,
overwrite,
callback);
}
private void downloadDataset(@NonNull final String url,
@NonNull final ManifestEntry entry,
@NonNull final File localFolder,
final boolean overwrite,
@Nullable final Extract[] extract,
@NonNull final Runnable callback)
{
final File localConverterFile;
localConverterFile = new File(localFolder,
"dataset");
if(extract == null)
{
download(url,
entry,
localConverterFile,
overwrite,
callback);
}
else
{
downloadAndExtract(url,
entry,
localConverterFile,
overwrite,
localFolder,
extract,
callback);
}
}
private void download(@NonNull final String url,
@NonNull final ManifestEntry entry,
@NonNull final File localFile,
final boolean overwrite,
@NonNull final Runnable downloadComplete)
{
if(shouldDownload(localFile,
overwrite))
{
addFile();
Downloader.download(url,
localFile,
(error) ->
{
if(error != null)
{
for(final ManifestDownloaderListener listener : listeners)
{
listener.downloadError(entry,
url,
error);
}
}
fileCompleted(downloadComplete);
});
}
}
private void downloadAndExtract(@NonNull final String url,
@NonNull final ManifestEntry entry,
@NonNull final File localFile,
final boolean overwrite,
@NonNull final File localFolder,
@NonNull final Extract[] extract,
@NonNull final Runnable downloadComplete)
{
if(shouldDownload(localFile,
overwrite))
{
addFile();
Downloader.download(url,
localFile,
(error) ->
{
if(error != null)
{
for(final ManifestDownloaderListener listener : listeners)
{
listener.downloadError(entry,
url,
error);
}
}
else
{
try
{
extractEntries(extract,
localFile,
localFolder);
}
catch(final IOException ex)
{
for(final ManifestDownloaderListener listener : listeners)
{
listener.unarchiveError(entry,
localFile,
ex);
}
}
}
fileCompleted(downloadComplete);
});
}
}
private void extractEntries(@NonNull final Extract[] extractEntries,
@NonNull final File archiveFile,
@NonNull final File localFolder)
throws
IOException
{
try(final ZipInputStream zipStream = new ZipInputStream(new FileInputStream(archiveFile)))
{
ZipEntry zipEntry;
while((zipEntry = zipStream.getNextEntry()) != null)
{
final String zipEntryName;
zipEntryName = zipEntry.getName();
for(final Extract extractEntry : extractEntries)
{
final String src;
src = extractEntry.getSrc();
if(src.equals(zipEntryName))
{
final File destinationFile;
final String path;
path = extractEntry.getDst();
destinationFile = new File(localFolder,
path);
FileUtils.copyFile(zipStream,
destinationFile);
}
}
}
}
}
private void convert(final ManifestEntry[] entries)
{
for(final ManifestEntry entry : entries)
{
convert(entry);
}
for(final ManifestDownloaderListener listener : listeners)
{
listener.conversionCompleted(entries);
}
}
private void convert(final ManifestEntry entry)
{
final File cityFolder;
final File providerFolder;
final File converterFile;
final File convertedFile;
final String provider;
cityFolder = Manifest.getLocalFolderFor(entry,
rootFolder);
provider = entry.getProvider();
providerFolder = new File(cityFolder,
provider);
converterFile = new File(providerFolder,
"converter.js");
convertedFile = new File(cityFolder,
provider + ".json");
try
{
// no schema - no way to convert
if(entry.getSchema() == null)
{
// how do we deal with this?
}
else
{
// yes schema, no converter - need to convert, proper format already
if(entry.getConverter() == null)
{
// for this to be the case we can only have a single data file, so it must be in 0
final File datasetFile = new File(providerFolder,
"0/dataset");
FileUtils.copyFile(datasetFile,
convertedFile);
}
else
{
runConversion(converterFile,
convertedFile,
entry,
providerFolder);
}
}
for(final ManifestDownloaderListener listener : listeners)
{
listener.converted(entry,
convertedFile);
}
}
catch(final IOException | JSException ex)
{
for(final ManifestDownloaderListener listener : listeners)
{
listener.conversionError(entry,
convertedFile,
ex);
}
}
}
private void runConversion(@NonNull final File converterFile,
@NonNull final File convertedFile,
@NonNull final ManifestEntry entry,
@NonNull final File providerFolder)
throws
IOException
{
final String converterJS;
final List<String> datasets;
final JSContext context;
final JSValue result;
final StringBuilder builder;
final Download[] downloads;
converterJS = FileUtils.readTextFile(converterFile);
datasets = new ArrayList<>();
downloads = entry.getDownloads();
for(int i = 0; i < downloads.length; i++)
{
final Download download;
final File downloadFolder;
final String path;
download = entry.getDownloads()[i];
path = Integer.toString(i);
downloadFolder = new File(providerFolder,
path);
if(download.getExtract() == null)
{
final File datasetFile;
final String dataset;
datasetFile = new File(downloadFolder,
"dataset");
dataset = FileUtils.readTextFile(datasetFile);
datasets.add(dataset);
}
else
{
final Extract[] extract;
extract = download.getExtract();
for(int j = 0; j < extract.length; j++)
{
final Extract extractEntry;
final File datasetFile;
final String dataset;
final String dstPath;
extractEntry = download.getExtract()[j];
dstPath = extractEntry.getDst();
datasetFile = new File(downloadFolder,
dstPath);
dataset = FileUtils.readTextFile(datasetFile);
datasets.add(dataset);
}
}
}
builder = new StringBuilder();
for(final String dataset : datasets)
{
builder.append(dataset);
builder.append(",");
}
builder.setLength(builder.length() - 1);
context = new JSContext();
context.evaluateScript("var module = {}");
context.evaluateScript(converterJS);
context.evaluateScript("var result = convert(" + builder.toString() + ");");
result = context.property("result");
FileUtils.writeTextFile(result.toString(),
convertedFile);
}
private void addFile()
{
toDownloadCount++;
}
private void fileCompleted(@NonNull final Runnable downloadComplete)
{
final int count;
count = downloadedCount.incrementAndGet();
if(allFilesAdded)
{
if(count == toDownloadCount)
{
downloadComplete.run();
}
}
}
private boolean shouldDownload(@NonNull final File file,
final boolean overwrite)
{
final boolean retVal;
if(overwrite)
{
retVal = true;
}
else if(file.exists())
{
retVal = false;
}
else
{
retVal = true;
}
return retVal;
}
}
| 32.929476 | 102 | 0.438331 |
a6d8dc217ac6ac3ae83a59bd1adddaa02aef5ddf | 37,311 | package com.hotel.model;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class WxConsumerExample {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table wx_consumer
*
* @mbggenerated
*/
protected String orderByClause;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table wx_consumer
*
* @mbggenerated
*/
protected boolean distinct;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table wx_consumer
*
* @mbggenerated
*/
protected List<Criteria> oredCriteria;
private Integer limit;
private Integer offset;
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table wx_consumer
*
* @mbggenerated
*/
public WxConsumerExample() {
oredCriteria = new ArrayList<Criteria>();
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table wx_consumer
*
* @mbggenerated
*/
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table wx_consumer
*
* @mbggenerated
*/
public String getOrderByClause() {
return orderByClause;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table wx_consumer
*
* @mbggenerated
*/
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table wx_consumer
*
* @mbggenerated
*/
public boolean isDistinct() {
return distinct;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table wx_consumer
*
* @mbggenerated
*/
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table wx_consumer
*
* @mbggenerated
*/
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table wx_consumer
*
* @mbggenerated
*/
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table wx_consumer
*
* @mbggenerated
*/
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table wx_consumer
*
* @mbggenerated
*/
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table wx_consumer
*
* @mbggenerated
*/
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
public void setLimit(Integer limit) {
this.limit = limit;
}
public Integer getLimit() {
return limit;
}
public void setOffset(Integer offset) {
this.offset = offset;
}
public Integer getOffset() {
return offset;
}
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table wx_consumer
*
* @mbggenerated
*/
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 andIdIsNull() {
addCriterion("id is null");
return (Criteria) this;
}
public Criteria andIdIsNotNull() {
addCriterion("id is not null");
return (Criteria) this;
}
public Criteria andIdEqualTo(Integer value) {
addCriterion("id =", value, "id");
return (Criteria) this;
}
public Criteria andIdNotEqualTo(Integer value) {
addCriterion("id <>", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThan(Integer value) {
addCriterion("id >", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThanOrEqualTo(Integer value) {
addCriterion("id >=", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThan(Integer value) {
addCriterion("id <", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThanOrEqualTo(Integer value) {
addCriterion("id <=", value, "id");
return (Criteria) this;
}
public Criteria andIdIn(List<Integer> values) {
addCriterion("id in", values, "id");
return (Criteria) this;
}
public Criteria andIdNotIn(List<Integer> values) {
addCriterion("id not in", values, "id");
return (Criteria) this;
}
public Criteria andIdBetween(Integer value1, Integer value2) {
addCriterion("id between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andIdNotBetween(Integer value1, Integer value2) {
addCriterion("id not between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andNameIsNull() {
addCriterion("name is null");
return (Criteria) this;
}
public Criteria andNameIsNotNull() {
addCriterion("name is not null");
return (Criteria) this;
}
public Criteria andNameEqualTo(String value) {
addCriterion("name =", value, "name");
return (Criteria) this;
}
public Criteria andNameNotEqualTo(String value) {
addCriterion("name <>", value, "name");
return (Criteria) this;
}
public Criteria andNameGreaterThan(String value) {
addCriterion("name >", value, "name");
return (Criteria) this;
}
public Criteria andNameGreaterThanOrEqualTo(String value) {
addCriterion("name >=", value, "name");
return (Criteria) this;
}
public Criteria andNameLessThan(String value) {
addCriterion("name <", value, "name");
return (Criteria) this;
}
public Criteria andNameLessThanOrEqualTo(String value) {
addCriterion("name <=", value, "name");
return (Criteria) this;
}
public Criteria andNameLike(String value) {
addCriterion("name like", value, "name");
return (Criteria) this;
}
public Criteria andNameNotLike(String value) {
addCriterion("name not like", value, "name");
return (Criteria) this;
}
public Criteria andNameIn(List<String> values) {
addCriterion("name in", values, "name");
return (Criteria) this;
}
public Criteria andNameNotIn(List<String> values) {
addCriterion("name not in", values, "name");
return (Criteria) this;
}
public Criteria andNameBetween(String value1, String value2) {
addCriterion("name between", value1, value2, "name");
return (Criteria) this;
}
public Criteria andNameNotBetween(String value1, String value2) {
addCriterion("name not between", value1, value2, "name");
return (Criteria) this;
}
public Criteria andNickNameIsNull() {
addCriterion("nick_name is null");
return (Criteria) this;
}
public Criteria andNickNameIsNotNull() {
addCriterion("nick_name is not null");
return (Criteria) this;
}
public Criteria andNickNameEqualTo(String value) {
addCriterion("nick_name =", value, "nickName");
return (Criteria) this;
}
public Criteria andNickNameNotEqualTo(String value) {
addCriterion("nick_name <>", value, "nickName");
return (Criteria) this;
}
public Criteria andNickNameGreaterThan(String value) {
addCriterion("nick_name >", value, "nickName");
return (Criteria) this;
}
public Criteria andNickNameGreaterThanOrEqualTo(String value) {
addCriterion("nick_name >=", value, "nickName");
return (Criteria) this;
}
public Criteria andNickNameLessThan(String value) {
addCriterion("nick_name <", value, "nickName");
return (Criteria) this;
}
public Criteria andNickNameLessThanOrEqualTo(String value) {
addCriterion("nick_name <=", value, "nickName");
return (Criteria) this;
}
public Criteria andNickNameLike(String value) {
addCriterion("nick_name like", value, "nickName");
return (Criteria) this;
}
public Criteria andNickNameNotLike(String value) {
addCriterion("nick_name not like", value, "nickName");
return (Criteria) this;
}
public Criteria andNickNameIn(List<String> values) {
addCriterion("nick_name in", values, "nickName");
return (Criteria) this;
}
public Criteria andNickNameNotIn(List<String> values) {
addCriterion("nick_name not in", values, "nickName");
return (Criteria) this;
}
public Criteria andNickNameBetween(String value1, String value2) {
addCriterion("nick_name between", value1, value2, "nickName");
return (Criteria) this;
}
public Criteria andNickNameNotBetween(String value1, String value2) {
addCriterion("nick_name not between", value1, value2, "nickName");
return (Criteria) this;
}
public Criteria andMobileIsNull() {
addCriterion("mobile is null");
return (Criteria) this;
}
public Criteria andMobileIsNotNull() {
addCriterion("mobile is not null");
return (Criteria) this;
}
public Criteria andMobileEqualTo(String value) {
addCriterion("mobile =", value, "mobile");
return (Criteria) this;
}
public Criteria andMobileNotEqualTo(String value) {
addCriterion("mobile <>", value, "mobile");
return (Criteria) this;
}
public Criteria andMobileGreaterThan(String value) {
addCriterion("mobile >", value, "mobile");
return (Criteria) this;
}
public Criteria andMobileGreaterThanOrEqualTo(String value) {
addCriterion("mobile >=", value, "mobile");
return (Criteria) this;
}
public Criteria andMobileLessThan(String value) {
addCriterion("mobile <", value, "mobile");
return (Criteria) this;
}
public Criteria andMobileLessThanOrEqualTo(String value) {
addCriterion("mobile <=", value, "mobile");
return (Criteria) this;
}
public Criteria andMobileLike(String value) {
addCriterion("mobile like", value, "mobile");
return (Criteria) this;
}
public Criteria andMobileNotLike(String value) {
addCriterion("mobile not like", value, "mobile");
return (Criteria) this;
}
public Criteria andMobileIn(List<String> values) {
addCriterion("mobile in", values, "mobile");
return (Criteria) this;
}
public Criteria andMobileNotIn(List<String> values) {
addCriterion("mobile not in", values, "mobile");
return (Criteria) this;
}
public Criteria andMobileBetween(String value1, String value2) {
addCriterion("mobile between", value1, value2, "mobile");
return (Criteria) this;
}
public Criteria andMobileNotBetween(String value1, String value2) {
addCriterion("mobile not between", value1, value2, "mobile");
return (Criteria) this;
}
public Criteria andAvatarUrlIsNull() {
addCriterion("avatar_url is null");
return (Criteria) this;
}
public Criteria andAvatarUrlIsNotNull() {
addCriterion("avatar_url is not null");
return (Criteria) this;
}
public Criteria andAvatarUrlEqualTo(String value) {
addCriterion("avatar_url =", value, "avatarUrl");
return (Criteria) this;
}
public Criteria andAvatarUrlNotEqualTo(String value) {
addCriterion("avatar_url <>", value, "avatarUrl");
return (Criteria) this;
}
public Criteria andAvatarUrlGreaterThan(String value) {
addCriterion("avatar_url >", value, "avatarUrl");
return (Criteria) this;
}
public Criteria andAvatarUrlGreaterThanOrEqualTo(String value) {
addCriterion("avatar_url >=", value, "avatarUrl");
return (Criteria) this;
}
public Criteria andAvatarUrlLessThan(String value) {
addCriterion("avatar_url <", value, "avatarUrl");
return (Criteria) this;
}
public Criteria andAvatarUrlLessThanOrEqualTo(String value) {
addCriterion("avatar_url <=", value, "avatarUrl");
return (Criteria) this;
}
public Criteria andAvatarUrlLike(String value) {
addCriterion("avatar_url like", value, "avatarUrl");
return (Criteria) this;
}
public Criteria andAvatarUrlNotLike(String value) {
addCriterion("avatar_url not like", value, "avatarUrl");
return (Criteria) this;
}
public Criteria andAvatarUrlIn(List<String> values) {
addCriterion("avatar_url in", values, "avatarUrl");
return (Criteria) this;
}
public Criteria andAvatarUrlNotIn(List<String> values) {
addCriterion("avatar_url not in", values, "avatarUrl");
return (Criteria) this;
}
public Criteria andAvatarUrlBetween(String value1, String value2) {
addCriterion("avatar_url between", value1, value2, "avatarUrl");
return (Criteria) this;
}
public Criteria andAvatarUrlNotBetween(String value1, String value2) {
addCriterion("avatar_url not between", value1, value2, "avatarUrl");
return (Criteria) this;
}
public Criteria andCityIsNull() {
addCriterion("city is null");
return (Criteria) this;
}
public Criteria andCityIsNotNull() {
addCriterion("city is not null");
return (Criteria) this;
}
public Criteria andCityEqualTo(String value) {
addCriterion("city =", value, "city");
return (Criteria) this;
}
public Criteria andCityNotEqualTo(String value) {
addCriterion("city <>", value, "city");
return (Criteria) this;
}
public Criteria andCityGreaterThan(String value) {
addCriterion("city >", value, "city");
return (Criteria) this;
}
public Criteria andCityGreaterThanOrEqualTo(String value) {
addCriterion("city >=", value, "city");
return (Criteria) this;
}
public Criteria andCityLessThan(String value) {
addCriterion("city <", value, "city");
return (Criteria) this;
}
public Criteria andCityLessThanOrEqualTo(String value) {
addCriterion("city <=", value, "city");
return (Criteria) this;
}
public Criteria andCityLike(String value) {
addCriterion("city like", value, "city");
return (Criteria) this;
}
public Criteria andCityNotLike(String value) {
addCriterion("city not like", value, "city");
return (Criteria) this;
}
public Criteria andCityIn(List<String> values) {
addCriterion("city in", values, "city");
return (Criteria) this;
}
public Criteria andCityNotIn(List<String> values) {
addCriterion("city not in", values, "city");
return (Criteria) this;
}
public Criteria andCityBetween(String value1, String value2) {
addCriterion("city between", value1, value2, "city");
return (Criteria) this;
}
public Criteria andCityNotBetween(String value1, String value2) {
addCriterion("city not between", value1, value2, "city");
return (Criteria) this;
}
public Criteria andGenderIsNull() {
addCriterion("gender is null");
return (Criteria) this;
}
public Criteria andGenderIsNotNull() {
addCriterion("gender is not null");
return (Criteria) this;
}
public Criteria andGenderEqualTo(Integer value) {
addCriterion("gender =", value, "gender");
return (Criteria) this;
}
public Criteria andGenderNotEqualTo(Integer value) {
addCriterion("gender <>", value, "gender");
return (Criteria) this;
}
public Criteria andGenderGreaterThan(Integer value) {
addCriterion("gender >", value, "gender");
return (Criteria) this;
}
public Criteria andGenderGreaterThanOrEqualTo(Integer value) {
addCriterion("gender >=", value, "gender");
return (Criteria) this;
}
public Criteria andGenderLessThan(Integer value) {
addCriterion("gender <", value, "gender");
return (Criteria) this;
}
public Criteria andGenderLessThanOrEqualTo(Integer value) {
addCriterion("gender <=", value, "gender");
return (Criteria) this;
}
public Criteria andGenderIn(List<Integer> values) {
addCriterion("gender in", values, "gender");
return (Criteria) this;
}
public Criteria andGenderNotIn(List<Integer> values) {
addCriterion("gender not in", values, "gender");
return (Criteria) this;
}
public Criteria andGenderBetween(Integer value1, Integer value2) {
addCriterion("gender between", value1, value2, "gender");
return (Criteria) this;
}
public Criteria andGenderNotBetween(Integer value1, Integer value2) {
addCriterion("gender not between", value1, value2, "gender");
return (Criteria) this;
}
public Criteria andCountryIsNull() {
addCriterion("country is null");
return (Criteria) this;
}
public Criteria andCountryIsNotNull() {
addCriterion("country is not null");
return (Criteria) this;
}
public Criteria andCountryEqualTo(String value) {
addCriterion("country =", value, "country");
return (Criteria) this;
}
public Criteria andCountryNotEqualTo(String value) {
addCriterion("country <>", value, "country");
return (Criteria) this;
}
public Criteria andCountryGreaterThan(String value) {
addCriterion("country >", value, "country");
return (Criteria) this;
}
public Criteria andCountryGreaterThanOrEqualTo(String value) {
addCriterion("country >=", value, "country");
return (Criteria) this;
}
public Criteria andCountryLessThan(String value) {
addCriterion("country <", value, "country");
return (Criteria) this;
}
public Criteria andCountryLessThanOrEqualTo(String value) {
addCriterion("country <=", value, "country");
return (Criteria) this;
}
public Criteria andCountryLike(String value) {
addCriterion("country like", value, "country");
return (Criteria) this;
}
public Criteria andCountryNotLike(String value) {
addCriterion("country not like", value, "country");
return (Criteria) this;
}
public Criteria andCountryIn(List<String> values) {
addCriterion("country in", values, "country");
return (Criteria) this;
}
public Criteria andCountryNotIn(List<String> values) {
addCriterion("country not in", values, "country");
return (Criteria) this;
}
public Criteria andCountryBetween(String value1, String value2) {
addCriterion("country between", value1, value2, "country");
return (Criteria) this;
}
public Criteria andCountryNotBetween(String value1, String value2) {
addCriterion("country not between", value1, value2, "country");
return (Criteria) this;
}
public Criteria andProvinceIsNull() {
addCriterion("province is null");
return (Criteria) this;
}
public Criteria andProvinceIsNotNull() {
addCriterion("province is not null");
return (Criteria) this;
}
public Criteria andProvinceEqualTo(String value) {
addCriterion("province =", value, "province");
return (Criteria) this;
}
public Criteria andProvinceNotEqualTo(String value) {
addCriterion("province <>", value, "province");
return (Criteria) this;
}
public Criteria andProvinceGreaterThan(String value) {
addCriterion("province >", value, "province");
return (Criteria) this;
}
public Criteria andProvinceGreaterThanOrEqualTo(String value) {
addCriterion("province >=", value, "province");
return (Criteria) this;
}
public Criteria andProvinceLessThan(String value) {
addCriterion("province <", value, "province");
return (Criteria) this;
}
public Criteria andProvinceLessThanOrEqualTo(String value) {
addCriterion("province <=", value, "province");
return (Criteria) this;
}
public Criteria andProvinceLike(String value) {
addCriterion("province like", value, "province");
return (Criteria) this;
}
public Criteria andProvinceNotLike(String value) {
addCriterion("province not like", value, "province");
return (Criteria) this;
}
public Criteria andProvinceIn(List<String> values) {
addCriterion("province in", values, "province");
return (Criteria) this;
}
public Criteria andProvinceNotIn(List<String> values) {
addCriterion("province not in", values, "province");
return (Criteria) this;
}
public Criteria andProvinceBetween(String value1, String value2) {
addCriterion("province between", value1, value2, "province");
return (Criteria) this;
}
public Criteria andProvinceNotBetween(String value1, String value2) {
addCriterion("province not between", value1, value2, "province");
return (Criteria) this;
}
public Criteria andUnionIdIsNull() {
addCriterion("union_id is null");
return (Criteria) this;
}
public Criteria andUnionIdIsNotNull() {
addCriterion("union_id is not null");
return (Criteria) this;
}
public Criteria andUnionIdEqualTo(String value) {
addCriterion("union_id =", value, "unionId");
return (Criteria) this;
}
public Criteria andUnionIdNotEqualTo(String value) {
addCriterion("union_id <>", value, "unionId");
return (Criteria) this;
}
public Criteria andUnionIdGreaterThan(String value) {
addCriterion("union_id >", value, "unionId");
return (Criteria) this;
}
public Criteria andUnionIdGreaterThanOrEqualTo(String value) {
addCriterion("union_id >=", value, "unionId");
return (Criteria) this;
}
public Criteria andUnionIdLessThan(String value) {
addCriterion("union_id <", value, "unionId");
return (Criteria) this;
}
public Criteria andUnionIdLessThanOrEqualTo(String value) {
addCriterion("union_id <=", value, "unionId");
return (Criteria) this;
}
public Criteria andUnionIdLike(String value) {
addCriterion("union_id like", value, "unionId");
return (Criteria) this;
}
public Criteria andUnionIdNotLike(String value) {
addCriterion("union_id not like", value, "unionId");
return (Criteria) this;
}
public Criteria andUnionIdIn(List<String> values) {
addCriterion("union_id in", values, "unionId");
return (Criteria) this;
}
public Criteria andUnionIdNotIn(List<String> values) {
addCriterion("union_id not in", values, "unionId");
return (Criteria) this;
}
public Criteria andUnionIdBetween(String value1, String value2) {
addCriterion("union_id between", value1, value2, "unionId");
return (Criteria) this;
}
public Criteria andUnionIdNotBetween(String value1, String value2) {
addCriterion("union_id not between", value1, value2, "unionId");
return (Criteria) this;
}
public Criteria andOpenIdIsNull() {
addCriterion("open_id is null");
return (Criteria) this;
}
public Criteria andOpenIdIsNotNull() {
addCriterion("open_id is not null");
return (Criteria) this;
}
public Criteria andOpenIdEqualTo(String value) {
addCriterion("open_id =", value, "openId");
return (Criteria) this;
}
public Criteria andOpenIdNotEqualTo(String value) {
addCriterion("open_id <>", value, "openId");
return (Criteria) this;
}
public Criteria andOpenIdGreaterThan(String value) {
addCriterion("open_id >", value, "openId");
return (Criteria) this;
}
public Criteria andOpenIdGreaterThanOrEqualTo(String value) {
addCriterion("open_id >=", value, "openId");
return (Criteria) this;
}
public Criteria andOpenIdLessThan(String value) {
addCriterion("open_id <", value, "openId");
return (Criteria) this;
}
public Criteria andOpenIdLessThanOrEqualTo(String value) {
addCriterion("open_id <=", value, "openId");
return (Criteria) this;
}
public Criteria andOpenIdLike(String value) {
addCriterion("open_id like", value, "openId");
return (Criteria) this;
}
public Criteria andOpenIdNotLike(String value) {
addCriterion("open_id not like", value, "openId");
return (Criteria) this;
}
public Criteria andOpenIdIn(List<String> values) {
addCriterion("open_id in", values, "openId");
return (Criteria) this;
}
public Criteria andOpenIdNotIn(List<String> values) {
addCriterion("open_id not in", values, "openId");
return (Criteria) this;
}
public Criteria andOpenIdBetween(String value1, String value2) {
addCriterion("open_id between", value1, value2, "openId");
return (Criteria) this;
}
public Criteria andOpenIdNotBetween(String value1, String value2) {
addCriterion("open_id not between", value1, value2, "openId");
return (Criteria) this;
}
public Criteria andCreatedAtIsNull() {
addCriterion("created_at is null");
return (Criteria) this;
}
public Criteria andCreatedAtIsNotNull() {
addCriterion("created_at is not null");
return (Criteria) this;
}
public Criteria andCreatedAtEqualTo(Date value) {
addCriterion("created_at =", value, "createdAt");
return (Criteria) this;
}
public Criteria andCreatedAtNotEqualTo(Date value) {
addCriterion("created_at <>", value, "createdAt");
return (Criteria) this;
}
public Criteria andCreatedAtGreaterThan(Date value) {
addCriterion("created_at >", value, "createdAt");
return (Criteria) this;
}
public Criteria andCreatedAtGreaterThanOrEqualTo(Date value) {
addCriterion("created_at >=", value, "createdAt");
return (Criteria) this;
}
public Criteria andCreatedAtLessThan(Date value) {
addCriterion("created_at <", value, "createdAt");
return (Criteria) this;
}
public Criteria andCreatedAtLessThanOrEqualTo(Date value) {
addCriterion("created_at <=", value, "createdAt");
return (Criteria) this;
}
public Criteria andCreatedAtIn(List<Date> values) {
addCriterion("created_at in", values, "createdAt");
return (Criteria) this;
}
public Criteria andCreatedAtNotIn(List<Date> values) {
addCriterion("created_at not in", values, "createdAt");
return (Criteria) this;
}
public Criteria andCreatedAtBetween(Date value1, Date value2) {
addCriterion("created_at between", value1, value2, "createdAt");
return (Criteria) this;
}
public Criteria andCreatedAtNotBetween(Date value1, Date value2) {
addCriterion("created_at not between", value1, value2, "createdAt");
return (Criteria) this;
}
public Criteria andUpdatedAtIsNull() {
addCriterion("updated_at is null");
return (Criteria) this;
}
public Criteria andUpdatedAtIsNotNull() {
addCriterion("updated_at is not null");
return (Criteria) this;
}
public Criteria andUpdatedAtEqualTo(Date value) {
addCriterion("updated_at =", value, "updatedAt");
return (Criteria) this;
}
public Criteria andUpdatedAtNotEqualTo(Date value) {
addCriterion("updated_at <>", value, "updatedAt");
return (Criteria) this;
}
public Criteria andUpdatedAtGreaterThan(Date value) {
addCriterion("updated_at >", value, "updatedAt");
return (Criteria) this;
}
public Criteria andUpdatedAtGreaterThanOrEqualTo(Date value) {
addCriterion("updated_at >=", value, "updatedAt");
return (Criteria) this;
}
public Criteria andUpdatedAtLessThan(Date value) {
addCriterion("updated_at <", value, "updatedAt");
return (Criteria) this;
}
public Criteria andUpdatedAtLessThanOrEqualTo(Date value) {
addCriterion("updated_at <=", value, "updatedAt");
return (Criteria) this;
}
public Criteria andUpdatedAtIn(List<Date> values) {
addCriterion("updated_at in", values, "updatedAt");
return (Criteria) this;
}
public Criteria andUpdatedAtNotIn(List<Date> values) {
addCriterion("updated_at not in", values, "updatedAt");
return (Criteria) this;
}
public Criteria andUpdatedAtBetween(Date value1, Date value2) {
addCriterion("updated_at between", value1, value2, "updatedAt");
return (Criteria) this;
}
public Criteria andUpdatedAtNotBetween(Date value1, Date value2) {
addCriterion("updated_at not between", value1, value2, "updatedAt");
return (Criteria) this;
}
}
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table wx_consumer
*
* @mbggenerated do_not_delete_during_merge
*/
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table wx_consumer
*
* @mbggenerated
*/
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);
}
}
} | 31.274937 | 102 | 0.577658 |
9ca4649085de9503b749803f9ca3caaaaa922425 | 10,030 | package com.checkmarx.flow.cucumber.integration.cli.ast;
import com.atlassian.jira.rest.client.api.domain.Issue;
import com.checkmarx.flow.CxFlowApplication;
import com.checkmarx.flow.CxFlowRunner;
import com.checkmarx.flow.config.FlowProperties;
import com.checkmarx.flow.config.JiraProperties;
import com.checkmarx.flow.cucumber.common.utils.TestUtils;
import com.checkmarx.flow.cucumber.integration.sca_scanner.ScaCommonSteps;
import com.checkmarx.flow.exception.ExitThrowable;
import com.checkmarx.flow.service.ASTScanner;
import com.checkmarx.flow.service.SCAScanner;
import com.checkmarx.jira.IJiraTestUtils;
import com.checkmarx.jira.JiraTestUtils;
import com.checkmarx.sdk.config.AstProperties;
import com.checkmarx.sdk.config.ScaProperties;
import com.checkmarx.sdk.dto.sast.Filter;
import io.cucumber.java.After;
import io.cucumber.java.Before;
import io.cucumber.java.PendingException;
import io.cucumber.java.en.And;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.file.PathUtils;
import org.junit.Assert;
import org.junit.platform.commons.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
@SpringBootTest(classes = {CxFlowApplication.class, JiraTestUtils.class})
@Slf4j
@RequiredArgsConstructor
public class AstCliSteps {
private static final String REPO_ARGS = " --repo-url=https://github.com/cxflowtestuser/testsAST.git --repo-name=CLI-public-rest-repo --branch=master --blocksysexit";
private static final String GITHUB_REPO_ARGS = REPO_ARGS + " --github ";
private static final String JIRA_PROJECT = "ASTCLITEST";
private static final String DIRECTORY_TO_SCAN = "input-code-for-sca";
private static final String NO_FILTERS = "none";
private static final int AT_LEAST_ONE = Integer.MAX_VALUE;
private final FlowProperties flowProperties;
private final JiraProperties jiraProperties;
private final ScaProperties scaProperties;
private final AstProperties astProperties;
private final CxFlowRunner cxFlowRunner;
private Throwable cxFlowExecutionException;
private String customAstProjectName;
private Path directoryToScan;
private static final String SEPARATOR = ",";
@Autowired
private IJiraTestUtils jiraUtils;
@Before
public void beforeEachScenario() throws IOException {
log.info("Setting bugTracker: Jira");
flowProperties.setBugTracker("JIRA");
ScaCommonSteps.initSCAConfig(scaProperties);
log.info("Jira project key: {}", JIRA_PROJECT);
jiraProperties.setProject(JIRA_PROJECT);
initJiraBugTracker();
log.info("reset sca filters");
scaProperties.setFilterSeverity(Collections.emptyList());
astProperties.setPreset("Checkmarx Default");
astProperties.setIncremental("false");
}
@After
public void afterEachScenario() throws IOException {
try {
log.info("Cleaning JIRA project: {}", jiraProperties.getProject());
jiraUtils.cleanProject(jiraProperties.getProject());
if (directoryToScan != null) {
log.info("Deleting temp directory: {}", directoryToScan);
PathUtils.deleteDirectory(directoryToScan);
}
}catch(Exception e){
log.warn("AstCliSteps.afterEachScenario(): Failed to clean issues: " + e.getMessage());
}
}
@Given("scanner is {}")
public void setScanInitiator(String initiatorList) {
List<String> scanners = Arrays.asList(initiatorList.toLowerCase().split(SEPARATOR));
flowProperties.setEnabledVulnerabilityScanners(scanners);
}
@And("source directory contains vulnerable files")
public void sourceDirectoryContainsVulnerableFiles() throws IOException {
directoryToScan = getTempDir();
copyTestProjectTo(directoryToScan);
}
@When("running a AST scan with break-build on {}")
public void runningWithBreakBuild(String issueType) {
StringBuilder commandBuilder = new StringBuilder();
setScanInitiator("AST");
switch (issueType) {
case "success":
commandBuilder.append("--scan --app=MyApp --cx-project=test").append(GITHUB_REPO_ARGS);
break;
case "missing-mandatory-parameter":
commandBuilder.append(GITHUB_REPO_ARGS);
break;
case "missing-project":
commandBuilder.append("--scan --app=MyApp --f=nofile").append(REPO_ARGS);
break;
default:
throw new PendingException("Issues type " + issueType + " isn't supported");
}
log.info("Running CxFlow scan with command line: {}", commandBuilder.toString());
try {
TestUtils.runCxFlow(cxFlowRunner, commandBuilder.toString());
cxFlowExecutionException = null;
} catch (Throwable e) {
cxFlowExecutionException = e;
}
}
@Then("run should exit with exit code {}")
public void validateExitCode(int expectedExitCode) {
Assert.assertNotNull("Expected an exception to be thrown.", cxFlowExecutionException);
Assert.assertEquals(InvocationTargetException.class, cxFlowExecutionException.getClass());
Throwable targetException = ((InvocationTargetException) cxFlowExecutionException).getTargetException();
Assert.assertTrue(targetException instanceof ExitThrowable);
int actualExitCode = ((ExitThrowable) targetException).getExitCode();
Assert.assertEquals("The expected exit code did not match", expectedExitCode, actualExitCode);
}
@When("repository is github")
public void runnningScan() {
customAstProjectName = "test";
StringBuilder commandLine = new StringBuilder();
commandLine.append(" --scan --app=MyApp --cx-project=test").append(GITHUB_REPO_ARGS);
tryRunCxFlow(commandLine.toString());
}
@Then("bug tracker contains {} issues")
public void validateBugTrackerIssues(int expectedIssuesCount) {
int actualIssueCount = jiraUtils.getNumberOfIssuesInProject(jiraProperties.getProject());
Iterable<Issue> actualIssues = jiraUtils.searchForAllIssues(jiraProperties.getProject()).getIssues();
actualIssues.forEach(issue -> {
if(flowProperties.getEnabledVulnerabilityScanners().size() ==1 && flowProperties.getEnabledVulnerabilityScanners().get(0).equalsIgnoreCase("AST")) {
//validate state
Assert.assertTrue(issue.getDescription().contains("TO_VERIFY"));
//validate description
if (issue.getDescription().contains("Cross_Site_History_Manipulation")) {
Assert.assertTrue(issue.getDescription().contains("Method @SourceMethod at line @SourceLine of @SourceFile may leak server-side conditional values, enabling user tracking from another website. This may constitute a Privacy Violation."));
}
// if (issue.getDescription().contains("Hardcoded_password_in_Connection_String")) {
// Assert.assertTrue(issue.getDescription().contains("The application contains hardcoded connection details, @SourceElement, at line @SourceLine of @SourceFile. This connection string contains a hardcoded password, which is used in @DestinationMethod at line @DestinationLine of @DestinationFile to connect to a database server with @DestinationElement. This can expose the database password, and impede proper password management."));
// }
}
});
log.info("comparing expected number of issues: {}, to actual bug tracker issues; {}", expectedIssuesCount, actualIssueCount);
Assert.assertEquals("Wrong issue count in bug tracker.", expectedIssuesCount, actualIssueCount);
}
@When("running CxFlow with `scan local sources` option and {}")
public void runningCxFlowWithScanLocalSourcesOptions(String customAstProjectName) {
String commandLine = String.format("--scan --cx-project=%s --app=MyApp --f=%s --blocksysexit",
customAstProjectName,
directoryToScan);
tryRunCxFlow(commandLine);
}
@And("no exception is thrown")
public void noExceptionIsThrown() {
Assert.assertNull("Unexpected exception while running CxFlow", cxFlowExecutionException);
}
private void tryRunCxFlow(String commandLine) {
try {
TestUtils.runCxFlow(cxFlowRunner, commandLine);
} catch (Throwable e) {
log.info("Caught CxFlow execution exception: {}.", e.getClass().getSimpleName());
}
}
private void initJiraBugTracker() throws IOException {
log.info("Cleaning jira project before test: {}", jiraProperties.getProject());
jiraUtils.ensureProjectExists(jiraProperties.getProject());
jiraUtils.cleanProject(jiraProperties.getProject());
}
private static Path getTempDir() {
String systemTempDir = FileUtils.getTempDirectoryPath();
String subdir = String.format("ast-cli-test-%s", UUID.randomUUID());
return Paths.get(systemTempDir, subdir);
}
private void copyTestProjectTo(Path targetDir) throws IOException {
log.info("Copying test project files from resources ({}) into a temp directory: {}", DIRECTORY_TO_SCAN, targetDir);
File directory = TestUtils.getFileFromResource(DIRECTORY_TO_SCAN);
FileUtils.copyDirectory(directory, targetDir.toFile());
}
} | 41.618257 | 454 | 0.700598 |
d1b1dd67abf6513bc05b8a178649f4ff2c74c72a | 2,720 | /*
* Copyright (C) 2015 University of Oregon
*
* You may distribute under the terms of either the GNU General Public
* License or the Apache License, as specified in the LICENSE file.
*
* For more information, see the LICENSE file.
*/
package vnmr.util;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.tree.*;
/********************************************************** <pre>
* Summary: Turn a JTree into a JTree with CheckBoxs
*
* Check boxes are tri state. Unselected, Selected, and gray selected
* where gray selected means that some, but not all, items below this node
* have been selected. If all items below a node are selected, it is a normal
* black check mark.
*
* To use, create a CheckTreeManager with your JTree as its arg
* JTree MyTree;
* Create the tree as desired
* CheckTreeManager checkTreeManager = new CheckTreeManager(tree);
* to get the paths that were checked
* TreePath checkedPaths[] =
* checkTreeManager.getSelectionModel().getSelectionPaths();
*
* The basic code was obtained from http://jroller.com/page/santhosh
*
</pre> **********************************************************/
public class CheckTreeManager extends MouseAdapter implements TreeSelectionListener{
private CheckTreeSelectionModel selectionModel;
private JTree tree = new JTree();
int hotspot = new JCheckBox().getPreferredSize().width;
public CheckTreeManager(JTree tree){
this.tree = tree;
selectionModel = new CheckTreeSelectionModel(tree.getModel());
tree.setCellRenderer(new CheckTreeCellRenderer(tree.getCellRenderer(),
selectionModel));
tree.addMouseListener(this);
selectionModel.addTreeSelectionListener(this);
}
public void mouseClicked(MouseEvent me){
TreePath path = tree.getPathForLocation(me.getX(), me.getY());
if(path==null)
return;
if(me.getX()>tree.getPathBounds(path).x+hotspot)
return;
boolean selected = selectionModel.isPathSelected(path, true);
selectionModel.removeTreeSelectionListener(this);
try{
if(selected)
selectionModel.removeSelectionPath(path);
else
selectionModel.addSelectionPath(path);
} finally{
selectionModel.addTreeSelectionListener(this);
tree.treeDidChange();
}
}
public CheckTreeSelectionModel getSelectionModel(){
return selectionModel;
}
public void valueChanged(TreeSelectionEvent e){
tree.treeDidChange();
}
}
| 33.170732 | 85 | 0.632353 |
5b998ee1570ffa7e4038267dce48040fcbcc5049 | 1,378 | package controller.helper;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import service.CacheService;
import service.UpdateBLService;
/**
* @author Qiang
* @date 6/9/16
*/
@Controller
public class Scheduler implements InitializingBean{
@Autowired
CacheService cacheService;
@Autowired
UpdateBLService updateBLService;
@Override
public void afterPropertiesSet() throws Exception {
new Thread(() -> {
System.out.println("preparing cache = = =");
cacheService.prepareCache();
System.out.println("Reading cache finish = = =");
}).start();
//TODO 部署的时候会自动更新数据
// System.out.println("Start schedule of update data");
// Calendar cal = Calendar.getInstance();
// //每天定点执行
// cal.set(Calendar.HOUR_OF_DAY,3);
// cal.set(Calendar.MINUTE,0);
// cal.set(Calendar.SECOND,0);
// Timer timer = new Timer();
// timer.schedule(new TimerTask() {
// public void run() {
// System.out.println("Start updating data = = =");
// updateBLService.update();
// System.out.println("Finish updating data = = =");
// }
// },cal.getTime(), 24*60*60*1000);
}
}
| 28.122449 | 67 | 0.618287 |
2c6fc453169cb4b631813264b134b513ba9be947 | 2,825 | package co.edu.usbbog.bdd.rest;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import co.edu.usbbog.bdd.model.TipoTransaccion;
import co.edu.usbbog.bdd.service.TipoTransaccionService;
@RestController
public class TipoTransaccionController {
@Autowired
TipoTransaccionService tipoService;
@GetMapping("/crearTipo")
// @Procedure("application/json")
public String crearTipo(@RequestBody TipoTransaccion newTipo) {
JSONObject respuesta= new JSONObject();
if(tipoService.crearTipoTransaccion(newTipo).equals("Se guardo el tipo de transaccion")) {
respuesta.put("respuesta", true);
return respuesta.toString();
}else {
respuesta.put("respuesta", false);
return respuesta.toString();
}
}
@PostMapping("/contarTipo")
public String contarTipo() {
JSONObject respuesta= new JSONObject();
int aux=tipoService.contarTipoTransaccion();
respuesta.put("Count", aux);
return respuesta.toString();
}
@PostMapping("/eliminarTipo")
public String eliminarTipo(@RequestBody TipoTransaccion newTipo) {
JSONObject respuesta= new JSONObject();
if(tipoService.eliminarTipoTransaccion(newTipo).equals("Se elimino el tipo de transaccion")) {
respuesta.put("respuesta", true);
return respuesta.toString();
}else {
respuesta.put("respuesta", false);
return respuesta.toString();
}
}
@PostMapping("/getTipo")
public String getTipo() {
JSONArray array= new JSONArray();
List<TipoTransaccion> tipo=tipoService.findAll();
for (int i = 0; i < tipo.size(); i++) {
JSONObject ciudadJson= new JSONObject();
ciudadJson.put("ID", tipo.get(i).getId());
ciudadJson.put("Nombre", tipo.get(i).getNombre());
array.put(ciudadJson);
}
return array.toString();
}
@PostMapping("/buscarTipo")
public String buscarTipo(@RequestBody TipoTransaccion tipo) {
JSONObject respuesta= new JSONObject();
if(tipoService.mostrarTipoTransaccion(tipo.getId())!=null) {
respuesta.put("respuesta", true);
return respuesta.toString();
}else {
respuesta.put("respuesta", false);
return respuesta.toString();
}
}
@PostMapping("/modificarTipo")
public String modificarTipo(@RequestBody TipoTransaccion newTipo) {
JSONObject respuesta= new JSONObject();
if(tipoService.modificarTipoTransaccion(newTipo).equals("Se modifico el tipo de transaccion")) {
respuesta.put("respuesta", true);
return respuesta.toString();
}else {
respuesta.put("respuesta", false);
return respuesta.toString();
}
}
}
| 29.123711 | 98 | 0.738761 |
bd88f8e7efec7dfd4aeb356784bb75ccc711f498 | 3,230 | /*
* Copyright 2015 - 2017 Xyanid
*
* 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 de.saxsys.svgfx.core;
import de.saxsys.svgfx.core.css.SVGCssStyle;
import de.saxsys.svgfx.core.elements.SVGClipPath;
import de.saxsys.svgfx.core.elements.SVGDefinitions;
import de.saxsys.svgfx.core.elements.SVGElementBase;
import de.saxsys.svgfx.core.elements.SVGElementFactory;
import de.saxsys.svgfx.core.elements.SVGGradientBase;
import de.saxsys.svgfx.core.elements.SVGStop;
import de.saxsys.svgfx.core.path.CommandParser;
import de.saxsys.svgfx.core.path.commands.CommandFactory;
import de.saxsys.svgfx.xml.core.SAXParser;
import javafx.scene.Group;
import javafx.scene.Node;
import org.xml.sax.EntityResolver;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
/**
* This parser is used to create SVG path data for javafx
*
* @author Xyanid on 24.10.2015.
*/
public class SVGParser extends SAXParser<Group, SVGDocumentDataProvider, SVGElementFactory, SVGElementBase<?>> implements EntityResolver {
// region Constants
private static final CommandFactory COMMAND_FACTORY = new CommandFactory();
private static final CommandParser COMMAND_PARSER = new CommandParser(COMMAND_FACTORY);
private static final SVGElementFactory SVG_ELEMENT_FACTORY = new SVGElementFactory(COMMAND_PARSER);
// endregion
// region Constructor
/**
* Creates a new instance of the parser and uses the given elementCreator.
*/
public SVGParser() {
super(SVG_ELEMENT_FACTORY, new SVGDocumentDataProvider());
}
// endregion
// region Override SAXParser
@Override
protected void configureReader(final XMLReader reader) throws SAXException {}
@Override
protected void enteringDocument() {}
@Override
protected Group leavingDocument(final SVGElementBase<?> element) throws SAXException {
final Group result = new Group();
if (element != null) {
for (final SVGElementBase child : element.getUnmodifiableChildren()) {
if (canConsumeElement(element)) {
result.getChildren().add((Node) child.getResult());
}
}
}
return result;
}
// endregion
// region Private
private boolean canConsumeElement(final SVGElementBase element) {
return !SVGClipPath.class.isAssignableFrom(element.getClass())
&& !SVGDefinitions.class.isAssignableFrom(element.getClass())
&& !SVGGradientBase.class.isAssignableFrom(element.getClass())
&& !SVGCssStyle.class.isAssignableFrom(element.getClass())
&& !SVGStop.class.isAssignableFrom(element.getClass());
}
// endregion
}
| 33.298969 | 138 | 0.716718 |
23e2481d28cd8b71959683b9e7a5f9c0e4abde62 | 183 | import java.math.BigDecimal;
interface Power {
static long digit(long exp) {
return new BigDecimal(".301029995663981195").multiply(new BigDecimal(exp)).longValue() + 1;
}
} | 26.142857 | 95 | 0.715847 |
8ed3cacdec5138389b74e5437d1b8ec3c67392f6 | 375 | package homework.homework1.homework6;
public class MilesToKilometersConverter {
public static final double KM_IN_A_MILE = 1.609;
public static void main(String[] args) {
System.out.print("Miles\t\tKilometers");
for (int mile = 1; mile <= 10; mile++) {
System.out.printf("\n%1d\t\t\t%.3f", mile, (mile * KM_IN_A_MILE));
}
}
}
| 28.846154 | 78 | 0.624 |
bd798126735476ff2c554ce23cced0437364662a | 363 | package br.com.wnascimento.entreguei.util;
import android.util.Patterns;
public class ValidateUtil {
public static boolean isValidateEmail(String email) {
return Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
public static boolean validateMinLength(String string, int maxLength) {
return string.length() < maxLength;
}
}
| 21.352941 | 75 | 0.721763 |
9967681e717b845654e14718be6946cf356add24 | 3,413 | package xyz.codemeans.mybatis.generator.config;
import com.google.common.base.CaseFormat;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import java.io.File;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import lombok.Data;
import lombok.experimental.Accessors;
/**
* @author yuanwq
*/
@Data
@Accessors(chain = true)
public class GenerationDef {
/**
* input package name
*
* @apiNote required
*/
@NotBlank
private String inputPackage;
/**
* root output dir
*
* @apiNote required
*/
@NotNull
private File outputDir;
/**
* charset for output files
*/
private Charset outputCharset = StandardCharsets.UTF_8;
/**
* config for name changing of auto-generated SqlSupport type
*
* @apiNote default suffix: `DynamicSqlSupport`
*/
private NamingProfile sqlSupportTypeNaming = new NamingProfile();
/**
* config for name changing of auto-generated SqlTable instance in SqlSupport
*
* @apiNote default format conversion: UPPER_CAMEL to LOWER_CAMEL
*/
private NamingProfile sqlTableInstanceNaming = new NamingProfile();
/**
* config for name changing of static SqlColumn fields in auto-generated SqlSupport type
*/
private NamingProfile sqlSupportFieldNaming = new NamingProfile();
/**
* config for name changing of auto-generated SqlTable subclass
*/
private NamingProfile sqlTableTypeNaming = new NamingProfile();
/**
* config for name changing of fields in auto-generated SqlTable
*/
private NamingProfile sqlTableFieldNaming = new NamingProfile();
/**
* base package name for output; if unset, use {@code <inputType.package>.sql}
*/
private String outputPackage;
/**
* whether to keep the same package structure for output as like #inputPackage. Only works if
* {@link #outputPackage} is set.
*/
private boolean keepPackageStructure = true;
/**
* whether to generate for inherited fields
*/
private boolean inheritField = true;
private int indentSize = 2;
/**
* whether to generate Fields class which contains namings of all fields in model type
*/
private boolean generateFieldsType = true;
/**
* config for name changing of auto-generated Fields class
*
* @apiNote default suffix: Fields
*/
private NamingProfile fieldsTypeNaming = new NamingProfile();
/**
* default catalog
*/
private String catalog;
/**
* default schema
*/
private String schema;
/**
* config for changing of auto-generated table name
*
* @apiNote default format conversion: UPPER_CAMEL to LOWER_UNDERSCORE
*/
private NamingProfile tableNaming = new NamingProfile();
/**
* config for changing of auto-generated column name
*
* @apiNote default format conversion: LOWER_CAMEL to LOWER_UNDERSCORE
*/
private NamingProfile columnNaming = new NamingProfile();
public GenerationDef() {
sqlSupportTypeNaming.setSuffix("DynamicSqlSupport");
sqlTableInstanceNaming
.setFromFormat(CaseFormat.UPPER_CAMEL)
.setToFormat(CaseFormat.LOWER_CAMEL);
fieldsTypeNaming
.setSuffix("Fields");
tableNaming
.setFromFormat(CaseFormat.UPPER_CAMEL)
.setToFormat(CaseFormat.LOWER_UNDERSCORE);
columnNaming
.setFromFormat(CaseFormat.LOWER_CAMEL)
.setToFormat(CaseFormat.LOWER_UNDERSCORE);
}
}
| 27.97541 | 95 | 0.714914 |
415c8a411888ad8b5212d25f5bc8b7c122f73aa5 | 1,318 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.codeInsight.stdlib;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.psi.PsiElement;
import com.intellij.psi.util.QualifiedName;
import com.jetbrains.python.codeInsight.PyCustomMember;
import com.jetbrains.python.psi.PyFile;
import com.jetbrains.python.psi.resolve.ResolveImportUtil;
import com.jetbrains.python.psi.types.PyModuleMembersProvider;
import com.jetbrains.python.psi.types.TypeEvalContext;
import org.jetbrains.annotations.NotNull;
import java.util.Collection;
import java.util.Collections;
/**
* @author yole
*/
public class PyStdlibModuleMembersProvider extends PyModuleMembersProvider {
@Override
@NotNull
protected Collection<PyCustomMember> getMembersByQName(@NotNull PyFile module, @NotNull String qName, @NotNull TypeEvalContext context) {
if (qName.equals("os")) {
final String pathModuleName = SystemInfo.isWindows ? "ntpath" : "posixpath";
final PsiElement path = ResolveImportUtil.resolveModuleInRoots(QualifiedName.fromDottedString(pathModuleName), module);
return Collections.singletonList(new PyCustomMember("path", path));
}
return Collections.emptyList();
}
}
| 39.939394 | 140 | 0.793627 |
02121a24b0b7697143df9bc6d877f212c1399e7a | 1,382 | package frc.acquisitions;
/**
* Class allowing the storage of speed values for motors. Used when setting motor speeds in the Acquisitions subsystem.
*/
public class AcquisitionsOutput
{
/**
* Output for the motor. Value between -1 and 1.
*/
private double motor;
/**
* True if the command has finished executing.
*/
private boolean isDone;
/**
* Used to set and store new speed values for the motors.
* @param armMotor The speed that the arm motor should be set to.
* @param intakeMotor The speed that the intake motor should be set to.
*/
public AcquisitionsOutput(double motor)
{
this.motor = motor;
this.isDone = false;
}
/**
* Used to set and store new speed values for the motors.
* @param motor The speed that the motor should be set to.
* @param isDone True if the command has finished executing.
*/
public AcquisitionsOutput(double motor, boolean isDone)
{
this.motor = motor;
this.isDone = isDone;
}
/**
* @return The set output speed of the motor.
*/
public double get()
{
return motor;
}
/**
* @return Whether or not the command has finished executing and should no longer be ran in the subsystem thread.
*/
public boolean isDone()
{
return isDone;
}
} | 25.127273 | 119 | 0.620839 |
0f122c593639822f7054c057f40660c78d7bcf3d | 2,562 | package com.iguerra94.weathernow.utils;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import com.iguerra94.weathernow.utils.sharedPrefs.SharedPrefsKeys;
import com.iguerra94.weathernow.utils.sharedPrefs.SharedPrefsManager;
import java.util.Locale;
public class LocaleHelper {
public static Context onAttach(Context context) {
String lang = getPersistedData(context, Locale.getDefault().getLanguage());
return setLocale(context, lang);
}
public static Context onAttach(Context context, String defaultLanguage) {
String lang = getPersistedData(context, defaultLanguage);
return setLocale(context, lang);
}
public static String getLanguage(Context context) {
return getPersistedData(context, Locale.getDefault().getLanguage());
}
public static Context setLocale(Context context, String language) {
persist(context, language);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return updateResources(context, language);
}
return updateResourcesLegacy(context, language);
}
private static String getPersistedData(Context context, String defaultLanguage) {
return SharedPrefsManager.getInstance(context).readString(SharedPrefsKeys.APP_LANGUAGE_LOCALE, defaultLanguage);
}
private static void persist(Context context, String language) {
SharedPrefsManager.getInstance(context).saveString(SharedPrefsKeys.APP_LANGUAGE_LOCALE, language);
}
@TargetApi(Build.VERSION_CODES.N)
private static Context updateResources(Context context, String language) {
Locale locale = new Locale(language);
Locale.setDefault(locale);
Configuration configuration = context.getResources().getConfiguration();
configuration.setLocale(locale);
configuration.setLayoutDirection(locale);
return context.createConfigurationContext(configuration);
}
private static Context updateResourcesLegacy(Context context, String language) {
Locale locale = new Locale(language);
Locale.setDefault(locale);
Resources resources = context.getResources();
Configuration configuration = resources.getConfiguration();
configuration.locale = locale;
configuration.setLayoutDirection(locale);
resources.updateConfiguration(configuration, resources.getDisplayMetrics());
return context;
}
} | 34.621622 | 120 | 0.735363 |
189200d94892ec49ee1fcabe8cb061ee93dfbae1 | 984 | package org.reactivecouchbase.json.exceptions;
import java.util.List;
import java.util.stream.Collectors;
public class JsWrappedException extends JsException {
private final List<Exception> exceptions;
public JsWrappedException(List<Exception> exceptions) {
this.exceptions = exceptions;
}
@Override
public void setStackTrace(StackTraceElement[] stackTraceElements) {
throw new IllegalAccessError("Can set stackstrace");
}
@Override
public String getMessage() {
return exceptions.stream().map(Throwable::getMessage).collect(Collectors.joining(" | "));
}
@Override
public String getLocalizedMessage() {
return exceptions.stream().map(Throwable::getLocalizedMessage).collect(Collectors.joining(" | "));
}
@Override
public String toString() {
return getMessage();
}
@Override
public void printStackTrace() {
exceptions.forEach(Throwable::printStackTrace);
}
} | 26.594595 | 106 | 0.694106 |
e46c7df469bfe29dd6ebc4517921c3d1a5a5de1d | 3,466 | package com.kgc.pojo;
import java.util.Date;
public class UserInfo {
private Integer uid;
private Integer accid;
private String nickname;
private Integer age;
private String sex;
private String address;
private String email;
private String phone;
private String touxiang;
private String qianming;
private Date modification;
private Integer utype;
private Integer score;
@Override
public String toString() {
return "UserInfo{" +
"uid=" + uid +
", accid=" + accid +
", nickname='" + nickname + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
", address='" + address + '\'' +
", email='" + email + '\'' +
", phone='" + phone + '\'' +
", touxiang='" + touxiang + '\'' +
", qianming='" + qianming + '\'' +
", modification=" + modification +
", utype=" + utype +
", score=" + score +
'}';
}
public UserInfo() {
}
public UserInfo(Integer uid, Integer utype) {
this.uid = uid;
this.utype = utype;
}
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public Integer getAccid() {
return accid;
}
public void setAccid(Integer accid) {
this.accid = accid;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname == null ? null : nickname.trim();
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex == null ? null : sex.trim();
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address == null ? null : address.trim();
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email == null ? null : email.trim();
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone == null ? null : phone.trim();
}
public String getTouxiang() {
return touxiang;
}
public void setTouxiang(String touxiang) {
this.touxiang = touxiang == null ? null : touxiang.trim();
}
public String getQianming() {
return qianming;
}
public void setQianming(String qianming) {
this.qianming = qianming == null ? null : qianming.trim();
}
public Date getModification() {
return modification;
}
public void setModification(Date modification) {
this.modification = modification;
}
public Integer getUtype() {
return utype;
}
public void setUtype(Integer utype) {
this.utype = utype;
}
public Integer getScore() {
return score;
}
public void setScore(Integer score) {
this.score = score;
}
} | 21.263804 | 67 | 0.502308 |
23033853c6e78925cd5c7c610d160a040320f21e | 3,793 | import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
public class CSVParser {
/**
* Parse CSV file to an ArrayList of City objects.
*
* @param csvFile Absolute path to the csv file.
* @return An ArrayList of the cities. The list is populated in the same order as the cities are read in the file.
* @throws FileNotFoundException The path to the file is invalid.
*/
//ArrayList always give O(1) time complexity (map can give O(n) in worst case)
public static ArrayList<City> parseCityList(String csvFile) throws FileNotFoundException {
BufferedReader br = null;
String line = "";
int n = 0;
ArrayList<City> cities = new ArrayList<>();
br = new BufferedReader(new FileReader(csvFile));
// Handle first line
try {
line = br.readLine();
try {
n = Integer.valueOf(line);
} catch(NumberFormatException e) {
e.printStackTrace();
System.err.println("Could not read CSV: first line must be the number of cities.");
return null;
}
int count = 0;
while((line = br.readLine()) != null) {
double x, y;
String[] coordinates = line.split(",");
x = Double.valueOf(coordinates[0]);
y = Double.valueOf(coordinates[1]);
// Create the city
City city = new City(new Coordinates(x,y));
// Add the city to the list
cities.add(city);
count++;
}
if(count != n) {
System.err.println("CSV format incorrect: the number of cities (first line) is not consistent with the " +
"number of coordinates (following lines).");
}
} catch (IOException e) {
e.printStackTrace();
}
return cities;
}
//UNUSED
/*public static TreeMap<Integer,City> parseCityTreeMap(String csvFile) throws FileNotFoundException {
BufferedReader br = null;
String line = "";
int n = 1;
TreeMap<Integer,City> cities = new TreeMap<>();
try {
br = new BufferedReader(new FileReader(csvFile));
// Handle first line
line = br.readLine();
try {
n = Integer.valueOf(line) +1;
} catch(NumberFormatException e) {
e.printStackTrace();
System.err.println("Could not read CSV: first line must be the number of cities.");
return null;
}
int count = 1;
while((line = br.readLine()) != null) {
double x, y;
String[] coordinates = line.split(",");
x = Double.valueOf(coordinates[0]);
y = Double.valueOf(coordinates[1]);
City city = null;
// create the city
if(count == 1){
city = new DepartureCity(new Coordinates(x,y),count);
} else{
city = new City(new Coordinates(x,y),count);
}
// Add the city to the Map
cities.put(city.getId(),city);
count++;
}
if(count != n) {
System.err.println("CSV format incorrect: the number of cities (first line) is not consistent with the " +
"number of coordinates (following lines).");
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
return cities;
}*/
}
| 34.171171 | 122 | 0.514369 |
e6fc2ad88f8a27a82968fda461357285206a7978 | 21,365 | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.components.page_info;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.provider.Settings;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.TextAppearanceSpan;
import android.view.Window;
import androidx.annotation.IntDef;
import androidx.annotation.VisibleForTesting;
import androidx.core.view.ViewCompat;
import org.chromium.base.ApiCompatibilityUtils;
import org.chromium.base.Consumer;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.NativeMethods;
import org.chromium.base.metrics.RecordUserAction;
import org.chromium.components.content_settings.ContentSettingValues;
import org.chromium.components.content_settings.CookieControlsEnforcement;
import org.chromium.components.content_settings.CookieControlsObserver;
import org.chromium.components.content_settings.CookieControlsStatus;
import org.chromium.components.dom_distiller.core.DomDistillerUrlUtils;
import org.chromium.components.embedder_support.util.UrlUtilities;
import org.chromium.components.omnibox.AutocompleteSchemeClassifier;
import org.chromium.components.omnibox.OmniboxUrlEmphasizer;
import org.chromium.components.page_info.PageInfoView.ConnectionInfoParams;
import org.chromium.components.page_info.PageInfoView.PageInfoViewParams;
import org.chromium.components.security_state.ConnectionSecurityLevel;
import org.chromium.components.security_state.SecurityStateModel;
import org.chromium.components.url_formatter.UrlFormatter;
import org.chromium.content_public.browser.WebContents;
import org.chromium.content_public.browser.WebContentsObserver;
import org.chromium.ui.base.Clipboard;
import org.chromium.ui.base.DeviceFormFactor;
import org.chromium.ui.base.WindowAndroid;
import org.chromium.ui.modaldialog.DialogDismissalCause;
import org.chromium.ui.modaldialog.ModalDialogProperties;
import org.chromium.ui.modaldialog.ModalDialogProperties.ButtonType;
import org.chromium.ui.modelutil.PropertyModel;
import org.chromium.ui.util.ColorUtils;
import org.chromium.url.URI;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.ref.WeakReference;
import java.net.URISyntaxException;
/**
* Java side of Android implementation of the page info UI.
*/
public class PageInfoController implements ModalDialogProperties.Controller,
SystemSettingsActivityRequiredListener,
CookieControlsObserver {
@IntDef({OpenedFromSource.MENU, OpenedFromSource.TOOLBAR, OpenedFromSource.VR})
@Retention(RetentionPolicy.SOURCE)
public @interface OpenedFromSource {
int MENU = 1;
int TOOLBAR = 2;
int VR = 3;
}
private final WindowAndroid mWindowAndroid;
private final WebContents mWebContents;
private final PageInfoControllerDelegate mDelegate;
// A pointer to the C++ object for this UI.
private long mNativePageInfoController;
// The view inside the popup.
private PageInfoView mView;
// The dialog the view is placed in.
private final PageInfoDialog mDialog;
// The full URL from the URL bar, which is copied to the user's clipboard when they select 'Copy
// URL'.
private String mFullUrl;
// Whether or not this page is an internal chrome page (e.g. the
// chrome://settings page).
private boolean mIsInternalPage;
// The security level of the page (a valid ConnectionSecurityLevel).
private int mSecurityLevel;
// The name of the content publisher, if any.
private String mContentPublisher;
// Observer for dismissing dialog if web contents get destroyed, navigate etc.
private WebContentsObserver mWebContentsObserver;
// A task that should be run once the page info popup is animated out and dismissed. Null if no
// task is pending.
private Runnable mPendingRunAfterDismissTask;
private Consumer<Runnable> mRunAfterDismissConsumer;
// Reference to last created PageInfoController for testing.
private static WeakReference<PageInfoController> sLastPageInfoControllerForTesting;
/**
* Creates the PageInfoController, but does not display it. Also initializes the corresponding
* C++ object and saves a pointer to it.
* @param activity Activity which is used for showing a popup.
* @param webContents The WebContents showing the page that the PageInfo is about.
* @param securityLevel The security level of the page being shown.
* @param publisher The name of the content publisher, if any.
* @param delegate The PageInfoControllerDelegate used to provide
* embedder-specific info.
*/
@VisibleForTesting(otherwise = VisibleForTesting.PROTECTED)
public PageInfoController(Activity activity, WebContents webContents, int securityLevel,
String publisher, PageInfoControllerDelegate delegate) {
mWebContents = webContents;
mSecurityLevel = securityLevel;
mDelegate = delegate;
mRunAfterDismissConsumer = new Consumer<Runnable>() {
@Override
public void accept(Runnable r) {
runAfterDismiss(r);
}
};
PageInfoViewParams viewParams = new PageInfoViewParams();
mWindowAndroid = webContents.getTopLevelNativeWindow();
mContentPublisher = publisher;
viewParams.urlTitleClickCallback = () -> {
// Expand/collapse the displayed URL title.
mView.toggleUrlTruncation();
};
// Long press the url text to copy it to the clipboard.
viewParams.urlTitleLongClickCallback =
() -> Clipboard.getInstance().copyUrlToClipboard(mFullUrl);
// Work out the URL and connection message and status visibility.
// TODO(crbug.com/1033178): dedupe the DomDistillerUrlUtils#getOriginalUrlFromDistillerUrl()
// calls.
mFullUrl = mDelegate.isShowingOfflinePage()
? mDelegate.getOfflinePageUrl()
: DomDistillerUrlUtils.getOriginalUrlFromDistillerUrl(
webContents.getVisibleUrlString());
// This can happen if an invalid chrome-distiller:// url was entered.
if (mFullUrl == null) mFullUrl = "";
try {
mIsInternalPage = UrlUtilities.isInternalScheme(new URI(mFullUrl));
} catch (URISyntaxException e) {
// Ignore exception since this is for displaying some specific content on page info.
}
String displayUrl = UrlFormatter.formatUrlForSecurityDisplay(mFullUrl);
if (mDelegate.isShowingOfflinePage()) {
displayUrl = UrlUtilities.stripScheme(mFullUrl);
}
SpannableStringBuilder displayUrlBuilder = new SpannableStringBuilder(displayUrl);
AutocompleteSchemeClassifier autocompleteSchemeClassifier =
delegate.createAutocompleteSchemeClassifier();
if (mSecurityLevel == ConnectionSecurityLevel.SECURE) {
OmniboxUrlEmphasizer.EmphasizeComponentsResponse emphasizeResponse =
OmniboxUrlEmphasizer.parseForEmphasizeComponents(
displayUrlBuilder.toString(), autocompleteSchemeClassifier);
if (emphasizeResponse.schemeLength > 0) {
displayUrlBuilder.setSpan(
new TextAppearanceSpan(activity, R.style.TextAppearance_RobotoMediumStyle),
0, emphasizeResponse.schemeLength, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
}
}
boolean useDarkText = ColorUtils.useDarkColors(activity);
OmniboxUrlEmphasizer.emphasizeUrl(displayUrlBuilder, activity.getResources(),
autocompleteSchemeClassifier, mSecurityLevel, mIsInternalPage, useDarkText,
/*emphasizeScheme=*/true);
viewParams.url = displayUrlBuilder;
viewParams.urlOriginLength = OmniboxUrlEmphasizer.getOriginEndIndex(
displayUrlBuilder.toString(), autocompleteSchemeClassifier);
autocompleteSchemeClassifier.destroy();
if (mDelegate.isSiteSettingsAvailable()) {
viewParams.siteSettingsButtonClickCallback = () -> {
// Delay while the dialog closes.
runAfterDismiss(() -> {
recordAction(PageInfoAction.PAGE_INFO_SITE_SETTINGS_OPENED);
mDelegate.showSiteSettings(mFullUrl);
});
};
viewParams.cookieControlsShown = delegate.cookieControlsShown();
} else {
viewParams.siteSettingsButtonShown = false;
viewParams.cookieControlsShown = false;
}
mDelegate.initPreviewUiParams(viewParams, mRunAfterDismissConsumer);
mDelegate.initOfflinePageUiParams(viewParams, mRunAfterDismissConsumer);
if (!mIsInternalPage && !mDelegate.isShowingOfflinePage() && !mDelegate.isShowingPreview()
&& mDelegate.isInstantAppAvailable(mFullUrl)) {
final Intent instantAppIntent = mDelegate.getInstantAppIntentForUrl(mFullUrl);
viewParams.instantAppButtonClickCallback = () -> {
try {
activity.startActivity(instantAppIntent);
RecordUserAction.record("Android.InstantApps.LaunchedFromWebsiteSettingsPopup");
} catch (ActivityNotFoundException e) {
mView.disableInstantAppButton();
}
};
RecordUserAction.record("Android.InstantApps.OpenInstantAppButtonShown");
} else {
viewParams.instantAppButtonShown = false;
}
mView = new PageInfoView(activity, viewParams);
if (isSheet(activity)) mView.setBackgroundColor(Color.WHITE);
// TODO(crbug.com/1040091): Remove when cookie controls are launched.
boolean showTitle = viewParams.cookieControlsShown;
mDelegate.createPermissionParamsListBuilder(
mWindowAndroid, mFullUrl, showTitle, this, mView::setPermissions);
mNativePageInfoController = PageInfoControllerJni.get().init(this, mWebContents);
mDelegate.createCookieControlsBridge(this);
CookieControlsView.CookieControlsParams cookieControlsParams =
new CookieControlsView.CookieControlsParams();
cookieControlsParams.onUiClosingCallback = mDelegate::onUiClosing;
cookieControlsParams.onCheckedChangedCallback = (Boolean blockCookies) -> {
recordAction(blockCookies ? PageInfoAction.PAGE_INFO_COOKIE_BLOCKED_FOR_SITE
: PageInfoAction.PAGE_INFO_COOKIE_ALLOWED_FOR_SITE);
mDelegate.setThirdPartyCookieBlockingEnabledForSite(blockCookies);
};
mView.getCookieControlsView().setParams(cookieControlsParams);
mWebContentsObserver = new WebContentsObserver(webContents) {
@Override
public void navigationEntryCommitted() {
// If a navigation is committed (e.g. from in-page redirect), the data we're showing
// is stale so dismiss the dialog.
mDialog.dismiss(true);
}
@Override
public void wasHidden() {
// The web contents were hidden (potentially by loading another URL via an intent),
// so dismiss the dialog).
mDialog.dismiss(true);
}
@Override
public void destroy() {
super.destroy();
// Force the dialog to close immediately in case the destroy was from Chrome
// quitting.
mDialog.dismiss(false);
}
};
mDialog = new PageInfoDialog(activity, mView,
webContents.getViewAndroidDelegate().getContainerView(), isSheet(activity),
delegate.getModalDialogManager(), this);
mDialog.show();
}
/**
* Whether to show a 'Details' link to the connection info popup.
*/
private boolean isConnectionDetailsLinkVisible() {
return mContentPublisher == null && !mDelegate.isShowingOfflinePage()
&& !mDelegate.isShowingPreview() && !mIsInternalPage;
}
/**
* Adds a new row for the given permission.
*
* @param name The title of the permission to display to the user.
* @param type The ContentSettingsType of the permission.
* @param currentSettingValue The ContentSetting value of the currently selected setting.
*/
@CalledByNative
private void addPermissionSection(
String name, int type, @ContentSettingValues int currentSettingValue) {
mDelegate.addPermissionEntry(name, type, currentSettingValue);
}
/**
* Update the permissions view based on the contents of mDisplayedPermissions.
*/
@CalledByNative
private void updatePermissionDisplay() {
mDelegate.updatePermissionDisplay(mView);
}
/**
* Sets the connection security summary and detailed description strings. These strings may be
* overridden based on the state of the Android UI.
*/
@CalledByNative
private void setSecurityDescription(String summary, String details) {
ConnectionInfoParams connectionInfoParams = new ConnectionInfoParams();
// Display the appropriate connection message.
SpannableStringBuilder messageBuilder = new SpannableStringBuilder();
Context context = mWindowAndroid.getActivity().get();
assert context != null;
if (mContentPublisher != null) {
messageBuilder.append(
context.getString(R.string.page_info_domain_hidden, mContentPublisher));
} else if (mDelegate.isShowingPreview() && mDelegate.isPreviewPageInsecure()) {
connectionInfoParams.summary = summary;
} else if (mDelegate.getOfflinePageConnectionMessage() != null) {
messageBuilder.append(mDelegate.getOfflinePageConnectionMessage());
} else {
if (!TextUtils.equals(summary, details)) {
connectionInfoParams.summary = summary;
}
messageBuilder.append(details);
}
if (isConnectionDetailsLinkVisible()) {
messageBuilder.append(" ");
SpannableString detailsText =
new SpannableString(context.getString(R.string.details_link));
final ForegroundColorSpan blueSpan =
new ForegroundColorSpan(ApiCompatibilityUtils.getColor(
context.getResources(), R.color.default_text_color_link));
detailsText.setSpan(
blueSpan, 0, detailsText.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
messageBuilder.append(detailsText);
}
// When a preview is being shown for a secure page, the security message is not shown. Thus,
// messageBuilder maybe empty.
if (messageBuilder.length() > 0) {
connectionInfoParams.message = messageBuilder;
}
if (isConnectionDetailsLinkVisible()) {
connectionInfoParams.clickCallback = () -> {
runAfterDismiss(() -> {
if (!mWebContents.isDestroyed()) {
recordAction(PageInfoAction.PAGE_INFO_SECURITY_DETAILS_OPENED);
ConnectionInfoPopup.show(context, mWebContents,
mDelegate.getModalDialogManager(), mDelegate.getVrHandler());
}
});
};
}
mView.setConnectionInfo(connectionInfoParams);
}
@Override
public void onSystemSettingsActivityRequired(Intent intentOverride) {
runAfterDismiss(() -> {
Context context = mWindowAndroid.getContext().get();
assert context != null;
Intent settingsIntent;
if (intentOverride != null) {
settingsIntent = intentOverride;
} else {
settingsIntent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
settingsIntent.setData(Uri.parse("package:" + context.getPackageName()));
}
settingsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(settingsIntent);
});
}
/**
* Dismiss the popup, and then run a task after the animation has completed (if there is one).
*/
private void runAfterDismiss(Runnable task) {
mPendingRunAfterDismissTask = task;
mDialog.dismiss(true);
}
@Override
public void onClick(PropertyModel model, @ButtonType int buttonType) {}
@Override
public void onDismiss(PropertyModel model, @DialogDismissalCause int dismissalCause) {
assert mNativePageInfoController != 0;
if (mPendingRunAfterDismissTask != null) {
mPendingRunAfterDismissTask.run();
mPendingRunAfterDismissTask = null;
}
mWebContentsObserver.destroy();
PageInfoControllerJni.get().destroy(mNativePageInfoController, PageInfoController.this);
mNativePageInfoController = 0;
}
private void recordAction(int action) {
if (mNativePageInfoController != 0) {
PageInfoControllerJni.get().recordPageInfoAction(
mNativePageInfoController, PageInfoController.this, action);
}
}
private boolean isSheet(Context context) {
return !DeviceFormFactor.isNonMultiDisplayContextOnTablet(context)
&& !mDelegate.getVrHandler().isInVr();
}
@VisibleForTesting
public PageInfoView getPageInfoViewForTesting() {
return mView;
}
/**
* Shows a PageInfo dialog for the provided WebContents. The popup adds itself to the view
* hierarchy which owns the reference while it's visible.
*
* @param activity The activity that is used for launching a dialog.
* @param webContents The web contents for which to show Website information. This
* information is retrieved for the visible entry.
* @param contentPublisher The name of the publisher of the content.
* @param source Determines the source that triggered the popup.
* @param delegate The PageInfoControllerDelegate used to provide embedder-specific info.
*/
public static void show(final Activity activity, WebContents webContents,
final String contentPublisher, @OpenedFromSource int source,
PageInfoControllerDelegate delegate) {
// If the activity's decor view is not attached to window, we don't show the dialog because
// the window manager might have revoked the window token for this activity. See
// https://crbug.com/921450.
Window window = activity.getWindow();
if (window == null || !ViewCompat.isAttachedToWindow(window.getDecorView())) return;
if (source == OpenedFromSource.MENU) {
RecordUserAction.record("MobileWebsiteSettingsOpenedFromMenu");
} else if (source == OpenedFromSource.TOOLBAR) {
RecordUserAction.record("MobileWebsiteSettingsOpenedFromToolbar");
} else if (source == OpenedFromSource.VR) {
RecordUserAction.record("MobileWebsiteSettingsOpenedFromVR");
} else {
assert false : "Invalid source passed";
}
sLastPageInfoControllerForTesting = new WeakReference<>(new PageInfoController(activity,
webContents, SecurityStateModel.getSecurityLevelForWebContents(webContents),
contentPublisher, delegate));
}
@VisibleForTesting(otherwise = VisibleForTesting.PACKAGE_PRIVATE)
public static PageInfoController getLastPageInfoControllerForTesting() {
return sLastPageInfoControllerForTesting != null ? sLastPageInfoControllerForTesting.get()
: null;
}
@Override
public void onCookieBlockingStatusChanged(
@CookieControlsStatus int status, @CookieControlsEnforcement int enforcement) {
mView.getCookieControlsView().setCookieBlockingStatus(
status, enforcement != CookieControlsEnforcement.NO_ENFORCEMENT);
}
@Override
public void onBlockedCookiesCountChanged(int blockedCookies) {
mView.getCookieControlsView().setBlockedCookiesCount(blockedCookies);
}
@NativeMethods
interface Natives {
long init(PageInfoController controller, WebContents webContents);
void destroy(long nativePageInfoControllerAndroid, PageInfoController caller);
void recordPageInfoAction(
long nativePageInfoControllerAndroid, PageInfoController caller, int action);
}
}
| 44.60334 | 100 | 0.680084 |
f810edcd3d1d94bc5e6e02d7e7ba8f868fe21e32 | 16,138 | package io.swagger.client.api;
import io.swagger.client.ApiException;
import io.swagger.client.ApiClient;
import io.swagger.client.Configuration;
import io.swagger.client.Pair;
import javax.ws.rs.core.GenericType;
import java.math.BigDecimal;
import io.swagger.client.model.Client;
import org.threeten.bp.LocalDate;
import org.threeten.bp.OffsetDateTime;
import io.swagger.client.model.OuterComposite;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class FakeApi {
private ApiClient apiClient;
public FakeApi() {
this(Configuration.getDefaultApiClient());
}
public FakeApi(ApiClient apiClient) {
this.apiClient = apiClient;
}
public ApiClient getApiClient() {
return apiClient;
}
public void setApiClient(ApiClient apiClient) {
this.apiClient = apiClient;
}
/**
*
* Test serialization of outer boolean types
* @param body Input boolean as post body (optional)
* @return Boolean
* @throws ApiException if fails to make API call
*/
public Boolean fakeOuterBooleanSerialize(Boolean body) throws ApiException {
Object localVarPostBody = body;
// create path and map variables
String localVarPath = "/fake/outer/boolean";
// query params
List<Pair> localVarQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
final String[] localVarContentTypes = {
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
String[] localVarAuthNames = new String[] { };
GenericType<Boolean> localVarReturnType = new GenericType<Boolean>() {};
return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType);
}
/**
*
* Test serialization of object with outer number type
* @param body Input composite as post body (optional)
* @return OuterComposite
* @throws ApiException if fails to make API call
*/
public OuterComposite fakeOuterCompositeSerialize(OuterComposite body) throws ApiException {
Object localVarPostBody = body;
// create path and map variables
String localVarPath = "/fake/outer/composite";
// query params
List<Pair> localVarQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
final String[] localVarContentTypes = {
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
String[] localVarAuthNames = new String[] { };
GenericType<OuterComposite> localVarReturnType = new GenericType<OuterComposite>() {};
return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType);
}
/**
*
* Test serialization of outer number types
* @param body Input number as post body (optional)
* @return BigDecimal
* @throws ApiException if fails to make API call
*/
public BigDecimal fakeOuterNumberSerialize(BigDecimal body) throws ApiException {
Object localVarPostBody = body;
// create path and map variables
String localVarPath = "/fake/outer/number";
// query params
List<Pair> localVarQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
final String[] localVarContentTypes = {
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
String[] localVarAuthNames = new String[] { };
GenericType<BigDecimal> localVarReturnType = new GenericType<BigDecimal>() {};
return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType);
}
/**
*
* Test serialization of outer string types
* @param body Input string as post body (optional)
* @return String
* @throws ApiException if fails to make API call
*/
public String fakeOuterStringSerialize(String body) throws ApiException {
Object localVarPostBody = body;
// create path and map variables
String localVarPath = "/fake/outer/string";
// query params
List<Pair> localVarQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
final String[] localVarContentTypes = {
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
String[] localVarAuthNames = new String[] { };
GenericType<String> localVarReturnType = new GenericType<String>() {};
return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType);
}
/**
* To test \"client\" model
* To test \"client\" model
* @param body client model (required)
* @return Client
* @throws ApiException if fails to make API call
*/
public Client testClientModel(Client body) throws ApiException {
Object localVarPostBody = body;
// verify the required parameter 'body' is set
if (body == null) {
throw new ApiException(400, "Missing the required parameter 'body' when calling testClientModel");
}
// create path and map variables
String localVarPath = "/fake";
// query params
List<Pair> localVarQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
final String[] localVarContentTypes = {
"application/json"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
String[] localVarAuthNames = new String[] { };
GenericType<Client> localVarReturnType = new GenericType<Client>() {};
return apiClient.invokeAPI(localVarPath, "PATCH", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType);
}
/**
* Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트
* Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트
* @param number None (required)
* @param _double None (required)
* @param patternWithoutDelimiter None (required)
* @param _byte None (required)
* @param integer None (optional)
* @param int32 None (optional)
* @param int64 None (optional)
* @param _float None (optional)
* @param string None (optional)
* @param binary None (optional)
* @param date None (optional)
* @param dateTime None (optional)
* @param password None (optional)
* @param paramCallback None (optional)
* @throws ApiException if fails to make API call
*/
public void testEndpointParameters(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback) throws ApiException {
Object localVarPostBody = null;
// verify the required parameter 'number' is set
if (number == null) {
throw new ApiException(400, "Missing the required parameter 'number' when calling testEndpointParameters");
}
// verify the required parameter '_double' is set
if (_double == null) {
throw new ApiException(400, "Missing the required parameter '_double' when calling testEndpointParameters");
}
// verify the required parameter 'patternWithoutDelimiter' is set
if (patternWithoutDelimiter == null) {
throw new ApiException(400, "Missing the required parameter 'patternWithoutDelimiter' when calling testEndpointParameters");
}
// verify the required parameter '_byte' is set
if (_byte == null) {
throw new ApiException(400, "Missing the required parameter '_byte' when calling testEndpointParameters");
}
// create path and map variables
String localVarPath = "/fake";
// query params
List<Pair> localVarQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
if (integer != null)
localVarFormParams.put("integer", integer);
if (int32 != null)
localVarFormParams.put("int32", int32);
if (int64 != null)
localVarFormParams.put("int64", int64);
if (number != null)
localVarFormParams.put("number", number);
if (_float != null)
localVarFormParams.put("float", _float);
if (_double != null)
localVarFormParams.put("double", _double);
if (string != null)
localVarFormParams.put("string", string);
if (patternWithoutDelimiter != null)
localVarFormParams.put("pattern_without_delimiter", patternWithoutDelimiter);
if (_byte != null)
localVarFormParams.put("byte", _byte);
if (binary != null)
localVarFormParams.put("binary", binary);
if (date != null)
localVarFormParams.put("date", date);
if (dateTime != null)
localVarFormParams.put("dateTime", dateTime);
if (password != null)
localVarFormParams.put("password", password);
if (paramCallback != null)
localVarFormParams.put("callback", paramCallback);
final String[] localVarAccepts = {
"application/xml; charset=utf-8", "application/json; charset=utf-8"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
final String[] localVarContentTypes = {
"application/xml; charset=utf-8", "application/json; charset=utf-8"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
String[] localVarAuthNames = new String[] { "http_basic_test" };
apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null);
}
/**
* To test enum parameters
* To test enum parameters
* @param enumFormStringArray Form parameter enum test (string array) (optional)
* @param enumFormString Form parameter enum test (string) (optional, default to -efg)
* @param enumHeaderStringArray Header parameter enum test (string array) (optional)
* @param enumHeaderString Header parameter enum test (string) (optional, default to -efg)
* @param enumQueryStringArray Query parameter enum test (string array) (optional)
* @param enumQueryString Query parameter enum test (string) (optional, default to -efg)
* @param enumQueryInteger Query parameter enum test (double) (optional)
* @param enumQueryDouble Query parameter enum test (double) (optional)
* @throws ApiException if fails to make API call
*/
public void testEnumParameters(List<String> enumFormStringArray, String enumFormString, List<String> enumHeaderStringArray, String enumHeaderString, List<String> enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/fake";
// query params
List<Pair> localVarQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "enum_query_string_array", enumQueryStringArray));
localVarQueryParams.addAll(apiClient.parameterToPairs("", "enum_query_string", enumQueryString));
localVarQueryParams.addAll(apiClient.parameterToPairs("", "enum_query_integer", enumQueryInteger));
if (enumHeaderStringArray != null)
localVarHeaderParams.put("enum_header_string_array", apiClient.parameterToString(enumHeaderStringArray));
if (enumHeaderString != null)
localVarHeaderParams.put("enum_header_string", apiClient.parameterToString(enumHeaderString));
if (enumFormStringArray != null)
localVarFormParams.put("enum_form_string_array", enumFormStringArray);
if (enumFormString != null)
localVarFormParams.put("enum_form_string", enumFormString);
if (enumQueryDouble != null)
localVarFormParams.put("enum_query_double", enumQueryDouble);
final String[] localVarAccepts = {
"*/*"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
final String[] localVarContentTypes = {
"*/*"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
String[] localVarAuthNames = new String[] { };
apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null);
}
/**
* test json serialization of form data
*
* @param param field1 (required)
* @param param2 field2 (required)
* @throws ApiException if fails to make API call
*/
public void testJsonFormData(String param, String param2) throws ApiException {
Object localVarPostBody = null;
// verify the required parameter 'param' is set
if (param == null) {
throw new ApiException(400, "Missing the required parameter 'param' when calling testJsonFormData");
}
// verify the required parameter 'param2' is set
if (param2 == null) {
throw new ApiException(400, "Missing the required parameter 'param2' when calling testJsonFormData");
}
// create path and map variables
String localVarPath = "/fake/jsonFormData";
// query params
List<Pair> localVarQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
if (param != null)
localVarFormParams.put("param", param);
if (param2 != null)
localVarFormParams.put("param2", param2);
final String[] localVarAccepts = {
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
final String[] localVarContentTypes = {
"application/json"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
String[] localVarAuthNames = new String[] { };
apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null);
}
}
| 37.705607 | 307 | 0.721651 |
316c1f1aae968a0ed6cacb0770c08d2b72e8b2a8 | 142 | package tanzu.workshop.paymentcalculator.service;
public interface HitCounterService {
long incrementCounter();
void resetCount();
}
| 20.285714 | 49 | 0.774648 |
181bbac0f30133a6a69c2320a9dafffdbdc4c5bf | 4,298 | package com.android.iam.cursofirebase.Activity;
import android.Manifest;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.iam.cursofirebase.Classes.Usuario;
import com.android.iam.cursofirebase.DAO.ConfiguracaoFirebase;
import com.android.iam.cursofirebase.Helper.Preferencias;
import com.android.iam.cursofirebase.R;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class MainActivity extends AppCompatActivity {
private FirebaseAuth autenticacao;
private EditText edtEmailLogin;
private EditText edtSenhaLogin;
private Button btnLogin;
private Usuario usuario;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtEmailLogin = (EditText) findViewById(R.id.edtEmail);
edtSenhaLogin = (EditText) findViewById(R.id.edtSenha);
btnLogin = (Button) findViewById(R.id.btnLogin);
permissoes();
if (usuarioLogado()) {
Intent intentMinhaConta = new Intent(MainActivity.this, PrincipalActivity.class);
abrirNovaActivity(intentMinhaConta);
finish();
} else {
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!edtEmailLogin.getText().toString().equals("") && !edtSenhaLogin.getText().toString().equals("")) {
usuario = new Usuario();
usuario.setEmail(edtEmailLogin.getText().toString());
usuario.setSenha(edtSenhaLogin.getText().toString());
validarLogin();
} else {
Toast.makeText(MainActivity.this, "Preencha os campos de E-mail e senha", Toast.LENGTH_SHORT).show();
}
}
});
}
}
private void validarLogin() {
autenticacao = ConfiguracaoFirebase.getFirebaseAuth();
autenticacao.signInWithEmailAndPassword(usuario.getEmail().toString(), usuario.getSenha().toString()).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
abrirTelaPrincipal();
Preferencias preferencias = new Preferencias(MainActivity.this);
preferencias.salvarUsuarioPreferencias(usuario.getEmail(), usuario.getSenha());
Toast.makeText(MainActivity.this, "Login efetuado com sucesso!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Usuário ou senha inválidos! Tente novamente!", Toast.LENGTH_SHORT).show();
}
}
});
}
private void abrirTelaPrincipal() {
Intent intent = new Intent(MainActivity.this, PrincipalActivity.class);
startActivity(intent);
finish();
}
public Boolean usuarioLogado() {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
return true;
} else {
return false;
}
}
public void abrirNovaActivity(Intent intent) {
startActivity(intent);
}
public void permissoes() {
int PERMISSION_ALL = 1;
String[] PERMISSIONS = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.ACCESS_NETWORK_STATE, Manifest.permission.INTERNET};
ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
}
}
| 34.66129 | 305 | 0.660074 |
877c8ecafa030c12ce18e2c62a6a8a2fb8b1e44b | 8,154 | package com.verdantartifice.thaumicwonders.common.items.tools;
import javax.annotation.Nullable;
import com.verdantartifice.thaumicwonders.ThaumicWonders;
import com.verdantartifice.thaumicwonders.common.items.ItemsTW;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.projectile.EntityArrow;
import net.minecraft.init.Enchantments;
import net.minecraft.init.Items;
import net.minecraft.init.SoundEvents;
import net.minecraft.item.IItemPropertyGetter;
import net.minecraft.item.ItemArrow;
import net.minecraft.item.ItemBow;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.SoundCategory;
import net.minecraft.world.World;
import thaumcraft.api.items.IRechargable;
import thaumcraft.api.items.RechargeHelper;
public class ItemBoneBow extends ItemBow implements IRechargable {
protected static final int VIS_CAPACITY = 200;
protected static final int POWERED_CHARGE_TIME = 10;
protected static final int UNPOWERED_CHARGE_TIME = 20;
public ItemBoneBow() {
this.setCreativeTab(ThaumicWonders.CREATIVE_TAB);
this.setRegistryName(ThaumicWonders.MODID, "bone_bow");
this.setUnlocalizedName(ThaumicWonders.MODID + "." + this.getRegistryName().getResourcePath());
this.setMaxStackSize(1);
this.setMaxDamage(512);
this.addPropertyOverride(new ResourceLocation(ThaumicWonders.MODID, "pull"), new IItemPropertyGetter() {
@Override
public float apply(ItemStack stack, @Nullable World worldIn, @Nullable EntityLivingBase entityIn) {
if (entityIn == null) {
return 0.0F;
} else {
float maxCharge = (RechargeHelper.getCharge(stack) > 0) ? (float)POWERED_CHARGE_TIME : (float)UNPOWERED_CHARGE_TIME;
return entityIn.getActiveItemStack().getItem() != ItemsTW.BONE_BOW ? 0.0F : (float)(stack.getMaxItemUseDuration() - entityIn.getItemInUseCount()) / maxCharge;
}
}
});
}
@Override
public boolean getIsRepairable(ItemStack toRepair, ItemStack repair) {
return repair.isItemEqual(new ItemStack(Items.BONE)) ? true : super.getIsRepairable(toRepair, repair);
}
@Override
public void onUsingTick(ItemStack stack, EntityLivingBase player, int count) {
int ticks = this.getMaxItemUseDuration(stack) - count;
if (ticks >= POWERED_CHARGE_TIME && RechargeHelper.getCharge(stack) > 0) {
player.stopActiveHand();
}
}
public static float getArrowVelocity(ItemStack stack, int charge) {
float maxCharge = (RechargeHelper.getCharge(stack) > 0) ? (float)POWERED_CHARGE_TIME : (float)UNPOWERED_CHARGE_TIME;
float f = (float)charge / maxCharge;
f = (f * f + f * 2.0F) / 3.0F;
if (f > 1.0F) {
f = 1.0F;
}
return f;
}
protected ItemStack findAmmo(EntityPlayer player) {
if (this.isArrow(player.getHeldItemOffhand())) {
return player.getHeldItemOffhand();
} else if (this.isArrow(player.getHeldItemMainhand())) {
return player.getHeldItemMainhand();
} else {
for (int i = 0; i < player.inventory.getSizeInventory(); i++) {
ItemStack itemstack = player.inventory.getStackInSlot(i);
if (this.isArrow(itemstack)) {
return itemstack;
}
}
return ItemStack.EMPTY;
}
}
@Override
public void onPlayerStoppedUsing(ItemStack stack, World worldIn, EntityLivingBase entityLiving, int timeLeft) {
if (entityLiving instanceof EntityPlayer) {
EntityPlayer entityplayer = (EntityPlayer)entityLiving;
boolean flag = entityplayer.capabilities.isCreativeMode || EnchantmentHelper.getEnchantmentLevel(Enchantments.INFINITY, stack) > 0;
ItemStack itemstack = this.findAmmo(entityplayer);
int charge = this.getMaxItemUseDuration(stack) - timeLeft;
charge = net.minecraftforge.event.ForgeEventFactory.onArrowLoose(stack, worldIn, entityplayer, charge, !itemstack.isEmpty() || flag);
if (charge < 0) {
return;
}
if (!itemstack.isEmpty() || flag) {
if (itemstack.isEmpty()) {
itemstack = new ItemStack(Items.ARROW);
}
float velocity = getArrowVelocity(stack, charge);
if ((double)velocity >= 0.1D) {
boolean flag1 = entityplayer.capabilities.isCreativeMode || (itemstack.getItem() instanceof ItemArrow && ((ItemArrow) itemstack.getItem()).isInfinite(itemstack, stack, entityplayer));
if (!worldIn.isRemote) {
ItemArrow itemarrow = (ItemArrow)(itemstack.getItem() instanceof ItemArrow ? itemstack.getItem() : Items.ARROW);
EntityArrow entityarrow = itemarrow.createArrow(worldIn, itemstack, entityplayer);
float velocityMultiplier = (RechargeHelper.getCharge(stack) > 0) ? 4.0F : 3.0F;
entityarrow.shoot(entityplayer, entityplayer.rotationPitch, entityplayer.rotationYaw, 0.0F, velocity * velocityMultiplier, 1.0F);
RechargeHelper.consumeCharge(stack, entityplayer, 1);
if (velocity == 1.0F) {
entityarrow.setIsCritical(true);
}
int powerLevels = EnchantmentHelper.getEnchantmentLevel(Enchantments.POWER, stack);
if (powerLevels > 0) {
entityarrow.setDamage(entityarrow.getDamage() + (double)powerLevels * 0.5D + 0.5D);
}
int punchLevels = EnchantmentHelper.getEnchantmentLevel(Enchantments.PUNCH, stack);
if (punchLevels > 0) {
entityarrow.setKnockbackStrength(punchLevels);
}
if (EnchantmentHelper.getEnchantmentLevel(Enchantments.FLAME, stack) > 0) {
entityarrow.setFire(100);
}
stack.damageItem(1, entityplayer);
if (flag1 || entityplayer.capabilities.isCreativeMode && (itemstack.getItem() == Items.SPECTRAL_ARROW || itemstack.getItem() == Items.TIPPED_ARROW)) {
entityarrow.pickupStatus = EntityArrow.PickupStatus.CREATIVE_ONLY;
}
worldIn.spawnEntity(entityarrow);
}
worldIn.playSound((EntityPlayer)null, entityplayer.posX, entityplayer.posY, entityplayer.posZ, SoundEvents.ENTITY_ARROW_SHOOT, SoundCategory.PLAYERS, 1.0F, 1.0F / (itemRand.nextFloat() * 0.4F + 1.2F) + velocity * 0.5F);
if (!flag1 && !entityplayer.capabilities.isCreativeMode) {
itemstack.shrink(1);
if (itemstack.isEmpty()) {
entityplayer.inventory.deleteStack(itemstack);
}
}
}
}
}
}
@Override
public int getMaxCharge(ItemStack stack, EntityLivingBase player) {
return VIS_CAPACITY;
}
@Override
public EnumChargeDisplay showInHud(ItemStack stack, EntityLivingBase player) {
return IRechargable.EnumChargeDisplay.NORMAL;
}
@Override
public boolean shouldCauseReequipAnimation(ItemStack oldStack, ItemStack newStack, boolean slotChanged) {
if (oldStack.getItem() == newStack.getItem() && !slotChanged) {
// Suppress the re-equip animation if only the NBT data has changed
return false;
} else {
return super.shouldCauseReequipAnimation(oldStack, newStack, slotChanged);
}
}
}
| 46.329545 | 239 | 0.617366 |
bb12989f5d6e597cb2ccf3f4d02b6e5ca72be0bc | 3,390 | /*
* 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.aevi.sdk.flow.models;
import java.util.ArrayList;
import java.util.List;
/**
* A utility class specifically to deal with combined receipt printing data that may be passed between applications.
*
*/
public class CombinedReceiptData {
public static final String DATA_KEY_COMBINED_RECEIPT = "combinedReceiptData";
public static final String POSITION_BASKET = "BASKET";
public static final String POSITION_HEADER = "HEADER";
public static final String POSITION_FOOTER = "FOOTER";
public static final String RECEIPT_TYPE_ALL = "ALL";
public static final String RECEIPT_TYPE_CUSTOMER = "CUSTOMER";
public static final String RECEIPT_TYPE_MERCHANT = "MERCHANT";
public static final String PAYMENT_STATUS_ALL = "ALL";
public static final String PAYMENT_STATUS_SUCCESS = "SUCCESS";
public static final String PAYMENT_STATUS_FAILURE = "FAILURE";
private List<ReceiptPayload> payloadList = new ArrayList<>();
public void addPayload(ReceiptPayload payload) {
payloadList.add(payload);
}
/**
* Returns all the payloads for this receipt data
*
* @return List of {@link ReceiptPayload} objects
*/
public List<ReceiptPayload> getPayloadList() {
return payloadList;
}
/**
* Each print payload is mapped to a single instance of this class
*
* The position, receiptType and paymentStatus can be used to determine which receipt to use the printData for and where the data corresponds to
*
*/
public static class ReceiptPayload {
private String position;
private String receiptType;
private String paymentStatus;
private String printData;
public ReceiptPayload(String position, String receiptType, String paymentStatus, String printData) {
this.receiptType = receiptType;
this.paymentStatus = paymentStatus;
this.position = position;
this.printData = printData;
}
/**
* @return The receipt type this print payload should be used for e.g. CUSTOMER or MERCHANT
*/
public String getReceiptType() {
return receiptType;
}
/**
* @return The payment status this print payload should be used for e.g. SUCCESS or FAILURE
*/
public String getPaymentStatus() {
return paymentStatus;
}
/**
* @return The position this print payload should appear in e.g. BASKET, HEADER or FOOTER
*/
public String getPosition() {
return position;
}
/**
* @return The print payload in JSON format use the AEVI print-api to deserialize
*/
public String getPrintData() {
return printData;
}
}
}
| 32.285714 | 148 | 0.667257 |
1a9034a9b50283c9a453a05413ef5c7b56d817de | 478 | package file;
import java.io.File;
import java.util.Scanner;
public class CaminhoFile {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a file path: ");
String strPath = sc.nextLine();
File path = new File(strPath);
System.out.println("getName: " + path.getName());
System.out.println("getParent: " + path.getParent());
System.out.println("getPath: " + path.getPath());
sc.close();
}
}
| 18.384615 | 55 | 0.654812 |
4dfd74ac42a8952a731c0934f93c88ce073e72dd | 6,399 | package com.project.sam.guguchat;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;
import de.hdodenhof.circleimageview.CircleImageView;
/**
* A simple {@link Fragment} subclass.
*/
public class ChatFragment extends Fragment {
private RecyclerView myChatList;
private View myChatView;
private DatabaseReference mFriendsDatabase;
private DatabaseReference mUsersDatabase;
private FirebaseAuth mAuth;
private String mCurrent_user_id;
public ChatFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
myChatView = inflater.inflate(R.layout.fragment_chat, container, false);
myChatList = (RecyclerView) myChatView.findViewById(R.id.chats_list);
mAuth = FirebaseAuth.getInstance();
mCurrent_user_id = mAuth.getCurrentUser().getUid();
mFriendsDatabase = FirebaseDatabase.getInstance().getReference().child("Friends").child(mCurrent_user_id);
mUsersDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
mUsersDatabase.keepSynced(true);
myChatList.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
myChatList.setLayoutManager(linearLayoutManager);
return myChatView;
}
@Override
public void onStart() {
super.onStart();
FirebaseRecyclerAdapter<Chats, ChatFragment.ChatsViewHolder> friendRecyclerViewAdapter =
new FirebaseRecyclerAdapter<Chats, ChatsViewHolder>(
Chats.class,
R.layout.user_single,
ChatFragment.ChatsViewHolder.class,
mFriendsDatabase
) {
@Override
protected void populateViewHolder(final ChatFragment.ChatsViewHolder friendsViewHolder, Chats friends, int position) {
//friendsViewHolder.setDate(friends.getDate());//changet to model
// renable to add date
//can be changed to set date
final String list_user_id = getRef(position).getKey();
mUsersDatabase.child(list_user_id).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
final String userName = dataSnapshot.child("name").getValue().toString(); //get username from db
String userThumb = dataSnapshot.child("thumb_image").getValue().toString();
String userStatus = dataSnapshot.child("status").getValue().toString(); // adding status to friends list
if (dataSnapshot.hasChild("online")){
String userOnline = dataSnapshot.child("online").getValue().toString();
friendsViewHolder.setUserOnline(userOnline);
}
friendsViewHolder.setName(userName);
friendsViewHolder.setUserImage(userThumb, getContext());
friendsViewHolder.userStatus(userStatus);
friendsViewHolder.mView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent ChatIntent = new Intent(getContext() , ChatActivity.class);
ChatIntent.putExtra("user_id", list_user_id);
ChatIntent.putExtra("user_name",userName);
startActivity(ChatIntent);
}
});
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
};
myChatList.setAdapter(friendRecyclerViewAdapter);
}
public static class ChatsViewHolder extends RecyclerView.ViewHolder {
View mView;
public ChatsViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
/// i changed from setdate to userStatus
public void userStatus(String userStatus) {
TextView userStatusView = (TextView) mView.findViewById(R.id.usr_single_status);
userStatusView.setText(userStatus);
}
public void setName(String name) {
TextView userNameView = (TextView) mView.findViewById(R.id.user_single_name);
userNameView.setText(name);
}
public void setUserImage(String thumb_image, Context ctx) {
CircleImageView userImageView = (CircleImageView) mView.findViewById(R.id.user_single_image);
Picasso.with(ctx).load(thumb_image).placeholder(R.drawable.default_avatar).into(userImageView);
}
public void setUserOnline(String online_status) {
//test to change icon color
ImageView userOnlineView = (ImageView) mView.findViewById(R.id.user_online);
if (online_status.equals("true")) {
userOnlineView.setVisibility(View.VISIBLE);
} else {
userOnlineView.setVisibility(View.INVISIBLE);
}
}
}
}
| 31.214634 | 130 | 0.633536 |
37dbb24365e28edeef76b5d27968eccd3904e4a1 | 1,558 | /**
* Copyright 2014 fastnsilver.io
*
* 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 io.fns.calculator.config;
import io.fns.calculator.filter.CORSFilter;
import java.io.IOException;
import java.util.Properties;
import org.springframework.boot.yaml.YamlPropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
/**
* {@link CORSFilter}'s configuration.
*
* @author Chris Phillipson
*
*/
@Configuration
public class CORSConfig {
/**
* Factory for converting <code>application.yml</code> on classpath to
* {@link Properties}.
*/
@Bean
public YamlPropertiesFactoryBean yamlProperties() throws IOException {
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
YamlPropertiesFactoryBean bean = new YamlPropertiesFactoryBean();
bean.setResources(resolver.getResources("classpath:application.yml"));
return bean;
}
}
| 31.16 | 91 | 0.774711 |
4bc349a58ead9045c9041a9e557bf75dffc02542 | 350 | package org.hamgen.testdata;
import javax.xml.bind.annotation.XmlType;
/**
* DO NOT CHANGE THIS CLASS! it will brake MatcherBuildTest
*/
@XmlType
public final class MatcherBuilderTestDataSomething {
public MatcherBuilderTestDataSomethingElse getSomethingElse() {
return new MatcherBuilderTestDataSomethingElse();
}
}
| 25 | 68 | 0.745714 |
be7138d29f94cdca57bfbbb2572b28feb9310269 | 1,717 | package Lists;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
public class CardsGame {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
List<Integer> player1 = Arrays.stream(input.nextLine().split(" ")).map(e -> Integer.parseInt(e)).collect(Collectors.toList());
List<Integer> player2 = Arrays.stream(input.nextLine().split(" ")).map(e -> Integer.parseInt(e)).collect(Collectors.toList());
while(player1.size() > 0 && player2.size() > 0){
if(player1.get(0).equals(player2.get(0))){
player1.remove(0);
player2.remove(0);
}
else if(player1.get(0) > player2.get(0)){
player1.add(player1.get(0));
player1.remove(0);
player1.add(player2.get(0));
player2.remove(0);
}
else if(player1.get(0) < player2.get(0)){
player2.add(player2.get(0));
player2.remove(0);
player2.add(player1.get(0));
player1.remove(0);
}
}
int sum = 0;
if(player1.size() > player2.size()){
for(int a = 0; a < player1.size(); a++){
sum += player1.get(a);
}
System.out.printf("First player wins! Sum: %d", sum);
}
else{
for(int b = 0; b < player2.size(); b++){
sum += player2.get(b);
}
System.out.printf("Second player wins! Sum: %d", sum);
}
}
}
//Земених player1.get(0) == player2.get(0) с player1.get(0).equals(player2.get(0))
| 33.019231 | 134 | 0.514851 |
ee3f21ee84fc96cc5b4fb38db6749dc2290cca9f | 35 | public class LogicalTreeNode {
}
| 8.75 | 30 | 0.742857 |
846ca2a10ea810fc3611e22fac7ee2720662b125 | 926 | package co.yixiang.modules.shop.web.vo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* <p>
* 病种 查询结果对象
* </p>
*
* @author visazhou
* @date 2020-06-03
*/
@Data
@ApiModel(value="YxStoreDiseaseQueryVo对象", description="病种查询参数")
public class YxStoreDiseaseQueryVo implements Serializable{
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "商品分类表ID")
private Integer id;
@ApiModelProperty(value = "父id")
private Integer pid;
@ApiModelProperty(value = "病种名称")
private String cateName;
@ApiModelProperty(value = "排序")
private Integer sort;
@ApiModelProperty(value = "图标")
private String pic;
@ApiModelProperty(value = "是否推荐")
private Boolean isShow;
@ApiModelProperty(value = "添加时间")
private Integer addTime;
@ApiModelProperty(value = "删除状态")
private Boolean isDel;
} | 19.702128 | 64 | 0.75486 |
a38febdccb220d2b4ef4f2c218324bdc0f11bf2a | 341 | package com.clsaa.maat.constant.state;
/**
* <p>
* 被动方业务完成后调用maat平台确认消息已被成功消费(消息状态转变为已完成)
* 不可转变为任何其他状态
* </p>
*
* @author 任贵杰 [email protected]
* @summary 已完成状态
* @since 2018-09-01
*/
public class FinishedState extends AbstractState {
@Override
boolean doValidateState(MessageState stateTo) {
return false;
}
}
| 17.947368 | 51 | 0.683284 |
1e1cfa54543fed091b5b0a9c58730832f23b3c76 | 16,348 | /*
* Copyright 1999-2002,2004,2005 The Apache Software Foundation.
*
* 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.apache.xerces.dom;
import org.apache.xerces.xs.XSSimpleTypeDefinition;
import org.apache.xerces.xs.XSTypeDefinition;
import org.apache.xerces.impl.dv.xs.XSSimpleTypeDecl;
import org.apache.xerces.impl.xs.XSComplexTypeDecl;
import org.apache.xerces.util.URI;
import org.apache.xerces.xni.NamespaceContext;
import org.w3c.dom.Attr;
import org.w3c.dom.DOMException;
/**
* ElementNSImpl inherits from ElementImpl and adds namespace support.
* <P>
* The qualified name is the node name, and we store localName which is also
* used in all queries. On the other hand we recompute the prefix when
* necessary.
*
* @xerces.internal
*
* @author Elena litani, IBM
* @author Neeraj Bajaj, Sun Microsystems
* @version $Id: ElementNSImpl.java,v 1.48 2005/05/10 15:36:42 ankitp Exp $
*/
public class ElementNSImpl
extends ElementImpl {
//
// Constants
//
/** Serialization version. */
static final long serialVersionUID = -9142310625494392642L;
static final String xmlURI = "http://www.w3.org/XML/1998/namespace";
//
// Data
//
/** DOM2: Namespace URI. */
protected String namespaceURI;
/** DOM2: localName. */
protected String localName;
/** DOM3: type information */
// REVISIT: we are losing the type information in DOM during serialization
transient XSTypeDefinition type;
protected ElementNSImpl() {
super();
}
/**
* DOM2: Constructor for Namespace implementation.
*/
protected ElementNSImpl(CoreDocumentImpl ownerDocument,
String namespaceURI,
String qualifiedName)
throws DOMException
{
super(ownerDocument, qualifiedName);
setName(namespaceURI, qualifiedName);
}
private void setName(String namespaceURI, String qname) {
String prefix;
// DOM Level 3: namespace URI is never empty string.
this.namespaceURI = namespaceURI;
if (namespaceURI != null) {
//convert the empty string to 'null'
this.namespaceURI = (namespaceURI.length() == 0) ? null : namespaceURI;
}
int colon1, colon2 ;
//NAMESPACE_ERR:
//1. if the qualified name is 'null' it is malformed.
//2. or if the qualifiedName is null and the namespaceURI is different from null,
// We dont need to check for namespaceURI != null, if qualified name is null throw DOMException.
if(qname == null){
String msg =
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"NAMESPACE_ERR",
null);
throw new DOMException(DOMException.NAMESPACE_ERR, msg);
}
else{
colon1 = qname.indexOf(':');
colon2 = qname.lastIndexOf(':');
}
ownerDocument.checkNamespaceWF(qname, colon1, colon2);
if (colon1 < 0) {
// there is no prefix
localName = qname;
if (ownerDocument.errorChecking) {
ownerDocument.checkQName(null, localName);
if (qname.equals("xmlns")
&& (namespaceURI == null
|| !namespaceURI.equals(NamespaceContext.XMLNS_URI))
|| (namespaceURI!=null && namespaceURI.equals(NamespaceContext.XMLNS_URI)
&& !qname.equals("xmlns"))) {
String msg =
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"NAMESPACE_ERR",
null);
throw new DOMException(DOMException.NAMESPACE_ERR, msg);
}
}
}//there is a prefix
else {
prefix = qname.substring(0, colon1);
localName = qname.substring(colon2 + 1);
//NAMESPACE_ERR:
//1. if the qualifiedName has a prefix and the namespaceURI is null,
//2. or if the qualifiedName has a prefix that is "xml" and the namespaceURI
//is different from " http://www.w3.org/XML/1998/namespace"
if (ownerDocument.errorChecking) {
if( namespaceURI == null || ( prefix.equals("xml") && !namespaceURI.equals(NamespaceContext.XML_URI) )){
String msg =
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"NAMESPACE_ERR",
null);
throw new DOMException(DOMException.NAMESPACE_ERR, msg);
}
ownerDocument.checkQName(prefix, localName);
ownerDocument.checkDOMNSErr(prefix, namespaceURI);
}
}
}
// when local name is known
protected ElementNSImpl(CoreDocumentImpl ownerDocument,
String namespaceURI, String qualifiedName,
String localName)
throws DOMException
{
super(ownerDocument, qualifiedName);
this.localName = localName;
this.namespaceURI = namespaceURI;
}
// for DeferredElementImpl
protected ElementNSImpl(CoreDocumentImpl ownerDocument,
String value) {
super(ownerDocument, value);
}
// Support for DOM Level 3 renameNode method.
// Note: This only deals with part of the pb. CoreDocumentImpl
// does all the work.
void rename(String namespaceURI, String qualifiedName)
{
if (needsSyncData()) {
synchronizeData();
}
this.name = qualifiedName;
setName(namespaceURI, qualifiedName);
reconcileDefaultAttributes();
}
/**
* NON-DOM: resets this node and sets specified values for the node
*
* @param ownerDocument
* @param namespaceURI
* @param qualifiedName
* @param localName
*/
protected void setValues (CoreDocumentImpl ownerDocument,
String namespaceURI, String qualifiedName,
String localName){
// remove children first
firstChild = null;
previousSibling = null;
nextSibling = null;
fNodeListCache = null;
// set owner document
attributes = null;
super.flags = 0;
setOwnerDocument(ownerDocument);
// synchronizeData will initialize attributes
needsSyncData(true);
super.name = qualifiedName;
this.localName = localName;
this.namespaceURI = namespaceURI;
}
//
// Node methods
//
//
//DOM2: Namespace methods.
//
/**
* Introduced in DOM Level 2. <p>
*
* The namespace URI of this node, or null if it is unspecified.<p>
*
* This is not a computed value that is the result of a namespace lookup based on
* an examination of the namespace declarations in scope. It is merely the
* namespace URI given at creation time.<p>
*
* For nodes created with a DOM Level 1 method, such as createElement
* from the Document interface, this is null.
* @since WD-DOM-Level-2-19990923
*/
public String getNamespaceURI()
{
if (needsSyncData()) {
synchronizeData();
}
return namespaceURI;
}
/**
* Introduced in DOM Level 2. <p>
*
* The namespace prefix of this node, or null if it is unspecified. <p>
*
* For nodes created with a DOM Level 1 method, such as createElement
* from the Document interface, this is null. <p>
*
* @since WD-DOM-Level-2-19990923
*/
public String getPrefix()
{
if (needsSyncData()) {
synchronizeData();
}
int index = name.indexOf(':');
return index < 0 ? null : name.substring(0, index);
}
/**
* Introduced in DOM Level 2. <p>
*
* Note that setting this attribute changes the nodeName attribute, which holds the
* qualified name, as well as the tagName and name attributes of the Element
* and Attr interfaces, when applicable.<p>
*
* @param prefix The namespace prefix of this node, or null(empty string) if it is unspecified.
*
* @exception INVALID_CHARACTER_ERR
* Raised if the specified
* prefix contains an invalid character.
* @exception DOMException
* @since WD-DOM-Level-2-19990923
*/
public void setPrefix(String prefix)
throws DOMException
{
if (needsSyncData()) {
synchronizeData();
}
if (ownerDocument.errorChecking) {
if (isReadOnly()) {
String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NO_MODIFICATION_ALLOWED_ERR", null);
throw new DOMException(
DOMException.NO_MODIFICATION_ALLOWED_ERR,
msg);
}
if (prefix != null && prefix.length() != 0) {
if (!CoreDocumentImpl.isXMLName(prefix,ownerDocument.isXML11Version())) {
String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "INVALID_CHARACTER_ERR", null);
throw new DOMException(DOMException.INVALID_CHARACTER_ERR, msg);
}
if (namespaceURI == null || prefix.indexOf(':') >=0) {
String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NAMESPACE_ERR", null);
throw new DOMException(DOMException.NAMESPACE_ERR, msg);
} else if (prefix.equals("xml")) {
if (!namespaceURI.equals(xmlURI)) {
String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NAMESPACE_ERR", null);
throw new DOMException(DOMException.NAMESPACE_ERR, msg);
}
}
}
}
// update node name with new qualifiedName
if (prefix !=null && prefix.length() != 0) {
name = prefix + ":" + localName;
}
else {
name = localName;
}
}
/**
* Introduced in DOM Level 2. <p>
*
* Returns the local part of the qualified name of this node.
* @since WD-DOM-Level-2-19990923
*/
public String getLocalName()
{
if (needsSyncData()) {
synchronizeData();
}
return localName;
}
/**
* DOM Level 3 WD - Experimental.
* Retrieve baseURI
*/
public String getBaseURI() {
if (needsSyncData()) {
synchronizeData();
}
// Absolute base URI is computed according to XML Base (http://www.w3.org/TR/xmlbase/#granularity)
// 1. the base URI specified by an xml:base attribute on the element, if one exists
if (attributes != null) {
Attr attrNode = (Attr)attributes.getNamedItemNS("http://www.w3.org/XML/1998/namespace", "base");
if (attrNode != null) {
String uri = attrNode.getNodeValue();
if (uri.length() != 0 ) {// attribute value is always empty string
try {
uri = new URI(uri).toString();
}
catch (org.apache.xerces.util.URI.MalformedURIException e) {
// This may be a relative URI.
// Start from the base URI of the parent, or if this node has no parent, the owner node.
NodeImpl parentOrOwner = (parentNode() != null) ? parentNode() : ownerNode;
// Make any parentURI into a URI object to use with the URI(URI, String) constructor.
String parentBaseURI = (parentOrOwner != null) ? parentOrOwner.getBaseURI() : null;
if (parentBaseURI != null) {
try {
uri = new URI(new URI(parentBaseURI), uri).toString();
}
catch (org.apache.xerces.util.URI.MalformedURIException ex){
// This should never happen: parent should have checked the URI and returned null if invalid.
return null;
}
return uri;
}
// REVISIT: what should happen in this case?
return null;
}
return uri;
}
}
}
//2.the base URI of the element's parent element within the document or external entity,
//if one exists
String parentElementBaseURI = (this.parentNode() != null) ? this.parentNode().getBaseURI() : null ;
//base URI of parent element is not null
if(parentElementBaseURI != null){
try {
//return valid absolute base URI
return new URI(parentElementBaseURI).toString();
}
catch (org.apache.xerces.util.URI.MalformedURIException e){
// REVISIT: what should happen in this case?
return null;
}
}
//3. the base URI of the document entity or external entity containing the element
String baseURI = (this.ownerNode != null) ? this.ownerNode.getBaseURI() : null ;
if(baseURI != null){
try {
//return valid absolute base URI
return new URI(baseURI).toString();
}
catch (org.apache.xerces.util.URI.MalformedURIException e){
// REVISIT: what should happen in this case?
return null;
}
}
return null;
}
/**
* @see org.w3c.dom.TypeInfo#getTypeName()
*/
public String getTypeName() {
if (type !=null){
if (type instanceof XSSimpleTypeDefinition) {
return ((XSSimpleTypeDecl) type).getTypeName();
} else {
return ((XSComplexTypeDecl) type).getTypeName();
}
}
return null;
}
/**
* @see org.w3c.dom.TypeInfo#getTypeNamespace()
*/
public String getTypeNamespace() {
if (type !=null){
return type.getNamespace();
}
return null;
}
/**
* Introduced in DOM Level 2. <p>
* Checks if a type is derived from another by restriction. See:
* http://www.w3.org/TR/DOM-Level-3-Core/core.html#TypeInfo-isDerivedFrom
*
* @param ancestorNS
* The namspace of the ancestor type declaration
* @param ancestorName
* The name of the ancestor type declaration
* @param type
* The reference type definition
*
* @return boolean True if the type is derived by restriciton for the
* reference type
*/
public boolean isDerivedFrom(String typeNamespaceArg, String typeNameArg,
int derivationMethod) {
if(needsSyncData()) {
synchronizeData();
}
if (type != null) {
if (type instanceof XSSimpleTypeDefinition) {
return ((XSSimpleTypeDecl) type).isDOMDerivedFrom(
typeNamespaceArg, typeNameArg, derivationMethod);
} else {
return ((XSComplexTypeDecl) type).isDOMDerivedFrom(
typeNamespaceArg, typeNameArg, derivationMethod);
}
}
return false;
}
/**
* NON-DOM: setting type used by the DOM parser
* @see NodeImpl#setReadOnly
*/
public void setType(XSTypeDefinition type) {
this.type = type;
}
}
| 33.63786 | 132 | 0.573403 |
80ced716dea59c19fb56b8379778222ea741d183 | 836 | package ExamPrep4.colonists.medics;
public class Surgeon extends Medic {
private static final int CLASS_BONUS = 2;
public Surgeon(String id, String familyId, int talent, int age, String sign) {
super(id, familyId, talent, age, sign);
}
@Override
public int getPotential() {
int ageBonus = 0;
int signBonus = 0;
if (super.getAge()>25 && super.getAge() < 35){
ageBonus = 2;
}
switch (super.getSign()){
case "precise":
signBonus = 3;
break;
case "butcher":
signBonus = -3;
break;
}
int totalBonus = this.CLASS_BONUS + ageBonus + signBonus + super.getTalent();
return totalBonus;
}
@Override
public void grow(int years) {
}
}
| 23.885714 | 85 | 0.535885 |
b5297907e1cb8fb9c77e14c388c7a1f1aa82e2ba | 2,708 | /**
* @author qybit
* @create 2020-12-03 16:14
*/
public class MagicDictionary1 {
static class Trie {
static class TrieNode {
boolean isEnd;
TrieNode[] next = new TrieNode[26];
}
TrieNode root;
public Trie() {
root = new TrieNode();
}
public void insert(String s) {
TrieNode node = root;
for (char c : s.toCharArray()) {
if (node.next[c-'a'] == null) {
node.next[c-'a'] = new TrieNode();
}
node = node.next[c-'a'];
}
node.isEnd = true;
}
public boolean search(String s) {
// TrieNode node = root;
// for (char c: s.toCharArray()) {
// node = node.next[c-'a'];
// if (node == null) {
// return false;
// }
// }
// return node.isEnd;
return search(s, 0, 1, root);
}
/**
*
* @param word 待查单词
* @param index 索引
* @param num 修改与否,改或者不改
* @param root 根节点
* @return
*/
private boolean search(String word, int index, int num, TrieNode root) {
if (num < 0) return false;
if (index == word.length()) return num==0&&root.isEnd;
char ch = word.charAt(index);
int idx = ch - 'a';
for (int i = 0; i < 26; i++) {
if (root.next[i] ==null) continue;
if (index == i) {
//不改
if (search(word, index + 1, num, root.next[idx])) return true;
// 改了
else if (search(word, index +1 , num-1, root.next[i])) return true;
}
}
return false;
}
}
Trie trie = new Trie();
/**
* Initialize your data structure here.
*/
public MagicDictionary1() {
}
public void buildDict(String[] dictionary) {
for (String word : dictionary) {
trie.insert(word);
}
}
public boolean search(String searchWord) {
return trie.search(searchWord);
}
/*'8
public boolean search(String searchWord) {
char[] array = searchWord.toCharArray();
for (int i = 0; i < searchWord.length(); i++) {
char c = searchWord.charAt(i);
for (char k = 'a'; k < 'z'; k++) {
if (c == k) continue;
array[i] = k;
if (trie.search(String.valueOf(array))) return true;
}
array[i] = c;
}
return false;
}*/
}
| 26.54902 | 87 | 0.430576 |
0ca41388e827763bfc727d8f40c54e68fb497ec7 | 2,554 | /**
* Copyright "TBD", Metron Aviation & CSSI. All rights reserved.
*
* This computer Software was developed with the sponsorship of the U.S. Government
* under Contract No. DTFAWA-10-D-00033, which has a copyright license in accordance with AMS 3.5-13.(c)(1).
*/
package gov.faa.ang.swac.datalayer.storage.db;
import java.sql.ResultSet;
import java.util.List;
import gov.faa.ang.swac.datalayer.DataAccessException;
import gov.faa.ang.swac.datalayer.storage.DataMarshaller;
import java.sql.Connection;
// TODO: use of generics needs a tune up...specifically, methods like selectAll that don't take T as a parameter have unchecked type erasure
public interface DataAccessObject<T> extends DataMarshaller {
/**
* Returns a result set based on an arbitrary list of parameters
* @param <T>
* @param params
* @return
*/
public List<T> select(Object... params) throws DataAccessException;
/**
* Returns all records
* @param <T>
* @return
* @throws DataAccessException
*/
public List<T> selectAll() throws DataAccessException;
/**
* Inserts one record
* @param <T>
* @param record
* @return uniqueId, if any
*/
public int insert(T record) throws DataAccessException;
/**
* Inserts all records in the list
* @param <T>
* @param records
* @return number of records inserted
*/
public int insertAll(List<T> records) throws DataAccessException;
/**
* Updates a single record. It is assumed that the record has some sort of unique identification to locate the record to be updated
* @param <T>
* @param record
* @return true if a record was actually updated
*/
public boolean update(T record) throws DataAccessException;
/**
* Deletes the given record, if found
* @param <T>
* @param record
* @return true if a record was found and deleted
*/
public boolean delete(T record) throws DataAccessException;
/**
* Deletes all records
* @param <T>
* @return the number of records deleted
*/
public int deleteAll() throws DataAccessException;
/**
* Execute an arbitrary query, as defined by the specific DAO implementation. For use as a catch-all
* @param params
* @return
* @throws DataAccessException
*/
public ResultSet executeQuery(Object... params) throws DataAccessException;
/**
* Parameterized clone, used by data descriptors to clone the prototype metadata, but use a specific connection.
* @param connection
* @return
*/
public DataAccessObject<T> copy(Connection connection);
}
| 28.696629 | 140 | 0.701253 |
ef3efa90a997b02280b2311bf40d6805b8533352 | 323 | package io.itcast.cfc.dto.out;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@ToString
@Getter
@Setter
public class AdministratorListOutDTO {
private Integer administratorId;
private String username;
private String realName;
private Byte status;
private Long createTimestamp;
}
| 17.944444 | 38 | 0.767802 |
d83babcf6452caabd65f379b2c1dd6ec8e37907c | 20,394 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF 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.apache.vinci.transport.vns.service;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Random;
import java.util.StringTokenizer;
import org.apache.vinci.transport.BaseClient;
import org.apache.vinci.transport.FrameLeaf;
import org.apache.vinci.transport.KeyValuePair;
import org.apache.vinci.transport.QueryableFrame;
import org.apache.vinci.transport.Transportable;
import org.apache.vinci.transport.VinciFrame;
import org.apache.vinci.transport.context.VinciContext;
import org.apache.vinci.transport.vns.VNSConstants;
/**
* Provides a command-line interface for querying VNS.
*/
public class NameClient {
String vnsHost;
int vnsPort = 9000;
static class HitsList {
public HitsList() {
}
String[] types;
int[] hits;
int totalhits;
//IC see: https://issues.apache.org/jira/browse/UIMA-48
String starttime;
};
static Random R = new Random();
public NameClient() {
configure(VinciContext.getGlobalContext().getVNSHost(), VinciContext.getGlobalContext()
.getVNSPort());
}
public NameClient(String host, int port) {
configure(host, port);
}
// Configure the VNS host / port
public void configure(String host, int port) {
if (host != null) {
vnsHost = host;
}
if (port > -1) {
vnsPort = port;
}
}
// Method to parse a fully qualified name into sub-parts
public static ServiceInfo parseQName(String qname) {
String[] result = new String[5];
int i = qname.indexOf("/");
if (i > -1)
result[0] = qname.substring(0, i);
i++;
qname = qname.substring(i);
i = qname.indexOf("[");
String lhi;
if (i > -1) {
lhi = qname.substring(i + 1, qname.length() - 1);
StringTokenizer str = new StringTokenizer(lhi, ",");
int j = 2;
while (str.hasMoreTokens())
result[j++] = str.nextToken().trim();
} else
i = qname.length();
result[1] = qname.substring(0, i);
return new ServiceInfo(result);
}
// Methods to perform service lookup
public ServiceInfo[] lookup(String name, int level, String host, String instance, String ws) {
VinciFrame req = new VinciFrame();
//IC see: https://issues.apache.org/jira/browse/UIMA-48
req.fadd("vinci:COMMAND", VNSConstants.RESOLVE_COMMAND).fadd("SERVICE", name).fadd("LEVEL",
level).fadd("HOST", host).fadd("INSTANCE", instance).fadd("WORKSPACE", ws);
System.out.println(req.toXML());
VinciFrame resp = (VinciFrame) transmit(req);
checkError(resp);
return constructServiceInfo(resp.fget("SERVER"), resp.fgetString("LEVEL"), name);
}
public ServiceInfo[] lookup(String name) {
return lookup(name, -1, null, null, null);
}
public ServiceInfo[] lookup(String name, int level) {
return lookup(name, level, null, null, null);
}
public ServiceInfo[] lookup(String name, int level, String host) {
return lookup(name, level, host, null, null);
}
public ServiceInfo[] lookup(String name, int level, String host, String instance) {
return lookup(name, level, host, instance, null);
}
public ServiceInfo[] lookup(String name, String host) {
return lookup(name, -1, host, null, null);
}
public ServiceInfo[] lookup(String name, String host, String instance) {
return lookup(name, -1, host, instance, null);
}
public ServiceInfo[] lookup(String name, String host, String instance, String ws) {
return lookup(name, -1, host, instance, ws);
}
// Method to perform service resolve
public ServiceInfo resolve(String name, String host, String ip, String ws, int level, int inst) {
VinciFrame req = new VinciFrame();
req.fadd("vinci:COMMAND", VNSConstants.RESOLVE_COMMAND).fadd("SERVICE", name);
smFrameAdd(req, "HOST", host);
smFrameAdd(req, "IP", ip);
smFrameAdd(req, "WORKSPACE", ws);
req.fadd("LEVEL", level);
if (inst > 0) {
req.fadd("INSTANCE", inst);
}
VinciFrame resp = (VinciFrame) transmit(req);
checkError(resp);
ServiceInfo[] S = constructServiceInfo(resp.fget("SERVER"), resp.fgetString("LEVEL"), name);
//IC see: https://issues.apache.org/jira/browse/UIMA-286
return ((S.length > 0) ? S[R.nextInt(S.length)] : null);
}
public static void smFrameAdd(VinciFrame v, String tag, String val) {
if (val != null && tag != null)
v.fadd(tag, val);
}
public ServiceInfo resolve(String name, int level) {
//IC see: https://issues.apache.org/jira/browse/UIMA-48
VinciFrame req = (VinciFrame) new VinciFrame().fadd("vinci:COMMAND",
VNSConstants.RESOLVE_COMMAND).fadd("SERVICE", name).fadd("LEVEL", level);
VinciFrame resp = (VinciFrame) transmit(req);
checkError(resp);
ServiceInfo[] S = constructServiceInfo(resp.fget("SERVER"), resp.fgetString("LEVEL"), name);
//IC see: https://issues.apache.org/jira/browse/UIMA-286
return ((S.length > 0) ? S[R.nextInt(S.length)] : null);
}
public ServiceInfo resolve(String name) {
return resolve(name, -1);
}
// Method to get the list of services that are registered
public ServiceInterface[] getList(String prefix, String level) {
VinciFrame req = new VinciFrame();
req.fadd("vinci:COMMAND", VNS.dirCmdGetList);
req.fadd("LEVEL", level);
smartAdd(req, "PREFIX", prefix);
VinciFrame resp = (VinciFrame) transmit(req);
checkError(resp);
ArrayList A = resp.fget("SERVICE");
Hashtable H;
QueryableFrame Q;
ServiceInterface[] S = new ServiceInterface[A.size()];
for (int i = 0; i < A.size(); i++) {
Q = (QueryableFrame) A.get(i);
// Check if it is a Service or a ServiceAlias and parse accordingly
if (Q.fgetString("TARGET") == null) {
H = new Hashtable();
int total = Q.getKeyValuePairCount();
KeyValuePair P = null;
for (int j = 0; j < total; j++) {
P = Q.getKeyValuePair(j);
if (P.isValueALeaf()) {
H.put(P.getKey(), P.getValueAsString());
} else {
H.put(P.getKey(), P.getValue());
}
}
S[i] = new Service(H);
} else {
S[i] = new ServiceAlias(Q.fgetString("NAME"), Q.fgetString("TARGET"));
}
}
return S;
}
public ServiceInterface[] getList(String prefix, int level) {
return getList(prefix, "" + level);
}
public ServiceInterface[] getList() {
return getList(null, -1);
}
public ServiceInterface[] getList(String prefix) {
return getList(prefix, -1);
}
public ServiceInterface[] getList(int level) {
return getList(null, level);
}
// Method to get the registered service names
public String[] getNames(String prefix, String level) {
VinciFrame req = new VinciFrame();
req.fadd("vinci:COMMAND", VNS.dirCmdGetNames);
req.fadd("LEVEL", level);
smartAdd(req, "PREFIX", prefix);
VinciFrame resp = (VinciFrame) transmit(req);
checkError(resp);
ArrayList A = resp.fget("SERVICE");
String[] S = new String[A.size()];
for (int i = 0; i < A.size(); i++) {
S[i] = ((FrameLeaf) A.get(i)).toString().trim();
}
return S;
}
public String[] getNames(String prefix, int level) {
return getNames(prefix, "" + level);
}
public String[] getNames() {
return getNames(null, -1);
}
public String[] getNames(String prefix) {
return getNames(prefix, -1);
}
public String[] getNames(int level) {
return getNames(null, level);
}
// Method to get the hits for a particular service
public int getHits(String type) {
VinciFrame out = new VinciFrame();
out.fadd("vinci:COMMAND", VNS.dirCmdGetHits);
smartAdd(out, "TYPE", type);
VinciFrame resp = (VinciFrame) transmit(out);
checkError(resp);
return (resp.fgetInt("HITS"));
}
public int getHits() {
return getHits(null);
}
// Method to get all the hits
public HitsList getAllHits() {
VinciFrame out = new VinciFrame();
out.fadd("vinci:COMMAND", VNS.dirCmdGetHits);
out.fadd("TYPE", "all");
VinciFrame resp = (VinciFrame) transmit(out);
checkError(resp);
HitsList H = new HitsList();
H.totalhits = resp.fgetInt("TOTAL");
H.starttime = resp.fgetString("STARTED");
ArrayList A = resp.fget("HITS");
H.hits = new int[A.size()];
H.types = new String[A.size()];
QueryableFrame Q;
for (int i = 0; i < H.hits.length; i++) {
Q = (QueryableFrame) A.get(i);
H.hits[i] = Q.fgetInt("COUNT");
H.types[i] = Q.fgetString("TYPE");
}
return H;
}
// Method to delete a service
public boolean delService(Service S) {
return modifyService(S, VNS.dirCmdDelService);
}
// Method to add a service
public boolean addService(Service S) {
return modifyService(S, VNS.dirCmdAddService);
}
// Method to update a service
public boolean updateService(Service S) {
return modifyService(S, VNS.dirCmdUpdateService);
}
// Generic service interaction method
public boolean modifyService(Service S, String type) {
VinciFrame out = new VinciFrame();
out.fadd("vinci:COMMAND", type);
out.fadd("SERVICE", S.toFrame());
VinciFrame resp = (VinciFrame) transmit(out);
checkError(resp);
return (resp.fgetString("STATUS").toLowerCase().trim().equals("ok"));
}
// Method to add an alias
public boolean addAlias(String name, String target) {
return modifyAlias(VNS.dirCmdAddAlias, name, target);
}
// Method to del an alias
public boolean delAlias(String name) {
return modifyAlias(VNS.dirCmdAddAlias, name, null);
}
// Generic alias interaction method
public boolean modifyAlias(String type, String name, String target) {
VinciFrame out = new VinciFrame();
out.fadd("vinci:COMMAND", type);
VinciFrame srv = new VinciFrame();
smartAdd(srv, "NAME", name);
smartAdd(srv, "TARGET", target);
out.fadd("SERVICE", srv);
VinciFrame resp = (VinciFrame) transmit(out);
checkError(resp);
return (resp.fgetString("STATUS").toLowerCase().trim().equals("ok"));
}
// Method to find out the port to serve on
public int[] serveon(String name, String host, int level, int instance) {
if (strip(host) == null || host.trim().toLowerCase().equals("localhost")) {
try {
host = InetAddress.getLocalHost().getHostName();
} catch (Exception e) {
throw new RuntimeException("Could not resolve local host");
}
}
//IC see: https://issues.apache.org/jira/browse/UIMA-48
VinciFrame out = (VinciFrame) new VinciFrame().fadd("vinci:COMMAND",
VNSConstants.SERVEON_COMMAND).fadd("SERVICE", name).fadd("HOST", host).fadd("LEVEL",
level).fadd("INSTANCE", instance);
VinciFrame resp = (VinciFrame) transmit(out);
checkError(resp);
int[] result = new int[3];
result[0] = resp.fgetInt("PORT");
result[1] = resp.fgetInt("LEVEL");
result[2] = resp.fgetInt("INSTANCE");
return result;
}
public int[] serveon(String name) {
return serveon(name, null, -1, 0);
}
// Helper methods
private void smartAdd(VinciFrame req, String tag, String val) {
if (val != null)
req.fadd(tag, val);
}
private ServiceInfo[] constructServiceInfo(ArrayList A, String level, String name) {
if (level == null)
level = "-1";
ServiceInfo[] S = new ServiceInfo[A.size()];
QueryableFrame L;
for (int i = 0; i < S.length; i++) {
L = (QueryableFrame) A.get(i);
//IC see: https://issues.apache.org/jira/browse/UIMA-48
S[i] = new ServiceInfo(name, L.fgetString("HOST"), L.fgetString("PORT"), level, L
.fgetString("INSTANCE"));
}
return S;
}
private Transportable transmit(Transportable T) {
try {
return BaseClient.rpc(T, vnsHost, vnsPort);
} catch (Exception e) {
VinciFrame F = new VinciFrame();
F.fadd("vinci:ERROR", e.toString());
return F;
}
}
private void checkError(VinciFrame in) {
String s = in.fgetString("vinci:ERROR");
if (s != null)
throw new RuntimeException(s);
}
// Main method for testing
public static void main(String[] args) {
NameClient nc = new NameClient();
if (args.length > 1) {
nc.configure(args[0], Integer.parseInt(args[1]));
}
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s;
while (true) {
prMainMenu();
s = getLine(br).trim();
if (s.equals("q"))
break;
try {
switch (parseMainOption(s)) {
case 0:
handleParseQName(br, nc);
break;
case 1:
handleLookup(br, nc);
break;
case 2:
handleResolve(br, nc);
break;
case 3:
handleGetList(br, nc);
break;
case 4:
handleGetNames(br, nc);
break;
case 5:
handleGetHits(br, nc);
break;
case 6:
handleGetAllHits(br, nc);
break;
case 7:
handleServeon(br, nc);
break;
case 8:
handleAddService(br, nc);
break;
default:
pr("Unknown option");
}
} catch (RuntimeException e) {
pr("" + e);
}
}
}
private static void handleParseQName(BufferedReader br, NameClient nc) {
pr("Enter the qname to parse : ", false);
ServiceInfo S = NameClient.parseQName(getLine(br));
pr(S.toString());
}
private static void handleLookup(BufferedReader br, NameClient nc) {
pr("Enter the service name : ", false);
String name = getLine(br);
pr("Enter the level : ", false);
String level = strip(getLine(br));
int l = -1;
try {
l = Integer.parseInt(level);
} catch (Exception e) {
l = -1;
}
pr("Enter the host : ", false);
String host = strip(getLine(br));
pr("Enter the instance : ", false);
String instance = strip(getLine(br));
pr("Enter the workspace : ", false);
String ws = strip(getLine(br));
ServiceInfo[] S = nc.lookup(name, l, host, instance, ws);
for (int i = 0; i < S.length; i++)
pr("Service " + i + ":\n" + S[i]);
}
private static void handleResolve(BufferedReader br, NameClient nc) {
pr("Enter the service name : ", false);
String name = getLine(br);
pr("Enter the service host : ", false);
String host = getLine(br);
pr("Enter the service IP : ", false);
String ip = getLine(br);
pr("Enter the service workspace : ", false);
String ws = getLine(br);
pr("Enter the level : ", false);
String level = strip(getLine(br));
int l = -1;
try {
l = Integer.parseInt(level);
} catch (Exception e) {
l = -1;
}
ServiceInfo S = nc.resolve(strip(name), strip(host), strip(ip), strip(ws), l, -1);
pr("Service : \n" + S);
}
private static void handleServeon(BufferedReader br, NameClient nc) {
pr("Enter the service name : ", false);
String name = getLine(br);
pr("Enter the host : ", false);
String host = strip(getLine(br));
pr("Enter the level : ", false);
String level = strip(getLine(br));
int l = -1;
try {
l = Integer.parseInt(level);
} catch (Exception e) {
l = -1;
}
pr("Enter the instance : ", false);
String instance = strip(getLine(br));
int inst = 0;
try {
inst = Integer.parseInt(instance);
} catch (Exception e) {
inst = 0;
}
int[] temp = nc.serveon(name, host, l, inst);
pr("PORT: " + temp[0]);
}
private static void handleGetList(BufferedReader br, NameClient nc) {
pr("Enter the prefix : ", false);
String name = getLine(br);
pr("Enter the level : ", false);
String level = strip(getLine(br));
// int l = -1;
// try {
// l = Integer.parseInt(level);
// } catch (Exception e) {
// l = -1;
// }
Object[] S = nc.getList(name, level);
for (int i = 0; i < S.length; i++)
if (ServiceAlias.isAlias(S[i]))
pr("Service alias " + i + ":\n" + ((ServiceAlias) S[i]).toXML());
else
pr("Service " + i + ":\n" + ((Service) S[i]).toXML());
}
private static void handleGetNames(BufferedReader br, NameClient nc) {
pr("Enter the prefix : ", false);
String name = getLine(br);
pr("Enter the level : ", false);
String level = strip(getLine(br));
// int l = -1;
// try {
// l = Integer.parseInt(level);
// } catch (Exception e) {
// l = -1;
// }
String[] S = nc.getNames(name, level);
for (int i = 0; i < S.length; i++)
pr("Service " + i + ": " + S[i]);
}
private static void handleGetHits(BufferedReader br, NameClient nc) {
pr("Enter the type : ", false);
String type = getLine(br);
pr("Result : " + nc.getHits(type));
}
private static void handleGetAllHits(BufferedReader br, NameClient nc) {
HitsList H = nc.getAllHits();
for (int i = 0; i < H.hits.length; i++) {
pr("[" + i + "] " + H.types[i].trim() + " : " + H.hits[i]);
}
pr("Total : " + H.totalhits);
pr("Starttime : " + H.starttime);
}
private static void handleAddService(BufferedReader br, NameClient nc) {
pr("Enter the service name : ", false);
String name = getLine(br);
pr("Enter the service host : ", false);
String host = getLine(br);
pr("Enter the service level : ", false);
String level = getLine(br);
pr("Enter the service minport : ", false);
String minport = getLine(br);
pr("Enter the service maxport : ", false);
String maxport = getLine(br);
pr("Enter the service port : ", false);
String port = getLine(br);
Hashtable H = new Hashtable();
smAddHT(H, "NAME", name);
smAddHT(H, "HOST", host);
smAddHT(H, "LEVEL", level);
smAddHT(H, "MINPORT", minport);
smAddHT(H, "MAXPORT", maxport);
smAddHT(H, "PORT", port);
Service S = new Service(H);
if (nc.addService(S))
System.out.println("Successfully added service.\n" + S);
else
System.out.println("Could not add the service");
}
private static String[] options = { "parseqname", "lookup", "resolve", "getlist", "getnames",
"gethits", "getallhits", "serveon", "addservice" };
//IC see: https://issues.apache.org/jira/browse/UIMA-48
private static void prMainMenu() {
pr("\nMenu \n");
for (int i = 0; i < options.length; i++) {
pr("" + i + " : " + options[i]);
}
pr("\nq : quit\n");
pr("Enter your selection : ", false);
}
private static void smAddHT(Hashtable H, String key, String val) {
if (key != null && val != null)
H.put(key, val);
}
private static int parseMainOption(String s) {
s = s.toLowerCase().trim();
for (int i = 0; i < options.length; i++)
if (s.equals(options[i]))
return i;
try {
return Integer.parseInt(s);
} catch (Exception e) {
}
return -1;
}
public static String pr(String s) {
System.out.println(s);
return s;
}
public static String pr(String s, boolean newline) {
System.out.print(s + ((newline) ? "\n" : ""));
return s;
}
private static String strip(String s) {
if (s == null || s.trim().equals(""))
return null;
return s.trim();
}
private static String getLine(BufferedReader br) {
try {
return br.readLine();
} catch (IOException e) {
return null;
}
}
}
| 27.975309 | 99 | 0.613514 |
7e05d2c05f5526f9d2caad08388eef06c54380c5 | 4,158 | package rainbow.db.ant;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
import picocli.CommandLine.Parameters;
import rainbow.core.util.StringBuilderX;
import rainbow.core.util.Utils;
import rainbow.core.util.json.JSON;
import rainbow.db.dao.NeoBean;
import rainbow.db.dao.model.Column;
import rainbow.db.dao.model.Entity;
import rainbow.db.database.DatabaseUtils;
import rainbow.db.model.Model;
@Command(name = "dbwork")
public class DeployWork implements Runnable {
@Option(names = { "-h", "--help" }, usageHelp = true, description = "display this help message")
boolean usageHelpRequested;
@Parameters(description = "model file name")
String modelFile;
@Parameters(index = "1", description = "database type")
String database;
@Parameters(index = "2..*", description = "init data dir")
List<Path> dataDirs;
@Override
public void run() {
if (!modelFile.endsWith(".rdmx"))
throw new RuntimeException("invalide model file name");
Path m = Paths.get("..", "rainbow", "conf", "db", modelFile);
Model model = DatabaseUtils.loadModel(m);
String name = Utils.substringBefore(modelFile, ".rdmx");
Path outputDir = Paths.get("..", "dist", "db");
ModelPublisher.publish(model, outputDir.resolve(String.format("%s.md", name)));
ModelPublisher.publish(model, database, outputDir.resolve(String.format("%s_%s.sql", name, database)));
if (Utils.hasContent(dataDirs)) {
Map<String, Entity> entityMap = DatabaseUtils.resolveModel(model);
Path dataSqlfile = outputDir.resolve(String.format("%s_data.sql", name));
System.out.println("generateing preset data sql file: " + dataSqlfile.getFileName());
generatePreset(dataSqlfile, entityMap);
}
}
private void generatePreset(Path file, Map<String, Entity> entityMap) {
try (PrintWriter writer = new PrintWriter(Files.newBufferedWriter(file))) {
for (Path p : dataDirs) {
System.out.println("processing preset data under " + p.getFileName());
Files.list(p).filter(f -> f.getFileName().toString().endsWith(".json")).sorted().forEach(f -> {
String entityName = Utils.substringBefore(f.getFileName().toString(), ".json");
System.out.print("processing ");
System.out.println(entityName);
Entity entity = Objects.requireNonNull(entityMap.get(entityName));
try {
generatePresetFile(writer, f, entity);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
} catch (IOException e) {
throw new RuntimeException(e);
}
System.out.println("Done!");
}
private void generatePresetFile(PrintWriter writer, Path file, Entity entity) throws IOException {
List<String> lines = Files.readAllLines(file);
List<String> values = new ArrayList<String>();
for (String line : lines) {
if (Utils.hasContent(line) && !line.startsWith("//")) {
Map<String, Object> map = JSON.parseObject(line);
NeoBean neo = new NeoBean(entity, map);
values.clear();
StringBuilderX sql = new StringBuilderX("insert into ").append(entity.getCode()).append("(");
for (Column column : entity.getColumns()) {
Object v = neo.getObject(column);
if (v != null) {
sql.append(column.getCode());
sql.appendTempComma();
switch (column.getType()) {
case DOUBLE:
case INT:
case NUMERIC:
case LONG:
case SMALLINT:
values.add(v.toString());
break;
case BLOB:
throw new RuntimeException("not support byte");
default:
values.add("'" + v.toString() + "'");
break;
}
}
}
sql.clearTemp().append(") values(");
for (String v : values) {
sql.append(v).appendTempComma();
}
sql.clearTemp().append(");");
writer.println(sql.toString());
}
}
}
public static void main(String[] args) {
int exitCode = new CommandLine(new DeployWork()).execute(args);
System.exit(exitCode);
}
}
| 32.232558 | 105 | 0.683261 |
b1c1b5c711c2abf49768a8a5290a9d38568a4be4 | 1,176 | package ImageSmoother;
/**
* Given a 2D integer matrix M representing the gray scale of an image, you need to design a
* smoother to make the gray scale of each cell becomes the average gray scale (rounding down) of
* all the 8 surrounding cells and itself. If a cell has less than 8 surrounding cells, then use as
* many as you can.
*/
class Solution {
public int[][] imageSmoother(int[][] M) {
int rowNums = M.length;
int colNums = M[0].length;
int[][] matrix = new int[rowNums][colNums];
int[] dx = {-1, -1, -1, 0, 0, 0, 1, 1, 1};
int[] dy = {-1, 0, 1, -1, 0, 1, -1, 0, 1};
for (int i = 0; i < rowNums; i++) {
for (int j = 0; j < colNums; j++) {
int sum = 0;
int count = 0;
for (int k = 0; k < 9; k++) {
int px = i + dx[k], py = j + dy[k];
if (px >= 0 && px < rowNums && py >= 0 && py < colNums) {
sum += M[px][py];
count++;
}
}
matrix[i][j] = sum / count;
}
}
return matrix;
}
} | 32.666667 | 99 | 0.44983 |
50ac513b3db22307f7738061d8ce5bc7ba88bca0 | 1,464 | package com.artaeum.uaa.controller.utils;
import org.junit.Test;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpHeaders;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class PaginationUtilTest {
@Test
public void generatePaginationHttpHeadersTest() {
String baseUrl = "/api/example";
List<String> content = new ArrayList<>();
Page<String> page = new PageImpl<>(content, PageRequest.of(6, 50), 400L);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, baseUrl);
List<String> strHeaders = headers.get(HttpHeaders.LINK);
assertEquals(1, strHeaders.size());
String headerData = strHeaders.get(0);
assertEquals(4, headerData.split(",").length);
String expectedData = "</api/example?page=7&size=50>; rel=\"next\","
+ "</api/example?page=5&size=50>; rel=\"prev\","
+ "</api/example?page=7&size=50>; rel=\"last\","
+ "</api/example?page=0&size=50>; rel=\"first\"";
assertEquals(expectedData, headerData);
List<String> xTotalCountHeaders = headers.get("X-Total-Count");
assertEquals(1, xTotalCountHeaders.size());
assertEquals(400L, Long.valueOf(xTotalCountHeaders.get(0)).longValue());
}
}
| 40.666667 | 90 | 0.676913 |
4b50c88a854549bcd9b1c946109b68eda7d77a8d | 758 | package com.mycompany.horadosistema;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.util.Date;
import java.util.Locale;
public class HoraDoSistema {
public static void main(String[] args) {
Date relogio = new Date();
Locale idioma = Locale.getDefault();
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension d = tk.getScreenSize();
System.out.print("A hora do sistema é: ");
System.out.println(relogio.toString());
System.out.print("O Idioma do sistema é: ");
System.out.println(idioma.getDisplayLanguage());
System.out.println("Resolução da tela é: " + d.width + " x " + d.height);
}
}
| 28.074074 | 81 | 0.58971 |
52ebe07882f44b463d0621cdd35a3f8d0b2f4336 | 17,993 | /*
* Copyright (C) 2008-2013 The Android Open Source Project,
* Sean J. Barbeau
*
* 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.android.gpstest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.location.GnssMeasurementsEvent;
import android.location.GnssStatus;
import android.location.GpsStatus;
import android.location.Location;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import com.android.gpstest.map.MapViewModelController;
import com.android.gpstest.map.OnMapClickListener;
import com.android.gpstest.util.MapUtils;
import com.android.gpstest.util.MathUtils;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.LocationSource;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.google.maps.android.SphericalUtil;
import java.util.ArrayList;
import java.util.Arrays;
import static com.android.gpstest.map.MapConstants.ALLOW_GROUND_TRUTH_CHANGE;
import static com.android.gpstest.map.MapConstants.CAMERA_ANCHOR_ZOOM;
import static com.android.gpstest.map.MapConstants.CAMERA_INITIAL_BEARING;
import static com.android.gpstest.map.MapConstants.CAMERA_INITIAL_TILT_ACCURACY;
import static com.android.gpstest.map.MapConstants.CAMERA_INITIAL_TILT_MAP;
import static com.android.gpstest.map.MapConstants.CAMERA_INITIAL_ZOOM;
import static com.android.gpstest.map.MapConstants.CAMERA_MAX_TILT;
import static com.android.gpstest.map.MapConstants.CAMERA_MIN_TILT;
import static com.android.gpstest.map.MapConstants.DRAW_LINE_THRESHOLD_METERS;
import static com.android.gpstest.map.MapConstants.GROUND_TRUTH;
import static com.android.gpstest.map.MapConstants.MODE;
import static com.android.gpstest.map.MapConstants.MODE_ACCURACY;
import static com.android.gpstest.map.MapConstants.MODE_MAP;
import static com.android.gpstest.map.MapConstants.MOVE_MAP_INTERACTION_THRESHOLD;
import static com.android.gpstest.map.MapConstants.PREFERENCE_SHOWED_DIALOG;
import static com.android.gpstest.map.MapConstants.TARGET_OFFSET_METERS;
public class GpsMapFragment extends SupportMapFragment
implements GpsTestListener, View.OnClickListener, LocationSource,
GoogleMap.OnCameraChangeListener, GoogleMap.OnMapClickListener,
GoogleMap.OnMapLongClickListener,
GoogleMap.OnMyLocationButtonClickListener, OnMapReadyCallback, MapViewModelController.MapInterface {
private Bundle mSavedInstanceState;
private GoogleMap mMap;
private LatLng mLatLng;
private OnLocationChangedListener mListener; //Used to update the map with new location
// Camera control
private long mLastMapTouchTime = 0;
private CameraPosition mlastCameraPosition;
private boolean mGotFix;
// User preferences for map rotation and tilt based on sensors
private boolean mRotate;
private boolean mTilt;
private OnMapClickListener mOnMapClickListener;
private Marker mGroundTruthMarker;
private Polyline mErrorLine;
private Location mLastLocation;
private ArrayList<Polyline> mPathLines = new ArrayList<>();
MapViewModelController mMapController;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = super.onCreateView(inflater, container, savedInstanceState);
mLastLocation = null;
if (isGooglePlayServicesInstalled()) {
// Save the savedInstanceState
mSavedInstanceState = savedInstanceState;
// Register for an async callback when the map is ready
getMapAsync(this);
} else {
final SharedPreferences sp = Application.getPrefs();
if (!sp.getBoolean(PREFERENCE_SHOWED_DIALOG, false)) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(getString(R.string.please_install_google_maps));
builder.setPositiveButton(getString(R.string.install),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
sp.edit().putBoolean(PREFERENCE_SHOWED_DIALOG, true).commit();
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(
"market://details?id=com.google.android.apps.maps"));
startActivity(intent);
}
}
);
builder.setNegativeButton(getString(R.string.no_thanks),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
sp.edit().putBoolean(PREFERENCE_SHOWED_DIALOG, true).commit();
}
}
);
AlertDialog dialog = builder.create();
dialog.show();
}
}
mMapController = new MapViewModelController(getActivity(), this);
return v;
}
@Override
public void onSaveInstanceState(Bundle bundle) {
bundle.putString(MODE, mMapController.getMode());
bundle.putBoolean(ALLOW_GROUND_TRUTH_CHANGE, mMapController.allowGroundTruthChange());
if (mMapController.getGroundTruthLocation() != null) {
bundle.putParcelable(GROUND_TRUTH, mMapController.getGroundTruthLocation());
}
super.onSaveInstanceState(bundle);
}
@Override
public void onResume() {
checkMapPreferences();
super.onResume();
}
public void onClick(View v) {
}
public void gpsStart() {
mGotFix = false;
}
public void gpsStop() {
}
public void onLocationChanged(Location loc) {
//Update real-time location on map
if (mListener != null) {
mListener.onLocationChanged(loc);
}
mLatLng = new LatLng(loc.getLatitude(), loc.getLongitude());
if (mMap != null) {
//Get bounds for detection of real-time location within bounds
LatLngBounds bounds = mMap.getProjection().getVisibleRegion().latLngBounds;
if (!mGotFix &&
(!bounds.contains(mLatLng) ||
mMap.getCameraPosition().zoom < (mMap.getMaxZoomLevel() / 2))) {
float tilt = mMapController.getMode().equals(MODE_MAP) ? CAMERA_INITIAL_TILT_MAP : CAMERA_INITIAL_TILT_ACCURACY;
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(mLatLng)
.zoom(CAMERA_INITIAL_ZOOM)
.bearing(CAMERA_INITIAL_BEARING)
.tilt(tilt)
.build();
mMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
mGotFix = true;
if (mMapController.getMode().equals(MODE_ACCURACY) && !mMapController.allowGroundTruthChange() && mMapController.getGroundTruthLocation() != null) {
// Draw error line between ground truth and calculated position
LatLng gt = MapUtils.makeLatLng(mMapController.getGroundTruthLocation());
LatLng current = MapUtils.makeLatLng(loc);
if (mErrorLine == null) {
mErrorLine = mMap.addPolyline(new PolylineOptions()
.add(gt, current)
.color(Color.WHITE)
.geodesic(true));
} else {
mErrorLine.setPoints(Arrays.asList(gt, current));
};
}
if (mMapController.getMode().equals(MODE_ACCURACY) && mLastLocation != null) {
// Draw line between this and last location
boolean drawn = drawPathLine(mLastLocation, loc);
if (drawn) {
mLastLocation = loc;
}
}
}
if (mLastLocation == null) {
mLastLocation = loc;
}
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
@Deprecated
public void onGpsStatusChanged(int event, GpsStatus status) {
}
@Override
public void onGnssFirstFix(int ttffMillis) {
}
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void onSatelliteStatusChanged(GnssStatus status) {
}
@Override
public void onGnssStarted() {
}
@Override
public void onGnssStopped() {
}
@Override
public void onGnssMeasurementsReceived(GnssMeasurementsEvent event) {
}
@Override
public void onNmeaMessage(String message, long timestamp) {
}
@Override
public void onOrientationChanged(double orientation, double tilt) {
// For performance reasons, only proceed if this fragment is visible
if (!getUserVisibleHint()) {
return;
}
// Only proceed if map is not null and we're in MAP mode
if (mMap == null || !mMapController.getMode().equals(MODE_MAP)) {
return;
}
/*
If we have a location fix, and we have a preference to rotate the map based on sensors,
and the user hasn't touched the map lately, then do the map camera reposition
*/
if (mLatLng != null && mRotate
&& System.currentTimeMillis() - mLastMapTouchTime
> MOVE_MAP_INTERACTION_THRESHOLD) {
if (!mTilt || Double.isNaN(tilt)) {
tilt = mlastCameraPosition != null ? mlastCameraPosition.tilt : 0;
}
float clampedTilt = (float) MathUtils.clamp(CAMERA_MIN_TILT, tilt, CAMERA_MAX_TILT);
double offset = TARGET_OFFSET_METERS * (clampedTilt / CAMERA_MAX_TILT);
CameraPosition cameraPosition = CameraPosition.builder().
tilt(clampedTilt).
bearing((float) orientation).
zoom((float) (CAMERA_ANCHOR_ZOOM + (tilt / CAMERA_MAX_TILT))).
target(mTilt ? SphericalUtil.computeOffset(mLatLng, offset, orientation)
: mLatLng).
build();
mMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
/**
* Maps V2 Location updates
*/
@Override
public void activate(OnLocationChangedListener listener) {
mListener = listener;
}
/**
* Maps V2 Location updates
*/
@Override
public void deactivate() {
mListener = null;
}
@Override
public void onCameraChange(CameraPosition cameraPosition) {
if (System.currentTimeMillis() - mLastMapTouchTime < MOVE_MAP_INTERACTION_THRESHOLD) {
/*
If the user recently interacted with the map (causing a camera change), extend the
touch time before automatic map movements based on sensors will kick in
*/
mLastMapTouchTime = System.currentTimeMillis();
}
mlastCameraPosition = cameraPosition;
}
@Override
public void onMapClick(LatLng latLng) {
mLastMapTouchTime = System.currentTimeMillis();
if (!mMapController.getMode().equals(MODE_ACCURACY) || !mMapController.allowGroundTruthChange()) {
// Don't allow changes to the ground truth location, so don't pass taps to listener
return;
}
if (mMap != null) {
addGroundTruthMarker(MapUtils.makeLocation(latLng));
}
if (mOnMapClickListener != null) {
Location location = new Location("OnMapClick");
location.setLatitude(latLng.latitude);
location.setLongitude(latLng.longitude);
mOnMapClickListener.onMapClick(location);
}
}
@Override
public void addGroundTruthMarker(Location location) {
if (mMap == null) {
return;
}
LatLng latLng = MapUtils.makeLatLng(location);
if (mGroundTruthMarker == null) {
mGroundTruthMarker = mMap.addMarker(new MarkerOptions()
.position(latLng)
.title(Application.get().getString(R.string.ground_truth_marker_title)));
} else {
mGroundTruthMarker.setPosition(latLng);
}
}
@Override
public void onMapLongClick(LatLng latLng) {
mLastMapTouchTime = System.currentTimeMillis();
}
@Override
public boolean onMyLocationButtonClick() {
mLastMapTouchTime = System.currentTimeMillis();
// Return false, so button still functions as normal
return false;
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMapController.restoreState(mSavedInstanceState, getArguments(), mGroundTruthMarker == null);
checkMapPreferences();
// Show the location on the map
try {
mMap.setMyLocationEnabled(true);
} catch (SecurityException e) {
Log.e(mMapController.getMode(), "Tried to initialize my location on Google Map - " + e);
}
// Set location source
mMap.setLocationSource(this);
// Listener for camera changes
mMap.setOnCameraChangeListener(this);
// Listener for map / My Location button clicks, to disengage map camera control
mMap.setOnMapClickListener(this);
mMap.setOnMapLongClickListener(this);
mMap.setOnMyLocationButtonClickListener(this);
mMap.getUiSettings().setMapToolbarEnabled(false);
GpsTestActivity.getInstance().addListener(this);
}
/**
* Returns true if Google Play Services is available, false if it is not
*/
private static boolean isGooglePlayServicesInstalled() {
return GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(Application.get()) == ConnectionResult.SUCCESS;
}
/**
* Sets the listener that should receive map click events
* @param listener the listener that should receive map click events
*/
public void setOnMapClickListener(OnMapClickListener listener) {
mOnMapClickListener = listener;
}
private void checkMapPreferences() {
SharedPreferences settings = Application.getPrefs();
if (mMap != null && mMapController.getMode().equals(MODE_MAP)) {
if (mMap.getMapType() != Integer.valueOf(
settings.getString(getString(R.string.pref_key_map_type),
String.valueOf(GoogleMap.MAP_TYPE_NORMAL))
)) {
mMap.setMapType(Integer.valueOf(
settings.getString(getString(R.string.pref_key_map_type),
String.valueOf(GoogleMap.MAP_TYPE_NORMAL))
));
}
} else if (mMap != null && mMapController.getMode().equals(MODE_ACCURACY)) {
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
}
if (mMapController.getMode().equals(MODE_MAP)) {
mRotate = settings
.getBoolean(getString(R.string.pref_key_rotate_map_with_compass), true);
mTilt = settings.getBoolean(getString(R.string.pref_key_tilt_map_with_sensors), true);
}
}
/**
* Draws a line on the map between the two locations if its greater than a threshold value defined
* by DRAW_LINE_THRESHOLD_METERS
* @param loc1
* @param loc2
*/
@Override
public boolean drawPathLine(Location loc1, Location loc2) {
if (loc1.distanceTo(loc2) < DRAW_LINE_THRESHOLD_METERS) {
return false;
}
Polyline line = mMap.addPolyline(new PolylineOptions()
.add(MapUtils.makeLatLng(loc1), MapUtils.makeLatLng(loc2))
.color(Color.RED)
.width(2.0f)
.geodesic(true));
mPathLines.add(line);
return true;
}
/**
* Removes all path lines from the map
*/
@Override
public void removePathLines() {
for (Polyline line : mPathLines) {
line.remove();
}
mPathLines = new ArrayList<>();
}
}
| 36.870902 | 160 | 0.64375 |
b45f0f8db5b9cc5fb2d73f53c7d2bda82770c25f | 3,436 | /**
* Copyright 2011 Peter Murray-Rust et. al.
*
* 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.xmlcml.cml.element.lite;
import static org.xmlcml.cml.element.main.AbstractTestBase.SIMPLE_RESOURCE;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import nu.xom.Elements;
import nu.xom.ParsingException;
import nu.xom.ValidityException;
import org.junit.Assert;
import org.junit.Test;
import org.xmlcml.cml.base.CMLBuilder;
import org.xmlcml.cml.base.CMLConstants;
import org.xmlcml.cml.base.CMLElements;
import org.xmlcml.cml.element.CMLCml;
import org.xmlcml.cml.element.CMLPeak;
import org.xmlcml.cml.element.CMLPeakList;
import org.xmlcml.cml.element.CMLSpectrum;
import org.xmlcml.euclid.Util;
/**
* test CMLPeak
*
* @author pmr
*
*/
public class CMLPeakTest extends PeakSpectrumBase {
/**
* get peaks.
*
* @throws IOException
* @throws ParsingException
* @throws ValidityException
*/
@Test
public void testGetPeaks() throws IOException, ValidityException,
ParsingException {
CMLCml cml = null;
InputStream in = Util.getInputStreamFromResource(SIMPLE_RESOURCE +CMLConstants.U_S
+ testfile2);
cml = (CMLCml) new CMLBuilder().build(in).getRootElement();
in.close();
Assert.assertNotNull("cml should not be null " + testfile2, cml);
Elements elements1 = cml.getChildElements();
Assert.assertEquals("cmlChildren", 2, elements1.size());
Elements elements = cml.getChildCMLElements(CMLSpectrum.TAG);
Assert.assertEquals("cmlChild", 1, elements.size());
CMLSpectrum spectrum = (CMLSpectrum) elements.get(0);
Assert.assertNotNull("spectrum", spectrum);
CMLPeakList peakList = spectrum.getPeakListElements().get(0);
Assert.assertNotNull("peakList", peakList);
CMLElements<CMLPeak> peaks = peakList.getPeakElements();
Assert.assertNotNull("peaks", peaks);
Assert.assertEquals("peak count", 1, peaks.size());
// check owner spectrum elements
CMLSpectrum spectrum1 = CMLSpectrum.getSpectrum(peaks.get(0));
Assert.assertNotNull("spectrum", spectrum1);
spectrum1 = CMLSpectrum.getSpectrum(peakList);
Assert.assertNotNull("spectrum", spectrum1);
}
/**
* tests
*
* getDescendantPeaks(CMLElement element)
*
* @throws IOException
* @throws ParsingException
* @throws ValidityException
*/
@Test
public void testGetDescendantPeaks() throws IOException, ValidityException,
ParsingException {
CMLCml cml = null;
InputStream in = Util.getInputStreamFromResource(SIMPLE_RESOURCE +CMLConstants.U_S
+ testfile2);
cml = (CMLCml) new CMLBuilder().build(in).getRootElement();
in.close();
List<CMLPeak> peaks = CMLSpectrum.getDescendantPeaks(cml);
Assert.assertNotNull("peaks ", peaks);
Assert.assertEquals("peak count ", 4, peaks.size());
}
}
| 32.11215 | 85 | 0.716822 |
970eeae4b1e9604cd515eb5db2a9592427045bbb | 8,843 | package ru.stqa.pft.addressbook.appmanager.appmanager;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.Sleeper;
import org.testng.Assert;
import ru.stqa.pft.addressbook.appmanager.model.ContactData;
import ru.stqa.pft.addressbook.appmanager.model.Contacts;
import ru.stqa.pft.addressbook.appmanager.model.GroupData;
import java.util.ArrayList;
import java.util.List;
public class ContactHelper extends HelperBase {
public ContactHelper(ApplicationManager app) {
super(app);
}
public void fillContactForm(ContactData contactData, boolean creation) {
type(By.name("firstname"), contactData.getName());
type(By.name("lastname"), contactData.getSurname());
type(By.name("mobile"), contactData.getMobilePhone());
type(By.name("email"), contactData.getMail1());
attach(By.name("photo"), contactData.getPhoto());
if (creation) {
if (contactData.getGroups().size() > 0) {
Assert.assertTrue(contactData.getGroups().size() == 1);
new Select(wd.findElement(By.name("new_group")))
.selectByVisibleText(contactData.getGroups().iterator().next().getName());
}
} else {
Assert.assertFalse(isElementPresent(By.name("new_group")));
}
}
public void fillContactForm(ContactData contactData) {
type(By.name("firstname"), contactData.getName());
type(By.name("lastname"), contactData.getSurname());
type(By.name("mobile"), contactData.getMobilePhone());
type(By.name("email"), contactData.getMail1());
attach(By.name("photo"), contactData.getPhoto());
}
public void submitNewContact() {
click(By.xpath("(//input[@name='submit'])[2]"));
}
public void selectContact(int index) {
wd.findElements(By.name("selected[]")).get(index).click();
//click(By.name("selected[]"));
}
public void selectContactByID(int id) {
wd.findElement(By.cssSelector("input[id='" + id + "']")).click();
}
public void deleteSelectContact() {
click(By.xpath("//input[@value='Delete']"));
}
public void waitDelete() {
wd.findElement(By.cssSelector("div.msgbox"));
}
public void edit(int index) {
wd.findElements(By.xpath("//img[@alt='Edit']")).get(index).click();
//click(By.xpath("//img[@alt='Edit']"));
}
public void editByIcon(int id) {
wd.findElement(By.cssSelector("a[href='edit.php?id=" + id + "']")).click();
// WebElement checkbox = wd.findElement(By.cssSelector(String.format("input[value='%s']", id)));
// WebElement row = checkbox.findElement(By.xpath("./../.."));
//List<WebElement> cells = row.findElements(By.tagName("td"));
// cells.get(7).findElement(By.tagName("a")).click();
//wd.findElement((By.xpath(String.format("//input[@value='%s']//../../td[8]/a", id)))).click();
}
public void modify(ContactData contact) {
app.goTo().homePage();
app.contact().allGroupsInContactPage();
editByIcon(contact.getId());
fillContactForm((contact), false);
submitEditContact();
contactCache = null;
app.goTo().homePage();
}
public void submitEditContact() {
click(By.name("update"));
}
public boolean isThereAContact() {
return isElementPresent(By.name("selected[]"));
}
//public boolean isThereAGroupContact() {
// new Select(wd.findElement(By.name("new_group"))).selectByVisibleText("test1");
// return true;
public void create(ContactData contact, boolean b) {
app.goTo().createContact();
fillContactForm(contact, b);
submitNewContact();
contactCache = null;
app.goTo().homePage();
}
public void create(ContactData contact) {
app.goTo().createContact();
fillContactForm(contact);
submitNewContact();
contactCache = null;
app.goTo().homePage();
}
public void delete(int index) {
selectContact(index);
deleteSelectContact();
isAlertPresent();
app.goTo().homePage();
}
public void delete(ContactData contact) {
app.goTo().homePage();
app.contact().allGroupsInContactPage();
selectContactByID(contact.getId());
deleteSelectContact();
isAlertPresent();
waitDelete();
contactCache = null;
app.goTo().homePage();
}
public int getContactCount() {
return wd.findElements(By.name("entry")).size();
}
private Contacts contactCache = null;
public List<ContactData> list() {
List<ContactData> contacts = new ArrayList<ContactData>();
List<WebElement> cells = wd.findElements(By.name("entry"));
for (WebElement cell : cells) {
String name = cell.findElement(By.xpath(".//td[3]")).getText();
String surname = cell.findElement(By.xpath(".//td[2]")).getText();
int id = Integer.parseInt(cell.findElement(By.name("selected[]")).getAttribute("value"));
contacts.add(new ContactData().withId(id).withName(name).withSurname(surname));
;
}
return contacts;
}
public Contacts all() {
if (contactCache != null) {
return new Contacts((contactCache));
}
contactCache = new Contacts();
List<WebElement> rows = wd.findElements(By.name("entry"));
for (WebElement row : rows) {
List<WebElement> cells = row.findElements(By.tagName("td"));
int id = Integer.parseInt(cells.get(0).findElement(By.tagName("input")).getAttribute("value"));
String name = cells.get(2).getText();
String surname = cells.get(1).getText();
String allPhones = cells.get(5).getText();
String allMails = cells.get(4).getText();
String address = cells.get(3).getText();
//String name = cell.findElement(By.xpath(".//td[3]")).getText();
//String surname = cell.findElement(By.xpath(".//td[2]")).getText();
//int id = Integer.parseInt(cell.findElement(By.name("selected[]")).getAttribute("value"));
//String[] phones = cell.findElements(By.xpath(".//td[6]")).get(7).getText().split("\n");
contactCache.add(new ContactData().withId(id).withName(name).withSurname(surname)
.withAllPhones(allPhones).withAllMails(allMails).withAddress(address));
}
return new Contacts((contactCache));
}
public ContactData infoFromEditForm(ContactData contact) {
editByIcon(contact.getId());
String name = wd.findElement(By.name("firstname")).getAttribute("value");
String surname = wd.findElement(By.name("lastname")).getAttribute("value");
String homePhone = wd.findElement(By.name("home")).getAttribute("value");
String mobilePhone = wd.findElement(By.name("mobile")).getAttribute("value");
String workPhone = wd.findElement(By.name("work")).getAttribute("value");
String mail1 = wd.findElement(By.name("email")).getAttribute("value");
String mail2 = wd.findElement(By.name("email2")).getAttribute("value");
String mail3 = wd.findElement(By.name("email3")).getAttribute("value");
String address = wd.findElement(By.name("address")).getAttribute("value");
wd.navigate().back();
return new ContactData().withId(contact.getId()).withName(name)
.withSurname(surname).withHomePhone(homePhone)
.withMobilePhone(mobilePhone).withWorkPhone(workPhone)
.withMail1(mail1).withMail2(mail2).withMail3(mail3).withAddress(address);
}
public void addContactToGroupAfterSelect(GroupData selectedGroup) {
String id = String.valueOf(selectedGroup.getId());
new Select(wd.findElement(By.name("to_group"))).selectByValue(id);
click(By.name("add"));
}
public void addInGroupFinal(ContactData selectedContact, GroupData selectedGroup) {
selectContactByID(selectedContact.getId());
addContactToGroupAfterSelect(selectedGroup);
}
public void deleteFromGroupFinal(ContactData contact, GroupData group) {
String id = String.valueOf(group.getId());
new Select(wd.findElement(By.name("group"))).selectByValue(id);
selectContactByID(contact.getId());
deleteContactFromGroupAfterSelect();
}
private void deleteContactFromGroupAfterSelect() {
click(By.name("remove"));
}
public void allGroupsInContactPage() {
new Select(wd.findElement(By.name("group"))).selectByVisibleText("[all]");
}
}
| 37.790598 | 107 | 0.624223 |
884f9bfb1bc7ca64625fcd190dfae184b33eff3c | 766 | package xyz.erupt.zeta_api.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* @author liyuepeng
* @date 2019-10-31.
*/
@Data
@Component
@ConfigurationProperties(prefix = "zeta-api")
public class ZetaApiProp {
private boolean hotReadXml = false;
private boolean enableCache = true;
private boolean enableApiDoc = true;
private String domain;
private List<String> ipWhite;
private String xmlbasePath = "/epi";
private boolean showSql = true;
private String cacheHandlerPath = "xyz.erupt.zeta_api.handler.CaffeineCacheHandler";
}
| 21.277778 | 88 | 0.758486 |
0a1e26371f8db5ea573a8f355e794e48f24ae5f1 | 10,783 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.ml.extractor;
import org.elasticsearch.action.fieldcaps.FieldCapabilities;
import org.elasticsearch.action.fieldcaps.FieldCapabilitiesResponse;
import org.elasticsearch.common.document.DocumentField;
import org.elasticsearch.index.mapper.BooleanFieldMapper;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.xpack.core.ml.utils.MlStrings;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
/**
* The fields the data[feed|frame] has to extract
*/
public class ExtractedFields {
private final List<ExtractedField> allFields;
private final List<ExtractedField> docValueFields;
private final List<ProcessedField> processedFields;
private final String[] sourceFields;
private final Map<String, Long> cardinalitiesForFieldsWithConstraints;
public ExtractedFields(List<ExtractedField> allFields,
List<ProcessedField> processedFields,
Map<String, Long> cardinalitiesForFieldsWithConstraints) {
this.allFields = new ArrayList<>(allFields);
this.docValueFields = filterFields(ExtractedField.Method.DOC_VALUE, allFields);
this.sourceFields = filterFields(ExtractedField.Method.SOURCE, allFields).stream().map(ExtractedField::getSearchField)
.toArray(String[]::new);
this.cardinalitiesForFieldsWithConstraints = Collections.unmodifiableMap(cardinalitiesForFieldsWithConstraints);
this.processedFields = processedFields == null ? Collections.emptyList() : processedFields;
}
public List<ProcessedField> getProcessedFields() {
return processedFields;
}
public List<ExtractedField> getAllFields() {
return allFields;
}
public Set<String> getProcessedFieldInputs() {
return processedFields.stream().map(ProcessedField::getInputFieldNames).flatMap(List::stream).collect(Collectors.toSet());
}
public String[] getSourceFields() {
return sourceFields;
}
public List<ExtractedField> getDocValueFields() {
return docValueFields;
}
public Map<String, Long> getCardinalitiesForFieldsWithConstraints() {
return cardinalitiesForFieldsWithConstraints;
}
public String[] extractOrganicFeatureNames() {
Set<String> processedFieldInputs = getProcessedFieldInputs();
return allFields
.stream()
.map(ExtractedField::getName)
.filter(f -> processedFieldInputs.contains(f) == false)
.toArray(String[]::new);
}
public String[] extractProcessedFeatureNames() {
return processedFields
.stream()
.map(ProcessedField::getOutputFieldNames)
.flatMap(List::stream)
.toArray(String[]::new);
}
private static List<ExtractedField> filterFields(ExtractedField.Method method, List<ExtractedField> fields) {
return fields.stream().filter(field -> field.getMethod() == method).collect(Collectors.toList());
}
public static ExtractedFields build(Set<String> allFields,
Set<String> scriptFields,
Set<String> searchRuntimeFields,
FieldCapabilitiesResponse fieldsCapabilities,
Map<String, Long> cardinalitiesForFieldsWithConstraints,
List<ProcessedField> processedFields) {
ExtractionMethodDetector extractionMethodDetector =
new ExtractionMethodDetector(scriptFields, fieldsCapabilities, searchRuntimeFields);
return new ExtractedFields(
allFields.stream().map(extractionMethodDetector::detect).collect(Collectors.toList()),
processedFields,
cardinalitiesForFieldsWithConstraints);
}
public static ExtractedFields build(Set<String> allFields,
Set<String> scriptFields,
FieldCapabilitiesResponse fieldsCapabilities,
Map<String, Long> cardinalitiesForFieldsWithConstraints,
List<ProcessedField> processedFields) {
return build(allFields, scriptFields, Collections.emptySet(), fieldsCapabilities,
cardinalitiesForFieldsWithConstraints, processedFields);
}
public static TimeField newTimeField(String name, ExtractedField.Method method) {
return new TimeField(name, method);
}
public static ExtractedField applyBooleanMapping(ExtractedField field) {
return new BooleanMapper<>(field, 1, 0);
}
public static class ExtractionMethodDetector {
private final Set<String> scriptFields;
private final Set<String> searchRuntimeFields;
private final FieldCapabilitiesResponse fieldsCapabilities;
public ExtractionMethodDetector(Set<String> scriptFields, FieldCapabilitiesResponse fieldsCapabilities,
Set<String> searchRuntimeFields) {
this.scriptFields = scriptFields;
this.fieldsCapabilities = fieldsCapabilities;
this.searchRuntimeFields = searchRuntimeFields;
}
public ExtractedField detect(String field) {
if (scriptFields.contains(field)) {
return new ScriptField(field);
}
if (searchRuntimeFields.contains(field)) {
return new DocValueField(field, Collections.emptySet());
}
ExtractedField extractedField = detectFieldFromFieldCaps(field);
String parentField = MlStrings.getParentField(field);
if (isMultiField(field, parentField)) {
if (isAggregatable(field)) {
return new MultiField(parentField, extractedField);
} else {
ExtractedField parentExtractionField = detectFieldFromFieldCaps(parentField);
return new MultiField(field, parentField, parentField, parentExtractionField);
}
}
return extractedField;
}
private ExtractedField detectFieldFromFieldCaps(String field) {
if (isFieldOfTypes(field, TimeField.TYPES) && isAggregatable(field)) {
return new TimeField(field, ExtractedField.Method.DOC_VALUE);
}
if (isFieldOfType(field, GeoPointField.TYPE)) {
if (isAggregatable(field) == false) {
throw new IllegalArgumentException("cannot use [geo_point] field with disabled doc values");
}
return new GeoPointField(field);
}
if (isFieldOfType(field, GeoShapeField.TYPE)) {
return new GeoShapeField(field);
}
Set<String> types = getTypes(field);
return isAggregatable(field) ? new DocValueField(field, types) : new SourceField(field, types);
}
private Set<String> getTypes(String field) {
Map<String, FieldCapabilities> fieldCaps = fieldsCapabilities.getField(field);
return fieldCaps == null ? Collections.emptySet() : fieldCaps.keySet();
}
public boolean isAggregatable(String field) {
Map<String, FieldCapabilities> fieldCaps = fieldsCapabilities.getField(field);
if (fieldCaps == null || fieldCaps.isEmpty()) {
throw new IllegalArgumentException("cannot retrieve field [" + field + "] because it has no mappings");
}
for (FieldCapabilities capsPerIndex : fieldCaps.values()) {
if (capsPerIndex.isAggregatable() == false) {
return false;
}
}
return true;
}
private boolean isFieldOfType(String field, String type) {
return isFieldOfTypes(field, Collections.singleton(type));
}
private boolean isFieldOfTypes(String field, Set<String> types) {
assert types.isEmpty() == false;
Map<String, FieldCapabilities> fieldCaps = fieldsCapabilities.getField(field);
if (fieldCaps != null && fieldCaps.isEmpty() == false) {
return types.containsAll(fieldCaps.keySet());
}
return false;
}
private boolean isMultiField(String field, String parent) {
if (Objects.equals(field, parent)) {
return false;
}
Map<String, FieldCapabilities> parentFieldCaps = fieldsCapabilities.getField(parent);
if (parentFieldCaps == null || (parentFieldCaps.size() == 1 && parentFieldCaps.containsKey("object"))) {
// We check if the parent is an object which is indicated by field caps containing an "object" entry.
// If an object, it's not a multi field
return false;
}
return true;
}
}
/**
* Makes boolean fields behave as a field of different type.
*/
private static final class BooleanMapper<T> extends DocValueField {
private static final Set<String> TYPES = Collections.singleton(BooleanFieldMapper.CONTENT_TYPE);
private final T trueValue;
private final T falseValue;
BooleanMapper(ExtractedField field, T trueValue, T falseValue) {
super(field.getName(), TYPES);
if (field.getMethod() != Method.DOC_VALUE || field.getTypes().contains(BooleanFieldMapper.CONTENT_TYPE) == false) {
throw new IllegalArgumentException("cannot apply boolean mapping to field [" + field.getName() + "]");
}
this.trueValue = trueValue;
this.falseValue = falseValue;
}
@Override
public Object[] value(SearchHit hit) {
DocumentField keyValue = hit.field(getName());
if (keyValue != null) {
return keyValue.getValues().stream().map(v -> Boolean.TRUE.equals(v) ? trueValue : falseValue).toArray();
}
return new Object[0];
}
@Override
public boolean supportsFromSource() {
return false;
}
@Override
public ExtractedField newFromSource() {
throw new UnsupportedOperationException();
}
}
}
| 42.286275 | 130 | 0.633961 |
889151a5772997fb260ec62c327c8211e3567288 | 1,886 | /* */ package jp.cssj.homare.xml.a;
/* */
/* */ import jp.cssj.homare.xml.d;
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public final class a
/* */ {
/* */ public static final String a = "cssj";
/* */ public static final String b = "http://www.cssj.jp/ns/cssjml";
/* 30 */ public static final jp.cssj.homare.xml.a c = new jp.cssj.homare.xml.a("http://www.cssj.jp/ns/cssjml", "cssj", "annot");
/* */
/* */
/* */
/* */
/* 35 */ public static final jp.cssj.homare.xml.a d = new jp.cssj.homare.xml.a("http://www.cssj.jp/ns/cssjml", "cssj", "header");
/* */
/* */
/* */
/* */
/* 40 */ public static final d e = new d("http://www.cssj.jp/ns/cssjml", "cssj", "make-toc");
/* */
/* */
/* */
/* */
/* 45 */ public static final d f = new d("http://www.cssj.jp/ns/cssjml", "cssj", "make-index");
/* */
/* */
/* */
/* */
/* 50 */ public static final d g = new d("http://www.cssj.jp/ns/cssjml", "cssj", "index");
/* */
/* */
/* */
/* */
/* 55 */ public static final d h = new d("http://www.cssj.jp/ns/cssjml", "cssj", "fail");
/* */ public static final String i = "jp.cssj.stylesheet";
/* */ public static final String j = "jp.cssj.document-info";
/* */ public static final String k = "jp.cssj.default-encoding";
/* */ public static final String l = "jp.cssj.default-style-type";
/* */ public static final String m = "jp.cssj.base-uri";
/* */ public static final String n = "jp.cssj.property";
/* */ }
/* Location: /mnt/r/ConTenDoViewer.jar!/jp/cssj/homare/xml/a/a.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/ | 27.735294 | 131 | 0.460764 |
7007eb4b9a2126302bc0294d4f179b970c1de8a0 | 3,984 | /*
* 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 builder;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.tree.ClassNode;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import static org.objectweb.asm.Opcodes.ASM9;
/**
* A class representing a node created for each class file in the jar file.
*/
public class ClassGraphNode extends ClassNode {
private List<ClassGraphNode> childNodes = new ArrayList<>();
private ClassReader reader;
private ClassGraphNode superNode;
private List<ClassGraphNode> interfaceNodes;
private boolean visited;
private boolean used;
private boolean isServiceProvider;
private DependencyCollector collector;
public ClassGraphNode(String name) {
super(ASM9);
this.name = name;
visited = false;
used = false;
isServiceProvider = false;
collector = new DependencyCollector();
}
public boolean isVisited() {
return visited;
}
public boolean isUsed() {
return used;
}
public void markAsVisited() {
visited = true;
}
public void markAsUsed() {
used = true;
}
public boolean isServiceProvider() {
return isServiceProvider;
}
public void markAsServiceProvider() {
isServiceProvider = true;
}
public Set<String> getDependencies() {
return collector.getDependencies();
}
public void addChildNode(ClassGraphNode childNode) {
childNodes.add(childNode);
}
public void setReader(byte[] bytes) {
reader = new ClassReader(bytes);
}
public void setReader() {
try {
this.reader = new ClassReader(this.name);
} catch (IOException ignored) {
}
}
public List<ClassGraphNode> getChildNodes() {
return childNodes;
}
public String getSuperName() {
if (reader == null) {
return null;
}
this.superName = reader.getSuperName();
return superName;
}
public ClassGraphNode getSuperNode() {
return superNode;
}
public void setSuperNode(ClassGraphNode superNode) {
this.superNode = superNode;
}
public String[] getInterfaceNames() {
if (reader == null) {
return null;
}
this.interfaces = Arrays.asList(reader.getInterfaces());
return reader.getInterfaces();
}
public List<ClassGraphNode> getInterfaceNodes() {
return interfaceNodes;
}
public void setInterfaceNodes(List<ClassGraphNode> interfaceNodes) {
this.interfaceNodes = interfaceNodes;
}
/**
* accepts a ClassVisitor object and pass it to the accept method of ClassReader
**/
@Override
public void accept(ClassVisitor cv) {
ClassNode cn = (ClassNode) cv;
cn.name = name;
cn.methods = methods;
cn.access = access;
cn.superName = superName;
if (cn instanceof ClassNodeVisitor) {
ClassNodeVisitor cnv = (ClassNodeVisitor) cn;
cnv.setCollector(collector);
}
reader.accept(cn, 0);
this.methods = cn.methods;
this.access = cn.access;
}
}
| 25.538462 | 84 | 0.642068 |
60c973b3039b7cf4314ffe0df8166817d10cc15f | 1,187 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.core.transform.transforms.pivot;
import org.elasticsearch.common.io.stream.Writeable.Reader;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.test.AbstractSerializingTestCase;
import java.io.IOException;
public class TermsGroupSourceTests extends AbstractSerializingTestCase<TermsGroupSource> {
public static TermsGroupSource randomTermsGroupSource() {
String field = randomAlphaOfLengthBetween(1, 20);
return new TermsGroupSource(field);
}
@Override
protected TermsGroupSource doParseInstance(XContentParser parser) throws IOException {
return TermsGroupSource.fromXContent(parser, false);
}
@Override
protected TermsGroupSource createTestInstance() {
return randomTermsGroupSource();
}
@Override
protected Reader<TermsGroupSource> instanceReader() {
return TermsGroupSource::new;
}
}
| 30.435897 | 90 | 0.764111 |
e09070b71fc3a85e165e3b10cb860ee58322847f | 50 | package cs451;
public class HashMap<T1, T2> {
}
| 8.333333 | 30 | 0.68 |
fce36cf80938ce0c31a993e528bd7e6d80986783 | 1,095 | package de.notecho.spotify.bot.modules.commands;
import de.notecho.spotify.bot.instance.BotInstance;
import de.notecho.spotify.bot.modules.Command;
import de.notecho.spotify.database.user.entities.module.Module;
import de.notecho.spotify.database.user.entities.module.ModuleEntry;
import de.notecho.spotify.module.ModuleType;
import de.notecho.spotify.module.UserLevel;
import lombok.SneakyThrows;
public class SkipCommand extends Command {
public SkipCommand(Module module, BotInstance root) {
super(module, root);
}
@SneakyThrows
@Override
public void exec(String userName, String id, UserLevel userLevel, String[] args) {
ModuleEntry sPause = getModule().getEntry("sSkip");
if (!userLevel.isHigherOrEquals(sPause.getUserLevel())) {
sendMessage(getModule(ModuleType.SYSTEM).getEntry("noPerms"), "$USER", userName, "$ROLE", sPause.getUserLevel().getPrettyName());
return;
}
getRoot().getSpotifyApi().skipUsersPlaybackToNextTrack().build().execute();
sendMessage(sPause, "$USER", userName);
}
}
| 37.758621 | 141 | 0.723288 |
64626828df7839d776dea07707d5516a0ec61358 | 18,755 | package org.alj.lightstick.lightsticksender;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private int MIN_PACKET_SIZE = 7;
final int ACTIVITY_CHOOSE_FILE = 1;
private EditText txtIpAddress;
private EditText valSize;
private EditText valFrames;
private EditText txtFilename;
private ProgressBar pgrDelay;
private Button btnBlack;
private Button btnRainbow;
private Button btnWhite;
private Button btnSelectFile;
private Button btnStartFile;
private Button btnStartFile5Sec;
private Button btnUploadFile;
private Button btnStartUploaded;
private String filePath = null;
private BusyUpdater busyUpdater = new BusyUpdater();
private Handler busyUpdaterHandler = new Handler(Looper.getMainLooper());
private AlertDialogDisplay alertDialogDisplay = new AlertDialogDisplay();
private Handler alertDialogDisplayHandler = new Handler(Looper.getMainLooper());
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtIpAddress = (EditText)findViewById(R.id.txtIpAddress);
valSize = (EditText)findViewById(R.id.valSize);
valFrames = (EditText)findViewById(R.id.valFrames);
txtFilename = (EditText)findViewById(R.id.txtFilename);
pgrDelay = (ProgressBar)findViewById(R.id.pgrDelay);
btnBlack = (Button)findViewById(R.id.btnBlack);
btnRainbow = (Button)findViewById(R.id.btnRainbow);
btnWhite = (Button)findViewById(R.id.btnWhite);
btnSelectFile = (Button)findViewById(R.id.btnSelectFile);
btnStartFile = (Button)findViewById(R.id.btnStartFile);
btnStartFile5Sec = (Button)findViewById(R.id.btnStartFile5Sec);
btnUploadFile = (Button)findViewById(R.id.btnUploadFile);
btnStartUploaded = (Button)findViewById(R.id.btnStartUploaded);
}
@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);
return true;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode) {
case ACTIVITY_CHOOSE_FILE: {
if (resultCode == RESULT_OK){
Uri uri = data.getData();
filePath = uri.getPath();
txtFilename.setText(uri.getLastPathSegment(), EditText.BufferType.EDITABLE);
}
}
}
}
@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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private int getSize() {
try {
return Integer.parseInt(valSize.getText().toString());
} catch (NumberFormatException ex) {
Log.e(TAG, "error in getSite", ex);
return 0;
}
}
private int getBufferSize(int thePixelCount) {
return thePixelCount * 3 + MIN_PACKET_SIZE;
}
private byte[] initBuffer(int theSize) {
int aBufferSize = getBufferSize(theSize);
byte aResult[] = new byte[aBufferSize];
aResult[0] = 'L';
aResult[1] = 'S';
aResult[2] = 0;
aResult[3] = 1;
aResult[4] = 'L';
aResult[5] = (byte)((aBufferSize - MIN_PACKET_SIZE) % 256);
aResult[6] = (byte)((aBufferSize - MIN_PACKET_SIZE) / 256);
return aResult;
}
private int getBufferIndex(int thePixel) {
return MIN_PACKET_SIZE + thePixel * 3;
}
public void btnBlackClicked(View theView) {
int aSize = getSize();
byte[] aBuffer = initBuffer(aSize);
for (int i = 0; i < aSize; i++) {
int anIndex = getBufferIndex(i);
aBuffer[anIndex] = 0;
aBuffer[anIndex + 1] = 0;
aBuffer[anIndex + 2] = 0;
}
sendBuffer(aBuffer, true, true);
}
public void btnRainbowClicked(View theView) {
int aSize = getSize();
byte[] aBuffer = initBuffer(aSize);
for (int i = 0; i < aSize; i++) {
int anIndex = getBufferIndex(i);
int aColor = Color.HSVToColor(new float[]{(float) (i * 360 / aSize), 1.0f, 0.5f});
aBuffer[anIndex] = (byte)Color.red(aColor);
aBuffer[anIndex + 1] = (byte)Color.green(aColor);
aBuffer[anIndex + 2] = (byte)Color.blue(aColor);
}
sendBuffer(aBuffer, true, true);
}
public void btnWhiteClicked(View theView) {
int aSize = getSize();
byte[] aBuffer = initBuffer(aSize);
for (int i = 0; i < aSize; i++) {
int anIndex = getBufferIndex(i);
aBuffer[anIndex] = (byte)255;
aBuffer[anIndex + 1] = (byte)255;
aBuffer[anIndex + 2] = (byte)255;
}
sendBuffer(aBuffer, true, true);
}
public void btnSelectFileClicked(View theView) {
Intent chooseFile;
Intent intent;
chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
chooseFile.setType("file/*");
intent = Intent.createChooser(chooseFile, "Choose a file");
startActivityForResult(intent, ACTIVITY_CHOOSE_FILE);
}
public void btnStartFileClicked(View theView) {
doStartFile(theView);
}
public void btnStartFile5SecClicked(final View theView) {
new DelayedStart() {
protected void doAfterDelay() {
doStartFile(theView);
}
}.execute();
}
public void btnUploadFileClicked(final View theView) {
final String anIpAddress = txtIpAddress.getText().toString();
Bitmap aBitmap = BitmapFactory.decodeFile(filePath);
new UploadBitmap(anIpAddress, aBitmap).execute();
}
public void btnStartUploadedClicked(final View theView) {
new DelayedStart() {
protected void doAfterDelay() {
doStartUploaded(theView);
}
}.execute();
}
private void doStartFile(View theView) {
Bitmap aBitmap = BitmapFactory.decodeFile(filePath);
String anIpAddress = txtIpAddress.getText().toString();
int aFramesPerSecond = Integer.parseInt(valFrames.getText().toString());
Thread aThread = new Thread(new SendBitmap(anIpAddress, aFramesPerSecond, aBitmap));
aThread.setPriority(Thread.MAX_PRIORITY);
aThread.start();
}
private void doStartUploaded(View theView) {
String anIpAddress = txtIpAddress.getText().toString();
int aFramesPerSecond = Integer.parseInt(valFrames.getText().toString());
new StartUploaded(anIpAddress, aFramesPerSecond).execute();
}
private void sendBuffer(byte[] theBuffer, boolean theToUdp, boolean theToTcp) {
String anIpAddress = txtIpAddress.getText().toString();
new SendBufferUDP(anIpAddress)
.setToUdp(theToUdp)
.setToTcp(theToTcp)
.execute(theBuffer);
}
private static final void sendBufferUDP(String theIpAddress, byte[] theBuffer, boolean theToUdp, boolean theToTcp) {
try {
if (theToUdp) {
byte[] aBuffer = new byte[] {0x4c, 0x53, 0x00, 0x01, 0x55, 0x00}; // LS<0><1><U
Socket aSocket = new Socket(theIpAddress, 7778);
OutputStream anOS = aSocket.getOutputStream();
anOS.write(aBuffer);
anOS.flush();
anOS.close();
Thread.sleep(500);
}
DatagramSocket aSocket = new DatagramSocket();
InetAddress anInetAdddress = InetAddress.getByName(theIpAddress);
DatagramPacket aPacket = new DatagramPacket(theBuffer, theBuffer.length, anInetAdddress, 7777);
aSocket.send(aPacket);
if (theToTcp) {
final byte[] aBuffer = new byte[] {'L', 'S', 0x00, 0x01, 'T'};
aPacket = new DatagramPacket(aBuffer, aBuffer.length, anInetAdddress, 7777);
aSocket.send(aPacket);
}
} catch (Exception ex) {
Log.e(TAG, "error in doInBackground", ex);
}
}
private abstract class DelayedStart extends AsyncTask<Void, Integer, Void> {
public DelayedStart() {
pgrDelay.setProgress(0);
setBusy(true);
}
protected Void doInBackground(Void... theNothing) {
for (int i = 0; i < 50; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
}
publishProgress(i * 2);
}
return null;
}
protected void onProgressUpdate(Integer... theProgress) {
pgrDelay.setProgress(theProgress[0]);
if (theProgress[0] % 20 == 0) {
ToneGenerator toneG = new ToneGenerator(AudioManager.STREAM_ALARM, 100);
toneG.startTone(ToneGenerator.TONE_CDMA_ALERT_INCALL_LITE, 200);
}
}
protected void onPostExecute(Void theResult) {
pgrDelay.setProgress(100);
ToneGenerator toneG = new ToneGenerator(AudioManager.STREAM_ALARM, 100);
toneG.startTone(ToneGenerator.TONE_CDMA_ALERT_CALL_GUARD, 200);
doAfterDelay();
}
abstract protected void doAfterDelay();
};
private class SendBufferUDP extends AsyncTask<byte[], Void, Void> {
private static final String TAG = MainActivity.TAG + ".SendBufferUDP";
private String ipAddress;
private boolean toUdp = false;
private boolean toTcp = false;
public SendBufferUDP(String theIpAddress) {
ipAddress = theIpAddress;
}
@Override
protected Void doInBackground(byte[]... params) {
try {
setBusy(true);
sendBufferUDP(ipAddress, params[0], toUdp, toTcp);
} finally {
setBusy(false);
}
return null;
}
public SendBufferUDP setToUdp(boolean theValue) {
toUdp = theValue;
return this;
}
public SendBufferUDP setToTcp(boolean theValue) {
toTcp = theValue;
return this;
}
}
private class SendBitmap implements Runnable {
private static final String TAG = MainActivity.TAG + ".SendBitmap";
private String ipAddress;
private int framesPerSecond;
private Bitmap bitmap;
public SendBitmap(String theIpAddress, int theFramesPerSecond, Bitmap theBitmap) {
ipAddress = theIpAddress;
framesPerSecond = theFramesPerSecond;
bitmap = theBitmap;
}
@Override
public void run() {
try {
setBusy(true);
int aHeight = bitmap.getHeight();
int aWidth = bitmap.getWidth();
long aDelta = 1000 / framesPerSecond;
byte[] aBuffer = initBuffer(aHeight);
for (int i = 0; i < aWidth; i++) {
long aStart = System.currentTimeMillis();
for (int j = 0; j < aHeight; j++) {
int aPixel = bitmap.getPixel(i, j);
int anIndex = getBufferIndex(j);
aBuffer[anIndex] = (byte)Color.red(aPixel);
aBuffer[anIndex + 1] = (byte)Color.green(aPixel);
aBuffer[anIndex + 2] = (byte)Color.blue(aPixel);
}
sendBufferUDP(ipAddress, aBuffer, i == 0, false);
// while (aStart + aDelta > System.currentTimeMillis()) {}
try {
long aDelay = aStart + aDelta - System.currentTimeMillis();
Thread.sleep(aDelay>0?aDelay:0);
} catch (InterruptedException ex) {
}
}
// black
for (int i = 0; i < aHeight; i++) {
int anIndex = getBufferIndex(i);
aBuffer[anIndex] = 0;
aBuffer[anIndex + 1] = 0;
aBuffer[anIndex + 2] = 0;
}
sendBufferUDP(ipAddress, aBuffer, false, true);
} finally {
setBusy(false);
}
}
}
private class UploadBitmap extends AsyncTask<Void, Void, Void> {
private String ipAddress;
private Bitmap bitmap;
public UploadBitmap(String theIpAddress, Bitmap theBitmap) {
ipAddress = theIpAddress;
bitmap = theBitmap;
}
@Override
protected Void doInBackground(Void... params) {
int aHeight = bitmap.getHeight();
int aWidth = bitmap.getWidth();
try {
setBusy(true);
Socket aSocket = new Socket(ipAddress, 7778);
OutputStream anOS = aSocket.getOutputStream();
InputStream anIS = aSocket.getInputStream();
anOS.write(new byte[] {'L', 'S', 0x00, 0x01, 'L'});
anOS.write(new byte[] {'L', 'S', 0x00, 0x01, 'B'});
anOS.write(aHeight%256);
anOS.write(aHeight/256);
anOS.write(aWidth%256);
anOS.write(aWidth/256);
for (int i = 0; i < aWidth; i++) {
for (int j = 0; j < aHeight; j++) {
int aPixel = bitmap.getPixel(i, j);
anOS.write(Color.red(aPixel));
anOS.write(Color.green(aPixel));
anOS.write(Color.blue(aPixel));
}
}
anOS.write(0x00); // why?
anOS.flush();
showResultFromLightStick(anIS);
anIS.close();
anOS.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
setBusy(false);
}
return null;
}
}
private class StartUploaded extends AsyncTask<Void, Void, Void> {
private static final String TAG = "MA.StartUploaded";
private String ipAddress;
private int framesPerSecond;
public StartUploaded(String theIpAddress, int theFramesPerSecond) {
ipAddress = theIpAddress;
framesPerSecond = theFramesPerSecond;
}
@Override
protected Void doInBackground(Void... params) {
try {
setBusy(true);
int aDelayMs = 1000 / framesPerSecond;
Socket aSocket = new Socket(ipAddress, 7778);
OutputStream anOS = aSocket.getOutputStream();
InputStream anIS = aSocket.getInputStream();
anOS.write(new byte[] {'L', 'S', 0x00, 0x01, 'S'});
anOS.write(aDelayMs % 256);
anOS.write((aDelayMs / 256) % 256);
anOS.write(0x00);
anOS.flush();
showResultFromLightStick(anIS);
anIS.close();
anOS.close();
} catch (Exception ex) {
Log.e(TAG, "error in StartUploaded", ex);
} finally {
setBusy(false);
}
return null;
}
}
private String showResultFromLightStick(InputStream theIS) throws IOException {
final int BUFFER_SIZE = 256;
byte buffer[] = new byte[BUFFER_SIZE];
for (int i = 0; i < BUFFER_SIZE; i++) buffer[i] = 0;
int aNumBytes = theIS.read(buffer, 0, BUFFER_SIZE);
String aResult = new String(buffer, 0, aNumBytes);
if (!"OK".equals(aResult)) {
alertDialogDisplay.setMessage(this, aResult);
alertDialogDisplayHandler.post(alertDialogDisplay);
}
return aResult;
}
private class BusyUpdater implements Runnable {
private boolean busy = false;
private void setBusy(boolean theBusy) {
busy = theBusy;
}
@Override
public void run() {
btnBlack.setEnabled(!busy);
btnRainbow.setEnabled(!busy);
btnWhite.setEnabled(!busy);
btnSelectFile.setEnabled(!busy);
btnStartFile.setEnabled(!busy);
btnStartFile5Sec.setEnabled(!busy);
btnUploadFile.setEnabled(!busy);
btnStartUploaded.setEnabled(!busy);
}
}
private void setBusy(boolean theBusy) {
busyUpdater.setBusy(theBusy);
busyUpdaterHandler.post(busyUpdater);
}
private class AlertDialogDisplay implements Runnable {
private Context context = null;
private String message = "???";
private void setMessage(Context theContext, String theMessage) {
context = theContext;
message = theMessage;
}
@Override
public void run() {
new AlertDialog.Builder(context)
.setTitle("FAILED")
.setMessage(message)
.setNeutralButton("Close", null)
.show();
}
}
}
| 32.845884 | 120 | 0.575153 |
ac4eee85673f7e342bf9458b634526dd690ecc18 | 1,408 | /**
* Copyright © 2021 Ingram Micro Inc. All rights reserved.
* The software in this package is published under the terms of the Apache-2.0
* license, a copy of which has been included with this distribution in the
* LICENSE file.
*/
package com.cloudblue.connect.internal.config;
import com.cloudblue.connect.internal.connection.provider.CBCConnectionProvider;
import com.cloudblue.connect.internal.operation.CreateResourceOperation;
import com.cloudblue.connect.internal.operation.DownloadResourceFileOperation;
import com.cloudblue.connect.internal.operation.GetResourceOperation;
import com.cloudblue.connect.internal.operation.ListResourcesOperation;
import com.cloudblue.connect.internal.operation.ResourceActionOperation;
import com.cloudblue.connect.internal.operation.UpdateResourceOperation;
import com.cloudblue.connect.internal.operation.UploadResourceFileOperation;
import org.mule.runtime.extension.api.annotation.Operations;
import org.mule.runtime.extension.api.annotation.connectivity.ConnectionProviders;
@Operations({
ListResourcesOperation.class,
GetResourceOperation.class,
CreateResourceOperation.class,
UpdateResourceOperation.class,
ResourceActionOperation.class,
DownloadResourceFileOperation.class,
UploadResourceFileOperation.class
})
@ConnectionProviders(CBCConnectionProvider.class)
public class CBCConfiguration {}
| 45.419355 | 82 | 0.821733 |
fb0a3e0bb01d892ea3b2426759c5f9fb9acf245a | 8,659 | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|// Copyright (C) 2017 The Android Open Source Project
end_comment
begin_comment
comment|//
end_comment
begin_comment
comment|// Licensed under the Apache License, Version 2.0 (the "License");
end_comment
begin_comment
comment|// you may not use this file except in compliance with the License.
end_comment
begin_comment
comment|// You may obtain a copy of the License at
end_comment
begin_comment
comment|//
end_comment
begin_comment
comment|// http://www.apache.org/licenses/LICENSE-2.0
end_comment
begin_comment
comment|//
end_comment
begin_comment
comment|// Unless required by applicable law or agreed to in writing, software
end_comment
begin_comment
comment|// distributed under the License is distributed on an "AS IS" BASIS,
end_comment
begin_comment
comment|// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
end_comment
begin_comment
comment|// See the License for the specific language governing permissions and
end_comment
begin_comment
comment|// limitations under the License.
end_comment
begin_package
DECL|package|com.google.gerrit.server.index.group
package|package
name|com
operator|.
name|google
operator|.
name|gerrit
operator|.
name|server
operator|.
name|index
operator|.
name|group
package|;
end_package
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|common
operator|.
name|collect
operator|.
name|ImmutableSet
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|gerrit
operator|.
name|entities
operator|.
name|AccountGroup
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|gerrit
operator|.
name|entities
operator|.
name|RefNames
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|gerrit
operator|.
name|index
operator|.
name|IndexConfig
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|gerrit
operator|.
name|index
operator|.
name|query
operator|.
name|FieldBundle
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|gerrit
operator|.
name|server
operator|.
name|config
operator|.
name|AllUsersName
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|gerrit
operator|.
name|server
operator|.
name|git
operator|.
name|GitRepositoryManager
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|gerrit
operator|.
name|server
operator|.
name|index
operator|.
name|StalenessCheckResult
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|inject
operator|.
name|Inject
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|inject
operator|.
name|Singleton
import|;
end_import
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|IOException
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Optional
import|;
end_import
begin_import
import|import
name|org
operator|.
name|eclipse
operator|.
name|jgit
operator|.
name|lib
operator|.
name|ObjectId
import|;
end_import
begin_import
import|import
name|org
operator|.
name|eclipse
operator|.
name|jgit
operator|.
name|lib
operator|.
name|Ref
import|;
end_import
begin_import
import|import
name|org
operator|.
name|eclipse
operator|.
name|jgit
operator|.
name|lib
operator|.
name|Repository
import|;
end_import
begin_comment
comment|/** * Checks if documents in the group index are stale. * *<p>An index document is considered stale if the stored SHA1 differs from the HEAD SHA1 of the * groups branch. */
end_comment
begin_class
annotation|@
name|Singleton
DECL|class|StalenessChecker
specifier|public
class|class
name|StalenessChecker
block|{
DECL|field|FIELDS
specifier|public
specifier|static
specifier|final
name|ImmutableSet
argument_list|<
name|String
argument_list|>
name|FIELDS
init|=
name|ImmutableSet
operator|.
name|of
argument_list|(
name|GroupField
operator|.
name|UUID
operator|.
name|getName
argument_list|()
argument_list|,
name|GroupField
operator|.
name|REF_STATE
operator|.
name|getName
argument_list|()
argument_list|)
decl_stmt|;
DECL|field|indexes
specifier|private
specifier|final
name|GroupIndexCollection
name|indexes
decl_stmt|;
DECL|field|repoManager
specifier|private
specifier|final
name|GitRepositoryManager
name|repoManager
decl_stmt|;
DECL|field|indexConfig
specifier|private
specifier|final
name|IndexConfig
name|indexConfig
decl_stmt|;
DECL|field|allUsers
specifier|private
specifier|final
name|AllUsersName
name|allUsers
decl_stmt|;
annotation|@
name|Inject
DECL|method|StalenessChecker ( GroupIndexCollection indexes, GitRepositoryManager repoManager, IndexConfig indexConfig, AllUsersName allUsers)
name|StalenessChecker
parameter_list|(
name|GroupIndexCollection
name|indexes
parameter_list|,
name|GitRepositoryManager
name|repoManager
parameter_list|,
name|IndexConfig
name|indexConfig
parameter_list|,
name|AllUsersName
name|allUsers
parameter_list|)
block|{
name|this
operator|.
name|indexes
operator|=
name|indexes
expr_stmt|;
name|this
operator|.
name|repoManager
operator|=
name|repoManager
expr_stmt|;
name|this
operator|.
name|indexConfig
operator|=
name|indexConfig
expr_stmt|;
name|this
operator|.
name|allUsers
operator|=
name|allUsers
expr_stmt|;
block|}
DECL|method|check (AccountGroup.UUID uuid)
specifier|public
name|StalenessCheckResult
name|check
parameter_list|(
name|AccountGroup
operator|.
name|UUID
name|uuid
parameter_list|)
throws|throws
name|IOException
block|{
name|GroupIndex
name|i
init|=
name|indexes
operator|.
name|getSearchIndex
argument_list|()
decl_stmt|;
if|if
condition|(
name|i
operator|==
literal|null
condition|)
block|{
comment|// No index; caller couldn't do anything if it is stale.
return|return
name|StalenessCheckResult
operator|.
name|notStale
argument_list|()
return|;
block|}
name|Optional
argument_list|<
name|FieldBundle
argument_list|>
name|result
init|=
name|i
operator|.
name|getRaw
argument_list|(
name|uuid
argument_list|,
name|IndexedGroupQuery
operator|.
name|createOptions
argument_list|(
name|indexConfig
argument_list|,
literal|0
argument_list|,
literal|1
argument_list|,
name|FIELDS
argument_list|)
argument_list|)
decl_stmt|;
if|if
condition|(
operator|!
name|result
operator|.
name|isPresent
argument_list|()
condition|)
block|{
comment|// The document is missing in the index.
try|try
init|(
name|Repository
name|repo
init|=
name|repoManager
operator|.
name|openRepository
argument_list|(
name|allUsers
argument_list|)
init|)
block|{
name|Ref
name|ref
init|=
name|repo
operator|.
name|exactRef
argument_list|(
name|RefNames
operator|.
name|refsGroups
argument_list|(
name|uuid
argument_list|)
argument_list|)
decl_stmt|;
comment|// Stale if the group actually exists.
if|if
condition|(
name|ref
operator|==
literal|null
condition|)
block|{
return|return
name|StalenessCheckResult
operator|.
name|notStale
argument_list|()
return|;
block|}
return|return
name|StalenessCheckResult
operator|.
name|stale
argument_list|(
literal|"Document missing in index, but found %s in the repo"
argument_list|,
name|ref
argument_list|)
return|;
block|}
block|}
try|try
init|(
name|Repository
name|repo
init|=
name|repoManager
operator|.
name|openRepository
argument_list|(
name|allUsers
argument_list|)
init|)
block|{
name|Ref
name|ref
init|=
name|repo
operator|.
name|exactRef
argument_list|(
name|RefNames
operator|.
name|refsGroups
argument_list|(
name|uuid
argument_list|)
argument_list|)
decl_stmt|;
name|ObjectId
name|head
init|=
name|ref
operator|==
literal|null
condition|?
name|ObjectId
operator|.
name|zeroId
argument_list|()
else|:
name|ref
operator|.
name|getObjectId
argument_list|()
decl_stmt|;
name|ObjectId
name|idFromIndex
init|=
name|ObjectId
operator|.
name|fromString
argument_list|(
name|result
operator|.
name|get
argument_list|()
operator|.
name|getValue
argument_list|(
name|GroupField
operator|.
name|REF_STATE
argument_list|)
argument_list|,
literal|0
argument_list|)
decl_stmt|;
if|if
condition|(
name|head
operator|.
name|equals
argument_list|(
name|idFromIndex
argument_list|)
condition|)
block|{
return|return
name|StalenessCheckResult
operator|.
name|notStale
argument_list|()
return|;
block|}
return|return
name|StalenessCheckResult
operator|.
name|stale
argument_list|(
literal|"Document has unexpected ref state (%s != %s)"
argument_list|,
name|head
argument_list|,
name|idFromIndex
argument_list|)
return|;
block|}
block|}
block|}
end_class
end_unit
| 14.079675 | 185 | 0.806098 |
deea5b808a76102d112e960d2ad66d03ed1a51d1 | 1,252 | package br.com.eduspaceandroid.cursoandroid.eduspace.Adapter;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import br.com.eduspaceandroid.cursoandroid.eduspace.fragment.ManhaFragment;
import br.com.eduspaceandroid.cursoandroid.eduspace.fragment.NoiteFragment;
import br.com.eduspaceandroid.cursoandroid.eduspace.fragment.TardeFragment;
public class TabAdapter extends FragmentStatePagerAdapter {
private String[] tituloAbas= {"MANHÃ","TARDE","NOITE"};
public TabAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position){
case 0:
fragment=new ManhaFragment();
break;
case 1:
fragment=new TardeFragment();
break;
case 2:
fragment=new NoiteFragment();
break;
}
return fragment;
}
@Override
public int getCount() {
return tituloAbas.length;
}
@Override
public CharSequence getPageTitle(int position) {
return tituloAbas[position];
}
}
| 27.217391 | 75 | 0.654153 |
6c98f007f4235f85ff307e9991b22d08aa01de22 | 2,477 | package de.gw.auto.reports;
import net.sf.dynamicreports.jasper.builder.JasperReportBuilder;
import net.sf.dynamicreports.report.builder.DynamicReports;
import net.sf.dynamicreports.report.builder.column.Columns;
import net.sf.dynamicreports.report.builder.component.Components;
import net.sf.dynamicreports.report.constant.PageOrientation;
import net.sf.dynamicreports.report.constant.PageType;
import net.sf.dynamicreports.report.exception.DRException;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import de.gw.auto.dao.Settings;
import de.gw.auto.service.implementation.TankenService;
@Controller
public class Report {
@Autowired
private TankenService tankenService;
private Settings setting;
protected Report() {
}
public void init(Settings settings) {
this.setting = setting;
}
public void build() {
JasperReportBuilder report = DynamicReports.report();
report.columns(Columns.column("Datum", "datum",
DynamicReports.type.dateType()), Columns.column("Benzinart",
"benzinArt.name", DynamicReports.type.stringType()), Columns
.column("Km-Stand", "kmStand",
DynamicReports.type.integerType()),
Columns.column("gefahren Km", "gefahreneKm",
DynamicReports.type.integerType()), Columns.column(
"Verbrauch auf 100Km", "verbrauch100Km",
DynamicReports.type.bigDecimalType()), Columns.column(
"Ort", "ort.ort", DynamicReports.type.stringType()),
Columns.column("Land", "land.name",
DynamicReports.type.stringType()), Columns.column(
"Tankinhalt", "tank.beschreibung",
DynamicReports.type.stringType()),
Columns.column("Liter", "liter",
DynamicReports.type.bigDecimalType()), Columns.column(
"Preis pro Liter", "preisProLiter",
DynamicReports.type.bigDecimalType()), Columns.column(
"Kosten", "kosten",
DynamicReports.type.bigDecimalType()));
report.title(Components.text("Test")
);
report.setDataSource(getDatasource());
report.setPageFormat(PageType.A4, PageOrientation.LANDSCAPE);
try {
report.show();
} catch (DRException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private JRDataSource getDatasource() {
tankenService.init(this.setting);
return new JRBeanCollectionDataSource(tankenService.getPrintList());
}
}
| 32.168831 | 70 | 0.750505 |
09501b1800aaa452914eea8511890fb9c68e564e | 7,385 | /* ** GENEREATED FILE - DO NOT MODIFY ** */
package com.wilutions.mslib.outlook;
import com.wilutions.com.*;
/**
* RuleActions.
*
*/
@CoClass(guid="{000610CE-0000-0000-C000-000000000046}")
public class RuleActions extends Dispatch implements _RuleActions {
static boolean __typelib__loaded = __TypeLib.load();
@DeclDISPID(61440) public _Application getApplication() throws ComException {
final Object obj = this._dispatchCall(61440,"Application", DISPATCH_PROPERTYGET,null);
if (obj == null) return null;
return Dispatch.as(obj, com.wilutions.mslib.outlook.impl._ApplicationImpl.class);
}
@DeclDISPID(61450) public OlObjectClass getClass_() throws ComException {
final Object obj = this._dispatchCall(61450,"Class", DISPATCH_PROPERTYGET,null);
if (obj == null) return null;
return OlObjectClass.valueOf((Integer)obj);
}
@DeclDISPID(61451) public _NameSpace getSession() throws ComException {
final Object obj = this._dispatchCall(61451,"Session", DISPATCH_PROPERTYGET,null);
if (obj == null) return null;
return Dispatch.as(obj, com.wilutions.mslib.outlook.impl._NameSpaceImpl.class);
}
@DeclDISPID(61441) public IDispatch getParent() throws ComException {
final Object obj = this._dispatchCall(61441,"Parent", DISPATCH_PROPERTYGET,null);
if (obj == null) return null;
return (IDispatch)obj;
}
@DeclDISPID(80) public Integer getCount() throws ComException {
final Object obj = this._dispatchCall(80,"Count", DISPATCH_PROPERTYGET,null);
if (obj == null) return null;
return (Integer)obj;
}
@DeclDISPID(81) public _RuleAction Item(final Integer Index) throws ComException {
assert(Index != null);
final Object obj = this._dispatchCall(81,"Item", DISPATCH_METHOD,null,Index);
if (obj == null) return null;
return Dispatch.as(obj, com.wilutions.mslib.outlook.impl._RuleActionImpl.class);
}
@DeclDISPID(64274) public MoveOrCopyRuleAction getCopyToFolder() throws ComException {
final Object obj = this._dispatchCall(64274,"CopyToFolder", DISPATCH_PROPERTYGET,null);
if (obj == null) return null;
final Dispatch disp = (Dispatch)obj;
return disp.as(MoveOrCopyRuleAction.class);
}
@DeclDISPID(64275) public RuleAction getDeletePermanently() throws ComException {
final Object obj = this._dispatchCall(64275,"DeletePermanently", DISPATCH_PROPERTYGET,null);
if (obj == null) return null;
final Dispatch disp = (Dispatch)obj;
return disp.as(RuleAction.class);
}
@DeclDISPID(61509) public RuleAction getDelete() throws ComException {
final Object obj = this._dispatchCall(61509,"Delete", DISPATCH_PROPERTYGET,null);
if (obj == null) return null;
final Dispatch disp = (Dispatch)obj;
return disp.as(RuleAction.class);
}
@DeclDISPID(64279) public RuleAction getDesktopAlert() throws ComException {
final Object obj = this._dispatchCall(64279,"DesktopAlert", DISPATCH_PROPERTYGET,null);
if (obj == null) return null;
final Dispatch disp = (Dispatch)obj;
return disp.as(RuleAction.class);
}
@DeclDISPID(64278) public RuleAction getNotifyDelivery() throws ComException {
final Object obj = this._dispatchCall(64278,"NotifyDelivery", DISPATCH_PROPERTYGET,null);
if (obj == null) return null;
final Dispatch disp = (Dispatch)obj;
return disp.as(RuleAction.class);
}
@DeclDISPID(64277) public RuleAction getNotifyRead() throws ComException {
final Object obj = this._dispatchCall(64277,"NotifyRead", DISPATCH_PROPERTYGET,null);
if (obj == null) return null;
final Dispatch disp = (Dispatch)obj;
return disp.as(RuleAction.class);
}
@DeclDISPID(64276) public RuleAction getStop() throws ComException {
final Object obj = this._dispatchCall(64276,"Stop", DISPATCH_PROPERTYGET,null);
if (obj == null) return null;
final Dispatch disp = (Dispatch)obj;
return disp.as(RuleAction.class);
}
@DeclDISPID(64280) public MoveOrCopyRuleAction getMoveToFolder() throws ComException {
final Object obj = this._dispatchCall(64280,"MoveToFolder", DISPATCH_PROPERTYGET,null);
if (obj == null) return null;
final Dispatch disp = (Dispatch)obj;
return disp.as(MoveOrCopyRuleAction.class);
}
@DeclDISPID(64281) public SendRuleAction getCC() throws ComException {
final Object obj = this._dispatchCall(64281,"CC", DISPATCH_PROPERTYGET,null);
if (obj == null) return null;
final Dispatch disp = (Dispatch)obj;
return disp.as(SendRuleAction.class);
}
@DeclDISPID(64282) public SendRuleAction getForward() throws ComException {
final Object obj = this._dispatchCall(64282,"Forward", DISPATCH_PROPERTYGET,null);
if (obj == null) return null;
final Dispatch disp = (Dispatch)obj;
return disp.as(SendRuleAction.class);
}
@DeclDISPID(64283) public SendRuleAction getForwardAsAttachment() throws ComException {
final Object obj = this._dispatchCall(64283,"ForwardAsAttachment", DISPATCH_PROPERTYGET,null);
if (obj == null) return null;
final Dispatch disp = (Dispatch)obj;
return disp.as(SendRuleAction.class);
}
@DeclDISPID(64284) public SendRuleAction getRedirect() throws ComException {
final Object obj = this._dispatchCall(64284,"Redirect", DISPATCH_PROPERTYGET,null);
if (obj == null) return null;
final Dispatch disp = (Dispatch)obj;
return disp.as(SendRuleAction.class);
}
@DeclDISPID(64290) public AssignToCategoryRuleAction getAssignToCategory() throws ComException {
final Object obj = this._dispatchCall(64290,"AssignToCategory", DISPATCH_PROPERTYGET,null);
if (obj == null) return null;
final Dispatch disp = (Dispatch)obj;
return disp.as(AssignToCategoryRuleAction.class);
}
@DeclDISPID(64291) public PlaySoundRuleAction getPlaySound() throws ComException {
final Object obj = this._dispatchCall(64291,"PlaySound", DISPATCH_PROPERTYGET,null);
if (obj == null) return null;
final Dispatch disp = (Dispatch)obj;
return disp.as(PlaySoundRuleAction.class);
}
@DeclDISPID(64294) public MarkAsTaskRuleAction getMarkAsTask() throws ComException {
final Object obj = this._dispatchCall(64294,"MarkAsTask", DISPATCH_PROPERTYGET,null);
if (obj == null) return null;
final Dispatch disp = (Dispatch)obj;
return disp.as(MarkAsTaskRuleAction.class);
}
@DeclDISPID(64296) public NewItemAlertRuleAction getNewItemAlert() throws ComException {
final Object obj = this._dispatchCall(64296,"NewItemAlert", DISPATCH_PROPERTYGET,null);
if (obj == null) return null;
final Dispatch disp = (Dispatch)obj;
return disp.as(NewItemAlertRuleAction.class);
}
@DeclDISPID(64530) public RuleAction getClearCategories() throws ComException {
final Object obj = this._dispatchCall(64530,"ClearCategories", DISPATCH_PROPERTYGET,null);
if (obj == null) return null;
final Dispatch disp = (Dispatch)obj;
return disp.as(RuleAction.class);
}
public RuleActions() throws ComException {
super("{000610CE-0000-0000-C000-000000000046}", "{000630CE-0000-0000-C000-000000000046}");
}
protected RuleActions(long ndisp) {
super(ndisp);
}
public String toString() {
return "[RuleActions" + super.toString() + "]";
}
}
| 47.645161 | 100 | 0.714557 |
543ef94c69d7a47f963dc03a0ffd85bd22f3d5fe | 2,671 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 com.gemstone.gemfire.pdx;
import org.junit.After;
import org.junit.Before;
import org.junit.experimental.categories.Category;
import com.gemstone.gemfire.internal.offheap.Chunk;
import com.gemstone.gemfire.internal.offheap.NullOffHeapMemoryStats;
import com.gemstone.gemfire.internal.offheap.NullOutOfOffHeapMemoryListener;
import com.gemstone.gemfire.internal.offheap.SimpleMemoryAllocatorImpl;
import com.gemstone.gemfire.internal.offheap.StoredObject;
import com.gemstone.gemfire.internal.offheap.UnsafeMemoryChunk;
import com.gemstone.gemfire.internal.tcp.ByteBufferInputStream.ByteSource;
import com.gemstone.gemfire.internal.tcp.ByteBufferInputStream.ByteSourceFactory;
import com.gemstone.gemfire.internal.tcp.ByteBufferInputStream.OffHeapByteSource;
import com.gemstone.gemfire.test.junit.categories.UnitTest;
@Category(UnitTest.class)
public class OffHeapByteSourceJUnitTest extends ByteSourceJUnitTest {
@Before
public void setUp() throws Exception {
SimpleMemoryAllocatorImpl.create(new NullOutOfOffHeapMemoryListener(), new NullOffHeapMemoryStats(), new UnsafeMemoryChunk[]{new UnsafeMemoryChunk(1024*1024)});
}
@After
public void tearDown() throws Exception {
SimpleMemoryAllocatorImpl.freeOffHeapMemory();
}
@Override
protected boolean isTestOffHeap() {
return true;
}
@Override
protected ByteSource createByteSource(byte[] bytes) {
StoredObject so = SimpleMemoryAllocatorImpl.getAllocator().allocateAndInitialize(bytes, false, false, null);
if (so instanceof Chunk) {
// bypass the factory to make sure that OffHeapByteSource is tested
return new OffHeapByteSource((Chunk)so);
} else {
// bytes are so small they can be encoded in a long (see DataAsAddress).
// So for this test just wrap the original bytes.
return ByteSourceFactory.wrap(bytes);
}
}
}
| 40.469697 | 164 | 0.781355 |
59c08d5feba344b9cf8370177b5e624e4dc98d02 | 2,795 | package io.ganguo.app.gcache;
import io.ganguo.app.gcache.disk.DiskBasedCache;
import io.ganguo.app.gcache.disk.DiskWithMemoryCache;
import io.ganguo.app.gcache.interfaces.GCache;
import io.ganguo.app.gcache.interfaces.Transcoder;
import io.ganguo.app.gcache.memory.MemoryCache;
import io.ganguo.app.gcache.transcoder.StringTranscoder;
import java.io.File;
public class CacheBuilder {
public enum Type {
DISK, MEMORY, DISK_WITH_MEMORY
}
public static Builder newBuilder() {
return new Builder(Type.DISK_WITH_MEMORY);
}
public static Builder newBuilderForMemory() {
return new Builder(Type.MEMORY);
}
public static Builder newBuilderForDisk() {
return new Builder(Type.DISK);
}
public static class Builder {
private Type type = Type.DISK_WITH_MEMORY;
private Config config = new Config();
private GCache gcache = null;
public Builder(Type type) {
this.type = type;
}
public Builder withTranscoder(Transcoder transcoder) {
switch (type) {
case DISK_WITH_MEMORY:
this.gcache = new DiskWithMemoryCache(transcoder);
break;
case MEMORY:
this.gcache = new MemoryCache(transcoder);
break;
case DISK:
this.gcache = new DiskBasedCache(transcoder);
break;
}
return this;
}
public Builder maxMemoryUsageBytes(long memoryUsageBytes) {
config.setMemoryUsageBytes(memoryUsageBytes);
return this;
}
public Builder maxDiskUsageBytes(long diskUsageBytes) {
config.setDiskUsageBytes(diskUsageBytes);
return this;
}
public Builder minCacheTime(int minCacheTime) {
config.setMinCacheTime(minCacheTime);
return this;
}
public Builder maxCacheTime(int maxCacheTime) {
config.setMaxCacheTime(maxCacheTime);
return this;
}
public Builder defaultCacheTime(int defaultCacheTime) {
config.setDefaultCacheTime(defaultCacheTime);
return this;
}
public Builder withCacheRootDirectory(File cacheRootDirectory) {
config.setCacheRootDirectory(cacheRootDirectory);
return this;
}
public GCache build() {
this.gcache.config(config);
this.gcache.initialize();
return this.gcache;
}
}
public static void main(String[] args) {
GCache gc = CacheBuilder.newBuilder()
.withTranscoder(new StringTranscoder())
.maxMemoryUsageBytes(20000)
.maxDiskUsageBytes(40000).maxCacheTime(3000)
.minCacheTime(1000).defaultCacheTime(1000)
.build();
GCache gc2 = CacheBuilder.newBuilderForMemory()
.withTranscoder(new StringTranscoder())
.maxMemoryUsageBytes(20000).maxCacheTime(3000)
.minCacheTime(1000).defaultCacheTime(1000)
.build();
GCache gc3 = CacheBuilder.newBuilderForDisk()
.withTranscoder(new StringTranscoder())
.maxDiskUsageBytes(40000).maxCacheTime(3000)
.minCacheTime(1000).defaultCacheTime(1000)
.build();
}
}
| 25.642202 | 66 | 0.742755 |
61f89e447b9511a0fd33fb054206e46e31bb9d00 | 1,495 | /*
* Copyright 2020 MISHMASH I O OOD
*
* 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 io.mishmash.common.ipc.client;
import io.mishmash.common.exception.MishmashException;
/**
* A leave method for a client builder.
*
* @param <I> - the GRPC input message type
* @param <O> - the GRPC output message type
* @param <CT> - the GRPC {@link BaseClient} type
* @param <MT> - the {@link ClientMishmash} type
* @param <BT> - the builder that will be left
*/
@FunctionalInterface
public interface BuilderLeave<
I, O,
CT extends BaseClient<I, O>,
MT extends ClientMishmash<I, O, CT>,
BT extends BaseClientMishmashBuilder<I, O, CT, MT>> {
/**
* Leave the builder.
*
* @param left - the builder that is being left
* @return - the new builder
* @throws MishmashException - thrown on failure
*/
BaseClientMishmashBuilder<I, O, CT, MT> leave(BT left)
throws MishmashException;
}
| 31.808511 | 75 | 0.676923 |
a798f07f1ae0c3a83d1f51896601448d6fe90612 | 1,419 | /*
* 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.aliyuncs.sofa.transform.v20190815;
import com.aliyuncs.sofa.model.v20190815.GetMiddlewareInstanceResponse;
import com.aliyuncs.transform.UnmarshallerContext;
public class GetMiddlewareInstanceResponseUnmarshaller {
public static GetMiddlewareInstanceResponse unmarshall(GetMiddlewareInstanceResponse getMiddlewareInstanceResponse, UnmarshallerContext _ctx) {
getMiddlewareInstanceResponse.setRequestId(_ctx.stringValue("GetMiddlewareInstanceResponse.RequestId"));
getMiddlewareInstanceResponse.setResultCode(_ctx.stringValue("GetMiddlewareInstanceResponse.ResultCode"));
getMiddlewareInstanceResponse.setResultMessage(_ctx.stringValue("GetMiddlewareInstanceResponse.ResultMessage"));
getMiddlewareInstanceResponse.setData(_ctx.stringValue("GetMiddlewareInstanceResponse.Data"));
return getMiddlewareInstanceResponse;
}
} | 44.34375 | 144 | 0.817477 |
89747df1f7d0350bc0087f8bcd7ced8452ec72fb | 858 | package com.shengfq.jvm;
import java.util.Vector;
public class HeapAlloc {
public static void main(String[] args) {
printDumpOOM();
}
public static void printMemory(){
printRuntime();
byte[] b=new byte[1*1024*1024];
System.out.println("分配了1M空间给数组");
printRuntime();
b = new byte[4*1024*1024];
System.out.println("分配了4M空间给数组");
printRuntime();
}
public static void printRuntime(){
System.out.println("maxMemory=");
System.out.println(Runtime.getRuntime().maxMemory()+"bytes");
System.out.println("free mem=");
System.out.println(Runtime.getRuntime().freeMemory()+"bytes");
System.out.println("total mem=");
System.out.println(Runtime.getRuntime().totalMemory()+"bytes");
}
public static void printDumpOOM(){
Vector v = new Vector();
for (int i = 0; i < 25; i++) {
v.add(new byte[1*1024*1024]);
}
}
}
| 22.578947 | 65 | 0.670163 |
36b60697dfc5f72f7a67d0abc4d2b5e862286130 | 5,338 | package com.ideandadream.rainydaygames;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import static java.sql.DriverManager.println;
public class MainActivity extends AppCompatActivity {
//the number of times the upScore button has been pressed the highest score
private int score;
private int highScore;
//The textview that holds the score and the textview that holds the high score
private TextView textScore;
private TextView textHighScore;
//The Button
Button buttonUpScore;
Button buttonSendReset;
Button buttonFetch;
private RequestQueue mQueue;
String sever_url = "http://proj309-vc-04.misc.iastate.edu:8080/scores?userid=2&game=1";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonUpScore = (Button) findViewById(R.id.buttonUpScore);
buttonSendReset= (Button) findViewById(R.id.buttonSendReset);
buttonFetch = (Button) findViewById(R.id.fetchScore);
score = 0;
textScore = (TextView) findViewById(R.id.textScore);
String resultObjScore;
mQueue = Volley.newRequestQueue(this);
//TODO set the highscore to the highest score in the database. Or change to last score or w.e
/** Need to get the highest score in the db
* set it to highscore
* change the inside of textHighScore
*
*Should probably aso do this in method, but that's a later thing.
* Let's just ace this demo first
*/
highScore = 0;
textHighScore = (TextView) findViewById(R.id.textHighScore);
getData();
//Handles the user clicking the upScore button
buttonUpScore.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Increments the score
score++;
//Sets the text in the score text view to reflect the score
textScore.setText("Score: " + score);
}
});
buttonFetch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Increments the score
getData();
}
});
buttonSendReset.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendData();
// getData();
//TODO post the current score
//Resets the score to 0
//Resets the score text to nothing, bad OOP I know. Probably should make an update method
// textScore.setText("Score: ");
//TODO get the high score
//TODO reset the text view that has the highscore
// textHighScore.setText("High Score: " + score);
}
});
}
private void getData()
{
StringRequest stringRequest = new StringRequest(Request.Method.GET, sever_url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// Log.d("response",response);
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
Score[] scores = gson.fromJson(response, Score[].class);
textHighScore.setText("High Score: " + scores[0].getScore().toString());
score = scores[0].getScore();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
mQueue.add(stringRequest);
}
private void sendData()
{
String server_url_post = "http://proj309-vc-04.misc.iastate.edu:8080/scores/new?userid=2&game=1&score="+score;
StringRequest stringRequest = new StringRequest(Request.Method.POST, server_url_post, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Toast.makeText(getApplication(), response, Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplication(), error+"", Toast.LENGTH_SHORT).show();
}
});
mQueue.add(stringRequest);
}
}
| 35.825503 | 132 | 0.604159 |
3e3ec3959fd74d617885d3c4810bd9264dd604b7 | 3,272 | /*
* -----------------------------------------------------------------------------
* VIPER SOFTWARE SERVICES
* -----------------------------------------------------------------------------
*
* MIT License
*
* Copyright (c) #{classname}.html #{util.YYYY()} Viper Software Services
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE
*
* -----------------------------------------------------------------------------
*/
package com.viper.database.filters;
import java.util.Comparator;
import java.util.List;
import com.viper.database.dao.DatabaseUtil;
import com.viper.database.model.ColumnParam;
import com.viper.database.model.SortType;
public class SortByOrder<T> implements Comparator<T> {
List<ColumnParam> columnParams;
public SortByOrder(List<ColumnParam> columnParams) {
this.columnParams = columnParams;
for (ColumnParam param : columnParams) {
System.out.println("MemoryAdapter: SortByOrder: " + param.getName() + " by " + param.getOrderBy());
}
}
public int compare(T a, T b) {
for (ColumnParam param : columnParams) {
if (param.getOrderBy() == SortType.NONE) {
continue;
}
int sgn = (param.getOrderBy() == SortType.ASCEND) ? 1 : -1;
String fieldname = param.getName().substring(param.getName().lastIndexOf('.') + 1);
Object v1 = DatabaseUtil.getValue(a, fieldname);
Object v2 = DatabaseUtil.getValue(b, fieldname);
if (v1 == null && v2 == null) {
return 0;
}
if (v1 == null) {
return -1 * sgn;
}
if (v2 == null) {
return 1 * sgn;
}
if (v1 instanceof Number) {
int dx = (int) (((Number) v1).longValue() - ((Number) v2).longValue());
if (dx != 0) {
return dx * sgn;
}
}
String s1 = v1.toString().toLowerCase();
String s2 = v2.toString().toLowerCase();
int dx = (s1).compareTo(s2);
if (dx != 0) {
return dx * sgn;
}
}
return 0;
}
}
| 37.609195 | 111 | 0.558985 |
dee702889299c2fbd0521a0312c372587b537633 | 2,333 | /*
* Copyright 2008-2009 the original author or authors.
*
* 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 net.hasor.dataql.runtime;
import net.hasor.dataql.compiler.ast.CodeLocation;
import net.hasor.dataql.compiler.ast.CodeLocation.CodeLocationInfo;
/**
* 位置
* @author 赵永春 ([email protected])
* @version : 2020-06-11
*/
public abstract class Location extends CodeLocationInfo {
public String toErrorMessage() {
return "line " + super.toString();
}
public static class RuntimeLocation extends Location {
private int methodAddress = -1; // 方法地址
private int programAddress = -1; // 执行指针
private RuntimeLocation(CodeLocation codeLocation, int methodAddress, int programAddress) {
setStartPosition(codeLocation.getStartPosition());
setEndPosition(codeLocation.getEndPosition());
this.methodAddress = methodAddress;
this.programAddress = programAddress;
}
public int getMethodAddress() {
return this.methodAddress;
}
public int getProgramAddress() {
return this.programAddress;
}
public String toErrorMessage() {
return super.toErrorMessage() + " ,QIL " + this.methodAddress + ":" + this.programAddress;
}
}
public static RuntimeLocation atRuntime(CodeLocation codeLocation, int methodAddress, int programAddress) {
return new RuntimeLocation(codeLocation, methodAddress, programAddress);
}
public static RuntimeLocation unknownLocation() {
CodeLocationInfo codeLocation = new CodeLocationInfo();
codeLocation.setStartPosition(new CodePosition(-1, -1));
codeLocation.setEndPosition(new CodePosition(-1, -1));
return new RuntimeLocation(codeLocation, -1, -1);
}
} | 36.453125 | 111 | 0.690956 |
3fed77102c60decda99a2638d0f4675ad1d13843 | 2,277 | package com.cluster.employeeproject.entity;
// Generated Feb 28, 2013 3:50:08 PM by Hibernate Tools 3.4.0.CR1
import java.math.BigDecimal;
import javax.persistence.Column;
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.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import com.cluster.employeeproject.common.entity.BaseDO;
/**
* EmployeePhone generated by hbm2java
*/
@Entity
@Table(name = "EMPLOYEE_PHONE", schema = "employeeproject")
public class EmployeePhone extends BaseDO implements java.io.Serializable {
private long employeePhoneId;
private PhoneType phoneType;
private Employee employee;
private String phoneNo;
public EmployeePhone() {
}
public EmployeePhone(long employeePhoneId) {
this.employeePhoneId = employeePhoneId;
}
public EmployeePhone(long employeePhoneId, PhoneType phoneType,
Employee employee, String phoneNo) {
this.employeePhoneId = employeePhoneId;
this.phoneType = phoneType;
this.employee = employee;
this.phoneNo = phoneNo;
}
@Id
@Column(name = "EMPLOYEE_PHONE_ID", unique = true, nullable = false, precision = 22, scale = 0)
/*@SequenceGenerator(name="employeePhone", sequenceName="EMPLOYEE_PHONE_SEQ")
@GeneratedValue(generator="employeePhone")*/
@GeneratedValue(strategy=GenerationType.AUTO)
public long getEmployeePhoneId() {
return this.employeePhoneId;
}
public void setEmployeePhoneId(long employeePhoneId) {
this.employeePhoneId = employeePhoneId;
}
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "PHONE_TYPE_ID")
public PhoneType getPhoneType() {
return this.phoneType;
}
public void setPhoneType(PhoneType phoneType) {
this.phoneType = phoneType;
}
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "EMPLOYEE_ID")
public Employee getEmployee() {
return this.employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
@Column(name = "PHONE_NO", length = 50)
public String getPhoneNo() {
return this.phoneNo;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
}
| 25.58427 | 96 | 0.77119 |
b79a5ae5f0dc511a2cd0ff966d70a87968468413 | 3,733 | /**
* Copyright 2007-2015, Kaazing Corporation. All rights reserved.
*
* 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.kaazing.k3po.launcher;
import java.io.File;
import java.net.URI;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.Parser;
import org.apache.commons.cli.PosixParser;
import org.kaazing.k3po.driver.internal.RobotServer;
/**
* Launcher / CLI to run the K3PO.
*
*/
public final class Launcher {
private Launcher() {
// no instances
}
/**
* Main entry point to running K3PO.
* @param args to run with
* @throws Exception if fails to run
*/
public static void main(String... args) throws Exception {
Options options = createOptions();
try {
Parser parser = new PosixParser();
CommandLine cmd = parser.parse(options, args);
if (cmd.hasOption("version")) {
System.out.println("Version: " + Launcher.class.getPackage().getImplementationVersion());
}
String scriptPathEntries = cmd.getOptionValue("scriptpath", "src/test/scripts");
String[] scriptPathEntryArray = scriptPathEntries.split(";");
List<URL> scriptUrls = new ArrayList<>();
for (String scriptPathEntry : scriptPathEntryArray) {
File scriptEntryFilePath = new File(scriptPathEntry);
scriptUrls.add(scriptEntryFilePath.toURI().toURL());
}
String controlURI = cmd.getOptionValue("control");
if (controlURI == null) {
controlURI = "tcp://localhost:11642";
}
boolean verbose = cmd.hasOption("verbose");
URLClassLoader scriptLoader = new URLClassLoader(scriptUrls.toArray(new URL[0]));
RobotServer server = new RobotServer(URI.create(controlURI), verbose, scriptLoader);
server.start();
server.join();
} catch (ParseException ex) {
HelpFormatter helpFormatter = new HelpFormatter();
helpFormatter.printHelp(Launcher.class.getSimpleName(), options, true);
}
}
private static Options createOptions() {
Options options = new Options();
Option scriptPath = new Option(null, "scriptpath", true,
"Path(s) to directory/jar for script(s) lookup. Multiple entries should be separated by semicolon.");
Option control = new Option(null, "control", true, "location to listen for K3PO control connections");
Option verbose = new Option(null, "verbose", false, "verbose");
Option version = new Option(null, "version", false, "version");
options.addOption(scriptPath);
options.addOption(control);
options.addOption(verbose);
options.addOption(version);
return options;
}
}
| 36.960396 | 118 | 0.641575 |
bb85fae1a77615514631eef8369051e257d4b3dc | 1,972 | package org.ffpy.easyexcel;
import com.sun.istack.internal.Nullable;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* 属性辅助类
*/
class PropertyHelper {
private PropertyDescriptor propertyDescriptor;
/**
* 创建一个PropertyHelper对象
*
* @param propertyDescriptor 属性描述符
* @return PropertyHelper对象
*/
public static PropertyHelper of(PropertyDescriptor propertyDescriptor) {
return new PropertyHelper(propertyDescriptor);
}
/**
* @param propertyDescriptor 属性描述符
*/
private PropertyHelper(PropertyDescriptor propertyDescriptor) {
this.propertyDescriptor = propertyDescriptor;
}
/**
* 获取属性描述符
*
* @return 属性描述符
*/
public PropertyDescriptor getPropertyDescriptor() {
return propertyDescriptor;
}
/**
* 获取属性的值
*
* @param bean Bean对象类型
* @param name 属性名
* @param <T> 属性类型
* @return 属性的值
*/
public <T> T getProperty(Object bean) {
try {
Method method = propertyDescriptor.getReadMethod();
if (method == null)
throw new IllegalArgumentException(getName() + "没有getter方法");
//noinspection unchecked
return (T) method.invoke(bean);
} catch (IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
/**
* 设置属性的值
*
* @param bean Bean对象类型
* @param name 属性名
* @param value 属性值
*/
public void setProperty(Object bean, @Nullable Object value) {
try {
Method method = propertyDescriptor.getWriteMethod();
if (method == null)
throw new IllegalArgumentException(getName() + "没有setter方法");
method.invoke(bean, value);
} catch (IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
/**
* 获取属性类型
*
* @return 属性类型
*/
public Class<?> getPropertyType() {
return propertyDescriptor.getPropertyType();
}
/**
* 获取属性名
*
* @return 属性名
*/
public String getName() {
return propertyDescriptor.getName();
}
}
| 20.329897 | 73 | 0.699797 |
e369a08a00ace83782f5a1057004c8c3f8df6712 | 150 | package club.yuit.oauth.boot.support.properities;
/**
* @author yuit
* @date 2019/11/26 15:33
**/
public enum CodeStoreType {
session,redis
}
| 15 | 49 | 0.686667 |
4b947239d51f2e7265b0e9d0226ddb8a336e1222 | 1,786 | package com.miicaa.base.share.contact;
import java.util.ArrayList;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import com.miicaa.base.share.ShareMain;
import com.miicaa.home.ui.contactGet.ContactViewShow;
import com.miicaa.home.ui.contactList.ContactUtil;
import com.miicaa.home.ui.pay.PayUtils;
import com.miicaa.home.view.LabelEditView;
public class AddContactMain extends ShareMain {
public AddContactMain(Context mContext) {
super(mContext);
// TODO Auto-generated constructor stub
}
public static final int REQUEST_CODE = 0X5;
ArrayList<Contact> mUsers;
String mRoundJson;
LabelEditView mView;
public ArrayList<Contact> getmUser() {
return mUsers;
}
public void setmUser(ArrayList<Contact> mUsers) {
this.mUsers = mUsers;
}
@Override
public void setRootView(View view) {
super.setRootView(view);
mView = (LabelEditView) view;
}
@Override
public void start(){
ShowContactActivity_.intent(mContext)
.startForResult(REQUEST_CODE);
super.start();
}
@Override
public boolean invalide(){
if(mUsers==null||mUsers.size()<1){
PayUtils.showToast(mContext, "联系人不能为空", 3000);
return false;
}
return true;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
mUsers = (ArrayList<Contact>) data.getSerializableExtra("data");
if (mUsers == null || mUsers.size() == 0) {
mView.setContent("");
return;
}
setCopyData(mUsers,mView);
}
public void setCopyData(ArrayList<Contact> data,LabelEditView mView){
if (data.size() > 1) {
mView.setContent(data.get(0).getmName() + "等" + data.size()
+ "个联系人");
} else if (data.size() == 1) {
mView.setContent(data.get(0).getmName());
} else {
mView.setContent("");
}
}
}
| 23.194805 | 77 | 0.714446 |
16a0e3325081c2f028218869d20bcb009d90ed57 | 1,339 | class Program1 {
static int fn(int n) {
if (n == 0) {
return 1;
} else if (n == 1) {
return 3;
} else if (n == 2) {
return 2;
} else if (n % 2 == 1) {
return fn(n - 1) - 2 * fn(n - 2);
} else {
return fn(n - 2) + 3 * fn(n - 3);
}
}
static int fn_akum(int f0, int f1, int f2, int i, int n) {
if (n > 2) {
if (i > n) {
return f2;
} else if (i % 2 == 1) {
return fn_akum(f1, f2, f2 - 2 * f1, i + 1, n);
} else {
return fn_akum(f1, f2, f1 + 3 * f0, i + 1, n);
}
} else {
if (n == 0) {
return 1;
} else if (n == 1) {
return 3;
} else {
return 2;
}
}
}
static int fn_iter(int n) {
int[] f = { 1, 3, 2 };
if (n > 2) {
for (int i = 3; i <= n; i++) {
int fi;
if (i % 2 == 1) {
fi = f[2] - 2 * f[1];
} else {
fi = f[1] + 3 * f[0];
}
f[0] = f[1];
f[1] = f[2];
f[2] = fi;
}
return f[2];
} else {
return f[n];
}
}
public static void main(String[] args) {
int n;
do {
n = Svetovid.in.readInt("Unesite n [0, 40]: ");
} while (n < 0 || n > 40);
System.out.println(fn(n) + " " + fn_akum(1, 3, 2, 3, n) + " " + fn_iter(n));
}
} | 20.921875 | 80 | 0.363704 |
8fed1da052f25d044a0022f88f87258ac27fa587 | 9,509 | package com.keqiang.table;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Build;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import com.keqiang.table.interfaces.CellClickListener;
import com.keqiang.table.interfaces.CellDragChangeListener;
import com.keqiang.table.interfaces.CellFactory;
import com.keqiang.table.interfaces.ICellDraw;
import com.keqiang.table.interfaces.ITable;
import com.keqiang.table.model.Cell;
import com.keqiang.table.model.ShowCell;
import com.keqiang.table.model.TableData;
import com.keqiang.table.util.AsyncExecutor;
import java.util.List;
/**
* 实现表格的绘制<br/>
* 主要类说明:
* <ul>
* <li>{@link TableConfig}用于配置一些基础的表格数据</li>
* <li>{@link TableData}用于指定表格行列数,增删行列,清除数据,记录单元格数据,用于绘制时提供每个单元格位置和大小</li>
* <li>{@link TouchHelper}用于处理点击,移动,快速滑动逻辑以及设置相关参数,获取表格滑动距离请用此类,
* 不要使用Table的{@link Table#getScrollX()}或{@link Table#getScrollY()}</li>
* <li>{@link CellFactory}用于提供单元格数据,指定固定宽高或自适应时测量宽高</li>
* <li>{@link ICellDraw}用于绘制整个表格背景和单元格内容</li>
* </ul>
*
* @author Created by 汪高皖 on 2019/1/15 0015 08:29
*/
public class Table<T extends Cell> extends View implements ITable<T> {
/**
* 屏幕上可展示的区域
*/
private Rect mShowRect;
/**
* 屏幕上可展示的区域,防止外部实际改变mShowRect
*/
private Rect mOnlyReadShowRect;
/**
* 表格数据
*/
private TableData<T> mTableData;
/**
* 表格配置
*/
private TableConfig mTableConfig;
/**
* 获取表格数据
*/
private CellFactory<T> mCellFactory;
/**
* 表格绘制
*/
private ICellDraw<T> mICellDraw;
/**
* 处理触摸逻辑
*/
private TouchHelper<T> mTouchHelper;
/**
* 确定单元格位置,固定行列逻辑
*/
private TableRender<T> mTableRender;
public Table(Context context) {
super(context);
init();
}
public Table(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public Table(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public Table(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
private void init() {
mShowRect = new Rect();
mTableData = new TableData<>(this);
mTableConfig = new TableConfig();
mTouchHelper = new TouchHelper<>(this);
mTableRender = new TableRender<>(this);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mTableRender.draw(canvas);
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
boolean dispose = mTouchHelper.dispatchTouchEvent(this, event);
boolean superDispose = super.dispatchTouchEvent(event);
return dispose || superDispose;
}
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouchEvent(MotionEvent event) {
return mTouchHelper.onTouchEvent(event);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mShowRect.set(0, 0, w, h);
mTouchHelper.onScreenSizeChange();
}
/*
滑动模型图解:https://blog.csdn.net/luoang/article/details/70912058
*/
/**
* 水平方向可滑动范围
*/
@Override
public int computeHorizontalScrollRange() {
return getActualSizeRect().right;
}
/**
* 垂直方向可滑动范围
*/
@Override
public int computeVerticalScrollRange() {
return getActualSizeRect().height();
}
/**
* 水平方向滑动偏移值
*
* @return 滑出View左边界的距离,>0的值
*/
@Override
public int computeHorizontalScrollOffset() {
return Math.max(0, mTouchHelper.getScrollX());
}
/**
* 垂直方向滑动偏移值
*
* @return 滑出View顶部边界的距离,>0的值
*/
@Override
public int computeVerticalScrollOffset() {
return Math.max(0, mTouchHelper.getScrollY());
}
/**
* 判断垂直方向是否可以滑动
*
* @param direction <0:手指滑动方向从上到下(显示内容逐渐移动到顶部),>0:手指滑动方向从下到上(显示内容逐渐移动到底部)
*/
@Override
public boolean canScrollVertically(int direction) {
if (mTouchHelper.isDragChangeSize()) {
return true;
}
if (direction < 0) {
// 向顶部滑动
return mTouchHelper.getScrollY() > 0;
} else {
// 向底部滑动
return getActualSizeRect().height() > mTouchHelper.getScrollY() + mShowRect.height();
}
}
/**
* 判断水平方向是否可以滑动
*
* @param direction <0:手指滑动方向从左到右(显示内容逐渐移动到左边界),>0:手指滑动方向从右到左(显示内容逐渐移动到右边界)
*/
@Override
public boolean canScrollHorizontally(int direction) {
if (mTouchHelper.isDragChangeSize()) {
return true;
}
if (direction < 0) {
// 向顶部滑动
return mTouchHelper.getScrollX() > 0;
} else {
// 向底部滑动
return getActualSizeRect().width() > mTouchHelper.getScrollX() + mShowRect.width();
}
}
/**
* 水平方向展示内容大小
*/
@Override
public int computeHorizontalScrollExtent() {
return mShowRect.width();
}
/**
* 垂直方向展示内容大小
*/
@Override
public int computeVerticalScrollExtent() {
return mShowRect.height();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
AsyncExecutor.getInstance().shutdown();
}
/**
* 禁止外部调用,这会导致绘制位置异常。
* 有关获取和设置滑动的ScrollY值,可通过{@link TouchHelper}操作,
* 不在此方法调用{@link TouchHelper}对应方法,还是防止一些第三库,
* 比如SmartRefreshLayout调用此方法,导致滑动到用户不希望滑动的位置
*/
@Override
public void setScrollY(int value) {
// super.setScrollY(value);
}
/**
* 禁止外部调用,这会导致绘制位置异常。
* 有关获取和设置滑动的ScrollX值,可通过{@link TouchHelper}操作,
* 不在此方法调用{@link TouchHelper}对应方法,还是防止一些第三库,
* 比如SmartRefreshLayout调用此方法,导致滑动到用户不希望滑动的位置
*/
@Override
public void setScrollX(int value) {
// super.setScrollX(value);
}
/**
* 禁止外部调用,这会导致绘制位置异常。
* 有关获取和设置滑动的ScrollX值、ScrollY值,可通过{@link TouchHelper}操作,
* 不在此方法调用{@link TouchHelper}对应方法,还是防止一些第三库,
* 比如SmartRefreshLayout调用此方法,导致滑动到用户不希望滑动的位置
*/
@Override
public void scrollTo(int x, int y) {
// super.scrollTo(x, y);
}
@Override
public void setCellFactory(CellFactory<T> cellFactory) {
if (cellFactory == null) {
return;
}
mCellFactory = cellFactory;
}
@Override
public CellFactory<T> getCellFactory() {
return mCellFactory;
}
@Override
public void setCellDraw(ICellDraw<T> iCellDraw) {
if (iCellDraw == null) {
return;
}
mICellDraw = iCellDraw;
}
@Override
public ICellDraw<T> getICellDraw() {
return mICellDraw;
}
@Override
public TableConfig getTableConfig() {
return mTableConfig;
}
@Override
public TableData<T> getTableData() {
return mTableData;
}
@Override
public Rect getShowRect() {
if (mOnlyReadShowRect == null) {
mOnlyReadShowRect = new Rect();
}
mOnlyReadShowRect.set(mShowRect);
return mOnlyReadShowRect;
}
@Override
public Rect getActualSizeRect() {
return mTableRender.getActualSizeRect();
}
@Override
public List<ShowCell> getShowCells() {
return mTableRender.getShowCells();
}
@Override
public TouchHelper<T> getTouchHelper() {
return mTouchHelper;
}
@Override
public void asyncReDraw() {
postInvalidate();
}
@Override
public void syncReDraw() {
invalidate();
}
/**
* 设置新数据(异步操作,可在任何线程调用),数据处理完成后会主动调用界面刷新操作。
* 调用此方法之前,请确保{@link ITable#getCellFactory()}不为null,否则将不做任何处理。
* 更多数据处理方法,请调用{@link #getTableData()}获取{@link TableData}
*
* @param totalRow 表格行数
* @param totalColumn 表格列数
*/
public void setNewData(int totalRow, int totalColumn) {
mTableData.setNewData(totalRow, totalColumn);
}
/**
* 清除表格数据,异步操作,数据处理完成后会主动调用界面刷新操作。
* 更多数据处理方法,请调用{@link #getTableData()}获取{@link TableData}
*/
public void clearData() {
mTableData.clear();
}
/**
* 设置单元格点击监听。
* 更多数据处理方法,请调用{@link #getTouchHelper()} 获取{@link TouchHelper}
*/
public void setCellClickListener(CellClickListener listener) {
mTouchHelper.setCellClickListener(listener);
}
/**
* 设置单元格拖拽监听。
* 更多数据处理方法,请调用{@link #getTouchHelper()} 获取{@link TouchHelper}
*/
public void setCellDragChangeListener(CellDragChangeListener listener) {
mTouchHelper.setCellDragChangeListener(listener);
}
/**
* 设置表格滑动监听
*/
public void setTableScrollChangeListener(com.keqiang.table.interfaces.OnScrollChangeListener listener) {
mTouchHelper.setOnScrollChangeListener(listener);
}
}
| 24.571059 | 108 | 0.611 |
f0fdc866d3bf300326a2f3dea0db7d5209815644 | 5,712 | package client;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.SecureRandom;
import java.util.concurrent.BlockingQueue;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLException;
import javax.net.ssl.TrustManagerFactory;
import commonUIElements.Message;
import commonUIElements.MessageQueueReaderThread;
import commonUIElements.SignatureSystem;
import commonUIElements.SocketReadThread;
/**
* Handles the socket connection to the server, for I/O.
*
* @author Kyle
*/
public class ClientSSLSocket {
// port the server is running on
private int port;
// address of the server
private String address;
// channel to talk to the server over
private AsynchronousSocketChannel socketChannel;
// GUI controller to report messages up to
private ClientUILayoutController controller;
// handles the message reader thread
private Thread msgThread;
// Reads messages from the queue
private MessageQueueReaderThread msgReader;
// Holds messages from the socket
private BlockingQueue<Message> messages;
// Reads messages from the socket
private SocketReadThread socketReader;
// handles the thread that reads from the socket
private Thread socketThread;
// holds the certificates
private KeyStore keyStore;
// holds the clients private key
private PrivateKey privateKey;
// Management objects for the key and trust stores
private KeyManagerFactory kmf;
private TrustManagerFactory tmf;
// SSL engine
private SSLEngine clientEngine;
// SSL Context, holds the key and trust managers
private SSLContext sslContext;
/**
* Sets up the socket connection to the server. This includes the SSLEngine
* setup as well.
*
* @param address
* of the server
* @param port
* of the server
* @param messages
* queue for received messages
* @param clientController
* GUI controller
*/
public ClientSSLSocket(String address, int port, BlockingQueue<Message> messages,
ClientUILayoutController clientController) {
this.address = address;
this.port = port;
this.messages = messages;
this.controller = clientController;
}
/**
* Handles connecting the client to the server.
*
* @param ks
* key store with certificates
* @param key
* private key of the clients
* @param kmf
* holds the client public/private keys
* @param tmf
* holds the server cert
* @throws Exception
* throws exception if connection error occurs
*/
public void startClient(KeyStore ks, PrivateKey key, KeyManagerFactory kmf, TrustManagerFactory tmf)
throws Exception {
System.out.println("Client connecting to: " + address + "@" + port);
// create the client channel
this.socketChannel = AsynchronousSocketChannel.open();
// store KS and private key
this.keyStore = ks;
this.privateKey = key;
// setup the SSL context and SSL engine
// this.sslContext = SSLContext.getInstance("TLSv1.2");
// this.sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(),
// SecureRandom.getInstance("SHA1PRNG"));
// // setup the SSL engine to connect to the client
// this.clientEngine = sslContext.createSSLEngine(this.address,
// this.port);
// // server always needs to authenticate
// this.clientEngine.setNeedClientAuth(true);
// this.clientEngine.setUseClientMode(true);
socketChannel.connect(new InetSocketAddress(address, port), this.socketChannel,
new CompletionHandler<Void, AsynchronousSocketChannel>() {
@Override
public void completed(Void result, AsynchronousSocketChannel ch) {
System.out.println("Connected to server");
// setup threads
// setup the socket reader
socketReader = new SocketReadThread(socketChannel, messages, "Server", keyStore, clientEngine);
socketThread = new Thread(socketReader);
socketThread.start();
// setup the message reader
msgReader = new MessageQueueReaderThread(messages, controller);
msgThread = new Thread(msgReader);
msgThread.start();
}
@Override
public void failed(Throwable exc, AsynchronousSocketChannel ch) {
System.err.println("Failed to connect to server");
}
});
}
/**
* Writes a message to the server.
*
* @param message
* to send to server
*/
public void writeMessage(Message message) {
// Create the message
commonUIElements.MessageProtos.Message msg = commonUIElements.MessageProtos.Message.newBuilder()
.setClearance(message.clearance).setMessage(message.message).setName(message.alias)
.setSender(message.senderName).setSignature(SignatureSystem.signMessage(message.message, privateKey))
.build();
// try {
// ByteBuffer dst = ByteBuffer.allocate(2048);
// this.clientEngine.wrap(ByteBuffer.wrap(msg.toByteArray()), dst);
socketChannel.write(ByteBuffer.wrap(msg.toByteArray()));
// } catch (SSLException e) {
// System.err.println("Error writing message over socket: " +
// e.getMessage());
// }
}
/**
* Stops the client socket.
*/
public void stop() {
try {
// kill the socket
this.socketChannel.close();
// kill the socket reader
this.socketReader.stop();
this.socketThread.interrupt();
this.socketThread.join();
this.msgReader.stop();
this.msgThread.interrupt();
this.msgThread.join();
} catch (Exception e) {
System.err.println("Failed to stop client reader thread: " + e.getMessage());
}
}
}
| 32.089888 | 105 | 0.720588 |
f2c921ec37fcf0cd8a80cd4298bae50b7544df08 | 6,619 | package es.gob.jmulticard.jse.provider.ceres;
import java.security.Provider;
import java.security.ProviderException;
import es.gob.jmulticard.apdu.connection.ApduConnection;
import es.gob.jmulticard.card.fnmt.ceres.Ceres;
/** Proveedor criptográfico JCA para tarjeta FNMT-RCM.CERES.
* Crea dos servicios:
* <dl>
* <dt><code>KeyStore</code></dt>
* <dd><i>CERES</i></dd>
* <dt><code>Signature</code></dt>
* <dd><i>SHA1withRSA</i>, <i>SHA256withRSA</i>, <i>SHA384withRSA</i>, <i>SHA512withRSA</i></dd>
* </dl>
* @author Tomás García-Merás */
public final class CeresProvider extends Provider {
private static final String SHA512WITH_RSA = "SHA512withRSA"; //$NON-NLS-1$
private static final String SHA384WITH_RSA = "SHA384withRSA"; //$NON-NLS-1$
private static final String SHA256WITH_RSA = "SHA256withRSA"; //$NON-NLS-1$
private static final String SHA1WITH_RSA = "SHA1withRSA"; //$NON-NLS-1$
private static final String ES_GOB_JMULTICARD_CARD_CERES_PRIVATE_KEY = "es.gob.jmulticard.jse.provider.ceres.CeresPrivateKey"; //$NON-NLS-1$
private static final long serialVersionUID = -1046745919235177156L;
private static final String INFO = "Proveedor para tarjeta FNMT-RCM-CERES"; //$NON-NLS-1$
private static final double VERSION = 0.1d;
private static final String NAME = "CeresJCAProvider"; //$NON-NLS-1$
private static ApduConnection defaultConnection = null;
/** Obtiene de forma estática el tipo de conexión de APDU que debe usar el <i>keyStore</i>.
* Si es nula (se ha invocado al constructor por defecto), es el propio <code>KeyStore</code> el que decide que
* conexión usar.
* @return Conexión por defecto */
static ApduConnection getDefaultApduConnection() {
return defaultConnection;
}
/** Crea un proveedor JCA para tarjeta FNMT-RCM-CERES con la conexión por defecto. */
public CeresProvider() {
this(null);
}
/** Crea un proveedor JCA para tarjeta FNMT-RCM-CERES.
* @param conn Conexión a usar para el envío y recepción de APDU. */
public CeresProvider(final ApduConnection conn) {
super(NAME, VERSION, INFO);
try {
defaultConnection = conn == null ?
(ApduConnection) Class.forName("es.gob.jmulticard.jse.smartcardio.SmartcardIoConnection").newInstance() : //$NON-NLS-1$
conn;
}
catch (final Exception e) {
throw new ProviderException(
"No se ha proporcionado una conexion con un lector y no ha podido instanciarse la por defecto: " + e, e //$NON-NLS-1$
);
}
try {
Ceres.connect(defaultConnection);
defaultConnection.close();
}
catch (final Exception e) {
throw new ProviderException(
"No se ha podido conectar con la tarjeta CERES: " + e, e //$NON-NLS-1$
);
}
// KeyStore
put("KeyStore.CERES", "es.gob.jmulticard.jse.provider.ceres.CeresKeyStoreImpl"); //$NON-NLS-1$ //$NON-NLS-2$
// Motores de firma
put("Signature.SHA1withRSA", "es.gob.jmulticard.jse.provider.ceres.CeresSignatureImpl$Sha1"); //$NON-NLS-1$ //$NON-NLS-2$
put("Signature.SHA256withRSA", "es.gob.jmulticard.jse.provider.ceres.CeresSignatureImpl$Sha256"); //$NON-NLS-1$ //$NON-NLS-2$
put("Signature.SHA384withRSA", "es.gob.jmulticard.jse.provider.ceres.CeresSignatureImpl$Sha384"); //$NON-NLS-1$ //$NON-NLS-2$
put("Signature.SHA512withRSA", "es.gob.jmulticard.jse.provider.ceres.CeresSignatureImpl$Sha512"); //$NON-NLS-1$ //$NON-NLS-2$
// Claves soportadas
put("Signature.SHA1withRSA SupportedKeyClasses", CeresProvider.ES_GOB_JMULTICARD_CARD_CERES_PRIVATE_KEY); //$NON-NLS-1$
put("Signature.SHA256withRSA SupportedKeyClasses", CeresProvider.ES_GOB_JMULTICARD_CARD_CERES_PRIVATE_KEY); //$NON-NLS-1$
put("Signature.SHA384withRSA SupportedKeyClasses", CeresProvider.ES_GOB_JMULTICARD_CARD_CERES_PRIVATE_KEY); //$NON-NLS-1$
put("Signature.SHA512withRSA SupportedKeyClasses", CeresProvider.ES_GOB_JMULTICARD_CARD_CERES_PRIVATE_KEY); //$NON-NLS-1$
// Alias de los nombres de algoritmos de firma
put("Alg.Alias.Signature.1.2.840.113549.1.1.5", CeresProvider.SHA1WITH_RSA); //$NON-NLS-1$
put("Alg.Alias.Signature.OID.1.2.840.113549.1.1.5", CeresProvider.SHA1WITH_RSA); //$NON-NLS-1$
put("Alg.Alias.Signature.1.3.14.3.2.29", CeresProvider.SHA1WITH_RSA); //$NON-NLS-1$
put("Alg.Alias.Signature.SHAwithRSA", CeresProvider.SHA1WITH_RSA); //$NON-NLS-1$
put("Alg.Alias.Signature.SHA-1withRSA", CeresProvider.SHA1WITH_RSA); //$NON-NLS-1$
put("Alg.Alias.Signature.SHA1withRSAEncryption", CeresProvider.SHA1WITH_RSA); //$NON-NLS-1$
put("Alg.Alias.Signature.SHA-1withRSAEncryption", CeresProvider.SHA1WITH_RSA); //$NON-NLS-1$
put("Alg.Alias.Signature.1.2.840.113549.1.1.11", CeresProvider.SHA256WITH_RSA); //$NON-NLS-1$
put("Alg.Alias.Signature.OID.1.2.840.113549.1.1.11", CeresProvider.SHA256WITH_RSA); //$NON-NLS-1$
put("Alg.Alias.Signature.SHA-256withRSA", CeresProvider.SHA256WITH_RSA); //$NON-NLS-1$
put("Alg.Alias.Signature.SHA-256withRSAEncryption", CeresProvider.SHA256WITH_RSA); //$NON-NLS-1$
put("Alg.Alias.Signature.SHA256withRSAEncryption", CeresProvider.SHA256WITH_RSA); //$NON-NLS-1$
put("Alg.Alias.Signature.1.2.840.113549.1.1.12", CeresProvider.SHA384WITH_RSA); //$NON-NLS-1$
put("Alg.Alias.Signature.OID.1.2.840.113549.1.1.12", CeresProvider.SHA384WITH_RSA); //$NON-NLS-1$
put("Alg.Alias.Signature.SHA-384withRSA", CeresProvider.SHA384WITH_RSA); //$NON-NLS-1$
put("Alg.Alias.Signature.SHA-384withRSAEncryption", CeresProvider.SHA384WITH_RSA); //$NON-NLS-1$
put("Alg.Alias.Signature.SHA384withRSAEncryption", CeresProvider.SHA384WITH_RSA); //$NON-NLS-1$
put("Alg.Alias.Signature.1.2.840.113549.1.1.13", CeresProvider.SHA512WITH_RSA); //$NON-NLS-1$
put("Alg.Alias.Signature.OID.1.2.840.113549.1.1.13", CeresProvider.SHA512WITH_RSA); //$NON-NLS-1$
put("Alg.Alias.Signature.SHA-512withRSA", CeresProvider.SHA512WITH_RSA); //$NON-NLS-1$
put("Alg.Alias.Signature.SHA-512withRSAEncryption", CeresProvider.SHA512WITH_RSA); //$NON-NLS-1$
put("Alg.Alias.Signature.SHA512withRSAEncryption", CeresProvider.SHA512WITH_RSA); //$NON-NLS-1$
}
} | 55.158333 | 145 | 0.677595 |
c1b54e093d851c6063964bb9e0995a51a0f9e5c8 | 1,730 | package com.myland.framework.common.utils;
import com.myland.framework.common.utils.validator.Assert;
import net.sf.cglib.beans.BeanCopier;
import org.apache.commons.lang3.ClassUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 缓存BeanCopier工具
*
* @author SunYanQing
*/
public class CachedBeanCopier {
private static final Map<String, BeanCopier> BEAN_COPIERS = new HashMap<>();
public static void copy(Object srcObj, Object destObj) {
Assert.isNotNull(srcObj, "BeanCopier source object is null.");
Assert.isNotNull(destObj, "BeanCopier dest object is null.");
String key = genKey(srcObj.getClass(), destObj.getClass());
BeanCopier copier;
if (!BEAN_COPIERS.containsKey(key)) {
copier = BeanCopier.create(srcObj.getClass(), destObj.getClass(), false);
BEAN_COPIERS.put(key, copier);
} else {
copier = BEAN_COPIERS.get(key);
}
copier.copy(srcObj, destObj, null);
}
private static String genKey(Class<?> srcClazz, Class<?> destClazz) {
return srcClazz.getName() + destClazz.getName();
}
public static <K, J> List<J> copy(List<K> srcList, Class<J> destClazz) {
Assert.isNotNull(srcList, "BeanCopier source list is null.");
Assert.isNotNull(destClazz, "BeanCopier dest class is null.");
try {
List<J> destList = new ArrayList<>(srcList.size());
for (K k : srcList) {
J j = destClazz.newInstance();
copy(k, j);
destList.add(j);
}
return destList;
} catch (InstantiationException e) {
throw new RuntimeException("目标类实例化异常, className=[" + destClazz.getName() + "]");
} catch (IllegalAccessException e) {
throw new RuntimeException("目标类非法访问, className=[" + destClazz.getName() + "]");
}
}
} | 30.350877 | 83 | 0.707514 |
f5a982df3cffeba4b8678f9f628fae155c6cc570 | 2,123 | package hu.elte.LifeBookProject.controllers;
import hu.elte.LifeBookProject.controllers.EatingHabitController;
import hu.elte.LifeBookProject.repositories.EatingHabitRepository;
import hu.elte.LifeBookProject.entities.EatingHabit;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@RunWith(SpringJUnit4ClassRunner.class)
public class EatingHabitControllerTest {
private MockMvc mockMvc;
@Mock
private EatingHabitRepository eatingHabitRepository;
@InjectMocks
private EatingHabitController eatingHabitController;
@Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders.standaloneSetup(eatingHabitController)
.build();
}
@Test
public void testGetAll() throws Exception {
mockMvc.perform(get("/eatinghabits"))
.andExpect(status().isOk());
}
@Test
public void testGetByType() throws Exception {
mockMvc.perform(get("/eatinghabits/type/fruit"))
.andExpect(status().isOk());
}
@Test
public void testByIsFood() throws Exception {
mockMvc.perform(get("/eatinghabits/food"))
.andExpect(status().isOk());
mockMvc.perform(get("/eatinghabits/drink"))
.andExpect(status().isOk());
}
@Test
public void testDelete() throws Exception {
mockMvc.perform(delete("/eatinghabits/Orange"))
.andExpect(status().isOk());
}
}
| 32.661538 | 89 | 0.715026 |
35b72f298faac4edab26c446824b69b5251b564a | 1,943 | /**
* Generated by OpenJPA MetaModel Generator Tool.
**/
package com.x.component.core.entity;
import com.x.base.core.entity.SliceJpaObject_;
import java.lang.Boolean;
import java.lang.Integer;
import java.lang.String;
import java.util.Date;
import javax.persistence.metamodel.ListAttribute;
import javax.persistence.metamodel.SingularAttribute;
@javax.persistence.metamodel.StaticMetamodel
(value=com.x.component.core.entity.Component.class)
@javax.annotation.Generated
(value="org.apache.openjpa.persistence.meta.AnnotationProcessor6",date="Sat May 06 19:34:52 CST 2017")
public class Component_ extends SliceJpaObject_ {
public static volatile ListAttribute<Component,String> allowList;
public static volatile ListAttribute<Component,String> controllerList;
public static volatile SingularAttribute<Component,Date> createTime;
public static volatile ListAttribute<Component,String> denyList;
public static volatile SingularAttribute<Component,String> iconPath;
public static volatile SingularAttribute<Component,String> id;
public static volatile SingularAttribute<Component,String> name;
public static volatile SingularAttribute<Component,Integer> order;
public static volatile SingularAttribute<Component,String> path;
public static volatile SingularAttribute<Component,String> sequence;
public static volatile SingularAttribute<Component,String> title;
public static volatile SingularAttribute<Component,Date> updateTime;
public static volatile SingularAttribute<Component,Boolean> visible;
public static volatile SingularAttribute<Component,String> widgetIconPath;
public static volatile SingularAttribute<Component,String> widgetName;
public static volatile SingularAttribute<Component,Boolean> widgetStart;
public static volatile SingularAttribute<Component,String> widgetTitle;
public static volatile SingularAttribute<Component,Boolean> widgetVisible;
}
| 49.820513 | 102 | 0.817293 |
1e322a248e3d77a7f7e99a5a5e9460a0b608f546 | 466 | package org.nzbhydra.indexers;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Collection;
public interface IndexerRepository extends JpaRepository<IndexerEntity, Integer> {
IndexerEntity findByName(String name);
Collection<IndexerEntity> findByNameNotIn(Collection<String> names);
void deleteAllByNameNotIn(Collection<String> names);
@Override
<S extends IndexerEntity> S save(S entity);
}
| 25.888889 | 83 | 0.759657 |
a5e02d64a7d1f7f4afe9cfbcca7dfe18b70ae293 | 337 | package javamoneyexamples.jsf.money.exchange;
import javax.enterprise.inject.Produces;
import javax.money.convert.ExchangeRateProvider;
import javax.money.convert.MonetaryConversions;
public class ExchangeRateProducer {
@Produces
public ExchangeRateProvider get() {
return MonetaryConversions.getExchangeRateProvider("ECB");
}
}
| 24.071429 | 60 | 0.827893 |
7783a21dd87c8f96c38dd2937d9360aaa2847132 | 293 | package cn.zull.netty.mock.common.global;
import cn.zull.netty.mock.common.constants.IMessage;
/**
* @author zurun
* @date 2018/5/12 12:10:21
*/
public class CipherException extends IflytekRuntimeException {
public CipherException(IMessage errCode) {
super(errCode);
}
}
| 19.533333 | 62 | 0.716724 |
b4e71023c86b7ef2af6914054a06dabccdf782e8 | 1,299 | package com.xfhy.architecturedemo.room.bean;
import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Embedded;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.Ignore;
import android.arch.persistence.room.PrimaryKey;
/**
* Created by xfhy on 2019/3/3 14:15
* Description :
*/
@Entity(tableName = "orders")
public class Order {
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "order_id")
public long orderId;
@ColumnInfo(name = "address")
public String address;
@ColumnInfo(name = "owner_name")
public String ownerName;
@ColumnInfo(name = "owner_phone")
public String ownerPhone;
//指示Room需要忽略的字段或方法
@Ignore
public String ignoreText;
@Embedded
public OwerAddress owerAddress;
static class OwerAddress {
}
@Override
public String toString() {
return "Order{" +
"orderId=" + orderId +
", address='" + address + '\'' +
", ownerName='" + ownerName + '\'' +
", ownerPhone='" + ownerPhone + '\'' +
", ignoreText='" + ignoreText + '\'' +
", owerAddress=" + owerAddress +
'}';
}
}
| 24.980769 | 55 | 0.582756 |
90396c2001f431a239526316ed4d7c47443392e9 | 1,520 | package io.metadew.iesi.metadata.configuration.type;
import io.metadew.iesi.metadata.definition.script.type.ScriptType;
import io.metadew.iesi.metadata.definition.script.type.ScriptTypeParameter;
public class ScriptTypeParameterConfiguration {
private ScriptTypeParameter scriptTypeParameter;
// Constructors
public ScriptTypeParameterConfiguration(ScriptTypeParameter scriptTypeParameter) {
this.setScriptTypeParameter(scriptTypeParameter);
}
public ScriptTypeParameterConfiguration() {
}
// Get Script Type Parameter
public ScriptTypeParameter getScriptTypeParameter(String scriptTypeName, String scriptTypeParameterName) {
ScriptTypeParameter scriptTypeParameterResult = null;
ScriptTypeConfiguration scriptTypeConfiguration = new ScriptTypeConfiguration();
ScriptType scriptType = scriptTypeConfiguration.getScriptType(scriptTypeName);
for (ScriptTypeParameter scriptTypeParameter : scriptType.getParameters()) {
if (scriptTypeParameter.getName().equalsIgnoreCase(scriptTypeParameterName)) {
scriptTypeParameterResult = scriptTypeParameter;
break;
}
}
return scriptTypeParameterResult;
}
// Getters and Setters
public ScriptTypeParameter getScriptTypeParameter() {
return scriptTypeParameter;
}
public void setScriptTypeParameter(ScriptTypeParameter scriptTypeParameter) {
this.scriptTypeParameter = scriptTypeParameter;
}
} | 38 | 110 | 0.754605 |
8a25ef485f4342bd627899f60b39fcf7932af615 | 2,262 | package codeGeneration.xml;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import specification.definitions.Definition;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.File;
import java.io.StringReader;
/**
* Tomas Hanus on 4/8/2015.
*/
public class DefinitionFileGenerator {
private Project project;
private JAXBContext jaxbContext;
private Marshaller marshaller;
private Unmarshaller unmarshaller;
private Document document;
private VirtualFile virtualFile;
private File file;
public DefinitionFileGenerator(Project project, File file) {
this.project = project;
this.file = file;
if (this.virtualFile == null)
this.document = null;
else this.document = FileDocumentManager.getInstance().getDocument(this.virtualFile);
initJAXBContext();
}
/**
* Serialize diagramDefinition into .jsd file
*/
public void marshal(Definition diagramDefinition) throws JAXBException {
this.marshaller.marshal(diagramDefinition, this.file);
LocalFileSystem.getInstance().refresh(true);
}
/**
* Create diagramDefinition from it's serialized form from .jsd dile
*/
public Definition unmarshal() throws JAXBException {
Definition definition = null;
try {
definition = (Definition)this.unmarshaller.unmarshal(this.file);
} catch (Exception e) {
}
return definition;
}
/**
* Init JAXB context, creates marshaller and unmarshaller
*/
public void initJAXBContext() {
try {
this.jaxbContext = JAXBContext.newInstance(Definition.class);
this.marshaller = jaxbContext.createMarshaller();
this.unmarshaller = jaxbContext.createUnmarshaller();
this.marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
} catch (JAXBException e) {
e.printStackTrace();
}
}
} | 30.16 | 93 | 0.691424 |
b0db94a0c9c2b33994525a7e876390dbb6d9c52e | 272 | package com.github.jgzl.common.core.exception;
/**
* 基础异常码接口
*
* @author lihaifeng
* @since 2020-09-27
*/
public interface BaseExceptionCode {
/**
* 异常编码
*
* @return code
*/
int getCode();
/**
* 异常消息
*
* @return 异常信息
*/
String getMessage();
}
| 10.461538 | 46 | 0.588235 |
164ed728e5ffe5a69eb21679f650ea8222d4e440 | 2,010 | /**
* Copyright (C) 2006-2018 Talend Inc. - www.talend.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.talend.sdk.component.proxy.model;
import java.util.Collection;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Node {
@ApiModelProperty("The identifier of this configuration/node.")
private String id;
@ApiModelProperty("The display name of this configuration.")
private String label;
@ApiModelProperty("The identifier of the family of this configuration.")
private String familyId;
@ApiModelProperty("The display name of the family of this configuration.")
private String familyLabel;
@ApiModelProperty("The icon of this configuration. If you use an existing bundle (@talend/ui/icon), ensure it "
+ "is present by default and if not do a request using the family on the related endpoint.")
private String icon;
@ApiModelProperty("The list of configuration reusing this one as a reference (can be created \"next\").")
private Collection<String> children;
@ApiModelProperty("The version of this configuration for the migration management.")
private Integer version;
@ApiModelProperty("The technical name of this node (it is human readable but not i18n friendly), useful for debug purposes.")
private String name;
}
| 34.655172 | 129 | 0.748756 |
1f0b4b044022fa4930524c356e6ec8538f536f00 | 635 | package nl.ekholabs.escode.graphics;
import nl.ekholabs.escode.core.EsCodeGenerator;
import java.awt.Graphics;
import java.util.List;
import javax.swing.JComponent;
public class GeneratedCanvas extends JComponent {
private static final long serialVersionUID = 8660447244732117207L;
private final List<EsCodeColour> colours;
public GeneratedCanvas(final List<EsCodeColour> colours) {
this.colours = colours;
}
@Override
public void paint(final Graphics graphics) {
setOpaque(true);
final EsCodeGenerator esCodeGenerator = new EsCodeGenerator();
esCodeGenerator.drawGraphics(colours, graphics);
}
} | 23.518519 | 68 | 0.774803 |
1c01a2fd1f446b45af709c36e2d604898048db36 | 157 | package io.wisoft.java_seminar.chap07.sec07.exam04_vehicle;
public class Vehicle {
public void run() {
System.out.println("차량이 달립니다.");
}
}
| 19.625 | 59 | 0.675159 |
3fc860c855cf5fabe72d5b617289f097e0e03102 | 5,217 | package u.aly;
import java.util.Collections;
import java.util.EnumMap;
import java.util.Map;
public class az extends cj<az, az.a>
{
public static final Map<az.a, cl> a;
private static final bR d = new bR("PropertyValue");
private static final bK e = new bK("string_value", 11, 1);
private static final bK f = new bK("long_value", 10, 2);
static
{
EnumMap localEnumMap = new EnumMap(az.a.class);
localEnumMap.put(az.a.a, new cl("string_value", 3, new cm(11)));
localEnumMap.put(az.a.b, new cl("long_value", 3, new cm(10)));
a = Collections.unmodifiableMap(localEnumMap);
cl.a(az.class, a);
}
public az()
{
}
public az(az.a parama, Object paramObject)
{
super(parama, paramObject);
}
public az(az paramaz)
{
super(paramaz);
}
public static az a(long paramLong)
{
az localaz = new az();
localaz.b(paramLong);
return localaz;
}
public static az a(String paramString)
{
az localaz = new az();
localaz.b(paramString);
return localaz;
}
protected Object a(bN parambN, bK parambK)
{
az.a locala = az.a.a(parambK.c);
String str = null;
if (locala != null);
switch (i()[locala.ordinal()])
{
default:
throw new IllegalStateException("setField wasn't null, but didn't match any of the case statements!");
case 1:
if (parambK.b == e.b)
{
str = parambN.p();
return str;
}
bP.a(parambN, parambK.b);
return null;
case 2:
}
if (parambK.b == f.b)
return Long.valueOf(parambN.n());
bP.a(parambN, parambK.b);
return null;
}
protected Object a(bN parambN, short paramShort)
{
az.a locala = az.a.a(paramShort);
if (locala != null)
{
switch (i()[locala.ordinal()])
{
default:
throw new IllegalStateException("setField wasn't null, but didn't match any of the case statements!");
case 1:
return parambN.p();
case 2:
}
return Long.valueOf(parambN.n());
}
throw new cz("Couldn't find a field with field id " + paramShort);
}
public az.a a(int paramInt)
{
return az.a.a(paramInt);
}
protected az.a a(short paramShort)
{
return az.a.b(paramShort);
}
public az a()
{
return new az(this);
}
protected bK a(az.a parama)
{
switch (i()[parama.ordinal()])
{
default:
throw new IllegalArgumentException("Unknown field id " + parama);
case 1:
return e;
case 2:
}
return f;
}
protected void a(az.a parama, Object paramObject)
{
switch (i()[parama.ordinal()])
{
default:
throw new IllegalArgumentException("Unknown field id " + parama);
case 1:
if ((paramObject instanceof String))
break;
throw new ClassCastException("Was expecting value of type String for field 'string_value', but got " + paramObject.getClass().getSimpleName());
case 2:
if ((paramObject instanceof Long))
break;
throw new ClassCastException("Was expecting value of type Long for field 'long_value', but got " + paramObject.getClass().getSimpleName());
}
}
public boolean a(az paramaz)
{
return (paramaz != null) && (j() == paramaz.j()) && (k().equals(paramaz.k()));
}
public int b(az paramaz)
{
int i = bB.a((Comparable)j(), (Comparable)paramaz.j());
if (i == 0)
i = bB.a(k(), paramaz.k());
return i;
}
public void b(long paramLong)
{
this.c = az.a.b;
this.b = Long.valueOf(paramLong);
}
public void b(String paramString)
{
if (paramString == null)
throw new NullPointerException();
this.c = az.a.a;
this.b = paramString;
}
protected bR c()
{
return d;
}
protected void c(bN parambN)
{
switch (i()[((az.a)this.c).ordinal()])
{
default:
throw new IllegalStateException("Cannot write union with unknown field " + this.c);
case 1:
parambN.a((String)this.b);
return;
case 2:
}
parambN.a(((Long)this.b).longValue());
}
public String d()
{
if (j() == az.a.a)
return (String)k();
throw new RuntimeException("Cannot get field 'string_value' because union is currently set to " + a((az.a)j()).a);
}
protected void d(bN parambN)
{
switch (i()[((az.a)this.c).ordinal()])
{
default:
throw new IllegalStateException("Cannot write union with unknown field " + this.c);
case 1:
parambN.a((String)this.b);
return;
case 2:
}
parambN.a(((Long)this.b).longValue());
}
public long e()
{
if (j() == az.a.b)
return ((Long)k()).longValue();
throw new RuntimeException("Cannot get field 'long_value' because union is currently set to " + a((az.a)j()).a);
}
public boolean equals(Object paramObject)
{
if ((paramObject instanceof az))
return a((az)paramObject);
return false;
}
public boolean f()
{
return this.c == az.a.a;
}
public boolean h()
{
return this.c == az.a.b;
}
public int hashCode()
{
return 0;
}
}
/* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar
* Qualified Name: u.aly.az
* JD-Core Version: 0.6.0
*/ | 21.828452 | 149 | 0.594786 |
2571bde29e3e5ca79a4d7d3c1dd7ed6586f681dc | 12,468 | package io.github.maximmaxims.thesimpsonsdatabasemobile;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.PreferenceManager;
import com.android.volley.*;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.switchmaterial.SwitchMaterial;
import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Locale;
public class EpisodeActivity extends AppCompatActivity {
public static final String EPISODEID = "io.github.maximmaxims.thesimpsonsdatabasemobile.EPISODEID";
private int episodeId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_episode);
Intent intent = getIntent();
episodeId = intent.getIntExtra(EpisodeActivity.EPISODEID, 0);
updateData(findViewById(android.R.id.content));
}
private void enableButtons(boolean enable) {
if (!enable) {
findViewById(R.id.switchWatched).setEnabled(false);
}
findViewById(R.id.buttonPrevious).setEnabled(enable);
findViewById(R.id.buttonNext).setEnabled(enable);
findViewById(R.id.textViewEpisodeId).setEnabled(enable);
findViewById(R.id.buttonDetails).setEnabled(enable);
}
public void updateData(View view) {
enableButtons(false);
RequestQueue queue = Volley.newRequestQueue(this);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String lang = preferences.getString("lang", "en");
String root2 = preferences.getString("address", "");
if (root2.equals("")) {
Snackbar.make(view, R.string.no_api, Snackbar.LENGTH_SHORT).setAnchorView(R.id.buttonPrevious).show();
return;
}
if (!root2.endsWith("/")) {
root2 += "/";
}
final String root = root2;
String episodeUrl = root + "episode/" + episodeId;
JsonObjectRequest episodeRequest = new JsonObjectRequest(Request.Method.GET, episodeUrl, null, response -> {
// On response:
try {
JSONObject episode = response.getJSONObject("episode");
TextView textViewName = findViewById(R.id.textViewName);
TextView textViewPremiere = findViewById(R.id.textViewPremiere);
TextView textViewDirection = findViewById(R.id.textViewDirection);
TextView textViewScreenplay = findViewById(R.id.textViewScreenplay);
String idString = "S" + String.format(Locale.US, "%02d", episode.getInt("seasonId")) + "E" + String.format(Locale.US, "%02d", episode.getInt("inSeasonId"));
setTitle(idString);
textViewName.setText(episode.getJSONObject("names").getString(lang));
textViewPremiere.setText(episode.getJSONObject("premieres").getString(lang));
textViewDirection.setText(episode.getString("direction"));
textViewScreenplay.setText(episode.getString("screenplay"));
} catch (JSONException e) {
Snackbar.make(findViewById(android.R.id.content), R.string.json_error, Snackbar.LENGTH_SHORT).setAnchorView(R.id.buttonPrevious).show();
e.printStackTrace();
enableButtons(true);
return;
}
String key = preferences.getString("key", "");
if (key.equals("")) {
Snackbar.make(view, R.string.no_key, Snackbar.LENGTH_SHORT).setAnchorView(R.id.buttonPrevious).show();
enableButtons(true);
return;
}
String watchedUrl = root + "watched/" + episodeId + "/?api_key=" + key;
queue.add(getWatched(view, watchedUrl));
enableButtons(true);
TextView epId = findViewById(R.id.textViewEpisodeId);
epId.setText(String.valueOf(episodeId));
}, error -> {
// On error:
// If network response was obtained
enableButtons(true);
String errMessage;
if (error.networkResponse != null) {
switch (error.networkResponse.statusCode) {
case 429:
errMessage = getResources().getString(R.string.error_429);
break;
case 404:
// errMessage = getResources().getString(R.string.error_404);
episodeId--;
updateData(view);
return;
case 500:
errMessage = getResources().getString(R.string.error_500);
break;
default:
errMessage = getResources().getString(R.string.error) + " (" + error.networkResponse.statusCode + ")";
}
} else if (error instanceof TimeoutError || error instanceof NoConnectionError) {
errMessage = getResources().getString(R.string.no_internet);
} else {
errMessage = error.getMessage();
if (errMessage == null) {
errMessage = getResources().getString(R.string.error);
}
}
Snackbar.make(view, errMessage, Snackbar.LENGTH_SHORT).setAnchorView(R.id.buttonPrevious).setAnchorView(R.id.buttonPrevious).show();
});
queue.add(episodeRequest);
}
public void markEpisode(View view) {
enableButtons(false);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
RequestQueue queue = Volley.newRequestQueue(this);
SwitchMaterial switchMaterial = findViewById(R.id.switchWatched);
boolean action = switchMaterial.isChecked();
JSONObject request = new JSONObject();
try {
request.put("watched", action);
String root = preferences.getString("address", "");
if (root.equals("")) {
Snackbar.make(view, R.string.no_api, Snackbar.LENGTH_SHORT).setAnchorView(R.id.buttonPrevious).show();
enableButtons(true);
return;
}
if (!root.endsWith("/")) {
root += "/";
}
String key = preferences.getString("key", "");
if (key.equals("")) {
Snackbar.make(view, R.string.no_key, Snackbar.LENGTH_SHORT).setAnchorView(R.id.buttonPrevious).show();
enableButtons(true);
return;
}
String watchedUrl = root + "watched/" + episodeId + "/?api_key=" + key;
JsonObjectRequest postWatched = new JsonObjectRequest(Request.Method.POST, watchedUrl, request, response -> {
// On response:
try {
boolean watched = response.getBoolean("watched");
enableButtons(true);
findViewById(R.id.switchWatched).setEnabled(true);
switchMaterial.setChecked(watched);
} catch (JSONException e) {
Snackbar.make(findViewById(android.R.id.content), R.string.json_error, Snackbar.LENGTH_SHORT).setAnchorView(R.id.buttonPrevious).show();
e.printStackTrace();
}
}, error -> {
// On error:
String errMessage;
if (error.networkResponse != null) {
switch (error.networkResponse.statusCode) {
case 429:
errMessage = getResources().getString(R.string.error_429);
break;
case 404:
errMessage = getResources().getString(R.string.error_404);
break;
case 500:
errMessage = getResources().getString(R.string.error_500);
break;
case 401:
errMessage = getResources().getString(R.string.error_401);
break;
case 400:
errMessage = getResources().getString(R.string.error_400);
break;
default:
errMessage = getResources().getString(R.string.error) + " (" + error.networkResponse.statusCode + ")";
}
queue.add(getWatched(view, watchedUrl));
} else if (error instanceof TimeoutError || error instanceof NoConnectionError) {
errMessage = getResources().getString(R.string.no_internet);
} else {
errMessage = error.getMessage();
if (errMessage == null) {
errMessage = getResources().getString(R.string.error);
}
}
Snackbar.make(view, errMessage, Snackbar.LENGTH_SHORT).setAnchorView(R.id.buttonPrevious).show();
});
queue.add(postWatched);
} catch (JSONException e) {
Snackbar.make(findViewById(android.R.id.content), R.string.json_error, Snackbar.LENGTH_SHORT).setAnchorView(R.id.buttonPrevious).show();
e.printStackTrace();
}
}
private @NotNull JsonObjectRequest getWatched(View view, String watchedUrl) {
return new JsonObjectRequest(Request.Method.GET, watchedUrl, null, response -> {
// On response:
try {
boolean watched = response.getBoolean("watched");
SwitchMaterial switchMaterial = findViewById(R.id.switchWatched);
findViewById(R.id.switchWatched).setEnabled(true);
enableButtons(true);
switchMaterial.setChecked(watched);
} catch (JSONException e) {
Snackbar.make(findViewById(android.R.id.content), R.string.json_error, Snackbar.LENGTH_SHORT).setAnchorView(R.id.buttonPrevious).show();
e.printStackTrace();
}
}, error -> {
// On error:
// If network response was obtained
String errMessage;
if (error.networkResponse != null) {
switch (error.networkResponse.statusCode) {
case 429:
errMessage = getResources().getString(R.string.error_429);
break;
case 404:
errMessage = getResources().getString(R.string.error_404);
break;
case 500:
errMessage = getResources().getString(R.string.error_500);
break;
case 401:
errMessage = getResources().getString(R.string.error_401);
break;
default:
errMessage = getResources().getString(R.string.error) + " (" + error.networkResponse.statusCode + ")";
}
} else if (error instanceof TimeoutError || error instanceof NoConnectionError) {
errMessage = getResources().getString(R.string.no_internet);
} else {
errMessage = error.getMessage();
if (errMessage == null) {
errMessage = getResources().getString(R.string.error);
}
}
Snackbar.make(view, errMessage, Snackbar.LENGTH_SHORT).setAnchorView(R.id.buttonPrevious).show();
});
}
public void openDetails(View view) {
Intent intent = new Intent(this, EpisodeDetailsActivity.class);
intent.putExtra(EPISODEID, episodeId);
startActivity(intent);
}
public void openPrevious(View view) {
if (episodeId > 1) {
episodeId--;
updateData(view);
}
}
public void openNext(View view) {
episodeId++;
updateData(view);
}
} | 44.212766 | 172 | 0.564485 |
5ce5f8820223f1fb5531427c6cf724c0e12fe37c | 4,580 | /**
*
*/
package org.vsg.crawler.service.impl;
import java.io.File;
import java.io.IOException;
import javax.inject.Inject;
import javax.inject.Named;
import org.iq80.leveldb.CompressionType;
import org.iq80.leveldb.DB;
import org.iq80.leveldb.DBException;
import org.iq80.leveldb.Options;
import org.iq80.leveldb.WriteBatch;
import org.iq80.leveldb.impl.Iq80DBFactory;
import org.vsg.common.async.AsyncResult;
import org.vsg.common.async.Callback;
import org.vsg.common.async.DefaultAsyncResult;
import org.vsg.cralwer.Task;
import org.vsg.crawler.service.TaskService;
import org.vsg.rmodel.crawler.schema.TaskSchema;
import io.protostuff.ProtobufIOUtil;
/**
* @author ruanweibiao
*
*/
public class SingleTaskServiceImpl implements TaskService {
@Inject
@Named("dir.data")
private String localDataPath;
/* (non-Javadoc)
* @see org.vsg.rmodel.crawler0.service.TaskService#checkTaskStatus(org.vsg.common.async.Callback)
*/
@Override
public void checkTaskStatus(Callback<AsyncResult<Byte>> callback , String taskName) {
// --- check folder exist ---
File dataDir = new File(localDataPath);
File taskDataDir = new File(dataDir , taskName);
if (!taskDataDir.exists()) {
taskDataDir.mkdirs();
}
LevelDBTaskState taskState = new LevelDBTaskState(dataDir);
byte state = taskState.getTaskStateByTaskName(taskName);
// --- check and return call back handle ---
DefaultAsyncResult<Byte> asyncResult = new DefaultAsyncResult<Byte>();
asyncResult.setResult( state );
asyncResult.setSucceeded(true);
if (callback != null) {
try {
callback.invoke( asyncResult );
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/* (non-Javadoc)
* @see org.vsg.rmodel.crawler0.service.TaskService#crateTask(org.vsg.common.async.Callback)
*/
@Override
public void createTask(Callback<AsyncResult<Task>> callback , String taskName) {
// --- check folder exist ---
File dataDir = new File(localDataPath);
LevelDBTaskState taskState = new LevelDBTaskState(dataDir);
}
private class LevelDBTaskState {
private File taskStateFolder;
private String __taskstate = "__taskstate";
public LevelDBTaskState(File dataFolder) {
this.taskStateFolder = new File(dataFolder , __taskstate);
// --- check the folder ---
if (!this.taskStateFolder.exists()) {
this.taskStateFolder.mkdirs();
}
options = new Options();
options.compressionType( CompressionType.SNAPPY );
}
public byte getTaskStateByTaskName(String taskName) {
byte state = Task.STATE_NOTEXISTED;
DB db = null;
try {
db = Iq80DBFactory.factory.open(taskStateFolder, options);
byte[] value = db.get(taskName.getBytes());
// --- parse status ---
if (null == value) {
return state;
}
// --- parse value to json ---
Task task = new Task();
TaskSchema taskSchema = new TaskSchema();
ProtobufIOUtil.mergeFrom(value, task, taskSchema);
state = task.getState();
} catch (DBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
close(db);
}
return state;
}
public Task getTaskByTaskName(String taskName) {
return null;
}
private Options options = new Options();
private DB db;
private WriteBatch batch = null;
public void open() {
// TODO Auto-generated method stub
// --- create tmp example ---
try {
this.db = Iq80DBFactory.factory.open(taskStateFolder, options);
// --- create write batch ---
batch = this.db.createWriteBatch();
} catch (DBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
}
}
public void close(DB db) {
// TODO Auto-generated method stub
try {
db.close();
} catch (DBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (db != null) {
db = null;
}
}
}
}
}
| 22.23301 | 100 | 0.631659 |
36e2466d851314a758975238cdf80ecf2c8c9235 | 10,253 | /*
* MIT License
*
* Copyright (c) 2018 Isaac Ellingson (Falkreon) and contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.elytradev.marsenal.client;
import java.util.HashSet;
import java.util.Set;
import com.elytradev.marsenal.ArsenalConfig;
import com.elytradev.marsenal.MagicArsenal;
import com.elytradev.marsenal.Proxy;
import com.elytradev.marsenal.block.IItemVariants;
import com.elytradev.marsenal.capability.IMagicResources;
import com.elytradev.marsenal.capability.impl.MagicResources;
import com.elytradev.marsenal.client.codex.XMLResourceLoader;
import com.elytradev.marsenal.entity.EntityFrostShard;
import com.elytradev.marsenal.entity.EntityWillOWisp;
import com.elytradev.marsenal.gui.ContainerCodex;
import com.elytradev.marsenal.item.ArsenalItems;
import com.elytradev.marsenal.item.IMetaItemModel;
import com.elytradev.marsenal.item.ISpellFocus;
import com.elytradev.marsenal.item.ItemCodex;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.util.NonNullList;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.event.ModelRegistryEvent;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.client.event.RenderGameOverlayEvent.ElementType;
import net.minecraftforge.client.event.RenderWorldLastEvent;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.fml.client.registry.RenderingRegistry;
import net.minecraftforge.fml.common.eventhandler.EventPriority;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent;
public class ClientProxy extends Proxy {
public static MagicResources scrambleTargets = new MagicResources();
@Override
public void preInit() {
Emitter.register("healingSphere", HealingSphereEmitter.class);
Emitter.register("drainLife", DrainLifeEmitter.class);
Emitter.register("infuseLife", InfuseLifeEmitter.class);
Emitter.register("disruption", DisruptionEmitter.class);
Emitter.register("spellGather", SpellGatherEmitter.class);
Emitter.register("magmaBlast", MagmaBlastEmitter.class);
Emitter.register("lightning", LightningEmitter.class);
Emitter.register("coalesce", CoalesceEmitter.class);
Emitter.registerWorldEmitter("chaosorb", ChaosOrbEmitter.class);
Emitter.registerWorldEmitter("radiantbeacon", RadiantBeaconEmitter.class);
RenderingRegistry.registerEntityRenderingHandler(EntityFrostShard.class, RenderFrostShard::new);
RenderingRegistry.registerEntityRenderingHandler(EntityWillOWisp.class, RenderWillOWisp::new);
//Unsatisfactory behavior. Using WorldEmitter.
//ClientRegistry.bindTileEntitySpecialRenderer(TileEntityChaosOrb.class, new RenderChaosOrb());
XMLResourceLoader.getInstance().preInit();
}
@Override
public void init() {
}
@SubscribeEvent
public void registerItemModels(ModelRegistryEvent event) {
for(Item item : ArsenalItems.itemsForModels()) {
if (item instanceof ItemCodex) {
ResourceLocation loc = Item.REGISTRY.getNameForObject(item);
for(int i=0; i<ContainerCodex.CODEX_PAGES.size()+100; i++) { //TODO: This will break eventually!
ModelLoader.setCustomModelResourceLocation(item, i, new ModelResourceLocation(loc, "inventory"));
}
ModelLoader.setCustomModelResourceLocation(item, 9000, new ModelResourceLocation(loc, "inventory")); //"Simple" book meta
continue;
}
if (item instanceof IMetaItemModel) {
String[] models = ((IMetaItemModel)item).getModelLocations();
for(int i=0; i<models.length; i++) {
ModelLoader.setCustomModelResourceLocation(item, i, new ModelResourceLocation(new ResourceLocation(MagicArsenal.MODID, models[i]), "inventory"));
}
} else {
NonNullList<ItemStack> variantList = NonNullList.create();
item.getSubItems(MagicArsenal.TAB_MARSENAL, variantList);
ResourceLocation loc = Item.REGISTRY.getNameForObject(item);
if (variantList.size()==1) {
registerModelVariant(new ItemStack(item), loc);
//ModelLoader.setCustomModelResourceLocation(item, 0, new ModelResourceLocation(loc, "inventory"));
} else {
for(ItemStack subItem : variantList) {
registerModelVariant(subItem, loc);
//ModelLoader.setCustomModelResourceLocation(item, subItem.getItemDamage(), new ModelResourceLocation(loc, "variant="+subItem.getItemDamage()));
}
}
}
}
}
private void registerModelVariant(ItemStack stack, ResourceLocation loc) {
if (stack.getItem() instanceof ItemBlock && ((ItemBlock)stack.getItem()).getBlock() instanceof IItemVariants) {
Block b = ((ItemBlock)stack.getItem()).getBlock();
String variant = ((IItemVariants)b).getVariantFromItem(stack);
ModelLoader.setCustomModelResourceLocation(stack.getItem(), stack.getItemDamage(), new ModelResourceLocation(loc, variant));
} else {
ModelLoader.setCustomModelResourceLocation(stack.getItem(), stack.getItemDamage(), new ModelResourceLocation(loc, "variant="+stack.getItemDamage()));
}
}
private static void drawBar(int x, int y, int width, int height, int cur, int total, int bg, int fg) {
float percent = cur/(float)total;
int barWidth = (int)(width*percent);
if (barWidth>width) barWidth = width;
Gui.drawRect(x, y, x+width, y+height, bg);
if (barWidth>0) {
Gui.drawRect(x, y, x+barWidth, y+height, fg);
}
}
private static void checkForResources(EntityLivingBase caster, ItemStack stack, Set<ResourceLocation> set) {
if (stack==null || stack.isEmpty()) return;
if (stack.getItem() instanceof ISpellFocus) {
((ISpellFocus)stack.getItem()).addResources(caster, stack, set);
}
}
@SubscribeEvent
public void onClientTick(TickEvent.ClientTickEvent event) {
if (event.phase != TickEvent.Phase.END) return;
if (Minecraft.getMinecraft().player==null) return;
ParticleEmitters.tick();
if (!Minecraft.getMinecraft().player.hasCapability(MagicArsenal.CAPABILTIY_MAGIC_RESOURCES, null)) return;
IMagicResources res = Minecraft.getMinecraft().player.getCapability(MagicArsenal.CAPABILTIY_MAGIC_RESOURCES, null);
//Scramble towards each resource value
ClientProxy.scrambleTargets.forEach((resource, val)->{
int oldValue = res.getResource(resource, 0);
int dist = Math.abs(val-oldValue);
dist /= 2;
if (dist<1) dist=1;
if (val>oldValue) {
res.set(resource, oldValue+dist);
} else if (val<oldValue) {
res.set(resource, oldValue-dist);
}
});
//Scramble towards the GCD target
res.setMaxCooldown(ClientProxy.scrambleTargets.getMaxCooldown());
int cur = res.getGlobalCooldown();
int target = ClientProxy.scrambleTargets.getGlobalCooldown();
int delta = Math.abs(cur - target) / 2;
if (delta<1) delta=1;
if (cur<target) {
if (res instanceof MagicResources) {
((MagicResources)res)._setGlobalCooldown(cur+delta);
} else {
res.setGlobalCooldown(cur+delta);
}
} else if (cur>target) {
res.reduceGlobalCooldown(delta);
}
}
@SubscribeEvent
public void onRenderScreen(RenderGameOverlayEvent.Post evt) {
EntityLivingBase player = Minecraft.getMinecraft().player;
if (!player.hasCapability(MagicArsenal.CAPABILTIY_MAGIC_RESOURCES, null)) return;
if (evt.getType()==ElementType.CROSSHAIRS) {
IMagicResources res = player.getCapability(MagicArsenal.CAPABILTIY_MAGIC_RESOURCES, null);
HashSet<ResourceLocation> relevantResources = new HashSet<ResourceLocation>();
checkForResources(player, player.getHeldItemMainhand(), relevantResources);
checkForResources(player, player.getHeldItemOffhand(), relevantResources);
int width = evt.getResolution().getScaledWidth();
int height = evt.getResolution().getScaledHeight();
int centerX = width/2;
int centerY = height/2;
if (res.getGlobalCooldown()>0) {
drawBar(centerX-15, centerY+20, 32, 2, res.getGlobalCooldown(), res.getMaxCooldown(), 0xFF333333, 0xFF777777);
}
if (relevantResources.contains(IMagicResources.RESOURCE_STAMINA) && res.getResource(IMagicResources.RESOURCE_STAMINA, ArsenalConfig.get().resources.maxStamina)<ArsenalConfig.get().resources.maxStamina) {
drawBar(centerX-15, centerY+23, 32, 2, res.getResource(IMagicResources.RESOURCE_STAMINA, ArsenalConfig.get().resources.maxStamina), ArsenalConfig.get().resources.maxStamina, 0xFF333333, 0xFF333399);
}
if (relevantResources.contains(IMagicResources.RESOURCE_RAGE) && res.getResource(IMagicResources.RESOURCE_RAGE, ArsenalConfig.get().resources.maxRage)<ArsenalConfig.get().resources.maxRage) {
drawBar(centerX-15, centerY+26, 32, 2, res.getResource(IMagicResources.RESOURCE_RAGE, ArsenalConfig.get().resources.maxRage), ArsenalConfig.get().resources.maxRage, 0xFF333333, 0xFF993333);
}
}
}
@SubscribeEvent(priority=EventPriority.LOW)
public void onRenderWorldLast(RenderWorldLastEvent event) {
ParticleEmitters.draw(event.getPartialTicks(), Minecraft.getMinecraft().player);
}
}
| 43.444915 | 206 | 0.767775 |
73cf79c6f60d275548a27a68b59550b8f02fec83 | 1,115 | package com.github.rozumek29.plantseekerpanel.data.service;
import com.github.rozumek29.plantseekerpanel.data.entity.PottedPlant;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.vaadin.crudui.crud.CrudListener;
import java.util.Collection;
import java.util.Optional;
@Service
public class PottedPlantService implements CrudListener<PottedPlant> {
@Autowired
private PottedPlantRepository repository;
@Override
public Collection<PottedPlant> findAll() {
return repository.findAll();
}
public Optional<PottedPlant> findById(Long id){
return repository.findById(id);
}
@Override
public PottedPlant add(PottedPlant plant) {
return repository.save(plant);
}
@Override
public PottedPlant update(PottedPlant plant) {
return repository.save(plant);
}
@Override
public void delete(PottedPlant plant) {
repository.delete(plant);
}
public Long count(){
return repository.count();
}
}
| 24.23913 | 70 | 0.727354 |
644222abdec2f1863404692fa319569d2b8f6589 | 6,125 | /*
* Copyright 2017-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.jvm.java.plugin.adapter;
import com.facebook.buck.jvm.java.lang.model.BridgeMethod;
import com.facebook.buck.jvm.java.lang.model.ElementsExtended;
import com.facebook.buck.jvm.java.lang.model.MoreElements;
import com.facebook.buck.util.liteinfersupport.Nullable;
import com.sun.source.util.Trees;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Name;
import javax.lang.model.element.TypeElement;
import javax.lang.model.util.ElementFilter;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
/**
* Wraps and extends {@link javax.lang.model.util.Elements} with methods that cannot be added as
* pure extension methods on {@link MoreElements} because they require per-instance state.
*/
public class ElementsExtendedImpl extends DelegatingElements implements ElementsExtended {
private final Map<TypeElement, Map<Name, List<ExecutableElement>>> declaredMethodsMaps =
new HashMap<>();
private final Map<TypeElement, Map<Name, List<ExecutableElement>>> allMethodsMaps =
new HashMap<>();
private final BridgeMethods bridgeMethods;
private final Types types;
private final Trees trees;
public ElementsExtendedImpl(Elements inner, Types types, Trees trees) {
super(inner);
this.types = types;
this.trees = trees;
bridgeMethods = new BridgeMethods(this, types);
}
@Override
public List<ExecutableElement> getDeclaredMethods(TypeElement owner, CharSequence name) {
return getMethods(owner, name, declaredMethodsMaps, Element::getEnclosedElements);
}
@Override
public List<ExecutableElement> getAllMethods(TypeElement owner, CharSequence name) {
return getMethods(owner, name, allMethodsMaps, this::getAllMembers);
}
@Override
public List<BridgeMethod> getBridgeMethods(TypeElement owner, CharSequence name) {
return bridgeMethods.getBridgeMethods(owner, getName(name));
}
@Override
@Nullable
public ExecutableElement getImplementation(ExecutableElement baseMethod, TypeElement inType) {
ExecutableElement result = null;
for (ExecutableElement candidate : getAllMethods(inType, baseMethod.getSimpleName())) {
Element enclosingElement = candidate.getEnclosingElement();
if (enclosingElement != inType && enclosingElement.getKind().isInterface()) {
continue;
}
if (overrides(candidate, baseMethod, inType) || (result == null && candidate == baseMethod)) {
result = candidate;
}
}
return result;
}
@Nullable
@Override
public TypeElement getBinaryImplementationOwner(ExecutableElement method, TypeElement inType) {
TypeElement implementationOwner = null;
ExecutableElement implementation = getImplementation(method, inType);
if (implementation != null && binarySignaturesMatch(implementation, method)) {
implementationOwner = (TypeElement) implementation.getEnclosingElement();
}
for (TypeElement type = inType; type != null; type = MoreElements.getSuperclass(type)) {
if (implementationOwner != null
&& !types.isSubtype(
types.erasure(type.asType()), types.erasure(implementationOwner.asType()))) {
break;
}
Name name = method.getSimpleName();
List<BridgeMethod> bridgeMethods = this.bridgeMethods.getBridgeMethodsNoCreate(type, name);
Optional<ExecutableElement> result =
bridgeMethods.stream()
.map(it -> it.to)
.filter(it -> binarySignaturesMatch(it, method))
.findFirst();
if (result.isPresent()) {
implementationOwner = type;
break;
}
}
return implementationOwner;
}
private boolean binarySignaturesMatch(ExecutableElement e1, ExecutableElement e2) {
return types.isSameType(types.erasure(e1.asType()), types.erasure(e2.asType()))
&& types.isSameType(types.erasure(e1.getReturnType()), types.erasure(e2.getReturnType()));
}
@Override
public List<BridgeMethod> getAllBridgeMethods(TypeElement type) {
return bridgeMethods.getBridgeMethods(type);
}
private List<ExecutableElement> getMethods(
TypeElement owner,
CharSequence name,
Map<TypeElement, Map<Name, List<ExecutableElement>>> methodsMaps,
Function<? super TypeElement, List<? extends Element>> getMembersFn) {
Map<Name, List<ExecutableElement>> methodsMap =
methodsMaps.computeIfAbsent(owner, el -> buildMethodsMap(el, getMembersFn));
List<ExecutableElement> result = methodsMap.get(getName(name));
if (result == null) {
result = Collections.emptyList();
}
return result;
}
@Override
public boolean isCompiledInCurrentRun(Element element) {
return trees.getTree(element) != null;
}
private static Map<Name, List<ExecutableElement>> buildMethodsMap(
TypeElement owner, Function<? super TypeElement, List<? extends Element>> getMembersFn) {
Map<Name, List<ExecutableElement>> result = new HashMap<>();
for (ExecutableElement method : ElementFilter.methodsIn(getMembersFn.apply(owner))) {
List<ExecutableElement> methodsWithName =
result.computeIfAbsent(method.getSimpleName(), ignored -> new ArrayList<>());
methodsWithName.add(method);
}
return result;
}
}
| 36.458333 | 100 | 0.728 |
9c7281ca4cf37ee303823a6c829c18fa63650960 | 3,455 | package io.rukkit.plugin;
import io.rukkit.*;
import io.rukkit.util.*;
import java.io.*;
import java.util.*;
import org.yaml.snakeyaml.*;
public abstract class RukkitPlugin implements Plugin
{
String pluginName;
String pluginVersion;
String mainClass;
boolean isEnabled;
private Logger log;
public RukkitPlugin(){}
public PluginManager getPluginManager(){
return Rukkit.getCurrentPluginManager();
//return Rukkit.getCurrentPluginHandler();
}
public final void initPlugin(PluginLoader loader) {
getPluginManager().loadPlugin(this);
log = new Logger(this.getClass().toString());
}
public final void setEnabled(boolean isEnabled) {
this.isEnabled = isEnabled;
if (isEnabled) {
onEnable();
} else {
onDisable();
}
}
public final boolean getEnabled() {
return isEnabled;
}
public final String getPluginName() {
return pluginName;
}
public final String getPluginVersion() {
return pluginVersion;
}
public final String getMainClass() {
return mainClass;
}
public final Logger getLogger() {
return log;
}
public final File getConfigFile(String config)
{
File configDir = new File(Rukkit.getEnvPath() + "/plugins/"+getPluginName());
if (configDir.isFile()) {
configDir.delete();
}
if (!configDir.exists()) {
configDir.mkdir();
}
File configFile = new File(configDir + "/" + config + ".yml");
if (configFile.isDirectory()) {
configFile.delete();
}
if (!configFile.exists()) {
try
{
configFile.createNewFile();
}
catch (IOException e)
{
e.printStackTrace();
}
}
return configFile;
}
public final void setConfig(String file, String key, Object value) throws FileNotFoundException, IOException {
setConfig(new File(Rukkit.getEnvPath() + "/plugins/"+getPluginName() + "/" + file + ".yml"), key, null);
}
public final void getConfig(String file, String key) throws FileNotFoundException {
getConfig(new File(Rukkit.getEnvPath() + "/plugins/"+getPluginName() + "/" + file + ".yml"), key, null);
}
public final void getConfig(String file, String key, Object defaultValue) throws FileNotFoundException {
getConfig(new File(Rukkit.getEnvPath() + "/plugins/"+getPluginName() + "/" + file + ".yml"), key, defaultValue);
}
public final void setConfig(File file, String key, Object value) throws FileNotFoundException, IOException {
Yaml yaml = new Yaml();
LinkedHashMap<String, Object> li = new LinkedHashMap<String, Object>();
if(yaml.load(new FileInputStream(file)) != null) {
li = yaml.load(new FileInputStream(file));
}
/*for (Map.Entry<String, Object> entry : li.entrySet()) {
log.d("KEY: " + entry.getKey() + " VALUE: " + entry.getValue());
}*/
li.put(key, value);
yaml.dump(li, new FileWriter(file));
}
public final Object getConfig(File file, String key, Object defaultValue) throws FileNotFoundException {
Yaml yaml = new Yaml();
LinkedHashMap<String, Object> li = new LinkedHashMap<String, Object>();
li = yaml.load(new FileInputStream(file));
/*for (Map.Entry<String, Object> entry : li.entrySet()) {
log.d("KEY: " + entry.getKey() + " VALUE: " + entry.getValue());
}*/
try {
return li.getOrDefault(key, defaultValue);
} catch (NullPointerException e) {
return null;
}
}
public abstract void onLoad();
public abstract void onEnable();
public abstract void onDisable();
public abstract void onServerDone();
public abstract void onStop();
}
| 26.174242 | 114 | 0.685962 |
9950dcf2d607baaed1e95b22eef33e56e48250dc | 133 | package it.qbteam.persistence.areautils;
public interface CoordinateFactory {
Coordinate buildCoordinate(double y, double x);
}
| 22.166667 | 51 | 0.796992 |
0c4f55bfcc0f68cf487c6abae063d12d81690c8c | 21,489 | /*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license. See terms of license at gnu.org.
*/
package org.atalk.impl.neomedia.jmfext.media.protocol.video4linux2;
import java.io.*;
import javax.media.*;
import javax.media.control.*;
import javax.media.format.*;
import org.atalk.impl.neomedia.NeomediaServiceUtils;
import org.atalk.impl.neomedia.codec.FFmpeg;
import org.atalk.impl.neomedia.codec.video.AVFrame;
import org.atalk.impl.neomedia.codec.video.AVFrameFormat;
import org.atalk.impl.neomedia.codec.video.ByteBuffer;
import org.atalk.android.util.java.awt.Dimension;
import org.atalk.impl.neomedia.jmfext.media.protocol.AbstractPullBufferStream;
import org.atalk.impl.neomedia.jmfext.media.protocol.AbstractVideoPullBufferStream;
import org.atalk.impl.neomedia.jmfext.media.protocol.ByteBufferPool;
/**
* Implements a <tt>PullBufferStream</tt> using the Video for Linux Two API Specification.
*
* @author Lyubomir Marinov
*/
public class Video4Linux2Stream extends AbstractVideoPullBufferStream<DataSource>
{
/**
* The <tt>AVCodecContext</tt> of the MJPEG decoder.
*/
private long avctx = 0;
/**
* The <tt>AVFrame</tt> which represents the media data decoded by the MJPEG decoder/
* {@link #avctx}.
*/
private long avframe = 0;
/**
* The pool of <tt>ByteBuffer</tt>s this instances is using to transfer the media data captured
* by the Video for Linux Two API Specification device out of this instance through the
* <tt>Buffer</tt>s specified in its {@link #read(Buffer)}.
*/
private final ByteBufferPool byteBufferPool = new ByteBufferPool();
/**
* The capabilities of the Video for Linux Two API Specification device represented by
* {@link #fd}.
*/
private int capabilities = 0;
/**
* The file descriptor of the Video for Linux Two API Specification device read through this
* <tt>PullBufferStream</tt>.
*/
private int fd = -1;
/**
* The last-known <tt>Format</tt> of the media data made available by this
* <tt>PullBufferStream</tt>
*/
private Format format;
/**
* The lengths in bytes of the buffers in the application's address space through which the
* Video for Linux Two API Specification device provides the captured media data to this
* instance when {@link #requestbuffersMemory} is equal to <tt>V4L2_MEMORY_MAP</tt>.
*/
private int[] mmapLengths;
/**
* The buffers through which the Video for Linux Two API Specification device provides the
* captured media data to this instance when {@link #requestbuffersMemory} is equal to
* <tt>V4L2_MEMORY_MAP</tt>. These are mapped in the application's address space.
*/
private long[] mmaps;
/**
* Native Video for Linux Two pixel format.
*/
private int nativePixelFormat = 0;
/**
* The number of buffers through which the Video for Linux Two API Specification device provides
* the captured media data to this instance when {@link #requestbuffersMemory} is equal to
* <tt>V4L2_MEMORY_MMAP</tt>.
*/
private int requestbuffersCount = 0;
/**
* The input method negotiated by this instance with the Video for Linux Two API Specification
* device.
*/
private int requestbuffersMemory = 0;
/**
* Tell device to start capture in read() method.
*/
private boolean startInRead = false;
/**
* The <tt>v4l2_buffer</tt> instance via which captured media data is fetched from the Video for
* Linux Two API Specification device to this instance in {@link #read(Buffer)}.
*/
private long v4l2_buffer;
/**
* Initializes a new <tt>Video4Linux2Stream</tt> instance which is to have its <tt>Format</tt>
* -related information abstracted by a specific <tt>FormatControl</tt>.
*
* @param dataSource
* the <tt>DataSource</tt> which is creating the new instance so that it becomes one of
* its <tt>streams</tt>
* @param formatControl
* the <tt>FormatControl</tt> which is to abstract the <tt>Format</tt>-related
* information of the new instance
*/
public Video4Linux2Stream(DataSource dataSource, FormatControl formatControl)
{
super(dataSource, formatControl);
v4l2_buffer = Video4Linux2.v4l2_buffer_alloc(Video4Linux2.V4L2_BUF_TYPE_VIDEO_CAPTURE);
if (0 == v4l2_buffer)
throw new OutOfMemoryError("v4l2_buffer_alloc");
Video4Linux2.v4l2_buffer_setMemory(v4l2_buffer, Video4Linux2.V4L2_MEMORY_MMAP);
}
/**
* Releases the resources used by this instance throughout its existence and makes it available
* for garbage collection. This instance is considered unusable after closing.
*
* @see AbstractPullBufferStream#close()
*/
@Override
public void close()
{
super.close();
if (v4l2_buffer != 0) {
Video4Linux2.free(v4l2_buffer);
v4l2_buffer = 0;
}
byteBufferPool.drain();
}
/**
* Gets the <tt>Format</tt> of this <tt>PullBufferStream</tt> as directly known by it.
*
* @return the <tt>Format</tt> of this <tt>PullBufferStream</tt> as directly known by it or
* <tt>null</tt> if this <tt>PullBufferStream</tt> does not directly know its
* <tt>Format</tt> and it relies on the <tt>PullBufferDataSource</tt> which created it
* to report its <tt>Format</tt>
* @see AbstractPullBufferStream#doGetFormat()
*/
@Override
protected Format doGetFormat()
{
Format format;
if (this.format == null) {
format = getFdFormat();
if (format == null)
format = super.doGetFormat();
else {
VideoFormat videoFormat = (VideoFormat) format;
if (videoFormat.getSize() != null)
this.format = format;
}
}
else
format = this.format;
return format;
}
/**
* Reads media data from this <tt>PullBufferStream</tt> into a specific <tt>Buffer</tt> with
* blocking.
*
* @param buffer
* the <tt>Buffer</tt> in which media data is to be read from this
* <tt>PullBufferStream</tt>
* @throws IOException
* if anything goes wrong while reading media data from this <tt>PullBufferStream</tt>
* into the specified <tt>buffer</tt>
* @see AbstractVideoPullBufferStream#doRead(Buffer)
*/
@Override
protected void doRead(Buffer buffer)
throws IOException
{
Format format = buffer.getFormat();
if (!(format instanceof AVFrameFormat))
format = null;
if (format == null) {
format = getFormat();
if (format != null)
buffer.setFormat(format);
}
if (startInRead) {
startInRead = false;
long v4l2_buf_type = Video4Linux2
.v4l2_buf_type_alloc(Video4Linux2.V4L2_BUF_TYPE_VIDEO_CAPTURE);
if (0 == v4l2_buf_type)
throw new OutOfMemoryError("v4l2_buf_type_alloc");
try {
if (Video4Linux2.ioctl(fd, Video4Linux2.VIDIOC_STREAMON, v4l2_buf_type) == -1) {
throw new IOException("ioctl: request= VIDIOC_STREAMON");
}
}
finally {
Video4Linux2.free(v4l2_buf_type);
}
}
if (Video4Linux2.ioctl(fd, Video4Linux2.VIDIOC_DQBUF, v4l2_buffer) == -1)
throw new IOException("ioctl: request= VIDIOC_DQBUF");
long timeStamp = System.nanoTime();
try {
int index = Video4Linux2.v4l2_buffer_getIndex(v4l2_buffer);
long mmap = mmaps[index];
int bytesused = Video4Linux2.v4l2_buffer_getBytesused(v4l2_buffer);
if ((nativePixelFormat == Video4Linux2.V4L2_PIX_FMT_JPEG)
|| (nativePixelFormat == Video4Linux2.V4L2_PIX_FMT_MJPEG)) {
/* Initialize the FFmpeg MJPEG decoder if necessary. */
if (avctx == 0) {
long avcodec = FFmpeg.avcodec_find_decoder(FFmpeg.CODEC_ID_MJPEG);
avctx = FFmpeg.avcodec_alloc_context3(avcodec);
FFmpeg.avcodeccontext_set_workaround_bugs(avctx, FFmpeg.FF_BUG_AUTODETECT);
if (FFmpeg.avcodec_open2(avctx, avcodec) < 0) {
throw new RuntimeException("" + "Could not open codec CODEC_ID_MJPEG");
}
avframe = FFmpeg.avcodec_alloc_frame();
}
if (FFmpeg.avcodec_decode_video(avctx, avframe, mmap, bytesused) != -1) {
Object out = buffer.getData();
if (!(out instanceof AVFrame) || (((AVFrame) out).getPtr() != avframe)) {
buffer.setData(new AVFrame(avframe));
}
}
}
else {
ByteBuffer data = byteBufferPool.getBuffer(bytesused);
if (data != null) {
Video4Linux2.memcpy(data.getPtr(), mmap, bytesused);
data.setLength(bytesused);
if (AVFrame.read(buffer, format, data) < 0)
data.free();
}
}
}
finally {
if (Video4Linux2.ioctl(fd, Video4Linux2.VIDIOC_QBUF, v4l2_buffer) == -1) {
throw new IOException("ioctl: request= VIDIOC_QBUF");
}
}
buffer.setFlags(Buffer.FLAG_LIVE_DATA | Buffer.FLAG_SYSTEM_TIME);
buffer.setTimeStamp(timeStamp);
}
/**
* Gets the <tt>Format</tt> of the media data captured by the Video for Linux Two API
* Specification device represented by the <tt>fd</tt> of this instance.
*
* @return the <tt>Format</tt> of the media data captured by the Video for Linux Two API
* Specification device represented by the <tt>fd</tt> of this instance
*/
private Format getFdFormat()
{
Format format = null;
if (-1 != fd) {
long v4l2_format = Video4Linux2
.v4l2_format_alloc(Video4Linux2.V4L2_BUF_TYPE_VIDEO_CAPTURE);
if (v4l2_format == 0)
throw new OutOfMemoryError("v4l2_format_alloc");
else {
try {
if (Video4Linux2.ioctl(fd, Video4Linux2.VIDIOC_G_FMT, v4l2_format) != -1) {
long fmtPix = Video4Linux2.v4l2_format_getFmtPix(v4l2_format);
int pixelformat = Video4Linux2.v4l2_pix_format_getPixelformat(fmtPix);
int ffmpegPixFmt = DataSource.getFFmpegPixFmt(pixelformat);
if (FFmpeg.PIX_FMT_NONE != ffmpegPixFmt) {
int width = Video4Linux2.v4l2_pix_format_getWidth(fmtPix);
int height = Video4Linux2.v4l2_pix_format_getHeight(fmtPix);
format = new AVFrameFormat(new Dimension(width, height),
Format.NOT_SPECIFIED, ffmpegPixFmt, pixelformat);
}
}
}
finally {
Video4Linux2.free(v4l2_format);
}
}
}
return format;
}
/**
* Unmaps the buffers through which the Video for Linux Two API Specification device provides
* the captured media data to this instance when {@link #requestbuffersMemory} is equal to
* <tt>V4L2_MEMORY_MMAP</tt> i.e. breaks the buffers' mappings between the driver's and the
* application's address spaces.
*/
private void munmap()
{
try {
if (mmaps != null) {
for (int i = 0; i < mmaps.length; i++) {
long mmap = mmaps[i];
if (mmap != 0) {
Video4Linux2.munmap(mmap, mmapLengths[i]);
mmaps[i] = 0;
mmapLengths[i] = 0;
}
}
}
}
finally {
mmaps = null;
mmapLengths = null;
}
}
/**
* Negotiates the input method with the Video for Linux Two API Specification device represented
* by the <tt>fd</tt> of this instance.
*
* @throws IOException
* if anything goes wrong while negotiating the input method with the Video for Linux
* Two API Specification device represented by the <tt>fd</tt> of this instance
*/
private void negotiateFdInputMethod()
throws IOException
{
long v4l2_capability = Video4Linux2.v4l2_capability_alloc();
if (0 == v4l2_capability)
throw new OutOfMemoryError("v4l2_capability_alloc");
try {
if (Video4Linux2.ioctl(fd, Video4Linux2.VIDIOC_QUERYCAP, v4l2_capability) == -1)
throw new IOException("ioctl: request= VIDIOC_QUERYCAP");
capabilities = Video4Linux2.v4l2_capability_getCapabilities(v4l2_capability);
}
finally {
Video4Linux2.free(v4l2_capability);
}
if ((capabilities & Video4Linux2.V4L2_CAP_STREAMING) != Video4Linux2.V4L2_CAP_STREAMING)
throw new IOException("Non-streaming V4L2 device not supported.");
long v4l2_requestbuffers = Video4Linux2
.v4l2_requestbuffers_alloc(Video4Linux2.V4L2_BUF_TYPE_VIDEO_CAPTURE);
if (0 == v4l2_requestbuffers)
throw new OutOfMemoryError("v4l2_requestbuffers_alloc");
try {
requestbuffersMemory = Video4Linux2.V4L2_MEMORY_MMAP;
Video4Linux2.v4l2_requestbuffers_setMemory(v4l2_requestbuffers, requestbuffersMemory);
Video4Linux2.v4l2_requestbuffers_setCount(v4l2_requestbuffers, 2);
if (Video4Linux2.ioctl(fd, Video4Linux2.VIDIOC_REQBUFS, v4l2_requestbuffers) == -1) {
throw new IOException("ioctl: request= VIDIOC_REQBUFS, memory= "
+ requestbuffersMemory);
}
requestbuffersCount = Video4Linux2.v4l2_requestbuffers_getCount(v4l2_requestbuffers);
}
finally {
Video4Linux2.free(v4l2_requestbuffers);
}
if (requestbuffersCount < 1)
throw new IOException("Insufficient V4L2 device memory.");
long v4l2_buffer = Video4Linux2.v4l2_buffer_alloc(Video4Linux2.V4L2_BUF_TYPE_VIDEO_CAPTURE);
if (0 == v4l2_buffer)
throw new OutOfMemoryError("v4l2_buffer_alloc");
try {
Video4Linux2.v4l2_buffer_setMemory(v4l2_buffer, Video4Linux2.V4L2_MEMORY_MMAP);
mmaps = new long[requestbuffersCount];
mmapLengths = new int[requestbuffersCount];
boolean munmap = true;
try {
for (int i = 0; i < requestbuffersCount; i++) {
Video4Linux2.v4l2_buffer_setIndex(v4l2_buffer, i);
if (Video4Linux2.ioctl(fd, Video4Linux2.VIDIOC_QUERYBUF, v4l2_buffer) == -1) {
throw new IOException("ioctl: request= VIDIOC_QUERYBUF");
}
int length = Video4Linux2.v4l2_buffer_getLength(v4l2_buffer);
long offset = Video4Linux2.v4l2_buffer_getMOffset(v4l2_buffer);
long mmap = Video4Linux2.mmap(0, length, Video4Linux2.PROT_READ
| Video4Linux2.PROT_WRITE, Video4Linux2.MAP_SHARED, fd, offset);
if (-1 == mmap)
throw new IOException("mmap");
mmaps[i] = mmap;
mmapLengths[i] = length;
}
munmap = false;
}
finally {
if (munmap)
munmap();
}
}
finally {
Video4Linux2.free(v4l2_buffer);
}
}
/**
* Sets the file descriptor of the Video for Linux Two API Specification device which is to be
* read through this <tt>PullBufferStream</tt>.
*
* @param fd
* the file descriptor of the Video for Linux Two API Specification device which is to be
* read through this <tt>PullBufferStream</tt>
* @throws IOException
* if anything goes wrong while setting the file descriptor of the Video for Linux Two
* API Specification device which is to be read through this <tt>PullBufferStream</tt>
*/
void setFd(int fd)
throws IOException
{
if (this.fd != fd) {
if (this.fd != -1) {
try {
stop();
}
catch (IOException ioex) {
}
munmap();
}
/*
* Before a Video for Linux Two API Specification device can be read, an attempt to set
* its format must be made and its cropping must be reset. We can only learn about the
* format to be set from formatControl. But since this AbstractPullBufferStream exists
* already, formatControl will ask it about its format. So pretend that there is no
* device prior to asking formatControl about the format in order to get the format that
* has been set by the user.
*/
this.fd = -1;
this.capabilities = 0;
this.requestbuffersMemory = 0;
this.requestbuffersCount = 0;
if (fd != -1) {
Format format = getFormat();
this.fd = fd;
if (format != null)
setFdFormat(format);
setFdCropToDefault();
negotiateFdInputMethod();
}
}
}
/**
* Sets the crop of the Video for Linux Two API Specification device represented by the
* <tt>fd</tt> of this instance to its default value so that this <tt>PullBufferStream</tt>
* reads media data without cropping.
*/
private void setFdCropToDefault()
{
// TODO Auto-generated method stub
}
/**
* Sets the <tt>Format</tt> in which the Video for Linux Two API Specification device
* represented by the <tt>fd</tt> of this instance is to capture media data.
*
* @param format
* the <tt>Format</tt> of the media data to be captured by the Video for Linux Two API
* Specification device represented by the <tt>fd</tt> of this instance
* @throws IOException
* if anything goes wrong while setting the <tt>Format</tt> of the media data to be
* captured by the Video for Linux Two API Specification device represented by the
* <tt>fd</tt> of this instance
*/
private void setFdFormat(Format format)
throws IOException
{
int pixelformat = 0;
if (format instanceof AVFrameFormat) {
pixelformat = ((AVFrameFormat) format).getDeviceSystemPixFmt();
nativePixelFormat = pixelformat;
}
if (Video4Linux2.V4L2_PIX_FMT_NONE == pixelformat)
throw new IOException("Unsupported format " + format);
long v4l2_format = Video4Linux2.v4l2_format_alloc(Video4Linux2.V4L2_BUF_TYPE_VIDEO_CAPTURE);
if (v4l2_format == 0)
throw new OutOfMemoryError("v4l2_format_alloc");
try {
if (Video4Linux2.ioctl(fd, Video4Linux2.VIDIOC_G_FMT, v4l2_format) == -1)
throw new IOException("ioctl: request= VIDIO_G_FMT");
VideoFormat videoFormat = (VideoFormat) format;
Dimension size = videoFormat.getSize();
long fmtPix = Video4Linux2.v4l2_format_getFmtPix(v4l2_format);
int width = Video4Linux2.v4l2_pix_format_getWidth(fmtPix);
int height = Video4Linux2.v4l2_pix_format_getHeight(fmtPix);
boolean setFdFormat = false;
if (size == null) {
// if there is no size in the format, respect settings
size = NeomediaServiceUtils.getMediaServiceImpl().getDeviceConfiguration()
.getVideoSize();
}
if ((size != null) && ((size.width != width) || (size.height != height))) {
Video4Linux2.v4l2_pix_format_setWidthAndHeight(fmtPix, size.width, size.height);
setFdFormat = true;
}
if (Video4Linux2.v4l2_pix_format_getPixelformat(v4l2_format) != pixelformat) {
Video4Linux2.v4l2_pix_format_setPixelformat(fmtPix, pixelformat);
setFdFormat = true;
}
if (setFdFormat)
setFdFormat(v4l2_format, fmtPix, size, pixelformat);
}
finally {
Video4Linux2.free(v4l2_format);
}
}
/**
* Sets the <tt>Format</tt> in which the Video for Linux Two API Specification device
* represented by the <tt>fd</tt> of this instance is to capture media data.
*
* @param v4l2_format
* native format to set on the Video for Linux Two API Specification device
* @param fmtPix
* native pixel format of the device
* @param size
* size to set on the device
* @param pixelformat
* requested pixel format
* @throws IOException
* if anything goes wrong while setting the native format of the media data to be
* captured by the Video for Linux Two API Specification device represented by the
* <tt>fd</tt> of this instance
*/
private void setFdFormat(long v4l2_format, long fmtPix, Dimension size, int pixelformat)
throws IOException
{
Video4Linux2.v4l2_pix_format_setField(fmtPix, Video4Linux2.V4L2_FIELD_NONE);
Video4Linux2.v4l2_pix_format_setBytesperline(fmtPix, 0);
if (Video4Linux2.ioctl(fd, Video4Linux2.VIDIOC_S_FMT, v4l2_format) == -1) {
throw new IOException("ioctl: request= VIDIOC_S_FMT"
+ ((size == null) ? "" : (", size= " + size.width + "x" + size.height))
+ ", pixelformat= " + pixelformat);
}
else if (Video4Linux2.v4l2_pix_format_getPixelformat(fmtPix) != pixelformat) {
throw new IOException("Failed to change the format of the V4L2 device to "
+ pixelformat);
}
}
/**
* Starts the transfer of media data from this <tt>PullBufferStream</tt>.
*
* @throws IOException
* if anything goes wrong while starting the transfer of media data from this
* <tt>PullBufferStream</tt>
* @see AbstractPullBufferStream#start()
*/
@Override
public void start()
throws IOException
{
super.start();
long v4l2_buffer = Video4Linux2.v4l2_buffer_alloc(Video4Linux2.V4L2_BUF_TYPE_VIDEO_CAPTURE);
if (0 == v4l2_buffer)
throw new OutOfMemoryError("v4l2_buffer_alloc");
try {
Video4Linux2.v4l2_buffer_setMemory(v4l2_buffer, Video4Linux2.V4L2_MEMORY_MMAP);
for (int i = 0; i < requestbuffersCount; i++) {
Video4Linux2.v4l2_buffer_setIndex(v4l2_buffer, i);
if (Video4Linux2.ioctl(fd, Video4Linux2.VIDIOC_QBUF, v4l2_buffer) == -1) {
throw new IOException("ioctl: request= VIDIOC_QBUF, index= " + i);
}
}
}
finally {
Video4Linux2.free(v4l2_buffer);
}
/*
* we will start capture in read() method (i.e do the VIDIOC_STREAMON ioctl) because for
* some couple of fps/resolution the captured image will be weird (shift, not a JPEG for
* JPEG/MJPEG format, ...) if it is done here. Maybe it is due because sometime JMF do the
* sequence start/stop/start too quickly...
*/
startInRead = true;
}
/**
* Stops the transfer of media data from this <tt>PullBufferStream</tt>.
*
* @throws IOException
* if anything goes wrong while stopping the transfer of media data from this
* <tt>PullBufferStream</tt>
* @see AbstractPullBufferStream#stop()
*/
@Override
public void stop()
throws IOException
{
try {
long v4l2_buf_type = Video4Linux2
.v4l2_buf_type_alloc(Video4Linux2.V4L2_BUF_TYPE_VIDEO_CAPTURE);
if (0 == v4l2_buf_type)
throw new OutOfMemoryError("v4l2_buf_type_alloc");
try {
if (Video4Linux2.ioctl(fd, Video4Linux2.VIDIOC_STREAMOFF, v4l2_buf_type) == -1) {
throw new IOException("ioctl: request= VIDIOC_STREAMOFF");
}
}
finally {
Video4Linux2.free(v4l2_buf_type);
}
}
finally {
super.stop();
if (avctx != 0) {
FFmpeg.avcodec_close(avctx);
FFmpeg.av_free(avctx);
avctx = 0;
}
if (avframe != 0) {
FFmpeg.avcodec_free_frame(avframe);
avframe = 0;
}
byteBufferPool.drain();
}
}
}
| 31.788462 | 97 | 0.700079 |
11fff13702db26c057a8d24c11ed2eea42f1fd16 | 1,539 | import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;
import java.lang.Thread;
public class GnawResources {
//Read file content into the string with - Files.lines(Path path, Charset cs)
private static String ReadFile(String path) {
StringBuilder contentBuilder = new StringBuilder();
try (Stream<String> stream = Files.lines( Paths.get(path), StandardCharsets.UTF_8)) {
stream.forEach(s->contentBuilder.append(s).append("\n"));
} catch (IOException e) {
//e.printStackTrace();
return null;
}
return contentBuilder.toString();
}
private static int ReadIntFile(String path) {
String data = ReadFile(path);
try {
data = data.replace("\n", "");
return Integer.valueOf(data);
} catch (Exception e) {
return 0;
}
}
public static void main(String[] args) throws InterruptedException {
int mem_usage = 0;
String path = "/tmp/gnaw-mem.txt";
int[] mem_user;
while (true) {
int new_mem_usage = ReadIntFile(path);
if (mem_usage != new_mem_usage) {
System.out.println(new_mem_usage);
mem_usage = new_mem_usage;
// size in Mb, 32-bit ints (4 bytes)
int int_count = mem_usage*1000000/4;
mem_user = new int[int_count];
}
Thread.sleep(1000);
}
}
}
| 30.176471 | 93 | 0.598441 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.