text
stringlengths 10
2.72M
|
|---|
package old.Data20180424;
import java.util.Stack;
public class LargestRectangleInHistogram {
public static void main(String[] args){
int[] a = new int[]{2,1,2};
System.out.print(new LargestRectangleInHistogram().largestRectangleArea(a));
}
/**
* 解决方法的主要思想为构建一个升序栈
* @param height
* @return
*/
public int largestRectangleArea(int[] height) {
int n = height.length, result = 0;
Stack<Integer> stack = new Stack<>();
for(int i = 0; i < n; i++){
while(!stack.isEmpty() && (height[stack.peek()] > height[i])){
int h = height[stack.peek()];
stack.pop();
result = Math.max(result, h * (i - 1 - (stack.isEmpty() ? -1 : stack.peek())));
}
stack.push(i);
}
while(!stack.empty()){
int h = height[stack.peek()];
stack.pop();
result = Math.max(result, h * (n - 1 - (stack.isEmpty() ? -1 : stack.peek())));
}
return result;
}
}
|
package presentation.webmanager.view;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import presentation.webmanager.MainAPP;
import vo.ManagerVO;
/**
* Created by 啊 on 2016/12/10.
*/
public class RootLayOutController {
private ManagerVO managerVO;
private MainAPP mainAPP;
@FXML
private Label usernameLabel;
@FXML
private Button customerInfoButton;
@FXML
private Button managerInfoButton;
@FXML
private Button addHotelAndWorkerButton;
@FXML
private Button addSalesManButton;
public void setMainApp(MainAPP mainApp) {
this.mainAPP = mainApp;
this.usernameLabel.setText("欢迎!" + managerVO.getUsername());
}
public void setManagerVO(ManagerVO managerVO){
this.managerVO=managerVO;
}
@FXML
private void customerInfoAction() {
this.customerInfoButton.getStyleClass().set(1, "button-navigation-selected");
this.managerInfoButton.getStyleClass().set(1, "button-navigation");
this.addHotelAndWorkerButton.getStyleClass().set(1, "button-navigation");
this.addSalesManButton.getStyleClass().set(1, "button-navigation");
mainAPP.showCustomerInfoView(managerVO);
}
@FXML
private void managerInfoAction() {
this.customerInfoButton.getStyleClass().set(1, "button-navigation");
this.managerInfoButton.getStyleClass().set(1, "button-navigation-selected");
this.addHotelAndWorkerButton.getStyleClass().set(1, "button-navigation");
this.addSalesManButton.getStyleClass().set(1, "button-navigation");
mainAPP.showManagerInfoView(managerVO);
}
@FXML
private void addHotelAndWorkerAction() {
this.customerInfoButton.getStyleClass().set(1, "button-navigation");
this.managerInfoButton.getStyleClass().set(1, "button-navigation");
this.addHotelAndWorkerButton.getStyleClass().set(1, "button-navigation-selected");
this.addSalesManButton.getStyleClass().set(1, "button-navigation");
mainAPP.showAddHotelView(managerVO);
}
@FXML
private void addSalesManAction() {
this.customerInfoButton.getStyleClass().set(1, "button-navigation");
this.managerInfoButton.getStyleClass().set(1, "button-navigation");
this.addHotelAndWorkerButton.getStyleClass().set(1, "button-navigation");
this.addSalesManButton.getStyleClass().set(1, "button-navigation-selected");
mainAPP.showAddWebSalesManView(managerVO);
}
@FXML
private void signOutAction() {
mainAPP.showSignInView();
}
}
|
package jnouse;
import jalgo.MatrixOperation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import jalgo.StudentTest;
import cern.colt.list.DoubleArrayList;
import jalgo.*;
public class metricDistance {
/**
* array of video matrices, each matrix has dim=[nofrms][256]
*/
List<double[]> videoMat;
/** Video matrix to test against array videoMat, dim=[nofrms][256]
*/
double[] mat;
/**
* error for every column of mat match with corresponding
* columns of matrices videoMat.
* dim=[#videosToTest][256]
*
*/
double[] error;
private static boolean showTest = true;
static List<String> thevideos = new ArrayList<String>();
static int totest = 0;
private static String testvid="";
private static Logger mLog =
Logger.getLogger(StudentTest.class.getName());
private boolean debug = false;
//it will exclude the video to test or index totest
public List<String> getThevideos(){
return thevideos;
}
public void setThevideos(List<String> vt){
thevideos=vt;
}
public String getTestvid(){
return testvid;
}
public void setTestvid(String vt){
testvid= vt;
}
public metricDistance(List<String> thevid){
if(!debug)
mLog.setLevel(Level.WARNING);
thevideos= thevid;
}
public metricDistance(List<double[]> v, double[] m, List<String> thevid){
this(thevid);
videoMat =v;
mat = m;
}
public StringBuffer[] errorTest(List<double[]>red,
List<double[]>green,
List<double[]>blue,int totest){
String testv = thevideos.get(totest);
if(!showTest)
thevideos.remove(totest);
testvid = testv;
StringBuffer res0 = new StringBuffer("Test video "+ testv);
StringBuffer[] res = new StringBuffer[3];
String mess1 = "Testing video: " + testv;
double[] Rtest = red.get(totest);
double[] Gtest = green.get(totest);
double[] Btest = blue.get(totest);
metricDistance rtest = new metricDistance(red,Rtest, thevideos);
res[0] = new StringBuffer();
res[0].append("\n"+res0);
res[0].append(rtest.RelativeError("RED"));
metricDistance gtest = new metricDistance(green,Gtest, thevideos);
res[1] = new StringBuffer("\n"+res0);
res[1].append(gtest.RelativeError("GREEN"));
metricDistance btest = new metricDistance(blue,Btest, thevideos);
res[2] = new StringBuffer("\n"+res0);
res[2].append( btest.RelativeError("BLUE"));
return res;
}
public StringBuffer RelativeError(String col){
int ncol= videoMat.get(0).length;
error = new double[mat.length];
StringBuffer res = new StringBuffer();
Iterator<double[]> it= videoMat.iterator();
int videoInd=-1;
while(it.hasNext()){
videoInd++;
String str = thevideos.get(videoInd);
int k=0;
double[] comp = it.next();
// double corr = calcuta(comp,mat);
error[videoInd] = calcnorms(comp, mat);
res.append("Color component "+ col + ": ");
res.append("\nVideo "+ str+ "\n= mean relative error =" +error[videoInd]);
}
return res;
}
//calculate correlation between rows of two matrices.
/**
* @param arrtmp: double array
* @param arrtest: double array
* @return double with correlation
*/
public static double calcuta(double[] arrtmp, double[] arrtest){
cern.colt.list.DoubleArrayList testD = new cern.colt.list.DoubleArrayList(arrtest);
cern.colt.list.DoubleArrayList tmpD = new cern.colt.list.DoubleArrayList(arrtmp);
double mntest = cern.jet.stat.Descriptive.mean(testD);
double vartest = cern.jet.stat.Descriptive.sampleVariance(testD, mntest);
int nln = arrtest.length;
double sdtest = Math.sqrt(vartest);
//cern.jet.stat.Descriptive.sampleStandardDeviation(nln,vartest);
double mntmp = cern.jet.stat.Descriptive.mean(tmpD);
double vartmp = cern.jet.stat.Descriptive.sampleVariance(tmpD, mntmp);
int nln2 = arrtmp.length;
double sdtmp = Math.sqrt(vartmp);
//cern.jet.stat.Descriptive.sampleStandardDeviation(nln2,vartmp);
double cov = cern.jet.stat.Descriptive.correlation(testD,sdtest, tmpD,sdtmp);
mLog.info("cov is ="+ cov);
return cov;
}
/**
* Calculate distance of tow mean frames
* @param comp: double array with mean frame
* @param mat: duble array with mean frame to test
* @return double with metrix
*/
public double calcnorms(double[]comp, double[] mat){
double normcomp=0;
double normtest=0;
double normcomp2=0;
double normtest2=0;
for(int k=0; k<comp.length; ++k){
normcomp += Math.abs(comp[k]);
normtest += Math.abs(mat[k]);
normcomp2 += comp[k]*comp[k];
normtest2 += mat[k]*mat[k];
}
int len = mat.length;
double error[] = new double[len];
double normdif=0;
double del, del2, den;
double mx =0;
int cnt=0;
for(int k=0; k<len; ++k){
if(comp[k] >1.e-5 && mat[k]>1.e-5)
cnt++;
del = (comp[k] - mat[k]);
del2 = del*del;
den= comp[k] * mat[k]+1.e-10;
normdif += Math.abs(del)/Math.sqrt(den);
error[k] = del/Math.sqrt(den);
}
Arrays.sort(error);
DoubleArrayList derror = new DoubleArrayList(error);
double mediana = cern.jet.stat.Descriptive.median(derror);
double rat =normdif/len;
return rat;
}
}
|
package paketmalimslovima;
import java.util.Scanner;
public class Zadatak_1_23082019 {
//Napisati program koji ucitava ceo broj n. Taj broj n se prosledjuje
//metodi koja formira i vraca ceo broj koji predstavlja inverzan broj.
//Glavni program nakon toga ispisuje taj inverzan broj.
public static void main(String[] args) {
Scanner ulaz = new Scanner(System.in);
System.out.print("Upisite broj koji zelite da se prikaze u inverznom obliku: ");
int broj = ulaz.nextInt();
ispisiInt(inverzija(broj));
}
public static int inverzija(int x) {
int y = 0;
while(x!=0) {
y*=10;
y += x % 10;
x/=10;
}
return y;
}
public static void ispisiInt(int x) {
System.out.println("Inverzni oblik: " + x);
}
}
|
package collection;
import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
import java.util.Iterator;
import java.util.WeakHashMap;
/**
* HashMap博客
*
* 1、WeakHashMap 特殊HashMap
* WeakHashMap的键关联的对象是弱引用对象
*
* static class Entry<K,V> extends WeakReference<Object> Entry继承自WeakReference
*
* java当中四种引用
* 1、强引用
* 通过new出来对象所关联的引用称之为强引用,只要强引用存在,当前对象不会被回收
* 2、软引用
* 通过SoftReference类实现,在系统内存即将要溢出的时候,才会回收软引用对象
* 3、弱引用
* 通过WeakReference实现,只要发生GC,被弱引用关联的对象就会被回收掉
* 4、虚引用
* 通过PhantomReference实现,无法通过虚引用获取对象实例,唯一作用就是在这个对象
* 被回收时,能够收到一个通知
*/
public class 引用 {
public static Object key1;
public static Object key2;
public static Object key3;
public static WeakHashMap<Object, Integer> getWeakHashMap(){
WeakHashMap<Object, Integer> map = new WeakHashMap<>();
key1 = new Object();//强引用
key2 = new Object();
key3 = new Object();
map.put(key1, 1);
map.put(key2, 1);
map.put(key3, 1);
return map;
}
public static void printWeakHashMap(WeakHashMap<Object, Integer> map){
System.out.println("================");
// for(Object key: map.keySet()){
// System.out.println("key: "+key+", value: "+map.get(key));
// }
Iterator<Object> iterator = map.keySet().iterator();
while(iterator.hasNext()){
Object obj = iterator.next();
System.out.println(obj+":: "+map.get(obj));
}
}
public static void main(String[] args) {
//虚引用
// PhantomReference ptr = new PhantomReference(new Object(),new ReferenceQueue());
// System.gc();
// if(ptr.isEnqueued()){
//
// }
// WeakHashMap<Object, Integer> map = getWeakHashMap();
// printWeakHashMap(map);
//
// System.gc();
// try {
// Thread.sleep(2000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// printWeakHashMap(map);
//
// key1 = null;
// key2 = null;
//
// System.gc();
// try {
// Thread.sleep(2000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// printWeakHashMap(map);
}
}
|
package net.lantrack.project.jasperreport.common;
public enum DocType {
PDF, HTML, XLS,XLSX, XML, RTF, CSV, TXT, DOC
}
|
/*
*
* * Copyright 2020 New Relic Corporation. All rights reserved.
* * SPDX-License-Identifier: Apache-2.0
*
*/
package org.springframework.web.reactive.function.client;
import com.newrelic.agent.bridge.AgentBridge;
import com.newrelic.agent.bridge.Transaction;
import com.newrelic.api.agent.NewRelic;
import com.newrelic.api.agent.Segment;
import com.newrelic.api.agent.weaver.MatchType;
import com.newrelic.api.agent.weaver.Weave;
import com.newrelic.api.agent.weaver.Weaver;
import com.nr.agent.instrumentation.spring_webclient.OutboundRequestWrapper;
import com.nr.agent.instrumentation.spring_webclient.Util;
import reactor.core.publisher.Mono;
import java.net.URI;
@Weave(type = MatchType.Interface, originalName = "org.springframework.web.reactive.function.client.WebClient")
public class WebClient_Instrumentation {
@Weave(type = MatchType.Interface, originalName = "org.springframework.web.reactive.function.client.WebClient$RequestHeadersSpec")
public abstract static class RequestHeadersSpec_Instrumentation<S extends RequestHeadersSpec_Instrumentation<S>> {
public abstract S header(String headerName, String... headerValues);
public Mono<ClientResponse> exchange() {
Object thisTemp = this;
URI uri = Util.getUri();
Segment segment = null;
if (thisTemp instanceof UriSpec_Instrumentation) {
if (uri != null) {
String scheme = uri.getScheme();
if (scheme != null) {
final Transaction txn = AgentBridge.getAgent().getTransaction(false);
final String lowerCaseScheme = scheme.toLowerCase();
if (txn != null && ("http".equals(lowerCaseScheme) || "https".equals(lowerCaseScheme))) {
segment = NewRelic.getAgent().getTransaction().startSegment("WebClient.exchange");
segment.addOutboundRequestHeaders(
new OutboundRequestWrapper((WebClient.RequestHeadersSpec) thisTemp));
}
}
}
}
Mono<ClientResponse> response = Weaver.callOriginal();
if (segment == null || uri == null) {
return response;
}
return response.doAfterSuccessOrError(Util.reportAsExternal(segment));
}
}
@Weave(type = MatchType.Interface, originalName = "org.springframework.web.reactive.function.client.WebClient$UriSpec")
public static class UriSpec_Instrumentation<S extends WebClient.RequestHeadersSpec<?>> {
public S uri(URI uri) {
Util.setUri(uri);
return Weaver.callOriginal();
}
}
@Weave(type = MatchType.Interface, originalName = "org.springframework.web.reactive.function.client.WebClient$Builder")
public static class Builder_Instrumentation {
public WebClient.Builder baseUrl(String baseUrl) {
Util.setUri(baseUrl);
return Weaver.callOriginal();
}
}
}
|
package com.rhino.userAttributesService.Test;
import java.io.IOException;
import java.util.Collection;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.rhino.userAttributesServic.UserAttributesServiceManagerImpl;
import com.rhino.userAttributesServic.data.UserDataInterface;
public class DBConnection {
private static Logger logger = Logger.getLogger(DBConnection.class);
@Test
public void test() throws ClassNotFoundException, IOException {
String sql = "select v from UserStatus v where v.dataSourceType = 'MAIL' and v.onProcess = false order by v.date";
//String sql = "select v from UserStatus v , UserStatus v1 where v.dataSourceType='PARSER' and v1.dataSourceType='MAIL' and v.userID=v1.userID and v.date>v1.date and v1.onProcess=false order by v.date";
@SuppressWarnings("resource")
ApplicationContext appCtx = new ClassPathXmlApplicationContext("classpath:configs/userAttributesServiceLayer.xml");
UserAttributesServiceManagerImpl service = appCtx.getBean("userAttributesServiceManager",UserAttributesServiceManagerImpl.class);
Collection<UserDataInterface> job = service.getNextJob(sql, 10);
logger.info("job size="+job.size());
}
}
|
package com.redsun.platf.web.service;
/**
* <p>Title: com.walsin.platf.web.MailEvenEnum</p>
* <p>Description: Mail模組定義</p>
* <p>Copyright: Copyright (c) 2010</p>
* <p>Company: FreeLance</p>
* @author Jason Huang
* @version 1.0
*/
public enum MailEvenEnum {
/** 密碼重置通知信件 */
RESET_USER_PASSWORD(new Integer(1), "system/reset-user-password"),
/** 啟用EP人員通知信件 */
ENABLE_USER_MAIL(new Integer(2), "system/enable-user-mail"),
/** EP08001 我的代辦請購單 - 採購員變更通知信件 */
PR_BUYER_CHANGE_MAIL(new Integer(3), "pr/change-buyer-mail"),
/** EP02004 單據負責人變更 - 請購員變更通知信件 */
PR_RECEIPT_UNDERTAKER_CHANGE_MAIL(new Integer(4), "changeReceiptUndertaker/change-pr-buyer-mail"),
/** EP02004 單據負責人變更 - 採購員變更通知信件 */
PO_RECEIPT_UNDERTAKER_CHANGE_MAIL(new Integer(5), "changeReceiptUndertaker/change-po-buyer-mail"),
/** EP02004 單據負責人變更 - 合約價格的採購員變更通知信件 */
PB_RECEIPT_UNDERTAKER_MAIL(new Integer(6), "changeReceiptUndertaker/change-pb-buyer-mail"),
/** EP02005 單據簽核人變更 通知信件 */
CHANGE_DOCUMENT_APPROVED_MAIL(new Integer(7), "workflow/change-document-approver-mail"),
/** EPB0101 已核准合約到期前XX日通知採購員 - 採購員通知信件 */
PRICEBANK_ALERTS_BUYER_MAIL(new Integer(8), "batch/pricebankAlerts/pricebank-alerts-buyer-mail"),
/** EPB0101 已核准合約到期前XX日通知採購員 - 採購員直屬主管通知信件 */
PRICEBANK_ALERTS_BUYER_MASTER_MAIL(new Integer(9), "batch/pricebankAlerts/pricebank-alerts-buyer-master-mail"),
/** EPB0100 已核准PR超過XX日未轉PO通知 - 請購員通知信件 */
PR_CONVERSION_PO_ALERTS_MAIL(new Integer(10), "batch/prConversionPoAlerts/pr-conversion-po-alerts-mail"),
/** EPB0102詢價單即將到期通知 - 採購員通知信件 */
RFQ_ALERTS_PURCHASER_MAIL(new Integer(11), "batch/rfqAlerts/rfq-alerts-purchaser-mail"),
/** EPB0102詢價單即將到期通知 - 採購員直屬主管通知信件 */
RFQ_ALERTS_PURCHASER_MASTER_MAIL(new Integer(12), "batch/rfqAlerts/rfq-alerts-purchaser-master-mail"),
/** EPB0103主管待簽核單據超過XX日尚未簽核通知 */
APPROVE_ALERTS_MAIL(new Integer(13), "batch/approveAlerts/approve-alerts-mail"),
/** EP08002 我的詢報價單 - 退回詢價單項目通知 */
RFQ_RETURN_MAIL(new Integer(14), "rfq/rfq-item-return"),
/** EP08002 我的詢報價單 - 寄送廠商報價通知信件 */
RFQ_NOTIFY_VENDOR_MAIL(new Integer(15), "rfq/rfq-notify-vendor"),
/** PR關閉 email */
COLSE_PR_ITEM_MAIL(new Integer(16), "pr/closePr"),
/** PR不再收貨 email */
STOP_PR_ITEM_RCV(new Integer(17), "pr/stopPrRcv"),
/** 取消PR不再收貨 */
CANCEL_STOP_PR_ITEM_RCV(new Integer(18), "pr/cancelStopPrRcv"),
/** 取消PR不再收貨 */
CONSUME_PRICEBANK_ERR(new Integer(19), "pr/consumePricebankErr"),
/** EP08002 我的採單 - 寄送廠商報價通知信件 */
PO_NOTIFY_VENDOR_MAIL(new Integer(20), "po/po-notify-vendor"),
/** 料號申請SAP失敗通知 */
MN_APPLY_FAIL_NOTIFY_MAIL(new Integer(21), "mn/apply-fail-notify"),
/** 請購流程信件表身 */
WORKFLOW_PR_MAIL(new Integer(101), "/workflow/pr"),
/** 採購流程信件表身 */
WORKFLOW_PO_MAIL(new Integer(102), "/workflow/po"),
/** 合約價格流程信件表身 */
WORKFLOW_PRICEBANK_MAIL(new Integer(103), "/workflow/pricebank"),
/** 料號流程信件表身 */
WORKFLOW_MN_MAIL(new Integer(104), "/workflow/mn");
/** 模組ID */
private Integer enenId;
/** Mail templet位置 */
private String templet;
MailEvenEnum(Integer enenId, String templet){
this.enenId = enenId;
this.templet = templet;
}
public Integer getEnenId() {
return enenId;
}
public void setEnenId(Integer enenId) {
this.enenId = enenId;
}
public String getTemplet() {
return templet;
}
public void setTemplet(String templet) {
this.templet = templet;
}
}
|
package inmobiliaria;
import java.util.TreeSet;
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Vista miVista = new Vista();
TreeSet<Propiedad>inmo = new TreeSet<>();
Inmobiliaria nuevo = new Inmobiliaria(inmo);
Controlador ctr = new Controlador(miVista, nuevo);
miVista.control(ctr);
JFrame ventana = new JFrame("Inmobiliaria");
ventana.setContentPane(miVista);
ventana.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ventana.pack();
ventana.setVisible(true);
}
}
|
package javaDay5;
interface Prog7{
default void printMessage(){
System.out.println("hello");
}
}
public class Program7 implements Prog7{
@Override
public void printMessage() {
System.out.println("This is Program 7");
}
public static void main(String[] args) {
Program7 P1 = new Program7();
P1.printMessage();
}
}
|
// RegistrationException.java
package org.google.code.netapps.chat.basic;
/**
* This exception is intended for registration exceptional situations.
*
* @version 1.1 08/09/2001
* @author Alexander Shvets
*/
public class RegistrationException extends Exception {
/**
* Creates new exception for registration process
*
* @param message the message
*/
public RegistrationException(String message) {
super(message);
}
}
|
package cn.jpush.impl.im;
import cn.jpush.kafka.MultiScheme;
import cn.jpush.kafka.MultiSchemeFactory;
public class OnlineSchemeFactory implements MultiSchemeFactory {
@Override
public MultiScheme createScheme() {
return new OnlineScheme();
}
}
|
package com.nit.car;
import java.util.List;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.nit.car.Dao.ProductDao;
import com.nit.car.Dao.SupplierDao;
import com.nit.car.Model.Product;
import com.nit.car.Model.Supplier;
public class SupplierTest {
public static void main(String args[]) {
AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext();
context.scan("com.nit.*");
context.refresh();
SupplierDao supplierDao=(SupplierDao)context.getBean("supplierDao");
Supplier supplier=(Supplier) context.getBean("supplier");
ProductDao productDao=(ProductDao)context.getBean("productDao");
Product product=(Product) context.getBean("product");
supplier.setSid("S6A7E9C");
supplier.setSname("rwer");
supplier.setAddress("adfghr123");
if(supplierDao.saveupdate(supplier)==true)
{
System.out.println("saved");
}
else
{
System.out.println("sorry");
}
Supplier sup=supplierDao.get("a333");
List<Product> lists=productDao.getProductBySupplier(sup.getSid());
if(lists==null||lists.isEmpty())
{
supplierDao.delete(sup);
}
else
{
for(Product pa:lists)
{
productDao.delete(pa);
}
supplierDao.delete(sup);
}
}
// List<Category> list=categoryDao.list();
// for(Category c:list){
// System.out.println(c.getCat_id());
// System.out.println(c.getCat_name());
//
// }
//
// if(categoryDao.delete("cat123")==true)
// {
// System.out.println("delete is successful");
// }
// else
// {
// System.out.println("sorry");
// }
}
|
package utilities;
public class StringUtils {
/*
public static boolean isPalindrome(String msg) {
if((msg.length()) == 1) {
return true;
}
else if(msg.charAt(0) == msg.charAt(msg.length()-1)) {
System.out.println("****** " + msg.length());
System.out.println(msg.charAt(0));
System.out.println(msg.charAt((msg.length()-1)));
System.out.println(msg.substring(1,msg.length()-1));
isPalindrome(msg.substring(1,msg.length()-1));
}
return false;
}
*/
public static boolean isPalindrome(String str) {
int i = 0, j = str.length() - 1;
// While there are characters to compare
while (i < j) {
// If there is a mismatch
if (str.charAt(i) != str.charAt(j))
return false;
// Increment first pointer and
// decrement the other
i++;
j--;
}
// Given string is a palindrome
return true;
}
public static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
public static String crypt(String plainText) {
plainText = plainText.toLowerCase();
String cipherText = "";
for (int i = 0; i < plainText.length(); i++)
{
if(plainText.charAt(i) != ' ') {
int charPosition = ALPHABET.indexOf(plainText.charAt(i));
int keyVal = (1 + charPosition) % 26;
char replaceVal = ALPHABET.charAt(keyVal);
cipherText += replaceVal;
}else {
cipherText += ' ';
}
}
return cipherText.toUpperCase();
}
public static String decrypt(String plainText) {
plainText = plainText.toLowerCase();
String cipherText = "";
for (int i = 0; i < plainText.length(); i++)
{
if(plainText.charAt(i) != ' ') {
int charPosition = ALPHABET.indexOf(plainText.charAt(i));
int keyVal = (charPosition - 1) % 26;
if (keyVal < 0)
{
keyVal = ALPHABET.length() + keyVal;
}
char replaceVal = ALPHABET.charAt(keyVal);
cipherText += replaceVal;
}else {
cipherText += ' ';
}
}
return cipherText.toUpperCase();
}
public static String capitalize(String name) {
return name.substring(0,1).toUpperCase() + name.substring(1);
}
}
|
package com.grocery.codenicely.vegworld_new.helper.image_loader;
/**
* Created by meghal on 13/10/16.
*/
public class PicassoImageLoader {
}
|
package com.github.rosjava.android_apps.blind_guide;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.github.rosjava.android_apps.teleop.R;
import com.github.rosjava.android_remocons.common_tools.apps.RosAppActivity;
import org.ros.node.NodeMainExecutor;
import java.net.URISyntaxException;
public class MainActivity extends RosAppActivity {
Intent intent;
RelativeLayout listLayout;
private Button startBtn;
private Button selectBtn;
private final int PERMISSION = 1;
private final String MASTER_URI = "http://192.168.0.23:11311";
private VoiceAssi voiceAssi;
private TextView statusTxt;
private String destination;
private String destinationId;
private String navigationFlag;
private NodeMainExecutor nodeMainExecutor;
private long backBtnTime = 0;
public MainActivity() throws URISyntaxException {
super("길안내 어플", "종료");
}
@SuppressLint("ClickableViewAccessibility")
@Override
public void onCreate(Bundle savedInstanceState) {
setDashboardResource(R.id.top_bar);
setMainWindowResource(R.layout.main);
super.onCreate(savedInstanceState);
voiceAssi = new VoiceAssi(intent, MainActivity.this);
voiceAssi.startReading(",,,,");
statusTxt = findViewById(R.id.status);
destination = getIntent().getStringExtra("destination");
destinationId = getIntent().getStringExtra("destinationId");
navigationFlag = getIntent().getStringExtra("navigation");
if(destination != null){
statusTxt.setText("목적지 : " + destination);
} else if (navigationFlag != null) {
statusTxt.setText("네비게이션 시작");
}
startBtn = (Button) findViewById(R.id.start_btn);
selectBtn = (Button) findViewById(R.id.select_btn);
listLayout = (RelativeLayout) findViewById(R.id.list_layout);
if(Build.VERSION.SDK_INT >= 23){
// 퍼미션 체크
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.INTERNET,
Manifest.permission.RECORD_AUDIO},PERMISSION);
}
selectBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
voiceAssi.destroyTTS();
Intent intent1 = new Intent(MainActivity.this, SelectActivity.class);
MainActivity.this.startActivity(intent1);
finish();
}
});
startBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(statusTxt.getText().toString().equals("목적지 선택 필요")) {
voiceAssi.startReading("설정된 목적지가 없습니다");
Toast.makeText(MainActivity.this, "설정된 목적지가 없습니다",Toast.LENGTH_SHORT).show();
} else {
voiceAssi.destroyTTS();
Intent intent1 = new Intent(MainActivity.this, NavigationActivity.class);
if(destination != null){
intent1.putExtra("destination", destination);
intent1.putExtra("destinationId", destinationId);
}
MainActivity.this.startActivity(intent1);
finish();
}
}
});
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
try {
voiceAssi.startReading("메인 화면입니다." +statusTxt.getText().toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}, 100);
}
@Override
public void onStart() {
voiceAssi.startReading("메인 화면입니다." + statusTxt.getText().toString());
super.onStart();
}
@Override
public void onDestroy() {
super.onDestroy();
this.voiceAssi = null;
}
@Override
public void startMasterChooser(){
try{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String masterURI = prefs.getString("masterURI", MASTER_URI);
Intent data = new Intent();
data.putExtra("ROS_MASTER_URI", masterURI);
onActivityResult(0, RESULT_OK, data);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
try {
voiceAssi.startReading("메인 화면입니다." +statusTxt.getText().toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}, 50);
} catch (Exception e){
Toast.makeText(MainActivity.this, "서버와 연결 실패", Toast.LENGTH_SHORT).show();
Log.e("Connection Error", "Master can't reachable");
}
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public void onBackPressed() {
//super.onBackPressed();
long curTime = System.currentTimeMillis();
long gapTime = curTime - backBtnTime;
if(0 <= gapTime && 2000 >= gapTime) {
moveTaskToBack(true);
finishAndRemoveTask();
android.os.Process.killProcess(android.os.Process.myPid());
}
else {
backBtnTime = curTime;
voiceAssi.startReading("한번 더 누르면 종료");
}
}
}
|
package ocdhis2;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="conflict")
public class ImportConflict
{
private String object;
private String value;
public String getObject()
{
return object;
}
@XmlAttribute(name="object")
public void setObject(String object)
{
this.object = object;
}
public String getValue()
{
return value;
}
@XmlAttribute(name="value")
public void setValue(String value)
{
this.value = value;
}
@Override
public String toString()
{
return "ImportConflict(object='" + object + "', " +
"value='" + value + "')";
}
}
|
package com.g52aim.lab02;
import java.util.Random;
import g52aim.domains.chesc2014_SAT.SAT;
import g52aim.satheuristics.SATHeuristic;
import g52aim.searchmethods.SinglePointSearchMethod;
public class IteratedLocalSearch extends SinglePointSearchMethod {
// local search / intensification heuristic
private SATHeuristic ls;
// mutation / perturbation heuristic
private SATHeuristic mtn;
// iom and dos parameter settings
private int intensityOfMutation;
private int depthOfSearch;
/**
*
* @param problem The problem to be solved.
* @param random The random number generator, use this one, not your own!
* @param mtn The mutation heuristic.
* @param ls The local search heuristic.
* @param intensityOfMutation The parameter setting for intensity of mutation.
* @param depthOfSearch The parameter setting for depth of search.
*/
public IteratedLocalSearch(SAT problem, Random random, SATHeuristic mtn, SATHeuristic ls, int intensityOfMutation, int depthOfSearch) {
super(problem, random);
this.mtn = mtn;
this.ls = ls;
this.intensityOfMutation = intensityOfMutation;
this.depthOfSearch = depthOfSearch;
}
/**
*
* Main loop for ILS. The experiment framework will continually call this loop until
* the allocated time has expired.
*
* -- ITERATED LOCAL SEARCH PSEUDO CODE --
*
* s <- currentSolution
* s' <- s
*
* // apply mutation heuristic "intensityOfMutation" times
* FOR 0 -> intensityOfMutation - 1 DO
* s' <- mutation(s')
* END_FOR
*
* // apply local search heuristic "depthOfSearch" times
* FOR 0 -> depthOfSearch - 1 DO
* s' <- localSearch(s')
* END_FOR
*
* IF f(s') ( < | <= ) f(s) THEN
* accept();
* ELIF
* reject();
* FI
*/
protected void runMainLoop() {
for(int i = 0; i < intensityOfMutation - 1; i++) {
mtn.applyHeuristic(problem);
}
for (int j = 0; j < depthOfSearch - 1; j++) {
ls.applyHeuristic(problem);
}
if(problem.getObjectiveFunctionValue(CURRENT_SOLUTION_INDEX) < problem.getObjectiveFunctionValue(BACKUP_SOLUTION_INDEX) || problem.getObjectiveFunctionValue(CURRENT_SOLUTION_INDEX) <= problem.getObjectiveFunctionValue(BACKUP_SOLUTION_INDEX)){
problem.copySolution(CURRENT_SOLUTION_INDEX, BACKUP_SOLUTION_INDEX);
}else{
problem.copySolution(BACKUP_SOLUTION_INDEX, CURRENT_SOLUTION_INDEX);
}
}
public String toString() {
return "Iterated Local Search";
}
}
|
package com.ngocdt.tttn.repository;
import com.ngocdt.tttn.entity.Receiption;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ReceiptionRepository extends JpaRepository<Receiption, Integer> {
}
|
package com.legaoyi.protocol.downstream.messagebody;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.legaoyi.protocol.message.MessageBody;
/**
* 临时位置跟踪控制
*
* @author <a href="mailto:shengbo.gao@gmail.com;78772895@qq.com">gaoshengbo</a>
* @version 1.0.0
* @since 2019-05-20
*/
@Scope("prototype")
@Component(MessageBody.MESSAGE_BODY_BEAN_PREFIX + "8203_2019" + MessageBody.MESSAGE_BODY_BEAN_SUFFIX)
public class Jt808_2019_8203_MessageBody extends MessageBody {
private static final long serialVersionUID = -3225041292826124334L;
public static final String MESSAGE_ID = "8203";
/** 报警消息流水号 **/
@JsonProperty("messageSeq")
private int messageSeq;
/** 报警类型 ,二进制字符串 **/
@JsonProperty("type")
private String type;
public final int getMessageSeq() {
return messageSeq;
}
public final void setMessageSeq(int messageSeq) {
this.messageSeq = messageSeq;
}
public final String getType() {
return type;
}
public final void setType(String type) {
this.type = type;
}
}
|
package org.una.inventario.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.una.inventario.dto.TransaccionDTO;
import org.una.inventario.entities.Transaccion;
import org.una.inventario.exceptions.NotFoundInformationException;
import org.una.inventario.repositories.ITransaccionRepository;
import org.una.inventario.utils.MapperUtils;
import java.util.Date;
import java.util.List;
import java.util.Optional;
@Service
public class TransaccionServiceImplementation implements ITransaccionService{
@Autowired
private ITransaccionRepository transaccionRepository;
@Override
@Transactional(readOnly = true)
public Optional<TransaccionDTO> findById(Long id) {
Optional<Transaccion> transaccion = transaccionRepository.findById(id);
if (transaccion.isEmpty()) throw new NotFoundInformationException();
TransaccionDTO transaccionDTO = MapperUtils.DtoFromEntity(transaccion.get(), TransaccionDTO.class);
return Optional.ofNullable(transaccionDTO);
}
@Override
@Transactional(readOnly = true)
public Optional<List<TransaccionDTO>> findByUsuarioIdAndFechaCreacionBetween(Long usuarioId, Date startDate, Date endDate) {
List<Transaccion> transaccionList = transaccionRepository.findByUsuarioIdAndFechaCreacionBetween(usuarioId,startDate,endDate);
List<TransaccionDTO> transaccionDTOList = MapperUtils.DtoListFromEntityList(transaccionList, TransaccionDTO.class);
return Optional.ofNullable(transaccionDTOList);
}
// @Override
// @Transactional(readOnly = true)
// public Optional<List<TransaccionDTO>> findByRolIdAndFechaCreacionBetween(Long rolId, Date startDate, Date endDate) {
// List<Transaccion> transaccionList = transaccionRepository.findByRolIdAndFechaCreacionBetween(rolId,startDate,endDate);
// List<TransaccionDTO> transaccionDTOList = MapperUtils.DtoListFromEntityList(transaccionList, TransaccionDTO.class);
// return Optional.ofNullable(transaccionDTOList);
// }
@Override
@Transactional(readOnly = true)
public Optional<List<TransaccionDTO>> findByObjetoAndFechaCreacionBetween(String objetoId, Date startDate, Date endDate) {
List<Transaccion> transaccionList = transaccionRepository.findByObjetoAndFechaCreacionBetween(objetoId,startDate,endDate);
List<TransaccionDTO> transaccionDTOList = MapperUtils.DtoListFromEntityList(transaccionList, TransaccionDTO.class);
return Optional.ofNullable(transaccionDTOList);
}
@Override
@Transactional(readOnly = true)
public Optional<List<TransaccionDTO>> findByFechaCreacionBetween(Date startDate, Date endDate) {
List<Transaccion> transaccionList = transaccionRepository.findByFechaCreacionBetween(startDate,endDate);
List<TransaccionDTO> transaccionDTOList = MapperUtils.DtoListFromEntityList(transaccionList, TransaccionDTO.class);
return Optional.ofNullable(transaccionDTOList);
}
@Override
@Transactional
public TransaccionDTO create(TransaccionDTO transaccionDTO) {
Transaccion transaccion = MapperUtils.EntityFromDto(transaccionDTO, Transaccion.class);
transaccion = transaccionRepository.save(transaccion);
return MapperUtils.DtoFromEntity(transaccion, TransaccionDTO.class);
}
private TransaccionDTO getSavedTransaccionDTO(TransaccionDTO transaccionDTO) {
Transaccion transaccion = MapperUtils.EntityFromDto(transaccionDTO, Transaccion.class);
Transaccion transaccionCreated = transaccionRepository.save(transaccion);
return MapperUtils.DtoFromEntity(transaccionCreated, TransaccionDTO.class);
}
}
|
package controller.member.stock;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import model.Member_DTO;
import model.Stock_DTO;
@Controller
public class Member_Stock_Controller {
@Autowired
Member_Stock_DAO stock;
public Member_Stock_DAO getStock() {
return stock;
}
public void setStock(Member_Stock_DAO stock) {
this.stock = stock;
}
@RequestMapping(value = "stock_status.do", method = RequestMethod.GET)
public ModelAndView stock_status(ModelAndView mav, Stock_DTO Stock_DTO, HttpSession session) {
Member_DTO session_member = (Member_DTO) session.getAttribute("login");
if (session_member == null) {
mav.setViewName("redirect:index.jsp");
return mav;
}
int s_no = session_member.getS_no();
List<Stock_DTO> list = stock.selectList(s_no);
mav.addObject("list", list);
mav.setViewName("stock/stock_status");
return mav;
}
}
|
package cc.aies.web.controller;
import cc.aies.web.beans.Dictionary;
import cc.aies.web.service.DictionaryService;
import cc.aies.web.utils.Msg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* Created by Intellij IDEA.
*
* @author: 霍运浩
* @date: 2018-09-23
* @time: 23:10
*/
@RestController
@RequestMapping("")
public class DictionaryController {
@Autowired
DictionaryService dictionaryService;
@RequestMapping(value = "dicP",method = RequestMethod.POST)
public Msg addDic(@RequestBody Dictionary dictionary){
dictionaryService.addDic(dictionary);
return Msg.success().add("msg","添加成功");
}
@RequestMapping(value = "dicP/{id}",method = RequestMethod.PUT)
public Msg updateDic(@PathVariable("id") String id,@RequestBody Dictionary dictionary){
dictionary.setDictionaryId(id);
dictionaryService.updateDic(dictionary);
return Msg.success().add("msg","更新成功");
}
@RequestMapping(value = "dicG/{id}",method =RequestMethod.GET)
public Msg getDicById(@PathVariable("id") String id){
return Msg.success().add("msg",dictionaryService.getDic(id));
}
/**
* 查询所有父类的dic
* @return
*/
@RequestMapping(value = "dicPa",method = RequestMethod.GET)
public Msg getDicPa(){
List<Dictionary> dictionaryList=dictionaryService.getDicPa();
return Msg.success().add("msg",dictionaryList);
}
/**
* 获取父字典下的子菜单
*/
@RequestMapping(value = "dicSon/{id}",method = RequestMethod.GET)
public Msg getSonPa(@PathVariable("id") String id){
List<Dictionary> dictionaryList=dictionaryService.getSonPa(id);
return Msg.success().add("msg",dictionaryList);
}
/**
* 删除字典通过字典id
*/
@RequestMapping(value = "dicD/{id}",method =RequestMethod.DELETE)
public Msg deleteDic(@PathVariable("id") String id){
dictionaryService.deleteDic(id);
return Msg.success().add("msg","删除成功");
}
/**
* 获取字典树
*/
@RequestMapping(value = "dicTree",method = RequestMethod.GET)
public Msg getTreeDic(){
List<Dictionary> dictionaryList=dictionaryService.getTreeDic();
return Msg.success().add("msg",dictionaryList);
}
}
|
package dynamic.programing;
import java.util.Arrays;
public class LongestIncreasingSubsequence {
public static void main(String[] args) {
int[] array = {3,4,-1,0,6,2,3};
// int[] array = {2,5,1,8,3};
int[] measure = new int[array.length];
int[] sequence = new int[array.length];
Arrays.fill(measure, 1);
for(int i=0;i<array.length;i++){
sequence[i]=i;
}
for(int i=1; i<array.length; i++){
for(int j=0; j<i; j++){
if(array[j]<array[i] && measure[i] < measure[j]+1){
measure[i] = measure[j] + 1;
sequence[i] = j;
}
}
}
int maxValue = -1;
int maxIndex = -1;
for(int i=0;i<array.length;i++){
if(measure[i]>maxValue){
maxValue=measure[i];
maxIndex=i;
}
}
System.out.println(maxValue);
do{
System.out.print(array[maxIndex]+" ");
maxIndex = sequence[maxIndex];
}while(sequence[maxIndex]!=maxIndex);
System.out.print(array[maxIndex]);
}
}
|
//License
/***
* Java Modbus Library (jamod)
* Copyright (c) 2002-2004, jamod development team
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the author nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS
* IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
***/
package net.wimpi.modbus.io;
import java.io.IOException;
import java.io.InputStream;
import java.io.FilterInputStream;
/**
* Class implementing a specialized <tt>InputStream</tt> which
* handles binary transmitted messages.
*
* @author Dieter Wimberger
* @version 1.2rc1 (09/11/2004)
*
* @see ModbusBINTransport#FRAME_START
* @see ModbusBINTransport#FRAME_END
*/
public class BINInputStream
extends FilterInputStream {
/**
* Constructs a new <tt>BINInputStream</tt> instance
* reading from the given <tt>InputStream</tt>.
*
* @param in a base input stream to be wrapped.
*/
public BINInputStream(InputStream in) {
super(in);
if(!in.markSupported()) {
throw new RuntimeException("Accepts only input streams that support marking.");
}
}//constructor
/**
* Reads a byte from the BIN encoded stream.
*
* @return int the byte read from the stream.
* @throws java.io.IOException if an I/O error occurs.
*/
public int read() throws IOException {
int ch = in.read();
if(ch == -1) {
return -1;
} else if (ch == ModbusBINTransport.FRAME_START_TOKEN) {
in.mark(1);
//read next
ch = in.read();
if(ch == ModbusBINTransport.FRAME_START_TOKEN) {
return ch;
} else {
in.reset();
return ModbusBINTransport.FRAME_START;
}
} else if(ch == ModbusBINTransport.FRAME_END_TOKEN) {
in.mark(1);
//read next
ch = in.read();
if(ch == ModbusBINTransport.FRAME_END_TOKEN) {
return ch;
} else {
in.reset();
return ModbusBINTransport.FRAME_END;
}
} else {
return ch;
}
}//read
}//class BINInputStream
|
package com.krish.impl;
import java.util.LinkedList;
import java.util.Queue;
public class BinaryTreeImpl {
public static void main(String[] args) {
BST bst = new BST();
bst.add(8);
bst.add(4);
bst.add(9);
bst.add(5);
bst.add(11);
bst.add(3);
bst.levelOrder();
}
}
class BST {
BNode root;
public void levelOrder() {
levelOrder(root);
}
private void levelOrder(BNode node) {
if(node != null) {
Queue<BNode> queue = new LinkedList<BNode>();
queue.add(node);
while(!queue.isEmpty()) {
BNode temp = queue.poll();
System.out.print(temp.data + " ");
if(temp.left != null) {
queue.add(temp.left);
}
if(temp.right != null) {
queue.add(temp.right);
}
}
}
}
public BNode findLCA(int n1, int n2) {
return findLCA(root, n1, n2);
}
private BNode findLCA(BNode node, int n1, int n2) {
if (node == null)
return null;
if (node.data == n1 || node.data == n2)
return node;
BNode left_lca_node = findLCA(node.left, n1, n2);
BNode right_lca_node = findLCA(node.right, n1, n2);
if(left_lca_node!= null && right_lca_node != null)
return node;
return (left_lca_node !=null) ? left_lca_node : right_lca_node;
}
public boolean lookup(int data) {
return lookup(root, data);
}
private boolean lookup(BNode node, int data) {
if (node == null) {
return false;
} else {
if (node.data == data) {
return true;
} else {
if (data < node.data) {
return lookup(node.left, data);
} else {
return lookup(node.right, data);
}
}
}
}
public void add(int data) {
root = add(root, data);
}
private BNode add(BNode node, int data) {
if (node == null) {
node = new BNode(data);
} else {
if (data < node.data) {
node.left = add(node.left, data);
} else {
node.right = add(node.right, data);
}
}
return node;
}
}
class BNode {
BNode left;
BNode right;
int data;
public BNode(int data) {
this.data = data;
}
}
|
package com.jaiaxn.design.pattern.created.abstractfactory;
import com.jaiaxn.design.pattern.created.abstractfactory.equipment.Equipment;
import com.jaiaxn.design.pattern.created.factory.hero.HeroMan;
/**
* @author: wang.jiaxin
* @date: 2019年08月16日
* @description: 抽象工厂模式
**/
public class AbstractFactoryDemoTest {
public static void main(String[] args) {
AbstractFactory equipmentFactory = FactoryProducer.getAbstractFactory("equipment");
Equipment xieZi = equipmentFactory.getEquipment("XIEZI");
xieZi.attribute();
Equipment wuJin = equipmentFactory.getEquipment("WUJIN");
wuJin.attribute();
AbstractFactory heroFactory = FactoryProducer.getAbstractFactory("hero");
HeroMan top = heroFactory.getHero("TOP");
top.play();
HeroMan jug = heroFactory.getHero("JUG");
jug.play();
HeroMan mid = heroFactory.getHero("MID");
mid.play();
HeroMan adc = heroFactory.getHero("ADC");
adc.play();
HeroMan sup = heroFactory.getHero("SUP");
sup.play();
}
// 输出
// 鞋子--移速、抗性
// 无尽--攻击、暴击
// 海洋之灾普朗克-上单
// 盲僧李青-打野
// 疾风剑豪压缩-中单
// 暗夜猎手薇恩-射手
// 魂锁典狱长锤石-辅助
}
|
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.StringTokenizer;
import java.util.Vector;
public class B3service {
private BufferedWriter bw=null;
private void initsave()
{
try{bw=new BufferedWriter(new FileWriter("insa.txt",true));
}
catch(IOException e){
}
}
public void saveFile (B3vo data)
{
initsave();
try{
bw.write(data.getName()+data.getAge());
bw.newLine();
}catch(IOException e){}
finally{
if(bw!=null)try{bw.close();}catch(Exception e){}
}
}
public Vector viewFile()
{
BufferedReader br = null;
Vector v= new Vector();
try
{
br=new BufferedReader(new FileReader("insa.txt"));
String content=null;
StringTokenizer stk;
while((content=br.readLine())!=null)
{
stk=new StringTokenizer(content, ",");
String name=stk.nextToken();
int age=Integer.parseInt(stk.nextToken().trim());
Vector data=new Vector();
data.add(name);
data.add(age);
v.add(data);
}
}catch(FileNotFoundException e)
{
System.out.println(e);
}catch(IOException e)
{
System.out.println(e);
}finally{if(br!=null)try{br.close();}catch(IOException e){}
}
return v;
}
}
|
package com.zzh.cloud.controller;
import com.zzh.cloud.entity.User;
import com.zzh.cloud.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
/**
* @author zhaozh
* @version 1.0
* @date 2018-1-21 1:01
**/
@RestController
public class UserDevtoolsController {
@Autowired
private UserRepository userRepository;
@GetMapping("/simple/{id}")
public User findById(@PathVariable Long id) {
return this.userRepository.findOne(id);
}
@GetMapping("simple")
public String simple() {
return "simple-2018-01";
}
@GetMapping("simple2")
public String simple2() {
return "simple2-2019";
}
}
|
package Abstract;
import Entities.Customer;
import Entities.Games;
public class BaseSellerManager implements SellerService{
@Override
public void sell(Games games, Customer customer) {
System.out.println(games.getGameName() + " oyunu " + customer.getFirstName() + " kişisine "+games.getPrice() +" TL ye satıldı ");
}
}
|
package Assignment2new;
public class Student extends Person {
String nextId;
int studentId;
Major studentMajor;
public int getStudentId() {
return studentId;
}
public Major getStudentMajor() {
return studentMajor;
}
public void setStudentMajor(Major studentMajor) {
this.studentMajor = studentMajor;
}
public Student( String firstName, String lastName) {
super(firstName, lastName);
// this.nextId = nextId;
// this.studentId = studentId;
}
}
|
package io.jenkins.plugins.audit.listeners;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import hudson.security.SecurityRealm;
import jenkins.model.IdStrategy;
import jenkins.model.Jenkins;
import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
import org.acegisecurity.Authentication;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.message.StructuredDataMessage;
import org.apache.logging.log4j.test.appender.ListAppender;
import org.jenkinsci.plugins.mocksecurityrealm.MockSecurityRealm;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.JenkinsRule.WebClient;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.util.List;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@RunWith(JUnitParamsRunner.class)
public class UserLoginListenerTest {
private ListAppender app;
private WebClient client;
private final String USERS = "alice admin\nbob dev\ncharlie qa\ndebbie admin qa";
private final SecurityRealm realm = new MockSecurityRealm(USERS, null, false,
IdStrategy.CASE_INSENSITIVE, IdStrategy.CASE_INSENSITIVE);
private static void assertEventCount(final List<LogEvent> events, final int expected) {
assertEquals("Incorrect number of events.", expected, events.size());
}
private static WebClient logout(final WebClient wc) throws IOException, SAXException {
wc.goTo("logout");
return wc;
}
@Rule
public JenkinsRule j = new JenkinsRule();
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Before
public void setup() throws IOException, SAXException {
// setup a mock security realm with dummy usernames
j.jenkins.setSecurityRealm(realm);
client = j.createWebClient();
logout(client);
app = ListAppender.getListAppender("AuditList").clear();
}
@After
public void teardown() {
app.clear();
}
@Issue("JENKINS-54087")
@Test
@Parameters({
"1, alice, alice, alice",
"1, bob, bob, bob",
"1, charlie, charlie, charlie",
"1, debbie, debbie, debbie"
})
public void testValidUserLoginEventsLogged(int expectedCount, String expected, String username, String password) throws Exception {
assertEventCount(app.getEvents(), 0);
client.login(username, password);
assertEventCount(app.getEvents(), expectedCount);
client.executeOnServer(() -> {
Authentication a = Jenkins.getAuthentication();
assertEquals(expected, a.getName());
return null;
});
}
@Issue("JENKINS-54087")
@Test
public void testValidUsernameInMessageLogged() throws Exception {
assertEventCount(app.getEvents(), 0);
client.login("debbie", "debbie");
StructuredDataMessage logMessage = (StructuredDataMessage) app.getEvents().get(0).getMessage();
assertEventCount(app.getEvents(), 1);
assertTrue(logMessage.toString().contains("login"));
assertEquals("debbie", logMessage.get("userId"));
}
@Issue("JENKINS-54087")
@Test
public void testInvalidUserLoginFailsWithError() throws Exception {
expectedException.expect(FailingHttpStatusCodeException.class);
expectedException.expectMessage(containsString("Unauthorized"));
client.login("john", "john");
assertEventCount(app.getEvents(), 0);
}
}
|
package com.otala.codereveals.web.rest;
import com.otala.codereveals.CodeRevealsApplicationApp;
import com.otala.codereveals.config.TestSecurityConfiguration;
import com.otala.codereveals.domain.Candidate;
import com.otala.codereveals.repository.CandidateRepository;
import com.otala.codereveals.web.rest.errors.ExceptionTranslator;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.Validator;
import javax.persistence.EntityManager;
import java.util.List;
import static com.otala.codereveals.web.rest.TestUtil.createFormattingConversionService;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Integration tests for the {@link CandidateResource} REST controller.
*/
@SpringBootTest(classes = {CodeRevealsApplicationApp.class, TestSecurityConfiguration.class})
public class CandidateResourceIT {
private static final String DEFAULT_FIRST_NAME = "AAAAAAAAAA";
private static final String UPDATED_FIRST_NAME = "BBBBBBBBBB";
private static final String DEFAULT_LAST_NAME = "AAAAAAAAAA";
private static final String UPDATED_LAST_NAME = "BBBBBBBBBB";
private static final String DEFAULT_EMAIL = "AAAAAAAAAA";
private static final String UPDATED_EMAIL = "BBBBBBBBBB";
@Autowired
private CandidateRepository candidateRepository;
@Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
@Autowired
private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
@Autowired
private ExceptionTranslator exceptionTranslator;
@Autowired
private EntityManager em;
@Autowired
private Validator validator;
private MockMvc restCandidateMockMvc;
private Candidate candidate;
@BeforeEach
public void setup() {
MockitoAnnotations.initMocks(this);
final CandidateResource candidateResource = new CandidateResource(candidateRepository);
this.restCandidateMockMvc = MockMvcBuilders.standaloneSetup(candidateResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setConversionService(createFormattingConversionService())
.setMessageConverters(jacksonMessageConverter)
.setValidator(validator).build();
}
/**
* Create an entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static Candidate createEntity(EntityManager em) {
Candidate candidate = new Candidate()
.firstName(DEFAULT_FIRST_NAME)
.lastName(DEFAULT_LAST_NAME)
.email(DEFAULT_EMAIL);
return candidate;
}
/**
* Create an updated entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static Candidate createUpdatedEntity(EntityManager em) {
Candidate candidate = new Candidate()
.firstName(UPDATED_FIRST_NAME)
.lastName(UPDATED_LAST_NAME)
.email(UPDATED_EMAIL);
return candidate;
}
@BeforeEach
public void initTest() {
candidate = createEntity(em);
}
@Test
@Transactional
public void createCandidate() throws Exception {
int databaseSizeBeforeCreate = candidateRepository.findAll().size();
// Create the Candidate
restCandidateMockMvc.perform(post("/api/candidates")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(candidate)))
.andExpect(status().isCreated());
// Validate the Candidate in the database
List<Candidate> candidateList = candidateRepository.findAll();
assertThat(candidateList).hasSize(databaseSizeBeforeCreate + 1);
Candidate testCandidate = candidateList.get(candidateList.size() - 1);
assertThat(testCandidate.getFirstName()).isEqualTo(DEFAULT_FIRST_NAME);
assertThat(testCandidate.getLastName()).isEqualTo(DEFAULT_LAST_NAME);
assertThat(testCandidate.getEmail()).isEqualTo(DEFAULT_EMAIL);
}
@Test
@Transactional
public void createCandidateWithExistingId() throws Exception {
int databaseSizeBeforeCreate = candidateRepository.findAll().size();
// Create the Candidate with an existing ID
candidate.setId(1L);
// An entity with an existing ID cannot be created, so this API call must fail
restCandidateMockMvc.perform(post("/api/candidates")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(candidate)))
.andExpect(status().isBadRequest());
// Validate the Candidate in the database
List<Candidate> candidateList = candidateRepository.findAll();
assertThat(candidateList).hasSize(databaseSizeBeforeCreate);
}
@Test
@Transactional
public void getAllCandidates() throws Exception {
// Initialize the database
candidateRepository.saveAndFlush(candidate);
// Get all the candidateList
restCandidateMockMvc.perform(get("/api/candidates?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(candidate.getId().intValue())))
.andExpect(jsonPath("$.[*].firstName").value(hasItem(DEFAULT_FIRST_NAME)))
.andExpect(jsonPath("$.[*].lastName").value(hasItem(DEFAULT_LAST_NAME)))
.andExpect(jsonPath("$.[*].email").value(hasItem(DEFAULT_EMAIL)));
}
@Test
@Transactional
public void getCandidate() throws Exception {
// Initialize the database
candidateRepository.saveAndFlush(candidate);
// Get the candidate
restCandidateMockMvc.perform(get("/api/candidates/{id}", candidate.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.id").value(candidate.getId().intValue()))
.andExpect(jsonPath("$.firstName").value(DEFAULT_FIRST_NAME))
.andExpect(jsonPath("$.lastName").value(DEFAULT_LAST_NAME))
.andExpect(jsonPath("$.email").value(DEFAULT_EMAIL));
}
@Test
@Transactional
public void getNonExistingCandidate() throws Exception {
// Get the candidate
restCandidateMockMvc.perform(get("/api/candidates/{id}", Long.MAX_VALUE))
.andExpect(status().isNotFound());
}
@Test
@Transactional
public void updateCandidate() throws Exception {
// Initialize the database
candidateRepository.saveAndFlush(candidate);
int databaseSizeBeforeUpdate = candidateRepository.findAll().size();
// Update the candidate
Candidate updatedCandidate = candidateRepository.findById(candidate.getId()).get();
// Disconnect from session so that the updates on updatedCandidate are not directly saved in db
em.detach(updatedCandidate);
updatedCandidate
.firstName(UPDATED_FIRST_NAME)
.lastName(UPDATED_LAST_NAME)
.email(UPDATED_EMAIL);
restCandidateMockMvc.perform(put("/api/candidates")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(updatedCandidate)))
.andExpect(status().isOk());
// Validate the Candidate in the database
List<Candidate> candidateList = candidateRepository.findAll();
assertThat(candidateList).hasSize(databaseSizeBeforeUpdate);
Candidate testCandidate = candidateList.get(candidateList.size() - 1);
assertThat(testCandidate.getFirstName()).isEqualTo(UPDATED_FIRST_NAME);
assertThat(testCandidate.getLastName()).isEqualTo(UPDATED_LAST_NAME);
assertThat(testCandidate.getEmail()).isEqualTo(UPDATED_EMAIL);
}
@Test
@Transactional
public void updateNonExistingCandidate() throws Exception {
int databaseSizeBeforeUpdate = candidateRepository.findAll().size();
// Create the Candidate
// If the entity doesn't have an ID, it will throw BadRequestAlertException
restCandidateMockMvc.perform(put("/api/candidates")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(candidate)))
.andExpect(status().isBadRequest());
// Validate the Candidate in the database
List<Candidate> candidateList = candidateRepository.findAll();
assertThat(candidateList).hasSize(databaseSizeBeforeUpdate);
}
@Test
@Transactional
public void deleteCandidate() throws Exception {
// Initialize the database
candidateRepository.saveAndFlush(candidate);
int databaseSizeBeforeDelete = candidateRepository.findAll().size();
// Delete the candidate
restCandidateMockMvc.perform(delete("/api/candidates/{id}", candidate.getId())
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isNoContent());
// Validate the database contains one less item
List<Candidate> candidateList = candidateRepository.findAll();
assertThat(candidateList).hasSize(databaseSizeBeforeDelete - 1);
}
}
|
package com.fr.demo;
import java.io.File;
import java.util.logging.Level;
import com.fr.base.FRContext;
import com.fr.report.CellElement;
import com.fr.report.Report;
import com.fr.report.TemplateWorkBook;
import com.fr.report.WorkBook;
import com.fr.report.WorkSheet;
import com.fr.report.io.TemplateImporter;
import com.fr.web.Reportlet;
import com.fr.web.ReportletRequest;
public class ChangeRowAndCol extends Reportlet{
public TemplateWorkBook createReport(ReportletRequest reportletrequest){
//定义最终需要返回的WorkBook对象
WorkBook workbook = new WorkBook();
WorkSheet newworksheet = new WorkSheet();
String change = "0";
try{
//读取模板保存为WorkBook对象
File cptfile = new File("C:\\FineReport6.5\\WebReport\\WEB-INF\\reportlets\\cross.cpt");
TemplateImporter tplimp = new TemplateImporter();
workbook = tplimp.generateTemplate(cptfile);
//读取请求中的参数判断是否需要切换行列显示,0表示不切换,1表示切换
if(reportletrequest.getParameter("change") != null){
change = reportletrequest.getParameter("change").toString();
}
if(change.equals("1")){
//获得单元格需要首先获得单元格所在的报表
Report report = workbook.getReport(0);
//遍历单元格
int col=0,row=0;
byte direction = 0;
java.util.Iterator it = report.cellIterator();
while(it.hasNext()){
CellElement cell = (CellElement) it.next();
//获取单元格的行号与列号并互换
col = cell.getColumn();
row = cell.getRow();
cell.setColumn(row);
cell.setRow(col);
//获取原单元格的扩展方向,0表示纵向扩展,1表示横向扩展
direction = cell.getCellExpandAttr().getDirection();
if(direction == 0){
cell.getCellExpandAttr().setDirection((byte) 1);
}else if(direction == 1){
cell.getCellExpandAttr().setDirection((byte) 0);
}
//将改变后的单元格添加进新的WorkSheet中
newworksheet.addCellElement(cell);
}
//替换原sheet
workbook.setReport(0, newworksheet);
}
}catch (Exception e) {
e.printStackTrace();
}
return workbook;
}
}
|
package mytest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import javax.swing.text.StyledEditorKit.ItalicAction;
import org.junit.Test;
public class CollectionTest{
@Test
public void test1(){
Collection list = new ArrayList();
list.add("aa");
list.add("bb");
System.out.println(list.size());
Object[] array = list.toArray();
System.out.println(Arrays.toString(array));
for (Object object : array) {
System.out.println(object);
}
}
@Test
public void test(){
String[] names = {"aa","cc"};
List asList2 = Arrays.asList(names);
List asList = Arrays.asList(new String[]{"aa","bb","cc"});
for (Object o : asList2) {
System.out.println(o);
}
System.out.println("----------------------");
for (Object obj : asList) {
System.out.println(obj);
}
}
@Test
public void test3(){
String[] str = {"a","b","d"};
List list = Arrays.asList(str);
System.out.println(list.size());
list.set(0, "cc");
// list.add("ff");
for (Object object : list) {
System.out.println(object);
}
// public static void main(String[] args) {
// Integer[] datas = {1,2,3,4,5};
// List<Integer> list = Arrays.asList(datas);
// list.add(5);
// System.out.println(list.size());
}
}
|
/*
* Created on Mar 18, 2007
*
*/
package com.citibank.ods.modules.product.productfamilyprvt.functionality;
import java.util.Date;
import com.citibank.ods.common.functionality.ODSDetailFnc;
import com.citibank.ods.common.functionality.valueobject.BaseFncVO;
import com.citibank.ods.entity.pl.TplProdSubFamlPrvtEntity;
import com.citibank.ods.entity.pl.TplProductFamilyPrvtEntity;
import com.citibank.ods.entity.pl.TplProductFamilyPrvtMovEntity;
import com.citibank.ods.entity.pl.valueobject.BaseTplProductFamilyPrvtEntityVO;
import com.citibank.ods.modules.product.productfamilyprvt.functionality.valueobject.BaseProductFamilyPrvtDetailFncVO;
import com.citibank.ods.modules.product.productfamilyprvt.functionality.valueobject.ProductFamilyPrvtDetailFncVO;
import com.citibank.ods.persistence.pl.dao.BaseTplProductFamilyPrvtDAO;
import com.citibank.ods.persistence.pl.dao.TplProdSubFamlPrvtDAO;
import com.citibank.ods.persistence.pl.dao.TplProductFamilyPrvtDAO;
import com.citibank.ods.persistence.pl.dao.TplProductFamilyPrvtMovDAO;
import com.citibank.ods.persistence.pl.dao.factory.ODSDAOFactory;
/**
* @author leonardo.nakada
*
*/
public class ProductFamilyPrvtDetailFnc extends BaseProductFamilyPrvtDetailFnc
implements ODSDetailFnc
{
/*
* Constante família
*/
private static final String C_PRODUCT_FAMILY_PRVT_REG = "O registro de família de produtos";
/*
* Sub-Família
*/
private static final String C_PROD_SUB_FAML_NAME = "Sub-Famílias";
/**
* Retorna o DAO utilizado pelo método load da super classe
*
* @see com.citibank.ods.modules.product.productfamilyprvt.functionality.BaseProductFamilyPrvtDetailFnc#getDAO()
*/
protected BaseTplProductFamilyPrvtDAO getDAO()
{
return ODSDAOFactory.getInstance().getTplProductFamilyPrvtDAO();
}
/**
* Retorna uma instância do FncVO
*/
public BaseFncVO createFncVO()
{
return new ProductFamilyPrvtDetailFncVO();
}
/**
* Insere os dados de uma Família de Produtos.
*/
public void insert( BaseFncVO fncVO_ )
{
validateInsert( fncVO_ );
if ( !fncVO_.hasErrors() )
{
ProductFamilyPrvtDetailFncVO detailFncVO = ( ProductFamilyPrvtDetailFncVO ) fncVO_;
TplProductFamilyPrvtEntity tplProductFamilyPrvtEntity = ( TplProductFamilyPrvtEntity ) detailFncVO.getBaseTplProductFamilyPrvtEntity();
BaseTplProductFamilyPrvtEntityVO familyPrvtEntityVO = tplProductFamilyPrvtEntity.getData();
familyPrvtEntityVO.setLastUpdDate( new Date() );
familyPrvtEntityVO.setLastUpdUserId( fncVO_.getLoggedUser() != null
? fncVO_.getLoggedUser().getUserID()
: "" );
TplProductFamilyPrvtMovEntity movEntity = new TplProductFamilyPrvtMovEntity(
tplProductFamilyPrvtEntity,
TplProductFamilyPrvtMovEntity.C_OPERN_CODE_INSERT );
TplProductFamilyPrvtMovDAO productFamilyPrvtMovDAO = ODSDAOFactory.getInstance().getTplProductFamilyPrvtMovDAO();
productFamilyPrvtMovDAO.insert( movEntity );
}
}
/**
* Atualiza os dados de uma Família de Produtos.
*/
public void update( BaseFncVO fncVO_ )
{
validateUpdate( fncVO_ );
if ( !fncVO_.hasErrors() )
{
ProductFamilyPrvtDetailFncVO detailFncVO = ( ProductFamilyPrvtDetailFncVO ) fncVO_;
TplProductFamilyPrvtEntity tplProductFamilyPrvtEntity = ( TplProductFamilyPrvtEntity ) detailFncVO.getBaseTplProductFamilyPrvtEntity();
BaseTplProductFamilyPrvtEntityVO familyPrvtEntityVO = tplProductFamilyPrvtEntity.getData();
familyPrvtEntityVO.setLastUpdDate( new Date() );
familyPrvtEntityVO.setLastUpdUserId( fncVO_.getLoggedUser() != null
? fncVO_.getLoggedUser().getUserID()
: "" );
TplProductFamilyPrvtMovEntity movEntity = new TplProductFamilyPrvtMovEntity(
tplProductFamilyPrvtEntity,
TplProductFamilyPrvtMovEntity.C_OPERN_CODE_UPDATE );
TplProductFamilyPrvtMovDAO productFamilyPrvtMovDAO = ODSDAOFactory.getInstance().getTplProductFamilyPrvtMovDAO();
productFamilyPrvtMovDAO.insert( movEntity );
}
}
/**
* Remove uma Família de Produtos.
*/
public void delete( BaseFncVO fncVO_ )
{
validateDelete( fncVO_ );
if ( !fncVO_.hasErrors() )
{
ProductFamilyPrvtDetailFncVO detailFncVO = ( ProductFamilyPrvtDetailFncVO ) fncVO_;
super.loadProductFamily( detailFncVO );
TplProductFamilyPrvtEntity tplProductFamilyPrvtEntity = ( TplProductFamilyPrvtEntity ) detailFncVO.getBaseTplProductFamilyPrvtEntity();
BaseTplProductFamilyPrvtEntityVO familyPrvtEntityVO = tplProductFamilyPrvtEntity.getData();
familyPrvtEntityVO.setLastUpdDate( new Date() );
familyPrvtEntityVO.setLastUpdUserId( fncVO_.getLoggedUser() != null
? fncVO_.getLoggedUser().getUserID()
: "" );
TplProductFamilyPrvtMovEntity movEntity = new TplProductFamilyPrvtMovEntity(
tplProductFamilyPrvtEntity,
TplProductFamilyPrvtMovEntity.C_OPERN_CODE_DELETE );
TplProductFamilyPrvtMovDAO productFamilyPrvtMovDAO = ODSDAOFactory.getInstance().getTplProductFamilyPrvtMovDAO();
productFamilyPrvtMovDAO.insert( movEntity );
}
}
/**
* Realiza as validações - Insert
*/
public void validateInsert( BaseFncVO fncVO_ )
{
ProductFamilyPrvtDetailFncVO detailFncVO = ( ProductFamilyPrvtDetailFncVO ) fncVO_;
BaseTplProductFamilyPrvtEntityVO familyPrvtEntityVO = detailFncVO.getBaseTplProductFamilyPrvtEntity().getData();
// Validar Campos Obrigatórios
if ( familyPrvtEntityVO.getProdFamlCode() == null
|| familyPrvtEntityVO.getProdFamlCode().intValue() == 0 )
{
fncVO_.addError( ProductFamilyPrvtDetailFncVO.C_ERROR_MANDATORY_FIELD,
C_DISPLAY_NAME_CODE );
}
if ( familyPrvtEntityVO.getProdFamlName() == null
|| familyPrvtEntityVO.getProdFamlName().equals( "" ) )
{
fncVO_.addError( ProductFamilyPrvtDetailFncVO.C_ERROR_MANDATORY_FIELD,
C_DISPLAY_NAME );
}
// Validar se já existe um registro com este codigo na "Current",
// caso os campos obrigatórios estejam presentes
if ( !fncVO_.hasErrors() )
{
if ( this.existsActive( detailFncVO ) )
{
fncVO_.addError( ProductFamilyPrvtDetailFncVO.C_ERROR_DUPLICATE_PK );
}
}
// Validar se já existe movimento com este codigo, caso os campos
// obrigatórios estejam presentes
if ( this.existsInMovement( detailFncVO ) )
{
fncVO_.addError( ProductFamilyPrvtDetailFncVO.C_ERROR_IN_MOVEMENT );
}
}
/**
* Realiza as validações - Update
*/
public void validateUpdate( BaseFncVO fncVO_ )
{
ProductFamilyPrvtDetailFncVO detailFncVO = ( ProductFamilyPrvtDetailFncVO ) fncVO_;
BaseTplProductFamilyPrvtEntityVO familyPrvtEntityVO = detailFncVO.getBaseTplProductFamilyPrvtEntity().getData();
// Validar Campos Obrigatórios
if ( familyPrvtEntityVO.getProdFamlCode() == null
|| familyPrvtEntityVO.getProdFamlCode().intValue() == 0 )
{
fncVO_.addError( ProductFamilyPrvtDetailFncVO.C_ERROR_MANDATORY_FIELD,
C_DISPLAY_NAME_CODE );
}
if ( familyPrvtEntityVO.getProdFamlName() == null
|| familyPrvtEntityVO.getProdFamlName().equals( "" ) )
{
fncVO_.addError( ProductFamilyPrvtDetailFncVO.C_ERROR_MANDATORY_FIELD,
C_DISPLAY_NAME );
}
// Validar se existe um registro com este codigo na "Current",
// caso os campos obrigatórios estejam presentes
if ( !fncVO_.hasErrors() )
{
if ( !this.existsActive( detailFncVO ) )
{
fncVO_.addError( ProductFamilyPrvtDetailFncVO.C_ERROR_PK_NOT_FOUND );
}
}
// Validar se já existe movimento com este codigo, caso os campos
// obrigatórios estejam presentes
if ( !fncVO_.hasErrors() )
{
if ( this.existsInMovement( detailFncVO ) )
{
fncVO_.addError( ProductFamilyPrvtDetailFncVO.C_ERROR_IN_MOVEMENT );
}
}
}
/**
* Realiza as validações - Delete
*/
public void validateDelete( BaseFncVO fncVO_ )
{
ProductFamilyPrvtDetailFncVO detailFncVO = ( ProductFamilyPrvtDetailFncVO ) fncVO_;
// Validar se existe um registro com este codigo na "Current",
// caso os campos obrigatórios estejam presentes
if ( !fncVO_.hasErrors() )
{
if ( !this.existsActive( detailFncVO ) )
{
fncVO_.addError( ProductFamilyPrvtDetailFncVO.C_ERROR_PK_NOT_FOUND );
}
if ( this.existsInMovement( detailFncVO ) )
{
// Validar se já existe movimento com este codigo, caso os campos
// obrigatórios estejam presentes
fncVO_.addError( ProductFamilyPrvtDetailFncVO.C_ERROR_IN_MOVEMENT );
}
// Verifica se alguém deste registro
if ( this.existsDependency( detailFncVO ) )
{
fncVO_.addError( ProductFamilyPrvtDetailFncVO.C_ERROR_IS_REFERENCED,
C_PRODUCT_FAMILY_PRVT_REG, C_PROD_SUB_FAML_NAME );
}
}
}
/**
* Carregamentos iniciais - Detail
*/
public void loadForConsult( BaseFncVO fncVO_ )
{
//
}
/**
* Carregamentos iniciais - Insert
*/
public void loadForInsert( BaseFncVO fncVO_ )
{
ProductFamilyPrvtDetailFncVO detailFncVO = ( ProductFamilyPrvtDetailFncVO ) fncVO_;
detailFncVO.getBaseTplProductFamilyPrvtEntity().getData().setProdFamlCode(
null );
detailFncVO.getBaseTplProductFamilyPrvtEntity().getData().setProdFamlName(
null );
detailFncVO.getBaseTplProductFamilyPrvtEntity().getData().setProdFamlText(
null );
}
/**
* Carregamentos iniciais - Update
*/
public void loadForUpdate( BaseFncVO fncVO_ )
{
ProductFamilyPrvtDetailFncVO detailFncVO = ( ProductFamilyPrvtDetailFncVO ) fncVO_;
// Validar se já existe movimento com este codigo, caso os campos
// obrigatórios estejam presentes
if ( this.existsInMovement( detailFncVO ) )
{
fncVO_.addError( ProductFamilyPrvtDetailFncVO.C_ERROR_IN_MOVEMENT );
}
else
{
super.loadProductFamily( ( BaseProductFamilyPrvtDetailFncVO ) fncVO_ );
}
}
/**
* Carregamentos iniciais - Delete
*/
public void loadForDelete( BaseFncVO fncVO_ )
{
//
}
/**
* Verifica se existe um registro na tabela de movimento
*/
private boolean existsInMovement( ProductFamilyPrvtDetailFncVO detailFncVO_ )
{
TplProductFamilyPrvtMovDAO familyPrvtMovDAO = ODSDAOFactory.getInstance().getTplProductFamilyPrvtMovDAO();
TplProductFamilyPrvtMovEntity familyPrvtMovEntity = new TplProductFamilyPrvtMovEntity();
familyPrvtMovEntity.getData().setProdFamlCode(
detailFncVO_.getBaseTplProductFamilyPrvtEntity().getData().getProdFamlCode() );
return familyPrvtMovDAO.exists( familyPrvtMovEntity );
}
/*
* Verifica se já existe um registro na tabela de "Current" com o código
* passado e o seu status é "Ativo"
*/
private boolean existsActive( ProductFamilyPrvtDetailFncVO detailFncVO_ )
{
TplProductFamilyPrvtDAO familyPrvtDAO = ODSDAOFactory.getInstance().getTplProductFamilyPrvtDAO();
return familyPrvtDAO.existsActive( ( TplProductFamilyPrvtEntity ) detailFncVO_.getBaseTplProductFamilyPrvtEntity() );
}
/*
* Verifica se existe alguma sub-família com status ativo, que utiliza esta
* família
*/
private boolean existsDependency( ProductFamilyPrvtDetailFncVO detailFncVO_ )
{
// Recupera a instância do DAO
TplProdSubFamlPrvtDAO prodSubFamlPrvtDAO = ODSDAOFactory.getInstance().getTplProductSubFamilyPrvtDAO();
// Cria uma entity de sub-família setando o id da família
TplProdSubFamlPrvtEntity subFamlEntity = new TplProdSubFamlPrvtEntity();
subFamlEntity.getData().setProdFamlCode(
detailFncVO_.getBaseTplProductFamilyPrvtEntity().getData().getProdFamlCode() );
// Verifica se existe alguma dependencia
return prodSubFamlPrvtDAO.existsProductFamilyPrvtDependency( subFamlEntity );
}
}
|
import java.util.Stack;
public class reversePrint {
static void reversePrint(SinglyLinkedListNode head) {
if (head == null) {
System.out.println("");
}
SinglyLinkedListNode iter = head;
Stack<Integer> stack = new Stack<>();
while (iter != null) {
stack.push(iter.data);
iter = iter.next;
}
while (!stack.isEmpty()) {
System.out.println(stack.pop());
}
}
}
|
package com.firedata.qtacker.repository.search;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Configuration;
/**
* Configure a Mock version of {@link LogUserSearchRepository} to test the
* application without starting Elasticsearch.
*/
@Configuration
public class LogUserSearchRepositoryMockConfiguration {
@MockBean
private LogUserSearchRepository mockLogUserSearchRepository;
}
|
package com.app.upworktest.activities;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.content.Intent;
import android.os.Bundle;
import com.app.upworktest.R;
import com.app.upworktest.models.QuizSession;
import com.app.upworktest.utils.JSONObjectCreator;
import com.app.upworktest.utils.UIUtils;
import java.io.IOException;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Setup support action bar.
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setTitle(R.string.app_name);
}
findViewById(R.id.btnStart).setOnClickListener(v -> {
QuizSession session = readQuizJSON();
if (session != null && session.questions != null) {
Intent intent = new Intent(MainActivity.this, QuizActivity.class);
intent.putExtra(QuizActivity.EXTRA_QUIZ_SESSION,
JSONObjectCreator.createJson(session));
startActivity(intent);
} else {
UIUtils.showMessage(MainActivity.this, R.string.json_failure);
}
});
}
private QuizSession readQuizJSON() {
try {
InputStream is = getAssets().open("quiz.json");
int size = is.available();
byte[] buffer = new byte[size];
int result = is.read(buffer);
is.close();
String json = new String(buffer, "UTF-8");
return JSONObjectCreator.createObject(json, QuizSession.class);
} catch (IOException ignored) {
return null;
}
}
}
|
package edu.uw.cwds.predictionservice.linearregression.test;
import static org.junit.Assert.*;
import java.util.Hashtable;
import org.junit.Test;
import edu.uw.cwds.predictionservice.linearregression.*;
public class LinearRegressionTest {
@Test
public void testSimpleParametersWithIntercept() throws Exception {
LinearRegressionModel model = new LinearRegressionModel();
model.setIntercept(3.4);
SimpleRegressionParameter simpleParam1 = new SimpleRegressionParameter();
simpleParam1.setCoefficient(2.3);
SimpleRegressionParameter simpleParam2 = new SimpleRegressionParameter();
simpleParam2.setCoefficient(39.2);
model.setRegressionParameters(new RegressionParameter[] { simpleParam1, simpleParam2 });
assertEquals(3.4 + 2.3*7.3 + 39.2*8.2, model.predict("7.3,8.2"), 1e-6);
}
@Test
public void testLookupParameter() throws Exception {
LinearRegressionModel model = new LinearRegressionModel();
LookupRegressionParameter lookupParam = new LookupRegressionParameter();
Hashtable<String, Double> lookupTable = new Hashtable<String, Double>();
lookupTable.put("KEY1", 5.7);
lookupTable.put("KEY99", 83.2);
lookupParam.setLookupTable(lookupTable);
lookupParam.setDefaultValue(7.2);
model.setRegressionParameters(new RegressionParameter[] {lookupParam});
assertEquals(5.7, model.predict("KEY1"), 1e-6);
assertEquals(7.2, model.predict("NONEXISTENT"), 1e-6);
}
@Test
public void testRangeParameter() throws Exception {
LinearRegressionModel model = new LinearRegressionModel();
RangeRegressionParameter rangeParam = new RangeRegressionParameter();
Range range1 = new Range();
range1.setLowerBound(1.5);
range1.setLowerInclusive(false);
range1.setUpperBound(4);
range1.setUpperInclusive(true);
range1.setValue(7.2);
Range range2 = new Range();
range2.setLowerBound(4);
range2.setLowerInclusive(false);
range2.setUpperBound(7);
range2.setUpperInclusive(true);
range2.setValue(8.7);
rangeParam.setRanges(new Range[] {range1, range2});
rangeParam.setDefaultValue(5.1);
model.setRegressionParameters(new RegressionParameter[] {rangeParam});
assertEquals(8.7, model.predict("5.5"), 1e-6);
assertEquals(5.1, model.predict("11.3"), 1e-6);
}
@Test
public void testRange() {
Range range = new Range();
range.setLowerBound(4.2);
range.setUpperBound(8.3);
assertTrue(range.isWithinRange(7));
assertFalse(range.isWithinRange(3));
assertFalse(range.isWithinRange(9));
assertFalse(range.isWithinRange(4.2));
range.setLowerInclusive(true);
assertTrue(range.isWithinRange(4.2));
assertFalse(range.isWithinRange(8.3));
range.setUpperInclusive(true);
assertTrue(range.isWithinRange(8.3));
}
}
|
package com.openproject.core;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class AppConfig {
@Value("${fresh.charging.url}")
private String freshChargingUrl;
@Value("${update.charging.url}")
private String updateChargingUrl;
@Value("${deactivate.charging.url}")
private String deactivateChargingUrl;
public String getFreshChargingUrl() {
return freshChargingUrl;
}
public void setFreshChargingUrl(String freshChargingUrl) {
this.freshChargingUrl = freshChargingUrl;
}
public String getUpdateChargingUrl() {
return updateChargingUrl;
}
public void setUpdateChargingUrl(String updateChargingUrl) {
this.updateChargingUrl = updateChargingUrl;
}
public String getDeactivateChargingUrl() {
return deactivateChargingUrl;
}
public void setDeactivateChargingUrl(String deactivateChargingUrl) {
this.deactivateChargingUrl = deactivateChargingUrl;
}
}
|
package com.Hackerrank.algos.warmup;
import java.util.Scanner;
public class CircularArrayRotation {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int r=sc.nextInt();
int q=sc.nextInt();
r=r%n;
int[] a=new int[n];
for(int i=0;i<n;i++){
a[i]=sc.nextInt();
}
for(int i=0;i<q;i++){
int m=sc.nextInt();
int j=m-r;
//System.out.println("j value"+j);
if(m-r>=0){
System.out.println(a[j]);
}else{
System.out.println(a[j+n]);
}
}
}
}
|
package com.xianzaishi.wms.tmscore.domain.client.impl;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import com.xianzaishi.wms.common.exception.BizException;
import com.xianzaishi.wms.common.vo.SimpleResultVO;
import com.xianzaishi.wms.tmscore.domain.client.itf.IDistributionBoxDomainClient;
import com.xianzaishi.wms.tmscore.domain.service.itf.IDistributionBoxDomainService;
import com.xianzaishi.wms.tmscore.vo.DistributionBoxVO;
public class DistributionBoxDomainClient implements
IDistributionBoxDomainClient {
private static final Logger logger = Logger
.getLogger(DistributionBoxDomainClient.class);
@Autowired
private IDistributionBoxDomainService distributionBoxDomainService = null;
public SimpleResultVO<Boolean> addDistributionBoxVO(
DistributionBoxVO distributionBoxVO) {
SimpleResultVO<Boolean> flag = null;
try {
flag = SimpleResultVO
.buildSuccessResult(distributionBoxDomainService
.addDistributionBoxVO(distributionBoxVO));
} catch (BizException e) {
logger.error(e.getMessage(), e);
flag = SimpleResultVO.buildBizErrorResult(e);
} catch (Exception e) {
logger.error(e.getMessage(), e);
flag = SimpleResultVO.buildErrorResult();
}
return flag;
}
public IDistributionBoxDomainService getDistributionBoxDomainService() {
return distributionBoxDomainService;
}
public void setDistributionBoxDomainService(
IDistributionBoxDomainService distributionBoxDomainService) {
this.distributionBoxDomainService = distributionBoxDomainService;
}
public SimpleResultVO<DistributionBoxVO> getDistributionBoxVOByBarcode(
String barcode) {
SimpleResultVO<DistributionBoxVO> flag = null;
try {
flag = SimpleResultVO
.buildSuccessResult(distributionBoxDomainService
.getDistributionBoxVOByBarcode(barcode));
} catch (BizException e) {
logger.error(e.getMessage(), e);
flag = SimpleResultVO.buildBizErrorResult(e);
} catch (Exception e) {
logger.error(e.getMessage(), e);
flag = SimpleResultVO.buildErrorResult();
}
return flag;
}
public SimpleResultVO<DistributionBoxVO> getDistributionBoxVOByID(Long id) {
SimpleResultVO<DistributionBoxVO> flag = null;
try {
flag = SimpleResultVO
.buildSuccessResult(distributionBoxDomainService
.getDistributionBoxVOByID(id));
} catch (BizException e) {
logger.error(e.getMessage(), e);
flag = SimpleResultVO.buildBizErrorResult(e);
} catch (Exception e) {
logger.error(e.getMessage(), e);
flag = SimpleResultVO.buildErrorResult();
}
return flag;
}
public SimpleResultVO<List<DistributionBoxVO>> batchGetDistributionBoxVOByBarcode(
List<String> barcodes) {
SimpleResultVO<List<DistributionBoxVO>> flag = null;
try {
flag = SimpleResultVO
.buildSuccessResult(distributionBoxDomainService
.batchGetDistributionBoxVOByBarcode(barcodes));
} catch (BizException e) {
logger.error(e.getMessage(), e);
flag = SimpleResultVO.buildBizErrorResult(e);
} catch (Exception e) {
logger.error(e.getMessage(), e);
flag = SimpleResultVO.buildErrorResult();
}
return flag;
}
public SimpleResultVO<List<DistributionBoxVO>> batchGetDistributionBoxVOByID(
List<Long> ids) {
SimpleResultVO<List<DistributionBoxVO>> flag = null;
try {
flag = SimpleResultVO
.buildSuccessResult(distributionBoxDomainService
.batchGetDistributionBoxVOByID(ids));
} catch (BizException e) {
logger.error(e.getMessage(), e);
flag = SimpleResultVO.buildBizErrorResult(e);
} catch (Exception e) {
logger.error(e.getMessage(), e);
flag = SimpleResultVO.buildErrorResult();
}
return flag;
}
}
|
package Bonusmaterial;
/**
* Caesar
*/
public class Caesar {
public static void main(String[] args) {
// System.out.println();
System.out.println(String.valueOf(encrypt("ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray(), 3)));
System.out.println(String.valueOf(encrypt("CAESAR".toCharArray(), 3)));
}
public static char[] encrypt(char[] arr, int offset) {
if (offset < 0) {
return null;
} else {
char[] result = new char[arr.length];
for (int i = 0; i < arr.length; i++) {
if (arr[i] < 'A' || arr[i] > 'Z') {
return null;
}
else {
result[i] = (char)((arr[i] - 'A' + offset) % 26 + 'A');
}
}
return result;
}
}
}
|
package com.test01;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MTest {
public static void main(String[] args) {
ApplicationContext factory = new ClassPathXmlApplicationContext("com/test01/applicationContext.xml");
MessageBean apple = (MessageBean) factory.getBean("apple");
apple.sayHello();
MessageBean watermelon = (MessageBean) factory.getBean("watermelon");
watermelon.sayHello();
MessageBean banana = (MessageBean) factory.getBean("banana");
banana.sayHello();
((ClassPathXmlApplicationContext)factory).close();
}
}
|
package lesson23;
public class Cat {
private String name = "Murzik";
}
|
package net.kkolyan.elements.game;
import net.kkolyan.elements.engine.core.Located;
/**
* @author nplekhanov
*/
public interface GtaStyleControllable extends TdsControllable {
void move(double timeDirection);
void turn(double timeDirection);
}
|
package com.example.abdullah.weatherapp;
import android.content.Context;
import android.database.Cursor;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.abdullah.weatherapp.data.Preferences;
import com.example.abdullah.weatherapp.utilities.MyDateUtils;
import com.example.abdullah.weatherapp.utilities.WeatherUtils;
public class ViewAdapter extends RecyclerView.Adapter<ViewAdapter.AdapterViewHolder> {
private static final int VIEW_TYPE_TODAY = 0;
private static final int VIEW_TYPE_FUTURE_DAY = 1;
private final Context context;
private Cursor cursor;
private boolean mUseTodayLayout;
private final AdapterOnClickHandler onClickHandler;
public ViewAdapter(@NonNull Context context, AdapterOnClickHandler clickHandler){
onClickHandler = clickHandler;
this.context = context;
mUseTodayLayout = context.getResources().getBoolean(R.bool.use_today_layout);
}
public interface AdapterOnClickHandler{
void onClick(long date);
}
@Override
public AdapterViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
int layoutId;
switch (viewType) {
// COMPLETED (12) If the view type of the layout is today, use today layout
case VIEW_TYPE_TODAY: {
layoutId = R.layout.list_item_today;
break;
}
// COMPLETED (13) If the view type of the layout is future day, use future day layout
case VIEW_TYPE_FUTURE_DAY: {
layoutId = R.layout.list_item;
break;
}
// COMPLETED (14) Otherwise, throw an IllegalArgumentException
default:
throw new IllegalArgumentException("Invalid view type, value of " + viewType);
}
View view = LayoutInflater.from(context).inflate(layoutId, parent, false);
view.setFocusable(true);
return new AdapterViewHolder(view);
}
@Override
public void onBindViewHolder(ViewAdapter.AdapterViewHolder holder, int position) {
cursor.moveToPosition(position);
int viewType = getItemViewType(position);
int weatherId = cursor.getInt(MainActivity.INDEX_WEATHER_CONDITION_ID);
int weatherImageId;
switch (viewType) {
// COMPLETED (15) If the view type of the layout is today, display a large icon
case VIEW_TYPE_TODAY:
weatherImageId = WeatherUtils
.getLargeArtResourceIdForWeatherCondition(weatherId);
String tempUnit;
if(Preferences.isMetric(context))
tempUnit = context.getResources().getString(R.string.temperature_celsius);
else
tempUnit = context.getResources().getString(R.string.temperature_farenheit);
holder.tempUnit.setText(tempUnit);
break;
// COMPLETED (16) If the view type of the layout is today, display a small icon
case VIEW_TYPE_FUTURE_DAY:
weatherImageId = WeatherUtils
.getSmallArtResourceIdForWeatherCondition(weatherId);
break;
// COMPLETED (17) Otherwise, throw an IllegalArgumentException
default:
throw new IllegalArgumentException("Invalid view type, value of " + viewType);
}
long dateInMillis = cursor.getLong(MainActivity.INDEX_WEATHER_DATE);
String dateString = MyDateUtils.getFriendlyDateString(context,dateInMillis,false);
holder.dateView.setText(dateString);
String description = WeatherUtils.getStringForWeatherCondition(context,weatherId);
String descriptionA11y = context.getString(R.string.a11y_forecast, description);
/* Set the text and content description (for accessibility purposes) */
holder.descriptionView.setText(description);
holder.descriptionView.setContentDescription(descriptionA11y);
holder.iconView.setImageResource(weatherImageId);
double highInCelsius = cursor.getDouble(MainActivity.INDEX_WEATHER_MAX_TEMP);
/*
* If the user's preference for weather is fahrenheit, formatTemperature will convert
* the temperature. This method will also append either °C or °F to the temperature
* String.
*/
String highString = WeatherUtils.formatTemperature(context, highInCelsius);
/* Create the accessibility (a11y) String from the weather description */
String highA11y = context.getString(R.string.a11y_high_temp, highString);
/* Set the text and content description (for accessibility purposes) */
holder.highTempView.setText(highString);
holder.highTempView.setContentDescription(highA11y);
/*************************
* Low (min) temperature *
*************************/
/* Read low temperature from the cursor (in degrees celsius) */
double lowInCelsius = cursor.getDouble(MainActivity.INDEX_WEATHER_MIN_TEMP);
/*
* If the user's preference for weather is fahrenheit, formatTemperature will convert
* the temperature. This method will also append either °C or °F to the temperature
* String.
*/
String lowString = WeatherUtils.formatTemperature(context, lowInCelsius);
String lowA11y = context.getString(R.string.a11y_low_temp, lowString);
/* Set the text and content description (for accessibility purposes) */
holder.lowTempView.setText(lowString);
holder.lowTempView.setContentDescription(lowA11y);
}
@Override
public int getItemCount() {
if (null == cursor) return 0;
return cursor.getCount();
}
@Override
public int getItemViewType(int position){
if (mUseTodayLayout && position == 0) {
return VIEW_TYPE_TODAY;
// COMPLETED (11) Otherwise, return the ID for future day viewType
} else {
return VIEW_TYPE_FUTURE_DAY;
}
}
void swapCursor(Cursor newCursor) {
cursor = newCursor;
notifyDataSetChanged();
}
class AdapterViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
final TextView dateView;
final TextView descriptionView;
final TextView highTempView;
final TextView lowTempView;
final TextView tempUnit;
// COMPLETED (5) Add an ImageView for the weather icon
final ImageView iconView;
AdapterViewHolder(View view) {
super(view);
iconView = (ImageView) view.findViewById(R.id.weather_icon);
dateView = (TextView) view.findViewById(R.id.date);
descriptionView = (TextView) view.findViewById(R.id.weather_description);
highTempView = (TextView) view.findViewById(R.id.high_temperature);
lowTempView = (TextView) view.findViewById(R.id.low_temperature);
tempUnit = (TextView)view.findViewById(R.id.temperatureUnit);
view.setOnClickListener(this);
}
@Override
public void onClick(View view) {
int adapterPosition = getAdapterPosition();
cursor.moveToPosition(adapterPosition);
long dateInMillis = cursor.getLong(MainActivity.INDEX_WEATHER_DATE);
onClickHandler.onClick(dateInMillis);
}
}
}
|
package com.es.core.service;
public interface PaginationService {
long getTotalPagesNumber(long limit, String searchQuery);
long getOffset(long limit, long currentPage);
}
|
package com.example.ridowanahmed.childlocator;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import com.example.ridowanahmed.childlocator.Dashboard.ChildDashboard;
import com.example.ridowanahmed.childlocator.Dashboard.ParentDashboard;
import com.example.ridowanahmed.childlocator.Login.ChildLoginActivity;
import com.example.ridowanahmed.childlocator.Login.ParentLoginActivity;
import com.google.firebase.auth.FirebaseAuth;
public class MainActivity extends AppCompatActivity {
private final String TAG = "MainActivity";
private FirebaseAuth mFirebaseAuth;
private AlertDialog alertDialog;
private TextView textView_loginOptions;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);
mFirebaseAuth = FirebaseAuth.getInstance();
Log.e(TAG, "Auth " + mFirebaseAuth.toString());
textView_loginOptions = (TextView) findViewById(R.id.textView_loginOptions);
Typeface lobster = Typeface.createFromAsset(getAssets(), "Lobster-Regular.ttf");
textView_loginOptions.setTypeface(lobster);
//alert dialog message for internet
alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Internet Connection Error !");
alertDialog.setMessage("Please, Check Your Internet Connection.");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
}
public void parentLoginBtn(View view){
if(!isConnected()){
alertDialog.show();
return;
}
SharedPreferences mSharedPreferences = MainActivity.this.getSharedPreferences(getString(R.string.PREF_FILE), MODE_PRIVATE);
final String phoneNumber = mSharedPreferences.getString(getString(R.string.PARENT_GIVE_NUMBER), "");
if(!TextUtils.isEmpty(phoneNumber)) {
startActivity(new Intent(MainActivity.this,ParentDashboard.class));
return;
} else if (mFirebaseAuth.getCurrentUser() != null){
mFirebaseAuth.signOut();
Log.e(TAG, "Starting ParenLoginActivity");
}
startActivity(new Intent(MainActivity.this,ParentLoginActivity.class));
}
public void childLoginBtn(View view){
if(!isConnected()){
alertDialog.show();
return;
}
SharedPreferences mSharedPreferences = MainActivity.this.getSharedPreferences(getString(R.string.PREF_FILE), MODE_PRIVATE);
final String phoneNumber = mSharedPreferences.getString(getString(R.string.CHILD_GIVE_NUMBER), "");
if(!TextUtils.isEmpty(phoneNumber)) {
startActivity(new Intent(MainActivity.this,ChildDashboard.class));
return;
} else if (mFirebaseAuth.getCurrentUser() != null){
mFirebaseAuth.signOut();
Log.e(TAG, "Starting ChildLoginActivity");
}
startActivity(new Intent(MainActivity.this,ChildLoginActivity.class));
}
@Override
protected void onResume() {
super.onResume();
Log.e(TAG, "onResume");
}
protected boolean isConnected(){
ConnectivityManager cm = (ConnectivityManager)getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean flag = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
return flag;
}
@Override
public void onBackPressed() {
final AlertDialog exitDialog = new AlertDialog.Builder(MainActivity.this).create();
exitDialog.setTitle("EXIT CHILD LOCATOR ?");
exitDialog.setMessage("Are you sure you want to exit ChiLdLocator ?");
exitDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
exitDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Cancel",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
exitDialog.dismiss();
return;
}
});
exitDialog.show();
//super.onBackPressed();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
}
|
package io.github.atomfrede.gradle.plugins.crowdincli.task.crowdin.git;
public interface GitSpec {
void enable(boolean enable);
void commitMessage(String commitMessage);
String getCommitMessage();
boolean isEnabled();
}
|
package de.fraunhofer.iais.kd.bda.spark;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import scala.Tuple2;
public class MinHashCluster implements Serializable{
public static void main(String[] args) {
//String inputFile = "resources/sorted_sample.tsv";
String inputFile = "resources/last-fm-sample1000000.tsv";
String appName = "MinHashAggregator";
SparkConf conf = new SparkConf().setAppName(appName).setMaster("local[*]");
JavaSparkContext context = new JavaSparkContext(conf);
// Read file
JavaRDD<String> input = context.textFile(inputFile);
JavaPairRDD<String, String> arts = input.mapToPair(line -> {
String[] parts = line.split("\t");
return new Tuple2<String, String>(parts[3], parts[0]);
});
// aggregate users' hashes
JavaPairRDD<String, MinHashAggregator> artminhashs = arts.aggregateByKey(new MinHashAggregator(),
(agg, value) -> agg.add(value), (agg1, agg2) -> agg1.combine(agg2));
// Initialization of the model
MinHashClusterModel model = new MinHashClusterModel("resources/sample_centers_users.csv");
//Maps to Artist - Cluster relation
JavaPairRDD<String, String> artNameClusterMap = artminhashs.mapToPair(tuple -> {
String key = model.findClosestCluster(tuple._2);
return new Tuple2<String, String>(tuple._1, key);
});
artNameClusterMap.saveAsTextFile("/tmp/minhashartcluster.txt");
// Inverts Artist - CLuster relation and gathers all artists, related to one cluster.
JavaPairRDD<String, String> clusterArtNameMap = artNameClusterMap.mapToPair(tuple -> {
return new Tuple2<String, String>(tuple._2, tuple._1);
}).reduceByKey((arg1, arg2) -> arg1 + "," + arg2);
clusterArtNameMap.saveAsTextFile("/tmp/minhashclusterarts.txt");
context.close();
}
}
|
package com.spreadtrum.android.eng;
import android.content.Context;
import android.net.LocalSocket;
import android.os.Bundle;
import android.os.SystemProperties;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;
import android.util.Log;
public class AOTASetting extends PreferenceActivity {
private Preference mClear;
private Context mContext = this;
private CheckBoxPreference mEnable;
private CheckBoxPreference mPreload;
private CheckBoxPreference mUser;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.layout.aota_setting);
this.mEnable = (CheckBoxPreference) findPreference("aota_support");
this.mPreload = (CheckBoxPreference) findPreference("authorized_preload");
this.mClear = findPreference("aota_clear");
this.mUser = (CheckBoxPreference) findPreference("aota_user_enable");
}
private void runCommand(final int command, boolean isEnable) {
final String option = isEnable ? " enable " : " disable ";
Log.e("duke", "isEnable = " + option + "command = " + command);
new Thread() {
public void run() {
try {
if (command == 0) {
Log.e("duke", "pm enable/disable");
Runtime.getRuntime().exec("pm" + option + "com.android.synchronism");
}
if (command == 1) {
Log.e("duke", "rm command");
Runtime.getRuntime().exec("rm /data/preloadapp/Synchronism.apk").waitFor();
Runtime.getRuntime().exec("rm /data/dalvik-cache/data@preloadapp@Synchronism.apk@classes.dex");
}
} catch (Exception e) {
Log.e("duke", "run command crashed " + e);
}
}
}.start();
}
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
LocalSocket clientSocket = new LocalSocket();
if (preference == this.mUser) {
SystemProperties.set("persist.sys.synchronism.enable", this.mUser.isChecked() ? "1" : "0");
Log.e("duke", "isAOTAEnable = " + String.valueOf(SystemProperties.getBoolean("persist.sys.synchronism.enable", false)));
runCommand(0, this.mUser.isChecked());
return true;
} else if (preference == this.mClear) {
Log.e("duke", "mClear == preference");
runCommand(1, false);
return true;
} else if (preference == this.mEnable) {
Log.e("duke", "mEnable == preference");
SystemProperties.set("persist.sys.synchronism.support", this.mEnable.isChecked() ? "1" : "0");
return true;
} else if (preference != this.mPreload) {
return false;
} else {
Log.e("duke", "mPreload");
SystemProperties.set("persist.sys.authorized.preload", this.mPreload.isChecked() ? "1" : "0");
return true;
}
}
}
|
package edu.nmsu;
import edu.nmsu.communication.DCOPagent;
import edu.nmsu.communication.DCOPinfo;
import edu.nmsu.communication.Spawner;
import edu.nmsu.kernel.DCOPInstance;
import edu.nmsu.kernel.DCOPInstanceFactory;
import edu.nmsu.problem.*;
import org.json.JSONObject;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class Main {
public static void execute(String file) {
List<Object> algParams = new ArrayList<>();
int nbIterations = 1;
long solverTimeoutMs = 10000;
double wCost = 1;
double wPower = 1;
DCOPInstance dcopInstance = DCOPInstanceFactory.importDCOPInstance(file);
Spawner spawner = new Spawner(dcopInstance);
algParams.add(nbIterations);
algParams.add(solverTimeoutMs);
algParams.add(wCost);
algParams.add(wPower);
spawner.spawn(algParams);
// // Summary Output
System.out.println(getSummary(spawner.getSpawnedAgents()));
}
public static void main(String[] args) {
for (int i=0; i < 50; i++) {
String file = "resources/inputs/1cluster/instance_PI_"+i+".json";
generateSHDSInstances(file, 6);
// execute(file);
// generateMultiSHDSInstances(file, 6, new int[] {10, 20, 100});
}
return;
}
public static void generateMultiSHDSInstances(String fileName, int nDevices, int[] radious) {
ArrayList<Topology> topologies = new ArrayList<>();
for (int r : radious) {
topologies.add(new Topology(500, 100, r));
}
RuleGenerator ruleGen = new RuleGenerator();
GeneratorMulti gen = new GeneratorMulti(topologies, ruleGen, nDevices);
for (int i = 0; i < radious.length; i++) {
JSONObject exp = gen.generate(i);
try {
FileWriter fileOut = new FileWriter(fileName + "_" + radious[i] + ".json");
fileOut.write(exp.toString(2));
fileOut.flush();
fileOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void generateSHDSInstances(String fileName, int nDevices) {
Topology topo = new Topology(70, 100, 1000);
//Topology topo = new Topology(718, 100, 100);
//Topology topo = new Topology(3766, 100, 100);
RuleGenerator ruleGen = new RuleGenerator();
Generator gen = new Generator(topo, ruleGen, nDevices);
JSONObject exp = gen.generate();
try {
FileWriter fileOut = new FileWriter(fileName);
fileOut.write(exp.toString(2));
fileOut.flush();
fileOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static String getUsage() {
return "dcop_jtool FILE.xml [options]\n" +
" where options is one of the following:\n" +
" --repair (-r) [GDBR, TDBR(default)]. The DLNS repair phase.\n" +
" --destroy (-d) [RAND(default), MEETINGS]. The DLNS destroy phase.\n" +
" --iterations (-i) (default=500). The number of iterations of DLNS.\n" +
" --timeout (-t) (default=no timeout (0)). The simulated time maximal execution time.\n";
}
public static String getSummary(Collection<DCOPagent> agents) {
String res = "iterNo\t"
+ "simTime\t"
+ "AvgCPTime\t"
+ "AvgMsgsSentIter\t"
+ "NetLoad\t"
+ "SumScheduleCost\t"
+ "SumPriceCost\t"
+ "AvgPriceCost\t"
+ "energyCost\t"
+ "avgEnergyCost\t"
+ "vgGain\t";
for (int i = 0; i < Parameters.getHorizon(); i++)
res += "pw_t_" + i + ((i == Parameters.getHorizon()- 1) ? "\n" : "\t");
DecimalFormat df = new DecimalFormat("#.00");
int maxIter = DCOPinfo.leaderAgent.getAgentStatistics().size();
long simTime = 0; int netLoad = 0;
double[] aggrPower = new double[Parameters.getHorizon()];
for (int iter = 0; iter < maxIter; iter++) {
int iterMsgsSent = 0;
double sumScheduleCost = 0;
double sumPriceCost = 0;
double sumPowerCost = 0;
double avgGain = 0;
double avgCPtime = 0;
for (int i = 0; i < aggrPower.length; i++) aggrPower[i] = 0;
for (DCOPagent agt : agents) {
if (iter >= agt.getAgentStatistics().size()) continue;
// time
simTime = Math.max(simTime, agt.getAgentStatistics().getMilliTime(iter));
avgCPtime += agt.getAgentStatistics().getSchedulingTimeMsIter(iter);
// msgs
int msgNow = agt.getAgentStatistics().getSentMessages(iter);
int msgPrev = iter == 0 ? 0 : agt.getAgentStatistics().getSentMessages(iter-1);
iterMsgsSent += (msgNow - msgPrev);
// Costs
// todo: check i think that cost takes into account the power consumption of neighbors -
sumScheduleCost += agt.getAgentStatistics().getScheduleCostIter(iter);
sumPriceCost += Utilities.sum(agt.getAgentStatistics().getPriceUSDIter(iter));
sumPowerCost += Utilities.sum(agt.getAgentStatistics().getPowerKWhIter(iter));
avgGain += agt.getAgentStatistics().getAgentGainIter(iter);
// Power
aggrPower = Utilities.sum(aggrPower, agt.getAgentStatistics().getPowerKWhIter(iter));
}
netLoad += iterMsgsSent;
res += iter +"\t "
+ df.format(simTime) + "\t "
+ df.format(avgCPtime/agents.size()) + "\t "
+ df.format(iterMsgsSent/agents.size()) + "\t "
+ df.format(netLoad) + "\t "
+ df.format(sumScheduleCost) + "\t "
+ df.format(sumPriceCost) + "\t "
+ df.format(sumPriceCost/agents.size()) + "\t "
+ df.format(sumPowerCost) + "\t "
+ df.format(sumPowerCost/agents.size()) + "\t "
+ df.format(avgGain/agents.size()) + "\t ";
for (int i = 0; i < aggrPower.length; i++)
res += df.format(aggrPower[i]) + ((i == aggrPower.length - 1) ? "\n" : "\t");
}
return res;
}
}
|
package food_ordering;
public class Pizza
{
private String Toppings;
private String Size;
private int quantity;
private String flavour;
private double price;
public Pizza(String toppings, String size, int quantity, String flavour)
{
this.flavour=flavour;
this.quantity=quantity;
this.Toppings = toppings;
this.Size = size;
}
public String getToppings() {
return Toppings;
}
public String getSize() {
return Size;
}
public void setToppings(String toppings) {
Toppings = toppings;
}
public void setSize(String size) {
Size = size;
}
public int getQuantity() {
return quantity;
}
public String getFlavour() {
return flavour;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public void setFlavour(String flavour) {
this.flavour = flavour;
}
public void setPrice(double price) {
this.price = price;
}
public double getPrice()
{
return price;
}
@Override
public String toString()
{
return "Pizza order : "+this.getFlavour()+" "+this.getQuantity()+" "+this.getToppings()+" "+this.getSize()+" "+this.getPrice();
}
public void calculatePizzaPrice()
{
double total_price = 0;
int count_no_of_toppings=0;
double size_price=0;
if(this.getToppings().contains("onions"))
++count_no_of_toppings;
if(this.getToppings().contains("corns"))
++count_no_of_toppings;
if(this.getToppings().contains("olives"))
++count_no_of_toppings;
double topping_price=0.5*count_no_of_toppings;
if(this.getSize().contains("small"))
size_price=2;
if(this.getSize().contains("medium"))
size_price=4;
if(this.getSize().contains("large"))
size_price=6;
if(this.getFlavour().contains("four season"))
{
total_price=this.getQuantity()*(2.5+topping_price+size_price);
}
if(getFlavour().contains("bbq chicken"))
{
total_price=this.getQuantity()*(1.5+topping_price+size_price);
}
if(getFlavour().contains("margherita"))
{
total_price=this.getQuantity()*(2+topping_price+size_price);
}
this.setPrice(total_price);
}
}
|
package com.zundrel.ollivanders.client.gui;
import com.mojang.blaze3d.platform.GlStateManager;
import com.zundrel.ollivanders.Ollivanders;
import com.zundrel.ollivanders.api.component.IPlayerComponent;
import com.zundrel.ollivanders.api.utils.OllivandersComponents;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.font.FontManager;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.text.LiteralText;
import net.minecraft.util.Identifier;
import net.minecraft.world.World;
import org.lwjgl.opengl.GL11;
public class PowerBarScreen extends Screen {
private final static Identifier overlayBar = new Identifier(Ollivanders.MODID,"textures/gui/powerbar.png");
private final static int ARROW_WIDTH = 12;
private final static int ARROW_HEIGHT = 7;
private final static int BAR_WIDTH = 180;
private final static int BAR_HEIGHT = 5;
private final static int STOPPER_WIDTH = 6;
private final static int STOPPER_HEIGHT = 7;
private MinecraftClient mc;
public PowerBarScreen (MinecraftClient mc) {
super (new LiteralText("powerbar"));
this.mc = mc;
}
public void renderPowerBar(int screenWidth, int screenHeight) {
World world = mc.world;
PlayerEntity player = mc.player;
FontManager fr = mc.getFontManager();
IPlayerComponent playerComponent = OllivandersComponents.getPlayerComponent(player);
GlStateManager.pushMatrix();
GlStateManager.enableBlend();
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
mc.getTextureManager().bindTexture(overlayBar);
final int posX = (screenWidth / 2) - (BAR_WIDTH / 2);
final int posY = BAR_HEIGHT;
GL11.glTranslatef(posX, posY, 0);
blit(0, 0, 0, 0, BAR_WIDTH, BAR_HEIGHT);
if (playerComponent != null && playerComponent.getSpell() != null) {
int clampedPowerLevel = Math.min(playerComponent.getPowerLevel(), Math.min(playerComponent.getSpell().getMaxSpellPower(player), playerComponent.getWandMaxPowerLevel()));
int maxPowerLevel = Math.min(playerComponent.getSpell().getMaxSpellPower(player), playerComponent.getWandMaxPowerLevel());
int differencePowerLevel = playerComponent.getPowerLevel() - clampedPowerLevel;
blit(0, 0, 0, BAR_HEIGHT, (int) (BAR_WIDTH*(clampedPowerLevel / 5F)), BAR_HEIGHT);
if (differencePowerLevel > 0) {
blit((36 * maxPowerLevel) - 3, -1, (ARROW_WIDTH * 2) + STOPPER_WIDTH, BAR_HEIGHT * 2, STOPPER_WIDTH, STOPPER_HEIGHT);
blit((36 * playerComponent.getPowerLevel()) - ARROW_WIDTH * 2, -1, ARROW_WIDTH, BAR_HEIGHT * 2, ARROW_WIDTH, ARROW_HEIGHT);
} else {
blit(36 * maxPowerLevel - 3, -1, ARROW_WIDTH * 2, BAR_HEIGHT * 2, STOPPER_WIDTH, STOPPER_HEIGHT);
blit((36 * playerComponent.getPowerLevel()) - ARROW_WIDTH * 2, -1, 0, BAR_HEIGHT * 2, ARROW_WIDTH, ARROW_HEIGHT);
}
} else if (playerComponent != null && playerComponent.getSpell() == null)
blit((36 * playerComponent.getPowerLevel()) - ARROW_WIDTH * 2, -1, ARROW_WIDTH, BAR_HEIGHT * 2, ARROW_WIDTH, ARROW_HEIGHT);
GlStateManager.disableBlend();
GlStateManager.popMatrix();
}
}
|
package com.wkrzywiec.spring.library.retrofit.model;
import java.util.List;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@EqualsAndHashCode
@ToString()
@NoArgsConstructor
public class VolumeInfoModel {
private String title;
private List<String> authors;
private String publisher;
private String publishedDate;
private String description;
private List<IsbnAPIModel> industryIdentifiers;
private int pageCount;
private List<String> categories;
private double averageRating;
private ImageLinksAPIModel imageLinks;
}
|
package com.example.sembi.logingui;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.text.InputType;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.google.android.gms.tasks.OnCanceledListener;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class LoginActivity extends AppCompatActivity {
ImageView eye;
EditText pass;
EditText user;
Boolean show;
private FirebaseAuth mAuth;
// RadioButton b;
boolean remMe = false;
String serial_user = "";
String serial_ASI = "";
String uid = "";
private boolean loginInProgress;
FirebaseDatabase database;
DatabaseReference myRef;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first__login);
database = FirebaseDatabase.getInstance();
myRef = database.getReference();
loginInProgress = false;
// b = findViewById(R.id.toggleButtonRemMe);
// b.setChecked(false);
mAuth = FirebaseAuth.getInstance();
eye = findViewById(R.id.eyeImageV);
pass = findViewById(R.id.passEditT);
user = findViewById(R.id.usernameEditT);
show = false;
// getCurrentPhoneSerial();
// setPhoneSerialUserListener();
// setAutoSignInListener();
// cheatTheSystem();
// autoSignIn();
}
// private void autoSignIn() {
// if (serial_ASI != null && serial_user != null && uid != "" && serial_ASI != "" && serial_user != "") {
// //TODO
// login();
// }
// }
// private void cheatTheSystem(){
// FirebaseDatabase database = FirebaseDatabase.getInstance();
// DatabaseReference myRef = database.getReference().child("phoneSerialNumbers").child(uid).child("user");
// myRef.setValue();
// }
private void getCurrentPhoneSerial() {
final int REQUEST_PHONE_STATE = 1;
TelephonyManager tManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, REQUEST_PHONE_STATE);
} else {
uid = tManager.getDeviceId();
}
}
// private void setPhoneSerialUserListener() {
// FirebaseDatabase database = FirebaseDatabase.getInstance();
// DatabaseReference myRef = database.getReference().child("phoneSerialNumbers").child(uid).child("user");
//
//
// myRef.addValueEventListener(new ValueEventListener() {
// @Override
// public void onDataChange(DataSnapshot dataSnapshot) {
// // This method is called once with the initial value and again
// // whenever data at this location is updated.
// serial_user = dataSnapshot.getValue(String.class);
// }
//
// @Override
// public void onCancelled(DatabaseError error) {
// // Failed to read value
// //TODO
// }
// });
// }
// private void setAutoSignInListener() {
// FirebaseDatabase database = FirebaseDatabase.getInstance();
// DatabaseReference myRef = database.getReference().child("phoneSerialNumbers").child(uid).child("AutoSignIn");
//
//
// myRef.addValueEventListener(new ValueEventListener() {
// @Override
// public void onDataChange(DataSnapshot dataSnapshot) {
// // This method is called once with the initial value and again
// // whenever data at this location is updated.
// serial_ASI = dataSnapshot.getValue(String.class);
// }
//
// @Override
// public void onCancelled(DatabaseError error) {
// // Failed to read value
// //TODO
// }
// });
// }
public void showPass(View view) {
String STRpassword = pass.getText().toString();
if (show) {
show = !show;
eye.setImageDrawable((getDrawable(R.drawable.eye)));
pass.setInputType( InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_VARIATION_PASSWORD);
}
else {
show = !show;
eye.setImageDrawable((getDrawable(R.drawable.eye_enabled)));
pass.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
pass.setText(STRpassword);
pass.setTextDirection(View.TEXT_DIRECTION_LTR);
}
pass.setSelection(pass.getText().length());
}
public void newAcount(View view){
Intent intent = new Intent(this, newAcount.class);
startActivity(intent);
}
public void loginAttempt(View view) {
if (loginInProgress){
Toast.makeText(this, "Login attempt in progress, please wait..", Toast.LENGTH_LONG);
return;
}
if (pass.getText().toString().equals("") || user.getText().toString().equals("")) {
Toast.makeText(this, "Fill in all fields.", Toast.LENGTH_LONG).show();
return;
}
loginInProgress = true;
pass.setTextColor(getColor(R.color.grey));
user.setTextColor(getColor(R.color.grey));
if (user.getText().toString().length() == 0){
Toast.makeText(this, "some fields left empty.", Toast.LENGTH_LONG)
.show();
return;
}
mAuth.signInWithEmailAndPassword(user.getText().toString(),pass.getText().toString())
.addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
pass.setTextColor(Color.BLACK);
user.setTextColor(Color.BLACK);
if(task.isSuccessful()){
Toast.makeText(LoginActivity.this, "Signing In..", Toast.LENGTH_SHORT).show();
login();
} else {
Toast.makeText(LoginActivity.this, "Authentication Failed!", Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(LoginActivity.this, new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
loginInProgress = false;
Toast.makeText(LoginActivity.this, "failed to sign in", Toast.LENGTH_LONG).show();
}
}).addOnCanceledListener(LoginActivity.this, new OnCanceledListener() {
@Override
public void onCanceled() {
Toast.makeText(LoginActivity.this, "failed to sign in", Toast.LENGTH_LONG).show();
}
});
}
private void login() {
// FirebaseDatabase DB = FirebaseDatabase.getInstance();
// DatabaseReference DBRef = DB.getReference();
// if (remMe) {
// DBRef.child("phoneSerialNumbers").child(uid).child("user").setValue(Profile.getMyUserName());
// } else {
// DBRef.child("phoneSerialNumbers").child(uid).child("user").setValue("");
// }
FirebaseAuth mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
myRef = FirebaseDatabase.getInstance().getReference().child("users").child(user.getUid()).child("personalData");
myRef.child("email").setValue(user.getEmail());
Intent intent = new Intent(LoginActivity.this, HomeScreen.class);
startActivity(intent);
}
// public void rememberMeClicked(View view) {
// remMe = b.isChecked();
//
// int RM = -1;
// if (remMe)
// RM = 1;
//
// myRef.child("phoneSerialNumbers").child(uid).child("AutoSignIn").setValue(String.valueOf(RM));
//
// }
}
|
package com.example.sys.entity;
import lombok.Data;
import java.util.Date;
@Data
public class HmVideoSearch {
/**
* 开始日期
*/
private String insertTimeStart;
/**
* 结束日期
*/
private String insertTimeEnd;
// ID
private Integer id;
// 终端IMEI
private String imei;
// 录制时长
private Integer timeInterval;
// 视频录像的序列号
private String serialNumber;
// 文件名
private String fileName;
// 文件路径
private String filePath;
// 开始时间
private String startTime;
// 结束时间
private String endTime;
// 创建时间
private Date createTime;
}
|
package com.awakenguys.kmitl.ladkrabangcountry;
import com.awakenguys.kmitl.ladkrabangcountry.model.Van_Route;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource(collectionResourceRel = "van_routes", path = "van_routes")
public interface VanRouteRepo extends MongoRepository<Van_Route, String> {
}
|
/**
* This class is generated by jOOQ
*/
package schema.tables.records;
import java.sql.Timestamp;
import javax.annotation.Generated;
import org.jooq.Field;
import org.jooq.Record1;
import org.jooq.Record14;
import org.jooq.Row14;
import org.jooq.impl.UpdatableRecordImpl;
import schema.tables.WikiAttachmentrevision;
/**
* This class is generated by jOOQ.
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.8.4"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class WikiAttachmentrevisionRecord extends UpdatableRecordImpl<WikiAttachmentrevisionRecord> implements Record14<Integer, Integer, String, String, String, Timestamp, Timestamp, Byte, Byte, String, String, Integer, Integer, Integer> {
private static final long serialVersionUID = -1585835598;
/**
* Setter for <code>bitnami_edx.wiki_attachmentrevision.id</code>.
*/
public void setId(Integer value) {
set(0, value);
}
/**
* Getter for <code>bitnami_edx.wiki_attachmentrevision.id</code>.
*/
public Integer getId() {
return (Integer) get(0);
}
/**
* Setter for <code>bitnami_edx.wiki_attachmentrevision.revision_number</code>.
*/
public void setRevisionNumber(Integer value) {
set(1, value);
}
/**
* Getter for <code>bitnami_edx.wiki_attachmentrevision.revision_number</code>.
*/
public Integer getRevisionNumber() {
return (Integer) get(1);
}
/**
* Setter for <code>bitnami_edx.wiki_attachmentrevision.user_message</code>.
*/
public void setUserMessage(String value) {
set(2, value);
}
/**
* Getter for <code>bitnami_edx.wiki_attachmentrevision.user_message</code>.
*/
public String getUserMessage() {
return (String) get(2);
}
/**
* Setter for <code>bitnami_edx.wiki_attachmentrevision.automatic_log</code>.
*/
public void setAutomaticLog(String value) {
set(3, value);
}
/**
* Getter for <code>bitnami_edx.wiki_attachmentrevision.automatic_log</code>.
*/
public String getAutomaticLog() {
return (String) get(3);
}
/**
* Setter for <code>bitnami_edx.wiki_attachmentrevision.ip_address</code>.
*/
public void setIpAddress(String value) {
set(4, value);
}
/**
* Getter for <code>bitnami_edx.wiki_attachmentrevision.ip_address</code>.
*/
public String getIpAddress() {
return (String) get(4);
}
/**
* Setter for <code>bitnami_edx.wiki_attachmentrevision.modified</code>.
*/
public void setModified(Timestamp value) {
set(5, value);
}
/**
* Getter for <code>bitnami_edx.wiki_attachmentrevision.modified</code>.
*/
public Timestamp getModified() {
return (Timestamp) get(5);
}
/**
* Setter for <code>bitnami_edx.wiki_attachmentrevision.created</code>.
*/
public void setCreated(Timestamp value) {
set(6, value);
}
/**
* Getter for <code>bitnami_edx.wiki_attachmentrevision.created</code>.
*/
public Timestamp getCreated() {
return (Timestamp) get(6);
}
/**
* Setter for <code>bitnami_edx.wiki_attachmentrevision.deleted</code>.
*/
public void setDeleted(Byte value) {
set(7, value);
}
/**
* Getter for <code>bitnami_edx.wiki_attachmentrevision.deleted</code>.
*/
public Byte getDeleted() {
return (Byte) get(7);
}
/**
* Setter for <code>bitnami_edx.wiki_attachmentrevision.locked</code>.
*/
public void setLocked(Byte value) {
set(8, value);
}
/**
* Getter for <code>bitnami_edx.wiki_attachmentrevision.locked</code>.
*/
public Byte getLocked() {
return (Byte) get(8);
}
/**
* Setter for <code>bitnami_edx.wiki_attachmentrevision.file</code>.
*/
public void setFile(String value) {
set(9, value);
}
/**
* Getter for <code>bitnami_edx.wiki_attachmentrevision.file</code>.
*/
public String getFile() {
return (String) get(9);
}
/**
* Setter for <code>bitnami_edx.wiki_attachmentrevision.description</code>.
*/
public void setDescription(String value) {
set(10, value);
}
/**
* Getter for <code>bitnami_edx.wiki_attachmentrevision.description</code>.
*/
public String getDescription() {
return (String) get(10);
}
/**
* Setter for <code>bitnami_edx.wiki_attachmentrevision.attachment_id</code>.
*/
public void setAttachmentId(Integer value) {
set(11, value);
}
/**
* Getter for <code>bitnami_edx.wiki_attachmentrevision.attachment_id</code>.
*/
public Integer getAttachmentId() {
return (Integer) get(11);
}
/**
* Setter for <code>bitnami_edx.wiki_attachmentrevision.previous_revision_id</code>.
*/
public void setPreviousRevisionId(Integer value) {
set(12, value);
}
/**
* Getter for <code>bitnami_edx.wiki_attachmentrevision.previous_revision_id</code>.
*/
public Integer getPreviousRevisionId() {
return (Integer) get(12);
}
/**
* Setter for <code>bitnami_edx.wiki_attachmentrevision.user_id</code>.
*/
public void setUserId(Integer value) {
set(13, value);
}
/**
* Getter for <code>bitnami_edx.wiki_attachmentrevision.user_id</code>.
*/
public Integer getUserId() {
return (Integer) get(13);
}
// -------------------------------------------------------------------------
// Primary key information
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Record1<Integer> key() {
return (Record1) super.key();
}
// -------------------------------------------------------------------------
// Record14 type implementation
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Row14<Integer, Integer, String, String, String, Timestamp, Timestamp, Byte, Byte, String, String, Integer, Integer, Integer> fieldsRow() {
return (Row14) super.fieldsRow();
}
/**
* {@inheritDoc}
*/
@Override
public Row14<Integer, Integer, String, String, String, Timestamp, Timestamp, Byte, Byte, String, String, Integer, Integer, Integer> valuesRow() {
return (Row14) super.valuesRow();
}
/**
* {@inheritDoc}
*/
@Override
public Field<Integer> field1() {
return WikiAttachmentrevision.WIKI_ATTACHMENTREVISION.ID;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Integer> field2() {
return WikiAttachmentrevision.WIKI_ATTACHMENTREVISION.REVISION_NUMBER;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field3() {
return WikiAttachmentrevision.WIKI_ATTACHMENTREVISION.USER_MESSAGE;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field4() {
return WikiAttachmentrevision.WIKI_ATTACHMENTREVISION.AUTOMATIC_LOG;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field5() {
return WikiAttachmentrevision.WIKI_ATTACHMENTREVISION.IP_ADDRESS;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Timestamp> field6() {
return WikiAttachmentrevision.WIKI_ATTACHMENTREVISION.MODIFIED;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Timestamp> field7() {
return WikiAttachmentrevision.WIKI_ATTACHMENTREVISION.CREATED;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Byte> field8() {
return WikiAttachmentrevision.WIKI_ATTACHMENTREVISION.DELETED;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Byte> field9() {
return WikiAttachmentrevision.WIKI_ATTACHMENTREVISION.LOCKED;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field10() {
return WikiAttachmentrevision.WIKI_ATTACHMENTREVISION.FILE;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field11() {
return WikiAttachmentrevision.WIKI_ATTACHMENTREVISION.DESCRIPTION;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Integer> field12() {
return WikiAttachmentrevision.WIKI_ATTACHMENTREVISION.ATTACHMENT_ID;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Integer> field13() {
return WikiAttachmentrevision.WIKI_ATTACHMENTREVISION.PREVIOUS_REVISION_ID;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Integer> field14() {
return WikiAttachmentrevision.WIKI_ATTACHMENTREVISION.USER_ID;
}
/**
* {@inheritDoc}
*/
@Override
public Integer value1() {
return getId();
}
/**
* {@inheritDoc}
*/
@Override
public Integer value2() {
return getRevisionNumber();
}
/**
* {@inheritDoc}
*/
@Override
public String value3() {
return getUserMessage();
}
/**
* {@inheritDoc}
*/
@Override
public String value4() {
return getAutomaticLog();
}
/**
* {@inheritDoc}
*/
@Override
public String value5() {
return getIpAddress();
}
/**
* {@inheritDoc}
*/
@Override
public Timestamp value6() {
return getModified();
}
/**
* {@inheritDoc}
*/
@Override
public Timestamp value7() {
return getCreated();
}
/**
* {@inheritDoc}
*/
@Override
public Byte value8() {
return getDeleted();
}
/**
* {@inheritDoc}
*/
@Override
public Byte value9() {
return getLocked();
}
/**
* {@inheritDoc}
*/
@Override
public String value10() {
return getFile();
}
/**
* {@inheritDoc}
*/
@Override
public String value11() {
return getDescription();
}
/**
* {@inheritDoc}
*/
@Override
public Integer value12() {
return getAttachmentId();
}
/**
* {@inheritDoc}
*/
@Override
public Integer value13() {
return getPreviousRevisionId();
}
/**
* {@inheritDoc}
*/
@Override
public Integer value14() {
return getUserId();
}
/**
* {@inheritDoc}
*/
@Override
public WikiAttachmentrevisionRecord value1(Integer value) {
setId(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public WikiAttachmentrevisionRecord value2(Integer value) {
setRevisionNumber(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public WikiAttachmentrevisionRecord value3(String value) {
setUserMessage(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public WikiAttachmentrevisionRecord value4(String value) {
setAutomaticLog(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public WikiAttachmentrevisionRecord value5(String value) {
setIpAddress(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public WikiAttachmentrevisionRecord value6(Timestamp value) {
setModified(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public WikiAttachmentrevisionRecord value7(Timestamp value) {
setCreated(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public WikiAttachmentrevisionRecord value8(Byte value) {
setDeleted(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public WikiAttachmentrevisionRecord value9(Byte value) {
setLocked(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public WikiAttachmentrevisionRecord value10(String value) {
setFile(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public WikiAttachmentrevisionRecord value11(String value) {
setDescription(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public WikiAttachmentrevisionRecord value12(Integer value) {
setAttachmentId(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public WikiAttachmentrevisionRecord value13(Integer value) {
setPreviousRevisionId(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public WikiAttachmentrevisionRecord value14(Integer value) {
setUserId(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public WikiAttachmentrevisionRecord values(Integer value1, Integer value2, String value3, String value4, String value5, Timestamp value6, Timestamp value7, Byte value8, Byte value9, String value10, String value11, Integer value12, Integer value13, Integer value14) {
value1(value1);
value2(value2);
value3(value3);
value4(value4);
value5(value5);
value6(value6);
value7(value7);
value8(value8);
value9(value9);
value10(value10);
value11(value11);
value12(value12);
value13(value13);
value14(value14);
return this;
}
// -------------------------------------------------------------------------
// Constructors
// -------------------------------------------------------------------------
/**
* Create a detached WikiAttachmentrevisionRecord
*/
public WikiAttachmentrevisionRecord() {
super(WikiAttachmentrevision.WIKI_ATTACHMENTREVISION);
}
/**
* Create a detached, initialised WikiAttachmentrevisionRecord
*/
public WikiAttachmentrevisionRecord(Integer id, Integer revisionNumber, String userMessage, String automaticLog, String ipAddress, Timestamp modified, Timestamp created, Byte deleted, Byte locked, String file, String description, Integer attachmentId, Integer previousRevisionId, Integer userId) {
super(WikiAttachmentrevision.WIKI_ATTACHMENTREVISION);
set(0, id);
set(1, revisionNumber);
set(2, userMessage);
set(3, automaticLog);
set(4, ipAddress);
set(5, modified);
set(6, created);
set(7, deleted);
set(8, locked);
set(9, file);
set(10, description);
set(11, attachmentId);
set(12, previousRevisionId);
set(13, userId);
}
}
|
// https://www.youtube.com/watch?v=hWFqtlbnQV8&list=PL1w8k37X_6L8xh476yG6UNfXBCT1tq2vM&index=28
class Solution {
public boolean possibleBipartition(int N, int[][] dislikes) {
int[] groups = new int[N];
Arrays.fill(groups, -1);
ArrayList<Integer>[] adj = new ArrayList[N];
for (int i = 0; i < N; i++)
adj[i] = new ArrayList();
for (int[] p : dislikes) {
adj[p[0] - 1].add(p[1] - 1);
adj[p[1] - 1].add(p[0] - 1);
}
for (int i = 0; i < N; i++) {
if (groups[i] == -1 && !dfs(adj, groups, i, 0))
return false;
}
return true;
}
private boolean dfs(ArrayList<Integer>[] adj, int[] groups, int v, int grp) {
if (groups[v] == -1) groups[v] = grp;
else return groups[v] == grp;
for (int n : adj[v]) {
if (!dfs(adj, groups, n, 1 - grp))
return false;
}
return true;
}
}
|
package edu.gatech.snickers.techflixandchill;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.ValueEventListener;
/**
* Created by Snickers on 2/14/16.
*
* Last modified on 2/21/16.
*
* This class provides the users with a way to view their profile, as well as provides the option
* to edit and save changes to their profile information. Updated to integrate Firebase database.
*
* @author Snickers
* @version 1.1
*/
public class UserProfile extends Activity {
/**
* TextViews that are populated with the user details for a given user, obtained through a
* query to the Firebase database.
*/
private TextView userProfileUsernameTV, userProfilePasswordTV, userProfileEmailTV, userProfileSecuHintTV, userProfileNameTV, userProfileMajorTV;
/**
* Firebase database references used to get the user details for a particular user.
*/
private Firebase ref;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_profile);
userProfileUsernameTV = (TextView) findViewById(R.id.userProfileUsernameTV);
userProfilePasswordTV = (TextView) findViewById(R.id.userProfilePasswordTV);
userProfileEmailTV = (TextView) findViewById(R.id.userProfileEmailTV);
userProfileSecuHintTV = (TextView) findViewById(R.id.userProfileSecuHintTV);
userProfileMajorTV = (TextView) findViewById(R.id.userProfileMajorTV);
userProfileNameTV = (TextView) findViewById(R.id.userProfileNameTV);
final Button editProfileButton = (Button) findViewById(R.id.editProfileButton);
final Button goHomeButton = (Button) findViewById(R.id.goHomeButton);
Firebase.setAndroidContext(this);
ref = new Firebase("https://techflixandchill.firebaseio.com");
final Bundle bundle;
bundle = getIntent().getExtras();
//Extract the data
final String name = bundle.getString("NAME");
final String username = bundle.getString("USERNAME");
final String password = bundle.getString("PASSWORD");
final String major = bundle.getString("MAJOR");
final String email = bundle.getString("EMAIL");
final String securityHint = bundle.getString("SECURITYHINT");
final Firebase editRef = ref.child("users").child(username);
editRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
final User user = dataSnapshot.getValue(User.class);
userProfileNameTV.setText("Name: " + user.getName());
userProfileUsernameTV.setText("Username: " + user.getUsername());
userProfilePasswordTV.setText("Password: " + user.getPassword());
userProfileEmailTV.setText("Email: " + user.getEmail());
userProfileSecuHintTV.setText("Security Hint: " + user.getSecurityHint());
userProfileMajorTV.setText("Major: " + user.getMajor());
}
@Override
public void onCancelled(FirebaseError firebaseError) {
//do nothing
}
});
//allows the user to edit their profile and save those changes
editProfileButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final Dialog dialog = new Dialog(UserProfile.this);
dialog.getWindow();
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.edit_user);
dialog.show();
//set up all editable fields, populate with current values
final TextView newUsername = (TextView) dialog.findViewById(R.id.editUsernameET);
newUsername.setText(username);
final EditText newPassword = (EditText) dialog.findViewById(R.id.editPasswordET);
newPassword.setText(password);
final EditText newEmail = (EditText) dialog.findViewById(R.id.editEmailET);
newEmail.setText(email);
final EditText newSecuHint = (EditText) dialog.findViewById(R.id.editSecuHintET);
newSecuHint.setText(securityHint);
final Spinner newMajor = (Spinner) dialog.findViewById(R.id.editMajorSpinner);
final String[] items = getResources().getStringArray(R.array.majors_array);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(UserProfile.this, android.R.layout.simple_spinner_dropdown_item, items);
//make sure that spinner initially starts on their original major selection
final int i = adapter.getPosition(major);
newMajor.setAdapter(adapter);
newMajor.setSelection(i, true);
final EditText newName = (EditText) dialog.findViewById(R.id.editNameET);
newName.setText(name);
final Button saveChanges = (Button) dialog.findViewById(R.id.save_changes_btn);
final Button cancel = (Button) dialog.findViewById(R.id.cancel_changes_btn);
saveChanges.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ref = new Firebase("https://techflixandchill.firebaseio.com");
//note: we don't allow users to change usernames at this time
//final String updatedUsername = newUsername.getText().toString();
final String updatedPassword = newPassword.getText().toString();
final String updatedEmail = newEmail.getText().toString();
final String updatedSecuHint = newSecuHint.getText().toString();
final String updatedMajor = newMajor.getSelectedItem().toString();
final String updatedName = newName.getText().toString();
//update database with new info
final Firebase editRef = ref.child("users").child(username);
editRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
editRef.child("password").setValue(updatedPassword);
editRef.child("email").setValue(updatedEmail);
editRef.child("securityHint").setValue(updatedSecuHint);
editRef.child("major").setValue(updatedMajor);
editRef.child("name").setValue(updatedName);
userProfileNameTV.setText("Name: " + updatedName);
userProfilePasswordTV.setText("Password: " + updatedPassword);
userProfileEmailTV.setText("Email: " + updatedEmail);
userProfileSecuHintTV.setText("Security Hint: " + updatedSecuHint);
userProfileMajorTV.setText("Major: " + updatedMajor);
}
@Override
public void onCancelled(FirebaseError firebaseError) {
}
});
final Intent iii = new Intent(UserProfile.this, Home.class);
bundle.putString("PASSWORD", updatedPassword);
bundle.putString("NAME", updatedName);
bundle.putString("MAJOR", updatedMajor);
bundle.putString("SECURITYHINT", updatedSecuHint);
bundle.putString("EMAIL", updatedEmail);
iii.putExtras(bundle);
finish();
startActivity(iii);
}
});
cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
});
goHomeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final Intent i = new Intent(UserProfile.this,Home.class);
i.putExtras(bundle);
//start the activity
startActivity(i);
}
});
}
}
|
package lab2;
import java.util.ArrayList;
/**
* Representa a conta de laboratório deve ser responsável por manter o registro da
* quantidade de espaço utilizado, pelo aluno, em determinado laboratório.
* Para cada laboratório, seria criado um objeto para controle desse estado (espaço ocupado)
*
* @author Charles Bezerra de Oliveira Júnior - 119110595
*/
public class ContaCantina {
/**
* Nome da cantina inicializado no construtor
* */
private String nomeCantina;
/**
* Valor em centavos que o aluno está devendo na Cantina
* */
private int debitoConta;
/**
* Valor quitado pelo o aluno na conta da cantina
* */
private int valorPagoConta = 0;
/**
* Quantidade de itens adiquidos pelo aluno
* */
private int qdtItens = 0;
/**
* Lista contendo detalhes de compras realizados pelo aluno
* */
private ArrayList<String> detalhesItens = new ArrayList<String>();
/**
* Constrói uma conta na Cantina a partir de seu nome.
*
* @param nomeCantina o nome da conta da cantina
*/
ContaCantina(String nomeCantina){
this.nomeCantina = nomeCantina;
}
/**
* Altera os valores dos atributos this.qtdItens, this.debitoConta adicionando os
* valores qtdItens e valorCentavos respectivamente
*
* @param qtdItens quantidade de itens comprados em um lanche
* @param valorCentavos valor total em centavos da compŕa
*/
public void cadastraLanche(int qtdItens, int valorCentavos) {
this.qdtItens += qtdItens;
this.debitoConta += valorCentavos;
}
/**
*
* Cadastra e adiciona compras reilizadas pelo aluno, além de adicionar detalhes
* na lista this.detalhesitens
*
* @param qtdItens inteiro com o valor da quantidade de itens da compra
* @param valorCentavos inteiro com o valor da compra em centavos
* @param detalhes string contendo detalhes da compra
* */
public void cadastraLanche(int qtdItens, int valorCentavos, String detalhes) {
this.detalhesItens.add(detalhes);
this.cadastraLanche(qtdItens, valorCentavos);
}
/**
*
* Procedimento que adicionar um valor em centavos ao
* montante já pago pelo aluno.
*
* @param valorCentavos valor em centavos que já foi pago pelo aluno
* */
public void pagaConta(int valorCentavos) {
if( (this.valorPagoConta + valorCentavos) <= this.debitoConta)
this.valorPagoConta += valorCentavos;
}
/**
*
* Retorna o valor que falta a ser abatido na conta
*
* @return valor em centavos que aluno ainda deve a cantina".
*/
public int getFaltaPagar() {
return this.debitoConta - this.valorPagoConta;
}
/**
* Retorna uma lista com os 5 últimos detalhes adicionado
*
* @return 5 últimas observações na forma que cada observação fique sepados com \n".
*/
public String listarDetalhes() {
String valor = "";
for(int i = this.detalhesItens.size() - 5; i < this.detalhesItens.size();i++) {
valor += this.detalhesItens.get(i) + "\n";
}
return valor;
}
/**
* Retorna o String contendo o nome da Cantina.
*
* @return nomeCantina a String contendo o nomeCantina.
*
*/
public String getNomeCantina() {
return this.nomeCantina;
}
/**
* Retorna o String que representa a Cantina.
*
* @return Representação da cantina com a forma: "<nome da cantina> <quantidade de itens> <debito da conta>".
*/
public String toString() {
return this.nomeCantina
+ " " + this.qdtItens
+ " " + this.debitoConta;
}
}
|
/*
* © Copyright 2016 CERN. This software is distributed under the terms of the Apache License Version 2.0, copied
* verbatim in the file “COPYING“. In applying this licence, CERN does not waive the privileges and immunities granted
* to it by virtue of its status as an Intergovernmental Organization or submit itself to any jurisdiction.
*/
package cern.molr.commons.registry.impl;
import cern.molr.commons.domain.Mission;
import cern.molr.commons.mission.MissionsDiscoverer;
/**
* In memory {@link Mission} registry that searches for {@link Mission}s on the construction phase using a
* {@link MissionsDiscoverer}.
*
* @see ObservableInMemoryEntriesRegistry
*/
public class InMemoryMissionsRegistry extends ObservableInMemoryEntriesRegistry<Mission> {
public InMemoryMissionsRegistry() {
}
public InMemoryMissionsRegistry(MissionsDiscoverer missionsDiscoverer) {
super();
if (null == missionsDiscoverer) {
throw new IllegalArgumentException("missions discoverer cannot be null");
}
registerEntries(missionsDiscoverer.availableMissions());
}
}
|
package com.mega.swipeit.Model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
public class User implements Serializable {
@SerializedName("id")
@Expose
private Integer id;
@SerializedName("name")
@Expose
private String name;
@SerializedName("email")
@Expose
private String email;
@SerializedName("otp")
@Expose
private String otp;
@SerializedName("avatar_url")
@Expose
private String avatarUrl;
@SerializedName("followers_count")
@Expose
private Integer followersCount;
@SerializedName("followings_count")
@Expose
private Integer followingsCount;
@SerializedName("likes_count")
@Expose
private Integer likesCount;
@SerializedName("is_followed")
@Expose
private Integer isFollowed;
@SerializedName("conversation_id")
@Expose
private Integer conversationId;
public Integer getConversationId() {
return conversationId;
}
public void setConversationId(Integer conversationId) {
this.conversationId = conversationId;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getOtp() {
return otp;
}
public void setOtp(String otp) {
this.otp = otp;
}
public String getAvatarUrl() {
return avatarUrl;
}
public void setAvatarUrl(String avatarUrl) {
this.avatarUrl = avatarUrl;
}
public Integer getFollowersCount() {
return followersCount;
}
public void setFollowersCount(Integer followersCount) {
this.followersCount = followersCount;
}
public Integer getFollowingsCount() {
return followingsCount;
}
public void setFollowingsCount(Integer followingsCount) {
this.followingsCount = followingsCount;
}
public Integer getLikesCount() {
return likesCount;
}
public void setLikesCount(Integer likesCount) {
this.likesCount = likesCount;
}
public Integer getIsFollowed() {
return isFollowed;
}
public void setIsFollowed(Integer isFollowed) {
this.isFollowed = isFollowed;
}
}
|
package io.zipcoder.interfaces;
public final class Students extends People<Student>{
private static final Students INSTANCE = new Students();
private Students(){
Student newStudent1 = new Student(10L, "Sam");
Student newStudent2 = new Student(20L, "Dan");
super.add(newStudent1);
super.add(newStudent2);
}
public Student[] getArray() {
return super.personList.toArray(new Student[0]);
}
public static Students getInstance(){
return INSTANCE;
}
}
|
package com.esum.comp.uadacom.inbound;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.esum.comp.uadacom.UaDacomConfig;
import com.esum.comp.uadacom.table.UaDacomInfoRecord;
import com.esum.comp.uadacom.table.UaDacomInfoTable;
import com.esum.framework.FrameworkSystemVariables;
import com.esum.framework.core.component.ComponentException;
import com.esum.framework.core.component.listener.LegacyListener;
import com.esum.framework.core.component.table.InfoTableManager;
import com.esum.framework.core.exception.SystemException;
/**
* Ua Dacom Legacy Listener.
*/
public class UaDacomLegacyListener extends LegacyListener {
private Logger log = LoggerFactory.getLogger(UaDacomLegacyListener.class);
private List<UaDacomInfoRecord> infoList;
private Hashtable<String, UaDacomReceiveScheduler> pollList = new Hashtable<String, UaDacomReceiveScheduler>();
private String nodeId;
public UaDacomLegacyListener() throws SystemException {
nodeId = System.getProperty(FrameworkSystemVariables.NODE_ID);
UaDacomInfoTable infoTable = (UaDacomInfoTable)InfoTableManager.getInstance().getInfoTable(UaDacomConfig.UADACOM_INFO_TABLE_ID);
infoList = infoTable.getInboundGatherInfoList();
}
@Override
protected void startupLegacy() throws SystemException {
traceId = "[" + getComponentId() + "][" + nodeId + "] ";
log.info(traceId+"UaDacom inbound starting. nodeId : "+nodeId);
Iterator<UaDacomInfoRecord> i = infoList.iterator();
while(i.hasNext()){
UaDacomInfoRecord info = i.next();
String interfaceId = info.getInterfaceId();
log.debug(traceId+"Starting UaDacom Scheduler. ip : "+info.getInboundIp()+", port : "+info.getInboundPort());
List<String> nodeList = info.getNodeList();
log.debug(traceId+"["+interfaceId+"] startup. nodeList : " + nodeList);
if (info.containsNodeId(nodeId)) {
try {
UaDacomReceiveScheduler listener = new UaDacomReceiveScheduler(info, this);
listener.startup();
pollList.put(interfaceId, listener);
log.info(traceId+"["+interfaceId+"] UaDacom listener started.");
} catch (Exception e) {
log.error(traceId+"["+interfaceId+"] UaDacom listener starting error.", e);
throw new ComponentException(e.toString());
}
}
}
log.debug(traceId + pollList.size() + " Inbound started.");
}
public void reload(String[] reloadIds) throws SystemException {
if (pollList.containsKey(reloadIds[0])) {
UaDacomReceiveScheduler listener = (UaDacomReceiveScheduler)pollList.get(reloadIds[0]);
listener.shutdown();
pollList.remove(reloadIds[0]);
listener = null;
}
UaDacomInfoTable infoTable = (UaDacomInfoTable)InfoTableManager.getInstance().getInfoTable(UaDacomConfig.UADACOM_INFO_TABLE_ID);
UaDacomInfoRecord uaInfo = null;
try{
uaInfo = (UaDacomInfoRecord)infoTable.getInfoRecord(reloadIds);
}catch(ComponentException e){
log.error(traceId + "reload()", e);
}
if (uaInfo != null && uaInfo.isUseInbound()) {
String interfaceId = uaInfo.getInterfaceId();
List<String> nodeList = uaInfo.getNodeList();
log.debug(traceId+"["+interfaceId+"] reload. nodeList : " + nodeList);
if (uaInfo.containsNodeId(nodeId)) {
try {
UaDacomReceiveScheduler handler = new UaDacomReceiveScheduler(uaInfo, this);
handler.startup();
pollList.put(interfaceId, handler);
log.info(traceId+"["+interfaceId+"] UaDacom listener after reloading info table restarted.");
} catch (Exception e) {
log.error(traceId+"["+interfaceId+"] UaDacom listener reload starting error.", e);
throw new ComponentException(e.toString());
}
}
}
}
protected void shutdownLegacy() throws SystemException {
Enumeration<String> e = pollList.keys();
while(e.hasMoreElements()) {
String key = e.nextElement();
UaDacomReceiveScheduler listener = (UaDacomReceiveScheduler)pollList.get(key);
listener.shutdown();
listener = null;
}
pollList.clear();
infoList = null;
}
}
|
package com.pykj.ykz.chapter4.aspect.service;
import com.pykj.ykz.chapter4.aspect.pojo.Person;
import com.pykj.ykz.chapter4.aspect.pojo.User;
/**
* @description: TODO
* @author: zhangpengxiang
* @time: 2020/4/21 17:14
*/
public interface UserService {
public Person printUser(User user);
}
|
package com.zl.controller;
import com.zl.aop.SystemControllerLog;
import com.zl.pojo.ContractDTO;
import com.zl.pojo.ContractVO;
import com.zl.pojo.GardenStuffDTO;
import com.zl.pojo.PeasantDO;
import com.zl.service.*;
import com.zl.util.AjaxPutPage;
import com.zl.util.AjaxResultPage;
import com.zl.util.Constants;
import com.zl.util.MessageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @program: FruitSales
* @classname: DealerController
* @description: 零售商特有权限Controlle
* @author: 朱林
* @create: 2019-05-16 11:55
**/
@Controller
@RequestMapping("/dealer")
public class DealerController {
@Autowired
private PeasantService peasantService;
@Autowired
private GardenStuffService gardenStuffService;
@Autowired
private ContractService contractService;
/**
* @Description: 跳转农民列表界面
* @Param: []
* @return: java.lang.String
* @Author: ZhuLin
* @Date: 2019/1/13
*/
@RequestMapping("/gotoPeasantList")
public String gotoPeasantList(){
return "dealer/peasantList";
}
/**
* @Description: 获取农民列表
* @Param: []
* @return: com.zl.util.AjaxResultPage<com.zl.pojo.PeasantDO>
* @Author: ZhuLin
* @Date: 2019/1/13
*/
@RequestMapping("/getPeasantList")
@ResponseBody
public AjaxResultPage<PeasantDO> getPeasantList(AjaxPutPage<PeasantDO> ajaxPutPage, PeasantDO peasantCondition){
ajaxPutPage.setCondition(peasantCondition);
AjaxResultPage<PeasantDO> result = peasantService.listPeasant(ajaxPutPage);
return result;
}
/**
* @Description: 获取果蔬列表
* @Param: [ajaxPutPage, GardenStuffCondition]
* @return: com.zl.util.AjaxResultPage<com.zl.pojo.GardenStuffDTO>
* @Author: ZhuLin
* @Date: 2019/1/22
*/
@RequestMapping("/getGardenStuffList")
@ResponseBody
public AjaxResultPage<GardenStuffDTO> getGardenStuffList(AjaxPutPage<GardenStuffDTO> ajaxPutPage, GardenStuffDTO GardenStuffCondition){
ajaxPutPage.setCondition(GardenStuffCondition);
AjaxResultPage<GardenStuffDTO> result = gardenStuffService.listGardenStuff(ajaxPutPage);
return result;
}
/**
* @Description: 跳转合同列表界面
* @Param: []
* @return: java.lang.String
* @date: 2019/2/5 20:12
*/
@RequestMapping("/gotoContractList")
public String gotoContractList(){
return "dealer/contractList";
}
/**
* @Description: 返回合同列表信息
* @Param: [ajaxPutPage, contractCondition]
* @return: com.zl.util.AjaxResultPage<com.zl.pojo.ContractDO>
* @date: 2019/2/5 15:41
*/
@RequestMapping("/getContractList")
@ResponseBody
public AjaxResultPage<ContractDTO> getContractList(AjaxPutPage<ContractDTO> ajaxPutPage, ContractDTO contractCondition){
contractCondition.setDealerId(BaseController.getSessionUser().getUserid());
ajaxPutPage.setCondition(contractCondition);
AjaxResultPage<ContractDTO> result = contractService.listContract(ajaxPutPage);
return result;
}
/**
* @Description: 取消合同
* @Param: [id]
* @return: com.zl.util.MessageBean
* @Author: ZhuLin
* @Date: 2019/2/13
*/
@SystemControllerLog(description = "删除合同")
@RequestMapping("/cancelContract")
@ResponseBody
public MessageBean cancelContract(String id) throws Exception{
contractService.updateContractByCheck(id,Constants.CONTRACT_CANCEL);
return new MessageBean(true,Constants.SUCCESS_DELETE);
}
/**
* @Description: 确认合同
* @Param: [id]
* @return: com.zl.util.MessageBean
* @Author: ZhuLin
* @Date: 2019/2/13
*/
@SystemControllerLog(description = "确认合同")
@RequestMapping("/confirmContract")
@ResponseBody
public MessageBean confirmContract(String id) throws Exception{
contractService.updateContractByCheck(id,Constants.CONTRACT_CONFIRM);
return new MessageBean(true,Constants.SUCCESS_DELETE);
}
/**
* @Description: 返回合同详情
* @Param: [contractId]
* @return: com.zl.pojo.ContractVO
* @date: 2019/2/8 12:23
*/
@RequestMapping("/getContractInfo")
@ResponseBody
public MessageBean getContractInfo(String contractId){
ContractVO contractVO = contractService.getContractInfo(contractId);
return new MessageBean(true,null,contractVO);
}
}
|
package com.zl.service;
import com.zl.pojo.AccessoryDO;
import com.zl.util.AjaxPutPage;
import com.zl.util.AjaxResultPage;
import com.zl.util.MessageException;
import java.util.List;
public interface AccessoryService {
/**
* @Description: 根据果蔬id返回对应的附属品
* @Param: [gardenstuffId]
* @return: java.util.List<com.zl.pojo.AccessoryDO>
* @Author: ZhuLin
* @Date: 2019/1/31
*/
AjaxResultPage<AccessoryDO> listAccessoryByGardenId(AjaxPutPage<AccessoryDO> ajaxPutPage);
/**
* @Description: 修改附属品
* @Param: [accessoryDO]
* @return: void
* @Author: ZhuLin
* @Date: 2019/1/31
*/
void updateAccessory(AccessoryDO accessoryDO) throws MessageException;
/**
* @Description: 删除附属品
* @Param: [id]
* @return: void
* @Author: ZhuLin
* @Date: 2019/1/31
*/
void deleteAccessory(String id) throws MessageException;
/**
* @Description: 添加附属品
* @Param: [accessoryDO]
* @return: void
* @date: 2019/2/2 21:09
*/
void insertAccessory(AccessoryDO accessoryDO) throws MessageException;
}
|
package day22stringbuildersencapsulation;
public class StringBuilders02 {
public static void main(String[] args) {
StringBuilder sb1 = new StringBuilder();
long startingTimeSb = System.nanoTime();
for (int i = 0; i < 1000; i++) {
sb1.append("xyz");
}
long endingTimeSb = System.nanoTime();
System.out.println(endingTimeSb - startingTimeSb);
String str = new String();
for (int i = 0; i < 1000; i++) {
str.concat("xyz");
}
long endingTimeStr = System.nanoTime();
System.out.println(endingTimeStr - endingTimeSb);
StringBuffer sbf = new StringBuffer();
for (int i = 0; i < 1000; i++) {
sbf.append("xyz");
}
long endingTimeSbf = System.nanoTime();
System.out.println(endingTimeSbf - endingTimeStr);
}
}
|
package com.nantian.foo.web.util.service.impl;
import com.nantian.foo.web.util.pools.BaseObjPool;
import com.nantian.foo.web.util.service.BaseService;
import org.springframework.stereotype.Service;
@Service
public class BaseServiceImpl implements BaseService {
@Override
public void baseDataInit() {
try {
if (BaseObjPool.getApplicationStatus() == BaseObjPool.APPLICATION_DATAINIT) {
BaseObjPool.setApplicationStatus(BaseObjPool.APPLICATION_NORMAL);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package webshop.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import webshop.dto.ProductDTO;
import webshop.service.ProductService;
@RestController
public class ProductController {
@Autowired
private ProductService productService;
@PostMapping("/products")
public ResponseEntity<?> registerProduct(@RequestBody ProductDTO productDTO){
ProductDTO productDTO1 = productService.add(productDTO);
return new ResponseEntity<>(productDTO1, HttpStatus.OK);
}
@PutMapping("/products/{productNumber}")
public ResponseEntity<?> updateProduct(@PathVariable String productNumber,@RequestBody ProductDTO productDTO){
ProductDTO productDTO1 = productService.update(productNumber,productDTO);
return new ResponseEntity<>(productDTO1,HttpStatus.OK);
}
@DeleteMapping("/products/{productNumber}")
public ResponseEntity<?> deleteProduct(@PathVariable String productNumber){
productService.remove(productNumber);
return new ResponseEntity<>(HttpStatus.NO_CONTENT,HttpStatus.OK);
}
@GetMapping("/products/{productNumber}")
public ResponseEntity<?> getProduct(@PathVariable String productNumber){
ProductDTO productDTO = productService.getProduct(productNumber);
return new ResponseEntity<>(productDTO,HttpStatus.OK);
}
@GetMapping("/products/{productNumber}/stock")
public Integer getProductQuantityStock(@PathVariable String productNumber){
ProductDTO productDTO = productService.getProduct(productNumber);
Integer quantity = productDTO.getNumberInStock();
return quantity;
}
}
|
package pl.basistam.guests;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
@WebServlet("/login")
public class LoginController extends HttpServlet {
private final String LOGIN = "marcin";
private final String PASSWORD = "admin1";
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String login = request.getParameter("login");
String password = request.getParameter("pass");
if (login == null || login.isEmpty()) {
request.setAttribute("ErrorMessage", "Login is empty!");
request.getRequestDispatcher("/WEB-INF/Login.jsp").forward(request,response);
return;
}
if (password == null || password.isEmpty()) {
request.setAttribute("ErrorMessage", "Password is empty!");
request.getRequestDispatcher("/WEB-INF/Login.jsp").forward(request,response);
return;
}
if (!LOGIN.equals(login) || !PASSWORD.equals(password)) {
request.setAttribute("ErrorMessage", "Login or password is incorrect!");
request.getRequestDispatcher("/WEB-INF/Login.jsp").forward(request,response);
return;
}
HttpSession session = request.getSession();
session.setAttribute("user", login);
Cookie cookie = new Cookie("user", login);
cookie.setMaxAge(3600);
response.addCookie(cookie);
response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", "/lab2/guests");
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (request.getCookies() != null) {
for (Cookie cookie : request.getCookies()) {
if ("user".equals(cookie.getName()) && LOGIN.equals(cookie.getValue())) {
response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", "/lab2/guests");
return;
}
}
}
request.getRequestDispatcher("/WEB-INF/Login.html").forward(request, response);
}
}
|
package com.gymteam.tom.gymteam.model;
import java.util.ArrayList;
/**
* Created by tomshabtay on 18/08/2017.
*/
public class User {
private String name;
private String id;
private int age;
public ArrayList<WorkoutInvite> invites;
public User(String name, String id){
this.name = name;
this.id = id;
this.age = 0;
invites = new ArrayList<WorkoutInvite>();
}
public User() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
|
package com.xnarum.thonline.entity.idd002;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
@XmlAccessorType(XmlAccessType.FIELD)
public class AccountDetailsQueryRequestBody {
@XmlElement(name="THAcct")
private String accountNo;
@XmlElement(name="THICNo")
private String thIcNumber;
public String getAccountNo() {
return accountNo;
}
public void setAccountNo(String accountNo) {
this.accountNo = accountNo;
}
public String getThIcNumber() {
return thIcNumber;
}
public void setThIcNumber(String thIcNumber) {
this.thIcNumber = thIcNumber;
}
}
|
package com.wqiang.service;
import com.myspring.Annotation.Component;
@Component("orderService")
public class OrderService {
}
|
package com.assignment.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.assignment.model.TodoItem;
@Service
public class TodoService {
@Autowired
TodoRepository repo;
public boolean saveNewItem(TodoItem item) {
try {
repo.save(item);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public TodoItem getTodoItem(int id) {
return repo.findById(id).orElse(null);
}
public List<TodoItem> getAllItems() {
return (List<TodoItem>) repo.findAll();
}
public boolean removeItem(int id) {
try {
repo.deleteById(id);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean updateItem(TodoItem item) {
try {
TodoItem i = null;
if (repo.existsById(item.getId())) {
i = repo.findById(item.getId()).orElse(null);
}
if (i == null) {
i = item;
} else {
i.setCompleted(item.isCompleted());
i.setDetails(item.getDetails());
}
repo.save(i);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
|
package com.logicbig.example;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultMatcher;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = WebConfigProduce.class)
public class UserControllerTestProduce {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup () {
DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(this.wac);
this.mockMvc = builder.build();
}
@Test
public void testMyMvcController () throws Exception {
ResultMatcher expected = MockMvcResultMatchers.jsonPath("userName")
.value("Joe");
MockHttpServletRequestBuilder builder =
MockMvcRequestBuilders.get("/users")
.accept(MediaType.APPLICATION_JSON);
this.mockMvc.perform(builder)
.andExpect(expected);
}
@Test
public void testMyMvcController2 () throws Exception {
ResultMatcher expected = MockMvcResultMatchers.xpath("userName")
.string("Joe");
MockHttpServletRequestBuilder builder =
MockMvcRequestBuilders.post("/users")
.accept(MediaType.APPLICATION_XML);
this.mockMvc.perform(builder)
.andExpect(expected);
}
}
|
package ru.alexside.model;
import lombok.Data;
import javax.persistence.*;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Alex on 25.03.2018.
*/
@Data
@Entity
@Table(name = "OM_STOPS")
public class Stop {
@Id
@SequenceGenerator(name = "SEQ_OM_STOPS_ID", allocationSize = 1, sequenceName = "SEQ_OM_STOPS_ID")
@GeneratedValue(generator = "SEQ_OM_STOPS_ID", strategy = GenerationType.SEQUENCE)
private Long id;
@Column
private String stopGroupId;
@Column
private String address;
@Column
private Double longitude;
@Column
private Double latitude;
@Column
private Integer stopOrder;
@Column
private Integer stopType;
@Column
private Duration waitTime;
@Column
private Duration layoverTime;
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "OM_GPO_CONTACTS",
joinColumns = {@JoinColumn(name = "STOP_ID", nullable = false, updatable = false)},
inverseJoinColumns = {@JoinColumn(name = "CONTACT_HEADER_ID", nullable = false, updatable = false)})
private List<Contact> contacts = new ArrayList<>();
}
|
package com.ConfigPoste.RecetteCuisine.RecetteCuisine.Repository;
import com.ConfigPoste.RecetteCuisine.RecetteCuisine.Model.FileImage;
import org.springframework.data.repository.CrudRepository;
public interface FileImageRepository extends CrudRepository<FileImage,Integer> {
}
|
package menghitungluas;
import java.util.Scanner;
public class MenghitungLuas
{
public static void main( String[] args ) {
System.out.println("****************************************");
System.out.println("Program Menghitung Luas Segitiga ^_^");
System.out.println("****************************************");
System.out.println("");
int a, t;
double luas;
Scanner bil = new Scanner(System.in);
System.out.print("Masukan Alas : ");
a = bil.nextInt();
System.out.print("Masukan Tinggi : ");
t = bil.nextInt();
luas = (a * t) / 2;
System.out.println("Luas Segitaga = " + luas);
}
}
|
package com.myth.springboot.dao;
import com.myth.springboot.entity.Class;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface ClassMapper {
//新增班级
int classInsert(Class cla);
//查询班级
List<Class> classSelect(Class cla);
//修改班级
int classUpdateById(Class cla);
//删除班级
int classDeleteById(Class cla);
}
|
package com.romens.yjkgrab.ui.widget;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Contacts;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.romens.yjkgrab.R;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by myq on 15-12-13.
*/
public class PhoneNumberDialog extends AlertDialog implements View.OnClickListener {
private String phoneNumber, name;
private RelativeLayout rl;
private TextView call, send_msg, save, cancel, title;
protected PhoneNumberDialog(Context context) {
this(context, R.style.full_dialog);
}
public PhoneNumberDialog(Context context, String phoneNumber, String name) {
this(context);
this.phoneNumber = replaceBlank(phoneNumber);
this.name = name;
}
protected PhoneNumberDialog(Context context, int themeResId) {
super(context, themeResId);
setOwnerActivity((Activity) context);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WindowManager windowManager = getOwnerActivity().getWindowManager();
Display display = windowManager.getDefaultDisplay();
WindowManager.LayoutParams lp = this.getWindow().getAttributes();
lp.width = (int) (display.getWidth()); //设置宽度
this.getWindow().setAttributes(lp);
setContentView(R.layout.full_screen_dialog_layout);
initView();
}
private void initView() {
rl = (RelativeLayout) findViewById(R.id.rl);
call = (TextView) findViewById(R.id.call);
send_msg = (TextView) findViewById(R.id.send_msg);
save = (TextView) findViewById(R.id.save);
cancel = (TextView) findViewById(R.id.cancel);
title = (TextView) findViewById(R.id.title);
title.setText(phoneNumber + "\n可能是一个电话号码,你可以");
rl.setOnClickListener(this);
cancel.setOnClickListener(this);
save.setOnClickListener(this);
send_msg.setOnClickListener(this);
call.setOnClickListener(this);
}
public String replaceBlank(String str) {
String dest = "";
if (str != null) {
Pattern p = Pattern.compile("\\s*|\t|\r|\n");
Matcher m = p.matcher(str);
dest = m.replaceAll("");
}
return dest;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.call:
Intent intentCall = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phoneNumber));
getContext().startActivity(intentCall);
break;
case R.id.send_msg:
Intent intentSms = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + phoneNumber));
getContext().startActivity(intentSms);
break;
case R.id.save:
Intent intent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
intent.setType(Contacts.People.CONTENT_ITEM_TYPE);
intent.putExtra(Contacts.Intents.Insert.NAME, name);
intent.putExtra(Contacts.Intents.Insert.PHONE, phoneNumber);
intent.putExtra(Contacts.Intents.Insert.PHONE_TYPE, Contacts.PhonesColumns.TYPE_MOBILE);
getContext().startActivity(intent);
break;
case R.id.title:
break;
case R.id.cancel:
break;
default:
break;
}
dismiss();
}
}
|
package com.igs.test;
import android.content.Context;
import android.test.AndroidTestCase;
import com.hl.util.LogUtils;
import com.igs.callback.CallBackToProduct;
import com.igs.entity.rsp.RspBodyProductList;
import com.igs.exception.ErrorBundle;
import com.igs.repository.RepositoryProduct;
import com.igs.repository.impl.RepositoryProductImpl;
import com.igs.util.UrlManager;
import java.util.concurrent.CountDownLatch;
/**
* 类描述:
* 创建人:heliang
* 创建时间:2015/10/22 17:04
* 修改人:8153
* 修改时间:2015/10/22 17:04
* 修改备注:
*/
public class RepositoryProductTest extends AndroidTestCase {
private Context context;
private RepositoryProduct productRepository;
final CountDownLatch signal = new CountDownLatch(1);
@Override
protected void setUp() throws Exception {
super.setUp();
context = getContext();
productRepository = new RepositoryProductImpl(context);
}
/**
* 测试登陆
* @throws InterruptedException
*/
public void testProductList() throws InterruptedException {
CallBackToProduct.list callBack = new CallBackToProduct.list() {
@Override
public void onSuccess(RspBodyProductList rsp) {
if ( !rsp.getResultCode().equals(UrlManager.RSP_OK)) {
LogUtils.d(rsp.getResDes());
fail();
signal.countDown();
}else{
LogUtils.d(rsp.toString());
signal.countDown();
}
}
@Override
public void onError(ErrorBundle errorBundle) {
fail(errorBundle.getErrorMessage());
}
};
productRepository.list(1, 1, 1, callBack);
signal.await();
}
}
|
package atm;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class MainMenu extends JFrame{
public Container c;
public JButton w,ch,de,cha,tra,logout;
public Font f;
public static String aa;
MainMenu()
{
display();
}
public void display()
{
//CreateAccount menu = new CreateAccount();
//aa = menu.y;
//System.out.println(aa);
c = this.getContentPane();
c.setLayout(null);
f = new Font("Arial", Font.BOLD,14);
w = new JButton("WITHDRAW");
w.setBounds(20,40,115,40);
w.setFont(f);
c.add(w);
w.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
dispose();
Widthdraw menu = new Widthdraw();
menu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
menu.setBounds(400,200,350,300);
menu.setVisible(true);
menu.setTitle("ATM");
}
});
ch = new JButton("CHECK BALANCE");
ch.setBounds(150,40,160,40);
ch.setFont(f);
c.add(ch);
ch.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent ae){
dispose();
CheckBalance menu = new CheckBalance();
menu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
menu.setBounds(400,200,350,300);
menu.setVisible(true);
menu.setTitle("ATM");
}
});
de = new JButton("DEPOSIT");
de.setBounds(25,100,100,40);
de.setFont(f);
c.add(de);
de.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
dispose();
Deposit menu = new Deposit();
menu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
menu.setBounds(400,200,350,300);
menu.setVisible(true);
menu.setTitle("ATM");
}
});
cha = new JButton("CHANGE PIN");
cha.setBounds(155,100,150,40);
cha.setFont(f);
c.add(cha);
cha.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
//System.out.println(aa);
dispose();
ChangePin menu = new ChangePin();
menu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
menu.setBounds(400,200,350,300);
menu.setVisible(true);
menu.setTitle("ATM");
//menu.mp = "dslkjfdslkjf";
}
});
tra = new JButton("TRANSFER");
tra.setBounds(20,160,110,40);
tra.setFont(f);
c.add(tra);
tra.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
dispose();
Transfer menu = new Transfer();
menu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
menu.setBounds(400,200,350,300);
menu.setVisible(true);
menu.setTitle("ATM");
}
});
logout = new JButton("LOGOUT");
logout.setBounds(177,160,110,40);
logout.setFont(f);
c.add(logout);
logout.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent ae) {
JOptionPane.showMessageDialog(null, "You are Successfully Logout");
dispose();
ATM user = new ATM();
user.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
user.setBounds(400,200,350,300);
user.setVisible(true);
user.setTitle("ATM");
}
});
}
public static void main(String[] args) {
MainMenu menu = new MainMenu();
menu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
menu.setBounds(400,200,350,300);
menu.setVisible(true);
menu.setTitle("ATM");
}
}
|
package com.java.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class GetProduct
*/
@WebServlet("/GetProduct")
public class GetProduct extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public GetProduct() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("Hello 1"); // Hello 1 will not go to client
RequestDispatcher rd = request.getRequestDispatcher("/Product");
rd.forward(request, response);
out.println("Hello 2"); // Hello 2 will not go to client
out.close();
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
|
package com.lenovohit.hcp.base.manager;
import java.util.List;
import com.lenovohit.hcp.base.model.ItemInfo;
import com.lenovohit.hcp.base.model.ItemShortDetail;
/**
*
* 类描述: 项目信息(暂时只有符合项目信息维护)
*@author GW
*@date 2017年7月11日
*
*/
public interface ItemInfoManager {
/**
* 功能描述:更新符合项目明细
*@param complexItem
*@param detailItem
*@return
*@author GW
*@date 2017年7月12日
*/
public String updateComplexItemInfo(ItemInfo complexItem, List<ItemShortDetail> detailItem);
/**
* 功能描述:删除原有符合项目明细
*@param complexItem
*@return
*@author GW
*@date 2017年7月12日
*/
public String deleteDetail(ItemInfo complexItem);
/**
* 功能描述:保存新的复合项目
*@param complexItem
*@param detailItem
*@return
*@author GW
*@date 2017年7月12日
*/
public String saveComplexItemInfoDetail(ItemInfo complexItem,List<ItemShortDetail> detailItem);
}
|
package org.study.member;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.study.member.Exception.WrongIdPasswordException;
@Service
public class AuthService {
@Autowired
private MemberDAO memberDao;
public AuthInfo authenticate(String id, String password) throws Exception {
MemberVO memberVO = memberDao.selectById(id);
if(memberVO == null) {
throw new WrongIdPasswordException();
}
return new AuthInfo(
memberVO.getId(), memberVO.getName());
}
}
|
public class InternalException extends RuntimeException {
public InternalException(String msg) {
super(msg);
}
}
|
package lab4;
import java.util.Scanner;
public class Main {
private static Scanner sc;
private static ControleDeAluno controleDeAluno;
private static String listagem, matricula, nome, curso, grupo, op;
private static final String LS = System.lineSeparator();
public static void exibirMenu(){
System.out.print("(C)adastrar Aluno" + LS +
"(E)xibir Aluno" + LS +
"(N)ovo Grupo" + LS +
"(A)locar Aluno no Grupo e Imprimir Grupos" + LS +
"(R)egistrar Aluno que Respondeu" + LS +
"(I)mprimir Alunos que Responderam" + LS +
"(O)ra, vamos fechar o programa!" + LS +
"" + LS +
"Opção> ");
}
public static enum MensagemAlocarAluno{
NullMatricula(1), NullGrupo(2), Sucesso(3);
private int mensagem;
MensagemAlocarAluno(int mensagem){
this.mensagem = mensagem;
}
public MensagemAlocarAluno getMensagem() {
switch(mensagem) {
case 1:{ return NullMatricula; }
case 2:{ return NullGrupo; }
default: return Sucesso;
}
}
}
public static void alocarAlunoImprimirGrupo(){
<<<<<<< HEAD
System.out.print("(A)locar Aluno ou (I)mprimir Grupo? ");
op = sc.nextLine();
=======
System.out.print("(A)locar Aluno ou (I)mprimir Grupo? "); op = sc.nextLine();
>>>>>>> d2675f048eb3a935a1bee6e9e2a93d4e10f2316b
switch(op) {
case "A":{
System.out.print("Matricula: "); matricula = sc.nextLine();
System.out.print("Grupo: "); grupo = sc.nextLine();
<<<<<<< HEAD
System.out.print("Grupo: ");
grupo = sc.nextLine();
MensagemAlocarAluno msg = Main.MensagemAlocarAluno( controleDeAluno.alocarAlunoEmGrupo(matricula, grupo) ).getMensagem();
switch(msg) {
case MensagemAlocarAluno.NullMatricula:{
}
}
System.out.println();
=======
MensagensAlocarAluno msg = controleDeAluno.alocarAlunoEmGrupo(matricula, grupo);
switch (msg){
case AlunoNaoEncontrado:{ System.out.println("Aluno não cadastrado." + LS); break; }
case GrupoNaoEncontrado:{ System.out.println("Grupo não cadastrado." + LS); break; }
case CadastradoComSucesso:{ System.out.println("ALUNO ALOCADO" + LS); break; }
}
break;
>>>>>>> d2675f048eb3a935a1bee6e9e2a93d4e10f2316b
}
case "I":{
System.out.print("Grupo: "); grupo = sc.nextLine();
listagem = controleDeAluno.listarGrupo(grupo);
System.out.println( listagem == null ? "Grupo não cadastrado." + LS : listagem );
break;
}
}
}
<<<<<<< HEAD
public static void main(String[] args){
controleDeAluno = new ControleDeAluno();
sc = new Scanner(System.in);
exibirMenu();
op = sc.nextLine();
while (true){
switch (op){
case "C": {
System.out.print("Maticula: ");
matricula = sc.nextLine();
System.out.print("Nome: ");
nome = sc.nextLine();
System.out.print("Curso: ");
curso = sc.nextLine();
System.out.println( controleDeAluno.cadastrarAluno(matricula,nome,curso) ? "CADASTRO REALIZADO!" + LS : "MATRÍCULA JÁ CADASTRADA!" + LS);
}
case "E": {
System.out.print("Matrícula: ");
matricula = sc.nextLine();
=======
>>>>>>> d2675f048eb3a935a1bee6e9e2a93d4e10f2316b
public static void cadastrarAluno(){
System.out.print("Maticula: "); matricula = sc.nextLine();
System.out.print("Nome: "); nome = sc.nextLine();
System.out.print("Curso: "); curso = sc.nextLine();
System.out.println( controleDeAluno.cadastrarAluno(matricula, nome, curso) ? "CADASTRO REALIZADO!" + LS : "MATRÍCULA JÁ CADASTRADA!" + LS);
}
public static void exibirAluno(){
System.out.print("Matrícula: "); matricula = sc.nextLine();
listagem = controleDeAluno.exibirAluno(matricula);
System.out.println(LS + (listagem != null ? listagem + LS: "Aluno não cadastrado." + LS) );
}
public static void novoGrupo(){
System.out.print("Grupo: ");
grupo = sc.nextLine();
System.out.println( controleDeAluno.cadastrarGrupoDeEstudo(grupo) ? "CADASTRO REALIZADO!" + LS : "GRUPO JÁ CADASTRADO!" + LS );
}
public static void registrarRespostaAluno(){
System.out.print("Aluno: ");
matricula = sc.nextLine();
System.out.println( controleDeAluno.cadastrarRespostaDeAlunos(matricula) ? "ALUNO REGISTRADO!" + LS : "Aluno não cadastrado." + LS );
}
public static void imprimirAlunoQueResponderam() {
listagem = controleDeAluno.listarRespostasDeAlunos();
System.out.println( listagem + LS != null ? listagem : "ALUNO REGISTRADO!" + LS );
}
public static void iniciarObjetos(){
controleDeAluno = new ControleDeAluno();
sc = new Scanner(System.in);
listagem = new String("");
matricula = new String("");
nome = new String("");
curso = new String("");
grupo = new String("");
op = new String("");
}
public static void main(String[] args){
iniciarObjetos();
exibirMenu(); op = sc.nextLine();
while (true){
switch (op){
case "C":{ cadastrarAluno(); break;}
case "E":{ exibirAluno(); break; }
case "N":{ novoGrupo(); break; }
case "A":{ alocarAlunoImprimirGrupo(); break; }
case "R":{ registrarRespostaAluno(); break; }
case "I":{ imprimirAlunoQueResponderam(); break; }
case "O":{ System.exit(0); }
default:{ System.out.println("OPÇÃO INVÁLIDA!" + LS); break; }
}
exibirMenu(); op = sc.nextLine();
}
}
}
|
package com.android.zjshare.entity;
import java.util.List;
public class ProductDetailBean {
private int id;
private String userId;
private String catCode;
private int brandId;
private String goodsCode;
private String goodsName;
private String goodsTitle;
private int salesVolume;
private String marketPrice;
private String costPrice;
private String defaultImg;
private List<String> imgs;
private String goodsPcDesc;
private int salesNumber;
private int isOnSale;
private String isBest;
private String isHot;
private String isPromote;
private String isDelete;
private String deliveryWay;
private int status;
private String typeId;
private String typeValue;
private int postagId;
private int limitNumber;
private int totalGoodsStock;
private String goodsType;
private String createTime;
private String updateTime;
private String auditUserName;
private String auditStatus;
private String auditOpinion;
private String auditTime;
private List<GoodsSpecList> goodsSpecList;
private List<GoodsAttrList> goodsAttrList;
private ShopInfo shopDto;
public ShopInfo getShopDto() {
return shopDto;
}
public void setShopDto(ShopInfo shopDto) {
this.shopDto = shopDto;
}
private String remarks;
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public GoodsSpecList getSelectSpec(){
if (goodsSpecList!=null&&goodsSpecList.size()>0){
for (GoodsSpecList item:goodsSpecList) {
if (item.isSelected())
return item;
}
}
return null;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserId() {
return userId;
}
public void setCatCode(String catCode) {
this.catCode = catCode;
}
public String getCatCode() {
return catCode;
}
public void setBrandId(int brandId) {
this.brandId = brandId;
}
public int getBrandId() {
return brandId;
}
public void setGoodsCode(String goodsCode) {
this.goodsCode = goodsCode;
}
public String getGoodsCode() {
return goodsCode;
}
public void setGoodsName(String goodsName) {
this.goodsName = goodsName;
}
public String getGoodsName() {
return goodsName;
}
public void setGoodsTitle(String goodsTitle) {
this.goodsTitle = goodsTitle;
}
public String getGoodsTitle() {
return goodsTitle;
}
public void setSalesVolume(int salesVolume) {
this.salesVolume = salesVolume;
}
public int getSalesVolume() {
return salesVolume;
}
public String getMarketPrice() {
return marketPrice;
}
public void setMarketPrice(String marketPrice) {
this.marketPrice = marketPrice;
}
public String getCostPrice() {
return costPrice;
}
public void setCostPrice(String costPrice) {
this.costPrice = costPrice;
}
public void setDefaultImg(String defaultImg) {
this.defaultImg = defaultImg;
}
public String getDefaultImg() {
return defaultImg;
}
public void setImgs(List<String> imgs) {
this.imgs = imgs;
}
public List<String> getImgs() {
return imgs;
}
public void setGoodsPcDesc(String goodsPcDesc) {
this.goodsPcDesc = goodsPcDesc;
}
public String getGoodsPcDesc() {
return goodsPcDesc;
}
public void setSalesNumber(int salesNumber) {
this.salesNumber = salesNumber;
}
public int getSalesNumber() {
return salesNumber;
}
public void setIsOnSale(int isOnSale) {
this.isOnSale = isOnSale;
}
public int getIsOnSale() {
return isOnSale;
}
public void setIsBest(String isBest) {
this.isBest = isBest;
}
public String getIsBest() {
return isBest;
}
public void setIsHot(String isHot) {
this.isHot = isHot;
}
public String getIsHot() {
return isHot;
}
public void setIsPromote(String isPromote) {
this.isPromote = isPromote;
}
public String getIsPromote() {
return isPromote;
}
public void setIsDelete(String isDelete) {
this.isDelete = isDelete;
}
public String getIsDelete() {
return isDelete;
}
public void setDeliveryWay(String deliveryWay) {
this.deliveryWay = deliveryWay;
}
public String getDeliveryWay() {
return deliveryWay;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public void setTypeId(String typeId) {
this.typeId = typeId;
}
public String getTypeId() {
return typeId;
}
public void setTypeValue(String typeValue) {
this.typeValue = typeValue;
}
public String getTypeValue() {
return typeValue;
}
public void setPostagId(int postagId) {
this.postagId = postagId;
}
public int getPostagId() {
return postagId;
}
public void setLimitNumber(int limitNumber) {
this.limitNumber = limitNumber;
}
public int getLimitNumber() {
return limitNumber;
}
public void setTotalGoodsStock(int totalGoodsStock) {
this.totalGoodsStock = totalGoodsStock;
}
public int getTotalGoodsStock() {
return totalGoodsStock;
}
public void setGoodsType(String goodsType) {
this.goodsType = goodsType;
}
public String getGoodsType() {
return goodsType;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public String getUpdateTime() {
return updateTime;
}
public void setUpdateTime(String updateTime) {
this.updateTime = updateTime;
}
public void setAuditUserName(String auditUserName) {
this.auditUserName = auditUserName;
}
public String getAuditUserName() {
return auditUserName;
}
public void setAuditStatus(String auditStatus) {
this.auditStatus = auditStatus;
}
public String getAuditStatus() {
return auditStatus;
}
public void setAuditOpinion(String auditOpinion) {
this.auditOpinion = auditOpinion;
}
public String getAuditOpinion() {
return auditOpinion;
}
public void setAuditTime(String auditTime) {
this.auditTime = auditTime;
}
public String getAuditTime() {
return auditTime;
}
public void setGoodsSpecList(List<GoodsSpecList> goodsSpecList) {
this.goodsSpecList = goodsSpecList;
}
public List<GoodsSpecList> getGoodsSpecList() {
return goodsSpecList;
}
public void setGoodsAttrList(List<GoodsAttrList> goodsAttrList) {
this.goodsAttrList = goodsAttrList;
}
public List<GoodsAttrList> getGoodsAttrList() {
return goodsAttrList;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
public String getRemarks() {
return remarks;
}
public static class ShopInfo{
private int id;
private int userId;
private String shopName;
private String shopLogo;
private String shopBannerImg;
private String shopVideo;
private String shopTemplate;
private String isClose;
private String goodsCount;
private String companyName;
private int shopType;
private String createTime;
private String createUser;
private String updateTime;
private String updateUser;
private String operationUser;
private String operationRemarks;
private String operationTime;
private String imgUrl1;
private String imgUrl2;
private String imgUrl3;
private String shopNotice;
private String shopProfile;
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public String getShopLogo() {
return shopLogo;
}
public void setShopLogo(String shopLogo) {
this.shopLogo = shopLogo;
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getUserId() {
return userId;
}
public void setShopName(String shopName) {
this.shopName = shopName;
}
public String getShopName() {
return shopName;
}
public void setShopBannerImg(String shopBannerImg) {
this.shopBannerImg = shopBannerImg;
}
public String getShopBannerImg() {
return shopBannerImg;
}
public void setShopVideo(String shopVideo) {
this.shopVideo = shopVideo;
}
public String getShopVideo() {
return shopVideo;
}
public void setShopTemplate(String shopTemplate) {
this.shopTemplate = shopTemplate;
}
public String getShopTemplate() {
return shopTemplate;
}
public void setIsClose(String isClose) {
this.isClose = isClose;
}
public String getIsClose() {
return isClose;
}
public void setGoodsCount(String goodsCount) {
this.goodsCount = goodsCount;
}
public String getGoodsCount() {
return goodsCount;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getCompanyName() {
return companyName;
}
public void setShopType(int shopType) {
this.shopType = shopType;
}
public int getShopType() {
return shopType;
}
public void setCreateUser(String createUser) {
this.createUser = createUser;
}
public String getCreateUser() {
return createUser;
}
public void setUpdateTime(String updateTime) {
this.updateTime = updateTime;
}
public String getUpdateTime() {
return updateTime;
}
public void setUpdateUser(String updateUser) {
this.updateUser = updateUser;
}
public String getUpdateUser() {
return updateUser;
}
public void setOperationUser(String operationUser) {
this.operationUser = operationUser;
}
public String getOperationUser() {
return operationUser;
}
public void setOperationRemarks(String operationRemarks) {
this.operationRemarks = operationRemarks;
}
public String getOperationRemarks() {
return operationRemarks;
}
public void setOperationTime(String operationTime) {
this.operationTime = operationTime;
}
public String getOperationTime() {
return operationTime;
}
public void setImgUrl1(String imgUrl1) {
this.imgUrl1 = imgUrl1;
}
public String getImgUrl1() {
return imgUrl1;
}
public void setImgUrl2(String imgUrl2) {
this.imgUrl2 = imgUrl2;
}
public String getImgUrl2() {
return imgUrl2;
}
public void setImgUrl3(String imgUrl3) {
this.imgUrl3 = imgUrl3;
}
public String getImgUrl3() {
return imgUrl3;
}
public void setShopNotice(String shopNotice) {
this.shopNotice = shopNotice;
}
public String getShopNotice() {
return shopNotice;
}
public void setShopProfile(String shopProfile) {
this.shopProfile = shopProfile;
}
public String getShopProfile() {
return shopProfile;
}
}
public static class GoodsAttrList {
private int id;
private int goodsId;
private int attributeTypeId;
private int attributeId;
private String attributeValues;
private int sort;
private String attributeName;
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setGoodsId(int goodsId) {
this.goodsId = goodsId;
}
public int getGoodsId() {
return goodsId;
}
public void setAttributeTypeId(int attributeTypeId) {
this.attributeTypeId = attributeTypeId;
}
public int getAttributeTypeId() {
return attributeTypeId;
}
public void setAttributeId(int attributeId) {
this.attributeId = attributeId;
}
public int getAttributeId() {
return attributeId;
}
public void setAttributeValues(String attributeValues) {
this.attributeValues = attributeValues;
}
public String getAttributeValues() {
return attributeValues;
}
public void setSort(int sort) {
this.sort = sort;
}
public int getSort() {
return sort;
}
public void setAttributeName(String attributeName) {
this.attributeName = attributeName;
}
public String getAttributeName() {
return attributeName;
}
}
public class GoodsSpecList {
boolean selected = false;
boolean enable = true;
private int id;
private int goodsId;
private String specGoodsCode;
private String specValues;
private int specGoodsStock;
private String specSellingPrice;
private String specType;
private String userId;
private String createTime;
private String updateTime;
private String isDel;
private String isOnSale;
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public boolean isEnable() {
return enable;
}
public void setEnable(boolean enable) {
this.enable = enable;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public void setGoodsId(int goodsId) {
this.goodsId = goodsId;
}
public int getGoodsId() {
return goodsId;
}
public void setSpecGoodsCode(String specGoodsCode) {
this.specGoodsCode = specGoodsCode;
}
public String getSpecGoodsCode() {
return specGoodsCode;
}
public void setSpecValues(String specValues) {
this.specValues = specValues;
}
public String getSpecValues() {
return specValues;
}
public void setSpecGoodsStock(int specGoodsStock) {
this.specGoodsStock = specGoodsStock;
}
public int getSpecGoodsStock() {
return specGoodsStock;
}
public void setSpecSellingPrice(String specSellingPrice) {
this.specSellingPrice = specSellingPrice;
}
public String getSpecSellingPrice() {
return specSellingPrice;
}
public void setSpecType(String specType) {
this.specType = specType;
}
public String getSpecType() {
return specType;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserId() {
return userId;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public String getUpdateTime() {
return updateTime;
}
public void setUpdateTime(String updateTime) {
this.updateTime = updateTime;
}
public void setIsDel(String isDel) {
this.isDel = isDel;
}
public String getIsDel() {
return isDel;
}
public void setIsOnSale(String isOnSale) {
this.isOnSale = isOnSale;
}
public String getIsOnSale() {
return isOnSale;
}
}
}
|
package analytics.analysis.algorithms.apriori;
public class AprioriAlgorithm {
private static Associations associations;
static {
associations = new Associations();
associations.buildData();
}
private AprioriAlgorithm() {}
public static Associations getInstance() {
return associations;
}
}
|
package com.proky.booking.persistence.entities;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.math.BigDecimal;
import java.util.Objects;
@Entity
@Table(name = "train_type", schema = "railway_ticket_booking_spring")
@Data
@NoArgsConstructor
public class TrainType {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "type")
private String type;
@Column(name = "seat_price")
private BigDecimal seatPrice;
}
|
package me.walkerknapp.cfi.structs;
import com.dslplatform.json.CompiledJson;
import com.dslplatform.json.JsonAttribute;
import java.util.List;
@CompiledJson
public class Toolchains implements CFIObject {
@JsonAttribute(mandatory = true)
public List<Toolchain> toolchains;
@CompiledJson
public static class Toolchain {
@JsonAttribute(mandatory = true)
public String language;
@JsonAttribute(mandatory = true)
public Compiler compiler;
@CompiledJson
public static class Compiler {
@JsonAttribute
public String path;
@JsonAttribute
public String id;
@JsonAttribute
public String version;
@JsonAttribute
public String target;
@JsonAttribute
public Implicit implicit;
@CompiledJson
public static class Implicit {
@JsonAttribute
public List<String> includeDirectories;
@JsonAttribute
public List<String> linkDirectories;
@JsonAttribute
public List<String> linkFrameworkDirectories;
@JsonAttribute
public List<String> linkLibraries;
}
}
@JsonAttribute
public List<String> sourceFileExtensions;
}
}
|
package com.sheygam.loginarchitectureexample.data.repositories.contactList.prefstore;
/**
* Created by Gleb on 16.02.2018.
*/
public interface IContactsListStoreRepository {
String getAuthToken();
void clearAuthToken();
}
|
/*
* 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.bionic.bibonline.validators;
import com.bionic.bibonline.entitiesbeans.users.UsersFacadeLocal;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
/**
*
* @author G_Art
*/
@FacesValidator("custom.freeLoginValidator")
public class FreeLoginValidator implements Validator {
@EJB
private UsersFacadeLocal userEJB;
@Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
if (!value.toString().equals("")) {
if (userEJB.checkLogin(value.toString())) {
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Validation Error: This login alredy taken, please try another one",
value + ": This login alredy taken, please try another one"));
}
}
}
}
|
package structural.flyweight.bookcode.forest;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import structural.flyweight.bookcode.tree.Tree;
import structural.flyweight.bookcode.tree.TreeFactory;
import structural.flyweight.bookcode.tree.TreeType;
import java.awt.*;
// 应用类
// context 对象容器
public class Forest extends JFrame {
private List<Tree> trees = new ArrayList<>();
public void plantTree(int x, int y, String name, Color color, String otherData) {
// 工厂方法查缓存池获取缓存对象
TreeType type = TreeFactory.getTreeType(name, color, otherData);
// 用缓存对象初始化(配置) context 对象
Tree tree = new Tree(x, y, type);
trees.add(tree);
}
@Override
public void paint(Graphics g) {
// 由 context 对象处理
for (Tree tree : trees)
tree.draw(g);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.