text
stringlengths
10
2.72M
package io.github.cottonmc.libcd.mixin; import io.github.cottonmc.libcd.impl.PlayerScreenHandlerAccessor; import net.minecraft.class_1657; import net.minecraft.class_1723; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @Mixin(class_1723.class) public class MixinPlayerScreenHandler implements PlayerScreenHandlerAccessor { @Shadow @Final private class_1657 owner; @Override public class_1657 libcd$getOwner() { return owner; } }
package com.toda.consultant; import android.os.Bundle; import android.widget.TextView; import com.toda.consultant.bean.SecondDetailBean; import com.toda.consultant.util.Ikeys; import butterknife.BindView; import butterknife.ButterKnife; /** * 二手房房源详情 * Created by yangwei on 2016/12/6. */ public class HousingProfileActivity extends BaseActivity { @BindView(R.id.tv_house_profile) TextView tvHouseProfile; @BindView(R.id.tv_leibie) TextView tvLeibie; @BindView(R.id.tv_woshi) TextView tvWoshi; @BindView(R.id.tv_keting) TextView tvKeting; @BindView(R.id.tv_chufang) TextView tvChufang; @BindView(R.id.tv_cesuo) TextView tvCesuo; @BindView(R.id.tv_yangtai) TextView tvYangtai; @BindView(R.id.tv_huayuan) TextView tvHuayuan; @BindView(R.id.tv_jianzhumianji) TextView tvJianzhumianji; @BindView(R.id.tv_taoneimianji) TextView tvTaoneimianji; @BindView(R.id.tv_louceng) TextView tvLouceng; @BindView(R.id.tv_junjia) TextView tvJunjia; @BindView(R.id.tv_zongjia) TextView tvZongjia; @BindView(R.id.tv_zhuangxiubiaozhun) TextView tvZhuangxiubiaozhun; @BindView(R.id.tv_chanquannianxian) TextView tvChanquannianxian; @BindView(R.id.tv_youwudianti) TextView tvYouwudianti; @BindView(R.id.tv_chaoxiang) TextView tvChaoxiang; private SecondDetailBean secondDetailBean; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_house_profile); initView(); getData(); setUi(); } private void setUi() { tvLeibie.setText(secondDetailBean.getHouseType()); tvWoshi.setText(secondDetailBean.getRoomType()); tvKeting.setText(secondDetailBean.getHallType()); tvChufang.setText(secondDetailBean.getCookroomType()); tvCesuo.setText(secondDetailBean.getWashroomType()); tvYangtai.setText(secondDetailBean.getShineroomType()); tvHuayuan.setText(secondDetailBean.getGardenType()); tvJianzhumianji.setText(secondDetailBean.getHouseArea() + "㎡"); tvTaoneimianji.setText(secondDetailBean.getRoomArea() + "㎡"); tvLouceng.setText("暂无"); tvJunjia.setText(secondDetailBean.getAveragePrice() + "元/㎡"); tvZongjia.setText(secondDetailBean.getHouseMoney() + "万元/套"); tvZhuangxiubiaozhun.setText(secondDetailBean.getDesignStandard()); tvChanquannianxian.setText(secondDetailBean.getOwnYear()); tvYouwudianti.setText(secondDetailBean.getLiftType()); tvChaoxiang.setText(secondDetailBean.getDirection()); } private void getData() { Bundle bd = getIntentData(); if (bd == null) return; secondDetailBean = (SecondDetailBean) bd.getSerializable(Ikeys.KEY_DATA); } @Override public void initView() { ButterKnife.bind(this); setTitle("房源介绍"); } }
package com.company; import java.util.*; /** * Created by 17032361 on 2017/8/8. * switch多分支结构 * 支持int与char 类型 */ public class chapter3_9 { public static void main(String[] args){ Scanner in = new Scanner(System.in); System.out.println("请输入你的名次"); int mingci = in.nextInt(); switch (mingci){ case 1: System.out.println("出任武林盟主"); break; case 2: System.out.println("出任武当掌门"); break; case 3: System.out.println("出任峨眉掌门"); break; default: System.out.println("逐出师门!"); } } }
public class HorseScore { private int value; HorseScore(int value){ this.value =value; } public int getValue() { return value; } public void addScore(HorseScore score) { this.value += score.getValue(); } }
package com.beike.biz.service.hessian; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.remoting.caucho.HessianServiceExporter; import com.beike.form.SmsInfo; import com.beike.service.common.SmsService; import com.beike.util.PropertyUtil; /** * @Title: TrxHessianServiceImpl.java * @Package com.beike.biz.service.hessian.ServerHessianServiceExporter * @Description: Hessian接口权限认证服务器端 * @author wh.cheng@sinobogroup.com * @date May 6, 2011 8:18:52 PM * @version V1.0 */ public class ServerHessianServiceExporter extends HessianServiceExporter { public static final Log logger = LogFactory .getLog(ServerHessianServiceExporter.class); PropertyUtil propertyUtil = PropertyUtil.getInstance("hessianAuth"); public String serverHessianAuth = propertyUtil .getProperty("serverHessianAuth"); @Autowired private SmsService smsService; @Override public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String auth = request.getHeader("hessianAuth"); logger.info("++++clientIp:" + request.getRemoteAddr()// 请求IP + "++++requestData:" + request.getRequestURL());// 目标应用路径 if (auth == null || !auth.equalsIgnoreCase(serverHessianAuth)) { // 记录异常日志 logger.info("+++++hessianAuth->fail"); SmsInfo sourceBean = new SmsInfo("13683334717", "主人,有人试图非法调用Heesian接口。让马云咬死他,咬死他。", "15", "1"); smsService.sendSms(sourceBean);// 短信报警 return; } super.handleRequest(request, response); } }
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import java.util.concurrent.TimeUnit; public class DragDropFrame { public static void main(String[] args) { InvokeBrowser myBrowser=new InvokeBrowser(); WebDriver driver=myBrowser.invokeChromeBrowser(); driver.get("http://jqueryui.com/droppable/"); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.switchTo().frame(driver.findElement(By.cssSelector("iframe.demo-frame"))); Actions myAction=new Actions(driver); WebElement webSource=driver.findElement(By.id("draggable")); WebElement webTarget=driver.findElement(By.id("droppable")); myAction.dragAndDrop(webSource,webTarget).build().perform(); driver.switchTo().defaultContent(); } }
package com.luke.volley.request; import com.android.volley.AuthFailureError; import com.android.volley.NetworkResponse; import com.android.volley.ParseError; import com.android.volley.Response; import com.android.volley.toolbox.HttpHeaderParser; import com.luke.gson.GsonUtil; import com.luke.volley.PatchedRequest; import com.luke.volley.callback.RequestCallback; import org.apache.http.entity.mime.MultipartEntity; import org.pmw.tinylog.Logger; import java.io.ByteArrayOutputStream; import java.io.IOException; /** * Created by cplu on 2016/3/16. */ public class GsonMultiPartRequest<T> extends PatchedRequest<T> { private final MultipartEntity m_multipartEntity; /** * make a http request (post/put) with MultipartEntity as body * * @param method * @param url * @param callback */ public GsonMultiPartRequest(int method, String url, MultipartEntity multipartEntity, Class<T> clazz, RequestCallback<T> callback) { super(method, url, clazz, null, callback); m_multipartEntity = multipartEntity; } public byte[] getBody() throws AuthFailureError { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { m_multipartEntity.writeTo(bos); return bos.toByteArray(); } catch (IOException e) { e.printStackTrace(); return null; } } @Override public String getBodyContentType() { return m_multipartEntity.getContentType().getValue(); } @Override protected Response<T> parseNetworkResponse(NetworkResponse response) { try { String json = new String( response.data, HttpHeaderParser.parseCharset(response.headers, DEFAULT_NETWORK_ENCODING)); Logger.debug("response of url " + getUrl() + " : " + json); return Response.success( GsonUtil.getGson().fromJson(json, m_clazz), HttpHeaderParser.parseCacheHeaders(response)); } catch (Exception e) { return Response.error(new ParseError()); } } }
package com.flower.api.ctrl; import com.flower.core.bean.UserBean; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; /** * @author cyk * @date 2018/8/15/015 17:47 * @email choe0227@163.com * @desc * @modifier * @modify_time * @modify_remark */ @RestController @RequestMapping("/user") public class UserController { @RequestMapping(method = {RequestMethod.POST}) public Object login(@RequestBody UserBean userBean){ return null; } }
/** * */ package com.UBQPageObjectLib; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.How; import com.UBQGenericLib.WebDriverCommonLib; /** * @author Basanagouda * */ public class StockReconciliation extends WebDriverCommonLib { public WebDriver driver; // ----------------------Constructor----------------------// public StockReconciliation(WebDriver driver) { this.driver = driver; } // ----------------------UI Elements----------------------// // ---For Store---// @FindBy(how = How.XPATH, using = "//select[@id='source_store']") private WebElement Store; // ---For ProductShortCode ---// @FindBy(how = How.XPATH, using = "//input[@id='prod_custom_code']") private WebElement ProductShortCode; // ---For ProductCode ---// @FindBy(how = How.XPATH, using = "//input[@id='prod_code']") private WebElement ProductCode; // ---For ProductName ---// @FindBy(how = How.XPATH, using = "//input[@id='productName']") private WebElement ProductName; // ---For ProductShortname ---// @FindBy(how = How.XPATH, using = "//input[@id='prod_short_name']") private WebElement ProductShortname; // ---For Casesize ---// @FindBy(how = How.XPATH, using = "//input[@id='prodCbbSize']") private WebElement Casesize; // ---For Select transfer type Radiobtns ---// // ---For StockinReconciliation to In-Transit Loss ---// @FindBy(how = How.XPATH, using = "//input[@id='actionType0']") private WebElement StkrecontoIntransit; // ---For StockinReconciliation to Damage ---// @FindBy(how = How.XPATH, using = "//input[@id='actionType1']") private WebElement StkrecontoDmg; // ---For In-TransitLoss to StockinReconciliation ---// @FindBy(how = How.XPATH, using = "//input[@id='actionType3']") private WebElement IntransittoStkrecon; // ---For Damage to StockinReconciliation ---// @FindBy(how = How.XPATH, using = "//input[@id='actionType2']") private WebElement DmgtoStkrecon; // ---For StockinReconciliation to Destruction ---// @FindBy(how = How.XPATH, using = "//input[@id='actionType4']") private WebElement StkrecontoDest; // ---For Viewbtn---// @FindBy(how = How.XPATH, using = "//input[@id='viewbtn']") private WebElement Viewbtn; // ---For Savebtn---// @FindBy(how = How.XPATH, using = "//input[@id='save_btn3']") private WebElement Savebtn; // ---For Clearbtn---// @FindBy(how = How.XPATH, using = "//input[@id='cancel4']") private WebElement Clearbtn; // ----------------------Functions----------------------// public void selectStore(String store) { selectvalue(store, Store); } public void enterProductShortCode(String productShortCode) { entervalue(productShortCode, ProductShortCode); ProductShortCode.sendKeys(Keys.TAB); } public String getProductCode() { return getvalue(ProductCode); } public String getProductName() { return getvalue(ProductName); } public String getProductShortname() { return getvalue(ProductShortname); } public String getCasesize() { return getvalue(Casesize); } public void clickRadioButton(String type) { if (type.contains("Stock in Reconciliation to In-Transit Loss")) { buttonClick(StkrecontoIntransit); } else if (type.contains("Stock in Reconciliation to Damage")) { buttonClick(StkrecontoDmg); } else if (type.contains("In-Transit Loss to Stock in Reconciliation ")) { buttonClick(IntransittoStkrecon); } else if (type.contains("Damage to Stock in Reconciliationansit Loss to Stock in Reconciliation")) { buttonClick(DmgtoStkrecon); } else if (type.contains("Stock in Reconciliation to Destruction")) { buttonClick(StkrecontoDest); } } public void clickViewbtn() { buttonClick(Viewbtn); } public void clickSavebtn() { buttonClick(Savebtn); } public void clickClearbtn() { buttonClick(Clearbtn); } }
package com.taotao.service; import java.util.Map; import org.springframework.web.multipart.MultipartFile; /** * 图片上传service * @author fenguriqi * 2017年3月5日 上午10:59:47 * ImageService */ public interface ImageService { /** * 上传图片 * @auther fengruiqi * 2017年3月5日 上午11:07:54 * @param multipartFile * @return */ public Map uploadImage(MultipartFile multipartFile); }
import java.util.*; public class MinStack { Stack<Integer> st; Stack<Integer> minStack; int min; /** initialize your data structure here. */ public MinStack() { st = new Stack<>(); minStack = new Stack<>(); min = Integer.MAX_VALUE; } public void push(int x) { // first element if(st.size()==0) min = x; // min element so far else if(x < min) min = x; st.push(x); minStack.push(min); } public void pop() { if(st.size()==0) return; st.pop(); minStack.pop(); if(st.size() != 0) min = minStack.peek(); } public int top() { if(st.size()==0) return -1; // not sure; error condition return st.peek(); } public int getMin() { if(minStack.size()==0) return -1; // not sure what to do; error condition return minStack.peek(); } }
package com.luv2code.mvc.mvcdemo.service; import java.util.List; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.luv2code.mvc.mvcdemo.dbo.Customer; import com.luv2code.mvc.mvcdemo.repository.CustomerRepository; @Service public class CustomerService { @Autowired private CustomerRepository customerRepository; @Transactional(rollbackOn = Exception.class) public List<Customer> getCustomers(){ List<Customer> list = customerRepository.findAll(); return list; } @Transactional(rollbackOn = Exception.class) public void saveCustomer(Customer customer){ Customer savedCustomer = customerRepository.save(customer); System.out.println(savedCustomer.getId()); } public Customer getCustomer(int customerId) { Customer customer = customerRepository.getOne(customerId); return customer; } public void delete(int customerId) { customerRepository.deleteById(customerId); } }
package org.dimigo.library; /** * Created by YuTack on 2015-11-10. */ public class GameCoordinate { public static final int RATIO = 4; public static final int RATIO_SCALE = 8; public static final int pixelWidth = 320; public static final int pixelHeight = 180; public static int toRealPos(int position) { return position * RATIO; } }
package com.anonymous9495.mashit; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; public class UserProfileFragment extends Fragment { UserData userData; TextView username, hotRate; ImageView myImage; Fonts myFontType; Button userProfile; String applink="https://play.google.com/store/apps/details?id=com.staffone.mashit"; public UserProfileFragment() { } public static UserProfileFragment newInstance() { UserProfileFragment fragment = new UserProfileFragment(); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle bundle = getActivity().getIntent().getExtras(); if(bundle!=null) { userData= (UserData) bundle.getSerializable("userObject"); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view= inflater.inflate(R.layout.fragment_user_profile, container, false); username = (TextView)view.findViewById(R.id.user_name); myImage = (ImageView)view.findViewById(R.id.user_image); hotRate = (TextView)view.findViewById(R.id.hotness_score); userProfile = view.findViewById(R.id.shareButton); myFontType = new Fonts(getContext()); username.setTypeface(myFontType.getCinzelBoldFont()); hotRate.setTypeface(myFontType.getCourgetteFont()); username.setText(userData.getName()); Glide.with(getContext()).load(Uri.parse(userData.getProfilePicUri())).fitCenter().into(myImage); hotRate.setText("Hotness score: "+userData.getHotScore()); return view; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); userProfile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String message = "My hotness Score: "+userData.getHotScore()+ "\nDownload app from playstore "+applink; Intent share = new Intent(Intent.ACTION_SEND); share.setType("text/plain"); share.putExtra(Intent.EXTRA_TEXT, message); getContext().startActivity(Intent.createChooser(share, "Share it with your friends :)")); } }); } }
package ua.com.juja.model.manager; import ua.com.juja.model.dataSet.DataSet; import java.util.List; import java.util.Map; import java.util.Set; /** * Interface for work with Database layer. */ public interface DatabaseManager { /** * Getting all tables of the required database * If no tables in current Database, he come back empty Set<String> * * @return Set<String> of exist table names */ Set<String> getTableNames(); /** * Getting data from required table. * If table is empty, he come back empty List<DataSet> * * @param tableName name of the required table * @return List<DataSet> with table data */ List<DataSet> getTableData(String tableName); /** * Getting column names from required table. * If table is empty, he come back empty List<String> * * @param tableName name of the required table * @return List<DataSet> with table data */ List<String> getColumnNames(String tableName); /** * Connection method insertRecord connection to required database. * * @param databaseName name of the database * @param userName name of registered user * @param password user password * @throws DatabaseManagerException if can't find driver or wrong user parameters */ void connect(String databaseName, String userName, String password); /** * Clear required table. All data will be deleted. * * @param tableName name of the required table */ void clearTable(String tableName); /** * Insert record to current table. * * @param tableName name of the table * @param columnData names of columns and value, that will be put to this columns. */ void insertRecord(String tableName, Map<String, Object> columnData); /** * Update values of record. * * @param tableName name of the table with needed record * @param keyValue value of the record id * @param columnData value of all other columns exclude id column */ void updateRecord(String tableName, Integer keyValue, Map<String, Object> columnData); /** * Getting column names of required table * * @param tableName name of the required table * @return Set<String> with column names inside */ Set<String> getTableColumns(String tableName); /** * Creating database using databaseName * * @param databaseName name of database which will be created. */ void createDatabase(String databaseName); /** * List of existing databases * * @return Set<String> where every element is name of exist database */ Set<String> databasesList(); /** * Drop required table with all data. * * @param tableName name of exist table for deleteRecord */ void deleteTable(String tableName); /** * Deleting exist record from table. * * @param tableName name of table with record * @param keyValue value of id column */ void deleteRecord(String tableName, String keyValue); /** * Deleting database. * * @param databaseName name of required database */ void deleteDatabase(String databaseName); /** * Creating table using tableName and columnParameter. * * @param tableName name of new table * @param columnParameters column names and column * types exclude identifier column id with value */ void createTable(String tableName, List<String> columnParameters); /** * Getting name of database which user is already connected * * @return name of database. */ String getDatabaseName(); /** * Getting name of user which already connected * * @return name of user. */ String getUserName(); }
package ch06; public class Initialization2 { static int count=0; int seNo; { count++; seNo=count; } public static void main(String[]args) { Initialization2 initi1=new Initialization2(); Initialization2 initi2=new Initialization2(); Initialization2 initi3=new Initialization2(); System.out.println("initi1의 제품번호는 "+initi1.seNo); System.out.println("initi2의 제품번호는 "+initi2.seNo); System.out.println("initi3의 제품번호는 "+initi3.seNo); System.out.println("총 갯수는 "+count+"개 입니다"); } }
package week4.homework; public class PropellerDriver extends Glider{ public PropellerDriver() { super(6000, "Propeller Driver"); } }
package com.coding4fun.models; import java.io.Serializable; /** * Created by coding4fun on 20-Oct-16. */ public abstract class Note implements Serializable { private int id; private String title, date, type; public static final String TYPE_VIDEO = "VIDEO"; public static final String TYPE_AUDIO = "AUDIO"; public static final String TYPE_PICTURE = "PICTURE"; public static final String TYPE_TEXT = "TEXT"; public Note() { } public Note(int id, String title, String date) { this.id = id; this.title = title; this.date = date; } public int getId() {return id;} public void setId(int id) {this.id = id;} public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getType() { return type; } public void setType(String type) { this.type = type; } public abstract String getDetails(); }
package com.norg.worldofwaste.gameobjects.valuables; import com.norg.worldofwaste.gameobjects.Subject; import com.norg.worldofwaste.gameobjects.Valuable; public class AbstractValuableSubject extends Subject implements Valuable { private double value; public AbstractValuableSubject(String name) { super(name); } @Override public double getValue() { return value; } @Override public void setValue(double value) { this.value = value; } }
/** * */ package edu.mycourses.adt.basic; import java.util.Iterator; /** * @author Ibrahima Diarra * */ public class CircularQueue <T> implements Iterable<T>{ private Node last; private int N = 0; public void enqueue(T item){ Node newnode = new Node(); newnode.item = item; if(last == null){ last = newnode; last.next = last; }else{ final Node old = last; newnode.next = last.next; last = newnode; old.next = last; } N++; } public T dequeue() { if (isEmpty()) return null; T item = null; if (last == last.next) { item = last.item; last = null; } else { item = last.next.item; last.next = last.next.next; } N--; return item; } public int size(){ return N; } public boolean isEmpty(){ return N == 0; } private class Node { T item; Node next; @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Node ["); if (item != null) builder.append("item=").append(item).append(", "); if (next != null) builder.append("next=").append(next); builder.append("]"); return builder.toString(); } } @Override public Iterator<T> iterator() { return new ListIterator(); } private class ListIterator implements Iterator<T>{ private Node current = null; public ListIterator() { if (last != null) current = last.next; } @Override public boolean hasNext() { return current != null; } @Override public T next() { T item = current.item; if (current == last) current = null; else current = current.next; return item; } @Override public void remove() { } } }
package com.jacaranda.entity; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class Customer implements Serializable, Comparable<Customer> { // Atributos private static int idComun = 1; private int id; private String fullName; private String address; private String phoneNumber; private String birthDate; private String dni; // Constructores public Customer() { super(); id = idComun++; } public Customer(String fullName, String address, String phoneNumber, String birthDate, String dni) { this.fullName = fullName; this.address = address; this.phoneNumber = phoneNumber; this.birthDate = birthDate; this.dni = dni; id = idComun++; } // Métodos get y set public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getBirthDate() { return birthDate; } public void setBirthDate(String birthDate) { this.birthDate = birthDate; } public String getDni() { return dni; } public void setDni(String dni) { this.dni = dni; } public int getId() { return id; } public int compareTo(Customer c1) { return this.getDni().compareTo(c1.getDni()); } @Override public String toString() { return "{\n\tid : " + id + ", \n\tfullName : " + fullName + ",\n\taddress : " + address + ", \n\tphoneNumber : " + phoneNumber + ", \n\tbirthDate : " + birthDate + ", \n\tdni : " + dni + "\n}"; } }
package com.alibaba.druid.bvt.sql.mysql.select; import com.alibaba.druid.sql.MysqlTest; import com.alibaba.druid.sql.SQLUtils; import com.alibaba.druid.sql.ast.SQLStatement; import com.alibaba.druid.sql.ast.statement.SQLSelectStatement; import com.alibaba.druid.util.JdbcConstants; import java.util.List; public class MySqlSelectTest_180_extract extends MysqlTest { public void test_0() throws Exception { String sql = "SELECT extract(day_of_week FROM '2001-08-22 03:04:05.321');"; List<SQLStatement> statementList = SQLUtils.parseStatements(sql, JdbcConstants.MYSQL); SQLSelectStatement stmt = (SQLSelectStatement) statementList.get(0); assertEquals(1, statementList.size()); assertEquals("SELECT EXTRACT(DAY_OF_WEEK FROM '2001-08-22 03:04:05.321');", stmt.toString()); } public void test_1() throws Exception { String sql = "SELECT extract(dow FROM '2001-08-22 03:04:05.321');"; List<SQLStatement> statementList = SQLUtils.parseStatements(sql, JdbcConstants.MYSQL); SQLSelectStatement stmt = (SQLSelectStatement) statementList.get(0); assertEquals(1, statementList.size()); assertEquals("SELECT EXTRACT(DOW FROM '2001-08-22 03:04:05.321');", stmt.toString()); } public void test_2() throws Exception { String sql = "SELECT extract(day_of_month FROM '2001-08-22 03:04:05.321');"; List<SQLStatement> statementList = SQLUtils.parseStatements(sql, JdbcConstants.MYSQL); SQLSelectStatement stmt = (SQLSelectStatement) statementList.get(0); assertEquals(1, statementList.size()); assertEquals("SELECT EXTRACT(DAY_OF_MONTH FROM '2001-08-22 03:04:05.321');", stmt.toString()); } public void test_3() throws Exception { String sql = "SELECT extract(day_of_year FROM '2001-08-22 03:04:05.321');"; List<SQLStatement> statementList = SQLUtils.parseStatements(sql, JdbcConstants.MYSQL); SQLSelectStatement stmt = (SQLSelectStatement) statementList.get(0); assertEquals(1, statementList.size()); assertEquals("SELECT EXTRACT(DAY_OF_YEAR FROM '2001-08-22 03:04:05.321');", stmt.toString()); } public void test_4() throws Exception { String sql = "SELECT extract(year_of_week FROM '2001-08-22 03:04:05.321');"; List<SQLStatement> statementList = SQLUtils.parseStatements(sql, JdbcConstants.MYSQL); SQLSelectStatement stmt = (SQLSelectStatement) statementList.get(0); assertEquals(1, statementList.size()); assertEquals("SELECT EXTRACT(YEAR_OF_WEEK FROM '2001-08-22 03:04:05.321');", stmt.toString()); } public void test_5() throws Exception { String sql = "SELECT extract(doy FROM '2001-08-22 03:04:05.321');"; List<SQLStatement> statementList = SQLUtils.parseStatements(sql, JdbcConstants.MYSQL); SQLSelectStatement stmt = (SQLSelectStatement) statementList.get(0); assertEquals(1, statementList.size()); assertEquals("SELECT EXTRACT(DOY FROM '2001-08-22 03:04:05.321');", stmt.toString()); } public void test_6() throws Exception { String sql = "SELECT extract(yow FROM '2001-08-22 03:04:05.321');"; List<SQLStatement> statementList = SQLUtils.parseStatements(sql, JdbcConstants.MYSQL); SQLSelectStatement stmt = (SQLSelectStatement) statementList.get(0); assertEquals(1, statementList.size()); assertEquals("SELECT EXTRACT(YOW FROM '2001-08-22 03:04:05.321');", stmt.toString()); } }
package util; /** * 配置文件.配置服务端地址,文件路径等信息 * @author roc_peng * */ public class GlobalConfig { // public static String filesRoot = "/usr/local/merkle/"; public static String filesRoot = "/Users/roc_peng/Downloads/merkle/"; public static String clientRoot = "/Users/roc_peng/Downloads/merkle/client/"; public static String getRootUrl="http://localhost:8666/MerkleTree/dataBlock"; }
package edu.neumont.csc280.lab4.user; /** * Created by blakerollins on 10/27/14. */ public class User { private static long counter = 0; private Long id; private final String username; private final String password; public User(String username, String password) { this.username = username; this.password = password; this.id = ++counter; } public Long getId() { return this.id; } public String getUsername() { return this.username; } public String getPassword() { return this.password; } }
package ru.fargus.testapp.network; /** * Created by Дмитрий on 01.02.2018. */ public class ApiConfig { public static final String BASE_URL = "https://yasen.hotellook.com/"; public static final String AUTOCOMPLETE_PATH = "autocomplete"; public static final String PARAM_TERM = "term"; public static final String PARAM_LANGUAGE = "lang"; }
package com.melodygram.activity; import android.app.Dialog; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.melodygram.R; import com.melodygram.constants.APIConstant; import com.melodygram.database.AppContactDataSource; import com.melodygram.database.FriendsDataSource; import com.melodygram.singleton.AppController; import org.json.JSONException; import org.json.JSONObject; /** * Created by LALIT on 25-06-2016. */ public class OtherUserProfileActivity extends MelodyGramActivity implements View.OnClickListener { private Bundle bundle; private TextView blockText; private AppController appController; private String blockValue; AppContactDataSource appContactDataSource; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.others_profile_layout); initView(); } private void initView() { appContactDataSource = new AppContactDataSource(getApplicationContext()); // TextView userName = (TextView) findViewById(R.id.header_name); TextView appName = (TextView) findViewById(R.id.name_edit_text); TextView statusText = (TextView) findViewById(R.id.status_edit_text); TextView phoneNumber = (TextView) findViewById(R.id.phone_number); ImageView imageHolder = (ImageView) findViewById(R.id.profile_image); imageHolder.setOnClickListener(this); findViewById(R.id.settings_button).setVisibility(View.INVISIBLE); findViewById(R.id.header_back_button_parent).setOnClickListener(this); blockText = (TextView) findViewById(R.id.block_text); blockText.setOnClickListener(this); bundle = getIntent().getExtras().getBundle("bundle"); appName.setText(bundle.getString("frendsAppName")); String statusPrivacy = bundle.getString("status_privacy"); if (statusPrivacy != null && statusPrivacy.equalsIgnoreCase("0")) { statusText.setText(bundle.getString("status")); }else if (statusPrivacy != null && statusPrivacy.equalsIgnoreCase("2")) { appContactDataSource.open(); if(appContactDataSource.isContactAvailableOrNot(bundle.getString("frendsNo"))) { statusText.setText(bundle.getString("status")); }else { statusText.setText(bundle.getString("")); } appContactDataSource.close(); }else { statusText.setText(bundle.getString("")); } String profilePicPrivacy = bundle.getString("profile_privacy"); FriendsDataSource friendsDataSource = new FriendsDataSource(OtherUserProfileActivity.this); friendsDataSource.open(); blockValue = friendsDataSource.getBlockValue(bundle.getString("contactsRoomId")); friendsDataSource.close(); phoneNumber.setText("+" + bundle.getString("countryCode") + bundle.getString("frendsNo")); appController = AppController.getInstance(); if (profilePicPrivacy != null && profilePicPrivacy.equalsIgnoreCase("0")) { appController.displayUrlImage(imageHolder, bundle.getString("friendProfilePicUrl"), null); } if (profilePicPrivacy != null && profilePicPrivacy.equalsIgnoreCase("2")) { appContactDataSource.open(); if(appContactDataSource.isContactAvailableOrNot(bundle.getString("frendsNo"))) { appController.displayUrlImage(imageHolder, bundle.getString("friendProfilePicUrl"), null); }else { // imageHolder.setBackgroundResource(R.drawable.default_profile_pic); } appContactDataSource.close(); }else { // imageHolder.setBackgroundResource(R.drawable.default_profile_pic); } setBlockValue(); } private void setBlockValue() { if (blockValue != null && blockValue.equalsIgnoreCase("1")) { blockText.setText(getResources().getString(R.string.unblock)); } else { blockText.setText(getResources().getString(R.string.block)); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.header_back_button_parent: finish(); break; case R.id.profile_image: Intent intent = new Intent(this, PicViewerActivity.class); intent.putExtra("imageURL", bundle.getString("friendProfilePicUrl")); startActivity(intent); break; case R.id.block_text: if (blockValue != null && blockValue.equalsIgnoreCase("1")) { blockUser("0"); } else { blockUser("1"); } break; } } private void blockUser(final String value) { JSONObject objJson = new JSONObject(); try { objJson.accumulate("value", value); objJson.accumulate("userid", appController.getUserId()); objJson.accumulate("type", "block"); objJson.accumulate("to_userid", bundle.getString("userId")); } catch (JSONException e) { e.printStackTrace(); } final Dialog dialog = AppController.getInstance().getLoaderDialog(this); dialog.show(); Log.v("request", objJson.toString()); JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST, APIConstant.BLOCK_USER, objJson, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.v("response", response.toString()); dialog.dismiss(); if (response != null) { try { if (response.getString("status").equalsIgnoreCase("success")) { blockValue = value; setBlockValue(); FriendsDataSource friendsDataSource = new FriendsDataSource(OtherUserProfileActivity.this); friendsDataSource.open(); friendsDataSource.updateBlock(bundle.getString("userId"), value); friendsDataSource.close(); } else { Toast.makeText(OtherUserProfileActivity.this, getResources().getString(R.string.failed), Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { Toast.makeText(OtherUserProfileActivity.this, getResources().getString(R.string.failed), Toast.LENGTH_SHORT).show(); e.printStackTrace(); } } else { Toast.makeText(OtherUserProfileActivity.this, getResources().getString(R.string.failed), Toast.LENGTH_SHORT).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { dialog.dismiss(); Toast.makeText(OtherUserProfileActivity.this, getResources().getString(R.string.failed), Toast.LENGTH_SHORT).show(); } }); appController.addToRequestQueue(jsonObjReq); } }
package fr.cea.nabla.interpreter.nodes.job; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.nodes.LoopNode; import fr.cea.nabla.interpreter.nodes.instruction.NablaWriteVariableNode; public class NablaTimeLoopJobNode extends NablaJobNode { @Child private NablaWriteVariableNode indexInitializer; @Child private LoopNode loopNode; public NablaTimeLoopJobNode(String name, NablaWriteVariableNode indexInitializer, LoopNode loopNode) { super(name); this.indexInitializer = indexInitializer; this.loopNode = loopNode; } protected NablaTimeLoopJobNode() { } @Override public Object executeGeneric(VirtualFrame frame) { indexInitializer.executeGeneric(frame); return loopNode.execute(frame); } }
class Method2 { void painting(int age,float c2,String name){//painting 안 변수이다.어떤값인지 알기 쉽게 이름을 같게한다. //지역변수임 painting끝나면 사라진다. //c1 c2 name 이것들은 매개변수이고 arguments라고도함 System.out.println("그립니다."); System.out.println(age+c2+name); } /*Sting tot(int c1,int c2, int c3){ return c1+c2+c3+"입니다."; }*/ int tot(int c1,int c2, int c3){ if(c1>10)// return c1+c2+c3; else return c1; } /*int tot(int c1,int c2, int c3){ if(c1>10)// return c1+c2+c3; //else가 생략된것 return c1; }*/ } public class Method1test { public static void main(String[] args) { // TODO Auto-generated method stub Method2 ins = new Method2(); int age=10; float jumsu=10.2f; String name="hong"; //ins.painting(10,10.2f,"hondgildong");//넘겨줄때 값을넣어도 되고 변수로 넣어도 된다. ins.painting(age, jumsu, name);//위에 변수를 설정해야 한다. ins.tot(80,89,90); } }
package com.example.agnciadeturismo.presenter.view.ui; import android.content.Intent; import android.os.Bundle; import androidx.fragment.app.Fragment; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProvider; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.Toast; import com.example.agnciadeturismo.R; import com.example.agnciadeturismo.data.repository.CidadeRepositoryTask; import com.example.agnciadeturismo.data.repository.PacoteRepositoryTask; import com.example.agnciadeturismo.model.PacoteDto; import com.example.agnciadeturismo.presenter.view.adapter.OnClickItemPacote; import com.example.agnciadeturismo.presenter.view.adapter.OfertaAdapter; import com.example.agnciadeturismo.presenter.viewmodel.CidadeViewModel; import com.example.agnciadeturismo.presenter.viewmodel.PacoteViewModel; import java.util.ArrayList; public class HomeFragment extends Fragment implements OnClickItemPacote { private static final String TAG = "HomeFragment"; AutoCompleteTextView autoCompleteTextViewTransporte, autoCompleteTextViewOrigem, autoCompleteTextViewDestino; RecyclerView recyclerViewOferta; Button buttonPesquisar; ArrayList<PacoteDto> listPacote = new ArrayList<>(); PacoteViewModel pacoteViewModel; CidadeViewModel cidadeViewModel; int cdOrigem = -1, cdDestino = -1; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_home, container, false); initView(view); initObserver(); buttonPesquisar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { cidadeViewModel.getCodigoCidade(autoCompleteTextViewOrigem.getText().toString(), autoCompleteTextViewDestino.getText().toString()); } }); return view; } private void initObserver() { pacoteViewModel.getOferta().observe(getActivity(), new Observer<ArrayList<PacoteDto>>() { @Override public void onChanged(ArrayList<PacoteDto> response) { listPacote = response; atualizaAdapter(listPacote); } }); cidadeViewModel.getTodasCidades().observe(getActivity(), new Observer<String[]>() { @Override public void onChanged(String[] cidades) { String[] listCidades = cidades; adapterAutoComplete(autoCompleteTextViewOrigem, listCidades); adapterAutoComplete(autoCompleteTextViewDestino, listCidades); Log.d(TAG, "Lista de cidades feito com sucesso"); } }); cidadeViewModel.getCodigoOrigem().observe(getActivity(), new Observer<Integer>() { @Override public void onChanged(Integer codigoOrigem) { if(codigoOrigem != null){ cdOrigem = codigoOrigem; buscarPacote(); }else{ cdOrigem = -1; } } }); cidadeViewModel.getCodigoDestino().observe(getActivity(), new Observer<Integer>() { @Override public void onChanged(Integer codigoDestino) { if(codigoDestino != null){ cdDestino = codigoDestino; buscarPacote(); }else{ cdDestino = -1; } } }); } private void buscarPacote() { if (cdOrigem != -1 && cdDestino != -1) { int transporte = -1; if(autoCompleteTextViewTransporte.getText().toString().equals("Avião")){ transporte = 1; }else if(autoCompleteTextViewTransporte.getText().toString().equals("Cruzeiro")){ transporte = 2; }else if(autoCompleteTextViewTransporte.getText().toString().equals("Ônibus")){ transporte = 3; } Intent intent = new Intent(getActivity(), BuscarActivity.class); intent.putExtra("tipo", transporte); intent.putExtra("cdOrigem", cdOrigem); intent.putExtra("cdDestino", cdDestino); intent.putExtra("destino", autoCompleteTextViewDestino.getText().toString()); startActivity(intent); }else if(cdOrigem != -1 && cdDestino == -1 || cdOrigem == -1 && cdDestino != -1){ Toast.makeText(getActivity(), "Cidade não encontrada", Toast.LENGTH_SHORT).show(); } } private void adapterAutoComplete(AutoCompleteTextView autoCompleteTextView, String[] arrayString) { ArrayAdapter adapter = new ArrayAdapter(getActivity(), R.layout.dropdown_item, arrayString); autoCompleteTextView.setAdapter(adapter); } private void initView(View view) { pacoteViewModel = new ViewModelProvider(this, new PacoteViewModel.ViewModelFactory(new PacoteRepositoryTask())).get(PacoteViewModel.class); cidadeViewModel = new ViewModelProvider(this, new CidadeViewModel.ViewModelFactory(new CidadeRepositoryTask())).get(CidadeViewModel.class); autoCompleteTextViewTransporte = view.findViewById(R.id.autoCompleteTextView_transporte); autoCompleteTextViewOrigem = view.findViewById(R.id.autoCompleteTextView_origem); autoCompleteTextViewDestino = view.findViewById(R.id.autoCompleteTextView_destino); recyclerViewOferta = view.findViewById(R.id.recycler_oferta); buttonPesquisar = view.findViewById(R.id.btn_pesquisarPacote); adapterAutoComplete(autoCompleteTextViewTransporte, getResources().getStringArray(R.array.tipo_transporte)); pacoteViewModel.getAllPacotesOferta(); cidadeViewModel.getAllCidades(); } private void atualizaAdapter(ArrayList<PacoteDto> listPacote) { OfertaAdapter adapter = new OfertaAdapter(this, listPacote); recyclerViewOferta.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false)); recyclerViewOferta.setAdapter(adapter); } @Override public void onClick(int posicao) { PacoteDto pacote = listPacote.get(posicao); Intent intent = new Intent(getActivity(), DetalhesActivity.class); intent.putExtra("codigo", pacote.getCd()); intent.putExtra("viagem", pacote.getCdViagem()); intent.putExtra("hotel", pacote.getCdHotel()); intent.putExtra("categoria", pacote.getCdCategoria()); intent.putExtra("tipoTransporte", pacote.getCdTipoTranporte()); intent.putExtra("origem", pacote.getCdOrigem()); intent.putExtra("destino", pacote.getCdDestino()); intent.putExtra("nomePacote", pacote.getNomePacote()); intent.putExtra("descricao", pacote.getDescricaoPacote()); intent.putExtra("checkin", pacote.getDtCheckin()); intent.putExtra("checkout", pacote.getDtCheckout()); intent.putExtra("img", pacote.getImg()); intent.putExtra("valor", pacote.getVlPacote()); startActivity(intent); } }
/** * Audit specific code. */ package ro.trc.office.ui.config.audit;
import javax.swing.*; import java.io.*; import java.awt.*; import java.util.*; import java.awt.event.*; class EditV { JTextField TrName,Tnode1,Tnode2,TrValue,TrAngle,TyPosition,TxPosition; JDialog jd; JButton Submit; JPanel wordPanel; public static final int DEFAULT_WIDTH = 400; public static final int DEFAULT_HEIGHT = 300; Voltage Vedit = new Voltage("v",1,2,100,100,0,4); EditV(JFrame j,Voltage v) { jd = new JDialog(j,"EditVesistorPanel",true); Vedit = v; jd.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); jd.setLayout(new BorderLayout()); wordPanel = new JPanel(); wordPanel.setLayout(new GridLayout(7, 1)); wordPanel.add(new JLabel("R name:")); wordPanel.add(TrName = new JTextField(Vedit.name)); wordPanel.add(new JLabel("node1 number:")); wordPanel.add(Tnode1 = new JTextField(Integer.toString(Vedit.node1))); wordPanel.add(new JLabel("node2 number:")); wordPanel.add(Tnode2 = new JTextField(Integer.toString(Vedit.node2))); wordPanel.add(new JLabel("location x:")); wordPanel.add(TxPosition = new JTextField(Integer.toString(Vedit.xloc))); wordPanel.add(new JLabel("location y:")); wordPanel.add(TyPosition = new JTextField(Integer.toString(Vedit.yloc))); wordPanel.add(new JLabel("angle:")); wordPanel.add(TrAngle = new JTextField(Double.toString(Vedit.orientation_angle))); wordPanel.add(new JLabel("value:")); wordPanel.add(TrValue = new JTextField(Double.toString(Vedit.value))); Submit = new JButton("Submit"); jd.add(wordPanel,BorderLayout.CENTER); jd.add(Submit, BorderLayout.SOUTH); myEvent();//必须在看的见前面 jd.setVisible(true); } private void myEvent() { Submit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("111111111111"); Vedit.setParameter(TrName.getText(), Integer.parseInt(Tnode1.getText()), Integer.parseInt(Tnode2.getText()), Integer.parseInt(TxPosition.getText()), Integer.parseInt(TyPosition.getText()), Double.parseDouble(TrAngle.getText()), Double.parseDouble(TrValue.getText()) ); System.out.println(Vedit); jd.setVisible(false); } }); } public static void main(String[] args) { JFrame frame = new JFrame("test"); Voltage v = new Voltage("v",1,2,30,10,0,100); EditV er = new EditV(frame,v); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); frame.setSize(500,300); frame.setVisible(true); } }
package com.example.enchanterswapna.foodpanda; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; public class finaladding extends AppCompatActivity { TextView txnum,txcst,txname,txcst1,tbasic; Button bsub,badd,bbas; int sub; String dgname,dgcost,dgmname; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_finaladding); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); bsub=(Button)findViewById(R.id.btnsub); badd=(Button)findViewById(R.id.btnadd); bbas=(Button)findViewById(R.id.addbas); txnum=(TextView)findViewById(R.id.txnumber); txcst=(TextView)findViewById(R.id.tvcost); txcst1=(TextView)findViewById(R.id.tvcost1); txname=(TextView)findViewById(R.id.typename); tbasic=(TextView)findViewById(R.id.txtv10); dgname= getIntent().getStringExtra("ptypename"); dgcost=getIntent().getStringExtra("pprice"); dgmname=getIntent().getStringExtra("pname"); setTitle(dgmname); txname.setText(dgname); txcst.setText(dgcost); tbasic.setText(dgcost); bsub.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { sub=Integer.parseInt(txnum.getText().toString()); sub--; if(sub>0) { txnum.setText(String.valueOf(sub)); } String fct=txnum.getText().toString(); String fcost=txcst.getText().toString(); int a=Integer.parseInt(fct); int b=Integer.parseInt(fcost); txcst.setVisibility(View.INVISIBLE); int c=a*b; String res=String.valueOf(c); txcst1.setText(res); } }); badd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { sub=Integer.parseInt(txnum.getText().toString()); sub++; txnum.setText(String.valueOf(sub)); String fct=txnum.getText().toString(); String fcost=txcst.getText().toString(); int a=Integer.parseInt(fct); int b=Integer.parseInt(fcost); txcst.setVisibility(View.INVISIBLE); int c=a*b; String res=String.valueOf(c); txcst1.setText(res); } }); bbas.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent int1=new Intent(finaladding.this,Cartact.class); String abcname=txname.getText().toString(); String abcnum=txnum.getText().toString(); String abccost=txcst.getText().toString(); int1.putExtra("gname",dgmname); int1.putExtra("fdname",abcname); int1.putExtra("fdnumber",abcnum); int1.putExtra("fdcost",abccost); startActivity(int1); } }); } public boolean onOptionsItemSelected(MenuItem item){ if(item.getItemId()==android.R.id.home) finish(); return super.onOptionsItemSelected(item); } }
public class exam06 { }
package com.application.settings.orginal; import org.codehaus.jackson.annotate.JsonIgnoreProperties; /** * Created by json2pojo */ @JsonIgnoreProperties(ignoreUnknown = true) public class Vegaheadfinder { }
package scut218.pisces.beans; /** * Created by Lenovo on 2018/3/14. */ public class Response { }
package com.seven.contract.manage.controller.contract; 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.Label; import com.seven.contract.manage.model.Member; import com.seven.contract.manage.service.LabelService; import com.seven.contract.manage.utils.NumberUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; 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 = "/label") public class LabelController extends BaseController { protected Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private LabelService labelService; @PostMapping("/list") public ApiResult getLabelList(HttpServletRequest request) { Member member; try { member = this.checkLogin(request); } catch (AppRuntimeException e) { return ApiResult.fail(request, e.getReqCode(), e.getMsg()); } long mid = member.getId(); Map<String, Object> params = new HashMap<>(); params.put("mid", mid); List<Label> labels = labelService.selectList(params); Map<String, Object> result = new HashMap<>(); result.put("labels", labels); return ApiResult.success(request, result); } @PostMapping("/add") public ApiResult addLabel(HttpServletRequest request, String labelName) { 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(labelName)) { return ApiResult.fail(request, "标签名称不能为空"); } Map<String, Object> result = new HashMap<>(); try{ int id = labelService.addLabel(mid, labelName); result.put("id", id); } catch (Exception e) { return ApiResult.fail(request, e.getMessage()); } return ApiResult.success(request, result); } @PostMapping("/update") public ApiResult updateLabel(HttpServletRequest request, String id, String labelName) { 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)) { ApiResult.fail(request, "标签ID错误"); } if (StringUtils.isEmpty(labelName)) { ApiResult.fail(request, "标签名称不能为空"); } Label label = labelService.selectOneById(Long.valueOf(id)); if (label == null) { ApiResult.fail(request, "标签信息不存在"); } if (label.getMid() != mid) { ApiResult.fail(request, "非法操作"); } label.setLabelName(labelName); label.setAddTime(new Date()); try{ labelService.updateLabel(label); } catch (Exception e) { e.printStackTrace(); return ApiResult.fail(request, "操作失败"); } return ApiResult.success(request); } @PostMapping("/delete") public ApiResult deleteLabel(HttpServletRequest request, String id) { 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)) { ApiResult.fail(request, "标签ID错误"); } Label label = labelService.selectOneById(Long.valueOf(id)); if (label == null) { ApiResult.fail(request, "标签信息不存在"); } if (label.getMid() != mid) { ApiResult.fail(request, "非法操作"); } try{ labelService.deleteById(Long.valueOf(id)); } catch (Exception e) { return ApiResult.fail(request, "操作失败"); } return ApiResult.success(request); } }
package com.spring.board.board.model; public class PageVO { private Integer page; private Integer countPerPage; private String keyword; private String condition; public PageVO(Integer page, Integer countPerPage, String keyword, String condition) { page = 1; this.countPerPage = 10; this.keyword = ""; this.condition = ""; } public Integer getPageStart() { return (this.page - 1) * this.countPerPage; } public Integer getPage() { return page; } public void setPage(Integer page) { this.page = page; } public Integer getCountPerPage() { return countPerPage; } public void setCountPerPage(Integer countPerPage) { this.countPerPage = countPerPage; } public String getKeyword() { return keyword; } public void setKeyword(String keyword) { this.keyword = keyword; } public String getCondition() { return condition; } public void setCondition(String condition) { this.condition = condition; } }
/** * $Id: Role.java,v 1.9 2005/08/21 19:06:23 nicks Exp nicks $ * * Originally part of the AMATO application. * * @author Nick Seidenman <nick@seidenman.net> * @version $Revision: 1.9 $ * * $Log: Role.java,v $ * Revision 1.9 2005/08/21 19:06:23 nicks * Changed comment header to conform with javadoc conventions. * * Revision 1.8 2005/08/15 14:26:28 nicks * Changed as_* to to* (more java-esque) * * Revision 1.7 2005/06/22 21:41:53 nicks * Cheap, demo version of cast selection working. (Will use real * java stuff, not this crappy html vaporware.) * Had to make the AmatoDB object globally visible for this * sort of thing to work. I hate doing it, but I guess there's no * harm for the moment since this is a self-contained application. * * Revision 1.6 2005/06/20 22:34:38 nicks * SeasonPanel is now working in a cheesy, demo-only sort of way. It's * at least enough for me to get the idea across to Irene and talk * through how it will work when finished.d * * Revision 1.5 2005/06/18 22:41:51 nicks * RosterPanel now working. * Several changes to the toHTML methods. * Fixed parsing in Musician so that list of instruments is properley * split along comma (,) delimiters. * * Revision 1.4 2005/06/18 04:19:02 nicks * Have OperaPanel and RosterPanel (cheesy versions) working. * This should be suitable for demo to Irene sometime soon. * I just want to more or less dummy up a SeasonPanel and I'll * be ready to demo. * * Revision 1.3 2005/06/17 17:11:19 nicks * First (cheesy) integration of GUI (OperaPanel) with the database (AmatoDB). * * Revision 1.2 2005/06/16 15:25:05 nicks * Added object_name (HashMap aMap) constructor so that I can simply pass * the attribute map from the parser without the parser itself ever * needing to know such details as which attributes are required and * which are optional. This is a slicker, cleaner, more OO way to * handle XML tag attributes. * * Revision 1.1 2005/06/15 14:51:08 nicks * Initial revision * */ import java.io.*; import java.util.*; public class Role implements Serializable { private static final long serialVersionUID = 20050915163020L; private Opera opera; private String name; private String voice; private String order; public Role (Opera opera, HashMap aMap) { this.opera = opera; name = (String) aMap.get ("name"); voice = (String) aMap.get ("voice"); order = (String) aMap.get ("order"); } public String toXML () { String result; result = "<role name=\"" + name + "\"" + " voice=\"" + voice + "\"" + " order=\"" + order + "\"/>"; return result; } public String toHTML_tr () { return new String ("<tr><td>" + name + "</td><td align='right'>" + voice + "</td></tr>"); } public int getOrder () { return Integer.parseInt (order); } public String getName () { return name; } public String getVoice () { return voice; } public Opera getOpera () { return opera; } }
package polak.adrian.blockgame; import android.graphics.RectF; /** * Created by adrian on 11.09.2018. */ public class Alien { private RectF rect; private boolean isVisible; private int padding = 2; public Alien(int x, int y, int width, int height) { isVisible = true; rect = new RectF( y * width + padding, x * height + padding, y * width + width - padding, x * height + height - padding ); } public boolean isVisible() { return isVisible; } public void setVisible(boolean visible) { isVisible = visible; } public RectF getRect() { return rect; } }
package com.wang.mapper; import com.wang.pojo.User; import org.apache.ibatis.annotations.Param; import java.util.List; public interface UserMapper { List<User> queryUser(); //添加一个用户 int addUser(User user); //删除一个用户 int deleteUser(@Param("id") int id); }
package com.pda.pda_android.service; import android.app.AlarmManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.Handler; import android.os.IBinder; import android.os.Message; import com.google.gson.Gson; import com.pda.pda_android.base.network.LoadCallBack; import com.pda.pda_android.base.network.OkHttpManager; import com.pda.pda_android.base.others.ContentUrl; import com.pda.pda_android.base.utils.LogUtils; import com.pda.pda_android.db.Entry.UserBean; import com.pda.pda_android.bean.UsersListBean; import com.pda.pda_android.db.dbutil.UserDaoOpe; import com.zhy.http.okhttp.OkHttpUtils; import com.zhy.http.okhttp.callback.StringCallback; import java.io.IOException; import java.util.List; import okhttp3.Call; import okhttp3.Response; /** * 梁佳霖创建于:2018/10/18 17:54 * 功能:获取用户列表的服务 */ public class UsersListService extends Service { private boolean pushthread = false; private static Context context; @Override public IBinder onBind(Intent intent) { LogUtils.showLog("UsersListService", "onBind"); throw new UnsupportedOperationException("Not yet implemented"); } @Override public int onStartCommand(Intent intent, int flags, int startId) { LogUtils.showLog("UsersListService", "onStartCommand"); if (intent != null) { if (intent.getStringExtra("flags").equals("3")) { //判断当系统版本大于20,即超过Android5.0时,我们采用线程循环的方式请求。 //当小于5.0时的系统则采用定时唤醒服务的方式执行循环 int currentapiVersion = android.os.Build.VERSION.SDK_INT; if (currentapiVersion > 20) { getPushThread(); } else { handler.sendEmptyMessage(DOINTERNET); } } } return super.onStartCommand(intent, flags, startId); } //循环请求的线程 public void getPushThread() { pushthread = true; handler.sendEmptyMessage(DOINTERNET); } public static final int DOINTERNET = 1111; //发送网络请求 public static final int DOINTERNETAGEN = 2222; //发送网络请求 Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what){ case DOINTERNET: getHttp(); handler.sendEmptyMessageDelayed(DOINTERNETAGEN,1000 * 60 * 3); break; case DOINTERNETAGEN: getHttp(); handler.sendEmptyMessageDelayed(DOINTERNET,1000 * 60 * 3); break; } super.handleMessage(msg); } }; //请求网络获取数据 private void getHttp() { OkHttpManager.getInstance().getRequest(context, ContentUrl.TestUrl_local + ContentUrl.getUsersList, new LoadCallBack<String>(context,false) { @Override protected void onEror(Call call, int statusCode, Exception e) { super.onEror(call, statusCode, e); handler.removeMessages(DOINTERNET); } @Override protected void onSuccess(Call call, Response response, String s) throws IOException { if (s.contains("\"response\": \"ok\"")) { UserDaoOpe.deleteAllData(context); LogUtils.showLog(ContentUrl.getUsersList+"----患者列表同步数据", s); UserDaoOpe.deleteAllData(context); Gson gson = new Gson(); UsersListBean usersListBeanList = gson.fromJson(s, UsersListBean.class); List<UserBean> userBeans = usersListBeanList.getData(); UserDaoOpe.insertData(context, userBeans); }else{ handler.removeMessages(DOINTERNET); } } }); } // //请求网络获取数据 // private void getHttp() { // String url = ContentUrl.TestUrl_local+ContentUrl.getUsersList; // OkHttpUtils.get().url(url).build().execute(new StringCallback() { // @Override // public void onError(Call call, Exception e) { // getHttp(); // } // // @Override // public void onResponse(Call call, String s) { // UserDaoOpe.deleteAllData(context); // LogUtils.showLog("患者列表同步数据", s); // UserDaoOpe.deleteAllData(context); // Gson gson = new Gson(); // UsersListBean usersListBeanList = gson.fromJson(s, UsersListBean.class); // List<UserBean> userBeans = usersListBeanList.getData(); // int a = usersListBeanList.getData().size(); // UserDaoOpe.insertData(context, userBeans); // Long bbb = 123123L; // for (int i = 0; i < a; i++) { // userBeans.get(i).setId(bbb + i + 100); // UserDaoOpe.insertData(context, userBeans.get(i)); // } // } // }); // } @Override public void onDestroy() { pushthread = false; LogUtils.showLog("UsersListService", "onDestroy"); super.onDestroy(); } //启动服务和定时器 public static void getConnet(Context mContext) { try { context = mContext; Intent intent = new Intent(mContext, UsersListService.class); intent.putExtra("flags", "3"); int currentapiVersion = android.os.Build.VERSION.SDK_INT; if (currentapiVersion > 20) { //一般的启动服务的方式 mContext.startService(intent); } else { //定时唤醒服务的启动方式 PendingIntent pIntent = PendingIntent.getService(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager alarmManager = (AlarmManager) mContext .getSystemService(Context.ALARM_SERVICE); alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 3000, pIntent); } } catch (Exception e) { e.printStackTrace(); } } //停止由AlarmManager启动的循环 public static void stop(Context mContext) { Intent intent = new Intent(mContext, UsersListService.class); PendingIntent pIntent = PendingIntent.getService(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager alarmManager = (AlarmManager) mContext .getSystemService(Context.ALARM_SERVICE); alarmManager.cancel(pIntent); } }
package com.testFileUpload.service.impl; import com.testFileUpload.service.UserRoleService; public class UserRoleServiceImpl implements UserRoleService { }
package com.google.activitydatatransfer; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class ActivityOne extends AppCompatActivity { private EditText edtName, edtAge, edtPro; Button btnNext; private final int requestcode = 1; String enteredName, enteredAge, enteredProfession; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_one); edtName = findViewById(R.id.edtOneName); edtAge = findViewById(R.id.edtOneAge); edtPro = findViewById(R.id.edtOnePro); btnNext = findViewById(R.id.btnOneNext); btnNext.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (edtName.getText() != null && edtAge.getText() != null && edtPro.getText() != null) {//check if all fields are filled //get text from all fields String name = edtName.getText().toString().trim(); String age = edtAge.getText().toString().trim(); String profession = edtPro.getText().toString().trim(); Intent intent = new Intent(ActivityOne.this, ActivityTwo.class); intent.putExtra("name", name); intent.putExtra("age", age); intent.putExtra("profession", profession); startActivityForResult(intent, requestcode); } else { Toast.makeText(ActivityOne.this, "Fill all fields!", Toast.LENGTH_SHORT).show(); } } }); } //To recieve data from activity Two @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == requestcode) { if (data != null) { enteredName = data.getStringExtra("name_entered"); enteredAge = data.getStringExtra("age_entered"); enteredProfession = data.getStringExtra("pro_entered"); } } } @Override protected void onPostResume() { super.onPostResume(); edtName.setText(enteredName); edtAge.setText(enteredAge); edtPro.setText(enteredProfession); } }
package br.pucrs.ep.es.model; import br.pucrs.ep.es.model.Cliente; import java.text.SimpleDateFormat; import java.util.Date; public class Atendimento { private Cliente cliente; private Date dataHoraAtendimento; private String data; private String hora; public Atendimento(Cliente cliente) { dataHoraAtendimento = new Date(); data = new SimpleDateFormat("dd/MM/yyyy").format(dataHoraAtendimento); hora = new SimpleDateFormat("HH:mm:ss").format(dataHoraAtendimento); } }
package com.xiaojianma.order.service; import com.xiaojianma.order.mapper.OrderMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service public class OrderService { @Autowired OrderMapper orderMapper; @Transactional() public int addOrder(String number) { return orderMapper.insertMember(number); } }
package shenzhen.teamway.aspect; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Inherited @Retention(RetentionPolicy.RUNTIME) public @interface AspectPojo { /** * @Author: Zhao Hong Ning * @Description:何种场景下打印日志 * @Date: 2019/4/18 * @param: null * @return: */ String modoule(); }
//good job! //for save space, can also use: sb.append((char)(r - 1 + 'A')) //there is one tricky detail in this problem //that when input 26, quotient will be 1, then while loop will execute one more time, give out "AZ" //to eliminate that problem, just careful observe the regular, when remain is 0, quotient--, problem solved public class Solution { public String convertToTitle(int n) { char[] table = {'Z','A','B','C','D','E','F','G','H','I' ,'J','K','L','M','N','O','P','Q','R','S','T' ,'U','V','W','X','Y'}; int current = n; String str = ""; while (current > 0) { int lowDigit = current % 26; str = table[lowDigit] + str; current /= 26; if (lowDigit == 0) current--; } return str; } }
package com.example.thibanglaixea1; import android.graphics.drawable.AnimationDrawable; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ImageView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); AnimationDrawable animation = new AnimationDrawable(); animation.addFrame(getResources().getDrawable(R.drawable.icon_menu), 10000); animation.addFrame(getResources().getDrawable(R.drawable.icon_start), 50000); animation.setOneShot(false); ImageView imageAnim = (ImageView) findViewById(R.id.image_view); imageAnim.setBackgroundDrawable(animation); // start the animation! animation.start(); } }
package com.company; import java.util.Arrays; import java.util.Scanner; public class Ejercicio6 { public static void main(String[] args) { Scanner teclado = new Scanner (System.in); System.out.println("Introduzca la longitud: "); int longitud=teclado.nextInt(); int t[] = new int[longitud]; for (int i=0;i<longitud;i++){ System.out.println("Introduzca los numeros:"); t[i]=teclado.nextInt(); } System.out.println(Arrays.toString(sinRepetidos(t))); } static int[] sinRepetidos(int tabla[]){ int longitud=tabla.length; for (int i=0;i<longitud;i++){ for (int j=i+1;j<longitud;j++){ if (tabla[i]==tabla[j]){ tabla[j]=tabla[longitud-1]; longitud--; } } } int tablaFinal[] = Arrays.copyOf(tabla,longitud); return tablaFinal; } }
import java.util.*; public class Mage extends baseChar{ //private String name = "DEFAULT"; //private int Health=20; // private int attack=3; // private int defense=2; private int mana=10; // private int dexterity=4; public Mage(String name){ super(name); setHealth(20); setDex(4); setAttack(4); setDef(2); setMana(7); } /* public Boolean runAway(){ //0-9 Random a = new Random(); int chance=a.nextInt(10); if (chance<dexterity){ return true; } else return false; } public int getHealth(){ return this.Health; }*/ }
package com.example.netflix_project.src.main.interfaces; import com.example.netflix_project.src.main.models.Movie; import java.util.List; public interface MovieInfoView { void onMovieDetailSuccess(Movie movies); void onError(); }
package com.spreadtrum.android.eng; import android.app.Notification; import android.app.PendingIntent; import android.app.Service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.IBinder; import android.util.Log; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class SlogUISnapService extends Service { private static final Class[] mStartSnapSvcSignature = new Class[]{Integer.TYPE, Notification.class}; private static final Class[] mStopSnapSvcSignature = new Class[]{Boolean.TYPE}; private final BroadcastReceiver mLocalChangeReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { Log.d("SlogUISnapService", "language is change...."); SlogUISnapService.this.setNotification(); } }; private Method mStartSnapSvc; private Object[] mStartSnapSvcArgs = new Object[2]; private Object[] mStopSnapArgs = new Object[1]; private Method mStopSnapSvc; private Notification notification; public void onCreate() { this.notification = new Notification(17301668, getText(R.string.notification_snapsvc_statusbarprompt), 0); setNotification(); registerReceiver(this.mLocalChangeReceiver, new IntentFilter("android.intent.action.LOCALE_CHANGED")); } private void setNotification() { this.notification.setLatestEventInfo(this, getText(R.string.notification_snapsvc_title), getText(R.string.notification_snapsvc_prompt), PendingIntent.getActivity(this, 0, new Intent(this, SlogUISnapAction.class).setFlags(268435456), 134217728)); try { this.mStartSnapSvc = getClass().getMethod("startForeground", mStartSnapSvcSignature); this.mStopSnapSvc = getClass().getMethod("stopForeground", mStopSnapSvcSignature); } catch (NoSuchMethodException e) { this.mStopSnapSvc = null; this.mStartSnapSvc = null; } new Thread(null, new Runnable() { public void run() { if (SlogUISnapService.this.mStartSnapSvc != null) { SlogUISnapService.this.mStartSnapSvcArgs[0] = Integer.valueOf(2); SlogUISnapService.this.mStartSnapSvcArgs[1] = SlogUISnapService.this.notification; try { SlogUISnapService.this.mStartSnapSvc.invoke(SlogUISnapService.this, SlogUISnapService.this.mStartSnapSvcArgs); } catch (InvocationTargetException e) { Log.w("Slog", "Unable to invoke startForeground", e); } catch (IllegalAccessException e2) { Log.w("Slog", "Unable to invoke startForeground", e2); } } } }, "SnapThread").start(); } public void onStart(Intent intent, int startId) { } public void onDestroy() { if (this.mStopSnapSvc != null) { this.mStopSnapArgs[0] = Boolean.TRUE; try { this.mStopSnapSvc.invoke(this, this.mStopSnapArgs); return; } catch (InvocationTargetException e) { Log.w("ApiDemos", "Unable to invoke stopForeground", e); return; } catch (IllegalAccessException e2) { Log.w("ApiDemos", "Unable to invoke stopForeground", e2); return; } } super.onDestroy(); } public IBinder onBind(Intent intent) { return null; } }
package com.yc.education.service.stock; import com.yc.education.model.stock.PurchaseStockProduct; import com.yc.education.service.IService; import java.util.List; /** * @ClassName PurchaseStockProductService * @Description TODO * @Author QuZhangJing * @Date 2018/10/25 15:28 * @Version 1.0 */ public interface PurchaseStockProductService extends IService<PurchaseStockProduct> { /** * @Description 根据产品编号查询未出库完的采购入库单 * @Author BlueSky * @Date 11:14 2019/5/5 **/ List<PurchaseStockProduct> listNotOutboundPurchaseStockProduct(String productNo); /** * @Author BlueSky * @Description //TODO 通过采购入库单查询下面所有的产品详情并携带入库单信息 * @Date 15:44 2019/3/28 * @Param [productNo] * @return java.util.List<com.yc.education.model.stock.PurchaseStockProduct> **/ List<PurchaseStockProduct> listPurchaseStockProductAndPurchaseStockByProdutNo(String stockOrder); /** * @Author BlueSky * @Description //TODO 根据产品编号查找产品库位和楼层 * @Date 15:40 2019/3/27 * @Param [productNo] * @return com.yc.education.model.stock.PurchaseStockProduct **/ PurchaseStockProduct getProductAddressByProductNo(String productNo); /** * @Author BlueSky * @Description //TODO 查询产品是否存在多个库位 * @Date 13:39 2019/3/27 * @Param [productNo] * @return java.util.List<java.lang.String> **/ List<String> listPurchaseStockProductMoreStockByproductNo(String productNo); /** * 根据采购入库单编号查询采购入库产品 * @param id * @return */ List<PurchaseStockProduct> findStockProductBypurchaseStockId(long id); /* *根据采购订单 */ List<PurchaseStockProduct> findPurchaseStockProductByPurchaseOrder(String purchaseOrder); Double findPurchaseStockProductPriceSUM(long id); /** * 根据产品名称和时间筛选查询采购入库产品 * @param productName * @param startTime * @param endTime * @return */ List<PurchaseStockProduct> findPurchaseStockProductByProductNameAndStartTimeAndEndTime(String productName,String startTime,String endTime); }
package lang; public class ByteDemo { public static void main(String[] argv) { oldDemo(); // getStrtingRadix(); // longToBinaryString(122); // longToBinaryString(Long.MAX_VALUE); // 63 digit 1 } private static void oldDemo() { String s1 = "This is an example"; byte[] bytes = s1.getBytes(); String s2 = new String(bytes); System.out.println("Text : " + s1); System.out.println("Text [Byte Format] : " + bytes); System.out.println("Text [Byte Format] : " + bytes.toString()); System.out.println("Text Decryted : " + s2); } private static void testByteToBinaryString() { System.out.println(byteToBinaryString((byte) 129)); // 10000001 System.out.println(byteToBinaryString((byte) 2)); // 00000010 System.out.println(byteToBinaryString((byte) 0)); // 00000000 System.out.println(byteToBinaryString((byte) 255)); // 11111111 } private static void longToBinaryString(long n) { String s = Long.toBinaryString(n); System.out.println(s); Long t = Long.parseUnsignedLong(s, 2); System.out.println(t); } private static void getStrtingRadix() { /* returns the string representation of the unsigned integer in concern radix */ System.out.println("Binary eqivalent of 100 = " + Integer.toString(100, 2)); System.out.println("Octal eqivalent of 100 = " + Integer.toString(100, 8)); System.out.println("Decimal eqivalent of 100 = " + Integer.toString(100, 10)); System.out.println("Hexadecimal eqivalent of 100 = " + Integer.toString(100, 16)); } public static String byteToBinaryString(byte n) { return String.format("%8s", Integer.toBinaryString(n & 0xFF)).replace(' ', '0'); } }
package com.carloseachaves.retrofit.api; import com.carloseachaves.retrofit.model.APIgeeResponseSuccess; import com.carloseachaves.retrofit.model.Book; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.DELETE; import retrofit2.http.GET; import retrofit2.http.Headers; import retrofit2.http.POST; import retrofit2.http.PUT; import retrofit2.http.Path; public interface APIgeeInterface { @GET("books?limit=100") Call<APIgeeResponseSuccess> listBooks(); @GET("books/{uuid}") Call<APIgeeResponseSuccess> getById(@Path("uuid") String uuid); @POST("books") @Headers({ "Content-type: application/json" }) Call<APIgeeResponseSuccess> addBook(@Body Book book); @PUT("books/{uuid}") @Headers({ "Content-type: application/json" }) Call<APIgeeResponseSuccess> updateBook(@Body Book book, @Path("uuid") String uuid); @DELETE("books/{uuid}") Call<APIgeeResponseSuccess> removeBook(@Path("uuid") String uuid); }
package com.jyn.masterroad.utils.dagger2.inject; import dagger.Component; /** * Created by jiao on 2020/8/17. */ @Component public interface CarComponent { void inject(Car car); }
package com.example.johann.santa; import android.app.Activity; import android.widget.TextView; import android.os.Bundle; public class EnfantDetailActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail_enfant); Enfant p = this.getIntent().getExtras().getParcelable("selected"); TextView tv1 = (TextView)this.findViewById(R.id.textView_detail_prenom); tv1.setText(String.valueOf(p.getPrenom())); TextView tv2 = (TextView)this.findViewById(R.id.textView_detail_sexe); tv2.setText(String.valueOf(p.getSexe())); } }
package mihnea.licenta.server.entity; import javax.persistence.*; import java.time.LocalDate; @Entity public class SensorsData { @Id @Column(unique = true, nullable = false) @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Basic private java.time.LocalDate date; // LocalDate.parse("2017-11-15") private double temp; private double earthHum; private double light; public double getTemp() { return temp; } public void setTemp(double temp) { this.temp = temp; } public double getEarthHum() { return earthHum; } public void setEarthHum(double earthHum) { this.earthHum = earthHum; } public double getLight() { return light; } public void setLight(double light) { this.light = light; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public LocalDate getDate() { return date; } public void setDate(LocalDate date) { this.date = date; } }
package com.acompanhamento.api.web.exception; public class BadRequestException extends RuntimeException{ public BadRequestException(String mensagem) { super(mensagem); } }
/* * NVH. */ package common.bean; import java.util.Date; import javax.servlet.http.HttpSession; /** * Luu thong tin nguoi dung. * * @author lockex1987 */ public class UserBean { private Long sysUserId; // Id nguoi dung private String loginName; // Ten dang nhap private String fullName; // Ten day du private Date loginTime; // Thoi gian dang nhap private String ipAddress; // Dia chi IP private String sessionId; // Session ID private HttpSession httpSession; // Doi tuong session private String userAgent; // User agent public UserBean() { } public String getLoginName() { return loginName; } public void setLoginName(String loginName) { this.loginName = loginName; } public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } public Date getLoginTime() { return loginTime; } public void setLoginTime(Date loginTime) { this.loginTime = loginTime; } public String getIpAddress() { return ipAddress; } public void setIpAddress(String ipAddress) { this.ipAddress = ipAddress; } public String getSessionId() { return sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } public HttpSession getHttpSession() { return httpSession; } public void setHttpSession(HttpSession httpSession) { this.httpSession = httpSession; } public Long getSysUserId() { return sysUserId; } public void setSysUserId(Long sysUserId) { this.sysUserId = sysUserId; } public String getUserAgent() { return userAgent; } public void setUserAgent(String userAgent) { this.userAgent = userAgent; } }
package com.fiume.billingmechine; /** * Created by Razi on 12/15/2015. */ class BillingMachineAppController { }
package com.example.demo.entity; import lombok.Data; /** * Department * * @author ZhangJP * @date 2020/8/5 */ @Data public class PublishDepartment { /** * 部门id */ private Long deptId; /** * 部门名称 */ private String deptName; /** * 项目组id */ private Long subDeptId; /** * 项目组名称 */ private String subDeptName; /** * 是不是该部门的领导 */ private Boolean isLeader; }
/* * Copyright 2002-2023 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.jms.listener.adapter; import jakarta.jms.Destination; import jakarta.jms.JMSException; import jakarta.jms.Session; import org.junit.jupiter.api.Test; import org.springframework.jms.support.destination.DestinationResolver; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * @author Stephane Nicoll */ public class JmsResponseTests { @Test public void destinationDoesNotUseDestinationResolver() throws JMSException { Destination destination = mock(); Destination actual = JmsResponse.forDestination("foo", destination).resolveDestination(null, null); assertThat(actual).isSameAs(destination); } @Test public void resolveDestinationForQueue() throws JMSException { Session session = mock(); DestinationResolver destinationResolver = mock(); Destination destination = mock(); given(destinationResolver.resolveDestinationName(session, "myQueue", false)).willReturn(destination); JmsResponse<String> jmsResponse = JmsResponse.forQueue("foo", "myQueue"); Destination actual = jmsResponse.resolveDestination(destinationResolver, session); assertThat(actual).isSameAs(destination); } @Test public void createWithNullResponse() { assertThatIllegalArgumentException().isThrownBy(() -> JmsResponse.forQueue(null, "myQueue")); } @Test public void createWithNullQueueName() { assertThatIllegalArgumentException().isThrownBy(() -> JmsResponse.forQueue("foo", null)); } @Test public void createWithNullTopicName() { assertThatIllegalArgumentException().isThrownBy(() -> JmsResponse.forTopic("foo", null)); } @Test public void createWithNulDestination() { assertThatIllegalArgumentException().isThrownBy(() -> JmsResponse.forDestination("foo", null)); } }
package calculator; import java.awt.Color; import java.awt.Font; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.SwingConstants; import javax.swing.border.Border; public class Utils { public static JFrame addFrame (int FRAME_WIDTH, int FRAME_HEIGHT) { JFrame frame = new JFrame("Calculator"); frame.setResizable(false); frame.setSize(FRAME_WIDTH, FRAME_HEIGHT); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); frame.setLayout(null); return frame; } public static JLabel addLabel(JFrame frame, String labelText) { JLabel label1 = new JLabel(); label1.setBounds(125, 0, 369, 80); label1.setOpaque(true); label1.setBackground(Color.WHITE); Border border = BorderFactory.createLineBorder(Color.BLACK, 1); label1.setBorder(border); frame.add(label1); label1.setText(labelText); label1.setHorizontalAlignment(SwingConstants.RIGHT); label1.setVerticalAlignment(SwingConstants.CENTER); label1.setFont(new Font("Dialog", Font.BOLD, 20)); return label1; } public static String numberAction(String text, String number) { if (text.equals("0")) { text = number; return text; } else { text += number; return text; } } public static String operatorAction(String text, String operator) { if(!Character.isDigit(text.charAt(text.length() - 1))) { text = text.substring(0,text.length() - 1); text += operator; return text; } else { text += operator; return text; } } }
package xtrus.user.apps.site.samsung.parser; import org.w3c.dom.Element; import org.w3c.dom.Node; import com.esum.framework.common.util.W3CXMLUtil; public class WOORIACKANSParser extends SamsungParser { public WOORIACKANSParser(Element root) throws Exception { Node node = W3CXMLUtil.selectSingleNode(root, "//*[name()='MessageSenderIdentifier']"); if (node == null) { throw new Exception("XML Node is not exist. (XPath: //*[name()='MessageSenderIdentifier'])"); } this.senderTpId = getTextValue(node); node = W3CXMLUtil.selectSingleNode(root, "//*[name()='MessageReceiverIdentifier']"); if (node == null) { throw new Exception("XML Node is not exist. (XPath: //*[name()='MessageReceiverIdentifier'])"); } this.receiverTpId = getTextValue(node); node = W3CXMLUtil.selectSingleNode(root, "//*[name()='MessageTypeIdentifier']"); if (node == null) { throw new Exception("XML Node is not exist. (XPath: //*[name()='MessageTypeIdentifier'])"); } this.documentName = getTextValue(node); this.documentVersion = "1.0"; node = W3CXMLUtil.selectSingleNode(root, "//*[name()='RelatedDocumentCode']"); if (node == null) { throw new Exception("XML Node is not exist. (XPath: //*[name()='RelatedDocumentCode'])"); } this.refDocumentName = getTextValue(node); node = W3CXMLUtil.selectSingleNode(root, "//*[name()='ProcessingResult']"); if (node == null) { throw new Exception("XML Node is not exist. (XPath: //*[name()='ProcessingResult'])"); } String processingResult = getTextValue(node); this.messageFunctionCode = processingResult.trim().equalsIgnoreCase("Success")?"S":"E"; node = W3CXMLUtil.selectSingleNode(root, "//*[name()='ApplicationAreaMessageIdentifier']"); if (node == null) { throw new Exception("XML Node is not exist. (XPath: //*[name()='ApplicationAreaMessageIdentifier'])"); } this.messageNumber = getTextValue(node); node = W3CXMLUtil.selectSingleNode(root, "//*[name()='ReferenceNumber']"); if (node != null) { this.documentNumber = getTextValue(node); } node = W3CXMLUtil.selectSingleNode(root, "//*[name()='ErrorDescription']"); if (node != null) { this.handlingInformation = getTextValue(node); } if (documentName.equals("ACKANS")) { //ACKANS_EXRADV this.documentName = documentName + "_" + refDocumentName; } else { throw new Exception("[WOORIACKANSParser] This is not ACKANS Message. (MessageTypeIdentifier: "+documentName+")"); } } }
package exemplos.aula10.isp.correto; /** * Exemplo retirado do artigo do Baeldung. * https://www.baeldung.com/solid-principles */ public class CrazyPerson implements BearPetter { public void petTheBear() { //Good luck with that! } }
/** * @(#) Command.java */ package command; import receiver.Buffer; import invoker.IHM; public abstract class Command { protected static final boolean VERBOSE = true; protected Buffer buffer; protected IHM ihm; public abstract void execute(); }
package com.example.cruiseTrip.authentication; import android.content.Context; import android.content.SharedPreferences; public class Session { private SharedPreferences prefs; public Session (Context context) { prefs = context.getSharedPreferences("session", Context.MODE_PRIVATE); } public void setUserId(int userId) { prefs.edit().putInt("user_id", userId).commit(); } public int getUserId() { return prefs.getInt("user_id",0); } public void setUsername(String username) { prefs.edit().putString("username", username).commit(); } public String getUsername() { return prefs.getString("username",""); } public void setPrice(int price) { prefs.edit().putInt("price", price).commit(); } public int getPrice() { return prefs.getInt("price",0); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.controller; import com.entity.Producto; import com.entity.Proveedor; import com.entity.Tienda; import com.services.ProductoServices; import com.services.ProveedorServices; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.AbstractList; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.context.FacesContext; import javax.mail.MessagingException; import javax.servlet.http.Part; import javax.swing.JOptionPane; import net.bootsfaces.utils.FacesMessages; import org.primefaces.model.UploadedFile; /** * * @author DAC-PC */ @ManagedBean @SessionScoped public class ProductoBean { private Producto pro = new Producto(); private Producto productomodificar = new Producto(); ProductoServices ps = new ProductoServices(); ProveedorServices provedorserv = new ProveedorServices(); private ArrayList<Producto> listaproducto = new ArrayList<>(); private String pruebaimg; private String resource; private UploadedFile img; private boolean mostrardetalles = false; private boolean catalogo = true; private Proveedor proveedor = new Proveedor(); private List<Proveedor> listaproveedor= new ArrayList<>(); private long idprove; public ProductoBean() { listar(); listarproveedores(); } public void listarproveedores(){ setListaproveedor(provedorserv.listarproveedor(Obtenertienda())); } public void TransferFile (String fileName , InputStream in){ Rutaimg ruta = new Rutaimg(); try{ Tienda p = Obtenertienda(); String[] a = fileName.split("\\."); String extension = a[1].toLowerCase(); String nombre = a[0]+"."+extension; getPro().setImg(p.getIdTienda()+"/"+a[0]+"."+extension); getPro().setTienda(Obtenertienda()); setProveedor(provedorserv.consultar(Proveedor.class, getIdprove())); getPro().setProveedor(getProveedor()); setIdprove(0); //ps.crear(getPro()); //setPro(new Producto()); OutputStream out = new FileOutputStream ( new File(ruta.getRutaproductos()+p.getIdTienda()+"\\"+nombre)); int reader = 0; byte[] bytes = new byte [(int)getImg().getSize()]; while ((reader = in.read(bytes)) != -1){ out.write(bytes,0,reader); } in.close(); out.flush(); out.close(); } catch(IOException e){ System.out.println(e.getMessage()); } } public void probar(){ JOptionPane.showMessageDialog(null, "ente"); } public void modificardatos(){ String extValidate; if (getImg()!= null){ String ext = getImg().getFileName(); if (ext != null){ extValidate = ext.substring(ext.indexOf(".")+1); } else{ extValidate = "null"; } if (extValidate.equals("jpg")){ try{ TransferFile(getImg().getFileName(),getImg().getInputstream()); ps.crear(getPro()); setPro(new Producto()); listar(); }catch(IOException e){ setPro(new Producto()); } }else{ setPro(new Producto()); } try{ Thread.sleep(2000); }catch(InterruptedException e){} } } public Tienda Obtenertienda(){ Tienda p= (Tienda) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("tienda"); return p; } public void listar(){ setListaproducto((ArrayList<Producto>) ps.listarproducto(Obtenertienda())); } public void verproducto(Long id){ setProductomodificar(ps.verproducto(id)); setMostrardetalles(true); setCatalogo(false); } public void mostrarcatalogo(){ setMostrardetalles(false); setCatalogo(true); } public void modificar(){ try { ps.modificar(getProductomodificar()); setMostrardetalles(false); setCatalogo(true); FacesMessages.info("Actualización exitosa!"); listar(); } catch (Exception e) { FacesMessages.error("No se ha podido modificar este producto, intentelo de nuevo"); } } public ArrayList<Producto> getListaproducto() { return listaproducto; } public void setListaproducto(ArrayList<Producto> listaproducto) { this.listaproducto = listaproducto; } public String getPruebaimg() { return pruebaimg; } public void setPruebaimg(String pruebaimg) { this.pruebaimg = pruebaimg; } public String getResource() { return resource; } public void setResource(String resource) { this.resource = resource; } /* public static void main(String[] args){ ProductoServices ps = new ProductoServices(); long p = ps.ObtenerUltimo(); System.out.println(p); }*/ public UploadedFile getImg() { return img; } public void setImg(UploadedFile img) { this.img = img; } public Producto getPro() { return pro; } public void setPro(Producto pro) { this.pro = pro; } public Producto getProductomodificar() { return productomodificar; } public void setProductomodificar(Producto productomodificar) { this.productomodificar = productomodificar; } public boolean isMostrardetalles() { return mostrardetalles; } public void setMostrardetalles(boolean mostrardetalles) { this.mostrardetalles = mostrardetalles; } public boolean isCatalogo() { return catalogo; } public void setCatalogo(boolean catalogo) { this.catalogo = catalogo; } public Proveedor getProveedor() { return proveedor; } public void setProveedor(Proveedor proveedor) { this.proveedor = proveedor; } public List<Proveedor> getListaproveedor() { return listaproveedor; } public void setListaproveedor(List<Proveedor> listaproveedor) { this.listaproveedor = listaproveedor; } public long getIdprove() { return idprove; } public void setIdprove(long idprove) { this.idprove = idprove; } }
package com.esum.web.ims.sftp.vo; /** * table: SFTP_SVR_INFO * * Copyright(c) eSum Technologies., Inc. All rights reserved. */ public class SftpServerInfo { // primary key private String svrInfoId; // fields private String sftpHostIp; private String sftpHostPort; private String sftpHostkeyPath; private String sftpHostkeyPass; private String useServer; private String useAuthPassword; private String useAuthPublickey; private String maxAuthTries; private String maxConnPerUser; private String useVirtual; private String virtualMaxCount; private String authTimeout; private String idleTimeout; private String regDate; private String modDate; public String getSvrInfoId() { return svrInfoId; } public void setSvrInfoId(String svrInfoId) { this.svrInfoId = svrInfoId; } public String getSftpHostIp() { return sftpHostIp; } public void setSftpHostIp(String sftpHostIp) { this.sftpHostIp = sftpHostIp; } public String getSftpHostPort() { return sftpHostPort; } public void setSftpHostPort(String sftpHostPort) { this.sftpHostPort = sftpHostPort; } public String getSftpHostkeyPath() { return sftpHostkeyPath; } public void setSftpHostkeyPath(String sftpHostkeyPath) { this.sftpHostkeyPath = sftpHostkeyPath; } public String getSftpHostkeyPass() { return sftpHostkeyPass; } public void setSftpHostkeyPass(String sftpHostkeyPass) { this.sftpHostkeyPass = sftpHostkeyPass; } public String getUseServer() { return useServer; } public void setUseServer(String useServer) { this.useServer = useServer; } public String getUseAuthPassword() { return useAuthPassword; } public void setUseAuthPassword(String useAuthPassword) { this.useAuthPassword = useAuthPassword; } public String getUseAuthPublickey() { return useAuthPublickey; } public void setUseAuthPublickey(String useAuthPublickey) { this.useAuthPublickey = useAuthPublickey; } public String getMaxAuthTries() { return maxAuthTries; } public void setMaxAuthTries(String maxAuthTries) { this.maxAuthTries = maxAuthTries; } public String getMaxConnPerUser() { return maxConnPerUser; } public void setMaxConnPerUser(String maxConnPerUser) { this.maxConnPerUser = maxConnPerUser; } public String getUseVirtual() { return useVirtual; } public void setUseVirtual(String useVirtual) { this.useVirtual = useVirtual; } public String getVirtualMaxCount() { return virtualMaxCount; } public void setVirtualMaxCount(String virtualMaxCount) { this.virtualMaxCount = virtualMaxCount; } public String getAuthTimeout() { return authTimeout; } public void setAuthTimeout(String authTimeout) { this.authTimeout = authTimeout; } public String getIdleTimeout() { return idleTimeout; } public void setIdleTimeout(String idleTimeout) { this.idleTimeout = idleTimeout; } public String getRegDate() { return regDate; } public void setRegDate(String regDate) { this.regDate = regDate; } public String getModDate() { return modDate; } public void setModDate(String modDate) { this.modDate = modDate; } }
package ModeloER; import java.util.ArrayList; /** * Classe de entidades * @author Guto Leoni */ public class Entidade{ public String nome; public String intensidade; public ArrayList<AtributoEnt> atributos = new ArrayList<>(); public Entidade() { } public Entidade(String nome, String intensidade) { this.nome = nome; this.intensidade = intensidade; } }
package com.hfjy.framework.message.entity; import java.io.Serializable; import java.util.List; import java.util.Properties; public class EmailInfo implements Serializable { private static final long serialVersionUID = 1L; private String serverHost; private String serverPort = "25"; private String userName; private String password; private String my; private String to; // 收件人 private String title; // 邮件标题 private String data; // 邮件正文 private List<byte[]> attachment; // 附件 private boolean verify = false; private boolean isHTML = false; public Properties getProperties() { Properties p = new Properties(); p.put("mail.smtp.host", serverHost); p.put("mail.smtp.port", serverPort); p.put("mail.smtp.auth", verify ? "true" : "false"); return p; } public EmailInfo(String to, String title, String data) { this.to = to; this.title = title; this.data = data; } public EmailInfo(String to, String title, String data, List<byte[]> attachment) { this.to = to; this.title = title; this.data = data; this.attachment = attachment; } public String getServerHost() { return serverHost; } public void setServerHost(String serverHost) { this.serverHost = serverHost; } public String getServerPort() { return serverPort; } public void setServerPort(String serverPort) { this.serverPort = serverPort; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getMy() { return my; } public void setMy(String my) { this.my = my; } public String getTo() { return to; } public void setTo(String to) { this.to = to; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getData() { return data; } public void setData(String data) { this.data = data; } public List<byte[]> getAttachment() { return attachment; } public void setAttachment(List<byte[]> attachment) { this.attachment = attachment; } public boolean isVerify() { return verify; } public void setVerify(boolean verify) { this.verify = verify; } public boolean isHTML() { return isHTML; } public void setHTML(boolean isHTML) { this.isHTML = isHTML; } }
package factorymethod2; /** * * BankAccountProduct este clasa abstract product care defines * clasele concrete product care sunt create de metodele factory * */ public abstract class BankAccountProduct { public abstract void depositMoney(double depositAmount); public abstract void displayBalance(); public abstract void withdrawMoney(double withdrawAmount); } // class BankAccountProduct
package com.nauka; public class AllFactors { public static void main(String[] args) { printFactors(32); } public static void printFactors(int number) { if (number < 1) { System.out.println("Invalid Value"); } else { int licznik = 0; while ( licznik <= number ) { licznik ++; if (number % licznik == 0) { System.out.println(licznik); } } } } }
package integration.consignas_semana_1; import static org.junit.Assert.assertTrue; import org.junit.Test; import model.Posicion; import model.Tablero; import model.Unidad; import model.error.ErrorPosicionInvalida; import model.personajes.Gohan; import model.personajes.Goku; import model.personajes.modos.GohanNormal; import model.personajes.modos.GokuNormal; public class TestSemana1Consigna03 { @Test (expected = ErrorPosicionInvalida.class) public void test03aNoSePuedeAtravesarUnidadAmistosa() throws ErrorPosicionInvalida { Tablero tablero = new Tablero(20,20); Unidad goku = new Goku(); Unidad gohan = new Gohan(); tablero.agregarUnidad(goku, new Posicion(1,1)); tablero.agregarUnidad(gohan, new Posicion(2,2)); tablero.moverUnidad(goku, new Posicion(3,3)); } @Test (expected = ErrorPosicionInvalida.class) public void test03bNoSePuedeAtravesarUnidadEnemiga() throws ErrorPosicionInvalida { Tablero tablero = new Tablero(20,20); Unidad goku = new Goku(); Unidad gohan = new Gohan(); tablero.agregarUnidad(goku, new Posicion(1,1)); tablero.agregarUnidad(gohan, new Posicion(2,2)); tablero.moverUnidad(goku, new Posicion(3,3)); } }
package calculator; import calculator.stateMachine.TransitionMatrix; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; import java.util.Set; import static calculator.MachineState.*; public class MachineTransitionMatrix implements TransitionMatrix<MachineState> { private static final Map<MachineState, Set<MachineState>> TRANSITIONS = new HashMap<MachineState, Set<MachineState>>() {{ put(START, EnumSet.of(NUMBER, BRACKET_OPEN, FUNCTION)); put(NUMBER, EnumSet.of(BINARY_OPERATOR, SEPARATOR, BRACKET_CLOSE, FINISH)); put(BINARY_OPERATOR, EnumSet.of(NUMBER, FUNCTION, BRACKET_OPEN)); put(FUNCTION, EnumSet.of(BRACKET_OPEN)); put(SEPARATOR, EnumSet.of(NUMBER, BRACKET_OPEN, FUNCTION)); put(BRACKET_OPEN, EnumSet.of(NUMBER, FUNCTION, BRACKET_OPEN, BRACKET_CLOSE)); put(BRACKET_CLOSE, EnumSet.of(BINARY_OPERATOR, SEPARATOR, FINISH, BRACKET_CLOSE)); put(FINISH, EnumSet.noneOf(MachineState.class)); }}; @Override public MachineState getStartState() { return START; } @Override public MachineState getFinishState() { return FINISH; } @Override public Set<MachineState> getPossibleTransitions(MachineState machineState) { return TRANSITIONS.get(machineState); } }
package com.needii.dashboard.dao; import com.needii.dashboard.model.ShippersPriceCombo; import com.needii.dashboard.model.ShippersPriceDay; import com.needii.dashboard.model.ShippersTypeCommissionPerShipping; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.criterion.Property; import org.hibernate.criterion.Restrictions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import java.util.List; /** * @author modani * */ @Repository("shippersTypeCommissionPerShippingDao") public class ShippersTypeCommissionPerShippingDaoImpl extends AbstractDao<Integer, ShippersTypeCommissionPerShipping> implements ShippersTypeCommissionPerShippingDao{ @Autowired private SessionFactory sessionFactory; @Override public List<ShippersTypeCommissionPerShipping> findAll() { Criteria criteria = sessionFactory.getCurrentSession() .createCriteria(ShippersTypeCommissionPerShipping.class) .addOrder(Property.forName("createdAt").desc()); criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); return criteria.list(); } @Override public ShippersTypeCommissionPerShipping findOne(long id) { return (ShippersTypeCommissionPerShipping)sessionFactory.getCurrentSession() .createCriteria(ShippersTypeCommissionPerShipping.class) .add(Restrictions.eq("id", id)) .uniqueResult(); } @Override public void create(ShippersTypeCommissionPerShipping entity) { Session session = sessionFactory.getCurrentSession(); session.persist(entity); } @Override public void update(ShippersTypeCommissionPerShipping entity) { Session session = sessionFactory.getCurrentSession(); session.update(entity); } @Override public void delete(ShippersTypeCommissionPerShipping entity) { Session session = sessionFactory.getCurrentSession(); session.delete(entity); } }
package ir.madreseplus.ui.view; import ir.madreseplus.data.DataManager; import ir.madreseplus.ui.base.BaseViewModel; import ir.madreseplus.utilities.rx.SchedulerProvider; public class MainActivityViewModel extends BaseViewModel<MainActivityNavigator> { public MainActivityViewModel(DataManager mDataManager, SchedulerProvider mSchedulerProvider) { super(mDataManager, mSchedulerProvider); } public void getProfile() { getCompositeDisposable().add( getDataManager().getStudent() .subscribeOn(getSchedulerProvider().io()) .observeOn(getSchedulerProvider().ui()) .subscribe(studentList -> { setIsLoading(false); getNavigator().getProfile(studentList); }, throwable -> { setIsLoading(false); getNavigator().error(throwable); }) ); } }
package OOP; public class InterfaceTest { public static void main(String[] args) { InterfaceClassB b=new InterfaceClassB(); b.I1(); b.I2(); b.I3(); b.I4(); InterfaceA a=new InterfaceClassB(); a.I1(); a.I2(); a.I3(); a.I4(); //InterfaceClassB ifcb=new InterfaceA(); //InterfaceA ia=new InterfaceA(); //4. The interface contains declaration of methods //it says interface is by default abstract then partially implement interface hence for partially implemented interface //object creation is not possible. If we are trying to create object of abstract class //compiler generate error message “Cannot instantiate the type 'Interface name'” } }
package com.lenovohit.hcp.finance.manager; import com.lenovohit.hcp.finance.model.CheckOutDto; import com.lenovohit.hcp.finance.model.OperBalance; /** * * @description 结账统一接口 * @author jatesun * @version 1.0.0 * @date 2017年4月17日 */ public interface CheckOutManager { /** * 获取结账信息 * 1发票来源invoicesource、invoice_oper当前操作工号、invoicetime在结账区间。 * 结账时间取oper_balance的balance——time最大时间,发票人员为invoice_oper * 2费用分类,发票号关联查询oc_invoiceinfo_detail 费用分类fee_code汇总费用 * 3支付方式,发票号关联oc_payway按支付方式汇总支付金额、退费金额。 */ CheckOutDto getCheckOutMsg(String hosId, String invoiceSource, String invoiceOper); /** * 获取已经结账的信息,最近一笔结账的信息 * tip:取oper_balance中未审结的记录(ischeck不为2)。取消结账是查出一笔已结账再取消 * @return */ CheckOutDto getCheckedMsg(String hosId, String invoiceSource, String invoiceOper); /** * 结账 * 界面信息归纳写入收费员结账信息 */ OperBalance checkOut(String hosId, CheckOutDto dto); /** * 取消结账 * 结账id直接删除状态为0未审、1打回的数据 2不允许取消结账 */ void cancelCheckOut(String balanceId); }
package com.leetcode.oj.binarytree; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.List; /** * https://oj.leetcode.com/problems/binary-tree-preorder-traversal/ * http://en.wikipedia.org/wiki/Tree_traversal#Depth-first_2 * * @author flu * */ public class PreOrderTraverse { public List<Integer> preorderTraversal(TreeNode root) { List<Integer> res = new ArrayList<>(); Deque<TreeNode> stack = new ArrayDeque<>(); while (stack.size() > 0 || root != null) { if (root != null) { // visit root, preorder res.add(root.val); // push right child to stack if (root.right != null) stack.push(root.right); // keep going left subtree root = root.left; } else { // node is null, pop one from stack, start visiting right child root = stack.pop(); } } return res; } }
package com.example.sypark9646.item06; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Test; public class InstanceCreationTest { public static int CYCLE = 5500000; @Test public void testRecycleInstance() { long beforeTime = System.currentTimeMillis(); Map<Integer, Boolean> map = new HashMap<>(); for (int i = 0; i < CYCLE; i++) { map.put(i, Boolean.valueOf("true")); } long afterTime = System.currentTimeMillis(); System.out.println("testRecycleInstance 시간차이: " + (afterTime - beforeTime)); // 451 } @Test public void testNewInstance() { long beforeTime = System.currentTimeMillis(); Map<Integer, Boolean> map = new HashMap<>(); for (int i = 0; i < CYCLE; i++) { map.put(i, new Boolean("true")); } long afterTime = System.currentTimeMillis(); System.out.println("testNewInstance 시간차이: " + (afterTime - beforeTime)); // 520 } }
package space.oldtaoge.audioserver.entity; import lombok.Data; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.time.Duration; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; import java.util.HashMap; import java.util.Map; @Data @Component public class PlayerEntity { private static final PlayerEntity instance = new PlayerEntity(); private Map<String, Client> CliRegister; @Data public static class Client { private boolean areConnect = false; private LocalDateTime lastKA; } @Scheduled(cron = "*/5 * * * * ?") public static void checkOnline() { // System.out.println("TimeTask"); LocalDateTime ndt = LocalDateTime.now(); PlayerEntity.getInstance().getCliRegister().forEach((k, v) -> { if (v.lastKA == null) { v.areConnect = false; } else { v.areConnect = v.lastKA.until(ndt, ChronoUnit.SECONDS) < 60; // v.areConnect = Duration.between(ndt, v.lastKA).toSeconds() < 60; } }); } public static PlayerEntity getInstance() { if (instance.getCliRegister() == null) { var tmpM = new HashMap<String, Client>(); tmpM.put("bd7dcd8c-c000-4967-bede-9fdd42e60cba", new Client()); instance.setCliRegister(tmpM); } return instance; } }
package org.auroraide.server.fileDownloader; import java.io.DataInputStream; import java.io.IOException; import java.util.List; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.ByteArrayInputStream; import org.auroraide.server.database.File; public class FileDownloadServlet extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{ String name=req.getParameter("name"); String project=req.getParameter("project"); String pkg=req.getParameter("pkg"); //pout a filename //String filename="A.class"; //bytes = any byte[] you want to send //byte[] bytes="".getBytes(); //read the query string //String q=req.getQueryString(); byte[] bytes=null; File file=null; try{ //read class file from the database file=new File(); List<?> files=file.loadAll(new String[] {"name","project","pkg"}, new Object[] {name,project,pkg}); file=(File)files.get(0); long length=file.compiled.length(); bytes=file.compiled.getBytes(1, (int)length); } catch(Exception ex){ ex.printStackTrace(); } int length = 0; ServletOutputStream op = res.getOutputStream(); ServletContext context = getServletConfig().getServletContext(); String mimetype = context.getMimeType( file.name ); // // Set the response and go! // // if(bytes==null) return; res.setContentType( (mimetype != null) ? mimetype : "application/octet-stream" ); res.setContentLength( bytes.length ); res.setHeader( "Content-Disposition", "attachment; filename=\"" + file.name + ".class\"" ); // // Stream to the requester. // byte[] bbuf = new byte[bytes.length]; DataInputStream in = new DataInputStream(new ByteArrayInputStream(bytes)); while ((in != null) && ((length = in.read(bbuf)) != -1)) { op.write(bbuf,0,length); } in.close(); op.flush(); op.close(); } }
package com.dmeo.composite.file; /** * @author: Maniac Wen * @create: 2020/5/22 * @update: 8:26 * @version: V1.0 * @detail: **/ public abstract class Directory { protected String name; public Directory(String name){ this.name = name; } public abstract void show(); }
// Allen Boynton // JAV1 - 1703 // PersonsAdapter.java package edu.fullsail.aboynton.boyntonallen_ce06; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; import edu.fullsail.aboynton.boyntonallen_ce06.Object.Person; class PersonsAdapter extends BaseAdapter { private final Context context; private ArrayList<Person> personList = new ArrayList<>(); PersonsAdapter(Context context, ArrayList<Person> personList) { this.context = context; this.personList = personList; } @Override public int getCount() { if (personList.size() > 0) { return this.personList.size(); } return 0; } @Override public Object getItem(int pos) { return personList.get(pos); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = LayoutInflater.from(context).inflate(R.layout.gridview_base, parent, false); holder = new ViewHolder(convertView); convertView.setTag(holder); } else { holder = (ViewHolder)convertView.getTag(); } //Display photo, name, and birth date in TextView widget Person person = personList.get(position); holder.nameText.setText(person.getName()); holder.birthdayText.setText(person.getBirthday()); holder.picture.setImageResource(person.getPictureIds()); return convertView; } // Keep all Images in array final Integer[] pictureIds = {R.drawable.gw, R.drawable.ja, R.drawable.tj, R.drawable.jm, R.drawable.jm2, R.drawable.jqa, R.drawable.aj, R.drawable.mvb, R.drawable.wh, R.drawable.dt }; @Override public boolean areAllItemsEnabled() { return false; } @Override public boolean isEnabled(int pos) { return false; } private static class ViewHolder { // Views in the item layout private TextView nameText; private TextView birthdayText; private ImageView picture; /** Unable to get name and birthday elements into viewHolder. I followed your * FS MDV JAV1 Custom Adapter video but it would not work for me in this case. */ // Parameters from Person class ViewHolder(View view) { nameText = (TextView) view.findViewById(R.id.grid_item_name); birthdayText = (TextView) view.findViewById(R.id.grid_item_birthday); picture = (ImageView) view.findViewById(R.id.grid_item_picture); } } }
package im.compIII.exghdecore.banco; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Collection; import im.compIII.exghdecore.entidades.Ambiente; import im.compIII.exghdecore.entidades.Contrato; import im.compIII.exghdecore.exceptions.CampoVazioException; import im.compIII.exghdecore.exceptions.ConexaoException; import im.compIII.exghdecore.exceptions.RelacaoException; public class ContratoDB { public final long salvar(Contrato contrato) throws ConexaoException, SQLException, ClassNotFoundException, NumberFormatException, RelacaoException { Conexao.initConnection(); long id = 0; String sql = "INSERT INTO contrato (COMISSAO) VALUES(?);"; PreparedStatement psmt = Conexao.prepare(sql); psmt.setFloat(1, contrato.getComissao()); int linhasAfetadas = psmt.executeUpdate(); if (linhasAfetadas == 0) { throw new ConexaoException(); } ResultSet generatedKeys = psmt.getGeneratedKeys(); if (generatedKeys.next()) { id = generatedKeys.getLong(1); } else { Conexao.rollBack(); Conexao.closeConnection(); throw new SQLException(); } Conexao.commit(); Conexao.closeConnection(); return id; } public final void atualizar(Contrato contrato) throws ConexaoException, SQLException, ClassNotFoundException, NumberFormatException, RelacaoException { Conexao.initConnection(); String sql = "UPDATE CONTRATO SET COMISSAO = ? WHERE CONTRATOID = " + contrato.getId(); PreparedStatement psmt = Conexao.prepare(sql); psmt.setFloat(1, contrato.getComissao()); int linhasAfetadas = psmt.executeUpdate(); if (linhasAfetadas == 0) { Conexao.rollBack(); Conexao.closeConnection(); throw new ConexaoException(); }else{ Conexao.commit(); Conexao.closeConnection(); } } public static Collection<Contrato> listarTodos(Collection<Long> ids) throws ConexaoException, SQLException, ClassNotFoundException { Conexao.initConnection(); String sql = "SELECT * FROM CONTRATO C JOIN AMBIENTE A where C.CONTRATOID = A.CONTRATOID order by C.CONTRATOID;"; Statement psmt = Conexao.prepare(); ResultSet result = psmt.executeQuery(sql); ArrayList<Contrato> list = new ArrayList<Contrato>(); Contrato contrato = null; while(result.next()) { float comissao = result.getFloat("COMISSAO"); long ambienteId = result.getLong("AMBIENTEID"); Ambiente ambiente = AmbienteDB.buscar(ambienteId); if (!ids.contains(result.getLong("CONTRATOID"))) { ids.add(result.getLong("CONTRATOID")); try { ArrayList<Ambiente> ambientes = new ArrayList<Ambiente>(); ambientes.add(ambiente); contrato = new Contrato(comissao); } catch (CampoVazioException e) { e.printStackTrace(); continue; } list.add(contrato); }else if (contrato != null){ //contrato.getAmbientes().add(ambiente); } } Conexao.closeConnection(); return list; } public final static Contrato buscar(long id) throws ConexaoException, SQLException, ClassNotFoundException { Conexao.initConnection(); String sql = "SELECT * FROM CONTRATO C JOIN AMBIENTE A where C.CONTRATOID = A.CONTRATOID AND C.CONTRATOID = " + id + " order by C.CONTRATOID;"; Statement psmt = Conexao.prepare(); ResultSet result = psmt.executeQuery(sql); ArrayList<Contrato> list = new ArrayList<Contrato>(); Contrato contrato = null; ArrayList<Ambiente> ambientes = new ArrayList<Ambiente>(); float comissao = 0; while(result.next()) { comissao = result.getFloat("COMISSAO"); long ambienteId = result.getLong("AMBIENTEID"); Ambiente ambiente = AmbienteDB.buscar(ambienteId); ambientes.add(ambiente); list.add(contrato); } try { contrato = new Contrato(comissao); contrato.setAmbientes(ambientes); } catch (CampoVazioException e) { e.printStackTrace(); } Conexao.closeConnection(); return contrato; } }
package com.rharo.jpastreamer.service; import java.util.List; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.rharo.jpastreamer.dto.CarDto; import com.rharo.jpastreamer.interfaces.CarService; import com.rharo.jpastreamer.model.Car; import com.rharo.jpastreamer.service.mapper.CarMapper; import com.speedment.jpastreamer.application.JPAStreamer; @Service public class CarServiceImpl implements CarService { @Autowired private JPAStreamer jpaStreamer; @Autowired private CarMapper carMapper; @Override public List<CarDto> findAll() { List<Car> carList = jpaStreamer.stream(Car.class).collect(Collectors.toList()); return carMapper.convertToDto(carList); } @Override public CarDto findById(Long id) { Car car = jpaStreamer.stream(Car.class).filter(item -> item.getId().equals(id)).findFirst().orElseThrow(); return carMapper.convertToDto(car); } }
package assignment4; import java.util.Scanner; public class Question28 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); Question28 obj = new Question28(); System.out.println("To check either the given number is prime or not"); System.out.print("\nEnter the number: "); int number = sc.nextInt(); boolean check = obj.isPrimeNumber(number); String print = (check) ? "\nGiven number is PRIME": "\ngiven number is NOT PRIME"; System.out.println(print); System.out.println("To print first nth prime numbers"); System.out.print("\nEnter the number: "); int num =sc.nextInt(); System.out.println("\nThe Prime numbers upto " + num + " are: \n"); obj.firstNthPrime(num); System.out.println("To Print all prime between given two numbers"); System.out.print("\nEnter first number: "); int first = sc.nextInt(); System.out.print("\nEnter second number: "); int second = sc.nextInt(); System.out.println("\nPrime number between " + first + " and "+ second + " are: \n"); obj.allPrimeBetween(first, second); sc.close(); } public boolean isPrimeNumber(int a) { if (a >0 && a <=2) return true; if(a == 0) return false; for (int i=2; i< a; i++) { if (a%i == 0) return false; } return true; } public void firstNthPrime(int a) { for (int i=1; i< a; i++) { if(isPrimeNumber(i)) System.out.print(i + " "); } } public void allPrimeBetween(int a, int b) { for (int i=a; i<b; i++) { if(isPrimeNumber(i)) System.out.print(i + " "); } } }
package com.infnet.at; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ProdutoCotacaoApplication { public static void main(String[] args) { SpringApplication.run(ProdutoCotacaoApplication.class, args); } }
package TestCase; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.AbstractMap.SimpleEntry; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ReadTestCases { // ArrayList<TestCaseFragments> testCaseData = new ArrayList<>(); ArrayList<TestCaseGroup> testCaseGroup; public ReadTestCases() { // Pattern pattern1 = Pattern.compile("\\(By.(.*?)\\(\"(.*?)\"\\)\\).(.*?)\\(\"(.*?)\"\\)"); testCaseGroup = new ArrayList<TestCaseGroup>(); } public ReadTestCases(ArrayList<TestCaseGroup> tcg) { if(tcg == null) tcg = new ArrayList<TestCaseGroup>(); testCaseGroup = tcg; } public ArrayList<TestCaseGroup> findFragments(File testCaseFile) { TestCaseGroup tg = new TestCaseGroup(); testCaseGroup.add(tg); TestCase tc = new TestCase(); tg.getTestCases().add(tc); try { BufferedReader br = new BufferedReader(new FileReader(testCaseFile)); String line = null; int lineNo = 0; while((line = br.readLine()) != null) { TestCaseFragment testCaseFragment = new TestCaseFragment(); Pattern pattern, pattern1, pattern2; Matcher matcher, matcher1, matcher2; testCaseFragment.setLineNo(++lineNo); System.out.print(lineNo + " "); pattern = Pattern.compile("\\bBy.(.*?)\\(\"(.*?)\"\\)"); matcher = pattern.matcher(line); if (matcher.find()) { System.out.print(matcher.group(1) + "=" + matcher.group(2) + " | "); SimpleEntry<String, String> findBy = new SimpleEntry<String, String>(matcher.group(1), matcher.group(2)); // testCaseFragment.setFindBy(findBy.getKey(), findBy.getValue()); testCaseFragment.setFindBy(findBy); } pattern1 = Pattern.compile("\\bBy.(.*?)\\(\"(.*?)\"\\)\\).(.*?)\\("); matcher1 = pattern1.matcher(line); if (matcher1.find()) { System.out.print(matcher1.group(3) + "="); if(!matcher1.group(3).equals("click")) { pattern2 = Pattern.compile("\\bBy.(.*?)\\(\"(.*?)\"\\)\\).(.*?)\\(\"(.*?)\"\\)"); matcher2 = pattern2.matcher(line); if (matcher2.find()) { System.out.print(matcher2.group(4)); SimpleEntry<String, String> operation = new SimpleEntry<String, String>(matcher2.group(3), matcher2.group(4)); testCaseFragment.setOperation(operation); } } else { SimpleEntry<String, String> operation = new SimpleEntry<String, String>(matcher1.group(3), null); testCaseFragment.setOperation(operation); } } System.out.println(); // testCaseFragment.display(); tc.getTestCaseFragments().add(testCaseFragment); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return testCaseGroup; } public ArrayList<TestCaseGroup> getTestCaseGroup() { return testCaseGroup; } public void setTestCaseGroup(ArrayList<TestCaseGroup> testCaseGroup) { this.testCaseGroup = testCaseGroup; } }
package com.lenovohit.hwe.mobile.core.web.rest; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.repository.RepositoryDefinition; import org.springframework.instrument.classloading.ResourceOverridingShadowingClassLoader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.lenovohit.core.manager.GenericManager; import com.lenovohit.core.utils.JSONUtils; import com.lenovohit.core.utils.StringUtils; import com.lenovohit.core.web.MediaTypes; import com.lenovohit.core.web.utils.Result; import com.lenovohit.core.web.utils.ResultUtils; import com.lenovohit.hwe.mobile.core.model.Disease; import com.lenovohit.hwe.mobile.core.model.Symptom; import com.lenovohit.hwe.treat.model.Profile; /** * 工具---病症查询 * @author redstar * */ @RestController @RequestMapping("hwe/app/triage") public class SymptomRestController extends MobileBaseRestController { @Autowired private GenericManager<Symptom, String> symptomManager; @Autowired private GenericManager<Disease, String> diseaseManager; // @Autowired // private GenericManager<Classification, String> classificationManager; //查找某一个身体部位对应的大病症 @RequestMapping(value = "/listBigSymptomsByPartId", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) public Result listBigSymptomsByPartId(@RequestParam(value = "data", defaultValue = "") String data) { Symptom model = JSONUtils.deserialize(data, Symptom.class); String gender = model.getGender() == "0" ? "F" : "M"; List<Symptom> symptoms = new ArrayList<Symptom>(); String sql = "SELECT symptom_id, symptom_name, ( SELECT count( * ) FROM APP_SYMPTOM WHERE parent_symptom_id = a.symptom_id ) " + "from APP_SYMPTOM a " + "where part_id = " + model.getPartId() + " and (gender='A' or gender='" + gender + "') and min_age <= " + model.getMinAge() + " and max_age >= " + model.getMaxAge(); List<?> list = this.symptomManager.findBySql(sql); for (Object obj : list) { Object[] objects = (Object[]) obj; Symptom symptom = new Symptom(); symptom.setSymptomId(Object2String(objects[0])); symptom.setSymptomName(Object2String(objects[1])); symptom.setChildSymptomCount(Integer.parseInt(Object2String(objects[2]))); symptoms.add(symptom); } return ResultUtils.renderSuccessResult(symptoms); } //查找某一个身体部位对应的大病症 @RequestMapping(value = "/listSmallSymptomsByBigSymptomId", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) public Result listSmallSymptomsByBigSymptomId(@RequestParam(value = "data", defaultValue = "") String data) { Symptom model = JSONUtils.deserialize(data, Symptom.class); List<Object> values=new ArrayList<Object>(); String jql="from Symptom where parentSymptomId = ? "; values.add(model.getParentSymptomId()); List<Symptom> symptoms=(List<Symptom>) symptomManager.findByJql(jql, values.toArray()); return ResultUtils.renderSuccessResult(symptoms); } //查找病症对应的疾病 @RequestMapping(value = "/listDiseasesBySymptomIds", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) public Result listDiseasesBySymptomIds(@RequestParam(value = "data", defaultValue = "") String data) { Symptom model = JSONUtils.deserialize(data, Symptom.class); String symptomIds = model.getSymptomId(); Map<String, Disease> diseases = new HashMap<String,Disease>(); Map<String, Double> diseasePresents = new HashMap<String, Double>(); String sql = "SELECT c.DISEASE_ID, c.DISEASE_NAME, a.CORRELATION_DEGREE,c.dept_name, " + "c.summary, c.pathogeny, c.symptom, c.disease_check, c.identify, c.prevention, " + "c.complication, c.treatment " + "FROM APP_SADR a,APP_SYMPTOM b,APP_DISEASE c " + "WHERE a.symptoms_id = b.symptom_id AND a.disease_id = c.disease_id " + "AND b.symptom_id in (" + symptomIds + ")" ; List<?> list = this.symptomManager.findBySql(sql); for (Object obj : list) { Object[] objects = (Object[]) obj; Disease curDisease = new Disease(); String curDiseaseId = Object2String(objects[0]); String curDiseaseName = Object2String(objects[1]); Double curDiseasePresent = Object2Double(objects[2]); curDisease.setDiseaseId(curDiseaseId); curDisease.setDiseaseName(curDiseaseName); curDisease.setDeptName(Object2String(objects[3])); curDisease.setSummary(Object2String(objects[4])); curDisease.setPathogeny(Object2String(objects[5])); curDisease.setSymptom(Object2String(objects[6])); curDisease.setDiseaseCheck(Object2String(objects[7])); curDisease.setIdentify(Object2String(objects[8])); curDisease.setPrevention(Object2String(objects[9])); curDisease.setComplication(Object2String(objects[10])); curDisease.setTreatment(Object2String(objects[11])); diseases.put(curDiseaseId, curDisease); if (diseasePresents.containsKey(curDiseaseId)) { diseasePresents.put(curDiseaseId, 1 - (1 - diseasePresents.get(curDiseaseId)) * (1 - curDiseasePresent)); } else { diseasePresents.put(curDiseaseId, curDiseasePresent); } } ArrayList<Disease> resDisease = new ArrayList<Disease>(); for (Map.Entry<String, Double> entry : diseasePresents.entrySet()) { int idx = 0; double curPresent = entry.getValue(); for (idx = 0; idx < resDisease.size(); idx++) { if (diseasePresents.get(resDisease.get(idx).getDiseaseId()) <= curPresent) { break; } } // 最多只返回10条疾病数据 if (idx == 10) { continue; } resDisease.add(idx, diseases.get(entry.getKey())); if (resDisease.size() > 10) { resDisease.remove(10); } } return ResultUtils.renderSuccessResult(resDisease); } // //查找大病症对应的小病症 // @RequestMapping(value = "/listSmallSymptomsByBigSymptomsId", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) // public Result listSmallSymptomsByBigSymptomsId(@RequestParam(value = "data", defaultValue = "") String data) { // Symptom model = JSONUtils.deserialize(data, Symptom.class); // List<Object> values=new ArrayList<Object>(); // String jql="from Symptom where bodyId like = ? "; // values.add("%" + model.getPartId() + "%"); // List<Symptom> symptoms=(List<Symptom>) SymptomManager.findByJql(jql, values.toArray()); // return ResultUtils.renderSuccessResult(symptoms); // } // // //查找化验单子分类 // @RequestMapping(value = "/listSecondLevelTest", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) // public Result listCommonDisease(@RequestParam(value = "data", defaultValue = "") String data) { // Classification model = JSONUtils.deserialize(data, Classification.class); // List<Object> values=new ArrayList<Object>(); // values.add(model.getParentNode()); // String jql="from Classification where classType = 3 and parentNode = ? "; // List<Classification> dicts=classificationManager.find(jql,values.toArray()); // return ResultUtils.renderSuccessResult(dicts); // } // //根据关键字搜索急救方法 // @RequestMapping(value = "/listByKeyWords", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) // public Result listByKeyWords(@RequestParam(value = "data", defaultValue = "") String data) { // Symptom model = JSONUtils.deserialize(data, Symptom.class); // List<Object> values=new ArrayList<Object>(); // String jql="from Symptom where laboratoryName like ? "; // values.add("%" + model.getSymptomName() + "%"); // List<Symptom> laboratory=(List<Symptom>) laboratoryManager.findByJql(jql, values.toArray()); // return ResultUtils.renderSuccessResult(laboratory); // } // //根据化验单类型搜索化验单明细 // @RequestMapping(value = "/listSymptomByType", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) // public Result listEmergencyByType(@RequestParam(value = "data", defaultValue = "") String data) { // Classification model = JSONUtils.deserialize(data, Classification.class); // String jql="from Symptom where classificationId = ? "; // List<Object> values=new ArrayList<Object>(); // values.add(model.getParentNode().trim()); // //c=emergencyManager.findByProp("classificationId", model.getClassificationId()); // List<Symptom> laboratory=(List<Symptom>) laboratoryManager.findByJql(jql, values.toArray()); // return ResultUtils.renderSuccessResult(laboratory); // } public String Object2String(Object object){ if(object == null){ return ""; } return object.toString(); } public Double Object2Double(Object object){ if(object == null){ return 0.0; } return Double.parseDouble(object.toString()); } }
package com.mesilat.gadget; import java.util.ResourceBundle; public class DefaultGenerator implements SQLGenerator { protected String sql1; protected String sql2; protected String sql3; protected String sql4; protected String sql5; @Override public String getQueryOne() { return sql1; } @Override public String getQueryTwo() { return sql2; } @Override public String getQueryTotalWorklog(){ return sql3; } @Override public String getQueryReport() { return sql4; } @Override public String getQueryUserName() { return sql5; } public DefaultGenerator(){ this("default"); } public DefaultGenerator(String bundleName){ ResourceBundle bundle = ResourceBundle.getBundle(bundleName); sql1 = bundle.getString("com.mesilat.week-load.sql1"); sql2 = bundle.getString("com.mesilat.week-load.sql2"); sql3 = bundle.getString("com.mesilat.week-load.sql3"); sql4 = bundle.getString("com.mesilat.week-load.sql4"); sql5 = bundle.getString("com.mesilat.week-load.sql5"); } }
package com.taim.backendservice.model.basemodels; import lombok.Data; import org.springframework.data.annotation.CreatedBy; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; import javax.persistence.*; import java.util.Date; /** * Created by Tjin on 7/20/2017. */ @MappedSuperclass @Data @EntityListeners(AuditingEntityListener.class) public class BaseModel { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private long id; @Temporal(TemporalType.TIMESTAMP) @Column(name = "date_created" ,nullable = false) @CreatedDate private Date dateCreated; @Temporal(TemporalType.TIMESTAMP) @Column(name = "date_modified" ,nullable = false) @LastModifiedDate private Date dateModified; @Column(nullable = false) private boolean deleted; }
package ufc.ia.cvts.main; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Random; import ufc.ia.cvts.entity.Caminho; import ufc.ia.cvts.entity.Cidade; import ufc.ia.cvts.util.ManipuladorArquivos; import ufc.ia.cvts.util.Operacao; import ufc.ia.cvts.util.TipoOperacao; public class Main { public static int QUTD_PONTOS = 15; public static ManipuladorArquivos mArq = new ManipuladorArquivos(); public static double fTemp1 = 500; public static double fTemp2 = 1000; public static double fTemp3 = 1500; public static double sResfri1 = 0.999999; public static double sResfri2 = 0.000001; public static Random randomNumber; public static void main(String[] args) { randomNumber = new Random(); //mArq.gerarPontos(QUTD_PONTOS); Caminho caminhoSimulacao = new Caminho(mArq.carregar()); Caminho melhorCaminhoSimulacao = new Caminho(caminhoSimulacao.getCaminho()); int debug = 1; System.out.println(debug++); simulacaoTempera(fTemp1,sResfri1,caminhoSimulacao,TipoOperacao.OP1,5,9); caminhoSimulacao = new Caminho(mArq.carregar()); System.out.println(debug++); simulacaoTempera(fTemp2,sResfri1,caminhoSimulacao,TipoOperacao.OP1,5,9); caminhoSimulacao = new Caminho(mArq.carregar()); System.out.println(debug++); simulacaoTempera(fTemp3,sResfri1,caminhoSimulacao,TipoOperacao.OP1,5,9); caminhoSimulacao = new Caminho(mArq.carregar()); System.out.println(debug++); simulacaoTempera(fTemp1,sResfri1,caminhoSimulacao,TipoOperacao.OP2,5,9); caminhoSimulacao = new Caminho(mArq.carregar()); System.out.println(debug++); simulacaoTempera(fTemp2,sResfri1,caminhoSimulacao,TipoOperacao.OP2,5,9); caminhoSimulacao = new Caminho(mArq.carregar()); System.out.println(debug++); simulacaoTempera(fTemp3,sResfri1,caminhoSimulacao,TipoOperacao.OP2,5,9); caminhoSimulacao = new Caminho(mArq.carregar()); System.out.println(debug++); simulacaoTempera(fTemp1,sResfri2,caminhoSimulacao,TipoOperacao.OP1,5,9); caminhoSimulacao = new Caminho(mArq.carregar()); System.out.println(debug++); simulacaoTempera(fTemp2,sResfri2,caminhoSimulacao,TipoOperacao.OP1,5,9); caminhoSimulacao = new Caminho(mArq.carregar()); System.out.println(debug++); simulacaoTempera(fTemp3,sResfri2,caminhoSimulacao,TipoOperacao.OP1,5,9); caminhoSimulacao = new Caminho(mArq.carregar()); System.out.println(debug++); simulacaoTempera(fTemp1,sResfri2,caminhoSimulacao,TipoOperacao.OP2,5,9); caminhoSimulacao = new Caminho(mArq.carregar()); System.out.println(debug++); simulacaoTempera(fTemp2,sResfri2,caminhoSimulacao,TipoOperacao.OP2,5,9); caminhoSimulacao = new Caminho(mArq.carregar()); System.out.println(debug++); simulacaoTempera(fTemp3,sResfri2,caminhoSimulacao,TipoOperacao.OP2,5,9); } public static String getCurrentTime() { Calendar cal1 = Calendar.getInstance(); SimpleDateFormat sdf1 = new SimpleDateFormat("HH:mm:ss.SSS"); String t1 = sdf1.format(cal1.getTime()).toString(); return t1; } public static void simulacaoTempera(double tempera, double resfriamento, Caminho caminho, TipoOperacao tipoOperacao, int inicio, int fim) { System.out.println("Caminho Inicial: \t" + caminho.getDistanciaTotal()); String t1 = getCurrentTime(); Operacao op = new Operacao(inicio, fim, tipoOperacao); op.operacaoShufle(caminho); Caminho melhorCaminho = new Caminho(caminho.getCaminho()); while (tempera > 1) { Caminho novaSolucao = new Caminho(caminho.getCaminho()); int posicaoA = Cidade.RandomIntFaixa(0, caminho.getCaminho().size()); int posicaoB = Cidade.RandomIntFaixa(0, caminho.getCaminho().size()); Cidade cidadeA = novaSolucao.getCidade(posicaoA); Cidade cidadeB = novaSolucao.getCidade(posicaoB); novaSolucao.getCaminho().set(posicaoB, cidadeA); novaSolucao.getCaminho().set(posicaoA, cidadeB); double distanciaAtual = caminho.getDistanciaTotal(); double distanciaVizinhanca = novaSolucao.getDistanciaTotal(); double random = randomNumber.nextDouble(); if(Cidade.calculaProbabilidade(distanciaAtual, distanciaVizinhanca, tempera) > random){ caminho = new Caminho(caminho.getCaminho()); } if(caminho.getDistanciaTotal() < melhorCaminho.getDistanciaTotal()){ melhorCaminho = new Caminho(caminho.getCaminho()); } tempera *= resfriamento; } String t2 = getCurrentTime(); System.out.println("Tempo t1:\t\t" + t1 ); System.out.println("Tempo t2:\t\t" + t2 ); melhorCaminho.getCidade(0).setNome("INI"); melhorCaminho.getCidade(QUTD_PONTOS-1).setNome("FIM"); System.out.println("Caminho Otimizado: \t" + melhorCaminho.getDistanciaTotal()); mArq.escreverResultado(cidadesToJS(melhorCaminho.getCaminho())); } //Mapeia os nos (cidades) e escreve o diagrama public static String cidadesToJS (ArrayList<Cidade> listaCidades){ String nodesHTML = ""; for (int i = 0; i < listaCidades.size(); i++) { nodesHTML += "{name: '"+listaCidades.get(i).getNome()+"', " + "row: "+listaCidades.get(i).getX()+" , " + "column: "+listaCidades.get(i).getY()+", connectsTo: " + "'"+listaCidades.get(i+1).getNome()+"'},"; if(i == listaCidades.size()-2){ nodesHTML += "{name: '"+listaCidades.get(i+1).getNome()+"', " + "row: "+listaCidades.get(i+1).getX()+" , " + "column: "+listaCidades.get(i+1).getY()+", " + "connectsTo: '"+listaCidades.get(0).getNome()+"'}"; break; } } return nodesHTML; } }
import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TreeMap; public class KClosetPoints { public static int[][] kClosest(int[][] points, int K) { Map<Double, List<List<Integer>>> distMap = new TreeMap<>(); for (int[] arr : points) { int x = arr[0]; int y = arr[1]; double dist = Math.sqrt(y * y + x * x); if (!distMap.containsKey(dist)) distMap.put(dist, new ArrayList<>()); List<Integer> tempList = new ArrayList<>(); tempList.add(x); tempList.add(y); distMap.get(dist).add(tempList); } int[][] result = new int[K][2]; int count = 0; for (double d : distMap.keySet()) { for (List<Integer> l : distMap.get(d)) { if (count > K - 1) break; result[count][0] = l.get(0); result[count][1] = l.get(1); count++; } } return result; } public static void main(String[] args) { int[][] points = {{1, 3}, {-2, 2}}; int[][] result = kClosest(points, 1); for (int[] a : result) { System.out.print(a[0] + "," + a[1]); System.out.println(); } } }
/* * Copyright (c) 2009-2010 David Grant * Copyright (c) 2010 ThruPoint Ltd * * 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 org.jscep.server; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.Writer; import java.math.BigInteger; import java.security.GeneralSecurityException; import java.security.PrivateKey; import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509CRL; import java.security.cert.X509Certificate; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Set; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.spongycastle.asn1.cms.IssuerAndSerialNumber; import org.spongycastle.asn1.x500.X500Name; import org.spongycastle.cert.X509CertificateHolder; import org.spongycastle.cert.jcajce.JcaCRLStore; import org.spongycastle.cert.jcajce.JcaCertStore; import org.spongycastle.cms.CMSAbsentContent; import org.spongycastle.cms.CMSException; import org.spongycastle.cms.CMSSignedData; import org.spongycastle.cms.CMSSignedDataGenerator; import org.spongycastle.cms.SignerInfoGenerator; import org.spongycastle.cms.SignerInfoGeneratorBuilder; import org.spongycastle.operator.ContentSigner; import org.spongycastle.operator.DigestCalculatorProvider; import org.spongycastle.operator.jcajce.JcaContentSignerBuilder; import org.spongycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder; import org.spongycastle.pkcs.PKCS10CertificationRequest; import org.spongycastle.util.Store; import org.spongycastle.util.encoders.Base64; import org.jscep.asn1.IssuerAndSubject; import org.jscep.message.CertRep; import org.jscep.message.MessageDecodingException; import org.jscep.message.MessageEncodingException; import org.jscep.message.PkcsPkiEnvelopeDecoder; import org.jscep.message.PkcsPkiEnvelopeEncoder; import org.jscep.message.PkiMessage; import org.jscep.message.PkiMessageDecoder; import org.jscep.message.PkiMessageEncoder; import org.jscep.transaction.FailInfo; import org.jscep.transaction.MessageType; import org.jscep.transaction.Nonce; import org.jscep.transaction.OperationFailureException; import org.jscep.transaction.TransactionId; import org.jscep.transport.request.Operation; import org.jscep.transport.response.Capability; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class provides a base Servlet which can be extended using the abstract * methods to implement a SCEP CA (or RA). */ public abstract class ScepServlet extends HttpServlet { private static final String GET = "GET"; private static final String POST = "POST"; private static final String MSG_PARAM = "message"; private static final String OP_PARAM = "operation"; private static final Logger LOGGER = LoggerFactory .getLogger(ScepServlet.class); /** * Serialization ID */ private static final long serialVersionUID = 1L; /** * {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public final void service(final HttpServletRequest req, final HttpServletResponse res) throws ServletException, IOException { byte[] body = getMessageBytes(req); final Operation op; try { op = getOperation(req); if (op == null) { // The operation parameter must be set. res.setStatus(HttpServletResponse.SC_BAD_REQUEST); Writer writer = res.getWriter(); writer.write("Missing \"operation\" parameter."); writer.flush(); return; } } catch (IllegalArgumentException e) { // The operation was not recognised. res.setStatus(HttpServletResponse.SC_BAD_REQUEST); Writer writer = res.getWriter(); writer.write("Invalid \"operation\" parameter."); writer.flush(); return; } LOGGER.debug("Incoming Operation: " + op); final String reqMethod = req.getMethod(); if (op == Operation.PKI_OPERATION) { if (!reqMethod.equals(POST) && !reqMethod.equals(GET)) { // PKIOperation must be sent using GET or POST res.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); res.addHeader("Allow", GET + ", " + POST); return; } } else { if (!reqMethod.equals(GET)) { // Operations other than PKIOperation must be sent using GET res.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); res.addHeader("Allow", GET); return; } } LOGGER.debug("Method " + reqMethod + " Allowed for Operation: " + op); if (op == Operation.GET_CA_CAPS) { try { LOGGER.debug("Invoking doGetCaCaps"); doGetCaCaps(req, res); } catch (Exception e) { throw new ServletException(e); } } else if (op == Operation.GET_CA_CERT) { try { LOGGER.debug("Invoking doGetCaCert"); doGetCaCert(req, res); } catch (Exception e) { throw new ServletException(e); } } else if (op == Operation.GET_NEXT_CA_CERT) { try { LOGGER.debug("Invoking doGetNextCaCert"); doGetNextCaCert(req, res); } catch (Exception e) { throw new ServletException(e); } } else if (op == Operation.PKI_OPERATION) { // PKIOperation res.setHeader("Content-Type", "application/x-pki-message"); CMSSignedData sd; try { sd = new CMSSignedData(body); } catch (CMSException e) { throw new ServletException(e); } Store reqStore = sd.getCertificates(); Collection<X509CertificateHolder> reqCerts = reqStore .getMatches(null); CertificateFactory factory; try { factory = CertificateFactory.getInstance("X.509"); } catch (CertificateException e) { throw new ServletException(e); } X509CertificateHolder holder = reqCerts.iterator().next(); ByteArrayInputStream bais = new ByteArrayInputStream( holder.getEncoded()); X509Certificate reqCert; try { reqCert = (X509Certificate) factory.generateCertificate(bais); } catch (CertificateException e) { throw new ServletException(e); } PkiMessage<?> msg; try { PkcsPkiEnvelopeDecoder envDecoder = new PkcsPkiEnvelopeDecoder( getRecipient(), getRecipientKey()); PkiMessageDecoder decoder = new PkiMessageDecoder(reqCert, envDecoder); msg = decoder.decode(sd); } catch (MessageDecodingException e) { LOGGER.error("Error decoding request", e); throw new ServletException(e); } LOGGER.debug("Processing message {}", msg); MessageType msgType = msg.getMessageType(); Object msgData = msg.getMessageData(); Nonce senderNonce = Nonce.nextNonce(); TransactionId transId = msg.getTransactionId(); Nonce recipientNonce = msg.getSenderNonce(); CertRep certRep; if (msgType == MessageType.GET_CERT) { final IssuerAndSerialNumber iasn = (IssuerAndSerialNumber) msgData; final X500Name principal = iasn.getName(); final BigInteger serial = iasn.getSerialNumber().getValue(); try { List<X509Certificate> issued = doGetCert(principal, serial); if (issued.size() == 0) { certRep = new CertRep(transId, senderNonce, recipientNonce, FailInfo.badCertId); } else { CMSSignedData messageData = getMessageData(issued); certRep = new CertRep(transId, senderNonce, recipientNonce, messageData); } } catch (OperationFailureException e) { certRep = new CertRep(transId, senderNonce, recipientNonce, e.getFailInfo()); } catch (Exception e) { throw new ServletException(e); } } else if (msgType == MessageType.GET_CERT_INITIAL) { final IssuerAndSubject ias = (IssuerAndSubject) msgData; final X500Name issuer = X500Name.getInstance(ias.getIssuer()); final X500Name subject = X500Name.getInstance(ias.getSubject()); try { List<X509Certificate> issued = doGetCertInitial(issuer, subject, transId); if (issued.size() == 0) { certRep = new CertRep(transId, senderNonce, recipientNonce); } else { CMSSignedData messageData = getMessageData(issued); certRep = new CertRep(transId, senderNonce, recipientNonce, messageData); } } catch (OperationFailureException e) { certRep = new CertRep(transId, senderNonce, recipientNonce, e.getFailInfo()); } catch (Exception e) { throw new ServletException(e); } } else if (msgType == MessageType.GET_CRL) { final IssuerAndSerialNumber iasn = (IssuerAndSerialNumber) msgData; final X500Name issuer = iasn.getName(); final BigInteger serialNumber = iasn.getSerialNumber() .getValue(); try { LOGGER.debug("Invoking doGetCrl"); CMSSignedData messageData = getMessageData(doGetCrl(issuer, serialNumber)); certRep = new CertRep(transId, senderNonce, recipientNonce, messageData); } catch (OperationFailureException e) { LOGGER.error("Error executing GetCRL request", e); certRep = new CertRep(transId, senderNonce, recipientNonce, e.getFailInfo()); } catch (Exception e) { LOGGER.error("Error executing GetCRL request", e); throw new ServletException(e); } } else if (msgType == MessageType.PKCS_REQ) { final PKCS10CertificationRequest certReq = (PKCS10CertificationRequest) msgData; try { LOGGER.debug("Invoking doEnrol"); List<X509Certificate> issued = doEnrol(certReq, transId); if (issued.size() == 0) { certRep = new CertRep(transId, senderNonce, recipientNonce); } else { CMSSignedData messageData = getMessageData(issued); certRep = new CertRep(transId, senderNonce, recipientNonce, messageData); } } catch (OperationFailureException e) { certRep = new CertRep(transId, senderNonce, recipientNonce, e.getFailInfo()); } catch (Exception e) { throw new ServletException(e); } } else { throw new ServletException("Unknown Message for Operation"); } PkcsPkiEnvelopeEncoder envEncoder = new PkcsPkiEnvelopeEncoder( reqCert, "DESede"); PkiMessageEncoder encoder = new PkiMessageEncoder(getSignerKey(), getSigner(), getSignerCertificateChain(), envEncoder); CMSSignedData signedData; try { signedData = encoder.encode(certRep); } catch (MessageEncodingException e) { LOGGER.error("Error decoding response", e); throw new ServletException(e); } res.getOutputStream().write(signedData.getEncoded()); res.getOutputStream().close(); } else { res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unknown Operation"); } } private CMSSignedData getMessageData(final List<X509Certificate> certs) throws IOException, CMSException, GeneralSecurityException { CMSSignedDataGenerator generator = new CMSSignedDataGenerator(); JcaCertStore store; try { store = new JcaCertStore(certs); } catch (CertificateEncodingException e) { IOException ioe = new IOException(); ioe.initCause(e); throw ioe; } generator.addCertificates(store); return generator.generate(new CMSAbsentContent()); } private CMSSignedData getMessageData(final X509CRL crl) throws IOException, CMSException, GeneralSecurityException { CMSSignedDataGenerator generator = new CMSSignedDataGenerator(); JcaCRLStore store; if (crl == null) { store = new JcaCRLStore(Collections.emptyList()); } else { store = new JcaCRLStore(Collections.singleton(crl)); } generator.addCertificates(store); return generator.generate(new CMSAbsentContent()); } private void doGetNextCaCert(final HttpServletRequest req, final HttpServletResponse res) throws Exception { res.setHeader("Content-Type", "application/x-x509-next-ca-cert"); List<X509Certificate> certs = getNextCaCertificate(req .getParameter(MSG_PARAM)); if (certs.size() == 0) { res.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, "GetNextCACert Not Supported"); } else { CMSSignedDataGenerator generator = new CMSSignedDataGenerator(); JcaCertStore store; try { store = new JcaCertStore(certs); } catch (CertificateEncodingException e) { IOException ioe = new IOException(); ioe.initCause(e); throw ioe; } generator.addCertificates(store); DigestCalculatorProvider digestProvider = new JcaDigestCalculatorProviderBuilder() .build(); SignerInfoGeneratorBuilder infoGenBuilder = new SignerInfoGeneratorBuilder( digestProvider); X509CertificateHolder certHolder = new X509CertificateHolder( getRecipient().getEncoded()); ContentSigner contentSigner = new JcaContentSignerBuilder( "SHA1withRSA").build(getRecipientKey()); SignerInfoGenerator infoGen = infoGenBuilder.build(contentSigner, certHolder); generator.addSignerInfoGenerator(infoGen); CMSSignedData degenerateSd = generator .generate(new CMSAbsentContent()); byte[] bytes = degenerateSd.getEncoded(); res.getOutputStream().write(bytes); res.getOutputStream().close(); } } private void doGetCaCert(final HttpServletRequest req, final HttpServletResponse res) throws Exception { final List<X509Certificate> certs = doGetCaCertificate(req .getParameter(MSG_PARAM)); final byte[] bytes; if (certs.size() == 0) { res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "GetCaCert failed to obtain CA from store"); bytes = new byte[0]; } else if (certs.size() == 1) { res.setHeader("Content-Type", "application/x-x509-ca-cert"); bytes = certs.get(0).getEncoded(); } else { res.setHeader("Content-Type", "application/x-x509-ca-ra-cert"); CMSSignedDataGenerator generator = new CMSSignedDataGenerator(); JcaCertStore store; try { store = new JcaCertStore(certs); } catch (CertificateEncodingException e) { IOException ioe = new IOException(); ioe.initCause(e); throw ioe; } generator.addCertificates(store); CMSSignedData degenerateSd = generator .generate(new CMSAbsentContent()); bytes = degenerateSd.getEncoded(); } res.getOutputStream().write(bytes); res.getOutputStream().close(); } private Operation getOperation(final HttpServletRequest req) { String op = req.getParameter(OP_PARAM); if (op == null) { return null; } return Operation.forName(req.getParameter(OP_PARAM)); } private void doGetCaCaps(final HttpServletRequest req, final HttpServletResponse res) throws Exception { res.setHeader("Content-Type", "text/plain"); final Set<Capability> caps = doCapabilities(req.getParameter(MSG_PARAM)); for (Capability cap : caps) { res.getWriter().write(cap.toString()); res.getWriter().write('\n'); } res.getWriter().close(); } /** * Returns the capabilities of the specified CA. * * @param identifier * the CA identifier, which may be an empty string. * @return the capabilities. * @throws Exception * if any problem occurs */ protected abstract Set<Capability> doCapabilities(final String identifier) throws Exception; /** * Returns the certificate chain of the specified CA. * * @param identifier * the CA identifier, which may be an empty string. * @return the CA's certificate. * @throws Exception * if any problem occurs */ protected abstract List<X509Certificate> doGetCaCertificate( String identifier) throws Exception; /** * Return the chain of the next X.509 certificate which will be used by the * specified CA. * * @param identifier * the CA identifier, which may be an empty string. * @return the list of certificates. * @throws Exception * if any problem occurs */ protected abstract List<X509Certificate> getNextCaCertificate( String identifier) throws Exception; /** * Retrieve the certificate chain identified by the given parameters. * * @param issuer * the issuer name. * @param serial * the serial number. * @return the identified certificate, if any. * @throws OperationFailureException * if the operation cannot be completed * @throws Exception * if any problem occurs */ protected abstract List<X509Certificate> doGetCert(final X500Name issuer, final BigInteger serial) throws Exception; /** * Checks to see if a previously-requested certificate has been issued. If * the certificate has been issued, this method will return the appropriate * certificate chain. Otherwise, this method should return null or an empty * list to indicate that the request is still pending. * * @param issuer * the issuer name. * @param subject * the subject name. * @param transId * the transaction ID. * @return the identified certificate, if any. * @throws OperationFailureException * if the operation cannot be completed * @throws Exception * if any problem occurs */ protected abstract List<X509Certificate> doGetCertInitial( final X500Name issuer, final X500Name subject, final TransactionId transId) throws Exception; /** * Retrieve the CRL covering the given certificate identifiers. * * @param issuer * the certificate issuer. * @param serial * the certificate serial number. * @return the CRL. * @throws OperationFailureException * if the operation cannot be completed * @throws Exception * if any problem occurs */ protected abstract X509CRL doGetCrl(final X500Name issuer, final BigInteger serial) throws Exception; /** * Enrols a certificate into the PKI represented by this SCEP interface. If * the request can be completed immediately, this method returns an * appropriate certificate chain. If the request is pending, this method * should return null or any empty list. * * @param certificationRequest * the PKCS #10 CertificationRequest * @param transId * the transaction ID * @return the certificate chain, if any * @throws OperationFailureException * if the operation cannot be completed * @throws Exception * if any problem occurs */ protected abstract List<X509Certificate> doEnrol( final PKCS10CertificationRequest certificationRequest, final TransactionId transId) throws Exception; /** * Returns the private key of the recipient entity represented by this SCEP * server. * * @return the private key. */ protected abstract PrivateKey getRecipientKey(); /** * Returns the certificate of the server recipient entity. * * @return the certificate. */ protected abstract X509Certificate getRecipient(); /** * Returns the private key of the entity represented by this SCEP server. * * @return the private key. */ protected abstract PrivateKey getSignerKey(); /** * Returns the certificate of the entity represented by this SCEP server. * * @return the certificate. */ protected abstract X509Certificate getSigner(); /** * Returns the certificate chain of the entity represented by this SCEP server. * * @return the chain */ protected abstract X509Certificate[] getSignerCertificateChain(); private byte[] getMessageBytes(final HttpServletRequest req) throws IOException { if (req.getMethod().equals(POST)) { return IOUtils.toByteArray(req.getInputStream()); } else { Operation op = getOperation(req); if (op == Operation.PKI_OPERATION) { String msg = req.getParameter(MSG_PARAM); if (msg.length() == 0) { return new byte[0]; } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Decoding {}", msg); } return Base64.decode(msg); } else { return new byte[0]; } } } }
package cz.neumimto.core.localization; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.format.TextColor; import org.spongepowered.api.text.serializer.TextSerializers; import java.util.ArrayList; import java.util.List; import java.util.Map; public class TextHelper { public static Text parse(String text) { return TextSerializers.FORMATTING_CODE.deserialize(text); } public static Text makeText(String nameById, TextColor c) { return Text.builder(nameById).color(c).build(); } public static Text parse(String text, Arg params) { for (Map.Entry<String, Object> par : params.getParams().entrySet()) { text = text.replace(par.getKey(), par.getValue().toString()); } return TextSerializers.FORMATTING_CODE.deserialize(text); } public static List<Text> splitStringByDelimiter(String text) { List<Text> lore = new ArrayList<>(); for (String s : text.split(":n")) { lore.add(parse(s)); } return lore; } }
/* * Copyright (C) 1998, 2009 John Pritchard and the Alto Project Group. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. */ package json; /** * <p> Fast hexidecimal numeric coding correct (as to recode itself) * across all integer and long values. Output A-F characters are * lower case. </p> * * @author jdp * @since 1.1 */ public abstract class Hex extends Bits { private final static char[] chars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; /** * From ASCII to binary */ public final static byte[] decode ( String h){ if (null != h){ int len = h.length(); byte[] ascii = new byte[len]; h.getBytes(0,len,ascii,0); return decode( ascii, 0, len); } else return null; } /** * From ASCII to binary */ public final static byte[] decode ( byte[] b){ if (null != b) return decode( b, 0, b.length); else return null; } /** * From ASCII to binary */ public final static byte[] decode ( byte[] cary, int ofs, int len){ int olen = len; int term = len-1; if ( 1 == (len&1)){ //(odd number of digits in `cary') len += 1; term = len-1; } byte[] buffer = new byte[len/2]; int bcm = 1; if ( 0 < ofs){ if (1 == (ofs&1)) bcm = 2; else bcm = 1; len += ofs; } byte ch; for ( int cc = ofs, bc = 0; cc < len; cc++){ if ( cc == term && cc == olen) break; //(odd number of digits in `cary') else ch = cary[cc]; if ( ofs < cc && (0 == (cc & bcm))) bc += 1; if ( '0' <= ch){ if ( '9' >= ch){ if ( 1 == (cc&1)) buffer[bc] += (byte)(ch-'0'); else buffer[bc] += (byte)((ch-'0')<<4); } else if ( 'a' <= ch && 'f' >= ch){ if ( 1 == (cc&1)) buffer[bc] += (byte)((ch-'a')+10); else buffer[bc] += (byte)(((ch-'a')+10)<<4); } else if ( 'A' <= ch && 'F' >= ch){ if ( 1 == (cc&1)) buffer[bc] += (byte)((ch-'A')+10); else buffer[bc] += (byte)(((ch-'A')+10)<<4); } else throw new IllegalArgumentException("String '"+new String(cary,0,ofs,olen)+"' is not hex."); } else throw new IllegalArgumentException("String '"+new String(cary,0,ofs,olen)+"' is not hex."); } return buffer; } /** * <p> Basic HEX encoding primitives. </p> * @param val An eight bit value. * @return Low four bits encoded to a hex character. */ public final static char encode8Low(int val){ return chars[val & 0xf]; } /** * <p> Basic HEX encoding primitives. </p> * @param val An eight bit value. * @return High four bits encoded to a hex character. */ public final static char encode8High(int val){ return chars[(val >>> 4) & 0xf]; } public final static String encode(byte ch){ char[] string = new char[]{ encode8High(ch), encode8Low(ch) }; return new String(string); } public final static String encode(java.math.BigInteger bint){ if (null == bint) return null; else return encode(bint.toByteArray()); } /** * <p> binary to hexadecimal</p> */ public final static String encode ( byte[] buffer){ if ( null == buffer) return null; else { int len = buffer.length; char[] cary = new char[(len*2)]; int val, ca = 0; for ( int cc = 0; cc < len; cc++){ val = (buffer[cc]&0xff); cary[ca++] = (chars[(val>>>4)&0xf]); cary[ca++] = (chars[ val&0xf]); } return new java.lang.String(cary); } } /** * <p> binary to hexadecimal</p> * @return Seven bit ASCII hexidecimal */ public final static byte[] encode2 ( byte[] buffer){ if ( null == buffer) return null; else { int len = buffer.length; byte[] bary = new byte[(len*2)]; int val, ca = 0; for ( int cc = 0; cc < len; cc++){ val = (buffer[cc]&0xff); bary[ca++] = (byte)(chars[(val>>>4)&0xf]); bary[ca++] = (byte)(chars[ val&0xf]); } return bary; } } public final static String encode( long value){ byte[] bvalue = Long(value); return encode(bvalue); } public final static String encode( int value){ byte[] bvalue = Integer(value); return encode(bvalue); } }
package org.example.data.model.user; import org.example.common.aspect.Encrypt; import org.example.data.model.BaseModel; import org.example.data.model.department.Department; import org.example.data.model.role.Role; import org.hibernate.annotations.Fetch; import org.hibernate.annotations.FetchMode; import javax.persistence.*; import java.util.List; @Entity @Table(name = "user") public class User extends BaseModel { @Column(name = "name") private String name; @Column(name = "login_account") private String loginAccount; @Column(name = "login_password") private String loginPassword; @JoinTable(name = "user_role", joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")}, inverseJoinColumns = {@JoinColumn(name = "role_id", referencedColumnName = "id")}) @OneToMany(fetch = FetchType.EAGER) @Fetch(FetchMode.SUBSELECT) private List<Role> roleList; @JoinTable(name = "user_department", joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")}, inverseJoinColumns = {@JoinColumn(name = "department_id", referencedColumnName = "id")}) @OneToMany(fetch = FetchType.EAGER) @Fetch(FetchMode.SUBSELECT) private List<Department> departmentList; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLoginAccount() { return loginAccount; } public void setLoginAccount(String loginAccount) { this.loginAccount = loginAccount; } public String getLoginPassword() { return loginPassword; } @Encrypt public void setLoginPassword(String loginPassword) { this.loginPassword = loginPassword; } public List<Role> getRoleList() { return roleList; } public void setRoleList(List<Role> roleList) { this.roleList = roleList; } public List<Department> getDepartmentList() { return departmentList; } public void setDepartmentList(List<Department> departmentList) { this.departmentList = departmentList; } }