text
stringlengths 10
2.72M
|
|---|
package io.breen.socrates.model.wrapper;
import io.breen.socrates.file.File;
import io.breen.socrates.model.*;
import io.breen.socrates.model.event.*;
import io.breen.socrates.submission.SubmittedFile;
import io.breen.socrates.test.*;
import io.breen.socrates.util.Observable;
import io.breen.socrates.util.*;
import io.breen.socrates.util.Observer;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import java.util.*;
/**
* This class "wraps" a SubmittedFile and contains outcomes of tests for the file. The outcomes are
* stored in a tree of wrapper objects, each of which individually represents either a Test (in
* the case of TestWrapperNode) or a TestGroup (in the case of TestGroupWrapperNode) from the
* criteria.
*
* Instances add the tree of TestWrapperNode objects to a DefaultTreeModel. When the GUI needs to
* display a tree containing the current state of the tests for the file, it can simply set its
* model reference to the one contained by an object of this class.
*/
public class SubmittedFileWrapperNode extends DefaultMutableTreeNode
implements Observer<TestWrapperNode>, Observable<SubmittedFileWrapperNode>
{
public final File matchingFile;
public final DefaultTreeModel treeModel;
public final ConstraintUpdater updater;
private final Map<TestWrapperNode, Boolean> finished;
private final List<Observer<SubmittedFileWrapperNode>> observers;
public SubmittedFileWrapperNode(SubmittedFile submittedFile, File matchingFile) {
super(submittedFile);
if (submittedFile == null)
throw new IllegalArgumentException("submitted file must not be null");
if (matchingFile == null)
throw new IllegalArgumentException("must have non-null matching file");
this.matchingFile = matchingFile;
finished = new HashMap<>();
observers = new LinkedList<>();
treeModel = new DefaultTreeModel(null);
updater = new ConstraintUpdater(treeModel);
DefaultMutableTreeNode root = buildTree(matchingFile.testRoot);
treeModel.setRoot(root);
}
private DefaultMutableTreeNode buildTree(TestGroup root) {
TestGroupWrapperNode parent = new TestGroupWrapperNode(root);
for (Object member : root.members) {
if (member instanceof Test) {
Test test = (Test)member;
TestWrapperNode child = new TestWrapperNode(test);
child.addObserver(updater);
child.addObserver(this);
finished.put(child, false);
parent.add(child);
} else if (member instanceof TestGroup) {
TestGroup group = (TestGroup)member;
parent.add(buildTree(group));
}
}
return parent;
}
@Override
public void objectChanged(ObservableChangedEvent<TestWrapperNode> event) {
/*
* TODO in order for this to affect the changed state of the entire submission,
* lots of changes need to be made (i.e., SubmissionCompletedChangeEvent is too
* specific?)
*/
if (event instanceof NotesChangedEvent) {
SubmissionWrapperNode swn = (SubmissionWrapperNode)this.getParent();
swn.setSaved(false);
return;
}
boolean completeBefore = isComplete();
if (event instanceof ResultChangedEvent) {
ResultChangedEvent e = (ResultChangedEvent)event;
switch (e.newResult) {
case PASSED:
case FAILED:
finished.put(e.source, true);
break;
case NONE:
finished.put(e.source, false);
}
} else if (event instanceof ConstraintChangedEvent) {
ConstraintChangedEvent e = (ConstraintChangedEvent)event;
if (e.isNowConstrained) {
finished.put(e.source, true);
} else if (e.source.getResult() == TestResult.NONE) {
finished.put(e.source, false);
}
}
boolean completeAfter = isComplete();
FileCompletedChangeEvent e;
if (!completeBefore && completeAfter) {
e = new FileCompletedChangeEvent(this, true);
for (Observer<SubmittedFileWrapperNode> o : observers)
o.objectChanged(e);
} else if (completeBefore && !completeAfter) {
e = new FileCompletedChangeEvent(this, false);
for (Observer<SubmittedFileWrapperNode> o : observers)
o.objectChanged(e);
}
}
@Override
public void addObserver(Observer<SubmittedFileWrapperNode> observer) {
observers.add(observer);
}
@Override
public void removeObserver(Observer<SubmittedFileWrapperNode> observer) {
observers.add(observer);
}
public boolean isComplete() {
return finished.isEmpty() || !finished.containsValue(false);
}
public void resetAllTests() {
DefaultMutableTreeNode root = (DefaultMutableTreeNode)treeModel.getRoot();
@SuppressWarnings("unchecked") Enumeration<DefaultMutableTreeNode> dfs = root
.depthFirstEnumeration();
while (dfs.hasMoreElements()) {
DefaultMutableTreeNode n = dfs.nextElement();
if (n instanceof TestWrapperNode) {
TestWrapperNode node = (TestWrapperNode)n;
Test test = (Test)node.getUserObject();
node.setResult(TestResult.NONE);
if (test instanceof Automatable) node.setAutomationStage(AutomationStage.NONE);
}
}
}
}
|
package edu.nifu.sas.dao;
import edu.nifu.sas.model.User;
import edu.nifu.sas.util.C3p0Util;
import edu.nifu.sas.util.DBHelper;
import edu.nifu.sas.util.Md5Util;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapHandler;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class UserDao {
//User对象 的增删改查
public boolean checkLogin(User user){
String sql="select count(*) as count from tbl_user where username=? and password=?";
// //把占位符的值放入list中
// List<Object> params=new ArrayList<Object>();
// //Object 是一个map对象
// params.add(user.getUsername());
// //把明文转换为密文
// String encryptPassword= Md5Util.stringToMD5(user.getPassword());
// params.add(user.getPassword());
// //创建DBHelper
// DBHelper deHelper=new DBHelper();
// List<Object> query = deHelper.query(sql, params);
// //System.out.println(query);
// //return true;
long count=0;
QueryRunner query = new QueryRunner(C3p0Util.getConnection());
try {
Map<String, Object> map = query.query(sql, new MapHandler(), new Object[]{user.getUserName(), user.getPassword()});
count=(long)map.get("count");
} catch (SQLException e) {
e.printStackTrace();
}
return count>0;
}
public boolean saveUser(User u){
String sql="insert into tbl_user (username,password)values(?,?)";
//对占位符进行赋值,保存到list
// List<Object> params=new ArrayList<>();
// params.add(u.getUserName());
// params.add(Md5Util.stringToMD5(u.getPassword()));
// //创建DBHelper
// DBHelper db = new DBHelper();
// int result=db.update(sql,params);
int result=0;
QueryRunner query = new QueryRunner(C3p0Util.getConnection());
try {
result = query.execute(sql, new Object[]{u.getUserName(), u.getPassword()});
} catch (SQLException e) {
e.printStackTrace();
}
return result>0;
}
boolean updateStuno(String no){
return false;
}
}
|
package com.itheima.rabbitmq.routing;
import com.itheima.util.ConnectionUtil;
import com.rabbitmq.client.*;
import java.io.IOException;
public class ConsumerRoutingA {
public static void main(String[] args) throws IOException {
//获取连接
Connection connection = ConnectionUtil.getConnection();
//创建Channel
Channel channel = connection.createChannel();
//声明交换机
// channel.exchangeDeclare(ProducerRouting.exchangeName, BuiltinExchangeType.DIRECT);
//声明队列
channel.queueDeclare(ProducerRouting.DIRECT_QUEUE_INSERT, true, false, false, null);
//绑定队列至交换机
channel.queueBind(ProducerRouting.DIRECT_QUEUE_INSERT, ProducerRouting.exchangeName, "insert");
// 接收消息
Consumer consumer = new DefaultConsumer(channel){
/*
回调方法,当收到消息后,会自动执行该方法
1. consumerTag:标识
2. envelope:获取一些信息,交换机,路由key...
3. properties:配置信息
4. body:数据
*/
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("body:"+new String(body));
System.out.println("将日志信息打印到控制台.....");
}
};
channel.basicConsume(ProducerRouting.DIRECT_QUEUE_INSERT, true, consumer);
}
}
|
package com.test.base;
import com.test.SolutionA;
import junit.framework.TestCase;
public class Sample extends TestCase
{
private Solution solution;
@Override
protected void setUp()
throws Exception
{
super.setUp();
solution = new SolutionA();
}
public void testSolution()
{
String[] str = new String[] {"leet1", "leet2", "le2et3", "leet4"};
String result = solution.longestCommonPrefix(str);
System.out.println("result = " + result);
String[] str2 = new String[] {"", "", ""};
String result2 = solution.longestCommonPrefix(str2);
System.out.println("result2 = " + result2);
String[] str3 = new String[] {"aca", "cba"};
String result3 = solution.longestCommonPrefix(str3);
System.out.println("result3 = " + result3);
}
@Override
protected void tearDown()
throws Exception
{
solution = null;
super.tearDown();
}
}
|
package com.sxb.service;
import com.sxb.model.Replay;
/**
* @description 视频回放服务接口
* @author <a href="mailto:ou8zz@sina.com">OLE</a>
* @date 2016/06/14
* @version 1.0
*/
public interface ReplayService {
/**
* 保存·直播视频addReplay
* @param Replay 视频对象
* @return 成功success或者抛出异常
*/
Object addReplay(Replay r);
/**
* 获取直播视频列表
* @param Replay 视频对象
* @return 返回视频直播信息对象
*/
Object getReplay(Replay r);
}
|
package com.zhiyou.mapper;
import com.zhiyou.model.User;
public interface UserMapper {
// 注册用户
public void add(User user);
// 修改用户
public void update(User user);
// 查询用户
public User selectById(int id);
//
public User selectByAccounts(String accounts);
}
|
package com.yea.dispatcher.test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.util.StringUtils;
import com.yea.remote.netty.server.NettyServer;
@SuppressWarnings("resource")
public class ServerLauncher {
private static NettyServer nettyServer;
static{
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:application-bean.xml");
context.registerShutdownHook();
nettyServer = (NettyServer) context.getBean("nettyServer");
}
public static void main(String[] args) throws Throwable {
if(!StringUtils.isEmpty(System.getProperty("server.port"))){
int port = Integer.valueOf(System.getProperty("server.port"));
nettyServer.setPort(port);
}
nettyServer.bind();
}
}
|
package com.ams.app.controller;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class LoginController {
@RequestMapping("/getAppName")
public String index() {
return "Greetings from AMS app";
}
@RequestMapping(value = "/login/{emailid}/{password}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody String login(@PathVariable("emailid") String emailid, @PathVariable("password") String password) {
if(emailid.equals("admin@gmail.com") && password.equals("admin")) {
//return new ResponseEntity<String>("Vaid User", HttpStatus.OK);
return "Vaid User";
}
//return new ResponseEntity<String>("InVaid User", HttpStatus.OK);
return "Vaid User";
}
}
|
public class Code {
public static void main(String[] args) {
short code = 0b0101; // 16 bit
char character = 'A';
System.out.println("Source symbol " + character + " in char table: " + (byte)character);
character = (char)(character ^ code);
System.out.println("Encrypted character: " + character + " in char table: " + (byte)character);
character = (char)(character ^ code);
System.out.println("Decrypted character: " + character + " in char table: " + (byte)character);
// Source symbol A in char table: 65
// Encrypted character: D in char table: 68
// Decrypted character: A in char table: 65
}
}
|
package idv.emp.dao;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import idv.emp.model.EmpId;
import idv.emp.model.Emp2;
public interface EmpVODao extends JpaRepository<Emp2,EmpId>{
List<Emp2> findAll();
}
|
package com.amol.springboot.demo.bootapp;
import static org.junit.Assert.assertEquals;
import java.util.HashMap;
import org.junit.Test;
import com.TacoLoco.springboot.demo.controller.OrderController;
import com.TacoLoco.springboot.demo.exception.TacoNotFoundException;
import com.TacoLoco.springboot.demo.model.TotalOrderRequest;
import com.TacoLoco.springboot.demo.model.TotalOrderResponse;
public class OrderControllerTest {
OrderController orderController = new OrderController();
//Test case without discount.
@Test
public void testNoDiscount() {
final HashMap<String, Integer> noDiscount = new HashMap<>();
noDiscount.put("Veggie Taco", 2);
final TotalOrderRequest noDiscountRequest = new TotalOrderRequest("Not Discountable", noDiscount);
final TotalOrderResponse noDiscountResponse = orderController.orderTotal(noDiscountRequest);
assertEquals(noDiscountResponse.getTotal(), 5, 1e-15); //Delta (1e-15) for Margin of error
}
//Test case with applying discount.
@Test
public void testDiscount() {
final HashMap<String, Integer> discount = new HashMap<>();
discount.put("Beef Taco", 5);
discount.put("Chicken Taco", 1);
discount.put("Chorizo Taco", 2);
discount.put("Veggie Taco", 1);
final TotalOrderRequest discountRequest = new TotalOrderRequest("Discountable", discount);
final TotalOrderResponse discountResponse = orderController.orderTotal(discountRequest);
assertEquals(discountResponse.getTotal(), 22, 1e-15); //Delta (1e-15) for Margin of error
}
//Test cases for non existing Tacos
@Test(expected = TacoNotFoundException.class)
public void testNonExistingTacos() {
final HashMap<String, Integer> nonExisting = new HashMap<>();
nonExisting.put("Pizza", 3);
final TotalOrderRequest nonExistingRequest = new TotalOrderRequest("nonexistentItemOrder", nonExisting);
@SuppressWarnings("unused")
final TotalOrderResponse nonExistingResponse = orderController.orderTotal(nonExistingRequest);
}
}
|
package buttley.nyc.esteban.magicbeans.model.boards.widgets;
/**
* Created by Spoooon on 1/19/2015.
*/
public enum WidgetTypeEnum {
BEAN_STAGE, PATIENT_STAGE, POOP_METER, POWER_UP_BAR,
SCORE_BOARD, BACKGROUND, TITLE,BUTTLEY_STAGE
}
|
package com.cs.config;
import com.cs.persistence.JpaConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
/**
* @author Joakim Gottzén
*/
@Configuration
@Import({JpaConfig.class})
public class CoreServiceConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
|
package be.openclinic.statistics;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.Iterator;
import be.mxs.common.util.db.MedwanQuery;
import be.mxs.common.util.system.Debug;
import be.openclinic.finance.Insurance;
public class UpdateStats2 extends UpdateStatsBase{
public UpdateStats2() {
setModulename("stats.hospitalstats");
}
public void execute(){
Date lastupdatetime;
Connection oc_conn=MedwanQuery.getInstance().getOpenclinicConnection();
try{
//Eerst maken we een lijst van alle encounters die moeten worden geupdated
//Vooreerst de encounters met een nieuwe updatetime
SortedSet encounters = new TreeSet();
HashSet allencounters = new HashSet();
setModulename("stats.hospitalstats.encounters");
lastupdatetime=getLastUpdateTime(STARTDATE);
Debug.println("executing "+this.modulename);
String sLocalDbType = "Microsoft SQL Server";
try {
sLocalDbType=oc_conn.getMetaData().getDatabaseProductName();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String sql = "SELECT top "+maxbatchsize+" * from OC_ENCOUNTERS where OC_ENCOUNTER_UPDATETIME>=? order by OC_ENCOUNTER_UPDATETIME ASC";
if(sLocalDbType.equalsIgnoreCase("MySQL")){
sql = "SELECT * from OC_ENCOUNTERS where OC_ENCOUNTER_UPDATETIME>=? order by OC_ENCOUNTER_UPDATETIME ASC limit "+maxbatchsize+"";
}
PreparedStatement ps = oc_conn.prepareStatement(sql);
ps.setTimestamp(1, new Timestamp(lastupdatetime.getTime()));
ResultSet rs = ps.executeQuery();
String euid;
while(rs.next()){
euid=rs.getInt("OC_ENCOUNTER_SERVERID")+"."+rs.getInt("OC_ENCOUNTER_OBJECTID");
if(!allencounters.contains(euid)){
allencounters.add(euid);
encounters.add(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(rs.getTimestamp("OC_ENCOUNTER_UPDATETIME"))+";"+euid);
}
}
rs.close();
ps.close();
Iterator iEncounters = encounters.iterator();
int n=0,counter=0;
while(iEncounters.hasNext()){
try{
n++;
String encounterString=(String)iEncounters.next();
String encounteruid=encounterString.split(";")[1];
counter++;
if(counter%100==0) Debug.println("U2 processing encounter UID "+encounteruid+" (#"+counter+") "+encounterString.split(";")[0]);
//register diagnoses for every service visited
sql="SELECT * from OC_ENCOUNTERS_VIEW where OC_ENCOUNTER_SERVERID=? and OC_ENCOUNTER_OBJECTID=?";
oc_conn=MedwanQuery.getInstance().getOpenclinicConnection();
PreparedStatement ps3=oc_conn.prepareStatement(sql);
ps3.setInt(1, Integer.parseInt(encounteruid.split("\\.")[0]));
ps3.setInt(2, Integer.parseInt(encounteruid.split("\\.")[1]));
ResultSet rs3 = ps3.executeQuery();
while(rs3.next()){
String patientuid=rs3.getString("OC_ENCOUNTER_PATIENTUID");
String type=rs3.getString("OC_ENCOUNTER_TYPE");
String outcome=rs3.getString("OC_ENCOUNTER_OUTCOME");
lastupdatetime=rs3.getTimestamp("OC_ENCOUNTER_UPDATETIME");
Date begindate=rs3.getDate("OC_ENCOUNTER_BEGINDATE");
Date enddate=rs3.getDate("OC_ENCOUNTER_ENDDATE");
//remove the encounter record(s) from the statstable
sql="DELETE FROM UPDATESTATS2 WHERE OC_ENCOUNTER_SERVERID=? and OC_ENCOUNTER_OBJECTID=?";
Connection stats_conn=MedwanQuery.getInstance().getStatsConnection();
PreparedStatement ps2 = stats_conn.prepareStatement(sql);
ps2.setInt(1, Integer.parseInt(encounteruid.split("\\.")[0]));
ps2.setInt(2, Integer.parseInt(encounteruid.split("\\.")[1]));
ps2.executeUpdate();
ps2.close();
stats_conn.close();
//add the encounter records
String serviceuid=rs3.getString("OC_ENCOUNTER_SERVICEUID");
sql="SELECT * from OC_DIAGNOSES_VIEW where OC_DIAGNOSIS_ENCOUNTERUID=?";
Connection loc_conn=MedwanQuery.getInstance().getLongOpenclinicConnection();
PreparedStatement ps4 = loc_conn.prepareStatement(sql);
ps4.setString(1, encounteruid);
ResultSet rs4=ps4.executeQuery();
boolean bDiagnosesFound=false;
while(rs4.next()){
stats_conn=MedwanQuery.getInstance().getStatsConnection();
try{
bDiagnosesFound=true;
String diagnosiscode=rs4.getString("OC_DIAGNOSIS_CODE");
String diagnosiscodetype=rs4.getString("OC_DIAGNOSIS_CODETYPE");
int diagnosisgravity=rs4.getInt("OC_DIAGNOSIS_GRAVITY");
int diagnosiscertainty=rs4.getInt("OC_DIAGNOSIS_CERTAINTY");
sql="INSERT INTO UPDATESTATS2(" +
"OC_ENCOUNTER_SERVERID," +
"OC_ENCOUNTER_OBJECTID," +
"OC_ENCOUNTER_PATIENTUID," +
"OC_ENCOUNTER_BEGINDATE," +
"OC_ENCOUNTER_ENDDATE," +
"OC_ENCOUNTER_OUTCOME," +
"OC_ENCOUNTER_TYPE," +
"OC_ENCOUNTER_SERVICEUID," +
"OC_DIAGNOSIS_CODE," +
"OC_DIAGNOSIS_CODETYPE," +
"OC_DIAGNOSIS_GRAVITY," +
"OC_DIAGNOSIS_CERTAINTY) values(?,?,?,?,?,?,?,?,?,?,?,?)";
ps2=stats_conn.prepareStatement(sql);
ps2.setInt(1, Integer.parseInt(encounteruid.split("\\.")[0]));
ps2.setInt(2, Integer.parseInt(encounteruid.split("\\.")[1]));
ps2.setString(3, patientuid);
ps2.setDate(4, new java.sql.Date(begindate.getTime()));
ps2.setDate(5, new java.sql.Date(enddate.getTime()));
ps2.setString(6, outcome);
ps2.setString(7, type);
ps2.setString(8, serviceuid);
ps2.setString(9, diagnosiscode);
ps2.setString(10, diagnosiscodetype);
ps2.setInt(11, diagnosisgravity);
ps2.setInt(12, diagnosiscertainty);
ps2.executeUpdate();
ps2.close();
}
catch(Exception e2){
e2.printStackTrace();
}
stats_conn.close();
}
rs4.close();
ps4.close();
loc_conn.close();
if(!bDiagnosesFound){
try{
sql="INSERT INTO UPDATESTATS2(" +
"OC_ENCOUNTER_SERVERID," +
"OC_ENCOUNTER_OBJECTID," +
"OC_ENCOUNTER_PATIENTUID," +
"OC_ENCOUNTER_BEGINDATE," +
"OC_ENCOUNTER_ENDDATE," +
"OC_ENCOUNTER_OUTCOME," +
"OC_ENCOUNTER_TYPE," +
"OC_ENCOUNTER_SERVICEUID," +
"OC_DIAGNOSIS_CODE," +
"OC_DIAGNOSIS_CODETYPE," +
"OC_DIAGNOSIS_GRAVITY," +
"OC_DIAGNOSIS_CERTAINTY) values(?,?,?,?,?,?,?,?,?,?,?,?)";
stats_conn=MedwanQuery.getInstance().getStatsConnection();
ps2=stats_conn.prepareStatement(sql);
ps2.setInt(1, Integer.parseInt(encounteruid.split("\\.")[0]));
ps2.setInt(2, Integer.parseInt(encounteruid.split("\\.")[1]));
ps2.setString(3, patientuid);
ps2.setDate(4, new java.sql.Date(begindate.getTime()));
ps2.setDate(5, new java.sql.Date(enddate.getTime()));
ps2.setString(6, outcome);
ps2.setString(7, type);
ps2.setString(8, serviceuid);
ps2.setObject(9, null);
ps2.setObject(10, null);
ps2.setObject(11, null);
ps2.setObject(12, null);
ps2.executeUpdate();
ps2.close();
stats_conn.close();
}
catch(Exception e2){
e2.printStackTrace();
}
}
}
rs3.close();
ps3.close();
oc_conn.close();
if(counter%10==0){
setModulename("stats.hospitalstats.encounters");
setLastUpdateTime(lastupdatetime);
}
}
catch (Exception e3) {
e3.printStackTrace();
}
}
rs.close();
ps.close();
//Vervolgens voegen we de encounters toe met een diagnose met nieuwe updatetime
encounters=new TreeSet();
setModulename("stats.hospitalstats.diagnoses");
sql = "SELECT top "+maxbatchsize+" * from OC_DIAGNOSES where OC_DIAGNOSIS_UPDATETIME>=? order by OC_DIAGNOSIS_UPDATETIME ASC";
if(sLocalDbType.equalsIgnoreCase("MySQL")){
sql = "SELECT * from OC_DIAGNOSES where OC_DIAGNOSIS_UPDATETIME>=? order by OC_DIAGNOSIS_UPDATETIME ASC limit "+maxbatchsize+"";
}
ps = oc_conn.prepareStatement(sql);
ps.setTimestamp(1, new Timestamp(lastupdatetime.getTime()));
rs = ps.executeQuery();
while(rs.next()){
encounters.add(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(rs.getTimestamp("OC_DIAGNOSIS_UPDATETIME"))+";"+rs.getString("OC_DIAGNOSIS_ENCOUNTERUID"));
}
rs.close();
ps.close();
oc_conn.close();
iEncounters = encounters.iterator();
n=0;
counter=0;
while(iEncounters.hasNext()){
try{
n++;
String encounterString=(String)iEncounters.next();
String encounteruid=encounterString.split(";")[1];
if(!allencounters.contains(encounteruid)){
counter++;
if(counter%100==0) Debug.println("U2 processing diagnosis-encounter UID "+encounteruid+" (#"+counter+") "+encounterString.split(";")[0]);
//register diagnoses for every service visited
sql="SELECT * from OC_ENCOUNTERS_VIEW where OC_ENCOUNTER_SERVERID=? and OC_ENCOUNTER_OBJECTID=?";
oc_conn=MedwanQuery.getInstance().getOpenclinicConnection();
PreparedStatement ps3=oc_conn.prepareStatement(sql);
ps3.setInt(1, Integer.parseInt(encounteruid.split("\\.")[0]));
ps3.setInt(2, Integer.parseInt(encounteruid.split("\\.")[1]));
ResultSet rs3 = ps3.executeQuery();
while(rs3.next()){
String patientuid=rs3.getString("OC_ENCOUNTER_PATIENTUID");
String type=rs3.getString("OC_ENCOUNTER_TYPE");
String outcome=rs3.getString("OC_ENCOUNTER_OUTCOME");
lastupdatetime=rs3.getTimestamp("OC_ENCOUNTER_UPDATETIME");
Date begindate=rs3.getDate("OC_ENCOUNTER_BEGINDATE");
Date enddate=rs3.getDate("OC_ENCOUNTER_ENDDATE");
//remove the encounter record(s) from the statstable
sql="DELETE FROM UPDATESTATS2 WHERE OC_ENCOUNTER_SERVERID=? and OC_ENCOUNTER_OBJECTID=?";
Connection stats_conn=MedwanQuery.getInstance().getStatsConnection();
PreparedStatement ps2 = stats_conn.prepareStatement(sql);
ps2.setInt(1, Integer.parseInt(encounteruid.split("\\.")[0]));
ps2.setInt(2, Integer.parseInt(encounteruid.split("\\.")[1]));
ps2.executeUpdate();
ps2.close();
stats_conn.close();
//add the encounter records
String serviceuid=rs3.getString("OC_ENCOUNTER_SERVICEUID");
sql="SELECT * from OC_DIAGNOSES_VIEW where OC_DIAGNOSIS_ENCOUNTERUID=?";
Connection loc_conn=MedwanQuery.getInstance().getLongOpenclinicConnection();
PreparedStatement ps4 = loc_conn.prepareStatement(sql);
ps4.setString(1, encounteruid);
ResultSet rs4=ps4.executeQuery();
boolean bDiagnosesFound=false;
while(rs4.next()){
stats_conn=MedwanQuery.getInstance().getStatsConnection();
try{
bDiagnosesFound=true;
String diagnosiscode=rs4.getString("OC_DIAGNOSIS_CODE");
String diagnosiscodetype=rs4.getString("OC_DIAGNOSIS_CODETYPE");
int diagnosisgravity=rs4.getInt("OC_DIAGNOSIS_GRAVITY");
int diagnosiscertainty=rs4.getInt("OC_DIAGNOSIS_CERTAINTY");
sql="INSERT INTO UPDATESTATS2(" +
"OC_ENCOUNTER_SERVERID," +
"OC_ENCOUNTER_OBJECTID," +
"OC_ENCOUNTER_PATIENTUID," +
"OC_ENCOUNTER_BEGINDATE," +
"OC_ENCOUNTER_ENDDATE," +
"OC_ENCOUNTER_OUTCOME," +
"OC_ENCOUNTER_TYPE," +
"OC_ENCOUNTER_SERVICEUID," +
"OC_DIAGNOSIS_CODE," +
"OC_DIAGNOSIS_CODETYPE," +
"OC_DIAGNOSIS_GRAVITY," +
"OC_DIAGNOSIS_CERTAINTY) values(?,?,?,?,?,?,?,?,?,?,?,?)";
ps2=stats_conn.prepareStatement(sql);
ps2.setInt(1, Integer.parseInt(encounteruid.split("\\.")[0]));
ps2.setInt(2, Integer.parseInt(encounteruid.split("\\.")[1]));
ps2.setString(3, patientuid);
ps2.setDate(4, new java.sql.Date(begindate.getTime()));
ps2.setDate(5, new java.sql.Date(enddate.getTime()));
ps2.setString(6, outcome);
ps2.setString(7, type);
ps2.setString(8, serviceuid);
ps2.setString(9, diagnosiscode);
ps2.setString(10, diagnosiscodetype);
ps2.setInt(11, diagnosisgravity);
ps2.setInt(12, diagnosiscertainty);
ps2.executeUpdate();
ps2.close();
}
catch(Exception e2){
e2.printStackTrace();
}
stats_conn.close();
}
rs4.close();
ps4.close();
loc_conn.close();
if(!bDiagnosesFound){
try{
sql="INSERT INTO UPDATESTATS2(" +
"OC_ENCOUNTER_SERVERID," +
"OC_ENCOUNTER_OBJECTID," +
"OC_ENCOUNTER_PATIENTUID," +
"OC_ENCOUNTER_BEGINDATE," +
"OC_ENCOUNTER_ENDDATE," +
"OC_ENCOUNTER_OUTCOME," +
"OC_ENCOUNTER_TYPE," +
"OC_ENCOUNTER_SERVICEUID," +
"OC_DIAGNOSIS_CODE," +
"OC_DIAGNOSIS_CODETYPE," +
"OC_DIAGNOSIS_GRAVITY," +
"OC_DIAGNOSIS_CERTAINTY) values(?,?,?,?,?,?,?,?,?,?,?,?)";
stats_conn=MedwanQuery.getInstance().getStatsConnection();
ps2=stats_conn.prepareStatement(sql);
ps2.setInt(1, Integer.parseInt(encounteruid.split("\\.")[0]));
ps2.setInt(2, Integer.parseInt(encounteruid.split("\\.")[1]));
ps2.setString(3, patientuid);
ps2.setDate(4, new java.sql.Date(begindate.getTime()));
ps2.setDate(5, new java.sql.Date(enddate.getTime()));
ps2.setString(6, outcome);
ps2.setString(7, type);
ps2.setString(8, serviceuid);
ps2.setObject(9, null);
ps2.setObject(10, null);
ps2.setObject(11, null);
ps2.setObject(12, null);
ps2.executeUpdate();
ps2.close();
stats_conn.close();
}
catch(Exception e2){
e2.printStackTrace();
}
}
}
rs3.close();
ps3.close();
oc_conn.close();
}
if(counter%10==0){
setModulename("stats.hospitalstats.diagnoses");
setLastUpdateTime(lastupdatetime);
}
}
catch (Exception e3) {
e3.printStackTrace();
}
}
rs.close();
ps.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
|
package org.shujito.cartonbox.view.fragment.dialog;
import org.shujito.cartonbox.R;
import org.shujito.cartonbox.controller.task.JsonDownloader;
import org.shujito.cartonbox.controller.task.SitesJsonDownloader;
import org.shujito.cartonbox.model.Site;
import org.shujito.cartonbox.util.ConcurrentTask;
import org.shujito.cartonbox.view.adapter.DefaultSitesAdapter;
import org.shujito.cartonbox.view.fragment.dialog.listener.AddSiteDialogCallback;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.actionbarsherlock.app.SherlockDialogFragment;
public class AddDefaultSiteDialogFragment extends SherlockDialogFragment
implements OnItemClickListener
{
public static final String TAG = "org.shujito.cartonbox.view.fragments.dialogs.AddDefaultSiteDialogFragment";
AddSiteDialogCallback callback = null;
ListView lvSites = null;
DefaultSitesAdapter defaultSitesAdapter = null;
JsonDownloader downloader = null;
public AddDefaultSiteDialogFragment() { }
@Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
if(activity instanceof AddSiteDialogCallback)
{ this.callback = (AddSiteDialogCallback)activity; }
}
@Override
public Dialog onCreateDialog(Bundle cirno)
{
LayoutInflater inf = this.getActivity().getLayoutInflater();
View v = inf.inflate(R.layout.dialog_listview, null);
// create the adapter
this.defaultSitesAdapter = new DefaultSitesAdapter(this.getActivity());
// download sites with this
this.downloader = new SitesJsonDownloader();
// make the adapter to listen for the request
this.downloader.setOnErrorListener(this.defaultSitesAdapter);
this.downloader.setOnResponseReceivedListener(this.defaultSitesAdapter);
ConcurrentTask.execute(this.downloader);
// get the listview
this.lvSites = (ListView)v.findViewById(R.id.lvList);
this.lvSites.setOnItemClickListener(this);
this.lvSites.setAdapter(this.defaultSitesAdapter);
/*
int lightdarktheme = com.actionbarsherlock.R.style.Theme_Sherlock_Light_DarkActionBar;
int currentTheme = 0;
try
{ currentTheme = this.getActivity().getPackageManager().getActivityInfo(this.getActivity().getComponentName(), 0).theme; }
catch(Exception ex)
{ }
//*/
return new AlertDialog.Builder(this.getActivity())
.setInverseBackgroundForced(true)
.setTitle(R.string.addsite)
.setView(v)
.setNegativeButton(android.R.string.cancel, null)
.create();
}
@Override
public void onItemClick(AdapterView<?> ada, View v, int pos, long id)
{
//Toast.makeText(this.getActivity(), String.format("selected %s", pos), Toast.LENGTH_SHORT).show();
Site site = (Site)this.defaultSitesAdapter.getItem(pos);
if(this.callback != null)
{
// TODO: download image
this.callback.onOk(site);
this.dismiss();
}
}
}
|
/*
* This code counts the distinct occurances of a subsequence
* In other words: Find number of times a string occurs as a subsequence in given string
* Reference: https://www.geeksforgeeks.org/find-number-times-string-occurs-given-string/
* Reference: https://www.geeksforgeeks.org/count-distinct-occurrences-as-a-subsequence/
* Example:
* Input : S = banana, T = ban
Output : 3
T appears in S as below three subsequences.
[ban], [ba n], [b an]
*/
public class CountDistinctSubseq {
// recursive function to count distinct occurances of a subsequence
public static int countDisSubseq(String superStr, int i, String subStr, int j) {
// base case 1
if ((i == 0 && j == 0) || j == 0)
return 1;
// base case 2
if(i == 0) {
return 0;
}
if(superStr.charAt(i - 1) != subStr.charAt(j - 1)) {
return countDisSubseq(superStr, i - 1, subStr, j);
} else {
return (countDisSubseq(superStr, i - 1, subStr, j - 1) + countDisSubseq(superStr, i - 1, subStr, j));
}
}
// function to count distint occurances of subsequence
public static int findSubsequenceCount(String superStr, String subStr) {
int m = subStr.length();
int n = superStr.length();
if(m > n) {
return 0;
}
int[][] mat = new int[m + 1][n + 1];
// Initializing first column with
// all 0s. An empty string can't have
// another string as subsequence
for(int i = 0; i <= m; i++) {
mat[i][0] = 0;
}
// Initializing first row with all 1s.
// An empty string is subsequence of all.
for(int j = 0; j <= n; j++) {
mat[0][j] = 1;
}
for(int i = 1; i <= m; i++) {
for(int j = 1; j <= n; j++) {
if(subStr.charAt(i - 1) != superStr.charAt(j - 1)) {
mat[i][j] = mat[i][j - 1];
} else {
mat[i][j] = mat[i][j - 1] + mat[i - 1][j - 1];
}
}
}
// uncomment this to print matrix mat
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++)
System.out.print ( mat[i][j] +" ");
System.out.println ();
}
return mat[m][n];
}
// main method
public static void main(String args[]) {
String T = "bag";
String S = "babag";
System.out.println(findSubsequenceCount(S, T));
int i = S.length();
int j = T.length();
System.out.println(countDisSubseq(S, i, T, j));
}
}
|
package cc.ipotato.reflect;
import java.util.Arrays;
public class GetSuperTest {
public static void main(String[] args) {
Class<?> cls = Apple.class;
System.out.println(cls.getName());
System.out.println(cls.getPackage().getName());
System.out.println(cls.getSuperclass().getName());
Class<?> interfaces[] = cls.getInterfaces();
System.out.println(Arrays.toString(interfaces));
}
}
|
package com.example.chessproject_java;
import android.util.Log;
import java.lang.reflect.Array;
import java.util.ArrayList;
import static com.example.chessproject_java.MainActivity.neighboorsCoord;
public class Layers {
static final private int[] X = {2, 1, -1, -2, -2, -1, 1, 2};
static final private int[] Y = {1, 2, 2, 1, -1, -2, -2, -1};
static ArrayList<Coordinates> findLayerCoordinates(ArrayList<Coordinates> totalList) {
ArrayList<Coordinates> queueLevel = new ArrayList<>();
for (int i = 0; i < totalList.size(); i++) {
Coordinates parentCoord = totalList.get(i);
for (int j = 0; j < 8; j++) {
int x = parentCoord.x + X[j];
int y = parentCoord.y + Y[j];
if (x >= 0 && y >= 0 && x < 8 && y < 8) {
Coordinates coordinates = new Coordinates(x, y, parentCoord);
addNeighboors(x,y, coordinates);
queueLevel.add(coordinates);
}
}
}
return queueLevel;
}
private static void addNeighboors(int x_after_move, int y_after_move, Coordinates coordinates) {
//πρεπει να παρω ολα τα πιθανα γειτονικα coordinates του καθε σημειου
// περιπτωση x==2 && y==1
String initPoint = (x_after_move - 2) + "," + (y_after_move - 1);
String firstPoint = (x_after_move - 1) + "," + (y_after_move - 1);
String secPoint = x_after_move + "," + (y_after_move - 1);
String thirdPoint = x_after_move + "," + y_after_move;
String total = initPoint+"-"+firstPoint + "-" + secPoint + "-" + thirdPoint;
neighboorsCoord.add(total);
// περιπτωση x==1 && y==2
String initPoint1 = (x_after_move - 1) + "," + (y_after_move - 2);
String firstPoint1 = (x_after_move - 1) + "," + (y_after_move - 1);
String secPoint1 = (x_after_move - 1) + "," + (y_after_move);
String thirdPoint1 = x_after_move + "," + y_after_move;
String total1 = initPoint1+"-"+firstPoint1 + "-" + secPoint1 + "-" + thirdPoint1;
neighboorsCoord.add(total1);
// περιπτωση x==-1 && y==2
String initPoint2 = (x_after_move + 1) + "," + (y_after_move - 2);
String firstPoint2 = (x_after_move + 1) + "," + (y_after_move - 1);
String secPoint2 = (x_after_move + 1) + "," + (y_after_move);
String thirdPoint2 = x_after_move + "," + y_after_move;
String total2 = initPoint2+"-"+firstPoint2 + "-" + secPoint2 + "-" + thirdPoint2;
neighboorsCoord.add(total2);
// περιπτωση x==-2 && y==1
String initPoint3 = (x_after_move + 2) + "," + (y_after_move -1);
String firstPoint3 = (x_after_move + 1) + "," + (y_after_move -1);
String secPoint3 = (x_after_move) + "," + (y_after_move-1);
String thirdPoint3 = x_after_move + "," + y_after_move;
String total3 = initPoint3+"-"+firstPoint3 + "-" + secPoint3 + "-" + thirdPoint3;
neighboorsCoord.add(total3);
// περιπτωση x==-2 && y==-1
String initPoint4 = (x_after_move + 2) + "," + (y_after_move + 1);
String firstPoint4 = (x_after_move + 1) + "," + (y_after_move + 1);
String secPoint4 = (x_after_move) + "," + (y_after_move+ 1);
String thirdPoint4 = x_after_move + "," + y_after_move;
String total4 = initPoint4+"-"+firstPoint4 + "-" + secPoint4 + "-" + thirdPoint4;
neighboorsCoord.add(total4);
// περιπτωση x==-1 && y==-2
String initPoint5 = (x_after_move + 1) + "," + (y_after_move + 2);
String firstPoint5 = (x_after_move + 1) + "," + (y_after_move + 1);
String secPoint5 = (x_after_move + 1) + "," + (y_after_move);
String thirdPoint5 = x_after_move + "," + y_after_move;
String total5 = initPoint5+"-"+firstPoint5 + "-" + secPoint5 + "-" + thirdPoint5;
neighboorsCoord.add(total5); //οκ double cjeck
// περιπτωση x==1 && y==-2
String initPoint6 = (x_after_move - 1 ) + "," + (y_after_move +2);
String firstPoint6 = (x_after_move - 1) + "," + (y_after_move + 1);
String secPoint6 = (x_after_move - 1) + "," + (y_after_move);
String thirdPoint6 = x_after_move + "," + y_after_move;
String total6 = initPoint6+"-"+firstPoint6 + "-" + secPoint6 + "-" + thirdPoint6;
neighboorsCoord.add(total6); //οκ
// περιπτωση x==2 && y==-1
String initPoint7 = (x_after_move -2 ) + "," + (y_after_move +1);
String firstPoint7 = (x_after_move - 1) + "," + (y_after_move + 1);
String secPoint7 = (x_after_move ) + "," + (y_after_move+1);
String thirdPoint7 = x_after_move + "," + y_after_move;
String total7 = initPoint7+"-"+firstPoint7 + "-" + secPoint7 + "-" + thirdPoint7;
neighboorsCoord.add(total7);
}
}
|
package com.prolific.vidmediaplayer.Activities;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.LoadAdError;
import com.prolific.vidmediaplayer.Others.AdLoader;
import com.prolific.vidmediaplayer.R;
import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
public class PermissionActivity extends BaseActivity {
private Button btnAllow;
private final int REQ_READ_WRITE_PERMISSION = 100;
private final int REQ_WRITE_SETTING = 101;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
final int flags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
/*| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN*/
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
/*| View.SYSTEM_UI_FLAG_FULLSCREEN*/
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
getWindow().getDecorView().setSystemUiVisibility(flags);
setContentView(R.layout.activity_permission);
btnAllow = findViewById(R.id.btnAllow);
btnAllow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getPermission();
}
});
}
public void getPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
checkSelfPermission(WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE}, REQ_READ_WRITE_PERMISSION);
} else {
checkNeededPermission();
}
} else {
checkNeededPermission();
}
}
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQ_READ_WRITE_PERMISSION) {
if (permissions.length > 0) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED &&
grantResults[1] == PackageManager.PERMISSION_GRANTED) {
checkNeededPermission();
} else {
if (!shouldShowRequestPermissionRationale(READ_EXTERNAL_STORAGE) || !shouldShowRequestPermissionRationale(WRITE_EXTERNAL_STORAGE)) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Permission needed");
alert.setMessage("You must have to grant all required permission from settings to work app functions.");
alert.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
try {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivityForResult(intent, REQ_READ_WRITE_PERMISSION);
} catch (Exception e) {
e.printStackTrace();
}
dialogInterface.dismiss();
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
finish();
}
});
alert.create();
alert.show();
} else {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Permission needed");
alert.setMessage("App needs all permissions to work app functions.");
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
requestPermissions(new String[]{READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE}, REQ_READ_WRITE_PERMISSION);
dialogInterface.dismiss();
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
finish();
}
});
alert.create();
alert.show();
}
}
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if(resultCode == RESULT_OK) {
if (requestCode == REQ_READ_WRITE_PERMISSION) {
getPermission();
} else if (requestCode == REQ_WRITE_SETTING) {
getPermission();
}
// }
}
public void alertForWritePermission() {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Permission needed");
alert.setMessage("App needs to allow modify system setting permission from settings window.");
alert.setPositiveButton("Allow", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
getPermission();
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
loadInterstitialAds(PermissionActivity.this);
}
});
alert.create();
alert.show();
}
public void checkNeededPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.System.canWrite(this)) {
Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS);
intent.setData(Uri.parse("package:" + getPackageName()));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivityForResult(intent, REQ_WRITE_SETTING);
} else {
openMainScreen();
}
} else {
openMainScreen();
}
}
public void loadInterstitialAds(Activity context) {
try {
if (AdLoader.getAd().isLoaded()) {
AdLoader.interstitialAd.show();
// new AdLoader.LoadingAds(context).execute();
AdLoader.getAd().setAdListener(new AdListener() {
@Override
public void onAdFailedToLoad(LoadAdError loadAdError) {
super.onAdFailedToLoad(loadAdError);
Log.e("TAG", "FAIL AD LOAD : " + loadAdError);
AdLoader.initInterstitialAds();
openMainScreen();
}
@Override
public void onAdClosed() {
super.onAdClosed();
AdLoader.initInterstitialAds();
openMainScreen();
}
});
} else {
AdLoader.initInterstitialAds();
openMainScreen();
}
} catch (Exception e) {
e.printStackTrace();
openMainScreen();
}
}
public void openMainScreen() {
startActivity(new Intent(PermissionActivity.this, MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION));
finish();
}
}
|
import java.util.Scanner;
public class SleepIn {
/**
* @Rakesh Yadav
* 17 Feb 2015
* The parameter weekday is true if it is a weekday, and the
* parameter vacation is true is we are on vacation. We sleep
* in if it is not a weekday or we're on vacation. Return true if we sleep in.
*
* sleepInFun(false, false) -> true
* sleepInFun(true, false) -> false
* sleepInFun(false, true) -> true
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Input a Day: ");
String day = sc.next();
System.out.println("Input true for vacation and false for not on vacation: ");
boolean vacation = sc.nextBoolean();
boolean weekday = false;
if(day.equalsIgnoreCase("Monday")||day.equalsIgnoreCase("Tuesday")||day.equalsIgnoreCase("Wednesday")||day.equalsIgnoreCase("Thursday")||day.equalsIgnoreCase("Friday")){
weekday = true;
}
boolean sleep = sleepInFun(weekday, vacation);
if(sleep == true){
System.out.println("No need to wakeup early in the morning");
}
else
System.out.println("Please wake up, you need to go to office");
}
static boolean sleepInFun(boolean weekday, boolean vacation){
if (weekday == false || vacation == true)
return true;
else
return false;
}
}
|
package com.needii.dashboard.dao;
import com.needii.dashboard.model.Skus;
import com.needii.dashboard.utils.Pagination;
import com.needii.dashboard.model.form.SearchForm;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Repository("skuDao")
@Transactional
public class SkuDaoImpl extends AbstractDao<Integer, Skus> implements SkuDao {
@Autowired
private SessionFactory sessionFactory;
@SuppressWarnings("unchecked")
@Override
public List<Skus> findAll(SearchForm seachForm, Pagination pagination) {
// TODO Auto-generated method stub
Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Skus.class)
.add(Restrictions.eq("isDeleted", false))
.addOrder(Property.forName("id").desc());
int offset = pagination.getOffset();
int limit = pagination.getLimit();
criteria.setFirstResult(offset).setMaxResults(limit);
return criteria.list();
}
@Override
public Long count(SearchForm formSearch) {
// TODO Auto-generated method stub
Criteria criteria = sessionFactory.getCurrentSession()
.createCriteria(Skus.class).add(Restrictions.eq("isDeleted", false));
return (Long) criteria.setProjection(Projections.rowCount()).uniqueResult();
}
@Override
public Skus findOne(long id) {
return (Skus) sessionFactory.getCurrentSession()
.createCriteria(Skus.class)
.add(Restrictions.eq("id", id))
.uniqueResult();
}
@Override
public Skus findOne(String name, String language) {
return (Skus) sessionFactory.getCurrentSession()
.createCriteria(Skus.class)
.add(Restrictions.eq("name", name))
.uniqueResult();
}
@Override
public void create(Skus model) {
// TODO Auto-generated method stub
Session session = sessionFactory.getCurrentSession();
session.persist(model);
}
@Override
public void update(Skus model) {
// TODO Auto-generated method stub
Session session = sessionFactory.getCurrentSession();
session.update(model);
}
@Override
public void delete(Skus model) {
// TODO Auto-generated method stub
Session session = sessionFactory.getCurrentSession();
session.delete(model);
}
}
|
package com.pd.security.shiro.base;
import com.pd.security.shiro.config.SecurityConfig;
import com.pd.security.shiro.config.UserInfo;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
/**
* @author peramdy on 2018/10/23.
*/
public abstract class AbstractShiroFilterCustom {
public abstract SecurityConfig securityConfig(SecurityConfig securityConfig);
public abstract UserInfo userInfo(UserInfo userInfo);
/**
* @param config
* @param bean
* @return
*/
public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityConfig config, ShiroFilterFactoryBean bean) {
SecurityConfig securityConfig = securityConfig(config);
bean.setUnauthorizedUrl(securityConfig.getUnauthorizedUrl());
bean.setLoginUrl(securityConfig.getLoginUrl());
bean.setSuccessUrl(securityConfig.getSuccessUrl());
bean.setFilters(securityConfig.getFilters());
bean.setFilterChainDefinitions(securityConfig.getFilterChainDefinitions());
bean.setFilterChainDefinitionMap(securityConfig.getFilterChainDefinitionMap());
return bean;
}
public UserInfo getUserInfo(UserInfo userInfo) {
return userInfo(userInfo);
}
}
|
package cn.v5cn.v5cms.controller;
import cn.v5cn.v5cms.entity.Comments;
import cn.v5cn.v5cms.service.CommentsService;
import cn.v5cn.v5cms.util.HttpUtils;
import cn.v5cn.v5cms.util.SystemUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.session.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpServletRequest;
/**
* Created by ZXF-PC1 on 2015/7/28.
*/
@Controller
@RequestMapping("/manager/comment")
public class CommentsController {
private static final Logger LOGGER = LoggerFactory.getLogger(CommentsController.class);
@Autowired
private CommentsService commentsService;
@RequestMapping(value = "/list/{p}",method = {RequestMethod.GET,RequestMethod.POST})
public String commentsList(Comments comment,@PathVariable Integer p,HttpServletRequest request,ModelMap modelMap){
Session session = SystemUtils.getShiroSession();
if(StringUtils.isNotBlank(comment.getCommentContent())){
session.setAttribute("commentsSearch",comment);
modelMap.addAttribute("searchComments",comment);
}else{
session.setAttribute("commentsSearch",null);
}
Object searchObj = session.getAttribute("commentsSearch");
Page<Comments> result = commentsService.findCommentsPageable((searchObj == null ? (new Comments()) : ((Comments) searchObj)), p);
modelMap.addAttribute("comments",result.getContent());
modelMap.addAttribute("pagination", SystemUtils.pagination(result, HttpUtils.getContextPath(request) + "/manager/comment/list"));
return "comments/comments_list";
}
}
|
public abstract class Base {
int hp;
int power;
int defense;
String name;
String type;
public boolean isLive() {
if (this.hp < 1) {
return false;
}
return true;
}
public abstract void action(Base[] player, Base[] enemy);
}
|
package com.seven.contract.manage.controller.member;
import com.alibaba.fastjson.JSON;
import com.seven.contract.manage.common.ApiResult;
import com.seven.contract.manage.common.AppRuntimeException;
import com.seven.contract.manage.common.BaseController;
import com.seven.contract.manage.model.Contact;
import com.seven.contract.manage.model.Member;
import com.seven.contract.manage.service.ContactService;
import com.seven.contract.manage.service.MemberService;
import com.seven.contract.manage.utils.NumberUtil;
import com.seven.contract.manage.vo.ContactVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@CrossOrigin(origins = "*", allowedHeaders = "*")
@RestController
@RequestMapping(value = "/contact")
public class ContactController extends BaseController {
@Autowired
private ContactService contactService;
@Autowired
private MemberService memberService;
/**
* 联系人管理列表查询
* @param request
* @param search
* @return
*/
@PostMapping("/list/search")
public ApiResult getListForSearch(HttpServletRequest request, String search) {
Member member;
//登陆检测
try {
member = this.checkLogin(request);
} catch (AppRuntimeException e) {
return ApiResult.fail(request, e.getReqCode(), e.getMsg());
}
long mid = member.getId();
List<ContactVo> result = contactService.getListForSearch(mid, search);
logger.debug("result = {}", JSON.toJSONString(result));
return ApiResult.success(request, result);
}
/**
* 添加联系人
* @param request
* @param type 添加类型 PHONE:手机号 PUBLIC_KEYS:公钥
* @param search
* @return
*/
@PostMapping("/add")
public ApiResult add(HttpServletRequest request, String type, String search) {
Member member;
//登陆检测
try {
member = this.checkLogin(request);
} catch (AppRuntimeException e) {
return ApiResult.fail(request, e.getReqCode(), e.getMsg());
}
long mid = member.getId();
if (StringUtils.isEmpty(type) || StringUtils.isEmpty(search)) {
return ApiResult.fail(request, "入参不能为空");
}
Member contactMember = null;
if (type.equals("PHONE")) {
contactMember = memberService.selectOneByPhone(search);
} else if (type.equals("PUBLIC_KEYS")) {
contactMember = memberService.selectOneByPublicKeys(search);
} else {
return ApiResult.fail(request, "查询类型不正确");
}
if (contactMember == null) {
return ApiResult.fail(request, "用户不存在");
}
if (contactMember.getId() == mid) {
return ApiResult.fail(request, "联系人不能添加自己");
}
Map<String, Object> params = new HashMap<>();
params.put("mid", mid);
params.put("contactMid", contactMember.getId());
List<Contact> contacts = contactService.selectList(params);
if (contacts != null && contacts.size() > 0) {
return ApiResult.fail(request, "联系人已存在");
}
Contact contact = new Contact();
contact.setMid(mid);
contact.setContactMid(contactMember.getId());
contact.setAddTime(new Date());
contactService.save(contact);
return ApiResult.success(request);
}
/**
* 修改联系人备注
* @param request
* @param id 联系人关系ID
* @param remark
* @return
*/
@PostMapping("/update")
public ApiResult update(HttpServletRequest request, String id, String remark) {
Member member;
//登陆检测
try {
member = this.checkLogin(request);
} catch (AppRuntimeException e) {
return ApiResult.fail(request, e.getReqCode(), e.getMsg());
}
long mid = member.getId();
if (!NumberUtil.isNumeric(id) || StringUtils.isEmpty(remark)) {
return ApiResult.fail(request, "入参错误");
}
Contact contact = contactService.selectOneById(Long.valueOf(id));
if (contact == null || contact.getMid() != mid) {
return ApiResult.fail(request, "非法操作");
}
contact.setRemark(remark);
contactService.updateContact(contact);
return ApiResult.success(request);
}
}
|
package com.paschburg.rich.popularmovies;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import org.json.JSONException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* A fragment containing a simple view.
*/
public class PopularMoviesFragment extends Fragment {
// private GridViewAdapter mPopularMoviesAdapter;
private GridViewAdapter mPopularMoviesAdapter;
private GridView gridVies;
Integer imageLocations[] = { R.drawable.spaceodyssey, R.drawable.spaceodysseycopy, R.drawable.spaceodysseycopy2,
R.drawable.spaceodysseycopy3, R.drawable.spaceodysseycopy4, R.drawable.spaceodysseycopy5,
R.drawable.spaceodysseycopy6, R.drawable.spaceodysseycopy7};
ImageItem[] imageitems = new ImageItem[4];
String[] imageitems1 = new String[] {
"movie information",
"second movie information",
"third movie information",
"fourth movie information",
"fifth movie information",
"sixth movie information",
"seventh movie information",
"eighth movie information",
"ninth movie information",
"tenth movie information",
"movie information",
"second movie information",
"third movie information",
"fourth movie information",
"fifty movie information",
"sixth movie information",
"seventh movie information",
"eighth movie information",
"ninth movie information",
"tenth movie information",
"movie information",
"second movie information",
"third movie information",
"fourth movie information",
"fifty movie information",
"sixth movie information",
"seventh movie information",
"eighth movie information",
"ninth movie information",
"tenth movie information",
"movie information",
"second movie information",
"third movie information",
"fourth movie information",
"fifty movie information",
"sixth movie information",
"seventh movie information",
"eighth movie information",
"ninth movie information",
"tenth movie information",
"movie information",
"second movie information",
"third movie information",
"fourth movie information",
"fifty movie information",
"sixth movie information",
"seventh movie information",
"eighth movie information",
"ninth movie information",
"tenth movie information",
"movie information",
"second movie information",
"third movie information",
"fourth movie information",
"fifty movie information",
"sixth movie information",
"seventh movie information",
"eighth movie information",
"ninth movie information",
"tenth movie information",
"movie information",
"second movie information",
"third movie information",
"fourth movie information",
"fifty movie information",
"sixth movie information",
"seventh movie information",
"eighth movie information",
"ninth movie information",
"tenth movie information"
};
public PopularMoviesFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.popularmoviesfragment, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
Log.e("****************", "hit refresh");
FetchMoviesTask popularmoviesTask = new FetchMoviesTask();
popularmoviesTask.execute("orderbyrating");
return true;
}
if (id == R.id.action_orderbypopularity) {
FetchMoviesTask popularmoviesTask = new FetchMoviesTask();
popularmoviesTask.execute("orderbypopularity");
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// todo
// List<ImageItem> data = new List<ImageItem>(imageitems);
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
// todo Debug this assignment and fix type mismatch
// gridView = (GridView) rootView.findViewById(R.id.gridView);
// gridView.setAdapter(mPopularMoviesAdapter);
// ListView listview = (ListView) rootView.findViewById(R.id.grid_item_layout);
// listview.setAdapter(mPopularMoviesAdapter);
GridView gridView = (GridView) rootView.findViewById(R.id.gridView1);
// gridView.setAdapter(mPopularMoviesAdapter);
String resultStrs[] = new String[20];
String[] json = {
"tbhdm8UJAb4ViCTsulYFL3lxMCd.jpg",
"kqjL17yufvn9OVLyXYpvtyrFfak.jpg",
"dkMD5qlogeRMiEixC4YNPUvax2T.jpg",
"g23cs30dCMiG4ldaoVNP1ucjs6.jpg",
"cUfGqafAVQkatQ7N4y08RNV3bgu.jpg",
"tbhdm8UJAb4ViCTsulYFL3lxMCd.jpg",
"kqjL17yufvn9OVLyXYpvtyrFfak.jpg",
"dkMD5qlogeRMiEixC4YNPUvax2T.jpg",
"g23cs30dCMiG4ldaoVNP1ucjs6.jpg",
"cUfGqafAVQkatQ7N4y08RNV3bgu.jpg",
"tbhdm8UJAb4ViCTsulYFL3lxMCd.jpg",
"kqjL17yufvn9OVLyXYpvtyrFfak.jpg",
"dkMD5qlogeRMiEixC4YNPUvax2T.jpg",
"g23cs30dCMiG4ldaoVNP1ucjs6.jpg",
"cUfGqafAVQkatQ7N4y08RNV3bgu.jpg",
"tbhdm8UJAb4ViCTsulYFL3lxMCd.jpg",
"kqjL17yufvn9OVLyXYpvtyrFfak.jpg",
"dkMD5qlogeRMiEixC4YNPUvax2T.jpg",
"g23cs30dCMiG4ldaoVNP1ucjs6.jpg",
"cUfGqafAVQkatQ7N4y08RNV3bgu.jpg"
};
ImageItem[] imageitems2 = new ImageItem[20];
Uri.Builder builder;
// http://image.tmdb.org/t/p/w185//nBNZadXqJSdt05SHLqgT0HuC5Gm.jpg
for (int i=0; i < 20; i++){
builder = new Uri.Builder();
builder.scheme("http")
.authority("image.tmdb.org")
.appendPath("t")
.appendPath("p")
.appendPath("w185")
.appendPath("")
.appendPath(json[i]);
imageitems2[i] = new ImageItem();
imageitems2[i].imagep = builder.build().toString();
}
mPopularMoviesAdapter = new GridViewAdapter (
getActivity(),
R.layout.grid_item_layout,
imageitems2);
gridView.setAdapter(mPopularMoviesAdapter);
// Reference: developer.android.com
FetchMoviesTask fetch=new FetchMoviesTask();
fetch.execute("orderbypopularity");
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("movie1", 1);
editor.putString("movieinfo1", "information on movie 1");
editor.putString("movieimage1", "key to get movie 1");
editor.putInt("movie2", 2);
editor.putString("movieinfo2","information on movie 2");
editor.putString("movieimage2","key to get movie 2");
editor.putInt("movie3",3);
editor.putString("movieinfo3","information on movie 3");
editor.putString("movieimage3","key to get movie 3");
editor.putInt("movie4",4);
editor.putString("movieinfo4","information on movie 4");
editor.putString("movieimage1","key to get movie 4");
editor.putInt("movie5",5);
editor.putString("movieinfo5","information on movie 5");
editor.putString("movieimage5","key to get movie 5");
editor.putInt("movie6",6);
editor.putString("movieinfo6","information on movie 6");
editor.putString("movieimage6","key to get movie 6");
editor.putInt("movie7",7);
editor.putString("movieinfo7","information on movie 7");
editor.putString("movieimage7","key to get movie 7");
editor.putInt("movie8",8);
editor.putString("movieinfo8","information on movie 8");
editor.putString("movieimage8","key to get movie 8");
editor.putInt("movie9",9);
editor.putString("movieinfo9","information on movie 9");
editor.putString("movieimage9","key to get movie 9");
editor.putInt("movie10",10);
editor.putString("movieinfo10","information on movie 10");
editor.putString("movieimage10","key to get movie 10");
editor.putInt("movie11",11);
editor.putString("movieinfo11","information on movie 11");
editor.putString("movieimage11","key to get movie 11");
editor.putInt("movie12",12);
editor.putString("movieinfo12","information on movie 12");
editor.putString("movieimage12","key to get movie 12");
editor.putInt("movie13",13);
editor.putString("movieinfo13","information on movie 13");
editor.putString("movieimage13","key to get movie 13");
editor.putInt("movie14",14);
editor.putString("movieinfo14","information on movie 14");
editor.putString("movieimage14","key to get movie 14");
editor.putInt("movie15",15);
editor.putString("movieinfo15","information on movie 15");
editor.putString("movieimage15","key to get movie 15");
editor.putInt("movie16",16);
editor.putString("movieinfo16","information on movie 16");
editor.putString("movieimage16","key to get movie 16");
editor.putInt("movie17",17);
editor.putString("movieinfo17","information on movie 17");
editor.putString("movieimage17","key to get movie 17");
editor.putInt("movie18",18);
editor.putString("movieinfo18","information on movie 18");
editor.putString("movieimage18","key to get movie 18");
editor.putInt("movie19",19);
editor.putString("movieinfo19","information on movie 19");
editor.putString("movieimage19","key to get movie 19");
editor.putInt("movie20",20);
editor.putString("movieinfo20","information on movie 20");
editor.putString("movieimage20","key to get movie 20");
// for (String dayForecastStr : result) {
// mPopularMoviesAdapter.add(dayForecastStr);
// }
return rootView;
}
/*
public class FetchMoviesTask extends AsyncTask<String, Void, String[]> {
private final String LOG_TAG = FetchMoviesTask.class.getSimpleName();
// The date/time conversion code is going to be moved outside the asynctask later,
// so for convenience we're breaking it out into its own method now.
//
//
// Prepare the weather high/lows for presentation.
//
private String formatHighLows(double high, double low) {
// For presentation, assume the user doesn't care about tenths of a degree.
long roundedHigh = Math.round(high);
long roundedLow = Math.round(low);
String highLowStr = roundedHigh + "/" + roundedLow;
return highLowStr;
}
//
// Take the String representing the complete forecast in JSON Format and
// pull out the data we need to construct the Strings needed for the wireframes.
//
// Fortunately parsing is easy: constructor takes the JSON string and converts it
// into an Object hierarchy for us.
//
private String[] getMovieDataFromJson(String movieJsonStr, int numMovies)
throws JSONException {
// These are the names of the JSON objects that need to be extracted.
final String OWM_LIST = "list";
final String OWM_WEATHER = "weather";
final String OWM_TEMPERATURE = "temp";
final String OWM_MAX = "max";
final String OWM_MIN = "min";
final String OWM_DESCRIPTION = "main";
JSONObject movieJson = new JSONObject(movieJsonStr);
JSONArray movieArray = movieJson.getJSONArray(OWM_LIST);
// OWM returns daily forecasts based upon the local time of the city that is being
// asked for, which means that we need to know the GMT offset to translate this data
// properly.
// Since this data is also sent in-order and the first day is always the
// current day, we're going to take advantage of that to get a nice
// normalized UTC date for all of our weather.
Time dayTime = new Time();
dayTime.setToNow();
// we start at the day returned by local time. Otherwise this is a mess.
int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);
// now we work exclusively in UTC
dayTime = new Time();
String[] resultStrs = new String[numMovie];
for (int i = 0; i < movieArray.length(); i++) {
// For now, using the format "Day, description, hi/low"
String day;
String description;
String highAndLow;
// Get the JSON object representing the day
JSONObject dayForecast = weatherArray.getJSONObject(i);
// The date/time is returned as a long. We need to convert that
// into something human-readable, since most people won't read "1400356800" as
// "this saturday".
long dateTime;
// Cheating to convert this to UTC time, which is what we want anyhow
dateTime = dayTime.setJulianDay(julianStartDay + i);
day = getReadableDateString(dateTime);
// description is in a child array called "weather", which is 1 element long.
JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
description = weatherObject.getString(OWM_DESCRIPTION);
// Temperatures are in a child object called "temp". Try not to name variables
// "temp" when working with temperature. It confuses everybody.
JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
double high = temperatureObject.getDouble(OWM_MAX);
double low = temperatureObject.getDouble(OWM_MIN);
highAndLow = formatHighLows(high, low);
resultStrs[i] = day + " - " + description + " - " + highAndLow;
}
return resultStrs;
}
public FetchWeatherTask() {
super();
}
@Override
protected String[] doInBackground(String... params) {
if (params.length == 0) {
return null;
}
HttpURLConnection urlConnection = null;
//BufferedReader reader =
// Will contain the raw JSON response as a String.
String forecastJsonStr;
// String zip = "95051";
String location = params[0] + ",us";
int numDays = 7;
try {
Uri.Builder builder = new Uri.Builder();
builder.scheme("http")
.authority("api.openweathermap.org")
.appendPath("data")
.appendPath("2.5")
.appendPath("forecast")
.appendPath("daily")
.appendQueryParameter("zip", location)
.appendQueryParameter("mode", "json")
.appendQueryParameter("units", "metric")
.appendQueryParameter("cnt", "7");
String myUrl = builder.build().toString();
URL url = new URL(myUrl);
// url = new URL("http://api.openweathermap.org/data/2.5/forecast/daily?zip=95051,us&mode=json&units=metric&cnt=7");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Nothing to do.
return null;
}
forecastJsonStr = buffer.toString();
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream.");
}
}
}
try {
return getWeatherDataFromJson(forecastJsonStr, numDays);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
// will normally not hit this code
return null;
}
@Override
protected void onPostExecute(String[] result) {
if (result != null) {
mPopularMoviesAdapter.clear();
for (String dayForecastStr : result) {
mPopularMoviesAdapter.add(dayForecastStr);
}
}
}
}
*/
public class FetchMoviesTask extends AsyncTask<String, Void, String[]> {
private final String LOG_TAG = FetchMoviesTask.class.getSimpleName();
public FetchMoviesTask() {
super();
}
@Override
protected String[] doInBackground(String... params) {
if (params.length == 0) {
return null;
}
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a String.
String popularMoviesJsonStr = null;
try
{
ApiKey apiKey = new ApiKey();
String apikeystring = apiKey.get();
Uri.Builder builder = new Uri.Builder();
/*
builder.scheme("http")
.authority("image.tmdb.org")
.appendPath("t")
.appendPath("p")
.appendPath("w185")
.appendPath(apiMovieJpg);
*/
builder.scheme("http")
.authority("api.themoviedb.org")
.appendPath("3")
.appendPath("discover")
.appendPath("movie")
.appendQueryParameter("sort_by","popularity.desc")
.appendQueryParameter("api_key",apikeystring);
String builderString = String.format("url = %1$s", builder);
Log.e(LOG_TAG, builderString);
String myUrl = builder.build().toString();
URL url = new URL(myUrl);
// url = new URL("http://api.themoviedb.org/3/<apikey>/discover/movie?sort_by=popularity.sort");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null){
Log.e(LOG_TAG, "line = " + line);
buffer.append(line);
}
if (buffer.length() == 0) {
// Nothing to do.
return null;
}
popularMoviesJsonStr = buffer.toString();
// Log.e(LOG_TAG, popularMoviesJsonStr); // debug statement
}
catch (IOException e)
{
Log.e(LOG_TAG, "Error = " + e.getMessage() , e);
return null;
}
finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null ) {
try {
reader.close();
}
catch (final IOException e){
Log.e(LOG_TAG, "Error closing stream.");
}
}
}
try {
return getPopularMoviesDataFromJson(popularMoviesJsonStr, 20);
}
catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
// will normally not hit this code
return null;
}
@Override
protected void onPostExecute(String[] result) {
if (result != null ) {
/*
imageitems = new ImageItem[result.length];
int i;
int j = result.length;
for ( i = 0; i < j; i++){
// imageitems[i] = BitmapFactory.decodeResource(getResources(), imageLocations[i]);
imageitems[ i ] = new ImageItem(result[i]);
}
*/
// List<ImageItem> imageitemslist = new ArrayList<ImageItem>(Arrays.asList(imageitems));
mPopularMoviesAdapter.clear();
int l = result.length;
for (int i=0; i<l; i++) {
ImageItem imageItem = new ImageItem();
imageItem.imagep = result[i];
mPopularMoviesAdapter.addImageItem(i,imageItem);
}
//gridView.setAdapter(mPopularMoviesAdapter);
}
}
private String[] getPopularMoviesDataFromJson(String popularMoviesJsonStr, int numMovies)
throws JSONException {
// TODO evaluate JSON from api
String resultStrs[] = new String[numMovies];
String[] json = {
"tbhdm8UJAb4ViCTsulYFL3lxMCd.jpg",
"kqjL17yufvn9OVLyXYpvtyrFfak.jpg",
"dkMD5qlogeRMiEixC4YNPUvax2T.jpg",
"g23cs30dCMiG4ldaoVNP1ucjs6.jpg",
"cUfGqafAVQkatQ7N4y08RNV3bgu.jpg",
"tbhdm8UJAb4ViCTsulYFL3lxMCd.jpg",
"kqjL17yufvn9OVLyXYpvtyrFfak.jpg",
"dkMD5qlogeRMiEixC4YNPUvax2T.jpg",
"g23cs30dCMiG4ldaoVNP1ucjs6.jpg",
"cUfGqafAVQkatQ7N4y08RNV3bgu.jpg",
"tbhdm8UJAb4ViCTsulYFL3lxMCd.jpg",
"kqjL17yufvn9OVLyXYpvtyrFfak.jpg",
"dkMD5qlogeRMiEixC4YNPUvax2T.jpg",
"g23cs30dCMiG4ldaoVNP1ucjs6.jpg",
"cUfGqafAVQkatQ7N4y08RNV3bgu.jpg",
"tbhdm8UJAb4ViCTsulYFL3lxMCd.jpg",
"kqjL17yufvn9OVLyXYpvtyrFfak.jpg",
"dkMD5qlogeRMiEixC4YNPUvax2T.jpg",
"g23cs30dCMiG4ldaoVNP1ucjs6.jpg",
"cUfGqafAVQkatQ7N4y08RNV3bgu.jpg"
};
// These are the names of the JSON objects that need to be extracted.
final String TMDB_IMAGE = "backdrop_path";
final String TMDB_TITLE = "original_title";
final String TMDB
Uri.Builder builder;
// http://image.tmdb.org/t/p/w185//nBNZadXqJSdt05SHLqgT0HuC5Gm.jpg
for (int i=0; i < numMovies; i++){
builder = new Uri.Builder();
builder.scheme("http")
.authority("image.tmdb.org")
.appendPath("t")
.appendPath("p")
.appendPath("w185")
.appendPath("")
.appendPath(json[i]);
resultStrs[i] = builder.build().toString();
}
return resultStrs;
}
}
}
|
package com.esum.framework.core.component.handler;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.esum.framework.core.component.interceptor.Interceptable;
/**
* Handler.
*/
public class BasicHandler implements Handler {
protected Logger log = LoggerFactory.getLogger(BasicHandler.class);
private String componentId;
protected String traceId = null;
private List<Interceptable> interceptors;
protected BasicHandler(String componentId) {
this.componentId = componentId;
this.traceId = "["+componentId+"] ";
interceptors = new ArrayList<Interceptable>();
}
public String getComponentId() {
return componentId;
}
public void setComponentId(String componentId) {
this.componentId = componentId;
}
public void setLog(Logger log) {
this.log = log;
}
public List<Interceptable> getInterceptors() {
return interceptors;
}
public void setInterceptors(List<Interceptable> interceptors) {
this.interceptors = interceptors;
}
public void addInterceptor(Interceptable interceptor) {
this.interceptors.add(interceptor);
}
public void removeInterceptor(Interceptable interceptor) {
this.interceptors.remove(interceptor);
}
}
|
package com.ahu.controller;
import com.ahu.constant.MessageConstant;
import com.ahu.entity.Result;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author :hodor007
* @date :Created in 2020/12/2
* @description :
* @version: 1.0
*/
@RestController
@RequestMapping("/user")
public class UserController {
@RequestMapping("/getUserName")
public Result getUserName(){
try {
//返回上下文对象
SecurityContext securityContext = SecurityContextHolder.getContext();
//获取认证信息
Authentication authentication = securityContext.getAuthentication();
//获取签名,是框架的User
User user = (User) authentication.getPrincipal();
return new Result(true, MessageConstant.GET_USERNAME_SUCCESS, user.getUsername());
} catch (Exception e) {
e.printStackTrace();
return new Result(true, MessageConstant.GET_USERNAME_FAIL);
}
}
}
|
import java.io.File;
import java.io.IOException;
public class FileTest {
public static void main(String[] args) throws IOException {
//file 的对象是目录或者文件
File file = new File("D:\\java\\eclipse-workspace\\IO\\.");
System.out.println("返回绝对经:: "+file.getAbsolutePath());
System.out.println("返回最后一级子路径名: "+file.getName());
System.out.println("返回file对象路径名: "+file.getPath());
System.out.println("返回getName的父路径名: "+file.getParent());
System.out.println("返回对象的绝对路径: "+file.getAbsoluteFile());
System.out.println("\n创建新的file对象");
File file1 = new File(".");
System.out.println("这种情况会出错: "+file1.getParent());
System.out.println("这种方式解决:"+file1.getAbsoluteFile().getParent()+'\n');
//若File对象对应的文件不存在,创建一个新的文件
File file2 = new File("D:\\java\\eclipse-workspace\\IO\\.test.txt");
if(file2.createNewFile()) {
System.out.println("新文件创建成功!");
}
else System.out.println("该文件已存在!\n");
//创建新的文件,并且在JVM退出时删除文件
//file2.delete();
//以系统时间为名字创建一个文件
File newFile = new File(System.currentTimeMillis()+" ");
newFile.createNewFile();
//输出当前路径下的所有文件和路径(返回该路径下所有的文件名)
File file3 = new File("D:\\java\\eclipse-workspace");
String[] fileList = file3.list(); //只能是路径,而不是当前文件下的所有路径和文件(返回该路径下所有的文件名)
for(String fileName : fileList) {
System.out.println(fileName+'\n');
}
//ListRoots()静态方法 获得所有磁盘的跟路径
File[] roots = File.listRoots();
for(File root : roots) {
System.out.println(root);
}
}
}
|
package com.pibs.constant;
/**
*
* @author dward
*
*/
public class ParamConstant {
public static final String AJAX_SEARCH = "ajaxSearch";
public static final String AJAX_SEARCH_BY_CRITERIA = "ajaxSearchByCriteria";
public static final String AJAX_ADD = "ajaxAdd";
public static final String AJAX_SAVE = "ajaxSave";
public static final String AJAX_EDIT = "ajaxEdit";
public static final String AJAX_UPDATE = "ajaxUpdate";
public static final String AJAX_DELETE = "ajaxDelete";
public static final String AJAX_RESTORE = "ajaxRestore";
public static final String AJAX_GENERATE = "ajaxGenerate";
public static final String AJAX_GO_TO = "ajaxGoTo";
public static final String AJAX_GO_TO_SEARCH = "ajaxGoToSearch";
public static final String AJAX_GO_TO_CHILD = "ajaxGoToChild";
public static final String AJAX_GO_TO_CHILD_SEARCH = "ajaxGoToChildSearch";
}
|
public class Statex {
int idno;
String name;
static String cmpname="TCS";
Statex(int i,String n)
{
idno=i;
name=n;
}
void disply()
{
System.out.println("emp id:"+idno);
System.out.println("emp name:"+name);
System.out.println("company name:"+cmpname);
}
public static void main(String[] args) {
Statex s1=new Statex(202014,"preetha");
Statex s2=new Statex(202015,"sheela");
s1.disply();
s2.disply();
}
}
output:
emp id:202014
emp name:preetha
company name:TCS
emp id:202015
emp name:sheela
company name:TCS
|
/* ------------------------------------------------------------------------------
*
* 软件名称:泡泡娱乐交友平台(手机版)
* 公司名称:北京双迪信息技术有限公司
* 开发作者:Yongchao.Yang
* 开发时间:2012-8-16/2012
* All Rights Reserved 2012-2015
* ------------------------------------------------------------------------------
* 注意:本内容仅限于北京双迪信息技术有限公司内部使用 禁止转发
* ------------------------------------------------------------------------------
* prj-name:com.popo.transaction
* fileName:com.popo.func.BasicFun.java
* -------------------------------------------------------------------------------
*/
package com.rednovo.ace.activity.ds;
import java.util.ArrayList;
/**
* 数据源管理器
*
* @author Administrator
*
*/
public class DataSourceUtil {
private static String DB_DATA_SOURCE_ACE_ACTIVITY = "ace_activity";
private static String DB_DATA_SOURCE_ACE_USER = "ace_user";
private static ArrayList<String> dsList = new ArrayList<String>();
static {
dsList.add(DB_DATA_SOURCE_ACE_ACTIVITY);
dsList.add(DB_DATA_SOURCE_ACE_USER);
}
public static ArrayList<String> getDataSourceList() {
return dsList;
}
public static String getActivityUserDataSource() {
return DB_DATA_SOURCE_ACE_ACTIVITY;
}
public static String getServiceUserDataSource() {
return DB_DATA_SOURCE_ACE_USER;
}
}
|
package com.grocery.codenicely.vegworld_new.products.model;
/**
* Created by Meghal on 6/28/2016.
*/
public class ProductQuantityUpdateData {
private boolean success;
private String message;
private int product_id;
private int quantity;
private int total;
private int total_discounted;
private int cart_count;
private int position;
public ProductQuantityUpdateData(boolean success, String message, int product_id, int quantity, int total, int total_discounted, int cart_count, int position) {
this.success = success;
this.message = message;
this.product_id = product_id;
this.quantity = quantity;
this.total = total;
this.total_discounted = total_discounted;
this.cart_count = cart_count;
this.position = position;
}
public boolean isSuccess() {
return success;
}
public String getMessage() {
return message;
}
public int getProduct_id() {
return product_id;
}
public int getQuantity() {
return quantity;
}
public int getTotal() {
return total;
}
public int getTotal_discounted() {
return total_discounted;
}
public int getCart_count() {
return cart_count;
}
public int getPosition() {
return position;
}
}
|
package com.nowcoder.community;
import com.nowcoder.community.dao.DiscussPostRepository;
import com.nowcoder.community.dao.DiscussionPostMapper;
import com.nowcoder.community.entity.DiscussPost;
import org.apache.kafka.common.protocol.types.Field;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = CommunityApplication.class)
public class ElasticSearchTest {
@Autowired
private DiscussPostRepository discussPostRepository;
@Autowired
private DiscussionPostMapper discussionPostMapper;
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
@Test
public void testInsert(){
discussPostRepository.save(discussionPostMapper.selectPostById(241));
discussPostRepository.save(discussionPostMapper.selectPostById(242));
discussPostRepository.save(discussionPostMapper.selectPostById(243));
}
@Test
public void testInsertList(){
discussPostRepository.saveAll(discussionPostMapper.selectUserPosts(101,0,100));
discussPostRepository.saveAll(discussionPostMapper.selectUserPosts(102,0,100));
discussPostRepository.saveAll(discussionPostMapper.selectUserPosts(103,0,100));
}
@Test
public void testUpdateList(){
DiscussPost discussPost = discussionPostMapper.selectPostById(241);
discussPost.setContent("4565456465465456");
discussPostRepository.save(discussPost);
}
@Test
public void testDeleteList(){
discussPostRepository.deleteAll();
}
@Test
public void testSearchByRepository(){
SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(QueryBuilders.multiMatchQuery("互联网寒冬","title","content"))
.withSort(SortBuilders.fieldSort("type").order(SortOrder.DESC))
.withSort(SortBuilders.fieldSort("score").order(SortOrder.DESC))
.withSort(SortBuilders.fieldSort("score").order(SortOrder.DESC))
.withPageable(PageRequest.of(0,100))
.withHighlightFields(
new HighlightBuilder.Field("title").preTags("<em>").postTags("</em>"),
new HighlightBuilder.Field("content").preTags("<em>").postTags("</em>")
).build();
Page<DiscussPost> page = discussPostRepository.search(searchQuery);
System.out.println(page.getTotalElements());
System.out.println(page.getTotalPages());
System.out.println(page.getNumber());
System.out.println(page.getSize());
for(DiscussPost post:page){
System.out.println(post);
}
}
@Test
public void testElasticsearchTemplate(){
SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(QueryBuilders.multiMatchQuery("互联网寒冬","title","content"))
.withSort(SortBuilders.fieldSort("type").order(SortOrder.DESC))
.withSort(SortBuilders.fieldSort("score").order(SortOrder.DESC))
.withSort(SortBuilders.fieldSort("score").order(SortOrder.DESC))
.withPageable(PageRequest.of(0,100))
.withHighlightFields(
new HighlightBuilder.Field("title").preTags("<em>").postTags("</em>"),
new HighlightBuilder.Field("content").preTags("<em>").postTags("</em>")
).build();
Page<DiscussPost> page = elasticsearchTemplate.queryForPage(searchQuery, DiscussPost.class, new SearchResultMapper() {
@Override
public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
SearchHits hits = response.getHits();
if (hits.getTotalHits() < 0) {
return null;
}
List<DiscussPost> list = new ArrayList<>();
for (SearchHit hit : hits) {
DiscussPost discussPost = new DiscussPost();
String id = hit.getSourceAsMap().get("id").toString();
discussPost.setId(Integer.valueOf(id));
String userId = hit.getSourceAsMap().get("userId").toString();
discussPost.setUserId(Integer.valueOf(userId));
String type = hit.getSourceAsMap().get("type").toString();
discussPost.setType(Integer.valueOf(type));
String status = hit.getSourceAsMap().get("status").toString();
discussPost.setType(Integer.valueOf(status));
String createTime = hit.getSourceAsMap().get("createTime").toString();
discussPost.setCreateTime(new Date(Long.valueOf(createTime)));
String commentCount = hit.getSourceAsMap().get("commentCount").toString();
discussPost.setCommentCount(Integer.valueOf(commentCount));
String score = hit.getSourceAsMap().get("score").toString();
discussPost.setScore(Double.valueOf(commentCount));
String content = hit.getSourceAsMap().get("content").toString();
discussPost.setContent(String.valueOf(content));
String title = hit.getSourceAsMap().get("title").toString();
discussPost.setContent(String.valueOf(title));
/**
* 这段代码
*/
HighlightField titleField = hit.getHighlightFields().get("title");
if (titleField != null) {
discussPost.setTitle(titleField.getFragments()[0].toString());
}
/**
* 这段代码
*/
HighlightField contentField = hit.getHighlightFields().get("content");
if (contentField != null) {
discussPost.setTitle(contentField.getFragments()[0].toString());
}
list.add(discussPost);
}
return new AggregatedPageImpl(list, pageable, hits.getTotalHits(), response.getAggregations(), response.getScrollId(), hits.getMaxScore());
}
});
// System.out.println(page.getTotalElements());
// System.out.println(page.getTotalPages());
// System.out.println(page.getNumber());
// System.out.println(page.getSize());
// for(DiscussPost post:page){
// System.out.println(post);
// }
}
}
|
package com.itheima.bos.web.action;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import cn.itcast.crm.domain.Customer;
import com.itheima.bos.crm.CustomerService;
import com.itheima.bos.domain.Decidedzone;
import com.itheima.bos.web.action.base.BaseAction;
/**
* 定区管理Action
*/
@Controller
@Scope("prototype")
public class DecidedzoneAction extends BaseAction<Decidedzone>{
//属性驱动,接收分区id数组
private String[] subareaid;
/**
* 添加定区
*/
public String add(){
decidedzoneService.save(model,subareaid);
return "list";
}
//注入代理对象
@Resource
private CustomerService customerService;
/**
* 分页查询
*/
public String pageQuery(){
decidedzoneService.pageQuery(pageBean);
String[] excludes = new String[]{"subareas","decidedzones"};
this.writePageBean2Json(pageBean, excludes );
return NONE;
}
/**
* 获取未关联到定区的客户数据,返回json
*/
public String findCustomerNotAssociation(){
//使用代理对象远程调用crm服务,获取客户数据
List<Customer> list = customerService.findnoassociationCustomers();
String[] excludes = new String[]{};
this.writeListBean2Json(list, excludes);
return NONE;
}
/**
* 获取已经关联到指定定区的客户数据,返回json
*/
public String findCustomerAssociation(){
String id = model.getId();
List<Customer> list = customerService.findhasassociationCustomers(id);
String[] excludes = new String[]{};
this.writeListBean2Json(list, excludes);
return NONE;
}
//接收客户id数组
private Integer[] customerIds;
/**
* 定区关联客户
*/
public String assigncustomerstodecidedzone(){
//调用代理对象,远程调用crm服务,完成定区关联客户
customerService.assignCustomersToDecidedZone(customerIds, model.getId());
return "list";
}
public void setSubareaid(String[] subareaid) {
this.subareaid = subareaid;
}
public void setCustomerIds(Integer[] customerIds) {
this.customerIds = customerIds;
}
}
|
package invadem;
import processing.core.PApplet;
import processing.core.PFont;
import java.awt.*;
import java.util.Random;
public class App extends PApplet {
static int BULLET_SIZE =2000;
static int POWER_BULLET_SIZE = 100;
static int INVADER_NUMBER =40;
static int spacer = 80;
static int HITS_NUM = 0;
static int CONDITION = 0;
static int BARRIER_BASE_X = 160;
static int BARRIER_NUM = 3;
static boolean ALIENS_FLAG = false;
static int FRAME_INDEX =0;
static int FRAME_RATE = 100;
PFont pFont;
ScoreBoard scoreBoard;
Tank tank;
Barrier barriers[];
Projectile[] projectiles = new Projectile[BULLET_SIZE];
PowerProjectile[] powerProjectiles = new PowerProjectile[POWER_BULLET_SIZE];
Invader[] invaders = new Invader[INVADER_NUMBER];
int saved_time;
public App() {
//Set up your objects
//init data
init();
}
/**
* Setup the game environment
*/
public void setup() {
frameRate(60);
pFont = createFont("PressStart2P-Regular.tff",32);
scoreBoard = new ScoreBoard();
}
public void settings() {
size(640, 480);
}
public void draw() {
//Main Game Loop
background(0);
textFont(pFont);
FRAME_INDEX++;
switch (CONDITION){
case 0:
//show score
showScoreBoard();
// aliens shot
aliensShot();
//check tank;
checkTank();
//show barriers
showBarriers();
//show tank
TankDisplay();
//check destroy
checkAliensDestoried();
//check BarrierHit
checkBarrierHit();
//show bullets
showBullets();
//show aliens
showAliens();
//Check condition
ConditionSwitch();
break;
case 1:
//show next stage image
nextStage();
break;
case 2:
gameOver();
default:
break;
}
}
public void keyPressed() {
if(keyCode==LEFT){
if(tank.x_pos<4){
return;
}
tank.x_pos-=4;
}
if(keyCode==RIGHT){
if(tank.x_pos>612){
return;
}
tank.x_pos+=4;
}
if(key==' '){
for(int i=0;i<BULLET_SIZE;i++){
if(projectiles[i].flag==0 && projectiles[i].shoter==0){
projectiles[i].shot(tank.x_pos,tank.y_pos);
break;
}
}
}
}
public void init(){
tank = new Tank(320,400,"tank1.png");
barriers = new Barrier[3];
//normal bullet
for(int i=0;i<BULLET_SIZE;i++){
projectiles[i] = new Projectile();
}
//Power bullet
for(int i=0; i< POWER_BULLET_SIZE;i++){
powerProjectiles[i]= new PowerProjectile();
}
//Armoured Invaders
for(int i=0;i<10;i++){
invaders[i] = new ArmouredInvader();
}
//Power Invaders
for(int i=10;i<20;i++){
invaders[i] = new PowerInvader();
}
//Normal
for(int i=20;i<40;i++){
invaders[i] = new Invader();
}
int index =0;
for(int i =0;i<4;i++){
for(int j = 0;j<10;j++){
invaders[index].x_pos=spacer+10+spacer/2*j;
invaders[index].y_pos=spacer+i*spacer/2-30;
index++;
}
}
// for(int i=0;i<ALIENS_BULLETS;i++){
// aliens_bullets[i] = new Bullet();
// }
for(int i=0;i<BARRIER_NUM;i++){
barriers[i] = new Barrier();
}
}
/**
* Set all the barriers on the screen, including the solids inside that
*/
public void showBarriers(){
for(int i=0;i<barriers.length; i++){
image(loadImage(barriers[i].img_left),BARRIER_BASE_X*(i+1)-8,360);
image(loadImage(barriers[i].img_top),BARRIER_BASE_X*(i+1),360);
image(loadImage(barriers[i].img_right),BARRIER_BASE_X*(i+1)+8,360);
barriers[i].top_pos = 360;
barriers[i].bot_pos = 368;
barriers[i].left_pos = BARRIER_BASE_X*(i+1)-8;
barriers[i].right_pos = BARRIER_BASE_X*(i+1)+8;
Solid[]left_solid = barriers[i].left_solids;
Solid[]right_solid = barriers[i].right_solids;
int index_l=0;
for(Solid s:left_solid){
image(loadImage(s.img),BARRIER_BASE_X*(i+1)-8,368+index_l*8);
s.top_pos = 368+index_l*8;
s.bot_pos = 368+index_l*8+8;
s.left_pos = BARRIER_BASE_X*(i+1)-8;
s.right_pos = BARRIER_BASE_X*(i+1);
index_l++;
}
int index_r =0;
for(Solid s:right_solid){
image(loadImage(s.img),BARRIER_BASE_X*(i+1)+8,368+index_r*8);
s.top_pos = 368+index_r*8;
s.bot_pos = 368+index_r*8+8;
s.left_pos = BARRIER_BASE_X*(i+1)+8;
s.right_pos = BARRIER_BASE_X*(i+1)+16;
index_r++;
}
}
}
/**
* Display the tank on the screen
*/
public void TankDisplay(){
if(!tank.crashed){
image(loadImage(tank.image),tank.x_pos,tank.y_pos);
}
}
/**
* Check both Projectile and invader iteratively,
* if the projectile is flying and hit one of the invaders,
* then set them both destroyed.
*/
public void checkAliensDestoried(){
for(Projectile b: projectiles){
for(Invader invader: invaders){
if(b.miss==1 && invader.destroy==0 && b.shoter==0){
if((b.x_pos<= invader.x_pos+10 && b.x_pos>=invader.x_pos-10)
&& (b.y_pos<= invader.y_pos+5 && b.y_pos>=invader.y_pos-1)){
b.miss =0;
invader.destroy =1;
int invaderType = invader.getType();
if(invaderType==0){
scoreBoard.normalInvader();
scoreBoard.updateHighest();
}
if(invaderType==1){
scoreBoard.armouredInvader();
scoreBoard.updateHighest();
}
if(invaderType==2){
scoreBoard.powerInvader();
scoreBoard.updateHighest();
}
HITS_NUM++;
}
}
}
}
}
/**
* Display all the bullets shot out, both from tank and invaders
*/
public void showBullets(){
for(int i=0; i<BULLET_SIZE;i++){
if(projectiles[i].flag==1 && projectiles[i].miss==1 ){
if(projectiles[i].shoter==0){
image(loadImage(projectiles[i].img), projectiles[i].x_pos, projectiles[i].y_pos);
projectiles[i].fly();
}
else{
image(loadImage(projectiles[i].img), projectiles[i].x_pos, projectiles[i].y_pos);
projectiles[i].aliensShot();
}
}
}
for(int i=0;i<POWER_BULLET_SIZE;i++){
if(powerProjectiles[i].flag==1){
image(loadImage(powerProjectiles[i].getImg()),powerProjectiles[i].x_pos,powerProjectiles[i].y_pos);
powerProjectiles[i].aliensShot();
}
}
}
/**
* Display all the existing invaders
*/
public void showAliens(){
for(int i=0;i<INVADER_NUMBER;i++){
if(invaders[i].y_pos>=330){
ALIENS_FLAG =true;
break;
}
if(invaders[i].destroy==0){
image(loadImage(invaders[i].getImg()),invaders[i].x_pos,invaders[i].y_pos);
invaders[i].move();
}
}
}
/**
* This method is used for change the condition of the game
* if the tank is destroyed or invaders are too close, then
* the game is over.
* if all the invaders are destroyed, then it should be go to
* next stage.
*/
public void ConditionSwitch(){
if(HITS_NUM==40){
CONDITION=1;
saved_time =millis();
}
if(tank.crashed || ALIENS_FLAG){
Toolkit.getDefaultToolkit().beep();
scoreBoard.score=0;
CONDITION =2;
saved_time =millis();
}
}
/**
* Display next stage image, and start next turn.
*/
public void nextStage(){
if(millis()-saved_time < 1000){
image(loadImage("nextlevel.png"),260,240);
}
else{
CONDITION =0;
HITS_NUM=0;
if(FRAME_RATE-1>=60){
FRAME_RATE--;
}
init();
}
}
/**
* Display game over image, and start next turn.
*/
public void gameOver(){
if(millis()-saved_time < 1000){
image(loadImage("gameover.png"),260,240);
}
else{
CONDITION =0;
HITS_NUM=0;
tank.crashed =false;
ALIENS_FLAG= false;
FRAME_INDEX=0;
FRAME_RATE=100;
init();
}
}
/**
* Check if any Projectile hits on barrier, using barrier functions to
* show the damage.
* Also, both tank and invaders may attack barrier, hence we need to check
* about that.
*/
public void checkBarrierHit(){
for(Projectile projectile : projectiles){
if(projectile.flag==1){
for(Barrier barrier:barriers){
Solid[] left_solid = barrier.left_solids;
Solid[] right_solid = barrier.right_solids;
// check left destroy
for(Solid s:left_solid){
if(!s.flag){
if(s.check(projectile.x_pos, projectile.y_pos)){
projectile.miss=0;
projectile.flag=0;
}
}
}
for(Solid s:right_solid){
if(!s.flag){
if(s.check(projectile.x_pos, projectile.y_pos)){
projectile.miss=0;
projectile.flag=0;
}
}
}
if(barrier.check(projectile.x_pos, projectile.y_pos)){
projectile.miss=0;
projectile.flag=0;
}
}
}
}
for(PowerProjectile powerProjectile : powerProjectiles){
if(powerProjectile.flag==1){
for(Barrier barrier:barriers){
Solid[] left_solid = barrier.left_solids;
Solid[] right_solid = barrier.right_solids;
// check left destroy
for(Solid s:left_solid){
if(!s.flag){
if(s.CheckPowerBullet(powerProjectile.x_pos, powerProjectile.y_pos)){
powerProjectile.miss=0;
powerProjectile.flag=0;
}
}
}
for(Solid s:right_solid){
if(!s.flag){
if(s.CheckPowerBullet(powerProjectile.x_pos, powerProjectile.y_pos)){
powerProjectile.miss=0;
powerProjectile.flag=0;
}
}
}
if(barrier.checkPowerBullet(powerProjectile.x_pos, powerProjectile.y_pos)){
powerProjectile.miss=0;
powerProjectile.flag=0;
}
}
}
}
}
/**
* Check if tank is under attack
* Tank can handle three bullets.
*/
public void checkTank(){
//Crashed by aliens (not be used, but )
for(Invader invader:invaders){
if(invader.destroy== 0){
if(tank.check(invader.x_pos,invader.y_pos)){
invader.destroy=1;
}
}
}
// check the normal bullet
for(Projectile projectile : projectiles){
if(projectile.shoter==1 && projectile.flag==1){
if(tank.check(projectile.x_pos, projectile.y_pos)){
projectile.flag=0;
}
}
}
// check the power bullet
for(PowerProjectile powerProjectile: powerProjectiles){
if(powerProjectile.flag==1){
if(tank.checkPowerProjectile(powerProjectile.x_pos,powerProjectile.y_pos)){
powerProjectile.flag=0;
}
}
}
}
/**
* Randomly choose an existing invader to shot
*/
public void aliensShot(){
if(FRAME_INDEX%FRAME_RATE==0){
Random random = new Random();
int random_index = random.nextInt(40);
Invader shoter = invaders[random_index];
if(shoter.getType()==2){
for(PowerProjectile powerProjectile: powerProjectiles){
if(powerProjectile.flag==0 && shoter.destroy!=1){
powerProjectile.x_pos = shoter.x_pos;
powerProjectile.y_pos = shoter.y_pos+5;
powerProjectile.flag =1;
powerProjectile.aliensShot();
break;
}
}
}
else{
for(Projectile projectile : projectiles){
if(projectile.flag==0 && shoter.destroy!=1){
projectile.x_pos = shoter.x_pos;
projectile.y_pos = shoter.y_pos+5;
projectile.flag =1;
projectile.shoter =1;
projectile.aliensShot();
break;
}
}
}
}
}
/**
* Display the score of the board
*/
public void showScoreBoard(){
text(scoreBoard.score,10,30);
text(scoreBoard.highest_score,530,30);
}
public static void main(String[] args) {
PApplet.main("invadem.App");
}
}
|
/*
* Copyright 2002-2021 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.beans.factory.annotation;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Constructor;
import java.lang.reflect.Executable;
import java.lang.reflect.Parameter;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.factory.config.DependencyDescriptor;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.core.annotation.SynthesizingMethodParameter;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
/**
* Public delegate for resolving autowirable parameters on externally managed
* constructors and methods.
*
* @author Sam Brannen
* @author Juergen Hoeller
* @since 5.2
* @see #isAutowirable
* @see #resolveDependency
*/
public final class ParameterResolutionDelegate {
private static final AnnotatedElement EMPTY_ANNOTATED_ELEMENT = new AnnotatedElement() {
@Override
@Nullable
public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
return null;
}
@Override
public Annotation[] getAnnotations() {
return new Annotation[0];
}
@Override
public Annotation[] getDeclaredAnnotations() {
return new Annotation[0];
}
};
private ParameterResolutionDelegate() {
}
/**
* Determine if the supplied {@link Parameter} can <em>potentially</em> be
* autowired from an {@link AutowireCapableBeanFactory}.
* <p>Returns {@code true} if the supplied parameter is annotated or
* meta-annotated with {@link Autowired @Autowired},
* {@link Qualifier @Qualifier}, or {@link Value @Value}.
* <p>Note that {@link #resolveDependency} may still be able to resolve the
* dependency for the supplied parameter even if this method returns {@code false}.
* @param parameter the parameter whose dependency should be autowired
* (must not be {@code null})
* @param parameterIndex the index of the parameter in the constructor or method
* that declares the parameter
* @see #resolveDependency
*/
public static boolean isAutowirable(Parameter parameter, int parameterIndex) {
Assert.notNull(parameter, "Parameter must not be null");
AnnotatedElement annotatedParameter = getEffectiveAnnotatedParameter(parameter, parameterIndex);
return (AnnotatedElementUtils.hasAnnotation(annotatedParameter, Autowired.class) ||
AnnotatedElementUtils.hasAnnotation(annotatedParameter, Qualifier.class) ||
AnnotatedElementUtils.hasAnnotation(annotatedParameter, Value.class));
}
/**
* Resolve the dependency for the supplied {@link Parameter} from the
* supplied {@link AutowireCapableBeanFactory}.
* <p>Provides comprehensive autowiring support for individual method parameters
* on par with Spring's dependency injection facilities for autowired fields and
* methods, including support for {@link Autowired @Autowired},
* {@link Qualifier @Qualifier}, and {@link Value @Value} with support for property
* placeholders and SpEL expressions in {@code @Value} declarations.
* <p>The dependency is required unless the parameter is annotated or meta-annotated
* with {@link Autowired @Autowired} with the {@link Autowired#required required}
* flag set to {@code false}.
* <p>If an explicit <em>qualifier</em> is not declared, the name of the parameter
* will be used as the qualifier for resolving ambiguities.
* @param parameter the parameter whose dependency should be resolved (must not be
* {@code null})
* @param parameterIndex the index of the parameter in the constructor or method
* that declares the parameter
* @param containingClass the concrete class that contains the parameter; this may
* differ from the class that declares the parameter in that it may be a subclass
* thereof, potentially substituting type variables (must not be {@code null})
* @param beanFactory the {@code AutowireCapableBeanFactory} from which to resolve
* the dependency (must not be {@code null})
* @return the resolved object, or {@code null} if none found
* @throws BeansException if dependency resolution failed
* @see #isAutowirable
* @see Autowired#required
* @see SynthesizingMethodParameter#forExecutable(Executable, int)
* @see AutowireCapableBeanFactory#resolveDependency(DependencyDescriptor, String)
*/
@Nullable
public static Object resolveDependency(
Parameter parameter, int parameterIndex, Class<?> containingClass, AutowireCapableBeanFactory beanFactory)
throws BeansException {
Assert.notNull(parameter, "Parameter must not be null");
Assert.notNull(containingClass, "Containing class must not be null");
Assert.notNull(beanFactory, "AutowireCapableBeanFactory must not be null");
AnnotatedElement annotatedParameter = getEffectiveAnnotatedParameter(parameter, parameterIndex);
Autowired autowired = AnnotatedElementUtils.findMergedAnnotation(annotatedParameter, Autowired.class);
boolean required = (autowired == null || autowired.required());
MethodParameter methodParameter = SynthesizingMethodParameter.forExecutable(
parameter.getDeclaringExecutable(), parameterIndex);
DependencyDescriptor descriptor = new DependencyDescriptor(methodParameter, required);
descriptor.setContainingClass(containingClass);
return beanFactory.resolveDependency(descriptor, null);
}
/**
* Due to a bug in {@code javac} on JDK versions prior to JDK 9, looking up
* annotations directly on a {@link Parameter} will fail for inner class
* constructors.
* <p>Note: Since Spring 6 may still encounter user code compiled with
* {@code javac 8}, this workaround is kept in place for the time being.
* <h4>Bug in javac in JDK < 9</h4>
* <p>The parameter annotations array in the compiled byte code excludes an entry
* for the implicit <em>enclosing instance</em> parameter for an inner class
* constructor.
* <h4>Workaround</h4>
* <p>This method provides a workaround for this off-by-one error by allowing the
* caller to access annotations on the preceding {@link Parameter} object (i.e.,
* {@code index - 1}). If the supplied {@code index} is zero, this method returns
* an empty {@code AnnotatedElement}.
* <h4>WARNING</h4>
* <p>The {@code AnnotatedElement} returned by this method should never be cast and
* treated as a {@code Parameter} since the metadata (e.g., {@link Parameter#getName()},
* {@link Parameter#getType()}, etc.) will not match those for the declared parameter
* at the given index in an inner class constructor.
* @return the supplied {@code parameter} or the <em>effective</em> {@code Parameter}
* if the aforementioned bug is in effect
*/
private static AnnotatedElement getEffectiveAnnotatedParameter(Parameter parameter, int index) {
Executable executable = parameter.getDeclaringExecutable();
if (executable instanceof Constructor && ClassUtils.isInnerClass(executable.getDeclaringClass()) &&
executable.getParameterAnnotations().length == executable.getParameterCount() - 1) {
// Bug in javac in JDK <9: annotation array excludes enclosing instance parameter
// for inner classes, so access it with the actual parameter index lowered by 1
return (index == 0 ? EMPTY_ANNOTATED_ELEMENT : executable.getParameters()[index - 1]);
}
return parameter;
}
}
|
import java.util.Random;
public class Obstacles {
int x, y;
Traps traps;
public Obstacles(){
Random r = new Random();
this.x = r.nextInt(15 - 1) + 1;
this.y = r.nextInt(15 - 1) + 1;
traps = Traps.PORTAL;
}
public String toString(){
return traps + " type of trap at x:" + x + " & y:" + y;
}
}
|
package nbi.implementCores;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import nbi.adapter.FilePatternBehaviorAdapter;
import nbi.adapter.ServerAdapter;
import nbi.xsd.model.FileDetailRecordType;
import nbi.xsd.model.FilePatternType;
import nbi.xsd.model.ServerType;
import nbi.xsd.model.Servers;
import org.slf4j.LoggerFactory;import org.slf4j.Logger;
/**
*/
public class LoadServerConfigXML {
final static Logger log = LoggerFactory.getLogger(LoadServerConfigXML.class);
/**
* @param args
*/
public static void main(String[] args) {
LoadServerConfigXML load = new LoadServerConfigXML();
try {
List<ServerType> alist = load.loadXML("d://serversSchema.xml");
for (ServerType server : alist) {
System.out.println(server.getServerName());
List<FileDetailRecordType> patternList = server.getFilePatterns().getFilePattern();
for (FileDetailRecordType fileDetailPattern : patternList) {
System.out.println("Pattern: " + fileDetailPattern.getPattern());
System.out.println("LocalFolderName: " + fileDetailPattern.getLocalFolderName());
System.out.println("RemoteFolderName: " + fileDetailPattern.getRemoteFolderName());
System.out.println("BulkTransport: " + fileDetailPattern.isBulkTransport());
System.out.println("CompressPut: " + fileDetailPattern.isCompressPut());
System.out.println("Description: " + fileDetailPattern.getDescription());
if(fileDetailPattern.getCustomLogicClassName()!=null){
System.out.println("CustomLogicClassName: " + fileDetailPattern.getCustomLogicClassName().getValue());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Method getUploadAndDownloadTasks.
* @param alist List<ServerType>
* @return List<ServerAdapter>[]
*/
public List<ServerAdapter>[] getUploadAndDownloadTasks(final List<ServerType> alist) {
if (alist == null || alist.size() == 0) {
return null;
}
List<ServerAdapter> uploadList = new ArrayList<ServerAdapter>();
List<ServerAdapter> downloadList = new ArrayList<ServerAdapter>();
for (ServerType aServerType : alist) {
ServerAdapter uploadServer = new ServerAdapter();
ServerAdapter downloadServer = new ServerAdapter();
List<FilePatternBehaviorAdapter> uploadBehaviors = uploadServer.getBehaviors();
List<FilePatternBehaviorAdapter> downloadBehaviors = downloadServer.getBehaviors();
uploadServer.setIp(aServerType.getIp());
uploadServer.setUserName(aServerType.getUserName());
uploadServer.setPasswd(aServerType.getPasswd());
uploadServer.setPort(aServerType.getPort());
uploadServer.setsFtp(aServerType.isSFtp());
downloadServer.setIp(aServerType.getIp());
downloadServer.setUserName(aServerType.getUserName());
downloadServer.setPasswd(aServerType.getPasswd());
downloadServer.setPort(aServerType.getPort());
downloadServer.setsFtp(aServerType.isSFtp());
FilePatternType aFilePatterns = aServerType.getFilePatterns();
List<FileDetailRecordType> aFilePatternList = aFilePatterns.getFilePattern();
for(FileDetailRecordType aFileDetailRecordType :aFilePatternList){
FilePatternBehaviorAdapter aFilePatternBehaviorAdapter = new FilePatternBehaviorAdapter();
aFilePatternBehaviorAdapter.setBulkTransport(aFileDetailRecordType.isBulkTransport());
aFilePatternBehaviorAdapter.setCompressPut(aFileDetailRecordType.isCompressPut());
aFilePatternBehaviorAdapter.setFilePatternString(aFileDetailRecordType.getPattern());
aFilePatternBehaviorAdapter.setLocalFolderName(aFileDetailRecordType.getLocalFolderName());
aFilePatternBehaviorAdapter.setRemoteFolderName(aFileDetailRecordType.getRemoteFolderName());
aFilePatternBehaviorAdapter.setPutOrGet(aFileDetailRecordType.isPutOrGet());
if(aFileDetailRecordType.getCustomLogicClassName()!=null){
aFilePatternBehaviorAdapter.setCustomLogicClassName(aFileDetailRecordType.getCustomLogicClassName().getValue());
}
if(aFilePatternBehaviorAdapter.isPutOrGet()){
//1 Download
downloadBehaviors.add(aFilePatternBehaviorAdapter);
}else{
//0 Upload
uploadBehaviors.add(aFilePatternBehaviorAdapter);
}
}
uploadServer.setBehaviors(uploadBehaviors);
downloadServer.setBehaviors(downloadBehaviors);
if(uploadServer.getBehaviors().size()>0)
uploadList.add(uploadServer);
if(downloadServer.getBehaviors().size()>0)
downloadList.add(downloadServer);
}
List<ServerAdapter>[] result = new List []{ uploadList,downloadList};
return result;
}
/**
* Method loadXML.
* @param arg String
* @return List<ServerType>
*/
public List<ServerType> loadXML(String arg) {
List<ServerType> serverTypeList = null;
// create JAXBContext for the server.xsd
try {
final JAXBContext context = JAXBContext.newInstance("nbi.xsd.model");
final Unmarshaller unmarshaller = context.createUnmarshaller();
Servers servers = (nbi.xsd.model.Servers) unmarshaller.unmarshal(new FileInputStream(arg));
serverTypeList = servers.getServer();
log.info("Success Loading configuration XML files.");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (JAXBException e) {
e.printStackTrace();
} finally {
if (serverTypeList == null) {
log.info("Failed to load XML files.");
}
}
return serverTypeList;
}
}
|
package com.qiuxy.miaosha1;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @RestController 便捷的annotation,itself annotated with @Controller and @ResponseBody.
*
* @EnableAutoConfiguration.
* This annotation tells Spring Boot to “guess” how you will want to configure Spring,
* based on the jar dependencies that you have added.
* Since spring-boot-starter-web added Tomcat and Spring MVC,
* the auto-configuration will assume that you are developing a web application and
* setup Spring accordingly.
* 启动自动配置特性,springboot会根据依赖关系,猜测??什么呢?会做什么呢?
*
* @ComponentScan
* If specific packages are not defined,
* scanning will occur from the package of the class that declares this annotation.
* 如果不指定扫描包位置,则默认从本包开始
*/
@RestController
@EnableAutoConfiguration
@ComponentScan
@EnableEurekaClient
public class App {
@RequestMapping("/")
String home() {
return "Hello World2!";
}
public static void main(String[] args) throws Exception {
/**
* Classes that can be used to bootstrap and launch a Spring application from a Java main method.
* By default class will perform the following steps to bootstrap your application:
1. Create an appropriate ApplicationContext instance (depending on your classpath)
2. Register a CommandLinePropertySource to expose command line arguments as Spring properties
3. Refresh the application context, loading all singleton beans
4. Trigger any CommandLineRunner beans
*/
// the run method to tell SpringApplication which is the primary Spring component
// The args array is also passed through to expose any command-line arguments.
SpringApplication.run(App.class, args);
}
}
|
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class checkbox2 extends JFrame implements ActionListener
{
JCheckBox check1,check2,check3,check4;
JTextField text;
public checkbox2()
{
Container c=this.getContentPane();
c.setLayout(new FlowLayout()) ;
c.setBackground(Color.cyan);
text=new JTextField(20);
check1=new JCheckBox("Check 1");
check2=new JCheckBox("Check 2");
check3=new JCheckBox("Check 3");
check4=new JCheckBox("Check 4");
check1.addActionListener(this);
check2.addActionListener(this);
check3.addActionListener(this);
check4.addActionListener(this);
c.add(check1);
c.add(check2);
c.add(check3);
c.add(check4) ;
c.add(text);
}
public void actionPerformed(ActionEvent ae)
{
if(check1.getModel().isSelected()==false)
{
text.setText("You clicked check box 1.");
text.setBackground(Color.red);
check1.setBackground(Color.green);
}
if(check2.getModel().isSelected())
{
text.setText("You clicked check box 2.");
text.setBackground(Color.cyan);
check2.setBackground(Color.red);
}
if(check3.isSelected())
{
text.setBackground(Color.pink);
text.setText("You clicked check box 3.");
check3.setBackground(Color.cyan);
}
if(check4.getModel().isSelected())
{
text.setBackground(Color.blue);
text.setText("You clicked check box 4.");
check4.setBackground(Color.pink);
}
}
public static void main(String args[])
{
checkbox2 chk2=new checkbox2();
chk2.setTitle("CheckBox Operation....");
chk2.setSize(200,200);
chk2.setVisible(true);
chk2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
|
package com.netcracker.CustomException;
public class ResponseNotOk extends Exception {
}
|
package maze;
/**
*
* @author Ryan
*/
public class Character {
//Save variables
private int numRooms;
private int direction;
private int xPos;
private int yPos;
private int zPos;
private int exp;
private int health;
private int endX;
private int endY;
private int endZ;
private int difficulty;
private int weapon;
private int armor;
private int magic;
//Referenced variables
private int level;
private double distToEnd;
//Unreferenced variables
private int lvlToXP=100;
public Character() { //Constructor
//PUT CODE HERE?
}
//SaveVars Setters
public void setnumRooms(int numRooms) {this.numRooms = numRooms;}
public void setdirection(int direction) {this.direction = direction;}
public void setxPos(int xPos) {this.xPos = xPos;}
public void setyPos(int yPos) {this.yPos = yPos;}
public void setzPos(int zPos) {this.zPos = zPos;}
public void setexp(int exp) {this.exp = exp;setlevel();}
public void sethealth(int health) {this.health = health;}
public void setendX(int endX) {this.endX = endX;}
public void setendY(int endY) {this.endY = endY;}
public void setendZ(int endZ) {this.endZ = endZ;}
public void setdifficulty(int difficulty) {this.difficulty = difficulty;}
public void setweapon(int weapon) {this.weapon = weapon;}
public void setarmor(int armor) {this.armor = armor;}
public void setmagic(int magic) {this.endX = magic;}
//RefVars Setters
public void setlevel() {
level = exp * lvlToXP;
}
public void setdistToEnd() {
distToEnd = Math.sqrt(Math.pow(endX-xPos,2)+Math.pow(endY-yPos,2)+Math.pow(endZ-zPos,2));
}
//SaveVars Getters
public int getnumRooms() {return numRooms;}
public int getdirection() {return direction;}
public int getxPos() {return xPos;}
public int getyPos() {return yPos;}
public int getzPos() {return zPos;}
public int getexp() {return exp;}
public int gethealth() {return health;}
public int getendX() {return endX;}
public int getendY() {return endY;}
public int getendZ() {return endZ;}
public int getdifficulty() {return difficulty;}
public int getweapon() {return weapon;}
public int getarmor() {return armor;}
public int getmagic() {return magic;}
//RefVars Getters
public int getlevel() {return level;}
public double getdistToEnd() {return distToEnd;}
public void newGame() {
numRooms = 0;
direction = 0;
xPos = (int)(Math.random()*21);
yPos = (int)(Math.random()*21);
zPos = (int)(Math.random()*3);
exp = 0;
health = 100;
endX = (int)(Math.random()*21);
while(Math.abs(endX-xPos) <= 3){
endX = (int)(Math.random()*21);
}
endY = (int)(Math.random()*21);
while(Math.abs(endY-yPos) <= 3){
endY = (int)(Math.random()*21);
}
endZ = (int)(Math.random()*3);
//difficulty menu to be shown from start menu
weapon = (int)(Math.random()*5) +8; //between 8 and 12
armor = 5*(20-weapon); //blocks 90% of damage, takes 110% as much
magic = 18-weapon; //inversely mapped to damage (8 to 10 and 12 to 6)
}
public void loadSave(String saveName) {
Inputter in1 = new Inputter("document",saveName);
}
}
|
package com.example.demo;
import static org.junit.Assert.fail;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.NoSuchElementException;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import com.model.Usuario;
import com.persistence.UsuarioRepository;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
public class PasosRegistro {
@Autowired
private UsuarioRepository usuarioRepository;
private Usuario usuario;
private Usuario usuarioAlmacenado;
String username;
Optional<Usuario> user;
@Given("se registra al usuario con {string}, {string} {string}, {string}, {string}, {string} y {string}")
public void se_registra_al_usuario_con_y(String username, String password, String roleID, String nombre,
String apellidos, String email, String telefono) {
this.usuario = new Usuario(username, encriptarMD5(password), roleID, nombre, apellidos, email,
Integer.parseInt(telefono));
}
@When("se recupera el usuario registrado de la base de datos")
public void se_recupera_el_usuario_registrado_de_la_base_de_datos() {
this.usuarioAlmacenado = this.usuarioRepository.insert(this.usuario);
}
@Then("los datos introducidos y los recuperados del registro coinciden")
public void los_datos_introducidos_y_los_recuperados_del_registro_coinciden() {
if (!(this.usuario.getUsername().equals(this.usuarioAlmacenado.getUsername())
&& this.usuario.getPassword().equals(this.usuarioAlmacenado.getPassword())
&& this.usuario.getNombre().equals(this.usuarioAlmacenado.getNombre())
&& this.usuario.getApellidos().equals(this.usuarioAlmacenado.getApellidos())
&& this.usuario.getEmail().equals(this.usuarioAlmacenado.getEmail())
&& this.usuario.getTelefono() == this.usuarioAlmacenado.getTelefono())) {
fail("El usuario introducido y recuperado no coinciden");
}
}
@Given("se elimina al usuario con {string}")
public void se_elimina_al_usuario_con(String username) {
this.usuarioRepository.deleteByUsername(username);
this.username = username;
}
@When("se busca el usuario registrado de la base de datos")
public void se_busca_el_usuario_registrado_de_la_base_de_datos() {
user = this.usuarioRepository.findOneByUsername(this.username);
}
@Then("el usuario ya no existe")
public void el_usuario_ya_no_existe() {
try {
this.user.get();
fail("El usuario no ha sido eliminado");
} catch (NoSuchElementException e) {
}
}
private static String encriptarMD5(String input) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] messageDigest = md.digest(input.getBytes());
BigInteger number = new BigInteger(1, messageDigest);
String hashtext = number.toString(16);
int diff = 32 - hashtext.length();
StringBuilder bld = new StringBuilder();
while (diff > 1) {
bld.append("0");
diff--;
}
return bld.toString() + hashtext;
} catch (NoSuchAlgorithmException e) {
return "";
}
}
}
|
package bfs;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
/**
* 炸弹人的例子 用广搜
*
* @author 丹丘生
*/
public class BFS_5 {
private static int[][] direction = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
static Queue<Node> que = new LinkedList<Node>();
private static int[][] book;
static char[][] chs;
static int n;
static int m;
public static void main(String[] args) {
// 定义变量
int max = 0;
Node maxNode;
Scanner read = new Scanner(System.in);
m = read.nextInt();
n = read.nextInt();
int startx = read.nextInt();
int starty = read.nextInt();
//
read.nextLine();
chs = new char[m][n];
book = new int[m][n];
for (int i = 0; i < m; i++) {
// 获取将数据转换为字符数组
chs[i] = read.nextLine().toCharArray();
}
Node node = new Node();
node.x = startx;
node.y = starty;
que.add(node);// 起始点进队列
// 得到起始点可以消灭的敌人数
max = getSum(node);
maxNode = node;
// 以当前点进行广搜
Node heads;
while ((heads = que.poll()) != null) {
for (int index = 0; index < 4; index++) {
int tx = heads.x + direction[index][0];
int ty = heads.y + direction[index][1];
// 判断是否越界
if (tx < 0 || tx >= n || ty < 0 || ty >= m) {
continue;
}
// 判断该点是否为障碍物并且有没有被访问
if (book[tx][ty] == 0 && chs[tx][ty] == '.') {
book[tx][ty] = 1; // 标记当前点已经访问
Node next = new Node();
next.x = tx;
next.y = ty;
int min = getSum(next);
if(max<min) {
max = min;
maxNode = next;
}
que.add(next);
}
}
}
System.out.println(maxNode);
System.out.println("消灭敌人的个数为:"+max);
}
// 得到当前点的总和
private static int getSum(Node next) {
// 上下左右方向 能消灭的敌人数
int sum = 0;
// 从上
int x = next.x;
int y = next.y;
while (chs[x][y] != '#' && x >= 0) {
if (chs[x][y] == 'G')
sum++;
x--;
}
// 从下
x = next.x;
y = next.y;
while (chs[x][y] != '#' && x < n) {
if (chs[x][y] == 'G')
sum++;
x++;
}
// 从左
x = next.x;
y = next.y;
while (chs[x][y] != '#' && y >= 0) {
if (chs[x][y] == 'G')
sum++;
y--;
}
// 从右
x = next.x;
y = next.y;
while (chs[x][y] != '#' && y < m) {
if (chs[x][y] == 'G')
sum++;
y++;
}
return sum;
}
static class Node {
int x;
int y;
public Node() {
}
public Node(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
@Override
public String toString() {
return "(" + x + "," + y + ")";
}
}
}
//#############
//#GG.GGG#GGG.#
//###.#G#G#G#G#
//#.......#..G#
//#G#.###.#G#G#
//#GG.GGG.#.GG#
//#G#.#G#.#.###
//##G...G.....#
//#G#.#G###.#G#
//#...G#GGG.GG#
//#G#.#G#G#.#G#
//#GG.GGG#G.GG#
//#############
//
|
package adapter;
public interface LibraryApi {
boolean isAvailable(String bookTitle);
boolean reserve(String bookTitle, String pesel);
}
|
package lambda;
/**
* @author songkaiwen
* @date 2020/12/8 3:17 下午
*/
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
/**
* Java8内置的四大核心函数式接口
* Consumer<T>:消费型接口
* void accept(T t);
* Supplier<T>: 供给型接口
* T get();
* Function<T,R>: 函数型接口
* R apply(T t);
* Predicate<T>: 断言型接口
* boolean test(T t);
*
* 一些子接口
* BiFunction<T,U,R>(Function子接口)
* R apply(T t, U u);
* UnaryOperator<T>(Function子接口)
* static <T> UnaryOperator<T> identity() {
* return t -> t;
* }
* 等。
*
*/
public class TestLambda3 {
//断言型接口
@Test
public void test4(){
List<String> strList = Arrays.asList("hello","world","Lambda","OK");
List<String> result = filterStr(strList,(s) -> s.length()>3);
System.out.println(result);
}
//需求:将满足条件的字符串添加到集合中
public List<String> filterStr(List<String> l, Predicate<String> pre){
List<String> list = new ArrayList<>();
for (String s: l) {
if(pre.test(s)){
list.add(s);
}
}
return list;
}
//函数型接口
@Test
public void test3(){
String result1 = processStr("karen",(s) -> s.toUpperCase());
System.out.println(result1);
}
//需求:用于处理字符串
public String processStr(String str, Function<String,String> fun){
return fun.apply(str);
}
//供给型接口
@Test
public void test2(){
List<Integer> result = getNumList(10,() -> (int)(Math.random()*100));
for(Integer i:result){
System.out.println(i);
}
}
//需求:产生指定个数的整数,并放入集合中
public List<Integer> getNumList(int num, Supplier<Integer> sup){
List<Integer>list = new ArrayList<>();
for(int i=0;i<num;i++){
Integer e = sup.get();
list.add(e);
}
return list;
}
//消费型接口
@Test
public void test1(){
happy(1000,(m) -> System.out.println("buying clothes consume "+m+" every time"));
}
public void happy(double money, Consumer<Double> con){
con.accept(money);
}
}
|
package com.imooc.ioc.beanshuxingzhurufangshi;
/**
* @Author: Asher Huang
* @Date: 2019-10-17
* @Description: com.imooc.ioc.beanshuxingzhurufangshi
* @Version:1.0
*/
public class ProductInfo {
public Double calcPrice() {
return Math.random()*1999.99;
}
}
|
package com.trump.auction.account.dao;
import com.trump.auction.account.domain.AccountBackcoinRecord;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
/**
* Created by wangyichao on 2018-01-05 下午 01:59.
*/
@Repository
public interface AccountBackCoinRecordDao {
AccountBackcoinRecord getAccountBackCoinRecordByOrderNo(@Param("orderNo") String orderNo, @Param("accountType") Integer accountType, @Param("userId") Integer userId);
int insertAccountBackCoinRecord(AccountBackcoinRecord accountBackcoinRecord);
}
|
package com.netcracker.entities;
import javax.persistence.*;
import javax.validation.constraints.Size;
@Entity
@Table(name = "Reviews")
public class Review {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "review_id_generator")
@SequenceGenerator(name = "review_id_generator", sequenceName = "review_id_seq", allocationSize = 1)
@Column(name = "Review_ID")
private Long reviewId;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "User_ID")
private User user;
@Column(name = "Additional_Text")
private String additionalText;
@Column(name = "Mark")
@Size(min = 0, max = 5)
private Integer mark;
@Column(name = "Is_passenger")
private Boolean isPassenger;
public Review() {
}
public Review(User user, String additionalText, Integer mark, Boolean isPassenger) {
this.additionalText = additionalText;
this.isPassenger = isPassenger;
this.user = user;
this.mark = mark;
}
public void setReviewId(Long reviewId) {this.reviewId = reviewId;}
public void setUser(User user) {this.user = user;}
public void setAdditionalText(String additionalText) { this.additionalText = additionalText; }
public void setMark(Integer mark) { this.mark = mark; }
public void setPassenger(Boolean passenger) { isPassenger = passenger; }
public Long getReviewId() { return reviewId; }
public User getUser() { return user; }
public String getAdditionalText() { return additionalText; }
public Integer getMark() { return mark; }
@Override
public String toString() {
return "Review{" +
"reviewId=" + reviewId +
", user=" + user +
", additionalText='" + additionalText + '\'' +
", mark=" + mark +
", isPassenger=" + isPassenger +
'}';
}
public Boolean getPassenger() { return isPassenger; }
}
|
package app.akeorcist.deviceinformation.model;
/**
* Created by Akexorcist on 2/27/15 AD.
*/
public class ScreenData {
private String resolutionPx;
private String resolutionDp;
private String dpiX;
private String dpiY;
private String dpi;
private String size;
private String density;
private String multitouch;
public ScreenData() { }
public String getResolutionPx() {
return resolutionPx;
}
public ScreenData setResolutionPx(String resolutionPx) {
this.resolutionPx = resolutionPx;
return this;
}
public String getResolutionDp() {
return resolutionDp;
}
public ScreenData setResolutionDp(String resolutionDp) {
this.resolutionDp = resolutionDp;
return this;
}
public String getDpiX() {
return dpiX;
}
public ScreenData setDpiX(String dpiX) {
this.dpiX = dpiX;
return this;
}
public String getDpiY() {
return dpiY;
}
public ScreenData setDpiY(String dpiY) {
this.dpiY = dpiY;
return this;
}
public String getDpi() {
return dpi;
}
public ScreenData setDpi(String dpi) {
this.dpi = dpi;
return this;
}
public String getSize() {
return size;
}
public ScreenData setSize(String size) {
this.size = size;
return this;
}
public String getDensity() {
return density;
}
public ScreenData setDensity(String density) {
this.density = density;
return this;
}
public String getMultitouch() {
return multitouch;
}
public ScreenData setMultitouch(String multitouch) {
this.multitouch = multitouch;
return this;
}
}
|
package haschlabs.pluginmanager;
import java.io.File;
import java.io.FileFilter;
/**
* Implementation of the FileFilter interface that accepts only .jar files.
*
* @author Hauke Schulz <hauke27@googlemail.com>
*/
public class JARFileFilter implements FileFilter {
/**
* This method checks if the given file object ends with .jar and returns
* a boolean value.
*
* @author Hauke Schulz <hauke27@googlemail.com>
* @param file A java.io.File instance
* @return bool true if the file ends with .jar
*/
@Override
public boolean accept(File file) {
return file.getName().toLowerCase().endsWith(".jar");
}
}
|
package mx.com.otss.barbershopapp.activities.menu_inferior;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import mx.com.otss.barbershopapp.R;
import mx.com.otss.barbershopapp.activities.comisiones.MenuComisionesActivity;
import mx.com.otss.barbershopapp.activities.empleados.ConsultarEmpleadoActivity;
import mx.com.otss.barbershopapp.activities.empleados.EliminarEmpleadoActivity;
import mx.com.otss.barbershopapp.activities.empleados.InsertarEmpleadosActivity;
import mx.com.otss.barbershopapp.request.empleados.ConsultarEmpleadosRequest;
import mx.com.otss.barbershopapp.request.franquicias.ConsultaFranquiciaRequest;
import mx.com.otss.barbershopapp.utils.BarberShop;
import mx.com.otss.barbershopapp.utils.Comunicador;
import static mx.com.otss.barbershopapp.utils.Red.verificaConexion;
public class PrincipalEmpleadosActivity extends AppCompatActivity {
private String nombreFranquicia;
private Button btnAgregar, btnActualizar, btnEliminar, btnConsultar;
private String usuario;
private Menu menu;
private MenuItem menuItem;
private BottomNavigationView navigation;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
/**
*
* @param item
* @return
*/
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_inferior_empleados:
Intent intent1=new Intent(getApplication(),PrincipalEmpleadosActivity.class);
intent1.putExtra("nombreFranquicia", getUsuario());
finish();
startActivity(intent1);
return true;
case R.id.menu_inferior_servicios:
Intent intent4=new Intent(getApplication(),PrincipalServiciosActivity.class);
intent4.putExtra("nombreFranquicia", getUsuario());
finish();
startActivity(intent4);
return true;
case R.id.menu_inferior_franquicias:
Intent exIntent = new Intent(getApplicationContext(), PrincipalFranquiciasActivity.class);
exIntent.putExtra("nombreFranquicia", getUsuario());
finish();
startActivity(exIntent);
return true;
case R.id.menu_inferior_listados:
Intent intentPrincipalClientes = new Intent(getApplicationContext(), ListadosActivity.class);
intentPrincipalClientes.putExtra("nombreFranquicia", getUsuario());
finish();
startActivity(intentPrincipalClientes);
return true;
case R.id.menu_inferior_reportes:
Intent intentReportes = new Intent(getApplicationContext(), ReportesActivity.class);
intentReportes.putExtra("nombreFranquicia", getUsuario());
finish();
startActivity(intentReportes);
return true;
}
return false;
}
};
/**
*
* @param savedInstanceState
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_principal_empleados);
btnAgregar = (Button)findViewById(R.id.btnIngresarEmpleados);
Intent intent_receptor = getIntent();
usuario = intent_receptor.getStringExtra("nombreFranquicia");
setUsuario(usuario);
btnConsultar = (Button)findViewById(R.id.btnConsultarEmpleados);
btnEliminar = (Button)findViewById(R.id.btnEliminarEmpleados);
navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
menu = navigation.getMenu();
menuItem = menu.getItem(0);
menuItem.setChecked(true);
btnAgregar.setOnClickListener(new View.OnClickListener() {
/**
*
* @param v
*/
@Override
public void onClick(View v) {
Comunicador.limpiar();
if (!verificaConexion(getApplication())) {
Toast.makeText(getBaseContext(),
"Comprueba tu conexión a Internet.... ", Toast.LENGTH_SHORT)
.show();
} else {
final ArrayList<BarberShop> arrayList = new ArrayList<BarberShop>();
String user = "";
final BarberShop obj = new BarberShop();
Response.Listener<String> responseListener = new Response.Listener<String>() {
/**
*
* @param response
*/
@Override
public void onResponse(String response) {
try {
JSONArray jsonResponse = new JSONArray(response);
Log.i("Info", "" + jsonResponse.length());
ArrayList<String> list = new ArrayList<String>();
String[] q = new String[jsonResponse.length()];
for (int x = 0; x < q.length; x++) {
String v = q[x] = jsonResponse.optString(x);
Log.i("info", "Mi lista" + v);
}
for (String s : q) {
JSONObject jsonObject = new JSONObject(s);
for (int z = 0; z < jsonObject.length(); z++) {
JSONArray array = jsonObject.getJSONArray("franquicias");
String cadena = null;
Comunicador obj = new Comunicador();
BarberShop o = new BarberShop();
for (int i = 0; i < array.length(); i++) {
o.setIdFranquisia(array.getJSONObject(i).getString("idFranquicia"));
o.setNombreFranquisia(array.getJSONObject(i).getString("nombre"));
o.setDireccionFranquisia(array.getJSONObject(i).getString("direccion"));
o.setTelefonoFranquisia(array.getJSONObject(i).getString("telefono"));
o.setIngresosGenerales(array.getJSONObject(i).getString("ingresos_generales"));
obj.setOBJ(o);
}
}
}
Intent intentAgregar = new Intent(getApplicationContext(), InsertarEmpleadosActivity.class);
intentAgregar.putExtra("nombreFranquicia", usuario);
finish();
startActivity(intentAgregar);
} catch (JSONException e) {
Log.e("Error", "Error" + e.getMessage());
e.printStackTrace();
Toast.makeText(getApplicationContext(), "No hay registros", Toast.LENGTH_SHORT).show();
}
}
};
ConsultaFranquiciaRequest consultaFranquiciaRequest = new ConsultaFranquiciaRequest(responseListener);
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
queue.add(consultaFranquiciaRequest);
}
}
});
btnConsultar.setOnClickListener(new View.OnClickListener() {
/**
*
* @param v
*/
@Override
public void onClick(View v) {
Comunicador.limpiar();
if (!verificaConexion(getApplication())) {
Toast.makeText(getBaseContext(),
"Comprueba tu conexión a Internet.... ", Toast.LENGTH_SHORT)
.show();
}else {
final ArrayList<BarberShop> arrayList = new ArrayList<BarberShop>();
String user = "";
final BarberShop obj = new BarberShop();
Response.Listener<String> responseListener = new Response.Listener<String>() {
/**
*
* @param response
*/
@Override
public void onResponse(String response) {
try{
JSONArray jsonResponse = new JSONArray(response);
Log.i("Info", "" + jsonResponse.length());
ArrayList<String> list = new ArrayList<String>();
String [] q = new String[jsonResponse.length()];
for(int x = 0; x<q.length; x ++){
String v = q[x] = jsonResponse.optString(x);
Log.i("info", "Mi lista"+v );
}
for(String s: q){
JSONObject jsonObject = new JSONObject(s);
for(int z=0; z<jsonObject.length();z++) {
JSONArray array = jsonObject.getJSONArray("empleados");
String cadena = null;
Comunicador obj = new Comunicador();
BarberShop o = new BarberShop();
for (int i = 0; i < array.length(); i++) {
o.setIdEmpleados(array.getJSONObject(i).getString("idEmpleado"));
o.setNombreEmpleado(array.getJSONObject(i).getString("nombre"));
o.setAppEmpleado(array.getJSONObject(i).getString("apellidoPaterno"));
o.setApmEmpleado(array.getJSONObject(i).getString("apellidoMaterno"));
o.setTelefonoEmpleado(array.getJSONObject(i).getString("telefono"));
o.setCorreoEmpleado(array.getJSONObject(i).getString("correo"));
o.setTipoEmpleado(array.getJSONObject(i).getString("tipoEmpleado"));
o.setNameUser(array.getJSONObject(i).getString("nameUser"));
o.setPassword(array.getJSONObject(i).getString("password"));
obj.setOBJ(o);
}
}
}
Intent intentConsultar = new Intent(getApplicationContext(), ConsultarEmpleadoActivity.class);
intentConsultar.putExtra("nombreFranquicia", getNombreFranquicia());
finish();
startActivity(intentConsultar);
} catch (JSONException e) {
Log.e("Error", "Error" + e.getMessage());
e.printStackTrace();
Toast.makeText(PrincipalEmpleadosActivity.this, "No hay registros", Toast.LENGTH_SHORT).show();
}
}
};
ConsultarEmpleadosRequest consultarEmpleadosRequest = new ConsultarEmpleadosRequest(responseListener);
RequestQueue queue = Volley.newRequestQueue(PrincipalEmpleadosActivity.this);
queue.add(consultarEmpleadosRequest);
}
}
});
btnEliminar.setOnClickListener(new View.OnClickListener() {
/**
*
* @param v
*/
@Override
public void onClick(View v) {
Comunicador.limpiar();
if (!verificaConexion(getApplication())) {
Toast.makeText(getBaseContext(),
"Comprueba tu conexión a Internet.... ", Toast.LENGTH_SHORT)
.show();
}else {
final ArrayList<BarberShop> arrayList = new ArrayList<BarberShop>();
String user = "";
final BarberShop obj = new BarberShop();
Response.Listener<String> responseListener = new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONArray jsonResponse = new JSONArray(response);
Log.i("Info", "" + jsonResponse.length());
ArrayList<String> list = new ArrayList<String>();
String[] q = new String[jsonResponse.length()];
for (int x = 0; x < q.length; x++) {
String v = q[x] = jsonResponse.optString(x);
Log.i("info", "Mi lista" + v);
}
for (String s : q) {
JSONObject jsonObject = new JSONObject(s);
for (int z = 0; z < jsonObject.length(); z++) {
JSONArray array = jsonObject.getJSONArray("empleados");
String cadena = null;
Comunicador obj = new Comunicador();
BarberShop o = new BarberShop();
for (int i = 0; i < array.length(); i++) {
o.setIdEmpleados(array.getJSONObject(i).getString("idEmpleado"));
o.setNombreEmpleado(array.getJSONObject(i).getString("nombre"));
// o.setAppEmpleado(array.getJSONObject(i).getString("apellidoPaterno"));
o.setApmEmpleado(array.getJSONObject(i).getString("apellidoMaterno"));
o.setTelefonoEmpleado(array.getJSONObject(i).getString("telefono"));
o.setCorreoEmpleado(array.getJSONObject(i).getString("correo"));
o.setTipoEmpleado(array.getJSONObject(i).getString("tipoEmpleado"));
o.setNameUser(array.getJSONObject(i).getString("nameUser"));
o.setPassword(array.getJSONObject(i).getString("password"));
obj.setOBJ(o);
}
}
}
Intent intentConsultar = new Intent(getApplicationContext(), EliminarEmpleadoActivity.class);
intentConsultar.putExtra("nombreFranquicia", getNombreFranquicia());
finish();
startActivity(intentConsultar);
} catch (JSONException e) {
Log.e("Error", "Error" + e.getMessage());
e.printStackTrace();
Toast.makeText(PrincipalEmpleadosActivity.this, "No hay registros", Toast.LENGTH_SHORT).show();
}
}
};
ConsultarEmpleadosRequest consultarEmpleadosRequest = new ConsultarEmpleadosRequest(responseListener);
RequestQueue queue = Volley.newRequestQueue(PrincipalEmpleadosActivity.this);
queue.add(consultarEmpleadosRequest);
Intent intentEliminar = new Intent(getApplicationContext(), EliminarEmpleadoActivity.class);
finish();
startActivity(intentEliminar);
}
}
});
}
/**
*
* @return
*/
public String getUsuario() {
return usuario;
}
/**
*
* @param usuario
*/
public void setUsuario(String usuario) {
this.usuario = usuario;
}
/**
*
* @param menu
* @return
*/
//menu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_superior, menu);
return true;
}
/**
*
* @param item
* @return
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == R.id.menu_superior_otros){
Intent intentMenuComisiones = new Intent(getApplicationContext(), MenuComisionesActivity.class);
startActivity(intentMenuComisiones);
}
if (id == R.id.menu_superior_salir) {
finish();
}
return super.onOptionsItemSelected(item);
}
/**
*
* @return
*/
public String getNombreFranquicia() {
return nombreFranquicia;
}
/**
*
* @param nombreFranquicia
*/
public void setNombreFranquicia(String nombreFranquicia) {
this.nombreFranquicia = nombreFranquicia;
}
}
|
package BridgePattern08.exercise.service.concreteService;
import BridgePattern08.exercise.service.FileImp;
public class SQLServerFileImp implements FileImp {
@Override
public void readData() {
System.out.println("从SQLServer中读取数据....");
}
}
|
package core;
import junit.framework.TestCase;
public class DeckTest extends TestCase {
public void testNumOfCardsInDeck() {
Deck deck = new Deck();
assertEquals(52, deck.getDeckSize());
}
public void testCardReturnedFromTakeCard() {
Deck deck = new Deck();
assertTrue(deck.takeCard() instanceof Card);
}
public void testForCompleteDeck() {
Deck deck = new Deck();
int numOfSpades = 0;
for (int i = 0; i < 52; i++) {
Card card = deck.takeCard();
if (card.printCard().charAt(0) == 'S') numOfSpades++;
if (numOfSpades == 4) break;
}
assertEquals(4, numOfSpades);
}
}
|
package ggboy.study.java.spring_mybatis;
import java.util.List;
import java.util.Map;
import ggboy.java.common.utils.sql.BaseSqlBuilder;
public interface BaseDao {
public int insert(BaseSqlBuilder builder);
public int delete(BaseSqlBuilder builder);
public List<Map<String, Object>> select(BaseSqlBuilder builder);
public int update(BaseSqlBuilder builder);
}
|
package technicalTest.beans;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Store {
private List<Sku> skus;
private FileReader file;
private BufferedReader reader;
public Store() {
}
public void createProducts() throws IOException {
skus = new ArrayList<Sku>();
if (reader != null) {
reader.readLine();
String read;
while ((read = reader.readLine()) != null) {
Sku sku = Sku.parse(read);
skus.add(sku);
}
reader.close();
file.close();
}
}
public void readFile(String fileName) throws FileNotFoundException {
file = new FileReader(fileName);
reader = new BufferedReader(file);
}
public Till getTill() {
return new Till(skus);
}
public List<Sku> getSkus() {
return skus;
}
public FileReader getFile() {
return file;
}
public BufferedReader getReader() {
return reader;
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
return super.hashCode();
}
@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
return super.equals(obj);
}
@Override
public String toString() {
// TODO Auto-generated method stub
return super.toString();
}
}
|
public class Square {
int number;
int[] posNum = {1,2,3,4,5,6,7,8,9};
/*=== constructors ===*/
Square(){
this.number = 0;
}
Square(int number){
this.number = number;
}
/*=== Behavor ===*/
public void testIfOnePosNum() {
// if there is only one number left then set square to that number.
}
/*===Set Funstions===*/
public void rmvPosNum(int rmvNum){
for(int i =0;i < 9;i++) {
if(rmvNum == posNum[i]) {
posNum[i] = 0;
break;
}
}
}
public void setNum(int number) {
this.number = number;
}
/*=== Get functions ===*/
public int[] getPosNum() {
return posNum;
}
public int getNum() {
return number;
}
/*
Square( int number,int x,int y){
this.x = x;
this.y = y;
}
public void setCoordinate(int x, int y) {
this.x = x;
this.y = y;
}
int x;
int y;
public int getX() {
return x;
}
public int getY() {
return y;
}
*/
}
|
package ch.mitti.yahtzee.view;
import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JPanel;
import ch.mitti.yahtzee.controller.DiceController;
public class FillerView extends JPanel{
public FillerView(){
init();
}
public void init(){
//Create Grid Layout
this.setLayout(new GridLayout(5,1,20,20));
for(int j=0; j<5; j++){
JLabel label = new JLabel(" ");
label.setBorder(BorderFactory.createLineBorder(Color.BLACK));
this.add(label);
}
}
}
|
package coreJava_programs.Java_Programs;
import java.util.Scanner;
public class PatternProgram3_22 {
/**
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7
1 2 3 4 5 6
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
**/
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
System.out.println("Please Enter a number :");
int number = scn.nextInt();
for(int i = number; i>=1; i--)
{
for(int j = 1; j<=i; j++)
{
System.out.print(j+" ");
}
System.out.println();
}
}
}
|
package com.easywidgets.lists;
public interface OnListMenuClickListener {
void onMenuItemClick(int itemId,int listPosition);
}
|
package deloitte.forecastsystem_bih.loadforecast.datavector;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.stereotype.Service;
import deloitte.forecastsystem_bih.loadforecast.config.CountriesEnum;
import deloitte.forecastsystem_bih.model.WeatherForecast;
import deloitte.forecastsystem_bih.model.WeatherForecastDaily;
import deloitte.forecastsystem_bih.model.WeatherForecastHourly;
//import deloitte.forecastsystem_bih.model.communication.LoadEntsoeForecastSumRecord;
import deloitte.forecastsystem_bih.model.communication.WeatherForecastRecord;
import deloitte.forecastsystem_bih.service.CountryService;
import deloitte.forecastsystem_bih.service.HistoryLoadForecastService;
import deloitte.forecastsystem_bih.service.LoadForecastArimaService;
import deloitte.forecastsystem_bih.service.LoadForecastSimilarDayService;
//import deloitte.forecastsystem_bih.service.LoadForecastEntsoeService;
import deloitte.forecastsystem_bih.service.PreparedDataLoadHoursService;
import deloitte.forecastsystem_bih.service.TempLoadForecastArimaService;
import deloitte.forecastsystem_bih.service.TempLoadForecastSimilarDayService;
import deloitte.forecastsystem_bih.service.WeatherForecastDailyService;
import deloitte.forecastsystem_bih.service.WeatherForecastHourlyService;
import deloitte.forecastsystem_bih.service.WeatherForecastService;
@Service("dataVectorHoursLoad")
@Configurable
public class DataVectorHoursLoad implements DataVector {
public CountriesEnum getCountry() {
return country;
}
public void setCountry(CountriesEnum country) {
this.country = country;
}
public Integer getDan() {
return dan;
}
public void setDan(Integer dan) {
this.dan = dan;
}
public Integer getMesec() {
return mesec;
}
public void setMesec(Integer mesec) {
this.mesec = mesec;
}
public Integer getGodina() {
return godina;
}
public void setGodina(Integer godina) {
this.godina = godina;
}
public Integer getLoadHour() {
return loadHour;
}
public void setLoadHour(Integer loadHour) {
this.loadHour = loadHour;
}
@Autowired
PreparedDataLoadHoursService preparedDataLoadHoursService;
@Autowired
CountryService countryService;
@Autowired
WeatherForecastService weatherForecastService;
@Autowired
//WeatherForecastHourlyService weatherForecastHourlyService;
WeatherForecastDailyService weatherForecastDailyService;
@Autowired
TempLoadForecastArimaService loadForecastArimaService;
@Autowired
TempLoadForecastSimilarDayService loadForecastSimilarDayService;
@Autowired
HistoryLoadForecastService historyLoadForecastService;
CountriesEnum country;
Integer dan;
Integer mesec;
Integer godina;
Integer loadHour;
public DataVectorHoursLoad() {
// TODO Auto-generated constructor stub
//SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
//this.country = CountriesEnum.CO_RS;
}
public DataVectorHoursLoad(CountriesEnum con,Integer loadHours, Integer dan, Integer mesec, Integer godina) {
// TODO Auto-generated constructor stub
this.country = con;
this.loadHour = loadHours;
this.dan = dan;
this.mesec = mesec;
this.godina = godina;
}
public double[] getPreparedData() {
return preparedDataLoadHoursService.findByDate(this.loadHour, this.dan, this.mesec, this.godina, countryService.findById(Long.valueOf(this.getCountry().ordinal()+1))).get(0).preparedVector();
}
public double[] getPreparedDataToday() {
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Europe/Belgrade"));
cal.set(this.godina, this.mesec-1, this.dan);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
cal.set(this.godina, this.mesec-1, this.dan);
Date dateYesterday = cal.getTime();
cal.set(this.godina, this.mesec-1, this.dan+1);
Date dateToday = cal.getTime();
// System.out.println("DateYesterday: " + dateYesterday);
// System.out.println("DateToday: " + dateToday);
//List<WeatherForecast> weatherForecastList;
List<WeatherForecastDaily> weatherForecastResults;
try {
//weatherForecastList = weatherForecastService.findByDate(countryService.findById(Long.valueOf(this.getCountry().ordinal()+1)), dateYesterday);
// Integer startPos = weatherForecastHourlyService.findByDayForecatsByHourStart(weatherForecastList.get(0), dateToday);
// weatherForecastResults = weatherForecastHourlyService.findByDayForecatsByHour(weatherForecastList.get(0), dateToday, loadHour+startPos);
weatherForecastResults = weatherForecastDailyService.findByDay(dateToday);
} catch (Exception e) {
return null;
}
List<Double> loadArimaForecastResult = loadForecastArimaService.findByDateLoadAndHour(countryService.findById(Long.valueOf(this.getCountry().ordinal()+1)), dateToday, loadHour);
List<Double> loadSimilarDayForecastResult = loadForecastSimilarDayService.findByDateLoadAndHour(countryService.findById(Long.valueOf(this.getCountry().ordinal()+1)), dateToday, loadHour);
double[] res = preparedDataLoadHoursService.findByDate(this.loadHour, this.dan, this.mesec, this.godina, countryService.findById(Long.valueOf(this.getCountry().ordinal()+1))).get(0).preparedVector();
res[33] = weatherForecastResults.get(0).getTemperatureMax();
res[34] = weatherForecastResults.get(0).getTemperatureMin();
res[35] = weatherForecastResults.get(0).getWindSpeed();
res[36] = weatherForecastResults.get(0).getHumidity();
res[37] = weatherForecastResults.get(0).getDewPoint();
res[38] = weatherForecastResults.get(0).getPressure();
res[39] = loadArimaForecastResult.get(0); // arima_forecast
res[40] = loadSimilarDayForecastResult.get(0); // similar_day_forecast
return res;
}
public double[] getPreparedDataTomorrow() {
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Europe/Belgrade"));
cal.set(this.godina, this.mesec-1, this.dan);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
cal.set(this.godina, this.mesec-1, this.dan);
Date dateYesterday = cal.getTime();
cal.set(this.godina, this.mesec-1, this.dan+1);
Date dateToday = cal.getTime();
cal.set(this.godina, this.mesec-1, this.dan+2);
Date dateTomorrow = cal.getTime();
// System.out.println("DateYesterday: " + dateYesterday);
// System.out.println("DateToday: " + dateToday);
// List<WeatherForecast> weatherForecastList;
List<WeatherForecastDaily> weatherForecastResults;
try {
// weatherForecastList = weatherForecastService.findByDate(countryService.findById(Long.valueOf(this.getCountry().ordinal()+1)), dateYesterday);
// Integer startPos = weatherForecastHourlyService.findByDayForecatsByHourStart(weatherForecastList.get(0), dateToday);
// weatherForecastResults = weatherForecastHourlyService.findByDayForecatsByHour(weatherForecastList.get(0), dateToday, loadHour+startPos);
weatherForecastResults = weatherForecastDailyService.findByDay(dateToday);
} catch (Exception e) {
return null;
}
List<Double> loadArimaForecastResult = loadForecastArimaService.findByDateLoadAndHour(countryService.findById(Long.valueOf(this.getCountry().ordinal()+1)), dateToday, loadHour);
List<Double> loadSimilarDayForecastResult = loadForecastSimilarDayService.findByDateLoadAndHour(countryService.findById(Long.valueOf(this.getCountry().ordinal()+1)), dateToday, loadHour);
List<Double> historyLoadForecastResult = historyLoadForecastService.findByDateLoadAndHour(countryService.findById(Long.valueOf(this.getCountry().ordinal()+1)), dateToday, loadHour);
// tomorrow
// List<WeatherForecast> weatherForecastListTomorrow;
List<WeatherForecastDaily> weatherForecastResultsTomorrow;
try {
// weatherForecastListTomorrow = weatherForecastService.findByDate(countryService.findById(Long.valueOf(this.getCountry().ordinal()+1)), dateToday);
// Integer startPos = weatherForecastHourlyService.findByDayForecatsByHourStart(weatherForecastListTomorrow.get(0), dateTomorrow);
// weatherForecastResultsTomorrow = weatherForecastHourlyService.findByDayForecatsByHour(weatherForecastListTomorrow.get(0), dateTomorrow, loadHour+startPos);
weatherForecastResultsTomorrow = weatherForecastDailyService.findByDay(dateTomorrow);
} catch (Exception e) {
return null;
}
List<Double> loadArimaForecastResultTomorrow = loadForecastArimaService.findByDateLoadAndHour(countryService.findById(Long.valueOf(this.getCountry().ordinal()+1)), dateTomorrow, loadHour);
List<Double> loadSimilarDayForecastResultTomorrow = loadForecastSimilarDayService.findByDateLoadAndHour(countryService.findById(Long.valueOf(this.getCountry().ordinal()+1)), dateTomorrow, loadHour);
double[] res = preparedDataLoadHoursService.findByDate(this.loadHour, this.dan, this.mesec, this.godina, countryService.findById(Long.valueOf(this.getCountry().ordinal()+1))).get(0).preparedVector();
res[24] = weatherForecastResults.get(0).getTemperatureMax();
res[25] = weatherForecastResults.get(0).getTemperatureMin();
res[26] = weatherForecastResults.get(0).getWindSpeed();
res[27] = weatherForecastResults.get(0).getHumidity();
res[28] = weatherForecastResults.get(0).getDewPoint();
res[29] = weatherForecastResults.get(0).getPressure();
res[30] = loadArimaForecastResult.get(0); // arima_forecast
res[31] = loadSimilarDayForecastResult.get(0); // similar_day_forecast
res[32] = historyLoadForecastResult.get(0); //load forecast for today
res[33] = weatherForecastResultsTomorrow.get(0).getTemperatureMax();
res[34] = weatherForecastResultsTomorrow.get(0).getTemperatureMin();
res[35] = weatherForecastResultsTomorrow.get(0).getWindSpeed();
res[36] = weatherForecastResultsTomorrow.get(0).getHumidity();
res[37] = weatherForecastResultsTomorrow.get(0).getDewPoint();
res[38] = weatherForecastResultsTomorrow.get(0).getPressure();
res[39] = loadArimaForecastResultTomorrow.get(0); // arima_forecast
res[40] = loadSimilarDayForecastResultTomorrow.get(0); // similar_day_forecast
return res;
}
public double getRealLoad() {
return preparedDataLoadHoursService.findRealByDate(this.loadHour, this.dan, this.mesec, this.godina, countryService.findById(Long.valueOf(this.getCountry().ordinal()+1)));
}
}
|
package com.java.practice.array;
/**
* Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate
* (i, ai). n vertical lines are drawn such that the two endpoints of the line i is at (i, ai)
* and (i, 0). Find two lines, which, together with the x-axis forms a container,
* such that the container contains the most water.
* <p>
* Notice that you may not slant the container.
* <p>
* Input: height = [1,8,6,2,5,4,8,3,7]
* Output: 49
* Explanation: The above vertical lines are represented by
* array [1,8,6,2,5,4,8,3,7]. In this case, the max area of
* water (blue section) the container can contain is 49.
* Example 2:
* <p>
* Input: height = [1,1]
* Output: 1
* Example 3:
* <p>
* Input: height = [4,3,2,1,4]
* Output: 16
* Example 4:
* <p>
* Input: height = [1,2,1]
* Output: 2
*/
public class MaxWaterContainer {
public static void main(String[] args) {
int[] nums = {1, 8, 6, 2, 5, 4, 8, 3, 7};
int left = 0;
int right = nums.length - 1;
int max = Integer.MIN_VALUE;
while (left < right) {
int min = Math.min(nums[left], nums[right]);
max = Math.max(max, min * (right - left));
if (nums[left] <= nums[right]) {
left++;
} else {
right--;
}
}
System.out.println(max);
}
}
|
/*
* 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 library.system.addbook;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXTextField;
import java.net.URL;
import java.sql.SQLException;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import library.system.dao.BookDAO;
import library.system.model.Book;
/**
* FXML Controller class
*
* @author Sithu
*/
public class AddbookController implements Initializable {
@FXML
private JFXTextField idField;
@FXML
private JFXTextField titleField;
@FXML
private JFXTextField authorField;
@FXML
private JFXTextField publisherField;
@FXML
private JFXButton saveBtn;
private BookDAO bookDAO;
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
bookDAO = new BookDAO();
}
@FXML
private void saveBookInfo(ActionEvent event) {
int id = 0;
try{
String idStr = idField.getText();
if(!idStr.isEmpty()){
id = Integer.parseInt(idField.getText());
}
}catch(NumberFormatException e){
System.out.println("Invalid input for id field.");
return;
}
String title = titleField.getText();
String author = authorField.getText();
String publisher = publisherField.getText();
if(title.isEmpty()||author.isEmpty()||publisher.isEmpty()){
System.out.println("Please fill all required fields.");
return;
}
Book book = new Book(id,title,author,publisher);
try {
bookDAO.saveBook(book);
System.out.println("Success");
} catch (SQLException ex) {
System.out.println("Failed.");
Logger.getLogger(AddbookController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
|
package com.yc.education.model.account;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleLongProperty;
import javafx.beans.property.SimpleStringProperty;
import java.math.BigDecimal;
/**
* @Description 成本核算-采购成本
* @Author BlueSky
* @Date 2019-01-18 11:24
*/
public class AccountCoastPurchaseProperty {
private SimpleLongProperty id = new SimpleLongProperty();
private SimpleIntegerProperty no = new SimpleIntegerProperty();
private SimpleStringProperty productNo = new SimpleStringProperty();
private SimpleStringProperty productName = new SimpleStringProperty();
private SimpleStringProperty warehousePosition = new SimpleStringProperty();
private SimpleStringProperty warehouseNum = new SimpleStringProperty();
private SimpleStringProperty price = new SimpleStringProperty();
private SimpleStringProperty dollar = new SimpleStringProperty();
private SimpleStringProperty orderNo = new SimpleStringProperty();
private SimpleStringProperty rmbMoney = new SimpleStringProperty();
private SimpleStringProperty usdMoney = new SimpleStringProperty();
private SimpleDoubleProperty tempProductPrice = new SimpleDoubleProperty(); //单项产品货款
private SimpleDoubleProperty tempGoodsTotalPrice = new SimpleDoubleProperty(); //货物总价
private SimpleDoubleProperty tempGoodsRate = new SimpleDoubleProperty(); //占货款比例
private SimpleDoubleProperty tempGoodsCost = new SimpleDoubleProperty(); //某商品成本
private SimpleDoubleProperty tempUnitCost = new SimpleDoubleProperty(); //单位成本
public AccountCoastPurchaseProperty(Long id,Integer no, String productNo, String productName, String warehousePosition, Integer warehouseNum, BigDecimal price, BigDecimal dollar, String orderNo, BigDecimal rmbMoney,BigDecimal usdMoney) {
if(id != null){
this.id = new SimpleLongProperty(id);
}
if(no != null){
this.no = new SimpleIntegerProperty(no);
}
if(productNo != null){
this.productNo = new SimpleStringProperty(productNo);
}
if(productName != null){
this.productName = new SimpleStringProperty(productName);
}
if(warehousePosition != null){
this.warehousePosition = new SimpleStringProperty(warehousePosition);
}
if(warehouseNum != null){
this.warehouseNum = new SimpleStringProperty(warehouseNum.toString());
}
if(price != null){
this.price = new SimpleStringProperty(price.toString());
}
if(dollar != null){
this.dollar = new SimpleStringProperty(dollar.toString());
}
if(orderNo != null){
this.orderNo = new SimpleStringProperty(orderNo);
}
if(rmbMoney != null){
this.rmbMoney = new SimpleStringProperty(rmbMoney.toString());
}
if(usdMoney != null){
this.usdMoney = new SimpleStringProperty(usdMoney.toString());
}
}
public AccountCoastPurchaseProperty( Integer no,String productNo, String productName, String warehousePosition, String warehouseNum, String price, String dollar, String orderNo, String rmbMoney,String usdMoney) {
if(no != null){
this.no = new SimpleIntegerProperty(no);
}
if(productNo != null){
this.productNo = new SimpleStringProperty(productNo);
}
if(productName != null){
this.productName = new SimpleStringProperty(productName);
}
if(warehousePosition != null){
this.warehousePosition = new SimpleStringProperty(warehousePosition);
}
if(warehouseNum != null){
this.warehouseNum = new SimpleStringProperty(warehouseNum);
}
if(price != null){
this.price = new SimpleStringProperty(price);
}
if(dollar != null){
this.dollar = new SimpleStringProperty(dollar);
}
if(orderNo != null){
this.orderNo = new SimpleStringProperty(orderNo);
}
if(rmbMoney != null){
this.rmbMoney = new SimpleStringProperty(rmbMoney);
}
if(usdMoney != null){
this.usdMoney = new SimpleStringProperty(usdMoney.toString());
}
}
public Long getId() {
if(id == null){
return null;
}else{
return id.get();
}
}
public SimpleLongProperty idProperty() {
return id;
}
public void setId(long id) {
this.id.set(id);
}
public String getUsdMoney() {
return usdMoney.get();
}
public SimpleStringProperty usdMoneyProperty() {
return usdMoney;
}
public void setUsdMoney(String usdMoney) {
this.usdMoney.set(usdMoney);
}
public int getNo() {
return no.get();
}
public SimpleIntegerProperty noProperty() {
return no;
}
public void setNo(int no) {
this.no.set(no);
}
public String getRmbMoney() {
if(rmbMoney == null){
return null;
}else {
return rmbMoney.get();
}
}
public SimpleStringProperty rmbMoneyProperty() {
return rmbMoney;
}
public void setRmbMoney(String rmbMoney) {
this.rmbMoney.set(rmbMoney);
}
public String getProductNo() {
if(productNo == null){
return null;
}else {
return productNo.get();
}
}
public SimpleStringProperty productNoProperty() {
return productNo;
}
public void setProductNo(String productNo) {
this.productNo.set(productNo);
}
public String getProductName() {
if(productName == null){
return null;
}else {
return productName.get();
}
}
public SimpleStringProperty productNameProperty() {
return productName;
}
public void setProductName(String productName) {
this.productName.set(productName);
}
public String getWarehousePosition() {
if(warehousePosition == null){
return null;
}else {
return warehousePosition.get();
}
}
public SimpleStringProperty warehousePositionProperty() {
return warehousePosition;
}
public void setWarehousePosition(String warehousePosition) {
this.warehousePosition.set(warehousePosition);
}
public String getWarehouseNum() {
if(warehouseNum == null){
return null;
}else {
return warehouseNum.get();
}
}
public SimpleStringProperty warehouseNumProperty() {
return warehouseNum;
}
public void setWarehouseNum(String warehouseNum) {
this.warehouseNum.set(warehouseNum);
}
public String getPrice() {
if(price == null){
return null;
}else {
return price.get();
}
}
public SimpleStringProperty priceProperty() {
return price;
}
public void setPrice(String price) {
this.price.set(price);
}
public String getDollar() {
if(dollar == null){
return null;
}else {
return dollar.get();
}
}
public SimpleStringProperty dollarProperty() {
return dollar;
}
public void setDollar(String dollar) {
this.dollar.set(dollar);
}
public String getOrderNo() {
if(orderNo == null){
return null;
}else {
return orderNo.get();
}
}
public SimpleStringProperty orderNoProperty() {
return orderNo;
}
public void setOrderNo(String orderNo) {
this.orderNo.set(orderNo);
}
public Double getTempProductPrice() {
return tempProductPrice.get();
}
public SimpleDoubleProperty tempProductPriceProperty() {
return tempProductPrice;
}
public void setTempProductPrice(double tempProductPrice) {
this.tempProductPrice.set(tempProductPrice);
}
public Double getTempGoodsTotalPrice() {
return tempGoodsTotalPrice.get();
}
public SimpleDoubleProperty tempGoodsTotalPriceProperty() {
return tempGoodsTotalPrice;
}
public void setTempGoodsTotalPrice(double tempGoodsTotalPrice) {
this.tempGoodsTotalPrice.set(tempGoodsTotalPrice);
}
public Double getTempGoodsRate() {
return tempGoodsRate.get();
}
public SimpleDoubleProperty tempGoodsRateProperty() {
return tempGoodsRate;
}
public void setTempGoodsRate(double tempGoodsRate) {
this.tempGoodsRate.set(tempGoodsRate);
}
public Double getTempGoodsCost() {
return tempGoodsCost.get();
}
public SimpleDoubleProperty tempGoodsCostProperty() {
return tempGoodsCost;
}
public void setTempGoodsCost(double tempGoodsCost) {
this.tempGoodsCost.set(tempGoodsCost);
}
public Double getTempUnitCost() {
return tempUnitCost.get();
}
public SimpleDoubleProperty tempUnitCostProperty() {
return tempUnitCost;
}
public void setTempUnitCost(double tempUnitCost) {
this.tempUnitCost.set(tempUnitCost);
}
}
|
package pardo.josengel.android_json;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
/**
* Created by JoseÁngel on 28/03/2015.
*/
public class tools {
/*
Comprobación conexion a internet
*/
public Boolean isOnline(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
}
|
package com.bpdts.testapp.api.spring.live;
import com.bpdts.testapp.api.spring.UserServiceSpringRestClient;
import com.bpdts.testapp.api.spring.UserServiceSpringRestClientTest;
import com.bpdts.testapp.client.model.spring.User;
import org.junit.Before;
import org.springframework.boot.web.client.RestTemplateBuilder;
public class UserServiceSpringRestClientAgainstRealServerTest extends UserServiceSpringRestClientTest
{
@Before
public void setUp() {
RestTemplateBuilder builder = new RestTemplateBuilder().rootUri( serverBaseUri() );
sut = new UserServiceSpringRestClient( builder );
}
@Override
protected void setUpForExistingUser( User user ) {
// NOP
}
@Override
protected void setUpForNonexistentUser( User user ) {
// NOP
}
@Override
protected void setUpForPopulatedCitySpecificUserData(String city) {
// NOP
}
@Override
protected void setUpForUnpopulatedCitySpecificUserData( String city ) {
// NOP
}
@Override
protected void setUpForCityAgnosticUserData() {
// NOP
}
}
|
package com.qac.nbg_app.managers;
import java.util.ArrayList;
import java.util.List;
import com.qac.nbg_app.entities.Product;
import com.qac.nbg_app.entities.ProductGroup;
public interface ProductManager {
public List<ProductGroup> findAll();
void persistProduct(Product p);
void persistProducts(ArrayList<Product> ps);
Product findByName(String name);
ArrayList<Product> getEntities();
void updateProduct(Product p);
void removeProduct(Product p);
}
|
/*
* MIT License
* Copyright (c) 2017-2019 nuls.io
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.nuls.block.thread.monitor;
import io.nuls.base.data.NulsHash;
import io.nuls.block.model.BlockSaveTemp;
import io.nuls.block.model.ChainContext;
import io.nuls.core.log.logback.NulsLogger;
import io.nuls.core.rpc.util.NulsDateUtils;
import java.util.*;
/**
* bzt校验的区块数据清理情况监控器
* 每隔固定时间间隔启动
* 如果发现缓存数据超出100size,则启动时间对比进行数据清理
*
* @author ljs
* @version 1.0
* @date 19-12-14 下午3:53
*/
public class BlockBZTClearMonitor extends BaseMonitor {
/**
* 如果缓存中有200个区块基础验证通过的区块在2分钟之内还未拜占庭通过则需要清理删除
* */
private static final short MAX_TEMP_SIZE = 200;
private static final short OVER_TIME_INTERVAL = 120;
private static final BlockBZTClearMonitor INSTANCE = new BlockBZTClearMonitor();
public static BlockBZTClearMonitor getInstance() {
return INSTANCE;
}
@Override
protected void process(int chainId, ChainContext context, NulsLogger commonLog) {
Map<NulsHash, BlockSaveTemp> blockSaveTempMap = context.getBlockVerifyResult();
long nowTime = NulsDateUtils.getCurrentTimeSeconds();
try {
if(blockSaveTempMap.size() > MAX_TEMP_SIZE){
blockSaveTempMap.entrySet().removeIf(entry -> (nowTime - entry.getValue().getTime() > OVER_TIME_INTERVAL));
}
}catch(Exception e){
commonLog.error(e);
}
}
}
|
package f.star.iota.milk.ui.lingyu.ling;
import android.util.Log;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import f.star.iota.milk.base.PVContract;
import f.star.iota.milk.base.StringPresenter;
public class LingYuPresenter extends StringPresenter<List<LingYuBean>> {
public LingYuPresenter(PVContract.View view) {
super(view);
}
@Override
protected List<LingYuBean> dealResponse(String s, HashMap<String, String> headers) {
List<LingYuBean> list = new ArrayList<>();
Document parse = Jsoup.parse(s);
parse.select("#slideshow").remove();
Elements select = parse.select("#main > div.wow");
for (Element element : select) {
LingYuBean bean = new LingYuBean();
String preview = element.select("article > div > figure div img").attr("data-original");
Log.i("preview", "apply: " + preview);
bean.setPreview(preview);
String url = element.select("article > header > h2 > a").attr("href");
bean.setUrl(url);
bean.setHeaders(headers);
String description = element.select("article > header > h2 > a").text();
bean.setDescription(description);
String date = element.select("article > div > span.entry-meta > span:nth-child(2)").text();
bean.setDate(date);
list.add(bean);
}
return list;
}
}
|
package com.practice.mybatistest;
import java.util.List;
import com.practice.mybatistest.dto.MyBatisTestDto;
public class MyBatisTestFindMain {
public static void main(String[] args) {
MyBatisTestDao<MyBatisTestDto> dao = new MyBatisTestDao<MyBatisTestDto>();
MyBatisTestDto dto = new MyBatisTestDto();
dto.setColTest1(null);
dto.setColTest2(null);
dto.setColTest3(null);
List<MyBatisTestDto> recs = dao.find(dto);
for (MyBatisTestDto rec : recs) {
System.out.print("id : " + rec.getId() + ", ");
System.out.print("col_test_1 : " + rec.getColTest1() + ", ");
System.out.print("col_test_2 : " + rec.getColTest2() + ", ");
System.out.print("col_test_3 : " + rec.getColTest3());
System.out.println();
}
}
}
|
package com.indictrans.model;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@Entity
@Table(name="commissionTable7")
public class CommissionTable {
@Id
@GeneratedValue
@Column(name="id")
private Long id;
@Column(name="fromArea")
private Long fromArea;
@Column(name = "toArea")
private Long toArea;
@Column(name="type")
private Integer type;
@Column(name = "fixed")
private Integer fixed;
@Column(name = "percentage")
private Integer percentage;
@Column(name = "fromCode")
private Long fromCode;
@Column(name = "toCode")
private Long toCode;
@Column(name = "fromDate")
private Date fromDate;
@Column(name="toDtate")
private Date toDate;
@JsonIgnore
@OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="commiTableId")
private List<Bill> block=new ArrayList<Bill>();
public List<Bill> getBlock() { return block; }
public void setBlock(List<Bill> block) { this.block = block; }
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public Integer getFixed() {
return fixed;
}
public void setFixed(Integer fixed) {
this.fixed = fixed;
}
public Integer getPercentage() {
return percentage;
}
public void setPercentage(Integer percentage) {
this.percentage = percentage;
}
public Long getFromArea() {
return fromArea;
}
public void setFromArea(Long fromArea) {
this.fromArea = fromArea;
}
public Long getToArea() {
return toArea;
}
public void setToArea(Long toArea) {
this.toArea = toArea;
}
public Long getFromCode() {
return fromCode;
}
public void setFromCode(Long fromCode) {
this.fromCode = fromCode;
}
public Long getToCode() {
return toCode;
}
public void setToCode(Long toCode) {
this.toCode = toCode;
}
public Date getFromDate() {
return fromDate;
}
public void setFromDate(Date fromDate) {
this.fromDate = fromDate;
}
public Date getToDate() {
return toDate;
}
public void setToDate(Date toDate) {
this.toDate = toDate;
}
@Override public String toString() { return "CommissionTable [id=" + id +
", fromArea=" + fromArea + ", toArea=" + toArea + ", type=" + type +
", fixed=" + fixed + ", percentage=" + percentage + ", fromCode=" + fromCode
+ ", toCode=" + toCode + ", fromDate=" + fromDate + ", toDate=" + toDate +
", block=" + block + "]"; }
}
|
package fr.myProject.dao;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import fr.myProject.entities.Product;
/**
* @author Bacem
*
*/
@Repository
public interface ProductRepository extends JpaRepository<Product, Long>{
Optional<Product> findById(Long id);
}
|
package mb.tianxundai.com.toptoken.bean;
/**
* @author txd_dbb
* @emil 15810277571@163.com
* create at 2018/10/1515:58
* description:
*/
public class ReceivablesBean {
/**
* code : 101
* message : 获取成功
* data : {"yestodayProceed":null,"fee":0,"selected":false,"priceBlock":0,"currentUsd":9.6479296818,"topCoin":{"minExchange":1,"MaxExchange":20000,"selected":false,"unit":1,"coinId":7,"shortName":"ETC","url":"https://img.jinse.com/529699_image20.png","minOut":1,"MaxExchange":20000,"decimals":null,"conversionCny":null,"enable":null,"tradingLimit":null,"outLimit":null,"status":null,"affirm":null,"outcommission":null,"orderNumber":1},"quantization":0,"currentCny":67.0550408742,"gasPrice":0,"userName":null,"userWalletCoinId":1193,"userWalletId":85500345261752320,"coinId":7,"coinShortName":"ETC","coinAddress":"0xa634cbdb57e48ab05d72ad4adac6710d6c54b5a0","price":2672.511,"enable":"1"}
*/
private int code;
private String message;
private DataBean data;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public DataBean getData() {
return data;
}
public void setData(DataBean data) {
this.data = data;
}
public static class DataBean {
/**
* yestodayProceed : null
* fee : 0.0
* selected : false
* priceBlock : 0.0
* currentUsd : 9.6479296818
* topCoin : {"minExchange":1,"MaxExchange":20000,"selected":false,"unit":1,"coinId":7,"shortName":"ETC","url":"https://img.jinse.com/529699_image20.png","minOut":1,"MaxExchange":20000,"decimals":null,"conversionCny":null,"enable":null,"tradingLimit":null,"outLimit":null,"status":null,"affirm":null,"outcommission":null,"orderNumber":1}
* quantization : 0.0
* currentCny : 67.0550408742
* gasPrice : 0.0
* userName : null
* userWalletCoinId : 1193
* userWalletId : 85500345261752320
* coinId : 7
* coinShortName : ETC
* coinAddress : 0xa634cbdb57e48ab05d72ad4adac6710d6c54b5a0
* price : 2672.511
* enable : 1
*/
private Object yestodayProceed;
private double fee;
private boolean selected;
private double priceBlock;
private double currentUsd;
private TopCoinBean topCoin;
private double quantization;
public long getUserWalletCoinId() {
return userWalletCoinId;
}
public void setUserWalletCoinId(long userWalletCoinId) {
this.userWalletCoinId = userWalletCoinId;
}
public long getCoinId() {
return coinId;
}
public void setCoinId(long coinId) {
this.coinId = coinId;
}
private double currentCny;
private double gasPrice;
private Object userName;
private long userWalletCoinId;
private long userWalletId;
private long coinId;
private String coinShortName;
private String coinAddress;
private double price;
private String enable;
public Object getYestodayProceed() {
return yestodayProceed;
}
public void setYestodayProceed(Object yestodayProceed) {
this.yestodayProceed = yestodayProceed;
}
public double getFee() {
return fee;
}
public void setFee(double fee) {
this.fee = fee;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public double getPriceBlock() {
return priceBlock;
}
public void setPriceBlock(double priceBlock) {
this.priceBlock = priceBlock;
}
public double getCurrentUsd() {
return currentUsd;
}
public void setCurrentUsd(double currentUsd) {
this.currentUsd = currentUsd;
}
public TopCoinBean getTopCoin() {
return topCoin;
}
public void setTopCoin(TopCoinBean topCoin) {
this.topCoin = topCoin;
}
public double getQuantization() {
return quantization;
}
public void setQuantization(double quantization) {
this.quantization = quantization;
}
public double getCurrentCny() {
return currentCny;
}
public void setCurrentCny(double currentCny) {
this.currentCny = currentCny;
}
public double getGasPrice() {
return gasPrice;
}
public void setGasPrice(double gasPrice) {
this.gasPrice = gasPrice;
}
public Object getUserName() {
return userName;
}
public void setUserName(Object userName) {
this.userName = userName;
}
public long getUserWalletId() {
return userWalletId;
}
public void setUserWalletId(long userWalletId) {
this.userWalletId = userWalletId;
}
public String getCoinShortName() {
return coinShortName;
}
public void setCoinShortName(String coinShortName) {
this.coinShortName = coinShortName;
}
public String getCoinAddress() {
return coinAddress;
}
public void setCoinAddress(String coinAddress) {
this.coinAddress = coinAddress;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getEnable() {
return enable;
}
public void setEnable(String enable) {
this.enable = enable;
}
public static class TopCoinBean {
/**
* minExchange : 1.0
* MaxExchange : 20000.0
* selected : false
* unit : 1
* coinId : 7
* shortName : ETC
* url : https://img.jinse.com/529699_image20.png
* minOut : 1
* MaxExchange : 20000
* decimals : null
* conversionCny : null
* enable : null
* tradingLimit : null
* outLimit : null
* status : null
* affirm : null
* outcommission : null
* orderNumber : 1
*/
private double minExchange;
private boolean selected;
private long unit;
private long coinId;
private String shortName;
private String url;
private double minOut;
private double maxExchange;
private Object decimals;
private Object conversionCny;
private Object enable;
private Object tradingLimit;
private Object outLimit;
private Object status;
private Object affirm;
private Object outcommission;
private double orderNumber;
public double getMinExchange() {
return minExchange;
}
public void setMinExchange(double minExchange) {
this.minExchange = minExchange;
}
public double getMaxExchange() {
return maxExchange;
}
public void setMaxExchange(double MaxExchange) {
this.maxExchange = MaxExchange;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public String getShortName() {
return shortName;
}
public void setShortName(String shortName) {
this.shortName = shortName;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Object getDecimals() {
return decimals;
}
public void setDecimals(Object decimals) {
this.decimals = decimals;
}
public Object getConversionCny() {
return conversionCny;
}
public void setConversionCny(Object conversionCny) {
this.conversionCny = conversionCny;
}
public Object getEnable() {
return enable;
}
public void setEnable(Object enable) {
this.enable = enable;
}
public Object getTradingLimit() {
return tradingLimit;
}
public void setTradingLimit(Object tradingLimit) {
this.tradingLimit = tradingLimit;
}
public long getUnit() {
return unit;
}
public void setUnit(long unit) {
this.unit = unit;
}
public long getCoinId() {
return coinId;
}
public void setCoinId(long coinId) {
this.coinId = coinId;
}
public double getMinOut() {
return minOut;
}
public void setMinOut(double minOut) {
this.minOut = minOut;
}
public double getOrderNumber() {
return orderNumber;
}
public void setOrderNumber(double orderNumber) {
this.orderNumber = orderNumber;
}
public Object getOutLimit() {
return outLimit;
}
public void setOutLimit(Object outLimit) {
this.outLimit = outLimit;
}
public Object getStatus() {
return status;
}
public void setStatus(Object status) {
this.status = status;
}
public Object getAffirm() {
return affirm;
}
public void setAffirm(Object affirm) {
this.affirm = affirm;
}
public Object getOutcommission() {
return outcommission;
}
public void setOutcommission(Object outcommission) {
this.outcommission = outcommission;
}
}
}
}
|
package com.kab.chatclient.data;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import com.kab.chatclient.data.MyDataBaseContract.ChatDbEntry;
/**
* Created by Kraskovskiy on 06.07.16.
*/
public class DbHelper extends SQLiteOpenHelper {
public static final Uri URI_TABLE_NAME = Uri.parse("sqlite://com.kab.chatclient/table/" + ChatDbEntry.TABLE_NAME);
static final String DB_CREATE_STRING = "create table "+ ChatDbEntry.TABLE_NAME+ " ("
+ ChatDbEntry.COLUMN_ID+" integer primary key autoincrement,"
+ ChatDbEntry.COLUMN_SENDER+" text,"
+ ChatDbEntry.COLUMN_MESSAGE+" text,"
+ ChatDbEntry.COLUMN_DATE+" text"
+");";
private static final int NUMBER_OF_VERSION_DB = 1;
DbHelper(Context context) {
super(context, ChatDbEntry.DATABASE_NAME, null, NUMBER_OF_VERSION_DB);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DB_CREATE_STRING);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
@Override
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
|
package com.giladkz.verticalEnsemble.Data;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
import weka.core.Attribute;
import weka.core.DenseInstance;
import weka.core.Instances;
import weka.core.converters.ArffSaver;
import java.io.File;
import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;
/**
* Created by giladkatz on 11/02/2016.
*/
public class Dataset implements Serializable{
private List<ColumnInfo> columns;
private int numOfInstancesPerColumn;
private List<Fold> folds;
private List<Integer> indices;
private List<Integer> indicesOfTrainingFolds;
private List<Integer> indicesOfValidationFolds;
private List<Integer> indicesOfTestFolds;
private List<Integer>[] trainingIndicesByClass;
private List<Integer>[] validationIndicesByClass;
private int[] numOfTrainingInstancesPerClass;
private int[] numOfValidationInstancesPerClass;
private int[] numOfTestInstancesPerClass;
private int numOfTrainingRows = 0;
private int numOfValidationRows = 0;
private int numOfTestRows = 0;
private int targetColumnIndex;
private String name;
private List<ColumnInfo> distinctValColumns = new ArrayList<>();
private List<ColumnInfo> distinctValueCompliantColumns = new ArrayList<>();
private HashMap<List<String>, List<Integer>> trainFoldDistinctValMappings;
private HashMap<List<String>, List<Integer>> validationFoldDistinctValMappings;
private HashMap<List<String>, List<Integer>> testFoldDistinctValMappings;
private List<Integer> trainFoldsDistinctValRepresentatives;
private List<Integer> testFoldsDistinctValRepresentatives;
//Defines the maximal number of distinct values a discrete attribute can have in order to be included in the ARFF file
private int maxNumOFDiscreteValuesForInstancesObject;
/**
* Used in all the operations which require a random variable. A fixed seed enables us to recreate experiments.
*/
private int randomSeed;
public Dataset(List<ColumnInfo> columns, List<Fold> folds, int targetClassIdx, String name, int numOfInstancesPerColumn, List<ColumnInfo> distinctValColumns, int randomSeed, int maxNumOfValsPerDiscreteAttribtue) throws Exception {
this.randomSeed = randomSeed;
this.columns = columns;
this.numOfInstancesPerColumn = numOfInstancesPerColumn;
this.folds = folds;
this.targetColumnIndex = targetClassIdx;
this.name = name;
this.maxNumOFDiscreteValuesForInstancesObject = maxNumOfValsPerDiscreteAttribtue;
if (distinctValColumns != null) {
this.distinctValColumns = distinctValColumns;
trainFoldDistinctValMappings = new HashMap<>();
testFoldDistinctValMappings = new HashMap<>();
}
this.indices = new ArrayList<>();
this.indicesOfTrainingFolds = new ArrayList<>();
this.indicesOfTestFolds = new ArrayList<>();
this.trainingIndicesByClass = new List[folds.get(0).getInstancesClassDistribution().length];
this.numOfTrainingInstancesPerClass = new int[folds.get(0).getInstancesClassDistribution().length];
this.numOfTestInstancesPerClass = new int[folds.get(0).getInstancesClassDistribution().length];
for (Fold fold: folds) {
this.indices.addAll(fold.getIndices());
if (fold.getTypeOfFold() == FoldsInfo.foldType.Train) {
this.indicesOfTrainingFolds.addAll(fold.getIndices());
for (int classIdx = 0; classIdx < fold.getInstancesClassDistribution().length; classIdx++) {
int numOfInstance = fold.getNumOfInstancesPerClass(classIdx);
this.numOfTrainingInstancesPerClass[classIdx] += numOfInstance;
this.numOfTrainingRows += numOfInstance;
}
for (int i=0; i<folds.get(0).getInstancesClassDistribution().length; i++) {
if (this.trainingIndicesByClass[i] == null) {
this.trainingIndicesByClass[i] = new ArrayList<>();
}
this.trainingIndicesByClass[i].addAll(fold.getIndicesPerClass(i));
}
//Add all the distint values of the fold to the dataset object
trainFoldDistinctValMappings.putAll(fold.getDistinctValMappings());
}
if (fold.getTypeOfFold() == FoldsInfo.foldType.Validation) {
this.indicesOfValidationFolds.addAll(fold.getIndices());
for (int classIdx = 0; classIdx < fold.getInstancesClassDistribution().length; classIdx++) {
int numOfInstance = fold.getNumOfInstancesPerClass(classIdx);
this.numOfValidationInstancesPerClass[classIdx] += numOfInstance;
this.numOfValidationRows += numOfInstance;
}
for (int i=0; i<folds.get(0).getInstancesClassDistribution().length; i++) {
if (this.validationIndicesByClass[i] == null) {
this.validationIndicesByClass[i] = new ArrayList<>();
}
this.validationIndicesByClass[i].addAll(fold.getIndicesPerClass(i));
}
//Add all the distint values of the fold to the dataset object
validationFoldDistinctValMappings.putAll(fold.getDistinctValMappings());
}
if (fold.getTypeOfFold() == FoldsInfo.foldType.Test) {
this.indicesOfTestFolds.addAll(fold.getIndices());
for (int classIdx = 0; classIdx < fold.getInstancesClassDistribution().length; classIdx++) {
int numOfInstance = fold.getNumOfInstancesPerClass(classIdx);
this.numOfTestInstancesPerClass[classIdx] += numOfInstance;
this.numOfTestRows += numOfInstance;
}
//Add all the distint values of the fold to the dataset object
testFoldDistinctValMappings.putAll(fold.getDistinctValMappings());
}
}
//Now that we are done processing the indices, we select one "representative" for each distinct value
trainFoldsDistinctValRepresentatives = new ArrayList<>();
for (List<String> key : trainFoldDistinctValMappings.keySet()) {
int index = trainFoldDistinctValMappings.get(key).get(0);
trainFoldsDistinctValRepresentatives.add(index);
}
testFoldsDistinctValRepresentatives = new ArrayList<>();
for (List<String> key : testFoldDistinctValMappings.keySet()) {
int index = testFoldDistinctValMappings.get(key).get(0);
testFoldsDistinctValRepresentatives.add(index);
}
//finally, we sort the indices so that they will correspond with the order of the values in the columns
Collections.sort(this.indices);
Collections.sort(this.indicesOfTrainingFolds);
Collections.sort(this.indicesOfTestFolds);
Collections.sort(trainFoldsDistinctValRepresentatives);
Collections.sort(testFoldsDistinctValRepresentatives);
for (int i=0; i<this.trainingIndicesByClass.length; i++) {
Collections.sort(this.trainingIndicesByClass[i]);
}
for (ColumnInfo ci : columns) {
if (isColumnDistinctValuesCompatibe(ci)) {
distinctValueCompliantColumns.add(ci);
}
}
}
/**
* Recieved another dataset that needs to be added to the current dataset as a test set
* @param testSet
*/
public void AttachExternalTestFold(Dataset testSet) throws Exception {
int numOfRowsInBaseDataset = this.numOfTrainingRows + this.numOfTestRows;
//If an existing fold is defined as test, change it to train
for (Fold fold : folds) {
if (fold.isTestFold()) {
fold.setIsTestFold(false);
}
}
Fold newTestFold = new Fold(numOfTrainingInstancesPerClass.length, FoldsInfo.foldType.Test);
if (testSet.getDistinctValueColumns() == null || testSet.getDistinctValueColumns().size() == 0) {
for (int i = 0; i < testSet.numOfTrainingRows + testSet.numOfTestRows; i++) {
newTestFold.addInstance(this.numOfTrainingRows + this.numOfTestRows + i, (Integer) testSet.getTargetClassColumn().getColumn().getValue(i));
}
}
else {
for (Fold testSetFold : testSet.folds) {
for (List<String> sources : testSetFold.getDistinctValMappings().keySet()) {
int firstItemIndexInBatch = testSetFold.getDistinctValMappings().get(sources).get(0);
int groupClass = (Integer) testSet.getTargetClassColumn().getColumn().getValue(firstItemIndexInBatch);
List<Integer> newIndices = new ArrayList<>();
for (int val : testSetFold.getDistinctValMappings().get(sources)) {
newIndices.add(val + numOfRowsInBaseDataset);
}
newTestFold.addDistinctValuesBatch(sources, newIndices, groupClass);
}
}
}
this.folds.add(newTestFold);
//change the folds indices
indices.addAll(testSet.getIndices());
indicesOfTrainingFolds.addAll(indicesOfTestFolds);
indicesOfTestFolds = testSet.getIndicesOfTestInstances();
indicesOfTestFolds.addAll(testSet.getIndicesOfTrainingInstances());
//update the total size of the joined datast
numOfTrainingRows = indicesOfTrainingFolds.size();
numOfTestRows = indicesOfTestFolds.size();
//now we need to update every aspect of the current Dataset object
numOfInstancesPerColumn += testSet.getNumOfInstancesPerColumn();
//the current division of train/test needs to be discarded. All items need to be transferred to the training
for (int i=0; i<numOfTrainingInstancesPerClass.length; i++) {
numOfTrainingInstancesPerClass[i] += numOfTestInstancesPerClass[i];
numOfTestInstancesPerClass[i] = testSet.getNumOfRowsPerClassInTrainingSet()[i] + testSet.getNumOfRowsPerClassInTestSet()[i];
}
//If the dataset has distinct values then we need to modify additional parameters
//move all the distinct values in the test (of the training dataset) to the train
if (distinctValColumns != null) {
AttachExternalDatasetDistinctValues(testSet);
}
//Finally, the task pf updating the column objects
for (int i=0; i<columns.size(); i++) {
Column currentColumn = columns.get(i).getColumn();
List<Integer> tempList = new ArrayList<>(); tempList.add(i);
Column testSetColumn = testSet.getColumns(tempList).get(0).getColumn();
switch (currentColumn.getType()) {
case Discrete:
DiscreteColumn discreteReplacementColumn = new DiscreteColumn(numOfInstancesPerColumn, ((DiscreteColumn)currentColumn).getNumOfPossibleValues());
populateJoinedColumnValues(discreteReplacementColumn, currentColumn, testSetColumn);
columns.get(i).setColumn(discreteReplacementColumn);
break;
case Numeric:
NumericColumn numericReplacementColumn = new NumericColumn(numOfInstancesPerColumn);
populateJoinedColumnValues(numericReplacementColumn, currentColumn, testSetColumn);
columns.get(i).setColumn(numericReplacementColumn);
break;
case Date:
DateColumn dateReplacementColumn = new DateColumn(numOfInstancesPerColumn, ((DateColumn)currentColumn).getDateFomat());
populateJoinedColumnValues(dateReplacementColumn, currentColumn, testSetColumn);
columns.get(i).setColumn(dateReplacementColumn);
break;
case String:
StringColumn stringReplacementColumn = new StringColumn(numOfInstancesPerColumn);
populateJoinedColumnValues(stringReplacementColumn, currentColumn, testSetColumn);
columns.get(i).setColumn(stringReplacementColumn);
break;
default:
throw new Exception("unidentified column type");
}
}
}
private void AttachExternalDatasetDistinctValues(Dataset testSet) {
trainFoldDistinctValMappings.clear();
testFoldDistinctValMappings.clear();
trainFoldsDistinctValRepresentatives.clear();
testFoldsDistinctValRepresentatives.clear();
for (Fold fold: folds) {
//Add all the distint values of the fold to the dataset object
if (!fold.isTestFold()) {
trainFoldDistinctValMappings.putAll(fold.getDistinctValMappings());
}
else {
testFoldDistinctValMappings.putAll(fold.getDistinctValMappings());
}
}
//Now that we are done processing the indices, we select one "representative" for each distinct value
trainFoldsDistinctValRepresentatives.clear();
testFoldsDistinctValRepresentatives.clear();
trainFoldsDistinctValRepresentatives = new ArrayList<>();
for (List<String> key : trainFoldDistinctValMappings.keySet()) {
int index = trainFoldDistinctValMappings.get(key).get(0);
trainFoldsDistinctValRepresentatives.add(index);
}
testFoldsDistinctValRepresentatives = new ArrayList<>();
for (List<String> key : testFoldDistinctValMappings.keySet()) {
int index = testFoldDistinctValMappings.get(key).get(0);
testFoldsDistinctValRepresentatives.add(index);
}
}
private void populateJoinedColumnValues(Column newColumn, Column currentColumn, Column testSetColumn) {
for (int j=0; j<numOfTrainingRows; j++) {
newColumn.setValue(j,currentColumn.getValue(j));
}
for (int j=numOfTrainingRows; j<numOfTrainingRows+numOfTestRows; j++) {
newColumn.setValue(j,testSetColumn.getValue(j-numOfTrainingRows));
}
}
/**
* Returns the required size of each
* @return
*/
public int getNumOfInstancesPerColumn() {
return this.numOfInstancesPerColumn;
}
/**
* Internal constructor, used for replication
*/
private Dataset() {}
/**
* Gets the indeices of the instances assigned to the training folds
* @return
*/
public List<Integer> getIndicesOfTrainingInstances() {
return indicesOfTrainingFolds;
}
/**
* Gets the idices of the instances assigned to the test folds
* @return
*/
public List<Integer> getIndicesOfTestInstances() {
return indicesOfTestFolds;
}
/**
* Returns the indices of the samples allocated to this dataset
* @return
*/
public List<Integer> getIndices() {
return indices;
}
/**
* Returns the number of samples in this dataset (both training and test)
* @return
*/
public int getNumberOfRows() {
return this.numOfTrainingRows + this.numOfTestRows + this.numOfValidationRows;
}
/**
* Returns the name of the dataset
* @return
*/
public String getName() {
return this.name;
}
/**
* Returns the total number of lines in the training dataset
* @return
*/
public int getNumOfTrainingDatasetRows() {
return this.numOfTrainingRows;
}
/**
* Returns the total number of lines in the test dataset
* @return
*/
public int getNumOfTestDatasetRows() {
return this.numOfTestRows;
}
/**
* Returns the number of classes in the dataset
* @return
*/
public int getNumOfClasses() {
return numOfTrainingInstancesPerClass.length;
}
/**
* Returns the number of samples that belong to each class in the training set
* @return
*/
public int[] getNumOfRowsPerClassInTrainingSet() {
return numOfTrainingInstancesPerClass;
}
/**
* Returns the number of samples that belong to each class in the test set
* @return
*/
public int[] getNumOfRowsPerClassInTestSet() {
return numOfTestInstancesPerClass;
}
public List<Integer>[] getTrainingIndicesByClass() {
return this.trainingIndicesByClass;
}
public List<Fold> getFolds() {
return this.folds;
}
/**
* Returns the index of the class with the least number of instances
* @return
*/
public int getMinorityClassIndex() {
int currentIdx = -1;
int numOfInstances = Integer.MAX_VALUE;
for (int i=0; i<numOfTrainingInstancesPerClass.length; i++) {
if (numOfTrainingInstancesPerClass[i]< numOfInstances) {
numOfInstances = numOfTrainingInstancesPerClass[i];
currentIdx = i;
}
}
return currentIdx;
}
/**
* Returns speofic columns from the dataset
* @param columnIndices
* @return
*/
public List<ColumnInfo> getColumns(List<Integer> columnIndices) {
List<ColumnInfo> columnsList = new ArrayList<>();
for (int columnIndex: columnIndices) {
columnsList.add(columns.get(columnIndex));
}
return columnsList;
}
public void addColumn(ColumnInfo column) {
this.columns.add(column);
}
/**
* Returns all the colums of the dataset object
* @param includeTargetColumn whether the target column should also be returned
* @return
*/
public List<ColumnInfo> getAllColumns(boolean includeTargetColumn) {
List<ColumnInfo> columnsList = new ArrayList<>();
for (ColumnInfo column: columns) {
if ((!distinctValColumns.contains(column)) && (!column.isTargetClass() || includeTargetColumn)) {
columnsList.add(column);
}
}
return columnsList;
}
/**
* Returns all the columns of a specified type
* @param columnType
* @param includeTargetColumn whether the target column should also be returned if it meets the criterion
* @return
*/
public List<ColumnInfo> getAllColumnsOfType (Column.columnType columnType, boolean includeTargetColumn) {
List<ColumnInfo> columnsToReturn = new ArrayList<>();
for (ColumnInfo ci: columns) {
if (ci.getColumn().getType() == columnType) {
if (ci == getTargetClassColumn()) {
if (includeTargetColumn) {
columnsToReturn.add(ci);
}
}
else {
columnsToReturn.add(ci);
}
}
}
return columnsToReturn;
}
/**
* Returns the target class column
* @return
*/
public ColumnInfo getTargetClassColumn() {
return columns.get(targetColumnIndex);
}
/**
* Returns the columns used to create the distinct value of the instances
* @return
*/
public List<ColumnInfo> getDistinctValueColumns() {
return this.distinctValColumns;
}
/**
* Samples a predefined number of samples from the dataset (while maintaining the ratio)
* and generates a Weka Instances object.
* IMPORTANT:this function is written so that it can only be applied on the training set, because
* the classification model is trained on it. The test set is meant to be used as a whole.
* @param numOfSamples
* @param randomSeed
* @return
* @throws Exception
*/
public Instances generateSetWithSampling(int numOfSamples, int randomSeed) throws Exception {
double[] numOfRequiredIntancesPerClass = new double[numOfTrainingInstancesPerClass.length];
//Start by getting the number of items we need from each class
for (int i=0; i<numOfRequiredIntancesPerClass.length; i++) {
numOfRequiredIntancesPerClass[i] = numOfSamples * (((double)numOfTrainingInstancesPerClass[i])/((double)numOfTrainingRows));
}
//Now we extract the subset for each class
Random rnd = new Random(randomSeed);
List<Integer> subsetIndicesList = new ArrayList<>();
for (int i=0; i<numOfRequiredIntancesPerClass.length; i++) {
int assignedItemsFromClass = 0;
while (assignedItemsFromClass < numOfRequiredIntancesPerClass[i]) {
int pos = rnd.nextInt(this.trainingIndicesByClass[i].size());
int index = trainingIndicesByClass[i].get(pos);
if (!subsetIndicesList.contains(index)) {
subsetIndicesList.add(index);
assignedItemsFromClass++;
}
}
}
//get all the attributes that need to be included in the set
ArrayList<Attribute> attributes = new ArrayList<>();
getAttributesListForClassifier(attributes);
Instances finalSet = new Instances("trainingSet", attributes, 0);
double[][] dataMatrix = getDataMatrixByIndices(subsetIndicesList);
for (int i=0; i<dataMatrix[0].length; i++) {
double[] arr = new double[dataMatrix.length];
for (int j=0; j<dataMatrix.length; j++) {
arr[j] = dataMatrix[j][i];
}
DenseInstance di = new DenseInstance(1.0, arr);
finalSet.add(i, di);
}
finalSet.setClassIndex(targetColumnIndex-getNumberOfDateStringAndDistinctColumns());
return finalSet;
}
/**
* Used to obtain either the training or test set of the dataset
* @param foldType the type of fold from which we want to extract the data
* @return
* @throws Exception
*/
public Instances generateSet(FoldsInfo.foldType foldType, List<Integer> instanceIndices) throws Exception {
ArrayList<Attribute> attributes = new ArrayList<>();
//get all the attributes that need to be included in the set
getAttributesListForClassifier(attributes);
//Create an empty set of instances and populate with the instances
double[][] dataMatrix = null;
Instances finalSet = null;
if (foldType == FoldsInfo.foldType.Train) {
finalSet = new Instances("trainingSet", attributes, 0);
dataMatrix = getTrainingDataMatrix(instanceIndices);
}
if (foldType == FoldsInfo.foldType.Validation) {
finalSet = new Instances("testSet", attributes, 0);
dataMatrix = getValidationDataMatrix(instanceIndices);
}
if (foldType == FoldsInfo.foldType.Test) {
finalSet = new Instances("testSet", attributes, 0);
dataMatrix = getTestDataMatrix(instanceIndices);
}
for (int i=0; i<dataMatrix[0].length; i++) {
double[] arr = new double[dataMatrix.length];
for (int j=0; j<dataMatrix.length; j++) {
arr[j] = dataMatrix[j][i];
}
DenseInstance di = new DenseInstance(1.0, arr);
finalSet.add(i, di);
}
finalSet.setClassIndex(targetColumnIndex-getNumberOfDateStringAndDistinctColumnsBeforeTargetClass());
return finalSet;
}
/**
* Iterates over all the columns of the dataset object and returns those that can be
* included in the Instances object that will be fed to Weka (i.e. excluding the Date
* and String columns)
* @param attributes
* @throws Exception
*/
private void getAttributesListForClassifier(ArrayList<Attribute> attributes) throws Exception {
for (int i =0; i< columns.size(); i++) {
ColumnInfo currentColumn = columns.get(i);
//The dataset will not include the distinct value columns, if they exist
if (this.distinctValColumns.contains(currentColumn)) {
continue;
}
Attribute att = null;
switch(currentColumn.getColumn().getType())
{
case Numeric:
att = new Attribute(Integer.toString(i),i);
break;
case Discrete:
List<String> values = new ArrayList<>();
int numOfDiscreteValues = ((DiscreteColumn)currentColumn.getColumn()).getNumOfPossibleValues();
//if the number of distinct values exceeds the maximal amount, skip it
if (numOfDiscreteValues > this.maxNumOFDiscreteValuesForInstancesObject) {
break;
}
for (int j=0; j<numOfDiscreteValues; j++) { values.add(Integer.toString(j)); }
att = new Attribute(Integer.toString(i), values, i);
break;
case String:
//Most classifiers can't handle Strings. Currently we don't include them in the dataset
break;
case Date:
//Currently we don't include them in the dataset. We don't have a way of handling "raw" dates
break;
default:
throw new Exception("unsupported column type");
}
if (att != null) {
attributes.add(att);
}
}
}
/**
* Returns the number of columns in the dataset which are either String or Date
* @return
*/
private int getNumberOfDateStringAndDistinctColumns() {
int numOfColumns = 0;
for (ColumnInfo ci : columns) {
if (ci.getColumn().getType().equals(Column.columnType.Date) || ci.getColumn().getType().equals(Column.columnType.String) ||
distinctValColumns.contains(ci)) {
numOfColumns++;
}
if (ci.getColumn().getType() == Column.columnType.Discrete && ((DiscreteColumn)ci.getColumn()).getNumOfPossibleValues() > this.maxNumOFDiscreteValuesForInstancesObject) {
numOfColumns++;
}
}
return numOfColumns;
}
/**
* In cases where the target class is not the last attribute, we need to determine its new index.
* @return
*/
private int getNumberOfDateStringAndDistinctColumnsBeforeTargetClass() {
int numOfColumns = 0;
for (ColumnInfo ci : columns) {
if (ci == columns.get(targetColumnIndex)) {
return numOfColumns;
}
if (ci.getColumn().getType().equals(Column.columnType.Date) || ci.getColumn().getType().equals(Column.columnType.String) ||
distinctValColumns.contains(ci)) {
numOfColumns++;
}
if (ci.getColumn().getType() == Column.columnType.Discrete && ((DiscreteColumn)ci.getColumn()).getNumOfPossibleValues() > this.maxNumOFDiscreteValuesForInstancesObject) {
numOfColumns++;
}
}
return numOfColumns;
}
/**
* Returns a two-dimensional, Weka-friendly array. The array contains only the lines whose indices
* were provided
* @param indicesList
* @return
*/
public double[][] getDataMatrixByIndices(List<Integer> indicesList) {
//we distinct val column(s) is not included in the matrix
double[][] data = new double[columns.size() - (this.distinctValColumns.size() + getNumberOfDateStringAndDistinctColumns())][indicesList.size()];
int skippedColumnsCounter = 0;
for (int col = 0; col < columns.size(); col++) {
//if this is a distinct val column or if the column is a raw string
if ( shouldColumnBeExludedFromDataMatrix(col)) {
skippedColumnsCounter++;
continue;
}
int rowCounter = 0;
boolean isNumericColumn = columns.get(col).getColumn().getType().equals(Column.columnType.Numeric);
for (int row : indicesList) {
if (isNumericColumn) {
data[col-skippedColumnsCounter][rowCounter] = (Double) columns.get(col).getColumn().getValue(row); }
else {
data[col-skippedColumnsCounter][rowCounter] = (Integer) columns.get(col).getColumn().getValue(row);
}
rowCounter++;
}
}
return data;
}
/**
* Used to return the target class values for a list of intances.
* @param instanceIndices
* @return
*/
public HashMap<Integer,Integer> getInstancesClassByIndex(List<Integer> instanceIndices) {
DiscreteColumn targetColumn = (DiscreteColumn)getTargetClassColumn().getColumn();
HashMap<Integer,Integer> mapToReturn = new HashMap<>();
for (int index : instanceIndices) {
mapToReturn.put(index, (Integer)targetColumn.getValue(index));
}
return mapToReturn;
}
/**
* Returns the training set instances in a Weka-friendly, two-dimentsional array format
* @return
*/
public double[][] getTrainingDataMatrix(List<Integer> indices) throws Exception {
if (trainFoldDistinctValMappings != null && trainFoldDistinctValMappings.size() > 0) {
throw new Exception("need to address this scenario");
}
List<Integer> indicesToRunOn;
if (indices != null) {
indicesToRunOn = indices;
}
else {
indicesToRunOn = indicesOfTrainingFolds;
}
double[][] data = new double[columns.size()][indicesToRunOn.size()];
int skippedColumnsCounter = 0;
for (int col = 0; col < columns.size(); col++) {
//if this is a distinct val column or if the column is a raw string
if ( shouldColumnBeExludedFromDataMatrix(col)) {
skippedColumnsCounter++;
continue;
}
int rowCounter = 0;
boolean isNumericColumn = columns.get(col).getColumn().getType().equals(Column.columnType.Numeric);
for (int row : indicesToRunOn) {
if (isNumericColumn) {
data[col-skippedColumnsCounter][rowCounter] = (Double) columns.get(col).getColumn().getValue(row); }
else {
data[col-skippedColumnsCounter][rowCounter] = (Integer) columns.get(col).getColumn().getValue(row);
}
rowCounter++;
}
}
return data;
}
/**
* Returns the training set instances in a Weka-friendly, two-dimentsional array format
* @return
*/
public double[][] getValidationDataMatrix(List<Integer> indices) throws Exception {
if (trainFoldDistinctValMappings != null && trainFoldDistinctValMappings.size() > 0)
return getValidationDataMatrixWithDistinctVals();
List<Integer> indicesToRunOn;
if (indices != null) {
indicesToRunOn = indices;
}
else {
indicesToRunOn = indicesOfValidationFolds;
}
double[][] data = new double[columns.size() - (getNumberOfDateStringAndDistinctColumns())][indicesToRunOn.size()];
int skippedColumnsCounter = 0;
for (int col = 0; col < columns.size(); col++) {
//if this is a distinct val column or if the column is a raw string
if ( shouldColumnBeExludedFromDataMatrix(col)) {
skippedColumnsCounter++;
continue;
}
int rowCounter = 0;
boolean isNumericColumn = columns.get(col).getColumn().getType().equals(Column.columnType.Numeric);
for (int row : indicesToRunOn) {
if (isNumericColumn) {
data[col-skippedColumnsCounter][rowCounter] = (Double) columns.get(col).getColumn().getValue(row); }
else {
data[col-skippedColumnsCounter][rowCounter] = (Integer) columns.get(col).getColumn().getValue(row);
}
rowCounter++;
}
}
return data;
}
/**
* Returns the test set instances in a Weka-friendly, two-dimentsional array format
* @return
*/
public double[][] getTestDataMatrix(List<Integer> indices) {
if (testFoldDistinctValMappings != null && testFoldDistinctValMappings.size() > 0)
return getTestDataMatrixWithDistinctVals();
List<Integer> indicesToRunOn;
if (indices != null) {
indicesToRunOn = indices;
}
else {
indicesToRunOn = indicesOfTestFolds;
}
double[][] data = new double[columns.size() - (getNumberOfDateStringAndDistinctColumns())][indicesToRunOn.size()];
int skippedColumnsCounter = 0;
for (int col = 0; col < columns.size(); col++) {
if ( shouldColumnBeExludedFromDataMatrix(col)) {
skippedColumnsCounter++;
continue;
}
int rowCounter = 0;
boolean isNumericColumn = columns.get(col).getColumn().getType().equals(Column.columnType.Numeric);
for (int row : indicesToRunOn) {
if (isNumericColumn) {
data[col-skippedColumnsCounter][rowCounter] = (Double) columns.get(col).getColumn().getValue(row);
}
else {
data[col-skippedColumnsCounter][rowCounter] = (Integer) columns.get(col).getColumn().getValue(row);
}
rowCounter++;
}
}
return data;
}
/**
* Identical to the getTrainingDataMatrix function, but returns a matrix containing a single index for
* each distinct value combination
* @return
*/
public double[][] getTrainingDataMatrixWithDistinctVals() {
double[][] data = new double[columns.size() - (getNumberOfDateStringAndDistinctColumns())][trainFoldDistinctValMappings.size()];
int skippedColumnsCounter = 0;
for (int col = 0; col < columns.size(); col++) {
//if this is a distinct val column or if the column is a raw string
if ( shouldColumnBeExludedFromDataMatrix(col)) {
skippedColumnsCounter++;
continue;
}
int rowCounter = 0;
boolean isNumericColumn = columns.get(col).getColumn().getType().equals(Column.columnType.Numeric);
for (List<String> key : trainFoldDistinctValMappings.keySet()) {
//now we take a single representative from this group
int index = trainFoldDistinctValMappings.get(key).get(0);
if (isNumericColumn) {
data[col-skippedColumnsCounter][rowCounter] = (Double) columns.get(col).getColumn().getValue(index); }
else {
data[col-skippedColumnsCounter][rowCounter] = (Integer) columns.get(col).getColumn().getValue(index);
}
rowCounter++;
}
}
return data;
}
/**
* Returns the distinct value mappings of each instance in the training set (for each instance, we get
* a list of all the instances with the same distinct value)
* @return
*/
public HashMap<List<String>, List<Integer>> getTrainFoldDistinctValMappings() { return trainFoldDistinctValMappings; }
/**
* Returns the distinct value mappings of each instance in the test set (for each instance, we get
* a list of all the instances with the same distinct value)
* @return
*/
public HashMap<List<String>, List<Integer>> getTestFoldDistinctValMappings() {
return testFoldDistinctValMappings;
}
private boolean shouldColumnBeExludedFromDataMatrix(int columnIndex) {
if (this.distinctValColumns.contains(columns.get(columnIndex)))
return true;
if (columns.get(columnIndex).getColumn().getType().equals(Column.columnType.String))
return true;
if (columns.get(columnIndex).getColumn().getType().equals(Column.columnType.Date))
return true;
if ((columns.get(columnIndex).getColumn().getType().equals(Column.columnType.Discrete) &&
((DiscreteColumn)columns.get(columnIndex).getColumn()).getNumOfPossibleValues() > this.maxNumOFDiscreteValuesForInstancesObject))
return true;
return false;
}
public double[][] getValidationDataMatrixWithDistinctVals() throws Exception{
throw new NotImplementedException();
}
/**
* * Identical to the getTrainingDataMatrix function, but returns a matrix containing a single index for
* each distinct value combination
* @return
*/
public double[][] getTestDataMatrixWithDistinctVals() {
double[][] data = new double[columns.size() - (getNumberOfDateStringAndDistinctColumns())][testFoldDistinctValMappings.size()];
int skippedColumnsCounter = 0;
for (int col = 0; col < columns.size(); col++) {
if ( shouldColumnBeExludedFromDataMatrix(col)) {
skippedColumnsCounter++;
continue;
}
int rowCounter = 0;
boolean isNumericColumn = columns.get(col).getColumn().getType().equals(Column.columnType.Numeric);
for (List<String> key : testFoldDistinctValMappings.keySet()) {
//now we take a single representative from this group
int index = testFoldDistinctValMappings.get(key).get(0);
if (isNumericColumn) {
data[col-skippedColumnsCounter][rowCounter] = (Double) columns.get(col).getColumn().getValue(index); }
else {
data[col-skippedColumnsCounter][rowCounter] = (Integer) columns.get(col).getColumn().getValue(index);
}
rowCounter++;
}
}
return data;
}
/**
* Partitions the training folds into a set of LOO folds. One of the training folds is designated as "test",
* while the remaining folds are used for training. All possible combinations are returned.
* @return
*/
public List<Dataset> GenerateTrainingSetSubFolds() throws Exception {
//first, get all the training folds in the current dataset
List<Fold> trainingFolds = new ArrayList<>();
for (Fold fold: folds) {
if (!fold.isTestFold()) {
trainingFolds.add(fold);
}
}
List<Dataset> trainingDatasets = new ArrayList<>();
for (int i=0; i<trainingFolds.size(); i++) {
List<Fold> newFoldsList = new ArrayList<>();
for (int j=0; j<trainingFolds.size(); j++) {
Fold currentFold = trainingFolds.get(j);
//if i==j, then this is the test fold
Fold newFold = new Fold(getNumOfClasses(),(i==j) ? FoldsInfo.foldType.Test : FoldsInfo.foldType.Train);
newFold.setIndices(currentFold.getIndices());
newFold.setNumOfInstancesInFold(currentFold.getNumOfInstancesInFold());
newFold.setInstancesClassDistribution(currentFold.getInstancesClassDistribution());
newFold.setIndicesPerClass(currentFold.getIndicesPerClass());
newFold.setDistinctValMappings(currentFold.getDistinctValMappings());
newFoldsList.add(newFold);
}
//now that we have the folds, we can generate the Dataset object
Dataset subDataset = new Dataset(this.columns, newFoldsList,this.targetColumnIndex, this.name, this.numOfInstancesPerColumn, this.distinctValColumns, this.randomSeed, this.maxNumOFDiscreteValuesForInstancesObject);
trainingDatasets.add(subDataset);
}
return trainingDatasets;
}
/**
* Determines whether the values of the a column adhere to the distinct value requirements.
* These columns will be used fot the initial candiate features generation
* @param ci
* @return
*/
private boolean isColumnDistinctValuesCompatibe(ColumnInfo ci) throws Exception {
if (ci.isTargetClass() || distinctValColumns.contains(ci) ||
ci.getColumn().getType().equals(Column.columnType.Date) || ci.getColumn().getType().equals(Column.columnType.String)) {
return false;
}
try {
HashMap<Object, Object> distinctValsDict = new HashMap<>();
HashMap<Object, Object> valuesMap = new HashMap<>();
for (int i = 0; i < indices.size(); i++) {
int j = indices.get(i);
List<Object> sourceValues = distinctValColumns.stream().map(c -> c.getColumn().getValue(j)).collect(Collectors.toList());
if (!distinctValsDict.containsKey(sourceValues)) {
distinctValsDict.put(sourceValues, ci.getColumn().getValue(j));
} else {
if (!distinctValsDict.get(sourceValues).equals(ci.getColumn().getValue(j))) {
return false;
}
}
}
}
catch (Exception ex) {
throw new Exception("Error in isColumnDistinctValuesCompatibe");
}
return true;
}
/**
* Generates a new Dataset object which points to a subset of the columns in the original dataset. The
* target class attribute is always added (if only the target class is returned then this function becomes
* the equivalent of emptyReplica()
* @param indices
* @return
*/
public Dataset replicateDatasetByColumnIndices(List<Integer> indices) {
Dataset dataset = new Dataset();
//We need to create a new columns object and just reference the same objects
dataset.columns = new ArrayList<>();
Collections.sort(indices);
for (int index : indices) {
dataset.columns.add(columns.get(index));
}
if (!dataset.columns.contains(getTargetClassColumn())) {
dataset.addColumn(getTargetClassColumn());
}
dataset.targetColumnIndex = dataset.columns.size()-1;
dataset.numOfInstancesPerColumn = this.numOfInstancesPerColumn;
dataset.indices = this.indices;
dataset.folds = this.folds;
dataset.indicesOfTrainingFolds = this.indicesOfTrainingFolds;
dataset.indicesOfValidationFolds = this.indicesOfValidationFolds;
dataset.indicesOfTestFolds = this.indicesOfTestFolds;
dataset.numOfTrainingInstancesPerClass = this.numOfTrainingInstancesPerClass;
dataset.numOfValidationInstancesPerClass = this.numOfValidationInstancesPerClass;
dataset.numOfTestInstancesPerClass = this.numOfTestInstancesPerClass;
dataset.numOfTrainingRows = this.numOfTrainingRows;
dataset.numOfValidationRows = this.numOfValidationRows;
dataset.numOfTestRows = this.numOfTestRows;
dataset.name = this.name;
dataset.distinctValColumns = this.distinctValColumns;
dataset.trainingIndicesByClass = this.trainingIndicesByClass;
dataset.trainFoldDistinctValMappings = this.trainFoldDistinctValMappings;
dataset.validationIndicesByClass = this.validationIndicesByClass;
dataset.validationFoldDistinctValMappings = this.validationFoldDistinctValMappings;
dataset.testFoldDistinctValMappings = this.testFoldDistinctValMappings;
dataset.trainFoldsDistinctValRepresentatives = this.trainFoldsDistinctValRepresentatives;
dataset.testFoldsDistinctValRepresentatives = this.testFoldsDistinctValRepresentatives;
dataset.distinctValueCompliantColumns = this.distinctValueCompliantColumns;
dataset.maxNumOFDiscreteValuesForInstancesObject = this.maxNumOFDiscreteValuesForInstancesObject;
return dataset;
}
/**
* Creates an exact replica of the dataset, except for the fact that it creates a new List of columns
* instead of referencing to the existing list. This enables the addition of columns to this object without
* adding them to the original.
* @return
*/
public Dataset replicateDataset() {
Dataset dataset = new Dataset();
//We need to create a new columns object and just reference the same objects
dataset.columns = new ArrayList<>();
for (ColumnInfo ci: this.columns) {
dataset.columns.add(ci);
}
dataset.numOfInstancesPerColumn = this.numOfInstancesPerColumn;
dataset.indices = this.indices;
dataset.folds = this.folds;
dataset.indicesOfTrainingFolds = this.indicesOfTrainingFolds;
dataset.indicesOfTestFolds = this.indicesOfTestFolds;
dataset.numOfTrainingInstancesPerClass = this.numOfTrainingInstancesPerClass;
dataset.numOfTestInstancesPerClass = this.numOfTestInstancesPerClass;
dataset.numOfTrainingRows = this.numOfTrainingRows;
dataset.numOfTestRows = this.numOfTestRows;
dataset.targetColumnIndex = this.targetColumnIndex;
dataset.name = this.name;
dataset.distinctValColumns = this.distinctValColumns;
dataset.trainingIndicesByClass = this.trainingIndicesByClass;
dataset.trainFoldDistinctValMappings = this.trainFoldDistinctValMappings;
dataset.testFoldDistinctValMappings = this.testFoldDistinctValMappings;
dataset.trainFoldsDistinctValRepresentatives = this.trainFoldsDistinctValRepresentatives;
dataset.testFoldsDistinctValRepresentatives = this.testFoldsDistinctValRepresentatives;
dataset.distinctValueCompliantColumns = this.distinctValueCompliantColumns;
dataset.maxNumOFDiscreteValuesForInstancesObject = this.maxNumOFDiscreteValuesForInstancesObject;
return dataset;
}
/**
* Creates an exact replica of the dataset, except for the fact that it creates a new List of columns
* instead of referencing to the existing list. This enables the addition of columns to this object without
* adding them to the original.
* @return
*/
public Dataset replicateDatasetDeep() {
Dataset dataset = new Dataset();
//We need to create a new columns object and just reference the same objects
dataset.columns = new ArrayList<>();
for (ColumnInfo ci: this.columns) {
dataset.columns.add(ci);
}
dataset.numOfInstancesPerColumn = this.numOfInstancesPerColumn;
dataset.indices = new ArrayList<>(this.indices);
dataset.folds = new ArrayList<>(this.folds);
dataset.indicesOfTrainingFolds = new ArrayList<>(this.indicesOfTrainingFolds);
dataset.indicesOfTestFolds = new ArrayList<>(this.indicesOfTestFolds);
dataset.numOfTrainingInstancesPerClass = new int[this.numOfTrainingInstancesPerClass.length];
System.arraycopy( this.numOfTrainingInstancesPerClass
, 0, dataset.numOfTrainingInstancesPerClass
, 0, this.numOfTrainingInstancesPerClass.length);
dataset.numOfTestInstancesPerClass = new int[this.numOfTestInstancesPerClass.length];
System.arraycopy( this.numOfTestInstancesPerClass, 0, dataset.numOfTestInstancesPerClass
, 0, this.numOfTestInstancesPerClass.length );
dataset.numOfTrainingRows = this.numOfTrainingRows;
dataset.numOfTestRows = this.numOfTestRows;
dataset.targetColumnIndex = this.targetColumnIndex;
dataset.name = this.name;
dataset.distinctValColumns = new ArrayList<>(this.distinctValColumns);
dataset.trainingIndicesByClass = new List[this.trainingIndicesByClass.length];
System.arraycopy( this.trainingIndicesByClass, 0, dataset.trainingIndicesByClass
, 0, this.trainingIndicesByClass.length );
dataset.trainFoldDistinctValMappings = new HashMap<>(this.trainFoldDistinctValMappings);
dataset.testFoldDistinctValMappings = new HashMap<>(this.testFoldDistinctValMappings);
dataset.trainFoldsDistinctValRepresentatives = new ArrayList<>(this.trainFoldsDistinctValRepresentatives);
dataset.testFoldsDistinctValRepresentatives = new ArrayList<>(this.testFoldsDistinctValRepresentatives);
dataset.distinctValueCompliantColumns = new ArrayList<>(this.distinctValueCompliantColumns);
dataset.maxNumOFDiscreteValuesForInstancesObject = this.maxNumOFDiscreteValuesForInstancesObject;
return dataset;
}
public Dataset generateRandomSubDataSet(int numOfInstancesPerFold, int randomSeed) throws Exception {
List<Fold> newFoldsList = new ArrayList<>();
//operatorAssignments.parallelStream().forEach(oa -> {
folds.parallelStream().forEach(fold -> {
//for (Fold fold: this.folds) {
Fold subFold = fold.generateSubFold(numOfInstancesPerFold, randomSeed);
newFoldsList.add(subFold);
});
Dataset dataset = new Dataset(this.columns,newFoldsList,this.targetColumnIndex,this.name+"_subfold",this.numOfInstancesPerColumn,this.distinctValColumns,randomSeed,this.maxNumOFDiscreteValuesForInstancesObject);
return dataset;
}
/**
* Creates a replica of the given Dataset object, but without any columns except for the target column and the
* distinct value columns (if they exist)
* @return
*/
public Dataset emptyReplica() {
Dataset dataset = new Dataset();
//We need to create a new columns object and just reference the same objects
dataset.columns = new ArrayList<>();
dataset.numOfInstancesPerColumn = this.numOfInstancesPerColumn;
dataset.indices = this.indices;
dataset.indicesOfTrainingFolds = this.indicesOfTrainingFolds;
dataset.indicesOfTestFolds = this.indicesOfTestFolds;
dataset.numOfTrainingInstancesPerClass = this.numOfTrainingInstancesPerClass;
dataset.numOfTestInstancesPerClass = this.numOfTestInstancesPerClass;
dataset.numOfTrainingRows = this.numOfTrainingRows;
dataset.numOfTestRows = this.numOfTestRows;
dataset.name = this.name;
dataset.distinctValColumns = this.distinctValColumns;
dataset.trainingIndicesByClass = this.trainingIndicesByClass;
dataset.trainFoldDistinctValMappings = this.trainFoldDistinctValMappings;
dataset.testFoldDistinctValMappings = this.testFoldDistinctValMappings;
dataset.trainFoldsDistinctValRepresentatives = this.trainFoldsDistinctValRepresentatives;
dataset.testFoldsDistinctValRepresentatives = this.testFoldsDistinctValRepresentatives;
dataset.distinctValueCompliantColumns = this.distinctValueCompliantColumns;
dataset.maxNumOFDiscreteValuesForInstancesObject = this.maxNumOFDiscreteValuesForInstancesObject;
//since we only add the target column, it's index in 0
dataset.targetColumnIndex = 0;
dataset.columns.add(this.columns.get(this.targetColumnIndex));
//add the distinct value columns to the empty dataset
for (ColumnInfo ci: distinctValColumns) {
dataset.columns.add(ci);
}
return dataset;
}
/**
* Returns a single indice for each distinct values combination in the training folds
* @return
*/
public List<Integer> getTrainFoldsDistinctValRepresentatives() {
return trainFoldsDistinctValRepresentatives;
}
/**
* Returns a single indice for each distinct values combination in the test folds
* @return
*/
public List<Integer> getTestFoldsDistinctValRepresentatives() {
return testFoldsDistinctValRepresentatives;
}
/**
* Returns the list of columns whose values satisfy the constraint of the distinct value
* @return
*/
public List<ColumnInfo> getDistinctValueCompliantColumns() {
return distinctValueCompliantColumns;
}
public List<Fold> getTrainingFolds() {
List<Fold> listToReturn = new ArrayList<>();
for (Fold fold : folds) {
if (fold.getTypeOfFold() == FoldsInfo.foldType.Train) {
listToReturn.add(fold);
}
}
return listToReturn;
}
public List<Fold> getValidationFolds() {
List<Fold> listToReturn = new ArrayList<>();
for (Fold fold : folds) {
if (fold.getTypeOfFold() == FoldsInfo.foldType.Validation) {
listToReturn.add(fold);
}
}
return listToReturn;
}
public List<Fold> getTestFolds() {
List<Fold> listToReturn = new ArrayList<>();
for (Fold fold : folds) {
if (fold.getTypeOfFold() == FoldsInfo.foldType.Test) {
listToReturn.add(fold);
}
}
return listToReturn;
}
/**
* returns a map with the ratio of each class in the dataset (can be calculated on the training instances or on
* all of the indices)
*
* @return
*/
public HashMap<Integer,Double> getClassRatios(boolean useAllIndices) {
/*
numOfTrainingInstancesPerClass;
numOfValidationInstancesPerClass;
numOfTestInstancesPerClass;
*/
HashMap<Integer, Double> totalNumberOfInstancesPerClass = new HashMap<>();
if (useAllIndices) {
for (int classIndex = 0; classIndex < getNumOfClasses(); classIndex++) {
if (numOfValidationInstancesPerClass != null) {
totalNumberOfInstancesPerClass.put(classIndex, (double) numOfTrainingInstancesPerClass[classIndex] +
numOfValidationInstancesPerClass[classIndex] + numOfTestInstancesPerClass[classIndex]);
}
else {
totalNumberOfInstancesPerClass.put(classIndex, (double) numOfTrainingInstancesPerClass[classIndex] +
numOfTestInstancesPerClass[classIndex]);
}
}
}
else {
for (int classIndex = 0; classIndex < getNumOfClasses(); classIndex++) {
totalNumberOfInstancesPerClass.put(classIndex, (double) numOfTrainingInstancesPerClass[classIndex]);
}
}
HashMap<Integer,Double> mapToReturn = new HashMap<>();
for (int classIndex = 0; classIndex<getNumOfClasses(); classIndex++) {
mapToReturn.put(classIndex, totalNumberOfInstancesPerClass.get(classIndex)/totalNumberOfInstancesPerClass.values().stream().mapToInt(Number::intValue).sum());
}
return mapToReturn;
}
/**
* Updates the class attribute values of the instances whose indices are provided to the one that is provided to the function (to be used in experimental settings such as co-training).
* @param instanceIndices
* @param newTargetClassValue
*/
public void updateInstanceTargetClassValue(List<Integer> instanceIndices, int newTargetClassValue) {
for (int index: instanceIndices) {
getTargetClassColumn().getColumn().setValue(index, newTargetClassValue);
}
}
/**
* Returns a (sorted by index) array of target class values, based on the provided indices
* @param indices
* @return
*/
public int[] getTargetClassLabelsByIndex(List<Integer> indices) {
int[] arrayToReturn = new int[indices.size()];
DiscreteColumn targetClassColumn = (DiscreteColumn)getTargetClassColumn().getColumn();
Collections.sort(indices);
for (int i=0; i<indices.size(); i++) {
// arrayToReturn[i] = ((int)targetClassColumn.getValue(i));
arrayToReturn[i] = ((int)targetClassColumn.getValue(indices.get(i)));
}
return arrayToReturn;
}
/**
* Receives an Instances object and writes it into an ARFF file (can be used as a convenient work around for
* replication and creating subsets of the data).
* @param instances
* @param path
* @return
* @throws Exception
*/
public boolean saveInstancesToARFFFile(Instances instances, String path) throws Exception {
try {
ArffSaver s = new ArffSaver();
s.setInstances(instances);
s.setFile(new File(path));
s.writeBatch();
return true;
}
catch (Exception ex) {
System.out.println("Error writing instances to ARFF file. Exception: " + ex.getMessage());
return false;
}
}
/**
* Returns the index of the class attribute
* @return
*/
public int getTargetColumnIndex() {
return targetColumnIndex;
}
}
|
package com.zhongyp.test;
import com.zhongyp.advanced.classloading.InitClass;
import java.util.Comparator;
/**
* @author zhongyp.
* @date 2019/7/25
*/
public class Test {
// static int java.lang.a = 1;
// int b = 2;
//
// public Test (){
// System.out.println("构造" + java.lang.a + b);
// }
// {
// System.out.println("普通方法块" + java.lang.a + b);
// }
// static {
// System.out.println("静态方法块" + java.lang.a);
// Test test = new Test();
// System.out.println(test.b);
// Arrays.asList();
// }
// public static void get(int i){
// List list = new ArrayList();
//
// }
//
// public static void get(Integer i){
// List list = new ArrayList();
//
// }
// String java.lang.a = "b";
//
// int b = 1;
//
// Integer c = 2;
// String java.lang.a = new String("abc");
// String b = new String("abc");
// String c = "abc";
// String d = new String("abc");
public static void main(String[] args) {
new Thread(){
@Override
public void run() {
InitClass initClass = new InitClass();
}
}.start();
new Thread(){
@Override
public void run() {
InitClass initClass = new InitClass();
}
}.start();
// try {
// throw new RuntimeException("呵呵");
//
// }catch (Exception e){
// e.printStackTrace();
// System.out.println(String.valueOf(e.getStackTrace()));
// }
// // 字符串
// String str = "str";
//
// System.out.println(str);
//
// // 基本类型
// int i = 1;
//
// // 基本类型数组
// int[] arrayI = new int[3];
//
// // 引用类型数组
// A [] arrayA = new A[3];
//
// // 引用类型
// A a = new A();
//
// // 引用方法
// a.test();
//
// // 接口声明
// C c = new B();
//
// // 接口方法
// c.test();
//
// // lambda
// Runnable x = ()->{};
// A a = new A();
// B b = (B) a;
// Object obj = "something";
// long start = System.currentTimeMillis();
// for (int i = 0; i < 1000000000; i++) {
// String a = (String)obj;
// }
// System.out.println(System.currentTimeMillis()-start);
// ClassStructureDemo classStructureDemo = new ClassStructureDemo();
// String str1 = new StringBuilder("计算机").append("软件").toString();
// System.out.println(str1.intern() == str1);
//
// String str2 = new StringBuilder("ja").append("va").toString();
// System.out.println(str2.intern() == str2);
// Test test = new Test();
// test.java.lang.a.intern();
// System.out.println(test.java.lang.a==test.b);
// System.out.println(test.java.lang.a==test.c);
// test.d.intern();
// System.out.println(test.java.lang.a==test.d);
// JavaBean javaBean = new JavaBean();
// Integer i = new Integer(3);
// get(i);
// get(3);
// ReentrantLock reentrantLock;
//
// new HashMap();
// List<String> list = new ArrayList<>(10);
// System.out.println(list.size());
// list.add(null);
// list.add(null);
// System.out.println(list.size());
// System.out.println(list.get(0));
// list.add("1");
// list.add("2");
// Iterator iterator = list.iterator();
// HashMap map = new HashMap();
// map.put("abcdkd", "ddad8");
// map.put("abcdkd3", "ddad6");
// map.put("abcdkd2", "ddad7");
// map.put("abcdkd1", "ddad9");
// map.put("abcdkd5", "ddad1");
// List<String> list = new ArrayList<>(map.values());
// Collections.sort(list, new MyComparator());
// for(String key:list){
// System.out.println(key);
// }
// int i=0;
// if(i==0){
// i=1;
// }else if(i==1){
// System.out.println("good");
// }else{
// System.out.println("bad");
// }
//
// while (iterator.hasNext()){
// String item = (String) iterator.next();
// if("1".equals(item)){
// iterator.remove();
// }
// }
// for(String it:list){
// if("1".equals(it)){
// list.remove(it);
// }
// }
// StringBuffer sql = new StringBuffer();
// sql.append(" select distinct d.chr_code1 vtcode, d.chr_name addr, c.chr_code stamp ");
// sql.append(" from epay_conf_addr_action java.lang.a, ");
// sql.append(" epay_conf_addr_stamp b, ");
// sql.append(" epay_stamp c, ");
// sql.append(" epay_billtypeaddr d ");
// sql.append(" where java.lang.a.action_id = ? ");
// sql.append(" and d.chr_code1 = ? ");
// sql.append(" and java.lang.a.addr_id = b.addr_id ");
// sql.append(" and b.stamp_id = c.chr_id ");
// sql.append(" and java.lang.a.addr_id = d.chr_id ");
// sql.append(" and java.lang.a.rg_code = b.rg_code " +
// " and java.lang.a.rg_code = c.rg_code " +
// " and java.lang.a.rg_code = d.rg_code " +
// " and java.lang.a.set_year = b.set_year " +
// " and java.lang.a.set_year = c.set_year " +
// " and java.lang.a.set_year = d.set_year ");
// sql.append(" and java.lang.a.rg_code = ? and java.lang.a.set_year = ? ");
// sql.append(" and exists (select 1 from epay_conf_stamp_user e ");
// sql.append(" where c.chr_id = e.stamp_id and e.user_id = ? and e.rg_code = ? and e.set_year = ? ) ");
// sql.append(" and exists (select 1 from epay_conf_sn_stamp f,epay_sn g ");
// sql.append(" where c.chr_id = f.stamp_id and g.chr_id = f.sn_id and f.rg_code = g.rg_code and f.set_year = g.set_year and f.rg_code = ? and f.set_year = ? and g.chr_code = ? ) ");
//
// System.out.println(sql.toString());
}
}
class MyComparator implements Comparator<String> {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
}
class A{
String d = "abc";
public void test(){}
}
class B implements C{
@Override
public void test(){}
}
interface C{
void test();
}
|
package com.git.cloud.cloudservice.dao.impl;
import java.util.Date;
import java.util.List;
import com.git.cloud.common.dao.CommonDAOImpl;
import com.git.cloud.common.exception.RollbackableBizException;
import com.git.cloud.common.model.IsActiveEnum;
import com.git.cloud.foundation.util.UUIDGenerator;
import com.git.cloud.cloudservice.dao.IModelDao;
import com.git.cloud.cloudservice.model.po.CloudImageSoftWareRef;
import com.git.cloud.cloudservice.model.po.ModelModel;
import com.git.cloud.cloudservice.model.po.PackageModel;
import com.git.cloud.cloudservice.model.vo.ModelModelVO;
import com.git.cloud.cloudservice.model.vo.PackageModelVO;
import com.git.cloud.cloudservice.model.vo.ScriptModelVO;
import com.sun.xml.xsom.impl.scd.Iterators.Map;
/**
* 脚本模块管理
* @ClassName: ModelDaoImpl
* @Description:TODO
* @author caohaihong
* @date 2014-11-27 下午3:47:17
*/
public class ModelDaoImpl extends CommonDAOImpl implements IModelDao {
@Override
public ModelModelVO load(String id) throws RollbackableBizException{
List<ModelModel> list =super.findByID("model.load", id);// (List<ModelModel>)findByID("model.load", id);
ModelModelVO target = new ModelModelVO();
if (list != null && list.size() > 0) {
for (ModelModel source : list) {
this.toModelModelVO(source, target);
}
}
return target;
}
@Override
public void delete(String id) throws RollbackableBizException {
/*super.deleteForIsActive("model.delete01", id);
super.deleteForIsActive("model.delete02", id);*/
super.deleteForIsActive("model.delete0", id);
// this.getSqlMapClientTemplate().update("model.delete0", id);
// this.getSqlMapClientTemplate().delete("model.delete1", id);
// this.getSqlMapClientTemplate().delete("model.delete2", id);
// this.getSqlMapClientTemplate().delete("model.delete", id);
}
@Override
public ModelModelVO save(ModelModelVO modelModelVO) throws RollbackableBizException {
ModelModelVO ret = null;
ModelModel m = new ModelModel();
if (modelModelVO.getId() == null || "".equals(modelModelVO.getId())) {
this.modelModelVOToEntity(modelModelVO, m, true);
m.setId(UUIDGenerator.getUUID());
m.setCreateDateTime(new Date());
m.setIsActive(IsActiveEnum.YES.getValue());
super.save("model.insert", m);
// this.getSqlMapClientTemplate().insert("model.insert", m);
} else {
this.modelModelVOToEntity(modelModelVO, m, true);
m.setId(modelModelVO.getId());
m.setUpdateDateTime(new Date());
super.save("model.update", m);
// this.getSqlMapClientTemplate().update("model.update", m);
}
ret = this.load(m.getId());
return ret;
}
@Override
public Map search(Map map) {
return null;
}
public void toModelModelVO(ModelModel source, ModelModelVO target) {
target.setName(source.getName());
target.setRemark(source.getRemark());
target.setFilePath(source.getFilePath());
target.setId(source.getId());
if (source.getPackageModel() != null) {
PackageModelVO p = new PackageModelVO();
p.setId(source.getPackageModel().getId());
target.setPackageModelVO(p);
}
}
public void modelModelVOToEntity(ModelModelVO source, ModelModel target, boolean copyIfNull) {
if (copyIfNull || source.getName() != null) {
target.setName(source.getName());
}
if (copyIfNull || source.getRemark() != null) {
target.setRemark(source.getRemark());
}
if (copyIfNull || source.getFilePath() != null) {
target.setFilePath(source.getFilePath());
}
if (copyIfNull || source.getPackageModelVO() != null) {
PackageModel p = new PackageModel();
p.setId(source.getPackageModelVO().getId());
target.setPackageModel(p);
}
}
/* (non-Javadoc)
* <p>Title:saveCloudImageSoftWareRef</p>
* <p>Description:</p>
* @param imageSoftWareRef
* @throws RollbackableBizException
* @see com.git.cloud.cloudservice.dao.IModelDao#saveCloudImageSoftWareRef(com.git.cloud.cloudservice.model.po.CloudImageSoftWareRef)
*/
@Override
public void saveCloudImageSoftWareRef(CloudImageSoftWareRef imageSoftWareRef)
throws RollbackableBizException {
// TODO Auto-generated method stub
}
//检查模板下面有没有脚本
@Override
public List<ScriptModelVO> findByModelId(String id)
throws RollbackableBizException {
// TODO Auto-generated method stub
List<ScriptModelVO> list =super.findByID("model.id", id);
return list;
}
}
|
package com.gxjtkyy.standardcloud.common.domain.dto;
import com.gxjtkyy.standardcloud.common.utils.MapUtil;
import lombok.ToString;
import java.io.Serializable;
/**
* 分页查询条件
* Created by ydlx on 2017/7/25.
*/
@ToString
public class CondictionDTO implements Serializable{
/**mysql分页开始行数*/
private int start;
/**mysql分页大小*/
private int pageSize = 100;
/**查询条件*/
private Object dto;
public int getStart() {
return start;
}
public CondictionDTO setStart(int start) {
this.start = start;
return this;
}
public int getPageSize() {
return pageSize;
}
public CondictionDTO setPageSize(int pageSize) {
this.pageSize = pageSize;
return this;
}
public Object getDto() {
return dto;
}
public CondictionDTO setDto(Object dto) {
this.dto = MapUtil.convertBeanToMap(dto);
return this;
}
}
|
package palamarchuk.bcalendargroups.adapters;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import palamarchuk.bcalendargroups.R;
public class EventMembersAdapter extends ArrayAdapter<Object> implements Filterable {
private Context context;
private ArrayList<Object> displayedItems;
private ArrayList<Object> originalItems;
private int resource;
public EventMembersAdapter(Context context, int resource) {
super(context, 0);
this.context = context;
this.resource = resource;
displayedItems = new ArrayList<Object>();
}
public static class OneEventMember {
public String groupId;
public String id;
public String name;
public String memberNote;
public String status;
public OneEventMember(JSONObject jsonObject) throws JSONException {
this.name = jsonObject.getString("name");
this.memberNote = jsonObject.getString("notes");
this.status = jsonObject.getString("status");
}
}
@Override
public int getCount() {
return displayedItems.size();
}
@Override
public void clear() {
displayedItems.clear();
}
public void add(JSONArray jsonArray) throws JSONException {
final int length = jsonArray.length();
for (int i = 0; i < length; i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
this.add(new OneEventMember(jsonObject));
}
notifyDataSetChanged();
}
private class ViewHolder {
public TextView eventMemberName;
public TextView eventMemberNote;
public ImageView eventMemberNoteStatusImage;
}
@Override
public void add(Object object) {
displayedItems.add(object);
}
@Override
public Object getItem(int position) {
return displayedItems.get(position);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final OneEventMember oneEventMember = (OneEventMember) getItem(position);
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
LayoutInflater layoutInflater = (LayoutInflater) context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(resource, null);
holder.eventMemberName = (TextView) convertView.findViewById(R.id.eventMemberName);
holder.eventMemberNote = (TextView) convertView.findViewById(R.id.eventMemberNote);
holder.eventMemberNoteStatusImage = (ImageView) convertView.findViewById(R.id.eventMemberNoteStatusImage);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.eventMemberName.setText(oneEventMember.name);
holder.eventMemberNote.setText(oneEventMember.memberNote);
if (oneEventMember.status.equalsIgnoreCase("0")) {
holder.eventMemberNoteStatusImage.setImageResource(R.drawable.no_complete);
} else {
holder.eventMemberNoteStatusImage.setImageResource(R.drawable.complete);
}
convertView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
return convertView;
}
@Override
public Filter getFilter() {
Filter filter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
ArrayList<Object> filteredCollection = new ArrayList<Object>();
if (originalItems == null) {
originalItems = new ArrayList<Object>(displayedItems);
}
if (constraint == null || constraint.length() == 0) {
filterResults.count = originalItems.size();
filterResults.values = originalItems;
} else {
constraint = constraint.toString().toLowerCase();
for (Object originalItem : originalItems) {
}
filterResults.count = filteredCollection.size();
filterResults.values = filteredCollection;
}
return filterResults;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
displayedItems = (ArrayList<Object>) results.values;
notifyDataSetChanged();
}
};
return filter;
}
}
|
package cn.hrbcu.com.servlet;
import cn.hrbcu.com.entity.User;
import cn.hrbcu.com.service.UserService;
import cn.hrbcu.com.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
/**
* @author: XuYi
* @date: 2021/5/29 21:47
* @description: 通过验证用户名重置密码
*/
@WebServlet("/FindPasswordServlet")
public class FindPasswordServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//好习惯---设置编码
request.setCharacterEncoding("utf-8");
//获取数据
Map<String, String[]> map = request.getParameterMap();
System.out.println("map="+map.size());
//封装对象
User user = new User();
try {
BeanUtils.populate(user,map);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
//调用服务方法
UserService service = new UserServiceImpl();
boolean reset = service.reset(user);
//判断结果状态
if (reset){
//存入resquest
request.setAttribute("resetMsg","<div style=\"color: orange;font-size: 20px\" >\n" +
" <span style=\"color: #117a8b;font-size: 20px\"></span> <svg t=\"1608292214189\" class=\"icon\" viewBox=\"0 0 1024 1024\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" p-id=\"7128\" width=\"25\" height=\"25\"><path d=\"M513 103.5C267.8 103.5 69 265 69 464.3 69 645.5 233.5 795 447.6 820.8v97.4s130.5-5.1 317.3-151c9.6-7.5 16.9-14 23-19.9 102.8-66.1 169-168.1 169-282.9 0.1-199.3-198.7-360.9-443.9-360.9zM295.6 398.6c0-32.6 26.4-59 59-59s59 26.4 59 59-26.4 59-59 59-59-26.4-59-59z m408.1 129.3c-41.3 69-93.2 107.8-154.4 115.4-7.5 0.9-14.9 1.4-22.3 1.4-106.5 0-198.2-90.5-202.4-94.6-6-6-6-15.7 0-21.7s15.7-6 21.7 0c1 1 98.3 96.8 199.3 84.5 51.2-6.4 95.6-40.3 131.7-100.7 4.4-7.3 13.8-9.6 21.1-5.3 7.3 4.3 9.6 13.7 5.3 21z m-32.4-70.3c-32.6 0-59-26.4-59-59s26.4-59 59-59 59 26.4 59 59-26.4 59-59 59z\" fill=\"#9E8EEF\" p-id=\"7129\"></path></svg>密码重置成功,请牢记~\n" +
"</div>");
//重定向页面
request.getRequestDispatcher("/findPwd.jsp").forward(request,response);
}else{
request.setAttribute("resetMsg","<div style=\"color: orange;font-size: 20px\" >\n" +
" <span style=\"color: #117a8b;font-size: 20px\"></span> <svg t=\"1608292214189\" class=\"icon\" viewBox=\"0 0 1024 1024\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" p-id=\"7128\" width=\"25\" height=\"25\"><path d=\"M513 103.5C267.8 103.5 69 265 69 464.3 69 645.5 233.5 795 447.6 820.8v97.4s130.5-5.1 317.3-151c9.6-7.5 16.9-14 23-19.9 102.8-66.1 169-168.1 169-282.9 0.1-199.3-198.7-360.9-443.9-360.9zM295.6 398.6c0-32.6 26.4-59 59-59s59 26.4 59 59-26.4 59-59 59-59-26.4-59-59z m408.1 129.3c-41.3 69-93.2 107.8-154.4 115.4-7.5 0.9-14.9 1.4-22.3 1.4-106.5 0-198.2-90.5-202.4-94.6-6-6-6-15.7 0-21.7s15.7-6 21.7 0c1 1 98.3 96.8 199.3 84.5 51.2-6.4 95.6-40.3 131.7-100.7 4.4-7.3 13.8-9.6 21.1-5.3 7.3 4.3 9.6 13.7 5.3 21z m-32.4-70.3c-32.6 0-59-26.4-59-59s26.4-59 59-59 59 26.4 59 59-26.4 59-59 59z\" fill=\"#9E8EEF\" p-id=\"7129\"></path></svg>用户名不存在,请检查后重试~\n" +
"</div>");
request.getRequestDispatcher("/findPwd.jsp").forward(request,response);
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
|
package cn.com.xbed.common.util;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.reflect.Method;
public class Base64Util {
private static Logger logger = LoggerFactory.getLogger(Base64Util.class);
/**
* Base64编码
*
* @param fileName 文件名
* @return
*/
public static String encodeBase64(String fileName) {
InputStream in;
byte[] data;
Object retObj = null;
try {
in = new FileInputStream(fileName);
data = new byte[in.available()];
in.read(data);
in.close();
Class<?> clazz = Class.forName("com.sun.org.apache.xerces.internal.impl.dv.util.Base64");
Method mainMethod = clazz.getMethod("encode", byte[].class);
mainMethod.setAccessible(true);
retObj = mainMethod.invoke(null, new Object[]{data});
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return retObj == null ? "" : retObj.toString();
}
/**
* 将字节流转换成Base64字符串
*
* @param bytes
* @return
*/
public static String encodeStr(byte[] bytes) {
Base64 base64 = new Base64();
bytes = base64.encode(bytes);
String str = new String(bytes);
return str;
}
public static void main(String[] args) {
String b = encodeBase64("E:\\yuan\\人脸识别\\1475045089256__769.jpg");
System.out.println(b);
}
}
|
package com.twp.baseline;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class NonExemptedFromSalesTaxImportedGoodsTest {
@Test
public void shouldReturnTenPercentOfPriceForNonExemptedGoods() {
NonExemptedFromSalesTaxImportedGoods nonExemptedFromSalesTaxImportedGoods = new NonExemptedFromSalesTaxImportedGoods("an imported Music CD", 19.89);
assertEquals(1.989, nonExemptedFromSalesTaxImportedGoods.salesTax(), 0.0001);
}
@Test
public void shouldReturnFivePercentAsImportDuty() {
NonExemptedFromSalesTaxImportedGoods nonExemptedFromSalesTaxImportedGoods = new NonExemptedFromSalesTaxImportedGoods("an imported Music CD", 19.89);
assertEquals(0.9945, nonExemptedFromSalesTaxImportedGoods.importDuty(), 0.0001);
}
}
|
package com.shangdao.phoenix.entity.companybill;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CompanyBillNoticeRepository extends JpaRepository<CompanyBillNotice, Long> {
}
|
package me.asyc.jchat.client.network;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import me.asyc.jchat.client.JChatClient;
import me.asyc.jchat.client.network.packet.factory.PacketList;
import me.asyc.jchat.client.network.pipeline.SocketChannelInitializer;
import java.net.SocketException;
public class Connection {
private final Bootstrap bootstrap;
public Connection(String ip, int port) throws SocketException {
EventLoopGroup group = new NioEventLoopGroup(1);
this.bootstrap = new Bootstrap()
.group(group)
.handler(new SocketChannelInitializer(JChatClient.INSTANCE.getCryptoManager(), PacketList.PACKET_RESOLVER));
this.bootstrap.bind(ip, port);
this.bootstrap.group(group);
if (!this.bootstrap.connect(ip, port).awaitUninterruptibly().isSuccess()) {
throw new SocketException();
}
}
}
|
package com.example.movieapp;
import android.app.Application;
import android.net.Uri;
import android.os.Bundle;
import android.widget.SearchView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.movieapp.JsonResponse;
import com.example.movieapp.JsonResultsResponse;
import com.example.movieapp.SearchListener;
import com.google.gson.Gson;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
public class SearchViewModel extends AndroidViewModel {
private String query;
private String query1;
private int page;
String url;
@NonNull
private RequestQueue queue;
public SearchViewModel(@NonNull Application application) {
super(application);
queue = Volley.newRequestQueue(application);
page=0;
url= "https://api.themoviedb.org/3/search/movie?api_key=3545652a5f9a12aa802c1fadad60d345&query=";
}
void retrieveData(String query,SearchListener search) {
page=page +1;
url = url +"&query=" + Uri.encode(query) + "&page=" + page;
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Gson gson = new Gson();
JsonResponse responseS = gson.fromJson(response,JsonResponse.class);
if(responseS.getTotal_results()==0 || responseS.getTotal_results()<0){
Toast toast = Toast.makeText(getApplication(), "No results found", Toast.LENGTH_LONG);
toast.show();
}
search.onSuccessResponse(responseS);
if(page<=responseS.getTotal_pages()){retrieveData(query,search);}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
search.onErrorResponse("That didn't work!");
}
});
queue.add(stringRequest);
}
}
|
package ru.parse.dump.objects;
/**
*
* Java array of primitives.
*
*/
public class DumpPrimitiveArray {
private final long address;
private final DumpPrimitiveType type;
private final long length;
private final int hash;
private final long size;
public DumpPrimitiveArray(long address, DumpPrimitiveType type, long length, int hash, long size) {
this.address = address;
this.type = type;
this.length = length;
this.hash = hash;
this.size = size;
}
public long getAddress() {
return address;
}
public DumpPrimitiveType getType() {
return type;
}
public long getLength() {
return length;
}
public int getHash() {
return hash;
}
public long getSize() {
return size;
}
}
|
/*
* Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE file for licensing information.
*/
package pl.edu.icm.unity.server.registries;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import pl.edu.icm.unity.types.basic.IdentityTypeDefinition;
/**
* Maintains a simple registry of available {@link IdentityTypeDefinition}s.
*
* @author K. Benedyczak
*/
@Component
public class IdentityTypesRegistry extends TypesRegistryBase<IdentityTypeDefinition>
{
private Collection<IdentityTypeDefinition> dynamic;
@Autowired
public IdentityTypesRegistry(List<IdentityTypeDefinition> typeElements)
{
super(typeElements);
dynamic = new ArrayList<IdentityTypeDefinition>();
for (IdentityTypeDefinition id: getAll())
{
if (id.isDynamic())
dynamic.add(id);
}
dynamic = Collections.unmodifiableList((List<? extends IdentityTypeDefinition>)dynamic);
}
@Override
protected String getId(IdentityTypeDefinition from)
{
return from.getId();
}
public Collection<IdentityTypeDefinition> getDynamic()
{
return dynamic;
}
}
|
package com.example.user.chendemo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class AnimationActivity extends BasicActivity {
private Animation alphaAnimation;
private Animation scaleAnimation;
private Animation rotateAnimation;
private Animation transAnimation;
private Animation setAnimation;
@BindView(R.id.animation_tv)
TextView tv;
@OnClick(R.id.animation_alpha)
public void clickAlpha(){
tv.startAnimation(alphaAnimation);
}
@OnClick(R.id.animation_rotate)
public void clickRotate(){
tv.startAnimation(rotateAnimation);
}
@OnClick(R.id.animation_scale)
public void clickScale(){
tv.startAnimation(scaleAnimation);
}
@OnClick(R.id.animation_trans)
public void clickTrans(){
tv.startAnimation(transAnimation);
}
@OnClick(R.id.animation_set)
public void clickSet(){
tv.startAnimation(setAnimation);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_animation);
ButterKnife.bind(this);
initialAnimation();
}
private void initialAnimation(){
alphaAnimation = AnimationUtils.loadAnimation(this, R.anim.anim_alpha);
scaleAnimation = AnimationUtils.loadAnimation(this,R.anim.anim_scale);
rotateAnimation = AnimationUtils.loadAnimation(this,R.anim.anim_rotate);
transAnimation = AnimationUtils.loadAnimation(this,R.anim.anim_trans);
setAnimation = AnimationUtils.loadAnimation(this,R.anim.anim_set);
}
}
|
package voc.ps.dao;
import voc.ps.model.AbstractWord;
import java.util.List;
/**
* Created by pavlo.shtefanesku on 10/20/2016.
*/
public interface MonthWordDAO {
void addWord(AbstractWord word);
void updateWord(AbstractWord weekWord);
List<AbstractWord> listWords();
AbstractWord getWordById(int id);
void deleteWord(int id);
}
|
package com.qihoo;
import com.qihoo.personal.PersonalActivity;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity
{
static final int NOTEWALLACTIVITY = 1;
static final int MYMOODACTIVITY = 2;
static final int PERSONALCENTER = 3;
MyImageView modeSquare;
MyImageView myModeWall;
MyImageView personalCenter;
ImageView goAhead;
ImageView exitActivity;
int latestActivity=1;
private long mExitTime;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.mainpanel);
goAhead = (ImageView)findViewById(R.id.btnGoAhead);
goAhead.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
createActivity(latestActivity);
}
});
modeSquare=(MyImageView) findViewById(R.id.modeSquareWall);
modeSquare.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
createActivity(NOTEWALLACTIVITY);
}
});
myModeWall=(MyImageView) findViewById(R.id.myModeWall);
myModeWall.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
createActivity(MYMOODACTIVITY);
}
});
personalCenter=(MyImageView) findViewById(R.id.personalCenter);
personalCenter.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
createActivity(PERSONALCENTER);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
latestActivity=requestCode;
super.onActivityResult(requestCode, resultCode, data);
}
private void createActivity(int activityFlag)
{
if(NOTEWALLACTIVITY==activityFlag)
{
Intent intent=new Intent(MainActivity.this,NoteWallActivity.class);
startActivityForResult(intent,NOTEWALLACTIVITY);
overridePendingTransition(R.anim.infromright,R.anim.outtoleft);
}
else if(MYMOODACTIVITY==activityFlag)
{
Intent intent=new Intent(MainActivity.this,MyMoodActivity.class);
startActivityForResult(intent,MYMOODACTIVITY);
overridePendingTransition(R.anim.infromright,R.anim.outtoleft);
}
else if(PERSONALCENTER==activityFlag)
{
Intent intent=new Intent(MainActivity.this,PersonalActivity.class);
startActivityForResult(intent,PERSONALCENTER);
overridePendingTransition(R.anim.infromright,R.anim.outtoleft);
}
}
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK)
{
if ((System.currentTimeMillis() - mExitTime) > 2000)
{
Object mHelperUtils;
Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
mExitTime = System.currentTimeMillis();
} else
{
finish();
}
return true;
}
return super.onKeyDown(keyCode, event);
}
}
|
package com.wiley.dao;
import java.util.List;
import com.wiley.model.Author;
public interface AuthorDao {
public Boolean add(Author author);
public List<Author> getAuthors();
}
|
package manager;
import scraping.Scraping;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.PrintWriter;
import java.io.Serializable;
@WebServlet(
name = "ManagerServlet",
urlPatterns = "/manageDB"
)
public class ManagerServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action=request.getParameter("action");
String url=request.getParameter("url");
String message="";
boolean dbstatus=Scraping.isRuning();
int status=0;
if(action.equals("start")){
if(url.equals("")){
message="URL input cannot be empty";
status=2;
}
else{
if(!Scraping.isRuning()){
message="Scraping is starting.";
Scraping.setStartingURL(url);
Scraping scraping=new Scraping();
scraping.start();
dbstatus=true;
status=0;
}
else{
message="Scraping is already running.";
status=1;
}
}
}
else {
if(!Scraping.isRuning()){
message="Scraping hasn't been started!";
status=1;
}
else {
message="Scraping is stopping!";
Scraping.stopScraping();
status=0;
}
}
request.setAttribute("message",message);
request.setAttribute("status",status);
//System.out.print(Scraping.isRuning());
request.setAttribute("dbstatus",dbstatus);
request.getRequestDispatcher("manager.jsp").forward(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
|
package com.midea.designmodel.factorypartern.abstractfactory;
/**
* 1. 抽象工厂角色
* 工厂方法模式的核心,创建产品的类必须实现该接口
* 2. 具体工厂角色 用来创建具体实例
* 该角色实现了抽象工厂接口,具体如何创建产品就是在该类中实现
* 3. 抽象产品角色
* 所有产品的超类,负责实现产品共性的抽象定义
* 4. 具体产品角色
* 该角色实现了抽象产品接口,负责具体不同产品的业务逻辑
*
* 接口当参数以及返回参数
* 向上转型:继承者类型对象(子) 向 被继承者类型(父) 转型(自动转型)
* 向下转型:被继承者类型对象(父) 向 继承者类型(子) 转型(强制转型)
*/
public interface AbstractFactory {
public Phone producePhone();
}
|
import Llist.List;
import java.util.Iterator;
/**
* Created by Lenovo on 17.01.2016
*/
public class Test {
public static void main(String[] args) {
List list = new List();
list.addLast(5);
list.addLast("Jak");
list.addLast('c');
list.addLast(4);
list.addLast(5.0067f);
List list2 = new List();
list2.addLast(4);
list.addLast(list2);
list.printList();
list.search(5.0067f);
/*Iterator it = list.iterator();
while(it.hasNext())
System.out.println(it.next());*/
}
}
|
package alien4cloud.model.components;
/**
* Exception happened while user would link tow incompatible PropertyDefinition
*
*/
public class IncompatiblePropertyDefinitionException extends Exception {
private static final long serialVersionUID = 1L;
public IncompatiblePropertyDefinitionException() {
super("The two PropertyDefinition are incompatible.");
}
public IncompatiblePropertyDefinitionException(String message) {
super(message);
}
public IncompatiblePropertyDefinitionException(String message, Throwable cause) {
super(message, cause);
}
}
|
/*
* Copyright 2002-2015 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.web.socket.sockjs.client;
import java.net.URI;
import org.springframework.http.HttpHeaders;
import org.springframework.web.socket.TextMessage;
/**
* A SockJS {@link Transport} that uses HTTP requests to simulate a WebSocket
* interaction. The {@code connect} method of the base {@code Transport} interface
* is used to receive messages from the server while the
* {@link #executeSendRequest} method here is used to send messages.
*
* @author Rossen Stoyanchev
* @since 4.1
*/
public interface XhrTransport extends Transport, InfoReceiver {
/**
* An {@code XhrTransport} supports both the "xhr_streaming" and "xhr" SockJS
* server transports. From a client perspective there is no implementation
* difference.
* <p>By default an {@code XhrTransport} will be used with "xhr_streaming"
* first and then with "xhr", if the streaming fails to connect. In some
* cases it may be useful to suppress streaming so that only "xhr" is used.
*/
boolean isXhrStreamingDisabled();
/**
* Execute a request to send the message to the server.
* <p>Note that as of 4.2 this method accepts a {@code headers} parameter.
* @param transportUrl the URL for sending messages.
* @param message the message to send
*/
void executeSendRequest(URI transportUrl, HttpHeaders headers, TextMessage message);
}
|
/*
* 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 hoangduc.dtos;
import java.io.Serializable;
import java.util.HashMap;
/**
*
* @author ADMIN
*/
public class ShoppingCart implements Serializable{
private String customerName;
private HashMap<Integer,ProductDTO> cart;
public ShoppingCart()
{
this.cart = new HashMap<>();
this.customerName = "Guest";
}
public ShoppingCart(String customerName)
{
this.cart = new HashMap<>();
this.customerName = customerName;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public HashMap<Integer, ProductDTO> getCart() {
return cart;
}
public void addCart(ProductDTO dto) throws Exception
{
if(this.cart.containsKey(dto.getProductid()))
{
int quantity = this.cart.get(dto.getProductid()).getProductquantity()+1;
dto.setProductquantity(quantity);
}
this.cart.put(dto.getProductid(), dto);
}
public void removeProductCart(int id) throws Exception
{
if(this.cart.containsKey(id))
{
this.cart.remove(id);
}
}
public float getTotal() throws Exception
{
float result = 0;
for(ProductDTO dto : this.cart.values()){
result += dto.getProductprice() * dto.getProductquantity();
}
return result;
}
public void updateCart(int id,int quantity) throws Exception
{
if(this.cart.containsKey(id))
{
this.cart.get(id).setProductquantity(quantity);
}
}
}
|
package mx.ine.padron.repositorio;
// import org.springframework.data.repository.CrudRepository;
import mx.ine.padron.modelo.Persona;
public interface RepositorioPersona { // extends CrudRepository<Persona, Integer> {
}
|
package org.wso2.carbon.securevault.myvault.repository;
import org.wso2.securevault.keystore.IdentityKeyStoreWrapper;
import org.wso2.securevault.keystore.TrustKeyStoreWrapper;
import org.wso2.securevault.secret.SecretRepository;
import org.wso2.securevault.secret.SecretRepositoryProvider;
public class MyVaultSecretRepositoryProvider implements SecretRepositoryProvider {
/**
* Get Secret Repository.
*
* @param identityKeyStoreWrapper Identity KeyStore Wrapper
* @param trustKeyStoreWrapper Trust KeyStore Wrapper
* @return
*/
public SecretRepository getSecretRepository(IdentityKeyStoreWrapper identityKeyStoreWrapper,
TrustKeyStoreWrapper trustKeyStoreWrapper) {
return new MyVaultSecretRepository(identityKeyStoreWrapper, trustKeyStoreWrapper);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.