text
stringlengths 10
2.72M
|
|---|
package exercises.chapter6.ex2;
import exercises.chapter6.ex2.nested.Integer;
//import java.lang.Integer;
/**
* @author Volodymyr Portianko
* @date.created 14.03.2016
*/
public class Exercise2 {
public static void main(String[] args) {
new Integer();
}
}
|
package com.jpeng.demo.adapter;
import android.content.Context;
import android.provider.ContactsContract;
import android.support.v7.widget.CardView;
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.RelativeLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.jpeng.demo.MainActivity;
import com.jpeng.demo.R;
import com.jpeng.demo.delete.LearnDelete;
import com.jpeng.demo.notes.Learn;
import java.util.List;
/**
* Created by ็ๅฐ on 2018/6/8.
*/
public class LearnAdapter extends RecyclerView.Adapter<LearnAdapter.ViewHolder> {
private List<Learn> learns;
private Context mContext;
public LearnAdapter(List<Learn> learnList){
learns=learnList;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (mContext==null){
mContext=parent.getContext();
}
View view= LayoutInflater.from(mContext).inflate(R.layout.iteam_learn_layout,parent,false);
ViewHolder holder=new ViewHolder(view);
holder.relativeLayout.setOnLongClickListener(MainActivity.onLongClickListener);
holder.relativeLayout.setOnClickListener(MainActivity.onClickListener);
holder.star.setOnClickListener(MainActivity.onClickListener);
return holder;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
Learn learn=learns.get(position);
String [] contents=learn.getContentLearn().split("&");
String [] prices=learn.getPricesLearn().split(";");
Glide.with(mContext).load(prices[0]).error(R.drawable.learn_backgound).centerCrop().into(holder.backGround);
holder.time.setText(learn.getCreateTime());
holder.content.setText(contents[0]);
holder.label.setText(learn.getLabelLearn());
if (learn.isCollection()){
holder.star.setImageResource(R.drawable.yes_star);
}else {
holder.star.setImageResource(R.drawable.no_star);
}
LearnDelete learnDelete=new LearnDelete();
learnDelete.setPosition(position);
learnDelete.setLearn(learn);
holder.star.setTag(learn);
holder.relativeLayout.setTag(learnDelete);
}
@Override
public int getItemCount() {
return learns.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
CardView cardView;
TextView time,content,label;
ImageView backGround,star;
RelativeLayout relativeLayout;
public ViewHolder(View itemView) {
super(itemView);
cardView=(CardView) itemView;
relativeLayout=(RelativeLayout) itemView.findViewById(R.id.item_rela_learn);
time=(TextView) itemView.findViewById(R.id.time_learn);
content=(TextView) itemView.findViewById(R.id.content_learn);
label=(TextView) itemView.findViewById(R.id.label_learn);
backGround=(ImageView) itemView.findViewById(R.id.image_learn);
star=(ImageView) itemView.findViewById(R.id.star_learn);
}
}
}
|
package com.itheima.day_06.demo_01;
import java.util.Comparator;
import java.util.TreeSet;
public class TreeSetDemo {
public static void main(String[] args) {
TreeSet<Student> set = new TreeSet<>(new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
int ageDiff = s1.getAge() - s2.getAge();
int nameDiff = ageDiff == 0 ? s1.getName().compareTo(s2.getName()) : ageDiff;
return nameDiff;
}
});
set.add(new Student("ๅผ ไธ", 20));
set.add(new Student("ๆๅ", 20));
set.add(new Student("็ไบ", 19));
set.add(new Student("่ตตๅ
ญ", 21));
for (Student student : set) {
System.out.println(student);
}
}
}
|
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class BruteCollinearPoints {
private List<LineSegment> lines;
public BruteCollinearPoints(Point[] points) {
check(points);
Point[] ps = Arrays.copyOf(points, points.length);
this.lines = new ArrayList<>();
Arrays.sort(ps, Point::compareTo);
int len = ps.length;
for (int i = 0; i < len - 3; i++) {
for (int j = i + 1; j < len - 2; j++) {
for (int k = j + 1; k < len - 1; k++) {
for (int l = k + 1; l < len; l++) {
if (ps[i].slopeTo(ps[j]) == ps[j].slopeTo(ps[k])
&& ps[j].slopeTo(ps[k]) == ps[k].slopeTo(ps[l])) {
lines.add(new LineSegment(ps[i], ps[l]));
}
}
}
}
}
}
public int numberOfSegments() {
return lines.size();
}
public LineSegment[] segments() {
return lines.toArray(new LineSegment[0]);
}
// could use set to check in O(n) time, but use O(n) extra space
// Since set has not mentioned in the course yet, not use it in this assignment
private void check(Point[] points) {
if (points == null) throw new IllegalArgumentException();
for(Point p : points) if (p == null) throw new IllegalArgumentException();
for (int i = 0; i < points.length; i++) {
for (int j = i + 1; j < points.length; j++) {
if (points[i].compareTo(points[j]) == 0) throw new IllegalArgumentException();
}
}
}
}
|
package egovframework.com.job.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import egovframework.adm.cfg.mem.service.MemberSearchService;
import egovframework.com.snd.controller.SendSmsMailManageController;
import egovframework.com.snd.service.SendSmsMailManageService;
public class SchedulerTask
{
/** sendMailManageService */
@Resource(name = "sendSmsMailManageService")
SendSmsMailManageService sendSmsMailManageService;
/** memberSearchService */
@Resource(name = "memberSearchService")
MemberSearchService memberSearchService;
public void printMessage() {
//System.out.println("Struts + Spring + Quartz integration example ~");
/*
*
* ํํด ํ์์ด ์๋๋ฉด์ 1๋
์ด์ ๋ก๊ทธ์ธ ํ์ง ์์ ํ์ ์กฐํ
1๋
์ด ์ง๋ ์ฌ๋ ๋ฉ์ผ ๋ฐ์ก
1๋
3๊ฐ์ ์ง๋ ๊ณ์ ํด๋ฉด ์ฒ๋ฆฌ
2๋
3๊ฐ์ ์ง๋ ๊ณ์ฉก ์ญ์ ์ฒ๋ฆฌ
*/
Map<String, Object> commandMap = new HashMap();
commandMap.put("p_title", "[๊ตญ๋ฆฝํน์๊ต์ก์๋ถ์ค์๊ฒฉ๊ต์ก์ฐ์์] [$name$] ์ ์๋. ๊ตญ๋ฆฝํน์๊ต์ก์ ์๊ฒฉ๊ต์ก์ฐ์์์
๋๋ค.์ ์๋ ID๊ฐ ํด๋ฉด์ํ๋ก ์ ํ ๋ ์์ ์
๋๋ค. ");
String str="";
str +="<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">";
str +="<html xmlns=\"http://www.w3.org/1999/xhtml\">";
str +=" <head> ";
str +="<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">";
str +="<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">";
str +="<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0\">";
str +="<title>ํด๋ฉด๊ณ์ ์๋ด ๋ฉ์ผ</title>";
str +="</head>";
str +=" <body width=\"700\" height=\"990\" style=\"margin:0; padding:0;\">";
str +=" <table width=\"700\" height=\"990\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:'dotum'; border:1px solid #315192; background:url(http://iedu.nise.go.kr/images/mail/mail_bg.jpg) bottom no-repeat;\">";
str +=" <tr>";
str +=" <td width=\"700\" height=\"472\" colspan=\"3\" style=\"background-color:#315192;\">";
str +=" <img width=\"700\" height=\"472\" src=\"http://iedu.nise.go.kr/images/mail/mail_top.jpg\" alt=\"ํด๋ฉด๊ณ์ ์๋ด ๋ฉ์ผ, ๊ตญ๋ฆฝํน์๊ต์ก์ ๋ถ์ค์๊ฒฉ๊ต์ก์ฐ์์ CI, ๊ตญ๋ฆฝํน์๊ต์ก์๋ถ์ค์๊ฒฉ๊ต์ก์ฐ์์์ ์ ์๋ ID๊ฐ ํด๋ฉด์ํ๋ก ์ ํ ๋ ์์ ์
๋๋ค. ์๋
ํ์ธ์. ๊ตญ๋ฆฝํน์๊ต์ก์๋ถ์ค์๊ฒฉ๊ต์ก์ฐ์์์
๋๋ค. ์ ๋ณดํต์ ๋ง ์ด์ฉ์ด์ง ๋ฐ ์ ๋ณด๋ณดํธ ๋ฑ์ ๊ดํ ๋ฒ๋ฅ ์ 29์กฐ 2ํญ ๋๋ฒ ์ํ๋ น ์ 16์กฐ์ ์๊ฑฐํ์ฌ ์๊ฒฉ๊ต์ก์ฐ์์ ์๋น์ค(์น ๋๋ ์ฑ)์ ์ด์ฉ ๋ด์์ด 1๋
์ด์ ์๋ ํ์ ๊ณ์ ์ ํด๋ฉด์ํ๋ก ์ ํ๋์ด ๊ฐ์ธ์ ๋ณด๋ฅผ ๋ณ๋ ๋ณด๊ด์ฒ๋ฆฌํจ์ ์๋ ค๋๋ฆฝ๋๋ค. ์ด๋ฅผ ์์น ์์ผ์ค ๊ฒฝ์ฐ ๊ตญ๋ฆฝํน์๊ต์ก์๋ถ์ค์๊ฒฉ๊ต์ก์ฐ์์ ํํ์ด์ง(http://iedu.nise.go.kr)์ ์ ์ํ์ฌ ๋ก๊ทธ์ธํด์ฃผ์๊ธฐ ๋ฐ๋๋๋ค. โป 3๊ฐ์ ๋์ ๋ก๊ทธ์ธ ํ์ง ์์์, ํด๋ฉด๊ณ์ ์ผ๋ก ์ ํ๋ฉ๋๋ค. ํด๋ฉด๊ณ์ ์ผ๋ก ์ ํ ์ ๋ณธ์ธํ์ธ ์ ์ฐจ๊ฐ ํ์ํฉ๋๋ค.\" border=\"0\" usemap=\"#Map2\" />";
str +=" <map name=\"Map2\" id=\"Map2\">";
str +=" <area shape=\"rect\" coords=\"146,377,310,397\" href=\"http://iedu.nise.go.kr\" target=\"_blank\" alt=\"๊ตญ๋ฆฝํน์๊ต์ก์๋ถ์ค์๊ฒฉ๊ต์ก์ฐ์์ ํํ์ด์ง\" />";
str +=" </map>";
str +=" </td>";
str +=" </tr>";
str +=" <tr>";
str +=" <td width=\"48\" height=\"129\" style=\"background-color:#315192; padding:0; margin:0;\"></td>";
str +=" <td width=\"604\" height=\"89\" style=\"background-color:#315192; letter-spacing:-0.05em;\">";
str +=" <table width=\"604\" height=\"89\" style=\"font-family:'dotum'; font-weight:700;\">";
str +=" <tr height=\"35\">";
str +=" <td height=\"35\" style=\"color:#c9d9fb; font-size:20px; vertical-align:bottom;\">ํด๋ฉด ์ ํ(๋ถ๋ฆฌ ๋ณด๊ด) ๋์ ๊ณ์ : [$userid$]</td>";
str +=" </tr>";
str +=" <tr height=\"42\">";
str +=" <td height=\"42\" style=\"color:#fff; font-size:16px;\">";
str +=" <ul height=\"42\" style=\"list-style-type:disc;\">";
str +=" <li height=\"21\">ํด๋ฉด์ ํ์ผ : [$rdate$]</li>";
str +=" <li height=\"21\">๋ถ๋ฆฌ๋ณด๊ด ๊ฐ์ธ์ ๋ณด : ํด๋น ๊ณ์ ์ฐ์์ด๋ ฅ</li>";
str +=" </ul>";
str +=" </td>";
str +=" </tr>";
str +=" </table>";
str +=" </td>";
str +=" <td width=\"48\" height=\"129\" style=\"background-color:#315192; padding:0; margin:0;\"></td>";
str +=" </tr>";
str +=" <tr>";
str +=" <td width=\"700\" height=\"256\" colspan=\"3\">";
str +=" <img width=\"700\" height=\"256\" src=\"http://iedu.nise.go.kr/images/mail/mail_bottom.jpg\" alt=\"๋ถ๋ฆฌ๋ณด๊ด ํ ์ด์ฉ ๋ถ๊ฐ ์๋น์ค ์๋ด ๋ถ๋ฆฌ๋ณด๊ด๊ณผ ๋์์ ํํ์ด์ง ํ์ ์ ์ฉ ์๋น์ค ๋ฉ๋ด๋ฅผ ์ด์ฉํ์ค ์ ์์ต๋๋ค. 1. ์๊ฒฉ์ฐ์ ์๊ฐ์ ์ฒญ 2. ์ฑ์ ํ์ธ ๋ฐ ์ฐ์๋ด์ญํ์ธ 3. ์๊ฐ์ ์๋น์ค(์ด์์ฆยท์์์ฆ ์ถ๋ ฅ ๋ฑ) 4. ์์ด๋, ๋น๋ฐ๋ฒํธ ์ฐพ๊ธฐ - ๋ณ๋ ๋ณด๊ด ์ฒ๋ฆฌ๋ฅผ ์ํ์ง ์์ผ์ค ๊ฒฝ์ฐ ํด๋ฉด ์ ํ ์์ ์ผ ์ด์ ๊น์ง ๊ตญ๋ฆฝํน์๊ต์ก์๋ถ์ค์๊ฒฉ๊ต์ก์ฐ์์ ํํ์ด์ง(http://iedu.nise.go.kr)์ 1ํ ์ด์ ๋ก๊ทธ์ธ ํ์๋ฉด ๊ฐ์ธ์ ๋ณด ๋ณ๋ ๋ณด๊ด์ฒ๋ฆฌ ๋์์์ ์ ์ธ๋ฉ๋๋ค. - ํด๋ฉด ์์ด๋๋ ์ ํ๋ ์ผ์๋ก๋ถํฐ ๋ก๊ทธ์ธ ํ ๋ณธ์ธ์ธ์ฆ์ ํตํด ๋ฐ๋ก ์ฌ์ฌ์ฉ ๊ฐ๋ฅํฉ๋๋ค.\" />";
str +=" </td>";
str +=" </tr>";
str +=" <tr>";
str +=" <td width=\"700\" height=\"54\" colspan=\"3\">";
str +=" <img width=\"700\" height=\"54\" src=\"http://iedu.nise.go.kr/images/mail/mail_footer.jpg\" alt=\"๋ณธ ์ด๋ฉ์ผ์ ํด๋ฉด๊ณ ์ ํ ๋์์ธ ํ์๋๊ป๋ง ๋ฐ์ก๋๋ ๋ฐ์ ์ ์ฉ ๋ฉ์ผ์
๋๋ค. ๋ฌธ์์ฌํญ์ ์ฐ์๊ด๋ จ ๋ฌธ์ ๊ฒ์ํ์ ์ด์ฉํด ์ฃผ์๊ธฐ ๋ฐ๋๋๋ค.\" border=\"0\" usemap=\"#Map\" />";
str +=" <map name=\"Map\" id=\"Map\">";
str +=" <area shape=\"rect\" coords=\"261,28,369,43\" href=\"http://iedu.nise.go.kr\" target=\"_blank\" alt=\"์ฐ์์๊ด๋ จ ๋ฌธ์ ๊ฒ์ํ\" />";
str +=" </map>";
str +=" </td>";
str +=" </tr>";
str +=" <tr>";
str +=" <td width=\"700\" height=\"79\" colspan=\"3\">";
str +=" <img width=\"700\" height=\"79\" src=\"http://iedu.nise.go.kr/images/mail/mail_address.jpg\" alt=\"๊ตญ๋ฆฝํน์๊ต์ก์ ๋ถ์ค์๊ฒฉ๊ต์ก์ฐ์ฃผ์ ์ฃผ์ : ์ถฉ๋จ ์์ฐ์ ๋ฐฐ๋ฐฉ์ ๊ณต์๋ก 40 Tel : 041 537 1475 Fax : 041 537 1473 ๊ณ ์ ๋ฒํธ : 134-83-01004 (๊ตญ๋ฆฝํน์๊ต์ก์ ๋ถ์ค ์๊ฒฉ๊ต์ก์ฐ์์) ๋ํ์ : ์ฐ์ด๊ตฌ COPYRIGHT(C)2010 ๊ตญ๋ฆฝํน์๊ต์ก์ All rights reserved\" border=\"0\" />";
str +=" </td>";
str +=" </tr>";
str +=" </table>";
str +=" </body>";
str +=" </html>";
commandMap.put("p_content", str);
commandMap.put("pGubun", "dormant");
int DormantCnt = 0;
try {
//ํํด ํ์์ด ์๋๋ฉด์ 1๋
์ด์ ๋ก๊ทธ์ธ ํ์ง ์์ ํ์ ์กฐํ 1๋
์ด ์ง๋ ์ฌ๋ ๋ฉ์ผ ๋ฐ์ก
DormantCnt = memberSearchService.selectDormantCnt(commandMap);
if(DormantCnt > 0 )
{
// Dormant N(1๋
์๋๋ฉด) -> Y(1๋
๋๊ณ ๋ฉ์ผ ๋ฐ์ก) -> E(1๋
3๊ฐ์)
// ๋ฉ์ผ ๋ฐ์ก
sendSmsMailManageService.insertCloseUserSendMail(commandMap);
// ๋ฉ์ผ ๋ฐ์ก ๋์ ๋ฉ์ผ ๋ฐ์ก send
memberSearchService.updateDormantYn(commandMap);
}
// 1๋
3๊ฐ์ ๋ ํด๋ฉด ๊ณ์ ์ ํ์ผ๋ก E๋ก update
// Y N ์ผ๋๋ ์
๋ฌด ์ด์ฉ๊ฐ๋ฅ
// Y ์ด๋ฉด์ ๋ฉ์ผ ๋ฐ์กํ์ง 3๊ฐ์ ๋ ๊ฒฝ์ฐ last login์ด ๋ฐ๋์ ์์
memberSearchService.updateDormantYnE(commandMap);
// ํด๋ฉด ๊ณ์ ์ด ๋์ง 1๋
๋ ๊ฒฝ์ฐ ํํด ๊ธฐ๋ฅ ํ์ฌ ISRETIRE ๋ง ์
๋ฐ์ดํธ ์ณ ์ค๋ค.
//memberSearchService.updateUserDelYn(commandMap);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package com.shadow.testLog4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created by qq65827 on 2015/1/3.
*/
public class test {
protected static final Logger logger = LoggerFactory.getLogger(test.class);
public static void main(String[] args) {
logger.info("shadow");
}
}
|
/* NodeInfo.java
Purpose:
Description:
History:
Mon Mar 26 17:33:45 2007, Created by tomyeh
Copyright (C) 2007 Potix Corporation. All Rights Reserved.
{{IS_RIGHT
This program is distributed under LGPL Version 2.1 in the hope that
it will be useful, but WITHOUT ANY WARRANTY.
}}IS_RIGHT
*/
package org.zkoss.zk.ui.metainfo;
import java.util.List;
import java.util.LinkedList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import org.zkoss.zk.xel.impl.EvaluatorRef;
/**
* Represents a node of the ZUML tree.
* It is an abstract class while the concrete classes include
* {@link PageDefinition} and {@link ComponentInfo}.
* The root must be an instance of {@link PageDefinition}
* and the other nodes must be instances of {@link ComponentInfo},
* {@link ZScript}, or {@link AttributesInfo}.
*
* <p>Note:it is not thread-safe.
*
* @author tomyeh
*/
abstract public class NodeInfo {
/** A list of {@link ComponentInfo} and {@link ZScript}. */
/*pacakge*/ List _children = new LinkedList();
public NodeInfo() {
}
/** Returns the page definition, or null if not available.
*/
abstract public PageDefinition getPageDefinition();
/** Returns the parent, or null if no parent.
*/
abstract public NodeInfo getParent();
/** Returns the evaluator reference (never null).
*
* <p>This method is used only for implementation only.
* @since 3.0.0
*/
abstract protected EvaluatorRef getEvaluatorRef();
/** Adds a zscript child.
*/
public void appendChild(ZScript zscript) {
appendChildDirectly(zscript);
}
/** Adds a variables child.
*/
public void appendChild(VariablesInfo variables) {
appendChildDirectly(variables);
}
/** Adds a custom-attributes child.
*/
public void appendChild(AttributesInfo custAttrs) {
appendChildDirectly(custAttrs);
}
/** Adds a {@link ComponentInfo} child.
* @since 2.4.0
*/
public void appendChild(ComponentInfo compInfo) {
compInfo.setParent(this); //it will call back appendChildDirectly
}
/** Removes a zscript child.
* @return whether the child is removed successfully.
*/
public boolean removeChild(ZScript zscript) {
return removeChildDirectly(zscript);
}
/** Removes a variables child.
* @return whether the child is removed successfully.
*/
public boolean removeChild(VariablesInfo variables) {
return removeChildDirectly(variables);
}
/** Removes a custom-attributes child.
* @return whether the child is removed successfully.
*/
public boolean removeChild(AttributesInfo custAttrs) {
return removeChildDirectly(custAttrs);
}
/** Removes a {@link ComponentInfo} child.
*
* <p>Call {@link ComponentInfo#setParent} instead.
* @return whether the child is removed successfully.
* @since 2.4.0
*/
public boolean removeChild(ComponentInfo compInfo) {
if (compInfo != null && removeChildDirectly(compInfo)) {
compInfo.setParentDirectly(null);
return true;
}
return false;
}
/** Adds a child.
* <p>Note: it does NOT maintain {@link ComponentInfo#getParent}.
*/
/*pacakge*/ void appendChildDirectly(Object child) {
if (child == null)
throw new IllegalArgumentException("child required");
_children.add(child);
}
/** Removes a child.
* <p>Note: it does NOT maintain {@link ComponentInfo#getParent}.
*/
/*package*/ boolean removeChildDirectly(Object child) {
return _children.remove(child);
}
/** Returns a list of children.
* Children include instances of {@link ComponentInfo}, {@link ZScript}
* {@link VariablesInfo}, or {@link AttributesInfo}.
*
* <p>Note: the returned list is live but it is not a good idea
* to modify it directly,
* because, unlike {@link org.zkoss.zk.ui.Component}, it doesn't maintain
* {@link NodeInfo#getParent}. Thus, it is better to invoke
* {@link #appendChild(ComponentInfo)} and {@link #removeChild(ComponentInfo)}
* instead.
*/
public List getChildren() {
return _children;
}
}
|
package at.ac.fhcampuswien.bouncingballs.controllers;
import at.ac.fhcampuswien.bouncingballs.balls.InfectableBalls;
import at.ac.fhcampuswien.bouncingballs.params.InfectableBallsParams;
import at.ac.fhcampuswien.bouncingballs.params.SimulationValues;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import java.io.IOException;
import java.util.ResourceBundle;
public class Homepage {
@FXML private Text actionTarget;
@FXML
private TextField pText;
@FXML
private TextField iText;
@FXML
private TextField bText;
private ResourceBundle resources;
@FXML protected void manageButton(ActionEvent event) {
try {
FXMLLoader loader = new FXMLLoader(getClass().getClassLoader().getResource("main.fxml")); //Start the simulation by pressing the button
String pTextNoSpace = pText.getText().replaceAll(" +","");
String iTextNoSpace = iText.getText().replaceAll(" +","");
String bTextNoSpace =bText.getText().replaceAll(" +","");
int population;
int initialInfections;
int ballRadius;
try{
population = Integer.parseInt(pTextNoSpace);
initialInfections = Integer.parseInt(iTextNoSpace);
ballRadius = Integer.parseInt(bTextNoSpace);
}
catch(NumberFormatException e){
Alert errorAlert = new Alert(Alert.AlertType.ERROR);
errorAlert.setHeaderText("Input not valid");
errorAlert.setContentText("Please enter numbers!");
errorAlert.showAndWait();
return;
}
SimulationValues.setBallCount(population);
SimulationValues.setInitalInfections(initialInfections);
InfectableBallsParams.setBallradius(ballRadius);
if (population > 5000) { //check Population
Alert errorAlert = new Alert(Alert.AlertType.ERROR);
errorAlert.setHeaderText("Input not valid");
errorAlert.setContentText("The Population size must be between 1 and 5000!");
errorAlert.showAndWait();
;
}else if(ballRadius <= 0 || population <= 0 || initialInfections <= 0){ //check if positive number
Alert errorAlert = new Alert(Alert.AlertType.ERROR);
errorAlert.setHeaderText("Input not valid");
errorAlert.setContentText("Please enter values greater than 0!");
errorAlert.showAndWait();
}
else if(ballRadius > 20 ){ //check radius
Alert errorAlert = new Alert(Alert.AlertType.ERROR);
errorAlert.setHeaderText("Input not valid");
errorAlert.setContentText("Ballradius must not be greater than 20!");
errorAlert.showAndWait();
}
else if(initialInfections > population ){
Alert errorAlert = new Alert(Alert.AlertType.ERROR);
errorAlert.setHeaderText("Input not valid");
errorAlert.setContentText("Population has to be greater than Infectiousness!");
errorAlert.showAndWait();
} else if(!InfectableBalls.checkIfBallsFitInCanvas(population,initialInfections)){
Alert errorAlert = new Alert(Alert.AlertType.ERROR);
errorAlert.setHeaderText("The Balls dont fit");
errorAlert.setContentText("The Balls do not fit on the Canvas! Please reduce the Population-Count or the Ballradius");
errorAlert.showAndWait();
}
else {
MainController controller = new MainController(); //start the simulation
loader.setController(controller);
Parent root = loader.load();
Stage stage = new Stage();
stage.setResizable(false);
stage.setTitle("Bouncing-Balls");
stage.setScene(new Scene(root, 1280, 720));
stage.show();
((Node) (event.getSource())).getScene().getWindow().hide();
//stage.setOnHidden(e-> controller.shutdown());
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
|
package Arrays;
import java.util.Scanner;
public class ArrayOperation {
private ArrayOperation(){
}
private static ArrayOperation ao;
static{
ao = new ArrayOperation();
}
public final static ArrayOperation getInstance(){
return ao;
}
int[] readElement()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of elements");
int n = in.nextInt();
int[] a = new int[n];
System.out.println("Enter the "+n+" elements");
for(int i=0; i<n; i++){
a[i] = in.nextInt();
}
in.close();
return a;
}
void dispArr(int[] a)
{
for(int i=0; i<a.length; i++){
System.out.print(a[i]+" ");
}
System.out.println();
}
int sumOfArr(int[] a){
int sum=0;
for(int i=0; i<a.length; i++){
sum = sum+a[i];
}
return sum;
}
int[] countEO(int[] a){
int c[]={0,0};
for(int i=0; i<a.length; i++){
/*if(a[i]%2==0)
c[0]++;
else
c[1]++;*/
c[a[i]%2]++;
}
return c;
}
int[] countPN(int[] a){
int[] c={0,0};
for(int i=0; i<a.length; i++){
if(a[i]>0)
c[0]++;
else
c[1]++;
}
return c;
}
int smallest(int[] a){
int smallest = a[0];
for(int i=0; i<a.length; i++){
if(smallest>a[i])
smallest=a[i];
}
return smallest;
}
static boolean isPrime(int n){
for(int i=2;i<=n/2;i++){
if(n%i==0)
return false;
}
return true;
}
int noOfPrimeNo(int[] a){
int count = 0;
for(int i=0; i<a.length; i++){
if(isPrime(a[i])==true)
count++;
}
return count;
}
static boolean isPalin(int n){
int rev=0, temp=n;
while(n!=0){
rev=rev*10+n%10;
n=n/10;
}
return rev==temp;
}
int noOfPalin(int[] a){
int count=0;
for(int i=0; i<a.length; i++){
if(isPalin(a[i])==true)
count++;
}
return count;
}
int[] sumOfEO(int[] a){
int c[]={0,0};
for(int i=0; i<a.length; i++){
/*if(a[i]%2==0)
c[0]=c[0]+a[i];
else
c[1]=c[1]+a[i];*/
c[a[i]%2] = c[a[i]%2]+a[i];
}
return c;
}
int[] merge(int[] a, int[] b){
int[] c = new int[a.length+b.length];
for(int i=0; i<a.length; i++){
c[i] = a[i];
}
for(int i=0; i<b.length; i++){
c[a.length+i] = b[i];
}
return c;
}
int[] insertAt(int[] a, int ele, int i){
if(i<0 || i>a.length){
System.out.println("Enter the valid index");
return a;
}
int[] b = new int[a.length+1];
b[i] = ele;
for(int j=0; j<a.length; j++){
if(j<i)
b[j] = a[j];
else
b[j+1] = a[j];
}
return b;
}
int[] deleteAt(int[] a, int i){
if(i<0 || i>=a.length){
System.out.println("Enter the valid index");
return a;
}
int[] b = new int[a.length-1];
for(int j=0; j<b.length; j++){
if(j<i)
b[j] = a[j];
else
b[j] = a[j+1];
}
return b;
}
int[] reverseArr(int[] a){
int n = a.length;
int n1 = a.length/2;
for(int i=0 ; i<n1; i++){
int temp = a[i];
a[i] = a[n-i-1];
a[n-i-1] = temp;
}
return a;
}
int[] merge2SotredArr(int[] a ,int[] b){
int[] c = new int[a.length+b.length];
int i=0, j=0, k=0;
while(i<a.length && j<b.length){
if(a[i] < b[j])
c[k++] = a[i++];
else
c[k++] = b[j++];
}
while(i<a.length){
c[k++] = a[i++];
}
while(j<b.length){
c[k++] = b[j++];
}
return c;
}
int[] mergeInZigZagOrd(int[] a, int[] b){
int[] c = new int[a.length+b.length];
int i=0,k=0;
while(i<a.length && i<b.length){
c[k++]=a[i];
c[k++]=b[i++];
}
while(i<a.length){
c[k++] = a[i++];
}
while(i<b.length){
c[k++] = b[i++];
}
return c;
}
int nthBiggest(int[] a,int n){
for(int i = 0; i<a.length; i++){
int count = 0;
for(int j=0; j<a.length; j++){
if(a[i] < a[j])
count++;
}
if(count==n-1)
return a[i];
}
return 0;
}
int nthSmallestt(int[] a,int n){
for(int i = 0; i<a.length; i++){
int count = 0;
for(int j=0; j<a.length; j++){
if(a[i] > a[j])
count++;
}
if(count==n-1)
return a[i];
}
return 0;
}
int[] highestGap(int[] a){
int gap=0;
int k = 0;
int[] gapbw= new int[2];
for(int i=0; i<a.length; i++){
int j=i+1;
if(j<a.length){
int g = a[i]-a[j];
if(g<0){
g = -1*g;
}
if(g>gap){
gap = g;
k = i;
}
}
}
gapbw[0] =a[k];
gapbw[1] = a[k+1];
return gapbw;
}
void highestGap1(int[] a){
int a1=a[0];
int b1=a[1];
int gap = a1 - b1;
if(gap<0){
gap= gap*-1;
}
for (int i = 1; i < a.length-1; i++) {
int g = a[i]-a[i+1];
if(g<0)
g=g*-1;
if(g>gap){
gap=g;
a1=a[i];
b1=a[i+1];
}
}
System.out.println(a1+" "+b1);
}
int[] highestSum(int[] a){
int sum=0;
int k = 0;
int[] gapbw= new int[2];
for(int i=0; i<a.length; i++){
int j=i+1;
if(j<a.length){
int s = a[i]+a[j];
if(s>sum){
sum = s;
k = i;
}
}
}
gapbw[0] =a[k];
gapbw[1] = a[k+1];
return gapbw;
}
int highestSum1(int[] a){
int sum = a[0]+a[1];
for(int i=1; i<a.length-1; i++){
if(a[i]+a[i+1] > sum)
sum = Math.abs(a[i]+a[i+1]);
}
return sum;
}
void frequency(int[] a){
// int[] counts = new int[a.length];
// int visited = -1;
int n = a.length;
for(int i=0; i<n; i++){
int count = 1;
for(int j=i+1; j<n; j++){
if(a[i]==a[j]){
count++;
a[j] = a[n-1];
j--;
n--;
}
}
// if(counts[i]!=visited)
// counts[i] = count;
System.out.println(a[i]+"---->"+count);
}
// for(int i=0; i<counts.length; i++){
// if(counts[i]!=visited){
// System.out.println(a[i]+" element occurs "+counts[i]+" times");
// }
// }
}
int[] unique(int[] a){
int[] unique = new int[a.length];
int k = 0;
for(int i = 0; i < a.length; i++){
boolean uq = true;
for(int j = 0 ; j < a.length; j++){
if(a[i]==a[j]&& i!=j){
uq = false;
break;
}
}
if(uq)
unique[k++]=a[i];
}
int[] unq = new int[k];
for (int i = 0; i < unq.length; i++) {
unq[i] = unique[i];
}
return unq;
}
int[] commomEle(int[] a, int[] b){
int[] common = new int[a.length];
int k=0;
for(int i=0;i<a.length; i++){
for(int j=0; j<b.length; j++){
if(a[i]==b[j]){
common[k++] = a[i];
break;
}
}
}
int[] com = new int[k];
for(int i=0; i<com.length; i++){
com[i]=common[i];
}
return com;
}
int[] removeDuplicate(int[] a){
int[] u = new int[a.length];
u[0] = a[0];
int k=1;
for (int i = 1; i < a.length; i++) {
int j = i-1;
while(j>=0 && a[i]!=a[j]){
j--;
}
if(j==-1){
u[k++] = a[i];
}
}
int[] noDup = new int[k];
for (int i = 0; i < noDup.length; i++) {
noDup[i] = u[i];
}
return noDup;
}
}
|
package com.pwq.mavenT;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* Created by BF100500 on 2017/3/21.
*/
public class TestThreadFactory {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getThreadGroup().getParent().getName());
ExecutorService es = Executors.newCachedThreadPool(new WorkThreadFactory());
es.execute(new WorkRunnable());
es.execute(new WorkRunnable());
es.execute(new WorkRunnable());
es.execute(new WorkRunnable());
es.execute(new WorkRunnable());
es.shutdown();
try{
es.awaitTermination(2*60, TimeUnit.SECONDS);
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
|
package interview;
import org.junit.After;
import org.junit.Before;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.PageFactory;
public class PageObject {
ChromeDriver driver;
@Before
public void setUp() {
System.setProperty("webdriver.chrome.driver", "./driver/chromedriver.exe");
driver = new ChromeDriver();
PageFactory.initElements(driver, this);
}
@After
public void closeBrowser() {
driver.close();
}
}
|
package us.team7pro.EventTicketsApp.Repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import us.team7pro.EventTicketsApp.Domain.User;
public interface UserRepository extends JpaRepository<User, Integer> {
public User findById(long id);
public User findByEmail(String email);
}
|
package com.dassa.vo;
import java.util.ArrayList;
public class MapImageData {
private ArrayList<String> imgList;
private ArrayList<ShopItemVO> list;
public MapImageData() {
super();
// TODO Auto-generated constructor stub
}
public MapImageData(ArrayList<String> imgList, ArrayList<ShopItemVO> list) {
super();
this.imgList = imgList;
this.list = list;
}
public ArrayList<String> getImgList() {
return imgList;
}
public void setImgList(ArrayList<String> imgList) {
this.imgList = imgList;
}
public ArrayList<ShopItemVO> getList() {
return list;
}
public void setList(ArrayList<ShopItemVO> list) {
this.list = list;
}
}
|
package org.bsns.server.board.file.fileauth;
import java.sql.SQLException;
import java.util.List;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.bsns.server.common.Condition;
import org.bsns.server.domain.FileAuthVO;
import org.springframework.stereotype.Service;
@Service(value="FileAuthService")
public class FileAuthServiceImpl
implements FileAuthService{
@Resource(name="FileAuthDAO")
private FileAuthDAO fileAuthDao;
private Logger log = Logger.getLogger(this.getClass());
@Override
public void create(FileAuthVO fileAuth) throws SQLException {
log.debug("===== FilaAuthService create() Start =====");
fileAuthDao.create(fileAuth);
log.debug("===== FilaAuthService create() End =====");
}
@Override
public FileAuthVO read(Condition condition) throws SQLException {
log.debug("===== FilaAuthService read(condition) Start =====");
FileAuthVO fileAuth = fileAuthDao.read(condition);
log.debug("read(condition) Result = " + fileAuth);
return fileAuth;
}
@Override
public FileAuthVO read(Integer key) throws SQLException {
log.debug("===== FilaAuthService read(condition) Start =====");
Condition<String, Integer> condition = new Condition<String, Integer>();
condition.put("fileAuthKey", key);
FileAuthVO fileAuth = fileAuthDao.read(condition);
log.debug("read(condition) Result = " + fileAuth);
return fileAuth;
}
@Override
public void update(FileAuthVO fileAuth) throws SQLException {
log.debug("===== FilaAuthService update(fileAuth) Start =====");
fileAuthDao.update(fileAuth);
log.debug("===== FilaAuthService update(fileAuth) End =====");
}
@Override
public void delete(Condition condition) throws SQLException {
log.debug("===== FilaAuthService delete(condition) Start =====");
fileAuthDao.delete(condition);
log.debug("===== FilaAuthService delete(condition) End =====");
}
@Override
public void delete(Integer key) throws SQLException {
log.debug("===== FilaAuthService delete(condition) Start =====");
Condition<String, Integer> condition = new Condition<String, Integer>();
condition.put("fileAuthKey", key);
fileAuthDao.delete(condition);
log.debug("===== FilaAuthService delete(condition) End =====");
}
@Override
public List<FileAuthVO> list(Condition condition) throws SQLException {
log.debug("===== FilaAuthService list(condition) Start =====");
List<FileAuthVO> fileAuthList = fileAuthDao.list(condition);
log.debug("list(condtion) Result = " + fileAuthList);
return fileAuthList;
}
}
|
package L5_ExerciciosFuncoes.L5_Main;
import java.util.Scanner;
public class Exercicio_05 {
public static void main(String[] args) {
System.out.println("Digite o valor do produto");
Scanner myScanner = new Scanner(System.in);
float valorProduto = myScanner.nextFloat();
System.out.println("Digite a taxa a ser aplicado ao produto (Ex: 2.5, 11, 30 %)");
float taxaProduto = myScanner.nextFloat();
float valorTaxa = somaImposto(taxaProduto, valorProduto);//valor da taxa
float valorFinalProduto = alterar(valorTaxa, valorProduto);
System.out.println("Valor final do produto: R$" + valorFinalProduto);
}
static float somaImposto(float taxaImposto, float custoProduto){
return custoProduto * (taxaImposto/100);
}
static float alterar(float valorTaxaProduto, float custoProduto){
return valorTaxaProduto + custoProduto;
}
}
|
package cn.e3mall.redis;
import org.junit.Test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
public class Redis {
@Test
public void testRedis() throws Exception{
Jedis jedis=new Jedis("95.169.31.254",6379);
jedis.set("aa", "1");
String string = jedis.get("aa");
System.out.println(string);
}
//ไฝฟ็จๅๆบ็ๆฌ่ฟๆฅ่ฟๆฅๆฑ
@Test
public void testJedisPool() throws Exception
{
JedisPool jedisPool =new JedisPool("95.169.31.254",6379);
Jedis jedis = jedisPool.getResource();
jedis.set("jedis", "test");
String result=jedis.get("jedis");
System.out.println(result);
jedis.close();
jedisPool.close();
}
}
|
package com.daikit.graphql.meta.custommethod;
import java.util.List;
/**
* GraphQL dynamic method argument {@link List} of entities meta data
*
* @author Thibaut Caselli
*/
public class GQLMethodArgumentListEntityMetaData extends GQLAbstractMethodArgumentMetaData {
private Class<?> foreignClass;
// *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
// CONSTRUCTORS
// *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
/**
* Default constructor
*/
public GQLMethodArgumentListEntityMetaData() {
// Nothing done
}
/**
* Constructor passing name and foreign entity class and keeping default
* values for other attributes.
*
* @param name
* the name for the method argument. This name will be used for
* building GraphQL schema query or mutation for this method
* @param foreignClass
* the foreign entity class
*/
public GQLMethodArgumentListEntityMetaData(final String name, final Class<?> foreignClass) {
super(name);
this.foreignClass = foreignClass;
}
// *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
// METHODS
// *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
@Override
protected void appendToString(final StringBuilder stringBuilder) {
stringBuilder.append("{METHOD-ARGUMENT-LIST-ENTITY(")
.append(foreignClass == null ? "" : foreignClass.getSimpleName()).append(")}");
super.appendToString(stringBuilder);
}
// *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
// GETTERS / SETTERS
// *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
/**
* Get the foreign entity class
*
* @return the foreignClass
*/
public Class<?> getForeignClass() {
return foreignClass;
}
/**
* Set the foreign entity class
*
* @param foreignClass
* the foreignClass to set
* @return this instance
*/
public GQLMethodArgumentListEntityMetaData setForeignClass(final Class<?> foreignClass) {
this.foreignClass = foreignClass;
return this;
}
}
|
package kr.co.wisenut.search.model;
import java.util.ArrayList;
public class Category {
String label;
ArrayList<String> entries;
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public ArrayList<String> getEntries() {
return entries;
}
public void setEntries(ArrayList<String> entries) {
this.entries = entries;
}
}
|
package com.moped.snake.resources;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import com.moped.snake.R;
import android.content.Context;
class LocalFieldLoader implements FieldLoader {
private final Context context;
public LocalFieldLoader(final Context context) {
this.context = context;
}
public String load() {
InputStream inputStream = context.getResources().openRawResource(R.raw.level);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try {
i = inputStream.read();
while (i != -1)
{
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return byteArrayOutputStream.toString();
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package hoangduc.dtos;
import java.io.Serializable;
/**
*
* @author ADMIN
*/
public class ProductDTO implements Serializable{
private int productid,productquantity,type;
private String productname, productdetail, productimage,typename;
private float productprice;
private boolean productstatus,productisdelete;
public ProductDTO() {
}
public ProductDTO(int productid, int productquantity, String productname, String productimage, float productprice) {
this.productid = productid;
this.productquantity = productquantity;
this.productname = productname;
this.productimage = productimage;
this.productprice = productprice;
}
public String getTypename() {
return typename;
}
public void setTypename(String typename) {
this.typename = typename;
}
public ProductDTO(int productquantity, String productname, String productdetail, String productimage, String typename, float productprice, boolean productstatus) {
this.productquantity = productquantity;
this.productname = productname;
this.productdetail = productdetail;
this.productimage = productimage;
this.typename = typename;
this.productprice = productprice;
this.productstatus = productstatus;
}
public ProductDTO(int productid, int productquantity, String productname, String productdetail, String productimage, String typename, float productprice, boolean productstatus) {
this.productid = productid;
this.productquantity = productquantity;
this.productname = productname;
this.productdetail = productdetail;
this.productimage = productimage;
this.typename = typename;
this.productprice = productprice;
this.productstatus = productstatus;
}
public ProductDTO(int productid, int productquantity, String productname, String productdetail, String productimage, float productprice) {
this.productid = productid;
this.productquantity = productquantity;
this.productname = productname;
this.productdetail = productdetail;
this.productimage = productimage;
this.productprice = productprice;
}
public ProductDTO(int productquantity, int type, String productname, String productdetail, String productimage, float productprice, boolean productstatus) {
this.productquantity = productquantity;
this.type = type;
this.productname = productname;
this.productdetail = productdetail;
this.productimage = productimage;
this.productprice = productprice;
this.productstatus = productstatus;
}
public boolean isProductisdelete() {
return productisdelete;
}
public void setProductisdelete(boolean productisdelete) {
this.productisdelete = productisdelete;
}
public int getProductid() {
return productid;
}
public void setProductid(int productid) {
this.productid = productid;
}
public int getProductquantity() {
return productquantity;
}
public void setProductquantity(int productquantity) {
this.productquantity = productquantity;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getProductname() {
return productname;
}
public void setProductname(String productname) {
this.productname = productname;
}
public String getProductdetail() {
return productdetail;
}
public void setProductdetail(String productdetail) {
this.productdetail = productdetail;
}
public String getProductimage() {
return productimage;
}
public void setProductimage(String productimage) {
this.productimage = productimage;
}
public float getProductprice() {
return productprice;
}
public void setProductprice(float productprice) {
this.productprice = productprice;
}
public boolean isProductstatus() {
return productstatus;
}
public void setProductstatus(boolean productstatus) {
this.productstatus = productstatus;
}
}
|
package net.tascalate.nio.channels;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.CompletionHandler;
import java.nio.channels.FileLock;
import java.nio.file.OpenOption;
import java.nio.file.Path;
import java.nio.file.attribute.FileAttribute;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import net.tascalate.concurrent.Promise;
public class AsynchronousFileChannel extends java.nio.channels.AsynchronousFileChannel {
protected final java.nio.channels.AsynchronousFileChannel delegate;
public static AsynchronousFileChannel open(Path file, OpenOption... options) throws IOException {
return new AsynchronousFileChannel(java.nio.channels.AsynchronousFileChannel.open(file, options));
}
public static AsynchronousFileChannel open(
Path file,
Set<? extends OpenOption> options,
ExecutorService executor,
FileAttribute<?>... attrs) throws IOException {
return new AsynchronousFileChannel(java.nio.channels.AsynchronousFileChannel.open(file, options, executor, attrs));
}
protected AsynchronousFileChannel(java.nio.channels.AsynchronousFileChannel delegate) {
this.delegate = delegate;
}
public boolean isOpen() {
return delegate.isOpen();
}
public void close() throws IOException {
delegate.close();
}
public long size() throws IOException {
return delegate.size();
}
public AsynchronousFileChannel truncate(long size) throws IOException {
delegate.truncate(size);
return this;
}
public void force(boolean metaData) throws IOException {
delegate.force(metaData);
}
public <A> void lock(long position, long size, boolean shared, A attachment,
CompletionHandler<FileLock, ? super A> handler) {
delegate.lock(position, size, shared);
}
public Promise<FileLock> lockAll() {
return lockAll(false);
}
public Promise<FileLock> lockAll(boolean shared) {
return doLock(0, Long.MAX_VALUE, shared);
}
public Promise<FileLock> lock(long position, long size, boolean shared) {
return doLock(position, size, shared);
}
public FileLock tryLock(long position, long size, boolean shared) throws IOException {
return delegate.tryLock(position, size, shared);
}
public <A> void read(ByteBuffer dst, long position, A attachment, CompletionHandler<Integer, ? super A> handler) {
delegate.read(dst, position, attachment, handler);
}
public Promise<Integer> read(ByteBuffer dst, long position) {
AsyncResult<Integer> asyncResult = new AsyncResult<>();
delegate.read(dst, position, null, asyncResult.handler);
return asyncResult;
}
public <A> void write(ByteBuffer src, long position, A attachment, CompletionHandler<Integer, ? super A> handler) {
delegate.write(src, position, attachment, handler);
}
public Promise<Integer> write(ByteBuffer src, long position) {
AsyncResult<Integer> asyncResult = new AsyncResult<>();
delegate.write(src, position, null, asyncResult.handler);
return asyncResult;
}
protected Promise<FileLock> doLock(long position, long size, boolean shared) {
AsyncResult<FileLock> asyncResult = new AsyncResult<>();
delegate.lock(position, size, shared, null, asyncResult.handler);
return asyncResult;
}
}
|
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.ArrayList;
import net.miginfocom.swing.MigLayout;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class MainWindow {
private JFrame frmTerminkalender;
private JTable tAppointments;
private ArrayList<Appointment> appointments = new ArrayList<Appointment>();
private void initialize() {
original();
JButton btnEdit = new JButton("Edit");
frmTerminkalender.getContentPane().add(btnEdit, "cell 12 8");
btnEdit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int selectedIndex = tAppointments.getSelectedRow();
if(selectedIndex < appointments.size() && selectedIndex > -1) {
Appointment appointment = appointments.get(selectedIndex);
CreateAppointmentDialog dialog = new CreateAppointmentDialog(appointment);
dialog.setVisible(true);
dialog.addWindowListener(new WindowListener() {
@Override
public void windowClosed(WindowEvent e) {
updateTable();
}
@Override
public void windowActivated(WindowEvent arg0) {
}
@Override
public void windowClosing(WindowEvent arg0) {
}
@Override
public void windowDeactivated(WindowEvent arg0) {
}
@Override
public void windowDeiconified(WindowEvent arg0) {
}
@Override
public void windowIconified(WindowEvent arg0) {
}
@Override
public void windowOpened(WindowEvent arg0) {
}
});
}
}
});
}
}
|
package com.zc.pivas.configfee.service;
import com.zc.pivas.docteradvice.entity.SynDoctorAdviceBean;
import com.zc.pivas.configfee.bean.ConfigFeeChargeBean;
import java.util.List;
/**
* ้
็ฝฎ่ดน่ฎก็ฎๆๅกๆฅๅฃ
*
* @author kunkka
* @version 1.0
*/
public interface ConfigFeeChargeService {
/**
* ้
็ฝฎ่ดน่งๅ่ฎก็ฎๆฅๅฃ
*
* @param yzList ๅปๅฑๅ่กจ๏ผๅช้ๅฏนๆ็ป็ไธๅ
ๆฐด
* @return ้่ฆๆถ่ดน็ๆถ่ดน็ผ็
*/
List<ConfigFeeChargeBean> findConfigCharge(List<SynDoctorAdviceBean> yzList);
}
|
/**
*
*/
package eu.fbk.dycapo.util;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
import android.util.Log;
import com.google.android.maps.GeoPoint;
/**
* @author riccardo
*
*/
public abstract class GeoGuard {
private static final String TAG = "GeoPointBuilder";
public static final GeoPoint parseGeoRSSPoint(String geo) {
int separator = geo.indexOf(" ");
String slat = geo.substring(0, separator - 1);
String slng = geo.substring(separator + 1);
double lat = parseStringToDouble(slat);
double lng = parseStringToDouble(slng);
GeoPoint point = new GeoPoint((int) ((lat) * 1E6), (int) ((lng) * 1E6));
return point;
}
public static final double parseStringToDouble(String number) {
NumberFormat nf = NumberFormat.getInstance(Locale.ENGLISH);
nf.setMaximumFractionDigits(6);
nf.setMinimumFractionDigits(6);
try {
Number number_value = nf.parse(number);
Log.d(TAG, number_value.toString());
return number_value.doubleValue();
} catch (ParseException e) {
Log.e(TAG, e.getMessage());
e.printStackTrace();
}
return (Double) null;
}
public static final String validateGeoRSSPoint(String geo) {
int separator = geo.indexOf(" ");
String slat = geo.substring(0, separator - 1).trim();
String slng = geo.substring(separator + 1).trim();
double lat = parseStringToDouble(slat);
double lng = parseStringToDouble(slng);
Log.d(TAG, (lat + " " + lng));
return (lat + " " + lng);
}
}
|
package com.trump.auction.goods.dao;
import com.trump.auction.goods.domain.MerchantInfo;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* Created by ็ฝๆพ on 2017/12/21.
*/
@Repository
public interface MerchantInfoDao {
/**
* ๆๅ็ปๆ่ฟๅ >0
* ๅคฑ่ดฅ็ปๆ่ฟๅ 0
* ๆทปๅ ๅๅฎถ
*/
int addMerchantInfo(MerchantInfo merchantInfo);
/**
* ๆ นๆฎๆกไปถๆฅ่ฏขๅพๅฐ็ๅๅฎถ้ๅ
* @param merchantInfo id merchant_name phone status
* @return
*/
List<MerchantInfo> getListMerchantInfo(MerchantInfo merchantInfo);
/**
* ๅ ้คๅๅฎถ
* @param ids
* @return
*/
int deleteMerchantInfo(String[] ids);
/**
* ไฟฎๆนๅๅฎถ
*/
int updateMerchantInfo(MerchantInfo merchantInfo);
}
|
package be.mxs.common.util.pdf.general.oc.examinations;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfPCell;
import java.sql.SQLException;
import java.util.Hashtable;
import java.util.Vector;
import java.util.Collections;
import be.mxs.common.util.pdf.general.PDFGeneralBasic;
import be.openclinic.medical.RequestedLabAnalysis;
import be.openclinic.medical.Labo;
public class PDFLabRequest extends PDFGeneralBasic {
// declarations
private StringBuffer monsters;
//--- ADD CONTENT ------------------------------------------------------------------------------
protected void addContent(){
try{
if(transactionVO.getItems().size() >= minNumberOfItems){
contentTable = new PdfPTable(1);
monsters = new StringBuffer();
// CHOSEN LABANALYSES
PdfPTable chosenLabs = getChosenLabAnalyses();
if(chosenLabs.size() > 0){
contentTable.addCell(createCell(new PdfPCell(chosenLabs),1,PdfPCell.ALIGN_CENTER,PdfPCell.NO_BORDER));
}
table = new PdfPTable(5);
// MONSTERS (calculated)
if(monsters.length() > 0){
addItemRow(table,getTran("labrequest.monsters"),monsters.toString());
}
// MONSTER HOUR
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_LAB_HOUR");
if(itemValue.length() > 0){
addItemRow(table,getTran("Web.Occup","labrequest.hour"),itemValue);
}
// COMMENT
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_LAB_COMMENT");
if(itemValue.length() > 0){
addItemRow(table,getTran("Web","comment"),itemValue);
}
// URGENCY
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_LAB_URGENCY");
if(itemValue.length() > 0){
addItemRow(table,getTran("Web.Occup","urgency"),getTran("labrequest.urgency",itemValue).toLowerCase());
}
// add table
if(table.size() > 0){
if(contentTable.size() > 0) contentTable.addCell(emptyCell());
contentTable.addCell(createCell(new PdfPCell(table),1,PdfPCell.ALIGN_CENTER,PdfPCell.BOX));
tranTable.addCell(new PdfPCell(contentTable));
}
// add transaction to doc
addTransactionToDoc();
}
}
catch(Exception e){
e.printStackTrace();
}
}
//### PRIVATE METHODS ##########################################################################
//--- GET CHOSEN LABANALYSES -------------------------------------------------------------------
private PdfPTable getChosenLabAnalyses() throws SQLException {
PdfPTable chosenAnalysesTable = new PdfPTable(14);
String sTmpCode, sTmpComment, sTmpModifier, sTmpResult, sTmpResultUnit, sTmpResultValue,
sTmpType = "", sTmpLabel = "", sTmpMonster = "";
// get chosen labanalyses from existing transaction.
Hashtable labAnalyses = RequestedLabAnalysis.getLabAnalysesForLabRequest(transactionVO.getServerId(),transactionVO.getTransactionId().intValue());
// sort analysis-codes
Vector codes = new Vector(labAnalyses.keySet());
Collections.sort(codes);
// run thru saved labanalysis
RequestedLabAnalysis labAnalysis;
for (int i=0; i<codes.size(); i++) {
sTmpCode = (String)codes.get(i);
labAnalysis = (RequestedLabAnalysis)labAnalyses.get(sTmpCode);
sTmpComment = labAnalysis.getComment();
sTmpModifier = labAnalysis.getResultModifier();
// get resultvalue
if(labAnalysis.getFinalvalidation()>0){
sTmpResultValue = labAnalysis.getResultValue();
}
else {
sTmpResultValue="";
}
sTmpResultUnit = getTran("labanalysis.resultunit",labAnalysis.getResultUnit());
sTmpResult = sTmpResultValue + " " + sTmpResultUnit;
// get default-data from DB
Hashtable hLabRequestData = Labo.getLabRequestDefaultData(sTmpCode,sPrintLanguage);
if (hLabRequestData != null) {
sTmpType = (String) hLabRequestData.get("labtype");
sTmpLabel = (String) hLabRequestData.get("OC_LABEL_VALUE");
sTmpMonster = (String) hLabRequestData.get("monster");
}
// translate labtype
if(sTmpType.equals("1")) sTmpType = getTran("Web.occup","labanalysis.type.blood");
else if(sTmpType.equals("2")) sTmpType = getTran("Web.occup","labanalysis.type.urine");
else if(sTmpType.equals("3")) sTmpType = getTran("Web.occup","labanalysis.type.other");
else if(sTmpType.equals("4")) sTmpType = getTran("Web.occup","labanalysis.type.stool");
else if(sTmpType.equals("5")) sTmpType = getTran("Web.occup","labanalysis.type.sputum");
else if(sTmpType.equals("6")) sTmpType = getTran("Web.occup","labanalysis.type.smear");
else if(sTmpType.equals("7")) sTmpType = getTran("Web.occup","labanalysis.type.liquid");
// add analysis to table
chosenAnalysesTable = addLabAnalysisToPDFTable(chosenAnalysesTable,sTmpCode,sTmpType,sTmpLabel,sTmpComment,sTmpMonster,sTmpResult,sTmpModifier);
// add monster if one is specified
if(sTmpMonster.length() > 0){
if(monsters.indexOf(sTmpMonster) < 0){
monsters.append(sTmpMonster).append(", ");
}
}
}
// remove last comma from monsters
if(monsters.indexOf(",") > -1){
monsters = monsters.deleteCharAt(monsters.length()-2);
}
return chosenAnalysesTable;
}
//--- ADD LABANALYSIS TO PDF TABLE -------------------------------------------------------------
private PdfPTable addLabAnalysisToPDFTable(PdfPTable pdfTable, String code, String type, String label,
String comment, String monster, String resultvalue, String resultmodifier){
// add header if no header yet
if(pdfTable.size() == 0){
pdfTable.addCell(createHeaderCell(getTran("web.manage","labanalysis.cols.code"),1));
pdfTable.addCell(createHeaderCell(getTran("web.manage","labanalysis.cols.type"),1));
pdfTable.addCell(createHeaderCell(getTran("web.manage","labanalysis.cols.name"),2));
pdfTable.addCell(createHeaderCell(getTran("web.manage","labanalysis.cols.comment"),3));
pdfTable.addCell(createHeaderCell(getTran("web.manage","labanalysis.cols.monster"),3));
pdfTable.addCell(createHeaderCell(getTran("web.manage","labanalysis.cols.resultvalue"),2));
pdfTable.addCell(createHeaderCell(getTran("web.manage","labanalysis.cols.resultmodifier"),2));
}
pdfTable.addCell(createValueCell(code,1));
pdfTable.addCell(createValueCell(type,1));
pdfTable.addCell(createValueCell(label,2));
pdfTable.addCell(createValueCell(comment,3));
pdfTable.addCell(createValueCell(monster,3));
pdfTable.addCell(createValueCell(resultvalue,2));
pdfTable.addCell(createValueCell(resultmodifier,2));
return pdfTable;
}
}
|
package com.meehoo.biz.core.basic.annotation;
import java.lang.annotation.*;
/**
* Created by zc on 2018/1/5 0005.
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Log {
String value() default "ๆฅๅฟ่ฎฐๅฝๅผๅง";
int paramNum() default 0; // ๆฏๅฆๆๅๆฐ๏ผ0 ๆฒกๆ ๅคงไบ0็ๆฏๅ
ทไฝๅๆฐ็ๆๅบ
int paramNum1() default 0; // ๆฏๅฆๆๅๆฐ๏ผ0 ๆฒกๆ ๅคงไบ0็ๆฏๅ
ทไฝๅๆฐ็ๆๅบ
// int paramNum2() default 0; // ๆฏๅฆๆๅๆฐ๏ผ0 ๆฒกๆ ๅคงไบ0็ๆฏๅ
ทไฝๅๆฐ็ๆๅบ
}
|
package fr.ecole.eni.lokacar.dao;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import fr.ecole.eni.lokacar.bddHelper.VehiculeHelper;
import fr.ecole.eni.lokacar.bean.Location;
import fr.ecole.eni.lokacar.bean.Vehicule;
import fr.ecole.eni.lokacar.contract.LocationContract;
import fr.ecole.eni.lokacar.contract.VehiculeContract;
import fr.ecole.eni.lokacar.bean.Agence;
import fr.ecole.eni.lokacar.bean.Model;
public class VehiculeDao {
ModelDao modelDao;
private VehiculeHelper dbhelper;
public VehiculeDao(Context context) {
this.dbhelper = new VehiculeHelper(context);
}
private ContentValues constructValuesDB(Vehicule vehicule) {
ContentValues values = new ContentValues();
values.put(VehiculeContract._CNIT, vehicule.getCnit());
values.put(VehiculeContract._PRIX, vehicule.getPrix());
values.put(VehiculeContract._PLAQUE, vehicule.getPlaque());
values.put(VehiculeContract._PHOTOPATH, vehicule.getPhotoPath());
values.put(VehiculeContract._ISDISPO, vehicule.isDispo() ? 1 : 0);
values.put(VehiculeContract._MARQUE, vehicule.getMarque());
values.put(VehiculeContract._CODEAGENCE, vehicule.getCodeAgence());
return values;
}
public long insert(Vehicule vehicule) {
SQLiteDatabase db = dbhelper.getWritableDatabase();
long id = db.insert(VehiculeContract.TABLE_VEHICULES_NAME, null, constructValuesDB(vehicule));
db.close();
return id;
}
public Vehicule getById(int id, Context context) throws ParseException {
modelDao = new ModelDao(context);
SQLiteDatabase db = dbhelper.getReadableDatabase();
Cursor cursor = db.query(
VehiculeContract.TABLE_VEHICULES_NAME, null,
VehiculeContract._VEHICULES_ID + "=?",
new String[]{String.valueOf(id)},
null,
null,
null);
Vehicule object = null;
if (cursor != null && cursor.moveToFirst()) {
String marque = cursor.getString(cursor.getColumnIndex(VehiculeContract._MARQUE));
String cnit = cursor.getString(cursor.getColumnIndex(VehiculeContract._CNIT));
Model model = modelDao.getByCnit(cnit);
Float prix = cursor.getFloat(cursor.getColumnIndex(VehiculeContract._PRIX));
String plaque = cursor.getString(cursor.getColumnIndex(VehiculeContract._PLAQUE));
int agence = cursor.getInt(cursor.getColumnIndex(VehiculeContract._CODEAGENCE));
boolean isDispo = cursor.getInt(cursor.getColumnIndex(VehiculeContract._ISDISPO)) == 1 ? true : false;
String photoPath = cursor.getString(cursor.getColumnIndex(VehiculeContract._PHOTOPATH));
object = new Vehicule(id, marque, model, cnit, prix, plaque, agence, isDispo, photoPath,0);
cursor.close();
}
return object;
}
public List<Vehicule> getListe(Context context) {
ModelDao modelDao = new ModelDao(context);
AgenceDao agenceDao = new AgenceDao(context);
SQLiteDatabase db = dbhelper.getReadableDatabase();
Cursor cursor = db.query(
VehiculeContract.TABLE_VEHICULES_NAME, null, null, null,
null,
null,
null);
List<Vehicule> objects = new ArrayList<Vehicule>();
if (cursor != null && cursor.moveToFirst()) {
do {
Integer id = cursor.getInt(cursor.getColumnIndex(VehiculeContract._VEHICULES_ID));
String marque = cursor.getString(cursor.getColumnIndex(VehiculeContract._MARQUE));
String cnit = cursor.getString(cursor.getColumnIndex(VehiculeContract._CNIT));
Model model = modelDao.getByCnit(cnit);
Float prix = cursor.getFloat(cursor.getColumnIndex(VehiculeContract._PRIX));
String plaque = cursor.getString(cursor.getColumnIndex(VehiculeContract._PLAQUE));
int agence = cursor.getInt(cursor.getColumnIndex(VehiculeContract._CODEAGENCE));
boolean isDispo = cursor.getInt(cursor.getColumnIndex(VehiculeContract._ISDISPO)) == 1 ? true : false;
String photoPath = cursor.getString(cursor.getColumnIndex(VehiculeContract._PHOTOPATH));
objects.add(new Vehicule(id, marque, model, cnit, prix, plaque,
agence, isDispo, photoPath,0));
} while (cursor.moveToNext());
cursor.close();
}
return objects;
}
public ArrayList<Vehicule> getListeBySearch(Context context, String... critereString) {
ModelDao modelDao = new ModelDao(context);
AgenceDao agenceDao = new AgenceDao(context);
SQLiteDatabase db = dbhelper.getReadableDatabase();
List<String> argsList = new ArrayList<>();
String selection = "1";
if (critereString != null) {
selection += critereString[0] != null ? " AND " + VehiculeContract._MARQUE + "=?" : ""; //marque
selection += critereString[1] != null ? " AND " + VehiculeContract._CNIT + "=? " : ""; //model ?
selection += critereString[2] != null ? " AND " + VehiculeContract._PRIX + "> ? " : ""; //prix min
selection += critereString[3] != null ? " AND " + VehiculeContract._PRIX + "< ? " : ""; //prix max
selection += critereString[4] != null ? " AND " + VehiculeContract._ISDISPO + "=? " : ""; // dispo
if (critereString[0] != null) {
argsList.add(critereString[0]);
}
if (critereString[1] != null) {
argsList.add(critereString[1]);
}
if (critereString[2] != null) {
argsList.add(critereString[2]);
}
if (critereString[3] != null) {
argsList.add(critereString[3]);
}
if (critereString[4] != null) {
argsList.add(critereString[4]);
}
}
String[] args = argsList.toArray(new String[argsList.size()]);
if (argsList.size() == 0) {
args = null;
}
Log.i("RUN", selection);
Cursor cursor = db.query(
VehiculeContract.TABLE_VEHICULES_NAME,
null,
selection,
args,
null,
null,
null);
ArrayList<Vehicule> objects = new ArrayList<Vehicule>();
if (cursor != null && cursor.moveToFirst()) {
do {
Integer id = cursor.getInt(cursor.getColumnIndex(VehiculeContract._VEHICULES_ID));
String marque = cursor.getString(cursor.getColumnIndex(VehiculeContract._MARQUE));
String cnit = cursor.getString(cursor.getColumnIndex(VehiculeContract._CNIT));
Model model = modelDao.getByCnit(cnit);
Float prix = cursor.getFloat(cursor.getColumnIndex(VehiculeContract._PRIX));
String plaque = cursor.getString(cursor.getColumnIndex(VehiculeContract._PLAQUE));
int agence = cursor.getInt(cursor.getColumnIndex(VehiculeContract._CODEAGENCE));
boolean isDispo = cursor.getInt(cursor.getColumnIndex(VehiculeContract._ISDISPO)) == 1 ? true : false;
String photoPath = cursor.getString(cursor.getColumnIndex(VehiculeContract._PHOTOPATH));
objects.add(new Vehicule(id, marque, model, cnit, prix, plaque,
agence, isDispo, photoPath,0));
} while (cursor.moveToNext());
cursor.close();
}
return objects;
}
}
|
package com.ar.ui;
import com.ar.ui.header.HeaderPanel;
import com.ar.ui.menu.Menu;
import com.vaadin.server.VaadinRequest;
import com.vaadin.ui.*;
public class HomeUI extends UI {
public VerticalLayout mainContent;
@Override
protected void init(VaadinRequest request) {
setTheme("example");
VerticalLayout verticalLayout = new VerticalLayout();
verticalLayout.setSizeFull();
verticalLayout.addComponent(new HeaderPanel());
verticalLayout.addComponent(new Menu());
mainContent = new VerticalLayout(new Label("Inicio"));
mainContent.setMargin(true);
mainContent.setSizeFull();
verticalLayout.addComponent(mainContent);
verticalLayout.setExpandRatio(mainContent,1);
setContent(verticalLayout);
}
public void changeMenuItem(Component component) {
mainContent.replaceComponent(mainContent.getComponent(0), component);
}
}
|
package com.oreilly.mvc_example.controllers;
import org.junit.jupiter.api.Test;
import org.springframework.ui.Model;
import org.springframework.validation.support.BindingAwareModelMap;
import static org.junit.jupiter.api.Assertions.*;
class HelloControllerTest {
@Test
void sayHello() {
HelloController controller = new HelloController();
Model model = new BindingAwareModelMap();
String result = controller.sayHello("World",model);
assertEquals("hello",result);
//assertEquals("world",model.asMap().get("user"));
}
}
|
package c.bwegener.bookstore;
import android.content.ContentValues;
import android.content.Context;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
public class DBHelper extends SQLiteOpenHelper {
private Context mContext;
private static final String TAG = "DBHelper";
static final String DATABASE_NAME = "AntiqueBookStore";
private static final int DATABASE_VERSION = 1;
// Database 1 -- Books Database + Fields
private static final String BOOKS_TABLE = "Books";
private static final String BOOKS_KEY_FIELD_ID = "_id";
private static final String FIELD_BOOKS_TITLE = "book_title";
private static final String FIELD_BOOKS_AUTHOR_LAST = "book_author_last"; // Relational Database
private static final String FIELD_BOOKS_AUTHOR_FIRST = "book_author_first"; // Relational Database
private static final String FIELD_BOOKS_PUBLISHER = "book_publisher";
private static final String FIELD_BOOKS_PUBLICATION_DATE = "book_publication_date";
private static final String FIELD_BOOKS_EDITION = "book_edition";
private static final String FIELD_BOOKS_COST = "book_cost";
private static final String FIELD_BOOKS_RETAIL_PRICE = "book_retail_price";
private static final String FIELD_BOOKS_RATING = "book_rating";
private static final String FIELD_BOOKS_COVER_TYPE = "book_cover_type";
private static final String FIELD_BOOKS_GENRE = "book_genre";
/*
// Database 2 -- Authors Database + Fields
private static final String AUTHORS_TABLE = "Authors";
private static final String AUTHORS_KEY_FIELD_ID = "_id";
private static final String FIELD_AUTHORS_LAST = "author_last"; // Relational Database
private static final String FIELD_AUTHORS_FIRST = "author_first"; // Relational Database
private static final String FIELD_AUTHORS_YEAR_BIRTH = "author_year_birth";
private static final String FIELD_AUTHORS_YEAR_DEATH = "author_year_death"; // If Applicable
*/
// Database 3 -- Employee Database + Fields
private static final String EMPLOYEES_TABLE = "Employees";
private static final String EMPLOYEES_KEY_FIELD_ID = "_id";
private static final String FIELD_EMPLOYEES_FIRST = "employee_first";
private static final String FIELD_EMPLOYEES_LAST = "employee_last";
private static final String FIELD_EMPLOYEES_ADDRESS = "employee_address";
private static final String FIELD_EMPLOYEES_PHONE = "employee_phone";
private static final String FIELD_EMPLOYEES_BIRTH = "employee_birth";
private static final String FIELD_EMPLOYEES_HIRE = "employee_hire";
// manager tracks employee sales
private static final String FIELD_EMPLOYEE_SALES = "employee_sales";
// Owner, Assistant Manager, Full Time Sales Clerk, Part Time Sales Clerk
private static final String FIELD_EMPLOYEE_POSITION = "employee_position";
// Database 4 -- Customer Database + Fields
private static final String CUSTOMERS_TABLE = "Customers";
private static final String CUSTOMERS_KEY_FIELD_ID = "_id";
private static final String FIELD_CUSTOMERS_FIRST = "customer_first";
private static final String FIELD_CUSTOMERS_LAST = "customer_last";
private static final String FIELD_CUSTOMERS_ADDRESS = "customer_address"; // Not required
private static final String FIELD_CUSTOMERS_ZIP = "customer_zip"; // Not required
private static final String FIELD_CUSTOMERS_PHONE = "customer_phone"; // Not required
private static final String FIELD_CUSTOMERS_BOOKS = "customer_books"; // Not required
private static final String FIELD_CUSTOMERS_ORDERS = "customer_orders"; // Not required
// Database 5 -- Cart Database + Fields
private static final String CART_TABLE = "Cart";
private static final String FIELD_ID = "_id";
private static final String FIELD_BOOKS_ID = "books_id";
// Database 6 -- Orders Database + Fields
private static final String ORDERS_TABLE = "Orders";
private static final String ORDERS_KEY_FIELD_ID = "_id";
// private static final String FIELD_ORDERS_BOOK_IS_SOLD = "book_sold"; // Relational Database
// Customer who bought the book
private static final String FIELD_ORDERS_CUSTOMER = "orders_customer"; // Relational Database
// Employee who sold the book
private static final String FIELD_ORDERS_EMPLOYEE = "orders_employee"; // Relational Database
// String -- Total cost of sales
private static final String FIELD_ORDERS_TOTAL = "order_total"; // Relational Database
// String -- Date of sale
private static final String FIELD_ORDERS_DATE = "orders_date"; // Relational Database
// String -- Payment Type
private static final String FIELD_ORDERS_PAYMENT = "payment_type";
// Bool to check if book is paid for, cannot be shipped unless paid for
private static final String FIELD_ORDERS_PAID = "orders_paid";
// Bool to check if order is complete
private static final String FIELD_ORDERS_COMPLETE = "orders_complete";
/*
// Bool to check if book is shipped
private static final String FIELD_SALES_SHIPPED = "sales_shipped";
// String -- Drop Down -- Payment type -- CASH/CHECK/CREDIT
private static final String FIELD_SALES_PAYMENT = "sales_payment";
*/
/*
// Database 7 -- User Database
private static final String USER_TABLE = "User";
private static final String USER_KEY_FIELD_ID = "_id";
private static final String FIELD_USER_NAME = "user_name";
private static final String FIELD_USER_PASSWORD = "user_password";
*/
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
mContext = context;
}
@Override
public void onCreate(SQLiteDatabase database) {
// Create Books table
String createQuery = "CREATE TABLE " + BOOKS_TABLE + "("
+ BOOKS_KEY_FIELD_ID + " INTEGER PRIMARY KEY, "
+ FIELD_BOOKS_TITLE + " TEXT, "
+ FIELD_BOOKS_AUTHOR_LAST + " TEXT, "
+ FIELD_BOOKS_AUTHOR_FIRST + " TEXT, "
+ FIELD_BOOKS_PUBLISHER + " TEXT, "
+ FIELD_BOOKS_PUBLICATION_DATE + " TEXT, "
+ FIELD_BOOKS_EDITION + " TEXT, "
+ FIELD_BOOKS_COST + " TEXT, "
+ FIELD_BOOKS_RETAIL_PRICE + " TEXT, "
+ FIELD_BOOKS_RATING + " REAL, "
+ FIELD_BOOKS_COVER_TYPE + " TEXT, "
+ FIELD_BOOKS_GENRE + " TEXT" + ")";
database.execSQL(createQuery);
/*
// Create Authors table
createQuery = "CREATE TABLE " + AUTHORS_TABLE + "("
+ AUTHORS_KEY_FIELD_ID + " INTEGER PRIMARY KEY, "
+ FIELD_AUTHORS_FIRST + " TEXT, "
+ FIELD_AUTHORS_LAST + " TEXT, "
+ FIELD_AUTHORS_YEAR_BIRTH + " TEXT, "
+ FIELD_AUTHORS_YEAR_DEATH + " TEXT" + ")";
database.execSQL(createQuery);
*/
// Create Employees table
createQuery = "CREATE TABLE " + EMPLOYEES_TABLE + "("
+ EMPLOYEES_KEY_FIELD_ID + " INTEGER PRIMARY KEY, "
+ FIELD_EMPLOYEES_FIRST + " TEXT, "
+ FIELD_EMPLOYEES_LAST + " TEXT, "
+ FIELD_EMPLOYEES_ADDRESS + " TEXT, "
+ FIELD_EMPLOYEES_PHONE + " TEXT, "
+ FIELD_EMPLOYEES_BIRTH + " TEXT, "
+ FIELD_EMPLOYEES_HIRE + " TEXT, "
+ FIELD_EMPLOYEE_SALES + " TEXT, "
+ FIELD_EMPLOYEE_POSITION + " TEXT" + ")";
database.execSQL(createQuery);
// Create Customers table
createQuery = "CREATE TABLE " + CUSTOMERS_TABLE + "("
+ CUSTOMERS_KEY_FIELD_ID + " INTEGER PRIMARY KEY, "
+ FIELD_CUSTOMERS_FIRST + " TEXT, "
+ FIELD_CUSTOMERS_LAST + " TEXT, "
+ FIELD_CUSTOMERS_ADDRESS + " TEXT, "
+ FIELD_CUSTOMERS_ZIP + " TEXT, "
+ FIELD_CUSTOMERS_PHONE + " TEXT, "
+ FIELD_CUSTOMERS_BOOKS + " TEXT, "
+ FIELD_CUSTOMERS_ORDERS + " TEXT" + ")";
database.execSQL(createQuery);
// Create Cart table
createQuery = "CREATE TABLE " + CART_TABLE + "("
+ FIELD_ID + " INTEGER, "
+ FIELD_BOOKS_ID + " INTEGER, "
+ "FOREIGN KEY(" + FIELD_BOOKS_ID + ") REFERENCES "
+ BOOKS_TABLE + "(" + BOOKS_KEY_FIELD_ID + "))";
database.execSQL(createQuery);
// Create Orders table
createQuery = "CREATE TABLE " + ORDERS_TABLE + "("
+ ORDERS_KEY_FIELD_ID + " INTEGER PRIMARY KEY, "
+ FIELD_ORDERS_CUSTOMER + " TEXT, "
+ FIELD_ORDERS_EMPLOYEE + " TEXT, "
+ FIELD_ORDERS_TOTAL + " TEXT, "
+ FIELD_ORDERS_DATE + " TEXT, "
+ FIELD_ORDERS_PAYMENT + " TEXT, "
+ FIELD_ORDERS_PAID + " BIT, "
+ FIELD_ORDERS_COMPLETE + " BIT" + ")";
database.execSQL(createQuery);
/*
// Create User table
createQuery = "CREATE TABLE " + USER_TABLE + "("
+ USER_KEY_FIELD_ID + " INTEGER PRIMARY KEY, "
+ FIELD_USER_NAME + " TEXT, "
+ FIELD_USER_PASSWORD + " TEXT" + ")";
database.execSQL(createQuery);
*/
}
// ******************* ON UPGRADE ***********************
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + BOOKS_TABLE);
/*
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + AUTHORS_TABLE);
*/
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + EMPLOYEES_TABLE);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + CUSTOMERS_TABLE);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + CART_TABLE);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + ORDERS_TABLE);
/*
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + USER_TABLE);
*/
onCreate(sqLiteDatabase);
}
// ******************* ADD TO TABLES ***********************
public void addBook(Book book) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(FIELD_BOOKS_TITLE, book.getTitle());
values.put(FIELD_BOOKS_AUTHOR_LAST, book.getAuthorLast());
values.put(FIELD_BOOKS_AUTHOR_FIRST, book.getAuthorFirst());
values.put(FIELD_BOOKS_PUBLISHER, book.getPublisher());
values.put(FIELD_BOOKS_PUBLICATION_DATE, book.getPublishDate());
values.put(FIELD_BOOKS_EDITION, book.getEdition());
values.put(FIELD_BOOKS_COST, book.getCost());
values.put(FIELD_BOOKS_RETAIL_PRICE, book.getRetailPrice());
values.put(FIELD_BOOKS_RATING, book.getRating());
values.put(FIELD_BOOKS_COVER_TYPE, book.getCoverType());
values.put(FIELD_BOOKS_GENRE, book.getGenre());
long id = db.insert(BOOKS_TABLE, null, values);
book.setId(id);
db.close();
}
/*
public void addAuthor(Author author)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(FIELD_AUTHORS_FIRST, author.getAuthorFirst());
values.put(FIELD_AUTHORS_LAST, author.getAuthorLast());
values.put(FIELD_AUTHORS_YEAR_BIRTH, author.getYearOfBirth());
values.put(FIELD_AUTHORS_YEAR_DEATH, author.getYearOfDeath());
long id = db.insert(AUTHORS_TABLE, null, values);
author.setId(id);
db.close();
}
*/
public void addEmployee(Employee employee) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(FIELD_EMPLOYEES_FIRST, employee.getFirstName());
values.put(FIELD_EMPLOYEES_LAST, employee.getLastName());
values.put(FIELD_EMPLOYEES_ADDRESS, employee.getAddress());
values.put(FIELD_EMPLOYEES_PHONE, employee.getPhoneNumber());
values.put(FIELD_EMPLOYEES_BIRTH, employee.getDateOfBirth());
values.put(FIELD_EMPLOYEES_HIRE, employee.getHireDate());
values.put(FIELD_EMPLOYEE_SALES, employee.getSales());
values.put(FIELD_EMPLOYEE_POSITION, employee.getPosition());
long id = db.insert(EMPLOYEES_TABLE, null, values);
employee.setId(id);
db.close();
}
public void addCustomer(Customer customer) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(FIELD_CUSTOMERS_FIRST, customer.getFirstName());
values.put(FIELD_CUSTOMERS_LAST, customer.getLastName());
values.put(FIELD_CUSTOMERS_ADDRESS, customer.getAddress());
values.put(FIELD_CUSTOMERS_ZIP, customer.getZipCode());
values.put(FIELD_CUSTOMERS_PHONE, customer.getPhoneNumber());
values.put(FIELD_CUSTOMERS_BOOKS, customer.getBooks());
values.put(FIELD_CUSTOMERS_ORDERS, customer.getOrders());
long id = db.insert(CUSTOMERS_TABLE, null, values);
customer.setId(id);
db.close();
}
// ADDS A BOOK TO THE CART TABLE
public void addToCart(long id, int bookId)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(FIELD_ID, id);
values.put(FIELD_BOOKS_ID, bookId);
db.insert(CART_TABLE, null, values);
db.close();
}
public void addOrders(Orders order)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(FIELD_ORDERS_CUSTOMER, order.getCustomer());
values.put(FIELD_ORDERS_EMPLOYEE, order.getEmployee());
values.put(FIELD_ORDERS_TOTAL, order.getTotal());
values.put(FIELD_ORDERS_DATE, order.getDate());
values.put(FIELD_ORDERS_PAYMENT, order.getPaymentType());
values.put(FIELD_ORDERS_PAID, order.isPaid());
values.put(FIELD_ORDERS_COMPLETE, order.isComplete());
long id = db.insert(ORDERS_TABLE, null, values);
order.setId(id);
db.close();
}
// TODO: FINISH ORDERS (UPDATE, GET, DELETE)
// TODO: START/FINISH USER DB (ADD, UPDATE, GET, DELETE)
/*
public void addUser(User user) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(FIELD_USER_NAME, user.getUserName());
values.put(FIELD_USER_PASSWORD, user.getPassword());
long id = db.insert(USER_TABLE, null, values);
user.setId(id);
db.close();
}
*/
//**************** UPDATE TABLES **************************
public void updateBook(Book book)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values= new ContentValues();
values.put(FIELD_BOOKS_TITLE, book.getTitle());
values.put(FIELD_BOOKS_AUTHOR_LAST, book.getAuthorLast());
values.put(FIELD_BOOKS_AUTHOR_FIRST, book.getAuthorFirst());
values.put(FIELD_BOOKS_PUBLISHER, book.getPublisher());
values.put(FIELD_BOOKS_PUBLICATION_DATE, book.getPublishDate());
values.put(FIELD_BOOKS_EDITION, book.getEdition());
values.put(FIELD_BOOKS_COST, book.getCost());
values.put(FIELD_BOOKS_RETAIL_PRICE, book.getRetailPrice());
values.put(FIELD_BOOKS_RATING, book.getRating());
values.put(FIELD_BOOKS_COVER_TYPE, book.getCoverType());
values.put(FIELD_BOOKS_GENRE, book.getGenre());
db.update(BOOKS_TABLE, values, BOOKS_KEY_FIELD_ID + " = ?",
new String[]{String.valueOf(book.getId())});
db.close();
}
/*
public void updateAuthor(Author author)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values= new ContentValues();
values.put(FIELD_AUTHORS_FIRST, author.getAuthorFirst());
values.put(FIELD_AUTHORS_LAST, author.getAuthorLast());
values.put(FIELD_AUTHORS_YEAR_BIRTH, author.getYearOfBirth());
values.put(FIELD_AUTHORS_YEAR_DEATH, author.getYearOfDeath());
db.update(AUTHORS_TABLE, values, AUTHORS_KEY_FIELD_ID + " = ?",
new String[]{String.valueOf(author.getId())});
db.close();
}
*/
public void updateEmployee(Employee employee)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values= new ContentValues();
values.put(FIELD_EMPLOYEES_FIRST, employee.getFirstName());
values.put(FIELD_EMPLOYEES_LAST, employee.getLastName());
values.put(FIELD_EMPLOYEES_ADDRESS, employee.getAddress());
values.put(FIELD_EMPLOYEES_PHONE, employee.getPhoneNumber());
values.put(FIELD_EMPLOYEES_BIRTH, employee.getDateOfBirth());
values.put(FIELD_EMPLOYEES_HIRE, employee.getHireDate());
values.put(FIELD_EMPLOYEE_SALES, employee.getSales());
values.put(FIELD_EMPLOYEE_POSITION, employee.getPosition());
db.update(EMPLOYEES_TABLE, values, EMPLOYEES_KEY_FIELD_ID + " = ?",
new String[]{String.valueOf(employee.getId())});
db.close();
}
public void updateCustomer(Customer customer)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values= new ContentValues();
values.put(FIELD_CUSTOMERS_FIRST, customer.getFirstName());
values.put(FIELD_CUSTOMERS_LAST, customer.getLastName());
values.put(FIELD_CUSTOMERS_ADDRESS, customer.getAddress());
values.put(FIELD_CUSTOMERS_ZIP, customer.getZipCode());
values.put(FIELD_CUSTOMERS_PHONE, customer.getPhoneNumber());
values.put(FIELD_CUSTOMERS_BOOKS, customer.getBooks());
values.put(FIELD_CUSTOMERS_ORDERS, customer.getOrders());
db.update(CUSTOMERS_TABLE, values, CUSTOMERS_KEY_FIELD_ID + " = ?",
new String[]{String.valueOf(customer.getId())});
db.close();
}
public void updateCart(Cart cart) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(FIELD_BOOKS_ID, cart.getBook().getId());
db.update(CART_TABLE, values, FIELD_ID + " = ?",
new String[]{String.valueOf(cart.getId())});
db.close();
}
public void updateOrders(Orders orders)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values= new ContentValues();
values.put(FIELD_ORDERS_CUSTOMER, orders.getCustomer());
values.put(FIELD_ORDERS_EMPLOYEE, orders.getEmployee());
values.put(FIELD_ORDERS_TOTAL, orders.getTotal());
values.put(FIELD_ORDERS_DATE, orders.getDate());
values.put(FIELD_ORDERS_PAYMENT, orders.getPaymentType());
values.put(FIELD_ORDERS_PAID, orders.isPaid());
values.put(FIELD_ORDERS_COMPLETE, orders.isComplete());
db.update(ORDERS_TABLE, values, ORDERS_KEY_FIELD_ID + " = ?",
new String[]{String.valueOf(orders.getId())});
db.close();
}
/*
public void updateUser(User user)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values= new ContentValues();
values.put(FIELD_USER_NAME, user.getUserName());
values.put(FIELD_USER_PASSWORD, user.getPassword());
db.update(USER_TABLE, values, USER_KEY_FIELD_ID + " = ?",
new String[]{String.valueOf(user.getId())});
db.close();
}
*/
// ******************* GET TABLES ***********************
public Book getBook(long id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(
BOOKS_TABLE,
new String[]{BOOKS_KEY_FIELD_ID,
FIELD_BOOKS_TITLE,
FIELD_BOOKS_AUTHOR_LAST,
FIELD_BOOKS_AUTHOR_FIRST,
FIELD_BOOKS_PUBLISHER,
FIELD_BOOKS_PUBLICATION_DATE,
FIELD_BOOKS_EDITION,
FIELD_BOOKS_COST,
FIELD_BOOKS_RETAIL_PRICE,
FIELD_BOOKS_RATING,
FIELD_BOOKS_COVER_TYPE,
FIELD_BOOKS_GENRE},
BOOKS_KEY_FIELD_ID + "=?",
new String[]{String.valueOf(id)},
null, null, null, null);
if(cursor != null) cursor.moveToFirst();
Book book = new Book(cursor.getLong(0),
cursor.getString(1),
cursor.getString(2),
cursor.getString(3),
cursor.getString(4),
cursor.getString(5),
cursor.getString(6),
cursor.getString(7),
cursor.getString(8),
cursor.getFloat(9),
cursor.getString(10),
cursor.getString(11));
cursor.close();
db.close();
return book;
}
/*
public Author getAuthor(int id)
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(
AUTHORS_TABLE,
new String[]{AUTHORS_KEY_FIELD_ID,
FIELD_AUTHORS_LAST,
FIELD_AUTHORS_FIRST,
FIELD_AUTHORS_YEAR_BIRTH,
FIELD_AUTHORS_YEAR_DEATH},
AUTHORS_KEY_FIELD_ID + "=?",
new String[]{String.valueOf(id)},
null, null, null, null);
if(cursor != null) cursor.moveToFirst();
Author author = new Author(cursor.getLong(0),
cursor.getString(1),
cursor.getString(2),
cursor.getString(3),
cursor.getString(4));
cursor.close();
db.close();
return author;
}
*/
public Employee getEmployee(long id)
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(
EMPLOYEES_TABLE,
new String[]{EMPLOYEES_KEY_FIELD_ID,
FIELD_EMPLOYEES_FIRST,
FIELD_EMPLOYEES_LAST,
FIELD_EMPLOYEES_ADDRESS,
FIELD_EMPLOYEES_PHONE,
FIELD_EMPLOYEES_BIRTH,
FIELD_EMPLOYEES_HIRE,
FIELD_EMPLOYEE_SALES,
FIELD_EMPLOYEE_POSITION},
EMPLOYEES_KEY_FIELD_ID + "=?",
new String[]{String.valueOf(id)},
null, null,null, null);
if(cursor != null) cursor.moveToFirst();
Employee employee = new Employee(cursor.getLong(0),
cursor.getString(1),
cursor.getString(2),
cursor.getString(3),
cursor.getString(4),
cursor.getString(5),
cursor.getString(6),
cursor.getString(7),
cursor.getString(8));
cursor.close();
db.close();
return employee;
}
public Customer getCustomer(long id)
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(
CUSTOMERS_TABLE,
new String[]{CUSTOMERS_KEY_FIELD_ID,
FIELD_CUSTOMERS_FIRST,
FIELD_CUSTOMERS_LAST,
FIELD_CUSTOMERS_ADDRESS,
FIELD_CUSTOMERS_ZIP,
FIELD_CUSTOMERS_PHONE,
FIELD_CUSTOMERS_BOOKS,
FIELD_CUSTOMERS_ORDERS},
CUSTOMERS_KEY_FIELD_ID + "=?",
new String[]{String.valueOf(id)},
null, null, null, null);
if(cursor != null) cursor.moveToFirst();
Customer customer = new Customer(cursor.getLong(0),
cursor.getString(1),
cursor.getString(2),
cursor.getString(3),
cursor.getString(4),
cursor.getString(5),
cursor.getString(6),
cursor.getString(7));
cursor.close();
db.close();
return customer;
}
public Orders getOrder(long id)
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(
ORDERS_TABLE,
new String[]{ORDERS_KEY_FIELD_ID,
FIELD_ORDERS_CUSTOMER,
FIELD_ORDERS_EMPLOYEE,
FIELD_ORDERS_TOTAL,
FIELD_ORDERS_DATE,
FIELD_ORDERS_PAYMENT,
FIELD_ORDERS_PAID,
FIELD_ORDERS_COMPLETE},
ORDERS_KEY_FIELD_ID + "=?",
new String[]{String.valueOf(id)},
null, null, null, null);
if(cursor != null) cursor.moveToFirst();
Orders order = new Orders(cursor.getLong(0),
cursor.getString(1),
cursor.getString(2),
cursor.getString(3),
cursor.getString(4),
cursor.getString(5),
Boolean.parseBoolean(cursor.getString(5)),
Boolean.parseBoolean(cursor.getString(6)));
cursor.close();
db.close();
return order;
}
/*
public User getUser(long id)
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(
USER_TABLE,
new String[]{USER_KEY_FIELD_ID,
FIELD_USER_NAME,
FIELD_USER_PASSWORD},
USER_KEY_FIELD_ID + "=?",
new String[]{String.valueOf(id)},
null, null, null, null);
if(cursor != null) cursor.moveToFirst();
User user = new User(cursor.getLong(0),
cursor.getString(1),
cursor.getString(2));
cursor.close();
db.close();
return user;
}
*/
// ******************* DELETE TABLES ***********************
public void deleteCart(Cart cart)
{
SQLiteDatabase db = this.getWritableDatabase();
db.delete(CART_TABLE, FIELD_ID + " = ?",
new String[]{String.valueOf(cart.getId())});
db.close();
}
public void deleteOrder(Orders order) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(ORDERS_TABLE, ORDERS_KEY_FIELD_ID + " = ?",
new String[]{String.valueOf(order.getId())});
db.close();
}
/*
public void deleteUser(User user)
{
SQLiteDatabase db = this.getWritableDatabase();
db.delete(USER_TABLE, FIELD_ID + " = ?",
new String[]{String.valueOf(user.getId())});
db.close();
}
*/
// ******************* DELETE ALL TABLES ***********************
public void deleteAllBooks()
{
SQLiteDatabase db = this.getWritableDatabase();
db.delete(BOOKS_TABLE, null, null);
db.close();
}
/*
public void deleteAllAuthors()
{
SQLiteDatabase db = this.getWritableDatabase();
db.delete(AUTHORS_TABLE, null, null);
db.close();
}
*/
public void deleteAllEmployees()
{
SQLiteDatabase db = this.getWritableDatabase();
db.delete(EMPLOYEES_TABLE, null, null);
db.close();
}
public void deleteAllCustomers()
{
SQLiteDatabase db = this.getWritableDatabase();
db.delete(CUSTOMERS_TABLE, null, null);
db.close();
}
public void deleteAllCarts()
{
SQLiteDatabase db = this.getWritableDatabase();
db.delete(CART_TABLE, null, null);
db.close();
}
public void deleteAllOrders() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(ORDERS_TABLE, null, null);
db.close();
}
/*
public void deleteAllUsers()
{
SQLiteDatabase db = this.getWritableDatabase();
db.delete(USER_TABLE, null, null);
db.close();
}
*/
// ******************* GET ALL TABLES ***********************
public ArrayList<Book> getAllBooks() {
ArrayList<Book> bookList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(
BOOKS_TABLE,
new String[]{BOOKS_KEY_FIELD_ID, FIELD_BOOKS_TITLE, FIELD_BOOKS_AUTHOR_LAST,
FIELD_BOOKS_AUTHOR_FIRST, FIELD_BOOKS_PUBLISHER, FIELD_BOOKS_PUBLICATION_DATE,
FIELD_BOOKS_EDITION, FIELD_BOOKS_COST, FIELD_BOOKS_RETAIL_PRICE, FIELD_BOOKS_RATING,
FIELD_BOOKS_COVER_TYPE, FIELD_BOOKS_GENRE},
null, null, null, null, null, null);
// Collect each row in the table
if(cursor.moveToFirst()) {
do {
Book book = new Book(cursor.getLong(0),
cursor.getString(1),
cursor.getString(2),
cursor.getString(3),
cursor.getString(4),
cursor.getString(5),
cursor.getString(6),
cursor.getString(7),
cursor.getString(8),
cursor.getFloat(9),
cursor.getString(10),
cursor.getString(11));
bookList.add(book);
} while (cursor.moveToNext());
}
return bookList;
}
/*
public ArrayList<Author> getAllAuthors() {
ArrayList<Author> authorList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(
AUTHORS_TABLE,
new String[]{AUTHORS_KEY_FIELD_ID, FIELD_AUTHORS_LAST, FIELD_AUTHORS_FIRST,
FIELD_AUTHORS_YEAR_BIRTH, FIELD_AUTHORS_YEAR_DEATH},
null, null, null, null, null, null);
// Collect each row in the table
if(cursor.moveToFirst()) {
do {
Author author = new Author(cursor.getLong(0),
cursor.getString(1),
cursor.getString(2),
cursor.getString(3),
cursor.getString(4));
authorList.add(author);
} while (cursor.moveToNext());
}
return authorList;
}
*/
public ArrayList<Employee> getAllEmployees() {
ArrayList<Employee> employeeList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(
EMPLOYEES_TABLE,
new String[]{EMPLOYEES_KEY_FIELD_ID, FIELD_EMPLOYEES_FIRST, FIELD_EMPLOYEES_LAST,
FIELD_EMPLOYEES_ADDRESS, FIELD_EMPLOYEES_PHONE,
FIELD_EMPLOYEES_BIRTH, FIELD_EMPLOYEES_HIRE,
FIELD_EMPLOYEE_SALES, FIELD_EMPLOYEE_POSITION},
null, null, null, null, null, null);
// Collect each row in the table
if(cursor.moveToFirst()) {
do {
Employee employee = new Employee(cursor.getLong(0),
cursor.getString(1),
cursor.getString(2),
cursor.getString(3),
cursor.getString(4),
cursor.getString(5),
cursor.getString(6),
cursor.getString(7),
cursor.getString(8));
employeeList.add(employee);
} while (cursor.moveToNext());
}
return employeeList;
}
public ArrayList<Customer> getAllCustomers() {
ArrayList<Customer> customerList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(
CUSTOMERS_TABLE,
new String[]{CUSTOMERS_KEY_FIELD_ID, FIELD_CUSTOMERS_FIRST, FIELD_CUSTOMERS_LAST,
FIELD_CUSTOMERS_ADDRESS, FIELD_CUSTOMERS_ZIP,
FIELD_CUSTOMERS_PHONE, FIELD_CUSTOMERS_BOOKS,
FIELD_CUSTOMERS_ORDERS},
null, null, null, null, null, null);
// Collect each row in the table
if(cursor.moveToFirst()) {
do {
Customer customer = new Customer(cursor.getLong(0),
cursor.getString(1),
cursor.getString(2),
cursor.getString(3),
cursor.getString(4),
cursor.getString(5),
cursor.getString(6),
cursor.getString(7));
customerList.add(customer);
} while (cursor.moveToNext());
}
return customerList;
}
public ArrayList<Cart> getAllCart() {
ArrayList<Cart> cartList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(
CART_TABLE,
new String[]{FIELD_ID, FIELD_BOOKS_ID},
null,
null,
null,
null, null, null);
if(cursor.moveToFirst()) {
do {
Book book = getBook(cursor.getLong(1));
Cart newCart = new Cart(cursor.getInt(0), book);
cartList.add(newCart);
} while(cursor.moveToNext());
}
cursor.close();
db.close();
return cartList;
}
public ArrayList<Orders> getAllOrders() {
ArrayList<Orders> ordersList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(
ORDERS_TABLE,
new String[]{ORDERS_KEY_FIELD_ID, FIELD_ORDERS_CUSTOMER, FIELD_ORDERS_EMPLOYEE,
FIELD_ORDERS_TOTAL, FIELD_ORDERS_DATE, FIELD_ORDERS_PAYMENT,
FIELD_ORDERS_PAID, FIELD_ORDERS_COMPLETE},
null, null, null, null, null, null);
// Collect each row in the table
if(cursor.moveToFirst()) {
do {
Orders orders = new Orders(cursor.getLong(0),
cursor.getString(1),
cursor.getString(2),
cursor.getString(3),
cursor.getString(4),
cursor.getString(5),
Boolean.parseBoolean(cursor.getString(5)),
Boolean.parseBoolean(cursor.getString(6)));
ordersList.add(orders);
} while (cursor.moveToNext());
}
return ordersList;
}
/*
public ArrayList<User> getAllUsers() {
ArrayList<User> userList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(
USER_TABLE,
new String[]{USER_KEY_FIELD_ID, FIELD_USER_NAME, FIELD_USER_PASSWORD},
null, null, null, null, null, null);
// Collect each row in the table
if(cursor.moveToFirst()) {
do {
User user = new User(cursor.getLong(0),
cursor.getString(1),
cursor.getString(2));
userList.add(user);
} while (cursor.moveToNext());
}
return userList;
}
*/
// ******************* IMPORT FROM CSV ***********************
public boolean importBooksFromCSV(String csvFileName) {
AssetManager am = mContext.getAssets();
InputStream inStream;
try {
inStream = am.open(csvFileName);
}
catch (IOException e) {
e.printStackTrace();
return false;
}
BufferedReader buffer = new BufferedReader(new InputStreamReader(inStream));
String line;
try {
while ((line = buffer.readLine()) != null) {
String[] fields = line.split(",");
if (fields.length != 12) {
Log.d("Book Finder", "Skipping Bad CSV Row: " + Arrays.toString(fields));
continue;
}
int id = Integer.parseInt(fields[0].trim());
String title = fields[1].trim();
String authorFirst = fields[2].trim();
String authorLast = fields[3].trim();
String publisher = fields[4].trim();
String publishDate = fields[5].trim();
String edition = fields[6].trim();
String cost = fields[7].trim();
String retailPrice = fields[8].trim();
String r = fields[9].trim();
float rating = Float.valueOf(r);
String coverType = fields[10].trim();
String genre = fields[11].trim();
addBook(new Book(id, title, authorFirst,
authorLast, publisher, publishDate,
edition, cost, retailPrice,
rating, coverType, genre));
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
public boolean importEmployeesFromCSV(String csvFileName) {
AssetManager am = mContext.getAssets();
InputStream inStream;
try {
inStream = am.open(csvFileName);
}
catch (IOException e) {
e.printStackTrace();
return false;
}
BufferedReader buffer = new BufferedReader(new InputStreamReader(inStream));
String line;
try {
while ((line = buffer.readLine()) != null) {
String[] fields = line.split(",");
if (fields.length != 9) {
Log.d("Employees Finder", "Skipping Bad CSV Row: " + Arrays.toString(fields));
continue;
}
int id = Integer.parseInt(fields[0].trim());
String employeeFirst = fields[1].trim();
String employeeLast = fields[2].trim();
String employeeAddress = fields[3].trim();
String employeePhone = fields[4].trim();
String employeeBirth = fields[5].trim();
String employeeHire = fields[6].trim();
String employeeSales = fields[7].trim();
String employeePosition = fields[8].trim();
addEmployee(new Employee(id, employeeFirst, employeeLast,
employeeAddress, employeePhone, employeeBirth,
employeeHire, employeeSales, employeePosition));
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
public boolean importCustomersFromCSV(String csvFileName) {
AssetManager am = mContext.getAssets();
InputStream inStream;
try {
inStream = am.open(csvFileName);
}
catch (IOException e) {
e.printStackTrace();
return false;
}
BufferedReader buffer = new BufferedReader(new InputStreamReader(inStream));
String line;
try {
while ((line = buffer.readLine()) != null) {
String[] fields = line.split(",");
if (fields.length != 8) {
Log.d("Customers Finder", "Skipping Bad CSV Row: " + Arrays.toString(fields));
continue;
}
int id = Integer.parseInt(fields[0].trim());
String customerFirst = fields[1].trim();
String customerLast = fields[2].trim();
String customerAddress = fields[3].trim();
String customerZip = fields[4].trim();
String customerPhone = fields[5].trim();
String customerBooks = fields[6].trim();
String customerOrders = fields[7].trim();
addCustomer(new Customer(id, customerFirst, customerLast,
customerAddress, customerZip, customerPhone,
customerBooks, customerOrders));
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
public boolean importOrdersFromCSV(String csvFileName) {
AssetManager am = mContext.getAssets();
InputStream inStream;
try {
inStream = am.open(csvFileName);
}
catch (IOException e) {
e.printStackTrace();
return false;
}
BufferedReader buffer = new BufferedReader(new InputStreamReader(inStream));
String line;
try {
while ((line = buffer.readLine()) != null) {
String[] fields = line.split(",");
if (fields.length != 8) {
Log.d("Orders Finder", "Skipping Bad CSV Row: " + Arrays.toString(fields));
continue;
}
int id = Integer.parseInt(fields[0].trim());
String ordersCustomer = fields[1].trim();
String ordersEmployee = fields[2].trim();
String ordersTotal = fields[3].trim();
String ordersDate = fields[4].trim();
String ordersPayment = fields[5].trim();
String ordersPaid = fields[5].trim();
String ordersComplete = fields[6].trim();
addOrders(new Orders(id, ordersCustomer, ordersEmployee,
ordersTotal, ordersDate, ordersPayment,
Boolean.parseBoolean(ordersPaid),
Boolean.parseBoolean(ordersComplete)));
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
/*
public boolean importUserFromCSV(String csvFileName) {
AssetManager am = mContext.getAssets();
InputStream inStream;
try {
inStream = am.open(csvFileName);
}
catch (IOException e) {
e.printStackTrace();
return false;
}
BufferedReader buffer = new BufferedReader(new InputStreamReader(inStream));
String line;
try {
while ((line = buffer.readLine()) != null) {
String[] fields = line.split(",");
if (fields.length != 3) {
Log.d("User Finder", "Skipping Bad CSV Row: " + Arrays.toString(fields));
continue;
}
int id = Integer.parseInt(fields[0].trim());
String userName = fields[1].trim();
String userPassword = fields[2].trim();
addUser(new User(id, userName, userPassword));
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
*/
// ******************* EXPORT TO CSV ***********************
}
|
package modnlp.tc.clasify;
import modnlp.tc.parser.*;
import modnlp.tc.dstruct.*;
import modnlp.tc.evaluation.*;
import modnlp.tc.util.*;
import java.util.Set;
import java.util.Enumeration;
import java.util.Iterator;
/**
* Document-size normalised Naive Bayes classifier for documents
* represented as Boolean vectors. This class uses the CSV described
* in (Sebastiani, 2002). CSV values are not probabilities but the
* function is monotonically increasing on the estimated probability
* function. In standard BVBayes, larger documents will tend to get
* disproportionally large CSV scores. DSNormalisedBayes tackles this
* problem by taking into account the size to the document when
* computing CSV.
*
* NB: For aggressively reduced term sets, document-size
* normalisation (dsn) doesn't seem to yield any improvement in
* classification. On the contrary, it seems to worsen things,
* slightly. However, for lightly reduced term sets (say, agrr = 100), dsn
* greatly improves accuracy.
*
* Categorise each news item in corpus_list according to categ using
* Boolean Vector Naive Bayes (see lecture notes ctinduction.pdf, p 7)
*
* Usage:
* <pre>
DSNormalisedBayes corpus_list categ prob_model
SYNOPSIS:
Categorise each news item in corpus_list according to categ using
Boolean Vector Naive Bayes (see lecture notes ctinduction.pdf, p 7)
ARGUMENTS
corpus_list: list of files to be classified
categ: target category (e.g. 'acq'.) The classifier will define CSV
as CSV_{categ}
pmfile: file containing a probability model generated via, say,
modnlp.tc.induction.MakeProbabilityModel.
</pre>
* @author Saturnino Luz <luzs@acm.org>
* @version <font size=-1>$Id: DSNormalisedBayes.java,v 1.1 2005/08/20 12:48:30 druid Exp $</font>
* @see BVProbabilityModel
* @see NewsParser
*/
public class DSNormalisedBayes
{
private CorpusList clist = null;
private BVProbabilityModel pm = null;
/**
* Set up the main user interface items
*/
public DSNormalisedBayes(String clist, String pmfile) {
super();
this.clist = new CorpusList(clist);
this.pm = (BVProbabilityModel)IOUtil.loadProbabilityModel(pmfile);
return;
}
/**
* pars: Set up a new parser object of type <code>plugin</code>, perform
* parsing, and return a ParsedCorpus
*
* @param filename the file to be parsed
* @param plugin the parser class name
* @return a <code>ParsedCorpus</code>
* @exception Exception if an error occurs
*/
public ParsedCorpus parse (String filename, String plugin) throws Exception
{
Parser np = IOUtil.loadParserPlugin(plugin);
np.setFilename(filename);
return np.getParsedCorpus();
}
/** CSV_i(d_j) = \sum_0^T tkj log p(t|c) * (1 - p(t|ยฌc) / p(t|ยฌc) * (1 - p(t|c)
*
* (where tkj \in {0, 1} is the binary weight at position k in
* vector d_j; multiplying by it causes terms that do not occur in
* the document to be ignored)
*/
public double computeCSV(String cat, ParsedDocument pni){
double csv = 0;
boolean barcat = false;
if ( Tokenizer.isBar(cat) ){
cat = Tokenizer.disbar(cat);
barcat = true;
}
SetOfWords sov = new SetOfWords(pni.getText());
for (Iterator e = sov.iterator(); e.hasNext() ; ) {
String term = (String)e.next();
if (! pm.containsTerm(term) )
continue;
Probabilities p = pm.getProbabilities(term, cat);
// traversing the set of terms that occur in the docment, so no need to multiply by tkj
// first compute CSV based on p(d|c)
csv += Maths.safeLog2((p.getPTgivenC() * (1 - p.getPTgiven_C()))
/ (p.getPTgiven_C() * (1 - p.getPTgivenC())));
}
if ( barcat )
// CSV based on p(d|ยฌc):
// if pcsv =def p(t|c) * (1 - p(t|ยฌc)) / p(t|ยฌc) * (1 - p(t|c))
// then that's simply log( 1 / pcsv ) = -log(pcsv)
return -1 * csv/(double) sov.size();
return csv/(double) sov.size();
}
public static void main(String[] args) {
try {
String clistfn = args[0];
String category = args[1];
String pmfile = args[2];
String tmethod = args[3];
String parser = args.length > 4 ? args[4] : "NewsParser";
System.err.println("Loading probability model...");
DSNormalisedBayes f = new DSNormalisedBayes(clistfn, pmfile);
CSVTable csvt = new CSVTable(category);
for (Enumeration e = f.clist.elements(); e.hasMoreElements() ;)
{
String fname = (String)e.nextElement();
System.err.print("\n----- Processing: "+fname+" ------\n");
ParsedCorpus pt = f.parse(fname,parser);
int i = 1;
for (Enumeration g = pt.elements(); g.hasMoreElements() ;){
PrintUtil.printNoMove("Classifying ...", i++);
ParsedDocument pni = (ParsedDocument)g.nextElement();
double csv = f.computeCSV(category, pni);
csvt.setCSV(pni.getId(), csv);
if (pni.isOfCategory(category))
csvt.addToTargetDocSet(pni.getId());
}
PrintUtil.donePrinting();
}
System.out.println("TARGET DOCS for "+category+": "+csvt.getTargetDocSet());
System.out.println("CSV RESULTS:\n"+csvt);
Set selected = csvt.applyThreshold(tmethod, f.pm.getCatGenerality(category));
System.out.println("SELECTED DOCS:\n"+selected);
System.out.println("EFFECTIVENESS:\n"
+" accuracy = "+csvt.getAccuracy()
+" precision = "+csvt.getPrecision()
+" recall = "+csvt.getRecall()
);
}
catch (Exception e){
System.err.println("USAGE:");
System.err.println(" DSNormalisedBayes corpus_list categ prob_model threshold\n");
System.err.println("SYNOPSIS:");
System.err.println(" Categorise each news item in corpus_list according to categ using");
System.err.println(" Boolean Vector Naive Bayes (see lecture notes ctinduction.pdf, p 7)\n");
System.err.println("ARGUMENTS:");
System.err.println(" corpus_list: list of files to be classified\n");
System.err.println(" categ: target category (e.g. 'acq'.) The classifier will define CSV ");
System.err.println(" as CSV_{categ}\n");
System.err.println(" pmfile: file containing a probability model generated via, say, ");
System.err.println(" modnlp.tc.induction.MakeProbabilityModel.\n");
System.err.println(" threshold: a real number (for RCut thresholding) or the name of a");
System.err.println(" thresholding strategy. Currently supported strategies:");
System.err.println(" - 'proportional': choose threshold s.t. that g_Tr(ci) is");
System.err.println(" closest to g_Tv(ci). [DEFAULT]");
System.err.println(" - ...");
System.err.println(" PARSER: parser to be used [default: 'news']");
System.err.println(" see modnlp.tc.parser.* for other options ");
e.printStackTrace();
}
}
}
|
package com.bicjo.sample.user;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.springframework.hateoas.EntityLinks;
import org.springframework.hateoas.ExposesResourceFor;
import org.springframework.hateoas.Resources;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping(value = "/users")
@ExposesResourceFor(User.class)
public class UserController {
private final EntityLinks entityLinks;
public UserController(EntityLinks entityLinks) {
this.entityLinks = entityLinks;
}
@GetMapping(produces = { MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<Resources<UserResource>> getUsers() {
List<ContactResource> contactResources = new ArrayList<>();
contactResources.add(new ContactResource("1234567890"));
contactResources.add(new ContactResource("0987654321"));
List<UserResource> userResources = new ArrayList<>();
userResources.add(new UserResource("Joven", new Resources<>(contactResources)));
userResources.add(new UserResource("Rose", new Resources<>(contactResources)));
userResources.add(new UserResource("Chance", new Resources<>(contactResources)));
Resources<UserResource> resources = new Resources<>(userResources);
resources.add(entityLinks.linkToCollectionResource(User.class));
return new ResponseEntity<>(resources, HttpStatus.OK);
}
@GetMapping(value = "/{uid}", //
produces = { MediaType.APPLICATION_JSON_VALUE, "application/hal+json" } //
)
public ResponseEntity<UserResource> getUser(@PathVariable(name = "uid") String userId) {
UserResource resource = new UserResource("Joven", new Resources<>(Collections.emptyList()));
resource.add(//
entityLinks.linkToSingleResource(User.class, userId) //
);
return ResponseEntity.ok(resource);
}
}
|
package tests.android;
import baseplatformANDROID.BaseTest;
import baseplatform.DataClass;
import objects.android.MainViewDR;
import org.testng.annotations.*;
import static java.lang.System.getProperty;
import static org.testng.Assert.assertTrue;
public class AddNameInputFieldTest extends BaseTest {
private MainViewDR mv;
private int testCount = 1;
@BeforeClass
public void setUpLaunching() {
mv = new MainViewDR(driver);
}
@BeforeMethod
public void onStartingMethodWithinClass() {
System.out.println("\033[0;95m" + this.getClass().getSimpleName() +
" --- Test Count = " + testCount + "\033[0m");
testCount++;
//driver.launchApp();
}
@AfterMethod
public void onFinishingMethodWithinCLass() {
mv.editNameFieldClear();
//driver.closeApp();
}
@Test(dataProvider = "riderName-Provider-3", dataProviderClass = DataClass.class,
description = "Verify that the \"Add Name\" field on main screen accepts case sensitive chars, " +
"Verify that the \"Add Name\" field on main screen supports multilanguage," +
"Verify that \"Add Name\" field on main screen accepts digits," +
"Verify that \"Add Name\" field on main screen accepts special chars," +
"Verify that the \"Add Name\" field on main screen accepts emoji," +
"Verify that the \"Add Name\" field on main screen accepts case sensitive chars, digits, special chars, emoji and double byte chars," +
"Verify that the \"Add Name\" field on main accepts 64 chars the most")
public void acceptVarietyValuesTest(String riderNameValue) {
String theName = null;
mv.inputNameIntoField(riderNameValue);
theName = String.join(" ", mv.gettingNameFromNameField());
assertTrue(theName.equals(riderNameValue), "Test failed");
/* System.out.println("riderNameValue: " + riderNameValue);
System.out.println("The Add Name field is filled with " + String.join("", theName));
*/
}
@Test(dataProvider = "riderName-Provider-4", dataProviderClass = DataClass.class,
description ="Verify that the \"Add Name\" field on main screen does not accept 65 or more chars")
public void acceptMorethan64CharsValueTest(String riderNameMoreThan64CharsValue) {
String theName = null;
String theCuttedName;
if (riderNameMoreThan64CharsValue.length() > 64) {
theCuttedName = riderNameMoreThan64CharsValue.substring(0, 64);
} else {
theCuttedName = riderNameMoreThan64CharsValue;
}
mv.inputNameIntoField(riderNameMoreThan64CharsValue);
theName = String.join(" ", mv.gettingNameFromNameField());
System.out.println("\033[0;95m riderNameMoreThan64CharsValue: " + riderNameMoreThan64CharsValue + "\033[0m");
System.out.println("\033[0;95m theCuttedName: " + theCuttedName + "\033[0m");
System.out.println("\033[0;95m The Add Name field is filled with " + String.join("", theName) + "\033[0m");
assertTrue(theName.equals(theCuttedName), "Test failed");
}
}
|
package com.wrathOfLoD.Models.Map.AreaEffect;
import com.wrathOfLoD.Models.Entity.Entity;
import com.wrathOfLoD.VisitorInterfaces.AreaEffectVisitor;
/**
* Created by luluding on 4/16/16.
*/
public class InstantDeathAreaEffect extends AreaEffect{
public InstantDeathAreaEffect(String name){
super(name);
}
@Override
public void interact(Entity entity) {
entity.die();
}
public void accept(AreaEffectVisitor aev){
aev.visitInstantDeathAreaEffect(this);
}
}
|
package com.cww.pojo;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Date;
public class Note {
private Integer id;
private Date date;
private Integer order;
private Integer themes;
private Integer comsumerId;
private String desc;
public Integer getComsumerId() {
return comsumerId;
}
public void setComsumerId(Integer comsumerId) {
this.comsumerId = comsumerId;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Integer getOrder() {
return order;
}
public void setOrder(Integer order) {
this.order = order;
}
public Integer getThemes() {
return themes;
}
public void setThemes(Integer themes) {
this.themes = themes;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public Note(Integer id, Date date, Integer order, Integer themes, Integer comsumerId, String desc) {
super();
this.id = id;
this.date = date;
this.order = order;
this.themes = themes;
this.comsumerId = comsumerId;
this.desc = desc;
}
public Note() {
super();
}
}
|
package com.ar.ui.views.error;
import com.vaadin.data.Item;
import com.vaadin.data.fieldgroup.FieldGroup;
import com.vaadin.data.util.ObjectProperty;
import com.vaadin.data.util.PropertysetItem;
import com.vaadin.data.validator.StringLengthValidator;
import com.vaadin.server.DefaultErrorHandler;
import com.vaadin.server.UserError;
import com.vaadin.shared.ui.label.ContentMode;
import com.vaadin.ui.*;
/**
* Created by joan on 13/10/15.
*/
public class Example {
public void errorhandler(final VerticalLayout root) {
// BEGIN-EXAMPLE: application.errors.error-indicator.errorhandler
// Here's some code that produces an uncaught exception
final VerticalLayout layout = new VerticalLayout();
final Button button = new Button("Click Me!",
new Button.ClickListener() {
private static final long serialVersionUID = -3138442059473438237L;
public void buttonClick(Button.ClickEvent event) {
((String)null).length(); // Null-pointer exception
}
});
layout.addComponent(button);
// Configure the error handler for the entire UI
UI.getCurrent().setErrorHandler(new DefaultErrorHandler() {
private static final long serialVersionUID = 3526469128352984806L;
@Override
public void error(com.vaadin.server.ErrorEvent event) {
String cause = "<b>The click ";
// Find the component causing the error
AbstractComponent c = findAbstractComponent(event);
if (c != null)
cause += "on a " + c.getClass().getSimpleName();
// Find the final cause
cause += " failed because:</b><br/>";
for (Throwable t = event.getThrowable(); t != null;
t = t.getCause())
if (t.getCause() == null) // We're at final cause
cause += t.getClass().getName() + "<br/>";
// Display the error message in a custom fashion
layout.addComponent(new Label(cause, ContentMode.HTML));
// Do the default error handling (optional)
doDefault(event);
}
});
// END-EXAMPLE: application.errors.error-indicator.errorhandler
root.addComponent(layout);
}
public void form(VerticalLayout layout) {
class MyForm extends CustomComponent {
private static final long serialVersionUID = 8893447767363695369L;
TextField name = new TextField("Name");
public MyForm(Item item) {
setCaption("My Form");
VerticalLayout content = new VerticalLayout();
// Configure fields
name.setRequired(true);
name.setRequiredError("Must be given");
name.addValidator(new StringLengthValidator("Too long", 0, 5, true));
name.setImmediate(true);
name.setValidationVisible(true);
// Build the form
FormLayout form = new FormLayout();
form.addComponent(name);
content.addComponent(form);
// Bind the form
final ErrorfulFieldGroup binder = new ErrorfulFieldGroup(item);
binder.setBuffered(true);
binder.bindMemberFields(this);
// Have an error display
final ErrorLabel formError = new ErrorLabel();
formError.setWidth(null);
content.addComponent(formError);
binder.setErrorDisplay(formError);
// Commit button
Button ok = new Button("OK");
ok.addClickListener(new Button.ClickListener() {
private static final long serialVersionUID = -5285421385946833355L;
@Override
public void buttonClick(Button.ClickEvent event) {
try {
binder.commit();
} catch (FieldGroup.CommitException e) {
}
}
});
content.addComponent(ok);
setCompositionRoot(content);
}
}
PropertysetItem item = new PropertysetItem();
item.addItemProperty("name", new ObjectProperty<String>(""));
MyForm form = new MyForm(item);
layout.addComponent(form);
///////////////////////////
// The old Vaadin 6 way
final Form oldForm = new Form();
oldForm.setBuffered(true);
oldForm.setCaption("Vaadin 6 Form");
TextField name = new TextField("Name");
name.setRequired(true);
name.setRequiredError("Must not be empty");
name.addValidator(new StringLengthValidator("Too long", 0, 5, true));
name.setImmediate(true);
oldForm.addField("name", name);
// Have a component that fires click events
final Button button = new Button("Click Me!");
oldForm.getFooter().addComponent(button);
// When clicked, set the form error
button.addClickListener(new Button.ClickListener() {
private static final long serialVersionUID = -3138442059473438237L;
public void buttonClick(Button.ClickEvent event) {
oldForm.setComponentError(new UserError("Bad click"));
}
});
layout.addComponent(oldForm);
// END-EXAMPLE: application.errors.error-indicator.form
layout.setSpacing(true);
}
}
|
package application;
import javafx.scene.input.KeyCode;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
public class Box {
public Rectangle rect;
public XShape xshape;
public OShape oshape;
public boolean hasShape;
public boolean highlighted;
public Box() {
xshape = new XShape();
oshape = new OShape();
}
public void highlight() {
if(!highlighted) {
rect.setStroke(Color.RED);
highlighted = true;
}
else {
rect.setStroke(Color.BLACK);
highlighted = false;
}
}
public void clear() {
}
public void setShape(String key) {
if (key.equalsIgnoreCase("o")){
this.oshape.setVisibility(true);
this.hasShape=true;
}
if (key.equalsIgnoreCase("x")){
this.xshape.setVisibility(true);
this.hasShape=true;
}
}
}
|
package com.zjf.myself.codebase.dialog;
import android.text.Spanned;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.zjf.myself.codebase.R;
import com.zjf.myself.codebase.util.CallBack;
import com.zjf.myself.codebase.util.DesityUtil;
public class TipsDialog extends BaseDialog implements View.OnClickListener{
private Button btnOk;
private CallBack callBack;
private TextView txtMsg,txtTitle;
private boolean isShowAnimation,isShowTitle=false;
private View layoutTitle;
@Override
protected void initView() {
dialogWindow.getDecorView().setPadding(DesityUtil.dp2px(getContext(),30),0,DesityUtil.dp2px(getContext(),30),0);
btnOk=(Button) findViewById(R.id.btn_ok);
txtMsg= (TextView) findViewById(R.id.txt_msg);
btnOk.setOnClickListener(this);
layoutTitle=findViewById(R.id.layout_title);
txtTitle=(TextView) findViewById(R.id.txtTitle);
}
public Button getOkbutton(){
return btnOk;
}
public TextView getContextText(){
return txtMsg;
}
public TextView getTitle(){
return txtTitle;
}
public void setIsShowTitle(boolean isShowTitle){
this.isShowTitle=isShowTitle;
}
@Override
protected boolean isShowAnimation() {
return isShowAnimation;
}
public void setIsShowAnimation(boolean isShowAnimation){
this.isShowAnimation=isShowAnimation;
}
@Override
public int getLayoutId() {
return R.layout.dialog_tips;
}
@Override
public int getGravity() {
return Gravity.CENTER;
}
public void show(CallBack callBack,Spanned msg) {
super.show();
this.callBack=callBack;
txtMsg.setText(msg);
}
public void show(String title,String msg,CallBack callBack) {
super.show();
this.callBack=callBack;
txtTitle.setText(title);
txtMsg.setText(msg);
}
public void show(CallBack callBack) {
if(isShowTitle)
layoutTitle.setVisibility(View.VISIBLE);
super.show();
this.callBack=callBack;
}
@Override
public void onClick(View v) {
if(v==btnOk)
{
this.callBack.onCall(null);
}
dismiss();
}
}
|
package org.mytvstream.converter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class Converter extends Thread implements IConverter {
private final Logger logger = LoggerFactory.getLogger(Converter.class);
protected boolean closed = false;
public void close() {
if (isAlive()) {
this.closed = true;
logger.debug("Closing current converter");
try {
join(2000);
} catch (InterruptedException e) {
logger.error("Timeout error waiting for converter to close :" + e.getMessage());
}
}
}
public void run() {
try {
mainLoop();
} catch (ConverterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* The main loop for the conversion, not implemented in converter.
* @throws ConverterException
*/
abstract protected void mainLoop() throws ConverterException;
/**
* Determine if the converter can handle a particular conversion
* @param inputUrl : The input URL to process
* @param inputType : The input format type
* @param outputUrl : The output URL to process
* @param outputType : The output format type.
* @return
*/
abstract protected boolean CanHandle(String inputUrl, ConverterFormatEnum inputFormat, String outputUrl, ConverterFormatEnum outputFormat);
}
|
package com.lmz.javabase;
public class InAndOut {
}
|
package com.example.canyetismis.coursework2;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.example.canyetismis.coursework2.MP3Player.MP3PlayerState;
public class MP3Service extends Service {
MP3Player player = new MP3Player();
private final IBinder binder = new MP3Binder();
private final String CHANNEL_ID = "100";
int NOTIFICATION_ID = 001;
public MP3Service() {
}
@Override
public IBinder onBind(Intent intent) {
return binder;
}
public class MP3Binder extends Binder{
void pause(){MP3Service.this.pause();}
void play(){MP3Service.this.play();}
void stop(){MP3Service.this.stop();}
void load(String s){MP3Service.this.load(s);}
void stopNotification(){MP3Service.this.stopNotification();}
int getDuration(){
int i = (player.getDuration()/1000);
return i;
}
int getProgress(){
int i =(player.getProgress()/1000);
return i;
}
MP3PlayerState getState(){
MP3PlayerState str = player.getState();
return str;
}
void createNotificationChannel(){MP3Service.this.createNotificationChannel();}
}
private void pause(){
Log.d("g53mdp", "pause");
player.pause();
}
private void play(){
Log.d("g53mdp", "play");
player.play();
}
private void stop(){
Log.d("g53mdp", "stop");
player.stop();
}
private void load(String song){
if(player.getState() == MP3PlayerState.PLAYING){
player.stop();
}
player.load(song);
}
private void createNotificationChannel(){
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "Music Player";
String description = "Playing music...";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name,
importance);
channel.setDescription(description);
notificationManager.createNotificationChannel(channel);
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this,
CHANNEL_ID)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle("Music Player")
.setContentText("Playing music...")
.setContentIntent(pendingIntent)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
startForeground(NOTIFICATION_ID, mBuilder.build());
}
}
private void stopNotification(){
stopForeground(true);
stopSelf();
}
}
|
package com.mycompany.task_1;
public class Child extends Parent {
public static void child()
{
System.out.println("ะกัะฐัะธัะตัะบะธะน ะฑะปะพะบ ะบะปะฐััะฐ Child");
}
/*public void childA()
{
System.out.println("ะะต ััะฐัะธัะตัะบะธะน ะผะตัะพะด ะบะปะฐััะฐ Child");
}*/
Child(String s) {
super(s);
}
}
|
package mulitThread.chapter02.t2_2_16.p1;
public class ThreadA extends Thread {
MyService service;
public ThreadA(MyService service) {
this.service = service;
}
public void run() {
try {
this.service.testMethod();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package com.getkhaki.api.bff.persistence.repositories;
import com.getkhaki.api.bff.persistence.models.OrganizationDao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
@Repository
public interface OrganizationRepositoryInterface extends JpaRepository<OrganizationDao, UUID> {
Optional<OrganizationDao> findDistinctByName(String name);
Optional<OrganizationDao> findById(UUID id);
List<OrganizationDao> findByAdminEmailId(UUID id);
}
|
package com.getkhaki.api.bff.persistence;
import com.getkhaki.api.bff.domain.models.OrganizationDm;
import com.getkhaki.api.bff.persistence.models.DomainDao;
import com.getkhaki.api.bff.persistence.models.EmailDao;
import com.getkhaki.api.bff.persistence.models.OrganizationDao;
import com.getkhaki.api.bff.persistence.repositories.OrganizationRepositoryInterface;
import lombok.val;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.modelmapper.ModelMapper;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
public class OrganizationPersistenceServiceUnitTests {
@Mock
private OrganizationRepositoryInterface organizationRepository;
@Mock
EmailDaoService emailDaoService;
@Mock
private ModelMapper modelMapper;
@InjectMocks
private OrganizationPersistenceService underTest;
@Test
public void success_getImportEnabledOrganizations() {
val daoOrgSet = Stream.of(
new OrganizationDao().setName("Billy"),
new OrganizationDao().setName("Red Barchetta")
).collect(Collectors.toSet());
val dmOrgSet = Stream.of(
new OrganizationDm().setName("Billy"),
new OrganizationDm().setName("Red Barchetta")
).collect(Collectors.toSet());
val dmSetItr = dmOrgSet.iterator();
when(organizationRepository.findAll()).thenReturn(new ArrayList<>(daoOrgSet));
daoOrgSet.forEach(
organizationDao -> when(modelMapper.map(organizationDao, OrganizationDm.class))
.thenReturn(dmSetItr.next())
);
val orgs = underTest.getImportEnabledOrganizations();
assertThat(orgs).hasSize(2);
assertThat(orgs).extracting(OrganizationDm::getName).contains("Billy");
assertThat(orgs).extracting(OrganizationDm::getName).contains("Red Barchetta");
}
@Test
public void upsertOrganization_notFound() {
var mockOrganizationDm = mock(OrganizationDm.class);
var mockEmailDao = mock(EmailDao.class);
var mockDomainDao = mock(DomainDao.class);
var mockOrganizationDao = mock(OrganizationDao.class);
var mockPersistedOrganizationDao = mock(OrganizationDao.class);
var mockMappedOrganizationDm = mock(OrganizationDm.class);
when(this.emailDaoService.upsertByEmailString(mockOrganizationDm.getAdminEmail()))
.thenReturn(mockEmailDao);
when(mockEmailDao.getDomain()).thenReturn(mockDomainDao);
when(mockDomainDao.setOrganization(mockOrganizationDao)).thenReturn(mockDomainDao);
when(this.modelMapper.map(mockOrganizationDm, OrganizationDao.class))
.thenReturn(mockOrganizationDao);
when(this.organizationRepository.findDistinctByName(mockOrganizationDao.getName()))
.thenReturn(Optional.empty());
when(mockOrganizationDao.setAdminEmail(mockEmailDao)).thenReturn(mockOrganizationDao);
when(mockOrganizationDao.setDomains(List.of(mockEmailDao.getDomain()))).thenReturn(mockOrganizationDao);
when(this.organizationRepository.save(mockOrganizationDao))
.thenReturn(mockPersistedOrganizationDao);
when(this.modelMapper.map(mockPersistedOrganizationDao, OrganizationDm.class))
.thenReturn(mockMappedOrganizationDm);
OrganizationDm result = this.underTest.upsertOrganization(mockOrganizationDm);
assertThat(result.getName()).isEqualTo(mockOrganizationDm.getName());
assertThat(result.getAdminEmail()).isEqualTo(mockEmailDao.getEmailString());
assertThat(result.getDepartments()).isEqualTo(mockOrganizationDm.getDepartments());
}
@Test
public void upsertOrganization_found() {
var mockOrganizationDm = mock(OrganizationDm.class);
var mockEmailDao = mock(EmailDao.class);
var mockDomainDao = mock(DomainDao.class);
var mockOrganizationDao = mock(OrganizationDao.class);
var mockFoundOrganizationDao = mock(OrganizationDao.class);
var mockPersistedOrganizationDao = mock(OrganizationDao.class);
var mockMappedOrganizationDm = mock(OrganizationDm.class);
when(this.emailDaoService.upsertByEmailString(mockOrganizationDm.getAdminEmail()))
.thenReturn(mockEmailDao);
when(mockEmailDao.getDomain()).thenReturn(mockDomainDao);
when(this.modelMapper.map(mockOrganizationDm, OrganizationDao.class))
.thenReturn(mockOrganizationDao);
when(this.organizationRepository.findDistinctByName(mockOrganizationDao.getName()))
.thenReturn(Optional.of(mockFoundOrganizationDao));
when(mockOrganizationDao.setAdminEmail(mockEmailDao)).thenReturn(mockOrganizationDao);
when(mockOrganizationDao.setDomains(any(List.class))).thenReturn(mockOrganizationDao);
when(this.organizationRepository.save(mockOrganizationDao))
.thenReturn(mockPersistedOrganizationDao);
when(this.modelMapper.map(mockPersistedOrganizationDao, OrganizationDm.class))
.thenReturn(mockMappedOrganizationDm);
OrganizationDm result = this.underTest.upsertOrganization(mockOrganizationDm);
assertThat(result.getName()).isEqualTo(mockOrganizationDm.getName());
assertThat(result.getAdminEmail()).isEqualTo(mockEmailDao.getEmailString());
assertThat(result.getDepartments()).isEqualTo(mockOrganizationDm.getDepartments());
}
}
|
package com.yeebar.aer;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.UUID;
/**
* Created by JD on 2016/4/25.
*/
public class Resource {
private String resourceName;
private int resourceId;
private int downloadMark = 0;
private int addMask = 0;
private String databaseName;
private String res_Intro;
private String resourcePic;
private static final String jsonResourceName = "resourcename";
private static final String jsonResourceId = "resourceid";
private static final String jsonDownloadMark = "downloadmark";
private static final String jsonAddMark = "addmark";
private static final String jsonDatabasename = "databasename";
private static final String jsonResInstro = "resourceintro";
private static final String jsonResPic = "resourcepic";
public JSONObject toJSON() throws JSONException {
JSONObject json = new JSONObject();
json.put(jsonResourceName, resourceName);
json.put(jsonResourceId , resourceId);
json.put(jsonDownloadMark, downloadMark);
json.put(jsonAddMark, addMask );
json.put(jsonDatabasename, databaseName);
json.put(jsonResInstro, res_Intro);
json.put(jsonResPic, resourcePic);
return json;
}
public Resource(JSONObject json)throws JSONException{
resourceName = json.getString(jsonResourceName);
resourceId = json.getInt(jsonResourceId);
databaseName = json.getString(jsonDatabasename);
res_Intro = json.getString(jsonResInstro);
downloadMark = json.getInt(jsonDownloadMark);
addMask = json.getInt(jsonAddMark);
resourcePic = json.getString(jsonResPic);
}
public Resource(int id, String name,String database_name, String res_intro, String res_pic){
resourceName = name;
resourceId = id;
databaseName = database_name;
res_Intro = res_intro;
resourcePic = res_pic;
}
public String getResourcePic() {
return resourcePic;
}
public void setResourcePic(String resourcePic) {
this.resourcePic = resourcePic;
}
public String getRes_Intro() {
return res_Intro;
}
public String getDatabaseName() {
return databaseName;
}
public String getResourceName() {
return resourceName;
}
public int getResourceId() {
return resourceId;
}
public int getDownloadMark() {
return downloadMark;
}
public int getAddMask() {
return addMask;
}
public void setResourceName(String resourceName) {
this.resourceName = resourceName;
}
public void setResourceId(int resourceId) {
this.resourceId = resourceId;
}
public void setDownloadMark(int downloadMark) {
this.downloadMark = downloadMark;
}
public void setAddMask(int addMask) {
this.addMask = addMask;
}
}
|
package com.example.covidtracer.Model;
import java.util.ArrayList;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
/**
* This class handles the object that will be stored in realm.
* It contains all the necessary methods to get and set data for that realm object
* Since objects are stored as strings, the getter methods will mainly focus on string
* manipulation
*/
public class UserModel extends RealmObject {
//realm object fields:
//user's id which is also the primary key
@PrimaryKey
String _id;
/**
* "list" of wifis in form of a string which contains wifis and
* distances to them
*/
String wifis;
/**
* "list" of contacts in form of a string which contains name of
* contact, when the contact was made, and time elapsed after contact
*/
String contacts;
//users that were in contact with this user and are positive
String positive_contact;
//when the user with created
Long created;
//when wifi list was last modified
Long wifiLastModified;
//when contacts were last modified
Long contactLastModified;
//when positives were last modified
Long positiveContactModified;
//current user positive check
boolean isPositive;
//UserModel constructor
int notification;
public UserModel() {
}
public String get_id() {
return _id;
}
public String getWifis() {
return wifis;
}
public void setWifis(String wifis) {
this.wifis = wifis;
}
/**
* Creates a list from wifis string
*
* @return arraylist of wifis from wifis string
*/
public ArrayList<String> individualWifi() {
ArrayList<String> wifisPerUser = new ArrayList<>();
if (wifis != null) {
boolean check = true;
int firstEquals = wifis.indexOf("=");
//make sure that the equal sign is not part of the wifis name
while (check) {
if (wifis.indexOf("=", firstEquals) - firstEquals == 1) {
firstEquals++;
} else {
check = false;
}
}
wifisPerUser.add(wifis.substring(1, wifis.indexOf("=")));
}
/**
* loop over wifis string to get the wifis
* each loop updates the location of the equal sign and comma
* that encompass a wifi
*/
for (int i = 0; i < wifis.length(); i++) {
int indexOfComma = wifis.indexOf(",", i);
int indexOfEquals = wifis.indexOf("=", indexOfComma);
if (indexOfComma >= 0) {
boolean equalCheck = true;
while (equalCheck) {
if (wifis.indexOf("=", indexOfEquals) - indexOfEquals == 1) {
indexOfEquals++;
} else {
equalCheck = false;
}
}
wifisPerUser.add(wifis.substring(indexOfComma + 2, indexOfEquals));
i = indexOfEquals;
}
}
return wifisPerUser;
}
/**
* Get the distance of the wifi to the user
*
* @param wifi the name of the wifi that the method will return the
* distance of
* @return an int that represents the distance from the wifi to the user
*/
public int getDistance(String wifi) {
int wifiIndex = wifis.indexOf(wifi);
int indexOfBreak = wifis.indexOf(",", wifiIndex);
int distanceOfWifi = 0;
if (wifiIndex > 0) {
if (indexOfBreak > 0) {
distanceOfWifi = Integer.parseInt(wifis.substring(wifiIndex + wifi.length() + 1, indexOfBreak));
} else {
distanceOfWifi = Integer.parseInt(wifis.substring(wifiIndex + wifi.length() + 1, wifis.length() - 1));
}
} else {
distanceOfWifi = -1;
}
return distanceOfWifi;
}
public void setCreated(Long created) {
this.created = created;
}
public void setWifiLastModified(Long wifiLastModified) {
this.wifiLastModified = wifiLastModified;
}
public void setContactLastModified(Long contactLastModified) {
this.contactLastModified = contactLastModified;
}
public void setPositiveContactModified(Long positiveContactModified) {
this.positiveContactModified = positiveContactModified;
}
/**
* Similar to individualWifi() but with contacts. This method returns the contacts
* in the contacts string
*
* @return an arraylist containing contacts
*/
public ArrayList<String> getContacts() {
if (contacts != null) {
ArrayList<String> contactsList = new ArrayList<>();
contactsList.add(contacts.substring(0, contacts.indexOf("#")));
for (int i = 0; i < contacts.length(); i++) {
int indexOfComma = contacts.indexOf(",", i);
int indexOfHash = contacts.indexOf("#", indexOfComma);
if (indexOfComma >= 0 && indexOfHash >= 0) {
contactsList.add(contacts.substring(indexOfComma + 2, indexOfHash));
i = indexOfHash;
}
}
return contactsList;
}
return null;
}
public void setContacts(String contacts) {
this.contacts = contacts;
}
public String getContactsMessy() {
return contacts;
}
public String getPositive_contact() {
return positive_contact;
}
public void setPositive_contact(String positive_contact) {
this.positive_contact = positive_contact;
}
/**
* Gets the date a contact was made
*
* @param user the user in the contacts that this method will return
* the contact date of
* @return a long that represents the time this contact was made in milliseconds
*/
public Long getDateContacts(String user) {
int indexOfUser = contacts.indexOf(user);
int indexOfComma = contacts.indexOf(",", indexOfUser);
int indexOfAprox = contacts.indexOf("~", indexOfUser);
if (indexOfUser >= 0) {
String dateString;
if (indexOfComma > 0 && indexOfAprox > 0) {
dateString = contacts.substring(indexOfUser + user.length() + 1, indexOfAprox);
} else if (indexOfAprox < 0 && indexOfComma > 0) {
dateString = contacts.substring(indexOfUser + user.length() + 1, indexOfComma);
} else if (indexOfAprox > 0 && indexOfComma < 0) {
dateString = contacts.substring(indexOfUser + user.length() + 1, indexOfAprox);
} else {
dateString = contacts.substring(indexOfUser + user.length() + 1);
}
return Long.parseLong(dateString);
}
return null;
}
/**
* Similar to getDateContacts(user) but returns the time elapsed
*
* @param user the user that this method will return the time elapsed of
* @return long representing the amount of time elapsed
*/
public Long getContactsElapsed(String user) {
if (contacts != null) {
int indexOfUser = contacts.indexOf(user);
int indexOfComma = contacts.indexOf(",", indexOfUser);
if (indexOfUser >= 0) {
String dateString;
String dates;
int indexOfAprox;
if (indexOfComma > 0) {
dates = contacts.substring(indexOfUser + user.length() + 1, indexOfComma);
indexOfAprox = dates.indexOf("~");
dateString = dates.substring(indexOfAprox + 1);
} else {
dates = contacts.substring(indexOfUser + user.length() + 1);
indexOfAprox = dates.indexOf("~");
dateString = dates.substring(indexOfAprox + 1);
}
if (indexOfAprox < 0) {
return null;
} else return Long.parseLong(dateString);
}
}
return null;
}
/**
* Simillar to getContactsElapsed() but returns the date a positive contact
* was made
*
* @return a long in the form of when a contact with a positive user was made
*/
public Long getDatePositives() {
ArrayList<Long> dates = new ArrayList<>();
long highest = 0;
if (positive_contact != null) {
int indexOfHash = positive_contact.indexOf("#");
int indexOfComma = positive_contact.indexOf(",", indexOfHash);
String dateString = "";
if (indexOfComma > 0) {
boolean check = true;
while (check) {
dateString = positive_contact.substring(indexOfHash + 1, indexOfComma);
dates.add(Long.parseLong(dateString));
indexOfHash = positive_contact.indexOf("#", indexOfComma);
indexOfComma = positive_contact.indexOf(",", indexOfHash);
if (indexOfComma < 0) {
dateString = positive_contact.substring(indexOfHash + 1);
dates.add(Long.parseLong(dateString));
check = false;
}
}
} else {
dateString = positive_contact.substring(indexOfHash + 1);
dates.add(Long.parseLong(dateString));
}
if (dates.size() == 1) {
return dates.get(0);
} else {
for (Long date : dates) {
if (date > highest) {
highest = date;
}
}
return highest;
}
}
return null;
}
public boolean isPositive() {
return isPositive;
}
public void setPositive(boolean positive) {
isPositive = positive;
}
public int getNotification() {
return notification;
}
public void setNotification(int notification) {
this.notification = notification;
}
}
|
package com.breakpoint.constans;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.Data;
import java.io.Serializable;
/**
* ่ฟๅๅฏน่ฑก
*
* @author :breakpoint/่ตต็ซๅ
* @date : 2017/11/15
*/
@Data
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class ResponseResult<D> {
/**
* ่ฟๅ็ๆไฝ็ 200๏ผ่ฏดๆๆไฝๆๅ 500๏ผ่ฏดๆๆไฝๅคฑ่ดฅ
*/
private int respCode;
/**
* ่ฟๅ็ไฟกๆฏๆ่ฟฐ
*/
private String message;
/**
* ๅๅบ็ๆฐๆฎ็ๅบๆฌ่ฟๅ
*/
private D data;
/**
* ็ปๅฝไนๅ่ฟๅ็่ทฏ็ฑไฟกๆฏ
*/
private String routing;
/**
* jsessionid
*/
private Serializable jsessionid;
private ResponseResult() {
}
private ResponseResult(int respCode, String message) {
this.respCode = respCode;
this.message = message;
}
private ResponseResult(int respCode, D data) {
this.respCode = respCode;
this.data = data;
}
private ResponseResult(int respCode, String message, D data) {
this.respCode = respCode;
this.message = message;
this.data = data;
}
private ResponseResult(int respCode, String message, D data, String routing) {
this.respCode = respCode;
this.message = message;
this.data = data;
this.routing = routing;
}
private ResponseResult(int respCode, String message, D data, String routing, Serializable jsessionid) {
this.respCode = respCode;
this.message = message;
this.data = data;
this.routing = routing;
this.jsessionid = jsessionid;
}
/**
* ่ฟ่กๅๅปบๆๅ็ไธๅคฑ่ดฅ็ๅบๆฌๆไฝ
*/
/**
* ่ฟๅ้ป่ฎค็ๆๅๅฏน่ฑก
*
* @return
*/
public static ResponseResult createSuccessResult() {
return new ResponseResult(RetCodeConstant.SUCCESS.getCode(),
RetCodeConstant.SUCCESS.getMsg());
}
/**
* ่ฟๅๅธฆๆ็นๅฎไฟกๆฏ็ๆๅๅฏน่ฑก
*
* @return
*/
public static ResponseResult createSuccessResult(String message) {
return new ResponseResult(RetCodeConstant.SUCCESS.getCode(), message);
}
/**
* ่ฟๅๅธฆๆๆฐๆฎ็ๆๅๅฏน่ฑก
*
* @param data
* @param <D>
* @return
*/
public static <D> ResponseResult createSuccessResult(D data) {
return new ResponseResult(RetCodeConstant.SUCCESS.getCode(), data);
}
/**
* @param message ่ฟๅ็ไฟกๆฏ
* @param data ่ฟๅ็ๆฐๆฎ
* @param <D>
* @return
*/
public static <D> ResponseResult createSuccessResult(String message, D data) {
return new ResponseResult(RetCodeConstant.SUCCESS.getCode(), message, data);
}
/**
* @param message
* @param data
* @param routing
* @param <D>
* @return
*/
public static <D> ResponseResult createSuccessResult(String message, D data, String routing) {
return new ResponseResult(RetCodeConstant.SUCCESS.getCode(), message, data, routing);
}
public static <D> ResponseResult createSuccessResult(String message, D data, String routing,Serializable jsessionid) {
return new ResponseResult(RetCodeConstant.SUCCESS.getCode(), message, data, routing,jsessionid);
}
/**
* @param retCodeConstant ่ฟๅๆไฝ็
* @param message ่ฟๅ็ไฟกๆฏ
* @param data ่ฟๅ็ๆฐๆฎ
* @param <D>
* @return
*/
public static <D> ResponseResult createSuccessResult(RetCodeConstant retCodeConstant, String message, D data) {
return new ResponseResult(retCodeConstant.getCode(), message, data);
}
/**
* ่ฟๅ้ป่ฎค็ๅคฑ่ดฅๅฏน่ฑก
*
* @return
*/
public static ResponseResult createFailResult() {
return new ResponseResult(RetCodeConstant.FAIL.getCode(),
RetCodeConstant.FAIL.getMsg());
}
/**
* ่ฟๅๅธฆๆ็นๅฎไฟกๆฏ็ๅคฑ่ดฅๅฏน่ฑก
*
* @return
*/
public static ResponseResult createFailResult(String message) {
return new ResponseResult(RetCodeConstant.FAIL.getCode(), message);
}
/**
* ่ฟๅๅธฆๆๆฐๆฎ็ๅคฑ่ดฅๅฏน่ฑก
*
* @param data
* @param <D>
* @return
*/
public static <D> ResponseResult createFailResult(D data) {
return new ResponseResult(RetCodeConstant.FAIL.getCode(), data);
}
/**
* @param message ่ฟๅ็ไฟกๆฏ
* @param data ่ฟๅ็ๆฐๆฎ
* @param <D>
* @return
*/
public static <D> ResponseResult createFailResult(String message, D data) {
return new ResponseResult(RetCodeConstant.FAIL.getCode(), message, data);
}
/**
* @param retCodeConstant ่ฟๅๆไฝ็
* @param message ่ฟๅ็ไฟกๆฏ
* @param data ่ฟๅ็ๆฐๆฎ
* @param <D>
* @return
*/
public static <D> ResponseResult createFailResult(RetCodeConstant retCodeConstant, String message, D data) {
return new ResponseResult(retCodeConstant.getCode(), message, data);
}
public static <D> ResponseResult createFailResult(RetCodeConstant retCodeConstant, String message, D data, Serializable jsessionid) {
return new ResponseResult(retCodeConstant.getCode(), message, data, null, jsessionid);
}
public static <D> ResponseResult createFailResult(String message, D data, String routing) {
return new ResponseResult(RetCodeConstant.FAIL.getCode(), message, data, routing);
}
public static <D> ResponseResult createFailResult(String message, D data, String routing, Serializable jsessionid) {
return new ResponseResult(RetCodeConstant.FAIL.getCode(), message, data, routing, jsessionid);
}
}
|
package com.example.elearning.web;
import com.example.elearning.entities.*;
import com.example.elearning.entities.Module;
import com.example.elearning.metier.IElearning;
import com.example.elearning.repositories.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import javax.validation.Valid;
import java.util.List;
import java.util.Optional;
@Controller
public class mainController {
@Autowired
private IElearning iElearning;
@Autowired
private FormationRepository formationRepository;
@Autowired
private ContactRepository contactRepository;
@Autowired
private ModuleRepository moduleRepository;
@Autowired
private FormateurRepository formateurRepository;
@Autowired
private ApprenantRepository apprenantRepository;
@GetMapping("/consulterFormation")
public String consulterFormation(Model model, int idFormation){
model.addAttribute("idFormation",idFormation);
try {
Optional<Formation> formation=iElearning.consulterFormation(idFormation);
/*Page<Formation> formationPage = iElearning.listFormation(0,10);*/
/*Page<Module> modulePage = iElearning.listModule(0,5);*/
Page<Module> pageModule = iElearning.pageModule(idFormation,0,5);
model.addAttribute("pageModule",pageModule.getContent());
/*model.addAttribute("listModule",modulePage.getContent());*/
/* model.addAttribute("listFormation",formationPage.getContent());*/
model.addAttribute("formation",formation);
List<Formation> formations=formationRepository.findAll();
model.addAttribute("listformations",formations);
}
catch (Exception e){
model.addAttribute("exception",e); //exception stockee dans le model, sera affiche dans la vue
}
return "catalogue";
}
@GetMapping("/apropos")
public String apropos(){
return "apropos";
}
@GetMapping("/")
public String ind(){
return "accueil";
}
@GetMapping("/accueil")
public String index(){
return "accueil";
}
@GetMapping("/identification")
public String identification(){
return "identification";
}
@RequestMapping(value = "/catalogue",method = RequestMethod.GET)
public String listformations(Model model,
@RequestParam(name="page",defaultValue = "0") int page,
@RequestParam(name="motCle",defaultValue = "") String mc){
Page<Formation> formation=formationRepository.findByDesignationContains("%"+mc+"%",PageRequest.of(page,5));
model.addAttribute("listformations",formation.getContent());
/*Page<Formation> formationPage = iElearning.listFormation(0,10);*/
model.addAttribute("pages",new int[formation.getTotalPages()]);
model.addAttribute("currentPage",page);
model.addAttribute("motCle",mc);
return "catalogue";
}
@RequestMapping(value = "/admin",method = RequestMethod.GET)
public String listformationsAdmin(Model model,
@RequestParam(name="page",defaultValue = "0") int page,
@RequestParam(name="motCle",defaultValue = "") String mc){
Page<Formation> formation=formationRepository.findByDesignationContains(String.format("%%%s%%", mc),PageRequest.of(page,5));
model.addAttribute("listformations",formation.getContent());
model.addAttribute("pages",new int[formation.getTotalPages()]);
model.addAttribute("currentPage",page);
model.addAttribute("motCle",mc);
return "admin";
}
@RequestMapping(value = "/adminFormateurs",method = RequestMethod.GET)
public String listformateursAdmin(Model model,
@RequestParam(name="page",defaultValue = "0") int page,
@RequestParam(name="motCle",defaultValue = "") String mc){
Page<Formateur> formateurs=formateurRepository.findByDesignationFormateur("%"+mc+"%",PageRequest.of(page,5));
model.addAttribute("listformateurs",formateurs.getContent());
model.addAttribute("pages",new int[formateurs.getTotalPages()]);
model.addAttribute("currentPage",page);
model.addAttribute("motCle",mc);
return "adminFormateurs";
}
@RequestMapping(value = "/adminApprenants",method = RequestMethod.GET)
public String listapprenantsAdmin(Model model,
@RequestParam(name="page",defaultValue = "0") int page,
@RequestParam(name="motCle",defaultValue = "") String mc){
Page<Apprenant> apprenants=apprenantRepository.findByDesignationApprenant("%"+mc+"%",PageRequest.of(page,5));
model.addAttribute("listapprenants",apprenants.getContent());
model.addAttribute("pages",new int[apprenants.getTotalPages()]);
model.addAttribute("currentPage",page);
model.addAttribute("motCle",mc);
return "adminApprenants";
}
@RequestMapping(value = "/adminSuppFormateur",method = RequestMethod.GET)
public String suppFormateur(Model model,
@RequestParam(name="page",defaultValue = "0") int page,
@RequestParam(name="motCle",defaultValue = "") String mc){
Page<Formateur> formateurs=formateurRepository.findByDesignationFormateur(String.format("%%%s%%", mc),PageRequest.of(page,5));
model.addAttribute("listformateurs",formateurs.getContent());
model.addAttribute("pages",new int[formateurs.getTotalPages()]);
model.addAttribute("currentPage",page);
model.addAttribute("motCle",mc);
return "admin";
}
@GetMapping("/delete")
public String delete(int id, int page, String motCle){
formationRepository.deleteById(id);
return "redirect:/admin?page="+page+"&motCle="+motCle;
}
@GetMapping("/deleteApprenant")
public String deleteApprenant(int id, int page, String motCle){
apprenantRepository.deleteById(id);
return "redirect:/adminApprenants?page="+page+"&motCle="+motCle;
}
@GetMapping("/deleteFormateur")
public String deleteFormateur(int id, int page, String motCle){
formateurRepository.deleteById(id);
return "redirect:/adminFormateurs?page="+page+"&motCle="+motCle;
}
@RequestMapping(value = "/inscription",method = RequestMethod.GET)
public String formInscription(Model model){
model.addAttribute("formateur",new Formateur());
return "inscription";
}
@RequestMapping(value = "/inscriptionApprenant",method = RequestMethod.GET)
public String formInscriptionApprenant(Model model){
model.addAttribute("apprenant",new Apprenant());
return "inscriptionApprenant";
}
@RequestMapping(value = "/saveFA",method = RequestMethod.POST)
public String saveProfile(Model model, Formateur formateur){
try{
formateurRepository.save(formateur);
}
catch (Exception e)
{
model.addAttribute("Erreur d'inscription",e);
}
return "/saveInscriptionFormateur";
}
@RequestMapping(value = "/saveApp",method = RequestMethod.POST)
public String saveApprenant(Model model, Apprenant apprenant){
try{
apprenantRepository.save(apprenant);
}
catch (Exception e)
{
model.addAttribute("Erreur d'inscription",e);
}
return "accueil";
}
@RequestMapping(value = "/contact",method = RequestMethod.GET)
public String formContact(Model model){
model.addAttribute("mmmm",new Contact());
return "contact";
}
@RequestMapping(value = "/saveContact",method = RequestMethod.POST)
public String saveContact(Contact contact){
contactRepository.save(contact);
return "/saveContact";
}
@RequestMapping(value = "/ajoutFormation",method = RequestMethod.GET)
public String formFormation(Model model){
model.addAttribute("formation",new Formation());
return "ajoutFormation";
}
@RequestMapping(value = "/saveFormation",method = RequestMethod.POST)
public String saveFormation(Formation formation){
formationRepository.save(formation);
return "redirect:/ajoutModules";
}
@GetMapping("/saveInscriptionFormateur")
public String ajoutSuppFormation(){
return "ajoutFormation";
}
@RequestMapping(value="/editerFormation")
public String editerFormation(int id, Model model){
Formation formation=formationRepository.getOne(id);
model.addAttribute("formation",formation);
return "editerFormation";
}
@RequestMapping(value = "/updateFormation",method=RequestMethod.POST)
public String update(@Valid Formation formation, BindingResult bindingResult){
if (bindingResult.hasErrors()){
return "editerFormation";
}
formationRepository.save(formation);
return "ajoutModules";
}
@RequestMapping(value = "/ajoutModules",method = RequestMethod.GET)
public String formModule(Model model){
model.addAttribute("module",new Module());
return "ajoutModules";
}
@RequestMapping(value = "/saveModule",method = RequestMethod.POST)
public String saveModule(Module module){
moduleRepository.save(module);
return "redirect:/admin";
}
@RequestMapping(value="/editerFormateur")
public String editerFormateur(int id, Model model){
Formateur formateur=formateurRepository.getOne(id);
model.addAttribute("formateur",formateur);
return "editerFormateur";
}
@RequestMapping(value = "/updateFormateur",method=RequestMethod.POST)
public String updateFormateur(@Valid Formateur formateur, BindingResult bindingResult){
if (bindingResult.hasErrors()){
return "editerFormateur";
}
formateurRepository.save(formateur);
return "redirect:/adminFormateurs";
}
@RequestMapping(value = "/ajoutFormateur",method = RequestMethod.GET)
public String formFormateur(Model model){
model.addAttribute("formateur",new Formateur());
return "ajoutFormateur";
}
@RequestMapping(value = "/saveFormateur",method = RequestMethod.POST)
public String saveFormateur(Formateur formateur){
formateurRepository.save(formateur);
return "redirect:/adminFormateurs";
}
@RequestMapping(value = "/ajoutApprenant",method = RequestMethod.GET)
public String formApprenant(Model model){
model.addAttribute("apprenant",new Apprenant());
return "ajoutApprenant";
}
@RequestMapping(value = "/saveApprenant",method = RequestMethod.POST)
public String saveApprenant(Apprenant apprenant){
apprenantRepository.save(apprenant);
return "redirect:/adminApprenants";
}
@RequestMapping(value="/editerApprenant")
public String editerApprenant(int id, Model model){
Apprenant apprenant=apprenantRepository.getOne(id);
model.addAttribute("apprenant",apprenant);
return "editerApprenant";
}
@RequestMapping(value = "/updateApprenant",method=RequestMethod.POST)
public String updateApprenant(@Valid Apprenant apprenant, BindingResult bindingResult){
if (bindingResult.hasErrors()){
return "editerApprenant";
}
apprenantRepository.save(apprenant);
return "redirect:/adminApprenants";
}
@GetMapping(value = "/logout")
public String logout(){
return "identification";
}
}
|
package org.giddap.dreamfactory.leetcode.onlinejudge.implementations;
import org.giddap.dreamfactory.leetcode.onlinejudge.RotateImage;
public class RotateImageImpl implements RotateImage {
@Override
public void rotate(int[][] matrix) {
final int n = matrix.length;
final int layers = n / 2;
for (int i = 0; i < layers; i++) {
int m = n - 2 * i - 2;
for (int j = 0; j <= m; j++) {
int tmp = matrix[i + j][i + m + 1];
matrix[i + j][i + m + 1] = matrix[i][i + j];
matrix[i][i + j] = tmp;
tmp = matrix[i + m + 1][i + m + 1 - j];
matrix[i + m + 1][i + m + 1 - j] = matrix[i][i + j];
matrix[i][i + j] = tmp;
tmp = matrix[i + m + 1 -j][i];
matrix[i + m + 1 -j][i] = matrix[i][i + j];
matrix[i][i + j] = tmp;
}
}
}
}
|
package main.java.main;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import main.java.constant.Constants;
import main.java.constant.NameConstants;
import main.java.handler.LogHandler;
import main.java.pane.MainMenu;
import main.java.pane.base.StyledPane;
public class Main extends Application
{
private static Stage primaryStage;
@Override
public void start(Stage primaryStage)
{
try
{
Main.primaryStage = primaryStage;
primaryStage.getIcons().add(new Image(Constants.ApplicationIcon));
primaryStage.setTitle(NameConstants.GetRandomTitle());
SwitchPane(new MainMenu());
primaryStage.setMaximized(true);
primaryStage.show();
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e)
{
LogHandler.WriteErrorToLogFile(e, "Class not found");
LogHandler.ShowWarning(Language.getTranslation("warning.nojdbcclass"));
}
catch (Exception e)
{
LogHandler.WriteErrorToLogFile(e, "Exception");
}
}
public static void main(String[] args)
{
launch(args);
}
public static void SwitchPane(StyledPane pane)
{
Scene scene = new Scene(pane, ScreenProperties.getScreenWidth(), ScreenProperties.getScreenHeight());
scene.getStylesheets().add(Constants.styleSheetLocation + "application.css");
primaryStage.setScene(scene);
pane.InitPane();
}
}
|
package com.ak.texasholdem.cards;
public enum Suit {
DIAMONDS("KรRร", '\u2666'),
CLUBS("TREFF", '\u2663'),
HEARTS("KรR", '\u2665'),
SPADES("PIKK", '\u2660');
private String hunName;
private char symbol;
private Suit(String hunName, char symbol) {
this.hunName = hunName;
this.symbol = symbol;
}
public String getHunName() {
return hunName;
}
public char getSymbol() {
return symbol;
}
}
|
package com.example.welcome.myregistration;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class LoginActivity extends AppCompatActivity {
EditText musername, mpassword;
Button mlogin;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
musername = (EditText)findViewById(R.id.etUsername);
mpassword = (EditText)findViewById(R.id.etPassword);
mlogin = (Button) findViewById(R.id.etLogin);
mlogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String name = musername.getText().toString();
String password = mpassword.getText().toString();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(LoginActivity.this);
SharedPreferences set = getSharedPreferences("MyPreferences", MODE_PRIVATE);
String name1 = set.getString("Name", "");
String password1 = set.getString("Password", "");
if ((name.equals(name1)) && (password.equals(password1))){
Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("Name", "true");
editor.commit();
startActivity(intent);
finish();
}
else {
Toast.makeText(LoginActivity.this, "Invalid username or password", Toast.LENGTH_SHORT).show();
}
}
});
}
}
|
package ejercicio.interfaces;
public class CajeroProdubanco implements CajeroInterfaz{
@Override
public void solicitarTarjeta(String numero) {
// TODO Auto-generated method stub
System.out.println("Bienvenido a Produbanco");
System.out.println("Por favor ingrese su tarjeta");
}
@Override
public void solicitarClave(String clave) {
// TODO Auto-generated method stub
System.out.println("Ingrese su clave");
}
@Override
public void solicitarTipoTranssaccion() {
// TODO Auto-generated method stub
System.out.println("Ingrese que tipo de transaccion necesita");
}
@Override
public void solicitarMonto(int monto) {
// TODO Auto-generated method stub
System.out.println("ingrese el monto que va a retirar");
}
@Override
public void validarSaldo() {
// TODO Auto-generated method stub
System.out.println("Espere un momento");
System.out.println("Se esta validando su saldo");
System.out.println("Espere un momento");
int saldo=200;
int retiro=100;
System.out.println("Usted tiene "+saldo+" seguro que desea retirar "+retiro);
System.out.println("de su saldo total?");
}
@Override
public void entregarDinero() {
// TODO Auto-generated method stub
System.out.println("Su dinero esta siendo entregado");
}
@Override
public void realizarTransaccion() {
// TODO Auto-generated method stub
System.out.println("Mientras se imprime el dinero");
System.out.println("Se completara la transaccion");
}
@Override
public void entregarRecibo() {
// TODO Auto-generated method stub
System.out.println("Aqui esta su recibo");
System.out.println("Gracias por preferirnos");
System.out.println("Enfocados en la calidad de servicio para usted");
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package acme_banking_system.data_access;
import acme_banking_system.exceptions.BusinessException;
import acme_banking_system.exceptions.DataLayerException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
*
* @author morga_000
*/
public class RDBPendingDAO implements PendingDAO {
private Connection dbConnection = null;
public RDBPendingDAO(Connection connection) {
this.dbConnection = connection;
}
@Override
public void createPending(Pending pending) throws DataLayerException, BusinessException {
try {
PreparedStatement sqlStatement = dbConnection.prepareStatement(
"SELECT * FROM JMH123.PENDINGTRANSACTIONS WHERE P_ID = ?",
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
sqlStatement.setInt(1, pending.getPID());
ResultSet res = sqlStatement.executeQuery();
// Check for unicity
if (res.last()) {
throw new BusinessException("This pending transaction already exists");
}
//Creating prepare statement
sqlStatement = dbConnection.prepareStatement(
"INSERT INTO JMH123.PENDINGTRANSACTIONS (C_ID, Amount)"
+ " VALUES (?, ?)", Statement.RETURN_GENERATED_KEYS);
sqlStatement.setInt(1, pending.getCID());
sqlStatement.setDouble(2, pending.getAmount());
sqlStatement.executeUpdate();
ResultSet result = sqlStatement.getGeneratedKeys();
result.next();
pending.setPID(result.getInt(1));
} catch (SQLException ex) {
throw new DataLayerException();
}
}
@Override
public void deletePending(int p_id) throws DataLayerException {
try {
//Deleting pending transaction
PreparedStatement sqlStatement = dbConnection.prepareStatement(
"DELETE FROM JMH123.PENDINGTRANSACTIONS WHERE P_ID = ?");
sqlStatement.setInt(1, p_id);
sqlStatement.executeQuery();
} catch (SQLException sqle) {
throw new DataLayerException();
}
}
@Override
public Pending getPending(int p_id) throws DataLayerException {
Pending pending;
try {
// Getting the pending transaction
PreparedStatement sqlStatement = dbConnection.prepareStatement(
"SELECT * FROM JMH123.PENDINGTRANSACTIONS WHERE P_ID = ?");
sqlStatement.setInt(1, p_id);
ResultSet result = sqlStatement.executeQuery();
// Creating the pending object
pending = new Pending(result.getInt(1), result.getInt(2), result.getDouble(3));
return pending;
} catch (SQLException sqle) {
throw new DataLayerException();
}
}
}
|
/*
* 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 hw8;
import java.io.File;
import java.io.FileNotFoundException;
import static java.lang.System.exit;
import java.util.ArrayList;
import java.util.Objects;
import java.util.Scanner;
import java.lang.Exception;
import java.rmi.UnexpectedException;
/**
*
* @author BEDO
*/
public class BigramDyn<T> implements Bigram<T>
{
private int size;
private final int datatype;
private T arr[];
public BigramDyn(int type){
arr =(T[]) new Objects[100];
datatype=type;
}
@Override
public void readFile(String file)throws Exception{
int i=0;
File inputFile = new File(file);
try {
Scanner inp= new Scanner(inputFile);
if(datatype==1){
Integer input = null;
while(inp.hasNext()){
if(inp.hasNextInt()){
input = inp.nextInt();
arr[i]=(T) input;
i++;
}
else {
}
}
}
else if(datatype==2){
String input=inp.next();
arr[i]=(T) input;
i++;
while(inp.hasNext()){
input = inp.next();
arr[i]=(T) input;
i++;
}
}
else if(datatype==3){
Double input = null;
while(inp.hasNext()){
if(inp.hasNextDouble()){
input = inp.nextDouble();
arr[i]=(T) input;
i++;
}
else {
}
}
}
size=i;
}
catch (FileNotFoundException ex) {
throw new myException("Dosya aรงฤฑlamadฤฑ..!!!");
}
catch (NumberFormatException e){
throw new myException("Formata uymayan yapi..HATA.!!!");
}
}
@Override
public int numGrams() {
return size-1;
}
@Override
public int numOfGrams(T first, T second) {
int count=0;
int i;
for(i=0; i<size-1; i++){
if(arr[i].equals(first) && arr[i+1].equals(second)){
count++;
}
}
return count;
}
public String toString(){
int i;
ArrayList< Mypair<T,T> > mypair = new ArrayList< Mypair<T,T> >();
Mypair<T,T> pair= new Mypair<>();
for(i=0; i<numGrams(); i++){
pair.first=(T)arr[i];
pair.second=(T)arr[i+1];
mypair.add(pair);
}
for(i=0; i<size-1; i++){
for(int j=0; j<numGrams()-1; j++){
if(numOfGrams(mypair.get(j).first,mypair.get(j).second)<=
numOfGrams(mypair.get(j+1).first,mypair.get(j+1).second)){
Mypair<T,T> temp = new Mypair<>();
temp=mypair.get(j);
mypair.set(j,mypair.get(j+1));
mypair.set(j+1, temp);
}
}
}
for(i=0; i<size-1; i++){
System.out.printf("%s %s (%s)",mypair.get(i).first,mypair.get(i).second,numOfGrams(mypair.get(i).first,mypair.get(i).second));
}
return String.format("");
}
}
|
package com.skilldistillery.venue.client;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import com.skilldistillery.venue.entities.Venue;
public class VenueClient {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("VenuePU");
EntityManager em = emf.createEntityManager();
// Venue venue = em.find(Venue.class, 6);
//
// System.out.println(venue);
Venue venue = new Venue();
em.close();
}
}
|
package com.icanit.app_v2.activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import com.icanit.app_v2.R;
import com.icanit.app_v2.common.IConstants;
import com.icanit.app_v2.entity.AppUser;
import com.icanit.app_v2.exception.AppException;
import com.icanit.app_v2.fragment.AbstractRadioBindFragment;
import com.icanit.app_v2.fragment.Main_community_Fragment;
import com.icanit.app_v2.fragment.Main_settings_Fragment;
import com.icanit.app_v2.fragment.Main_usercentral_Fragment;
import com.icanit.app_v2.fragment.Main_userlogin_Fragment;
import com.icanit.app_v2.ui.CustomizedDialog;
import com.icanit.app_v2.util.AppUtil;
public class MainActivity extends FragmentActivity {
private int containerId=R.id.frameLayout1;
private FrameLayout container;
private RadioGroup radioGroup;
private RadioButton rb0, rb1, rb2, rb3, rb4;
private AbstractRadioBindFragment home_bottomtab00Fragment,
home_bottomtab01Fragment, home_bottomtab02Fragment,
home_bottomtab03Fragment, home_bottomtab04Fragment;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
AppUtil.loadShoppingCartInfo();
init();
initRadios();
home_bottomtab02Fragment = new Main_community_Fragment();
home_bottomtab02Fragment.setTrigger(rb2);
getSupportFragmentManager().beginTransaction()
.add(containerId, home_bottomtab02Fragment).commit();
AppUtil.checkAutoLoginIf();
shortcutPrompt();
} catch (AppException e) {
e.printStackTrace();
}
}
private void shortcutPrompt() {
if (AppUtil.getSharedPreferencesUtilInstance().getShortcutPromptStatus()) {
final CustomizedDialog dialog=CustomizedDialog.initDialog("ๆ็คบ", "ๆฏๅฆๆทปๅ ๅฐๆก้ขๅฟซๆทๆนๅผ?",
"ไธๆฌกไธๅๆ้", 0,this).setPositiveButton("ๆทปๅ ", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface idialog, int which) {
AppUtil.addShortcutToDesktop(MainActivity.this);
AppUtil.getSharedPreferencesUtilInstance().setShortcutPromptStatus(false);
}
});
dialog.setNegativeButton("ไธไบ",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface idialog, int which) {
AppUtil.getSharedPreferencesUtilInstance().setShortcutPromptStatus(!dialog.getCheckedTextStatus());
}
});
dialog.show();
}
}
protected void onNewIntent(Intent intent) {
String action = intent.getAction();
if(IConstants.LEAD_TO_MERCHANT_LIST.equals(action)){
if (home_bottomtab02Fragment == null)
createFragment(R.id.radio2);
if (!home_bottomtab02Fragment.isResumed())
getSupportFragmentManager()
.beginTransaction()
.replace(containerId,
home_bottomtab02Fragment, null)
.addToBackStack(null).commitAllowingStateLoss();
}
}
/*private String getAuthorityThroughPermission(Context context, String permission) {
if (TextUtils.isEmpty(permission)) {
return null;
}
List<PackageInfo> packs =context.getPackageManager().getInstalledPackages(
PackageManager.GET_PERMISSIONS|PackageManager.GET_PROVIDERS|
PackageManager.GET_URI_PERMISSION_PATTERNS|PackageManager.GET_ACTIVITIES|PackageManager.GET_GIDS);
if (packs == null) {
return null;
}
for (PackageInfo pack : packs) {
if(!pack.packageName.contains("launcher")&&!pack.packageName.contains("app_v2")) continue;
System.out.println("packName="+pack.packageName+",permission="+Arrays.toString(pack.permissions)+
"|"+Arrays.toString(pack.requestedPermissions)+" @MainActivity");
System.out.println("appPermission="+pack.applicationInfo.permission+",uid="+Arrays.toString(pack.gids)+" @MainActivity");
ProviderInfo[] providers = pack.providers;
if (providers != null) {
for (ProviderInfo provider : providers) {
provider.exported=true;provider.grantUriPermissions=true;
System.out.println("providerName="+provider.name+",permission="+provider.readPermission+"|"+provider.writePermission+
",authority="+provider.authority+",uriPermission="+provider.grantUriPermissions+
"|"+provider.exported+"|"+Arrays.toString(provider.pathPermissions)+",pattern="+provider.uriPermissionPatterns+" -------------@MainActivity");
if (permission.equals(provider.readPermission)
|| permission.equals(provider.writePermission)) {
return provider.authority;
}
}
}
}
return null;
}
private boolean hasInstallShortcut() {
System.out.println("authority="+getAuthorityThroughPermission(getApplicationContext(), "com.android.launcher.permission.READ_SETTINGS")+" @MainActivity");
boolean isInstallShortcut = false;
final ContentResolver cr = getContentResolver();
final Uri CONTENT_URI = Uri
.parse("content://com.sonyericsson.tvlauncher.provider1/favorites?notify=true");
Cursor c = cr.query(CONTENT_URI, null, null, null, null);
System.out.println(c + " @MainActivity");
if (c != null && c.getCount() > 0) {
isInstallShortcut = true;
System.out.println("ๅทฒๅๅปบ");
c.moveToFirst();
do {
for (int i = 0; i < c.getColumnCount(); i++)
System.out.print(c.getColumnName(i) + "=" + c.getString(i)
+ ", ");
System.out.println();
} while (c.moveToNext());
}
System.out.println(isInstallShortcut + " @MainActivity");
return isInstallShortcut;
// boolean hasInstall = false;
// Uri CONTENT_URI =
// Uri.parse("content://com.android.launcher.settings/favorites?notify=true");
// Cursor cursor = this.getContentResolver().query(CONTENT_URI,new
// String[] { "title", "iconResource"},
// "title=?",new String[] { this.getString(R.string.app_name) }, null);
// if (cursor != null && cursor.getCount() > 0) {
// hasInstall = true;
// }
// System.out.println(hasInstall+" @MainActivity");
// return hasInstall;
}*/
public void toHome_bottomtab03Fragment(AbstractRadioBindFragment fragment){
createFragment(R.id.radio3);
if (!home_bottomtab03Fragment.isResumed())
getSupportFragmentManager().beginTransaction()
.replace(containerId,home_bottomtab03Fragment,null).addToBackStack(null).commit();
}
public void setHome_bottomtab03Fragment(AbstractRadioBindFragment fragment) {
getSupportFragmentManager().beginTransaction().remove(fragment).commit();
createFragment(R.id.radio3);
if (!home_bottomtab03Fragment.isResumed())
getSupportFragmentManager().beginTransaction()
.add(containerId,home_bottomtab03Fragment,null).addToBackStack(null).commit();
}
private void createFragment(int id) {
switch (id) {
case R.id.radio0:
home_bottomtab00Fragment = new Main_community_Fragment();
home_bottomtab00Fragment.setTrigger(rb0);
break;
case R.id.radio1:
home_bottomtab01Fragment = new Main_community_Fragment();
home_bottomtab01Fragment.setTrigger(rb1);
break;
case R.id.radio2:
home_bottomtab02Fragment = new Main_community_Fragment();
home_bottomtab02Fragment.setTrigger(rb2);
break;
case R.id.radio3:
AppUser user = AppUtil.getLoginUser();
if (user == null) {
if (home_bottomtab03Fragment == null
|| home_bottomtab03Fragment.getClass() != Main_userlogin_Fragment.class)
home_bottomtab03Fragment = new Main_userlogin_Fragment();
} else {
if (home_bottomtab03Fragment == null
|| home_bottomtab03Fragment.getClass() != Main_usercentral_Fragment.class)
home_bottomtab03Fragment = new Main_usercentral_Fragment();
}
home_bottomtab03Fragment.setTrigger(rb3);
break;
case R.id.radio4:
home_bottomtab04Fragment = new Main_settings_Fragment();
home_bottomtab04Fragment.setTrigger(rb4);
break;
default:
break;
}
}
private void initRadios() {
OnClickListener listener = new OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.radio0:
if (home_bottomtab00Fragment == null) {
createFragment(R.id.radio0);
}
if (!home_bottomtab00Fragment.isResumed())
getSupportFragmentManager()
.beginTransaction()
.replace(containerId,
home_bottomtab00Fragment, null)
.addToBackStack(null).commit();
break;
case R.id.radio1:
if (home_bottomtab01Fragment == null)
createFragment(R.id.radio1);
if (!home_bottomtab01Fragment.isResumed())
getSupportFragmentManager()
.beginTransaction()
.replace(containerId,
home_bottomtab01Fragment, null)
.addToBackStack(null).commit();
break;
case R.id.radio2:
if (home_bottomtab02Fragment == null)
createFragment(R.id.radio2);
if (!home_bottomtab02Fragment.isResumed())
getSupportFragmentManager()
.beginTransaction()
.replace(containerId,
home_bottomtab02Fragment, null)
.addToBackStack(null).commit();
break;
case R.id.radio3:
createFragment(R.id.radio3);
if (!home_bottomtab03Fragment.isResumed()
|| (home_bottomtab00Fragment != null && home_bottomtab00Fragment
.isResumed())
|| (home_bottomtab01Fragment != null && home_bottomtab01Fragment
.isResumed())
|| (home_bottomtab02Fragment != null && home_bottomtab02Fragment
.isResumed())
|| (home_bottomtab04Fragment != null && home_bottomtab04Fragment
.isResumed()))
getSupportFragmentManager()
.beginTransaction()
.replace(containerId,
home_bottomtab03Fragment, null)
.addToBackStack(null).commit();
System.out.println("fragment02IsResume="+home_bottomtab02Fragment.isResumed()
+ ",Fragment03IsResume=" + home_bottomtab03Fragment.isResumed()
+ " @MainActivity");
break;
case R.id.radio4:
if (home_bottomtab04Fragment == null) {
createFragment(R.id.radio4);
}
if (!home_bottomtab04Fragment.isResumed())
getSupportFragmentManager()
.beginTransaction()
.replace(containerId,
home_bottomtab04Fragment, null)
.addToBackStack(null).commit();
break;
}
}
};
rb0 = (RadioButton) findViewById(R.id.radio0);
rb1 = (RadioButton) findViewById(R.id.radio1);
rb2 = (RadioButton) findViewById(R.id.radio2);
rb3 = (RadioButton) findViewById(R.id.radio3);
rb4 = (RadioButton) findViewById(R.id.radio4);
rb0.setOnClickListener(listener);
rb1.setOnClickListener(listener);
rb2.setOnClickListener(listener);
rb3.setOnClickListener(listener);
rb4.setOnClickListener(listener);
}
private void init() throws AppException {
container = (FrameLayout) findViewById(containerId);
radioGroup = (RadioGroup) findViewById(R.id.radioGroup1);
}
@Override
protected void onDestroy() {
Log.d("infoTag", "@HomePageActivity onDestroy");
AppUtil.updateShoppingCartDB();
// AppUtil.deleteFileFromSDCard(newVersionName+IConstants.APP_NEWVERSION_FILE);
AppUtil.clearAllCaches();
super.onDestroy();
}
}
|
package com.app.controller;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.app.model.Customer;
import com.app.model.Login;
import com.app.model.Response;
import com.app.service.ICustomerService;
@RestController
public class CustomerController {
@Autowired
ICustomerService service;
@RequestMapping("/")
public String index() {
return "Greetings from Banking Application!";
}
@RequestMapping(value = "/login", method = RequestMethod.POST, produces = "application/json")
public Response login(@RequestBody Login login, HttpServletRequest request) {
Response appResponse = new Response();
/*if (login != null) {
if ("admin".equals(login.getUsername()) && "admin".equals(login.getPassword())) {
Cookie ck = new Cookie("name", login.getUsername());
response.addCookie(ck);
appResponse.setMessage("login successfull");
appResponse.setData(true);
}
}else{
appResponse.setMessage("invalid username and password");
}*/
HttpSession session = request.getSession(false);
if (session != null) {
// a session exists
//user is already logged in
session.setAttribute("loggedInUser", login.getUsername());
appResponse.setMessage("login success");
} else {
// no session create session
session=request.getSession();
session.setAttribute("loggedInUser", login.getUsername());
appResponse.setMessage("login success");
}
return appResponse;
}
@RequestMapping(value = "/logout", method = RequestMethod.GET, produces = "application/json")
public Response logout(HttpServletRequest request) {
Response appResponse = new Response();
/* Cookie ck = new Cookie("name", "");
ck.setMaxAge(0);
response.addCookie(ck);*/
HttpSession session = request.getSession(false);
if(session!=null){
session.invalidate();
appResponse.setMessage("logout success");
}
return appResponse;
}
@RequestMapping(value = "/customer/{accountNumber}", method = RequestMethod.GET, produces = "application/json")
public Response getCustomer(@PathVariable("accountNumber") long accountNumber, HttpServletRequest request) {
Response appResponse = new Response();
/*Cookie ck[] = request.getCookies();
if (ck != null) {
String user = ck[0].getValue();
if ("admin".equals(user)) {
appResponse.setData(service.getCustomer(accountNumber));
}
} else {
return appResponse;
}*/
HttpSession session = request.getSession(false);
if (session != null) {
// a session exists
List<Customer> list= (List<Customer>) session.getAttribute("customers");
if(list!=null){
for (Customer customer : list) {
if(customer.getAccountNumber()==accountNumber){
appResponse.setData(customer);
appResponse.setMessage("success");
break ;
}
}
}else{
appResponse.setData(null);
appResponse.setMessage("No record found");
}
} else {
appResponse.setMessage("Unauthorised request");
}
return appResponse;
}
@RequestMapping(value = "/customer", method = RequestMethod.POST, consumes = "application/json")
public Response addCustomer(@RequestBody Customer customer, HttpServletRequest request) {
Response appResponse = new Response();
HttpSession session = request.getSession(false);
if (session != null) {
List<Customer> list= (List<Customer>) session.getAttribute("customers");
if(list!=null){
list.add(customer);
}else{
list=new ArrayList<Customer>();
list.add(customer);
}
session.setAttribute("customers", list);
appResponse.setMessage("success");
}else{
appResponse.setMessage("Unauthorised request");
}
return appResponse;
}
@RequestMapping(value = "/customer", method = RequestMethod.PUT, consumes = "application/json")
public Response updateCustomer(Customer customer, HttpServletRequest request) {
Response appResponse = new Response();
HttpSession session = request.getSession(false);
if (session != null) {
List<Customer> list= (List<Customer>) session.getAttribute("customers");
for (Customer c : list) {
if(c.getAccountNumber()==customer.getAccountNumber()){
c.setAccountBalance(customer.getAccountBalance());
break ;
}
}
session.setAttribute("customers", list);
appResponse.setMessage("success");
}else{
appResponse.setMessage("Unauthorised request");
}
return appResponse;
}
@RequestMapping(value = "/customer/{accountNumber}", method = RequestMethod.DELETE, produces = "application/json")
public Response deleteCustomer(@PathVariable("accountNumber") long accountNumber, HttpServletRequest request) {
Response appResponse = new Response();
HttpSession session = request.getSession(false);
if (session != null) {
List<Customer> list= (List<Customer>) session.getAttribute("customers");
for (Customer c : list) {
if(c.getAccountNumber()==accountNumber){
list.remove(c);
break ;
}
}
session.setAttribute("customers", list);
appResponse.setMessage("success");
}else{
appResponse.setMessage("Unauthorised request");
}
return appResponse;
}
@RequestMapping(value = "/customer", method = RequestMethod.GET, produces = "application/json")
public Response getallCustomer(HttpServletRequest request) {
Response appResponse = new Response();
HttpSession session = request.getSession(false);
if (session != null) {
List<Customer> list= (List<Customer>) session.getAttribute("customers");
appResponse.setData(list);
appResponse.setMessage("success");
}else{
appResponse.setMessage("Unauthorised request");
}
return appResponse;
}
}
|
package com.zxt.compplatform.workflow.dao;
import java.util.List;
public interface PidaidWorkFlowDao {
/**
*
* @param processDefId ่ฟ็จๅฎไนid
* @param activityDefId ๆดปๅจๅฎไนid
* @return List 1๏ผ่ฟ็จname 2๏ผๆดปๅจname
*/
public List pidaidfindfn(int processDefId, int activityDefId);
}
|
package com.hfjy.framework.init;
import java.io.File;
import com.hfjy.framework.cache.CacheAccess;
import com.hfjy.framework.common.util.ConvertUtil;
import com.hfjy.framework.common.util.StringUtils;
import com.hfjy.framework.database.base.DBConnectionPool;
import com.hfjy.framework.database.base.DBSessionFactory;
import com.hfjy.framework.database.nosql.DataAccess;
public class Initial {
/** ้
็ฝฎๆไปถ็ฎๅฝ */
public final static String SYSTEM_CONFIG_PATH = StringUtils.unite(System.getProperty("user.home"), File.separator, "configs", File.separator);
/** ๆฐๆฎๅบ้
็ฝฎๆไปถ็ฎๅฝ */
public final static String DB_CONFIG_PATH = StringUtils.unite(SYSTEM_CONFIG_PATH, "db", File.separator);
/** ้
็ฝฎๆไปถ */
public final static String CONFIG_DB_FILE = StringUtils.unite(SYSTEM_CONFIG_PATH, "frameworkConfig.db");
public final static String CONFIG_H2_DB_FILE = StringUtils.unite(SYSTEM_CONFIG_PATH, "frameworkConfig");
public final static String DB_CONFIG_FILE = StringUtils.unite(DB_CONFIG_PATH, "DBsConfig.properties");
public final static String LOG_CONFIG_FILE = StringUtils.unite(SYSTEM_CONFIG_PATH, "log", File.separator, "logback.xml");
public final static String JEDIS_CONFIG_FILE = StringUtils.unite(SYSTEM_CONFIG_PATH, "cache", File.separator, "jedis.properties");
public final static String MONGODB_CONFIG_FILE = StringUtils.unite(SYSTEM_CONFIG_PATH, "cache", File.separator, "mongodb.properties");
public final static String XMEMCACHED_CONFIG_FILE = StringUtils.unite(SYSTEM_CONFIG_PATH, "cache", File.separator, "xmemcached.properties");
/** ๅๅงๅๅๆฐ */
public static boolean CONFIG_DB_INIT_OK = false;
public static boolean CACHE_ACCESS_INIT_OK = false;
public final static boolean SYSTEM_IS_DEBUG = initValue(ConfigDbUtil.init(CONFIG_DB_FILE).getConfig("default", "isDebug"), true);
public final static boolean SYSTEM_IS_ALL_STATIC = initValue(ConfigDbUtil.init(CONFIG_DB_FILE).getConfig("default", "isAllStatic"), false);
public final static boolean SYSTEM_IS_ALL_STATIC_LOCAL = initValue(ConfigDbUtil.init(CONFIG_DB_FILE).getConfig("default", "isAllStaticLocal"), true);
public final static String SYSTEM_DEFAULT_CHARSET = initValue(ConfigDbUtil.init(CONFIG_DB_FILE).getConfig("default", "charset"), "UTF-8");
public final static String SYSTEM_DEFAULT_DATE_FORMAT = initValue(ConfigDbUtil.init(CONFIG_DB_FILE).getConfig("default", "dateFormat"), "yyyy-MM-dd HH:mm:ss");
public final static String SYSTEM_SHOW_DATE_FORMAT = initValue(ConfigDbUtil.init(CONFIG_DB_FILE).getConfig("default", "showDateFormat"), "yyyyๅนดMMๆddๆฅ HHๆถmmๅss็ง");
public final static String SYSTEM_DEFAULT_TIME_ZONE = initValue(ConfigDbUtil.init(CONFIG_DB_FILE).getConfig("default", "timeZone"), "ETC/GMT-8");
public final static Integer SYSTEM_DEFAULT_WAIT_TIMEOUT = initValue(ConfigDbUtil.init(CONFIG_DB_FILE).getConfig("default", "timeout"), 10000);
public final static String DB_CONFIG_DEFAULT_KEY = initValue(ConfigDbUtil.init(CONFIG_DB_FILE).getConfig("default", "configDefaultKey"), "DEFAULT");
public final static String SQL_DEFAULT_EXTERNAL_DB_ACHIEVE = initValue(ConfigDbUtil.init(CONFIG_DB_FILE).getConfig("default", "sqlDefaultExternalAchieve"), "com.hfjy.framework.database.nosql.JDBCDataAccessObject");
public final static String SQL_DEFAULT_EXTERNAL_TABLE_NAME = initValue(ConfigDbUtil.init(CONFIG_DB_FILE).getConfig("default", "sqlDefaultExternalTable"), "zoo_sql_store");
public final static String SYSTEM_ACHIEVE_CACHE_ACCESS = initValue(ConfigDbUtil.init(CONFIG_DB_FILE).getDefaultAchieve(CacheAccess.class), "com.hfjy.framework3rd.cache.RedisAccess");
public final static String SYSTEM_ACHIEVE_DB_CONNECTION_POOL = initValue(ConfigDbUtil.init(CONFIG_DB_FILE).getDefaultAchieve(DBConnectionPool.class), "com.hfjy.framework.database.base.SimpleKeepDBConnectionPool");
public final static String SYSTEM_ACHIEVE_DB_SESSION_FACTORY = initValue(ConfigDbUtil.init(CONFIG_DB_FILE).getDefaultAchieve(DBSessionFactory.class), "com.hfjy.framework.database.base.SimpleDBSessionFactory");
public final static String SYSTEM_ACHIEVE_DATA_ACCESS = initValue(ConfigDbUtil.init(CONFIG_DB_FILE).getDefaultAchieve(DataAccess.class), "com.hfjy.framework3rd.database.mongodb.MongodbDataAccess");
@SuppressWarnings("unchecked")
private static <T> T initValue(Object value, T defaultValue) {
if (value == null) {
return defaultValue;
} else {
Object tmp = defaultValue;
if (defaultValue instanceof Boolean) {
if (value.toString().trim().equalsIgnoreCase("true")) {
tmp = true;
} else {
tmp = false;
}
} else if (defaultValue instanceof Integer) {
tmp = ConvertUtil.toIt(value, Integer.class);
}
return (T) tmp;
}
}
}
|
package com.krish.iw;
public class FizzBuzz {
public static void main(String[] args) {
printFizzBuzz(100);
}
private static void printFizzBuzz(int num) {
for (int i = 1; i <= num; i++) {
if (i == 0)
System.out.print(i + " ");
else if (i % (3 * 5) == 0)
System.out.print(" FizzBuzz ");
if (i % 3 == 0)
System.out.print(" Fizz ");
else if (i % 5 == 0)
System.out.print(" Buzz ");
else
System.out.print(" " + i + " ");
}
}
}
|
package main;
public class DualRole {
public interface IParent {
public void feedBaby();
public void takeBabyForWalk();
}
public interface IWorker {
public void commuteToWork();
public void accomplishTaskAtWork();
}
public class WorkingParent implements IParent, IWorker {
private int energyLevel;
private String name;
public WorkingParent(String name, int energyLevel) {
this.name = name;
this.energyLevel = energyLevel;
}
public int getEnergyLevel() {
return energyLevel;
}
private boolean hasEnergy() {
if (energyLevel >= 1) {
return true;
}
System.out.println(name + " is burned out! " + name + " needs to eat food");
return false;
}
private void doTask(String message) {
if (hasEnergy()) {
System.out.println(name + " is " + message);
energyLevel--;
}
}
public void commuteToWork() {
doTask("commuting to work!");
}
public void accomplishTaskAtWork() {
doTask("accomplishing tasks at work!");
}
public void feedBaby() {
doTask("Feeding the baby!");
}
public void takeBabyForWalk() {
doTask("Taking baby for a walk!");
}
public void eatFood() {
System.out.println(name + "has eaten food!");
energyLevel++;
}
}
public static void main(String[] args) {
WorkingParent mom = new DualRole().new WorkingParent("mom", 2);
IParent parent = mom;
IWorker worker = mom;
parent.feedBaby();
worker.commuteToWork();
worker.accomplishTaskAtWork();
mom.eatFood();
parent.takeBabyForWalk();
}
}
|
package view;
import java.awt.EventQueue;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import controller.ComparaImagensController;
import model.Relatorio;
import javax.swing.JButton;
public class telaAnalise {
public JFrame frame_analise;
private Relatorio r;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
telaAnalise window = new telaAnalise();
window.frame_analise.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public telaAnalise() {
//initialize();
}
/**
* Initialize the contents of the frame.
*/
public void initialize() {
frame_analise = new JFrame("Analisando Imagem...");
frame_analise.setBounds(100, 100, 665, 418);
frame_analise.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame_analise.getContentPane().setLayout(null);
r = getRelatorio();
JLabel lblFoto = new JLabel("");
lblFoto.setBounds(34, 32, 261, 292);
frame_analise.getContentPane().add(lblFoto);
Image img = new ImageIcon(r.getFoto()).getImage();
Image imgIcon = img.getScaledInstance(lblFoto.getWidth(), lblFoto.getHeight(), Image.SCALE_DEFAULT);
lblFoto.setIcon(new ImageIcon(imgIcon));
JLabel lblMsg = new JLabel("Comparando com fotos do banco de dados...");
lblMsg.setBounds(337, 40, 278, 14);
frame_analise.getContentPane().add(lblMsg);
JLabel lblEstadoFoto = new JLabel("Estado Foto");
lblEstadoFoto.setBounds(337, 65, 104, 14);
frame_analise.getContentPane().add(lblEstadoFoto);
JButton btnMenuPrincipal = new JButton("Menu Principal");
btnMenuPrincipal.setBounds(452, 61, 146, 23);
frame_analise.getContentPane().add(btnMenuPrincipal);
JLabel lblFrutosEncontrados = new JLabel("Frutos encontrados:");
lblFrutosEncontrados.setBounds(337, 106, 135, 14);
frame_analise.getContentPane().add(lblFrutosEncontrados);
lblFrutosEncontrados.setVisible(false);
JLabel lblVlrFrutos = new JLabel("");
lblVlrFrutos.setBounds(470, 106, 135, 14);
frame_analise.getContentPane().add(lblVlrFrutos);
lblVlrFrutos.setVisible(false);
JLabel lblVlrFrutosVermelhos = new JLabel("");
lblVlrFrutosVermelhos.setBounds(470, 131, 135, 14);
frame_analise.getContentPane().add(lblVlrFrutosVermelhos);
lblVlrFrutosVermelhos.setVisible(false);
JLabel lblVlrFrutosVerdes = new JLabel("");
lblVlrFrutosVerdes.setBounds(470, 156, 135, 14);
frame_analise.getContentPane().add(lblVlrFrutosVerdes);
lblVlrFrutosVerdes.setVisible(false);
JLabel lblFrutosVerdes = new JLabel("Frutos verdes:");
lblFrutosVerdes.setBounds(337, 131, 135, 14);
frame_analise.getContentPane().add(lblFrutosVerdes);
lblFrutosVerdes.setVisible(false);
JLabel lblFrutosMaduros = new JLabel("Frutos maduros:");
lblFrutosMaduros.setBounds(337, 156, 125, 14);
frame_analise.getContentPane().add(lblFrutosMaduros);
frame_analise.setLocationRelativeTo(null);
lblFrutosMaduros.setVisible(false);
btnMenuPrincipal.setVisible(false);
ComparaImagensController cic = new ComparaImagensController();
try {
Relatorio rel = cic.iniciarRelatorio(r);
Integer integerVermelhos = rel.getFrutos_vermelhos();
Integer integerVerdes = rel.getN_frutos() - rel.getFrutos_vermelhos();
Integer integerTotal = rel.getN_frutos();
Integer integerPorcentagemVerm = rel.getPorcentagemVermelho();
Integer integerPorcentagemVerdes = rel.getPorcentagemVerde();
if (rel.isEh_cafe()) {
lblEstadoFoto.setText("<html><font color='green'>Foto vรกlida!</font></html>");
lblVlrFrutos.setText(integerTotal.toString());
lblVlrFrutosVerdes.setText(integerVerdes.toString() + " - (" + integerPorcentagemVerdes.toString() + "%)");
lblVlrFrutosVermelhos.setText(integerVermelhos.toString() + " - (" + integerPorcentagemVerm.toString() + "%)");
lblFrutosEncontrados.setVisible(true);
lblFrutosMaduros.setVisible(true);
lblFrutosVerdes.setVisible(true);
lblVlrFrutos.setVisible(true);
lblVlrFrutosVerdes.setVisible(true);
lblVlrFrutosVermelhos.setVisible(true);
btnMenuPrincipal.setVisible(true);
} else {
lblEstadoFoto.setText("<html><font color='red'>Foto invรกlida!</font></html>");
btnMenuPrincipal.setVisible(true);
}
} catch (Exception e1) {
e1.printStackTrace();
}
btnMenuPrincipal.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
telaInicial ti = new telaInicial();
frame_analise.setVisible(false);
ti.frame_inicial.setVisible(true);
}
});
}
public void setRelatorio(Relatorio rel) {
this.r = rel;
}
public Relatorio getRelatorio() {
return r;
}
}
|
package Controladores;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import Generadores.*;
import ControladoresTeclas.*;
public class ElegirAtenEncTaxis extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
private double numeroConstante = 0;
private double numeroExponencial = 0;
private double numeroNormalDesvio = 0;
private double numeroNormalMedia = 0;
private double numeroParaTodos = 1;
private JLabel titulo = new JLabel("Seleccione : ");
private JLabel etiNormalMedia = new JLabel("Media:");
private JLabel etiNormalDesvio = new JLabel("Desvio:");
private JLabel etiExpoMedia = new JLabel("Media:");
private JLabel etiConstante = new JLabel("Constante:");
private ButtonGroup Distribuciones = new ButtonGroup();
private JRadioButton radioNormal;
private JRadioButton radioExponencial;
private JRadioButton radioConstante;
private JTextField campoNormalMedia;
private JTextField campoNormalDesvio;
private JTextField campoExpoMedia;
private JTextField campoUniforme;
private JButton botonAceptar = new JButton("Aceptar");
private JButton botonCancelar = new JButton("Cancelar ");
private boolean constante =false;
private boolean exponencial = false;
private boolean normal = false;
private static ElegirAtenEncTaxis instancia ;
private ImageIcon image = new ImageIcon("imagenes/atencionLlamada.gif");
private Image icono = image.getImage().getScaledInstance(50, 50,Image.SCALE_DEFAULT);
public ElegirAtenEncTaxis(){
setBounds(100, 100, 200, 300);
getContentPane().setLayout(null);
setTitle("Configurar Distribucion");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
ajusteComponentes();
anidarComponentes();
controlTeclas();
anidarOyente();
this.dispose();
//Israel
//setVisible(true);
}
public static ElegirAtenEncTaxis getInstancia(){
if(instancia == null){
instancia = new ElegirAtenEncTaxis();
}
return instancia;
}
public JTextField getCampoConstante() {
return campoUniforme;
}
public void setCampoConstante(JTextField campoConstante) {
this.campoUniforme = campoConstante;
}
public JTextField getCampoNormalMedia() {
return campoNormalMedia;
}
public void setCampoNormalMedia(JTextField campoNormalMedia) {
this.campoNormalMedia = campoNormalMedia;
}
public JTextField getCampoNormalDesvio() {
return campoNormalDesvio;
}
public void setCampoNormalDesvio(JTextField campoNormalDesvio) {
this.campoNormalDesvio = campoNormalDesvio;
}
public JTextField getCampoExpoMedia() {
return campoExpoMedia;
}
public void setCampoExpoMedia(JTextField campoExpoMedia) {
this.campoExpoMedia = campoExpoMedia;
}
public double getNumeroConstante() {
return numeroConstante;
}
public void setNumeroConstante(double numeroConstante) {
this.numeroConstante = numeroConstante;
}
public double getNumeroExponencial() {
return numeroExponencial;
}
public void setNumeroExponencial(double numeroExponencial) {
this.numeroExponencial = numeroExponencial;
}
public double getNumeroNormalDesvio() {
return numeroNormalDesvio;
}
public void setNumeroNormalDesvio(double numeroNormalDesvio) {
this.numeroNormalDesvio = numeroNormalDesvio;
}
public double getNumeroNormalMedia() {
return numeroNormalMedia;
}
public void setNumeroNormalMedia(double numeroNormalMedia) {
this.numeroNormalMedia = numeroNormalMedia;
}
public double getNumeroParaTodos() {
return numeroParaTodos;
}
public void setNumeroParaTodos(double numeroParaTodos) {
this.numeroParaTodos = numeroParaTodos;
//System.out.println("El numero se cambio a:" + numeroParaTodos);
}
public boolean getConstanteBoolean() {
return constante;
}
public void setConstanteBoolean(boolean constante) {
this.constante = constante;
}
public boolean getExponencialBoolean() {
return exponencial;
}
public void setExponencialBoolean(boolean exponencial) {
this.exponencial = exponencial;
}
public boolean getNormalBoolean() {
return normal;
}
public void setNormalBoolean(boolean normal) {
this.normal = normal;
}
public void ajusteComponentes(){
titulo.setBounds(50, 10, 100, 20);
radioNormal = new JRadioButton("Normal (Minutos)");
radioNormal.setBounds(5, 40, 150, 20);
etiNormalMedia.setBounds(35, 65, 50, 20);
etiNormalMedia.setEnabled(false);
campoNormalMedia = new JTextField();
campoNormalMedia.setBounds(80, 65, 50, 25);
campoNormalMedia.setEnabled(false);
etiNormalDesvio.setBounds(35, 90, 50, 20);
etiNormalDesvio.setEnabled(false);
campoNormalDesvio = new JTextField();
campoNormalDesvio.setBounds(80, 90, 50, 25);
campoNormalDesvio.setEnabled(false);
radioExponencial = new JRadioButton("Exponencial (Minutos)");
radioExponencial.setBounds(5, 125, 150, 20);
etiExpoMedia.setBounds(35, 150, 50, 20);
etiExpoMedia.setEnabled(false);
campoExpoMedia = new JTextField();
campoExpoMedia.setBounds(80, 150, 50, 25);
campoExpoMedia.setEnabled(false);
radioConstante = new JRadioButton("Constante (Minutos)");
radioConstante.setBounds(5, 185, 150, 20);
etiConstante.setBounds(35, 210, 50, 20);
etiConstante.setEnabled(false);
campoUniforme = new JTextField();
campoUniforme.setBounds(80, 210, 50, 25);
campoUniforme.setEnabled(false);
botonAceptar.setBounds(0,240,190,30);
botonAceptar.setEnabled(false);
}
public void controlTeclas(){
campoUniforme.setDocument(new ControlTeclas());
campoExpoMedia.setDocument(new ControlTeclas());
campoNormalDesvio.setDocument(new ControlTeclas());
campoNormalMedia.setDocument(new ControlTeclas());
}
public void anidarComponentes(){
add(titulo);
add(etiExpoMedia);
add(etiNormalDesvio);
add(etiNormalMedia);
add(etiConstante);
Distribuciones.add(radioConstante);
Distribuciones.add(radioExponencial);
Distribuciones.add(radioNormal);
add(radioExponencial);
add(radioNormal);
add(radioConstante);
add(campoExpoMedia);
add(campoNormalDesvio);
add(campoNormalMedia);
add(campoUniforme);
add(botonAceptar);
}
public void anidarOyente(){
ElegirAtenEncTaxis.Oyente oyente = new ElegirAtenEncTaxis.Oyente();
botonAceptar.addActionListener(oyente);
radioNormal.addChangeListener(oyente);
radioConstante.addChangeListener(oyente);
radioExponencial.addChangeListener(oyente);
}
public void cerrar(){
this.dispose();
}
public class Oyente implements ActionListener,ChangeListener {
public void actionPerformed(ActionEvent e) {
if(radioNormal.isSelected()){
ElegirAtenEncTaxis.getInstancia().setNumeroNormalDesvio(Double.parseDouble(campoNormalDesvio.getText()));
ElegirAtenEncTaxis.getInstancia().setNumeroNormalMedia(Double.parseDouble(campoNormalMedia.getText()));
ElegirAtenEncTaxis.getInstancia().setNormalBoolean(true);
calcularValor();
JOptionPane.showMessageDialog(null, "Se cambio tiempo de \n Arribo de los clientes", "Message", JOptionPane.INFORMATION_MESSAGE, new ImageIcon(icono));
cerrar();
}
if(radioExponencial.isSelected()){
ElegirAtenEncTaxis.getInstancia().setExponencialBoolean(true);
ElegirAtenEncTaxis.getInstancia().setNumeroExponencial(Integer.parseInt(campoExpoMedia.getText()));
calcularValor();
JOptionPane.showMessageDialog(null, "Se cambio tiempo de \n Arribo de los clientes", "Message", JOptionPane.INFORMATION_MESSAGE, new ImageIcon(icono));
cerrar();
}
if(radioConstante.isSelected()){
ElegirAtenEncTaxis.getInstancia().setNumeroConstante(Double.parseDouble(campoUniforme.getText()));
ElegirAtenEncTaxis.getInstancia().setConstanteBoolean(true);
calcularValor();
JOptionPane.showMessageDialog(null, "Se cambio tiempo de \n Arribo de los clientes", "Message", JOptionPane.INFORMATION_MESSAGE, new ImageIcon(icono));
cerrar();
}
}
public void stateChanged(ChangeEvent e) {
if(radioNormal.isSelected()){
if(etiExpoMedia.isEnabled()){
etiExpoMedia.setEnabled(false);
campoExpoMedia.setEnabled(false);
}
if(etiConstante.isEnabled()){
etiConstante.setEnabled(false);
campoUniforme.setEnabled(false);
}
if(!etiNormalDesvio.isEnabled()){
etiNormalDesvio.setEnabled(true);
campoNormalDesvio.setEnabled(true);
etiNormalMedia.setEnabled(true);
campoNormalMedia.setEnabled(true);
}
botonAceptar.setEnabled(true);
}
if(radioExponencial.isSelected()){
if(etiConstante.isEnabled()){
etiConstante.setEnabled(false);
campoUniforme.setEnabled(false);
}
if(etiNormalDesvio.isEnabled()){
etiNormalDesvio.setEnabled(false);
campoNormalDesvio.setEnabled(false);
etiNormalMedia.setEnabled(false);
campoNormalMedia.setEnabled(false);
}
if(!etiExpoMedia.isEnabled()){
etiExpoMedia.setEnabled(true);
campoExpoMedia.setEnabled(true);
}
botonAceptar.setEnabled(true);
}
if(radioConstante.isSelected()){
if(!etiConstante.isEnabled()){
etiConstante.setEnabled(true);
campoUniforme.setEnabled(true);
}
if(etiNormalDesvio.isEnabled()){
etiNormalDesvio.setEnabled(false);
campoNormalDesvio.setEnabled(false);
etiNormalMedia.setEnabled(false);
campoNormalMedia.setEnabled(false);
}
if(etiExpoMedia.isEnabled()){
etiExpoMedia.setEnabled(false);
campoExpoMedia.setEnabled(false);
}
botonAceptar.setEnabled(true);
}
}
}
public double calcularValor(){
if( ElegirAtenEncTaxis.getInstancia().getConstanteBoolean()== true){
ElegirAtenEncTaxis.getInstancia().setNumeroParaTodos(ElegirAtenEncTaxis.getInstancia().getNumeroConstante());
}
if(ElegirAtenEncTaxis.getInstancia().getExponencialBoolean() == true){
DistribucionExponencial distriExponencial = new DistribucionExponencial();
distriExponencial.generarValor(ElegirAtenEncTaxis.getInstancia().getNumeroExponencial());
numeroParaTodos = distriExponencial.getValor();
ElegirAtenEncTaxis.getInstancia().setNumeroParaTodos(numeroParaTodos);
}
if(ElegirAtenEncTaxis.getInstancia().getNormalBoolean() == true){
DistribucionMedia distriMedia = new DistribucionMedia();
distriMedia.generar(ElegirAtenEncTaxis.getInstancia().getNumeroNormalMedia(), ElegirAtenEncTaxis.getInstancia().getNumeroNormalDesvio());
numeroParaTodos = distriMedia.getValor();
ElegirAtenEncTaxis.getInstancia().setNumeroParaTodos(numeroParaTodos);
}
if(ElegirAtenEncTaxis.getInstancia().getConstanteBoolean()==false && ElegirAtenEncTaxis.getInstancia().getExponencialBoolean()==false && ElegirAtenEncTaxis.getInstancia().getNormalBoolean()==false){
DistribucionMedia distriMedia = new DistribucionMedia();
distriMedia.generar(10, 2);
numeroParaTodos = distriMedia.getValor();
ElegirAtenEncTaxis.getInstancia().setNumeroParaTodos(numeroParaTodos);
}
return numeroParaTodos;
}
/*
public static void main(String[]args)
{
new ElegirArriboCamionetas();
}*/
}
|
package com.example.my_attend;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.widget.ListView;
import com.example.Class.GetAllParams;
import com.example.Class.Person;
import com.example.firstprogram.R;
import com.example.firstprogram.myAdapter.CardsAdapter;
import com.example.my_publish.event;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* Created by ๆผซ่ฑ็ป่ฝ on 2015/8/10.
*/
public class MyAttendActivity extends Activity {
private ListView listview;
private CardsAdapter cardsAdapter;
private GetAllParams getAllParams;
private JSONArray jsonArray;
private List<event> listData;
private Person person;
private Context mContext;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myattend_activity);
init();
set_Adapter();
}
private void init() {
mContext = this;
person = (Person) getApplication();
getAllParams = new GetAllParams(this);
//findviewbyid
listview = (ListView) findViewById(R.id.listview);
}
//่ทๅพlist็ๆฐๆฎๆบ
private List<event> getListData() throws JSONException {
List<event> mylist = new ArrayList<>();
for(int i=0;i<jsonArray.length();i++) {
event e = new event((JSONObject) jsonArray.get(i));
mylist.add(e);
}
return mylist;
}
private void set_Adapter(){
//http://120.24.208.130:1503/event/query_join
JSONObject param = new JSONObject();
try {
param.put("id", person.getId());
param.put("type", 2);
} catch (JSONException e) {
e.printStackTrace();
}
getAllParams.getList("http://120.24.208.130:1503/event/query_join",
param,
new GetAllParams.VolleyJsonCallback() {
@Override
public void onSuccess(JSONObject result) {
try {
jsonArray = result.getJSONArray("event_list");
listData = getListData();
cardsAdapter = new CardsAdapter(mContext, listData);
listview.setAdapter(cardsAdapter);
cardsAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
|
package com.bridgelabz.book;
import java.util.ArrayList;
import java.util.Date;
public class MainBook {
ArrayList<Book> books = new ArrayList<>();
public void loadBooks() {
Book book1 = new Book("Rich Dad Poor Dad", "Shubham", 2000, new Date());
Book book2 = new Book("Java Basics", "Varad", 1000, new Date());
Book book3 = new Book("Java Basics", "Varad", 1000, new Date());
Book book4 = new Book("Linux Basics", "Piyush", 1500, new Date());
Book book5 = new Book("Java Basics", "Varad", 1800, new Date());
books.add(book1);
books.add(book2);
books.add(book3);
books.add(book4);
books.add(book5);
}
public void calculateTotal() {
int totals = 0;
for (Book book : books) {
totals += book.getPrice();
}
System.out.println(totals);
}
public void storeNames() {
String[] bookNames = new String[5];
for (int i = 0; i < books.size(); i++) {
// bookNames[i] = books.get(i).getBookName();
Book book = books.get(i);
bookNames[i] = book.getBookName();
}
for (String bName : bookNames) {
System.out.println(bName);
}
}
public void reverseNames() {
for (int i = books.size() - 1; i >= 0; i--) {
System.out.println(books.get(i).getBookName());
}
}
public static void main(String[] args) {
MainBook mainBook = new MainBook();
mainBook.loadBooks();
mainBook.calculateTotal();
mainBook.storeNames();
mainBook.reverseNames();
/*
* Book book1 = new Book("Rich Dad Poor Dad", "Shubham", 2000, new Date()); Book
* book2 = new Book("Java Basics", "Varad", 1000, new Date()); Book book3 = new
* Book("Java Basics", "Varad", 1000, new Date()); Book book4 = new
* Book("Linux Basics", "Piyush", 1500, new Date()); Book book5 = new
* Book("Java Basics", "Varad", 1800, new Date());
*/
/*
* System.out.println(book1); System.out.println(book2);
* System.out.println(book3); System.out.println(book4);
* System.out.println(book5);
*/
/*
* System.out.println(reverseString(book1.bookName));
* System.out.println(reverseString(book2.bookName));
* System.out.println(reverseString(book3.bookName));
* System.out.println(reverseString(book4.bookName));
* System.out.println(reverseString(book5.bookName));
*/
}
public static String reverseString(String str) {
StringBuilder sb = new StringBuilder(str);
sb.reverse();
return sb.toString();
}
}
|
package com.pyr0g3ist.knowmasu.entity.enums;
public enum TestType {
CHOICE,
INPUT
}
|
package com.lenovohit.hwe.treat.web.his;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.lenovohit.core.utils.JSONUtils;
import com.lenovohit.core.web.MediaTypes;
import com.lenovohit.core.web.utils.Result;
import com.lenovohit.core.web.utils.ResultUtils;
import com.lenovohit.hwe.org.web.rest.OrgBaseRestController;
import com.lenovohit.hwe.treat.model.Profile;
import com.lenovohit.hwe.treat.service.HisProfileService;
import com.lenovohit.hwe.treat.transfer.RestEntityResponse;
import com.lenovohit.hwe.treat.transfer.RestListResponse;
/**
*
* ็ฑปๆ่ฟฐ๏ผ ๆกฃๆก็ธๅ
ณๅค็
*@author GW
*@date 2018ๅนด2ๆ1ๆฅ
*
*/
@RestController
@RequestMapping("/hwe/treat/his/profile/")
public class ProfileHisController extends OrgBaseRestController {
@Autowired
private HisProfileService hisProfileService;
/**
* ๅ่ฝๆ่ฟฐ๏ผๆ นๆฎๆกไปถๆฅ่ฏขๆกฃๆกๅ่กจ
*@param data
*@return
*@author GW
*@date 2018ๅนด2ๆ1ๆฅ
*/
@RequestMapping(value = "list", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
public Result forList(@RequestParam(value = "data", defaultValue = "") String data) {
Profile model = JSONUtils.deserialize(data, Profile.class);
RestListResponse<Profile> response = this.hisProfileService.findList(model, null);
if(response.isSuccess())
return ResultUtils.renderSuccessResult(response.getList());
else
return ResultUtils.renderFailureResult(response.getMsg());
}
/**
* ๅ่ฝๆ่ฟฐ๏ผๆ นๆฎๆกไปถๆฅ่ฏขๆกฃๆก่ฏฆๆ
*@param data
*@return
*@author GW
*@date 2018ๅนด2ๆ1ๆฅ
*/
@RequestMapping(value = "info", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
public Result forProfileInfo(@RequestParam(value = "data", defaultValue = "") String data) {
Profile model = JSONUtils.deserialize(data, Profile.class);
RestEntityResponse<Profile> response = this.hisProfileService.getInfo(model, null);
if(response.isSuccess())
return ResultUtils.renderSuccessResult(response.getEntity());
else
return ResultUtils.renderFailureResult(response.getMsg());
}
}
|
/**
* This code finds first circular tour that visits all petrol pumps
* Reference: https://www.geeksforgeeks.org/find-a-tour-that-visits-all-stations/
* example: {4, 6}, {6, 5}, {7, 3} and {4, 5}
* {4, 6}, {6, 3}, {7, 11} and {4, 5}
*/
class PetrolPump {
int petrol;
int distance;
public PetrolPump(int petrol, int distance) {
this.petrol = petrol;
this.distance = distance;
}
}
public class GasStationProblem {
// This function returns the starting point, if there is possible solution,
// otherwise returns -1
public static int printTour(PetrolPump[] arr, int n) {
int start = 0;
int end = 1;
int current_Petrol = arr[start].petrol - arr[start].distance;
while(end != start || current_Petrol < 0) {
// If current amount of petrol in truck becomes less than 0, then
// remove the starting petrol pump from tour
while(current_Petrol < 0 && start != end) {
// remove starting point and change start
current_Petrol -= arr[start].petrol - arr[start].distance;
start = (start + 1) % n;
// If 0 is being considered as start again, then there is no
// possible solution
if(start == 0)
return -1;
}
// add a petrol pump to the current tour
current_Petrol += arr[end].petrol - arr[end].distance;
end = (end + 1) % n; // do not forget mod n to avoid index out of bound exception
}
return start;
}
// main method
public static void main(String args[]) {
PetrolPump[] arr = {new PetrolPump(4, 6),
new PetrolPump(6, 5),
new PetrolPump(7, 3),
new PetrolPump(4, 5)};
int start = printTour(arr, arr.length);
System.out.println(start == -1 ? "No Solution" : "Start = " + start);
}
}
|
/**
* Sencha GXT 3.0.1 - Sencha for GWT
* Copyright(c) 2007-2012, Sencha, Inc.
* licensing@sencha.com
*
* http://www.sencha.com/products/gxt/license/
*/
package com.sencha.gxt.explorer.client.thumbs;
import com.google.gwt.core.client.GWT;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.ImageResource;
public interface ExampleThumbs extends ClientBundle {
public static ExampleThumbs THUMBS = GWT.create(ExampleThumbs.class);
ImageResource accordionlayout();
ImageResource accordionwindow();
ImageResource advancedbinding();
ImageResource advancedcombobox();
ImageResource advancedforms();
ImageResource advancedlistview();
ImageResource advancedtabs();
ImageResource advancedtoolbar();
ImageResource aggregationrowgrid();
ImageResource anchorlayout();
ImageResource areachart();
ImageResource arearendererchart();
ImageResource asynctree();
ImageResource asynctreegrid();
ImageResource asyncxmltreepanel();
ImageResource barchart();
ImageResource barrendererchart();
ImageResource basicbinding();
ImageResource basicdnd();
ImageResource basicdraw();
ImageResource basicgrid();
ImageResource basictabs();
ImageResource basictoolbar();
ImageResource basictree();
ImageResource basictreegrid();
ImageResource beanmodelgrid();
ImageResource bluechart();
ImageResource borderlayout();
ImageResource bufferedgrid();
ImageResource buttonaligning();
ImageResource buttons();
ImageResource cardlayout();
ImageResource cellactiontree();
ImageResource cellgrid();
ImageResource centerlayout();
ImageResource checkboxgrid();
ImageResource checkboxlistview();
ImageResource checkboxtree();
ImageResource columnchart();
ImageResource columngrouping();
ImageResource columnlayout();
ImageResource columnrendererchart();
ImageResource combobox();
ImageResource contextmenutree();
ImageResource converter();
ImageResource customizedtree();
ImageResource customslider();
ImageResource dashboard();
ImageResource datecelllistview();
ImageResource datepicker();
ImageResource dialog();
ImageResource draggable();
ImageResource duallistfield();
ImageResource dynamicchart();
ImageResource editablebufferedgrid();
ImageResource editablegrid();
ImageResource editortreegrid();
ImageResource fasttree();
ImageResource fileupload();
ImageResource filterchart();
ImageResource filtergrid();
ImageResource filtertree();
ImageResource filtertreegrid();
ImageResource forms();
ImageResource fx();
ImageResource gaugechart();
ImageResource gridbinding();
ImageResource gridplugins();
ImageResource gridstorebinding();
ImageResource gridtogrid();
ImageResource groupedbarchart();
ImageResource grouping();
ImageResource hboxlayout();
ImageResource helloworld();
ImageResource htmllayoutcontainer();
ImageResource imagechart();
ImageResource imageorganizer();
ImageResource jsongrid();
ImageResource layoutpanel();
ImageResource linechart();
ImageResource linegapchart();
ImageResource listpropertybinding();
ImageResource listtolist();
ImageResource listview();
ImageResource listviewbinding();
ImageResource livechart();
ImageResource livegrid();
ImageResource livegroupsummary();
ImageResource localpaging();
ImageResource localstoragegrid();
ImageResource menubar();
ImageResource messagebox();
ImageResource mixedchart();
ImageResource multicomponent();
ImageResource overflowtoolbar();
ImageResource overview();
ImageResource paging();
ImageResource pagingbeanmodelgrid();
ImageResource paginggrid();
ImageResource paginguibinder();
ImageResource piechart();
ImageResource pierendererchart();
ImageResource portal();
ImageResource radarchart();
ImageResource reorderingtree();
ImageResource reorderingtreegrid();
ImageResource requestfactory();
ImageResource resizable();
ImageResource rotatetext();
ImageResource roweditorgrid();
ImageResource roweditortreegrid();
ImageResource rowexpander();
ImageResource rowlayout();
ImageResource rownumberer();
ImageResource rownumbertreegrid();
ImageResource scatterchart();
ImageResource scatterrendererchart();
ImageResource sencha();
ImageResource slider();
ImageResource stackedbarchart();
ImageResource statustoolbar();
ImageResource templates();
ImageResource tooltipchart();
ImageResource tooltips();
ImageResource treegridtotreegrid();
ImageResource treetotree();
ImageResource vboxlayout();
ImageResource widgetrenderergrid();
ImageResource widgetrenderertreegrid();
ImageResource xmlgrid();
}
|
package com.ecjtu.hotel.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ecjtu.hotel.pojo.Room;
import com.ecjtu.hotel.service.IRoomService;
@Controller
public class RoomController {
@Autowired
private IRoomService roomService;
@RequestMapping("/addRoom")
@ResponseBody
public String addRoom(@ModelAttribute Room room) {
return roomService.addRoom(room)!=0?"ok":"error";
}
@RequestMapping("/deleteRoom")
@ResponseBody
public String deleteRoom(Integer id) {
return roomService.deleteRoomById(id)!=0?"ok":"error";
}
@RequestMapping("/updateRoom")
@ResponseBody
public String updateRoom(@ModelAttribute Room room) {
return roomService.updateRoomById(room)!=0?"ok":"error";
}
@RequestMapping("/listRoom")
public String listRoom(Model model) {
List<Room>rooms=roomService.getAllRooms();
model.addAttribute("rooms", rooms);
return "WEB-INF/app/showrooms";
}
@RequestMapping("/edidtRoom")
@ResponseBody
public Room listRoom(Model model,Integer id) {
Room room=roomService.getRoomById(id);
model.addAttribute("room", room);
return room;
}
}
|
package com.esum.comp.dbc.jdbc.common;
import java.util.LinkedList;
import java.util.List;
/**
* Holds information about a parsed SQL statement.
*/
public class ParsedSQL {
private String actualSql;
private String originalSql;
private List<String> parameterNames = new LinkedList<String>();
private List<int[]> parameterIndexes = new LinkedList<int[]>();
private int namedParameterCount;
private int unnamedParameterCount;
private int totalParameterCount;
public ParsedSQL(String originalSql) {
this.originalSql = originalSql;
}
public String getOriginalSql() {
return this.originalSql;
}
public void setActualSql(String actualSql) {
this.actualSql = actualSql;
}
public String getActualSql() {
return this.actualSql;
}
public void addNamedParameter(String parameterName, int startIndex, int endIndex) {
this.parameterNames.add(parameterName);
this.parameterIndexes.add(new int[] {startIndex, endIndex});
}
public void addNamedParameter(String parameterName) {
this.parameterNames.add(parameterName);
}
public List<String> getParameterNames() {
return this.parameterNames;
}
public int[] getParameterIndexes(int parameterPosition) {
return this.parameterIndexes.get(parameterPosition);
}
public void setNamedParameterCount(int namedParameterCount) {
this.namedParameterCount = namedParameterCount;
}
public int getNamedParameterCount() {
return this.namedParameterCount;
}
public void setUnnamedParameterCount(int unnamedParameterCount) {
this.unnamedParameterCount = unnamedParameterCount;
}
public int getUnnamedParameterCount() {
return this.unnamedParameterCount;
}
public void setTotalParameterCount(int totalParameterCount) {
this.totalParameterCount = totalParameterCount;
}
public int getTotalParameterCount() {
return this.totalParameterCount;
}
public void cleanup() {
parameterNames.clear();
parameterNames = null;
parameterIndexes.clear();
parameterIndexes = null;
originalSql = null;
actualSql = null;
}
/**
* Exposes the original SQL String.
*/
@Override
public String toString() {
return this.originalSql;
}
}
|
package com.yg.dao;
import java.util.List;
public interface BaseMapper<T> {
Integer save(T entity);
Integer delete(Integer id);
Integer update(T entity);
T get(Integer id);
List<T> findAll();
}
|
package com.proyecto.proyecto.rest;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.proyecto.proyecto.dao.ContactsDAO;
import com.proyecto.proyecto.entidades.Contacts;
@RestController
@RequestMapping("products")
public class ContactsREST {
@Autowired
private ContactsDAO productDao;
//@GetMapping
@CrossOrigin(origins = "http://localhost:8080")
@GetMapping
public ResponseEntity<List<Contacts>> getContacts() {
List<Contacts> contacts = productDao.findAll();
return ResponseEntity.ok(contacts);
}
//@GetMapping
@RequestMapping(value= "{contactId}")
public ResponseEntity<Contacts> getProductById(@PathVariable("contactId") Long productId) {
Optional<Contacts> optionalContact = productDao.findById(productId);
if (optionalContact.isPresent()) {
return ResponseEntity.ok(optionalContact.get());
} else {
return ResponseEntity.noContent().build();
}
}
@PostMapping
public ResponseEntity<Contacts> createProduct(@RequestBody Contacts contact) {
Contacts newProduct = productDao.save(contact);
return ResponseEntity.ok(newProduct);
}
@DeleteMapping (value ="{contactId}")
public ResponseEntity<Void> deleteProduct(@PathVariable("contactId") Long contactId) {
productDao.deleteById(contactId);
return ResponseEntity.ok(null);
}
@PutMapping
public ResponseEntity<Contacts> updateContact (@RequestBody Contacts contact){
Optional<Contacts> optionalContact = productDao.findById(contact.getId());
if (optionalContact.isPresent()) {
Contacts updateContact = optionalContact.get();
updateContact.getName();
productDao.save(updateContact);
return ResponseEntity.ok(updateContact);
} else {
return ResponseEntity.notFound().build();
}
}
}
|
package co.udea.registro.api;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class RegistroApiApplication {
public static void main(String[] args) {
SpringApplication.run(RegistroApiApplication.class, args);
}
}
|
/**
* HTTPๅ่ฝๆๅก.
*/
package xyz.noark.network.http;
|
import java.util.Scanner;
/**
* Kaydee Gilson
* Final Project
* PigGame Class: this class contains the methods that actually play the game of pig.
*/
public class PigGame {
//instance data
private PigPlayer player1;
private PigPlayer player2;
public static final int GOAL = 100;
public static boolean verbose = false;
//constructors
//a default constructor that creates two UserPigPlayers (Player 1 and Player 2)
public PigGame() {
player1 = new UserPigPlayer("Player 1");
player2 = new UserPigPlayer("Player 2");
}
//a constructor that takes two Strings, and creates two UserPigPlayers with those two Strings as the names
public PigGame(String player1, String player2) {
this.player1 = new UserPigPlayer(player1);
this.player1 = new UserPigPlayer(player1);
}
//a constructor that takes two PigPlayers
public PigGame(PigPlayer player1, PigPlayer player2) {
this.player1 = player1;
this.player2 = player2;
}
//resets the two PigPlayers
public void reset() {
player1.reset();
player2.reset();
}
//////////////////// playTurn method //////////////////
//The playTurn method returns the turn total rolled (0 if 1 was rolled, or the turn total if the player chose to stop rolling.
public static int playTurn(PigPlayer player, PigPlayer opponent) {
int turnTotal = 0;
while (player.isRolling(turnTotal, opponent.getScore()) == true) {
int value = Die.roll();
if (verbose == true) {
System.out.println("Roll: " + value);
}
if (value == 1) {
return 0;
}
else {
turnTotal = turnTotal + value;
}
}
if (verbose == true) {
System.out.println();
}
return turnTotal;
}
//////////////////////////////////// playGame method ////////////////////////////////////
//plays an entire game of Pig, where each PigPlayer gets a turn until one player wins
public void playGame() {
int turnTotal = 0;
int currentTurn = 1;
reset();
while (player1.won() == false && player2.won() == false) {
//print score of first player
if (verbose == true) {
System.out.println(player1.getName() + "'s score: " + player1.getScore());
}
//print score of second player
if (verbose == true) {
System.out.println(player2.getName() + "'s score: " + player2.getScore());
System.out.println();
}
//determines whose turn it is and adds their points to the score
if (currentTurn == 1) {
player1.addPoints(playTurn(player1, player2));
currentTurn++;
if (verbose == true) {
System.out.println("It is " + player2.getName() + "'s turn.");
}
}
else {
player2.addPoints(playTurn(player2, player1));
currentTurn--;
if (verbose == true) {
System.out.println("It is " + player1.getName() + "'s turn.");
}
}
}
//determines if somebody wins
if (player1.won() == true) {
if (verbose == true) {
System.out.println(player1.getName() + " wins!");
}
}
else if (player2.won() == true) {
if (verbose == true) {
System.out.println(player2.getName() + " wins!");
}
}
}
//////////////////////////////////// UserVsUser Method ////////////////////////////////////
public static void userVsUser() {
System.out.println("Let's play Pig!");
System.out.println("Two players race to reach 100 points.");
System.out.println("Each turn, a player repeatedly rolls a die until either a 1 is rolled or");
System.out.println("the player holds and scores the sum of the rolls (i.e. the turn total).");
System.out.println("When given a choice to roll or hold, please type enter to roll, anything else to hold.");
System.out.println();
//take in and record first name using setName
Scanner keyboard;
System.out.println("What's the first player's name?");
keyboard = new Scanner(System.in);
String firstPlayerName = keyboard.nextLine();
UserPigPlayer firstPlayer = new UserPigPlayer(firstPlayerName);
firstPlayer.setName(firstPlayerName);
//take in and record second name using setName
System.out.println("What's the second player's name? ");
keyboard = new Scanner(System.in);
String secondPlayerName = keyboard.nextLine();
UserPigPlayer secondPlayer = new UserPigPlayer(secondPlayerName);
secondPlayer.setName(secondPlayerName);
PigGame game1;
//calculate who will go first
if (Math.random() > .5) {
System.out.println(firstPlayer.getName() + ", you will go first");
game1 = new PigGame(firstPlayer, secondPlayer);
}
else {
System.out.println(secondPlayer.getName() + ", you will go first");
game1 = new PigGame(secondPlayer, firstPlayer);
}
game1.playGame();
}
//////////////////////////////////// UserVsComputer Method ////////////////////////////////////
public static void userVsComputer() {
System.out.println("Let's play Pig!");
System.out.println("You will race the computer to reach 100 points.");
System.out.println("Each turn, you will roll a die until either a 1 is rolled or");
System.out.println("you choose to hold and then your score will be added to the sum of the rolls (i.e. the turn total).");
System.out.println("When given a choice to roll or hold, please type enter to roll, anything else to hold.");
System.out.println();
//take in and record first name using setName
Scanner keyboard;
System.out.println("What's your name?");
keyboard = new Scanner(System.in);
String firstPlayerName = keyboard.nextLine();
UserPigPlayer firstPlayer = new UserPigPlayer(firstPlayerName);
firstPlayer.setName(firstPlayerName);
//creates computer player
//SimpleHoldPlayer computer = new SimpleHoldPlayer("Computer");
FourTurnsPlayer computer = new FourTurnsPlayer("Computer");
PigGame game1;
//calculate who will go first
if (Math.random() > .5) {
System.out.println(firstPlayer.getName() + ", you will go first");
game1 = new PigGame(firstPlayer, computer);
}
else {
System.out.println("The computer will go first.");
game1 = new PigGame(computer, firstPlayer);
}
game1.playGame();
}
//////////////////////////////////// computerVsComputer Method ////////////////////////////////////
public static void computerVsComputer() {
if (verbose == true) {System.out.println("Let's play Pig!");}
//creates two computer players
SimpleHoldPlayer player1 = new SimpleHoldPlayer("Player 1");
SimpleHoldPlayer player2 = new SimpleHoldPlayer("Player 2");
PigGame game1;
//calculate who will go first
if (Math.random() > .5) {
if (verbose == true) {System.out.println(player1.getName() + ", you will go first");}
game1 = new PigGame(player1, player2);
}
else {
if (verbose == true) {System.out.println(player2.getName() + ", you will go first");}
game1 = new PigGame(player2, player1);
}
game1.playGame();
}
//////////////////////////////////// Main Method ////////////////////////////////////
public static void main(String[] args) {
//userVsUser();
userVsComputer();
//computerVsComputer();
}
}
|
package play.domain.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import lombok.Data;
@Entity
@Data
public class CachePath {
@Id
@GeneratedValue
private Integer id;
private Integer type;
private String key;
private String value;
private String hKey;
private String hVal;
private String score;
private String summary;
public static final int TYPE_STRING = 1;
public static final int TYPE_HASH = 2;
public static final int TYPE_LIST = 3;
public static final int TYPE_SET = 4;
public static final int TYPE_ZSET = 5;
}
|
package queue;
public class Operasi {
private Node FRONT;
private Node REAR;
public void enqueue(int data) {
Node newNode = new Node(data);
if(isEmpty()) {
FRONT = newNode;
REAR = newNode;
} else {
REAR.setNext(newNode);
REAR = newNode;
}
}
public int dequeue() {
Node temp = null;
if(FRONT != null) {
if(FRONT == REAR) {
FRONT = null;
REAR = null;
} else {
temp = FRONT;
FRONT = FRONT.getNext();
dispose(temp);
}
}
return temp.getData();
}
public boolean isEmpty() {
if(FRONT == null) {
return true;
}
return false;
}
private void dispose(Node temp) {
}
public void displayElement() {
Node curNode = FRONT;
if (curNode == null) {
System.out.println("Data kosong");
}
while (curNode != null) {
System.out.print(curNode.getData() + " ");
curNode = curNode.getNext();
}
System.out.println("");
}
public int dataSize() {
int jmlData = 0;
Node curNode = FRONT;
while (curNode != null) {
jmlData++;
curNode = curNode.getNext();
}
return(jmlData);
}
public Node getFRONT() {
return FRONT;
}
public void setFRONT(Node fRONT) {
FRONT = fRONT;
}
public Node getREAR() {
return REAR;
}
public void setREAR(Node rEAR) {
REAR = rEAR;
}
}
|
package com.raydevelopers.sony.match.utils;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.Image;
import android.preference.PreferenceManager;
import android.provider.ContactsContract;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.BounceInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.raydevelopers.sony.match.MainActivity;
import com.raydevelopers.sony.match.R;
import com.raydevelopers.sony.match.UserDetails;
import com.raydevelopers.sony.match.model.Interest;
import com.raydevelopers.sony.match.model.User;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
/**
* Created by SONY on 20-08-2017.
*/
public class MainRecyclerViewAdapter extends RecyclerView.Adapter<MainRecyclerViewAdapter.MyViewHolder> {
private Context mContext;
private ArrayList<User> mUser;
private FirebaseUser user;
private String key;
public MainRecyclerViewAdapter(Context c, ArrayList<User> user)
{
this.mContext=c;
this.mUser=user;
}
@Override
public MainRecyclerViewAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v=LayoutInflater.from(mContext).inflate(R.layout.main_rv,parent,false);
MyViewHolder holder=new MyViewHolder(v);
return holder;
}
@Override
public void onBindViewHolder(final MainRecyclerViewAdapter.MyViewHolder holder, final int position) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i=new Intent(mContext, UserDetails.class);
i.putExtra(Constants.ARG_KEY,mUser.get(position).mkey);
mContext.startActivity(i);
}
});
holder.name.setText(mUser.get(position).mName+", ");
holder.age.setText(String.valueOf(mUser.get(position).mAge));
Picasso.with(mContext).load(mUser.get(position).mProfilePic).into(holder.imageView);
int resultCode=getInterest(mUser.get(position).mkey);
if(resultCode==1)
{
holder.sendInterest.setText("Interest Send");
holder.sendInterest.setEnabled(false);
}
else if(resultCode==2)
{
}
else if(resultCode==0)
{
holder.sendInterest.setText("freinds");
holder.sendInterest.setEnabled(false);
}
holder.sendInterest.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences sharedPreferences= PreferenceManager.getDefaultSharedPreferences(mContext);
String key=sharedPreferences.getString(Constants.ARG_KEY,null);
String bindIds=key+"match"+mUser.get(position).mkey;
ObjectAnimator animY = ObjectAnimator.ofFloat(holder.sendInterest, "translationY", 100f, 0f);
animY.setDuration(1000);//1sec
animY.setInterpolator(new BounceInterpolator());
animY.setRepeatCount(0);
animY.start();
UpdateFirebaseSendUsers(bindIds);
holder.sendInterest.setText("Interest Send");
holder.sendInterest.setEnabled(false);
}
});
}
@Override
public int getItemCount() {
if(mUser.size()>0)
return mUser.size();
else
return 0;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
Button sendInterest;
TextView name,age;
public MyViewHolder(View itemView) {
super(itemView);
sendInterest=(Button)itemView.findViewById(R.id.sendInterest);
imageView=(ImageView)itemView.findViewById(R.id.profile_pic);
name=(TextView)itemView.findViewById(R.id.displayname);
age=(TextView)itemView.findViewById(R.id.age);
}
}
public void UpdateFirebaseSendUsers(final String bindIds)
{
final DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("interest").child(bindIds).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
//Already sent
}
else {
Interest user1 = new Interest();
ref.child("interest").child(bindIds).setValue(user1);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private int getInterest(final String key)
{ SharedPreferences sharedPreferences= PreferenceManager.getDefaultSharedPreferences(mContext);
String currentUser=sharedPreferences.getString(Constants.ARG_KEY,null);
final String sentInterest=currentUser+"match"+key;
final String receivedInterest=key+"match"+currentUser;
final int[] returnCode={-1} ;
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("interest");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dataSnapshot1:dataSnapshot.getChildren())
{
if(dataSnapshot1.getKey().equals(sentInterest))
{
Interest i=dataSnapshot1.getValue(Interest.class);
if(i.mConnected)
{
//freinds return 0
returnCode[0] =0;
}
else
{
//interest already sent return 1
returnCode[0] =1;
}
}
else if(dataSnapshot1.getKey().equals(receivedInterest))
{
Interest i=dataSnapshot1.getValue(Interest.class);
if(i.mConnected)
{
//freinds return 0
returnCode[0] =0;
}
else
{
//interest received show accept button return 2
returnCode[0] =2;
}
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
System.out.println(returnCode[0]);
return returnCode[0];
}
}
|
package com.designurway.idlidosa.ui.home_page.fragments;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavDirections;
import androidx.navigation.Navigation;
import android.os.Parcelable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.designurway.idlidosa.R;
import com.designurway.idlidosa.a.model.AddressModel;
import com.designurway.idlidosa.a.model.CheckServiceModel;
import com.designurway.idlidosa.a.model.CustomerAddress;
import com.designurway.idlidosa.a.retrofit.BaseClient;
import com.designurway.idlidosa.a.retrofit.RetrofitApi;
import com.designurway.idlidosa.a.utils.PreferenceManager;
import com.designurway.idlidosa.databinding.FragmentAddressBookBinding;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.libraries.places.api.Places;
import com.google.android.libraries.places.api.model.Place;
import com.google.android.libraries.places.widget.Autocomplete;
import com.google.android.libraries.places.widget.AutocompleteActivity;
import com.google.android.libraries.places.widget.model.AutocompleteActivityMode;
import org.parceler.Parcels;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static android.app.Activity.RESULT_CANCELED;
import static android.app.Activity.RESULT_OK;
public class AddressBookFragment extends Fragment {
FragmentAddressBookBinding binding;
AddressBookFragmentArgs args;
NavDirections action;
private static int AUTOCOMPLETE_REQUEST_CODE = 1;
String amount, FromSetting, orderId;
private static final String TAG = "AddressFragment";
ImageView checkBox;
ImageView homeChk;
TextView nameTv, addressTv, homePhoneTv, ofcNameTv;
TextView ofcAddressTv, ofcPhoneTv;
ImageView imgSadFace;
CardView cardHomeAddress;
CardView cardOfcAddress;
String name, address, phone;
ImageView imgEditHome;
ImageView imgEditOffice;
LinearLayout linearHome;
LinearLayout LinearOffice;
ImageView officeChk;
TextView officeNameTv, officeAddressTv, ofc_phone_tv, manualLocationAdb, TextOr;
String homePincode, officePincode, pincode;
ConstraintLayout currentLocationLayout;
FusedLocationProviderClient fusedLocationProviderClient;
Context context;
ConstraintLayout constraintItem;
ProgressBar progressAddress;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
binding = FragmentAddressBookBinding.inflate(inflater, container, false);
officeChk = binding.officeChk;
progressAddress = binding.progressAddress;
constraintItem = binding.constraintItem;
officeNameTv = binding.officeNameTv;
officeAddressTv = binding.officeAddressTv;
ofc_phone_tv = binding.ofcPhoneTv;
homeChk = binding.homeChk;
nameTv = binding.nameTv;
addressTv = binding.homeAddressTv;
homePhoneTv = binding.homePhoneTv;
ofcNameTv = binding.officeNameTv;
ofcAddressTv = binding.officeAddressTv;
ofcPhoneTv = binding.ofcPhoneTv;
imgSadFace = binding.imgSadFace;
cardHomeAddress = binding.cardHomeAddress;
cardOfcAddress = binding.cardOfcAddress;
imgEditHome = binding.imgEditHome;
imgEditOffice = binding.imgEditOffice;
linearHome = binding.linearHome;
LinearOffice = binding.LinearOffice;
currentLocationLayout = binding.currentLocationLayout;
manualLocationAdb = binding.manualLocationAdb;
TextOr = binding.TextOr;
context = container.getContext();
args = AddressBookFragmentArgs.fromBundle(getArguments());
amount = args.getAmount();
FromSetting = args.getFromSetting();
orderId = args.getOrderId();
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getActivity());
checkAddressEmpty();
Bundle bundle = getArguments();
Geocoder coder = new Geocoder(getActivity());
List<Address> Homeaddress = null;
try {
Homeaddress = coder.getFromLocationName(addressTv.getText().toString(), 5);
} catch (IOException e) {
e.printStackTrace();
}
if (FromSetting.equals("viewCart")) {
if (FromSetting.equals("viewCart")) {
linearHome.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (addressTv.getText().toString().isEmpty()) {
Toast.makeText(getContext(), "add missing address", Toast.LENGTH_SHORT).show();
return;
} else {
name = officeNameTv.getText().toString();
address = addressTv.getText().toString();
phone = ofc_phone_tv.getText().toString();
checkService(homePincode);
/*
action = AddressBookFragmentDirections.actionAddressBookFragmentToPaymentFragment(name,address,amount,phone,"none","none",orderId);
Navigation.findNavController(getView()).navigate(action);*/
}
}
});
LinearOffice.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (officeAddressTv.getText().toString().isEmpty()) {
Toast.makeText(getContext(), "add missing address", Toast.LENGTH_SHORT).show();
return;
} else {
name = nameTv.getText().toString();
address = officeAddressTv.getText().toString();
phone = homePhoneTv.getText().toString();
checkService(officePincode);
}
}
});
} else {
Toast.makeText(context, "From cart", Toast.LENGTH_SHORT).show();
}
} else {
homeChk.setVisibility(View.GONE);
officeChk.setVisibility(View.GONE);
currentLocationLayout.setVisibility(View.GONE);
manualLocationAdb.setVisibility(View.GONE);
imgEditHome.setVisibility(View.VISIBLE);
imgEditOffice.setVisibility(View.VISIBLE);
TextOr.setVisibility(View.GONE);
imgEditOffice.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
action = AddressBookFragmentDirections.actionAddressBookFragmentToChangeAddressFragment("office");
Navigation.findNavController(getView()).navigate(action);
}
});
imgEditHome.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
action = AddressBookFragmentDirections.actionAddressBookFragmentToChangeAddressFragment("home");
Navigation.findNavController(getView()).navigate(action);
}
});
}
getAddressDetails();
return binding.getRoot();
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Places.initialize(getContext().getApplicationContext(), getString(R.string.google_maps_key));
currentLocationLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
name = officeNameTv.getText().toString();
address = addressTv.getText().toString();
phone = ofc_phone_tv.getText().toString();
action = AddressBookFragmentDirections.actionAddressBookFragmentToLocationFragment(amount, name, phone, orderId);
Navigation.findNavController(v).navigate(action);
}
});
manualLocationAdb.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
List<Place.Field> fields = Arrays.asList(Place.Field.ID, Place.Field.NAME, Place.Field.ADDRESS, Place.Field.ADDRESS_COMPONENTS, Place.Field.LAT_LNG);
// Start the autocomplete intent.
Intent intent = new Autocomplete.IntentBuilder(AutocompleteActivityMode.FULLSCREEN, fields)
.build(getContext());
startActivityForResult(intent, AUTOCOMPLETE_REQUEST_CODE);
}
});
}
public void getAddressDetails() {
RetrofitApi retrofitApi = BaseClient.getClient().create(RetrofitApi.class);
Call<AddressModel> call = retrofitApi.getAddress(PreferenceManager.getCustomerPhone());
call.enqueue(new Callback<AddressModel>() {
@Override
public void onResponse(Call<AddressModel> call, Response<AddressModel> response) {
if (response.isSuccessful()) {
constraintItem.setVisibility(View.VISIBLE);
progressAddress.setVisibility(View.INVISIBLE);
nameTv.setText(response.body().getName());
addressTv.setText(response.body().getHomeAddress());
homePhoneTv.setText(response.body().getPhone());
homePincode = response.body().getPin_code();
officePincode = response.body().getOffice_pin_code();
ofcNameTv.setText(response.body().getName());
ofcAddressTv.setText(response.body().getOtherAddress());
ofcPhoneTv.setText(response.body().getPhone());
} else {
constraintItem.setVisibility(View.VISIBLE);
progressAddress.setVisibility(View.INVISIBLE);
imgSadFace.setVisibility(View.VISIBLE);
cardHomeAddress.setVisibility(View.GONE);
cardOfcAddress.setVisibility(View.GONE);
}
}
@Override
public void onFailure(Call<AddressModel> call, Throwable t) {
Log.d(TAG, "onFailure" + t.getMessage());
constraintItem.setVisibility(View.VISIBLE);
progressAddress.setVisibility(View.INVISIBLE);
}
});
}
public void checkService(String pinCode) {
RetrofitApi retrofitApi = BaseClient.getClient().create(RetrofitApi.class);
Call<CheckServiceModel> call = retrofitApi.checkService(pinCode);
call.enqueue(new Callback<CheckServiceModel>() {
@Override
public void onResponse(Call<CheckServiceModel> call, Response<CheckServiceModel> response) {
if (response.isSuccessful() && response.body().getMessage().equals("available")) {
action = AddressBookFragmentDirections.actionAddressBookFragmentToPaymentFragment(name, address, amount, phone, "none", "none", orderId);
Navigation.findNavController(getView()).navigate(action);
} else {
action = AddressBookFragmentDirections.actionAddressBookFragmentToServiceNotAvailableFragment(address);
Navigation.findNavController(getView()).navigate(action);
}
}
@Override
public void onFailure(Call<CheckServiceModel> call, Throwable t) {
Toast.makeText(getContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
public void checkAddressEmpty() {
if (ofcAddressTv.getText().toString().isEmpty()) {
Toast.makeText(getContext(), "please add missing address", Toast.LENGTH_SHORT).show();
return;
}
if (addressTv.getText().toString().isEmpty()) {
Toast.makeText(getContext(), "please add missing address", Toast.LENGTH_SHORT).show();
return;
}
}
private void getCurrentLoc() {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
fusedLocationProviderClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
@Override
public void onComplete(@NonNull Task<Location> task) {
Location location = task.getResult();
if (location != null) {
Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
String pincode = null;
if (addresses != null && addresses.size() > 0) {
pincode = addresses.get(0).getPostalCode();
Log.d("pincode", "current address" + pincode);
}
/* action = SelectLocationFragmentDirections.actionSelectLocationFragmentToAuthProfileFragment(addresses.get(0).getAddressLine(0),pincode,referralCode,phone);
Navigation.findNavController(getView()).navigate(action);
Toast.makeText(getActivity(), String.valueOf(addresses), Toast.LENGTH_SHORT).show();*/
// action = AddressBookFragmentDirections.actionAddressBookFragmentToServiceNotAvailableFragment(addresses.get(0).getAddressLine(0) );
// Navigation.findNavController(getView()).navigate(action);
name = officeNameTv.getText().toString();
address = addresses.get(0).getAddressLine(0);
phone = ofc_phone_tv.getText().toString();
checkService(pincode);
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, @org.jetbrains.annotations.Nullable Intent data) {
List<Address> addresses = null;
if (requestCode == AUTOCOMPLETE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
Place place = Autocomplete.getPlaceFromIntent(data);
LatLng latLng = place.getLatLng();
try {
Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault());
addresses = geocoder.getFromLocation(place.getLatLng().latitude, place.getLatLng().longitude, 1);
if (addresses != null && addresses.size() > 0) {
pincode = addresses.get(0).getPostalCode();
Log.d("pincode", pincode);
}
} catch (IOException e) {
e.printStackTrace();
}
name = officeNameTv.getText().toString();
address = addresses.get(0).getAddressLine(0);
phone = ofc_phone_tv.getText().toString();
checkService(pincode);
} else if (resultCode == AutocompleteActivity.RESULT_ERROR) {
// TODO: Handle the error.
Status status = Autocomplete.getStatusFromIntent(data);
Log.i(TAG, status.getStatusMessage());
} else if (resultCode == RESULT_CANCELED) {
// The user canceled the operation.
}
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
}
|
/*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jdbc.object;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.PreparedStatementCreatorFactory;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.namedparam.NamedParameterUtils;
import org.springframework.jdbc.core.namedparam.ParsedSql;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
/**
* Operation object representing an SQL-based operation such as a query or update,
* as opposed to a stored procedure.
*
* <p>Configures a {@link org.springframework.jdbc.core.PreparedStatementCreatorFactory}
* based on the declared parameters.
*
* @author Rod Johnson
* @author Juergen Hoeller
*/
public abstract class SqlOperation extends RdbmsOperation {
/**
* Object enabling us to create PreparedStatementCreators efficiently,
* based on this class's declared parameters.
*/
@Nullable
private PreparedStatementCreatorFactory preparedStatementFactory;
/** Parsed representation of the SQL statement. */
@Nullable
private ParsedSql cachedSql;
/** Monitor for locking the cached representation of the parsed SQL statement. */
private final Object parsedSqlMonitor = new Object();
/**
* Overridden method to configure the PreparedStatementCreatorFactory
* based on our declared parameters.
*/
@Override
protected final void compileInternal() {
this.preparedStatementFactory = new PreparedStatementCreatorFactory(resolveSql(), getDeclaredParameters());
this.preparedStatementFactory.setResultSetType(getResultSetType());
this.preparedStatementFactory.setUpdatableResults(isUpdatableResults());
this.preparedStatementFactory.setReturnGeneratedKeys(isReturnGeneratedKeys());
if (getGeneratedKeysColumnNames() != null) {
this.preparedStatementFactory.setGeneratedKeysColumnNames(getGeneratedKeysColumnNames());
}
onCompileInternal();
}
/**
* Hook method that subclasses may override to post-process compilation.
* This implementation does nothing.
* @see #compileInternal
*/
protected void onCompileInternal() {
}
/**
* Obtain a parsed representation of this operation's SQL statement.
* <p>Typically used for named parameter parsing.
*/
protected ParsedSql getParsedSql() {
synchronized (this.parsedSqlMonitor) {
if (this.cachedSql == null) {
this.cachedSql = NamedParameterUtils.parseSqlStatement(resolveSql());
}
return this.cachedSql;
}
}
/**
* Return a PreparedStatementSetter to perform an operation
* with the given parameters.
* @param params the parameter array (may be {@code null})
*/
protected final PreparedStatementSetter newPreparedStatementSetter(@Nullable Object[] params) {
Assert.state(this.preparedStatementFactory != null, "No PreparedStatementFactory available");
return this.preparedStatementFactory.newPreparedStatementSetter(params);
}
/**
* Return a PreparedStatementCreator to perform an operation
* with the given parameters.
* @param params the parameter array (may be {@code null})
*/
protected final PreparedStatementCreator newPreparedStatementCreator(@Nullable Object[] params) {
Assert.state(this.preparedStatementFactory != null, "No PreparedStatementFactory available");
return this.preparedStatementFactory.newPreparedStatementCreator(params);
}
/**
* Return a PreparedStatementCreator to perform an operation
* with the given parameters.
* @param sqlToUse the actual SQL statement to use (if different from
* the factory's, for example because of named parameter expanding)
* @param params the parameter array (may be {@code null})
*/
protected final PreparedStatementCreator newPreparedStatementCreator(String sqlToUse, @Nullable Object[] params) {
Assert.state(this.preparedStatementFactory != null, "No PreparedStatementFactory available");
return this.preparedStatementFactory.newPreparedStatementCreator(sqlToUse, params);
}
}
|
package com.gxc.stu.back.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class PageController {
@RequestMapping("/index.html")
public String backIndex(){
return "chartList";
}
@RequestMapping("/{page}")
public String goPage(@PathVariable String page){
return page;
}
}
|
package com.edasaki.rpg.mobs.spells;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import com.edasaki.rpg.SakiRPG;
import com.edasaki.rpg.mobs.MobData;
public class SlowMobSpell extends MobSpell {
private int duration, tier;
private long cooldown;
private String msg = null;
public SlowMobSpell() {
duration = 5;
tier = 1;
cooldown = 10000;
}
public SlowMobSpell(int duration, int tier, long cooldown, String msg) {
this.duration = duration;
this.tier = tier;
this.cooldown = cooldown;
this.msg = msg;
}
public void castSpell(final LivingEntity caster, final MobData md, Player target) {
if(msg != null)
md.say(target, msg);
if (SakiRPG.plugin.getPD(target) != null)
SakiRPG.plugin.getPD(target).giveSlow(duration, tier);
}
@Override
public long getCastDelay() {
return cooldown;
}
}
|
// This section is for use at end of the mouse handling practical sheet
/** To hold an off-screen image area. For double buffered painting.*/
private Image buffer;
/** For drawing onto buffer. */
private Graphics bufferG;
/** Redraw the drawing panel using an off-screen image for double buffering. */
private void paintDoubleBuffered() {
if (buffer == null) // If necessary, allocate off-screen image for drawing onto
buffer = createImage(400, 400);
bufferG = buffer.getGraphics(); // Get a Graphics to draw on the off-screen image
bufferG.setColor( Color.white ); // White background for drawing
bufferG.fillRect( 0, 0, 400, 400 );
paintScreen(bufferG); // Do standard painting onto the off-screen image
Graphics g = panel.getGraphics(); // Get Graphics for the actual display panel
g.drawImage(buffer, 0, 0, this); // Then replace whole of current panel with new image
} // End of paintDoubleBuffered
|
package AbstractNotes;
//public class Accountant extends Employee {
// public String work() {
// return "Crunching numbers";
// }
//
// Employee bob = new Accountant();
//}
|
package org.vaadin.peter.contextmenu.client;
import java.util.Set;
import org.vaadin.peter.contextmenu.client.ContextMenuState.ContextMenuItemState;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Event.NativePreviewEvent;
import com.google.gwt.user.client.Event.NativePreviewHandler;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.Widget;
/**
* Client side implementation for ContextMenu component
*
* @author Peter Lehto / Vaadin Ltd
*/
public class ContextMenuWidget extends Widget {
private final ContextMenuOverlay menuOverlay;
private final NativePreviewHandler nativeEventHandler = new NativePreviewHandler() {
@Override
public void onPreviewNativeEvent(NativePreviewEvent event) {
if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ESCAPE) {
// Always close the context menu on esc, no matter the focus
hide();
}
Event nativeEvent = Event.as(event.getNativeEvent());
boolean targetsContextMenu = eventTargetContextMenu(nativeEvent);
if (!targetsContextMenu) {
int type = nativeEvent.getTypeInt();
switch (type) {
case Event.ONMOUSEDOWN: {
if (isHideAutomatically()) {
hide();
}
}
}
}
}
};
private final HandlerRegistration nativeEventHandlerRegistration;
private boolean hideAutomatically;
private Widget extensionTarget;
public ContextMenuWidget() {
Element element = DOM.createDiv();
setElement(element);
nativeEventHandlerRegistration = Event
.addNativePreviewHandler(nativeEventHandler);
menuOverlay = new ContextMenuOverlay();
}
protected boolean eventTargetContextMenu(Event nativeEvent) {
for (ContextMenuItemWidget item : menuOverlay.getMenuItems()) {
if (item.eventTargetsPopup(nativeEvent)) {
return true;
}
}
return false;
}
protected boolean isShowing() {
return menuOverlay.isShowing();
}
public void hide() {
menuOverlay.hide();
}
/**
* Adds new item as context menu root item.
*
* @param rootItem
* @param connector
*/
public void addRootMenuItem(ContextMenuItemState rootItem,
ContextMenuConnector connector) {
ContextMenuItemWidget itemWidget = createEmptyItemWidget(rootItem.id,
rootItem.caption, connector);
itemWidget.setEnabled(rootItem.enabled);
itemWidget.setSeparatorVisible(rootItem.separator);
setStyleNames(itemWidget, rootItem.getStyles());
menuOverlay.addMenuItem(itemWidget);
for (ContextMenuItemState childState : rootItem.getChildren()) {
createSubMenu(itemWidget, childState, connector);
}
}
private void setStyleNames(ContextMenuItemWidget item, Set<String> styles) {
for (String style : styles) {
item.addStyleName(style);
}
}
/**
* Creates new empty menu item
*
* @param id
* @param caption
* @param contextMenuConnector
* @return
*/
private ContextMenuItemWidget createEmptyItemWidget(String id,
String caption, ContextMenuConnector contextMenuConnector) {
ContextMenuItemWidget widget = GWT.create(ContextMenuItemWidget.class);
widget.setId(id);
widget.setCaption(caption);
widget.setIcon(contextMenuConnector.getConnection().getIcon(contextMenuConnector.getResourceUrl(id)));
ContextMenuItemWidgetHandler handler = new ContextMenuItemWidgetHandler(
widget, contextMenuConnector);
widget.addClickHandler(handler);
widget.addMouseOutHandler(handler);
widget.addMouseOverHandler(handler);
widget.addKeyUpHandler(handler);
widget.setRootComponent(this);
return widget;
}
private void createSubMenu(ContextMenuItemWidget parentWidget,
ContextMenuItemState childState, ContextMenuConnector connector) {
ContextMenuItemWidget childWidget = createEmptyItemWidget(
childState.id, childState.caption, connector);
childWidget.setEnabled(childState.enabled);
childWidget.setSeparatorVisible(childState.separator);
setStyleNames(childWidget, childState.getStyles());
parentWidget.addSubMenuItem(childWidget);
for (ContextMenuItemState child : childState.getChildren()) {
createSubMenu(childWidget, child, connector);
}
}
public void clearItems() {
menuOverlay.clearItems();
}
public void showContextMenu(int rootMenuX, int rootMenuY) {
menuOverlay.showAt(rootMenuX, rootMenuY);
}
public void showContextMenu(Widget widget) {
menuOverlay.showRelativeTo(widget);
}
public HandlerRegistration addCloseHandler(
CloseHandler<PopupPanel> popupCloseHandler) {
return menuOverlay.addCloseHandler(popupCloseHandler);
}
public void setHideAutomatically(boolean hideAutomatically) {
this.hideAutomatically = hideAutomatically;
}
public boolean isHideAutomatically() {
return hideAutomatically;
}
public void unregister() {
nativeEventHandlerRegistration.removeHandler();
menuOverlay.unregister();
}
public void setExtensionTarget(Widget extensionTarget) {
this.extensionTarget = extensionTarget;
menuOverlay.setOwner(extensionTarget);
}
public Widget getExtensionTarget() {
return extensionTarget;
}
}
|
package com.penglai.haima.dialog;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.penglai.haima.R;
import com.penglai.haima.base.BaseActivity;
import com.penglai.haima.bean.WithdrawDetailBean;
/**
* Created by on 2019/11/5.
* ๆไปถ่ฏดๆ๏ผ
*/
public class WithdrawInfoShowDialog extends BaseDialogView {
TextView tv_name, tv_process0, tv_process1, tv_process2, tv_account;
ImageView img_close;
WithdrawDetailBean withdrawDetailBean;
public WithdrawInfoShowDialog(BaseActivity activity, WithdrawDetailBean withdrawDetailBean) {
super(activity);
this.withdrawDetailBean = withdrawDetailBean;
init(R.layout.dialog_withdraw_info);
}
@Override
public void initData() {
}
@Override
public void initView() {
tv_name = findViewById(R.id.tv_name);
tv_process0 = findViewById(R.id.tv_process0);
tv_process1 = findViewById(R.id.tv_process1);
tv_process2 = findViewById(R.id.tv_process2);
tv_account = findViewById(R.id.tv_account);
img_close = findViewById(R.id.img_close);
}
@Override
public void initViewData() {
//0๏ผๆไบคๆๅ๏ผ1๏ผๅทฒๅ็๏ผ2๏ผๆ็ฐๆๅ
switch (withdrawDetailBean.getProgress()) {
case "0":
tv_process0.setTextColor(getResources().getColor(R.color.red));
tv_process1.setTextColor(getResources().getColor(R.color.text_grey999));
tv_process2.setTextColor(getResources().getColor(R.color.text_grey999));
break;
case "1":
tv_process0.setTextColor(getResources().getColor(R.color.red));
tv_process1.setTextColor(getResources().getColor(R.color.red));
tv_process2.setTextColor(getResources().getColor(R.color.text_grey999));
break;
case "2":
tv_process0.setTextColor(getResources().getColor(R.color.red));
tv_process1.setTextColor(getResources().getColor(R.color.red));
tv_process2.setTextColor(getResources().getColor(R.color.red));
break;
}
tv_account.setText("่ดฆๅท:" + withdrawDetailBean.getAccount());
tv_name.setText("ๅงๅ:" + withdrawDetailBean.getName());
}
@Override
public void initViewListener() {
img_close.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dismiss();
}
});
}
}
|
package com.zhaoyan.ladderball.dao.account;
import com.zhaoyan.ladderball.domain.account.db.Administrator;
public interface AdministratorDao {
/**
* ๆ นๆฎ่ดฆๅทๅๅฏ็ ๆฅ่ฏข
*/
Administrator getAdministrator(String userName, String password);
/**
* ๆ นๆฎ่ดฆๅทๆฅ่ฏข
*/
Administrator getAdministrator(String userName);
}
|
package com.rk.jarjuggler.service;
import java.util.Comparator;
public class WorkItemComparator implements Comparator<WorkItem> {
public int compare(WorkItem workItem1, WorkItem workItem2) {
int level1 = workItem1.getParent().getLevel();
int level2 = workItem2.getParent().getLevel();
int levelCompare = level2 - level1;
// return levelCompare;
if (levelCompare != 0){
return levelCompare;
}
String name1 = workItem1.getParent().getName() == null ? "" : workItem1.getParent().getName();
String name2 = workItem2.getParent().getName() == null ? "" : workItem2.getParent().getName();
return name1.compareTo(name2);
}
}
|
package com.example.emergents;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.emergents.DB.MyHelper;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
public class MainRecyclerViewAdapter extends RecyclerView.Adapter<MainRecyclerViewAdapter.ViewHolder> {
private static Context context;
private InputStream mFile;
private ArrayList<HashMap<String, String>> data;
private MyHelper dbHelper;
private SQLiteDatabase db;
private Cursor mCursor;
public MainRecyclerViewAdapter(Context context, InputStream file) {
this.context = context;
this.mFile = file;
prepareData();
}
public void prepareData() {
dbHelper = new MyHelper(context, mFile);
db = dbHelper.getWritableDatabase();
data = new ArrayList<>();
mCursor = dbHelper.getDataFromType(db);
if (mCursor.moveToFirst()) {
do {
String nameTH = mCursor.getString(mCursor.getColumnIndex(MyHelper.COL_TYPE_NAME_TH));
String nameEN = mCursor.getString(mCursor.getColumnIndex(MyHelper.COL_TYPE_NAME_EN));
HashMap<String, String> map = new HashMap<>();
map.put("nameTH", nameTH);
map.put("nameEN", nameEN);
data.add(map);
} while (mCursor.moveToNext());
}
mCursor.close();
}
@Override
public MainRecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_card, null);
ViewHolder viewHolder = new ViewHolder(itemView);
return viewHolder;
}
@Override
public void onBindViewHolder(MainRecyclerViewAdapter.ViewHolder holder, int position) {
String type = data.get(position).get("nameEN").toLowerCase();
int imageId = context.getResources().getIdentifier(type, "drawable", context.getPackageName());
holder.image.setImageResource(imageId);
String name = data.get(position).get("nameTH");
holder.name.setText(name);
}
@Override
public int getItemCount() {
return data.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public ImageView image;
public TextView name;
public ViewHolder(View itemView) {
super(itemView);
image = (ImageView) itemView.findViewById(R.id.imageView);
name = (TextView) itemView.findViewById(R.id.name);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i("RecyclerViewAdapter", String.valueOf(getAdapterPosition()));
Intent intent = new Intent(context, InsideActivity.class);
intent.putExtra("Type", getAdapterPosition());
context.startActivity(intent);
}
});
}
}
}
|
package trees;
class SpiralNode {
int data;
SpiralNode left, right;
public SpiralNode(int value) {
data = value;
left = right = null;
}
}
public class SpiralTraverse {
SpiralNode root;
void printspiral(SpiralNode node) {
int height = getHeight(node);
int i;
boolean ltr = false;
for (i = 1; i <= height; i++) {
printLevel(node, i, ltr);
ltr = !ltr;
}
}
void printLevel(SpiralNode node, int level, boolean ltr) {
if (node == null)
return;
if (level == 1)
System.out.println(node.data);
if (level > 1) {
if (ltr != false) {
printLevel(node.left, level - 1, ltr);
printLevel(node.right, level - 1, ltr);
} else {
printLevel(node.right, level - 1, ltr);
printLevel(node.left, level - 1, ltr);
}
}
}
int getHeight(SpiralNode node) {
if (node == null)
return 0;
else {
int lh = getHeight(node.left);
int rh = getHeight(node.right);
if (lh > rh)
return (lh + 1);
else
return (rh + 1);
}
}
public static void main(String[] args) {
SpiralTraverse st = new SpiralTraverse();
st.root = new SpiralNode(1);
st.root.left = new SpiralNode(2);
st.root.right = new SpiralNode(3);
st.root.left.left = new SpiralNode(7);
st.root.left.right = new SpiralNode(6);
st.root.right.left = new SpiralNode(5);
st.root.right.right = new SpiralNode(4);
st.printspiral(st.root);
}
}
|
package mx.infornet.smartgym;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.material.button.MaterialButton;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class AlimentacionActivity extends AppCompatActivity {
private TextView error;
private ImageView btn_back;
private ProgressBar progressBar;
private String token, token_type;
private RecyclerView recyclerView;
private StringRequest request;
private RequestQueue queue;
private List<PlanesAlimentacion> alimentacionList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alimentacion);
error = findViewById(R.id.txt_error_alimentacion);
error.setVisibility(View.GONE);
recyclerView = findViewById(R.id.recycler_view_alimentacion);
recyclerView.setAdapter(null);
btn_back = findViewById(R.id.btn_back_alimentacion);
btn_back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
progressBar = findViewById(R.id.prog_bar_alimentacion);
alimentacionList = new ArrayList<>();
ConexionSQLiteHelper conn = new ConexionSQLiteHelper(getApplicationContext(), "usuarios", null, 4);
SQLiteDatabase db = conn.getWritableDatabase();
try {
String query = "SELECT * FROM usuarios";
Cursor cursor = db.rawQuery(query, null);
for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
token = cursor.getString(cursor.getColumnIndex("token"));
token_type = cursor.getString(cursor.getColumnIndex("tokenType"));
}
cursor.close();
}catch (Exception e){
Toast toast = Toast.makeText(getApplicationContext(), "Error: "+ e.toString(), Toast.LENGTH_SHORT);
toast.show();
}
db.close();
Log.d("token", token);
queue = Volley.newRequestQueue(getApplicationContext());
request = new StringRequest(Request.Method.GET, Config.PLANES_ALIM_GYM_URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("string response", response);
progressBar.setVisibility(View.GONE);
try {
JSONObject jsonObject = new JSONObject(response);
Log.d("RESPONSE_PLAN", jsonObject.toString());
if (jsonObject.has("status")){
String status = jsonObject.getString("status");
if (status.equals("Token is Expired")){
Toast.makeText(getApplicationContext(), status+". Favor de iniciar sesiรณn nuevamente", Toast.LENGTH_LONG).show();
ConexionSQLiteHelper conn = new ConexionSQLiteHelper(getApplicationContext(), "usuarios", null, 4);
SQLiteDatabase db = conn.getWritableDatabase();
db.execSQL("DELETE FROM usuarios");
startActivity(new Intent(getApplicationContext(), LoginActivity.class));
finish();
}
} else if (jsonObject.toString().isEmpty()){
error.setVisibility(View.VISIBLE);
error.setText(R.string.erroralimentacion);
} else {
alimentacionList.add(new PlanesAlimentacion(
jsonObject.getInt("id"),
jsonObject.getString("nombre"),
jsonObject.getString("descripcion")
));
AdapterAlimentacion adaper = new AdapterAlimentacion(getApplicationContext(), alimentacionList);
LinearLayoutManager llm = new LinearLayoutManager(getApplicationContext());
llm.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(llm);
recyclerView.setAdapter(adaper);
}
}catch (JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
progressBar.setVisibility(View.GONE);
Log.d("ERROR", error.toString());
if (error instanceof TimeoutError) {
Toast.makeText(getApplicationContext(),
"Oops. Timeout error!",
Toast.LENGTH_LONG).show();
}
}
}){
@Override
public Map<String, String> getHeaders()throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put("Authorization", token_type+" "+token);
return headers;
}
};
queue.add(request);
}
@Override
public void onBackPressed() {
super.onBackPressed();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
finish();
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.lifespeedtechnologies.OpenTracker;
import java.util.HashMap;
import org.OpenNI.*;
/**
*
* @author dean
*/
public class DepthDriver extends Driver {
private OpenTrackerDemo parent;
public DepthDriver ( Context c, OpenTrackerDemo p ) {
super( c );
parent = p;
}
public void init () throws GeneralException {
initDepth();
initUser();
}
public void updateDepth () {
try {
context.waitAnyUpdateAll();
DepthMetaData depthMD = depthGen.getMetaData();
SceneMetaData sceneMD = userGen.getUserPixels( 0 );
java.nio.ShortBuffer scene = sceneMD.getData().createShortBuffer();
java.nio.ShortBuffer depth = depthMD.getData().createShortBuffer();
calcHist( depth );
depth.rewind();
while ( depth.remaining() > 0 ) {
int pos = depth.position();
short pixel = depth.get();
short user = scene.get();
dimgbytes[3 * pos] = 0;
dimgbytes[3 * pos + 1] = 0;
dimgbytes[3 * pos + 2] = 0;
if ( drawBackground || pixel != 0 ) {
int colorID = user % ( colors.length - 1 );
if ( user == 0 ) {
colorID = colors.length - 1;
}
if ( pixel != 0 ) {
float histValue = dhistogram[pixel];
dimgbytes[3 * pos] = (byte) ( histValue *
colors[colorID].getRed() );
dimgbytes[3 * pos + 1] = (byte) ( histValue *
colors[colorID].
getGreen() );
dimgbytes[3 * pos + 2] = (byte) ( histValue *
colors[colorID].
getBlue() );
}
}
}
repaint();
} catch ( GeneralException e ) {
e.printStackTrace();
}
}
protected void initUser () {
try {
userGen = UserGenerator.create( context );
skeletonCap = userGen.getSkeletonCapability();
poseDetectionCap = userGen.getPoseDetectionCapability();
userGen.getNewUserEvent().addObserver( new NewUserObserver( this ) );
userGen.getLostUserEvent().
addObserver( new LostUserObserver( this ) );
skeletonCap.getCalibrationCompleteEvent().addObserver(
new CalibrationCompleteObserver( this ) );
poseDetectionCap.getPoseDetectedEvent().addObserver(
new PoseDetectedObserver( this ) );
calibPose = skeletonCap.getSkeletonCalibrationPose();
joints = new HashMap<>();
skeletonCap.setSkeletonProfile( SkeletonProfile.ALL );
} catch ( GeneralException e ) {
e.printStackTrace();
System.exit( 1 );
}
}
protected void initDepth () throws GeneralException {
depthGen = DepthGenerator.create( context );
DepthMetaData depthMD = depthGen.getMetaData();
dhistogram = new float[10000];
dwidth = depthMD.getFullXRes();
dheight = depthMD.getFullYRes();
dimgbytes = new byte[dwidth * dheight * 3];
}
public static void drawSkeleton ( java.awt.Graphics g, int user ) throws
org.OpenNI.StatusException {
getJoints( user );
java.util.HashMap<org.OpenNI.SkeletonJoint, org.OpenNI.SkeletonJointPosition> dict =
joints.
get(
new Integer( user ) );
drawLine( g, dict, org.OpenNI.SkeletonJoint.HEAD,
org.OpenNI.SkeletonJoint.NECK );
drawLine( g, dict, org.OpenNI.SkeletonJoint.LEFT_SHOULDER,
org.OpenNI.SkeletonJoint.TORSO );
drawLine( g, dict, org.OpenNI.SkeletonJoint.RIGHT_SHOULDER,
org.OpenNI.SkeletonJoint.TORSO );
drawLine( g, dict, org.OpenNI.SkeletonJoint.NECK,
org.OpenNI.SkeletonJoint.LEFT_SHOULDER );
drawLine( g, dict, org.OpenNI.SkeletonJoint.LEFT_SHOULDER,
org.OpenNI.SkeletonJoint.LEFT_ELBOW );
drawLine( g, dict, org.OpenNI.SkeletonJoint.LEFT_ELBOW,
org.OpenNI.SkeletonJoint.LEFT_HAND );
drawLine( g, dict, org.OpenNI.SkeletonJoint.NECK,
org.OpenNI.SkeletonJoint.RIGHT_SHOULDER );
drawLine( g, dict, org.OpenNI.SkeletonJoint.RIGHT_SHOULDER,
org.OpenNI.SkeletonJoint.RIGHT_ELBOW );
drawLine( g, dict, org.OpenNI.SkeletonJoint.RIGHT_ELBOW,
org.OpenNI.SkeletonJoint.RIGHT_HAND );
drawLine( g, dict, org.OpenNI.SkeletonJoint.LEFT_HIP,
org.OpenNI.SkeletonJoint.TORSO );
drawLine( g, dict, org.OpenNI.SkeletonJoint.RIGHT_HIP,
org.OpenNI.SkeletonJoint.TORSO );
drawLine( g, dict, org.OpenNI.SkeletonJoint.LEFT_HIP,
org.OpenNI.SkeletonJoint.RIGHT_HIP );
drawLine( g, dict, org.OpenNI.SkeletonJoint.LEFT_HIP,
org.OpenNI.SkeletonJoint.LEFT_KNEE );
drawLine( g, dict, org.OpenNI.SkeletonJoint.LEFT_KNEE,
org.OpenNI.SkeletonJoint.LEFT_FOOT );
drawLine( g, dict, org.OpenNI.SkeletonJoint.RIGHT_HIP,
org.OpenNI.SkeletonJoint.RIGHT_KNEE );
drawLine( g, dict, org.OpenNI.SkeletonJoint.RIGHT_KNEE,
org.OpenNI.SkeletonJoint.RIGHT_FOOT );
}
protected static void drawLine ( java.awt.Graphics g,
HashMap<SkeletonJoint, SkeletonJointPosition> jointHash,
SkeletonJoint joint1, SkeletonJoint joint2 ) {
org.OpenNI.Point3D pos1 = jointHash.get( joint1 ).getPosition();
org.OpenNI.Point3D pos2 = jointHash.get( joint2 ).getPosition();
if ( jointHash.get( joint1 ).getConfidence() == 0 || jointHash.get(
joint2 ).getConfidence() == 0 ) {
return;
}
g.drawLine( (int) pos1.getX(), (int) pos1.getY(), (int) pos2.getX(),
(int) pos2.getY() );
}
@Override
public void paint ( java.awt.Graphics g ) {
if ( drawPixels ) {
java.awt.image.DataBufferByte dataBuffer =
new java.awt.image.DataBufferByte(
dimgbytes, dwidth *
dheight *
3 );
java.awt.image.WritableRaster raster = java.awt.image.Raster.
createInterleavedRaster( dataBuffer,
dwidth,
dheight,
dwidth * 3,
3,
new int[] {
0, 1, 2 }, null );
java.awt.image.ColorModel colorModel =
new java.awt.image.ComponentColorModel(
java.awt.color.ColorSpace.
getInstance( java.awt.color.ColorSpace.CS_sRGB ),
new int[] { 8, 8, 8 },
false, false,
java.awt.image.ComponentColorModel.OPAQUE,
java.awt.image.DataBuffer.TYPE_BYTE );
dbimg = new java.awt.image.BufferedImage( colorModel, raster, false,
null );
g.drawImage( dbimg, 0, 0, null );
}
try {
int[] users = userGen.getUsers();
for ( int i = 0; i < users.length; ++i ) {
java.awt.Color c = colors[users[i] % colors.length];
c = new java.awt.Color( 255 - c.getRed(), 255 - c.getGreen(),
255 - c.
getBlue() );
g.setColor( c );
if ( drawSkeleton && skeletonCap.isSkeletonTracking( users[i] ) ) {
DepthDriver.drawSkeleton( g, users[i] );
}
if ( printID ) {
Point3D com = depthGen.convertRealWorldToProjective(
userGen.getUserCoM( users[i] ) );
String label = null;
if ( !printState ) {
label = new String( "" + users[i] );
} else if ( skeletonCap.isSkeletonTracking( users[i] ) ) {
// Tracking
label = new String( users[i] + " - Tracking" );
} else if ( skeletonCap.isSkeletonCalibrating( users[i] ) ) {
// Calibrating
label = new String( users[i] + " - Calibrating" );
} else {
// Nothing
label = new String( users[i] + " - Looking for pose (" +
calibPose + ")" );
}
g.drawString( label, (int) com.getX(), (int) com.getY() );
}
}
} catch ( StatusException e ) {
e.printStackTrace();
}
}
}
|
import java.io.File;
import com.opensymphony.xwork2.ActionSupport;
public class FileUploadAction extends ActionSupport{
private File fileUpload;
private String fileType;
private String fileName;
public File getFileUpload() {
return fileUpload;
}
public void setFileUpload(File fileUpload) {
this.fileUpload = fileUpload;
}
public String getFileType() {
return fileType;
}
public void setFileType(String fileType) {
this.fileType = fileType;
}
public String getFileName() {
return fileUpload.getName();
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
return SUCCESS;
}
public String display(){
return NONE;
}
}
|
package com.sh.offer.array;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @Auther: bjshaohang
* @Date: 2021/1/17
*/
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input1 = scan.nextLine();
System.out.println(strAmountChn(input1));
}
private static String strAmountChn(String amount) {
if (amount == null || !isNumeric(amount)) {
return "่พๅ
ฅๆฐๆฎ้ๆฐๅญ๏ผๅช่ฝๅ
ๅซไปฅไธๅ
ๅฎน(0๏ฝ9๏ผ'.')๏ผไธๅฐๆฐ็นๅ้ขๅช่ฝๆ็นไธคไฝ๏ผ่ฏทๆฃๆฅ~";
}
String amountTrim = amount.trim();
String bigNums = "้ถๅฃน่ดฐๅ่ไผ้ๆๆ็";
String units = "ๅ่งๆดๅ
ๆพไฝฐไปไธๆพไฝฐไปไบฟๆพไฝฐไป";
String result = "";
int index;
String num, unit;
int length = !amountTrim.contains(".") ? amountTrim.length() : amountTrim.indexOf(".");
if (length > units.length() - 3) {
return ("่พๅ
ฅ็ๅ
ๅฎนๆๅคงๅช่ฝ็ฒพ็กฎๅฐไปไบฟ๏ผ่ฏทๆฃๆฅ~");
}
for (int i = 0; i < amountTrim.length(); i++) {
if (i > length +2) {
break;
}
if (i == length) {
continue;
}
index = Integer.parseInt(String.valueOf(amountTrim.charAt(i)));
num = bigNums.substring(index, index+1);
index = length - i + 2;
unit = units.substring(index, index+1);
result = result + num + unit;
}
if ((length == amountTrim.length()) || (length == amountTrim.length() - 1)) {
result = result.concat("ๆด");
}
if (length == amountTrim.length() - 2) {
result = result.concat("้ถๅ");
}
result = result.replace("้ถๅ", "");
result = result.replace("้ถ่ง", "้ถ");
int m = result.length();
int n = 0;
while (m != n) {
m = result.length();
if (!result.startsWith("้ถๅ
")) {
result = result.replace("้ถๅ
", "ๅ
");
}
if (!result.startsWith("้ถไธ")) {
result = result.replace("้ถไธ", "ไธ");
}
if (!result.startsWith("้ถไบฟ")) {
result = result.replace("้ถไบฟ", "ไบฟ");
}
if (!result.startsWith("้ถไป")) {
result = result.replace("้ถไป", "้ถ");
}
if (!result.startsWith("้ถไฝฐ")) {
result = result.replace("้ถไฝฐ", "้ถ");
}
if (!result.startsWith("้ถ้ถ")) {
result = result.replace("้ถ้ถ", "้ถ");
}
if (!result.startsWith("้ถๆพ")) {
result = result.replace("้ถๆพ", "้ถ");
}
if (!result.startsWith("ไบฟไธ")) {
result = result.replace("ไบฟไธ", "ไบฟ้ถ");
}
if (!result.startsWith("ไธไป")) {
result = result.replace("ไธไป", "ไธ้ถ");
}
if (!result.startsWith("ไปไฝฐ")) {
result = result.replace("ไปไฝฐ", "ไป้ถ");
}
n = result.length();
}
int tempLength = result.length();
if (result.charAt(tempLength - 1) == '้ถ') {
result = result.substring(0, tempLength - 1);
}
tempLength = result.length();
if (result.charAt(tempLength - 1) == 'ๅ
') {
result = result + 'ๆด';
}
return result;
}
public static boolean isNumeric(String str) {
Pattern pattern = Pattern.compile("[0-9]*\\.?[0-9][0-9]");
Matcher isNum = pattern.matcher(str);
if (!isNum.matches()) {
return false;
}
return true;
}
}
|
package com.test;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import com.test.base.Solution;
/**
* BFS๏ผ้ๅๆๆ็ๅฏ่ฝ
*
* ไฝฟ็จ int[1<<N][N]๏ผๅ้ๅค่ฎก็ฎ่ฟๆปคใ้็นใ
*
* xไธบ๏ผstate๏ผๅฝๅ็ป่ฟ็็น็ไฝ็ฝฎ๏ผๅ๏ผไธชๆฐ
* yไธบ๏ผhead๏ผๅฝๅ็็น็ไฝ็ฝฎ
*
* @author YLine
*
* 2019ๅนด9ๆ12ๆฅ ไธๅ3:23:13
*/
public class SolutionB implements Solution
{
@Override
public int shortestPathLength(int[][] graph)
{
final int N = graph.length;
final int endState = (1 << N) - 1;
Queue<State> queue = new LinkedList<>();
int[][] dist = new int[1 << N][N];
for (int[] row : dist)
{
Arrays.fill(row, N * N);
}
for (int x = 0; x < N; ++x)
{
queue.offer(new State(1 << x, x));
dist[1 << x][x] = 0;
}
while (!queue.isEmpty())
{
State node = queue.poll();
int d = dist[node.state][node.head];
if (node.state == endState)
{
return d;
}
for (int child : graph[node.head])
{
int cover2 = node.state | (1 << child);
if (d + 1 < dist[cover2][child]) // ๅฝ state้ๅคใindex็ธๅๆถ๏ผstep่พๅค็็ดๆฅๆ้ค
{
dist[cover2][child] = d + 1;
queue.offer(new State(cover2, child));
}
}
}
throw null;
}
private static class State
{
private int state; // 2^0 + 2^1 ... + 2^n, ็จๆฅ่กจ็คบ0-n๏ผๆฏๅฆๅญๅจ
private int head; // ๅฝๅ็ index
State(int c, int h)
{
state = c;
head = h;
}
}
}
|
package com.jia.bigdata.mr.wordcount;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
import java.io.IOException;
import java.util.stream.StreamSupport;
/**
* @author tanjia
* @email 378097217@qq.com
* @date 2019/7/15 2:09
*/
public class WordCounterReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
protected void reduce(final Text key, final Iterable<IntWritable> values, final Reducer.Context context) throws IOException, InterruptedException {
final int ret = StreamSupport.stream(values.spliterator(), false).mapToInt(e -> e.get()).sum();
context.write(key, new IntWritable(ret));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.