text
stringlengths 10
2.72M
|
|---|
package com.tencent.mm.plugin.wallet.balance.a.a;
import com.tencent.mm.modelsfs.FileOp;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
class i$1 implements Runnable {
final /* synthetic */ byte[] jXt;
final /* synthetic */ boolean oYQ;
final /* synthetic */ i oYR;
i$1(i iVar, byte[] bArr, boolean z) {
this.oYR = iVar;
this.jXt = bArr;
this.oYQ = z;
}
public final void run() {
if (this.jXt != null) {
if (this.oYQ) {
if (FileOp.cn(i.bO())) {
FileOp.I(i.bO(), true);
}
FileOp.mL(i.bO());
i.a(this.oYR);
} else {
if (FileOp.cn(i.ath())) {
FileOp.I(i.ath(), true);
}
FileOp.mL(i.ath());
i.b(this.oYR);
}
try {
String str = System.currentTimeMillis();
String str2 = "MicroMsg.LqtBindQueryInfoCache";
String str3 = "saveCacheToDisk, dir: %s, name: %s, save: %s";
Object[] objArr = new Object[3];
objArr[0] = this.oYQ ? i.bO() : i.ath();
objArr[1] = str;
objArr[2] = Boolean.valueOf(this.oYQ);
x.i(str2, str3, objArr);
long VG = bi.VG();
FileOp.l((this.oYQ ? i.bO() : i.ath()) + str, this.jXt);
x.i("MicroMsg.LqtBindQueryInfoCache", "finish saveCacheToDisk, used %sms", new Object[]{Long.valueOf(bi.bI(VG))});
} catch (Throwable e) {
x.printErrStackTrace("MicroMsg.LqtBindQueryInfoCache", e, "saveCacheToDisk error: %s", new Object[]{e.getMessage()});
}
}
}
}
|
package edu.oakland;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import static org.junit.Assert.*;
public class CalendarTest {
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void getMonthEvents() {
Calendar c = new Calendar();
String[] arr = new String[]{"2018-02-03T10:15:30+01:00[Europe/Paris]","2018-03-17T10:15:30+01:00[Europe/Paris]",
"2018-02-03T10:15:30+01:00[Europe/Paris]", "2018-02-27T10:15:30+01:00[Europe/Paris]",
"2018-03-03T10:15:30+01:00[Europe/Paris]", "2018-03-16T10:15:30+01:00[Europe/Paris]",
"2018-03-14T10:15:30+01:00[Europe/Paris]", "2018-04-18T10:15:30+01:00[Europe/Paris]",
"2018-04-04T10:15:30+01:00[Europe/Paris]", "2018-04-27T10:15:30+01:00[Europe/Paris]",
"2018-02-03T10:15:30+01:00[Europe/Paris]", "2018-04-27T10:15:30+01:00[Europe/Paris]"};
List<String> successes = new ArrayList<>(Arrays.asList("1", "3", "4", "dup", "6"));
for (int i = 0; i < arr.length; i += 2) {
SingularEvent e = new SingularEvent(ZonedDateTime.parse(arr[i]), ZonedDateTime.parse(arr[i + 1]),
Integer.toString(i / 2 + 1));
c.addEvent(e);
}
SingularEvent duplicateTime = new SingularEvent(ZonedDateTime.parse(arr[0]), ZonedDateTime.parse(arr[1]), "dup");
c.addEvent(duplicateTime);
Set<Event> resultSet = c.getMonthEvents(YearMonth.of(2018, 3));
assertTrue(resultSet.size() == successes.size());
for (Event e : c.startingSet) {
if (successes.contains(e.getEventName())) {
assertTrue(resultSet.contains(e));
} else {
assertFalse(resultSet.contains(e));
}
}
}
@Test
public void getDayEvents() {
Calendar c = new Calendar();
String[] arr = new String[]{"2018-02-03T10:15:30+01:00[Europe/Paris]", "2018-03-17T10:15:30+01:00[Europe/Paris]",
"2018-02-03T10:15:30+01:00[Europe/Paris]", "2018-02-27T10:15:30+01:00[Europe/Paris]",
"2018-03-03T10:15:30+01:00[Europe/Paris]", "2018-03-16T10:15:30+01:00[Europe/Paris]",
"2018-03-14T10:15:30+01:00[Europe/Paris]", "2018-04-18T10:15:30+01:00[Europe/Paris]",
"2018-04-04T10:15:30+01:00[Europe/Paris]", "2018-04-27T10:15:30+01:00[Europe/Paris]",
"2017-02-01T10:18:30+01:00[Europe/Paris]", "2017-02-03T10:15:31+01:00[Europe/Paris]",
"2017-02-01T10:15:30+01:00[Europe/Paris]", "2017-02-26T10:15:31+01:00[Europe/Paris]"};
for (int i = 0; i < arr.length; i += 2) {
SingularEvent e = new SingularEvent(ZonedDateTime.parse(arr[i]), ZonedDateTime.parse(arr[i + 1]),
Integer.toString(i / 2 + 1));
c.addEvent(e);
}
SingularEvent duplicateTime = new SingularEvent(ZonedDateTime.parse(arr[0]), ZonedDateTime.parse(arr[1]), "dup");
c.addEvent(duplicateTime);
Set<Event> resultSet1 = c.getDayEvents(LocalDate.of(2018, 2, 3));
assertEquals(3, resultSet1.size());
for (Event e : resultSet1) {
if (e.getEventName().equals("1") || e.getEventName().equals("2") ||
e.getEventName().equals("dup")) {
assertTrue(resultSet1.contains(e));
} else {
assertFalse(resultSet1.contains(e));
}
}
Set<Event> resultSet2 = c.getDayEvents(LocalDate.of(2018, 4, 6));
assertEquals(2, resultSet2.size());
int iResSet2 = 1;
for (Event e : resultSet2) {
if (iResSet2 == 1) {
assertEquals("First event should be '4'", "4", e.getEventName());
iResSet2++;
} else if (iResSet2 == 2) {
assertEquals("Second event should be '5'", "5", e.getEventName());
iResSet2++;
}
if (e.getEventName().equals("4") || e.getEventName().equals("5")) {
assertTrue(resultSet2.contains(e));
} else {
assertFalse(resultSet2.contains(e));
}
}
Set<Event> resultSet3 = c.getDayEvents(LocalDate.of(2018, 4, 4));
assertEquals(2, resultSet3.size());
for (Event e : resultSet3) {
if (e.getEventName().equals("4")|| e.getEventName().equals("5")) {
assertTrue(resultSet3.contains(e));
} else {
assertFalse(resultSet3.contains(e));
}
}
Set<Event> resultSet4 = c.getDayEvents(LocalDate.of(2017, 2, 1));
assertEquals(2, resultSet4.size());
int iResSet4 = 1;
for (Event e: resultSet4) {
switch (iResSet4) {
case 1:
assertEquals("First event should be '7'", "7", e.getEventName());
iResSet4++;
break;
case 2:
assertEquals("Second event should be '6'", "6", e.getEventName());
iResSet4++;
break;
default:
assertTrue("should not get here", false);
}
}
// Recurrence
Calendar c2 = new Calendar();
Event recur1 = new RecurrentEvent(ZonedDateTime.parse("2017-02-01T10:15:30+01:00[Europe/Paris]"),
ZonedDateTime.parse("2017-02-01T10:18:30+01:00[Europe/Paris]"),
"recurEvent1", Frequency.DAILY,
ZonedDateTime.parse("2017-02-01T10:15:30+01:00[Europe/Paris]"),
ZonedDateTime.parse("2017-02-26T10:15:00+01:00[Europe/Paris]"));
c2.addEvent(recur1);
assertTrue("Recurrence ended on this day, but before the event started", c2.getDayEvents(LocalDate.of(2017, 2, 26)).isEmpty());
for (int i = 1; i < 26; i++){
Set<Event> rs = c2.getDayEvents(LocalDate.of(2017, 2, i));
assertEquals(1, rs.size());
}
Calendar c3 = new Calendar();
SingularEvent recur2 = new RecurrentEvent(ZonedDateTime.parse("2017-02-01T10:15:30+01:00[Europe/Paris]"),
ZonedDateTime.parse("2017-02-01T10:18:30+01:00[Europe/Paris]"),
"recurEvent1", Frequency.WEEKLY,
ZonedDateTime.parse("2017-02-01T10:15:30+01:00[Europe/Paris]"),
ZonedDateTime.parse("2017-02-26T10:15:00+01:00[Europe/Paris]"));
c3.addEvent(recur2);
for (int i = 1; i < 28; i++){
Set<Event> rs = c3.getDayEvents(LocalDate.of(2017, 2, i));
assertEquals((i - 1) % 7 == 0 ? 1 : 0, rs.size());
}
Calendar c4 = new Calendar();
SingularEvent recur3 = new RecurrentEvent(ZonedDateTime.parse("2017-01-01T10:15:30+01:00[Europe/Paris]"),
ZonedDateTime.parse("2017-01-08T10:18:30+01:00[Europe/Paris]"), "recurEvent1", Frequency.MONTHLY,
ZonedDateTime.parse("2017-01-01T10:10:30+01:00[Europe/Paris]"),
ZonedDateTime.parse("2018-01-02T10:15:00+01:00[Europe/Paris]"));
c4.addEvent(recur3);
for (int month = 1; month <= 12; month++){
for (int day = 1; day <= YearMonth.of(2017, month).lengthOfMonth(); day++) {
Set<Event> rs = c4.getDayEvents(LocalDate.of(2017, month, day));
if (day <= 8) {
assertEquals(1, rs.size());
} else {
assertEquals(0, rs.size());
}
}
}
assertEquals("recurrence ended midway through the event duration",0, c4.getDayEvents(LocalDate.of(2018, 1, 1)).size());
assertEquals(0, c4.getDayEvents(LocalDate.of(2018, 2, 1)).size());
}
@Test
public void getMonthSpan() {
String[] ym1 = new String[] {"2017-01", "2017-06", "2017-12"};
String[] ym2 = new String[] {"2017-05", "2017-12", "2018-01"};
int[] goalLengths = new int[] {5, 7, 2};
List<YearMonth> y1 = Arrays.stream(ym1).map(YearMonth::parse).collect(Collectors.toList());
List<YearMonth> y2 = Arrays.stream(ym2).map(YearMonth::parse).collect(Collectors.toList());
for (int i = 0; i < ym1.length; i++) {
List<YearMonth> list = Calendar.getMonthSpan(y1.get(i), y2.get(i));
assertEquals(list.size(), goalLengths[i]);
}
}
@Test
public void checkProperCaching() {
Calendar c = new Calendar();
YearMonth[] ym1 = new YearMonth[] {YearMonth.of(2017, 1), YearMonth.of(2017, 6),
YearMonth.of(2017, 3), YearMonth.of(2016, 7)};
for (YearMonth y : ym1) {
c.getMonthEvents(y);
}
assertEquals(c.monthCache.size(), 4);
Event e = new SingularEvent(ZonedDateTime.parse("2017-01-08T10:18:30+01:00[Europe/Paris]"),
ZonedDateTime.parse("2017-03-12T10:18:30+01:00[Europe/Paris]"), "example");
c.addEvent(e);
assertEquals(c.monthCache.size(), 2);
}
}
|
package com.xvr.serviceBook.service;
import com.xvr.serviceBook.entity.StatusTicket;
import java.util.List;
public interface StatusTicketService {
List<StatusTicket> findAllStatusTicketList();
}
|
package chapter_1_06_Interfaces;
public class Inner {
private int i = 4;
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Inner i = new Inner();
In in = i.new In();
System.out.println(in.getI());
System.out.println(i.newIn().getOuterI());
System.out.println((new Static()).getJ());
}
In newIn() {
return new In();
}
class In {
int i = 5;
int getI () {
return i;
}
int getOuterI () {
return Inner.this.i;
}
}
static class Static {
int j = 7;
int getJ(){
return j;
}
}
}
|
/**
*
*/
package com.hermes.ah3.jdbc.communication.implc;
/**
* @author wuwl
*
*/
public class ah3dri {
static{
System.out.println(System.getProperty("java.library.path"));
System.loadLibrary("ah3dri");
}
public native int JInit();
public native int JAuthenticate(String serverIP, String serverPort, String username, String userPwd);
public native int JConn();
public native int JSqlcode();
public native int JQuery(String expr);
public native int JFetch();
public native String JFldname(int colid);
public native int JFldid(String colname);
public native String JGetLine();
public native short JGetShortFid(int colid);
public native int JGetIntFid(int colid);
public native double JGetDoubleFid(int colid);
public native String JGetStringFid(int colid);
public native short JGetShortFname(String colname);
public native int JGetIntFname(String colname);
public native double JGetDoubleFname(String colname);
public native String JGetStringFname(String colname);
public native String JGetCStringFname(String colname);
public native int JClose();
public native int JDestory();
/**
*
*/
public ah3dri() {
// TODO Auto-generated constructor stub
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
|
package com.kdp.wanandroidclient.ui.project;
import com.kdp.wanandroidclient.bean.ProjectCate;
import com.kdp.wanandroidclient.ui.core.view.IListDataView;
/***
* @author kdp
* @date 2019/3/20 16:58
* @description
*/
public interface ProjectCateContract {
interface IProjectCatePresenter {
void getProjectCate();
}
interface IProjectCateView extends IListDataView<ProjectCate>{
}
}
|
package com.tks;
import com.tks.ds.Graph;
import java.io.*;
import java.util.LinkedList;
import java.util.Map;
public class RandomGraphDataGen {
private int vertexCount;
private float density;
private int minWeight;
private int maxWeight;
private String filename;
private RandomGraphDataGen(int vertexCount, float density, int minWeight, int maxWeight, String filename) {
this.vertexCount = vertexCount;
this.density = density;
this.minWeight = minWeight;
this.maxWeight = maxWeight;
this.filename = filename;
genGraph();
}
static class Builder {
private int vertexCount = 10;
private float density = 0.5f;
private int minWeight = 5;
private int maxWeight = minWeight + 20;
private String filename = "./randGraphData";
public Builder vertexCount(int val) {
this.vertexCount = val;
return this;
}
public Builder density(float val) {
this.density = val;
return this;
}
public Builder minWeight(int val) {
this.minWeight = val;
return this;
}
public Builder maxWeight(int val) {
if (val <= this.minWeight) {
this.maxWeight = this.minWeight + val;
}
else {
this.maxWeight = val;
}
return this;
}
public Builder filename(String val) {
this.filename = val;
return this;
}
public RandomGraphDataGen build() {
return new RandomGraphDataGen(this.vertexCount, this.density, this.minWeight, this.maxWeight, this.filename);
}
}
private void genGraph() {
try(PrintWriter pw = new PrintWriter(new FileOutputStream(filename))) {
Graph gh = new Graph();
int maxChild = (int) (vertexCount * density);
for (int i = 1; i <= vertexCount; i++) {
int children = (int)(Math.random() * (maxChild - 1) + 1);
LinkedList<Graph.Edge> edges = new LinkedList<>();
if (gh.graph.containsKey(i)) {
edges = gh.graph.get(i);
}
for (int j = 0; j < children; j++) {
int child = (int)(Math.random() * (vertexCount - 1) + 1);
int weight = (int) (Math.random() * (maxWeight - minWeight) + minWeight);
Graph.Edge edge = new Graph.Edge(child, i, weight);
edges.add(edge);
if (gh.graph.containsKey(child)) {
gh.graph.get(child).add(edge.getReverse());
}else{
LinkedList<Graph.Edge> temp = new LinkedList<>();
temp.add(edge.getReverse());
gh.graph.put(child, temp);
}
}
gh.graph.put(i, edges);
}
for(Map.Entry<Integer, LinkedList<Graph.Edge>> entry: gh.graph.entrySet()){
pw.print(entry.getKey()+" ");
for (Graph.Edge edge :
entry.getValue()) {
pw.print(edge.getTo()+","+edge.getWeight()+" ");
}
pw.println();
}
System.out.println("Generated graph: ");
gh.printGraph();
}catch (IOException ex) {
ex.printStackTrace();
}
}
}
|
public enum PenWidth {
THIN, REGULAR, WIDE
}
|
//test FION
//test FION1
import java.util.ArrayList;
import java.util.Collections;
public class Card {
private String mask;
private int value;
private int icon;
private String iconMask;
private boolean isShow;
private static ArrayList<Card> cards = new ArrayList<Card>();
// Card建構子123
//ellen test2
public Card(String mask, int value, int icon, String iconMask, boolean isShow) {
this.mask = mask;
this.value = value;
this.icon = icon;
this.iconMask = iconMask;
this.isShow = isShow;
}
//測試
//測試二二二
//測試三三三
//測試五五五
// 洗牌
public static void shuffleDeck(ArrayList<Card> card) {
Collections.shuffle(card);
}
// 創建牌堆 cards :花色、值,
public static ArrayList<Card> createDeck(int numofDeck) {
for (int a = 0; a < numofDeck ; a++) {
for (int icon = 1; icon < 5; icon++) {
int index = 0;
String iconMask = "";
// 初始化花色、字標
if (icon == 1) {
index = 0;
iconMask = "♥";
} else if (icon == 2) {
index = 13;
iconMask = "♦";
} else if (icon == 3) {
index = 26;
iconMask = "♠";
} else if (icon == 4) {
index = 39;
iconMask = "♣";
}
for (int i = index; i < index + 13; i++) {
if (i == index + 0) {
Card c = new Card("A", i - index + 11, icon, iconMask, true);
cards.add(c);
} else if (i > index && i < 10 + index) {
Card c = new Card(String.valueOf(i + 1 - index), i - index + 1, icon, iconMask, true);
cards.add(c);
} else if (i >= 10 + index && i < 13 + index) {
if (i == 10 + index) {
Card c = new Card("J", 10, icon, iconMask, true);
cards.add(c);
} else if (i == 11 + index) {
Card c = new Card("Q", 10, icon, iconMask, true);
cards.add(c);
} else if (i == 12 + index) {
Card c = new Card("K", 10, icon, iconMask, true);
cards.add(c);
}
}
}
}
}
return cards;
}
public boolean isShow() {
return isShow;
}
public void setShow(boolean isShow) {
this.isShow = isShow;
}
public int getIcon() {
return icon;
}
public void setIcon(int icon) {
this.icon = icon;
}
public String getIconMask() {
return iconMask;
}
public void setIconMask(String iconMask) {
this.iconMask = iconMask;
}
public String getMask() {
return mask;
}
public void setMask(String mask) {
this.mask = mask;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
|
package com.apri.test.service;
import com.apri.test.entity.User;
import java.util.List;
public interface UserService extends BaseService<User> {
List<User> findByUsername(User param);
List<User> findByUsernameAndPassword(User param);
User findByUsername(String username);
}
|
import java.util.Scanner;
public class Source {
public String customerArray[][]=new String[5][3];
public void createCustomer(String[][] array)
{
// your code here
for(int i=0;i<5;i++)
{
for(int j=0;j<3;j++)
{
customerArray[i][j] = array[i][j];
}
}
}
public static void sort2D(String [] [] array, int column_index){
for(int i=1; i<array.length; i++){
int index = i;
for(int j=i-1; j>=0; j--, index--)
if(Integer.parseInt(array[j][column_index])>Integer.parseInt(array[index][column_index]))
swap2rows(array, index,j);
else
break;
}
}
// swap 2 rows subroutine
public static void swap2rows(String [][] array, int index, int j){
String temp;
for(int i=0; i<array[j].length; i++){
temp = array[j][i];
array[j][i] = array[index][i];
array[index][i] = temp;
}
}
public String[][] getCustomers()
{
sort2D(customerArray,0);
return customerArray;
}
public static void main(String args[])
{
Source s = new Source();
Scanner sc = new Scanner(System.in);
String customerDetails[][] = new String[5][3];
for(int i=0;i<5;i++)
{
for(int j=0;j<3;j++)
{
customerDetails[i][j] = sc.next();
}
}
s.createCustomer(customerDetails);
String [][] result = s.getCustomers();
for(int i=0;i<5;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(result[i][j]+" ");
}
System.out.println();
}
}
}
|
package com.mrhan.db;
import com.mrhan.db.allrounddaos.IFeild;
import java.util.List;
import java.util.Set;
/**
* 描述数据库中的表和实体类的关系接口
*
*/
public interface ITable {
/**
* 获取当前实体类对应的表名
* @return String 返回实体类上映射的表明
*/
String getTableName();
/**
* 获取对应的实体类的类信息 类模板
* @return 返回实体类的类模板 {@link Class}
*/
Class<?> getEntityClass();
/**
* 获取指定类型的字段信息
* @param type 注解类型的Class <br/>
* 限定于此包下的类:{@link com.mrhan.database.entitydaos.keytype}
* @return ArrayList<IField> {@link java.util.ArrayList} 返回字段对象集合
*/
List<IField> findTypeField(Class<?> type);
/**
* 返回当前实体类中所有需要映射 的字段关系对象
* @return {@link IFeild}
*/
Set<IField> fields();
/**
* 根据实体类对应的表中,获取指定列明(字段名)的字段关系对象
* @param columentName 数据表中字段(列)名称
* @return IFeild 映射关系对象
*/
IField getField(String columentName);
/**
* 创建一个新的实体对象,创建前,请保证此实体类有无参数的构造函数
* @param <E> 实体类型
* @return 返回一个实体类型的对象
*/
<E extends Object> E createEntity();
/**
* 根据此实体类的模板,和指定获取数据源的对象来创建插入语句!
* @param entityObj 模板需要获取数据的实体类具体对象
* @return 返回 SQLStatement 返回具体的语句对象
* @see SQLStatement
*/
SQLStatement createInset(Object entityObj);
/**
* 根据此实体类的模板,和指定获取数据源的对象来创建修改语句!
* @param entityObj 模板需要获取数据的实体类具体对象
* @return 返回 SQLStatement 返回具体的语句对象
* @see SQLStatement
*/
SQLStatement createUpdate(Object entityObj, SQLWhere... where);
/**
* 根据此实体类的模板,和指定获取数据源的对象来创建插入语句!
* @param entityObj 模板需要获取数据的实体类具体对象
* @return 返回 SQLStatement 返回具体的语句对象
* @see SQLStatement
*/
SQLStatement createDelete(Object entityObj, SQLWhere... where);
/**
* 创建查询语句
* @param where 条件
* @return 返回 SQLStatement 返回具体的语句对象
* @see SQLStatement
*/
SQLStatement createSelect(SQLWhere... where);
}
|
package com.example.rozrywka.myapplication;
import android.app.ActionBar;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Rozrywka on 2016-07-26.
*/
public class DataBaseHelper extends SQLiteOpenHelper {
private static final String LOG ="DatabaseHelper";
private static final int DATABASE_VERSION=1;
private static final String DATABASE_NAME="SesjePokerowe";
private static final String TABLE_SESJE="sesje";
private static final String TABLE_TURNIEJE="turnieje";
private static final String TABLE_STOLIKI="stoly";
//Kolumny tabeli sesje
private static final String KEY_IDS="ids";
//Kolumny tabeli turnieje
private static final String KEY_IDT="idt";
//Kolumny tabeli stoliki
private static final String KEY_IDSTOLIKI="idStoliki";
//kolumny powtarzalne
private static final String KEY_WPLATA="wplata";
private static final String KEY_WYPLATA="wyplata";
private static final String KEY_DATADOD="dataDodania";
private static final String CREATAE_TABLE_SESJE ="CREATE TABLE "+TABLE_SESJE+"("+KEY_IDS+" INTEGER PRIMARY KEY, "
+ KEY_WPLATA+" REAL, "+KEY_WYPLATA+" REAL, "+KEY_DATADOD+" TEXT"+")";
private static final String CREATAE_TABLE_TURNIEJE ="CREATE TABLE "+TABLE_TURNIEJE+"("+KEY_IDT+" INTEGER PRIMARY KEY, "+ KEY_IDS+" INTEGER, "
+ KEY_WPLATA+" REAL, "+KEY_WYPLATA+" REAL, "+KEY_DATADOD+" TEXT"+")";
private static final String CREATAE_TABLE_STOLIKI ="CREATE TABLE "+TABLE_STOLIKI+"("+KEY_IDSTOLIKI+" INTEGER PRIMARY KEY, "+ KEY_IDS+" INTEGER, "
+ KEY_WPLATA+" REAL, "+KEY_WYPLATA+" REAL, "+KEY_DATADOD+" TEXT"+")";
public DataBaseHelper(Context context)
{
super(context, DATABASE_NAME,null,DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db){
db.execSQL(CREATAE_TABLE_SESJE);
db.execSQL(CREATAE_TABLE_TURNIEJE);
db.execSQL(CREATAE_TABLE_STOLIKI);
}
@Override
public void onUpgrade(SQLiteDatabase db,int oldVersion, int newVersion){
db.execSQL("DROP TABLE IF EXISTS "+TABLE_SESJE);
db.execSQL("DROP TABLE IF EXISTS "+TABLE_TURNIEJE);
db.execSQL("DROP TABLE IF EXISTS "+TABLE_STOLIKI);
onCreate(db);
}
//Metody sesji
public long createSesja(Sesja sesja)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_WPLATA,sesja.wplata);
values.put(KEY_WYPLATA,sesja.wyplata);
values.put(KEY_DATADOD,sesja.data);
long idS = db.insert(TABLE_SESJE,null,values);
sesja.setIdS(idS);//Potrzebne?
return idS;
}
public Sesja getSesja(long idS)
{
SQLiteDatabase db =this.getReadableDatabase();
String selectQuery = "SELECT * FROM "+TABLE_SESJE+" WHERE "+KEY_IDS+" = "+idS;
Log.e(LOG,selectQuery);
Cursor c =db.rawQuery(selectQuery,null);
if(c!=null)
{
c.moveToFirst();
}
Sesja sesja = new Sesja();
sesja.setWplata(c.getDouble(c.getColumnIndex(KEY_WPLATA)));
sesja.setWyplata(c.getDouble(c.getColumnIndex(KEY_WYPLATA)));
sesja.setData(c.getString(c.getColumnIndex(KEY_DATADOD)));
sesja.setIdS(c.getLong(c.getColumnIndex(KEY_IDS)));
return sesja;
}
public List<Sesja> getAllSesja()
{
List<Sesja> sesjeTemp = new ArrayList<Sesja>();
String selectQuery = "SELECT * FROM "+TABLE_SESJE;
Log.e(LOG,selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery,null);
if (c.moveToFirst()) {
do {
Sesja sesja = new Sesja();
sesja.setWplata(c.getDouble(c.getColumnIndex(KEY_WPLATA)));
sesja.setWyplata(c.getDouble(c.getColumnIndex(KEY_WYPLATA)));
sesja.setData(c.getString(c.getColumnIndex(KEY_DATADOD)));
sesja.setIdS(c.getLong(c.getColumnIndex(KEY_IDS)));
sesjeTemp.add(sesja);
} while (c.moveToNext());
}
return sesjeTemp;
}
public int updateSesja(Sesja sesja){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_WPLATA,sesja.wplata);
values.put(KEY_WYPLATA,sesja.wyplata);
return db.update(TABLE_SESJE,values,KEY_IDS+" =?",new String[]{ String.valueOf(sesja.getId())});
}
public void deleteSesja(long idS)
{
SQLiteDatabase db = this.getWritableDatabase();
String where = KEY_IDS+"="+idS;
deleteStolikBySesja(idS);
deleteTurniejBySesja(idS);
db.delete(TABLE_SESJE,where,null);
// db.delete(TABLE_SESJE,KEY_IDS+" =?",new String[]{String.valueOf(idS)});
}
//Metody Turnieju
public long createTurniej(Turniej turniej)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_WPLATA,turniej.getWplata());
values.put(KEY_WYPLATA,turniej.getWyplata());
values.put(KEY_IDS,turniej.getNrSesji());
values.put(KEY_DATADOD,turniej.getData());
long idT = db.insert(TABLE_TURNIEJE,null,values);
turniej.setIdT(idT);
return idT;
}
public Turniej getTurniej(long idT)
{
SQLiteDatabase db =this.getReadableDatabase();
String selectQuery = "SELECT * FROM "+TABLE_TURNIEJE+" WHERE "+KEY_IDT+" = "+idT;
Log.e(LOG,selectQuery);
Cursor c =db.rawQuery(selectQuery,null);
if(c!=null)
{
c.moveToFirst();
}
Turniej turniej = new Turniej();
turniej.setWplata(c.getDouble(c.getColumnIndex(KEY_WPLATA)));
turniej.setWyplata(c.getDouble(c.getColumnIndex(KEY_WYPLATA)));
turniej.setData(c.getString(c.getColumnIndex(KEY_DATADOD)));
turniej.setIdT(c.getLong(c.getColumnIndex(KEY_IDT)));
return turniej;
}
public List<Wejscie> getAllTurnieje(long idS)
{
List<Wejscie> turnieje = new ArrayList<Wejscie>();
String selectQuery = "SELECT * FROM " + TABLE_TURNIEJE + " tt "
+ " WHERE tt."
+ KEY_IDS + " = " + idS;
Log.e(LOG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
if (c.moveToFirst()) {
do {
Turniej turniej = new Turniej();
turniej.setIdT(c.getLong(c.getColumnIndex(KEY_IDT)));
turniej.setWplata(c.getDouble(c.getColumnIndex(KEY_WPLATA)));
turniej.setWyplata(c.getDouble(c.getColumnIndex(KEY_WYPLATA)));
turniej.setData(c.getString(c.getColumnIndex(KEY_DATADOD)));
turnieje.add(turniej);
} while (c.moveToNext());
}
return turnieje;
}
public int updateTurniej(Turniej turniej){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_WPLATA,turniej.getWplata());
values.put(KEY_WYPLATA,turniej.getWyplata());
values.put(KEY_DATADOD,turniej.getData());
return db.update(TABLE_TURNIEJE,values,KEY_IDT+" =?",new String[]{ String.valueOf(turniej.getIdT())});
}
public void deleteTurniej(long idT)
{
SQLiteDatabase db = this.getWritableDatabase();
String where = KEY_IDT+"="+idT;
db.delete(TABLE_TURNIEJE,where,null);
// db.delete(TABLE_SESJE,KEY_IDS+" =?",new String[]{String.valueOf(idS)});
}
public void deleteTurniejBySesja(long idS)
{
SQLiteDatabase db = this.getWritableDatabase();
ArrayList<Wejscie> lista =(ArrayList<Wejscie>) getAllTurnieje(idS);
for(Wejscie w: lista)
{
Turniej t = (Turniej) w;
deleteTurniej(t.getIdT());
}
}
//Metody Stolika
public long createStolik(Stolik stolik) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_WPLATA, stolik.getWplata());
values.put(KEY_WYPLATA, stolik.getWyplata());
values.put(KEY_IDS, stolik.getNrSesji());
values.put(KEY_DATADOD, stolik.getData());
long idSTOLIKA = db.insert(TABLE_TURNIEJE, null, values);
stolik.setIdSt(idSTOLIKA);
return idSTOLIKA;
}
public Stolik getStolik(long idSt)
{
SQLiteDatabase db =this.getReadableDatabase();
String selectQuery = "SELECT * FROM "+TABLE_STOLIKI+" WHERE "+KEY_IDSTOLIKI+" = "+idSt;
Log.e(LOG,selectQuery);
Cursor c =db.rawQuery(selectQuery,null);
if(c!=null)
{
c.moveToFirst();
}
Stolik stolik = new Stolik();
stolik.setWplata(c.getDouble(c.getColumnIndex(KEY_WPLATA)));
stolik.setWyplata(c.getDouble(c.getColumnIndex(KEY_WYPLATA)));
stolik.setData(c.getString(c.getColumnIndex(KEY_DATADOD)));
stolik.setIdSt(c.getLong(c.getColumnIndex(KEY_IDS)));
return stolik;
}
public List<Wejscie> getAllStoliki(long idSTOLIK)
{
List<Wejscie> stoliki = new ArrayList<Wejscie>();
String selectQuery = "SELECT * FROM " + TABLE_STOLIKI + " tt "
+ " WHERE tt."
+ KEY_IDS + " = " + idSTOLIK;
Log.e(LOG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
if (c.moveToFirst()) {
do {
Stolik stolik = new Stolik();
stolik.setIdSt(c.getLong(c.getColumnIndex(KEY_IDSTOLIKI)));
stolik.setWplata(c.getDouble(c.getColumnIndex(KEY_WPLATA)));
stolik.setWyplata(c.getDouble(c.getColumnIndex(KEY_WYPLATA)));
stolik.setData(c.getString(c.getColumnIndex(KEY_DATADOD)));
stoliki.add(stolik);
} while (c.moveToNext());
}
return stoliki;
}
public int updateStolik(Stolik stolik){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_WPLATA,stolik.getWplata());
values.put(KEY_WYPLATA,stolik.getWyplata());
values.put(KEY_DATADOD,stolik.getData());
return db.update(TABLE_STOLIKI,values,KEY_IDSTOLIKI+" =?",new String[]{ String.valueOf(stolik.getIdSt())});
}
public void deleteStolik(long idSt)
{
SQLiteDatabase db = this.getWritableDatabase();
String where = KEY_IDSTOLIKI+"="+idSt;
db.delete(TABLE_STOLIKI,where,null);
// db.delete(TABLE_SESJE,KEY_IDS+" =?",new String[]{String.valueOf(idS)});
}
public void deleteStolikBySesja(long idS)
{
SQLiteDatabase db = this.getWritableDatabase();
ArrayList<Wejscie> lista =(ArrayList<Wejscie>) getAllStoliki(idS);
for(Wejscie w: lista)
{
Stolik s = (Stolik) w;
deleteStolik(s.getIdSt());
}
}
public void closeDB() {
SQLiteDatabase db = this.getReadableDatabase();
if (db != null && db.isOpen())
db.close();
}
public int getSesjaCount() {
String countQuery = "SELECT * FROM " + TABLE_SESJE;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
// return count
return count;
}
public int getTurniejCount() {
String countQuery = "SELECT * FROM " + TABLE_TURNIEJE;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
// return count
return count;
}
public int getStolikCount() {
String countQuery = "SELECT * FROM " + TABLE_STOLIKI;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
// return count
return count;
}
}
|
package tkhub.project.kesbewa.databinding;
import tkhub.project.kesbewa.R;
import tkhub.project.kesbewa.BR;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.view.View;
@SuppressWarnings("unchecked")
public class ListviewCartitemsBindingImpl extends ListviewCartitemsBinding {
@Nullable
private static final androidx.databinding.ViewDataBinding.IncludedLayouts sIncludes;
@Nullable
private static final android.util.SparseIntArray sViewsWithIds;
static {
sIncludes = null;
sViewsWithIds = new android.util.SparseIntArray();
sViewsWithIds.put(R.id.divider, 10);
}
// views
@NonNull
private final androidx.constraintlayout.widget.ConstraintLayout mboundView0;
// variables
// values
// listeners
// Inverse Binding Event Handlers
public ListviewCartitemsBindingImpl(@Nullable androidx.databinding.DataBindingComponent bindingComponent, @NonNull View root) {
this(bindingComponent, root, mapBindings(bindingComponent, root, 11, sIncludes, sViewsWithIds));
}
private ListviewCartitemsBindingImpl(androidx.databinding.DataBindingComponent bindingComponent, View root, Object[] bindings) {
super(bindingComponent, root, 0
, (androidx.appcompat.widget.AppCompatTextView) bindings[7]
, (android.view.View) bindings[10]
, (androidx.appcompat.widget.AppCompatImageView) bindings[1]
, (androidx.appcompat.widget.AppCompatTextView) bindings[2]
, (androidx.appcompat.widget.AppCompatTextView) bindings[4]
, (androidx.appcompat.widget.AppCompatTextView) bindings[3]
, (androidx.appcompat.widget.AppCompatTextView) bindings[5]
, (androidx.appcompat.widget.AppCompatTextView) bindings[9]
, (androidx.appcompat.widget.AppCompatTextView) bindings[8]
, (androidx.appcompat.widget.AppCompatTextView) bindings[6]
);
this.appCompatTextView13.setTag(null);
this.imgCartProduct.setTag(null);
this.mboundView0 = (androidx.constraintlayout.widget.ConstraintLayout) bindings[0];
this.mboundView0.setTag(null);
this.textview1.setTag(null);
this.textview2.setTag(null);
this.textview22.setTag(null);
this.textview3.setTag(null);
this.textviewBtnAddmore.setTag(null);
this.textviewBtnRemove.setTag(null);
this.textviewSelectedQty.setTag(null);
setRootTag(root);
// listeners
invalidateAll();
}
@Override
public void invalidateAll() {
synchronized(this) {
mDirtyFlags = 0x4L;
}
requestRebind();
}
@Override
public boolean hasPendingBindings() {
synchronized(this) {
if (mDirtyFlags != 0) {
return true;
}
}
return false;
}
@Override
public boolean setVariable(int variableId, @Nullable Object variable) {
boolean variableSet = true;
if (BR.cartitem == variableId) {
setCartitem((tkhub.project.kesbewa.data.model.CartItem) variable);
}
else if (BR.clickListener == variableId) {
setClickListener((android.view.View.OnClickListener) variable);
}
else {
variableSet = false;
}
return variableSet;
}
public void setCartitem(@Nullable tkhub.project.kesbewa.data.model.CartItem Cartitem) {
this.mCartitem = Cartitem;
synchronized(this) {
mDirtyFlags |= 0x1L;
}
notifyPropertyChanged(BR.cartitem);
super.requestRebind();
}
public void setClickListener(@Nullable android.view.View.OnClickListener ClickListener) {
this.mClickListener = ClickListener;
synchronized(this) {
mDirtyFlags |= 0x2L;
}
notifyPropertyChanged(BR.clickListener);
super.requestRebind();
}
@Override
protected boolean onFieldChange(int localFieldId, Object object, int fieldId) {
switch (localFieldId) {
}
return false;
}
@Override
protected void executeBindings() {
long dirtyFlags = 0;
synchronized(this) {
dirtyFlags = mDirtyFlags;
mDirtyFlags = 0;
}
java.lang.String doubleToStringCartitemProPriceJavaLangStringLKR = null;
int androidxDatabindingViewDataBindingSafeUnboxCartitemProTotalQty = 0;
java.lang.String cartitemProImage = null;
java.lang.Integer cartitemProTotalQty = null;
tkhub.project.kesbewa.data.model.CartItem cartitem = mCartitem;
java.lang.String cartitemProCode = null;
double androidxDatabindingViewDataBindingSafeUnboxCartitemProPrice = 0.0;
java.lang.String cartitemProColour = null;
java.lang.String doubleToStringCartitemProPrice = null;
java.lang.String cartitemProSize = null;
java.lang.String cartitemProName = null;
android.view.View.OnClickListener clickListener = mClickListener;
java.lang.Double cartitemProPrice = null;
java.lang.String integerToStringCartitemProTotalQty = null;
if ((dirtyFlags & 0x5L) != 0) {
if (cartitem != null) {
// read cartitem.pro_image
cartitemProImage = cartitem.getPro_image();
// read cartitem.pro_total_qty
cartitemProTotalQty = cartitem.getPro_total_qty();
// read cartitem.pro_code
cartitemProCode = cartitem.getPro_code();
// read cartitem.pro_colour
cartitemProColour = cartitem.getPro_colour();
// read cartitem.pro_size
cartitemProSize = cartitem.getPro_size();
// read cartitem.pro_name
cartitemProName = cartitem.getPro_name();
// read cartitem.pro_price
cartitemProPrice = cartitem.getPro_price();
}
// read androidx.databinding.ViewDataBinding.safeUnbox(cartitem.pro_total_qty)
androidxDatabindingViewDataBindingSafeUnboxCartitemProTotalQty = androidx.databinding.ViewDataBinding.safeUnbox(cartitemProTotalQty);
// read androidx.databinding.ViewDataBinding.safeUnbox(cartitem.pro_price)
androidxDatabindingViewDataBindingSafeUnboxCartitemProPrice = androidx.databinding.ViewDataBinding.safeUnbox(cartitemProPrice);
// read Integer.toString(androidx.databinding.ViewDataBinding.safeUnbox(cartitem.pro_total_qty))
integerToStringCartitemProTotalQty = java.lang.Integer.toString(androidxDatabindingViewDataBindingSafeUnboxCartitemProTotalQty);
// read Double.toString(androidx.databinding.ViewDataBinding.safeUnbox(cartitem.pro_price))
doubleToStringCartitemProPrice = java.lang.Double.toString(androidxDatabindingViewDataBindingSafeUnboxCartitemProPrice);
// read (Double.toString(androidx.databinding.ViewDataBinding.safeUnbox(cartitem.pro_price))) + (" LKR")
doubleToStringCartitemProPriceJavaLangStringLKR = (doubleToStringCartitemProPrice) + (" LKR");
}
if ((dirtyFlags & 0x6L) != 0) {
}
// batch finished
if ((dirtyFlags & 0x5L) != 0) {
// api target 1
androidx.databinding.adapters.TextViewBindingAdapter.setText(this.appCompatTextView13, doubleToStringCartitemProPriceJavaLangStringLKR);
tkhub.project.kesbewa.ui.adapters.CustomBindingAdapter.cart_img(this.imgCartProduct, cartitemProImage);
androidx.databinding.adapters.TextViewBindingAdapter.setText(this.textview1, cartitemProName);
androidx.databinding.adapters.TextViewBindingAdapter.setText(this.textview2, cartitemProSize);
androidx.databinding.adapters.TextViewBindingAdapter.setText(this.textview22, cartitemProCode);
androidx.databinding.adapters.TextViewBindingAdapter.setText(this.textview3, cartitemProColour);
androidx.databinding.adapters.TextViewBindingAdapter.setText(this.textviewSelectedQty, integerToStringCartitemProTotalQty);
}
if ((dirtyFlags & 0x6L) != 0) {
// api target 1
this.textviewBtnAddmore.setOnClickListener(clickListener);
this.textviewBtnRemove.setOnClickListener(clickListener);
}
}
// Listener Stub Implementations
// callback impls
// dirty flag
private long mDirtyFlags = 0xffffffffffffffffL;
/* flag mapping
flag 0 (0x1L): cartitem
flag 1 (0x2L): clickListener
flag 2 (0x3L): null
flag mapping end*/
//end
}
|
package sample;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXTextField;
import com.jfoenix.controls.JFXToggleButton;
import com.jfoenix.transitions.JFXKeyFrame;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javax.xml.soap.Text;
import java.util.ArrayList;
public class startNewGameSettings {
Stage window = new Stage();
GUIGame guiGame = new GUIGame();
settingsGUI settings = new settingsGUI();
String themepath = "";
String player, Player2NameString;
public int width, height, bombsNum;
public void startingGameSettings(boolean themeSelector) {
if (themeSelector) {
themepath = "./DarkStyle.css";
} else if (!themeSelector)
themepath = "./style.css";
ScrollPane scrollPane = new ScrollPane();
scrollPane.getStylesheets().add(themepath);
//To center It
scrollPane.setFitToHeight(true);
scrollPane.setFitToWidth(true);
VBox menu = new VBox();
menu.setAlignment(Pos.CENTER);
///////////////// Set NO. of Players
Label numberOfPlayers = new Label("Enter The Number Of Players: ");
numberOfPlayers.getStyleClass().add("settingsLabel");
JFXTextField numberOP = new JFXTextField();
numberOP.setLabelFloat(true);
numberOP.setPromptText("Number");
numberOP.getStyleClass().add("settingsTextField");
JFXButton submitNumber = new JFXButton("Add Players");
submitNumber.setId("addPlayersButton");
submitNumber.getStyleClass().add("button-raised");
submitNumber.getStylesheets().add(themepath);
HBox numberOPHBox = new HBox();
numberOPHBox.setAlignment(Pos.CENTER);
HBox.setMargin(numberOfPlayers, new Insets(25, 30, 30, 40));
numberOPHBox.getChildren().addAll(numberOfPlayers, numberOP, submitNumber);
////////////////////
/////////////////////
Label firstPlayerNameLabel = new Label("Name: ");
firstPlayerNameLabel.getStyleClass().add("settingsLabel");
JFXTextField player1Name = new JFXTextField();
player1Name.setLabelFloat(true);
player1Name.setPromptText("First PLayer");
player1Name.getStyleClass().add("settingsTextField");
HBox player1 = new HBox();
player1.setAlignment(Pos.CENTER);
HBox.setMargin(firstPlayerNameLabel, new Insets(25, 30, 30, 40));
player1.getChildren().addAll(firstPlayerNameLabel, player1Name);
////////////////////
Label secondPlayerNameLabel = new Label("Name: ");
secondPlayerNameLabel.getStyleClass().add("settingsLabel");
JFXTextField player2Name = new JFXTextField();
player2Name.setLabelFloat(true);
player2Name.setPromptText("Second PLayer");
player2Name.setDisable(true);
player2Name.getStyleClass().add("settingsTextField");
HBox player2 = new HBox();
player2.setAlignment(Pos.CENTER);
HBox.setMargin(secondPlayerNameLabel, new Insets(25, 30, 30, 40));
player2.getChildren().addAll(secondPlayerNameLabel, player2Name);
///////////////////
Label gridWidthLabel = new Label("Grid Width: ");
gridWidthLabel.getStyleClass().add("settingsLabel");
JFXTextField gridWidth = new JFXTextField();
gridWidth.setLabelFloat(true);
gridWidth.setPromptText("Width");
gridWidth.getStyleClass().add("settingsTextField");
HBox width = new HBox();
width.setAlignment(Pos.CENTER);
HBox.setMargin(gridWidthLabel, new Insets(25, 30, 30, 40));
width.getChildren().addAll(gridWidthLabel, gridWidth);
//////////////////
Label gridHeightLabel = new Label("Grid Height: ");
gridHeightLabel.getStyleClass().add("settingsLabel");
JFXTextField gridHeight = new JFXTextField();
gridHeight.setLabelFloat(true);
gridHeight.setPromptText("Height");
gridHeight.getStyleClass().add("settingsTextField");
HBox height = new HBox();
HBox.setMargin(gridHeightLabel, new Insets(25, 30, 30, 40));
height.setAlignment(Pos.CENTER);
height.getChildren().addAll(gridHeightLabel, gridHeight);
//////////////////
Label minesNumLabel = new Label("No. Mines: ");
minesNumLabel.getStyleClass().add("settingsLabel");
JFXTextField minesNum = new JFXTextField();
minesNum.setLabelFloat(true);
minesNum.setPromptText("Mines");
minesNum.getStyleClass().add("settingsTextField");
HBox mines = new HBox();
mines.setAlignment(Pos.CENTER);
HBox.setMargin(minesNumLabel, new Insets(25, 30, 30, 40));
mines.getChildren().addAll(minesNumLabel, minesNum);
//////////////////////////
Label toggleLabel = new Label("Activate Second Player");
toggleLabel.getStyleClass().add("settingsLabel");
Label AutoPlayerLabel = new Label("Activate Auto Player");
AutoPlayerLabel.getStyleClass().add("settingLabel");
Label autoPlayer = new Label("Activate Auto player");
JFXToggleButton autoplayerToggleButton = new JFXToggleButton();
autoplayerToggleButton.setSelected(false);
autoplayerToggleButton.setId("toggleButton");
autoplayerToggleButton.setOnAction(e -> {
if (autoplayerToggleButton.isSelected()) {
player2Name.setText("");
player2Name.setDisable(true);
} else player2Name.setDisable(false);
});
HBox autoplayerBox = new HBox();
autoplayerBox.setAlignment(Pos.CENTER);
HBox.setMargin(autoPlayer, new Insets(10, 30, 30, 40));
autoplayerBox.getChildren().addAll(autoPlayer, autoplayerToggleButton);
JFXToggleButton toggleSecPlayer = new JFXToggleButton();
toggleSecPlayer.setSelected(false);
toggleSecPlayer.setId("toggleButton");
toggleSecPlayer.getStylesheets().add(themepath);
toggleSecPlayer.setOnAction(e -> {
if (!toggleSecPlayer.isSelected()) {
toggleSecPlayer.setSelected(false);
player2Name.setDisable(true);
} else {
toggleSecPlayer.setSelected(true);
player2Name.setDisable(false);
}
});
HBox toggle = new HBox();
toggle.setAlignment(Pos.CENTER);
HBox.setMargin(toggleLabel, new Insets(5, 30, 20, 40));
toggle.getChildren().addAll(toggleLabel, toggleSecPlayer);
///////////////////
JFXButton startGameButton = new JFXButton("Start !");
startGameButton.getStyleClass().add("button-raised");
startGameButton.setOnAction(e -> {
/////////////////////////////////////////////////////////// INIT NEW GAME ON ACTION HERE
ArrayList<Player> players = new ArrayList<>();
try {
this.Player2NameString = player2Name.getText();
this.player = player1Name.getText();
this.width = Integer.parseInt(gridWidth.getText());
this.height = Integer.parseInt(gridHeight.getText());
this.bombsNum = Integer.parseInt(minesNum.getText());
} catch (Exception ex) {
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Wrong input");
alert.setContentText("rechange the field properly!");
alert.showAndWait();
return;
}
Player p1 = new HumanPlayer();
Player p2 = new HumanPlayer();
p1.getShield().setShieldCount(Integer.parseInt(settings.shieldsCount));
p2.getShield().setShieldCount(Integer.parseInt(settings.shieldsCount));
p1.setName(player1Name.getText());
p2.setName(player2Name.getText());
players.add(p1);
if (toggleSecPlayer.isSelected())
players.add(p2);
if (autoplayerToggleButton.isSelected()) {
toggleSecPlayer.setSelected(false);
p2 = new autoPlayer();
p2.getShield().setShieldCount(0);
players.add(p2);
}
System.out.println(player + width + height);
Grid grid = new Grid(this.width, this.height, bombsNum);
System.out.println(settings.bombkScore);
if (Integer.parseInt(settings.bombkScore) > 0)
guiGame = new GUIGame(players, grid, Integer.parseInt(settings.bombkScore), Integer.parseInt(settings.blankScore)
, Integer.parseInt(settings.flagScore), Integer.parseInt(settings.shieldsCount), true, GameMode.NEW_GAME);
else
guiGame = new GUIGame(players, grid, Integer.parseInt(settings.bombkScore), Integer.parseInt(settings.blankScore)
, Integer.parseInt(settings.flagScore), Integer.parseInt(settings.shieldsCount), false,
GameMode.NEW_GAME);
window.setScene(guiGame.returnScene(this.width, this.height, player, Player2NameString, 1100,
700, themeSelector, settings.shieldsCount));
window.setMaximized(true);
window.setOnCloseRequest(event -> guiGame.timer.interrupt());
});
menu.setAlignment(Pos.CENTER);
menu.getStylesheets().
add(themepath);
menu.getChildren().
addAll(player1, player2, width, height, mines, toggle, autoplayerBox, startGameButton);
Scene newGameSettings = new Scene(menu, 1100, 700);
window.setScene(newGameSettings);
window.setTitle("Mine Sweeper - The Game");
window.show();
}
}
|
package 线程基础;
import org.junit.jupiter.api.Test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class 线程池 {
//创建线程池
public void PoolTest(){
//单一的线程池,一次只能存放一个线程,串行运行
ExecutorService eServer = Executors.newSingleThreadExecutor();
//往线程池中添加线程
eServer.execute(new MyRunnable());
eServer.execute(new MyRunnable());
eServer.execute(new MyRunnable());
//关闭线程池
eServer.shutdown();
}
public void PoolTest2(){
//设置固定容量的线程池
ExecutorService eServer = Executors.newFixedThreadPool(3);
eServer.execute(new MyRunnable());
eServer.execute(new MyRunnable());
eServer.execute(new MyRunnable());
eServer.shutdown();
}
public void PoolTest3(){
//大小没用限制可以缓存的Pool
//缺点线程个数是不可控的
ExecutorService eServer = Executors.newCachedThreadPool();
eServer.execute(new MyRunnable());
eServer.execute(new MyRunnable());
eServer.execute(new MyRunnable());
eServer.execute(new MyRunnable());
eServer.execute(new MyRunnable());
eServer.shutdown();
}
@Test
public void PoolTest4(){
//可以延时处理
ScheduledExecutorService eServer = Executors.newScheduledThreadPool(5);
eServer.schedule(new MyRunnable(),1, TimeUnit.MILLISECONDS);
eServer.shutdown();
}
class MyRunnable implements Runnable{
@Override
public void run() {
for(int i=0;i<5;i++){
System.out.println(i);
}
System.out.println(Thread.currentThread().getName()+" 结束");
}
}
}
|
package com.gxuwz.attend.service;
import org.springframework.transaction.annotation.Transactional;
import com.gxuwz.attend.dao.LoginDao;
import com.gxuwz.attend.entity.Admin;
@Transactional
public class LoginServiceimp implements LoginService {
LoginDao loginDao;
public String login(Admin admin){
String a="login";
if(loginDao.login(admin)){
if(admin.getAdminType().equals("A")){
a = "studnet";
}if(admin.getAdminType().equals("B")){
a = "teacher";
}if(admin.getAdminType().equals("C")){
a= "user";
}}
return a;
}
//gt
public void setLoginDao(LoginDao loginDao) {
this.loginDao = loginDao;
}
}
|
package exer;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import org.junit.Test;
public class Test1 {
@Test
public void test1() throws Exception{
Connection conn = getConnection1();
Statement state = conn.createStatement();
String sql = "insert into test values (null,'王五',1000)";
int i = state.executeUpdate(sql);
System.out.println(i > 0 ? "修改成功" : "修改失败");
state.close();
conn.close();
}
@Test
public void test3() throws Exception{
Connection conn = getConnection2();
Statement state = conn.createStatement();
String sql = "select * from test";
ResultSet rs = state.executeQuery(sql);
while(rs.next()){
Object name = rs.getObject(1);
Object balance = rs.getObject(2);
System.out.println(name + ":" + balance);
}
rs.close();
state.close();
conn.close();
}
public Connection getConnection1() throws ClassNotFoundException, SQLException{
// Driver driver = new com.mysql.jdbc.Driver();
String driverClass = "com.mysql.jdbc.Driver";
Class.forName(driverClass);
String url = "jdbc:mysql://localhost:3306/db1?rewriteBatchedStatements=true";
// String url = "jdbc:mysql://localhost:3306/db1";
String user = "root";
String password = "root";
Connection conn = DriverManager.getConnection(url, user, password);
return conn;
}
@Test
public static Connection getConnection2(){
Properties pros = new Properties();
Connection conn = null;
try {
pros.load(Test1.class.getClassLoader().getResourceAsStream("jdbc.properties"));
String url = pros.getProperty("url");
String user = pros.getProperty("user");
String password = pros.getProperty("password");
String driverClass = pros.getProperty("driverClass");
Class.forName(driverClass);
conn = DriverManager.getConnection(url, user, password);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
}
|
package sistema.presentation.prestamos;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import sistema.Application;
import sistema.logic.Cliente;
import sistema.logic.Prestamo;
import sistema.logic.Service;
public class ControllerPrestamo {
ModelPrestamo model;
ViewPrestamo view;
public ControllerPrestamo(ModelPrestamo model, ViewPrestamo view) {
this.model = model;
this.view = view;
model.setPrestamo(new Prestamo());
model.setPrestamos(new ArrayList<>());
view.setModel(model);
view.setController(this);
}
public void show(){
this.view.setVisible(true);
}
public void show(Cliente c){
this.model.setCliente(c);
this.view.setVisible(true);
}
public void hide(){
this.view.setVisible(false);
Application.CLIENTES.show();
}
public void prestamoAdd(String ced, Prestamo prestamo){
try {
Service.instance().prestamoAdd(ced, prestamo);
model.setPrestamo(new Prestamo("", 0, 0, 0));
model.setPrestamos(Arrays.asList(prestamo));
model.commit();
} catch (Exception ex) {
}
}
public void prestamoGet(String ced, String numero){
try {
Prestamo prestamo = Service.instance().prestamoGet(ced, numero);
model.setPrestamo(prestamo);
model.setPrestamos(Arrays.asList(prestamo));
model.commit();
} catch (Exception ex) {
model.setPrestamo(new Prestamo());
model.setPrestamos(new ArrayList<>());
model.commit();
}
}
public void prestamoEdit(int row){
Prestamo prestamo = model.getPrestamos().get(row);
model.setPrestamo(prestamo);
model.commit();
}
public void mensualidadShow(){
this.hide();
Application.PAGOS.show();
}
public void prestamoSearch(String ced){
List<Prestamo> prestamos = Service.instance().prestamoSearch(ced);
model.setPrestamo(new Prestamo("", 0, 0, 0));
model.setPrestamos(prestamos);
model.commit();
}
public void setCliente(Cliente cliente){
this.model.setCliente(cliente);
this.model.setPrestamos(cliente.getPrestamos());
this.model.commit();
}
void createPdfPrestamos(List<Prestamo> prestamos) throws IOException{
Application.createPdfPrestamos(model.getPrestamos());
}
}
|
package webmail;
/**
* Created by JOKER on 10/28/14.
*/
import org.eclipse.jetty.server.*;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import webmail.entities.Folder;
import webmail.managers.ajaxManagers.TestManager;
import webmail.managers.ajaxManagers.addEmailPageManagers.AddEmailManager;
import webmail.managers.ajaxManagers.addEmailPageManagers.AddEmailPasswordManager;
import webmail.managers.ajaxManagers.registrationPageManagers.ConfirmManager;
import webmail.managers.ajaxManagers.registrationPageManagers.PasswordManager;
import webmail.managers.ajaxManagers.registrationPageManagers.SubmitButtonManager;
import webmail.managers.ajaxManagers.registrationPageManagers.UsernameManager;
import webmail.managers.emailManagers.*;
import webmail.managers.userManagers.*;
import webmail.misc.STListener;
import webmail.pages.*;
import org.eclipse.jetty.server.handler.RequestLogHandler;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
public class WebmailServer {
public static final String WEBMAIL_TEMPLATES_ROOT = "resources/templates";
public static final STListener stListener = new STListener(); //listen error not used now
public static Map<String,Class> mapping = new HashMap<String, Class>(); //store <url,page>
static {
//mapping.put("", HomePage.class); //change to login maybe
mapping.put("/", LoginPage.class);
mapping.put("/amail", AmailPage.class);
mapping.put("/login", LoginPage.class);
mapping.put("/registration", RegistrationPage.class);
mapping.put("/addAccount", AddEmailPage.class);
mapping.put("/users", UserListPage.class);
mapping.put("/welcome", WelcomePage.class);
mapping.put("/help", HelpPage.class);
mapping.put("/service", ServicePage.class);
mapping.put("/aboutAmail", AboutAmailPage.class);
// user Managers
mapping.put("/userCreationManager", UserCreationManager.class);
mapping.put("/userLoginManager", UserLoginManager.class);
mapping.put("/userLogoutManager", UserLogoutManager.class);
mapping.put("/userAddEmailManager", UserAddEmailManager.class);
mapping.put("/edit", EditPage.class);
mapping.put("/changePwdManager", ChangePwdManager.class);
mapping.put("/testManager", TestManager.class);
// registrationPage Managers
mapping.put("/usernameManager", UsernameManager.class);
mapping.put("/passwordManager", PasswordManager.class);
mapping.put("/confirmManager", ConfirmManager.class);
mapping.put("/submitButtonManager", SubmitButtonManager.class);
// addEmailPage Managers
mapping.put("/addEmailManager", AddEmailManager.class);
mapping.put("/addEmailPassword", AddEmailPasswordManager.class);
// email pages
mapping.put("/afterWelcomeBeforeInboxManager", AfterWelcomeBeforeInboxManager.class);
mapping.put("/inbox", InboxPage.class);
mapping.put("/sent", SentPage.class);
mapping.put("/draft", DraftPage.class);
mapping.put("/trash", TrashPage.class);
mapping.put("/sendEmail", SendEmailPage.class);
mapping.put("/sendEmailManager", SendEmailManager.class);
mapping.put("/emailSendSuccess", EmailSendSuccessPage.class);
mapping.put("/checkEmailManager", CheckEmailManager.class);
mapping.put("/viewEmail", ViewEmailPage.class);
mapping.put("/reply", ReplyPage.class);
mapping.put("/forward", ForwardPage.class);
mapping.put("/replyManager", ReplyManager.class);
mapping.put("/forwardManager", ForwardManager.class);
mapping.put("/deleteManager", DeleteManager.class);
mapping.put("/emptyManager", EmptyManager.class);
mapping.put("/leftManager", LeftManager.class);
mapping.put("/rightManager", RightManager.class);
mapping.put("/orderbyManager", OrderbyManager.class);
mapping.put("/searchPage", SearchPage.class);
mapping.put("/contacts", ContactsPage.class);
mapping.put("/addContact", AddContactPage.class);
mapping.put("/addContactManager", AddContactManager.class);
mapping.put("/contactEdit", ContactEditPage.class);
mapping.put("/editContactManager", EditContactManager.class);
mapping.put("/contactDeleteManager", ContactDeleteManager.class);
mapping.put("/sendEmailWithTo", SendEmailWithToPage.class);
//mapping.put("/page",Page.class);
mapping.put("/unreadManager", UnreadManager.class);
mapping.put("/folder", FolderPage.class);
mapping.put("/addFolder", AddFolderPage.class);
mapping.put("/addFolderManager", AddFolderManager.class);
mapping.put("/folderEdit", FolderEditPage.class);
mapping.put("/editFolderManager", EditFolderManager.class);
mapping.put("/folderDeleteManager", FolderDeleteManager.class);
mapping.put("/moveFolderManager", MoveFolderManager.class);
mapping.put("/userFolder", UserFolderPage.class);
mapping.put("/returnManager", ReturnManager.class);
mapping.put("/uploadManager", UploadManager.class);
}
public static void main(String[] args) throws Exception {
if ( args.length<2 ) {
System.err.println("java webmail.Server static-files-dir log-dir");
System.exit(1);
}
String staticFilesDir = args[0]; //mark
String logDir = args[1]; //mark
//Server server = new Server(8080);
ServletContextHandler context = new
ServletContextHandler(ServletContextHandler.SESSIONS); //option = 1
context.setContextPath("/");
// server.setHandler(context);
String jettyDistKeystore = "resources/keystore";
String keystorePath = System.getProperty(
"example.keystore", jettyDistKeystore);
File keystoreFile = new File(keystorePath);
if (!keystoreFile.exists())
{
throw new FileNotFoundException(keystoreFile.getAbsolutePath());
}
// Create a basic jetty server object without declaring the port. Since
// we are configuring connectors directly we'll be setting ports on
// those connectors.
Server server = new Server();
// HTTP Configuration
// HttpConfiguration is a collection of configuration information
// appropriate for http and https. The default scheme for http is
// <code>http</code> of course, as the default for secured http is
// <code>https</code> but we show setting the scheme to show it can be
// done. The port for secured communication is also set here.
HttpConfiguration http_config = new HttpConfiguration();
http_config.setSecureScheme("https");
http_config.setSecurePort(8443);
http_config.setOutputBufferSize(32768);
// HTTP connector
// The first server connector we create is the one for http, passing in
// the http configuration we configured above so it can get things like
// the output buffer size, etc. We also set the port (8080) and
// configure an idle timeout.
ServerConnector http = new ServerConnector(server,
new HttpConnectionFactory(http_config));
http.setPort(8080);
http.setIdleTimeout(30000);
// SSL Context Factory for HTTPS and SPDY
// SSL requires a certificate so we configure a factory for ssl contents
// with information pointing to what keystore the ssl connection needs
// to know about. Much more configuration is available the ssl context,
// including things like choosing the particular certificate out of a
// keystore to be used.
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setKeyStorePath(keystoreFile.getAbsolutePath());
sslContextFactory.setKeyStorePassword("OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4");
sslContextFactory.setKeyManagerPassword("OBF:1u2u1wml1z7s1z7a1wnl1u2g");
// HTTPS Configuration
// A new HttpConfiguration object is needed for the next connector and
// you can pass the old one as an argument to effectively clone the
// contents. On this HttpConfiguration object we add a
// SecureRequestCustomizer which is how a new connector is able to
// resolve the https connection before handing control over to the Jetty
// Server.
HttpConfiguration https_config = new HttpConfiguration(http_config);
https_config.addCustomizer(new SecureRequestCustomizer());
// HTTPS connector
// We create a second ServerConnector, passing in the http configuration
// we just made along with the previously created ssl context factory.
// Next we set the port and a longer idle timeout.
ServerConnector https = new ServerConnector(server,
new SslConnectionFactory(sslContextFactory, "http/1.1"),
new HttpConnectionFactory(https_config));
https.setPort(8443);
https.setIdleTimeout(500000);
// Here you see the server having multiple connectors registered with
// it, now requests can flow into the server from both http and https
// urls to their respective ports and be processed accordingly by jetty.
// A simple handler is also registered with the server so the example
// has something to pass requests off to.
// Set the connectors
server.setConnectors(new Connector[] { http, https });
// add a simple Servlet at "/dynamic/*"
ServletHolder holderDynamic = new ServletHolder("dynamic", DispatchServlet.class);
context.addServlet(holderDynamic, "/*");
// add special pathspec of "/home/" content mapped to the homePath
ServletHolder holderHome = new ServletHolder("static-home", DefaultServlet.class);
holderHome.setInitParameter("resourceBase",staticFilesDir);
holderHome.setInitParameter("dirAllowed","true");
holderHome.setInitParameter("pathInfoOnly","true");
context.addServlet(holderHome, "/files/*");
// Lastly, the default servlet for root content (always needed, to satisfy servlet spec)
// It is important that this is last.
ServletHolder holderPwd = new ServletHolder("default", DefaultServlet.class);
holderPwd.setInitParameter("resourceBase","/tmp/foo");
holderPwd.setInitParameter("dirAllowed","true");
context.addServlet(holderPwd, "/");
// log using NCSA (common log format)
// http://en.wikipedia.org/wiki/Common_Log_Format
NCSARequestLog requestLog = new NCSARequestLog();
requestLog.setFilename(logDir + "/yyyy_mm_dd.request.log");
requestLog.setFilenameDateFormat("yyyy_MM_dd");
requestLog.setRetainDays(90);
requestLog.setAppend(true);
requestLog.setExtended(true);
requestLog.setLogCookies(false);
requestLog.setLogTimeZone("GMT");
RequestLogHandler requestLogHandler = new RequestLogHandler();
requestLogHandler.setRequestLog(requestLog);
requestLogHandler.setServer(server);
HandlerCollection handlerCollection=new HandlerCollection();
handlerCollection.addHandler(requestLogHandler);
handlerCollection.addHandler(context);
server.setHandler(handlerCollection);
server.start();
server.join();
}
}
|
package com.tencent.mm.plugin.honey_pay.a;
import com.tencent.mm.ab.b;
import com.tencent.mm.ab.b.a;
import com.tencent.mm.network.q;
import com.tencent.mm.protocal.c.avh;
import com.tencent.mm.protocal.c.avi;
import com.tencent.mm.protocal.c.bao;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.wallet_core.c.h;
public final class j extends h {
private final String TAG = "MicroMsg.NetSceneModifyHoneyPayerPayWay";
private avi kjK;
public j(bao bao, String str) {
a aVar = new a();
aVar.dIG = new avh();
aVar.dIH = new avi();
aVar.dIF = 2941;
aVar.uri = "/cgi-bin/mmpay-bin/modifyhppayerpayway";
aVar.dII = 0;
aVar.dIJ = 0;
this.diG = aVar.KT();
avh avh = (avh) this.diG.dID.dIL;
avh.rPo = bao;
avh.rIw = str;
x.i("MicroMsg.NetSceneModifyHoneyPayerPayWay", "cardNo: %s, suffix: %s, bankType: %s", new Object[]{str, bao.scZ, bao.lMV});
}
public final int getType() {
return 2941;
}
public final void b(int i, int i2, String str, q qVar) {
x.i("MicroMsg.NetSceneModifyHoneyPayerPayWay", "errType: %s, errCode: %s, errMsg: %s", new Object[]{Integer.valueOf(i), Integer.valueOf(i2), str});
this.kjK = (avi) ((b) qVar).dIE.dIL;
x.i("MicroMsg.NetSceneModifyHoneyPayerPayWay", "retcode: %s, retmsg: %s", new Object[]{Integer.valueOf(this.kjK.hwV), this.kjK.hwW});
if (this.diJ != null) {
this.diJ.a(i, i2, str, this);
}
}
protected final void f(q qVar) {
avi avi = (avi) ((b) qVar).dIE.dIL;
this.uXe = avi.hwV;
this.uXf = avi.hwW;
}
}
|
package com.webcloud.widget;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.widget.ScrollView;
public class MultiScroll extends ScrollView {
private Handler handler;
private View view;
public MultiScroll(Context context) {
super(context);
}
public MultiScroll(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MultiScroll(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
/**
* @Override public boolean onInterceptTouchEvent(MotionEvent event)
* //这个方法如果返回 true 的话 两个手指移动,启动一个按下的手指的移动不能被传播出去。 {
* super.onInterceptTouchEvent(event); return false; }
* @Override public boolean onTouchEvent(MotionEvent event) //这个方法如果 true
* 则整个Activity 的 onTouchEvent() 不会被系统回调 {
* super.onTouchEvent(event); return false; }
*/
// 这个获得总的高度
public int computeVerticalScrollRange() {
return super.computeHorizontalScrollRange();
}
public int computeVerticalScrollOffset() {
return super.computeVerticalScrollOffset();
}
private void init() {
this.setOnTouchListener(onTouchListener);
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// process incoming messages here
super.handleMessage(msg);
switch (msg.what) {
case 1:
if (view.getMeasuredHeight() <= getScrollY() + getHeight()) {
if (onScrollListener != null) {
onScrollListener.onBottom();
}
} else if (getScrollY() == 0) {
if (onScrollListener != null) {
onScrollListener.onTop();
}
} else {
if (onScrollListener != null) {
onScrollListener.onScroll();
}
}
break;
default:
break;
}
}
};
}
private VelocityTracker mVelocityTracker;
OnTouchListener onTouchListener = new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(event);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
break;
case MotionEvent.ACTION_UP:
if (view != null && onScrollListener != null) {
//handler.sendMessageDelayed(handler.obtainMessage(1), 200);
}
break;
case MotionEvent.ACTION_MOVE:
final VelocityTracker velocityTracker = mVelocityTracker;
velocityTracker.computeCurrentVelocity(1000);
int velocityY = (int) velocityTracker.getYVelocity();
int velocityX = (int) velocityTracker.getYVelocity();
if (velocityY > 100) {
if (view != null && onScrollListener != null) {
handler.sendMessageDelayed(handler.obtainMessage(1), 200);
}
}
if (mVelocityTracker != null) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
break;
default:
break;
}
return false;
}
};
/**
* 获得参考的View,主要是为了获得它的MeasuredHeight,然后和滚动条的ScrollY+getHeight作比较。
*/
public void getView() {
this.view = getChildAt(0);
if (view != null) {
init();
}
}
/**
* 定义接口
*
* @author admin
*
*/
public interface OnScrollListener {
void onBottom();
void onTop();
void onScroll();
}
private OnScrollListener onScrollListener;
public void setOnScrollListener(OnScrollListener onScrollListener) {
this.onScrollListener = onScrollListener;
}
}
|
package com.coinhunter.core.domain.strategy;
import lombok.AllArgsConstructor;
import java.io.Serializable;
@AllArgsConstructor
public class Strategy implements Serializable {
private ProfitTarget profitTarget;
private StopLoss stopLoss;
private TrailingStop trailingStop;
}
|
/*
* Copyright 2013 Cloudera.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kitesdk.data.spi;
import com.google.common.base.Preconditions;
import java.text.NumberFormat;
import org.apache.avro.Schema;
import org.apache.avro.specific.SpecificData;
import org.kitesdk.data.DatasetDescriptor;
import org.kitesdk.data.PartitionStrategy;
/**
* Static helper methods for converting between types.
*
* @since 0.9.0
*/
public class Conversions {
public static <T> T convert(Object obj, Class<T> returnType) {
if (returnType.isAssignableFrom(Long.class)) {
return returnType.cast(makeLong(obj));
} else if (returnType.isAssignableFrom(Integer.class)) {
return returnType.cast(makeInteger(obj));
} else if (returnType.isAssignableFrom(String.class)) {
return returnType.cast(makeString(obj));
} else if (returnType.isAssignableFrom(Double.class)) {
return returnType.cast(makeDouble(obj));
} else if (returnType.isAssignableFrom(Float.class)) {
return returnType.cast(makeFloat(obj));
} else if (returnType.isAssignableFrom(Object.class)) {
return returnType.cast(obj);
} else {
throw new ClassCastException(
"Cannot convert to unknown return type:" + returnType.getName());
}
}
public static Long makeLong(Object value) {
if (value instanceof Number) {
return ((Number) value).longValue();
} else if (value instanceof String) {
return Long.valueOf((String) value);
} else {
throw new RuntimeException(
"Cannot coerce \"" + value + "\" to Long");
}
}
public static Integer makeInteger(Object value) {
if (value instanceof Number) {
return ((Number) value).intValue();
} else if (value instanceof String) {
return Integer.valueOf((String) value);
} else {
throw new RuntimeException(
"Cannot coerce \"" + value + "\" to Integer");
}
}
public static Double makeDouble(Object value) {
if (value instanceof Number) {
return ((Number) value).doubleValue();
} else if (value instanceof String) {
return Double.valueOf((String) value);
} else {
throw new RuntimeException(
"Cannot coerce \"" + value + "\" to Double");
}
}
public static Float makeFloat(Object value) {
if (value instanceof Number) {
return ((Number) value).floatValue();
} else if (value instanceof String) {
return Float.valueOf((String) value);
} else {
throw new RuntimeException(
"Cannot coerce \"" + value + "\" to Double");
}
}
public static String makeString(Object value) {
// start simple, but we may want more complicated conversion here if, for
// example, we needed to support Writables or other serializations
return value.toString();
}
public static String makeString(Object value, Integer width) {
if (width != null && value instanceof Number) {
NumberFormat format = NumberFormat.getInstance();
format.setMinimumIntegerDigits(width);
format.setGroupingUsed(false);
return format.format(value);
} else {
return makeString(value);
}
}
/**
* Checks that the type of each of {@code values} is consistent with the type of
* field {@code fieldName} declared in the Avro schema (from {@code descriptor}).
*/
public static void checkTypeConsistency(DatasetDescriptor descriptor, String fieldName,
Object... values) {
Preconditions.checkArgument(hasField(descriptor, fieldName),
"No field '%s' in descriptor %s", fieldName, descriptor);
Schema schema = descriptor.getSchema();
Schema.Field field = schema.getField(fieldName);
for (Object value : values) {
// SpecificData#validate checks consistency for generic, reflect,
// and specific models.
Preconditions.checkArgument(SpecificData.get().validate(field.schema(), value),
"Value '%s' of type '%s' inconsistent with field %s.", value, value.getClass(),
field);
}
}
private static boolean hasField(DatasetDescriptor descriptor, String fieldName) {
Schema schema = descriptor.getSchema();
Schema.Field field = schema.getField(fieldName);
if (field != null) {
return true;
}
PartitionStrategy partitionStrategy = descriptor.getPartitionStrategy();
for (FieldPartitioner<?, ?> fp : partitionStrategy.getFieldPartitioners()) {
if (fp.getName().equals(fieldName)) {
return true;
}
}
return false;
}
}
|
package mod.tainan;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import sqlite.DB_Model;
import _util.jsonResultToDB;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;
public class MainSwitcher extends HttpLoadActivity {
final String jsonUrl = "http://odata.tn.edu.tw/tnsport.json";
private ProgressDialog progreeDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main_switcher);
DB_Model DB = new DB_Model(MainSwitcher.this);
DB.None_insert_1();
}
public void goToGamePage_click(View view) {
startActivity(new Intent(MainSwitcher.this,testMsg.class));
}
public void goToRunningPage_click(View view) {
startActivity(new Intent(MainSwitcher.this, Running_map.class));
}
public void goToShowHistoryPage_click(View view) {
startActivity(new Intent(MainSwitcher.this, Hitory.class));
}
public void goResetInfo(View view) {
startActivity(new Intent(MainSwitcher.this, ResetUserInfo.class));
}
public void toAbout(View view){
startActivity(new Intent(MainSwitcher.this, about_this_team.class));
}
public void loadData(View view) {
if (isConnected()) {
progreeDialog = ProgressDialog.show(MainSwitcher.this,
"opdata load", "loading");
new HttpAsyncTask() {
@Override
protected void onPostExecute(String result) {
progreeDialog.dismiss();
Toast.makeText(getBaseContext(), "Received!",
Toast.LENGTH_LONG).show();
jsonResultToDB jsonModel = new jsonResultToDB(
MainSwitcher.this);
try {
jsonModel.Tnsport(result);
} catch (JSONException ex) {
}
}
}.execute(jsonUrl);
}
}
}
|
package app.model;
import java.io.Serializable;
import javax.persistence.*;
import java.math.BigDecimal;
import java.util.List;
/**
* The persistent class for the PRODUCTS database table.
*
*/
@Entity
@Table(name="PRODUCTS", schema="MARKET")
@NamedQuery(name="Product.findAll", query="SELECT p FROM Product p")
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name="PRODUCT_ID")
private long productId;
@Column(name="LIST_PRICE")
private BigDecimal listPrice;
private String product;
//bi-directional many-to-one association to OrderItem
@OneToMany(mappedBy="product")
private List<OrderItem> orderItems;
public Product() {
}
public long getProductId() {
return this.productId;
}
public void setProductId(long productId) {
this.productId = productId;
}
public BigDecimal getListPrice() {
return this.listPrice;
}
public void setListPrice(BigDecimal listPrice) {
this.listPrice = listPrice;
}
public String getProduct() {
return this.product;
}
public void setProduct(String product) {
this.product = product;
}
public List<OrderItem> getOrderItems() {
return this.orderItems;
}
public void setOrderItems(List<OrderItem> orderItems) {
this.orderItems = orderItems;
}
public OrderItem addOrderItem(OrderItem orderItem) {
getOrderItems().add(orderItem);
orderItem.setProduct(this);
return orderItem;
}
public OrderItem removeOrderItem(OrderItem orderItem) {
getOrderItems().remove(orderItem);
orderItem.setProduct(null);
return orderItem;
}
}
|
package com.forsrc.utils;
import org.springframework.context.MessageSource;
/**
* The type My message source.
*/
public class MyMessageSource {
private MessageSource MessageSource;
private MyMessageSource() {
}
/**
* Gets instance.
*
* @return the instance
*/
public static MyMessageSource getInstance() {
return MyMessageSourceClass.INSTANCE;
}
/**
* Gets message source.
*
* @return the message source
*/
public org.springframework.context.MessageSource getMessageSource() {
return MessageSource;
}
/**
* Sets message source.
*
* @param messageSource the message source
*/
public void setMessageSource(org.springframework.context.MessageSource messageSource) {
MessageSource = messageSource;
}
private static class MyMessageSourceClass {
private static final MyMessageSource INSTANCE = new MyMessageSource();
}
}
|
package com.chalienko.medcard.domain.model;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
import java.util.List;
import javax.persistence.*;
@Entity
@Table(name = "users")
@Transactional
public class User implements Serializable {
@Id
@GeneratedValue
private Long id;
@Column(name = "username")
private String userName;
@Column(name = "password")
private String password;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "second_name")
private String secondName;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "id_role")
private Role role;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "id_department")
private Department department;
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "user")
private List<Examination> examinations;
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "doctor")
private List<Patient> patients;
public List<Patient> getPatients() {
return patients;
}
public void setPatients(List<Patient> patients) {
this.patients = patients;
}
public User() {
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
public User(String userName, String password, String firstName, String lastName, String secondName, Role role,
List<Examination> examinations) {
this.userName = userName;
this.password = password;
this.firstName = firstName;
this.lastName = lastName;
this.secondName = secondName;
this.role = role;
this.examinations = examinations;
}
public User(User user) {
this.userName = user.getUserName();
this.password = user.getPassword();
this.firstName = user.getFirstName();
this.lastName = user.getLastName();
this.secondName = user.getSecondName();
this.role = user.getRole();
this.examinations = user.getExaminations();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getSecondName() {
return secondName;
}
public void setSecondName(String secondName) {
this.secondName = secondName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
public List<Examination> getExaminations() {
return examinations;
}
public void setExaminations(List<Examination> examinations) {
this.examinations = examinations;
}
}
|
package ch02.ex02_13;
import static org.junit.Assert.*;
import org.junit.Test;
public class VehicleTest {
//methodTest
@Test
public void testMethod() {
Vehicle car = new Vehicle("Mike");
car.setVelocity(2.0);
car.setDirection(Math.PI / 2);
double expectedVelocity = 2.0;
assertEquals(new Double(expectedVelocity), new Double(car.getVelocity()));
double expectedDirection = Math.PI / 2;
assertEquals(new Double(expectedDirection), new Double(car.getDirection()));
Vehicle train = new Vehicle("Joe");
train.setVelocity(4.0);
train.setDirection(Math.PI * 2);
expectedVelocity = 4.0;
assertEquals(new Double(expectedVelocity), new Double(train.getVelocity()));
expectedDirection = Math.PI * 2;
assertEquals(new Double(expectedDirection), new Double(train.getDirection()));
Vehicle airplane = new Vehicle("Nick");
airplane.setVelocity(8.0);
airplane.setDirection(Math.PI);
expectedVelocity = 8.0;
assertEquals(new Double(expectedVelocity), new Double(airplane.getVelocity()));
expectedDirection = Math.PI;
assertEquals(new Double(expectedDirection), new Double(airplane.getDirection()));
}
}
|
package hr.mealpler.database.entities;
import java.sql.Date;
public class Warning {
private Long id;
private Long user_id;
private Date date;
private String text;
public Warning() {
}
public Warning(Long id, Long userId, Date date, String text) {
super();
this.id = id;
this.user_id = userId;
this.date = date;
this.text = text;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getUserId() {
return user_id;
}
public void setUserId(Long userId) {
this.user_id = userId;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
|
package com.eason.lottert;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
/**
* @ 文件名: main
* @ 创建者: Eason
* @ 时间: 2018/9/24 17:31
* @ 描述:
*/
@SpringBootApplication
@ServletComponentScan
public class LotteryMain {
public static void main(String[] args) {
SpringApplication.run(LotteryMain.class, args);
}
}
|
package pms.dto;
import java.util.ArrayList;
import org.springframework.web.multipart.MultipartFile;
public class Task {
private int pno;
private int project_no;
private int task_no;
private String task_content;
private int task_parent_no;
private String startdte;
private String enddte;
private String task_status;
private String task_priority; //추가
private String task_name; //추가
private String name; // 추가 // 디테일 화면에서 사원이름 조회 위함
private String project_name; // 추가 // 디테일 화면에서 프로젝트 이름 조회 위함
private MultipartFile[] report; // 업로드 시 필요(파일 수정 시 업로드)
private ArrayList<TaskFile> fileInfo; // 다운로드 시 필요
private int tasktotal; // 추가 //대시보드 화면
private int taskcnt; // 추가 // 대시보드 화면
public Task() {
super();
// TODO Auto-generated constructor stub
}
public int getPno() {
return pno;
}
public void setPno(int pno) {
this.pno = pno;
}
public int getProject_no() {
return project_no;
}
public void setProject_no(int project_no) {
this.project_no = project_no;
}
public int getTask_no() {
return task_no;
}
public void setTask_no(int task_no) {
this.task_no = task_no;
}
public String getTask_content() {
return task_content;
}
public void setTask_content(String task_content) {
this.task_content = task_content;
}
public int getTask_parent_no() {
return task_parent_no;
}
public void setTask_parent_no(int task_parent_no) {
this.task_parent_no = task_parent_no;
}
public String getStartdte() {
return startdte;
}
public void setStartdte(String startdte) {
this.startdte = startdte;
}
public String getEnddte() {
return enddte;
}
public void setEnddte(String enddte) {
this.enddte = enddte;
}
public String getTask_status() {
return task_status;
}
public void setTask_status(String task_status) {
this.task_status = task_status;
}
public String getTask_priority() {
return task_priority;
}
public void setTask_priority(String task_priority) {
this.task_priority = task_priority;
}
public String getTask_name() {
return task_name;
}
public void setTask_name(String task_name) {
this.task_name = task_name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getProject_name() {
return project_name;
}
public void setProject_name(String project_name) {
this.project_name = project_name;
}
public MultipartFile[] getReport() {
return report;
}
public void setReport(MultipartFile[] report) {
this.report = report;
}
public ArrayList<TaskFile> getFileInfo() {
return fileInfo;
}
public void setFileInfo(ArrayList<TaskFile> fileInfo) {
this.fileInfo = fileInfo;
}
public int getTasktotal() {
return tasktotal;
}
public void setTasktotal(int tasktotal) {
this.tasktotal = tasktotal;
}
public int getTaskcnt() {
return taskcnt;
}
public void setTaskcnt(int taskcnt) {
this.taskcnt = taskcnt;
}
}
|
package com.example.ComicToon.Models.ModelRepositories;
import java.util.List;
import com.example.ComicToon.Models.ComicModel;
import com.example.ComicToon.Models.ReportedComicsModel;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface ReportedComicsRepository extends MongoRepository<ReportedComicsModel, String>{
public ReportedComicsModel findByid(String id);
public List<ReportedComicsModel> findByuserID(String userID); //person who's reporting
public List<ReportedComicsModel> findBycomicID(String comicID); //instances of comics reported
public List<ReportedComicsModel> findAll();
}
|
package com.tencent.mm.plugin.wallet_payu.create.ui;
import android.support.v4.view.ViewPager.e;
class WalletPayUOpenIntroView$1 implements e {
final /* synthetic */ WalletPayUOpenIntroView pEJ;
WalletPayUOpenIntroView$1(WalletPayUOpenIntroView walletPayUOpenIntroView) {
this.pEJ = walletPayUOpenIntroView;
}
public final void a(int i, float f, int i2) {
}
public final void O(int i) {
if (WalletPayUOpenIntroView.a(this.pEJ).getParent() != null) {
WalletPayUOpenIntroView.a(this.pEJ).getParent().requestDisallowInterceptTouchEvent(true);
}
WalletPayUOpenIntroView.b(this.pEJ).setPage(i);
}
public final void N(int i) {
}
}
|
import java.util.ArrayList;
import java.util.HashMap;
/**
* Contains a list of all things that are presently true
* in the world.
* @author cdgira
*
*/
public class WorldState
{
HashMap<String,Actor> m_actors = new HashMap<String,Actor>();
ArrayList<Literal> m_bindings = new ArrayList<Literal>();
/**
* Constructs a new empty WorldState.
*/
public WorldState()
{
}
/**
* Constructs a new WorldState by initializing it from a
* list of provided Literals.
*/
public WorldState(ArrayList<Literal> bindings)
{
for (Literal literal : bindings)
{
m_bindings.add(literal);
Actor[] actors = literal.getActors();
for (Actor a : actors)
{
String key = a.getType()+":"+a.getValue();
if (!m_actors.containsKey(key))
m_actors.put(key,a);
}
}
}
/**
* Adds a Literal to the list of present
* bindings for this state of the world.
* @param literal
*/
public void addLiteral(Literal literal)
{
m_bindings.add(literal);
Actor[] actors = literal.getActors();
for (Actor a : actors)
{
String key = a.getKey();
if (!m_actors.containsKey(key))
m_actors.put(key,a);
}
}
/**
* Checks to see if this literal is contained in the WorldState
* @param literal
* @return
*/
public boolean hasLiteral(Literal literal)
{
for (Literal item : m_bindings)
{
if (item.equals(literal))
return true;
}
return false;
}
/**
* How many actors are presently represented in this world.
* @return
*/
public int getNumActors()
{
return m_actors.size();
}
public Actor[] getActors()
{
Actor[] actors = new Actor[m_actors.size()];
int x = 0;
for (Actor a : m_actors.values())
{
actors[x] = a;
x++;
}
return actors;
}
/**
* Removes a Literal from the world and if no other
* literals use those actors, removes them as well.
* @param literal
*/
public void removeLiteral(Literal literal)
{
if (m_bindings.remove(literal))
{
Actor[] actors = literal.getActors();
for (Actor a : actors)
{
boolean remove = true;
for (Literal lit : m_bindings)
{
if (lit.hasActor(a))
{
remove = false;
break;
}
}
if (remove)
m_actors.remove(a.getKey());
}
}
}
/**
*
* @return an array of all the Literals presently in this WorldState.
*/
public Literal[] getBindings()
{
Literal[] literals = new Literal[m_bindings.size()];
int loc = 0;
for (Literal literal : m_bindings)
{
literals[loc] = literal;
loc++;
}
return literals;
}
}
|
package application;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
public class secondWindowController {
@FXML
Button about;
private Main main1;
public void setMain(Main main)
{
this.main1=main;
}
public void about1()
{
main1.mainWindow();
}
}
|
package com.hs.doubaobao.model.department;
import android.content.Context;
import com.hs.doubaobao.base.BaseParams;
import com.hs.doubaobao.bean.DepartmentStatisticsBean;
import com.hs.doubaobao.http.JsonWrap;
import com.hs.doubaobao.http.OKHttpWrap;
import com.hs.doubaobao.http.requestCallBack;
import com.hs.doubaobao.utils.log.Logger;
import java.util.Map;
import okhttp3.Call;
/**
* 作者:zhanghaitao on 2017/9/12 11:03
* 邮箱:820159571@qq.com
*
* @describe:复制粘贴类
*/
public class DSPresener implements DSContract.Presenter {
private static final String TAG = "CopyPresener";
DSContract.View viewRoot;
private Context context;
public DSPresener(DSContract.View viewRoot, Context context) {
this.viewRoot = viewRoot;
this.context = context;
viewRoot.setPresenter(this);
}
@Override
public void getData(Map mapParameter) {
OKHttpWrap.getOKHttpWrap(context)
.requestPost(BaseParams.DEPARTMENT_STATISTICS_URL, mapParameter, new requestCallBack() {
private DepartmentStatisticsBean bean;
@Override
public void onError(Call call, Exception e) {
viewRoot.setError(e.getLocalizedMessage());
}
@Override
public void onResponse(String response) {
Logger.e(TAG, response);
bean = JsonWrap.getObject(response, DepartmentStatisticsBean.class);
//回到不能在子线程中
if (bean != null) {
viewRoot.setData(bean);
} else {
viewRoot.setError("Json解析异常");
}
}
});
}
}
|
package br.com.fiap.trabalho.rm78856;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
public class MainActivity extends AppCompatActivity {
SharedPreferences sp;
Database db;
public void splash(int tempo){
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
Intent it = new Intent(MainActivity.this, LoginActivity.class);
startActivity(it);
finish();
}
}, tempo);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sp = getPreferences(MODE_PRIVATE);
db = new Database(this);
try {
FileInputStream fis = openFileInput("TempoSplashscreen.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String tempoArquivo = br.readLine();
int tempo = Integer.parseInt(tempoArquivo);
splash(tempo * 1000);
fis.close();
} catch (FileNotFoundException e){
int tempo = 10 * 1000;
splash(tempo);
} catch (IOException IOe){
IOe.printStackTrace();
}
}
@Override
protected void onStart() {
super.onStart();
Log log = new Log();
log.setDescricao( "MainActivity" );
log.setData( System.currentTimeMillis() );
db.criarLog(log);
}
}
|
/*
* frmFree.java
*
* Created on 24 Kasım 2007 Cumartesi, 14:48
*/
package askan;
import askan.configuration.*;
import askan.systems.*;
import askan.steelyard.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
/**
*
* @author Kerem
*/
public class frmFree extends javax.swing.JFrame {
private FreeProcess freeProcess;
private TwoWaySerialComm.TRUCK_STATUS truckStatus;
private boolean itemSaved;
/** Creates new form frmFree */
public frmFree() {
initComponents();
}
public frmFree(TwoWaySerialComm.TRUCK_STATUS TruckStatus)
{
ActionMap am;
InputMap im;
KeyStroke ks;
initComponents();
freeProcess = new FreeProcess();
truckStatus = TruckStatus;
Action plateActionListener = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
btnPlateActionPerformed(actionEvent);
}
};
am = btnPlate.getActionMap();
im = btnPlate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
ks = KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0);
im.put(ks, "plate");
am.put("plate", plateActionListener);
Action saveActionListener = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
btnSaveActionPerformed(actionEvent);
}
};
am = btnSave.getActionMap();
im = btnSave.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
ks = KeyStroke.getKeyStroke(KeyEvent.VK_F11, 0);
im.put(ks, "save");
am.put("save", saveActionListener);
Action weighActionListener = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
btnWeighActionPerformed(actionEvent);
}
};
am = btnWeigh.getActionMap();
im = btnWeigh.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
ks = KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0);
im.put(ks, "weigh");
am.put("weigh", weighActionListener);
Action printActionListener = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
btnPrintActionPerformed(actionEvent);
}
};
am = btnPrint.getActionMap();
im = btnPrint.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
ks = KeyStroke.getKeyStroke(KeyEvent.VK_F10, 0);
im.put(ks, "print");
am.put("print", printActionListener);
Action closeActionListener = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
btnCloseActionPerformed(actionEvent);
}
};
am = btnClose.getActionMap();
im = btnClose.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
ks = KeyStroke.getKeyStroke(KeyEvent.VK_F12, 0);
im.put(ks, "close");
am.put("close", closeActionListener);
this.setTitle("Serbest Araç Tartımı");
if (TruckStatus == TwoWaySerialComm.TRUCK_STATUS.EMPTY)
{
txtWeightEmpty.setEditable(Main.config.intParam.manualWeight);
txtVrkmeEmpty.setEditable(Main.config.intParam.manualWeight);
}
else
{
txtWeightFull.setEditable(Main.config.intParam.manualWeight);
txtVrkmeFull.setEditable(Main.config.intParam.manualWeight);
}
setStatus("Lütfen plakayı girin ve SEÇ düğmesine tıklayın");
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
btnSave = new javax.swing.JButton();
btnClose = new javax.swing.JButton();
lblStatus = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
txtPlate = new javax.swing.JTextField();
jPanel1 = new javax.swing.JPanel();
jLabel3 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel12 = new javax.swing.JLabel();
txtWeightEmpty = new javax.swing.JTextField();
txtWeightFull = new javax.swing.JTextField();
txtWeightCalc = new javax.swing.JTextField();
txtVrkmeEmpty = new javax.swing.JTextField();
txtVrkmeFull = new javax.swing.JTextField();
txtVrkmeCalc = new javax.swing.JTextField();
btnWeigh = new javax.swing.JButton();
btnPlate = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
txtCompany = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
txtNote = new javax.swing.JTextField();
btnPrint = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setResizable(false);
btnSave.setIcon(new javax.swing.ImageIcon(getClass().getResource("/askan/binaries/save_16.gif"))); // NOI18N
btnSave.setText("F11 - Kaydet");
btnSave.setEnabled(false);
btnSave.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSaveActionPerformed(evt);
}
});
btnClose.setIcon(new javax.swing.ImageIcon(getClass().getResource("/askan/binaries/delete_16.gif"))); // NOI18N
btnClose.setText("F12 - Kapat");
btnClose.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCloseActionPerformed(evt);
}
});
lblStatus.setText("...");
lblStatus.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14));
jLabel1.setText("Plaka");
txtPlate.setFont(new java.awt.Font("Tahoma", 0, 14));
jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14));
jLabel3.setText("Boş Ağırlık");
jLabel7.setFont(new java.awt.Font("Tahoma", 0, 14));
jLabel7.setText("Dolu Ağırlık");
jLabel12.setFont(new java.awt.Font("Tahoma", 0, 14));
jLabel12.setText("Tartılan Ağırlık");
txtWeightEmpty.setEditable(false);
txtWeightEmpty.setFont(new java.awt.Font("Tahoma", 0, 14));
txtWeightFull.setEditable(false);
txtWeightFull.setFont(new java.awt.Font("Tahoma", 0, 14));
txtWeightCalc.setEditable(false);
txtWeightCalc.setFont(new java.awt.Font("Tahoma", 0, 14));
txtVrkmeEmpty.setEditable(false);
txtVrkmeEmpty.setFont(new java.awt.Font("Tahoma", 0, 14));
txtVrkmeFull.setEditable(false);
txtVrkmeFull.setFont(new java.awt.Font("Tahoma", 0, 14));
txtVrkmeCalc.setEditable(false);
txtVrkmeCalc.setFont(new java.awt.Font("Tahoma", 0, 14));
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(16, 16, 16)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(txtWeightCalc, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtWeightFull, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtWeightEmpty, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 8, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtVrkmeEmpty, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtVrkmeFull, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtVrkmeCalc, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(txtWeightEmpty, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(txtWeightFull, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel12)
.addComponent(txtWeightCalc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(txtVrkmeEmpty, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtVrkmeFull, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtVrkmeCalc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
btnWeigh.setIcon(new javax.swing.ImageIcon(getClass().getResource("/askan/binaries/applications_16.gif"))); // NOI18N
btnWeigh.setText("F5 - Tart");
btnWeigh.setEnabled(false);
btnWeigh.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnWeighActionPerformed(evt);
btnWeighjButton1ActionPerformed(evt);
}
});
btnPlate.setIcon(new javax.swing.ImageIcon(getClass().getResource("/askan/binaries/add_16.gif"))); // NOI18N
btnPlate.setText("F1 - Seç");
btnPlate.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnPlateActionPerformed(evt);
}
});
jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14));
jLabel2.setText("Firma");
txtCompany.setFont(new java.awt.Font("Tahoma", 0, 14));
jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14));
jLabel4.setText("Notlar");
txtNote.setFont(new java.awt.Font("Tahoma", 0, 14));
btnPrint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/askan/binaries/S_B_PRNT.gif"))); // NOI18N
btnPrint.setText("F10");
btnPrint.setEnabled(false);
btnPrint.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnPrintActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGap(19, 19, 19)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(26, 26, 26)
.addComponent(txtPlate, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnWeigh, javax.swing.GroupLayout.DEFAULT_SIZE, 121, Short.MAX_VALUE)
.addComponent(btnPlate, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 121, Short.MAX_VALUE)))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(btnPrint, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(btnSave, javax.swing.GroupLayout.PREFERRED_SIZE, 205, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnClose, javax.swing.GroupLayout.DEFAULT_SIZE, 120, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(10, 10, 10)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGap(98, 98, 98)
.addComponent(txtNote, javax.swing.GroupLayout.DEFAULT_SIZE, 204, Short.MAX_VALUE))
.addComponent(jLabel4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(26, 26, 26)
.addComponent(txtCompany, javax.swing.GroupLayout.DEFAULT_SIZE, 204, Short.MAX_VALUE)))
.addGap(127, 127, 127)))))
.addContainerGap())
.addComponent(lblStatus, javax.swing.GroupLayout.DEFAULT_SIZE, 459, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtPlate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addComponent(btnPlate))
.addGap(6, 6, 6)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(btnWeigh, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(txtCompany, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtNote, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnPrint))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnClose)
.addComponent(btnSave)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(lblStatus))
);
pack();
}// </editor-fold>//GEN-END:initComponents
public void saveEnable(boolean Enable)
{
btnSave.setEnabled(itemSaved ? false : Enable);
btnPrint.setEnabled(Enable);
}
private void transferFormToObject()
{
freeProcess.trmtyp = askan.systems.Util.formatPlate(txtPlate.getText());
freeProcess.notes = txtNote.getText();
freeProcess.company = txtCompany.getText();
if (freeProcess.truckStatus == null) freeProcess.truckStatus = truckStatus;
if (truckStatus == TwoWaySerialComm.TRUCK_STATUS.EMPTY)
{
freeProcess.passedEmpty = true;
freeProcess.dateEmpty = Calendar.getInstance();
}
if (truckStatus == TwoWaySerialComm.TRUCK_STATUS.FULL)
{
freeProcess.passedFull = true;
freeProcess.dateFull = Calendar.getInstance();
}
}
private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
saveEnable(false);
if (!itemSaved) {
try {
transferFormToObject();
if (
(truckStatus == TwoWaySerialComm.TRUCK_STATUS.EMPTY &&
freeProcess.passedEmpty && !freeProcess.passedFull)
||
(truckStatus == TwoWaySerialComm.TRUCK_STATUS.FULL &&
freeProcess.passedFull && !freeProcess.passedEmpty)
)
{
freeProcess.insert(Main.sql);
}
else
{
freeProcess.update();
}
setStatus("Ağırlık kaydedildi");
itemSaved = true;
} catch(Exception ex) {
setStatus("Ağırlık kaydedilirken bir hata oluştu");
Main.appendLog(freeProcess.trmtyp + " aracına ait ağırlık kaydedilirken bir hata oluştu: " + ex.toString());
saveEnable(true);
return;
}
}
saveEnable(true);
}//GEN-LAST:event_btnSaveActionPerformed
private void btnCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCloseActionPerformed
this.dispose();
}//GEN-LAST:event_btnCloseActionPerformed
private void btnWeighActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnWeighActionPerformed
btnWeigh.setEnabled(false);
if (truckStatus == TwoWaySerialComm.TRUCK_STATUS.FULL)
{
if (Main.config.intParam.manualWeight)
{
try
{
freeProcess.fullWeight = new Weight();
freeProcess.fullWeight.setWeight(txtWeightFull.getText(), txtVrkmeFull.getText());
}
catch(Exception ex)
{
Main.appendLog("Ağırlık hatası: " + ex.toString());
setStatus("Lütfen ağırlıkları kontrol edin");
return;
}
}
else
{
Main.steelYard.truckStatus = TwoWaySerialComm.truckStatus.FULL;
freeProcess.fullWeight = Main.steelYard.getLastWeight();
txtWeightFull.setText(freeProcess.fullWeight.toString(false));
txtVrkmeFull.setText(freeProcess.fullWeight.getUOM());
}
if (freeProcess.passedEmpty)
{
freeProcess.calculateCalcWeight();
txtWeightCalc.setText(freeProcess.calcWeight.toString(false));
txtVrkmeCalc.setText(freeProcess.calcWeight.getUOM());
}
}
if (truckStatus == TwoWaySerialComm.TRUCK_STATUS.EMPTY)
{
if (Main.config.intParam.manualWeight)
{
try
{
freeProcess.emptyWeight = new Weight();
freeProcess.emptyWeight.setWeight(txtWeightEmpty.getText(), txtVrkmeEmpty.getText());
}
catch(Exception ex)
{
Main.appendLog("Ağırlık hatası: " + ex.toString());
setStatus("Lütfen ağırlıkları kontrol edin");
return;
}
}
else
{
Main.steelYard.truckStatus = TwoWaySerialComm.truckStatus.EMPTY;
freeProcess.emptyWeight = Main.steelYard.getLastWeight();
txtWeightEmpty.setText(freeProcess.emptyWeight.toString(false));
txtVrkmeEmpty.setText(freeProcess.emptyWeight.getUOM());
}
if (freeProcess.passedFull)
{
freeProcess.calculateCalcWeight();
txtWeightCalc.setText(freeProcess.calcWeight.toString(false));
txtVrkmeCalc.setText(freeProcess.calcWeight.getUOM());
}
}
setStatus("Tartım tamamlandı, kaydedip kapatabilirsiniz");
saveEnable(true);
}//GEN-LAST:event_btnWeighActionPerformed
private void btnWeighjButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnWeighjButton1ActionPerformed
}//GEN-LAST:event_btnWeighjButton1ActionPerformed
public void setStatus(String Status)
{
lblStatus.setText(Status);
}
private boolean connectToSql()
{
try
{
Main.sql.connect();
return true;
}
catch(Exception ex)
{
Main.appendLog("SQL bağlantı hatası: " + ex.toString());
setStatus("SQL bağlantı hatası");
return false;
}
}
private void enableAfterPlateQuery(boolean Enabled)
{
txtPlate.setEditable(Enabled);
btnPlate.setEnabled(Enabled);
}
private void btnPlateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPlateActionPerformed
connectToSql();
// Ekranı kapat
setStatus("Araç sorgulanıyor...");
enableAfterPlateQuery(false);
// Bu araç daha önce girilmiş mi, ilk kez mi giriliyor?
FreeProcess f = FreeProcess.getActiveFreeProcess(askan.systems.Util.formatPlate(txtPlate.getText()));
if (f == null)
{
freeProcess.truckStatus = truckStatus;
}
else
{
if (
(truckStatus == TwoWaySerialComm.TRUCK_STATUS.EMPTY && f.passedEmpty)
||
(truckStatus == TwoWaySerialComm.TRUCK_STATUS.FULL && f.passedFull)
)
{
if (askan.systems.Util.confirmStep(this, "Bu araca ait açık bir tartım gözüküyor! \nEğer devam ederseniz, eski kayıt iptal edilecektir."))
{
try
{
FreeProcess.cancelActiveFreeProcesses(txtPlate.getText());
}
catch(Exception ex)
{
setStatus("İptal sırasında bir hata oluştu");
Main.appendLog(txtPlate.getText() + " plakasına ait eski kayıtlar iptal edilirken bir hata oluştu: " + ex.toString());
return;
}
}
else
{
btnPlate.setEnabled(true);
setStatus("Lütfen plakayı girip sorgulayın");
return;
}
}
freeProcess = f;
}
enableAfterPlateQuery(true);
// Aktarım
if (freeProcess.truckStatus == TwoWaySerialComm.TRUCK_STATUS.EMPTY && freeProcess.passedEmpty)
{
txtWeightEmpty.setText(freeProcess.emptyWeight.toString(false));
txtVrkmeEmpty.setText(freeProcess.emptyWeight.getUOM());
}
if (freeProcess.truckStatus == TwoWaySerialComm.TRUCK_STATUS.FULL && freeProcess.passedFull)
{
txtWeightFull.setText(freeProcess.fullWeight.toString(false));
txtVrkmeFull.setText(freeProcess.fullWeight.getUOM());
}
txtNote.setText(freeProcess.notes == null ? "" : freeProcess.notes);
txtCompany.setText(freeProcess.company == null ? "" : freeProcess.company);
btnWeigh.setEnabled(true);
setStatus("Lütfen aracı tartın");
}//GEN-LAST:event_btnPlateActionPerformed
private void btnPrintActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPrintActionPerformed
if (freeProcess.id == 0)
{
setStatus("Lütfen yazdırmadan önce kaydedin");
return;
}
btnPrint.setEnabled(false);
this.setStatus("Kantar fişi yazdırılıyor, lütfen bekleyin");
if (!itemSaved) transferFormToObject();
freeProcess.print();
setStatus("Kantar fişi yazdırıldı");
btnPrint.setEnabled(true);
}//GEN-LAST:event_btnPrintActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new frmFree().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnClose;
private javax.swing.JButton btnPlate;
private javax.swing.JButton btnPrint;
private javax.swing.JButton btnSave;
private javax.swing.JButton btnWeigh;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel7;
private javax.swing.JPanel jPanel1;
private javax.swing.JLabel lblStatus;
private javax.swing.JTextField txtCompany;
private javax.swing.JTextField txtNote;
private javax.swing.JTextField txtPlate;
private javax.swing.JTextField txtVrkmeCalc;
private javax.swing.JTextField txtVrkmeEmpty;
private javax.swing.JTextField txtVrkmeFull;
private javax.swing.JTextField txtWeightCalc;
private javax.swing.JTextField txtWeightEmpty;
private javax.swing.JTextField txtWeightFull;
// End of variables declaration//GEN-END:variables
}
|
public class ClientMessages {
// Client message flags
public static final short CLIENT_MESSAGE_ADD_POINT = 0;
// We'll need to obtain the number of flags that the client has
// as our server flags should increment off this value. We should not
// mix client message flags with server message flags as this will lead to
// ClassCastExceptions from the message pool
public static final int CLIENT_FLAG_COUNT = CLIENT_MESSAGE_ADD_POINT + 1;
// Create a bew client message to be sent to the server when a client adds
// a point to the screen via touch events
public static class AddPointClientMessage extends ClientMessage{
// Color flags
public static final int COLOR_RED = 0;
public static final int COLOR_GREEN = 1;
public static final int COLOR_BLUE = 2;
// Member variables to be read in from the server and sent to clients
private int mID;
private float mX;
private float mY;
private int mColorId;
// Empty constructor needed for message pool allocation
public AddPointClientMessage(){
// Do nothing...
}
// Constructor
public AddPointClientMessage(final int pID, final float pX, final float pY, final int pColorId){
this.mID = pID;
this.mX = pX;
this.mY = pY;
this.mColorId = pColorId;
}
// A Setter is needed to change values when we obtain a message from the message pool
public void set(final int pID, final float pX, final float pY, final int pColorId){
this.mID = pID;
this.mX = pX;
this.mY = pY;
this.mColorId = pColorId;
}
// Getters
public int getID(){
return this.mID;
}
public float getX(){
return this.mX;
}
public float getY(){
return this.mY;
}
public int getColorId(){
return this.mColorId;
}
// Get the message flag
@Override
public short getFlag() {
return CLIENT_MESSAGE_ADD_POINT;
}
// Apply the read data to the message's member variables
@Override
protected void onReadTransmissionData(DataInputStream pDataInputStream)
throws IOException {
this.mID = pDataInputStream.readInt();
this.mX = pDataInputStream.readFloat();
this.mY = pDataInputStream. readFloat();
this.mColorId = pDataInputStream.readInt();
}
// Write the message's member variables to the output stream
@Override
protected void onWriteTransmissionData(
DataOutputStream pDataOutputStream) throws IOException {
pDataOutputStream.writeInt(this.mID);
pDataOutputStream.writeFloat(this.mX);
pDataOutputStream.writeFloat(this.mY);
pDataOutputStream.writeInt(mColorId);
}
}
}
|
package android.com.provider.apiResponses.getProfileApi;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class PayLoad {
@SerializedName("id")
@Expose
private Integer id;
@SerializedName("serviceprovider_id")
@Expose
private Integer serviceproviderId;
@SerializedName("image")
@Expose
private String image;
@SerializedName("status")
@Expose
private String status;
@SerializedName("created_at")
@Expose
private String createdAt;
@SerializedName("updated_at")
@Expose
private String updatedAt;
@SerializedName("first_name")
@Expose
private String firstName;
@SerializedName("last_name")
@Expose
private String lastName;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getServiceproviderId() {
return serviceproviderId;
}
public void setServiceproviderId(Integer serviceproviderId) {
this.serviceproviderId = serviceproviderId;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
public String getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(String updatedAt) {
this.updatedAt = updatedAt;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
|
package com.example.network;
import com.example.network.thread.MessageTransmit;
import com.example.network.util.DateUtil;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
/**
* Created by ouyangshen on 2017/11/11.
*/
@SuppressLint(value={"HandlerLeak","StaticFieldLeak"})
public class SocketActivity extends AppCompatActivity implements OnClickListener {
private final static String TAG = "SocketActivity";
private EditText et_socket;
private static TextView tv_socket;
private MessageTransmit mTransmit; // 声明一个消息传输对象
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_socket);
et_socket = findViewById(R.id.et_socket);
tv_socket = findViewById(R.id.tv_socket);
findViewById(R.id.btn_socket).setOnClickListener(this);
mTransmit = new MessageTransmit(); // 创建一个消息传输
new Thread(mTransmit).start(); // 启动消息传输线程
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.btn_socket) {
// 获得一个默认的消息对象
Message msg = Message.obtain();
msg.obj = et_socket.getText().toString(); // 消息内容
// 通过消息线程的发送处理器,向后端发送消息
mTransmit.mSendHandler.sendMessage(msg);
}
}
// 创建一个主线程的接收处理器,专门处理服务器发来的消息
public static Handler mHandler = new Handler() {
// 在收到消息时触发
public void handleMessage(Message msg) {
Log.d(TAG, "handleMessage: " + msg.obj);
if (tv_socket != null) {
// 拼接服务器的应答字符串
String desc = String.format("%s 收到服务器的应答消息:%s",
DateUtil.getNowTime(), msg.obj.toString());
tv_socket.setText(desc);
}
}
};
}
|
package com.example.lastminute.Trips;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.widget.PopupMenu;
import androidx.recyclerview.widget.RecyclerView;
import com.example.lastminute.R;
import com.example.lastminute.Trips.TripActivitiesDetails;
import com.firebase.ui.firestore.FirestoreRecyclerAdapter;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.google.firebase.firestore.DocumentSnapshot;
import java.util.ArrayList;
import java.util.Collections;
public class TripActivitiesRecyclerAdapter extends FirestoreRecyclerAdapter<TripActivitiesDetails, TripActivitiesRecyclerAdapter.TripActivitiesViewHolder> {
private TripActivitiesListener tripActivitiesListener;
/**
* Create a new RecyclerView adapter that listens to a Firestore Query. See {@link
* FirestoreRecyclerOptions} for configuration options.
*
* @param options
*/
public TripActivitiesRecyclerAdapter(@NonNull FirestoreRecyclerOptions<TripActivitiesDetails> options
, TripActivitiesListener tripActivitiesListener) {
super(options);
this.tripActivitiesListener = tripActivitiesListener;
}
@Override
protected void onBindViewHolder(@NonNull TripActivitiesViewHolder holder, int position,
@NonNull TripActivitiesDetails model) {
holder.activityName.setText(model.getActivityName());
holder.activityPlace.setText(model.getActivityPlace());
holder.activityDate.setText(model.getActivityDate());
holder.activityTime.setText(model.getActivityTime());
}
@NonNull
@Override
public TripActivitiesViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.activities_view, parent, false);
return new TripActivitiesViewHolder(view);
}
public void deleteItem(int position) {
getSnapshots().getSnapshot(position).getReference().delete();
}
class TripActivitiesViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, PopupMenu.OnMenuItemClickListener {
private TextView activityName, activityPlace, activityDate, activityTime;
private ImageButton moreButton;
public TripActivitiesViewHolder(@NonNull View itemView) {
super(itemView);
setUpUIView(itemView);
EditTripActivities(itemView);
openPopup(itemView);
}
private void setUpUIView(View itemView) {
activityName = (TextView) itemView.findViewById(R.id.activityName);
activityPlace = (TextView) itemView.findViewById(R.id.activityPlace);
activityDate = (TextView) itemView.findViewById(R.id.activityDate);
activityTime = (TextView) itemView.findViewById(R.id.activityTime);
moreButton = (ImageButton) itemView.findViewById(R.id.moreActivityButton);
}
private void EditTripActivities(View itemView) {
itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
DocumentSnapshot snapshot = getSnapshots().getSnapshot(getAdapterPosition());
tripActivitiesListener.handleEditTripActivities(snapshot, v);
return true;
}
});
}
private void openPopup(View itemView) {
moreButton.setOnClickListener(this);
}
@Override
public void onClick(View v) {
showPopup(v);
}
private void showPopup(View v) {
PopupMenu popupMenu = new PopupMenu(itemView.getContext(), v);
popupMenu.inflate(R.menu.activity_more_menu);
popupMenu.setOnMenuItemClickListener(this);
popupMenu.show();
}
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.popup_activity_edit:
DocumentSnapshot snapshotEdit = getSnapshots().getSnapshot(getAdapterPosition());
tripActivitiesListener.handleEditTripActivities(snapshotEdit, itemView);
return true;
case R.id.popup_activity_delete:
deleteItem(getAdapterPosition());
return true;
default:
return false;
}
}
}
public interface TripActivitiesListener {
void handleEditTripActivities(DocumentSnapshot snapshot, View v);
}
}
|
package com.stryksta.swtorcentral.util.database;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;
import com.stryksta.swtorcentral.models.AchievementCategoryItem;
import com.stryksta.swtorcentral.models.AchievementsItem;
public class AchievementsDatabase extends SQLiteAssetHelper {
private static final String DATABASE_NAME = "swtor";
private static final int DATABASE_VERSION = 1;
public AchievementsDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public int getOverallCompleted() {
int achCompleted = 0;
SQLiteDatabase db = getReadableDatabase();
@SuppressWarnings("StringBufferReplaceableByString") StringBuilder builder = new StringBuilder();
String sqlSelect = builder
.append("SELECT ")
.append("SUM(CASE WHEN ca.achievements_id is not null then achRewardPoints end) AS achCompleted ")
.append("FROM achievements ")
.append("LEFT JOIN categories ")
.append("ON achievements.achCategory = categories.achCategory ")
.append("LEFT JOIN completed_achievements ca ")
.append("ON ca.achievements_id = achievements._id ")
.append("WHERE achievements.achCategory IS NOT null ")
.toString();
Cursor c = db.rawQuery(sqlSelect, null);
if (c.moveToFirst()) {
do {
achCompleted = c.getInt(c.getColumnIndex("achCompleted"));
} while (c.moveToNext());
}
c.close();
db.close();
return achCompleted;
}
public int geOverallTotal() {
int achTotal = 0;
SQLiteDatabase db = getReadableDatabase();
@SuppressWarnings("StringBufferReplaceableByString") StringBuilder builder = new StringBuilder();
String sqlSelect = builder
.append("SELECT ")
.append("SUM(achRewardPoints) achTotal ")
.append("FROM achievements ")
.append("LEFT JOIN categories ")
.append("ON achievements.achCategory = categories.achCategory ")
.append("LEFT JOIN completed_achievements ca ")
.append("ON ca.achievements_id = achievements._id ")
.append("WHERE achievements.achCategory IS NOT null ")
.toString();
Cursor c = db.rawQuery(sqlSelect, null);
if (c.moveToFirst()) {
do {
achTotal = c.getInt(c.getColumnIndex("achTotal"));
} while (c.moveToNext());
}
c.close();
db.close();
return achTotal;
}
public HashMap<Integer, Integer> getCompletedandTotal(String achCategory1, String achCategory2, String achCategory3) {
HashMap<Integer,Integer> achCompletedandTotal = new HashMap<>();
SQLiteDatabase db = getReadableDatabase();
@SuppressWarnings("StringBufferReplaceableByString") StringBuilder builder = new StringBuilder();
String sqlSelect = builder
.append("SELECT achievements.achTertiaryCategory as achCategory4, ")
.append("SUM(CASE WHEN ca.achievements_id is not null then achRewardPoints end) AS achCompleted, ")
.append("SUM(achRewardPoints) achTotal ")
.append("FROM achievements ")
.append("LEFT JOIN categories ")
.append("ON achievements.achCategory = categories.achCategory ")
.append("LEFT JOIN completed_achievements ca ")
.append("ON ca.achievements_id = achievements._id ")
.append("WHERE achievements.achCategory = ? AND achievements.achSubCategory = ? AND achievements.achTertiaryCategory = ? ")
.append("GROUP BY achievements.achTertiaryCategory ")
.append("ORDER BY achCategory4 ASC ")
.toString();
Cursor c = db.rawQuery(sqlSelect, new String[]{String.valueOf(achCategory1), String.valueOf(achCategory2), String.valueOf(achCategory3)});
if (c.moveToFirst()) {
do {
int achCompleted = c.getInt(c.getColumnIndex("achCompleted"));
int achTotal = c.getInt(c.getColumnIndex("achTotal"));
achCompletedandTotal.put(achCompleted, achTotal);
} while (c.moveToNext());
}
c.close();
db.close();
return achCompletedandTotal;
}
public ArrayList<AchievementCategoryItem> getCategory1() {
ArrayList<AchievementCategoryItem> categoryItem = new ArrayList<AchievementCategoryItem>();
SQLiteDatabase db = getReadableDatabase();
@SuppressWarnings("StringBufferReplaceableByString") StringBuilder builder = new StringBuilder();
String sqlSelect = builder
.append("SELECT achievements.achCategory as achCategory1,categories.achievementOrderPosition, ")
.append("SUM(CASE WHEN ca.achievements_id is not null then achRewardPoints end) AS achCompleted, ")
.append("SUM(achRewardPoints) achTotal ")
.append("FROM achievements ")
.append("LEFT JOIN categories ")
.append("ON achievements.achCategory = categories.achCategory ")
.append("LEFT JOIN completed_achievements ca ")
.append("ON ca.achievements_id = achievements._id ")
.append("WHERE achievements.achCategory IS NOT null ")
.append("GROUP BY achievements.achCategory ")
.append("ORDER BY cast(categories.achievementOrderPosition as unsigned) ASC, achCategory1 DESC ")
.toString();
Cursor c = db.rawQuery(sqlSelect, null);
if (c.moveToFirst()) {
do {
String category = c.getString(c.getColumnIndex("achCategory1"));
int completed = c.getInt(c.getColumnIndex("achCompleted"));
int total = c.getInt(c.getColumnIndex("achTotal"));
categoryItem.add(new AchievementCategoryItem(category, completed, total));
} while (c.moveToNext());
}
c.close();
db.close();
return categoryItem;
}
public ArrayList<AchievementCategoryItem> getCategory2(String Category1) {
ArrayList<AchievementCategoryItem> categoryItem = new ArrayList<AchievementCategoryItem>();
SQLiteDatabase db = getReadableDatabase();
@SuppressWarnings("StringBufferReplaceableByString") StringBuilder builder = new StringBuilder();
String sqlSelect = builder
.append("SELECT achievements.achSubCategory as achCategory2, ")
.append("SUM(CASE WHEN ca.achievements_id is not null then achRewardPoints end) AS achCompleted, ")
.append("SUM(achRewardPoints) achTotal ")
.append("FROM achievements ")
.append("LEFT JOIN categories ")
.append("ON achievements.achCategory = categories.achCategory ")
.append("LEFT JOIN completed_achievements ca ")
.append("ON ca.achievements_id = achievements._id ")
.append("WHERE achievements.achCategory = ? ")
.append("GROUP BY achievements.achSubCategory ")
.append("ORDER BY achCategory2 ASC ")
.toString();
Cursor c = db.rawQuery(sqlSelect, new String[]{String.valueOf(Category1)});
if (c.moveToFirst()) {
do {
String category = c.getString(c.getColumnIndex("achCategory2"));
int completed = c.getInt(c.getColumnIndex("achCompleted"));
int total = c.getInt(c.getColumnIndex("achTotal"));
categoryItem.add(new AchievementCategoryItem(category, completed, total));
} while (c.moveToNext());
}
c.close();
db.close();
return categoryItem;
}
public ArrayList<AchievementCategoryItem> getCategory3(String Category1, String Category2) {
ArrayList<AchievementCategoryItem> categoryItem = new ArrayList<AchievementCategoryItem>();
SQLiteDatabase db = getReadableDatabase();
@SuppressWarnings("StringBufferReplaceableByString") StringBuilder builder = new StringBuilder();
String sqlSelect = builder
.append("SELECT achievements.achTertiaryCategory as achCategory3, ")
.append("SUM(CASE WHEN ca.achievements_id is not null then achRewardPoints end) AS achCompleted, ")
.append("SUM(achRewardPoints) achTotal ")
.append("FROM achievements ")
.append("LEFT JOIN categories ")
.append("ON achievements.achCategory = categories.achCategory ")
.append("LEFT JOIN completed_achievements ca ")
.append("ON ca.achievements_id = achievements._id ")
.append("WHERE achievements.achCategory = ? AND achievements.achSubCategory = ? ")
.append("GROUP BY achievements.achTertiaryCategory ")
.append("ORDER BY achCategory3 ASC ")
.toString();
Cursor c = db.rawQuery(sqlSelect, new String[]{String.valueOf(Category1), String.valueOf(Category2)});
if (c.moveToFirst()) {
do {
String category = c.getString(c.getColumnIndex("achCategory3"));
int completed = c.getInt(c.getColumnIndex("achCompleted"));
int total = c.getInt(c.getColumnIndex("achTotal"));
categoryItem.add(new AchievementCategoryItem(category, completed, total));
} while (c.moveToNext());
}
c.close();
db.close();
return categoryItem;
}
public ArrayList<AchievementsItem> getAchievements(String Category1, String Category2, String Category3) {
ArrayList<AchievementsItem> achievementItem = new ArrayList<AchievementsItem>();
SQLiteDatabase db = getReadableDatabase();
@SuppressWarnings("StringBufferReplaceableByString") StringBuilder builder = new StringBuilder();
String sqlSelect = builder
.append("SELECT achievements._id, achievements.achCategory, achievements.achSubCategory, achievements.achTertiaryCategory, achievements.achTitle, achievements.achDescription, achievements.achRewardPoints, achievements.achRewardTitle, achievements.achRewardFleetRequisition, achievements.achVisibility, ")
.append("CASE WHEN (a._id is not null) ")
.append("THEN \'1\' ")
.append("ELSE \'0\' ")
.append("END AS achCompleted ")
.append("FROM achievements ")
.append("LEFT JOIN completed_achievements a ")
.append("ON achievements._id = a.achievements_id ")
.append("WHERE achCategory = ? AND achSubCategory = ? and achTertiaryCategory = ?")
.toString();
Cursor c = db.rawQuery(sqlSelect, new String[]{String.valueOf(Category1), String.valueOf(Category2), String.valueOf(Category3)});
if (c.moveToFirst()) {
do {
int achID = c.getInt(c.getColumnIndex("_id"));
String achCategory1 = c.getString(c.getColumnIndex("achCategory"));
String achCategory2 = c.getString(c.getColumnIndex("achSubCategory"));
String achCategory3 = c.getString(c.getColumnIndex("achTertiaryCategory"));
String achTitle = c.getString(c.getColumnIndex("achTitle"));
String achDescription = c.getString(c.getColumnIndex("achDescription"));
int achRewardPoints = c.getInt(c.getColumnIndex("achRewardPoints"));
String achRewardTitle = c.getString(c.getColumnIndex("achRewardTitle"));
Integer achRewardFleetRequisition = c.getInt(c.getColumnIndex("achRewardFleetRequisition"));
String achVisibility = c.getString(c.getColumnIndex("achVisibility"));
int achCompleted = c.getInt(c.getColumnIndex("achCompleted"));
achievementItem.add(new AchievementsItem(achID, achCategory1, achCategory2, achCategory3, achTitle, achDescription, achRewardPoints, achRewardTitle, achRewardFleetRequisition, achVisibility, achCompleted));
} while (c.moveToNext());
}
c.close();
db.close();
return achievementItem;
}
public void setCompleted (int achievementID) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("achievements_id", achievementID);
try {
db.insert("completed_achievements", "achievements_id", values);
//Toast.makeText(getApplicationContext(), "Character ID: " + characterID + " Achievement ID: " + achievementAdapter.getItem(position).getAchievementID(), Toast.LENGTH_SHORT).show();
Log.d("SWTORCentral", "Added Successfully");
} catch (SQLException ex) {
}
db.close();
}
public void removeCompleted (int achievementID) {
SQLiteDatabase db = this.getWritableDatabase();
String sqlSelect = "achievements_id = ?";
try {
db.delete("completed_achievements", sqlSelect , new String[]{String.valueOf(achievementID)});
Log.d("SWTORCentral", "Removed Successfully");
} catch (SQLException ex) {
}
db.close();
}
}
|
package pl.finsys.matrixVars;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.MatrixVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping(value = "/matrixvars")
public class MatrixVariableController {
private static final Logger logger = LoggerFactory.getLogger(MatrixVariableController.class);
public static final String VIEW_STOCKS = "stocks";
/**
* respond to GET http://localhost:8080/matrixvars/, with url like this:
*
* http://localhost:8080/matrixvars/BT.A=276.70,+10.40,+3.91;AZN=236.00,+103.00,+3.29;SBRY=375.50,+7.60,+2.07
*/
@RequestMapping(value = "/{stocks}", method = RequestMethod.GET)
public String showPortfolioValues(@MatrixVariable Map<String, List<String>> stocks, Model model) {
logger.info("Storing {} Values which are: {}", new Object[] { stocks.size(), stocks });
List<List<String>> outlist = map2List(stocks);
model.addAttribute("stocks", outlist);
return VIEW_STOCKS;
}
private List<List<String>> map2List(Map<String, List<String>> stocksMap) {
List<List<String>> outlist = new ArrayList<>();
Collection<Entry<String, List<String>>> stocksSet = stocksMap.entrySet();
for (Entry<String, List<String>> entry : stocksSet) {
List<String> rowList = new ArrayList<>();
String name = entry.getKey();
rowList.add(name);
List<String> stock = entry.getValue();
rowList.addAll(stock);
outlist.add(rowList);
}
return outlist;
}
/**
* respond to GET http://localhost:8080/matrixvars/stocks, with url like this:
*
* http://localhost:8080/matrixvars/stocks;BT.A=276.70,,+3.91;AZN=236.00,+103.00;SBRY=375.50/account;name=roger;number=105;location=stoke-on-trent
*/
@RequestMapping(value = "/{stocks}/{account}", method = RequestMethod.GET)
public String showPortfolioValuesWithAccountInfo(@MatrixVariable(pathVar = "stocks") Map<String, List<String>> stocks,
@MatrixVariable(pathVar = "account") Map<String, List<String>> accounts, Model model) {
List<List<String>> stocksView = map2List(stocks);
model.addAttribute("stocks", stocksView);
List<List<String>> accountDetails = map2List(accounts);
model.addAttribute("accountDetails", accountDetails);
return VIEW_STOCKS;
}
}
|
/*
* 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 contextoProblema;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;
/**
* Clase fabrica donde se crean pedidos de poleras con sus caracteristicas
*
* @author Sebastián Sanchez
*/
public class Fabrica {
ArrayList<String> pedido = new ArrayList<>();
ArrayList<String> tipo = new ArrayList<>();
ArrayList<String> talla = new ArrayList<>();
/**
* Método que guarda el pedido en el ArrayList pedido
*
* @param tipo Un string con el tipo de material de la polera
* @param talla Un string con la talla de la polera
* @param estampado Un string estampado o sinEstampado de la polera
* @return ArrayList con el pedido guardado
*/
public ArrayList<String> agregarPedido(String tipo, String talla, String estampado) {
this.pedido.add(tipo + "," + talla + "," + estampado);
return pedido;
}
/**
* Método que pide seleccionar el tipo de material de la polera
*
* @return el tipo de material elegido por el usuario
*/
public String pedirTipo() {
System.out.println("Ingrese el tipo de su polera\n1.algodón\n2.polyester\n3.spandex");
this.tipo.add("algodón");
this.tipo.add("polyester");
this.tipo.add("spandex");
return tipo.get(leerTeclado() - 1);
}
/**
* Método que pide seleccionar la talla de la polera
*
* @return la talla elegida por el usario
*/
public String pedirTalla() {
System.out.println("Ingrese la talla de su polera\n1.S\n2.M\n3.L\n4.XL");
this.talla.add("S");
this.talla.add("M");
this.talla.add("L");
this.talla.add("XL");
return talla.get(leerTeclado() - 1);
}
/**
* Método que pide la opcion para guardar su pedido de polera con o sin
* estampado
*
* @return la opcion elegida por el usuario como cadena de texto
*/
public String pedirEstampado() {
System.out.println("Ingrese 0 si desea su polera con estampado o un 1 si desea su polera sin estampado");
String estampado = "";
if (leerTeclado() == 0) {
estampado = "estampado";
} else if (leerTeclado() == 1) {
estampado = "sinEstampado";
}
return estampado;
}
/**
* Método que muestra el contenido del ArrayList
*
* @param pedido el ArrayList que se desea mostrar
*/
public static void mostrarPedidos(ArrayList<String> pedido) {
for (int i = 0; i < pedido.size(); i++) {
System.out.println((i + 1) + ".- " + pedido.get(i));
}
}
/**
* Método para borrar un pedido
*
* @param indice la posicion donde se encuentra el pediodo a borrar
*/
public void borrarPedidos(int indice) {
this.pedido.remove(indice);
}
/**
* Método que lee la entrada por teclado del usuario
*
* @return numero ingresado
*/
public int leerTeclado() {
Scanner teclado = new Scanner(System.in);
int numero;
try {
numero = teclado.nextInt();
if (numero < 0) {
leerTeclado();
}
} catch (InputMismatchException e) {
System.out.println("Dato ingresado incorrecto, intentar nuevamente");
numero = leerTeclado();
}
return numero;
}
/**
* Método que despliega el menu de la fabrica de poleras
*/
public void menu() {
boolean bandera = true;
System.out.println("Bienvenido a la fábrica textil Raptor");
while (bandera) {
System.out.println("\n1.Agregar pedido\n2.Eliminar pedido\n3.Mostrar pedidos\n4.Salir");
int opcion = leerTeclado();
switch (opcion) {
case 1:
agregarPedido(pedirTipo(), pedirTalla(), pedirEstampado());
System.out.println("Pedido agregado");
break;
case 2:
mostrarPedidos(pedido);
System.out.println("Ingrese el numero de pedido que desea eliminar");
borrarPedidos(leerTeclado() - 1);
System.out.println("Pedido eliminado");
break;
case 3:
System.out.println("----------------------");
mostrarPedidos(pedido);
break;
case 4:
bandera = false;
break;
}
}
}
}
|
package com.axicik;
import java.sql.SQLException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
/**
* REST Web Service
*
* @author Ioulios Tsiko: cs131027
* @author Theofilos Axiotis: cs131011
*/
@Path("getInfo")
public class GetStudentInfoResource {
@Context
private UriInfo context; // Δημιουργείτε μόνο του απο το Net-beans, όταν δημιουργείτε η κλάση και δεν το χρησιμοποιούμε κάπου.
private final int serviceNum=3; // Σταθερά - Μοναδικός Κωδικός του κάθε web service.
private final int serviceNum2=6; // Σταθερά - Μοναδικός Κωδικός του κάθε web service.
/**
* Creates a new instance of GetStudentInfoResource
*/
public GetStudentInfoResource() {
}
/**
* Επιστρέφει τα στοιχεία(προσωπικά και βαθμούς) ενός φοιτητη. Ο χρήστης πρέπει να
* έχει τα απαραίτητα δικαιώματα και να έχει κάνει login.
*
* @param username Όνομα Χρήστη
* @param key Κλείδι Χρηστη
* @param info Αριθμό μητρώου φοιτητή προς αναζήτηση στοιχείων ή null;
* @return ένα String που περιέχει τα στοιχεία σε μορφη json array. Σε περίπτωση σφάλματος ένα μήνυμα που αναφέρει τι πήγε στραβά.
* Μορφή json :
* { "PersonalInfo":
* { "name": Ονομα χρήστη,
* "last_name": Επίθετο χρήστη,
* "phone": αριθμός τηλεφόνου,
* "username": Όνομα Χρήστη,
* "registrationNumber": Αριθμό μητρόου,
* "email": email,
* "role": κωδικός ρόλου
* },
* "lessons":
* [{ "name": Ονομα μαθήματος,
* "lessid": κωδικός μαθήματος,
* "grade": βαθμός},
* ... ,
* { "name": Ονομα μαθήματος,
* "lessid": κωδικός μαθήματος,
* "grade": βαθμός}
* ]
* }
* @throws ClassNotFoundException
* @throws SQLException
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
@Consumes("text/plain")
public String getUserInfo(@QueryParam ("usr") String username,@QueryParam("key") String key,@QueryParam ("info") String info) throws SQLException, ClassNotFoundException {
DBManager dbm=DBManager.getInstance(); // Πέρνει το μοναδικό αντικείμενο τηs κλάσης DBManager.
User u=dbm.checkKey(username,key); //Ελέγχει αν υπάρχει χρήστης και επιστρέφει ένα αντικείμενο User στοιχεία του χρήστη .
if(u.getUsrExist()) // Αν ο χρήστης υπάρχει τότε επιστρέφει true αλλιώς false.
if(u.hasService(serviceNum)) // Αν ο χρήστης έχει δικαίωμα να καλεί το συγκεκριμένο web service τότε επιστρέφει true αλλιώς false.
return dbm.getStudInfo(info); //Επιστρέφει τα στοιχεία του φοιτητη "info".
else if (u.hasService(serviceNum2)) // Αν ο χρήστης έχει δικαίωμα να καλεί το συγκεκριμένο web service τότε επιστρέφει true αλλιώς false.
return dbm.getStudInfo(username); //Επιστρέφει τα στοιχεία του χρήστη που καλεί το Web Service.
else
return "An error has occured: Permission Denied";
else
return "403";
}
}
|
package com.example.aashna.mynotes;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class MainActivity extends AppCompatActivity {
Button loginSign;
private FirebaseAuth mAuth;
EditText email, password;//emailTxt, passwordTxt
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
loginSign=findViewById(R.id.loginSignupBtn);
email=findViewById(R.id.emailTxt);
password=findViewById(R.id.passwordTxt);
loginSign.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(MainActivity.this,Main2Activity.class);
startActivity(intent);
}
});
}
@Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
// updateUI(currentUser);
}
public void saveDetailsBtn(View view) {
if(TextUtils.isEmpty(email.getText().toString()) && TextUtils.isEmpty(password.getText().toString())){
Toast.makeText(MainActivity.this, "email and password cannot be empty", Toast.LENGTH_SHORT).show();
}
else{
//create and delete file here...
Toast.makeText(MainActivity.this, "your credentials are successfully saved...", Toast.LENGTH_SHORT).show();
startActivity(new Intent(MainActivity.this,Main2Activity.class));// starting next activity
}
}
public void loginBtn(View view) {
String mailID=email.getText().toString().trim();
String passwrd=password.getText().toString().trim();
mAuth.createUserWithEmailAndPassword(mailID,passwrd).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
}
});
}
}
|
/*******************************************************************************
* =============LICENSE_START=========================================================
*
* =================================================================================
* Copyright (c) 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END=========================================================
*
*******************************************************************************/
package org.onap.ccsdk.dashboard.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
/**
* Publishes a list of constants and methods to access the properties that are
* read by Spring from the specified configuration file(s).
*
* Should be used like this (and never in a constructor):
*
* <pre>
* @Autowired
* DashboardProperties properties;
* </pre>
*/
@Configuration
@PropertySource(value = {"${container.classpath:}/WEB-INF/conf/dashboard.properties"})
public class DashboardProperties {
/**
* Key for property with list of sites.
*/
public static final String CONTROLLER_SITE_LIST = "controller.site.list";
/**
* Subkey for property with site name.
*/
public static final String SITE_SUBKEY_NAME = "name";
/**
* Subkey for property with Cloudify URL.
*/
public static final String SITE_SUBKEY_CLOUDIFY_URL = "cloudify.url";
/**
* Subkey for property with Inventory URL.
*/
public static final String SITE_SUBKEY_INVENTORY_URL = "inventory.url";
/**
* Subkey for property with Deployment Handler URL.
*/
public static final String SITE_SUBKEY_DHANDLER_URL = "dhandler.url";
/**
* Subkey for property with Consul URL.
*/
public static final String SITE_SUBKEY_CONSUL_URL = "consul.url";
/**
* Subkey for property with DBCL URL.
*/
public static final String SITE_SUBKEY_DBCL_URL = "dbcl.url";
/**
* Subkey for property with Feed Mgmt URL.
*/
public static final String SITE_SUBKEY_FEED_URL = "feed_m.url";
/**
* Subkey for property with Controller user name for authentication.
*/
public static final String SITE_SUBKEY_CLOUDIFY_USERNAME = "cloudify.username";
/**
* Subkey for property with Controller password.
*/
public static final String SITE_SUBKEY_CLOUDIFY_PASS = "cloudify.password";
/**
* Subkey for property with Controller password encryption status.
*/
public static final String SITE_SUBKEY_CLOUDIFY_ENCRYPTED = "is_encrypted";
/**
* Key for dashboard deployment environment.
*/
public static final String CONTROLLER_IN_ENV = "controller.env";
/**
* Key for K8s deploy permission string.
*
*/
public static final String APP_K8S_PERM = "k8s.deploy.perm";
private static Environment environment;
protected Environment getEnvironment() {
return environment;
}
/**
* @param environment Environment
*/
@Autowired
public void setEnvironment(final Environment environment) {
this.environment = environment;
}
/**
* @param key Property key
* @return True or false
*/
public static boolean containsProperty(final String key) {
return environment.containsProperty(key);
}
/**
* @param key Property key
* @return String value; throws unchecked exception if key is not found
*/
public static String getProperty(final String key) {
return environment.getRequiredProperty(key);
}
/**
* @param key Property key
* @return String value; throws unchecked exception if key is not found
*/
public static String getPropertyDef(final String key, String defVal) {
return environment.getProperty(key, defVal);
}
/**
* @param key Property key
* @return True or False; null if key is not found
*/
public static Boolean getBooleanProperty(final String key) {
final String value = getProperty(key);
return Boolean.parseBoolean(value);
}
/**
* Gets the values for a comma-separated list property value as a String array.
*
* @param key Property key
* @return Array of values with leading and trailing whitespace removed; null if
* key is not found.
*/
public static String[] getCsvListProperty(final String key) {
String listVal = getProperty(key);
if (listVal == null)
return null;
String[] vals = listVal.split("\\s*,\\s*");
return vals;
}
/**
* Convenience method to get a property from the fake hierarchical key-value.
* set.
*
* @param controllerKey First part of key
* @param propKey Second part of key
* @return Property value for key "controllerKey.propKey"
*/
public static String getControllerProperty(final String controllerKey, final String propKey) {
final String key = controllerKey + '.' + propKey;
return getProperty(key);
}
/**
* Convenience method to get a property from the fake hierarchical key-value
* set.
*
* @param controllerKey First part of key
* @param propKey Second part of key
* @return Property value for key "controllerKey.propKey"
*/
public static String getControllerPropertyDef(final String controllerKey, final String propKey,
String defVal) {
final String key = controllerKey + '.' + propKey;
return getPropertyDef(key, defVal);
}
}
|
package com.iwars.mine.Model;
public class ModelListUmum {
String tanggal, ket_status, nama, no_antrian;
public ModelListUmum(){}
public ModelListUmum(String no_antrian, String nama, String ket_status, String tanggal) {
this.tanggal= tanggal;
this.no_antrian = no_antrian;
this.nama = nama;
this.ket_status = ket_status;
}
public String getTanggal() {
return tanggal;
}
public void setTanggal(String tanggal) {
this.tanggal = tanggal;
}
public String getKet_status(){
return ket_status;
}
public void setKet_status(String ket_status){
this.ket_status = ket_status;
}
public String getNama() {
return nama;
}
public void setNama(String nama) {
this.nama = nama;
}
public String getNo_antrian() {
return no_antrian;
}
public void setNo_antrian(String no_antrian) {
this.no_antrian = no_antrian;
}
}
|
/*
* 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 Dao;
import Entidades.entUsuario;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author rosemary
*/
public class UsuarioDAO {
public static List<entUsuario> Listar(boolean activo) throws Exception
{
List<entUsuario> lista = null;
Connection conn =null;
CallableStatement stmt = null;
ResultSet dr = null;
try {
String sql="select id_usuario,login,contrasena,codigo_erp,nombre,apellido,email,telefono,celular,fecha_nacimiento,"
+ " foto,estado,usuario_responsable,fecha_modificacion,es_administrador "
+ " from usuario where es_administrador=0 ";
if(activo)
sql+=" and estado=1 ";
conn = ConexionDAO.getConnection();
stmt = conn.prepareCall(sql);
dr = stmt.executeQuery();
while(dr.next())
{
if(lista==null)
lista= new ArrayList<entUsuario>();
entUsuario entidad = new entUsuario();
entidad.setId_usuario(dr.getInt(1));
entidad.setLogin(dr.getString(2));
entidad.setContrasena(dr.getString(3));
entidad.setCodigo_erp(dr.getString(4));
entidad.setNombre(dr.getString(5));
entidad.setApellido(dr.getString(6));
entidad.setEmail(dr.getString(7));
entidad.setTelefono(dr.getString(8));
entidad.setCelular(dr.getString(9));
entidad.setFecha_nacimiento(dr.getDate(10));
entidad.setFoto(dr.getBytes(11));
entidad.setEstado(dr.getBoolean(12));
entidad.setUsuario_responsable(dr.getString(13));
entidad.setFecha_modificacion(dr.getTimestamp(14));
entidad.setEs_administrador(dr.getBoolean(15));
lista.add(entidad);
}
} catch (Exception e) {
throw new Exception("Listar "+e.getMessage(), e);
}
finally{
try {
dr.close();
stmt.close();
conn.close();
} catch (SQLException e) {
}
}
return lista;
}
public static byte[] getFoto(int IdUsuario) throws Exception
{
byte[] foto = null;
Connection conn =null;
CallableStatement stmt = null;
ResultSet dr = null;
try {
String sql="select foto from usuario where id_usuario="+IdUsuario;
conn = ConexionDAO.getConnection();
stmt = conn.prepareCall(sql);
dr = stmt.executeQuery();
if(dr.next())
{
foto=dr.getBytes(1);
}
} catch (Exception e) {
throw new Exception("Listar "+e.getMessage(), e);
}
finally{
try {
dr.close();
stmt.close();
conn.close();
} catch (SQLException e) {
}
}
return foto;
}
public static int insertar(entUsuario entidad) throws Exception
{
int rpta = 0;
Connection conn =null;
PreparedStatement stmt = null;
try {
String sql="INSERT INTO usuario(login,contrasena,codigo_erp,nombre,apellido,email,telefono,celular,fecha_nacimiento,"
+ " foto,estado,usuario_responsable,fecha_modificacion,es_administrador)"
+ " VALUES(?,?,?,?,?,?,?,?,?,?,?,?,GETDATE(),0);";
conn = ConexionDAO.getConnection();
stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
stmt.setString(1, entidad.getLogin());
stmt.setString(2, entidad.getContrasena());
stmt.setString(3, entidad.getCodigo_erp());
stmt.setString(4, entidad.getNombre());
stmt.setString(5, entidad.getApellido());
stmt.setString(6, entidad.getEmail());
stmt.setString(7, entidad.getTelefono());
stmt.setString(8, entidad.getCelular());
stmt.setDate(9, new java.sql.Date(entidad.getFecha_nacimiento().getTime()));
stmt.setBytes(10, entidad.getFoto());
stmt.setBoolean(11, entidad.getEstado());
stmt.setString(12, entidad.getUsuario_responsable());
stmt.executeUpdate();
ResultSet rs = stmt.getGeneratedKeys();
if (rs.next()){
rpta=rs.getInt(1);
}
rs.close();
} catch (Exception e) {
throw new Exception("Insertar"+e.getMessage(), e);
}
finally{
try {
stmt.close();
conn.close();
} catch (SQLException e) {
}
}
return rpta;
}
public static boolean actualizar(entUsuario entidad) throws Exception
{
boolean rpta = false;
Connection conn =null;
CallableStatement stmt = null;
try {
String sql="UPDATE usuario SET login = ?,"
+ "codigo_erp= ?,nombre=?,apellido=?,email=?,telefono=?,celular=?,fecha_nacimiento=?,"
+ " estado= ?,"
+ " usuario_responsable = ?,fecha_modificacion = GETDATE() WHERE id_usuario = ?;";
conn = ConexionDAO.getConnection();
conn.setAutoCommit(false);
stmt = conn.prepareCall(sql);
stmt.setString(1, entidad.getLogin());
stmt.setString(2, entidad.getCodigo_erp());
stmt.setString(3, entidad.getNombre());
stmt.setString(4, entidad.getApellido());
stmt.setString(5, entidad.getEmail());
stmt.setString(6, entidad.getTelefono());
stmt.setString(7, entidad.getCelular());
stmt.setTimestamp(8, new Timestamp(entidad.getFecha_nacimiento().getTime()));
stmt.setBoolean(9, entidad.getEstado());
stmt.setString(10, entidad.getUsuario_responsable());
stmt.setInt(11,entidad.getId_usuario());
rpta = stmt.executeUpdate() == 1;
if(entidad.getFoto()!=null)
{
sql="UPDATE usuario SET foto=? WHERE id_usuario = ?;";
CallableStatement stmtFoto = conn.prepareCall(sql);
stmtFoto.setBytes(1, entidad.getFoto());
stmtFoto.setInt(2,entidad.getId_usuario());
stmtFoto.executeUpdate();
}
conn.commit();
} catch (Exception e) {
if (conn != null) {
conn.rollback();
}
throw new Exception("Insertar"+e.getMessage(), e);
}
finally{
try {
stmt.close();
conn.close();
} catch (SQLException e) {
}
}
return rpta;
}
public static boolean contrasena(int IdUsuario,String contrasena) throws Exception
{
boolean rpta = false;
Connection conn =null;
CallableStatement stmt = null;
try {
String sql="UPDATE usuario SET contrasena = ? WHERE id_usuario = ?;";
conn = ConexionDAO.getConnection();
stmt = conn.prepareCall(sql);
stmt.setString(1, contrasena);
stmt.setInt(2,IdUsuario);
rpta = stmt.executeUpdate() == 1;
} catch (Exception e) {
throw new Exception("Error Actualizar "+e.getMessage(), e);
}
finally{
try {
stmt.close();
conn.close();
} catch (SQLException e) {
}
}
return rpta;
}
public static boolean restablecer(int Id,String Contrasena) throws Exception
{
boolean rpta = false;
Connection conn =null;
CallableStatement stmt = null;
try {
String sql="UPDATE usuario SET contrasena = ?,fecha_modificacion = GETDATE() WHERE id_usuario = ?;";
conn = ConexionDAO.getConnection();
stmt = conn.prepareCall(sql);
stmt.setString(1, Contrasena);
stmt.setInt(2,Id);
rpta = stmt.executeUpdate() == 1;
} catch (Exception e) {
throw new Exception("Error Actualizar "+e.getMessage(), e);
}
finally{
try {
stmt.close();
conn.close();
} catch (SQLException e) {
}
}
return rpta;
}
}
|
package components;
import components.goat.Goat;
import org.javatuples.Pair;
import org.lwjgl.opengl.GL11;
import physics.Collider;
import physics.Rigidbody;
import utils.Util;
import window.GameWindow;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
public final class CannonBall extends Rigidbody implements Component, Collider {
private final float ejectForce = 1100.0f;
private final float gravityForce = -20.0f;
private final float[] cannonBallColor = Util.OpenGLRGB(51, 51, 0, 0);
public static final float radius = 0.2f / 8;
private boolean ejectFlag = false;
private final float ejectAngle;
public CannonBall(float initX, float initY, float ejectAngle) {
super(initX, initY, 10.0f);
this.ejectAngle = ejectAngle;
}
@Override
public void draw() {
if (!(-1.0 <= coordinate[0] && coordinate[0] <= 1.0) ||
!(-1.0 <= coordinate[1] && coordinate[1] <= 1.0)) {
GameWindow.singleton().removeComponent(this);
GameWindow.singleton().removeRigidbody(this);
GameWindow.singleton().collisionManager.removeCollider(this);
}
Util.drawLock.lock();
try {
GL11.glColor4fv(cannonBallColor);
GL11.glBegin(GL11.GL_TRIANGLE_FAN);
GL11.glVertex2fv(coordinate);
for (int i = 0; i < 365; i++) {
GL11.glVertex2f(
coordinate[0] + (float) (radius * Math.cos(Math.toRadians((double) i))),
coordinate[1] + (float) (radius * Math.sin(Math.toRadians((double) i)))
);
}
GL11.glEnd();
} finally {
Util.drawLock.unlock();
}
}
@Override
public void updateForce() {
if (!ejectFlag) {
this.addForce(
(float) (ejectForce * Math.sin(Math.toRadians(ejectAngle))),
(float) (ejectForce * Math.cos(Math.toRadians(ejectAngle)))
);
ejectFlag = true;
}
this.addForce(0.0f, gravityForce);
final float velocity = (float) Math.sqrt(Math.pow(momentum[0] / mass, 2) + Math.pow(momentum[1] / mass, 2));
if (velocity != 0.0f) {
final float airDrag = (float) (-0.1 * Math.pow(velocity, 2));
Pair<Float, Float> airResistance = new Pair<>(
momentum[0] / (mass * velocity) * airDrag,
momentum[1] / (mass * velocity) * airDrag
);
this.addForce(airResistance);
}
}
@Override
public List<Pair<Float, Float>> getColliderPolygon() {
List<Pair<Float, Float>> polygonVertexList = new LinkedList<>();
Pair<Float, Float> future = new Pair<>(
momentum[0] / mass * GameWindow.deltaTime * 0.5f * 0.001f,
momentum[1] / mass * GameWindow.deltaTime * 0.5f * 0.001f
);
for (int i = 0; i < 360; i++) {
polygonVertexList.add(new Pair<>(
coordinate[0] + (float) (Math.sin(Math.toRadians((double) i)) * radius) + future.getValue0(),
coordinate[1] + (float) (Math.cos(Math.toRadians((double) i)) * radius) + future.getValue1()
));
}
return Collections.unmodifiableList(polygonVertexList);
}
@Override
public void onCollideTerrain(Pair<Float, Float> segLeft, Pair<Float, Float> segRight) {
if (segLeft.getValue0() <= 2.0f / 3 - 1.0f && segRight.getValue0() <= 2.0f / 3 - 1.0f) {
GameWindow.singleton().removeComponent(this);
GameWindow.singleton().removeRigidbody(this);
GameWindow.singleton().collisionManager.removeCollider(this);
}
if (segLeft.getValue0() >= 2.0f * 2 / 3 - 1.0f && segRight.getValue0() >= 2.0f * 2 / 3 - 1.0f) {
GameWindow.singleton().removeComponent(this);
GameWindow.singleton().removeRigidbody(this);
GameWindow.singleton().collisionManager.removeCollider(this);
}
if (segLeft.getValue1() - segRight.getValue1() != 0) {
//momentum[0] = +momentum[0] * 0.7f;
//momentum[1] = -momentum[1] * 0.7f;
float d = (segRight.getValue1() - segLeft.getValue1()) / (segRight.getValue0() - segRight.getValue0());
float dPrime = -1 / d;
Pair<Float, Float> verVector = new Pair<>(1.0f, dPrime);
Pair<Float, Float> inVector = new Pair<>(momentum[0], momentum[1]);
double cosTheta = (verVector.getValue0() * inVector.getValue0() + verVector.getValue1() * inVector.getValue1()) /
(Math.sqrt(Math.pow(verVector.getValue0(), 2) + Math.pow(verVector.getValue1(), 2)) +
Math.sqrt(Math.pow(inVector.getValue0(), 2) + Math.pow(inVector.getValue1(), 2))
);
double theta = Math.acos(cosTheta);
Pair<Float, Float> v1 = new Pair<>(
(float) (-inVector.getValue0() * Math.cos(theta)),
(float) (-inVector.getValue1() * Math.cos(theta))
);
Pair<Float, Float> v2 = new Pair<>(
(float) (-inVector.getValue0() * Math.sin(theta)),
(float) (-inVector.getValue1() * Math.sin(theta))
);
momentum[0] = (v1.getValue0() + v2.getValue0()) * 0.5f;
momentum[1] = (v1.getValue1() + v2.getValue1()) * 0.5f;
} else {
momentum[0] = +momentum[0] * 0.5f;
momentum[1] = -momentum[1] * 0.5f;
}
if (Math.sqrt(Math.pow(momentum[0], 2) + Math.pow(momentum[1], 2)) <= 0.15f) {
GameWindow.singleton().removeComponent(this);
GameWindow.singleton().removeRigidbody(this);
GameWindow.singleton().collisionManager.removeCollider(this);
}
}
@Override
public String toString() {
return String.format("[CannonBall@%x, X:%.2f, Y:%.2f]", this.hashCode(), coordinate[0], coordinate[1]);
}
@Override
public void onCollideWithEachother(Collider collider, Pair<Float, Float> pos) {
assert collider instanceof Goat;
GameWindow.singleton().removeComponent(this);
GameWindow.singleton().removeRigidbody(this);
GameWindow.singleton().collisionManager.removeCollider(this);
}
}
|
package com.hit.neuruimall.service.impl;
import com.hit.neuruimall.mapper.OrderItemMapper;
import com.hit.neuruimall.model.OrderItemModel;
import com.hit.neuruimall.service.IOrderItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class OrderItemServiceImpl implements IOrderItemService {
@Autowired
private OrderItemMapper orderItemMapper;
@Override
public List<Integer> getAllOrderId() {
return orderItemMapper.selectAllOrderId();
}
@Override
public List<OrderItemModel> getById(Integer orderId) {
return orderItemMapper.selectById(orderId);
}
@Override
public List<Integer> getAllOrderIdWithUserId(Integer userId) {
return orderItemMapper.selectAllOrderIdWithUserId(userId);
}
}
|
package exercicio_12;
import java.util.Scanner;
public class Exercicio_12 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double nota1;
double nota2;
double nota3;
double media;
System.out.println("Calcula a media de tres notas");
//entrada de dados
System.out.print("Digite a primeira nota: ");
nota1 = keyboard.nextDouble();
System.out.print("Digite a segunda nota: ");
nota2 = keyboard.nextDouble();
System.out.print("Digite a terceira nota: ");
nota3 = keyboard.nextDouble();
System.out.println("");
//processamento
media = (nota1 + nota2 + nota3) / 3.0d;
//saida de dados
System.out.println("A media do aluno e: " + media);
if (media >= 6.0d){
System.out.println("Aluno esta APROVADO");
}else{
if (media >= 3.0d){
System.out.println("EXAME");
}else{
System.out.println("Aluno esta REPROVADO");
}
}
}
}
|
/*
* Copyright 2017 University of Michigan
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.umich.verdict.relation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.tuple.Pair;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import edu.umich.verdict.VerdictContext;
import edu.umich.verdict.datatypes.SampleParam;
import edu.umich.verdict.datatypes.TableUniqueName;
import edu.umich.verdict.exceptions.VerdictException;
import edu.umich.verdict.relation.condition.Cond;
import edu.umich.verdict.relation.expr.ColNameExpr;
import edu.umich.verdict.relation.expr.Expr;
import edu.umich.verdict.relation.expr.FuncExpr;
import edu.umich.verdict.relation.expr.SelectElem;
import edu.umich.verdict.util.VerdictLogger;
/**
* Represents aggregation operations on any source relation. This relation is
* expected to be a child of a ProjectedRelation instance (which is always
* ensured when this instance is created from a sql statement).
*
* @author Yongjoo Park
*
* This class provides extended operations than ProjectedRelation
*
*/
public class AggregatedRelation extends ExactRelation {
protected ExactRelation source;
protected List<SelectElem> elems;
protected AggregatedRelation(VerdictContext vc, ExactRelation source, List<SelectElem> elems) {
super(vc);
this.source = source;
this.elems = elems;
subquery = true;
}
@Override
protected String getSourceName() {
return getAlias();
}
public ExactRelation getSource() {
return source;
}
public List<SelectElem> getElemList() {
return elems;
}
/*
* Approx
*/
/**
* if the source is a grouped relation, only a few sample types are allowed as a
* source of another aggregate relation. 1. stratified sample: the groupby
* column must be equal to the columns on which samples were built on. the
* sample type of the aggregated relation will be "nosample" and the sample type
* will be "1.0". 2. universe sample: the groupby column must be equal to the
* columns on which samples where built on. the sample type of the aggregated
* relation will be "universe" sampled on the same columns. the sampling
* probability will also stays the same.
*/
@Override
protected List<ApproxRelation> nBestSamples(Expr elem, int n) throws VerdictException {
SamplePlans plans = candidatesAsRoot();
List<ApproxRelation> candidates = new ArrayList<ApproxRelation>();
List<FuncExpr> funcs = elem.extractFuncExpr();
for (SamplePlan plan : plans.getPlans()) {
ApproxRelation a = plan.toRelation(vc, getAlias());
boolean isEligible = true;
for (FuncExpr fexpr : funcs) {
if (fexpr.getFuncName().equals(FuncExpr.FuncName.COUNT)
|| fexpr.getFuncName().equals(FuncExpr.FuncName.AVG)
|| fexpr.getFuncName().equals(FuncExpr.FuncName.SUM)
|| fexpr.getFuncName().equals(FuncExpr.FuncName.COUNT_DISTINCT)) {
if (source instanceof GroupedRelation) {
if (a.sampleType().equals("universe") || a.sampleType().equals("stratified")
|| a.sampleType().equals("nosample")) {
} else {
isEligible = false;
}
}
} else {
// for all other functions, we don't perform any approximations.
// this was introduced to handle tpch q15; we need a better mechanism.
}
}
if (isEligible) {
candidates.add(a);
}
}
return candidates;
}
private SamplePlans candidatesAsRoot() throws VerdictException {
// these are candidates for the sources of this relation
List<List<SampleGroup>> candidates_list = new ArrayList<List<SampleGroup>>();
for (int i = 0; i < elems.size(); i++) {
SelectElem elem = elems.get(i);
Expr agg = elem.getExpr();
// TODO: make this number (10) configurable.
List<ApproxRelation> candidates = source.nBestSamples(agg, 10);
List<SampleGroup> sampleGroups = new ArrayList<SampleGroup>();
for (ApproxRelation a : candidates) {
sampleGroups.add(new SampleGroup(a, Arrays.asList(elem)));
}
candidates_list.add(sampleGroups);
}
// We test if we can consolidate those sample candidates so that the number of
// select statements is less than
// the number of the expressions. In the worst case (e.g., all count-distinct),
// the number of select statements
// will be equal to the number of the expressions. If the cost of running those
// select statements individually
// is higher than the cost of running a single select statement using the
// original tables, samples are not used.
SamplePlans consolidatedPlans = consolidate(candidates_list);
return consolidatedPlans;
}
public ApproxRelation approx() throws VerdictException {
SamplePlans consolidatedPlans = candidatesAsRoot();
SamplePlan plan = chooseBestPlan(consolidatedPlans);
if (plan == null) {
String msg = "No feasible sample plan is found.";
VerdictLogger.error(this, msg);
throw new VerdictException(msg);
}
VerdictLogger.debug(this, "The sample plan to use: ");
VerdictLogger.debugPretty(this, plan.toPrettyString(), " ");
ApproxRelation r = plan.toRelation(vc, getAlias());
r.setOriginalRelation(this);
return r;
}
public ApproxRelation approxWith(Map<TableUniqueName, SampleParam> replace) {
return new ApproxAggregatedRelation(vc, source.approxWith(replace), elems);
}
/*
* Sql
*/
protected String selectSql() {
StringBuilder sql = new StringBuilder();
sql.append("SELECT ");
sql.append(Joiner.on(", ").join(elems));
return sql.toString();
}
@Deprecated
protected String withoutSelectSql() {
StringBuilder sql = new StringBuilder();
Pair<List<Expr>, ExactRelation> groupsAndNextR = allPrecedingGroupbys(this.source);
List<Expr> groupby = groupsAndNextR.getLeft();
Pair<Optional<Cond>, ExactRelation> filtersAndNextR = allPrecedingFilters(groupsAndNextR.getRight());
String csql = (filtersAndNextR.getLeft().isPresent()) ? filtersAndNextR.getLeft().get().toString() : "";
sql.append(String.format(" FROM %s", sourceExpr(filtersAndNextR.getRight())));
if (csql.length() > 0) {
sql.append(" WHERE ");
sql.append(csql);
}
if (groupby.size() > 0) {
sql.append(" GROUP BY ");
sql.append(Joiner.on(", ").join(groupby));
}
return sql.toString();
}
public String toSql() {
StringBuilder sql = new StringBuilder();
Pair<List<Expr>, ExactRelation> groupsAndNextR = allPrecedingGroupbys(this.source);
List<Expr> groupby = groupsAndNextR.getLeft();
Pair<Optional<Cond>, ExactRelation> filtersAndNextR = allPrecedingFilters(groupsAndNextR.getRight());
String csql = (filtersAndNextR.getLeft().isPresent()) ? filtersAndNextR.getLeft().get().toString() : "";
sql.append(selectSql());
sql.append(String.format(" FROM %s", sourceExpr(filtersAndNextR.getRight())));
if (csql.length() > 0) {
sql.append(" WHERE ");
sql.append(csql);
}
if (groupby.size() > 0) {
sql.append(" GROUP BY ");
sql.append(Joiner.on(", ").join(groupby));
}
return sql.toString();
}
@Override
public List<ColNameExpr> accumulateSamplingProbColumns() {
ColNameExpr expr = new ColNameExpr(vc, samplingProbabilityColumnName(), getAlias());
return Arrays.asList(expr);
}
@Override
protected String toStringWithIndent(String indent) {
StringBuilder s = new StringBuilder(1000);
s.append(indent);
s.append(String.format("%s(%s) [%s]\n", this.getClass().getSimpleName(), getAlias(),
Joiner.on(", ").join(elems)));
s.append(source.toStringWithIndent(indent + " "));
return s.toString();
}
@Override
public ColNameExpr partitionColumn() {
ColNameExpr col = new ColNameExpr(vc, partitionColumnName(), getAlias());
return col;
}
}
|
package question4;
public class MoneyClient {
int j;
static int k;
public static void main(String[] args) {
Money obj1=new Money(100.00f,0.85f);
float a=obj1.addition(5.00f,0.90f);
System.out.println(a);
k=8;
// Money obj2=new Money(100.00f,0.25f);
float b=obj1.subtraction(5.0f,0.25f);
System.out.println(b);
}
int addition() {
this.j=5;
k=8;
return j;
}
}
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Created by SangEun on 2019-12-19.
*/
public class p8 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("How many people? ");
int people = ConvertUtil.parseStringToInt(br.readLine());
System.out.print("How many pizzas do you have? ");
int pizzas = ConvertUtil.parseStringToInt(br.readLine());
System.out.println(people + " people with " + pizzas + " pieces of pizza.");
int piecesPerPerson = pizzas * 8 / people;
int leftPieces = pizzas * 8 % people;
System.out.println("Each person gets " + piecesPerPerson + " pieces of pizza.");
System.out.println("There are " + leftPieces + " leftover pieces");
}
}
|
package com.box.androidsdk.content.models;
import com.eclipsesource.json.JsonObject;
import java.util.EnumSet;
import java.util.Map;
/**
* Holds the API representation of a permission set for a {@link BoxItem} which is a string to
* boolean mapping. Convenience methods are provided ({@link BoxFolder#getPermissions()} and
* {@link BoxFile#getPermissions()}) to make permission comparison easier
*/
public class BoxPermission extends BoxJsonObject {
public BoxPermission() {
super();
}
public BoxPermission(JsonObject object) {
super(object);
}
EnumSet<BoxItem.Permission> getPermissions() {
EnumSet<BoxItem.Permission> permissions = EnumSet.noneOf(BoxItem.Permission.class);
for (String key : getPropertiesKeySet()){
Boolean value = getPropertyAsBoolean(key);
if (value == null || value == false) {
continue;
}
if (key.equals(BoxItem.Permission.CAN_DOWNLOAD.toString())) {
permissions.add(BoxItem.Permission.CAN_DOWNLOAD);
} else if (key.equals(BoxItem.Permission.CAN_UPLOAD.toString())) {
permissions.add(BoxItem.Permission.CAN_UPLOAD);
} else if (key.equals(BoxItem.Permission.CAN_RENAME.toString())) {
permissions.add(BoxItem.Permission.CAN_RENAME);
} else if (key.equals(BoxItem.Permission.CAN_DELETE.toString())) {
permissions.add(BoxItem.Permission.CAN_DELETE);
} else if (key.equals(BoxItem.Permission.CAN_SHARE.toString())) {
permissions.add(BoxItem.Permission.CAN_SHARE);
} else if (key.equals(BoxItem.Permission.CAN_SET_SHARE_ACCESS.toString())) {
permissions.add(BoxItem.Permission.CAN_SET_SHARE_ACCESS);
} else if (key.equals(BoxItem.Permission.CAN_PREVIEW.toString())) {
permissions.add(BoxItem.Permission.CAN_PREVIEW);
} else if (key.equals(BoxItem.Permission.CAN_COMMENT.toString())) {
permissions.add(BoxItem.Permission.CAN_COMMENT);
} else if (key.equals(BoxItem.Permission.CAN_INVITE_COLLABORATOR.toString())) {
permissions.add(BoxItem.Permission.CAN_INVITE_COLLABORATOR);
}
}
return permissions;
}
}
|
package numbers.trial.exerc1;
|
package tmosq.com.androidworkshop.helper;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import tmosq.com.androidworkshop.BuildConfig;
import tmosq.com.androidworkshop.model.Company;
import static org.junit.Assert.assertEquals;
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, manifest = "src/main/AndroidManifest.xml", sdk = 21)
public class CompanyConverterTest {
private CompanyConverter companyConverter;
@Before
public void setUp() throws Exception {
companyConverter = new CompanyConverter(RuntimeEnvironment.application);
}
@Test
public void generateAllCompanies() throws Exception {
Company firstCompany = Company.builder()
.id(1)
.name("Tesla")
.maximumSalary(150000.00)
.minimumSalary(50000.00)
.position("Service Technician")
.description("We are looking for a Service Technician to work on one of the most progressive vehicles in the world. This position is customer facing, so solid customer service skills combined with exceptional 'hands on' technical ability go hand in hand.")
.build();
assertEquals(companyConverter.getAllCompanies().get(0), firstCompany);
}
}
|
package DM;
//create a new student form, students have forms
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Scanner;
//Student menu; gets list of students, displays students allows a student to be selected, allows a student to be created
//try to only run this once
public class StudentMenu {
private Hashtable<String, Student> studenttable;
//Constructor builds and populates linked list of student objects
StudentMenu(){
Statement stmt = null;
String queryid = "SELECT * FROM id WHERE Permission = 0";
try{
Connection conn = ConnectDB.getConn();
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(queryid);
studenttable = new Hashtable();
while (rs.next()) {
String studentid = rs.getString("id"); //grab id
Student student = new Student(studentid); //make a student
student.setID(studentid);
student.setName(rs.getString("name"));
student.setDegree(rs.getString("degree"));
studenttable.put(studentid, student); //put student object in hashtable
}
stmt.close();
rs.close();
conn.close();
displayStudentMenu(); //display stuff
}
catch (SQLException e ) {
e.printStackTrace();
} finally {
if (stmt != null) { try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public void displayStudentMenu(){
System.out.println("Listed Students: ");
Enumeration e = studenttable.keys();
while(e.hasMoreElements()){
System.out.println(e.nextElement());
System.out.println("\n");
}
System.out.println("Please select a student ID or type 'new' to create a new student: \n");
Scanner reader = new Scanner(System.in);
Student stud = studenttable.get(reader.next()); //pull student from table
if(stud != null){ //if it was found display attributes
System.out.println("Student ID: " + stud.getID() + "\n");
System.out.println("Student Name: " + stud.getName() + "\n");
System.out.println("Student Degree: " + stud.getDegree() + "\n");
System.out.println("Edit/View courses and forms for this student? (y/n)\n");
String input = reader.next();
if((input.toLowerCase().equals("y")) || (input.toLowerCase().equals("yes"))){
//go to dispclassmenu method
displayStudentClasses(stud);
}
else if((input.toLowerCase().equals("n")) || (input.toLowerCase().equals("no"))){
System.out.println("exiting \n");
}
else{
System.out.println("nooo");
}
}
else{
System.out.println("create new student?(y/n)\n"); //go to create student method if not found
String select = reader.next();
if(select.toLowerCase().equals("y") || select.toLowerCase().equals("yes"))
createStudent();
}
}
private void createStudent(){
Scanner reader = new Scanner(System.in);
System.out.println("Student ID: ");
String id = reader.next();
while(studenttable.get(id) != null){
System.out.println("\nThat ID is taken, select a different ID: ");
id = reader.next();
}
System.out.println("\nStudent Name: ");
String name = reader.next();
System.out.println("\nStudent Degree: ");
String degree = reader.next();
Statement stmt = null; //INSERT INTO id (id, name, degree, Permission) values ('00624604', 'Clayton', 'cs', 0);
String queryid = String.format("insert into id values ('%s', '%s', '%s', '%s', %d)", id, name, degree,null, 0);
//"INSERT INTO id (id, name, degree, password, Permission) values (" + "'" + id + "', " + "'" + name + "', " + "'" + degree + "', " + "NULL, " + "'0'" + ");";
System.out.println(queryid);
try{
Connection conn = ConnectDB.getConn();
stmt = conn.createStatement();
stmt.executeUpdate(queryid);
stmt.close();
System.out.println("\nStudent added");
conn.close();
}
catch (SQLException e ) {
e.printStackTrace();
} finally {
if (stmt != null) { try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
private void createStudentForm(Student s){
Scanner reader = new Scanner(System.in);
System.out.println("Select Year: ");
int year = reader.nextInt();
System.out.println("Select Term: ");
String term = reader.next();
System.out.println("Select prefered days for the term (MWF, TR, MW): ");
String days = reader.next();
System.out.println("Select prefered times (morning, afternoon, evening): ");
String times = reader.next();
StudentForm sform = new StudentForm();
sform.setID(s.getID());
sform.setYear(year);
sform.setTerm(term);
sform.setDays(days);
sform.setTimes(times);
s.addForm(sform);
Statement stmt = null;
String querystud = String.format("insert into Student_Form (id, year, term, day, time) values ('%s', %d, '%s', '%s', '%s')",
s.getID(), year, term, days, times);
try{
Connection conn = ConnectDB.getConn();
stmt = conn.createStatement();
stmt.executeQuery(querystud);
System.out.println("\nStudent form added");
stmt.close();
}
catch (SQLException e ) {
e.printStackTrace();
} finally {
if (stmt != null) { try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
private void displayStudentClasses(Student stud){
boolean exit = true;
while(exit){
System.out.println("Student class menu for " + stud.getName() + "\n");
System.out.println("1. View enrolled courses\n");
System.out.println("2. See available courses\n");
System.out.println("3. Enroll in a course\n");
System.out.println("4. Create New Form\n");
System.out.println("5. Exit");
Scanner reader = new Scanner(System.in);
int selection = reader.nextInt();
switch (selection){
case 1: viewEnrolled(stud);
break;
case 2: showAvailable(stud);
break;
case 3: showEnroll(stud);
break;
case 4: createStudentForm(stud);
break;
case 5: exit = false;
break;
}
}
}
private void viewEnrolled(Student s){
System.out.println("Select a form");
if(s.forms.size()>0){
for(int i = 0;i<s.forms.size();i++){
System.out.println(i + ". " + s.forms.get(i).getTerm() + " " + s.forms.get(i).getYear());
}
Scanner reader = new Scanner(System.in);
int selection = reader.nextInt();
Statement stmt = null;
String query = "SELECT * FROM Form_Course WHERE id = " + s.getID() + "AND term = " + "'" + s.forms.get(selection).getTerm().toLowerCase() + "'";
try{
Connection conn = ConnectDB.getConn();
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
int n = 1;
while (rs.next()) {
System.out.println(n + ". " + rs.getString("course_number") + "\n");
n++;
}
}
catch (SQLException e ) {
e.printStackTrace();
} finally {
if (stmt != null) { try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
else{
System.out.println("Error: No student form has been created");
}
}
private void showAvailable(Student s){
if(s.forms.size()>0){
System.out.println("Select a form");
for(int i = 0;i<s.forms.size();i++){
System.out.println(i + ". " + s.forms.get(i).getTerm() + " " + s.forms.get(i).getYear());
}
Scanner reader = new Scanner(System.in);
int selection = reader.nextInt();
Statement stmt = null;
String query = "SELECT * FROM Course WHERE term = " + "'" + s.forms.get(selection).getTerm().toLowerCase() + "'";
try{
Connection conn = ConnectDB.getConn();
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
int n = 1;
while (rs.next()) {
System.out.println(n + ". " + rs.getString("course_number") + " " + rs.getString("name") + "\n");
n++;
}
System.out.println("--------------------------");
rs.close();
stmt.close();
}
catch (SQLException e ) {
e.printStackTrace();
} finally {
if (stmt != null) { try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
else{
System.out.println("Error: No student form has been created");
}
}
private void showEnroll(Student s){
System.out.println("Select a form");
if(s.forms.size()>0){
for(int i = 0;i<s.forms.size();i++){
System.out.println(i + ". " + s.forms.get(i).getTerm() + " " + s.forms.get(i).getYear());
}
Scanner reader = new Scanner(System.in);
int selection = reader.nextInt();
Statement stmt = null;
String query = "SELECT * FROM Course WHERE term = " + "'" + s.forms.get(selection).getTerm().toLowerCase() + "'";
try{
Connection conn = ConnectDB.getConn();
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
int n = 1;
while (rs.next()) {
System.out.println(n + ". " + rs.getString("course_number") + " " + rs.getString("name") + "\n");
n++;
}
System.out.println("Type in a CRN to enroll in that course or exit to exit: \n");
String input = reader.next();
String enrollquery = String.format("insert into Form_Course (id, year, term, course_number, ranking) values ('%s', %d, '%s', '%s', %d)",
s.forms.get(selection).getID(), s.forms.get(selection).getYear(), s.forms.get(selection).getTerm(), input, 0);
try {
stmt.executeQuery(enrollquery);
rs.close();
stmt.close();
}
catch (SQLException e ) {
e.printStackTrace();
} finally {
if (stmt != null) { try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
catch (SQLException e ) {
e.printStackTrace();
} finally {
if (stmt != null) { try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
else{
System.out.println("Error: No student form has been created");
}
}
}
|
package com.jk.jkproject.net.im;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.frame.FrameDecoder;
public class MessageDecoder extends FrameDecoder {
private String TAG = "MessageDecoder";
// 用来临时保留没有处理过的请求报文
ChannelBuffer tempMsg = ChannelBuffers.dynamicBuffer();
/**
* {[消息类型 short 2][包体大小 int 4]}
* {[序列化类型 short 2][路径字符串长度short 2][路径 string X][数据 byte数组 Y]}
* <p>
* {[2][4]} {[2][2][X][Y]}
* 头 包体
*
* @param channelHandlerContext
* @param channel
* @param channelBuffer
* @return
* @throws Exception
*/
protected Object decode(ChannelHandlerContext channelHandlerContext, Channel channel, ChannelBuffer channelBuffer) throws Exception {
// 合并报文
ChannelBuffer message = null;
int tmpMsgSize = tempMsg.readableBytes();
// 如果暂存有上一次余下的请求报文,则合并
// LogUtils.e(TAG, "包的长度" + channelBuffer.readableBytes());
if (tmpMsgSize > 0) {
message = ChannelBuffers.dynamicBuffer();
message.writeBytes(tempMsg);
message.writeBytes(channelBuffer);
// LogUtils.e(TAG,"合并:上一数据包余下的长度为:" + tmpMsgSize + ",合并后长度为:" + message.readableBytes());
} else {
message = channelBuffer;
}
while (true) {
channelBuffer.markReaderIndex();
if (message.readableBytes() < 6) {
channelBuffer.resetReaderIndex();
break;
}
short type = message.readShort();
int i = message.readInt();
if (message.readableBytes() < i) {
channelBuffer.resetReaderIndex();
break;
}
byte[] arrayOfByte1 = new byte[1], arrayOfByte2 = new byte[1];
if (i > 0) {
short i1 = message.readShort();
int length = message.readShort();
arrayOfByte1 = new byte[length];
message.readBytes(arrayOfByte1);
i = i - 2 - 2 - arrayOfByte1.length;
arrayOfByte2 = new byte[i];
message.readBytes(arrayOfByte2);
}
if (type == 5) {
return ProtocolUtil.decode("header_method", new byte[1]);
} else {
return ProtocolUtil.decode(new String(arrayOfByte1, "utf-8"), arrayOfByte2);
}
}
int size = message.readableBytes();
if (size != 0) {
// LogUtils.e(TAG,"剩下来的数据放到tempMsg暂存" + size);
// 剩下来的数据放到tempMsg暂存
tempMsg.clear();
tempMsg.writeBytes(message.readBytes(size));
}
return null;
}
}
|
/**
*
*/
/**
* @author Darkaz
*
*/
public class prob2 {
// calcul de fibo au rang n
public int fibo2(int n, int acc, int accb) {
if (n == 0)
return accb;
else if (n == 1)
return acc;
else
return fibo2(n - 1, acc + accb, acc);
}
// la suite de fibo depasse 4 million au rang 33
public static void main(String[] args) {
prob2 f = new prob2();
int res = 0;
// on calcul fibo du rang 0 a 33 et si c est pair on somme
for (int k = 0; k <= 33; k++) {
int n = f.fibo2(k, 1, 0);
if (n>0 && n%2==0)
res = res +n ;
if (n<0 && n%2==0)
res = res -n ;
}
System.out.println("somme = " + res);
}
}
|
package Frames;
import Listeners.MainFrameListeners.ActionListeners.*;
import Listeners.MainFrameListeners.MouseListeners.*;
import SaveLoad.Load;
import util.WorkMasters;
import util.WorkRecords;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
/**
* Конструктор формы
*/
public class MainFrame extends JFrame {
//Таблица
private DefaultTableModel clientModel, masterModel, adminModel;
private JScrollPane clientScroll, masterScroll, adminScroll;
private MyTable clientTable, masterTable, adminTable;
private JTabbedPane tables;
//Тулбар
private JButton createBut, openBut, saveBut, exitBut;
private JToolBar toolBar;
//Диалоги сохранения-загрузки
private FileDialog save, load;
//Интерфейс
private JButton addMasterBut, removeMasterBut, addClientBut, removeClientBut, readyBut;
private JPanel interfacePanel;
//База
private WorkMasters wm;
private WorkRecords wr;
/**
* Инициализация всех элементов и отображение формы на экране
*/
public void Show() {
FrameInit();
ToolBarInit(); //Наверх формы
TableInit(); //Посередине формы
SaveLoadDialogInit();
InterfaceInit(); //Вниз формы
BaseInit();
ListenersInit();
setVisible(true);
}
/**
* Инициализация главной формы
*/
private void FrameInit() {
setTitle("Автомастерская");
setSize(700, 300);
setMinimumSize(new Dimension(1000, 500));
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
/**
* Инициализация тулбара
*/
private void ToolBarInit() {
createBut = new JButton(new ImageIcon(getClass().getResource("/pictures/create.png")));
createBut.setToolTipText("Создать новую базу данных");
openBut = new JButton(new ImageIcon(getClass().getResource("/pictures/open.png")));
openBut.setToolTipText("Открыть базу данных");
saveBut = new JButton(new ImageIcon(getClass().getResource("/pictures/save.png")));
saveBut.setToolTipText("Сохранить базу данных");
exitBut = new JButton(new ImageIcon(getClass().getResource("/pictures/exit.png")));
exitBut.setToolTipText("Выход");
toolBar = new JToolBar("Панель инструментов");
toolBar.add(createBut);
toolBar.add(openBut);
toolBar.add(saveBut);
toolBar.add(exitBut);
add(toolBar, BorderLayout.NORTH); //тулбар
}
/**
* Инициализация таблицы
*/
private void TableInit() {
String columns[] = {"Клиент", "Марка машины", "Вид работы", "Готовность"};
clientModel = new DefaultTableModel(null, columns);
clientTable = new MyTable(clientModel);
clientScroll = new JScrollPane(clientTable);
String columns1[] = {"Клиент", "Мастер", "Вид работы", "Описание неисправности"};
adminModel = new DefaultTableModel(null, columns1);
adminTable = new MyTable(adminModel);
adminScroll = new JScrollPane(adminTable);
String columns2[] = {"Имя мастера", "Специализация", "Доп. специализация №1",
"Доп. специализация №2", "Загруженность", "Max загруженность"};
masterModel = new DefaultTableModel(null, columns2);
masterTable = new MyTable(masterModel);
masterScroll = new JScrollPane(masterTable);
tables = new JTabbedPane();
tables.addTab("Основная информация", clientScroll);
tables.addTab("Дополнительная информация", adminScroll);
tables.addTab("Мастера", masterScroll);
add(tables, BorderLayout.CENTER); //Таблицы
}
/**
* Инициализация save- и load-диалогов
*/
private void SaveLoadDialogInit() {
save = new FileDialog(MainFrame.this, "Сохранение таблицы", FileDialog.SAVE);
save.setFile("*.xml");
save.setDirectory("D:\\Work\\Java\\Универ\\curs\\Сохранённые таблицы");
load = new FileDialog(MainFrame.this, "Загрузка таблицы", FileDialog.LOAD);
load.setFile("*.xml");
load.setDirectory("D:\\Work\\Java\\Универ\\curs\\Сохранённые таблицы");
}
/**
* Инициализация интерфейса
*/
private void InterfaceInit() {
interfacePanel = new JPanel();
interfacePanel.setLayout(new BoxLayout(interfacePanel, BoxLayout.X_AXIS));
addMasterBut = new JButton("Добавить мастера");
removeMasterBut = new JButton("Удалить мастера");
addClientBut = new JButton("Добавить заявку");
readyBut = new JButton("Машина готова");
removeClientBut = new JButton("Выписать заявку");
interfacePanel.add(addClientBut);
interfacePanel.add(readyBut);
interfacePanel.add(removeClientBut);
interfacePanel.add(addMasterBut);
interfacePanel.add(removeMasterBut);
add(interfacePanel, BorderLayout.SOUTH);
}
private void BaseInit() {
Load loadb = new Load();
wm = new WorkMasters(masterModel);
wr = new WorkRecords(clientModel, adminModel);
loadb.LoadXML("D:\\Work\\Java\\Универ\\curs\\Сохранённые таблицы\\saved.xml", wm, wr);
}
/**
* Привязка слушателей к объектам
*/
private void ListenersInit() {
//ActionListeners
//Тулбар
exitBut.addActionListener(new ActionExitListener(wm, wr));
saveBut.addActionListener(new ActionSaveListener(MainFrame.this, save, wm, wr));
openBut.addActionListener(new ActionLoadListener(MainFrame.this, load, wm, wr));
createBut.addActionListener(new ActionCreateListener(wm, wr));
//Интерфейс
addMasterBut.addActionListener(new ActionAddMasterListener(MainFrame.this, wm));
readyBut.addActionListener(new ActionReadyListener(MainFrame.this, tables, clientTable, wr, wm));
removeClientBut.addActionListener(new ActionRemoveRecordListener(MainFrame.this, tables, clientTable, wr));
removeMasterBut.addActionListener(new ActionRemoveMasterListener(MainFrame.this, tables, masterTable, wm));
addClientBut.addActionListener(new ActionAddClientListener(MainFrame.this, wm, wr));
//MouseListeners
//Тулбар
saveBut.addMouseListener(new MouseSaveListener(saveBut)); // (\(\
openBut.addMouseListener(new MouseOpenListener(openBut)); // (>'•')
exitBut.addMouseListener(new MouseExitListener(exitBut)); // (~(")(")
createBut.addMouseListener(new MouseCreateListener(createBut));
}
}
|
package com.marvik.apps.firstaid.activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.marvik.apps.firstaid.R;
import com.marvik.apps.firstaid.utils.activities.ActivityWrapper;
import java.util.ArrayList;
/**
* Created by victor on 9/2/2015.
*/
public class ActivityEmergencySupport extends ActivityWrapper implements AdapterView.OnItemClickListener {
private ListView lvEmergencyAndSupport;
@Override
protected void onCreateActivity(Bundle savedInstanceState) {
setContentView(R.layout.activity_emergency_and_support);
initChildViews();
}
private void initChildViews() {
lvEmergencyAndSupport = (ListView) findViewById(R.id.activity_emergency_and_support_listView_emergency_and_support);
lvEmergencyAndSupport.setOnItemClickListener(this);
ArrayList<String> emergencyAndSupport = new ArrayList<String>();
emergencyAndSupport.add("Purchase a first aid kit");
emergencyAndSupport.add("Get emergency medical unit");
emergencyAndSupport.add("Nearest hospital to you");
emergencyAndSupport.add("Ask a doctor");
emergencyAndSupport.add(" Report a medical issue");
emergencyAndSupport.add("Get check-up and testing");
lvEmergencyAndSupport.setAdapter(new ArrayAdapter<String>(getApplicationContext(), R.layout.list_emergency_and_support, R.id.list_emergency_and_support_textView_item, emergencyAndSupport));
}
@Override
protected void onResumeActivity() {
}
@Override
protected void onPauseActivity() {
}
@Override
protected void onDestroyActivity() {
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"+getString(R.string.country_firestation_tel))));
}
}
|
import java.util.ArrayList;
public class TextView {
private String text;
private ArrayList<Element> elements = new ArrayList<>();
public TextView(String text) {
this.text = text;
}
public void display() {
System.out.printf("%s", this.text);
for (Element element : this.elements) {
element.display();
}
System.out.printf("\n");
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public ArrayList<Element> getElements() {
return elements;
}
public void setElements(ArrayList<Element> elements) {
this.elements = elements;
}
}
|
package com.accp.pub.pojo;
import java.util.Date;
import org.springframework.format.annotation.DateTimeFormat;
import com.fasterxml.jackson.annotation.JsonFormat;
public class Grade {
private String gradeid;
private String gradename;
private Integer classid;
private String classname;
@DateTimeFormat(pattern = "MM/dd/yyyy")
private Date bdate;
private Date odate;
@DateTimeFormat(pattern = "MM/dd/yyyy")
private Date predictdate;
private String operator;
private Date operatortime;
private String bz1;
private String bz2;
private String bz3;
public Date getPredictdate() {
return predictdate;
}
public void setPredictdate(Date predictdate) {
this.predictdate = predictdate;
}
public String getGradeid() {
return gradeid;
}
public void setGradeid(String gradeid) {
this.gradeid = gradeid;
}
public String getGradename() {
return gradename;
}
public void setGradename(String gradename) {
this.gradename = gradename == null ? null : gradename.trim();
}
public Integer getClassid() {
return classid;
}
public void setClassid(Integer classid) {
this.classid = classid;
}
public String getClassname() {
return classname;
}
public void setClassname(String classname) {
this.classname = classname == null ? null : classname.trim();
}
// springmvc的jackson的json解析
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
public Date getBdate() {
return bdate;
}
public void setBdate(Date bdate) {
this.bdate = bdate;
}
// springmvc的jackson的json解析
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
public Date getOdate() {
return odate;
}
public void setOdate(Date odate) {
this.odate = odate;
}
public String getOperator() {
return operator;
}
public void setOperator(String operator) {
this.operator = operator == null ? null : operator.trim();
}
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
public Date getOperatortime() {
return operatortime;
}
public void setOperatortime(Date operatortime) {
this.operatortime = operatortime;
}
public String getBz1() {
return bz1;
}
public void setBz1(String bz1) {
this.bz1 = bz1 == null ? null : bz1.trim();
}
public String getBz2() {
return bz2;
}
public void setBz2(String bz2) {
this.bz2 = bz2 == null ? null : bz2.trim();
}
public String getBz3() {
return bz3;
}
public void setBz3(String bz3) {
this.bz3 = bz3 == null ? null : bz3.trim();
}
}
|
package test0;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
//@BeforeTest : methods under this annotation will be executed prior to the first test case in the TestNG file.
//@AfterTest :methods under this annotation will be executed after all test cases in the TestNG file are executed.
//@BeforeMethod :methods under this annotation will be executed prior to each method in each test case.
//@AfterMethod :methods under this annotation will be executed after each method in each test case.
/**
@Test - for every test method.
if we have 6 test methods
@Test will execute for 6 times
@BeforeMethod - is executed before every test method.
if we have 6 test methods, then "@BeforeMethod" will execute for 6 times
@AfterMethod - is executed before after test method.
if we have 6 test methods, then "@AfterMethod" will execute for 6 times
@BeforeTest - 1 time before every TestClass.
@AfterTest - 1 time after every TestClass.
Req:
A test class has
- one @BeforeTest method
- one @AfterTest method
- one @BeforeMethod method
- one @AfterMethod method
- three @Test methods
print the order of execution??
o/p:
before Test
before method
In T1
after method
before method
In T2
after method
before method
In T3
after method
after Test
*/
public class Ex16Annotations {
@BeforeTest
public static void testBeforeTest() {
System.out.println("before Test");
}
@AfterTest
public static void testafterClass() {
System.out.println("after Test");
}
@BeforeMethod
public void beforeMethod() {
System.out.println("before method");
}
@AfterMethod
public void afterMethod() {
System.out.println("after method");
}
@Test
public void T1() {
System.out.println("In T1");
}
@Test
public void T2() {
System.out.println("In T2");
}
@Test
public void T3() {
System.out.println("In T3");
}
}
|
package com.example.kz.newcuview;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.Rect;
import android.view.MotionEvent;
import android.view.View;
import java.util.ArrayList;
import java.util.List;
/**
* Created by 方坤镇 on 17-6-6.
*/
public class DrawingView extends View {
private List<CustomBitmap> mbitmap;
private Context mContext;
private CustomBitmap mCustomBitmap;
private Matrix currentMatrix = new Matrix();
private enum MODE {
NONE, DRAG, ZOOM
//模式 NONE:无 DRAG:拖拽. ZOOM:缩放
}
private MODE mode = MODE.NONE;//默认模式
public DrawingView(Context context) {
super(context);
this.mContext = context;
mbitmap = new ArrayList<>();
}
public void addBitmap(CustomBitmap bitmap) {
mbitmap.add(bitmap);
}
public List<CustomBitmap> getView() {
return mbitmap;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setAntiAlias(true);
for (CustomBitmap bitmap : mbitmap) {
canvas.drawBitmap(bitmap.getBitmap(), bitmap.matrix, paint);
}
}
//计算两点之间的距离
public float distance(MotionEvent event) {
float dx = event.getX(1) - event.getX(0);
float dy = event.getX(1) - event.getY(0);
return (float) Math.sqrt(dx * dx + dy * dy);
}
//计算两点之间的中间点
public PointF mid(MotionEvent event) {
float midX = (event.getX(1) + event.getX(0)) / 2;
float midY = (event.getY(1) + event.getY(0)) / 2;
return new PointF(midX, midY);
}
//计算旋转点
public float rotation(MotionEvent event) {
double deX = (event.getX(0) - event.getX(1));
double deY = (event.getY(0) - event.getY(1));
double radians = Math.atan2(deX, deY);
return (float) Math.toDegrees(radians);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
mode = MODE.DRAG;
if (mCustomBitmap == null && mbitmap.size() > 0) {
mCustomBitmap = mbitmap.get(mbitmap.size() - 1);
}
boolean isChange = false;
//判断当前的bitmap是否改变
for (CustomBitmap bitmap : mbitmap) {
float[] value = new float[9];
bitmap.matrix.getValues(value);
float globalX = value[Matrix.MTRANS_X];
float globalY = value[Matrix.MTRANS_Y];
float width = value[Matrix.MSCALE_X] * bitmap.getBitmap().getWidth();
float height = value[Matrix.MSCALE_Y] * bitmap.getBitmap().getHeight();
Rect rect = new Rect((int) globalX, (int) globalY, (int) (globalX + width), (int) (globalY + height));
if (rect.contains((int) event.getX(), (int) event.getY())) {
mCustomBitmap = bitmap;
isChange = true;
}
}
//切换操作对象,只要把这个对象添加到栈底就行
if (isChange) {
mbitmap.remove(mCustomBitmap);
mbitmap.add(mCustomBitmap);
}
// 记录ImageView当前的移动位置
currentMatrix.set(mCustomBitmap.matrix);
mCustomBitmap.matrix.set(currentMatrix);
mCustomBitmap.startPoint.set(event.getX(), event.getY());
postInvalidate();
break;
// 当屏幕上还有触点(手指),再有一个手指压下屏幕
case MotionEvent.ACTION_POINTER_DOWN:
mode = MODE.ZOOM;
mCustomBitmap.oldRotation = rotation(event);
mCustomBitmap.startDis = distance(event);
if (mCustomBitmap.startDis > 10f) {
mCustomBitmap.midPoint = mid(event);
// 记录ImageView当前的缩放倍数
currentMatrix.set(mCustomBitmap.matrix);
}
break;
case MotionEvent.ACTION_MOVE:
if (mode == MODE.DRAG) {
// 得到在x轴的移动距离
float dx = event.getX() - mCustomBitmap.startPoint.x;
// 得到在y轴的移动距离
float dy = event.getY() - mCustomBitmap.startPoint.y;
// 在没有进行移动之前的位置基础上进行移动
mCustomBitmap.matrix.set(currentMatrix);
mCustomBitmap.matrix.postTranslate(dx, dy);
} else if (mode == MODE.ZOOM) {// 缩放与旋转
float endDis = distance(event);// 结束距离
mCustomBitmap.rotation = rotation(event) - mCustomBitmap.oldRotation;
if (endDis > 10f) {
float scale = endDis / mCustomBitmap.startDis;// 得到缩放倍数
mCustomBitmap.matrix.set(currentMatrix);
mCustomBitmap.matrix.postScale(scale, scale, mCustomBitmap.midPoint.x, mCustomBitmap.midPoint.y);
mCustomBitmap.matrix.postRotate(mCustomBitmap.rotation, mCustomBitmap.midPoint.x, mCustomBitmap.midPoint.y);
}
}
break;
case MotionEvent.ACTION_UP:
break;
// 有手指离开屏幕,但屏幕还有触点(手指)
case MotionEvent.ACTION_POINTER_UP:
mode = MODE.NONE;
break;
}
invalidate();
return true;
}
}
|
package com.odm.managesystem.service;
public class TestService {
}
|
package com.webcloud.func.voice;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import com.iflytek.speech.SpeechError;
import com.iflytek.speech.SynthesizerPlayer;
import com.iflytek.speech.SynthesizerPlayerListener;
import com.iflytek.ui.SynthesizerDialog;
import com.webcloud.R;
import com.webcloud.WebCloudApplication;
import com.webcloud.component.NewToast;
/**
* 文字合成语音。
*
* @author bangyue
* @version [版本号, 2013-11-7]
* @see [相关类/方法]
* @since [产品/模块版本]
*/
public class VoiceTtsHolder implements SynthesizerPlayerListener{
private Application context;
private VoiceTextListener textLisr;
public VoiceTtsHolder(Activity context,VoiceTextListener textLisr){
this.context = WebCloudApplication.getInstance();
this.textLisr = textLisr;
initTts();
}
/**
* 初始化语音tts,语音合成.
*
*/
public void initTts() {
mSharedPreferences = context.getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE);
//初始化合成Dialog.
ttsDialog = new SynthesizerDialog(context, "appid=" + context.getString(R.string.flytek_key));
}
/**
* 使用SynthesizerPlayer合成语音,不弹出合成Dialog.
* @param
*/
private void synthetizeInSilence() {
if (null == mSynthesizerPlayer) {
//创建合成对象.
mSynthesizerPlayer =
SynthesizerPlayer.createSynthesizerPlayer(context, "appid=" + context.getString(R.string.flytek_key));
}
//设置合成发音人.
String role =
mSharedPreferences.getString(context.getString(R.string.preference_key_tts_role),
context.getString(R.string.preference_default_tts_role));
mSynthesizerPlayer.setVoiceName(role);
//设置发音人语速
int speed = mSharedPreferences.getInt(context.getString(R.string.preference_key_tts_speed), 50);
mSynthesizerPlayer.setSpeed(speed);
//设置音量.
int volume = mSharedPreferences.getInt(context.getString(R.string.preference_key_tts_volume), 50);
mSynthesizerPlayer.setVolume(volume);
//设置背景音.
String music =
mSharedPreferences.getString(context.getString(R.string.preference_key_tts_music),
context.getString(R.string.preference_default_tts_music));
mSynthesizerPlayer.setBackgroundSound(music);
String source = textLisr.getText();
//进行语音合成.
mSynthesizerPlayer.playText(source, null, this);
NewToast.show(context, String.format(context.getString(R.string.tts_toast_format), 0, 0));
}
/**
* 弹出合成Dialog,进行语音合成
* @param
*/
public void showSynDialog() {
String source = textLisr.getText();
//设置合成文本.
ttsDialog.setText(source, null);
//设置发音人.
String role =
mSharedPreferences.getString(context.getString(R.string.preference_key_tts_role),
context.getString(R.string.preference_default_tts_role));
ttsDialog.setVoiceName(role);
//设置语速.
int speed = mSharedPreferences.getInt(context.getString(R.string.preference_key_tts_speed), 50);
ttsDialog.setSpeed(speed);
//设置音量.
int volume = mSharedPreferences.getInt(context.getString(R.string.preference_key_tts_volume), 50);
ttsDialog.setVolume(volume);
//设置背景音.
String music =
mSharedPreferences.getString(context.getString(R.string.preference_key_tts_music),
context.getString(R.string.preference_default_tts_music));
ttsDialog.setBackgroundSound(music);
//弹出合成Dialog
ttsDialog.show();
}
//缓存对象.
private SharedPreferences mSharedPreferences;
//合成对象.
private SynthesizerPlayer mSynthesizerPlayer;
//缓冲进度
private int mPercentForBuffering = 0;
//播放进度
private int mPercentForPlaying = 0;
//合成Dialog
private SynthesizerDialog ttsDialog;
/**
* SynthesizerPlayerListener的"播放进度"回调接口.
* @param percent,beginPos,endPos
*/
@Override
public void onBufferPercent(int percent, int beginPos, int endPos) {
mPercentForBuffering = percent;
NewToast.show(context,
String.format(context.getString(R.string.tts_toast_format), mPercentForBuffering, mPercentForPlaying));
}
/**
* SynthesizerPlayerListener的"开始播放"回调接口.
* @param
*/
@Override
public void onPlayBegin() {
}
/**
* SynthesizerPlayerListener的"暂停播放"回调接口.
* @param
*/
@Override
public void onPlayPaused() {
}
/**
* SynthesizerPlayerListener的"播放进度"回调接口.
* @param percent,beginPos,endPos
*/
@Override
public void onPlayPercent(int percent, int beginPos, int endPos) {
mPercentForPlaying = percent;
NewToast.show(context,
String.format(context.getString(R.string.tts_toast_format), mPercentForBuffering, mPercentForPlaying));
}
/**
* SynthesizerPlayerListener的"恢复播放"回调接口,对应onPlayPaused
* @param
*/
@Override
public void onPlayResumed() {
}
/**
* SynthesizerPlayerListener的"结束会话"回调接口.
* @param error
*/
@Override
public void onEnd(SpeechError error) {
}
public void showTts(){
boolean show = mSharedPreferences.getBoolean(context.getString(R.string.preference_key_tts_show), true);
if (show) {
//显示合成Dialog.
showSynDialog();
} else {
//不显示Dialog,后台合成语音.
synthetizeInSilence();
}
}
public void release(){
if (null != mSynthesizerPlayer) {
try {
if(ttsDialog != null){
ttsDialog.destory();
}
mSynthesizerPlayer.cancel();
mSynthesizerPlayer.destory();
} catch (Exception e) {
e.printStackTrace();
}
}
context = null;
}
}
|
import java.util.Scanner;
public class MotelRoom {
private double soNgaytro;
private String loaiPhongTro;
private double giaPhong;
private People people = new People();
public MotelRoom(double soNgaytro, String loaiPhongTro, double giaPhong, People people) {
this.soNgaytro = soNgaytro;
this.loaiPhongTro = loaiPhongTro;
this.giaPhong = giaPhong;
this.people = people;
}
public MotelRoom() {
}
public double getSoNgaytro() {
return soNgaytro;
}
public void setSoNgaytro(double soNgaytro) {
this.soNgaytro = soNgaytro;
}
public String getLoaiPhongTro() {
return loaiPhongTro;
}
public void setLoaiPhongTro(String loaiPhongTro) {
this.loaiPhongTro = loaiPhongTro;
}
public double getGiaPhong() {
return giaPhong;
}
public void setGiaPhong(double giaPhong) {
this.giaPhong = giaPhong;
}
public People getPeople() {
return people;
}
public void setPeople(People people) {
this.people = people;
}
public void inputInfoRoom(){
Scanner scanner=new Scanner(System.in);
System.out.println("so ngay tro");
this.soNgaytro=scanner.nextDouble();
System.out.println("loai phong tro");
this.loaiPhongTro=scanner.nextLine();
System.out.println("gia phong");
this.giaPhong=scanner.nextDouble();
this.people.inputPersoninfo();
}
public void showInpuInfoRoom(){
System.out.printf("so ngay tro %s","loai phong %s","gia phong %s \n",this.soNgaytro,this.loaiPhongTro,this.giaPhong);
}
@Override
public String toString() {
return "MotelRoom{" +
"soPhongtro=" + soNgaytro +
", loaiPhongTro='" + loaiPhongTro + '\'' +
", people=" + people +
'}';
}
}
|
package org.webmaple.admin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.stereotype.Component;
import org.webmaple.admin.mapper.SpiderMapper;
/**
* @author lyifee
* on 2021/4/23
*/
@Component
public class ExitCode implements ApplicationListener<ContextClosedEvent> {
private static final Logger logger = LoggerFactory.getLogger(ExitCode.class);
// @Autowired
// private SpiderMapper spiderMapper;
@Override
public void onApplicationEvent(ContextClosedEvent contextClosedEvent) {
logger.info("=======run close event=======");
// logger.info("removing all spiders...");
// spiderMapper.removeAllSpider();
// logger.info("========close success=======");
}
}
|
package round.first.templete;
import java.util.Arrays;
//https://www.geeksforgeeks.org/quick-sort/
public class QuickSort {
public static void main(String[] args) {
int[] arr = {38, 27, 43, 3, 9, 82, 10};
QuickSort sorter = new QuickSort();
sorter.sort(arr, 0 , arr.length -1);
System.out.println(Arrays.toString(arr));
}
public void sort(int[] arr, int h, int t) {
if (h < t) {
int partionIndex = partion(arr, h, t);
sort(arr, h, partionIndex - 1);
sort(arr, partionIndex + 1, t);
}
}
private int partion(int[] arr, int h, int t) {
int pivot = arr[t];
int curt = h - 1;
for (int i = h; i < t; i++) {
if (arr[i] < pivot) {
curt++;
int temp = arr[i];
arr[i] = arr[curt];
arr[curt] = temp;
}
}
int temp = arr[curt + 1];
arr[curt + 1] = arr[t];
arr[t] = temp;
System.out.println(curt + 1);
return curt + 1;
}
}
|
package leetcode.SQL;
/**
* Created by yang on 17-7-30.
* Given a Weather table, write a SQL query to find all dates' Ids with higher temperature compared to its previous (yesterday's) dates.
+---------+------------+------------------+
| Id(INT) | Date(DATE) | Temperature(INT) |
+---------+------------+------------------+
| 1 | 2015-01-01 | 10 |
| 2 | 2015-01-02 | 25 |
| 3 | 2015-01-03 | 20 |
| 4 | 2015-01-04 | 30 |
+---------+------------+------------------+
For example, return the following Ids for the above Weather table:
+----+
| Id |
+----+
| 2 |
| 4 |
+----+
SELECT t1.Id
FROM Weather t1
INNER JOIN Weather t2
ON TO_DAYS(t1.Date) = TO_DAYS(t2.Date) + 1
WHERE t1.Temperature > t2.Temperature
to_days()函数作用:
TO_DAYS(date) 给定一个日期date, 返回一个天数 (从年份0开始的天数 )
mysql> SELECT TO_DAYS(‘1997-10-07′); -> 729669
*/
public class RisingTemperature197 {
String sql = "";
}
|
package sample.SignUpWindow;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
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.stage.Stage;
import sample.Main;
import sample.logInWindow.LogInWindowController;
import java.io.IOException;
public class SignUpWindowController {
@FXML
private TextField loginField;
@FXML
private TextField passwordField;
@FXML
private Button SignUpButton;
private Stage primaryStage=null;
// @FXML
// void initialize() {
// SignUpButton.setOnAction(event -> {
// String username=loginField.getText();
// String password=passwordField.getText();
// String clM="checkUserInDB"+username;
//
// try {
// Main.os.writeObject(clM);
// String message=(String)Main.is.readObject();
// if (message.equals("success")) {
// String msg="addUser," + username + "," + password;
// try {
// Main.os.writeObject(msg);
// } catch (IOException e) {
// e.printStackTrace();
// }
//
// returnToSignIn();
// }
// else if (message.equals("fail")) {
// Alert alert = new Alert(Alert.AlertType.INFORMATION);
// alert.setTitle("Ошибка");
// alert.setHeaderText(null);
// alert.setContentText("Неверно введены пароль или логин.");
//
// alert.showAndWait();
//
// loginField.clear();
// passwordField.clear();
// }
// } catch (IOException | ClassNotFoundException e) {
// e.printStackTrace();
// }
//
// });
// }
private void returnToSignIn() {
FXMLLoader fxmlLoader=new FXMLLoader();
Parent root=null;
try {
root=fxmlLoader.load(getClass().getResource("/sample/logInWindow/LogInWindow.fxml").openStream());
} catch (IOException e) {
e.printStackTrace();
}
LogInWindowController logInWindowController=(LogInWindowController) fxmlLoader.getController();
logInWindowController.setStage(primaryStage);
primaryStage.setTitle("Вход в систему");
Scene scene = new Scene(root);
scene.getStylesheets().add("sample/logInWindow/style.css");
primaryStage.setResizable(true);
primaryStage.setScene(scene);
primaryStage.setResizable(false);
primaryStage.show();
}
public void setStage(Stage stage) {
primaryStage= stage;
}
public void signUpClick(ActionEvent actionEvent) {
String username=loginField.getText();
String password=passwordField.getText();
String clM="checkUserInDB,"+username;
try {
Main.os.writeObject(clM);
String message=(String)Main.is.readObject();
if (message.equals("success")) {
String msg="addUser," + username + "," + password;
try {
Main.os.writeObject(msg);
} catch (IOException e) {
e.printStackTrace();
}
returnToSignIn();
}
else if (message.equals("fail")) {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Ошибка");
alert.setHeaderText(null);
alert.setContentText("Такой пользователь уже существует.");
alert.showAndWait();
loginField.clear();
passwordField.clear();
}
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
|
public class MenuMusic extends BaseGameActivity {
public static int WIDTH = 800;
public static int HEIGHT = 480;
public static final int MUTE = 0;
public static final int UNMUTE = 1;
private Scene mScene;
private Camera mCamera;
private TiledSprite mMuteButton;
/* Music object containing a sound file of the music to be played */
private Music mMenuMusic;
private ITiledTextureRegion mButtonTextureRegion;
@Override
public EngineOptions onCreateEngineOptions() {
mCamera = new Camera(0, 0, WIDTH, HEIGHT);
EngineOptions engineOptions = new EngineOptions(true,
ScreenOrientation.LANDSCAPE_FIXED, new FillResolutionPolicy(),
mCamera);
/* Tell the engineOptions that we want to play music */
engineOptions.getAudioOptions().setNeedsMusic(true);
return engineOptions;
}
@Override
public void onCreateResources(
OnCreateResourcesCallback pOnCreateResourcesCallback) {
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
/*
* Create the bitmap texture atlas.
*
* The bitmap texture atlas is created to fit a texture region of 100x50
* pixels
*/
BuildableBitmapTextureAtlas bitmapTextureAtlas = new BuildableBitmapTextureAtlas(
mEngine.getTextureManager(), 100, 50);
/* Create the buttons texture region with 2 columns, 1 row */
mButtonTextureRegion = BitmapTextureAtlasTextureRegionFactory
.createTiledFromAsset(bitmapTextureAtlas, getAssets(),
"sound_button_tiles.png", 2, 1);
/* Build the bitmap texture atlas */
try {
bitmapTextureAtlas
.build(new BlackPawnTextureAtlasBuilder<IBitmapTextureAtlasSource, BitmapTextureAtlas>(
0, 0, 0));
} catch (TextureAtlasBuilderException e) {
e.printStackTrace();
}
/* Load the bitmap texture atlas */
bitmapTextureAtlas.load();
/* Set the asset path for our sound files to "assets/sfx/" */
MusicFactory.setAssetBasePath("sfx/");
/* Create the mMenuMusic object from the specified mp3 file */
try {
mMenuMusic = MusicFactory.createMusicFromAsset(
mEngine.getMusicManager(), this, "menu_music.mp3");
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
pOnCreateResourcesCallback.onCreateResourcesFinished();
}
@Override
public void onCreateScene(OnCreateSceneCallback pOnCreateSceneCallback) {
mScene = new Scene();
pOnCreateSceneCallback.onCreateSceneFinished(mScene);
}
@Override
public void onPopulateScene(Scene pScene,
OnPopulateSceneCallback pOnPopulateSceneCallback) {
final float buttonX = (int) ((int) mButtonTextureRegion.getWidth() * 0.5f);
final float buttonY = buttonX;
/* Create the music mute/unmute button */
mMuteButton = new TiledSprite(buttonX, buttonY, mButtonTextureRegion,
mEngine.getVertexBufferObjectManager()) {
/*
* Override the onAreaTouched() method allowing us to define custom
* actions
*/
@Override
public boolean onAreaTouched(TouchEvent pSceneTouchEvent,
float pTouchAreaLocalX, float pTouchAreaLocalY) {
/* In the event the mute button is pressed down on... */
if (pSceneTouchEvent.isActionDown()) {
if (mMenuMusic.isPlaying()) {
/*
* If music is playing, pause it and set tile index to
* MUTE
*/
this.setCurrentTileIndex(MUTE);
mMenuMusic.pause();
} else {
/*
* If music is paused, play it and set tile index to
* UNMUTE
*/
this.setCurrentTileIndex(UNMUTE);
mMenuMusic.play();
}
return true;
}
return super.onAreaTouched(pSceneTouchEvent, pTouchAreaLocalX,
pTouchAreaLocalY);
}
};
/* Set the current tile index to unmuted on application startup */
mMuteButton.setCurrentTileIndex(UNMUTE);
/* Register and attach the mMuteButton to the Scene */
mScene.registerTouchArea(mMuteButton);
mScene.attachChild(mMuteButton);
/* Set the mMenuMusic object to loop once it reaches the track's end */
mMenuMusic.setLooping(true);
/* Play the mMenuMusic object */
mMenuMusic.play();
pOnPopulateSceneCallback.onPopulateSceneFinished();
}
@Override
public synchronized void onResumeGame() {
super.onResumeGame();
/* If the music and button have been created */
if (mMenuMusic != null && mMuteButton != null) {
/* If the mMuteButton is set to unmuted on resume... */
if(mMuteButton.getCurrentTileIndex() == UNMUTE){
/* Play the menu music */
mMenuMusic.play();
}
}
}
@Override
public synchronized void onPauseGame() {
super.onPauseGame();
/* Always pause the music on pause */
if(mMenuMusic != null && mMenuMusic.isPlaying()){
mMenuMusic.pause();
}
}
}
|
package lesson21.Lythuyet;
public class Animal {
public void move() {
System.out.println("Animal is moving...");
}
}
class dog extends Animal {
@Override
public void move() {
System.out.println("Fish is moving by swimming...");
}
}
class cat extends Animal {
@Override
public void move() {
System.out.println("Cat is running...");
}
}
class bird extends Animal {
@Override
public void move() {
System.out.println("Bird is flying");
}
}
|
/**
*
*/
package edu.fjnu.smd.mapper;
import java.util.List;
import java.util.Map;
import edu.fjnu.smd.domain.CourseType;
/**
* @author xiaoze
*
*/
public interface CourseTypeMapper {
void addCourseType(CourseType courseType);
void removeCourseType(Integer typeId);
void updateCourseType(CourseType courseType);
CourseType getCourseTypeById(Integer typeId);
List<CourseType> loadAll();
List<CourseType> loadPage(Map map);
int getpages();
}
|
package ua.lviv.iot.uklon.domain;
import javax.persistence.*;
import java.util.Objects;
@Entity
@Table(name = "order_type")
public class OrderType {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Integer id;
@Column(name = "name")
private String name;
public OrderType() {
}
public OrderType(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof OrderType)) return false;
OrderType orderType = (OrderType) o;
return id.equals(orderType.id) &&
name.equals(orderType.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
@Override
public String toString() {
return "OrderType{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
|
package org.sge.graph;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import org.sge.graph.api.Vertices;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.function.BiFunction;
import static org.junit.jupiter.api.Assertions.*;
@ExtendWith(MockitoExtension.class)
class VerticesImplTest {
@Mock
private EdgesCleanup<Vertex, Object> cleanupEdge;
@Test
void testAdd_Simple() {
var vertices = new VerticesImpl<>(cleanupEdge, new HashMap<>());
var vertex = new Vertex(0);
vertices.add(vertex);
var iterator = vertices.iterator();
assertTrue(iterator.hasNext());
assertSame(vertex, iterator.next());
}
@Test
void testAddAll_Simple() {
var vertices = new VerticesImpl<>(cleanupEdge, new HashMap<>());
var a = new Vertex(0);
var b = new Vertex(1);
vertices.addAll(List.of(a,b ));
var iterator = vertices.iterator();
assertTrue(iterator.hasNext());
assertSame(a, iterator.next());
assertTrue(iterator.hasNext());
assertSame(b, iterator.next());
assertFalse(iterator.hasNext());
}
@Test
void testRemove_Simple() {
var vertex = new Vertex(0);
var vertices = new VerticesImpl<>(cleanupEdge, new HashMap<>());
vertices.add(vertex);
vertices.remove(vertex);
var iterator = vertices.iterator();
assertFalse(iterator.hasNext());
}
@Test
void testRemoveAll_Simple() {
var a = new Vertex(0);
var b = new Vertex(1);
var c = new Vertex(2);
var vertices = new VerticesImpl<>(cleanupEdge, new HashMap<>());
vertices.addAll(List.of(a, b, c));
vertices.removeAll(List.of(a, c));
var iterator = vertices.iterator();
assertTrue(iterator.hasNext());
assertSame(b, iterator.next());
assertFalse(iterator.hasNext());
}
private record Vertex(int id){}
//private record Edge(){}
}
|
/**
* Created by ben on 07/12/17.
*/
public class Program {
public static void main(String[] args) {
}
}
|
package com.google.android.gms.tagmanager;
public final class a {
final String bbj;
ac bbk;
final synchronized ac qV() {
return this.bbk;
}
}
|
package servlets;
import com.fasterxml.jackson.databind.ObjectMapper;
import models.Login;
import models.User;
import services.UserService;
import utils.FileLogger;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
public class LoginServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
{
try {
//arguably, this should be a get request I think. but I'm taking in the username and password
//and putting it into my login model
InputStream requestBody = req.getInputStream();
Scanner sc = new Scanner(requestBody, StandardCharsets.UTF_8.name());
String jsonText = sc.useDelimiter("\\A").next();
ObjectMapper objectMapper = new ObjectMapper();
Login payload = objectMapper.readValue(jsonText, Login.class);
//password validation here
User loggedIn = UserService.checkPassword(payload.getUsername(), payload.getPassword());
//if checkPassword returned a user, then we successfully logged in.
if (loggedIn != null) {
resp.setStatus(200);
System.out.println("Successful login!");
//send back the object as json so the front end can pull the role out of it and redirect the user
resp.setContentType("application/json");
ObjectMapper mapper = new ObjectMapper();
resp.getWriter().write(mapper.writeValueAsString(loggedIn));
} else {
//response setup
resp.setContentType("text/plain");
PrintWriter out = resp.getWriter();
resp.setStatus(401);
//401 unauthorized response
out.println("Incorrect username and password combination.\n" +
"Please go back and try again.");
}
}
catch(IOException e)
{
FileLogger.getFileLogger().console().threshold(0).writeLog("No request body to get response from.", 0);
}
}
}
|
package logicaDeNegocio;
public class JavaBeanRoom{
private int numSala;
private String nombre;
private String descripcion;
private int capacidad;
private String departamento;
private String id;
/**
* @return the id
*/
public String getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(String id) {
this.id = id;
}
/**
* @return the departamento
*/
public String getDepartamento() {
return departamento;
}
/**
* @param departamento the departamento to set
*/
public void setDepartamento(String departamento) {
this.departamento = departamento;
}
/**
* @return the numSala
*/
public int getNumSala() {
return numSala;
}
/**
* @param numSala the numSala to set
*/
public void setNumSala(int numSala) {
this.numSala = numSala;
}
/**
* @return the nombre
*/
public String getNombre() {
return nombre;
}
/**
* @param nombre the nombre to set
*/
public void setNombre(String nombre) {
this.nombre = nombre;
}
/**
* @return the descripcion
*/
public String getDescripcion() {
return descripcion;
}
/**
* @param descripcion the descripcion to set
*/
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
/**
* @return the capacidad
*/
public int getCapacidad() {
return capacidad;
}
/**
* @param capacidad the capacidad to set
*/
public void setCapacidad(int capacidad) {
this.capacidad = capacidad;
}
}
|
package crossing.strategy;
import bplusTree.BPlusTree;
import com.carrotsearch.hppc.ObjectArrayList;
import com.carrotsearch.hppc.ObjectObjectMap;
import com.carrotsearch.hppc.ObjectObjectScatterMap;
import leafNode.OrderList;
import orderBook.OrderBook;
import java.util.Arrays;
public class AuctionStrategy {
private ObjectObjectMap<Long, AuctionData> auctionMap;
private boolean aggressBuySide;
public AuctionStrategy(){
this.auctionMap = new ObjectObjectScatterMap<>();
}
public void process(PriceTimePriorityStrategy priceTimePriorityStrategy, OrderBook orderBook) {
init();
orderBook.setStaticPriceReference(-1);
orderBook.setDynamicPriceReference(-1);
long[] prices = getPrices(orderBook);
setAggregateBuyQuantity(prices,orderBook);
setAggregateSellQuantity(prices, orderBook);
Object[] data = auctionMap.values().toArray();
Arrays.sort(data);
long targetPrice = getExecutionPrice(data);
priceTimePriorityStrategy.setTargetPrice(targetPrice);
setReferencePrice(orderBook,targetPrice);
if(aggressBuySide){
priceTimePriorityStrategy.buySideAgressSellSide();
}else{
priceTimePriorityStrategy.sellSideAgressBuySide();
}
priceTimePriorityStrategy.setTargetPrice(0);
}
private void setReferencePrice(OrderBook orderBook,long price){
if(price != 0){
orderBook.setStaticPriceReference(price);
orderBook.setDynamicPriceReference(price);
}
}
private void init() {
auctionMap.clear();
aggressBuySide = false;
}
private long[] getPrices(OrderBook orderBook){
long[] prices = orderBook.getPrices();
Arrays.sort(prices);
return prices;
}
private void setAggregateBuyQuantity(long[] prices,OrderBook orderBook){
BPlusTree<Long, OrderList> bidTree = orderBook.getBidTree();
long aggregateBuy = 0L;
for(int i=prices.length - 1; i>=0; i--){
if(prices[i] == 0){
continue;
}
OrderList bidList = bidTree.get(prices[i]);
if(bidList != null){
aggregateBuy += bidList.total();
}
AuctionData data = auctionMap.get(prices[i]);
if(data == null) {
data = new AuctionData(prices[i]);
auctionMap.put(prices[i], data);
}
data.setAggregateBuy(aggregateBuy);
}
}
private void setAggregateSellQuantity(long[] prices,OrderBook orderBook){
BPlusTree<Long, OrderList> offerTree = orderBook.getOfferTree();
long aggregateSell = 0L;
for(int i=0; i<prices.length; i++){
if(prices[i] == 0){
continue;
}
OrderList offerList = offerTree.get(prices[i]);
if(offerList != null){
aggregateSell += offerList.total();
}
AuctionData data = auctionMap.get(prices[i]);
if(data == null) {
data = new AuctionData(prices[i]);
auctionMap.put(prices[i], data);
}
data.setAggregateSell(aggregateSell);
}
}
private long getExecutionPrice(Object[] data){
ObjectArrayList<AuctionData> auctionList = new ObjectArrayList<>();
long maxVolume = 0L;
long minSurplus = 0L;
long maxPrice = 0L;
long minPrice = 0L;
for(int i=0; i<data.length - 1; i++){
AuctionData auctionData = (AuctionData)data[i];
if(maxVolume != 0 && maxVolume != auctionData.getVolume()){
break;
}
maxVolume = auctionData.getVolume();
if(maxPrice == 0 || maxPrice < auctionData.getPrice()){
maxPrice = auctionData.getPrice();
}
if(minPrice == 0 || minPrice > auctionData.getPrice()){
minPrice = auctionData.getPrice();
}
minSurplus += auctionData.getSurplus();
auctionList.add(auctionData);
}
if(auctionList.size() == 1){
return auctionList.get(0).getPrice();
}
if(minSurplus > 0){
aggressBuySide = false;
return maxPrice;
}else if (minSurplus < 0){
aggressBuySide = true;
return minPrice;
}else{
//TODO: return reference price;
return 0;
}
}
}
|
package com.plter.lib.android.java.controls;
import android.content.Context;
/**
* 对系统的ProgressDialog进行封装,用以提供更加简单的调用方式
* @author xtiqin
*
*/
public class ProgressDialog {
private static android.app.ProgressDialog __dialog =null;
/**
* 呈现一个等待提示框
* @param context
* @param message 提示框中呈现的内容
* @param title 提示框的标题
*/
public static final void show(Context context,String message,String title){
if (__dialog==null) {
__dialog= android.app.ProgressDialog.show(context, title, message);
}else{
__dialog.setTitle(title);
__dialog.setMessage(message);
}
}
/**
* 呈现一个等待提示框
* @param context
* @param message 提示框中呈现的内容
*/
public static final void show(Context context,String message){
show(context, message, "");
}
public static final void hide(){
if (__dialog!=null) {
__dialog.dismiss();
__dialog=null;
}
}
}
|
/*
* 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 pe.gob.onpe.adan.service.Admin;
import pe.gob.onpe.adan.model.admin.Usuario;
/**
*
* @author bvaldez
*/
public interface UsuarioService {
Usuario findById(int id);
Usuario findByUsuario(String usuario);
Usuario updateUsuario(Usuario usuario);
}
|
package com.example.kcroz.joggr;
public enum ExportType {
AllPointData, SpecificRunPointData
}
|
/*
* 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 de.htw_berlin.rz.room_finder.data;
import javax.xml.bind.annotation.*;
/**
* Equipment data, as returned by the underlying webservice.
*
* @author Kai Puth
*/
@XmlRootElement(name = "room")
@XmlAccessorType(XmlAccessType.FIELD)
public class Equipment {
@XmlElement
public String name;
@XmlElement
public int count;
public Equipment() {}
@Override
public String toString() {
return String.format("equipment name: %s\n", name);
}
}
|
package com.beiyelin.projectportal.controller;
import com.beiyelin.account.bean.AccountQuery;
import com.beiyelin.account.entity.Account;
import com.beiyelin.account.security.AccessPermission;
import com.beiyelin.account.service.AccountService;
import com.beiyelin.common.reqbody.QueryReqBody;
import com.beiyelin.common.resbody.PageResp;
import com.beiyelin.common.resbody.ResultBody;
import com.beiyelin.projectportal.bean.ProjectManagerPoolQuery;
import com.beiyelin.projectportal.entity.ProjectManagerPool;
import com.beiyelin.projectportal.service.ProjectManagerPoolService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import static com.beiyelin.account.constant.PermissionConstant.*;
import static com.beiyelin.projectportal.constant.PermissionConstant.PERMISSION_PROJECT_PACKAGE_NAME;
/**
* @Description: 项目经理资源池管理
* @Author: newmann
* @Date: Created in 9:26 2018-02-25
*/
@RestController
@RequestMapping("/api/project/project-manager-pool")
public class ProjetManagerPoolController {
public final static String PERMISSION_PROJECT_PROJECTMANAGERPOOLMODULE_NAME ="项目经理资源池管理";
private ProjectManagerPoolService projectManagerPoolService;
@Autowired
public void setProjectManagerPoolService(ProjectManagerPoolService service){
this.projectManagerPoolService = service;
}
//
// private AccountService accountService;
//
// @Autowired
// public void setAccountService(AccountService service){
// this.accountService = service;
// }
/**
* 新增
* @param projectManagerPool
* @return
*/
@AccessPermission(packageName = PERMISSION_PROJECT_PACKAGE_NAME,
moduleName = PERMISSION_PROJECT_PROJECTMANAGERPOOLMODULE_NAME,
action = PERMISSION_ACTION_NEW)
@PostMapping("/add")
public ResultBody< ProjectManagerPool> add(@RequestBody ProjectManagerPool projectManagerPool) {
return new ResultBody< ProjectManagerPool>(projectManagerPoolService.create(projectManagerPool));
}
/**
* 批量新增
* @param projectManagerPools
* @return
*/
@AccessPermission(packageName = PERMISSION_PROJECT_PACKAGE_NAME,
moduleName = PERMISSION_PROJECT_PROJECTMANAGERPOOLMODULE_NAME,
action = PERMISSION_ACTION_NEW)
@PostMapping("/batch-add")
public ResultBody< List<ProjectManagerPool>> batchAdd(@RequestBody List<ProjectManagerPool> projectManagerPools) {
return new ResultBody< List<ProjectManagerPool>>(projectManagerPoolService.batchAdd(projectManagerPools));
}
/**
* 修改
* @param projectManagerPool
* @return
*/
@AccessPermission(packageName = PERMISSION_PROJECT_PACKAGE_NAME,
moduleName = PERMISSION_PROJECT_PROJECTMANAGERPOOLMODULE_NAME,
action = PERMISSION_ACTION_NEW)
@PostMapping("/update")
public ResultBody< ProjectManagerPool> update(@RequestBody ProjectManagerPool projectManagerPool) {
return new ResultBody< ProjectManagerPool>(projectManagerPoolService.update(projectManagerPool));
}
/**
* 删除
* @param id
* @return
*/
@AccessPermission(packageName = PERMISSION_PROJECT_PACKAGE_NAME,
moduleName = PERMISSION_PROJECT_PROJECTMANAGERPOOLMODULE_NAME,
action = PERMISSION_ACTION_DELETE)
@DeleteMapping("/delete-by-id/{id}")
public ResultBody<Boolean> deleteById(@PathVariable String id) {
try{
projectManagerPoolService.delete(id);
return new ResultBody<>(true);
} catch (Exception e){
throw e;
}
}
@GetMapping("/find-by-id/{id}")
public ResultBody<ProjectManagerPool> findById(@PathVariable String id) {
return new ResultBody<>(projectManagerPoolService.findById(id));
}
@GetMapping("/find-by-poolid/{id}")
public ResultBody<ProjectManagerPool> findByPoolId(@PathVariable String id) {
return new ResultBody<>(projectManagerPoolService.findFirstByPoolId(id));
}
@GetMapping("/fetch-available-by-code-or-name/{searchStr}")
public ResultBody<List<ProjectManagerPool>> fetchAvailableByCodeOrName(@PathVariable String searchStr){
return new ResultBody<>(projectManagerPoolService.fetchAvailableByCodeOrName(searchStr));
}
@PostMapping("/find-page")
public ResultBody<PageResp<ProjectManagerPool>> findPage(@RequestBody QueryReqBody<ProjectManagerPoolQuery> reqBody){
return new ResultBody<>(projectManagerPoolService.fetchByQuery(reqBody.getQueryReq(),reqBody.getPageReq()));
}
@PostMapping("/find-available-account-pools-page")
public ResultBody<PageResp<Account>> findAvailableAccountPoolsPage(@RequestBody QueryReqBody<AccountQuery> reqBody){
return new ResultBody<>(projectManagerPoolService.fetchAvaiablePoolsByQuery(reqBody.getQueryReq(),reqBody.getPageReq()));
}
}
|
package com.athbk.ultimatetablayout;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.Nullable;
import android.text.InputFilter;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
* Created by ATHBK on 23,July,2018
*/
public class BadgeView extends android.support.v7.widget.AppCompatTextView {
private int styleBadge = 0; // 0 : none, 1: no-number, 2: number
private int styleSize;
public BadgeView(Context context) {
super(context);
init(context);
}
public BadgeView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context);
}
public BadgeView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
public BadgeView(Context context, int styleBadge, int styleSize){
super(context);
this.styleBadge = styleBadge;
this.styleSize = styleSize;
init(context);
}
private void init(Context context){
int px1 = (int) DeviceDimensionsHelper.convertDpToPixel(1, context);
int px5 = (int) DeviceDimensionsHelper.convertDpToPixel(5, context);
int px6 = (int) DeviceDimensionsHelper.convertDpToPixel(6, context);
int px10 = (int) DeviceDimensionsHelper.convertDpToPixel(10, context);
if (styleBadge == 1){
setBackgroundResource(R.drawable.icon_badge_circle);
if (styleSize > 0){
px10 = styleSize;
}
FrameLayout.LayoutParams badgeParams = new FrameLayout.LayoutParams(px10, px10);
badgeParams.gravity = Gravity.TOP | Gravity.RIGHT;
badgeParams.setMargins(0,2, 2, 0);
setLayoutParams(badgeParams);
setPadding(px6, px1, px6, px1);
}
else {
// set max leng
int maxLength = 2;
InputFilter[] fArray = new InputFilter[1];
fArray[0] = new InputFilter.LengthFilter(maxLength);
setFilters(fArray);
setBackgroundResource(R.drawable.icon_badge);
setTextAppearance(context, R.style.TextAppearance_AppCompat_Small);
setTextColor(getResources().getColor(android.R.color.white));
if (styleSize == 0){
styleSize = 2;
}
setTextSize(TypedValue.COMPLEX_UNIT_SP, styleSize);
setText("0");
FrameLayout.LayoutParams badgeParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
badgeParams.gravity = Gravity.TOP | Gravity.RIGHT;
badgeParams.width = badgeParams.height;
badgeParams.setMargins(30,0, 0, 0);
setLayoutParams(badgeParams);
setPadding(px5, px1, px5, px1);
}
}
public void setNumberBadge(int number){
if (number > 0){
if (styleBadge == 1) {
setBackgroundResource(R.drawable.icon_badge_circle);
}
else {
setBackgroundResource(R.drawable.icon_badge);
setText(String.valueOf(number));
}
setVisibility(VISIBLE);
}
else {
setBackgroundResource(R.drawable.icon_transparecy);
setText("");
setVisibility(GONE);
}
}
}
|
package com.fleet.redis.controller;
import com.fleet.redis.util.RedisUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
@RestController
@RequestMapping("/redis")
public class RedisController {
@Resource
RedisUtil redisUtil;
@RequestMapping("/set")
public void set(@RequestParam("key") String key, @RequestParam("value") Object value) {
redisUtil.set(key, value);
}
@RequestMapping("/delete")
public void delete(String key) {
redisUtil.delete(key);
}
@RequestMapping("/get")
public Object get(String key) {
return redisUtil.get(key);
}
}
|
class Solution {
public String reverseWords(String s) {
String [] input = s.split("\\s+");
String ans = new String();
int len = input.length;
for (int i = len - 1; i >= 0; i--)
{
ans += " " + input[i];
}
ans = ans.trim();
return ans;
}
}
|
package com.sabre.api.sacs.rest.domain.bargainfindermax;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("org.jsonschema2pojo")
@JsonPropertyOrder({
"RequestorID"
})
public class Source {
@JsonProperty("RequestorID")
private com.sabre.api.sacs.rest.domain.bargainfindermax.RequestorID RequestorID;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
*
* @return
* The RequestorID
*/
@JsonProperty("RequestorID")
public com.sabre.api.sacs.rest.domain.bargainfindermax.RequestorID getRequestorID() {
return RequestorID;
}
/**
*
* @param RequestorID
* The RequestorID
*/
@JsonProperty("RequestorID")
public void setRequestorID(com.sabre.api.sacs.rest.domain.bargainfindermax.RequestorID RequestorID) {
this.RequestorID = RequestorID;
}
public Source withRequestorID(com.sabre.api.sacs.rest.domain.bargainfindermax.RequestorID RequestorID) {
this.RequestorID = RequestorID;
return this;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
public Source withAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
return this;
}
}
|
package com.tencent.mm.plugin.sns.ui.b;
import android.view.View;
import android.view.View.OnClickListener;
import com.tencent.mm.kernel.g;
import com.tencent.mm.plugin.sns.a.b.c;
import com.tencent.mm.plugin.sns.data.b;
import com.tencent.mm.plugin.sns.model.af;
import com.tencent.mm.plugin.sns.storage.n;
class b$24 implements OnClickListener {
final /* synthetic */ b olf;
b$24(b bVar) {
this.olf = bVar;
}
public final void onClick(View view) {
this.olf.cI(view);
if (view.getTag() != null && (view.getTag() instanceof b)) {
b bVar = (b) view.getTag();
n Nl = af.byo().Nl(bVar.bKW);
if (Nl != null && Nl.xb(32)) {
bVar.nkJ = System.currentTimeMillis();
c cVar = new c(Nl.bBn(), 20, this.olf.scene == 0 ? 1 : 2, "", Nl.bBr(), Nl.bAK());
g.Ek();
g.Eh().dpP.a(cVar, 0);
}
}
}
}
|
/*
* Copyright ApeHat.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.apehat.newyear.core.env;
import com.apehat.newyear.util.ClassUtils;
import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
/**
* Be used to boot all framework plugins.
*
* @author hanpengfei
* @since 1.0
*/
public final class BootPluginLoader implements PluginLoader {
private static final String BOOT_PACKAGE_NAME = "com.apehat.newyear";
private static final Set<Plugin> BOOT_PLUGINS = new HashSet<>();
public BootPluginLoader() {
ClassLoader clToUse = ClassUtils.getDefaultClassLoader();
if (clToUse == null) {
clToUse = getClass().getClassLoader();
}
try {
Enumeration<URL> resources = clToUse.getResources(BOOT_PACKAGE_NAME);
while (resources.hasMoreElements()) {
URL url = resources.nextElement();
}
} catch (IOException e) {
throw new InitializationException();
}
}
@Override
public PluginLoader getParent() {
return null;
}
@Override
public void loadPluginsFrom(String packageName) {
throw new UnsupportedOperationException(getClass() + " not support manual launch type.");
}
@Override
public void loadPlugin(Plugin plugin) {
}
@Override
public Plugin getPlugins() {
return null;
}
}
|
package com.revature.test.services;
import static org.junit.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.testng.annotations.BeforeClass;
import com.revature.dao.UserDao;
import com.revature.entity.TfUser;
import com.revature.services.JWTService;
import io.jsonwebtoken.Claims;
/**
* Not implemented at this time. Mocking tokens is tricky and may require a different approach
* to how we want to test tokens. Will return to this class as time allows but for now leaving
* untested.
* @author Jesse
* @since 6.18.06.08
*/
public class JWTServiceTest {
@Mock
private UserDao userDao;
@InjectMocks
private JWTService jwt = new JWTService();
TfUser tf = new TfUser();
Claims claim;
private void setupMocks() {
Mockito.when(userDao.getUser(Mockito.anyString())).thenReturn(tf);
Mockito.when(userDao.getUser("baduser")).thenReturn(null);
Mockito.when(JWTService.processToken("token")).thenReturn(claim);
//Mockito.when(methodCall)
}
@BeforeClass
public void beforeClass() {
setupMocks();
}
@Test
public void test() {
String token = jwt.createToken("TestAdmin", 1);
assertTrue(jwt.validateToken(token));
String token2 = "asdfasddfae";
assertFalse(jwt.validateToken(token2));
}
}
|
package es.davidcampos.yep;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
public class RecipientsActivityWithFragment extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recipients_activity_with_fragment);
}
}
|
package cb;
import java.util.Scanner;
//Writes all the numbers that come in the order before a certain place in Fibonacci
//plus the number in that place
//ex. for all the numbers till the 10th place it gives
//{ 0,1,1,2,3,5,8,13,21,34, }
public class Fibonacci_Numbers_Array {
public static void main(String[] args) {
System.out.print("Give me a place(integer) in the fibonacci order : ");
Scanner ScanInput=new Scanner(System.in);
int Num=ScanInput.nextInt();
//System.out.println("Answer = "+FibonacciByHand(Num-1)+" with FibonacciByHand Method");
System.out.print("{ ");
for(int w=0;w<(Num);w++) {
System.out.print(fibonacci(w));
System.out.print(",");
}
System.out.print(" }");
}
public static int fibonacci(int n) {
if(n==0||n==1) {
return n;
}
else {
return fibonacci(n-1)+fibonacci(n-2);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.