text stringlengths 10 2.72M |
|---|
package test;
import java.util.Arrays;
import vo.PlayerSortBy;
import vo.SortType;
public class PlayerCommand
{
int avg_total = 0; //0代表场均数据,1代表赛季总数据。默认为场均数据
int all_hot_king = 0; //0代表all所有球员数据,1代表hot热门球员信息(均为场均数据),2代表king获得数据王
int season_daily = 0; //0代表赛季数据王,1代表当日数据王
int n = -1; //-1代表默认值
int low_high = 0 ; //0代表基本数据low,1代表高阶数据high
int filter = 0; //0代表非筛选操作,1代表筛选操作
String position = "All"; //F(前锋),G(后卫),C(中锋),All 所有的 (默认)
String league = "All"; //West(西部联盟),East(东部联盟),All(所有,默认)
int year = -1; //0(<=22),1(22<X<=25),2(25<X<=30),3(X>30); -1(all default)
int sort = 0 ; //0表示选择默认排序操作,基础数据的默认排序依据为 -sort score.desc,高阶数据的默认排序依据为-sort winRate.desc
//对于排序属性的值相同的按球队名的升序排序
PlayerSortBy[] sorts = new PlayerSortBy[10];
SortType[] sortType = new SortType[10];
int sort_len = -1;
String hotPlayerSort;
String kingPlayerSort;
public void readCommand(String[] commands)
{
int len = commands.length;
String temp = null;
for (int i = 0; i < len; i++)
{
switch (commands[i])
{
case "-avg":
avg_total = 0;
break;
case "-total":
avg_total = 1;
break;
case "-all":
all_hot_king = 0;
break;
case "-hot":
all_hot_king = 1;
++i;
hotPlayerSort = commands[i];
break;
case "-king":
all_hot_king = 2;
++i;
kingPlayerSort = commands[i];
break;
case "-season":
season_daily = 0;
break;
case "-daily":
season_daily = 1;
break;
case "-n":
++i;
n = Integer.parseInt(commands[i]);
break;
case "-high":
low_high = 1;
break;
case "-filter":
filter = 1;
++i;
String filter_choice = commands[i];
String[] choices = null;
String[] filter_choice_list = filter_choice.split(",");
for (int k = 0;k < filter_choice_list.length; k++)
{
choices = filter_choice_list[k].split("\\.");
switch (choices[0])
{
case "position":
position = choices[1];
break;
case "league":
league = choices[1];
break;
case "age":
switch (choices[1])
{
case "<=22":
year = 0;
break;
case "22<X<=25":
year = 1;
break;
case "25<X<=30":
year = 2;
break;
case ">30":
year =3;
break;
case "All":
year = -1;
break;
}
break;
}
}
break;
case "-sort":
sort = 1;
++i;
String[] choice = commands[i].split(",");
for (String temp1 : choice)
{
dealWithOneSortField(temp1);
}
break;
}
}
}
private void dealWithOneSortField(String field)
{
String[] choices = field.split("\\.");
++sort_len;
PlayerSortBy sortBy = null;
SortType sortType = null;
switch (choices[0])
{
//得分
case "score":
case "point":
sortBy = PlayerSortBy.points;
break;
//篮板
case "rebound":
sortBy = PlayerSortBy.rebound;
break;
//助攻
case "assist":
sortBy = PlayerSortBy.assistNo;
break;
//盖帽
case "blockShot":
sortBy = PlayerSortBy.blockNo;
break;
//抢断
case "steal":
sortBy = PlayerSortBy.stealsNo;
break;
//犯规
case "foul":
sortBy = PlayerSortBy.foulsNo;
break;
//失误
case "fault":
sortBy = PlayerSortBy.mistakesNo;
break;
//分钟(上场时间)
case "minute":
sortBy = PlayerSortBy.minute;
break;
//效率
case "efficient":
sortBy = PlayerSortBy.efficiency;
break;
//投篮命中率
case "shot":
sortBy = PlayerSortBy.hitRate;
break;
//三分球命中率
case "three":
sortBy = PlayerSortBy.threeHitRate;
break;
//罚球命中率
case "penalty":
sortBy = PlayerSortBy.penaltyHitRate;
break;
//两双
case "doubleTwo":
sortBy = PlayerSortBy.twoPair;
break;
//真实投篮命中率
case "realShot":
sortBy = PlayerSortBy.trueHitRate;
break;
//gmsc效率值
case "GmSc":
sortBy = PlayerSortBy.gmScEfficiency;
break;
//投篮效率
case "shotEfficient":
sortBy = PlayerSortBy.hitEfficiency;
break;
//篮板效率
case "reboundEfficient":
sortBy = PlayerSortBy.rebEfficiency;
break;
//进攻篮板率
case "offendReboundEfficient":
sortBy = PlayerSortBy.offenseRebsEfficiency;
break;
//防守篮板率
case "defendReboundEfficient":
sortBy = PlayerSortBy.defenceRebsEfficiency;
break;
//助攻率
case "assistEfficient":
sortBy = PlayerSortBy.assistEfficiency;
break;
//抢断率
case "stealEfficient":
sortBy = PlayerSortBy.stealsEfficiency;
break;
//盖帽率
case "blockShotEfficient":
sortBy = PlayerSortBy.blockEfficiency;
break;
//失误率
case "faultEfficient":
sortBy = PlayerSortBy.mistakeEfficiency;
break;
//使用率
case "frequency":
sortBy = PlayerSortBy.useEfficiency;
break;
}
switch (choices[1])
{
case "desc":
sortType = SortType.DESEND;
break;
case "asc":
sortType = SortType.ASEND;
break;
}
sorts[sort_len] = sortBy;
this.sortType[sort_len] = sortType;
}
public int getAvg_total() {
return avg_total;
}
public int getAll_hot_king() {
return all_hot_king;
}
public int getSeason_daily() {
return season_daily;
}
public int getN() {
return n;
}
public int getLow_high() {
return low_high;
}
public int getFilter() {
return filter;
}
public String getPositon() {
return position;
}
public String getLeague() {
return league;
}
public int getYear() {
return year;
}
public int getSort() {
return sort;
}
public PlayerSortBy[] getSorts() {
return Arrays.copyOf(sorts, sort_len+1);
}
public SortType[] getSortType() {
return Arrays.copyOf(sortType, sort_len+1);
}
public String getHotPlayerSort() {
return hotPlayerSort;
}
public String getKingPlayerSort()
{
return kingPlayerSort;
}
public int getSortLen()
{
return sort_len;
}
}
|
package com.lesson02.calculator;
public class Calculator {
void calculate(int a, char operator, int b) {
switch(operator) {
case '+':
System.out.println("Сумма чисел a и b равна " + (a + b));
break;
case '-':
System.out.println("Разница чисел a и b равна " + (a - b));
break;
case '*':
System.out.println("Произведение чисел a и b равно " + (a * b));
break;
case '/':
if (b != 0) {
System.out.println("Частное чисел a и b равно " + (double) a / b);
// Без явного приведения операция совершается как int
} else {
System.out.println("Некорретный ввод. b не должно быть равным 0 ");
}
break;
case '%':
System.out.println("Остаток от деления чисел a и b равно " + (a % b));
break;
case '^':
int k = 1;
for (int i = 0; i < b; i++) {
k *= a;
}
System.out.println(a + " в степени " + b + " равно " + k);
break;
default:
System.out.println("Некорректная операция: " + operator);
}
}
} |
package com.ngocdt.tttn.controller;
import com.ngocdt.tttn.dto.BrandDTO;
import com.ngocdt.tttn.dto.CharacteristicDTO;
import com.ngocdt.tttn.service.BrandService;
import com.ngocdt.tttn.service.CharacteristicService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
@RequiredArgsConstructor
@Controller
@RequestMapping("api/admin/characteristics")
public class CharacteristicController {
private final CharacteristicService characteristicService;
@GetMapping()
public ResponseEntity<List<CharacteristicDTO>> showAll() {
return ResponseEntity.ok().body(characteristicService.showAll());
}
}
|
package cn.lyh.spa.ptrnew;
import android.content.Context;
/**
* Created by liyuhao on 2017/6/7.
*/
public class CnsCommonUtil {
/**
* dp转px
* @param context 上下文
* @param dpValue dp值
* @return px值
*/
public static int dip2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale);
}
/**
* px转dp
* @param context 上下文
* @param pxValue px值
* @return dp值
*/
public static int px2dip(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale);
}
}
|
package net.mv.shopping;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.ejb.*;
import dataservice.ShoppingDAO;
import dataservice.ShoppingDAOImpl;
/**
* Session Bean implementation class ShoppingCartBean
*/
//@Stateful(name="shoppingcart")
@Stateless(name="shoppingcart")
public class ShoppingCartBean implements ShoppingCart {
/**
* Default constructor.
*/
public ShoppingCartBean() {
// TODO Auto-generated constructor stub
}
private ArrayList<String> cart;
@Override
public void addToCart(String item) {
// TODO Auto-generated method stub
System.out.println("Added " + item + " to cart.");
ShoppingDAO shop = new ShoppingDAOImpl();
shop.add(item);
cart.add(item);
}
@Override
public List<String> getCartItems() {
// TODO Auto-generated method stub
System.out.println("Getting cart items... ");
return cart;
}
@Override
@Remove
public void remove() {
// TODO Auto-generated method stub
System.out.println("Bean is removed");
}
@PostConstruct
public void init(){
System.out.println("Post construction of bean");
cart = new ArrayList<String>();
}
@PreDestroy
public void destroy(){
System.out.println("Pre destruction of bean");
}
@PrePassivate
public void passive(){
System.out.println("Pre passivation of bean");
}
@PostActivate
public void activate(){
System.out.println("Post activation of bean");
}
}
|
package com.org.spring.boot.amqp.publisher;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.retry.backoff.ExponentialBackOffPolicy;
import org.springframework.retry.policy.SimpleRetryPolicy;
import org.springframework.retry.support.RetryTemplate;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Random;
@Slf4j
@Service
public class InspectionMessagePublisher {
@Autowired
protected ObjectMapper objectMapper;
@Autowired
protected CachingConnectionFactory connectionFactory;
@Value("${inspection.messaging.exchange}")
private String inspectionExchange;
public void sendMessage(final List<String> inspectionMessageEnvelopes) {
try {
for (final String inspectionMessageEnvelope : inspectionMessageEnvelopes) {
final String jsonMessage = objectMapper.writeValueAsString(inspectionMessageEnvelope);
final Message message = new Message(jsonMessage.getBytes(), new MessageProperties());
final String routingKey = "jci.tofs.inspection." + new Random().nextInt(1000);
rabbitTemplate().convertAndSend(inspectionExchange, routingKey, message);
log.info("Message [ {} ] is published with routing key [ {} ]", jsonMessage, routingKey);
}
} catch (final JsonProcessingException jsonParseException) {
log.error("Parsing exception ", jsonParseException);
}
}
@Bean
public RabbitTemplate rabbitTemplate() {
final RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
RetryTemplate retryTemplate = new RetryTemplate();
ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
//backOffPolicy.setInitialInterval(200);
//backOffPolicy.setMultiplier(2.0);
//backOffPolicy.setMaxInterval(100000);
retryTemplate.setBackOffPolicy(backOffPolicy);
SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
retryPolicy.setMaxAttempts(3);
retryTemplate.setRetryPolicy(retryPolicy);
rabbitTemplate.setRetryTemplate(retryTemplate);
//rabbitTemplate.setRecoveryCallback(recoveryCallBack);
rabbitTemplate.setMessageConverter(jackson2JsonMessageConverter());
return rabbitTemplate;
}
@Bean
public Jackson2JsonMessageConverter jackson2JsonMessageConverter() {
return new Jackson2JsonMessageConverter();
}
}
|
package com.example.sys.controller;
import com.alibaba.fastjson.JSON;
import com.example.sys.entity.BusClick;
import com.example.sys.entity.Product;
import com.example.sys.entity.ProductSearch;
import com.example.sys.entity.User;
import com.example.sys.service.AsyncTaskService;
import com.example.sys.service.ProductService;
import com.example.sys.util.DownloadFileUtil;
import com.example.sys.util.ExcelUtils;
import com.example.sys.util.PageDataResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
/**
* Created by tyj on 2019/07/03.
*/
@Slf4j
@Controller
@RequestMapping("/product")
public class ProductController extends BaseController{
// 文件上级目录
String PATH = "excel";
// 文件名
String FILENAME ="imei.xlsx";
@Autowired
private ProductService productService;
@Autowired
private AsyncTaskService asyncTaskService;
List<BusClick> failList = new ArrayList<>();
List<BusClick> busClicks = new ArrayList<>();
@RequestMapping("/index")
public String index(Model model, HttpServletRequest request, HttpServletResponse response) throws IOException {
log.debug("-------------index------------");
User user = (User) request.getSession().getAttribute("admin");
if (user == null) {
response.sendRedirect(request.getContextPath()+"/admin/login");
return null;
}
model.addAttribute("username", user.getUsername());
log.debug("用户名:"+user.getUsername());
return "product/index";
}
/**
* 分页查询产品列表
* @return ok/fail
*/
@RequestMapping(value = "/getProducts", method = RequestMethod.POST)
@ResponseBody
public PageDataResult getProducts(@RequestParam("page") Integer page,
@RequestParam("limit") Integer limit, ProductSearch productSearch,HttpServletRequest request) {
log.debug("分页查询产品列表!搜索条件:productSearch:" + productSearch + ",page:" + page
+ ",每页记录数量limit:" + limit);
System.out.println(request.toString());
PageDataResult pdr = new PageDataResult();
try {
if (null == page) {
page = 1;
}
if (null == limit) {
limit = 10;
}
// 获取产品列表
pdr = productService.getProducts(productSearch, page, limit);
log.info("产品列表查询=pdr:" + pdr);
} catch (Exception e) {
e.printStackTrace();
log.error("产品列表查询异常!", e);
}
return pdr;
}
/**
* 下载模板
* @return 返回excel模板
*/
@RequestMapping(value = "/export", method = RequestMethod.GET, produces ="application/json;charset=UTF-8")
@ResponseBody
public Object export(){
ResponseEntity<InputStreamResource> response = null;
try {
response = DownloadFileUtil.download(PATH, FILENAME, "导入模板");
} catch (Exception e) {
log.error("下载模板失败");
}
return response;
}
public static boolean isLetterDigit(String str) {
if(!StringUtils.isNotEmpty(str))
{return false;}
String regex = "^[a-z0-9A-Z]+$";
return str.matches(regex);
}
@ResponseBody
@RequestMapping(value = "/upload")
public String readExcel(@RequestParam("file") MultipartFile file){
long t1 = System.currentTimeMillis();
List<BusClick> list = ExcelUtils.readExcel("", BusClick.class, file);
long t2 = System.currentTimeMillis();
System.out.println(String.format("read over! cost:%sms", (t2 - t1)));
failList.clear();
log.info("开始处理数据************************");
long t3 = System.currentTimeMillis();
list.stream().forEach(o -> {
int index = list.indexOf(o);
System.out.println(JSON.toJSONString(o));
// 数据格式过滤
String imei1 = o.getImei_1();
if (!isLetterDigit(imei1) || imei1.length()!=15 ){
failList.add(o);
return ;
}
String iccid1 = o.getICCID1();
if (!isLetterDigit(iccid1) || iccid1.length()!=20){
failList.add(o);
return ;
}
String machine_sn =o.getMachine_sn();
if (!isLetterDigit(machine_sn)|| machine_sn.length()!=16){
failList.add(o);
return ;
}
// 异步任务开启
asyncTaskService.executeAsyncTask(o,index);
});
long t4 = System.currentTimeMillis();
log.info("成功处理数据消耗时间:"+(t4-t3)+" ms");
log.info("结束处理数据************************");
String msg ;
if(failList.size() > 0 ) {
msg = "共计" + list.size() + "条数据,导入成功" +(list.size() - failList.size()) + "条数据,导入失败" + failList.size() + "条,失败原因:数据无效,请检查数据重新上传!";
}else {
msg = "共计" + list.size() + "条数据,导入成功" + list.size() + "条数据,导入失败0条。";
}
return this.outPutData(msg);
}
@RequestMapping(value = "/exportExcel", method = RequestMethod.GET)
public void exportExcel(HttpServletResponse response) throws IOException {
List<BusClick> resultList =failList;
long t1 = System.currentTimeMillis();
ExcelUtils.writeExcel(response, resultList, BusClick.class);
long t2 = System.currentTimeMillis();
System.out.println(String.format("write over! cost:%sms", (t2 - t1)));
}
/**
* 批量查询下载
* @return ok/fail
*/
@ResponseBody
@RequestMapping(value = "/upload1")
public String batch(@RequestParam("file") MultipartFile file ){
long t1 = System.currentTimeMillis();
List<BusClick> list = ExcelUtils.readExcel("", BusClick.class, file);
long t2 = System.currentTimeMillis();
System.out.println(String.format("read over! cost:%sms", (t2 - t1)));
long t3 = System.currentTimeMillis();
List<Product> listAll = new ArrayList<Product>();
for (int i=0 ;i<list.size();i++){
ProductSearch productSearch = new ProductSearch();
productSearch.setMachine_sn(list.get(i).getMachine_sn());
List<Product> productList = productService.getProductList(productSearch);
listAll.addAll(productList);
}
listAll = new ArrayList<Product>(new LinkedHashSet<>(listAll));
listAll.stream().forEach(o->{
BusClick busClick = new BusClick();
BeanUtils.copyProperties(o, busClick);
busClicks.add(busClick);
});
String msg = "共计匹配到" + listAll.size() + "条数据,请下载!";
return this.outPutData(msg);
}
@RequestMapping(value = "/exportExcel1", method = RequestMethod.GET)
public void exportExcel1(HttpServletResponse response) throws IOException {
List<BusClick> resultList =busClicks;
long t1 = System.currentTimeMillis();
ExcelUtils.writeExcel1(response, resultList, BusClick.class);
long t2 = System.currentTimeMillis();
System.out.println(String.format("write over! cost:%sms", (t2 - t1)));
}
/**
* 批量删除
* @return ok/fail
*/
@RequestMapping(value = "/delProduct", method = RequestMethod.POST)
@ResponseBody
public String delProduct(@RequestParam("data") String proData) {
log.debug("需要删除的产品信息:"+proData);
List<Map> list= JSON.parseArray(proData, Map.class);
try {
if (list.size()==0) {
log.debug("请求参数有误,请您稍后再试");
return this.outPutErr("请求参数有误,请您稍后再试!");
}
/**删除*/
list.stream().forEach(o->{
int pid = (int) o.get("id");
productService.deleteProduct(pid);
});
} catch (Exception e) {
e.printStackTrace();
log.error("操作异常!", e);
return this.outPutErr("操作异常,请您稍后再试!");
}
return this.outPutData("成功删除"+list.size()+"数据!");
}
}
|
/*
* Copyright 2002-2022 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
*
* https://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.springframework.aop.aspectj.annotation;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.AjType;
import org.aspectj.lang.reflect.AjTypeSystem;
import org.aspectj.lang.reflect.PerClauseKind;
import org.springframework.aop.Pointcut;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.aspectj.TypePatternClassFilter;
import org.springframework.aop.framework.AopConfigException;
import org.springframework.aop.support.ComposablePointcut;
/**
* Metadata for an AspectJ aspect class, with an additional Spring AOP pointcut
* for the per clause.
*
* <p>Uses AspectJ 5 AJType reflection API, enabling us to work with different
* AspectJ instantiation models such as "singleton", "pertarget" and "perthis".
*
* @author Rod Johnson
* @author Juergen Hoeller
* @since 2.0
* @see org.springframework.aop.aspectj.AspectJExpressionPointcut
*/
@SuppressWarnings("serial")
public class AspectMetadata implements Serializable {
/**
* The name of this aspect as defined to Spring (the bean name) -
* allows us to determine if two pieces of advice come from the
* same aspect and hence their relative precedence.
*/
private final String aspectName;
/**
* The aspect class, stored separately for re-resolution of the
* corresponding AjType on deserialization.
*/
private final Class<?> aspectClass;
/**
* AspectJ reflection information.
* <p>Re-resolved on deserialization since it isn't serializable itself.
*/
private transient AjType<?> ajType;
/**
* Spring AOP pointcut corresponding to the per clause of the
* aspect. Will be the {@code Pointcut.TRUE} canonical instance in the
* case of a singleton, otherwise an AspectJExpressionPointcut.
*/
private final Pointcut perClausePointcut;
/**
* Create a new AspectMetadata instance for the given aspect class.
* @param aspectClass the aspect class
* @param aspectName the name of the aspect
*/
public AspectMetadata(Class<?> aspectClass, String aspectName) {
this.aspectName = aspectName;
Class<?> currClass = aspectClass;
AjType<?> ajType = null;
while (currClass != Object.class) {
AjType<?> ajTypeToCheck = AjTypeSystem.getAjType(currClass);
if (ajTypeToCheck.isAspect()) {
ajType = ajTypeToCheck;
break;
}
currClass = currClass.getSuperclass();
}
if (ajType == null) {
throw new IllegalArgumentException("Class '" + aspectClass.getName() + "' is not an @AspectJ aspect");
}
if (ajType.getDeclarePrecedence().length > 0) {
throw new IllegalArgumentException("DeclarePrecedence not presently supported in Spring AOP");
}
this.aspectClass = ajType.getJavaClass();
this.ajType = ajType;
switch (this.ajType.getPerClause().getKind()) {
case SINGLETON -> {
this.perClausePointcut = Pointcut.TRUE;
}
case PERTARGET, PERTHIS -> {
AspectJExpressionPointcut ajexp = new AspectJExpressionPointcut();
ajexp.setLocation(aspectClass.getName());
ajexp.setExpression(findPerClause(aspectClass));
ajexp.setPointcutDeclarationScope(aspectClass);
this.perClausePointcut = ajexp;
}
case PERTYPEWITHIN -> {
// Works with a type pattern
this.perClausePointcut = new ComposablePointcut(new TypePatternClassFilter(findPerClause(aspectClass)));
}
default -> throw new AopConfigException(
"PerClause " + ajType.getPerClause().getKind() + " not supported by Spring AOP for " + aspectClass);
}
}
/**
* Extract contents from String of form {@code pertarget(contents)}.
*/
private String findPerClause(Class<?> aspectClass) {
String str = aspectClass.getAnnotation(Aspect.class).value();
int beginIndex = str.indexOf('(') + 1;
int endIndex = str.length() - 1;
return str.substring(beginIndex, endIndex);
}
/**
* Return AspectJ reflection information.
*/
public AjType<?> getAjType() {
return this.ajType;
}
/**
* Return the aspect class.
*/
public Class<?> getAspectClass() {
return this.aspectClass;
}
/**
* Return the aspect name.
*/
public String getAspectName() {
return this.aspectName;
}
/**
* Return a Spring pointcut expression for a singleton aspect.
* (e.g. {@code Pointcut.TRUE} if it's a singleton).
*/
public Pointcut getPerClausePointcut() {
return this.perClausePointcut;
}
/**
* Return whether the aspect is defined as "perthis" or "pertarget".
*/
public boolean isPerThisOrPerTarget() {
PerClauseKind kind = getAjType().getPerClause().getKind();
return (kind == PerClauseKind.PERTARGET || kind == PerClauseKind.PERTHIS);
}
/**
* Return whether the aspect is defined as "pertypewithin".
*/
public boolean isPerTypeWithin() {
PerClauseKind kind = getAjType().getPerClause().getKind();
return (kind == PerClauseKind.PERTYPEWITHIN);
}
/**
* Return whether the aspect needs to be lazily instantiated.
*/
public boolean isLazilyInstantiated() {
return (isPerThisOrPerTarget() || isPerTypeWithin());
}
private void readObject(ObjectInputStream inputStream) throws IOException, ClassNotFoundException {
inputStream.defaultReadObject();
this.ajType = AjTypeSystem.getAjType(this.aspectClass);
}
}
|
package sg.edu.iss.ad;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableScheduling;
import sg.edu.iss.ad.utility.DbSeeding;
@EnableScheduling
@SpringBootApplication
public class T11AdProjectApplication {
@Autowired
DbSeeding DbSeeding;
public static void main(String[] args) {
SpringApplication.run(T11AdProjectApplication.class, args);
}
@Bean
CommandLineRunner runner() {
return args->{
//Seed data only done once
//DbSeeding.seedDB1();
//DbSeeding.seedDB2();
// 2 users
// 4 candlesticks
// 2 stocks AAPL and GOOG
// Both users have both AAPL and GOOG in the watchlist,
// Both users commented on both stocks before
// User 1, added enabled tracking : 4 candles, for AAPL stock , Morning star and evening star for GOOG stock
// User 2, added candle tracking: engulfing bullish and engulfing bearish for AAPL stock
};
}
}
|
package com.minhvu.proandroid.sqlite.database.main.model;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.SharedPreferences;
import android.net.Uri;
import com.minhvu.proandroid.sqlite.database.main.model.view.IDetailModel;
import com.minhvu.proandroid.sqlite.database.main.presenter.view.IDetailPresenter;
/**
* Created by vomin on 8/26/2017.
*/
public class DetailModel implements IDetailModel {
private IDetailPresenter mMainPresenter;
private SharedPreferences mPreferences = null;
public DetailModel(SharedPreferences preferences){
this.mPreferences = preferences;
}
@Override
public void setPresenter(IDetailPresenter presenter) {
mMainPresenter = presenter;
}
@Override
public void onDestroy(boolean isChangingConfiguration) {
if(!isChangingConfiguration){
mMainPresenter = null;
mPreferences = null;
}
}
@Override
public void setDataSharePreference(String key, String content) {
SharedPreferences.Editor editor = mPreferences.edit();
editor.putString(key, content);
editor.apply();
}
@Override
public String getDataSharePreference( String key) {
return mPreferences.getString(key, "");
}
@Override
public Uri insertData(Uri uri, ContentValues cv) {
ContentResolver contentResolver = mMainPresenter.getActivityContext().getContentResolver();
Uri uriInsert = null;
uriInsert = contentResolver.insert(uri, cv);
return uriInsert;
}
@Override
public boolean update(Uri uri, ContentValues cv, String where, String[] selectionArgs) {
ContentResolver contentResolver = mMainPresenter.getActivityContext().getContentResolver();
int success = contentResolver.update(uri, cv, where, selectionArgs);
return success > 0;
}
@Override
public boolean delete(Uri uri, String where, String[] selectionArgs) {
ContentResolver contentResolver = mMainPresenter.getActivityContext().getContentResolver();
int success = contentResolver.delete(uri, where, selectionArgs);
if(success > 0){
return true;
}
return false;
}
}
|
package artronics.gsdwn.node;
public enum NodeType
{
SINK,
NORMAL,
}
|
package com.example;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
public class Criteria1 {
public static void main(String args[]) {
Data.prepareData();
Session session = HibernateSessionFactory.getSession();
Criteria crit = session.createCriteria(Supplier.class);
Criteria prdCrit = crit.createCriteria("products");
prdCrit.add(Restrictions.gt("price", new Double(22.0)));
@SuppressWarnings("unchecked")
List<Supplier> results = (List<Supplier>)crit.list();
System.out.println("Suppliers list is:");
displaySupplierList(results);
session.close();
}
static public void displaySupplierList(List<?> list) {
Iterator<?> iter = list.iterator();
if (!iter.hasNext()) {
System.out.println("No suppliers to display.");
return;
}
while (iter.hasNext()) {
Supplier supplier = (Supplier) iter.next();
String msg = supplier.getName();
System.out.println(msg);
}
}
}
|
package com.mediafire.sdk.api;
import com.mediafire.sdk.MFApiException;
import com.mediafire.sdk.MFException;
import com.mediafire.sdk.MFSessionNotStartedException;
import com.mediafire.sdk.MediaFire;
import com.mediafire.sdk.api.responses.*;
import com.mediafire.sdk.requests.ApiPostRequest;
import java.util.LinkedHashMap;
/**
* http://www.mediafire.com/developers/core_api/1.3/getting_started/
* @see <a href="http://www.mediafire.com/developers/core_api/1.3/getting_started/">MediaFire Developer Portal</a>
*/
public class NotificationsApi {
private NotificationsApi() {
// no instantiation, utility class only
}
/**
* Gets and clears a specified number of the most recent cache-only notifications for the current user.
*
* @param mediaFire an instance of MediaFire which has a session in progress
* @param requestParams a LinkedHashMap of required and optional parameters
* @param apiVersion version of the api to call e.g. 1.0, 1.1, 1.2
* @param classOfT the .class file passed which will be used to parse the api JSON response using Gson (must extend ApiResponse)
* @return an instance of {@param classOfT}
* @throws com.mediafire.sdk.MFException if an exception occurred
* @throws MFApiException, MFSessionNotStartedException if there was an api error
*/
public static <T extends ApiResponse> T getCache(MediaFire mediaFire, LinkedHashMap<String, Object> requestParams, String apiVersion, Class<T> classOfT) throws MFException, MFApiException, MFSessionNotStartedException {
ApiPostRequest apiPostRequest = new ApiPostRequest("/api/" + apiVersion + "/notifications/get_cache.php", requestParams);
return mediaFire.doApiRequest(apiPostRequest, classOfT);
}
/**
* Gets the number of cache-only notifications for the current user.
*
* @param mediaFire an instance of MediaFire which has a session in progress
* @param requestParams a LinkedHashMap of required and optional parameters
* @param apiVersion version of the api to call e.g. 1.0, 1.1, 1.2
* @param classOfT the .class file passed which will be used to parse the api JSON response using Gson (must extend ApiResponse)
* @return an instance of {@param classOfT}
* @throws com.mediafire.sdk.MFException if an exception occurred
* @throws MFApiException, MFSessionNotStartedException if there was an api error
*/
public static <T extends ApiResponse> T peekCache(MediaFire mediaFire, LinkedHashMap<String, Object> requestParams, String apiVersion, Class<T> classOfT) throws MFException, MFApiException, MFSessionNotStartedException {
ApiPostRequest apiPostRequest = new ApiPostRequest("/api/" + apiVersion + "/notifications/peek_cache.php", requestParams);
return mediaFire.doApiRequest(apiPostRequest, classOfT);
}
/**
* Sends a generic message with a list of file and folder keys to one or more contacts.
*
* @param mediaFire an instance of MediaFire which has a session in progress
* @param requestParams a LinkedHashMap of required and optional parameters
* @param apiVersion version of the api to call e.g. 1.0, 1.1, 1.2
* @param classOfT the .class file passed which will be used to parse the api JSON response using Gson (must extend ApiResponse)
* @return an instance of {@param classOfT}
* @throws com.mediafire.sdk.MFException if an exception occurred
* @throws MFApiException, MFSessionNotStartedException if there was an api error
*/
public static <T extends ApiResponse> T sendMessage(MediaFire mediaFire, LinkedHashMap<String, Object> requestParams, String apiVersion, Class<T> classOfT) throws MFException, MFApiException, MFSessionNotStartedException {
ApiPostRequest apiPostRequest = new ApiPostRequest("/api/" + apiVersion + "/notifications/send_message.php", requestParams);
return mediaFire.doApiRequest(apiPostRequest, classOfT);
}
/**
*
* @param mediaFire an instance of MediaFire which has a session in progress
* @param requestParams a LinkedHashMap of required and optional parameters
* @param apiVersion version of the api to call e.g. 1.0, 1.1, 1.2
* @param classOfT the .class file passed which will be used to parse the api JSON response using Gson (must extend ApiResponse)
* @return an instance of {@param classOfT}
* @throws com.mediafire.sdk.MFException if an exception occurred
* @throws MFApiException, MFSessionNotStartedException if there was an api error
*/
public static <T extends ApiResponse> T sendNotification(MediaFire mediaFire, LinkedHashMap<String, Object> requestParams, String apiVersion, Class<T> classOfT) throws MFException, MFApiException, MFSessionNotStartedException {
ApiPostRequest apiPostRequest = new ApiPostRequest("/api/" + apiVersion + "/notifications/send_notification.php", requestParams);
return mediaFire.doApiRequest(apiPostRequest, classOfT);
}
}
|
package com.test.promanage.service;
import java.util.List;
import org.springframework.stereotype.Service;
import com.test.promanage.po.ProUserJur;
import com.test.promanage.po.TableFile;
import com.test.promanage.po.TableProject;
import com.test.promanage.po.TableProjectCustom;
import com.test.promanage.po.TableRate;
import com.test.promanage.po.TableTask;
import com.test.promanage.po.TableVersion;
import com.test.promanage.po.TableVersionCustom;
import com.test.promanage.po.TaskCustom;
@Service
public interface ProService {
/**
* 查找与自己相关的项目的详细信息
*
* @author guosuzhou
*
* @param uid
* @return
* @throws Exception
*
*date 2017年12月4日 下午7:59:17
*/
List<TableProjectCustom> selectProInfromByUid(String uid)throws Exception;
/**
* 添加项目
*
* @author guosuzhou
*
* @param tableProject
* @return
* @throws Exception
*
*date 2017年12月6日 下午2:35:06
*/
int insertTableProject(TableProject tableProject)throws Exception;
/**
* 添加项目相关数据
*
* @author guosuzhou
*
* @param proUserJur
* @return
* @throws Exception
*
*date 2017年12月6日 下午2:34:41
*/
int insertProUserJur(ProUserJur proUserJur)throws Exception;
/**
* 查询进度
*
* @author guosuzhou
*
* @return
* @throws Exception
*
*date 2017年12月6日 下午2:34:29
*/
List<TableRate> selectRate()throws Exception;
/**
* 获取项目信息tableProject
*
* @author guosuzhou
*
* @param proId
* @return
* @throws Exception
*
*date 2017年12月7日 下午4:59:31
*/
TableProject selectTableProjectByPid(String proId) throws Exception;
/**
* 查找项目普通成员
*
* @author guosuzhou
*
* @param proId
* @return
* @throws Exception
*
*date 2017年12月7日 下午8:50:41
*/
List<ProUserJur> selectProUserJurByPid(String proId)throws Exception;
/**
* 根据项目id和用户id获取相关信息
*
* @author guosuzhou
*
* @param proId
* @param uid
* @return
* @throws Exception
*
*date 2017年12月7日 下午9:38:11
*/
ProUserJur selectProUserJurByPUid(String proId,String uid)throws Exception;
/**
*
* 根据主键更新项目信息
*
* @title ProService.java
* @author guosuzhou
* @param tableProject
* @return
* @throws Exception
*
* @date 2017年12月11日
*/
int updateProjectById(TableProject tableProject)throws Exception;
/**
*
* 删除项目信息
*
* @title ProService.java
* @author guosuzhou
* @param pid
* @return
* @throws Exception
*
* @date 2017年12月11日
*/
int deleteProByPid(String pid)throws Exception;
/**
* 查找项目文件信息最新的消息
*
*
* @title ProService.java
* @author guosuzhou
* @param pid
* @return
* @throws Exception
*
* @date 2017年12月11日
*/
TableVersion selectTableVersionByPid(String pid) throws Exception;
/**
* 查询项目的版本信息
*
*
* @title ProService.java
* @author guosuzhou
* @param pid
* @return
* @throws Exception
*
* @date 2018年1月2日
*/
List<TableVersionCustom> selectVersionByPid(String pid) throws Exception;
/**
* 获取文件的信息
*
*
* @title ProService.java
* @author guosuzhou
* @param id
* @return
* @throws Exception
*
* @date 2018年1月2日
*/
TableFile selectFileById(int id) throws Exception;
/**
* 全文模糊搜索
*
*
* @title ProService.java
* @author guosuzhou
* @param tableProject
* @return
* @throws Exception
*
* @date 2018年1月3日
*/
List<TableProjectCustom> selectProByLike(String str,String uid)throws Exception;
/**
* 从项目中删除用户
*
*
* @title ProService.java
* @author guosuzhou
* @param pid
* @return
* @throws Exception
*
* @date 2018年1月3日
*/
int deleteUserByPidUid(String pid,String uid) throws Exception;
/**
* 获取任务信息
*
*
* @title ProService.java
* @author guosuzhou
* @param pid
* @param uid
* @return
* @throws Exception
*
* @date 2018年1月3日
*/
List<TableTask> selectTaskByPidUid(String pid,String uid) throws Exception;
/**
* 添加任务
*
*
* @title ProService.java
* @author guosuzhou
* @param tableTask
* @return
* @throws Exception
*
* @date 2018年1月3日
*/
int inserTask(TableTask tableTask) throws Exception;
/**
* 获取任务信息
*
*
* @title ProService.java
* @author guosuzhou
* @param pid
* @return
* @throws Exception
*
* @date 2018年1月3日
*/
List<TaskCustom> selectTaskInformByPid(String pid)throws Exception;
}
|
package com.larrywang.app.elmhurst;
import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
enum SignKey {
BORO_CODE,
STATUS_NUMBER,
SEQUENCE_NUMBER,
DISTANCE,
ARROW_DIRECTION,
DISC
}
public class mongoDbDao {
Logger logger = LoggerFactory.getLogger(mongoDbDao.class);
private static MongoClient mongoClient;
private final String MONGO_HOST = "localhost";
private final int MONGO_PORT = 27017;
private final String MONGO_DB = "elmhurst";
private final String MONGO_TABLE = "nyparking_signs";
private final int SIGN_COLUMN_SIZE = 6;
public mongoDbDao() {
if (mongoClient == null) {
mongoClient = new MongoClient(MONGO_HOST, MONGO_PORT);
}
}
public void addSign(Document doc) {
MongoDatabase database = mongoClient.getDatabase(MONGO_DB);
MongoCollection<Document> collection = database.getCollection(MONGO_TABLE);
collection.insertOne(doc);
}
public Document getSignDocFromCsv(String csv) {
String[] tokens = csv.split(",", 6);
if (tokens.length != SIGN_COLUMN_SIZE) {
logger.error("Ignored illigle line {}.", csv);
}
Document doc = new Document();
int i = 0;
for (SignKey each : SignKey.values()) {
try {
String token = tokens[i].trim();
switch (each) {
case DISTANCE:
doc.append(each.name(), Integer.parseInt(token));
break;
case ARROW_DIRECTION:
case BORO_CODE:
doc.append(each.name(), token);
break;
case DISC:
case SEQUENCE_NUMBER:
case STATUS_NUMBER:
doc.append(each.name(), token);
break;
default:
logger.warn("Wrong column {}", each.name());
}
} catch (Exception e) {
logger.error("Exception thown when parsing the line", e);
continue;
}
i++;
}
return doc;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
MongoDatabase database = mongoClient.getDatabase("mydb");
MongoCollection<Document> collection = database.getCollection("test");
Document doc = new Document("name", "MongoDB")
.append("type", "database")
.append("count", 1)
.append("info", new Document("x", 203).append("y", 102));
collection.insertOne(doc);
Document myDoc = collection.find().first();
System.out.println(myDoc);
}
}
|
package program;
import java.text.ParseException;
import java.util.List;
import java.util.Locale;
import db.DB;
import model.dao.DAOFactory;
import model.dao.SellerDAO;
import model.entities.Department;
import model.entities.Seller;
public class SellerDAOTest {
public static void main(String[] args) throws ParseException {
Locale.setDefault(Locale.US);
SellerDAO sellerDAO = DAOFactory.createSellerDAO();
/*Test 1: Find By Id*/
Seller seller = sellerDAO.findById(2);
System.out.println(seller);
/*Test 2: Find By Department*/
List<Seller> sellers = sellerDAO.findByDepartment(new Department(2, null));
sellers.forEach(System.out::println);
/*Test 3: Find All*/
List<Seller> allSellers = sellerDAO.findAll();
allSellers.forEach(System.out::println);
/*Test 4: Insert*/
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("dd/MM/yyyy");
seller = new Seller(null, "Cassio Costa", "cassio298@hotmail.com", sdf.parse("27/07/1996"), 1500.0, new Department(2, null));
sellerDAO.insert(seller);
System.out.println(seller);
/*Test 5: Delete*/
sellerDAO.deleteById(6);
/*Test 6: Update*/
seller = new Seller(8, "Cassio Costa", "cassio298@hotmail.com", sdf.parse("27/07/1996"), 2500.0, new Department(2, null));
sellerDAO.update(seller);
DB.closeConnection();
}
}
|
package StepDef;
import org.openqa.selenium.WebDriver;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.GherkinKeyword;
import com.aventstack.extentreports.gherkin.model.Scenario;
import Listeners.ExtentReportListeners;
import PageObject.CalculatorPage;
import Utility.Helper;
import cucumber.api.java.en.When;
public class TC2_Steps extends ExtentReportListeners{
private CalculatorPage CalculatorPage;
@When("^I enter start data in module (\\d+)$")
public void i_enter_start_data_in_module(int arg1) throws Throwable {
ExtentTest logInfo = null;
try {
logInfo = test.createNode(new GherkinKeyword("When"), "I enter start date");
System.out.println("Start date entered");
CalculatorPage = new CalculatorPage(Helper.driver);
CalculatorPage.input_StartYear_AddYear();
logInfo.pass("Start Date entered");
logInfo.addScreenCaptureFromPath(captureScreenShot(Helper.driver));
}
catch(AssertionError | Exception e) {
testStepHandle("FAIL", Helper.driver, logInfo, e);
}
}
@When("^I enter value \"([^\"]*)\" to get added in years$")
public void i_enter_value_to_get_added_in_years(String value) throws Throwable {
ExtentTest logInfo = null;
try {
logInfo = test.createNode(new GherkinKeyword("When"), "I enter start date");
System.out.println("years added");
CalculatorPage.input_YearsToBeAdded(value);
logInfo.pass("Added yeats");
logInfo.addScreenCaptureFromPath(captureScreenShot(Helper.driver));
}
catch(AssertionError | Exception e) {
testStepHandle("FAIL", Helper.driver, logInfo, e);
}
}
@When("^Click calculate button to \"([^\"]*)\"$")
public void click_calculate_button_to(String arg1) throws Throwable {
ExtentTest logInfo = null;
try {
logInfo = test.createNode(new GherkinKeyword("When"), "I enter start date");
System.out.println("Clicked calculate button to "+arg1);
CalculatorPage.click_Calc2_CalculateButton();
logInfo.pass("Calculate button clicked");
logInfo.addScreenCaptureFromPath(captureScreenShot(Helper.driver));
}
catch(AssertionError | Exception e) {
testStepHandle("FAIL", Helper.driver, logInfo, e);
}
}
}
|
package com.hcg.web;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan(basePackages = {"com.hcg.commondal","com.hcg.commonservice","com.hcg.web"})
@MapperScan("com.hcg.commondal.mapper")
public class WebApplication {
public static void main(String[] args) {
System.out.println("启动成功!");
SpringApplication.run(WebApplication.class, args);
}
}
|
package com.example.game_set_match;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.google.firebase.firestore.FirebaseFirestore;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private Button signin;
private Button signup;
FirebaseFirestore db = FirebaseFirestore.getInstance();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initialize();
setContentView(R.layout.signinfrontend);
signin =(Button) findViewById(R.id.sign_in);
signin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openactivity_sign_in();
}
});
signup=(Button) findViewById(R.id.sign_up);
signup.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openactivity_sign_up();
}
});
setContentView(R.layout.signinfrontend);
}
public void initialize(){
//new Game_type("Chess", db);
//new Game_type("Ping Pong",db);
}
public void openactivity_sign_up() {
Intent intent = new Intent(this,SignUpActivity.class);
startActivity(intent);}
public void openactivity_sign_in() {
Intent intent = new Intent(this,sign_in.class);
startActivity(intent);}
}
/*
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if false;
}
}
}*/
|
package com.threadpool.countdown;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.CountDownLatch;
@Slf4j
public class Worker implements Runnable{
private final CountDownLatch startSignal;
private final CountDownLatch doneSignal;
Worker(CountDownLatch startSignal,CountDownLatch doneSignal){
this.startSignal = startSignal;
this.doneSignal = doneSignal;
}
@Override
public void run(){
try {
startSignal.await();
doWork();
doneSignal.countDown();;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void doWork() {
log.info("current thread:{},work ...",Thread.currentThread().getName());
}
}
|
package com.example.gamedb.db.entity;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
@Entity
public class Game {
@PrimaryKey
private Integer id;
private String backgroundImage;
private String posterImage;
private String name;
private Long firstReleaseDate;
private Double totalRating;
private String summary;
private String storyline;
private Long expiryDate;
public Game(Integer id, String backgroundImage, String posterImage, String name,
Long firstReleaseDate, Double totalRating, String summary, String storyline,
Long expiryDate) {
this.id = id;
this.backgroundImage = backgroundImage;
this.posterImage = posterImage;
this.name = name;
this.firstReleaseDate = firstReleaseDate;
this.totalRating = totalRating;
this.summary = summary;
this.storyline = storyline;
this.expiryDate = expiryDate;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getBackgroundImage() {
return backgroundImage;
}
public void setBackgroundImage(String backgroundImage) {
this.backgroundImage = backgroundImage;
}
public String getPosterImage() {
return posterImage;
}
public void setPosterImage(String posterImage) {
this.posterImage = posterImage;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getFirstReleaseDate() {
return firstReleaseDate;
}
public void setFirstReleaseDate(Long firstReleaseDate) {
this.firstReleaseDate = firstReleaseDate;
}
public Double getTotalRating() {
return totalRating;
}
public void setTotalRating(Double totalRating) {
this.totalRating = totalRating;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getStoryline() {
return storyline;
}
public void setStoryline(String storyline) {
this.storyline = storyline;
}
public Long getExpiryDate() {
return expiryDate;
}
public void setExpiryDate(Long expiryDate) {
this.expiryDate = expiryDate;
}
}
|
import org.sql2o.*;
import java.util.ArrayList;
import java.util.List;
public class EndangeredAnimal extends Animal {
public String health;
public String age;
public static final String HEALTH_1 = "healthy";
public static final String HEALTH_2 = "okay";
public static final String HEALTH_3 = "ill";
public static final String AGE_1 = "newborn";
public static final String AGE_2 = "young";
public static final String AGE_3 = "adult";
public EndangeredAnimal(String name, String health, String age){
super(name);
this.health = health;
this.age = age;
}
public String getHealth(){
return health;
}
public String getAge(){
return age;
}
public static EndangeredAnimal find(int id){
try(Connection con = DB.sql2o.open()){
String sql = "SELECT * FROM animals where id=:id";
EndangeredAnimal animal = con.createQuery(sql).addParameter("id", id).throwOnMappingFailure(false).executeAndFetchFirst(EndangeredAnimal.class);
return animal;
}
}
@Override
public void save(){
try(Connection con = DB.sql2o.open()){
String sql = "INSERT INTO animals (name, health, age) VALUES (:name, :health, :age)";
this.id = (int) con.createQuery(sql, true).addParameter("name", this.name).addParameter("health", this.health
).addParameter("age", this.age).throwOnMappingFailure(false).executeUpdate().getKey();
}
}
}
|
package com.mqld.controller;
import java.util.Map;
import java.util.TreeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.mqld.annotation.FireAuthority;
import com.mqld.enums.AuthorityType;
import com.mqld.enums.ResultType;
import com.mqld.model.Page;
import com.mqld.model.QueueItem;
import com.mqld.model.TeachersPerfQueryConditionDTO;
import com.mqld.model.User;
import com.mqld.service.QueueService;
import com.mqld.util.JsonUtil;
@Controller
public class PerformanceController {
@Autowired
QueueService queueService;
@FireAuthority(authorityTypes=AuthorityType.TEACHER)
@RequestMapping("/performance")
public String performance(HttpServletRequest request){
return "performance";
}
@FireAuthority(authorityTypes=AuthorityType.ADMIN)
@RequestMapping("/adminSidePerformance")
public String adminSidePerformance(HttpServletRequest request){
return "admin_side_performance";
}
@FireAuthority(authorityTypes=AuthorityType.TEACHER, resultType=ResultType.json)
@RequestMapping("/getTeacherPerf")
public void getTeacherPerf(HttpServletRequest request,HttpServletResponse response,HttpSession session,@RequestParam("currentPage")String currentPage,@RequestParam("pageSize")String pageSize){
int currentPageNum =Integer.parseInt(currentPage);
int pageSizeNum=Integer.parseInt(pageSize);
Page<QueueItem> page=new Page<QueueItem>(currentPageNum, pageSizeNum);
User user =(User) session.getAttribute("user");
page=queueService.getTeacherPerf(user.getID(),page);
if (null==page) {
JsonUtil.flushError(response, "服务器出错");
}else {
Map<String, Object> data=new TreeMap<String, Object>();
data.put("page", page);
JsonUtil.flushData(response, data);
}
}
@FireAuthority(authorityTypes=AuthorityType.ADMIN, resultType=ResultType.json)
@RequestMapping(value="/getTeachersPerf" ,method=RequestMethod.POST,consumes = "application/json")
public void getTeachersPerf(HttpServletRequest request,HttpServletResponse response,@RequestParam("currentPage")String currentPage,@RequestParam("pageSize")String pageSize,@RequestBody TeachersPerfQueryConditionDTO condition){
int currentPageNum =Integer.parseInt(currentPage);
int pageSizeNum=Integer.parseInt(pageSize);
Page<QueueItem> page=new Page<QueueItem>(currentPageNum, pageSizeNum);
page=queueService.getTeachersPerf(condition,page);
if (null==page) {
JsonUtil.flushError(response, "服务器出错");
}else {
Map<String, Object> data=new TreeMap<String, Object>();
data.put("page", page);
JsonUtil.flushData(response, data);
}
}
}
|
package liu.lang.Class;
class Test{}
public class About_getComponentType {
public static void main(String[] args) {
//该类为数组类型时,可通过getComponentType()方法获取其组件类型。
System.out.println(int[].class.getComponentType());
System.out.println(int[][].class.getComponentType());
System.out.println(Test[].class.getComponentType().getName());
System.out.println(Test[].class.getComponentType().getSimpleName());
}
}
|
package com.dhankher.slider;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
/**
* Created by Dhankher on 2/9/2017.
*/
public class PermissionManager {
private Context context;
private static final int MY_PERMISSIONS_REQUEST_READ_CONTACTS = 0;
public static void checkForOverlayPermission(Activity activity) {
if (android.os.Build.VERSION.SDK_INT >= 23) { //Android M Or Over
if (!Settings.canDrawOverlays(activity)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + activity.getPackageName()));
activity.startActivityForResult(intent, 1);
}
}
}
public static void checkForNotificationListeningPermission(Activity activity) {
Intent intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
activity.startActivity(intent);
}
public static void checkForReadContactsPermission(Activity activity){
if (ContextCompat.checkSelfPermission(activity,
Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity,
new String[]{Manifest.permission.READ_CONTACTS},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
}
}
public static void checkForAccesLocationPermission(Activity activity){
if (ContextCompat.checkSelfPermission(activity,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(activity,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
}
}
public static void checkForReadSMSPermission(Activity activity){
if (ContextCompat.checkSelfPermission(activity,
Manifest.permission.READ_SMS)
!= PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(activity,
new String[]{Manifest.permission.READ_SMS},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
}
}
public static void checkForReadCallLogsPermission(Activity activity){
if (ContextCompat.checkSelfPermission(activity,
Manifest.permission.READ_CALL_LOG)
!= PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(activity,
new String[]{Manifest.permission.READ_CALL_LOG},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
}
}
public static boolean hasPermissions(Activity activity, String... permissions) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && activity != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.pmm.sdgc.model;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Objects;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
*
* @author ajuliano
*/
@Entity
@Table(name = "variaveisCodValid")
public class VariaveisCodigoValidade implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private String id;
@Column(name = "codVald")
private String codValidade;
@Column(name = "dataHora")
private LocalDateTime dataHora;
@Column(name = "ativo")
private Boolean ativo;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCodValidade() {
return codValidade;
}
public void setCodValidade(String codValidade) {
this.codValidade = codValidade;
}
public LocalDateTime getDataHora() {
return dataHora;
}
public void setDataHora(LocalDateTime dataHora) {
this.dataHora = dataHora;
}
public Boolean getAtivo() {
return ativo;
}
public void setAtivo(Boolean ativo) {
this.ativo = ativo;
}
@Override
public int hashCode() {
int hash = 3;
hash = 37 * hash + Objects.hashCode(this.id);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final VariaveisCodigoValidade other = (VariaveisCodigoValidade) obj;
if (!Objects.equals(this.id, other.id)) {
return false;
}
return true;
}
}
|
package com.swapping.springcloud.ms.member.feign.integral.client;
import com.swapping.springcloud.ms.core.response.UniVerResponse;
import com.swapping.springcloud.ms.member.feign.integral.bean.Integral;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* feignClient 接口
*
* 1.注意:feign接口上 尽量不要使用@RequestMapping()注解
* 因为若请求中含有Accept header,会出现404
*
* 2.@FeignClient(name = "springcloud-ms-integral")
* 其中的name代表这个feignClient指向的服务名称,
* 也就是ms-integral服务中的application.prperties中定义的【spring.application.name=springcloud-ms-integral】
*
* 3.如果被调用方,也就是服务提供者在服务注册中心有多个实例,则调用方的多次请求会自动轮询到每个服务提供方来处理,
* 这就是注册中心的负载均衡的功能
*/
@FeignClient(name = "springcloud-ms-integral",fallback = FeignMsIntegralClientHystric.class)
public interface FeignMsIntegralClient {
/**
* 为会员添加原始积分记录
* jpa分布式事务
*
*
* 1.【注意】
* 接口的地址需要完整对应到 被调用方接口的完整地址
* 因为feignClient上不推荐直接使用@RequestMapping,
* 所以将@RequestMapping("/integral")和@RequestMapping("/save")合并到具体接口上的@RequestMapping("/integral/save")
*
* 2.接口的方法名要和被调用接口的方法名一致!!
* @param entity
* @return
*/
@RequestMapping(value = "/integral/save", method = RequestMethod.POST)
public UniVerResponse<Integral> save(@RequestBody Integral entity);
/**
* 为会员添加原始积分记录
*
* 测试mybatis分布式事务
*
* 由于已经有了统一的异常拦截处理
* 故而 本方法不用在熔断器中设定熔断方法
*
* 但是熔断器类必须存在,因为启动需要查找熔断器类,否则报错
* @param integral
* @return
*/
@RequestMapping(value = "/integral/saveByMybatis", method = RequestMethod.POST)
public UniVerResponse<Integer> saveByMybatis(@RequestBody Integral integral);
}
|
import content.Crawler;
import content.HerderArticle;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<DisplayPage> displayPages = new ArrayList<>();
Crawler crawler = new Crawler();
HerderArticle localArticle;
for (int i = 0; i < 6; i++) {
localArticle = crawler.getContent().get(i);
displayPages.add(new DisplayPage("Herder News", localArticle.getTitle(), localArticle.getDescription(), localArticle.getLink(), i+1, 6));
}
displayPages.forEach(System.out::println);
}
}
|
//заполняем симметричную матрицу от 0 до n
package Array;
import java.util.Scanner;
public class array_23 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int arr[][] = new int [n][n];
for(int i = 0; i < n; i++){
for(int j = i + 1; j < n; j++){
arr[i][j] = j - i;
arr[j][i] = j - i;
}
}
for(int b = 0; b < n; b++){
for(int k = 0; k < n; k++){
System.out.print(arr[k][b] + " ");
}
System.out.println();
}
}
}
|
package TestNGRun;
import Dirvers.DriverSet;
import Smoke.OverallUrlCheckUp;
import org.testng.annotations.Test;
import java.io.IOException;
public class OverallUrlCheckUpTest extends DriverSet {
OverallUrlCheckUp overallUrlCheckUp;
@Test
public void runOverallUrlCheckUpTest() throws IOException {
overallUrlCheckUp = new OverallUrlCheckUp(wDriver);
overallUrlCheckUp.linkCheck();
}
}
|
import java.util.Map;
import model.Instance;
import textFile.CreateSolutionTextFile;
import textFile.InstanceTextFileReader;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Team Foufou
*/
public class TestCreateSolutionTextFile {
/**
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
Map<Integer, String> files = InstanceTextFileReader.getNameFile();
//List<Instance> instances = new ArrayList<>();
for (Map.Entry file : files.entrySet()) {
Instance instance = InstanceTextFileReader.readInstance((String) file.getValue());
CreateSolutionTextFile.writeFile((String) file.getValue(), instance);
if(instance == null){
throw new Exception("Instance is null");
}
//instances.add(instance);
}
}
}
|
package com.driva.drivaapi.exception;
public class StudentAlreadyExistException extends RuntimeException {
public StudentAlreadyExistException(String message) {
super(message);
}
}
|
package com.evan.demo.yizhu.shouye;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.evan.demo.yizhu.R;
public class maoyan_jiudianrenyuan extends Fragment {
private View rootView;
@Override
public void onAttach(Context context) {
super.onAttach(context);
}
@Override
public View onCreateView(@Nullable LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_maoyan_jiudianrenyuan, container, false);
initUi();
return rootView;
}
private void initUi() {
//这里写加载布局的代码
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//这里写逻辑代码
}
}
|
package cn.itheima.methodPractice;
import java.util.Random;
public class ArrayGetAvg {
/*
(1) 定义方法public static int getAvg(int[] arr),获取数组中的平均数并返回;
(2) 在main方法内,定义长度为10的int数组,使用随机数赋值,并调用getAvg方法获取平均分。然后遍历数组,统计高于平均分的分数有多少个。
打印结果:高于平均分:80 的个数有 5 个。
*/
public static void main(String[] args) {
Random rd = new Random();
int[] arr = new int[10];
for (int i = 0; i < arr.length; i++) {
arr[i] = rd.nextInt(100);
}
int avg = getAvg(arr);
int count = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] > avg) {
count++;
}
}
System.out.printf("高于平均分%d的个数有%d个",avg, count);
}
private static int getAvg(int[] arr) {
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum / arr.length;
}
}
|
package com.acewill.ordermachine.fragmentdialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;
import com.acewill.ordermachine.R;
import com.acewill.ordermachine.dialog.BaseDialog;
import com.acewill.ordermachine.eventbus.OnEditTextFinishEvent;
import com.acewill.ordermachine.util_new.ToastUtils;
import com.acewill.ordermachine.widget.CommonEditText;
import com.acewill.ordermachine.widget.WindowUtil;
import org.greenrobot.eventbus.EventBus;
/**
* Author:Anch
* Date:2017/11/21 11:37
* Desc:
*/
public class PayInputDialog extends BaseDialog implements View.OnClickListener {
/**
* @param type 支付成功或失败
* @return
*/
public static PayInputDialog newInstance(int type) {
PayInputDialog fragment = new PayInputDialog();
Bundle bundle = new Bundle();
bundle.putInt("type", type);
fragment.setArguments(bundle);
return fragment;
}
private CommonEditText mEditText;
private int type;
@Override
public View getView() {
Dialog dialog = getDialog();
View view = View.inflate(mcontext, R.layout.fragment_payinput_dialog, null);
if (dialog != null) {
getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
//若无该段代码则用系统的样式而不是自己定义的背景样式
getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
}
type = getArguments().getInt("type");
mEditText = (CommonEditText) view
.findViewById(R.id.ligangsuoding_pwd_e2t);
view.findViewById(R.id.close_img).setOnClickListener(this);
TextView tv = (TextView) view.findViewById(R.id.dialog_title);
switch (type) {
case 3://会员
tv.setText(mcontext.getResources().getString(R.string.huiyuanzhifu));
mEditText.setHint(mcontext.getResources().getString(R.string.qingsaohuiyuan));
break;
case 102://移动支付
break;
}
mEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
//当actionId == XX_SEND 或者 XX_DONE时都触发
//或者event.getKeyCode == ENTER 且 event.getAction == ACTION_DOWN时也触发
//注意,这是一定要判断event != null。因为在某些输入法上会返回null。
if (actionId == EditorInfo.IME_ACTION_SEND
|| actionId == EditorInfo.IME_ACTION_DONE
|| (event != null && KeyEvent.KEYCODE_ENTER == event
.getKeyCode() && KeyEvent.ACTION_DOWN == event.getAction())) {
//处理事件
String code = mEditText.getText().toString().trim();
if (TextUtils.isEmpty(code)) {
ToastUtils.showToast(mcontext, "支付码不能为空!");
return false;
}
EventBus.getDefault()
.post(new OnEditTextFinishEvent(type, code));
}
return false;
}
});
view.findViewById(R.id.dialog_btn).setOnClickListener(this);
WindowUtil.hiddenKey();
WindowUtil.hiddenSysKey(mEditText);
WindowUtil.showKey(mcontext, mEditText);
return view;
}
@Override
public float getSize() {
return 0.5f;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.close_img:
dismiss();
break;
case R.id.dialog_btn:
String code = mEditText.getText().toString().trim();
if (TextUtils.isEmpty(code)) {
ToastUtils.showToast(mcontext, "支付码不能为空!");
return;
}
EventBus.getDefault()
.post(new OnEditTextFinishEvent(type, code));
break;
}
}
@Override
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
if (mOnDialogDismissListener != null)
mOnDialogDismissListener.onDialogDismiss();
}
public interface OnDialogDismissListener {
void onDialogDismiss();
}
public OnDialogDismissListener mOnDialogDismissListener;
public void setOnDialogDismiss(OnDialogDismissListener listener) {
mOnDialogDismissListener = listener;
}
}
|
package com.andy.myapplication.Test_Broadcast;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.andy.myapplication.Collector.BaseActivity;
import com.andy.myapplication.R;
public class Activity_Broadcast4_LoginActivity extends BaseActivity {
private EditText accountEdit, passwoedEdit;
private Button login;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_broadcast4_loginactivity);
accountEdit = findViewById(R.id.account);
passwoedEdit = findViewById(R.id.password);
login = findViewById(R.id.login);
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String account = accountEdit.getText().toString();
String password = passwoedEdit.getText().toString();
if (account.equals("admin") && password.equals("123456")) {
Intent intent = new Intent(Activity_Broadcast4_LoginActivity.this, Activity_Broadcast4_MainActivity.class);
startActivity(intent);
finish();
} else {
Toast.makeText(Activity_Broadcast4_LoginActivity.this, "account or password is invalid", Toast.LENGTH_SHORT).show();
}
}
});
}
}
|
package com.anyuaning.osp.utils;
/**
* Created by thom on 14-4-26.
*/
public class ConvertUtils {
private ConvertUtils() {};
}
|
package com.atguigu.lgl;
//继承Thread类
class TestLuo3 extends Thread{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName()+ "--" + i);
}
}
}
public class MakeThread1_2 {
public static void main(String[] args) {
//主线程
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName()+ "==" + i);
}
//普通创建
new TestLuo3().start();
//匿名对象
new Thread(){
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName()+ "++" + i);
}
};
}.start();
}
}
|
/**
* Nate West
* CSMC 256 - Project 4
* Priority Request Processing
* Purpose: This class models a Clerk who handles process Requests
* Description: This class handles all the processing and moving of
* requests. If an active Request's priority is lower than
* an incoming Request's, the active Request is pushed onto the
* pendingRequest Stack and waits, while the incoming Request begins processing.
* Input: A text file with Requests
* Output: Times requests finish processing
*/
import java.util.PriorityQueue;
import java.util.Stack;
public class Clerk {
private int time;
private Stack<Request> pendingRequests = new Stack<Request>();
// default constructor
public Clerk() {
incrementTime();
}
// parameterized constructor
public Clerk(Request request) {
Clerk clerk = new Clerk();
clerk.processRequest(request);
}
// actually processes the request, using a counter to count up to it's processingTime
public void processRequest(Request current) {
int counter = 0;
System.out.println(time + ": Request #" + current.getID() + " begins processing");
while (counter != current.getPT()) {
counter++;
}
System.out.println(time + ": Request #" + current.getID() + " finishes processing");
}
/*
* adds the requests to the queue, while comparing it
* to the top of the stack for processing
*/
public void addRequest(Request current, PriorityQueue<Request> queue) {
Clerk clerk = new Clerk();
System.out.println(time + ": Request #" + current.getID() + " (time needed: " + current.getPT() + ")"
+ " arrives with a priority of " + current.getPriority());
queue.add(current);
if (pendingRequests.empty()) {
clerk.processRequest(current);
} else {
Request temp = pendingRequests.peek();
if (temp.getPriority() < current.getPriority()) {
clerk.processRequest(pendingRequests.pop());
pendingRequests.push(current);
}
}
}
// gets the next requests to be processed
public void getNextRequest(Stack<Request> pendingRequests, PriorityQueue<Request> queue) {
Request next = queue.peek();
Request temp = pendingRequests.peek();
if (next.getPriority() < temp.getPriority()) {
processRequest(queue.poll());
} else
processRequest(pendingRequests.pop());
}
// increments time when called
public void incrementTime() {
time++;
}
// returns time
public int getTime() {
return time;
}
}
|
package gil.server.http;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertEquals;
public class ResponseTest {
@Test
public void shouldAllowSettingHTTPProtocol() {
Response response = new Response();
response.setProtocol(HTTPProtocol.PROTOCOL);
assertEquals(HTTPProtocol.PROTOCOL, response.getProtocol());
}
@Test
public void shouldAllowSettingHTTPStatusCode() {
Response response = new Response();
response.setStatusCode(HTTPProtocol.STATUS_CODE_200);
assertEquals(HTTPProtocol.STATUS_CODE_200, response.getStatusCode());
}
@Test
public void shouldAllowSettingReasonPhrase() {
Response response = new Response();
response.setReasonPhrase(HTTPProtocol.REASON_PHRASE_OK);
assertEquals(HTTPProtocol.REASON_PHRASE_OK, response.getReasonPhrase());
}
@Test
public void shouldHaveAStartLine() {
Response response = new Response();
String startLine = "HTTP/1.1 200 OK";
response.setProtocol(HTTPProtocol.PROTOCOL);
response.setStatusCode(HTTPProtocol.STATUS_CODE_200);
response.setReasonPhrase(HTTPProtocol.REASON_PHRASE_OK);
assertEquals(startLine, response.getStartLine());
}
@Test
public void shouldAllowSettingBody() {
Response response = new Response();
String body = "Some amazing content...";
response.setBody(body.getBytes());
assertEquals(body, new String(response.getBody()));
}
@Test
public void shouldHaveADateHeader() {
Response response = new Response();
String headers = response.getHeaders();
assertTrue(headers.contains("Date"));
}
@Test
public void shouldAllowSettingABody() {
Response response = new Response();
String body = "<!DOCTYPE html><html lang=\"en-us\"><head></head><body><h1>Hello, world!</h1></body></html>";
response.setBody(body.getBytes());
assertEquals(body, new String(response.getBody()));
}
@Test
public void shouldHaveAContentLengthWhenGivenABody() {
Response response = new Response();
String body = "<!DOCTYPE html><html lang=\"en-us\"><head></head><body><h1>Hello, world!</h1></body></html>";
response.setBody(body.getBytes());
String headers = response.getHeaders();
assertTrue(headers.contains("Content-Length:"));
}
@Test
public void shouldSetAHeaderField() {
Response response = new Response();
response.setProtocol(HTTPProtocol.PROTOCOL);
response.setStatusCode(HTTPProtocol.STATUS_CODE_200);
response.setReasonPhrase(HTTPProtocol.REASON_PHRASE_OK);
String allowHeaderValue = "OPTIONS, GET";
response.addHeader(HTTPProtocol.ALLOW, allowHeaderValue);
assertTrue(response.getHeaders().contains(allowHeaderValue));
}
@Test
public void shouldSetTwoHeaderFields() {
Response response = new Response();
String allowHeaderValue = "OPTIONS, GET";
String contentTypeHeaderValue = "\"text/html; charset=UTF-8\"";
response.addHeader(HTTPProtocol.ALLOW, allowHeaderValue);
response.addHeader(HTTPProtocol.CONTENT_TYPE, contentTypeHeaderValue);
assertTrue(response.getHeaders().contains(allowHeaderValue));
assertTrue(response.getHeaders().contains(contentTypeHeaderValue));
}
@Test
public void shouldSetLocationHeaderField() {
Response response = new Response();
String expectedLocationHeader = "Location: /api/people/1";
response.addHeader(HTTPProtocol.LOCATION, expectedLocationHeader);
assertTrue(response.getHeaders().contains(expectedLocationHeader));
}
@Test
public void shouldSetAReasonPhraseProgrammatically() {
Response response = new Response();
response.setProtocol(HTTPProtocol.PROTOCOL);
response.setStatusCode(HTTPProtocol.STATUS_CODE_200);
assertEquals(HTTPProtocol.REASON_PHRASE_OK, response.getReasonPhrase());
}
@Test
public void shouldReturnABytesArrayRepresentationOfTheResponse() {
Response response = new Response();
StringBuilder expectedResponse = new StringBuilder();
response.setProtocol(HTTPProtocol.PROTOCOL);
response.setStatusCode(HTTPProtocol.STATUS_CODE_200);
response.setReasonPhrase(HTTPProtocol.REASON_PHRASE_OK);
response.setBody("".getBytes());
expectedResponse.append(response.getStartLine() + HTTPProtocol.CRLF +
response.getHeaders() +
HTTPProtocol.CRLF +
new String(response.getBody()));
assertEquals(expectedResponse.toString(), new String(response.toByteArray()));
}
}
|
package com.mobdeve.s11.g32.tindergree.Activities;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.WindowManager;
import com.mobdeve.s11.g32.tindergree.R;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// TODO (1) Update this to activity_main once the activity for activity_login has been created
setContentView(R.layout.activity_post_register_upload_photos);
hideBar();
}
private void hideBar(){
ActionBar actionBar = getSupportActionBar();
actionBar.hide();
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
} |
package View;
import java.awt.GridLayout;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.Arrays;
import javax.swing.table.DefaultTableCellRenderer;
import Controller.*;
import Model.*;
public class Scherm extends JFrame implements ActionListener {
private JButton jbStart;
private JButton jbStop;
private JLabel jlSimulatie;
private JLabel jlResultaat;
private JLabel jlAlgoritme;
private JLabel jlOrdernr;
private JComboBox jcAlgoritme;
private JTable tResultaat;
private JLabel jlNummer;
private TravellingSalesmanProblem tsp;
private Dimension size;
private int count = 0;
private Timer t;
private ArrayList<String> Algoritmes;
private ArrayList<String> Afstanden;
private ArrayList<String> ALTijd;
private Tekenpanel tSimulator;
private Magazijn magazijn;
private Order order;
private String algoritme;
private ArrayList<Artikel> lijst;
private ArrayList<Vak> vakLijst;
private boolean drawing;
private int drawingCount;
public Scherm(Magazijn magazijn, Order order, TravellingSalesmanProblem tsp) {
this.algoritme = null;
this.tsp = tsp;
this.magazijn = magazijn;
this.order = order;
this.setTitle("TSP");
this.setSize(800, 600);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
drawing = false;
drawingCount = 0;
// initialiseren arraylisten
vakLijst = new ArrayList<>();
lijst = new ArrayList<>();
Algoritmes = new ArrayList<>();
Afstanden = new ArrayList<>();
ALTijd = new ArrayList<>();
//initialiseren jframe
jbStart = new JButton("Start simulatie");
jbStop = new JButton("Stop simulatie");
jlSimulatie = new JLabel("Simulatie");
jlResultaat = new JLabel("Resultaat");
jlAlgoritme = new JLabel("Algoritme");
jlOrdernr = new JLabel("Order nummer");
jcAlgoritme = new JComboBox();
jlNummer = new JLabel(String.valueOf(order.getOrderNummer()));
// wat custom fonds
Font header = new Font("Arial", Font.BOLD, 25);
Font defaultFont = new Font("Arial", Font.PLAIN, 14);
//dit zijn de gegevens voor de tabel om mee te beginnen
Algoritmes.add("Volledige enumeratie");
Algoritmes.add("Simpel gretig algoritme");
Algoritmes.add("Volgorde van order");
Afstanden.add("-");
Afstanden.add("-");
Afstanden.add("-");
Insets insets = this.getInsets();
// hie rmaken we de tabel aan
ArrayList<String> wachtrijHeading = new ArrayList<String>(Arrays.asList("Algoritme", "Afstand"));
tResultaat = new JTable(new PakketTableModel(Algoritmes, Afstanden, wachtrijHeading));
getContentPane().add(new JScrollPane(tResultaat), BorderLayout.CENTER);
tResultaat.setPreferredSize(new Dimension(275, 422));
tResultaat.setFont(defaultFont);
tResultaat.setRowHeight(20);
//wat gegevens om de tabel beter eruit te laten zien
DefaultTableCellRenderer wachtrijRenderer = new DefaultTableCellRenderer();
wachtrijRenderer.setHorizontalAlignment(SwingConstants.CENTER);
tResultaat.getColumnModel().getColumn(0).setCellRenderer(wachtrijRenderer);
tResultaat.getTableHeader().setReorderingAllowed(false);
tResultaat.getTableHeader().setFont(defaultFont);
tResultaat.getColumnModel().getColumn(0).setPreferredWidth(100);
tResultaat.getColumnModel().getColumn(1).setPreferredWidth(15);
//een panel om de tabel in te zetten, de tabel kan niet in een absolute layout
JPanel j = new JPanel(new BorderLayout());
j.add(tResultaat.getTableHeader(), BorderLayout.PAGE_START);
j.add(tResultaat, BorderLayout.CENTER);
j.setBorder(BorderFactory.createLineBorder(Color.black));
j.add(new JScrollPane(tResultaat));
j.setPreferredSize(new Dimension(380, 150));
add(j);
size = j.getPreferredSize();
j.setBounds(insets.left + 30, insets.top + 400, size.width, size.height);
// de tekenpanel
tSimulator = new Tekenpanel(this.order, this.algoritme);
JPanel drawPanel = new JPanel();
drawPanel.setBounds(insets.left + 450, insets.top + 100, 400, 400);
drawPanel.add(tSimulator);
//toevoegen van de knoppen en schermen aan het JFrame
add(drawPanel);
add(jbStart);
add(jbStop);
add(jlSimulatie);
add(jlResultaat);
add(jlAlgoritme);
add(jlOrdernr);
add(jlNummer);
jlSimulatie.setFont(header);
jlResultaat.setFont(header);
jlAlgoritme.setFont(defaultFont);
jlOrdernr.setFont(defaultFont);
jlNummer.setFont(defaultFont);
//het bepalen van de locaties van alles
size = jbStart.getPreferredSize();
jbStart.setBounds(insets.left + 30, insets.top + 300, size.width, size.height);
size = jbStop.getPreferredSize();
jbStop.setBounds(insets.left + 180, insets.top + 300, size.width, size.height);
size = jlSimulatie.getPreferredSize();
jlSimulatie.setBounds(insets.left + 450, insets.top + 45, size.width, size.height);
size = jlResultaat.getPreferredSize();
jlResultaat.setBounds(insets.left + 30, insets.top + 350, size.width, size.height);
size = jlAlgoritme.getPreferredSize();
jlAlgoritme.setBounds(insets.left + 30, insets.top + 50, size.width, size.height);
size = jlOrdernr.getPreferredSize();
jlOrdernr.setBounds(insets.left + 30, insets.top + 220, size.width, size.height);
size = jlNummer.getPreferredSize();
jlNummer.setBounds(insets.left + 180, insets.top + 220, size.width, size.height);
// keuzes aan de combobox toevoegen
jcAlgoritme.addItem("Kies algoritme");
jcAlgoritme.addItem("Volledige enumeratie");
jcAlgoritme.addItem("Simpel gretig algoritme");
jcAlgoritme.addItem("Volgorde van order");
// panel voor de combobox, netzoals de tabel kan de combobox niet in absolute layout
JPanel a = new JPanel(new FlowLayout());
a.add(jcAlgoritme);
a.setBorder(BorderFactory.createLineBorder(Color.black));
JPanel fieldPanel = new JPanel(new GridLayout(1, 1)); // 2 rows 1 column
add(fieldPanel, BorderLayout.CENTER);
fieldPanel.add(jcAlgoritme);
fieldPanel.setPreferredSize(new Dimension(180, 20));
size = fieldPanel.getPreferredSize();
fieldPanel.setBounds(insets.left + 180, insets.top + 50, size.width, size.height);
add(a);
// toevoegen van actionlisteners
this.jbStart.addActionListener(this);
this.jbStop.addActionListener(this);
this.jcAlgoritme.addActionListener(this);
revalidate();
pack();
this.setVisible(true);
// de timer
t = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// hier kijkt hij of er een algoritme is gekozen, als dat zo is gaat hij de route tekenen afhankelijk van het gekozen
// algoritme
if (algoritme != null) {
tSimulator = new Tekenpanel(order, algoritme);
drawPanel.remove(0);
drawPanel.add(tSimulator);
if (algoritme == "Volledige enumeratie") {
if (lijst.isEmpty()) {
order.emptyAlgoritmeLijst();
vakLijst = tsp.artikelToVak(order.getProductLijst());
TravellingSalesmanProblem.permute(vakLijst, 0);
lijst = tsp.vakToArtikel(tsp.kortsteRoute);
lijst.add(new Artikel(1, 1, null, 5, 1, 1));
}
if (!lijst.isEmpty()) {
order.addAlgoritmeLijst(lijst.get(0));
lijst.remove(0);
}
if (lijst.isEmpty()) {
Afstanden.set(0, Integer.toString(tsp.kortsteDistance));
t.stop();
}
} else if (algoritme == "Simpel gretig algoritme") {
if (lijst.isEmpty()) {
order.emptyAlgoritmeLijst();
lijst = tsp.nearestNeighboor(order.getProductLijst());
lijst.add(new Artikel(1, 1, null, 5, 1, 1));
}
if (!lijst.isEmpty()) {
order.addAlgoritmeLijst(lijst.get(0));
lijst.remove(0);
}
if (lijst.isEmpty()) {
Afstanden.set(1, Integer.toString(tsp.getNearestNeighboorAfstand()));
t.stop();
}
} else if (algoritme == "Volgorde van order") {
if (!drawing) {
order.emptyAlgoritmeLijst();
drawing = true;
}
if (drawing && drawingCount - 1 < order.getProductLijst().size()) {
if(drawingCount < order.getProductLijst().size()){
order.addAlgoritmeLijst(order.getArtikel(drawingCount));
}else{
order.addAlgoritmeLijst(new Artikel(1, 1, null, 5, 1, 99));
}
if (drawingCount == order.getProductLijst().size()) {
drawing = false;
}
drawingCount++;
}
if (!drawing) {
Afstanden.set(2, Integer.toString(tsp.getOrderAfstand(order.getProductLijst())));
drawingCount = 0;
t.stop();
}
}
revalidate();
repaint();
} else {
t.stop();
}
}
});
}
@Override
public void actionPerformed(ActionEvent e) {
// kijkt welke knop is ingedrukt
if (e.getSource() == jbStart) {
t.start();
} else if (e.getSource() == jbStop) {
t.stop();
} else if (e.getSource() == jcAlgoritme) {
JComboBox comboBox = (JComboBox) e.getSource();
Object selected = comboBox.getSelectedItem();
if (selected.toString().equals("Volledige enumeratie")) {
algoritme = "Volledige enumeratie";
if (count == 0) {
comboBox.removeItemAt(0);
count++;
}
} else if (selected.toString().equals("Simpel gretig algoritme")) {
algoritme = "Simpel gretig algoritme";
if (count == 0) {
comboBox.removeItemAt(0);
count++;
}
} else if (selected.toString().equals("Volgorde van order")) {
algoritme = "Volgorde van order";
if (count == 0) {
comboBox.removeItemAt(0);
count++;
}
}
}
revalidate();
repaint();
}
}
|
package com.egorand.aademo.noannotations;
public final class Constants {
private Constants() {
}
public static final String DEBUG_TAG = "AndroidAnnotationsDemo";
public static final String DATA_FRAGMENT_TAG = "data_fragment";
public static final int MSG_PROGRESS_UPDATE = 1;
public static final int MSG_REGISTER_CLIENT = 2;
public static final int MSG_UNREGISTER_CLIENT = 3;
public static final String ARGUMENT_PROGRESS = "progress";
public static final String ARGUMENT_START_BTN_ENABLED = "start_btn_enabled";
public static final String ARGUMENT_STOP_BTN_ENABLED = "stop_btn_enabled";
}
|
package heylichen.leetcode;
import org.junit.Test;
import java.util.List;
public class BSTLevelOrderTest {
private BSTLevelOrder bean = new BSTLevelOrder();
@Test
public void name() {
TreeNode node = createTree();
TreeNodeHelper.print(node);
List<List<Integer>> levels = bean.levelOrder(node);
System.out.println(levels);
}
private TreeNode createTree() {
TreeNode n10 = new TreeNode(10);
TreeNode n5 = new TreeNode(5);
TreeNode n4 = new TreeNode(4);
n10.left = (n5);
n5.left = (n4);
TreeNode n20 = new TreeNode(20);
TreeNode n30 = new TreeNode(30);
TreeNode n15 = new TreeNode(15);
TreeNode n12 = new TreeNode(12);
TreeNode n18 = new TreeNode(18);
n20.left = n15;
n20.right = n30;
n15.left = n12;
n15.right = n18;
n10.right = n20;
return n10;
}
} |
package com.example.htw.currencyconverter.scopes.components;
import com.example.htw.currencyconverter.scopes.modules.PlatformModule;
import com.example.htw.currencyconverter.ui.MainListFragment;
import com.example.htw.currencyconverter.viewmodel.CurrencyViewModel;
import javax.inject.Singleton;
import dagger.Component;
@Singleton
@Component(modules = {PlatformModule.class})
public interface AppComponent {
void inject(CurrencyViewModel viewModel);
}
|
package com.streetsnax.srinidhi.streetsnax.models;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.ArrayList;
import java.util.List;
/**
* Created by I15230 on 12/26/2015.
*/
public class Users extends BaseRecord {
@JsonProperty("resource")
public List<User> userRecord = new ArrayList<>();
}
|
package de.scads.gradoop_service.server.helper.filtering.enums;
/**
* Supported types for filter operations.
*/
public enum FilterType {
/**
* NUMERIC support all common types numerical like int, long, float, double
*/
NUMERIC,
/**
* Is meant for Strings.
*/
TEXTUAL;
}
|
package listview;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.peek_mapdemotest.buy_test1.R;
import java.util.List;
import operation.GetImage;
/**
* Created by Administrator on 2017/5/23.
*/
public class Order_genAdapter extends ArrayAdapter<Order_gen>{
private int resource;
// private List<Goods> mGoodsList;
public Order_genAdapter(Context context, int resourceID, List<Order_gen> objects) {
super(context, resourceID, objects);
resource = resourceID;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Order_gen og = getItem(position);
View view = LayoutInflater.from(getContext()).inflate(resource, parent, false);
TextView order_no = (TextView) view.findViewById(R.id.order_no);
TextView pay = (TextView) view.findViewById(R.id.pay);
TextView created_at = (TextView) view.findViewById(R.id.created_at);
pay.setText(og.getPay());
order_no.setText(og.getOrder_no());
created_at.setText(og.getCreated_at());
return view;
}
}
|
package com.wzh.crocodile.ex02_01_facade;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Locale;
/**
* @Description: 响应外观类
* @Author: 吴智慧
* @Date: 2019/11/8 17:13
*/
public class ResponseFacade implements ServletResponse {
/**
* 持有私有response对象
*/
private ServletResponse response = null;
public ResponseFacade(Response response) {
this.response = response;
}
@Override
public String getCharacterEncoding() {
return null;
}
@Override
public String getContentType() {
return null;
}
@Override
public ServletOutputStream getOutputStream() throws IOException {
return null;
}
@Override
public PrintWriter getWriter() throws IOException {
if (response instanceof Response){
return ((Response)response).getWriter();
}
return null;
}
@Override
public void setCharacterEncoding(String charset) {
}
@Override
public void setContentLength(int len) {
}
@Override
public void setContentLengthLong(long len) {
}
@Override
public void setContentType(String type) {
}
@Override
public void setBufferSize(int size) {
}
@Override
public int getBufferSize() {
return 0;
}
@Override
public void flushBuffer() throws IOException {
}
@Override
public void resetBuffer() {
}
@Override
public boolean isCommitted() {
return false;
}
@Override
public void reset() {
}
@Override
public void setLocale(Locale loc) {
}
@Override
public Locale getLocale() {
return null;
}
}
|
public class ForLoopOdometer {
public static void main(String[] args) {
/*for(int a=0; a<10;a++) {
for(int b=0;b<10; b++) {
for(int c=0;c<10;c++) {
for(int d=0;d<10;d++) {
System.out.println(a+" "+b+" "+c+" "+d);}
}
}
}
*/
/*for(int a1=5; a1>=1;a1--) {//row
for(int b1=5;b1>=1; b1--) {//colomn
System.out.print(a1);
}
System.out.println();*/
/*for(int a1=1; a1<5;a1++) {//row
for(int b1=1;b1<a1; b1++) {//colomn
System.out.print(b1);
}
System.out.println();*/
/*for(int a1=1; a1<=5;a1++) {//row
for(int b1=1;b1<=5; b1++) {//colomn
System.out.print(a1);
}
System.out.println();*/
for(int a=1; a<=9;a++) {
for(int b=1;b<=a; b++) {
System.out.print(a);
}
System.out.println();
/*for(int i=9;i>=1;i--) {
for(int j=1;j<=i;j++) {
System.out.println(i);
}
System.out.println();
}*/
}
/*for(int i=5;i>0;i++) {
for(int j=1;j<=5;j++) {
System.out.println(i);
}
System.out.println();*/
}
}
|
package com.trump.auction.back.sensitiveWord.dao.write;
import com.trump.auction.back.sensitiveWord.model.SensitiveWord;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
/**
* Author: zhanping
*/
@Repository
public interface SensitiveWordDao {
/**
* 新增
* @param obj
* @return
*/
int add(SensitiveWord obj);
/**
* 根据主键id修改
* @param obj
* @return
*/
int edit(SensitiveWord obj);
/**
* 根据主键删除
* @param id
* @return
*/
int deleteById(@Param("id") Integer id);
}
|
package pattern.mediator;
public class TestaMediator {
public static void main(String[] args) {
TaxiStation taxiStation = new TaxiStation();
Passageiro p1 = new Passageiro(taxiStation, "Jonas");
Passageiro p2 = new Passageiro(taxiStation, "Erick");
Passageiro p3 = new Passageiro(taxiStation, "Fernando");
Taxi t1 = new Taxi(taxiStation);
Taxi t2 = new Taxi(taxiStation);
taxiStation.add(t1);
taxiStation.add(t2);
new Thread(p1).start();
new Thread(p2).start();
new Thread(p3).start();
}
}
|
public class MissingNumber268 {
public static void main(String[] args) {
int[] nums = {3,0,1};
System.out.println(missingNumber(nums));
}
public static int missingNumber(int[] nums) {
int sum = 0;
for (int i = 0; i < nums.length; i++){
sum+=nums[i];
}
return nums.length * (nums.length + 1) / 2 - sum;
}
}
|
package Study.ex02;
import java.io.IOException;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
@WebServlet("/ex02/s1")
@SuppressWarnings("serial")
public class Servlet01 extends GenericServlet{
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
System.out.println("ex02/s1");
}
}
|
package Books;
import java.util.Scanner;
class Menu {
public static Scanner yourChoice;
public String Choice() {
yourChoice = new Scanner(System.in);
System.out.println("Нажмите 1,\nесли хотите вывести список книг одного автора\n\n"
+ "Нажмите 2,\nесли хотите вывести список книг одного издательства\n\n"
+ "Нажмите 3,\nесли хотите вывести список книг выпущенных после ХХХХ года\n");
String firstChoice = yourChoice.nextLine();
switch (firstChoice) {
case "1":
System.out.println("какого автора вы выбираете:");
String secondChoiceAuthor = yourChoice.nextLine();
firstChoice = secondChoiceAuthor;
break;
case "2":
System.out.println("какое издательство вы выбираете:");
String secondChoicePubHouse = yourChoice.nextLine();
firstChoice = secondChoicePubHouse;
break;
case "3":
System.out.println("после какого года книги вас интересуют:");
String secondChoiceYear = yourChoice.nextLine();
firstChoice = secondChoiceYear;
break;
default:
System.out.println("вы выбрали неправильно");
break;
}
return firstChoice;
}
}
|
package com.eussi._01_jca_jce.cryptopkg;
import org.junit.Test;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.util.Arrays;
/**
* Created by wangxueming on 2019/4/1.
*/
public class _05_Cipher {//未加密解密提供密码功能,他是JCE框架的核心
@Test
public void test() {//密码的包装和解包操作
//实例化
try {
//实例化KeyPairGenerator
KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
//生成SecretKey
SecretKey secretKey = keyGenerator.generateKey();
byte[] key = secretKey.getEncoded();
System.out.println("secretyKey:" + Arrays.toString(secretKey.getEncoded()));
//实例化Cipher对象
Cipher cipher = Cipher.getInstance("DES");
//初始化Cipher对象,用于包装
cipher.init(Cipher.WRAP_MODE, secretKey);
//包装秘密密钥
byte[] k = cipher.wrap(secretKey);
//得到字节数组后,可以将其传给需要解包的一方//初始化Cipher对象,用于包装
cipher.init(Cipher.UNWRAP_MODE, secretKey);
//解包秘密密钥
SecretKey secretKey1 = (SecretKey) cipher.unwrap(k, "DES", Cipher.SECRET_KEY);
System.out.println("secretyKey1:" + Arrays.toString(secretKey1.getEncoded()));
//初始化,用于加密
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
//加密
byte[] input = cipher.doFinal("test".getBytes());
System.out.println("test加密后信息:" + Arrays.toString(input));
//初始化,用与解密
cipher.init(Cipher.DECRYPT_MODE, secretKey);
//解密
byte[] output = cipher.doFinal(input);
System.out.println("解密后信息:" + new String(output));
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
// **********************************************************
// 1. 제 목:
// 2. 프로그램명: SulmunSubjResultBean.java
// 3. 개 요:
// 4. 환 경: JDK 1.3
// 5. 버 젼: 0.1
// 6. 작 성: Administrator 2003-08-18
// 7. 수 정:
//
// **********************************************************
package com.ziaan.research;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.StringTokenizer;
import java.util.Vector;
import com.ziaan.library.DBConnectionManager;
import com.ziaan.library.DataBox;
import com.ziaan.library.ErrorManager;
import com.ziaan.library.ListSet;
import com.ziaan.library.RequestBox;
import com.ziaan.library.SQLString;
import com.ziaan.library.StringManager;
import com.ziaan.system.SelectionUtil;
/**
* @author Administrator
*
* To change the template for this generated type comment go to
* Window > Preferences > Java > Code Generation > Code and Comments
*/
public class SulmunSubjResultBean {
public SulmunSubjResultBean() { }
/**
과목설문 결과 보기
@param box receive from the form object and session
@return ArrayList
*/
public ArrayList SelectObectResultList(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
ArrayList list = null;
String v_action = box.getString("p_action");
try {
if ( v_action.equals("go") ) {
connMgr = new DBConnectionManager();
list = getObjectSulmunResult(connMgr, box);
} else {
list = new ArrayList();
}
} catch ( Exception ex ) {
ErrorManager.getErrorStackTrace(ex);
throw new Exception(ex.getMessage() );
} finally {
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } }
}
return list;
}
/**
과목설문 결과 보기
@param box receive from the form object and session
@return ArrayList
*/
public ArrayList getObjectSulmunResult(DBConnectionManager connMgr, RequestBox box) throws Exception {
Vector v_sulnums = null;
ArrayList QuestionExampleDataList = null;
Vector v_answers = null;
String v_subj = box.getStringDefault("p_subj", box.getString("s_subjcourse") );
String v_subjseq = box.getStringDefault("p_subjseq", box.getString("s_subjseq") );
int v_sulpapernum = box.getInt("p_sulpapernum");
if ( v_sulpapernum == 0) v_sulpapernum = box.getInt("s_sulpapernum");
String v_grseq = box.getStringDefault("s_grseq","0001");
// 설문번호 선택조건
String v_grcode = box.getString("p_grcode");
String v_gyear = box.getString("p_gyear");
// 응답자 선택조건
String v_company = box.getStringDefault("p_company","ALL");
String v_jikwi = box.getStringDefault("p_jikwi","ALL");
String v_jikun = box.getStringDefault("p_jikun","ALL");
String v_workplc = box.getStringDefault("p_workplc","ALL");
int v_studentcount = 0;
try {
// v_sulpapernum = getPapernumSeq(v_subj, v_grcode) - 1;
// 설문지번호에 해당하는 설문번호를 vector로 받아온다. 벡터(설문번호1,3,5 ....)
// v_sulnums = getSulnums(connMgr, v_grcode, v_gyear, v_subj, v_subjseq, v_sulpapernum);
v_sulnums = getSulnums(connMgr, "ALL", v_gyear, "ALL", v_subjseq, v_sulpapernum);
// 설문번호에 해당하는 문제리스트를 만든다. 리스트((설문번호1, 보기1,2,3..))
// QuestionExampleDataList = getSelnums(connMgr, v_subj, v_sulnums);
QuestionExampleDataList = getSelnums(connMgr, "ALL", v_sulnums);
// 설문지 답변모음을 읽어온다. 벡터(답변1,3,2,3..)
v_answers = getSulmunAnswers(connMgr, v_grcode, v_gyear, v_grseq, v_subj, v_sulpapernum, v_subjseq, v_company, v_jikwi, v_jikun, v_workplc);
// 리스트((설문번호1, 보기1,2,3..)) + 벡터(답변1,3,2,3..) 이용해서 응답자수 및 비율을 계산한다.
ComputeCount(QuestionExampleDataList, v_answers);
// 응답자수
box.put("p_replycount", String.valueOf(v_answers.size() ));
// 수강자수
v_studentcount = getStudentCount(connMgr, v_grcode, v_gyear, v_grseq, v_subj, v_subjseq, v_company, v_jikwi, v_jikun, v_workplc);
box.put("p_studentcount", String.valueOf(v_studentcount));
} catch ( Exception ex ) {
ErrorManager.getErrorStackTrace(ex);
throw new Exception(ex.getMessage() );
}
return QuestionExampleDataList;
}
/**
문제번호(안쓰임)
@param box receive from the form object and session
@return ArrayList
*/
public Vector getSulnums(DBConnectionManager connMgr, String p_grcode, String p_subj, int p_sulpapernum) throws Exception {
ListSet ls = null;
String sql = "";
Vector v_sulnums = new Vector();
String v_tokens = "";
StringTokenizer st = null;
try {
sql = "select sulnums ";
sql += " from tz_sulpaper ";
sql += " where grcode = " + SQLString.Format(p_grcode);
// sql += " where grcode = " + SQLString.Format(SulmunSubjBean.DEFAULT_GRCODE);
sql += " and subj = " + SQLString.Format(p_subj);
sql += " and sulpapernum = " + SQLString.Format(p_sulpapernum);
ls = connMgr.executeQuery(sql);
while ( ls.next() ) {
v_tokens = ls.getString("sulnums");
}
st = new StringTokenizer(v_tokens,SulmunSubjBean.SPLIT_COMMA);
while ( st.hasMoreElements() ) {
v_sulnums.add((String)st.nextToken() );
}
} catch ( Exception ex ) {
ErrorManager.getErrorStackTrace(ex);
throw new Exception(ex.getMessage() );
} finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
}
return v_sulnums;
}
/**
문제번호(쓰임)
@param box receive from the form object and session
@return ArrayList
*/
public Vector getSulnums(DBConnectionManager connMgr, String p_grcode, String p_gyear, String p_subj, String p_subjseq, int p_sulpapernum) throws Exception {
ListSet ls = null;
String sql = "";
Vector v_sulnums = new Vector();
String v_tokens = "";
StringTokenizer st = null;
try {
// subj='ALL' , GRCODE='ALL'
sql = "select sulnums ";
sql += " from tz_sulpaper ";
sql += " where grcode = " + SQLString.Format(p_grcode);
// sql += " and year = " + SQLString.Format(p_gyear);
sql += " and subj = " + SQLString.Format(p_subj);
// if ( !p_subjseq.equals("ALL"))
// sql += " and subjseq = " + SQLString.Format(p_subjseq);
sql += " and sulpapernum = " + SQLString.Format(p_sulpapernum);
ls = connMgr.executeQuery(sql);
while ( ls.next() ) {
v_tokens = ls.getString("sulnums");
}
st = new StringTokenizer(v_tokens,SulmunSubjBean.SPLIT_COMMA);
while ( st.hasMoreElements() ) {
v_sulnums.add((String)st.nextToken() );
}
} catch ( Exception ex ) {
ErrorManager.getErrorStackTrace(ex);
throw new Exception(ex.getMessage() );
} finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
}
return v_sulnums;
}
/**
문제리스트
@param box receive from the form object and session
@return ArrayList
*/
public ArrayList getSelnums(DBConnectionManager connMgr, String p_subj, Vector p_sulnums) throws Exception {
Hashtable hash = new Hashtable();
ArrayList list = new ArrayList();
ListSet ls = null;
String sql = "";
SulmunQuestionExampleData data = null;
SulmunExampleData exampledata = null;
int v_bef_sulnum = 0;
String v_sulnums = "";
for ( int i = 0; i < p_sulnums.size(); i++ ) {
v_sulnums += (String)p_sulnums.get(i);
if ( i<p_sulnums.size()-1) {
v_sulnums += ", ";
}
}
if ( v_sulnums.equals("")) v_sulnums = "-1";
try {
/*sql = "select a.subj, a.sulnum, ";
sql +=" a.distcode, c.codenm distcodenm, ";
sql += " a.sultype, d.codenm sultypenm, ";
sql += " a.sultext, b.selnum, b.seltext, b.selpoint ";
sql += " from tz_sul a, ";
sql += " tz_sulsel b, ";
sql += " tz_code c, ";
sql += " tz_code d ";
sql += " where a.subj = b.subj( +) ";
sql += " and a.sulnum = b.sulnum( +) ";
sql += " and a.distcode = c.code ";
sql += " and a.sultype = d.code ";
sql += " and a.subj = " + SQLString.Format(p_subj);
sql += " and a.sulnum in (" + v_sulnums + ")";
sql += " and c.gubun = " + SQLString.Format(SulmunSubjBean.DIST_CODE);
sql += " and d.gubun = " + SQLString.Format(SulmunSubjBean.SUL_TYPE);
sql += " order by a.subj, a.sulnum, b.selnum ";*/
sql = "select a.subj, a.sulnum, a.distcode, c.codenm distcodenm, a.sultype, d.codenm sultypenm, ";
sql += " a.sultext, b.selnum, b.seltext, b.selpoint ";
sql += " from tz_sul a, tz_sulsel b, tz_code c, tz_code d ";
sql += " where a.subj = b.subj( +) AND a.GRCODE = b.GRCODE( +) ";
sql += " and a.sulnum = b.sulnum( +) and a.distcode = c.code ";
sql += " and a.sultype = d.code and a.subj = 'ALL' AND a.GRCODE = 'ALL' ";
sql += " and a.sulnum in (" + v_sulnums + ")";
sql += " and c.gubun = " + SQLString.Format(SulmunSubjBean.DIST_CODE);
sql += " and d.gubun = " + SQLString.Format(SulmunSubjBean.SUL_TYPE);
sql += " order by a.subj, a.sulnum, b.selnum ";
System.out.println("설문 >> " +sql);
ls = connMgr.executeQuery(sql);
while ( ls.next() ) {
if ( v_bef_sulnum != ls.getInt("sulnum") ) {
data = new SulmunQuestionExampleData();
data.setSubj( ls.getString("subj") );
data.setSulnum( ls.getInt("sulnum") );
data.setSultext( ls.getString("sultext") );
data.setSultype( ls.getString("sultype") );
data.setSultypenm( ls.getString("sultypenm") );
data.setDistcode( ls.getString("distcode") );
data.setDistcodenm( ls.getString("distcodenm") );
}
exampledata = new SulmunExampleData();
exampledata.setSubj(data.getSubj() );
exampledata.setSulnum(data.getSulnum() );
exampledata.setSelnum( ls.getInt("selnum") );
exampledata.setSelpoint( ls.getInt("selpoint") );
exampledata.setSeltext( ls.getString("seltext") );
data.add(exampledata);
if ( v_bef_sulnum != data.getSulnum() ) {
hash.put(String.valueOf(data.getSulnum() ), data);
v_bef_sulnum = data.getSulnum();
}
}
data = null;
System.out.println(" >> >> >> >> > p_sulnums" +p_sulnums.size() );
for ( int i = 0; i < p_sulnums.size(); i++ ) {
data = (SulmunQuestionExampleData)hash.get((String)p_sulnums.get(i));
if ( data != null ) {
list.add(data);
}
}
} catch ( Exception ex ) {
ErrorManager.getErrorStackTrace(ex);
throw new Exception(ex.getMessage() );
} finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
}
return list;
}
/**
과목설문 결과보기 응답율 구하기
@param box receive from the form object and session
@return ArrayList
*/
public void ComputeCount(ArrayList p_list, Vector p_answers) throws Exception {
StringTokenizer st1 = null;
StringTokenizer st2 = null;
SulmunQuestionExampleData data = null;
Vector subject = new Vector();
Vector complex = new Vector();
String v_answers = "";
String v_answer = "";
int index=0;
try {
for ( int i = 0; i < p_answers.size(); i++ ) {
v_answers = (String)p_answers.get(i);
st1 = new StringTokenizer(v_answers,SulmunSubjBean.SPLIT_COMMA);
index = 0;
while ( st1.hasMoreElements() && index < p_list.size() ) {
v_answer = (String)st1.nextToken();
data = (SulmunQuestionExampleData)p_list.get(index);
if ( data.getSultype().equals(SulmunSubjBean.OBJECT_QUESTION)) {
data.IncreasReplyCount(Integer.valueOf(v_answer).intValue() );
} else if ( data.getSultype().equals(SulmunSubjBean.MULTI_QUESTION)) {
st2 = new StringTokenizer(v_answer,SulmunSubjBean.SPLIT_COLON);
while ( st2.hasMoreElements() ) {
v_answer = (String)st2.nextToken();
data.IncreasReplyCount(Integer.valueOf(v_answer).intValue() );
}
} else if ( data.getSultype().equals(SulmunSubjBean.SUBJECT_QUESTION)) {
subject.add(v_answer);// System.out.println("v_answer " + v_answer);
} else if ( data.getSultype().equals(SulmunSubjBean.COMPLEX_QUESTION)) {
st2 = new StringTokenizer(v_answer,SulmunSubjBean.SPLIT_COLON);
v_answer = (String)st2.nextToken();
data.IncreasReplyCount(Integer.valueOf(v_answer).intValue() );
String v_sanswer = "";
if ( st2.hasMoreElements() ) {
v_sanswer = (String)st2.nextToken();
}
complex.add(v_sanswer);
} else if ( data.getSultype().equals(SulmunSubjBean.FSCALE_QUESTION)) {
data.IncreasReplyCount(Integer.valueOf(v_answer).intValue() );
} else if ( data.getSultype().equals(SulmunSubjBean.SSCALE_QUESTION)) {
data.IncreasReplyCount(Integer.valueOf(v_answer).intValue() );
}
index++;
}
}
// 응답비율을 계산한다. 리스트((설문번호1, 보기1,2,3..))
for ( int i = 0; i < p_list.size(); i++ ) {
data = (SulmunQuestionExampleData)p_list.get(i);
data.ComputeRate();
data.setComplexAnswer(complex);
data.setSubjectAnswer(subject);System.out.println(subject);
}
} catch ( Exception ex ) { ex.printStackTrace();
ErrorManager.getErrorStackTrace(ex);
throw new Exception(ex.getMessage() );
}
}
/**
과목설문 결과보기 정답 구하기
@param box receive from the form object and session
@return Vector
*/
public Vector getSulmunAnswers(DBConnectionManager connMgr, String p_grcode, String p_gyear,
String p_grseq, String p_subj, int p_sulpapernum, String p_subjseq,
String p_company, String p_jikwi, String p_jikun, String p_workplc) throws Exception {
ListSet ls = null;
String sql = "";
Vector v_answers = new Vector();
String v_comp = "";
try {
/* sql = " select c.answers ";
sql += " from tz_subjseq a, ";
sql += " tz_student b, ";
sql += " tz_suleach c, ";
sql += " tz_member d ";
sql += " where a.subj = b.subj ";
sql += " and a.year = b.year ";
sql += " and a.subjseq = b.subjseq ";
sql += " and b.subj = c.subj ";
sql += " and b.year = c.year ";
sql += " and b.subjseq = c.subjseq ";
sql += " and b.userid = c.userid ";
sql += " and c.userid = d.userid ";
if ( !p_grcode.equals("ALL"))
sql += " and c.grcode = " + SQLString.Format(p_grcode);
if ( !p_gyear.equals("ALL"))
sql += " and c.year = " + SQLString.Format(p_gyear);
// if ( !p_grseq.equals("ALL"))
// sql += " and a.grseq = " + SQLString.Format(p_grseq);
// sql += " and c.f_gubun = " + SQLString.Format(p_gubun);
sql += " and c.subj = " + SQLString.Format(p_subj);
if ( !p_subjseq.equals("ALL"))
sql += " and c.subjseq = " + SQLString.Format(p_subjseq);
sql += " and c.sulpapernum = " + SQLString.Format(p_sulpapernum);
if ( !p_company.equals("ALL"))
sql += " and d.comp = " + SQLString.Format(p_company);
if ( !p_jikwi.equals("ALL"))
sql += " and d.jikwi = " + SQLString.Format(p_jikwi);
if ( !p_jikun.equals("ALL"))
sql += " and d.jikun = " + SQLString.Format(p_jikun);
if ( !p_workplc.equals("ALL"))
sql += " and d.work_plc = " + SQLString.Format(p_workplc);*/
sql = " select answers \n"
+ " from tz_suleach \n"
+ " where grcode = " + SQLString.Format(p_grcode ) + " \n";
if ( p_subj.equals("ALL") )
sql += " and (subj, subjseq) IN ( SELECT Subj, subjseq FROM Tz_Subjseq WHERE Year = " + SQLString.Format(p_gyear) + " AND grseq = " + SQLString.Format(p_grseq )+ ") \n";
else
sql += " and subj = " + SQLString.Format(p_subj ) + " \n";
sql += " and year = " + SQLString.Format(p_gyear ) + " \n";
if ( p_subjseq.equals("ALL") )
sql += " and (subj, subjseq) IN ( SELECT subj, subjseq FROM Tz_Subjseq WHERE Year = " + SQLString.Format(p_gyear) + " AND grseq = " + SQLString.Format(p_grseq )+ ") \n";
else
sql += " and subjseq = " + SQLString.Format(p_subjseq) + " \n";
sql += " and sulpapernum = " + SQLString.Format(p_sulpapernum) + " \n";
System.out.println(sql);
ls = connMgr.executeQuery(sql);
while ( ls.next() ) {
v_answers.add( ls.getString("answers") );
}
} catch ( Exception ex ) {
ErrorManager.getErrorStackTrace(ex);
throw new Exception(ex.getMessage() );
} finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
}
return v_answers;
}
/**
과목설문 결과보기 학생수 구하기
@param box receive from the form object and session
@return int
*/
public int getStudentCount(DBConnectionManager connMgr, String p_grcode, String p_gyear, String p_grseq, String p_subj, String p_subjseq,
String p_company, String p_jikwi, String p_jikun, String p_workplc) throws Exception {
ListSet ls = null;
String sql = "";
String v_comp = "";
int v_count = 0;
try {
sql = " select count(*) cnt ";
sql += " from tz_subjseq a, ";
sql += " tz_student b, ";
sql += " tz_member c ";
sql += " where a.subj = b.subj ";
sql += " and a.year = b.year ";
sql += " and a.subjseq = b.subjseq ";
sql += " and b.userid = c.userid ";
sql += " and a.subj = " + SQLString.Format(p_subj);
if ( !p_grcode.equals("ALL"))
sql += " and a.grcode = " + SQLString.Format(p_grcode);
if ( !p_gyear.equals("ALL"))
sql += " and a.gyear = " + SQLString.Format(p_gyear);
if ( !p_subjseq.equals("ALL"))
sql += " and a.subjseq = " + SQLString.Format(p_subjseq);
if ( !p_grseq.equals("ALL"))
// sql += " and a.grseq = " + SQLString.Format(p_grseq);
if ( !p_company.equals("ALL"))
sql += " and c.comp = " + SQLString.Format(p_company);
if ( !p_jikwi.equals("ALL"))
sql += " and c.jikwi = " + SQLString.Format(p_jikwi);
if ( !p_jikun.equals("ALL"))
sql += " and c.jikun = " + SQLString.Format(p_jikun);
if ( !p_workplc.equals("ALL"))
sql += " and c.work_plc = " + SQLString.Format(p_workplc);
ls = connMgr.executeQuery(sql);
while ( ls.next() ) {
v_count = ls.getInt("cnt");
}
} catch ( Exception ex ) {
ErrorManager.getErrorStackTrace(ex);
throw new Exception(ex.getMessage() );
} finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
}
return v_count;
}
public int getPapernumSeq(String p_subj, String p_grcode) throws Exception {
Hashtable maxdata = new Hashtable();
maxdata.put("seqcolumn","sulpapernum");
maxdata.put("seqtable","tz_sulpaper");
maxdata.put("paramcnt","2");
maxdata.put("param0","subj");
maxdata.put("param1","grcode");
maxdata.put("subj", SQLString.Format(p_subj));
maxdata.put("grcode", SQLString.Format(p_grcode));
return SelectionUtil.getSeq(maxdata);
}
public int getPapernumSeq(String p_subj, String p_grcode, String p_gyear, String p_subjseq) throws Exception {
Hashtable maxdata = new Hashtable();
maxdata.put("seqcolumn","sulpapernum");
maxdata.put("seqtable","tz_sulpaper");
maxdata.put("paramcnt","4");
maxdata.put("param0","subj");
maxdata.put("param1","grcode");
maxdata.put("param2","year");
maxdata.put("param3","subjseq");
maxdata.put("subj", SQLString.Format(p_subj));
maxdata.put("grcode", SQLString.Format(p_grcode));
maxdata.put("year", SQLString.Format(p_gyear));
maxdata.put("subjseq", SQLString.Format(p_subjseq));
return SelectionUtil.getSeq(maxdata);
}
/**
* 자료실 리스트화면 select
* @param box receive from the form object and session
* @return ArrayList 자료실 리스트
* @throws Exception
*/
public ArrayList selectBoardList(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
ListSet ls = null;
ArrayList list = null;
String sql = "";
DataBox dbox = null;
Vector v_answers = null;
int v_pageno = box.getInt("p_pageno");
if ( v_pageno == 0) v_pageno=1;
int v_row = box.getInt("p_row");
if ( v_row == 0) v_row=10;
java.util.Date d_now = new java.util.Date();
String v_gyear = box.getStringDefault("s_gyear", String.valueOf(d_now.getYear() +1900));
String v_searchtype = box.getString("s_searchtype");
String v_searchtext = box.getString("s_searchtext");
String v_grseq = box.getStringDefault("p_grseq","0001");
// 응답자 선택조건
String v_company = box.getStringDefault("p_company","ALL");
String v_jikwi = box.getStringDefault("p_jikwi","ALL");
String v_jikun = box.getStringDefault("p_jikun","ALL");
String v_workplc = box.getStringDefault("p_workplc","ALL");
try {
connMgr = new DBConnectionManager();
list = new ArrayList();
sql = "select distinct p.subj, p.subjseq, p.grcode, p.sulpapernum, p.sulpapernm, p.year, p.edustart, p.eduend, p.subjnm";
sql +=" from";
sql += " (select b.subj, b.subjseq, b.grcode, ";
sql +=" a.sulpapernum, a.sulpapernm, b.year, ";
sql += " b.edustart, b.eduend, ";
sql += " b.subjnm ";
sql += " from tz_sulpaper a, ";
sql += " tz_subjseq b ";
sql += " where a.subj = b.subj ";
sql += " and a.subjseq = b.subjseq ";
sql += " and b.year = " + SQLString.Format(v_gyear);
sql += " and b.isclosed = 'Y'";
if ( !v_searchtext.equals("") ) { // 검색어가 있으면
// 검색할 경우 첫번째 페이지가 로딩된다
if ( v_searchtype.equals("1") ) { // 설문제목으로 검색할때
sql += " and a.sulpapernm like " + StringManager.makeSQL("%" + v_searchtext + "%");
}
else if ( v_searchtype.equals("2") ) { // 과목명으로 검색할때
sql += " and b.subjnm like " + StringManager.makeSQL("%" + v_searchtext + "%");
}
}
sql += " ) p, ";
sql += " tz_suleach q ";
sql += " where p.subj = q.subj and p.grcode = q.grcode and p.year = q.year and p.subjseq = q.subjseq ";
sql += " and p.sulpapernum = q.sulpapernum ";
sql += " order by p.edustart desc, p.subjnm";
// System.out.println(sql);
ls = connMgr.executeQuery(sql);
ls.setPageSize(v_row); // 페이지당 row 갯수를 세팅한다
ls.setCurrentPage(v_pageno); // 현재페이지번호를 세팅한다.
int totalpagecount = ls.getTotalPage(); // 전체 페이지 수를 반환한다
int totalrowcount = ls.getTotalCount(); // 전체 row 수를 반환한다
while ( ls.next() ) {
dbox = ls.getDataBox();
// 설문지 답변모음을 읽어온다. 벡터(답변1,3,2,3..)
v_answers = getSulmunAnswers(connMgr, dbox.getString("d_grcode"), v_gyear, v_grseq, dbox.getString("d_subj"), dbox.getInt("d_sulpapernum"), dbox.getString("d_subjseq"), v_company, v_jikwi, v_jikun, v_workplc);
// 응답자수
dbox.put("d_replycount", String.valueOf(v_answers.size() ));
dbox.put("d_dispnum", new Integer(totalrowcount - ls.getRowNum() + 1));
dbox.put("d_totalpage", new Integer(totalpagecount));
dbox.put("d_rowcount", new Integer(v_row));
list.add(dbox);
}
} catch ( Exception ex ) {
ErrorManager.getErrorStackTrace(ex, box, sql);
throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() );
} finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } }
}
return list;
}
/**
과목설문 결과 엑셀리스트_상세
@param box receive from the form object and session
@return ArrayList 과목설문 결과 엑셀리스트
*/
public ArrayList selectSulmunDetailResultExcelList(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
ArrayList list = null;
ArrayList list2 = null;
ListSet ls = null;
ListSet ls2 = null;
DataBox dbox = null;
// DataBox dbox2 = null;
String sql = "";
String sql2 = "";
try {
String ss_grcode = box.getString("s_grcode");
String ss_subjcourse = box.getString("s_subjcourse");
String ss_year = box.getString("s_gyear");
String ss_subjseq = box.getString("s_subjseq");
String v_action = box.getString("p_action");
int v_sulpapernum = box.getInt("s_sulpapernum");
String v_subjusernm = "";
list = new ArrayList();
if ( v_action.equals("go") ) {
connMgr = new DBConnectionManager();
sql = "select a.userid, b.comp asgn, get_compnm(b.comp,2,4) asgnnm, b.divinam,";
sql += " b.jikwi, get_jikwinm(b.jikwi, b.comp) jikwinm, ";
sql += " b.cono, b.name ";
sql += " from ";
sql += " ( select userid, subj, year, subjseq ";
sql += " from tz_student ";
sql += " where subj = " + SQLString.Format(ss_subjcourse);
sql += " and year = " + SQLString.Format(ss_year);
sql += " and subjseq = " + SQLString.Format(ss_subjseq) + " ) a, ";
sql += " tz_member b ";
sql += " where a.userid = b.userid ";
sql += " order by a.userid ";
ls = connMgr.executeQuery(sql);
Vector sulnum = new Vector();
while ( ls.next() ) {
dbox = ls.getDataBox();
v_subjusernm = dbox.getString("d_name");
dbox.put("d_subjusernm", v_subjusernm);
dbox.put("d_subjasgmnm", dbox.getString("d_asgnnm") );
sql2 = "select userid, sulnums, answers";
sql2 += " from tz_suleach";
sql2 += " where subj = " + SQLString.Format(ss_subjcourse);
sql2 += " and grcode = " + SQLString.Format(ss_grcode);
sql2 += " and year = " + SQLString.Format(ss_year);
sql2 += " and subjseq = " + SQLString.Format(ss_subjseq);
sql2 += " and sulpapernum = " + SQLString.Format(v_sulpapernum);
sql2 += " and userid = " + SQLString.Format(dbox.getString("d_userid") );
ls2 = connMgr.executeQuery(sql2);// System.out.println("sql2" + sql2);
if ( ls2.next() ) {
// dbox2 = ls2.getDataBox();
dbox.put("d_anwsers", ls2.getString("answers") );// System.out.println("sulnums" + ls2.getString("sulnums") );
StringTokenizer st = new StringTokenizer( ls2.getString("sulnums"), ",");
while ( st.hasMoreElements() ) {
sulnum.addElement(st.nextToken() );
}
String selpoint = "";
StringTokenizer f_st = new StringTokenizer( ls2.getString("answers"), ",");// System.out.println("fanswers" + ls2.getString("fanswers") );
for ( int i = 0; f_st.hasMoreElements(); i++ ) {
String token = f_st.nextToken();
if ( token.equals("")) break;
selpoint = selpoint + this.getSelpoints(connMgr, ss_subjcourse, ss_grcode, (String)(sulnum.elementAt(i)), token) + ",";
} // System.out.println(selpoint);
dbox.put("d_selpoint", selpoint);
}
ls2.close();
list.add(dbox);
}
}
} catch ( Exception ex ) { ex.printStackTrace();
ErrorManager.getErrorStackTrace(ex);
throw new Exception(ex.getMessage() );
} finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
if ( ls2 != null ) { try { ls2.close(); } catch ( Exception e ) { } }
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } }
}
return list;
}
public String getSelpoints(DBConnectionManager connMgr, String p_subj, String p_grcode, String p_sulnum, String p_sulselnum) throws Exception {
ListSet ls1 = null;
ListSet ls2 = null;
String sql1 = "";
String sql2 = "";
String v_result = "0";
try {
sql1 = "select sultype from tz_sul where sulnum = " + p_sulnum;
sql1 += " and subj = " + SQLString.Format(p_subj);
sql1 += " and grcode = " + SQLString.Format(p_grcode);
ls1 = connMgr.executeQuery(sql1);
while ( ls1.next() ) {
sql2 = "select selpoint";
sql2 += " from tz_sulsel ";
sql2 += " where subj = " + SQLString.Format(p_subj);
sql2 += " and grcode = " + SQLString.Format(p_grcode);
sql2 += " and sulnum = " + p_sulnum;
sql2 += " and selnum = " + p_sulselnum;
// System.out.println(( ls1.getString("sultype")));
// System.out.println(p_sulselnum);
if ( ls1.getString("sultype").equals("5") || ls1.getString("sultype").equals("6") ) {
ls2 = connMgr.executeQuery(sql2);
while ( ls2.next() ) {
v_result = ls2.getInt(1) + "";
}
if ( ls2 != null ) { try { ls2.close(); } catch ( Exception e ) { } }
}
}
if ( ls1 != null ) { try { ls1.close(); } catch ( Exception e ) { } }
} catch ( Exception ex ) {
ErrorManager.getErrorStackTrace(ex);
throw new Exception(ex.getMessage() );
} finally {
if ( ls1 != null ) { try { ls1.close(); } catch ( Exception e ) { } }
if ( ls2 != null ) { try { ls2.close(); } catch ( Exception e ) { } }
}
return v_result;
}
/**
개인별 리스트
@param box receive from the form object and session
@return ArrayList
*/
public ArrayList selectResultMemberList(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
ListSet ls = null;
ArrayList list = new ArrayList();
StringBuffer sbSQL = new StringBuffer("");
DataBox dbox = null;
int iSysAdd = 0; // System.out.println을 Mehtod에서 사용하는 순서를 표시하는 변수
String v_action = box.getString("p_action" );
String v_subj = box.getString("p_subj" );
String v_gyear = box.getString("p_gyear" );
String v_subjseq = box.getString("p_subjseq" );
String v_grcode = box.getString("p_grcode" );
String v_grseq = box.getString("s_grseq" );
String v_sulmuntype = box.getString("p_sulmuntype" );
// int v_sulpapernum = box.getInt ("p_sulpapernum" ) == 0 ? box.getInt("s_sulpapernum") : box.getInt("p_sulpapernum") ;
try {
connMgr = new DBConnectionManager();
if ( v_action.equals("go") ) {
sbSQL.append(" select a.userid \n")
.append(" , b.name \n")
.append(" , b.hometel \n")
.append(" , b.handphone \n")
.append(" , nvl(a.distcode1 , 0) distcode1 \n")
.append(" , nvl(a.distcode2 , 0) distcode2 \n")
.append(" , nvl(a.distcode3 , 0) distcode3 \n")
.append(" , nvl(a.distcode4 , 0) distcode4 \n")
.append(" , nvl(a.distcode5 , 0) distcode5 \n")
.append(" , nvl(a.distcode6 , 0) distcode6 \n")
.append(" , nvl(a.distcode7 , 0) distcode7 \n")
.append(" , nvl(a.distcode8 , 0) distcode8 \n")
.append(" , nvl(a.distcode10 , 0) distcode10 \n")
.append(" , nvl(a.distcode1_avg , 0) distcode1_avg \n") // 학습성과
.append(" , nvl(a.distcode2_avg , 0) distcode2_avg \n") // 내용적정
.append(" , nvl(a.distcode3_avg , 0) distcode3_avg \n") // 과정설계
.append(" , nvl(a.distcode4_avg , 0) distcode4_avg \n") // 과정운영
.append(" , nvl(a.distcode5_avg , 0) distcode5_avg \n") // 강사만족
.append(" , nvl(a.distcode6_avg , 0) distcode6_avg \n") // LMS
.append(" , nvl(a.distcode7_avg , 0) distcode7_avg \n") // 과정만족도
.append(" , nvl(a.distcode8_avg , 0) distcode8_avg \n") // 개선사항
.append(" , a.answers \n")
.append(" , a.ldate \n")
.append(" , a.sulpapernum \n")
.append(" , a.grcode \n")
.append(" , a.subj \n")
.append(" from tz_suleach a \n")
.append(" , tz_member b \n")
.append(" , tz_subjseq c \n")
.append(" where a.userid = b.userid \n")
.append(" and a.subj = c.subj \n")
.append(" and a.subjseq = c.subjseq \n")
.append(" and a.grcode = c.grcode \n")
.append(" and a.year = c.year \n");
if ( v_subj.equals("ALL") )
sbSQL.append(" and (a.subj, a.subjseq) IN ( SELECT Subj, subjseq FROM Tz_Subjseq WHERE Year = " + SQLString.Format(v_gyear) + " AND grseq = " + SQLString.Format(v_grseq )+ ") \n");
else
sbSQL.append(" and a.subj = " + StringManager.makeSQL(v_subj ) + " \n");
if ( v_subjseq.equals("ALL") )
sbSQL.append(" and (a.subj, a.subjseq) IN ( SELECT subj, subjseq FROM Tz_Subjseq WHERE Year = " + SQLString.Format(v_gyear) + " AND grseq = " + SQLString.Format(v_grseq )+ ") \n");
else
sbSQL.append(" and a.subjseq = " + StringManager.makeSQL(v_subjseq ) + " \n");
sbSQL.append(" and a.grcode = " + StringManager.makeSQL(v_grcode ) + " \n")
.append(" and a.year = " + StringManager.makeSQL(v_gyear ) + " \n")
.append(" and a.sulpapernum = c." + v_sulmuntype );
System.out.println(this.getClass().getName() + "." + "selectResultMemberList() Printing Order " + ++iSysAdd + ". ======[SQL] : " + " [\n" + sbSQL.toString() + "\n]");
ls = connMgr.executeQuery(sbSQL.toString());
while ( ls.next() ) {
dbox = ls.getDataBox();
dbox.put("distcode1avg", new Double( ls.getDouble("distcode1_avg")));
dbox.put("distcode2avg", new Double( ls.getDouble("distcode2_avg")));
dbox.put("distcode3avg", new Double( ls.getDouble("distcode3_avg")));
dbox.put("distcode4avg", new Double( ls.getDouble("distcode4_avg")));
dbox.put("distcode5avg", new Double( ls.getDouble("distcode5_avg")));
dbox.put("distcode6avg", new Double( ls.getDouble("distcode6_avg")));
dbox.put("distcode7avg", new Double( ls.getDouble("distcode7_avg")));
dbox.put("distcode8avg", new Double( ls.getDouble("distcode8_avg")));
box.put( "p_sulpapernum", ls.getInt("sulpapernum"));
list.add(dbox);
}
}
} catch ( SQLException e ) {
ErrorManager.getErrorStackTrace(e, box, sbSQL.toString());
throw new Exception("\n SQL : [\n" + sbSQL.toString() + "]\n e.getMessage() : [\n" + e.getMessage() + "\n]");
} catch ( Exception e ) {
ErrorManager.getErrorStackTrace(e, box, "");
throw new Exception("\n e.getMessage() : [\n" + e.getMessage() + "\n]");
} finally {
if ( ls != null ) {
try {
ls.close();
} catch ( Exception e ) { }
}
if ( connMgr != null ) {
try {
connMgr.freeConnection();
} catch ( Exception e ) { }
}
}
return list;
}
}
|
package com.syscxp.biz.web;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.RepositoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
/**
* @Author: sunxuelong.
* @Cretion Date: 2018-08-10.
* @Description: .
*/
@Controller
@RequestMapping("/issues")
public class Index {
@RequestMapping("/index")
public String index() {
return "hello.html";
}
}
|
package de.omikron.client;
import java.io.IOException;
import javax.swing.JComponent;
import javax.swing.plaf.metal.MetalScrollBarUI;
import javax.imageio.ImageIO;
import java.io.File;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.geom.AffineTransform;
public class MyScrollBar {
static class MyScrollbarUI extends MetalScrollBarUI {
private Image imageThumb, imageTrack;
public MyScrollbarUI() {
try {
imageThumb = ImageIO.read(new File("res/thumb.png"));
imageTrack = ImageIO.read(new File("res/track.png"));
} catch (IOException e){}
}
@Override
protected void paintThumb(Graphics g, JComponent c, Rectangle thumbBounds) {
g.translate(thumbBounds.x, thumbBounds.y);
g.setColor( Color.red );
g.drawRect( 0, 0, thumbBounds.width - 2, thumbBounds.height - 1 );
AffineTransform transform = AffineTransform.getScaleInstance((double)thumbBounds.width/imageThumb.getWidth(null),(double)thumbBounds.height/imageThumb.getHeight(null));
((Graphics2D)g).drawImage(imageThumb, transform, null);
g.translate( -thumbBounds.x, -thumbBounds.y );
}
@Override
protected void paintTrack(Graphics g, JComponent c, Rectangle trackBounds) {
g.translate(trackBounds.x, trackBounds.y);
((Graphics2D)g).drawImage(imageTrack,AffineTransform.getScaleInstance(1,(double)trackBounds.height/imageTrack.getHeight(null)),null);
g.translate( -trackBounds.x, -trackBounds.y );
}
}
} |
package com.kieferlam.battlelan.game.states;
import com.kieferlam.battlelan.game.maths.Vector;
import com.kieferlam.battlelan.settings.InputHandler;
import com.kieferlam.battlelan.settings.Settings;
import org.lwjgl.glfw.GLFW;
import org.lwjgl.glfw.GLFWCursorPosCallback;
import org.lwjgl.glfw.GLFWKeyCallback;
import org.lwjgl.glfw.GLFWMouseButtonCallback;
import org.lwjgl.opengl.GL11;
import java.lang.reflect.MalformedParameterizedTypeException;
import java.util.ArrayList;
/**
* Created by Kiefer on 22/03/2015.
*/
public class StateManager {
private ArrayList<State> states;
private int currentState;
private GLFWCursorPosCallback cursorPosCallback;
private GLFWMouseButtonCallback cursorButtonCallback;
private GLFWKeyCallback keyCallback;
public final Settings settings;
private final long mainWindowId;
private InputHandler inputHandler;
public StateManager(long windowID, Settings settings){
mainWindowId = windowID;
states = new ArrayList<>();
currentState = 0;
this.settings = settings;
inputHandler = new InputHandler();
setupInputCallbacks(windowID);
setupStates();
states.get(currentState).init(settings, windowID);
}
private void setupInputCallbacks(long windowID){
cursorPosCallback = new GLFWCursorPosCallback() {
@Override
public void invoke(long window, double xpos, double ypos) {
if(currentState < states.size()) {
states.get(currentState).cursorPositionEvent(window, xpos, ypos);
}
}
};
GLFW.glfwSetCursorPosCallback(windowID, cursorPosCallback);
cursorButtonCallback = new GLFWMouseButtonCallback() {
@Override
public void invoke(long window, int button, int action, int mods) {
inputHandler.cursorButtonEvent(window, button, action, mods, settings);
if (currentState < states.size()) {
states.get(currentState).cursorButtonEvent(windowID, button, action, mods);
}
}
};
GLFW.glfwSetMouseButtonCallback(windowID, cursorButtonCallback);
keyCallback = new GLFWKeyCallback() {
@Override
public void invoke(long window, int key, int scancode, int action, int mods) {
inputHandler.keyEvent(window, key, scancode, action, mods, settings);
if(currentState < states.size()) {
states.get(currentState).keyEvent(windowID, key, scancode, action, mods);
}
}
};
GLFW.glfwSetKeyCallback(windowID, keyCallback);
}
private void setupStates(){
states.add(new WorldState());
}
public void changeState(int state){
currentState = state;
states.get(currentState).init(settings, mainWindowId);
}
public void manage(double delta, double time){
if(currentState < states.size()){
states.get(currentState).logic(delta, time, inputHandler);
GL11.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
states.get(currentState).render(delta);
}
}
public void delete(){
states.forEach((state)->state.delete());
cursorPosCallback.release();
cursorButtonCallback.release();
keyCallback.release();
}
}
|
/*
* //Nama : Hayya Apriligiani Mutiara Riadi
* //Nim : 11200930000003
* //Kelas : 2A - Sistem Informasi
*/
package Person;
/**
*
* @author Hayya AM Riadi
*/
public class Person2 {
public static void main(String[] args)
{
Person1 umur = new Person1();
umur.Person1 ("Joe Smith", 24);
umur.Person2("Mary Sharp", 52);
}
} |
package com.duanc.model.dto;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import org.springframework.stereotype.Component;
import com.duanc.model.User;
import com.duanc.utils.Pagination;
/**
* @Description: 库存
* @author duanchao
*/
@Component("storageDTO")
public class StorageDTO implements Serializable{
private static final long serialVersionUID = 7768626286667545489L;
private Integer id;
private String storageId;
private Integer phoneId;
private Integer count;
private BigDecimal price;
private Integer status;
private String statusName;
private Date createdTime;
private PhoneDTO phone;
private User createUser;
private BigDecimal minPrice;
private BigDecimal maxPrice;
private Pagination pagination;
public BigDecimal getMinPrice() {
return minPrice;
}
public void setMinPrice(BigDecimal minPrice) {
this.minPrice = minPrice;
}
public BigDecimal getMaxPrice() {
return maxPrice;
}
public void setMaxPrice(BigDecimal maxPrice) {
this.maxPrice = maxPrice;
}
public Pagination getPagination() {
return pagination;
}
public void setPagination(Pagination pagination) {
this.pagination = pagination;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getStorageId() {
return storageId;
}
public void setStorageId(String storageId) {
this.storageId = storageId;
}
public Integer getPhoneId() {
return phoneId;
}
public void setPhoneId(Integer phoneId) {
this.phoneId = phoneId;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getStatusName() {
return statusName;
}
public void setStatusName(String statusName) {
this.statusName = statusName;
}
public Date getCreatedTime() {
return createdTime;
}
public void setCreatedTime(Date createdTime) {
this.createdTime = createdTime;
}
public User getCreateUser() {
return createUser;
}
public void setCreateUser(User createUser) {
this.createUser = createUser;
}
public PhoneDTO getPhone() {
return phone;
}
public void setPhone(PhoneDTO phone) {
this.phone = phone;
}
}
|
package com.binarysprite.evemat.entity;
import org.seasar.doma.Dao;
import org.seasar.doma.Delete;
import org.seasar.doma.Insert;
import org.seasar.doma.Script;
import org.seasar.doma.Select;
import org.seasar.doma.Update;
import com.binarysprite.evemat.DB;
/**
*/
@Dao(config = DB.class)
public interface IconDao {
/**
* テーブルを作成します。
*/
@Script
void createTable();
/**
* @param iconId
* @return the Icon entity
*/
@Select
Icon selectById(Integer iconId);
/**
* @param entity
* @return affected rows
*/
@Insert
int insert(Icon entity);
/**
* @param entity
* @return affected rows
*/
@Update
int update(Icon entity);
/**
* @param entity
* @return affected rows
*/
@Delete
int delete(Icon entity);
} |
package cs3500.animator.view;
import java.awt.*;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import cs3500.animator.animation.IAnimation;
import cs3500.animator.shape.IShape;
import cs3500.animator.shape.ReadableShape;
import cs3500.animator.shape.ShapeType;
import cs3500.animator.util.ButtonListener;
public class SvgView implements IView {
private String filePath = "out.svg";
private List<IShape> shapes;
private String finalString;
private int fps = 1;
private boolean loop = false;
private double maxFrame = 0;
public SvgView() {
//to make the contructor public
}
@Override
public void drawForSVG(List<IShape> shape) throws IOException {
this.shapes = shape;
}
public void export() {
String tempFinal = "";
if(loop){
String duration = Double.toString(maxFrame / fps * 1000);
String fauxShape = "<rect>\n"
+ "<animate id=\"base\" begin=\"0;base.end\" "
+ "dur=\"" + duration +"ms\" "
+ "attributeName=\"visibility\" from=\"hide\" to=\"hide\"/>\n" +
"</rect>\n";
tempFinal += fauxShape;
}
for(IShape s : shapes) {
String temp = "";
temp += s.generateSVG(this.fps, loop) + "\n";
for (IAnimation a : s.getAnimations()) {
temp += a.generateSVG(this.fps,loop) + "\n";
}
if(loop){
temp += s.generateLoop();
}
if (s.getType().equals(ShapeType.rectangle)) {
temp += "</rect>";
}
if (s.getType().equals(ShapeType.oval)) {
temp += "</ellipse>";
}
tempFinal = tempFinal + temp;
}
tempFinal = "<svg width=\"1200\" height=\"1200\" version=\"1.1\"" +
" xmlns=\"http://www.w3.org/2000/svg\">" + tempFinal + "</svg>";
this.finalString = tempFinal;
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(filePath));
writer.write(tempFinal);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void drawShapes(ArrayList<ReadableShape> shape) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public void drawString(String in) {
return;
}
@Override
public void setFps(int fps) {
this.fps = fps;
}
@Override
public void setButtonListener(ButtonListener buttonListener) {
throw new UnsupportedOperationException("this doesnt have a buttonlistner");
}
@Override
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public String getFinal(){
return this.finalString;
}
public void setLooping(double maxFrame){
this.loop = true;
this.maxFrame = maxFrame;
}
@Override
public int getEnd() {
throw new UnsupportedOperationException();
}
@Override
public void setShapes(ArrayList<ReadableShape> shapes) {
throw new UnsupportedOperationException();
}
@Override
public boolean scrubContains(Point e) {
throw new UnsupportedOperationException();
}
}
|
package person;
public enum EyesColor {
BLUE("голубые"),
GREEN("зелёные"),
BROWN("карие"),
GRAY("серые"),
DIFF("разные");
private final String colorEyes;
EyesColor(final String colorEyes) {
this.colorEyes = colorEyes;
}
public String getColorEyes() {
return colorEyes;
}
}
|
package com.sullbrothers.crypto.mancer;
import com.sullbrothers.crypto.database.RateHistoryDAO.RateHistory;
import java.util.List;
import weka.classifiers.Classifier;
import weka.core.Attribute;
import weka.core.Instance;
import weka.core.Instances;
/**
* DecisionInterface
*/
public interface DecisionInterface {
/**
* Given a set of historical points, can I tell if performing an action on those points would have been beneficial,
* and can I also tell to what extent?
*
* First pass at this method will return the action that is predicted
*/
String predictResult(MancerState state, int rateHistoryPosition);
Instance getInstanceFromRateHistory(List<RateHistory> historicalRates, List<Attribute> dataVector, List<String> currencies, int rhPos);
/**
* Given a set of historical points, can I bring in data from even further in history to enrich my data for classification?
* First thought for this is to take data from 24 hours prior (roughly 1480 positions in the past) and add that to the data row
* and let the classifier determine it's value. Maybe get points from more than just the last day? Can try several methods and
* plug them into weka and see what happens
*/
//TODO: come up with method sig here
/**
* Determine what action should be performed given current state and position in state
*
* @param state Representation of the current state of the application
* @param rhPos Current position in the state's rate history list (for production this will always be histories.last)
* @param previousAction Action decided on by previous classifier, null if first algo
*/
MancerAction shouldPerform(MancerState state, int rhPos, MancerAction previousAction);
// This implementation creates a J48 decision tree
// TODO: make this a real interface that allows for different classifiers
Classifier buildAndTrainClassifier(Instances trainingSet);
Instances generateDataSet(MancerState state, String relationshipName, double percentToKeep);
void setClassifier(Classifier c);
} |
package com.pinyougou.manager.controller;
import com.alibaba.dubbo.config.annotation.Reference;
import com.pinyougou.pojo.TbOrder;
import com.pinyougou.order.service.OrderService;
import com.pinyougou.pojo.TbSalesreturn;
import com.pinyougou.pojo.group.Order;
import entity.PageResult;
import entity.Result;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import util.ExcelOperateUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/order")
public class OrderController {
@Reference
private OrderService orderService;
@RequestMapping("/findAll")
public List<TbOrder> findAll() {
List<TbOrder> orderList = orderService.findAll();
System.out.println(orderList);
return orderList;
}
/**
* 返回全部列表
*
* @return
*/
@RequestMapping("/findPage")
public PageResult findPage(int page, int rows) {
return orderService.findPage(page, rows);
}
/**
* 条件分页查询
*
* @param order
* @param page
* @param rows
* @return
*/
@RequestMapping("/search")
public PageResult search(@RequestBody TbOrder order, int page, int rows) {
return orderService.findByPage(order, page, rows);
}
/**
* 勾选删除
*
* @param ids
* @return
*/
@RequestMapping("/delete")
public Result delete(Long[] ids) {
try {
orderService.delete(ids);
return new Result(true, "删除成功!");
} catch (Exception e) {
e.printStackTrace();
return new Result(false, "删除失败!");
}
}
/**
* 单点删除
*
* @param id
* @return
*/
@RequestMapping("/deleteOne")
public Result deleteOne(Long id) {
try {
orderService.deleteOne(id);
return new Result(true, "删除成功!");
} catch (Exception e) {
e.printStackTrace();
return new Result(false, "删除失败!");
}
}
/**
* 查询组合实体 wjk
*
* @param id
* @return
*/
@RequestMapping("/findOne")
public Order findOne(Long id) {
System.out.println(id);
return orderService.findOne(id);
}
/**
* 更新状态 wjk
*
* @param id
* @param status
* @return
*/
@RequestMapping("/updateStatus")
public Result updateStatus(Long id, String status) {
try {
orderService.updateStatus(id, (Integer.parseInt(status) + 1) + "");
return new Result(true, "订单状态修改成功");
} catch (Exception e) {
e.printStackTrace();
return new Result(false, "订单状态修改失败");
}
}
/**
* 导出excel报表
*
* @param order
* @return
*/
@RequestMapping("/excel222")//不用的接口
public Result excel(@RequestBody TbOrder order) {
try {
orderService.excel(order);
return new Result(true, "导出Excel成功");
} catch (Exception e) {
e.printStackTrace();
return new Result(false, "导出Excel失败");
}
}
/**
* 查询退货商品详情 wjk
*
* @param id
* @return
*/
@RequestMapping("/findReturnOne")
public TbSalesreturn findReturnOne(String id) {
return orderService.findReturnOne(id);
}
/**
* controller层查询每种状态订单数
*
* @return
*/
@RequestMapping("/findCountOfEveryStatus")
public Map findCountOfEveryStatus() {
Map<String, Integer> map = orderService.findCountOfEveryStatus();
return map;
}
/**
* 导出excel(下载到客户端本地) whk
*
* @param receiver
* @param request
* @param response
*/
@RequestMapping("/excel")
public void exportExcel(String receiver, String receiverMobile, Long orderId, String status, String sourceType, HttpServletRequest request, HttpServletResponse response) {
//根据条件查询出订单集合
//将查询的条件封装到order中
List<TbOrder> list = null;
try {
String ecode_receiver = URLDecoder.decode(receiver, "UTF-8");
TbOrder order = new TbOrder();
order.setReceiver(ecode_receiver);
order.setReceiverMobile(receiverMobile);
order.setOrderId(orderId);
order.setStatus(status);
order.setSourceType(sourceType);
list = orderService.excel(order);
} catch (UnsupportedEncodingException e) {
System.out.println("解码异常,重试");
}
//excel标题
String[] title = {"订单编号", "用户账号", "收货人", "手机号", "订单金额", "支付方式", "订单来源", "订单状态"};
//excel文件名
String fileName = "订单信息表" + System.currentTimeMillis() + ".xls";
//sheet名
String sheetName = "订单信息";
//二维数组用于装要导出的数据
String[][] content = new String[list.size()][title.length];
for (int i = 0; i < list.size(); i++) {
TbOrder obj = list.get(i);
content[i][0] = obj.getOrderId() + "";
content[i][1] = obj.getUserId() + "";
content[i][2] = obj.getReceiver() + "";
content[i][3] = obj.getReceiverMobile() + "";
content[i][4] = obj.getPayment() + "";
if ("1".equals(obj.getPaymentType() + "")) {
content[i][5] = "在线支付";
} else if ("2".equals(obj.getPaymentType() + "")) {
content[i][5] = "货到付款";
} else {
content[i][5] = "其他";
}
if ("2".equals(obj.getSourceType() + "")) {
content[i][6] = "pc端";
} else {
content[i][6] = "其他";
}
if ("1".equals(obj.getStatus() + "")) {
content[i][7] = "未付款";
} else if ("2".equals(obj.getStatus() + "")) {
content[i][7] = "已付款";
} else if ("3".equals(obj.getStatus() + "")) {
content[i][7] = "未发货";
} else if ("4".equals(obj.getStatus() + "")) {
content[i][7] = "已发货";
} else if ("5".equals(obj.getStatus() + "")) {
content[i][7] = "交易成功";
} else if ("6".equals(obj.getStatus() + "")) {
content[i][7] = "交易关闭";
} else if ("7".equals(obj.getStatus() + "")) {
content[i][7] = "待评价";
} else {
content[i][7] = "其他";
}
}
//创建HSSFWorkbook
HSSFWorkbook wb = ExcelOperateUtil.getHSSFWorkbook(sheetName, title, content, null);
//响应到客户端
try {
this.setResponseHeader(response, fileName);
OutputStream os = response.getOutputStream();
wb.write(os);
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//发送响应流方法
public void setResponseHeader(HttpServletResponse response, String fileName) {
try {
try {
fileName = new String(fileName.getBytes(), "ISO8859-1");
} catch (Exception e) {
e.printStackTrace();
}
response.setContentType("application/octet-stream;charset=ISO8859-1");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
response.addHeader("Pargam", "no-cache");
response.addHeader("Cache-Control", "no-cache");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
|
package com.beike.wap.entity;
import java.io.Serializable;
import java.sql.Date;
/**
* <p>
* Title:WAP端数据库保存信息
* </p>
* <p>
* Description:
* </p>
* <p>
* Copyright: Copyright (c) 2011
* </p>
* <p>
* Company: qianpin.com
* </p>
*
* @date 2011-09-23
* @author lvjx
* @version 1.0
*/
@SuppressWarnings("serial")
public class MWapType implements Serializable {
private int id;
private int typeId;
private String typeUrl;
private int typeType;
private int typeFloor;
private int typePage;
private Date typeDate;
private String typeArea;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getTypeId() {
return typeId;
}
public void setTypeId(int typeId) {
this.typeId = typeId;
}
public String getTypeUrl() {
return typeUrl;
}
public void setTypeUrl(String typeUrl) {
this.typeUrl = typeUrl;
}
public int getTypeType() {
return typeType;
}
public void setTypeType(int typeType) {
this.typeType = typeType;
}
public int getTypeFloor() {
return typeFloor;
}
public void setTypeFloor(int typeFloor) {
this.typeFloor = typeFloor;
}
public int getTypePage() {
return typePage;
}
public void setTypePage(int typePage) {
this.typePage = typePage;
}
public Date getTypeDate() {
return typeDate;
}
public void setTypeDate(Date typeDate) {
this.typeDate = typeDate;
}
public String getTypeArea() {
return typeArea;
}
public void setTypeArea(String typeArea) {
this.typeArea = typeArea;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result
+ ((typeArea == null) ? 0 : typeArea.hashCode());
result = prime * result
+ ((typeDate == null) ? 0 : typeDate.hashCode());
result = prime * result + typeFloor;
result = prime * result + typeId;
result = prime * result + typePage;
result = prime * result + typeType;
result = prime * result + ((typeUrl == null) ? 0 : typeUrl.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MWapType other = (MWapType) obj;
if (id != other.id)
return false;
if (typeArea == null) {
if (other.typeArea != null)
return false;
} else if (!typeArea.equals(other.typeArea))
return false;
if (typeDate == null) {
if (other.typeDate != null)
return false;
} else if (!typeDate.equals(other.typeDate))
return false;
if (typeFloor != other.typeFloor)
return false;
if (typeId != other.typeId)
return false;
if (typePage != other.typePage)
return false;
if (typeType != other.typeType)
return false;
if (typeUrl == null) {
if (other.typeUrl != null)
return false;
} else if (!typeUrl.equals(other.typeUrl))
return false;
return true;
}
@Override
public String toString() {
return "WapType [id=" + id + ", typeArea=" + typeArea + ", typeDate="
+ typeDate + ", typeFloor=" + typeFloor + ", typeId=" + typeId
+ ", typePage=" + typePage + ", typeType=" + typeType
+ ", typeUrl=" + typeUrl + "]";
}
}
|
/*
* Copyright © 2020-2022 ForgeRock AS (obst@forgerock.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 com.forgerock.sapi.gateway.ob.uk.common.datamodel.converter.event;
import com.forgerock.sapi.gateway.ob.uk.common.datamodel.event.FREventPolling;
import com.forgerock.sapi.gateway.ob.uk.common.datamodel.event.FREventPollingError;
import uk.org.openbanking.datamodel.event.OBEventPolling1;
import uk.org.openbanking.datamodel.event.OBEventPolling1SetErrs;
import java.util.Map;
import java.util.stream.Collectors;
public class FREventPollingConverter {
public static FREventPolling toFREventPolling(OBEventPolling1 obEventPolling) {
return obEventPolling == null ? null : FREventPolling.builder()
.maxEvents(obEventPolling.getMaxEvents())
.returnImmediately(obEventPolling.isReturnImmediately())
.ack(obEventPolling.getAck())
.setErrs(toFREventPollingErrors(obEventPolling.getSetErrs()))
.build();
}
public static Map<String, FREventPollingError> toFREventPollingErrors(Map<String, OBEventPolling1SetErrs> setErrs) {
return setErrs == null ? null : setErrs.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, e -> toFREventPollingError(e.getValue())));
}
public static FREventPollingError toFREventPollingError(OBEventPolling1SetErrs eventPolling1SetErrs) {
return eventPolling1SetErrs == null ? null : FREventPollingError.builder()
.error(eventPolling1SetErrs.getErr())
.description(eventPolling1SetErrs.getDescription())
.build();
}
}
|
package com.meehoo.biz.core.basic.remote;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.meehoo.biz.core.basic.param.HttpResult;
import com.meehoo.biz.core.basic.param.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
import java.util.Map;
/**
* @author zc
* @date 2020-08-10
*/
//@Component
@Slf4j
public class BasePost extends BaseHttp{
private final RestTemplate restTemplate;
private final Gson gson;
private final BaseRemoteService remoteService;
public BasePost(BaseRemoteService remoteService) {
this.restTemplate = new RestTemplate();
this.gson = new Gson();
this.remoteService = remoteService;
}
private String basePost(String path,Object body){
String url = remoteService.postUrl(path);
HttpResult<Object> httpResult = null;
if(body instanceof Map){
// 表单
HttpEntity<Map<String,Object>> request = remoteService.postFormHttpEntity((Map<String, Object>) body);
ResponseEntity<HttpResult<Object>> responseEntity = restTemplate.exchange(url, HttpMethod.POST, request, new ParameterizedTypeReference<HttpResult<Object>>() {});
httpResult = responseEntity.getBody();
}else{
// json
HttpEntity<Object> request = remoteService.postJsonHttpEntity(body);
ResponseEntity<HttpResult<Object>> responseEntity = restTemplate.exchange(url, HttpMethod.POST, request, new ParameterizedTypeReference<HttpResult<Object>>() {
});
httpResult = responseEntity.getBody();
}
if (httpResult==null){
log.error("数据中台无法连接:"+path);
throw new RuntimeException("网络连接错误");
} else if (httpResult.getFlag()==0){
Object data = httpResult.getData();
return gson.toJson(data);
}else{
log.error("数据中台报错","path:\n"+httpResult.getMsg());
throw new RuntimeException("获得数据错误");
}
}
public <T> PageResult<T> forPageResult(String path, Object body){
String json = basePost(path, body);
PageResult<T> list = gson.fromJson(json,new TypeToken<PageResult<T>>(){}.getType());
return list;
}
public <T> List<T> forList(String path,Object body) throws Exception {
String json = basePost(path, body);
List<T> list = gson.fromJson(json,new TypeToken<List<T>>(){}.getType());
return list;
}
public <T> T forEntity(String path,Object body,Class<T> tClass){
String json = basePost(path, body);
T t = gson.fromJson(json,tClass);
return t;
}
public String fileForString(String path, MultipartFile file, Map<String,Object> params){
// String url = tdcURL + "/"+path;
// //设置请求头
// HttpHeaders headers = new HttpHeaders();
// MediaType type = MediaType.parseMediaType("multipart/form-data");
// headers.setContentType(type);
//
// //设置请求体,注意是LinkedMultiValueMap
// FileSystemResource fileSystemResource = new FileSystemResource(filePath+"/"+fileName);
// MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
// form.add("excel", fileSystemResource);
// form.add("filename",file.getOriginalFilename());
// for (Map.Entry<String, Object> entry : params.entrySet()) {
// form.add(entry.getKey(),entry.getValue());
// }
//
// //用HttpEntity封装整个请求报文
// HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(form, headers);
//
// String s = restTemplate.postForObject(url, files, String.class);
// return s;
throw new RuntimeException("不可用");
}
@Override
protected void log(String s, Object o) {
log.error(s,o);
}
}
|
package com.learn.leetcode.week3;
import java.util.Arrays;
public class SolutionRob {
/**
* 你是一个专业的小偷,计划偷窃沿街的房屋。
* 每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。
* <p>
* 给定一个代表每个房屋存放金额的非负整数数组,
* 计算你 不触动警报装置的情况下 ,一夜之内能够偷窃到的最高金额。
* f(n) = max(f(n-2) + A[n],f(n-1))
* F(n) = Max(f(n))
* @param nums
* @return
*/
public static int rob(int[] nums) {
if(nums.length == 0)
return 0;
int[] dp = new int[nums.length];
Arrays.fill(dp,-1);
return doRob(nums,dp,nums.length-1);
}
private static int doRob(int[] nums,int[] dp,int n){
int rval = 0;
if(n<0)
return Integer.MIN_VALUE;
else if(n == 0)
rval = nums[0];
else if(n == 1)
rval = Math.max(nums[0],nums[1]);
else if(dp[n]>=0){
rval = dp[n];
}else{
rval = Math.max(doRob(nums,dp,n-2) +nums[n],doRob(nums,dp,n-1));
}
dp[n] = rval;
return rval;
}
}
|
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
// write your code here
Scanner scn = new Scanner(System.in);
int n =scn.nextInt();
int[]nums = new int[n];
for(int i=0; i< n; i++){
nums[i] = scn.nextInt();
}
if(n==0){
System.out.println(0);
}else if(n==1){
System.out.println(nums[0]);
}
else{
int dp[] = new int[n];
dp[0] = nums[0];
int Sum=0;
for(int i=1; i<n; i++){
int maxSum = 0;
for(int j=0; j<i; j++){
if(nums[i] >= nums[j] && dp[j] > maxSum){
maxSum = dp[j];
}
}
dp[i] = maxSum + nums[i];
Sum = Math.max(Sum, dp[i]);
}
System.out.println(Sum);
}
}
} |
package com.example.testproject.main;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Toast;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.testproject.R;
import com.example.testproject.dialog_detail.DialogDetailActivity;
import com.example.testproject.main.adapter.RecyclerViewDialogListAdapter;
import com.example.testproject.utils.objects.MainDialogListItem;
import java.util.ArrayList;
import java.util.List;
public class DialogListFragment extends Fragment {
private RecyclerView rvDialog;
public DialogListFragment() {
// Required empty public constructor
}
public static DialogListFragment newInstance() {
return new DialogListFragment();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main_dialog_list, container, false);
rvDialog = view.findViewById(R.id.rv_dialog_list);
RecyclerViewDialogListAdapter adapter = new RecyclerViewDialogListAdapter(getDialogList());
adapter.setListener(new RecyclerViewDialogListAdapter.OnItemClickListener() {
@Override
public void onClickItem(MainDialogListItem item) {
DialogDetailActivity.start(getActivity(), item);
}
@Override
public void onClickMinus(MainDialogListItem item) {
Toast.makeText(getActivity(), "minus", Toast.LENGTH_SHORT).show();
}
@Override
public void onClickDelete(MainDialogListItem item) {
Toast.makeText(getActivity(), "delete", Toast.LENGTH_SHORT).show();
}
});
rvDialog.setHasFixedSize(true);
rvDialog.setLayoutManager(new LinearLayoutManager(getActivity()));
rvDialog.setAdapter(adapter);
return view;
}
private List<MainDialogListItem> getDialogList() {
List<MainDialogListItem> list = new ArrayList<>();
list.add(new MainDialogListItem(true, "Сегодня", "", 0, ""));
list.add(new MainDialogListItem(false, "+7 965 407 00 39", "Привет, увидел ваше объявление на Авито увидел ваше объявление на Авито", R.mipmap.ic_selected, "15:30"));
list.add(new MainDialogListItem(false, "+7 965 407 00 39", "Привет, увидел ваше объявление на Авито увидел ваше объявление на Авито", R.mipmap.ic_not_selected, "15:30"));
list.add(new MainDialogListItem(false, "+7 965 407 00 39", "Привет, увидел ваше объявление на Авито увидел ваше объявление на Авито", R.mipmap.ic_selected, "15:30"));
list.add(new MainDialogListItem(false, "+7 965 407 00 39", "Привет, увидел ваше объявление на Авито увидел ваше объявление на Авито", R.mipmap.ic_not_selected, "15:30"));
list.add(new MainDialogListItem(false, "+7 965 407 00 39", "Привет, увидел ваше объявление на Авито увидел ваше объявление на Авито", R.mipmap.ic_selected, "15:30"));
list.add(new MainDialogListItem(false, "+7 965 407 00 39", "Привет, увидел ваше объявление на Авито увидел ваше объявление на Авито", R.mipmap.ic_not_selected, "15:30"));
list.add(new MainDialogListItem(false, "+7 965 407 00 39", "Привет, увидел ваше объявление на Авито увидел ваше объявление на Авито", R.mipmap.ic_selected, "15:30"));
list.add(new MainDialogListItem(false, "+7 965 407 00 39", "Привет, увидел ваше объявление на Авито увидел ваше объявление на Авито", R.mipmap.ic_not_selected, "15:30"));
list.add(new MainDialogListItem(true, "Вчера", "", 0, ""));
list.add(new MainDialogListItem(false, "+7 965 407 00 39", "Привет, увидел ваше объявление на Авито увидел ваше объявление на Авито", R.mipmap.ic_selected, "15:30"));
list.add(new MainDialogListItem(false, "+7 965 407 00 39", "Привет, увидел ваше объявление на Авито увидел ваше объявление на Авито", R.mipmap.ic_not_selected, "15:30"));
list.add(new MainDialogListItem(false, "+7 965 407 00 39", "Привет, увидел ваше объявление на Авито увидел ваше объявление на Авито", R.mipmap.ic_selected, "15:30"));
list.add(new MainDialogListItem(false, "+7 965 407 00 39", "Привет, увидел ваше объявление на Авито увидел ваше объявление на Авито", R.mipmap.ic_not_selected, "15:30"));
list.add(new MainDialogListItem(false, "+7 965 407 00 39", "Привет, увидел ваше объявление на Авито увидел ваше объявление на Авито", R.mipmap.ic_selected, "15:30"));
list.add(new MainDialogListItem(false, "+7 965 407 00 39", "Привет, увидел ваше объявление на Авито увидел ваше объявление на Авито", R.mipmap.ic_not_selected, "15:30"));
list.add(new MainDialogListItem(false, "+7 965 407 00 39", "Привет, увидел ваше объявление на Авито увидел ваше объявление на Авито", R.mipmap.ic_selected, "15:30"));
list.add(new MainDialogListItem(false, "+7 965 407 00 39", "Привет, увидел ваше объявление на Авито увидел ваше объявление на Авито", R.mipmap.ic_not_selected, "15:30"));
return list;
}
@Override
public void onResume() {
super.onResume();
Window window = getActivity().getWindow();
window.setStatusBarColor(Color.parseColor("#FA00D43B"));
}
} |
package exam.iz0_803;
public class Exam_028 {
}
/*
Which two may precede the word "class" in a class declaration?
A. local
B. public
C. static
D. volatile
E. synchronized
Answer: BC
*/
|
package sop.persistence.beans;
import java.math.BigDecimal;
import java.util.Date;
/**
* @Author: LCF
* @Date: 2020/1/9 10:01
* @Package: sop.persistence.beans
*/
public class PurchaseOrderSbk extends BaseBean {
private static final long serialVersionUID = -185248557316796065L;
private Date po3ExpShpDate;
private BigDecimal po3ExpShpQty;
private String po3No;
private String po3Remk;
private Integer id;
public PurchaseOrderSbk() {
}
public PurchaseOrderSbk(SaleOrderSbk saleOrderSbk) {
this.po3ExpShpDate = saleOrderSbk.getSo3ExpShpDate();
this.po3ExpShpQty = saleOrderSbk.getSo3ExpShpQty();
this.po3Remk = saleOrderSbk.getSo3Remk();
}
public Date getPo3ExpShpDate() {
return po3ExpShpDate;
}
public void setPo3ExpShpDate(Date po3ExpShpDate) {
this.po3ExpShpDate = po3ExpShpDate;
}
public BigDecimal getPo3ExpShpQty() {
return po3ExpShpQty;
}
public void setPo3ExpShpQty(BigDecimal po3ExpShpQty) {
this.po3ExpShpQty = po3ExpShpQty;
}
public String getPo3No() {
return po3No;
}
public void setPo3No(String po3No) {
this.po3No = po3No;
}
public String getPo3Remk() {
return po3Remk;
}
public void setPo3Remk(String po3Remk) {
this.po3Remk = po3Remk;
}
@Override
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
|
package arrays;
import java.util.Scanner;
/*
-Write a method called readIntegers() with a parameter called count that represents how many integers the user needs to enter.
-The method needs to read from the console until all the numbers are entered, and then return an array containing the numbers entered.
-Write a method findMin() with the array as a parameter. The method needs to return the minimum value in the array.
-In the main() method read the count from the console and call the method readIntegers() with the count parameter.
-Then call the findMin() method passing the array returned from the call to the readIntegers() method.
-Finally, print the minimum element in the array.
Tips:
-Assume that the user will only enter numbers, never letters
-For simplicity, create a Scanner as a static field to help with data input
-Create a new console project with the name ÅeMinElementChallengeÅf
*/
public class FindMinValue {
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Enter the number of elements to be compared \r");
int count = scanner.nextInt();
scanner.nextLine();
int[] myArray = readIntegers(count);
int min = findMin(myArray);
System.out.println("The minimum element is "+min);
}
private static int findMin(int[] myArray) {
int minValue = Integer.MAX_VALUE;
for(int i:myArray){
if(minValue>i){
minValue=i;
}
}
return minValue;
}
private static int[] readIntegers(int size) {
System.out.println("Enter "+size+ " integer values \r");
int[] intArray = new int[size];
for(int i=0; i<size;i++){
intArray[i] = scanner.nextInt();
scanner.nextLine();
}
return intArray;
}
}
|
package generics;
import java.io.Serializable;
public class Test_Generics {
public interface Interface<X extends Number> {
public X getValue();
public void setValue(X value);
}
public static class Super<X, Y, Z extends Serializable> {
public void print(X param1, Y param2, Z param3) {
System.out.println(param1 + " - " + param2 + " - " + param3);
}
}
public static class Sub<X extends Number, Y, W extends Serializable> extends Super<X, Y, W> implements Interface<X> {
private X value;
public X getValue() {
return value;
}
public void setValue(X value) {
this.value = value;
}
}
public static void main(String ... args) {
Super s = new Super();
//Sub<String, Integer, Double> s2 = new Sub<String, Integer, Double>();
//s2.print(new Integer(1), "teste", new Double(2.5));
//s.prin
// ArrayList<String> strings = new ArrayList<String>();
// strings.add("Jo�o");
// strings.add("Maria");
// strings.add("Jos�");
// for (String x : strings) {
// System.out.println(x);
// }
//
// ArrayList<Integer> inteiros = new ArrayList<Integer>();
// inteiros.add(1);
// inteiros.add(2);
// inteiros.add(3);
// ArrayList<? extends Number> numeros = inteiros;
// System.out.println(numeros);
//
// Sub subClass = new Sub();
// subClass.setValue(12);
// System.out.println(subClass.getValue());
// subClass.print(13, "teste", 2.52);
}
}
|
package com.edasaki.rpg.vip;
import com.edasaki.rpg.AbstractManagerRPG;
import com.edasaki.rpg.SakiRPG;
public class BoostManager extends AbstractManagerRPG {
public BoostManager(SakiRPG plugin) {
super(plugin);
}
@Override
public void initialize() {
}
// public static void openMenu(Player p, PlayerData pd) {
// Inventory i = Bukkit.createInventory(null, InventoryType.ANVIL, "Item Renaming");
// p.openInventory(i);
//
// }
}
|
package net.earthcomputer.collectvis.visualizers;
import java.awt.*;
import java.util.function.Function;
public class TransformingVisualizer<A, B> extends Visualizer<A> {
private Function<? super A, ? extends B> transformer;
private Visualizer<? super B> delegate;
public TransformingVisualizer(Function<? super A, ? extends B> transformer, Visualizer<? super B> delegate) {
this.transformer = transformer;
this.delegate = delegate;
}
@Override
public void layout(A object, Graphics2D g) {
delegate.layout(transformer.apply(object), g);
}
@Override
public Dimension getContentSize() {
return delegate.getTotalSize();
}
@Override
public void drawContent(Graphics2D g, int x, int y) {
delegate.draw(g, x, y);
}
}
|
package controller;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import beans.Funcionario;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.stage.Stage;
import negocio.FachadaCalcada;
import negocio.ICalcada;
import telas.TelaCadastroFuncionario;
import telas.TelaLoginFuncionario;
public class TelaCadastroFuncionarioController extends Saida implements Initializable{
@FXML private TextField txtNome;
@FXML private TextField txtEmail;
@FXML private TextField txtCpf;
@FXML private Button btnCadastro;
@FXML private Button btnVoltar;
ICalcada fachada;
FachadaCalcada fachadacalcada;
@Override
public void initialize(URL url, ResourceBundle rb) {
btnVoltar.setOnMouseClicked((MouseEvent e)->{
voltar();
fechar();
});
btnVoltar.setOnKeyPressed((KeyEvent e) -> {
if(e.getCode() == KeyCode.ENTER)
{
voltar();
fechar();
}
});
btnCadastro.setOnMouseClicked((MouseEvent e) -> {
try {
fachada = FachadaCalcada.getInstance();
Funcionario f = new Funcionario(txtNome.getText(), txtEmail.getText(), txtCpf.getText());
fachada.cadastrar(f);
} catch (ClassNotFoundException ex) {
Logger.getLogger(TelaCadastroFuncionarioController.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(TelaCadastroFuncionarioController.class.getName()).log(Level.SEVERE, null, ex);
}
});
btnCadastro.setOnKeyPressed((KeyEvent e) -> {
if(e.getCode() == KeyCode.ENTER)
{
try {
fachada = FachadaCalcada.getInstance();
Funcionario f = new Funcionario(txtNome.getText(), txtEmail.getText(), txtCpf.getText());
fachada.cadastrar(f);
} catch (ClassNotFoundException ex) {
Logger.getLogger(TelaCadastroFuncionarioController.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(TelaCadastroFuncionarioController.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
public void fechar ()
{
TelaCadastroFuncionario.getStage().close();
}
public void voltar(){
TelaLoginFuncionario l = new TelaLoginFuncionario();
try {
l.start(new Stage());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
/*
* Copyright 2020 WeBank
*
* 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.webank.wedatasphere.schedulis.common.system.common;
import com.webank.wedatasphere.schedulis.common.system.SystemUserManagerException;
import com.webank.wedatasphere.schedulis.common.system.SystemManager;
import com.webank.wedatasphere.schedulis.common.system.entity.DepartmentMaintainer;
import com.webank.wedatasphere.schedulis.common.system.entity.WebankDepartment;
import com.webank.wedatasphere.schedulis.common.system.entity.WebankUser;
import com.webank.wedatasphere.schedulis.common.system.entity.WtssUser;
import azkaban.user.User;
import azkaban.user.UserManager;
import azkaban.utils.Props;
import java.util.List;
import javax.inject.Inject;
/**
* 过渡接口服务工具类
*/
public class TransitionService {
private UserManager userManager;
private SystemManager systemManager;
private Props props;
@Inject
public TransitionService(UserManager userManager, SystemManager systemManager, Props props) {
this.userManager = userManager;
this.systemManager = systemManager;
this.props = props;
}
public SystemManager getSystemManager() {
return systemManager;
}
public UserManager getUserManager() {
return userManager;
}
/**
* 根据用户名查找所在部门
* @param userName
* @return
* @throws SystemUserManagerException
*/
public String getUserDepartmentByUsername(String userName) throws SystemUserManagerException {
return this.systemManager.getUserDepartmentByUsername(userName);
}
/**
* 根据用户名查找WTSS用户
* @param userName
* @return
* @throws SystemUserManagerException
*/
public WtssUser getSystemUserByUserName(String userName) throws SystemUserManagerException {
return this.systemManager.getSystemUserByUserName(userName);
}
/**
* 根据用户ID查找WTSS用户
* @param userId
* @return
* @throws SystemUserManagerException
*/
public WtssUser getSystemUserById(String userId) throws SystemUserManagerException {
return this.systemManager.getSystemUserById(userId);
}
/**
* 根据用户名查找webank用户
* @param userName
* @return
*/
public WebankUser getWebankUserByUserName(String userName) {
return this.systemManager.getWebankUserByUserName(userName);
}
/**
* 根据部门编号查找所在部门
* @param departmentId
* @return
* @throws SystemUserManagerException
*/
public WebankDepartment getWebankDepartmentByDpId(Integer departmentId) throws SystemUserManagerException {
return this.systemManager.getWebankDepartmentByDpId(departmentId);
}
/**
* 根据用户名查找所有需要运维的部门编号
* @param userName
* @return
* @throws SystemUserManagerException
*/
public List<Integer> getDepartmentMaintainerDepListByUserName(String userName) throws SystemUserManagerException {
return this.systemManager.getDepartmentMaintainerDepListByUserName(userName);
}
/**
* 根据用户名查找所有需要运维的部门编号
* @param departmentId
* @return
* @throws SystemUserManagerException
*/
public String getDepartmentMaintainerByDepId(long departmentId) throws SystemUserManagerException {
DepartmentMaintainer departmentMaintainer = this.systemManager.getDepMaintainerByDepId(departmentId);
if (departmentMaintainer != null) {
return departmentMaintainer.getOpsUser();
} else {
return null;
}
}
/**
* 根据部门查找用户
* @param depId
* @return
*/
public List<WtssUser> getSystemUserByDepId(Integer depId) {
return this.systemManager.getSystemUserByDepartmentId(depId);
}
public Boolean validateProxyUser(String proxyUserName, User user) {
return this.userManager.validateProxyUser(proxyUserName, user);
}
public Boolean validateGroup(String group) {
return this.userManager.validateGroup(group);
}
public Boolean validateUser(String userName) {
return this.userManager.validateUser(userName);
}
}
|
package com.juannarvaez.taskworkout.model.entily;
import java.io.Serializable;
public class Protocolos implements Serializable {
private String tituloProtocolo;
private String descripcionProtocolo;
private String requerimientosProtocolo;
private String adicionalProtocolo;
private String urlProtocolo;
private String idProtocolo;
public Protocolos(String tituloProtocolo, String descripcionProtocolo, String requerimientoProtocolos, String adicionalProtocolo, String urlProtocolo) {
this.tituloProtocolo = tituloProtocolo;
this.descripcionProtocolo = descripcionProtocolo;
this.requerimientosProtocolo = requerimientosProtocolo;
this.adicionalProtocolo = adicionalProtocolo;
this.urlProtocolo = urlProtocolo;
this.idProtocolo = "";
}
public Protocolos() {
this.tituloProtocolo = "";
this.descripcionProtocolo = "";
this.requerimientosProtocolo = "";
this.adicionalProtocolo = "";
this.urlProtocolo = "";
this.idProtocolo = "";
}
public String getTituloProtocolo() {
return tituloProtocolo;
}
public void setTituloProtocolo(String tituloProtocolo) {
this.tituloProtocolo = tituloProtocolo;
}
public String getDescripcionProtocolo() {
return descripcionProtocolo;
}
public void setDescripcionProtocolo(String descripcionProtocolo) {
this.descripcionProtocolo = descripcionProtocolo;
}
public String getRequerimientosProtocolo() {
return requerimientosProtocolo;
}
public void setRequerimientosProtocolo(String requerimientosProtocolo) {
this.requerimientosProtocolo = requerimientosProtocolo;
}
public String getAdicionalProtocolo() {
return adicionalProtocolo;
}
public void setAdicionalProtocolo(String adicionalProtocolo) {
this.adicionalProtocolo = adicionalProtocolo;
}
public String getUrlProtocolo() {
return urlProtocolo;
}
public void setUrlProtocolo(String urlProtocolo) {
this.urlProtocolo = urlProtocolo;
}
public String getIdProtocolo() {
return idProtocolo;
}
public void setIdProtocolo(String idProtocolo) {
this.idProtocolo = idProtocolo;
}
}
|
package ggwozdz.nordea.syntax;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Stream;
import com.google.common.base.Joiner;
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import com.google.common.base.Splitter;
import com.google.common.collect.ComparisonChain;
import com.google.common.collect.Lists;
public final class WordList implements Comparable<WordList>{
private static final Joiner JOINER = Joiner.on(",");
private static final String SEPARATOR_PATTERN = "\\W";
private final List<String> sortedWords;
private final int hashCode;
private WordList(String sentence){
this.sortedWords = splitSentenceAndSortWords(sentence.trim());
this.hashCode = this.sortedWords.hashCode();
}
public static WordList from(String sentence){
return new WordList(sentence);
}
public void forEach(Consumer<String> action) {
this.sortedWords.forEach(action);
}
public Stream<String> stream(){
return this.sortedWords.stream();
}
public List<String> getSortedWords() {
return sortedWords;
}
private List<String> splitSentenceAndSortWords(String sentence) {
List<String> words = Lists.newArrayList(Splitter.onPattern(SEPARATOR_PATTERN)
.trimResults()
.omitEmptyStrings()
.split(sentence));
words.sort((x,y) -> x.toLowerCase().compareTo(y.toLowerCase()));
return words;
}
@Override
public int hashCode() {
return this.hashCode;
}
@Override
public boolean equals(Object obj) {
if(this == obj){
return true;
}else if(obj instanceof WordList){
return Objects.equal(sortedWords, ((WordList)obj).sortedWords);
}else{
return false;
}
}
@Override
public int compareTo(WordList other) {
return ComparisonChain.start()
.compare(JOINER.join(this.sortedWords), JOINER.join(other.sortedWords))
.result();
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("sortedWords", this.sortedWords)
.toString();
}
}
|
package casestudy;
import static org.junit.Assert.*;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class cs2 {
WebDriver driver=null;
@Given("^user click on sign in$")
public void user_click_on_sign_in(){
System.setProperty("webdriver.chrome.driver", "C:\\Users\\Training_b6b.01.16\\Desktop\\Browser Drivers\\chromedriver_win32\\chromedriver.exe");
driver=new ChromeDriver();
driver.get("http://10.232.237.143:443/TestMeApp/fetchcat.htm");
driver.manage().window().maximize();
driver.findElement(By.xpath("//a[@href='login.htm']")).click();
}
@When("^user enters username \"([^\"]*)\"$")
public void user_enters_username(String arg1){
driver.findElement(By.id("userName")).sendKeys(arg1);
}
@When("^user enters \"([^\"]*)\"$")
public void user_enters(String arg1){
driver.findElement(By.id("password")).sendKeys(arg1);
}
@Then("^user click login button$")
public void user_click_login_button(){
driver.findElement(By.xpath("//input[@value='Login']")).click();
}
} |
/**
* Copyright 2015 Thomas Cashman
*/
package org.protogen.compiler.core;
import org.protogen.compiler.core.condition.Condition;
import org.protogen.compiler.core.output.OutputWriter;
/**
*
* @author Thomas Cashman
*/
public class Extend extends Protocol implements DslElement {
private final Condition condition;
public Extend(String name, Condition condition) {
super(name);
this.condition = condition;
}
@Override
public void accept(OutputWriter writer) {
writer.visit(this);
}
public Condition getCondition() {
return condition;
}
}
|
package xiao.yang.microservice.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.aop.Advisor;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.interceptor.*;
import javax.sql.DataSource;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean (name = "dataSource")
public DataSource druid(){
return new DruidDataSource();
}
//配置Druid的监控
//1、配置一个管理后台的Servlet
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
Map<String,String> initParams = new HashMap<>();
initParams.put("loginUsername","admin");
initParams.put("loginPassword","123456");
// initParams.put("allow","");// 设置允许访问 默认就是允许所有访问
// initParams.put("deny","192.168.15.21");// 设置不允许访问
bean.setInitParameters(initParams);
return bean;
}
//2、配置一个web监控的filter
@Bean
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
Map<String,String> initParams = new HashMap<>();
initParams.put("exclusions","*.js,*.css,/druid/*");
bean.setInitParameters(initParams);
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}
// @Bean(name = "sqlSessionFactory")
// public SqlSessionFactory sqlSessionFactoryBean(@Qualifier("dataSource") DataSource dataSource) throws Exception {
// SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
// sqlSessionFactoryBean.setDataSource(dataSource);
// PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
//// sqlSessionFactoryBean.setConfigLocation(new ClassPathResource("mybatis/mybatis-config.xml"));
// sqlSessionFactoryBean.setTypeAliasesPackage("xiao.yang.microservice.mapper");
// sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:mapper/**/*.xml"));
// return sqlSessionFactoryBean.getObject();
// }
//
// @Bean
// public MapperScannerConfigurer mapperScannerConfigurer() {
// MapperScannerConfigurer cfg = new MapperScannerConfigurer();
// cfg.setBasePackage("xiao.yang.microservice.mapper");
// cfg.setSqlSessionFactoryBeanName("sqlSessionFactory");
// return cfg;
// }
////
@Bean(name ="txManager")
public PlatformTransactionManager annotationDrivenTransactionManager(@Qualifier("dataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
private static final int TX_METHOD_TIMEOUT = 50000;//xiao.yang.microservice.service.DeptService
private static final String AOP_POINTCUT_EXPRESSION = "execution(* xiao.yang.microservice.service.*.*(..))";
// 事务的实现Advice
@Bean
public TransactionInterceptor txAdvice(@Qualifier("txManager")PlatformTransactionManager m) {
NameMatchTransactionAttributeSource source = new NameMatchTransactionAttributeSource();
RuleBasedTransactionAttribute readOnlyTx = new RuleBasedTransactionAttribute();
readOnlyTx.setReadOnly(true);
readOnlyTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED);
RuleBasedTransactionAttribute requiredTx = new RuleBasedTransactionAttribute();
requiredTx.setRollbackRules(Collections.singletonList(new RollbackRuleAttribute(Exception.class)));
requiredTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
requiredTx.setTimeout(TX_METHOD_TIMEOUT);
Map<String, TransactionAttribute> txMap = new HashMap<>();
txMap.put("add*", requiredTx);
txMap.put("save*", requiredTx);
txMap.put("insert*", requiredTx);
txMap.put("update*", requiredTx);
txMap.put("delete*", requiredTx);
txMap.put("get*", readOnlyTx);
txMap.put("query*", readOnlyTx);
source.setNameMap(txMap);
TransactionInterceptor txAdvice = new TransactionInterceptor(m, source);
return txAdvice;
}
// 切面的定义,pointcut及advice
@Bean
public Advisor txAdviceAdvisor(@Qualifier("txAdvice") TransactionInterceptor txAdvice) {
AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
pointcut.setExpression(AOP_POINTCUT_EXPRESSION);
return new DefaultPointcutAdvisor(pointcut, txAdvice);
}
}
|
class A{
int a=10;
int b=30;
void display(){
System.out.println("a "+a);
System.out.println("b "+b);
}
}
class Amain{
public static void main(String args[]){
//A obj;
String a[] ={"Hello","World"};//creating a string array to pass as argument to main
A obj = new A(); //instantiating for class A
Amain Am = new Amain(); //instantiating for class Amain
obj.display(); //calling display method of class A
Am.main(a); //recursive call?? whether it will loop or only once?
System.out.println(args[0]); //what is the value of args[0]
}
} |
import java.util.Scanner;
public class Courses {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("What is the description of the course? ");
String colCourse = scan.nextLine();
int indexSpace1 = colCourse.indexOf(' ');
int indexSpace2 = colCourse.indexOf(' ', (indexSpace1 + 1));
int courseLength = colCourse.length();
System.out.println("Department: " + colCourse.substring(0, indexSpace1));
System.out.println("Course Number: " + colCourse.substring((indexSpace1 + 1), indexSpace2));
System.out.println("Title: " + colCourse.substring((indexSpace2 + 1), courseLength));
}
}
|
package com.example.cow.helpers;
public enum SnackType {
ERROR("ERROR"),
WARNING("WARNING"),
NORMAL("NORMAL");
private String key;
SnackType(String key) {
this.key = key;
}
public String getKey() {
return key;
}
}
|
package rimabegum.example.com.quizrima;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class SolutionCatagory extends AppCompatActivity {
private Button CN,EN,BN,PY,HM;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_solution_catagory);
CN = (Button) findViewById(R.id.Computer_Networking);
EN = (Button) findViewById(R.id.English);
BN = (Button) findViewById(R.id.বাংলা);
HM = (Button) findViewById(R.id.Home);
CN.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(SolutionCatagory.this,GenaralKnowledge.class);
startActivity(intent);
finish();
}
});
EN.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(SolutionCatagory.this,English.class);
startActivity(intent);
finish();
}
});
BN.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(SolutionCatagory.this,Bangla.class);
startActivity(intent);
finish();
}
});
HM.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(SolutionCatagory.this,Home.class);
startActivity(intent);
finish();
}
});
}
}
|
package mycalculator;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.SwingConstants;
import javax.swing.JRadioButton;
import java.awt.Color;
public class Calculator {
private JFrame frame;
private JTextField textField;
double firstnumber;
double secondnumber;
double result;
String operations;
String answer;
private JTextField txtMyCalculator;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Calculator window = new Calculator();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Calculator() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 479, 431);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
textField = new JTextField();
textField.setForeground(Color.MAGENTA);
textField.setHorizontalAlignment(SwingConstants.RIGHT);
textField.setBounds(10, 28, 439, 50);
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton btnNewButton_1 = new JButton("1");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String EnterNumber = textField.getText() + btnNewButton_1.getText();
textField.setText(EnterNumber);
}
});
btnNewButton_1.setFont(new Font("Times New Roman", Font.BOLD, 15));
btnNewButton_1.setBounds(22, 253, 60, 50);
frame.getContentPane().add(btnNewButton_1);
JButton btnNewButton_0 = new JButton("0");
btnNewButton_0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String EnterNumber = textField.getText() + btnNewButton_0.getText();
textField.setText(EnterNumber);
}
});
btnNewButton_0.setFont(new Font("Times New Roman", Font.BOLD, 15));
btnNewButton_0.setBounds(22, 314, 60, 50);
frame.getContentPane().add(btnNewButton_0);
JButton btnNewButton_5 = new JButton("5");
btnNewButton_5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String EnterNumber = textField.getText() + btnNewButton_5.getText();
textField.setText(EnterNumber);
}
});
btnNewButton_5.setFont(new Font("Times New Roman", Font.BOLD, 15));
btnNewButton_5.setBounds(111, 192, 60, 50);
frame.getContentPane().add(btnNewButton_5);
JButton btnNewButton_6 = new JButton("2");
btnNewButton_6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String EnterNumber = textField.getText() + btnNewButton_6.getText();
textField.setText(EnterNumber);
}
});
btnNewButton_6.setFont(new Font("Times New Roman", Font.BOLD, 15));
btnNewButton_6.setBounds(111, 253, 60, 50);
frame.getContentPane().add(btnNewButton_6);
JButton btnNewButton_7 = new JButton(".");
btnNewButton_7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnNewButton_7.setFont(new Font("Times New Roman", Font.BOLD, 15));
btnNewButton_7.setBounds(111, 314, 60, 50);
frame.getContentPane().add(btnNewButton_7);
JButton button = new JButton("9");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String EnterNumber = textField.getText() + button.getText();
textField.setText(EnterNumber);
}
});
button.setFont(new Font("Times New Roman", Font.BOLD, 15));
button.setBounds(202, 126, 60, 50);
frame.getContentPane().add(button);
JButton button_7 = new JButton("7");
button_7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String EnterNumber = textField.getText() + button_7.getText();
textField.setText(EnterNumber);
}
});
button_7.setFont(new Font("Times New Roman", Font.BOLD, 15));
button_7.setBounds(22, 126, 60, 50);
frame.getContentPane().add(button_7);
JButton button_4 = new JButton("4");
button_4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String EnterNumber = textField.getText() + button_4.getText();
textField.setText(EnterNumber);
}
});
button_4.setFont(new Font("Times New Roman", Font.BOLD, 15));
button_4.setBounds(22, 192, 60, 50);
frame.getContentPane().add(button_4);
JButton button_8 = new JButton("8");
button_8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String EnterNumber = textField.getText() + button_8.getText();
textField.setText(EnterNumber);
}
});
button_8.setFont(new Font("Times New Roman", Font.BOLD, 15));
button_8.setBounds(111, 126, 60, 50);
frame.getContentPane().add(button_8);
JButton btnNewButton = new JButton("6");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String EnterNumber = textField.getText() + btnNewButton.getText();
textField.setText(EnterNumber);
}
});
btnNewButton.setFont(new Font("Times New Roman", Font.BOLD, 15));
btnNewButton.setBounds(202, 192, 60, 50);
frame.getContentPane().add(btnNewButton);
JButton btnNewButton_2 = new JButton("3");
btnNewButton_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String EnterNumber = textField.getText() + btnNewButton_2.getText();
textField.setText(EnterNumber);
}
});
btnNewButton_2.setFont(new Font("Times New Roman", Font.BOLD, 15));
btnNewButton_2.setBounds(202, 253, 60, 50);
frame.getContentPane().add(btnNewButton_2);
JButton btnReset = new JButton("RESET");
btnReset.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText(null);
}
});
btnReset.setBounds(202, 315, 136, 50);
frame.getContentPane().add(btnReset);
JButton button_1 = new JButton("+");
button_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
firstnumber = Double.parseDouble(textField.getText());
textField.setText("");
operations = "+";
}
});
button_1.setFont(new Font("Times New Roman", Font.BOLD, 15));
button_1.setBounds(293, 127, 60, 50);
frame.getContentPane().add(button_1);
JButton button_2 = new JButton("-");
button_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
firstnumber = Double.parseDouble(textField.getText());
textField.setText("");
operations = "-";
}
});
button_2.setFont(new Font("Times New Roman", Font.BOLD, 15));
button_2.setBounds(370, 126, 60, 50);
frame.getContentPane().add(button_2);
JButton btnX = new JButton("x");
btnX.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
firstnumber = Double.parseDouble(textField.getText());
textField.setText("");
operations = "x";
}
});
btnX.setFont(new Font("Tahoma", Font.BOLD, 15));
btnX.setBounds(293, 192, 60, 50);
frame.getContentPane().add(btnX);
JButton button_3 = new JButton("/");
button_3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
firstnumber = Double.parseDouble(textField.getText());
textField.setText("");
operations = "/";
}
});
button_3.setFont(new Font("Times New Roman", Font.BOLD, 15));
button_3.setBounds(370, 192, 60, 50);
frame.getContentPane().add(button_3);
JButton button_5 = new JButton("=");
button_5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String answer;
secondnumber = Double.parseDouble(textField.getText());
if (operations == "+")
{
result = firstnumber + secondnumber;
answer = String.format("%.1f", result);
textField.setText(answer);
}
else if (operations == "-")
{
result = firstnumber - secondnumber;
answer = String.format("%.1f", result);
textField.setText(answer);
}
else if (operations == "x")
{
result = firstnumber * secondnumber;
answer = String.format("%.1f", result);
textField.setText(answer);
}
else if (operations == "/")
{
result = firstnumber / secondnumber;
answer = String.format("%.1f", result);
textField.setText(answer);
}
}
});
button_5.setFont(new Font("Times New Roman", Font.BOLD, 15));
button_5.setBounds(370, 253, 60, 109);
frame.getContentPane().add(button_5);
JButton btnDel = new JButton("DEL");
btnDel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String backspace=null;
if(textField.getText().length() > 0) {
StringBuilder strB = new StringBuilder(textField.getText());
strB.deleteCharAt(textField.getText().length() - 1);
backspace = strB.toString();
textField.setText(backspace);
}
}
});
btnDel.setBounds(293, 254, 60, 50);
frame.getContentPane().add(btnDel);
txtMyCalculator = new JTextField();
txtMyCalculator.setFont(new Font("Times New Roman", Font.BOLD | Font.ITALIC, 17));
txtMyCalculator.setBackground(Color.BLUE);
txtMyCalculator.setHorizontalAlignment(SwingConstants.CENTER);
txtMyCalculator.setText("My Calculator");
txtMyCalculator.setBounds(131, -3, 158, 25);
frame.getContentPane().add(txtMyCalculator);
txtMyCalculator.setColumns(10);
}
}
|
package com.example.crawl.service;
import com.example.crawl.entity.CrawlResult;
/**
* 抽象类设计是为直接实现SpiderJob时每个子类必须实现其方法
* 这样抽离一个抽象类出来 方便子类的化简
*/
public abstract class AbstractSpiderJob implements SpiderJob {
@Override
public void run() {
this.beforeRun();
try {
this.doFetchPage();
} catch (Exception e) {
e.printStackTrace();
}
this.afterRun();
}
/**
* 具体的抓取实现由子类进行完成
* @throws Exception
*/
protected abstract void doFetchPage() throws Exception;
@Override
public void beforeRun() {
//微博模拟登陆
}
@Override
public void afterRun() {
}
/**
* 解析完网页后的回调方法
*
* @param crawlResult
*/
protected abstract void visit(CrawlResult crawlResult);
}
|
package com.wenyuankeji.spring.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.wenyuankeji.spring.dao.IUserEvaluateDao;
import com.wenyuankeji.spring.model.UserEvaluateModel;
import com.wenyuankeji.spring.service.IUserEvaluateService;
import com.wenyuankeji.spring.util.BaseException;
@Service
public class UserEvaluateServiceImpl implements IUserEvaluateService{
@Autowired
private IUserEvaluateDao userEvaluateDao;
@Override
public UserEvaluateModel searchUserEvaluate(int evaid) throws BaseException {
return userEvaluateDao.searchUserEvaluate(evaid);
}
@Override
public List<UserEvaluateModel> searchUserEvaluate(String userid,String bindphone ,String startTime, String endTime, int page,
int rows) throws BaseException {
return userEvaluateDao.searchUserEvaluate(userid,bindphone ,startTime, endTime, page, rows);
}
@Override
public int searchUserEvaluateCount(String userid,String bindphone ,String startTime, String endTime) throws BaseException {
return userEvaluateDao.searchUserEvaluateCount(userid,bindphone,startTime, endTime);
}
@Override
public boolean deleteUserEvaluate(int evaid) {
return userEvaluateDao.deleteUserEvaluate(evaid);
}
}
|
package com.yxkj.facexradix.view;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.yxdz.commonlib.util.SPUtils;
import com.yxkj.facexradix.R;
import com.yxkj.facexradix.Constants;
import java.util.Arrays;
import java.util.List;
public class ModeSettingDialog extends Dialog implements View.OnClickListener {
TextView tvDeviceMode;
private LinearLayout compositelayout;
private CheckBox face;
private CheckBox card;
private CheckBox password;
private CheckBox qrcode;
public ModeSettingDialog(Context context, TextView tvDeviceMode) {
super(context);
this.tvDeviceMode = tvDeviceMode;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_modesetting);
RelativeLayout cardAndFace = findViewById(R.id.cardAndFace);
cardAndFace.setOnClickListener(this);
RelativeLayout cardAndPassword = findViewById(R.id.cardAndPassword);
cardAndPassword.setOnClickListener(this);
RelativeLayout cardAndPasswordAndFace = findViewById(R.id.cardAndPasswordAndFace);
cardAndPasswordAndFace.setOnClickListener(this);
RelativeLayout faceAndPassword = findViewById(R.id.faceAndPassword);
faceAndPassword.setOnClickListener(this);
findViewById(R.id.Composite).setOnClickListener(this);
findViewById(R.id.submit_mode).setOnClickListener(this);
compositelayout = findViewById(R.id.compositelayout);
face = findViewById(R.id.box1);
card = findViewById(R.id.box2);
password = findViewById(R.id.box3);
qrcode = findViewById(R.id.box4);
try {
Integer.parseInt(SPUtils.getInstance().getString(Constants.DEVICE_OPEATOR_MODE));
switch (Integer.parseInt(SPUtils.getInstance().getString(Constants.DEVICE_OPEATOR_MODE))) {
case 11:
case 12:
case 13:
case 14:
compositelayout.setVisibility(View.GONE);
break;
default:
compositelayout.setVisibility(View.VISIBLE);
break;
}
} catch (NumberFormatException e) {
compositelayout.setVisibility(View.VISIBLE);
}
checkCode();
}
private void checkCode() {
String[] codes = SPUtils.getInstance().getString(Constants.DEVICE_OPEATOR_MODE).split("-");
List<String> list = Arrays.asList(codes);
if (list.contains("0")) {
card.setChecked(true);
} else {
card.setChecked(false);
}
if (list.contains("1")) {
face.setChecked(true);
} else {
face.setChecked(false);
}
if (list.contains("2")) {
qrcode.setChecked(true);
} else {
qrcode.setChecked(false);
}
if (list.contains("3")) {
password.setChecked(true);
} else {
password.setChecked(false);
}
}
private String getCode() {
String code = "";
if (face.isChecked()) {
code += 1;
}
if (card.isChecked()) {
code += 0;
}
if (password.isChecked()) {
code += 3;
}
if (qrcode.isChecked()) {
code += 2;
}
String s2 = code.replaceAll("(.{1})", "$1-");
if (s2.isEmpty()){
s2 = "1";
}
String sop2 = s2.substring(0, s2.length() - 1);
return sop2;
}
@Override
public void onClick(View v) {
Intent intent = new Intent("WAKE_UP_MODE");
intent.putExtra("type", SPUtils.getInstance().getInt("DEVICE_WAKE_MODE", 1));
switch (v.getId()) {
case R.id.Composite:
if (compositelayout.getVisibility() == View.GONE) {
compositelayout.setVisibility(View.VISIBLE);
} else {
compositelayout.setVisibility(View.GONE);
}
break;
case R.id.submit_mode:
SPUtils.getInstance().put(Constants.DEVICE_OPEATOR_MODE, getCode());
// log.d("ModeSettingDialog", "getCode():" + getCode());
getContext().sendBroadcast(intent);
this.dismiss();
tvDeviceMode.setText("多选模式");
break;
case R.id.cardAndFace:
SPUtils.getInstance().put(Constants.DEVICE_OPEATOR_MODE, "11");
getContext().sendBroadcast(intent);
this.dismiss();
tvDeviceMode.setText("卡+人脸");
break;
case R.id.cardAndPassword:
SPUtils.getInstance().put(Constants.DEVICE_OPEATOR_MODE, "12");
getContext().sendBroadcast(intent);
this.dismiss();
tvDeviceMode.setText("卡+密码");
break;
case R.id.cardAndPasswordAndFace:
SPUtils.getInstance().put(Constants.DEVICE_OPEATOR_MODE, "13");
getContext().sendBroadcast(intent);
this.dismiss();
tvDeviceMode.setText("卡+人脸+密码");
break;
case R.id.faceAndPassword:
SPUtils.getInstance().put(Constants.DEVICE_OPEATOR_MODE, "14");
getContext().sendBroadcast(intent);
this.dismiss();
tvDeviceMode.setText("人脸+密码");
break;
}
}
}
|
package com.kafka.producer.producer;
import com.kafka.producer.model.News;
import lombok.RequiredArgsConstructor;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.time.Duration;
import java.util.Random;
@Service
@RequiredArgsConstructor
public class ProducerService {
private final KafkaTemplate<News, News> kafkaTemplate;
private final Random random = new Random();
private boolean isProducing = false;
public Flux<News> startProducing() {
isProducing = true;
return Flux.interval(Duration.ofSeconds(2))
.map(e -> produceNews());
}
private News produceNews() {
String key = String.valueOf(random.nextInt(255));
String value = "Some news - " + random.nextInt(1000);
News news = new News("Key: " + key + " Value: " + value);
kafkaTemplate.send("news", news, news);
return news;
}
public Mono<String> stopProducing() {
isProducing = false;
return Mono.just("Producing has stopped");
}
}
|
public class Test {
private String text = "Hey";
private int num = 1;
public Test (int ble, double ble2) {
ble = ble;
ble2 = ble2;
}
public void writeInit() {
System.out.print();
System.out.print(this.ble2);
}
public static void main(String[] args) {
Test q = new Test(1, 2.0);
q.writeInit();
}
}
|
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.http.*;
public class TriggerFine extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
DbUpdate.executeTrigger();
out.println("<script>window.alert(\"Fines table has been updated\")</script>");
request.getRequestDispatcher("home.jsp").include(request, response);
out.close();
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
|
/*
* SocialFragment
*
* Version 1.0
*
* November 25, 2017
*
* Copyright (c) 2017 Team 26, CMPUT 301, University of Alberta - All Rights Reserved.
* You may use, distribute, or modify this code under terms and conditions of the Code of Student Behavior at University of Alberta.
* You can find a copy of the license in this project. Otherwise please contact rohan@ualberta.ca
*
* Purpose: Fragment to show the social feed.
* With the help of the social adapter, shows the user's social feed.
* Provides functionality for swipe to refresh.
*/
package cmput301f17t26.smores.all_fragments;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import cmput301f17t26.smores.R;
import cmput301f17t26.smores.all_adapters.SocialAdapter;
import cmput301f17t26.smores.dummy.DummyContent;
import cmput301f17t26.smores.dummy.DummyContent.DummyItem;
import cmput301f17t26.smores.utils.NetworkUtils;
public class SocialFragment extends Fragment {
// TODO: Customize parameter argument names
private static final String ARG_COLUMN_COUNT = "column-count";
// TODO: Customize parameters
private int mColumnCount = 1;
private SocialAdapter mSocialAdapter;
private ImageView background;
private RecyclerView recyclerView;
private SwipeRefreshLayout mSwipeRefreshLayout;
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public SocialFragment() {
}
// TODO: Customize parameter initialization
@SuppressWarnings("unused")
public static SocialFragment newInstance(int columnCount) {
SocialFragment fragment = new SocialFragment();
Bundle args = new Bundle();
args.putInt(ARG_COLUMN_COUNT, columnCount);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_social_list, container, false);
Context context = view.getContext();
mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipeRefreshLayout);
recyclerView = (RecyclerView) view.findViewById(R.id.list);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
background = (ImageView) view.findViewById(R.id.SocialBG);
mSocialAdapter = new SocialAdapter(getActivity(), recyclerView, background);
recyclerView.setAdapter(mSocialAdapter);
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
refreshItems();
}
});
return view;
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser && mSocialAdapter != null) {
mSocialAdapter.loadList();
}
}
void refreshItems() {
mSocialAdapter.loadList();
mSwipeRefreshLayout.setRefreshing(false);
if (mSocialAdapter.getItemCount() == 0) {
recyclerView.setVisibility(View.GONE);
background.setVisibility(View.VISIBLE);
} else {
background.setVisibility(View.GONE);
recyclerView.setVisibility(View.VISIBLE);
}
}
}
|
package DAO;
import Utilities.JDBCHelper;
import entities.Vehicle;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
/**
* Created by donuric on 7/13/2017.
*/
public class VehicleDaoImpl implements VehicleDao {
public List<Vehicle> getAllVehicles(int start, int total) {
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
List<Vehicle> vehicleList = null;
try{
con = JDBCHelper.getConnection();
ps=con.prepareStatement(
"select * from vehicle limit "+(start-1)+","+total);
ps.execute();
rs = ps.getResultSet();
while(rs.next()){
Vehicle e=new Vehicle();
e.setReg_num(rs.getString(1));
e.setOwner_name(rs.getString(2));
e.setVehicle_model(rs.getString(3));
e.setDate(rs.getString(4));
e.setPrice(rs.getDouble(5));
e.setTax(rs.getDouble(6));
e.setNumbers(rs.getInt(7));
vehicleList.add(e);
}
return vehicleList;
} catch(SQLException e){
System.out.println("OOPs error occured in connecting database " + e.getMessage());
return null;
}
finally {
JDBCHelper.close(rs);
JDBCHelper.close(ps);
JDBCHelper.close(con);
}
//return null;
}
public boolean addVehicle(Vehicle vehicle) {
Connection con = null;
PreparedStatement ps = null;
try {
con = JDBCHelper.getConnection();
con.setAutoCommit(false);
Vehicle vh = findVehicle(vehicle.getVehicle_model());
if(vh == null) {
String sql = "insert into vehicle values(?,?,?,?,?,?,?)";
ps = con.prepareStatement(sql);
ps.setString(1,vehicle.getReg_num());
ps.setString(2,vehicle.getOwner_name());
ps.setString(3, vehicle.getVehicle_model());
ps.setString(4, vehicle.getDate());
ps.setDouble(5, vehicle.getPrice());
ps.setDouble(6, vehicle.getTax());
ps.setInt(7, vehicle.getNumbers());
ps.executeUpdate();
con.commit();
}else{}
/*
double price = vh.getPrice();
double tax = vh.getTax();
double units = vh.getNumbers();
String owner=vh.getOwner_name();
String sql = "update vehicle set owner = ?,price = ?, units = ?, tax = ? where vehicle_model = ?";
ps = con.prepareStatement(sql);
ps.setDouble(5, vh.getPrice());
ps.setInt(7, vh.getNumbers());
ps.setDouble(6, vh.getTax());
ps.setString(4, vehicle.getVehicle_model());
ps.executeUpdate();
con.commit();*/
} catch (SQLException e) {
System.out.println("SQL Error :"+e.getMessage());
return false;
} finally {
JDBCHelper.close(con);
JDBCHelper.close(ps);
}
return false;
}
public boolean removeVehicles(String model, int number) {
return false;
}
public Vehicle findVehicle(String model) {
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
con = JDBCHelper.getConnection();
String sql = "Select * from vehicle where vehicle_model = ?";
ps = con.prepareStatement(sql);
ps.setString(1, model);
ps.execute();
rs = ps.getResultSet();
if(rs.next()) {
Vehicle vehicle = new Vehicle(rs.getString("reg_num"),rs.getString("owner_name"),rs.getString("vehicle_model"),rs.getString("date"),
rs.getDouble("price"), rs.getDouble("tax"), rs.getInt("numbers"));
return vehicle;
}
else{
return null;
}
} catch (SQLException e) {
System.out.print("Data Base Error"+e.getMessage());
return null;
} finally {
JDBCHelper.close(rs);
JDBCHelper.close(ps);
JDBCHelper.close(con);
}
}
}
|
package org.maxhoffmann.dev.Chain;
import java.util.ArrayList;
import java.util.Set;
import java.util.TreeSet;
import org.apache.log4j.Logger;
import org.maxhoffmann.dev.object.ProcessChainEvaluation;
import org.maxhoffmann.dev.object.ProcessChainObject;
public class ProcessChainMainOperations {
private static final Logger LOGGER = Logger
.getLogger(ProcessChainMainOperations.class);
Set<ProcessChainObject> mainChains = new TreeSet<>();
ArrayList<String> generatedChains = new ArrayList<String>();
ArrayList<String> workingChains = new ArrayList<String>();
ArrayList<String> regularProcessChains = new ArrayList<String>();
ArrayList<String> specialProcessChains = new ArrayList<String>();
ArrayList<Integer> regularChainsIteration = new ArrayList<Integer>();
ArrayList<Integer> specialChainsIteration = new ArrayList<Integer>();
int iterationNum;
int iterationMax;
public ProcessChainMainOperations() {
}
public ProcessChainMainOperations(Set<ProcessChainObject> mainChains,
ArrayList<String> generatedChains) {
this.mainChains = mainChains;
this.generatedChains = generatedChains;
}
public void setMainChains(Set<ProcessChainObject> mainChains) {
this.mainChains = mainChains;
}
public void setGeneratedChains(ArrayList<String> generatedChains) {
this.generatedChains = generatedChains;
}
public void setIterationNumber(int iterationNum) {
this.iterationNum = iterationNum;
}
public void setIterationMax(int iterationMax) {
this.iterationMax = iterationMax;
}
public ProcessChainEvaluation chainResults() {
workingChains.clear();
for (ProcessChainObject mainChain : mainChains) {
String actualChain = mainChain.getProcessChain();
workingChains.add(actualChain);
}
if (iterationNum == 0) {
LOGGER.info("\n\nHauptprozessketten (A priori):\n");
}
else if (iterationNum == iterationMax) {
LOGGER.info("\n\nHauptprozessketten (" + iterationNum + ". approximation / final):\n");
}
else {
LOGGER.info("\n\nHauptprozessketten (" + iterationNum + ". approximation):\n");
}
for (int i = 0; i < workingChains.size(); i++) {
LOGGER.info((i + 1) + ".\tProzesskette: " + workingChains.get(i));
}
regularProcessChains.clear();
for (String chain : generatedChains) {
for (String workingChain : workingChains) {
if (workingChain.contains(chain)) {
regularProcessChains.add(chain);
break;
}
}
}
regularChainsIteration.add(regularProcessChains.size());
specialProcessChains.clear();
for (String chain : generatedChains) {
boolean equalChains = false;
for (String regularChain : regularProcessChains) {
if (chain.equals(regularChain)) {
equalChains = true;
}
}
if (equalChains == false) {
specialProcessChains.add(chain);
}
}
specialChainsIteration.add(specialProcessChains.size());
LOGGER.info("\nRegular Process Chains:\t"
+ regularChainsIteration.get(regularChainsIteration.size() - 1)
+ "\t=> "
+ (float) 100
* (regularChainsIteration.get(regularChainsIteration.size() - 1))
/ (regularChainsIteration.get(regularChainsIteration.size() - 1) + specialChainsIteration
.get(specialChainsIteration.size() - 1))
+ " %\t of the products can be manufactured using the main process chains.");
LOGGER.info("Special Process Chains:\t"
+ specialChainsIteration.get(specialChainsIteration.size() - 1)
+ "\t=> "
+ (float) 100
* (specialChainsIteration.get(specialChainsIteration.size() - 1))
/ (regularChainsIteration.get(regularChainsIteration.size() - 1) + specialChainsIteration
.get(specialChainsIteration.size() - 1))
+ " %\t can not be manufactured using the current configuration.");
ProcessChainEvaluation evaluation = new ProcessChainEvaluation();
evaluation.setCurrentMainChains(workingChains);
evaluation.setRegularProcessChains(regularProcessChains);
evaluation.setSpecialProcessChains(specialProcessChains);
evaluation.setRegularChains(regularChainsIteration);
evaluation.setSpecialChains(specialChainsIteration);
return evaluation;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.