text stringlengths 10 2.72M |
|---|
package com.itheima.day_12.demo_05;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class ClientDemo_FeedBack {
/*
客户端:发送数据,接收服务器反馈
*/
public static void main(String[] args) throws IOException {
//创建客户端的Socket对象(Socket)
Socket s = new Socket("127.0.0.1",10010);
//获取输出流,写数据
OutputStream os = s.getOutputStream();
os.write("客户端发送Hello,javaEE".getBytes());
//接收服务器反馈
InputStream is = s.getInputStream();
byte[] bytes = new byte[1024];
int len = is.read(bytes);
String data = new String(bytes, 0, len);
System.out.println("客户端:" + data);
//释放资源
s.close();
}
}
|
/*
* 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 Controller;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import service.ServiceInterface;
public class addSensorController {
private static ServiceInterface s1;
private static HttpURLConnection connection;
public addSensorController()throws RemoteException, NotBoundException{
Registry reg = LocateRegistry.getRegistry("localhost", 9090);
s1 = (ServiceInterface) reg.lookup("Sensor_server");
}
public void insertSensor(String floor_no,String room_no,String sensor){
String resp = new Controller.httpJson().jsonRequest1("http://localhost:5000/sensors/addsensor/"+sensor+"/"+floor_no+"/"+room_no+"/0/0");
System.out.println(resp);
System.out.println("----------------------------------------------------");
}
}
|
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Point {
private ArrayList<Point> neighbourList;
private int currentState;
private int nextState;
private int numStates = 6;
private int localGrowthForce;
private int localMilitaryForce;
private int localScienceForce;
private int currentCivId;
private boolean isCity = false;
private boolean habitable;
public Point() {
Random generator = new Random();
int tmp = generator.nextInt(4);
currentCivId = 0;
localGrowthForce = 4 - tmp;
localMilitaryForce = tmp;
localScienceForce = 0;
currentState = 0;
nextState = 0;
neighbourList = new ArrayList<Point>();
}
public void clicked() {
currentState = (++currentState) % numStates;
}
public int getState() {
return currentState;
}
public void setState(int s, int civ) {
currentState = s;
currentCivId = civ;
}
public void calculateNewState() {
if (currentState == 0 && countNeighbours() > 3)
nextState = 1;
/*else if (currentState == 1 && (countNeighbours()>3 || countNeighbours() <2) )
nextState = 0;*/
else
nextState = currentState;
//System.out.print("elo");
}
public void changeState() {
currentState = nextState;
}
public void addNeighbour(Point nei) {
neighbourList.add(nei);
}
private int countNeighbours() {
int count = 0;
for (Point n : neighbourList) {
if (n.currentState == 1)
count += 1;
}
return count;
}
public int getLocalGrowthForce() {
return localGrowthForce;
}
public void setLocalGrowthForce(int localGrowthForce) {
this.localGrowthForce = localGrowthForce;
}
public int getLocalMilitaryForce() {
return localMilitaryForce;
}
public void setLocalMilitaryForce(int localMilitaryForce) {
this.localMilitaryForce = localMilitaryForce;
}
public int getCurrentCivId() {
return currentCivId;
}
public void setCurrentCivId(int currentCivId) {
this.currentCivId = currentCivId;
}
public int getCurrentState() {
return currentState;
}
public void setCurrentState(int currentState) {
this.currentState = currentState;
}
public boolean isHabitable() {
return habitable;
}
public void setHabitable(boolean habitable) {
this.habitable = habitable;
}
public int getLocalScienceForce() {
return localScienceForce;
}
public void setLocalScienceForce(int localScienceForce) {
this.localScienceForce = localScienceForce;
}
public List<Integer> neighbourTakenBy() {
List<Integer> civs = new ArrayList<Integer>();
for (Point neighbour : neighbourList) {
if (neighbour.getCurrentCivId() != 0) {
civs.add(neighbour.getCurrentCivId());
}
}
return civs;
}
public int checkIfSurrounded() {
int hostileNeighbours = 0;
int idToReturn = 0;
int inhabitableFields = 0;
for (Point neighbor : neighbourList) {
if (neighbor.getCurrentCivId() != currentCivId && neighbor.getCurrentCivId() != 0) {
hostileNeighbours++;
idToReturn = neighbor.currentCivId;
}
if (!neighbor.isHabitable()) {
inhabitableFields++;
}
}
if (hostileNeighbours > 8 - inhabitableFields -4) {
return idToReturn;
} else
return 0;
}
public void revolt() {
setCurrentCivId(Integer.MAX_VALUE);
for (Point neighbour : neighbourList) {
neighbour.setCurrentCivId(Integer.MAX_VALUE);
}
}
public List<Point> getNeighbours() {
List<Point> result = new ArrayList<>();
for (Point neighbour : neighbourList) {
result.add(neighbour);
}
return result;
}
public void createCity() {
isCity = true;
localMilitaryForce = localGrowthForce * 5;
localGrowthForce = localGrowthForce * 5;
localScienceForce = localGrowthForce;
}
public boolean isCity() {
return isCity;
}
} |
package Model.Expression;
import Model.ADT.IDictionary;
import Model.ADT.IHeap;
import Model.Exception.ToyException;
import Model.Type.BoolType;
import Model.Type.IntType;
import Model.Type.Type;
import Model.Value.IntValue;
import Model.Value.BoolValue;
import Model.Value.Value;
public class RelationalExp implements Exp {
private Exp exp1;
private Exp exp2;
private int op; // 1 - < | 2 - <= | 3 - == | 4 - != | 5 - > | 6 - >=
public RelationalExp(int o, Exp e1, Exp e2)
{
exp1 = e1;
exp2 = e2;
op = o;
}
@Override
public String toString() {
if (op == 1)
return exp1.toString() + "<" + exp2.toString();
else if (op == 2)
return exp1.toString() + "<=" + exp2.toString();
else if (op == 3)
return exp1.toString() + "==" + exp2.toString();
else if (op == 4)
return exp1.toString() + "!=" + exp2.toString();
else if (op == 5)
return exp1.toString() + ">" + exp2.toString();
else if (op == 6)
return exp1.toString() + ">=" + exp2.toString();
else return null;
}
@Override
public Value evaluate(IDictionary<String, Value> table, IHeap heap) throws ToyException {
Value v1,v2;
v1 = exp1.evaluate(table, heap);
if (v1.getType().equals(new IntType())) {
v2 = exp2.evaluate(table, heap);
if (v2.getType().equals(new IntType())) {
IntValue i1 = (IntValue)v1;
IntValue i2 = (IntValue)v2;
int n1, n2;
n1 = i1.getValue();
n2 = i2.getValue();
if (op == 1) return new BoolValue(n1<n2);
if (op == 2) return new BoolValue(n1<=n2);
if (op == 3) return new BoolValue(n1==n2);
if (op == 4) return new BoolValue(n1!=n2);
if (op == 5) return new BoolValue(n1>n2);
if (op == 6) return new BoolValue(n1>=n2);
}
else
throw new ToyException("Second operand is not int");
}
else
throw new ToyException("First operand is not int");
return null;
}
@Override
public Type typeCheck(IDictionary<String, Type> typeEnv) throws ToyException {
Type type1, type2;
type1 = exp1.typeCheck(typeEnv);
type2 = exp2.typeCheck(typeEnv);
if (type1.equals(new IntType())) {
if (type2.equals(new IntType())) {
return new BoolType();
}
else throw new ToyException("Second operand is not an integer");
}
else throw new ToyException("First operand is not an integer");
}
@Override
public Exp deepCopy() {
return new RelationalExp(op, exp1.deepCopy(), exp2.deepCopy());
}
}
|
package datastructure.graphs;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
class Graph {
int V;
ArrayList<LinkedList<Integer>> adjListArray;
Graph(int V) {
this.V = V;
adjListArray = new ArrayList<LinkedList<Integer>>(V);
for(int i = 0; i < V; i++) {
adjListArray.add(new LinkedList<>());
}
}
public void printGraph(Graph graph) {
for (int v = 0; v < graph.V; v++) {
System.out.println("Adjacency list of vertex "+ v);
System.out.print("head");
for (Integer pCrawl : graph.adjListArray.get(v)) {
System.out.print("-->" + pCrawl);
}
System.out.println("\n");
}
}
public void addEdge(Graph graph, int src, int dest) {
// Add an edge from src --> desc
graph.adjListArray.get(src).add(dest);
// Add an edge from desc --> src;
graph.adjListArray.get(dest).add(src);
}
public void BFS(int vertex) {
boolean visited[] = new boolean[V];
LinkedList<Integer> queue = new LinkedList<>();
// Mark the vertex as visited and push it to the Queue
visited[vertex]=true;
queue.add(vertex);
while(queue.size() != 0) {
int v = queue.poll();
System.out.print(v + " ");
Iterator<Integer> itr = adjListArray.get(v).listIterator();
while(itr.hasNext()) {
int n = itr.next();
if(!visited[n]) {
visited[n] = true;
queue.add(n);
}
}
}
}
}
|
package com.kheirallah.inc.queues;
//Hard
//Crack the coding interview 3.6
/*
An animal shelter, which holds only dogs and cats, operates on a strictly "first in, first out" basis. People must adopt either the "oldest" (based on arrival time) of all animals at
the shelter, or they can select whether they would prefer a dog or a cat (and will receive the oldest animal of that type). They cannot select which specific animal they would like. Create
the data structure to maintain this system and implement operations such as enqueue, dequeueAny, dequeueDog, and dequeueCat. You may use the built-in LinkedList data structure.
Example
Input: 2, 9, 4, 5, 1 (Stack) (top to bottom)
Output: 1, 2, 4, 5, 9 (Stack) (top to bottom)
*/
import java.util.LinkedList;
public class AnimalQueue {
LinkedList<Dog> dogs = new LinkedList<>();
LinkedList<Cat> cats = new LinkedList<>();
private int order = 0; //acts as timestamp
public void enqueue(Animal a) {
//Order is used as a sort of timestamp, so that we can compare the insertion order of a dog or a cat
a.setOrder(order);
order++;
if (a instanceof Dog) {
dogs.addLast((Dog) a);
} else if (a instanceof Cat) {
cats.addLast((Cat) a);
}
}
public Animal dequeueAny() {
//look at tops of dog and cat queue, and pop the queue with the oldest value
if (dogs.size() == 0) {
return dequeueCats();
} else if (cats.size() == 0) {
return dequeueDogs();
}
Dog dog = dogs.peek();
Cat cat = cats.peek();
if (dog.isOlderThan(cat)) {
return dequeueDogs();
} else {
return dequeueCats();
}
}
public Dog dequeueDogs() {
return dogs.poll();
}
public Cat dequeueCats() {
return cats.poll();
}
abstract class Animal {
private int order;
protected String name;
public Animal(String n) {
name = n;
}
public void setOrder(int ord) {
order = ord;
}
public int getOrder() {
return order;
}
//Compare orders of animals to return the older item.
public boolean isOlderThan(Animal a) {
return this.order < a.getOrder();
}
}
public class Dog extends Animal {
public Dog(String n) {
super(n);
}
}
public class Cat extends Animal {
public Cat(String n) {
super(n);
}
}
}
|
package com.danerdaner.activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.danerdaner.Items.ListItem;
import com.danerdaner.simple_voca.ImageSerializer;
import com.danerdaner.simple_voca.R;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import java.util.ArrayList;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
public class AddEditVocaActivity extends AppCompatActivity {
private TextView add_voca_select_group;
private TextView add_voca_title;
private TextInputEditText add_voca_word;
private TextInputEditText add_voca_mean;
private TextInputEditText add_voca_announce;
private TextInputEditText add_voca_example;
private TextInputEditText add_voca_example_mean;
private TextInputEditText add_voca_memo;
private ImageView add_voca_select_picture_imageview;
private Spinner add_select_group_spinner;
private ImageButton add_voca_word_search_button;
private TextInputLayout err1, err2;
private ArrayList<String> categoryList;
private final String INLINE = ",";
private final String LINER = "%%@@%@@%%@@%";
private final String SMALL_QUOTATION_MARK = "@@@!!!###%%%";
private final String BIG_QUOTATION_MARK = "%%%##@#@@#@!!!";
private Button add_voca_save_button;
private String SAVE_STATE = "SAVE";
private int POSITION = -1;
private int SPINNER_SELETED_POSITION;
private String prevWord, prevGroup;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_voca);
SAVE_STATE = "SAVE";
POSITION = -1;
categoryList = new ArrayList<>();
for(int i = 0; i < LoadingActivity.categoryList.size(); i++){
categoryList.add(LoadingActivity.categoryList.get(i).getData()[0]);
if(LoadingActivity.categoryList.get(i).getData()[0].equals(LoadingActivity.SELECTED_CATEGORY_NAME)){
SPINNER_SELETED_POSITION = i;
}
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(getApplicationContext(),
android.R.layout.simple_spinner_dropdown_item, categoryList);
add_select_group_spinner = findViewById(R.id.add_voca_select_group_spinner);
add_select_group_spinner.setAdapter(arrayAdapter);
add_voca_title = findViewById(R.id.add_voca_title);
add_voca_word = findViewById(R.id.add_voca_word);
add_voca_mean = findViewById(R.id.add_voca_mean);
add_voca_announce = findViewById(R.id.add_voca_announce);
add_voca_example = findViewById(R.id.add_voca_example);
add_voca_example_mean = findViewById(R.id.add_voca_example_mean);
add_voca_memo = findViewById(R.id.add_voca_memo);
add_voca_select_picture_imageview = findViewById(R.id.add_voca_select_picture_imageview);
add_voca_word_search_button = findViewById(R.id.add_voca_word_search_button);
err1 = findViewById(R.id.add_voca_word_layout);
err2 = findViewById(R.id.add_voca_mean_layout);
add_voca_select_picture_imageview.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent. setDataAndType(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
startActivityForResult(intent, 200);
}
});
// 저장 버튼 클릭
add_voca_save_button = findViewById(R.id.add_voca_save_button);
add_voca_save_button.setOnClickListener(new View.OnClickListener() {
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public void onClick(View view) {
String word = add_voca_word.getText().toString();
String mean = add_voca_mean.getText().toString();
String announce = add_voca_announce.getText().toString();
String example = add_voca_example.getText().toString();
String example_mean = add_voca_example_mean.getText().toString();
String memo = add_voca_memo.getText().toString();
String group = add_select_group_spinner.getSelectedItem().toString();
if(word.length() <= 0){
Toast.makeText(getApplicationContext(),
"단어를 입력해주세요.", Toast.LENGTH_SHORT).show();
return;
}
if(mean.length() <= 0){
Toast.makeText(getApplicationContext(),
"단어의 뜻을 입력해주세요.", Toast.LENGTH_SHORT).show();
return;
}
if(!checkString(word, getApplicationContext())) return;
if(!checkString(mean, getApplicationContext())) return;
if(!checkString(announce, getApplicationContext())) return;
if(!checkString(example, getApplicationContext())) return;
if(!checkString(example_mean, getApplicationContext())) return;
if(!checkString(memo, getApplicationContext())) return;
if(!checkString(group, getApplicationContext())) return;
if(SAVE_STATE.equals("SAVE")) {
if(LoadingActivity.vocaDatabase.CheckIfWordInCategory(word, group, POSITION)){
Toast.makeText(getApplicationContext(),
"해당 카테고리에 이미 같은 단어가 존재합니다.", Toast.LENGTH_SHORT).show();
return;
}
// 데이터베이스에 넣기
LoadingActivity.vocaDatabase.insert(
word,
mean,
announce,
example,
example_mean,
memo,
ImageSerializer.PackImageToSerialized(add_voca_select_picture_imageview),
group,
"0");
String[] data = new String[]{
word, mean, announce, example, example_mean, mean,
ImageSerializer.PackImageToSerialized(add_voca_select_picture_imageview),
group, "0"
};
if(!LoadingActivity.vocaShuffleLists.containsKey(group)){
LoadingActivity.vocaDatabase.makeShuffleList(group);
}
// 자신의 셔플 맨 뒤에 단어 추가하기
LoadingActivity.vocaShuffleLists.get(group).add(new ListItem(data, 0));
// 전체 셔플 맨 뒤에도 단어 추가하기
LoadingActivity.vocaShuffleLists.get("전체").add(new ListItem(data, 0));
LoadingActivity.vocaDatabase.makeList(LoadingActivity.vocaList);
}
else if(SAVE_STATE.equals("EDIT") && POSITION >= 0){
if(LoadingActivity.vocaDatabase.CheckIfWordInCategory(word, group, POSITION)){
Toast.makeText(getApplicationContext(),
"해당 카테고리에 이미 같은 단어가 존재합니다.", Toast.LENGTH_SHORT).show();
return;
}
LoadingActivity.vocaDatabase.change(
POSITION,
word,
mean,
announce,
example,
example_mean,
memo,
ImageSerializer.PackImageToSerialized(add_voca_select_picture_imageview),
group,
"0");
// 전체 shuffle에도 수정한 단어 수정하기
ArrayList<ListItem> allArrayList = new ArrayList<>();
allArrayList.addAll(LoadingActivity.vocaShuffleLists.get("전체"));
for(int i = 0; i < allArrayList.size(); i++){
if(allArrayList.get(i).getData()[0].equals(prevWord) &&
allArrayList.get(i).getData()[7].equals(prevGroup)){
String[] data = new String[]{
word, mean, announce, example, example_mean, mean,
ImageSerializer.PackImageToSerialized(add_voca_select_picture_imageview),
group, "0"
};
allArrayList.remove(i);
allArrayList.add(i, new ListItem(data, 0));
LoadingActivity.vocaShuffleLists.put("전체", allArrayList);
break;
}
}
// shuffle에도 수정한 단어 수정하기
ArrayList<ListItem> specArrayList = new ArrayList<>();
specArrayList.addAll(LoadingActivity.vocaShuffleLists.get(group));
for(int i = 0; i < specArrayList.size(); i++){
if(specArrayList.get(i).getData()[0].equals(prevWord) &&
specArrayList.get(i).getData()[7].equals(prevGroup)){
String[] data = new String[]{
word, mean, announce, example, example_mean, mean,
ImageSerializer.PackImageToSerialized(add_voca_select_picture_imageview),
group, "0"
};
specArrayList.remove(i);
specArrayList.add(i, new ListItem(data, 0));
break;
}
}
LoadingActivity.vocaDatabase.makeList(LoadingActivity.vocaList);
MainActivity.vocaRecyclerViewAdapter.notifyDataSetChanged();
}
SAVE_STATE = "SAVE";
Intent intent = new Intent(AddEditVocaActivity.this, MainActivity.class);
startActivity(intent);
}
});
add_voca_word_search_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://en.dict.naver.com/#/search?range=all&query="+add_voca_word.getText()));
startActivity(intent);
}
});
}
@Override
protected void onStart() {
super.onStart();
add_select_group_spinner.setSelection(SPINNER_SELETED_POSITION);
Intent intent = getIntent();
if(intent.getStringExtra("STATE") != null) {
SAVE_STATE = intent.getStringExtra("STATE");
POSITION = intent.getIntExtra("POSITION", -1);
}
if(SAVE_STATE.equals("EDIT")){
String[] data = LoadingActivity.vocaDatabase.findTableData(POSITION);
add_voca_title.setText("단어 수정");
add_voca_save_button.setText("단어 수정하기");
data[0] = change_code_to_small_quotation_mark(data[0]);
data[1] = change_code_to_small_quotation_mark(data[1]);
data[2] = change_code_to_small_quotation_mark(data[2]);
data[3] = change_code_to_small_quotation_mark(data[3]);
data[4] = change_code_to_small_quotation_mark(data[4]);
data[5] = change_code_to_small_quotation_mark(data[5]);
add_voca_word.setText(data[0]);
add_voca_mean.setText(data[1]);
add_voca_announce.setText(data[2]);
add_voca_example.setText(data[3]);
add_voca_example_mean.setText(data[4]);
add_voca_memo.setText(data[5]);
if(data[6] != null && data[6].length() > 10) {
add_voca_select_picture_imageview.setImageDrawable(new BitmapDrawable(
getApplicationContext().getResources(), ImageSerializer.PackSerializedToImage(data[6])));
}
prevGroup = add_select_group_spinner.getSelectedItem().toString();
prevWord = add_voca_word.getText().toString();
// 전체 카테고리에서 단어 수정을 실행할 때는 각 단어가 포함 되어 있는 카테고리 이름을 불러준다.
if(LoadingActivity.SELECTED_CATEGORY_NAME.equals("전체")){
for(int i = 0; i < categoryList.size(); i++){
if(categoryList.get(i).equals(data[7])){
add_select_group_spinner.setSelection(i); break;
}
}
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode,resultCode,data);
if (requestCode == 200 && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri selectedImageUri = data.getData();
TextView picture_text = findViewById(R.id.picture_text);
picture_text.setText("");
int width = ((LinearLayout)add_voca_select_picture_imageview.getParent().getParent()).getWidth();
int height = ((LinearLayout)add_voca_select_picture_imageview.getParent()).getHeight();
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
300, 300
);
params.gravity = Gravity.CENTER;
add_voca_select_picture_imageview.getLayoutParams().width = width / 4;
add_voca_select_picture_imageview.getLayoutParams().height = width / 4;
//add_voca_select_picture_imageview.setLayoutParams(params);
add_voca_select_picture_imageview.setImageURI(selectedImageUri);
}
}
private boolean checkString(String str, Context context){
if(!str.contains(LINER)) {
return true;
}
else{
Toast.makeText(context, "적절하지 않은 형식입니다.", Toast.LENGTH_SHORT).show();
return false;
}
}
private String change_code_to_small_quotation_mark(String str){
str = str.replaceAll(SMALL_QUOTATION_MARK, "'");
str = str.replaceAll(BIG_QUOTATION_MARK, "\"");
return str;
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onStop() {
super.onStop();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
public void add_edit_onBackClick(View view){
finish();
}
}
|
package cl.eternaletulf.bot.bots;
import cl.eternaletulf.bot.TwitchEvents.WriteToDiscordMessage;
import com.github.philippheuer.events4j.simple.SimpleEventHandler;
import com.github.twitch4j.TwitchClient;
import com.github.twitch4j.chat.events.channel.ChannelMessageEvent;
import com.github.twitch4j.events.ChannelGoLiveEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
@Component
@Slf4j
public class TwitchBot {
final TwitchClient twitchClient;
final WriteToDiscordMessage writeToDiscordMessage;
public TwitchBot(TwitchClient twitchClient,
WriteToDiscordMessage writeToDiscordMessage) {
this.twitchClient = twitchClient;
this.writeToDiscordMessage = writeToDiscordMessage;
SimpleEventHandler eventHandler = twitchClient.getEventManager()
.getEventHandler(SimpleEventHandler.class);
eventHandler.onEvent(ChannelMessageEvent.class, event -> onChannelMessage(event));
eventHandler.onEvent(ChannelGoLiveEvent.class, live -> onLiveEvent(live));
}
private void onChannelMessage(ChannelMessageEvent event) {
String message = event.getMessage();
event.getChannel();
switch (message) {
case "!Pog":
twitchClient.getChat().sendMessage(event.getChannel().getName(), "Pog !");
break;
case "!totodile":
twitchClient.getChat().sendMessage(event.getChannel().getName(), "TOOOOOOOOOTODILE");
break;
case "!deer":
twitchClient.getChat().sendMessage(event.getChannel().getName(), "D e e R F o r C e");
break;
}
}
//TODO aqui me muero
private void onLiveEvent(ChannelGoLiveEvent live) {
if (!live.getStream().getUptime().isZero() || !live.getStream().getUptime().isNegative()) {
} else {
writeToDiscordMessage.showOnDiscord(live);
}
}
}
|
/*
* ### Copyright (C) 2001-2003 Michael Fuchs ###
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*
* Author: Michael Fuchs
* E-Mail: mfuchs@unico-consulting.com
*
* RCS Information:
* ---------------
* Id.........: $Id: MiscTests.java,v 1.1.1.1 2004/12/21 14:00:08 mfuchs Exp $
* Author.....: $Author: mfuchs $
* Date.......: $Date: 2004/12/21 14:00:08 $
* Revision...: $Revision: 1.1.1.1 $
* State......: $State: Exp $
*/
package org.dbdoclet.test.parser;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.dbdoclet.log.Logger;
public class MiscTests extends ParserTestCase {
/**
* The variable <code>logger</code>{@link org.apache.log4j.Logger (org.apache.log4j.Logger)}
* can be used to print logging information via the log4j framework.
*/
private static Log logger = LogFactory.getLog(MiscTests.class);
public MiscTests(String name) {
super(name);
}
public static Test suite() {
return new TestSuite(MiscTests.class);
}
public void testParseSplittedTag() throws Exception {
String code = "<a\n" + " href=\"http://www.javasoft.com\"\n" +
">\nJavaSoft</\n" + "a>";
checkHtml(code, 86);
}
public void testParseComment() throws Exception {
String code = "<p> <!-- Some comment --> With comment </p>\n";
checkHtml(code, 51);
}
public void testParseGregorJasny1() throws Exception {
String code =
"Meldet einen Benutzer mittels Benutzer-Id und Passwort an.\n" +
"<br>\n" +
"Wenn der UserId oder der UserPasswort Parameter nicht existiert bzw. die\n" +
"Länge Null hat, wird nicht angemeldet und auch kein Fehler ausgegeben.\n" +
"<br><br>\n" + "Parameter:<ul>\n" +
"<li><b>ifOK</b> - Legt die Seite fest, zu der bei erfolgreichem Login redirected wird.\n" +
"<li><b>userIdParam</b> - Legt den Namen des Parameters fest, der die UserId enthält.\n" +
"<li><b>userPwParam</b> - Legt den Namen der Parameters fest, der das Passwort enthält.\n" +
"<li>myDateParam - Legt den Namen des Parameters fest, in dem die lokale Zeit übergeben wird. Das Format ist das ISO-Format.\n" +
"</ul>\n" + "Rückgabewerte:<ul>\n" +
"<li>null bei erfolgreicher Anmeldung.\n" +
"<li>\"\" bei einem fehlenden Parameter\n" +
"<li>Die i18n Fehlermeldung, falls die Anmeldung fehlschlug.\n" +
"</ul>\n" + "Beispiel:<br>\n" + "<code><pre>\n" +
"<VidSoft:Logon ifOK=\"FrameIt.jsp\"\n" +
"userIdParam=\"LoginUserId\"\n" +
"userPwParam=\"UserPassword\">\n" +
"<VidSoft:IfNotNull>\n" + "\n" +
"<form method=\"post\" action=\"Logon.jsp\">\n" + "\n" +
"<!-- Um die eventuelle Fehlermeldung auszugeben: -->\n" +
"<VidSoft:Insert/>\n" +
"<input type=\"text\" name=\"LoginUserId\">\n" +
"<input type=\"text\" name=\"UserPassword\">\n" +
"</form>\n" + "</VidSoft:IfNotNull>\n" +
"</VidSoft:Logon>\n" + "</pre></code>\n" + "@since 3.0\n" +
"@author Gregor Jasny\n" + "\n";
checkHtml(code, 1648);
}
public void testParseCaseRoole1() throws Exception {
String code = "<h1>First section</h1>\n" + "\n" + "<p>\n" +
"Here is an unordered list:\n" + "<ul>\n" + "<li>first item\n" +
"<li>second item\n" + "</ul>\n" +
"Having a text here after the </UL> prevents the rest of the doc from being truncated.\n" +
"</p>\n" + "\n" + "<h1>Second section</h1>\n" + "<p>\n" +
"Here is another unordered list:\n" + "<ul>\n" +
"<li>first item\n" + "<li>second item\n" + "</ul>\n" + "</p>\n" +
"<p>\n" +
"There is nothing between the </UL> and the </P> above and everything after it is truncated.\n" +
"</p>\n" + "\n" + "<h1>Third section</h1>\n" + "\n" + "<p>\n" +
"This section is not processed.\n" + "</p>\n" + "\n";
checkHtml(code, 673);
}
public void testParseUpperLowerCase() throws Exception {
String code = "<table>\n" + "<TR><td>First</td></tr>\n" +
"<Tr><td>First</td></tr>\n" + "<tr><td>First</td></tr>\n" +
"</table>\n";
checkHtml(code, 163);
}
static public void main(String[] args) {
junit.textui.TestRunner.run(suite());
}
}
/*
* $Log: MiscTests.java,v $
* Revision 1.1.1.1 2004/12/21 14:00:08 mfuchs
* Reimport
*
* Revision 1.2 2004/10/05 13:13:18 mfuchs
* Sicherung
*
* Revision 1.1.1.1 2004/02/17 22:49:31 mfuchs
* dbdoclet
*
* Revision 1.1.1.1 2004/01/05 14:57:05 cvs
* dbdoclet
*
* Revision 1.1.1.1 2003/08/01 13:19:24 cvs
* DocBook Doclet
*
* Revision 1.2 2003/08/01 10:32:05 mfuchs
* Fixes for release 0.46
*
* Revision 1.1.1.1 2003/07/31 17:05:40 mfuchs
* DocBook Doclet since 0.46
*
* Revision 1.2 2003/06/27 08:39:12 mfuchs
* Fixes and improvemts for 0.45
*
* Revision 1.1.1.1 2003/05/30 11:09:40 mfuchs
* dbdoclet
*
* Revision 1.1.1.1 2003/03/18 07:41:37 mfuchs
* DocBook Doclet 0.40
*
* Revision 1.1.1.1 2003/03/17 20:51:37 cvs
* dbdoclet
*
*/
|
package easii.com.br.iscoolapp.adapters;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.gson.Gson;
import java.util.List;
import java.util.Random;
import easii.com.br.iscoolapp.R;
import easii.com.br.iscoolapp.objetos.Aluno2;
import easii.com.br.iscoolapp.objetos.Message;
import easii.com.br.iscoolapp.objetos.Professor2;
import easii.com.br.iscoolapp.util.MaterialColorPalette;
/**
* Created by gustavo on 26/10/2016.
*/
public class MsgAdapter extends BaseAdapter {
private List<Message> lista;
private LayoutInflater inflater;
private Context context;
private LinearLayout singleMessageContainer;
public MsgAdapter(Context context, List<Message> plista) {
this.lista = plista;
this.context = context;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void addItem(final Message item) {
this.lista.add(item);
//Atualizar a lista caso seja adicionado algum item
notifyDataSetChanged();
}
@Override
public int getCount() {
return lista.size();
}
@Override
public Object getItem(int position) {
return lista.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Random rand = new Random();
Message pm = lista.get(position);
convertView = inflater.inflate(R.layout.item_msg, null);
View row = convertView;
if (row == null) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.item_msg, parent, false);
}
singleMessageContainer = (LinearLayout) row.findViewById(R.id.singleMessageContainer);
TextView tvTitle = (TextView) convertView.findViewById(R.id.msgUser);
TextView tvMsg = (TextView) convertView.findViewById(R.id.msgText);
String id = pm.getId();
String idCell = acessaSharedPreferences();
MaterialColorPalette myCustomPalette = new MaterialColorPalette(Color.YELLOW);
int my200Color = myCustomPalette.getColor("200");
if(id.equals(idCell)){
tvTitle.setText(pm.getUser());
// tvTitle.setPadding(64, 16, 32, 0);
tvMsg.setText(pm.getMsg());
// tvMsg.setPadding(64, 16, 32, 16);
// convertView = inflater.inflate(R.layout.list_item_message_right, null);
}else{
tvTitle.setText(pm.getUser());
// tvTitle.setPadding(32, 16, 64, 0);
tvMsg.setText(pm.getMsg());
// tvMsg.setPadding(32, 16, 64, 16);
tvMsg.setBackgroundColor(my200Color);
//tvMsg.setBackgroundColor(context.getResources().getColor(R.color.colorAccent));
// convertView = inflater.inflate(R.layout.list_item_message_left, null);
}
// tvMsg.setBackgroundResource( R.drawable.bolha);
singleMessageContainer.setGravity(id.equals(idCell) ? Gravity.RIGHT : Gravity.LEFT);
// singleMessageContainer.setBackgroundResource(R.drawable.bolha);
return convertView;
}
private String acessaSharedPreferences() {
SharedPreferences sharedPref = context.getSharedPreferences("CONSTANTES", Context.MODE_PRIVATE);
String tipo = sharedPref.getString("TIPO", "NULL");
if (tipo.equals("ALUNO")) {
String alunoJson = sharedPref.getString("ALUNO", "NULL");
Gson gson = new Gson();
Aluno2 aluno2 = gson.fromJson(alunoJson, Aluno2.class);
return "" + aluno2.getId();
} else {
String profJson = sharedPref.getString("PROFESSOR", "NULL");
Gson gson = new Gson();
Professor2 professor2 = gson.fromJson(profJson, Professor2.class);
return "" + professor2.getId();
}
}
}
|
package model.fighter;
import model.board.Content;
import model.element.Blood;
import model.fighter.level.EnemyLevel;
public class Enemy1 extends Enemy {
private int moveCounter = 0;
public Enemy1(int level) {
super(new EnemyLevel(level, 1, 0.7));
}
@Override
public Content contentLeft() {
return new Blood();
}
@Override
public void heroMoveListener() {
this.moveCounter++;
if(this.isAlive() && ((moveCounter % 2) == 0))
this.heal(1);
}
public void injured(int value){
super.injured(value);
moveCounter=0;
}
}
|
/*
* @(#) TpservService.java
* Copyright (c) 2007 eSumTech Co., Ltd. All Rights Reserved.
*/
package com.esum.wp.ims.tpsecu.service.impl;
import java.util.List;
import com.esum.appframework.exception.ApplicationException;
import com.esum.appframework.service.impl.BaseService;
import com.esum.wp.ims.tpsecu.Tpsecu;
import com.esum.wp.ims.tpsecu.dao.ITpsecuDAO;
import com.esum.wp.ims.tpsecu.service.ITpsecuService;
import com.esum.wp.ims.tpserv.dao.ITpservDAO;
/**
*
* @author heowon@esumtech.com
* @version $Revision: 1.1 $ $Date: 2009/01/20 01:31:00 $
*/
public class TpsecuService extends BaseService implements ITpsecuService {
/**
* Default constructor. Can be used in place of getInstance()
*/
public TpsecuService () {}
public Object removeTpservList(Object object) {
List list = (List) object;
for (int i = 0; i < list.size(); i++) {
Tpsecu tpserv = (Tpsecu) (list.get(i));
super.delete(tpserv);
}
return list;
}
public Object selectPageList(Object object) {
try {
ITpsecuDAO iTpsecuDAO = (ITpsecuDAO)iBaseDAO;
return iTpsecuDAO.selectPageList(object);
} catch (ApplicationException e) {
e.setMouduleName(moduleName);
e.printException("");
return e;
} catch (Exception e) {
ApplicationException ae = new ApplicationException(e);
ae.setMouduleName(moduleName);
return ae;
}
}
public Object detail(Object object) {
try {
ITpsecuDAO iTpsecuDAO = (ITpsecuDAO)iBaseDAO;
return iTpsecuDAO.detail(object);
} catch (ApplicationException e) {
e.setMouduleName(moduleName);
e.printException("");
return e;
} catch (Exception e) {
ApplicationException ae = new ApplicationException(e);
ae.setMouduleName(moduleName);
return ae;
}
}
public Object insertTpsecu(Object object) {
try {
ITpsecuDAO iTpsecuDAO = (ITpsecuDAO)iBaseDAO;
return iTpsecuDAO.detail(object);
} catch (ApplicationException e) {
e.setMouduleName(moduleName);
e.printException("");
return e;
} catch (Exception e) {
ApplicationException ae = new ApplicationException(e);
ae.setMouduleName(moduleName);
return ae;
}
}
public Object selectCheck(Object object) {
try {
ITpsecuDAO iTpsecuDAO = (ITpsecuDAO)iBaseDAO;
return iTpsecuDAO.selectCheck(object);
} catch (ApplicationException e) {
e.setMouduleName(moduleName);
e.printException("");
return e;
} catch (Exception e) {
ApplicationException ae = new ApplicationException(e);
ae.setMouduleName(moduleName);
return ae;
}
}
}
|
package com.generic.core.model.entities;
import java.io.Serializable;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name="ITEMS", schema="factory")
public class Items implements Serializable{
private static final long serialVersionUID = 1L;
public Items() {}
public Items(String itemId) {
this.itemId = itemId;
}
public Items(String itemId, String itemName, String imageName, String description, String brand) {
this.itemId = itemId;
this.itemName = itemName;
this.imageName = imageName;
this.description = description;
this.brand = brand;
}
public Items(String itemId, String itemName, String imageName, String description, String brand, Categories category) {
this.itemId = itemId;
this.itemName = itemName;
this.imageName = imageName;
this.description = description;
this.brand = brand;
this.category = category;
}
@Id
@Column(name="ITEM_ID", length=20)
private String itemId;
@Column(name="ITEM_NAME", length=200)
private String itemName;
@Column(name="IMAGE_NAME", length=100)
private String imageName;
@Column(name="DESCRIPTION", length=200)
private String description;
@Column(name="BRAND", length=100)
private String brand;
@ManyToOne
@JoinColumn(name="CATEGORY_ID")
private Categories category;
@OneToMany(mappedBy="shopIdItemId.item")
private Set<ShopsItems> shopItem;
public String getItemId() {
return itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getImageName() {
return imageName;
}
public void setImageName(String imageName) {
this.imageName = imageName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Categories getCategory() {
return category;
}
public void setCategory(Categories category) {
this.category = category;
}
public Set<ShopsItems> getShopItem() {
return shopItem;
}
public void setShopItem(Set<ShopsItems> shopItem) {
this.shopItem = shopItem;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
}
|
package com.lsjr.zizisteward.coustom;
import android.content.Context;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ViewConfiguration;
/**
* Created by admin on 2017/5/20.
*/
public class MySwipeRefreshLayout extends SwipeRefreshLayout {
private float downX;
private float downY;
private int mTouchSlop;
public MySwipeRefreshLayout(Context context) {
this(context,null);
}
public MySwipeRefreshLayout(Context context, AttributeSet attrs) {
super(context, attrs);
mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
int action= MotionEventCompat.getActionMasked(ev);
switch (action){
case MotionEvent.ACTION_DOWN:
downY=ev.getY();
downX=ev.getX();
return super.onInterceptTouchEvent(ev);
case MotionEvent.ACTION_MOVE:
float lastX=ev.getRawX();
float lastY=ev.getRawY();
float distanceX=lastX-downX;
float distanceY=lastY-downY;
/*反向*/
float distanceXX=downX-lastX;
if (Math.abs(distanceX)>0){
//右滑动
if (Math.abs(distanceX)>Math.abs(distanceY)){
return false;
}else {
return super.onInterceptTouchEvent(ev);
}
}else {
//左边滑动
if (Math.abs(distanceXX)>Math.abs(distanceY)) {
return false;
}else {
super.onInterceptTouchEvent(ev);
}
}
case MotionEvent.ACTION_UP:
downY=0;
downX=0;
return super.onInterceptTouchEvent(ev);
}
return false;
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.dthebus.designpatterns.behavioral.interpreter;
/**
*
* @author darren
*/
public class BExpression extends Expression{
@Override
public void interpret(Context context) {
String input = context.getInput();
context.setInput(input.substring(1));
context.setOutPut(context.getOutput()+"2");
}
}
|
/**
* Kenny Akers
* Mr. Paige
* Homework #17
* 2/9/18
*/
public class Identifier extends Leaf {
private final String variable;
public Identifier(String ID) {
super(7); // Variables have a precedence of 7.
this.variable = ID;
SymbolTable.table.put(ID, 0); // Default value of 0.
}
public void setValue(int newValue) {
SymbolTable.table.replace(variable, newValue);
}
@Override
public String format() {
return this.variable;
}
@Override
public int evaluate() {
return SymbolTable.table.get(variable);
}
}
|
package org.giddap.dreamfactory.leetcode.onlinejudge;
import org.giddap.dreamfactory.leetcode.onlinejudge.implementations.MedianofTwoSortedArraysMergeAndCountImpl;
import org.giddap.dreamfactory.leetcode.onlinejudge.implementations.MedianofTwoSortedArraysBinarySearchOnMedianImpl;
import org.giddap.dreamfactory.leetcode.onlinejudge.implementations.MedianofTwoSortedArraysWithFindKthElementImpl;
import org.junit.Assert;
import org.junit.Test;
public class MedianofTwoSortedArraysTest {
private MedianofTwoSortedArrays solution = new MedianofTwoSortedArraysBinarySearchOnMedianImpl();
private MedianofTwoSortedArrays solution2 = new MedianofTwoSortedArraysMergeAndCountImpl();
private MedianofTwoSortedArrays solution3 = new MedianofTwoSortedArraysWithFindKthElementImpl();
@Test
public void small01() {
int[] a = {5, 25, 35};
int[] b = {1, 7, 9, 11};
double median = solution.findMedianSortedArrays(a, b);
Assert.assertTrue(new Double(9).compareTo(median) == 0);
}
@Test
public void small02() {
int[] a = {5, 25, 27};
int[] b = {1, 7, 99};
double median = solution.findMedianSortedArrays(a, b);
Assert.assertTrue(new Double(16).compareTo(median) == 0);
}
@Test
public void small03() {
int[] a = {};
int[] b = {1};
double median = solution.findMedianSortedArrays(a, b);
Assert.assertTrue(new Double(1.0).compareTo(median) == 0);
}
@Test
public void small04() {
int[] a = {1};
int[] b = {1};
double median = solution.findMedianSortedArrays(a, b);
Assert.assertTrue(new Double(1.0).compareTo(median) == 0);
}
@Test
public void small05() {
int[] a = {2, 2, 2};
int[] b = {2, 2, 2, 2};
double median = solution.findMedianSortedArrays(a, b);
Assert.assertTrue(new Double(2.0).compareTo(median) == 0);
}
@Test
public void small06() {
int[] a = {1};
int[] b = {2, 3, 4, 5};
double median = solution.findMedianSortedArrays(a, b);
Assert.assertTrue(new Double(3.0).compareTo(median) == 0);
}
@Test
public void small07() {
int[] a = {3};
int[] b = {1 , 2};
double median = solution.findMedianSortedArrays(a, b);
Assert.assertTrue(new Double(2.0).compareTo(median) == 0);
}
@Test
public void small08() {
int[] a = {};
int[] b = {1 , 2, 3, 4};
double median = solution.findMedianSortedArrays(a, b);
Assert.assertTrue(new Double(2.5).compareTo(median) == 0);
}
}
|
import java.util.Iterator;
public class traverse {
private final String str = "poiuyttrewq*&^$";
private final char c = '8';
private final String str2 = "123124";
private final int num = 455657;
private final int[] arr = {1,3,4,5,6};
public void traverse(){
//字符串遍历
for(int i=0;i<str.length();i++){
System.out.println(str.charAt(i));
}
//字符串转整数方式1
int t = Integer.valueOf(str2);
System.out.println(t);
//字符/字符串转整数
int t2 = c - '0';
//整数转字符串
String tempstr = String.valueOf(num);
//字符串转字符数组
char[] temp = str.toCharArray();
System.out.println(temp.length);
}
}
|
public class CuckooHT extends HashTable {
long[][] table = new long[2][]; // the ht
long[][] tableCopy = new long[2][]; // used to restore to prev state
private Hash[] hashFuncs;
private long swaps; // swaps per insertion attempt
private long steps; // total steps including rehash insertions
private long maxRehashes; // to control when to cut off insert
private long maxSwaps; // to determine when to rehash
private int nRehashes; // counter for each insert of a new key
public CuckooHT(long m, Hash hashA, Hash hashB, long maxSwaps) {
super(m);
this.hashFuncs = new Hash[] { hashA, hashB };
this.maxRehashes = 10; // = log2(m) / 2;
this.maxSwaps = maxSwaps; // max loops only depends on max number of items in hash
// source (Dr. Mares' class notes, 6-12)
this.nRehashes = 0;
n = 0;
// Build first table
long[] keysA = new long[(int) m / 2];
for (int i = 0; i < m / 2; i++) // init array
keysA[i] = -1; // since no null for primitives in Java...
// Build second table / 2
long[] keysB = new long[(int) m / 2];
for (int i = 0; i < m / 2; i++) // init array
keysB[i] = -1; // since no null for primitives in Java...
this.table[0] = keysA;
this.table[1] = keysB;
}
/**
* Insert a given key at a given hash index. Useful if one wishes to use a
* specific hash function
*
* @param k
* key
* @return i index
*/
@Override
public boolean insert(long k) {
if (find(k))
return false;
// initial insertion
tableCopy = deepCopyHashTable(table); // copy tables once
boolean status = put(k); // call internal method put()
if (status) {
n++;
return true;
}
table = tableCopy; // revert back to old tables
return false;
}
/**
* Internal insertion method
*
* @param k
* @return true if insertion is successful or else false, for failure rehashing
*/
private boolean put(long k) {
if (nRehashes >= maxRehashes)
return false;
int whichTable = 0;
swaps = 0;
while (swaps <= maxSwaps) {
long i = hashFuncs[whichTable].hash(k); // smoke new hash
if (table[whichTable][(int) i] != -1) {
swaps++;
steps++;
long ejectedKey = table[whichTable][(int) i]; // eject key
table[whichTable][(int) i] = k; // insert new key
k = ejectedKey; // swap
whichTable = Math.abs(whichTable - 1); // goto other table for next iter
} else {
// This table pos vacant, so insert this key and we done
table[whichTable][(int) i] = k; // insert
return true;
}
}
// Need to rehash and then insert uninserted element after
if (nRehashes <= maxRehashes) {
rehash();
put(k);
}
// Failed (max limit for) rehash
return false;
}
/**
* Rehash both hash functions and rebuild table. This is done when a maximum
* limit of steps has been reached. int nRehashes,
*
* @param nRehashes
* @param k
* table[tableNumber][i] = -1; this is the last key that needs to be
* re-inserted
*/
public void rehash() {
if (nRehashes >= maxRehashes)
return;
// Keep track of rehashes
nRehashes++;
// Init new hash functions
for (int hash = 0; hash < 2; hash++)
hashFuncs[hash] = hashFuncs[hash].rehash();
// Check tables and if keys are no in correct places the
// reinsert
for (int tableNumber = 0; tableNumber < 2; tableNumber++) {
for (int i = 0; i < m / 2; i++) { // init array
long k = table[tableNumber][i];
if (k != -1 && !find(k)) {
table[tableNumber][i] = -1;
put(k);
}
}
}
}
/**
* Find a given key in one of its two positions.
*
* @param k
* key
* @param j
* hashed index or
* @return i index or -1 if not found
*/
@Override
public boolean find(long k) {
return (table[0][(int) hashFuncs[0].hash(k)] == k || table[1][(int) hashFuncs[1].hash(k)] == k);
}
public long steps() {
return steps;
}
public long getNRehashes() {
return nRehashes;
}
public void resetSteps() {
steps = 0;
}
public void print() {
System.out.println("printing table a");
for (int i = 0; i < m / 2; i++)
System.out.print(table[0][i] + " ");
System.out.println();
System.out.println("printing table b");
for (int i = 0; i < m / 2; i++)
System.out.print(table[1][i] + " ");
System.out.println();
}
/**
* Deep copy a table (used to backup and restore to another state)
*
* @param src
* @return new table
*/
public long[][] deepCopyHashTable(long[][] src) {
long[][] newTable = new long[2][];
// Copy first table to temp set
for (int tableX = 0; tableX < 2; tableX++) {
long[] keys = new long[(int) m / 2];
for (int i = 0; i < m / 2; i++)
keys[i] = src[tableX][i];
newTable[tableX] = keys;
}
return newTable;
}
public static void main(String[] args) {
// Unit tests
int w = 32; // 32-bit unsigned
long MAX_U32 = (2L << 32 - 1) - 1; // universe, here 2^32-1 bits
int l = 3; // bits, m=2^l
long m = 2L << l - 1; // size of table, here 2^20-1 bits
System.out.println("size of table =" + m);
// Init random generator (my class not java.util)
RandGenerator rand = new RandGenerator(0, MAX_U32);
Hash hashA, hashB; // two hash funcs for table
long key;
// Cuckoo with mult shift
// hashA = new MultShiftHash(w, l - 1); // init hash function with w-bit output
// hashB = new MultShiftHash(w, l - 1); // init hash function with w-bit output
hashA = new TabularHash(w, m / 2);
hashB = new TabularHash(w, m / 2);
// long maxSwaps = Hash.log2(m);
long maxSwaps = 6*l;
CuckooHT ht = new CuckooHT(m, hashA, hashB, maxSwaps);
// System.out.println("inserting");
for (int j = 0; j < m; j++) {
key = rand.nextLong(); // generate random element
// System.out.println("inserting " + key);
boolean idx = ht.insert(key);
if (!idx)
System.out.println("failed insert with rehashes for key " + key);
}
System.out.println("printing table a");
for (int i = 0; i < m / 2; i++)
System.out.println(ht.table[0][i]);
System.out.println("printing table b");
for (int i = 0; i < m / 2; i++)
System.out.println(ht.table[1][i]);
}
}
|
package com.company;
import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.stream.Collectors;
public class DataReadWrite {
public static String dataReader(String path){
if(path == "No file selected"){ System.exit(0);}
File data = new File(path);
try{
BufferedReader getData = new BufferedReader(new FileReader(data));
String dataString = getData.lines().collect(Collectors.joining());
getData.close();
return dataString;
} catch(FileNotFoundException e ){
System.out.println("Couldn't find the file");
System.exit(0);
} catch (IOException e) {
System.out.println("An I/O Error Occurred");
System.exit(0);
}
return null;
}
public static PrintWriter dataWriter(String path){
File data = new File(path);
try{
PrintWriter infoToWrite = new PrintWriter(new BufferedWriter(new FileWriter(data)));
return infoToWrite;
} catch (IOException e) {
System.out.println("An I/O Error Occurred");
System.exit(0);
}
return null;
}
}
|
package com.weili.dao;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import com.shove.data.DataException;
import com.shove.data.DataSet;
import com.shove.util.BeanMapUtils;
import com.weili.database.Dao;
import com.weili.database.Dao.Tables;
import com.weili.database.Dao.Tables.t_materials_attribute;
public class MaterialsDao {
public long addMaterials(Connection conn,String name,String number,Long productId,String path,String size,Integer sortIndex,Integer status,String seoTitle,String seoKeywords,String seoDescription) throws SQLException{
Dao.Tables.t_materials materials = new Dao().new Tables().new t_materials();
materials._name.setValue(name);
materials.number.setValue(number);
materials.productId.setValue(productId);
materials.path.setValue(path);
materials.size.setValue(size);
materials.sortIndex.setValue(sortIndex);
materials.status.setValue(status);
materials.seoTitle.setValue(seoTitle);
materials.seoKeywords.setValue(seoKeywords);
materials.seoDescription.setValue(seoDescription);
materials.addTime.setValue(new Date());
return materials.insert(conn);
}
public long updateMaterials(Connection conn,long id,String name,String number,Long productId,String path,String size,Integer sortIndex,Integer status,String seoTitle,String seoKeywords,String seoDescription) throws SQLException{
Dao.Tables.t_materials materials = new Dao().new Tables().new t_materials();
if(StringUtils.isNotBlank(name)){
materials._name.setValue(name);
}
if(StringUtils.isNotBlank(number)){
materials.number.setValue(number);
}
if(productId != null&&productId > 0){
materials.productId.setValue(productId);
}
if(StringUtils.isNotBlank(path)){
materials.path.setValue(path);
}
if(StringUtils.isNotBlank(size)){
materials.size.setValue(size);
}
if(sortIndex != null&&sortIndex > 0){
materials.sortIndex.setValue(sortIndex);
}
if(status != null&&status > 0){
materials.status.setValue(status);
}
if(StringUtils.isNotBlank(seoTitle)){
materials.seoTitle.setValue(seoTitle);
}
if(StringUtils.isNotBlank(seoKeywords)){
materials.seoKeywords.setValue(seoKeywords);
}
if(StringUtils.isNotBlank(seoDescription)){
materials.seoDescription.setValue(seoDescription);
}
return materials.update(conn, " id = "+id);
}
public long deleteMaterials(Connection conn,String ids) throws SQLException{
Dao.Tables.t_materials materials = new Dao().new Tables().new t_materials();
return materials.delete(conn, " id in("+ids+") ");
}
public Map<String,String> queryMaterialsById(Connection conn,long id) throws SQLException, DataException{
Dao.Tables.t_materials materials = new Dao().new Tables().new t_materials();
DataSet ds = materials.open(conn, " ", " id = "+id, "", -1, -1);
return BeanMapUtils.dataSetToMap(ds);
}
/////////
public List<Map<String,Object>> queryMaterById(Connection conn,long materialsId) throws SQLException, DataException{
// Dao.Views.v_t_materials_attribute_dateils mate = new Dao().new Views().new v_t_materials_attribute_dateils();
Dao.Tables.t_materials tm = new Dao().new Tables().new t_materials();
DataSet ds = tm.open(conn, " ", " id= "+materialsId, "", -1, -1);
ds.tables.get(0).rows.genRowsMap();
return ds.tables.get(0).rows.rowsMap;
}
public List<Map<String, Object>> queryMaterialsAll(Connection conn,String fieldList,String condition,String order)throws SQLException, DataException {
Dao.Tables.t_materials materials = new Dao().new Tables().new t_materials();
DataSet ds = materials.open(conn, fieldList, condition,order, -1, -1);
ds.tables.get(0).rows.genRowsMap();
return ds.tables.get(0).rows.rowsMap;
}
public List<Map<String, Object>> queryAdvertisementAll(Connection conn,String fieldList,String condition,String order)throws SQLException, DataException {
Dao.Tables.t_appadv t_appadv = new Dao().new Tables().new t_appadv();
DataSet ds = t_appadv.open(conn, fieldList, condition,order, -1, -1);
ds.tables.get(0).rows.genRowsMap();
return ds.tables.get(0).rows.rowsMap;
}
}
|
package edu.cmu.lti.oaqa.qa4ds.input;
import com.google.common.base.Predicate;
import edu.cmu.lti.oaqa.qa4ds.types.DecisionConfiguration;
public class MatchesTemplateName implements Predicate<DecisionConfiguration> {
private String templateName;
public MatchesTemplateName(String templateName) {
this.templateName = templateName;
}
@Override
public boolean apply(DecisionConfiguration input) {
return input.getTemplateName().equals(templateName);
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.unisports.rest.controller;
import com.unisports.entities.Sport;
import com.unisports.enums.SportType;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.PathParam;
import javax.ws.rs.POST;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.enterprise.context.RequestScoped;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.codehaus.jackson.map.ObjectMapper;
/**
* REST Web Service
*
* @author koraniar
*/
@Path("/test")
@RequestScoped
public class TestsResource {
@Context
private UriInfo context;
/**
* Creates a new instance of TestsResource
*/
public TestsResource() {
}
/**
* POST method for creating an instance of TestResource
* @param content representation for the new resource
* @return an HTTP response with content of the created resource
*/
@POST
//@Consumes(MediaType.APPLICATION_JSON)
public String postJson(@DefaultValue("default") @QueryParam("user") String user, String sport) {
try {
System.out.println(user);
//TODO
ObjectMapper mapper = new ObjectMapper();
Sport object = mapper.readValue(sport, Sport.class);
if (object != null) {
System.out.println(object.getId().toString());
System.out.println(object.getName());
System.out.println(object.getType().toString());
}else{
System.out.println("error");
}
return "ok ok";
//return Response.ok("{'Message' : 'ok' }").build();
} catch (IOException ex) {
return "ex";
//return Response.ok("{'Message' : 'error' }").build();
}
}
/**
* Sub-resource locator method for {id}
*/
@GET
@Path("{name}")
@Produces(MediaType.APPLICATION_JSON)
public String getTestResource(@PathParam("name") String name) {
//Accepts:
//http://localhost:8080/UnisportsRest/rest/test/hola
Sport sp = new Sport();
sp.setName(name);
sp.setType(SportType.Futbol);
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.writeValueAsString(sp);
//TODO return proper representation object
//throw new UnsupportedOperationException();
} catch (IOException ex) {
return "error";
//Logger.getLogger(TestsResource.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Retrieves representation of an instance of com.unisports.rest.controller.TestsResource
* @return an instance of java.lang.String
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
public String getJson(@DefaultValue("default") @QueryParam("name") String name) {
//Accepts:
//http://localhost:8080/UnisportsRest/rest/test?name=hola
Sport sp = new Sport();
sp.setName(name);
sp.setType(SportType.Futbol);
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.writeValueAsString(sp);
//TODO return proper representation object
//throw new UnsupportedOperationException();
} catch (IOException ex) {
return "error";
//Logger.getLogger(TestsResource.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
|
package com.zxt.framework.jdbc;
public class Configuration {
private String JDBCDriver="";
private String URL="";
private String USER="";
private String PASSWORD="";
/**
* jdbc配置
* @param driver
* @param url
* @param user
* @param pwd
*/
public Configuration(final String driver,final String url,
final String user,final String pwd){
this.JDBCDriver=driver;
this.URL=url;
this.USER=user;
this.PASSWORD=pwd;
}
/**
* jdbc工具类拼接连接信息
* @param ip
* @param port
* @param sid
* @param dbType
* @param username
* @param password
*/
public Configuration(String ip,String port,String sid,String dbType,String username,String password){
String url = "";
String driverName = "";
String dbSid = "";
if(dbType.equals("1")){
url = "jdbc:oracle:thin:@";
driverName = "oracle.jdbc.driver.OracleDriver";
dbSid = ":" + sid;
}else if(dbType.equals("2")){
url = "jdbc:sqlserver://";
driverName = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
dbSid = ";databasename=" + sid;
}else if(dbType.equals("3")){
url = "";
driverName = "";
}
url += ip + ":" + port + dbSid;
this.JDBCDriver = driverName;
this.URL = url;
this.USER = username;
this.PASSWORD = password;
}
public String getJDBCDriver() {
return JDBCDriver;
}
public String getURL() {
return URL;
}
public String getUSER() {
return USER;
}
public String getPASSWORD() {
return PASSWORD;
}
}
|
package com.zhongyp.spring.demo.injection;
public interface Person {
public void useGun();
}
|
/**
*
*/
package com.karya.service.impl;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.karya.dao.ITestCaseDAO;
import com.karya.model.TestCase001MB;
import com.karya.service.ITestCaseService;
/**
* Handles CRUD services for users
*
*/
@Service("TestCaseService")
@Transactional
public class TestCaseService implements ITestCaseService {
@Autowired
private ITestCaseDAO testCaseDAO;
private List<TestCase001MB> dummyUsersList = new ArrayList<TestCase001MB>();
protected static Logger logger = Logger.getLogger("service");
@Override
@Transactional
public List<TestCase001MB> getAll() {
logger.debug("Retrieving all users");
return testCaseDAO.getAll();
}
public TestCase001MB get( String id ) {
logger.debug("Retrieving an existing user");
return dummyUsersList.get( Integer.valueOf(id) );
}
@Override
@Transactional
public Boolean add( TestCase001MB testCase001MB ) {
logger.debug("Adding a new user");
try {
// Assign a new id
testCaseDAO.add(testCase001MB);
return true;
} catch (Exception e) {
return false;
}
}
public Boolean delete( TestCase001MB testCase001MB ) {
logger.debug("Deleting an existing user");
try {
// id to delete
Long id = Long.valueOf( testCase001MB.getId().toString() );
testCaseDAO.delete(id);
return true;
} catch (Exception e) {
return false;
}
}
public Boolean edit( TestCase001MB testCase001MB ) {
logger.debug("Editing an existing user");
try {
testCaseDAO.edit(testCase001MB);
return true;
} catch (Exception e) {
return false;
}
}
}
|
/*
* 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 byui.cit260.LehisDream.view;
/**
*
* @author fairy_000
*/
public class SwordView extends View {
public SwordView(){
super("\n You have chosen to active your Sword. "
+"\n Enter Y for yes or N for no");
}
@Override
public boolean doAction(String choice) {
choice = choice.toUpperCase(); // convert choice to upper case
switch (choice) {
case "Y":
this.console.println("You have chosen to use the Sword. This will help you in your battle."
+ " You will lose less energy with the Sword.");
break;
case "N":
this.console.println("You chose No");
break;
default:
ErrorView.display(this.getClass().getName(),"\n*** Invalid selection *** Try again");
break;
}
return false;
}
}
|
package com.example.placesdemo;
import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.example.placesdemo.databinding.PlaceIsOpenActivityBinding;
import com.google.android.gms.tasks.Task;
import com.google.android.libraries.places.api.Places;
import com.google.android.libraries.places.api.model.Place;
import com.google.android.libraries.places.api.model.Place.Field;
import com.google.android.libraries.places.api.net.FetchPlaceRequest;
import com.google.android.libraries.places.api.net.FetchPlaceResponse;
import com.google.android.libraries.places.api.net.IsOpenRequest;
import com.google.android.libraries.places.api.net.IsOpenResponse;
import com.google.android.libraries.places.api.net.PlacesClient;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
/**
* Activity to demonstrate {@link PlacesClient#isOpen(IsOpenRequest)}.
*/
public class PlaceIsOpenActivity extends AppCompatActivity {
private final String defaultTimeZone = "America/Los_Angeles";
@NonNull
private Calendar isOpenCalendar = Calendar.getInstance();
private PlaceIsOpenActivityBinding binding;
private FieldSelector fieldSelector;
private PlacesClient placesClient;
private Place place;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = PlaceIsOpenActivityBinding.inflate(getLayoutInflater());
View rootView = binding.getRoot();
setContentView(rootView);
// Retrieve a PlacesClient (previously initialized - see MainActivity)
placesClient = Places.createClient(/* context= */ this);
fieldSelector =
new FieldSelector(
binding.checkBoxUseCustomFields,
binding.textViewCustomFieldsList,
savedInstanceState);
binding.buttonFetchPlace.setOnClickListener(view -> fetchPlace());
binding.buttonIsOpen.setOnClickListener(view -> isOpenByPlaceId());
isOpenCalendar = Calendar.getInstance(TimeZone.getTimeZone(defaultTimeZone));
// UI initialization
setLoading(false);
initializeSpinnerAndAddListener();
addIsOpenDateSelectionListener();
addIsOpenTimeSelectionListener();
updateIsOpenDate();
updateIsOpenTime();
}
@Override
protected void onSaveInstanceState(@NonNull Bundle bundle) {
super.onSaveInstanceState(bundle);
fieldSelector.onSaveInstanceState(bundle);
}
/**
* Get details about the Place ID listed in the input field, then check if the Place is open.
*/
private void fetchPlace() {
clearViews();
dismissKeyboard(binding.editTextPlaceId);
setLoading(true);
List<Field> placeFields = getPlaceFields();
FetchPlaceRequest request = FetchPlaceRequest.newInstance(getPlaceId(), placeFields);
Task<FetchPlaceResponse> placeTask = placesClient.fetchPlace(request);
placeTask.addOnSuccessListener(
(response) -> {
place = response.getPlace();
isOpenByPlaceObject(place);
});
placeTask.addOnFailureListener(
(exception) -> {
exception.printStackTrace();
binding.textViewResponse.setText(exception.getMessage());
});
placeTask.addOnCompleteListener(response -> setLoading(false));
}
/**
* Check if the place is open at the time specified in the input fields.
* Requires a Place object that includes Place.Field.ID
*/
@SuppressLint("SetTextI18n")
private void isOpenByPlaceObject(Place place) {
clearViews();
dismissKeyboard(binding.editTextPlaceId);
setLoading(true);
IsOpenRequest request;
try {
request = IsOpenRequest.newInstance(place, isOpenCalendar.getTimeInMillis());
} catch (IllegalArgumentException e) {
e.printStackTrace();
binding.textViewResponse.setText(e.getMessage());
setLoading(false);
return;
}
Task<IsOpenResponse> placeTask = placesClient.isOpen(request);
placeTask.addOnSuccessListener(
(response) -> binding.textViewResponse.setText("Is place open? "
+ response.isOpen()
+ "\nExtra place details: \n"
+ StringUtil.stringify(place)));
placeTask.addOnFailureListener(
(exception) -> {
exception.printStackTrace();
binding.textViewResponse.setText(exception.getMessage());
});
placeTask.addOnCompleteListener(response -> setLoading(false));
}
/**
* Check if the place is open at the time specified in the input fields.
* Use the Place ID in the input field for the isOpenRequest.
*/
@SuppressLint("SetTextI18n")
private void isOpenByPlaceId() {
clearViews();
dismissKeyboard(binding.editTextPlaceId);
setLoading(true);
IsOpenRequest request;
try {
request = IsOpenRequest.newInstance(getPlaceId(), isOpenCalendar.getTimeInMillis());
} catch (IllegalArgumentException e) {
e.printStackTrace();
binding.textViewResponse.setText(e.getMessage());
setLoading(false);
return;
}
Task<IsOpenResponse> placeTask = placesClient.isOpen(request);
placeTask.addOnSuccessListener(
(response) -> binding.textViewResponse.setText("Is place open? " + response.isOpen()));
placeTask.addOnFailureListener(
(exception) -> {
exception.printStackTrace();
binding.textViewResponse.setText(exception.getMessage());
});
placeTask.addOnCompleteListener(response -> setLoading(false));
}
//////////////////////////
// Helper methods below //
//////////////////////////
private void dismissKeyboard(EditText focusedEditText) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(focusedEditText.getWindowToken(), 0);
}
private String getPlaceId() {
return ((TextView) binding.editTextPlaceId).getText().toString();
}
/**
* Fetch the fields necessary for an isOpen request, unless user has checked the box to
* select a custom list of fields. Also fetches name and address for display text.
*/
private List<Field> getPlaceFields() {
if (((CheckBox) binding.checkBoxUseCustomFields).isChecked()) {
return fieldSelector.getSelectedFields();
} else {
return new ArrayList<>(Arrays.asList(
Field.ADDRESS,
Field.BUSINESS_STATUS,
Field.CURRENT_OPENING_HOURS,
Field.ID,
Field.NAME,
Field.OPENING_HOURS,
Field.UTC_OFFSET
));
}
}
private void setLoading(boolean loading) {
binding.progressBarLoading.setVisibility(loading ? View.VISIBLE : View.INVISIBLE);
}
private void clearViews() {
binding.textViewResponse.setText(null);
}
private void initializeSpinnerAndAddListener() {
ArrayAdapter<String> adapter =
new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, TimeZone.getAvailableIDs());
binding.spinnerTimeZones.setAdapter(adapter);
binding.spinnerTimeZones.setSelection(adapter.getPosition(defaultTimeZone));
binding.spinnerTimeZones.setOnItemSelectedListener(
new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String timeZone = parent.getItemAtPosition(position).toString();
isOpenCalendar.setTimeZone(TimeZone.getTimeZone(timeZone));
updateIsOpenDate();
updateIsOpenTime();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
private void addIsOpenDateSelectionListener() {
DatePickerDialog.OnDateSetListener listener =
(view, year, month, day) -> {
isOpenCalendar.set(Calendar.YEAR, year);
isOpenCalendar.set(Calendar.MONTH, month);
isOpenCalendar.set(Calendar.DAY_OF_MONTH, day);
updateIsOpenDate();
};
binding.editTextIsOpenDate.setOnClickListener(
view -> new DatePickerDialog(
PlaceIsOpenActivity.this,
listener,
isOpenCalendar.get(Calendar.YEAR),
isOpenCalendar.get(Calendar.MONTH),
isOpenCalendar.get(Calendar.DAY_OF_MONTH))
.show());
}
private void updateIsOpenDate() {
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yy", Locale.US);
binding.editTextIsOpenDate.setText(dateFormat.format(isOpenCalendar.getTime()));
}
private void addIsOpenTimeSelectionListener() {
TimePickerDialog.OnTimeSetListener listener =
(view, hourOfDay, minute) -> {
isOpenCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
isOpenCalendar.set(Calendar.MINUTE, minute);
updateIsOpenTime();
};
binding.editTextIsOpenTime.setOnClickListener(
view -> new TimePickerDialog(
PlaceIsOpenActivity.this,
listener,
isOpenCalendar.get(Calendar.HOUR_OF_DAY),
isOpenCalendar.get(Calendar.MINUTE),
true)
.show());
}
private void updateIsOpenTime() {
String formattedHour =
String.format(Locale.getDefault(), "%02d", isOpenCalendar.get(Calendar.HOUR_OF_DAY));
String formattedMinutes =
String.format(Locale.getDefault(), "%02d", isOpenCalendar.get(Calendar.MINUTE));
binding.editTextIsOpenTime.setText(
String.format(Locale.getDefault(), "%s:%s", formattedHour, formattedMinutes));
}
} |
package com.lesports.albatross.custom.dialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.lesports.albatross.R;
/**
* Created by zhouchenbin on 16/6/24.
*/
public class ConfirmDialog extends Dialog implements View.OnClickListener {
private View.OnClickListener listener;
private String title;
private String content;
public ConfirmDialog(Context context, String title, String content, View.OnClickListener listener) {
super(context, R.style.RssDialog);
this.listener = listener;
this.title = title;
this.content = content;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rss_dialog);
TextView titleText = (TextView) findViewById(R.id.dialog_title);
titleText.setText(title);
TextView contentText = (TextView) findViewById(R.id.dialog_content);
contentText.setText(content);
Button confirm = (Button) findViewById(R.id.btn_ok);
Button cancel = (Button) findViewById(R.id.btn_cancel);
confirm.setOnClickListener(this);
cancel.setOnClickListener(this);
}
@Override
public void onClick(View v) {
listener.onClick(v);
dismiss();
}
}
|
package HelloWorldUI;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
public class MainViewModel {
// http://openbook.rheinwerk-verlag.de/javainsel/12_004.html
private final StringProperty input = new SimpleStringProperty("");
private final StringProperty output = new SimpleStringProperty("Hello VM!");
private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);
public StringProperty inputProperty() {
System.out.println("VM: get input prop");
return input;
}
public StringProperty outputProperty() {
System.out.println("VM: get output prop");
return output;
}
public void calculateOutputString() {
System.out.println("VM: calculate Output");
this.output.set("Hello ".concat(this.input.get()).concat("!"));
this.input.set("");
this.propertyChangeSupport.firePropertyChange("RequiresPropertyChange", false, true);
}
public void addPropertyChangeListener(PropertyChangeListener pcl) {
propertyChangeSupport.addPropertyChangeListener(pcl);
}
public void removePropertyChangeListener(PropertyChangeListener pcl) {
propertyChangeSupport.removePropertyChangeListener(pcl);
}
}
|
package ru.intcode.repostme.webapp.logic;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.sql2o.Connection;
public class Offer {
private long id;
private String name;
private String description;
private String fullDescription;
private String vkDescription;
private double discFrom;
private double discTo;
private long amount;
private String pic;
private int kuponAmount;
private long aid;
private Timestamp untill;
private long catId;
public long getId() {
return id;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public String getFullDescription() {
return fullDescription;
}
public double getDiscFrom() {
return discFrom;
}
public double getDiscTo() {
return discTo;
}
public long getAmount() {
return amount;
}
public String getPic() {
return pic;
}
public int getKuponAmount() {
return kuponAmount;
}
public long getAid() {
return aid;
}
public Timestamp getUntill() {
return untill;
}
public long getCatId() {
return catId;
}
public String getVkDescription() {
return vkDescription;
}
public void setName(String name) {
this.name = name;
}
public void setDescription(String description) {
this.description = description;
}
public void setFullDescription(String fullDescription) {
this.fullDescription = fullDescription;
}
public void setDiscFrom(double discFrom) {
this.discFrom = discFrom;
}
public void setDiscTo(double discTo) {
this.discTo = discTo;
}
public void setAmount(long amount) {
this.amount = amount;
}
public void setPic(String pic) {
this.pic = pic;
}
public void setKuponAmount(int kuponAmount) {
this.kuponAmount = kuponAmount;
}
public void setAid(long aid) {
this.aid = aid;
}
public void setUntill(Timestamp untill) {
this.untill = untill;
}
public void setCatId(long catId) {
this.catId = catId;
}
public void setVkDescription(String vkDescription) {
this.vkDescription = vkDescription;
}
public static final String selectByIdQuery
= "SELECT * FROM offers WHERE id = :id;";
public static final String selectAllQuery
= "SELECT * FROM offers;";
public static final String selectAllByCatQuery
= "SELECT * FROM offers WHERE catId = :catId";
public static Offer selectById(Database db, long id) {
try (Connection c = db.getSql2o().open()) {
return c.createQuery(selectByIdQuery).addParameter("id", id).executeAndFetchFirst(Offer.class);
}
}
public static Map<Category, List<Offer>> selectAll(Database db) {
Map<Category, List<Offer>> map = new HashMap<>();
try (Connection c = db.getSql2o().open()) {
List<Category> cats = c.createQuery(Category.selectAllQuery).executeAndFetch(Category.class);
for (Category cat : cats) {
List<Offer> offers = c.createQuery(Offer.selectAllByCatQuery).addParameter("catId", cat.getId()).executeAndFetch(Offer.class);
if (!offers.isEmpty()) {
map.put(cat, offers);
}
}
}
return map;
}
public static Map<Category, List<Offer>> selectAllByCat(Database db, Category category) {
Map<Category, List<Offer>> map = new HashMap<>();
try (Connection c = db.getSql2o().open()) {
List<Category> cats = Arrays.asList(category);
for (Category cat : cats) {
List<Offer> offers = c.createQuery(Offer.selectAllByCatQuery).addParameter("catId", cat.getId()).executeAndFetch(Offer.class);
if (!offers.isEmpty()) {
map.put(cat, offers);
}
}
}
return map;
}
}
|
package com.xtruong.petapp.ui.recyclerview;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import com.xtruong.petapp.R;
import com.xtruong.petapp.data.db.model.recyclerview.Contact;
import java.util.ArrayList;
/**
* Created by truongtx on 7/26/2019
*
* 1. Add RecyclerView support library to the Gradle build file
* 2. Define a model class to use as the data source
* 3. Add a RecyclerView to your activity to display the items
* 4. Create a custom row layout XML file to visualize the item
* 5. Create a RecyclerView.Adapter and ViewHolder to render the item
* 6. Bind the adapter to the data source to populate the RecyclerView
*/
public class UserListActivity extends AppCompatActivity {
ArrayList<Contact> contacts;
//private UserListActivityBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_recycler_users);
// Lookup the recyclerview in activity layout
RecyclerView rvContacts = (RecyclerView) findViewById(R.id.rvContacts);
// Initialize contacts
contacts = Contact.createContactsList(20);
// Create adapter passing in the sample user data
ContactsAdapter adapter = new ContactsAdapter(contacts);
// Attach the adapter to the recyclerview to populate items
rvContacts.setAdapter(adapter);
// Set layout manager to position the items
rvContacts.setLayoutManager(new LinearLayoutManager(this));
// That's all!
}
}
|
/*
* 2010-2017 (C) Antonio Redondo
* http://antonioredondo.com
* http://github.com/AntonioRedondo/AnotherMonitor
*
* Code under the terms of the GNU General Public License v3.
*
*/
package com.example.shreysindher.procspy;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.LinearLayout;
public class LinearLayoutCustomised extends LinearLayout {
private boolean touchEventsDisabled = true;
// public LinearLayoutCustomised(Context context) {
// super(context);
// }
public LinearLayoutCustomised(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return touchEventsDisabled;
}
public void interceptChildTouchEvents(boolean b) {
touchEventsDisabled = b;
}
}
|
package sql;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
public class Turns {
private int turn;
private int populationNumber;
private int SimulationId;
private int populationId;
/**
* @return the turn
*/
public int getTurn() {
return turn;
}
/**
* @param turn the turn to set
*/
public void setTurn(int turn) {
this.turn = turn;
}
/**
* @return the idSimu
*/
public int getSimulationId() {
return SimulationId;
}
/**
* @param simulationId the idSimu to set
*/
public void setSimulationId(int simulationId) {
this.SimulationId = simulationId;
}
/**
* @return the nbPop
*/
public int getPopulationNumber() {
return populationNumber;
}
/**
* @param populationNumber the nbPop to set
*/
public void setPopulationNumber(int populationNumber) {
this.populationNumber = populationNumber;
}
/**
* @return the idPop
*/
public int getPopulationId() {
return populationId;
}
/**
* @param populationId the idPop to set
*/
public void setpopulationId(int populationId) {
this.populationId = populationId;
}
/**
* Permet de retourner le nombre de tours et les différentes populations comprise dans la simulation
*
* @return String[][] getRestrictedTurnPopulation(ArrayList<String>, ArrayList<String>)
*/
public String[][] getNumberTurnPopulation() {
ArrayList<String> numberTurn = new ArrayList<String>();
ArrayList<String> population = new ArrayList<String>();
try {
Connection cn = DriverManager.getConnection(
"jdbc:mysql://localhost/algo?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC",
"root", "root");
Statement st = cn.createStatement();
ResultSet rs = st.executeQuery("CALL affPopSim('" + getSimulationId() + "')");
while (rs.next()) {
numberTurn.add(rs.getString(1));
population.add(rs.getString(2));
}
} catch (SQLException e) {
System.out.println(e);
}
return getRestrictedTurnPopulation(numberTurn, population);
}
/**
* Permet de retourner le nombre de tours et les différentes populations comprise dans la simulation
* en enlevant les doublons
*
* @return String[][] viewArraySimulation(ArrayList<String> ArrayList<String>)
*/
public String[][] getRestrictedTurnPopulation(ArrayList<String> inNumberTurn, ArrayList<String> inPopulation) {
ArrayList<String> numberTurn = new ArrayList<String>();
ArrayList<String> population = new ArrayList<String>();
for (int i = 0; i < inNumberTurn.size(); i++) {
if (!numberTurn.contains(inNumberTurn.get(i))) {
numberTurn.add(inNumberTurn.get(i));
}
}
for (int i = 0; i < inPopulation.size(); i++) {
if (!population.contains(inPopulation.get(i))) {
population.add(inPopulation.get(i));
}
}
return viewArraySimulation(numberTurn, population);
}
/**
* Permet de retourner le tableau général d'une simulation
*
* @return String[][] tab
*/
public String[][] viewArraySimulation(ArrayList<String> inNumberTurn, ArrayList<String> inPopulation){
String[][] tab = new String[inNumberTurn.size()+1][inPopulation.size()+1];
int numberPopulationLength = tab.length;
int numberTurnLength = tab[0].length;
for (int line = 0; line<numberPopulationLength; line++)
{
for(int column = 0 ; column<numberTurnLength ; column++)
{
if(line==0 && column==0)
{
tab[line][column] = " ";
}
else if(line==0)
{
tab[line][column] = inPopulation.get(column-1);
}
else if(column==0)
{
tab[line][column] = inNumberTurn.get(line-1);
}
else
{
try {
Connection cn = DriverManager.getConnection(
"jdbc:mysql://localhost/algo?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC",
"root", "root");
Statement st = cn.createStatement();
ResultSet rs = st.executeQuery("CALL AffPopQu('" + inNumberTurn.get(line-1) +"','"
+ inPopulation.get(column-1) +"')");
while (rs.next()){
tab[line][column] = rs.getString(1);
}
}
catch (SQLException e) {
System.out.println(e);
}
}
}
}
for (int line = 0; line<numberPopulationLength; line++)
{
for(int column = 0 ; column<numberTurnLength ; column++)
{
System.out.print(tab[line][column] + " ");
}
System.out.println();
}
return tab;
}
/**
* Permet de placer dans la base de donnée un nouveau tour et l'aspect de la
* simulation
*
* @return String = réussi
*/
public String setPopulationTurn() {
try {
Connection cn = DriverManager.getConnection(
"jdbc:mysql://localhost/algo?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC",
"root", "root");
Statement st = cn.createStatement();
st.executeUpdate("CALL insertPopSim ('" + getPopulationNumber() + "','" + getPopulationId() + "','" + getTurn() + "','"
+ getSimulationId() + "')");
} catch (SQLException e) {
System.out.println(e);
}
return "réussi";
}
/**
* Permet de savoi si un tours existe dans la base de donnée
*
* @return String = réussi
*/
public boolean tryTurn() {
try {
int s = 0;
Connection cn = DriverManager.getConnection(
"jdbc:mysql://localhost/algo?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC",
"root", "root");
Statement st = cn.createStatement();
ResultSet rs = st.executeQuery("SELECT idSimulationTurn FROM simulationturn WHERE turn=" + getTurn()
+ " AND idSimulation = " + getSimulationId() + "");
while (rs.next()) {
s++;
}
if (s < 1) {
st.executeUpdate("INSERT INTO `simulationturn`(`turn`, `idSimulation`) VALUES ('" + getTurn() + "','"
+ getSimulationId() + "');");
}
} catch (SQLException e) {
System.out.println(e);
return false;
}
return true;
}
/**
* Permet de placer dans la base de donnée un nouveau tour si il n'existe pas, et d'ajouter une population
* avec son nombre de popuation
*
* @return String = réussi
*/
public void uploadPopulationTurn(int simulationTurn, String population, int populationNumber, String simulation) {
setPopulationNumber(populationNumber);
Simulation s = new Simulation();
int SimulationId = s.viewSimulationId(simulation);
Population p = new Population();
int populationId = p.viewPopulationId(population);
setpopulationId(populationId);
setTurn(simulationTurn);
setSimulationId(SimulationId);
tryTurn();
setPopulationTurn();
}
/**
* Permet d'afficher un tableau de toute la simuation
*
* @return String = réussi
*/
public void viewPopulationSimulation(String simulation) {
Simulation s = new Simulation();
int simulationId = s.viewSimulationId(simulation);
setSimulationId(simulationId);
getNumberTurnPopulation();
}
}
|
package edu.lewis.ap.britt.emory;
import edu.jenks.dist.lewis.ap.AbstractName;
public class Name extends AbstractName {
public Name(String firstName, String lastName) {
super(firstName, lastName);
}
public int compareTo(AbstractName arg0) {
String fName = this.getFirst();
String lName = this.getLast();
String compareFName = arg0.getFirst();
String compareLName = arg0.getLast();
if(lName.equals(compareLName)){
if(fName.equals(compareFName)){
setDuplicates(getDuplicates() + 1);
return 0;
}
int returnVal = fName.compareTo(compareFName);
return returnVal;
}
int returnVal = lName.compareTo(compareLName);
return returnVal;
}
public String toString() {
String fName = this.getFirst();
String lName = this.getLast();
return lName + ", " + fName;
}
}
|
package agh.musicapplication.mappdao;
import agh.musicapplication.mappdao.interfaces.MAlbumRepositoryInterface;
import agh.musicapplication.mappdao.interfaces.MAlbumSongRepositoryInterface;
import agh.musicapplication.mappmodel.MAlbum;
import agh.musicapplication.mappmodel.MAlbumSong;
import agh.musicapplication.mappmodel.MBand;
import agh.musicapplication.mappmodel.MSong;
import java.io.Serializable;
import java.util.List;
import org.hibernate.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
/**
*
* @author Agata
*/
@Repository
@Transactional
public class MAlbumSongRepository extends AbstractCrudRepository<MAlbumSong> implements Serializable,MAlbumSongRepositoryInterface {
@Override
public MAlbumSong getMAlbumSongWithSomeAlbumNameAndSongName(MAlbum a, MSong s){
Query query = getSession().createQuery("from MAlbumSong where album = :album and song = :song");
query.setParameter("album", a);
query.setParameter("song", s);
return (MAlbumSong) query.uniqueResult();
}
@Override
public List<MSong> getAllSongsOfSomeAlbum(MAlbum album) {
Query query = getSession().createQuery("select m.song from MAlbumSong m where m.album = :album");
query.setParameter("album", album);
return (List<MSong>) query.list();
}
}
|
package com.hiplatform.teste.hipermercadohi;
/**
*
* @author Jose
*/
public class Main {
public static void main(String[] args) {
TipoItem tipo;
double custo = 100;
int validade = 30;
double preco;
tipo = TipoItem.VERDURAS;
HiperMercado.Hi.escolheTipoItem(tipo);
preco = HiperMercado.Hi.formulaMagica(custo, validade);
System.out.println("O preço do item tipo " + tipo.name() + " é R$ " + preco);
System.out.println();
tipo = TipoItem.CARNES;
HiperMercado.Hi.escolheTipoItem(tipo);
preco = HiperMercado.Hi.formulaMagica(custo, validade);
System.out.println("O preço do item tipo " + tipo.name() + " é R$ " + preco);
System.out.println();
tipo = TipoItem.ELETRODOMESTICOS;
HiperMercado.Hi.escolheTipoItem(tipo);
preco = HiperMercado.Hi.formulaMagica(custo, validade);
System.out.println("O preço do item tipo " + tipo.name() + " é R$ " + preco);
}
}
|
package com.chisw.timofei.booking.accommodation.data.document.embeddable;
import lombok.Builder;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
/**
* @author timofei.kasianov 10/2/18
*/
@RequiredArgsConstructor
@Getter
@Builder
public class Address {
private final String country;
private final String city;
private final String line1;
private final String line2;
}
|
package com.clever.presenter;
/**
* 注册控制类
*
* @author liuhea
* @date 2016-12-30</p>
*/
public interface RegisterPresenter {
void registerUser(String username, String password);
}
|
package com.cy.service.user.impl;
import javax.persistence.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.cy.bean.user.Users;
import com.cy.service.base.DAOSupport;
import com.cy.service.user.UsersService;
import com.cy.utils.MD5;
/**
* Users接口实现类
* @author CY
*
*/
@Service
@Transactional
public class UsersServiceBean extends DAOSupport<Users> implements UsersService {
@Override
public Users login(Users users) {
String jql = "select o from Users o where o.username = ?1";
Query query = em.createQuery(jql);
query.setParameter(1, users.getUsername());
Users user = (Users) query.getSingleResult();
if(user != null && user.getPassword().equals(MD5.MD5Encode(users.getPassword()))) {
return user;
}
return null;
}
}
|
package org.smp.test;
import com.jme3.app.Application;
import com.jme3.app.SimpleApplication;
import com.jme3.app.state.BaseAppState;
import com.jme3.font.BitmapFont;
import com.jme3.font.BitmapText;
import com.jme3.input.KeyInput;
import com.jme3.input.controls.ActionListener;
import com.jme3.input.controls.KeyTrigger;
import com.jme3.math.ColorRGBA;
import com.jme3.renderer.RenderManager;
import com.jme3.scene.Node;
import org.smp.player.SimpleMediaPlayer;
/**
* Test to show how to use MediaPlayer as intro or cutscene/outro.
*/
public class IntroStateTest extends SimpleApplication {
//Main player
SimpleMediaPlayer mediaPlayer;
//Initial intro state - generated by mediaplayer
BaseAppState introState;
//State shown after the intro
MenuState menuState;
//Listener for breaking the intro with keys
ActionListener breakListener;
public static void main(String[] args) {
IntroStateTest app = new IntroStateTest();
app.start();
}
@Override
public void simpleInitApp() {
setDisplayStatView(false);
//setDisplayFps(false);
//Init player
mediaPlayer=new SimpleMediaPlayer(this);
//Config
//Node to add the geometry to. It gets self attached and dettached on enable/disable
Node guiNode=getGuiNode();
//Original movie dimentions - relevant only for keeping aspect ratio
int movieWidth=960;
int movieHeight=540;
//True if aspect ratio should be kept. False is the movie should be stretched to the screen
boolean keepAspect=true;
//Unique name
String screenName="Intro";
//Image to display when player is idle. Null to use screenColor
String idleImageAssetPath="Textures/idleImageAssetPath.jpg";
//Image to display when player is loading. Null to use screenColor
String loadingImageAssetPath="Textures/loadingImageAssetPath.jpg";
//Image to display when player is paused. Null to last frame
String pausedImageAssetPath="Textures/pausedImageAssetPath.jpg";
//Color to use if above pictures are not provided.
ColorRGBA screenColor=ColorRGBA.Black;
//Video to play. Must not be null
String videoAssetPath="Media/960_540.mjpg";
//Audio to play. Null if no audio
String audioAssetPath="Media/audio.ogg";
//Source FPS. Should be consistent with original FPS. In most cases 25 or 30
int framesPerSec=30;
//Playback mode. Play once or loop
int playBackMode=SimpleMediaPlayer.PB_MODE_ONCE;
//Transparency of the screen. 1 for intro, material and menu geometries. Below 1 for HUD geometries
float alpha=1f;
//Generate state
introState=mediaPlayer.genState(guiNode, movieWidth, movieHeight, keepAspect,screenName, idleImageAssetPath, loadingImageAssetPath, pausedImageAssetPath,screenColor,videoAssetPath,audioAssetPath, framesPerSec, playBackMode,alpha );
//Add intro state. Auto load and play video on enabled
stateManager.attach(introState);
//Listener to chain next (menu)state. On end switches states
mediaPlayer.setListener(new SimpleMediaPlayer.VideoScreenListener() {
@Override
public void onPreLoad(String screenName) {
System.out.println("Media event: onPreLoad by "+screenName);
}
@Override
public void onLoaded(String screenName) {
System.out.println("Media event: onLoaded by "+screenName);
}
@Override
public void onPrePlay(String screenName) {
System.out.println("Media event: onPrePlay by "+screenName);
}
@Override
public void onLoopEnd(String screenName) {
System.out.println("Media event: onLoopEnd by "+screenName);
}
@Override
public void onEnd(String screenName) {
System.out.println("Media event: onEnd by "+screenName);
//
inputManager.deleteMapping("StopBySpace");
inputManager.deleteMapping("StopByEnter");
inputManager.removeListener(breakListener );
//
//
switchFromIntroToMenu();
}
});
//Key listener to stop the intro in the course of playback. Calls onEnd and switches to menu
breakListener=new ActionListener(){
@Override
public void onAction(String name, boolean isPressed, float tpf) {
mediaPlayer.stopMedia();
}
};
inputManager.addMapping("StopBySpace", new KeyTrigger(KeyInput.KEY_SPACE));
inputManager.addMapping("StopByEnter", new KeyTrigger(KeyInput.KEY_RETURN));
inputManager.addListener(breakListener, new String[]{"StopBySpace"});
inputManager.addListener(breakListener, new String[]{"StopByEnter"});
//Menu state - switched after intro. Initially detached. Attached on movie end
menuState = new MenuState(guiNode);
}
/**
*Method to switch between player and other screen/state. If BaseAppState is not used attach and dettach instead of enable/disable
*/
void switchFromIntroToMenu()
{
stateManager.detach(introState);
stateManager.attach(menuState);
}
@Override
public void simpleUpdate(float tpf) {
//!!!!!!!!!!IMPORTANT
mediaPlayer.update(tpf);
}
@Override
public void simpleRender(RenderManager rm) {
//TODO: add render code
}
//Fake state representing main menu
class MenuState extends BaseAppState
{
Node guiNode;
BitmapText hintText ;
MenuState( Node guiNode)
{
this.guiNode=guiNode;
BitmapFont font = getAssetManager().loadFont("Interface/Fonts/Default.fnt");
//Hint
hintText = new BitmapText(font);
hintText.setSize(font.getCharSet().getRenderedSize()*3.0f);
hintText.setColor(ColorRGBA.Red);
hintText.setText("MAIN MENU STATE" );
hintText.setLocalTranslation(20, 400, 1.0f);
hintText.updateGeometricState();
}
@Override
protected void initialize(Application app) {
}
@Override
protected void cleanup(Application app) {
}
@Override
protected void onEnable() {
guiNode.attachChild(hintText);
}
@Override
protected void onDisable() {
guiNode.detachChild(hintText);
}
};
}
|
package com.mkdutton.labfive.fragments;
import android.app.Fragment;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.mkdutton.labfive.DetailsActivity;
import com.mkdutton.labfive.FormActivity;
import com.mkdutton.labfive.MainActivity;
import com.mkdutton.labfive.MarkerViewAdapter;
import com.mkdutton.labfive.SavedLocation;
import java.util.ArrayList;
/**
* A simple {@link Fragment} subclass.
*
*/
public class GoogleMapsFragment extends MapFragment implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener, GoogleMap.OnMapLongClickListener,
GoogleMap.OnInfoWindowClickListener{
public static final String TAG = "GOOGLE_MAP_FRAGMENT";
public static final String EXTRA_DETAILS = "com.mkdutton.labfive.EXTRA_DETAILS";
GoogleMap mMap;
LocationClient mLocationClient;
public Location mLocation;
ArrayList<SavedLocation> mLocations;
public static GoogleMapsFragment newInstance(){
return new GoogleMapsFragment();
}
public GoogleMapsFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLocationClient = new LocationClient( getActivity(), this, this );
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mMap = getMap();
mMap.setOnMapLongClickListener(this);
mMap.setOnInfoWindowClickListener(this);
mMap.setMyLocationEnabled(true);
}
@Override
public void onStart() {
super.onStart();
mLocationClient.connect();
}
@Override
public void onResume() {
super.onResume();
}
@Override
public void onStop() {
mLocationClient.disconnect();
super.onStop();
}
@Override
public void onConnected(Bundle bundle) {
mLocation = mLocationClient.getLastLocation();
mMap.animateCamera( CameraUpdateFactory.newLatLngZoom(
new LatLng(mLocation.getLatitude(),mLocation.getLongitude()), 15) );
}
@Override
public void onInfoWindowClick(Marker marker) {
SavedLocation location = null;
double markerLat = marker.getPosition().latitude;
for (SavedLocation loc: mLocations){
if (loc.getmLat() == markerLat){
location = loc;
}
}
Intent detailIntent = new Intent(getActivity(), DetailsActivity.class);
detailIntent.putExtra(EXTRA_DETAILS, location);
startActivity(detailIntent);
}
@Override
public void onMapLongClick(LatLng latLng) {
Intent addPinIntent = new Intent(getActivity(), FormActivity.class);
addPinIntent.putExtra(MainActivity.EXTRA_LOCATION_DATA, latLng);
startActivity(addPinIntent);
}
@Override
public void onDisconnected() {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public void updateMap(ArrayList<SavedLocation> _locations){
mLocations = _locations;
mMap.clear();
MarkerViewAdapter adapter = new MarkerViewAdapter(getActivity(), mLocations);
mMap.setInfoWindowAdapter(adapter);
for (SavedLocation location : _locations){
LatLng pos = new LatLng(location.getmLat(), location.getmLong());
MarkerOptions option = new MarkerOptions();
option.position(pos);
mMap.addMarker(option);
}
}
}
|
package com.wdqsoft.common.config;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
@Configuration
public class MysqlDBConfig {
static final String MAPPER_LOCATION = "classpath*:mapper/mysqldb/*.xml";
static final String TypeAliasesPackage="com.cms.bean";
/**
* 初始化数据库 创建数据源
* @return
*/
@Bean(name = "mysqldbDataSource")
@ConfigurationProperties(prefix = "spring.datasource.mysqldb")
@Primary
public DataSource dataSource(){
return DataSourceBuilder.create().build();
}
/**
* 创建sqlsessionfactory工厂
* @param dataSource
* @return
* @throws Exception
*/
@Bean(name = "mysqldbSqlSessionFactory")
@Primary
public SqlSessionFactory sqlSessionFactory(@Qualifier("mysqldbDataSource") DataSource dataSource) throws Exception{
SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION));
sqlSessionFactoryBean.setTypeAliasesPackage(TypeAliasesPackage);
return sqlSessionFactoryBean.getObject();
}
/**
* 创建事务
* @param dataSource
* @return
* @throws Exception
*/
@Bean(name = "mysqldbDataSourceTransactionManager")
@Primary
public DataSourceTransactionManager dataSourceTransactionManager(
@Qualifier("mysqldbDataSource") DataSource dataSource) throws Exception {
return new DataSourceTransactionManager(dataSource);
}
/**
* 创建模板
*@param sqlSessionFactory
*@return SqlSessionTemplate
*/
@Bean(name = "mysqldbSqlSessionTemplate")
@Primary
public SqlSessionTemplate primarySqlSessionTemplate(@Qualifier("mysqldbSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
|
package dominion.card;
import java.util.*;
import dominion.*;
/**
* Les cartes Réaction
* Rmq: les cartes Réaction sont toutes des cartes Action
*/
public abstract class ReactionCard extends ActionCard {
} |
/*
* Tigase XMPP Client Library
* Copyright (C) 2006-2012 "Bartosz Małkowski" <bartosz.malkowski@tigase.org>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. Look for COPYING file in the top folder.
* If not, see http://www.gnu.org/licenses/.
*/
package tigase.jaxmpp.core.client.xmpp.modules.pubsub;
import tigase.jaxmpp.core.client.AsyncCallback;
import tigase.jaxmpp.core.client.JID;
import tigase.jaxmpp.core.client.PacketWriter;
import tigase.jaxmpp.core.client.SessionObject;
import tigase.jaxmpp.core.client.exceptions.JaxmppException;
import tigase.jaxmpp.core.client.xml.Element;
import tigase.jaxmpp.core.client.xml.XMLException;
import tigase.jaxmpp.core.client.xmpp.forms.JabberDataElement;
import tigase.jaxmpp.core.client.xmpp.stanzas.IQ;
import tigase.jaxmpp.core.client.xmpp.stanzas.StanzaType;
public abstract class FormSubmitter {
protected final JabberDataElement form;
protected final JID serviceJID;
protected final SessionObject sessionObject;
protected final PacketWriter writer;
public FormSubmitter(SessionObject sessionObject, PacketWriter packetWriter, JID serviceJID, JabberDataElement form) {
this.form = form;
this.serviceJID = serviceJID;
this.sessionObject = sessionObject;
this.writer = packetWriter;
}
public JabberDataElement getForm() {
return form;
}
protected abstract Element prepareIqPayload() throws XMLException;
public void submit(final AsyncCallback callback) throws XMLException, JaxmppException {
IQ iq = IQ.create();
iq.setType(StanzaType.set);
iq.setTo(serviceJID);
Element payload = prepareIqPayload();
iq.addChild(payload);
writer.write(iq, callback);
}
} |
package com.myvodafone.android.front.helpers;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Handler;
import android.support.percent.PercentRelativeLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import com.facebook.rebound.SimpleSpringListener;
import com.facebook.rebound.Spring;
import com.facebook.rebound.SpringSystem;
import com.myvodafone.android.R;
import com.myvodafone.android.business.managers.MemoryCacheManager;
import com.myvodafone.android.business.managers.ProfileManager;
import com.myvodafone.android.business.managers.SupportManager;
import com.myvodafone.android.front.VFGRActivity;
import com.myvodafone.android.front.soasta.OmnitureHelper;
import com.myvodafone.android.front.support.FragmentSupportChat;
import com.myvodafone.android.front.support.FragmentSupportFAQ;
import com.myvodafone.android.front.support.FragmentSupportPTWrapper;
import com.myvodafone.android.front.support.SupportDialog;
import com.myvodafone.android.front.support.UserInfo;
import com.myvodafone.android.model.business.VFAccount;
import com.myvodafone.android.model.service.GetPTAgentsResponse;
import com.myvodafone.android.model.service.UserTypeSmartResponse;
import com.myvodafone.android.model.service.fixed.FixedFAQCategory;
import com.myvodafone.android.utils.StaticTools;
import java.lang.ref.WeakReference;
/**
* Created by p.koutsias on 4/7/2016.
*/
public class Support implements ProfileManager.UserTypeListener, SupportManager.PTAgentsListener {
private static final int SCALE_ANIMATION_DURATION = 350;
private static final int NUDGE_ANIMATION_DURATION = 200;
public boolean fromDeepLink = false;
private FragmentActivity activity;
private boolean progressVIsible;
LinearLayout btnSupport;
RelativeLayout supportContainer;
RelativeLayout layoutTopSupport;
LinearLayout tabsContainer;
PercentRelativeLayout progressContainer;
ScrollView scrollView;
ScrollView scrollViewTop;
LinearLayout btnSupportTop;
ViewGroup layoutMain;
Spring spring;
PagerSlidingTabStrip tabs;
Animation scaleAnimation;
DemoCollectionPagerAdapter mDemoCollectionPagerAdapter;
ViewPager mViewPager;
private boolean hasPT = false;
private boolean hasPTAgents = false;
private int imgTopMargin;
private int containerMargin;
private boolean isOpen;
SupportDialog supportDialog;
View root;
private boolean callRunning = false;
private FragmentSupportPTWrapper fragmentSupportPTWrapper = null;
public Support() {
}
public void init(FragmentActivity activity, View _root, SupportDialog supportDialog){
this.activity = activity;
this.supportDialog = supportDialog;
this.root = _root;
btnSupport = (LinearLayout) root.findViewById(R.id.btnSupport);
scrollView = (ScrollView) root.findViewById(R.id.tutorial_scrollview);
scrollViewTop = (ScrollView) root.findViewById(R.id.tutorial_scrollview_top);
layoutTopSupport = (RelativeLayout) root.findViewById(R.id.layoutTopSupport);
btnSupportTop = (LinearLayout) root.findViewById(R.id.btnSupportTop);
layoutMain = (ViewGroup) root.findViewById(R.id.layoutMain);
layoutTopSupport.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return true;
}
});
imgTopMargin = activity.getResources().getDimensionPixelOffset(R.dimen.profile_selector_badge_top_margin);
containerMargin = activity.getResources().getDimensionPixelOffset(R.dimen.home_horizontal_small);
//Set support to open
SupportManager.setIsSupportOpen(true);
SupportManager.setHasPT(false);
SupportManager.setHasPTAgent(false);
resetFAQsExpanded();
}
private void resetFAQsExpanded() {
//Reset expande faqs here
if(MemoryCacheManager.getFixedFAQCategories() != null) {
for (FixedFAQCategory fixedFAQCategory : MemoryCacheManager.getFixedFAQCategories()) {
for (int i = 0; i<= fixedFAQCategory.getFixedFaqs().size() - 1; i++) {
fixedFAQCategory.getFixedFaqs().get(i).setExpanded(false);
}
}
}
//Reset expande faqs here
if(MemoryCacheManager.getMobileFAQs() != null) {
for(int i =0; i<= MemoryCacheManager.getMobileFAQs().size()-1; i++) {
MemoryCacheManager.getMobileFAQs().get(i).setExpanded(false);
}
}
}
@Override
public void onSuccessUserType(UserTypeSmartResponse userTypeSmartResponse) {
StaticTools.Log("success user type");
//Save it to Cache
MemoryCacheManager.setUserPTStatus(userTypeSmartResponse, StaticTools.getBizAccountNumber(MemoryCacheManager.getSelectedAccount()));
if (hasPT(userTypeSmartResponse)) {
//Check for PT Agents
hasPTAgents();
} else {
hasPTAgents = false;
hasPT = false;
switchToNonPT();
MemoryCacheManager.setPtAgents(null);
closeProgress();
callRunning = false;
}
}
@Override
public void onErrorUserType(String message) {
StaticTools.Log("error user type");
hasPTAgents = false;
hasPT = false;
switchToNonPT();
MemoryCacheManager.setPtAgents(null);
closeProgress();
callRunning = false;
}
@Override
public void onGenericErrorUserType(int errorCode) {
StaticTools.Log("generic error user type");
hasPTAgents = false;
hasPT = false;
switchToNonPT();
MemoryCacheManager.setPtAgents(null);
closeProgress();
callRunning = false;
}
public class DemoCollectionPagerAdapter extends FragmentStatePagerAdapter {
public DemoCollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
private Fragment fragmentPt;
@Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
//Select fragment to show based on Fix/Mobile here
//For PT/Contanct Use the wrapper Fragment
@Override
public Fragment getItem(int i) {
switch (i) {
case 0:
//Omniture ** Chat 24/7 live chat **
OmnitureHelper.trackView("Chat 24/7 live chat");
return new FragmentSupportChat();
case 2:
OmnitureHelper.trackView("Chat 24/7 FAQ");
return new FragmentSupportFAQ();
case 1:
//Omniture ** Chat 24/7 PT **
OmnitureHelper.trackView("Chat 24/7 PT");
if (fragmentSupportPTWrapper == null) {
fragmentSupportPTWrapper = new FragmentSupportPTWrapper();
if(fromDeepLink){
fragmentSupportPTWrapper.setFromDeepLink(true);
tabs.addTab(1, null);
tabs.clickMiddleTab();
}
}
fragmentPt = fragmentSupportPTWrapper;
return fragmentPt;
default:
//Omniture ** Chat 24/7 live chat **
OmnitureHelper.trackView("Chat 24/7 live chat");
return new FragmentSupportChat();
}
}
@Override
public int getCount() {
return 3;
}
@Override
public CharSequence getPageTitle(int position) {
if (MemoryCacheManager.getSelectedAccount() == null) {
return "";
}
switch (position) {
case 1:
return activity.getBaseContext().getResources().getString(R.string.contact_us);
case 0:
return activity.getBaseContext().getResources().getString(R.string.live_chat_tab);
case 2:
return activity.getBaseContext().getResources().getString(R.string.faq_button);
default:
return "";
}
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
try {
super.destroyItem(container, position, object);
} catch (Exception e){
StaticTools.Log("Support : " + e.toString());
}
}
}
public void showSupport(){
showSupport(0);
}
public void initializeProgress(){
//Inflate the base container here
if (supportContainer == null)
supportContainer = (RelativeLayout) activity.getLayoutInflater().inflate(R.layout.layout_support_container, null);
if(progressContainer == null)
progressContainer = (PercentRelativeLayout) supportContainer.findViewById(R.id.progressContainer);
}
public void showSupport(int selectedTab) {
//Omniture ** Chat 24/7 contact **
OmnitureHelper.trackView("Chat 24/7 contact");
((VFGRActivity) activity).sideMenuHelper.disableSwipe();
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) btnSupportTop.getLayoutParams();
params.topMargin = (int) (btnSupport.getY() + ((RelativeLayout) btnSupport.getParent()).getY()) - scrollView.getScrollY();
params.leftMargin = (int) (btnSupport.getX() + ((RelativeLayout) btnSupport.getParent()).getX());
btnSupportTop.setLayoutParams(params);
layoutTopSupport.setVisibility(View.VISIBLE);
scrollViewTop.setVisibility(View.VISIBLE);
btnSupport.setVisibility(View.INVISIBLE);
//Inflate the base container here
if (supportContainer == null)
supportContainer = (RelativeLayout) activity.getLayoutInflater().inflate(R.layout.layout_support_container, null);
//Init the viewpager
mViewPager = (ViewPager) supportContainer.findViewById(R.id.pager);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
if(position == 1) {
//On slide to tab 3, Load the PT/Agent Data
loadPTStatusData();
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
tabsContainer = (LinearLayout) supportContainer.findViewById(R.id.tabsContainer);
progressContainer = (PercentRelativeLayout) supportContainer.findViewById(R.id.progressContainer);
SpringSystem springSystem = SpringSystem.create();
spring = springSystem.createSpring();
Animation nudgeDown = new TranslateAnimation(0, 0, 0, imgTopMargin);
nudgeDown.setDuration(NUDGE_ANIMATION_DURATION);
nudgeDown.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
afterNudgeDown();
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
btnSupportTop.startAnimation(nudgeDown);
loadPTStatusData();
showTabs(selectedTab);
}
public void initializeFromDeepLink(){
fromDeepLink = true;
showSupport(1);
}
public void loadPTStatusData() {
VFAccount selectedAccount = MemoryCacheManager.getSelectedAccount();
if (selectedAccount != null) {
if (selectedAccount.getAccountType() == VFAccount.TYPE_FIXED_LINE) {
hasPT = false;
closeProgress();
switchToNonPT();
} else {
if(mViewPager.getCurrentItem() == 1) {
showProgress();
}
if (MemoryCacheManager.getUserPTStatus() != null &&
MemoryCacheManager.getUserPTStatus().getMsisdn().equals(StaticTools.getBizAccountNumber(MemoryCacheManager.getSelectedAccount()))) {
hasPT = hasPT(MemoryCacheManager.getUserPTStatus());
if (hasPT) {
hasPTAgents();
} else {
hasPTAgents = false;
closeProgress();
switchToNonPT();
}
} else {
if(MemoryCacheManager.getSelectedAccount() != null && MemoryCacheManager.getSelectedAccount().getAccountSegment() != VFAccount.TYPE_MOBILE_PREPAY) {
String msisdn = StaticTools.getBizAccountNumber(MemoryCacheManager.getSelectedAccount());
if(!callRunning) {
callRunning = true;
MemoryCacheManager.setPtAgents(null);
MemoryCacheManager.setUserPTStatus(null);
ProfileManager.getUserType(activity, selectedAccount, msisdn, true, true, false, new WeakReference<ProfileManager.UserTypeListener>(this), AsyncTask.THREAD_POOL_EXECUTOR);
}
} else {
hasPT = false;
hasPTAgents = false;
MemoryCacheManager.setPtAgents(null);
MemoryCacheManager.setUserPTStatus(null);
closeProgress();
switchToNonPT();
}
}
}
}
}
private void afterNudgeDown() {
final float startY = btnSupport.getY() + ((RelativeLayout) btnSupport.getParent()).getY() - scrollView.getScrollY();
final float diff = -(int) (startY - imgTopMargin);
spring.addListener(new SimpleSpringListener() {
@Override
public void onSpringUpdate(Spring spring) {
float value = (float) spring.getCurrentValue();
btnSupportTop.setY(startY + value * diff);
}
@Override
public void onSpringAtRest(Spring spring) {
afterSpringUp();
}
});
spring.setEndValue(1);
}
private void afterSpringUp() {
layoutMain.addView(supportContainer);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(supportContainer.getLayoutParams());
params.setMargins(containerMargin, btnSupportTop.getHeight() + imgTopMargin, containerMargin, containerMargin);
supportContainer.setLayoutParams(params);
supportContainer.forceLayout();
int measureSpecW = View.MeasureSpec.makeMeasureSpec(supportContainer.getWidth(), View.MeasureSpec.EXACTLY);
int measureSpecH = View.MeasureSpec.makeMeasureSpec(layoutMain.getHeight(), View.MeasureSpec.EXACTLY);
supportContainer.measure(measureSpecW, measureSpecH);
int targetHeight = supportContainer.getMeasuredHeight();
scaleAnimation = new ExpandAnimation(supportContainer, 0, targetHeight);
scaleAnimation.setFillAfter(true);
scaleAnimation.setDuration(SCALE_ANIMATION_DURATION);
scaleAnimation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
supportContainer.setVisibility(View.VISIBLE);
}
@Override
public void onAnimationEnd(Animation animation) {
isOpen = true;
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
supportContainer.findViewById(R.id.selectorHeader).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
close();
}
});
supportContainer.startAnimation(scaleAnimation);
}
public void close() {
if (progressVIsible) {
return;
}
((VFGRActivity) activity).sideMenuHelper.enableSwipe();
scaleAnimation.setDuration(SCALE_ANIMATION_DURATION);
scaleAnimation.setInterpolator(new ReverseInterpolator());
scaleAnimation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
afterSlideUp();
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
supportContainer.startAnimation(scaleAnimation);
//Set support to closed
SupportManager.setIsSupportOpen(false);
SupportManager.setSupportPTInstance(null);
SupportManager.setSuppportNonPtInstance(null);
}
private void afterSlideUp() {
layoutMain.removeView(supportContainer);
Animation nudgeUp = new TranslateAnimation(0, 0, 0, -imgTopMargin);
nudgeUp.setDuration(NUDGE_ANIMATION_DURATION);
nudgeUp.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
afterNudgeUp();
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
btnSupportTop.startAnimation(nudgeUp);
}
private void afterNudgeUp() {
final float startY = btnSupportTop.getY();
final float diff = btnSupport.getY() + ((RelativeLayout) btnSupport.getParent()).getY() - scrollView.getScrollY() - startY;
spring.removeAllListeners();
spring.setCurrentValue(0).setAtRest();
spring.addListener(new SimpleSpringListener() {
@Override
public void onSpringUpdate(Spring spring) {
float value = (float) spring.getCurrentValue();
btnSupportTop.setY(startY + value * diff);
}
@Override
public void onSpringAtRest(Spring spring) {
afterSpringDown();
}
});
spring.setEndValue(1);
}
private void afterSpringDown() {
isOpen = false;
scrollViewTop.setVisibility(View.GONE);
layoutTopSupport.setVisibility(View.GONE);
btnSupport.setVisibility(View.VISIBLE);
if(supportDialog != null) {
supportDialog.getDialog().cancel();
}
}
public boolean isOpen() {
return isOpen;
}
private void showTabs(){
showTabs(0);
}
private void showTabs(final int tabIndex) {
progressVIsible = false;
hasPT = hasPT(MemoryCacheManager.getUserPTStatus());
boolean showPT = hasPT && hasPTAgents;
if(supportDialog == null){
mDemoCollectionPagerAdapter = new DemoCollectionPagerAdapter(activity.getSupportFragmentManager());
} else {
mDemoCollectionPagerAdapter = new DemoCollectionPagerAdapter(supportDialog.getChildFragmentManager());
}
mViewPager.setCurrentItem(tabIndex);
mViewPager.setAdapter(mDemoCollectionPagerAdapter);
mViewPager.setOffscreenPageLimit(2);
// Bind the tabs to the ViewPager
tabs = (PagerSlidingTabStrip) supportContainer.findViewById(R.id.tabs);
// tabs.setShouldExpand(true);
tabs.setViewPager(mViewPager);
prepareTabs(showPT);
tabs.setCurrentPosition(tabIndex);
tabs.refreshSelection();
tabsContainer.setVisibility(View.VISIBLE);
mViewPager.setVisibility(View.VISIBLE);
progressContainer.setVisibility(View.GONE);
}
//Use this to fix the tabs as needed
private void prepareTabs(boolean showPT){
tabs.setTabsContainerGravity(Gravity.CENTER);
tabs.setTextSize(activity.getResources().getDimensionPixelSize(R.dimen.text_normal));
tabs.setMinimumHeight(R.dimen.btn_height);
Typeface typeface = Typeface.createFromAsset(activity.getResources().getAssets(), "fonts/VodafoneRg.ttf");
tabs.setTypeface(typeface, Typeface.NORMAL);
if(tabs != null && tabs.getChildAt(0) != null && ((RelativeLayout)((ViewGroup)tabs.getChildAt(0)).getChildAt(0)) != null ) {
for (int i = 0; i <= ((ViewGroup) tabs.getChildAt(0)).getChildCount() - 1; i++) {
if (((RelativeLayout) ((ViewGroup) tabs.getChildAt(0)).getChildAt(i)).getChildAt(0) instanceof TextView) {
((RelativeLayout) ((ViewGroup) tabs.getChildAt(0)).getChildAt(i)).setGravity(Gravity.CENTER);
TextView textView = ((TextView) ((RelativeLayout) ((ViewGroup) tabs.getChildAt(0)).getChildAt(i)).getChildAt(0));
textView.setGravity(Gravity.CENTER);
textView.setLines(2);
textView.setMaxLines(2);
textView.setPadding((int)activity.getResources().getDimension(R.dimen.fxl_container_padding),0,(int)activity.getResources().getDimension(R.dimen.fxl_container_padding),0);
//First item
if (i == 1 && MemoryCacheManager.getSelectedAccount() != null && MemoryCacheManager.getSelectedAccount().getAccountType() != VFAccount.TYPE_FIXED_LINE) {
if(MemoryCacheManager.getPtAgents() != null && MemoryCacheManager.getPtAgents().getAgentList().size() > 0){
String txt = activity.getString(R.string.personal_advisor_button);
txt = txt.replace("_n",System.getProperty("line.separator"));
textView.setText(txt);
} else {
textView.setText(activity.getString(R.string.contact_us));
}
}
}
}
}
}
public void showProgress() {
progressVIsible = true;
progressContainer.setVisibility(View.VISIBLE);
if(tabsContainer!=null)
tabsContainer.setVisibility(View.GONE);
if(mViewPager!=null)
mViewPager.setVisibility(View.GONE);
}
public void closeProgress(){
progressVIsible = false;
progressContainer.setVisibility(View.GONE);
tabsContainer.setVisibility(View.VISIBLE);
mViewPager.setVisibility(View.VISIBLE);
}
private boolean hasPT(UserTypeSmartResponse userTypeSmartResponse) {
return userTypeSmartResponse != null
&& !StaticTools.isNullOrEmpty(userTypeSmartResponse.getSmartInfo())
&& userTypeSmartResponse.getSmartInfo().equalsIgnoreCase("pt");
}
private void hasPTAgents(){
UserInfo userInfo = SupportManager.setupUserDetails();
if(SupportManager.getUserInfo() != null && MemoryCacheManager.getPtAgents() == null) {
SupportManager.getPTAgents(userInfo.getUsername(), userInfo.getPassword(), userInfo.getNumber(), userInfo.getAfm(), activity.getBaseContext(), new WeakReference<SupportManager.PTAgentsListener>(this));
} else {
onSuccessPTAgents(MemoryCacheManager.getPtAgents());
}
}
private void setLastTabText(int txtID) {
if(tabs != null && tabs.getChildAt(0) != null && ((RelativeLayout)((ViewGroup)tabs.getChildAt(0)).getChildAt(0)) != null ) {
if (((RelativeLayout) ((ViewGroup) tabs.getChildAt(0)).getChildAt(2)).getChildAt(0) instanceof TextView) {
TextView textView = ((TextView) ((RelativeLayout) ((ViewGroup) tabs.getChildAt(0)).getChildAt(1)).getChildAt(0));
String txt = activity.getString(txtID);
txt = txt.replace("_n",System.getProperty("line.separator"));
textView.setText(txt);
}
}
}
@Override
public void onSuccessPTAgents(GetPTAgentsResponse ptAgentsResponse) {
if(ptAgentsResponse.getAgentList() != null && ptAgentsResponse.getAgentList().size() > 0) {
MemoryCacheManager.setPtAgents(ptAgentsResponse);
hasPTAgents = true;
SupportManager.setHasPT(true);
SupportManager.setHasPTAgent(true);
} else {
hasPTAgents = false;
MemoryCacheManager.setPtAgents(null);
}
callRunning = false;
if(mViewPager.getCurrentItem() == 1) {
// ((FragmentStatePagerAdapter)mViewPager.getAdapter()).notifyDataSetChanged();
if(SupportManager.isPT() && SupportManager.hasPTAgent() && fragmentSupportPTWrapper != null) {
fragmentSupportPTWrapper.switchToPT(activity);
} else {
fragmentSupportPTWrapper.switchToNonPt(activity);
}
mViewPager.invalidate();
setLastTabText(R.string.personal_advisor_button);
}
closeProgress();
}
@Override
public void onErrorPTAgents(String message) {
MemoryCacheManager.setPtAgents(null);
hasPTAgents = false;
if(fragmentSupportPTWrapper!= null) {
fragmentSupportPTWrapper.switchToNonPt(activity);
}
closeProgress();
callRunning = false;
}
@Override
public void onGenericErrorPTAgents() {
///???
MemoryCacheManager.setPtAgents(null);
hasPTAgents = false;
closeProgress();
callRunning = false;
}
private void switchToNonPT() {
if(fragmentSupportPTWrapper!= null && hasPT == false) {
fragmentSupportPTWrapper.switchToNonPt(activity);
}
}
}
|
public class Gravitacija {
public static void main(String[] args){
System.out.println("OIS je zakon");
System.out.println("test druge veje");
}
}
|
package com.mingrisoft;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class ReadXmlFrame extends JFrame {
/**
*
*/
private static final long serialVersionUID = -1297399552701564382L;
private JPanel contentPane;
private JTextField classNameTextField;
private JTextField urlTextField;
private JTextField userNameTextField;
private JTextField passWordTextField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ReadXmlFrame frame = new ReadXmlFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ReadXmlFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 273);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
setTitle("从XML文件中读取内容");
JPanel panel = new JPanel();
panel.setBounds(0, 0, 434, 245);
contentPane.add(panel);
panel.setLayout(null);
JLabel classNameLabel = new JLabel("驱动代码:");
classNameLabel.setBounds(48, 49, 74, 15);
panel.add(classNameLabel);
classNameTextField = new JTextField();
ReadXMLDataBase readXml = new ReadXMLDataBase();
classNameTextField.setBounds(132, 46, 238, 21);
classNameTextField.setText(readXml.readXml("className"));
panel.add(classNameTextField);
classNameTextField.setColumns(10);
JLabel urlLabel = new JLabel(" URL :");
urlLabel.setBounds(66, 90, 54, 15);
panel.add(urlLabel);
urlTextField = new JTextField();
urlTextField.setText(readXml.readXml("url"));
urlTextField.setBounds(132, 87, 238, 21);
panel.add(urlTextField);
urlTextField.setColumns(10);
JLabel userNameLabel = new JLabel("用户名:");
userNameLabel.setBounds(66, 127, 54, 15);
panel.add(userNameLabel);
userNameTextField = new JTextField();
userNameTextField.setBounds(132, 124, 238, 21);
userNameTextField.setText(readXml.readXml("userName"));
panel.add(userNameTextField);
userNameTextField.setColumns(10);
JLabel passWordLabel = new JLabel("密 码 :");
passWordLabel.setBounds(66, 171, 54, 15);
panel.add(passWordLabel);
passWordTextField = new JTextField();
passWordTextField.setBounds(132, 168, 238, 21);
passWordTextField.setText(readXml.readXml("passWord"));
panel.add(passWordTextField);
passWordTextField.setColumns(10);
}
}
|
import java.awt.*;
/**
* Created with IntelliJ IDEA.
* User: dexctor
* Date: 12-11-20
* Time: 上午10:41
* To change this template use File | Settings | File Templates.
*/
public class p1_2_1 {
public static void main(String[] args)
{
int N = StdIn.readInt();
Point2D[] points = new Point2D[N];
for(int i = 0; i < N; ++i)
{
Point2D point = new Point2D(StdRandom.uniform(), StdRandom.uniform());
points[i] = point;
StdDraw.setPenRadius(0.01);
StdDraw.point(point.x(), point.y());
}
double min = Double.MAX_VALUE;
int point1index = 0, point2index = 0;
for(int i = 0; i < N; ++i)
{
for(int j = i + 1; j < N; ++j)
{
if(points[i].distanceTo(points[j]) < min)
{
min = points[i].distanceTo(points[j]);
point1index = i;
point2index = j;
}
}
}
StdDraw.setPenColor(Color.RED);
StdDraw.point(points[point1index].x(), points[point1index].y());
StdDraw.point(points[point2index].x(), points[point2index].y());
}
}
|
package lesson11.lesson;
public class Coal extends Resource {
@Override
public void print(){
System.out.println("Это уголь");
}
}
|
int isSumOfConsecutive2(int n) {
int ways = 0;
for(int i = 1; i < n; i++){
int tmp = n;
int bab = i;
while(tmp > 0){
tmp -= bab;
bab++;
}
if(tmp == 0)
ways++;
}
return ways;
}
|
// Generated code from Butter Knife. Do not modify!
package com.tdr.registrationv3.ui.activity.insurance;
import android.support.annotation.CallSuper;
import android.support.annotation.UiThread;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import butterknife.Unbinder;
import butterknife.internal.Utils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.tdr.registrationv3.R;
import com.tdr.registrationv3.view.SearchView;
import java.lang.IllegalStateException;
import java.lang.Override;
public class InsuranceWaitActivity_ViewBinding implements Unbinder {
private InsuranceWaitActivity target;
@UiThread
public InsuranceWaitActivity_ViewBinding(InsuranceWaitActivity target) {
this(target, target.getWindow().getDecorView());
}
@UiThread
public InsuranceWaitActivity_ViewBinding(InsuranceWaitActivity target, View source) {
this.target = target;
target.comTitleBack = Utils.findRequiredViewAsType(source, R.id.com_title_back, "field 'comTitleBack'", RelativeLayout.class);
target.textTitle = Utils.findRequiredViewAsType(source, R.id.text_title, "field 'textTitle'", TextView.class);
target.comTitleSettingIv = Utils.findRequiredViewAsType(source, R.id.com_title_setting_iv, "field 'comTitleSettingIv'", ImageView.class);
target.comTitleSettingTv = Utils.findRequiredViewAsType(source, R.id.com_title_setting_tv, "field 'comTitleSettingTv'", TextView.class);
target.searchView = Utils.findRequiredViewAsType(source, R.id.search_view, "field 'searchView'", SearchView.class);
target.insuranceRv = Utils.findRequiredViewAsType(source, R.id.insurance_rv, "field 'insuranceRv'", RecyclerView.class);
target.refresh = Utils.findRequiredViewAsType(source, R.id.refresh, "field 'refresh'", SmartRefreshLayout.class);
target.emptyIv = Utils.findRequiredViewAsType(source, R.id.empty_iv, "field 'emptyIv'", ImageView.class);
target.emptyTv = Utils.findRequiredViewAsType(source, R.id.empty_tv, "field 'emptyTv'", TextView.class);
target.emptyDataRl = Utils.findRequiredViewAsType(source, R.id.empty_data_rl, "field 'emptyDataRl'", RelativeLayout.class);
}
@Override
@CallSuper
public void unbind() {
InsuranceWaitActivity target = this.target;
if (target == null) throw new IllegalStateException("Bindings already cleared.");
this.target = null;
target.comTitleBack = null;
target.textTitle = null;
target.comTitleSettingIv = null;
target.comTitleSettingTv = null;
target.searchView = null;
target.insuranceRv = null;
target.refresh = null;
target.emptyIv = null;
target.emptyTv = null;
target.emptyDataRl = null;
}
}
|
package com.dfire.common.service.impl;
import com.dfire.common.constants.Constants;
import com.dfire.common.entity.HeraAction;
import com.dfire.common.entity.model.TablePageForm;
import com.dfire.common.entity.vo.HeraActionVo;
import com.dfire.common.kv.Tuple;
import com.dfire.common.mapper.HeraJobActionMapper;
import com.dfire.common.service.HeraJobActionService;
import com.dfire.common.service.HeraJobHistoryService;
import com.dfire.common.service.HeraJobService;
import com.dfire.common.util.ActionUtil;
import com.dfire.common.util.BeanConvertUtils;
import com.dfire.common.vo.GroupTaskVo;
import com.dfire.common.vo.JobStatus;
import com.dfire.logs.ScheduleLog;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import java.util.*;
/**
* @author: <a href="mailto:lingxiao@2dfire.com">凌霄</a>
* @time: Created in 下午3:43 2018/5/16
* @desc
*/
@Service("heraJobActionService")
public class HeraJobActionServiceImpl implements HeraJobActionService {
@Autowired
private HeraJobActionMapper heraJobActionMapper;
@Autowired
@Qualifier("heraJobMemoryService")
private HeraJobService heraJobService;
@Autowired
private HeraJobHistoryService heraJobHistoryService;
@Override
public List<HeraAction> batchInsert(List<HeraAction> heraActionList, Long nowAction) {
ScheduleLog.info("batchInsert-> batch size is :{}", heraActionList.size());
List<HeraAction> insertList = new ArrayList<>();
for (HeraAction heraAction : heraActionList) {
//更新时单条更新
//原因:批量更新时,在极端情况下,数据会有批量数据处理时间的buff
// 此时如果有其它地方修改了某条数据 会数据库中的数据被批量更新的覆盖
if (isNeedUpdateAction(heraAction, nowAction)) {
update(heraAction);
} else {
insertList.add(heraAction);
}
}
if (insertList.size() != 0) {
heraJobActionMapper.batchInsert(insertList);
}
return heraActionList;
}
/**
* 判断是更新该是修改
*
* @param heraAction
* @return
*/
private boolean isNeedUpdateAction(HeraAction heraAction, Long nowAction) {
HeraAction action = heraJobActionMapper.findById(heraAction);
if (action != null) {
//如果该任务不是在运行中
if (!Constants.STATUS_RUNNING.equals(action.getStatus())) {
heraAction.setStatus(action.getStatus());
heraAction.setHistoryId(action.getHistoryId());
heraAction.setReadyDependency(action.getReadyDependency());
heraAction.setGmtCreate(action.getGmtCreate());
} else {
BeanUtils.copyProperties(action, heraAction);
heraAction.setGmtModified(new Date());
}
return true;
} else {
if (heraAction.getId() < nowAction) {
heraAction.setStatus(Constants.STATUS_FAILED);
heraAction.setLastResult("生成action时,任务过时,直接设置为失败");
}
}
return false;
}
@Override
public int insert(HeraAction heraAction, Long nowAction) {
if (isNeedUpdateAction(heraAction, nowAction)) {
return heraJobActionMapper.update(heraAction);
} else {
return heraJobActionMapper.insert(heraAction);
}
}
@Override
public int delete(String id) {
return heraJobActionMapper.delete(id);
}
@Override
public int update(HeraAction heraAction) {
return heraJobActionMapper.update(heraAction);
}
@Override
public List<HeraAction> getAll() {
return heraJobActionMapper.getAll();
}
@Override
public HeraAction findById(String actionId) {
HeraAction heraAction = HeraAction.builder().id(Long.parseLong(actionId)).build();
return heraJobActionMapper.findById(heraAction);
}
@Override
public HeraAction findLatestByJobId(String jobId) {
return heraJobActionMapper.findLatestByJobId(jobId);
}
@Override
public List<HeraAction> findByJobId(String jobId) {
return heraJobActionMapper.findByJobId(jobId);
}
@Override
public int updateStatus(JobStatus jobStatus) {
HeraAction heraAction = findById(jobStatus.getActionId());
heraAction.setGmtModified(new Date());
HeraAction tmp = BeanConvertUtils.convert(jobStatus);
heraAction.setStatus(tmp.getStatus());
heraAction.setReadyDependency(tmp.getReadyDependency());
heraAction.setHistoryId(jobStatus.getHistoryId());
return update(heraAction);
}
@Override
public Tuple<HeraActionVo, JobStatus> findHeraActionVo(String actionId) {
HeraAction heraActionTmp = findById(actionId);
if (heraActionTmp == null) {
return null;
}
return BeanConvertUtils.convert(heraActionTmp);
}
@Override
public JobStatus findJobStatus(String actionId) {
Tuple<HeraActionVo, JobStatus> tuple = findHeraActionVo(actionId);
return tuple.getTarget();
}
/**
* 根据jobId查询版本运行信息,只能是取最新版本信息
*
* @param jobId
* @return
*/
@Override
public JobStatus findJobStatusByJobId(String jobId) {
HeraAction heraAction = findLatestByJobId(jobId);
return findJobStatus(heraAction.getId().toString());
}
@Override
public Integer updateStatus(HeraAction heraAction) {
return heraJobActionMapper.updateStatus(heraAction);
}
@Override
public Integer updateStatusAndReadDependency(HeraAction heraAction) {
return heraJobActionMapper.updateStatusAndReadDependency(heraAction);
}
@Override
public List<HeraAction> getTodayAction() {
return heraJobActionMapper.selectTodayAction(ActionUtil.getInitActionVersion());
}
@Override
public List<String> getActionVersionByJobId(Long jobId) {
return heraJobActionMapper.getActionVersionByJobId(jobId);
}
@Override
public List<HeraActionVo> getNotRunScheduleJob() {
return heraJobActionMapper.getNotRunScheduleJob();
}
@Override
public List<HeraActionVo> getFailedJob() {
return heraJobActionMapper.getFailedJob();
}
@Override
public List<GroupTaskVo> findByJobIds(List<Integer> idList, String startDate, String endDate, TablePageForm pageForm, Integer type) {
if (idList == null || idList.size() == 0) {
return null;
}
Map<String, Object> params = new HashMap<>(3);
params.put("startDate", startDate);
params.put("endDate", endDate);
params.put("list", idList);
params.put("page", (pageForm.getPage() - 1) * pageForm.getLimit());
params.put("limit", pageForm.getPage() * pageForm.getLimit());
List<HeraAction> actionList;
if (type == 0) {
params.put("status", null);
} else if (type == 1) {
params.put("status", Constants.STATUS_RUNNING);
} else if (type == 2) {
params.put("status", Constants.STATUS_FAILED);
} else {
return null;
}
pageForm.setCount(heraJobActionMapper.findByJobIdsCount(params));
actionList = heraJobActionMapper.findByJobIdsAndPage(params);
List<GroupTaskVo> res = new ArrayList<>(actionList.size());
actionList.forEach(action -> {
GroupTaskVo taskVo = new GroupTaskVo();
taskVo.setActionId(buildFont(String.valueOf(action.getId()), Constants.STATUS_NONE));
taskVo.setJobId(buildFont(String.valueOf(action.getJobId()), Constants.STATUS_NONE));
taskVo.setName(buildFont(action.getName(), Constants.STATUS_NONE));
if (action.getStatus() != null) {
taskVo.setStatus(buildFont(action.getStatus(), action.getStatus()));
} else {
taskVo.setStatus(buildFont("未执行", Constants.STATUS_FAILED));
}
taskVo.setLastResult(buildFont(action.getLastResult(), action.getLastResult()));
if (action.getScheduleType() == 0) {
taskVo.setReadyStatus(buildFont("独立任务", Constants.STATUS_NONE));
} else {
String[] dependencies = action.getDependencies().split(Constants.COMMA);
StringBuilder builder = new StringBuilder();
HeraAction heraAction;
for (String dependency : dependencies) {
heraAction = this.findById(dependency);
if (heraAction != null) {
if (Constants.STATUS_SUCCESS.equals(heraAction.getStatus())) {
builder.append(Constants.HTML_FONT_GREEN_LEFT).append("依赖任务:").append(dependency).append(",结束时间:").append(ActionUtil.getFormatterDate(ActionUtil.MON_MIN, heraAction.getStatisticEndTime()));
} else if (Constants.STATUS_RUNNING.equals(heraAction.getStatus())) {
builder.append(Constants.HTML_FONT_BLUE_LEFT).append("依赖任务:").append(dependency).append(",执行中");
} else if (Constants.STATUS_FAILED.equals(heraAction.getStatus())) {
builder.append(Constants.HTML_FONT_RED_LEFT).append("依赖任务:").append(dependency).append(",执行失败");
} else {
builder.append(Constants.HTML_FONT_RED_LEFT).append("依赖任务:").append(dependency).append(",未执行");
}
} else {
builder.append(Constants.HTML_FONT_RED_LEFT).append("依赖任务:").append(dependency).append(",未找到");
}
builder.append(Constants.HTML_FONT_RIGHT).append(Constants.HTML_NEW_LINE);
}
taskVo.setReadyStatus(builder.toString());
}
res.add(taskVo);
});
return res;
}
private String buildFont(String str, String type) {
if (type == null) {
return Constants.HTML_FONT_RED_LEFT + str + Constants.HTML_FONT_RIGHT;
}
switch (type) {
case Constants.STATUS_RUNNING:
return Constants.HTML_FONT_BLUE_LEFT + str + Constants.HTML_FONT_RIGHT;
case Constants.STATUS_SUCCESS:
return Constants.HTML_FONT_GREEN_LEFT + str + Constants.HTML_FONT_RIGHT;
case Constants.STATUS_NONE:
return Constants.HTML_FONT_LEFT + str + Constants.HTML_FONT_RIGHT;
case Constants.STATUS_FAILED:
return Constants.HTML_FONT_RED_LEFT + str + Constants.HTML_FONT_RIGHT;
default:
return Constants.HTML_FONT_RED_LEFT + str + Constants.HTML_FONT_RIGHT;
}
}
}
|
/*
* (C) Mississippi State University 2009
*
* The WebTOP employs two licenses for its source code, based on the intended use. The core license for WebTOP applications is
* a Creative Commons GNU General Public License as described in http://*creativecommons.org/licenses/GPL/2.0/. WebTOP libraries
* and wapplets are licensed under the Creative Commons GNU Lesser General Public License as described in
* http://creativecommons.org/licenses/*LGPL/2.1/. Additionally, WebTOP uses the same licenses as the licenses used by Xj3D in
* all of its implementations of Xj3D. Those terms are available at http://www.xj3d.org/licenses/license.html.
*/
//Updated May 13 2004
package webtop.wsl.client;
import java.applet.Applet;
import java.net.*;
import java.io.*;
import java.util.*;
import org.xml.sax.*;
import vrml.external.field.*;
import webtop.util.*;
import webtop.wsl.script.*;
import webtop.wsl.event.*;
/**
* <code>WSLPlayer</code> is the central class of WSLAPI. Most of the features
* provided by WSLAPI are handled in this class. In essence, it provides
* methods to record, load, and playback scripts, plus other methods to set and
* get certain attributes. The methods that deal with recording, loading, and
* playing are listed as follow:
*
* <ul>
* <li> <a href="#load"><code>load()</code></a>
* -- Loads a script from an InputStream object, a String representing a filename, or from a URL
* <li> <a href="#play"><code>play()</code></a>
* -- Start playing the loaded script
* <li> <a href="#pause"><code>pause()</code></a>
* -- Pause the playback of a script
* <li> <a href="stop"><code>record()</code></a>
* -- Start recording a script
* <li> <a href="stop"><code>stop()</code></a>
* -- Stop playing or recording of a script
* <li> <a href="reset"><code>reset()</code></a>
* -- Reset the playback to the beginning of a script
* <li> <a href="unload"><code>unload()</code></a>
* -- Unloads a script
* </ul>
*
* <p>Not all methods are accessible in a state that <code>WSLPlayer</code>
* might be in. For example, when <code>WSLPlayer</code> is playing,
* <code>record()</code> should not be called; <strong>such calls will raise
* an <code>IllegalStateException</code></strong>. However, for convenience,
* the <code>record</code>* methods return silently when not recording.
*
* <p><code>WSLPlayer</code> uses an event model that is similar to the one
* used in Java's Abstract Windowing Toolkit (AWT) package. In WSLAPI,
* <code>WSLPlayer</code> generates events during state transitions, and
* during playback of a script. Objects interested in responding to these
* events can register themselves through the <code>addListener()</code>
* method. In addition, those objects should implement one or more of these
* interfaces: <code>WSLScriptListener</code>, <code>WSLPlayerListener</code>,
* and <code>WSLProgressListener</code>. These interfaces correspond to the
* three types of events that <code>WSLPlayer</code> generates:
* <code>WSLScriptEvent</code>, <code>WSLPlayerEvent</code>, and
* <code>WSLProgressEvent</code>. These classes contain various constants
* used as event-type identifiers.
*
* <p>Note that there is no specialized
* <code>add</code><i>Event</i><code>Listener()</code> method for each
* different type of event. Instead, the generalized
* <code>addListener()</code> method is used. <code>WSLPlayer</code>
* determines which types of events to fire to which objects based on the
* interfaces that the objects implement.</p>
*
* <p>There are ten types of WebTOP user interactions that can be recorded
* using WSLPlayer: <code>OBJECT_ADDED</code>, <code>OBJECT_REMOVED</code>,
* <code>MOUSE_ENTERED</code>, <code>MOUSE_EXITED</code>,
* <code>MOUSE_PRESSED</code>, <code>MOUSE_RELEASED</code>,
* <code>MOUSE_DRAGGED</code>, <code>ACTION_PERFORMED</code>,
* <code>VIEWPOINT_CHANGED</code>, and <code>VIEWPOINT_SELECTED</code>. There
* is a corresponding <code>record<i><Interaction></i>()</code> method
* for each type of user interaction.</p>
*
* @author Yong Tze Chi
* @author Davis Herring
*/
public class WSLPlayer implements Runnable/*,EventOutObserver*/ {
public static final int MAJOR_VERSION=3,MINOR_VERSION=3,REVISION=4;
public static final String VERSION=WTString.versionString(MAJOR_VERSION,MINOR_VERSION,REVISION);
//The maximum amount of time to wait before posting progress, etc. (ms)
private static final long MAX_IDLE=20;
public static final String DEFAULT_APPLET_PARAMETER="wslscript";
//Action names
private static final String VIEWPOINT_CHANGED="viewpointChanged",
VIEWPOINT_SELECTED="viewpointSelected",
OBJECT_ADDED="objectAdded",
OBJECT_REMOVED="objectRemoved",
ACTION_PERFORMED="actionPerformed",
MOUSE_IN="mouseEntered",
MOUSE_OUT="mouseExited",
MOUSE_DOWN="mousePressed",
MOUSE_UP="mouseReleased",
MOUSE_DRAG="mouseDragged";
private static final String EXCEPTION_MSG="Exception occurred during WSL event handling:";
private final WSLModule module;
private WSLScript script;
private WSLNode moduleNode,scriptNode;
private int scriptIndex;
//State; thread control (these do need to be volatile, yes?)
private volatile boolean playing,paused,recording;
//A suffixed T indicates a logical time variable expressed in the ideal
//world of the script; a suffixed Time represents a physical value gotten
//(at some point or another) from System.currentTimeMillis(). Physical and
//logical values cannot be mixed, but the difference between two of one kind
//can be mixed with the other.
private long totalScriptT; // length of script
private long lastEventTime; // real time at which last event was sent
private long scriptT,lastEventT,nextEventT; // logical times of interest
private long prevRecordTime; // when we last recorded something
private final Vector listeners=new Vector();
private Thread thread;
private final Object lock=new Object(); // for synchronization
//===============
// EAI interface
//===============
// private EventInSFBool navPanel_setEnabled;
// private EventInMFFloat set_view;
// private EventInSFInt32 set_activeView;
// private EventInSFBool query_view;
// private EventOutMFFloat view_changed;
// private EventOutSFInt32 activeView_changed;
// private EventOutMFFloat queryView_changed;
// private final float view[] = new float[6];
// private static final int VIEW_CHANGED=1,ACTIVEVIEW_CHANGED=2,
// QUERYVIEW_CHANGED=3;
private boolean viewpointEventEnabled=true,playbackVPEnabled;
/**
* The constructor of <code>WSLPlayer</code>, requires a reference of
* <code>WSLModule</code> it is tied to during runtime.
*
* @param module reference to a class that implements the
* <code>WSLModule</code> interface.
*/
public WSLPlayer(WSLModule module) {
if(module==null) throw new NullPointerException("no module given");
this.module=module;
}
//===========================
// Principal control methods
//===========================
//Loads script; does not post state changed event, as more may need
//to be done before that event can be reasonably generated. Nor does
//it use the title of the loaded script.
private boolean loadScript(InputStream is) throws WSLParser.InvalidScriptException {
if(loaded()) throw new IllegalStateException("already loaded a script");
//state = LOADING;
script = new WSLParser(module.getWSLModuleName()).parse(is);
scriptNode = script.getScriptNode();
moduleNode = script.getModuleNode();
if(scriptNode!=null) {
scriptIndex=0;
calculateScriptLength();
}
//initNavigationPanelInfo();
postInitialize();
return true;
}
/**
* Tries to load a script specified by the default applet parameter.
*
* @see #loadParameter(Applet,String)
*/
public boolean loadParameter(Applet app) {
return loadParameter(app,DEFAULT_APPLET_PARAMETER);
}
/**
* Tries to load a script specified by the given applet parameter. Unlike
* other <code>load</code>*<code>()</code> methods,
* <code>loadParameter()</code> throws no exceptions; if there is no
* parameter by the given name, or if no valid script can be read from the
* location it specifies, an error message is printed to standard error and
* the call returns false.
*
* @param app the applet whose parameters to examine.
* @param param the parameter to read.
* @return true if the script was successfully loaded; false if there was no
* script or if it could not be loaded.
*
* @see webtop.wsl.event.WSLPlayerEvent#SCRIPT_LOADED
*/
public boolean loadParameter(Applet app,String param) {
final String epfx="WSLPlayer::loadParameter: ";
String script=app.getParameter(param);
if(script==null || script.length()==0)
DebugPrinter.println(epfx+"No '"+param+"' parameter specified.");
else {
try {
load(new URL(app.getCodeBase(),script));
return true;
}
catch(Exception e) {
System.err.print(epfx+"could not load '"+script+"'; encountered ");
e.printStackTrace();
}
}
return false;
}
/**
* Loads a script from the given URL. If this call returns normally the
* script was successfully loaded.
*
* @param url location of the script file to be loaded.
*
* @exception IOException if the given URL was invalid or could not be read.
* @exception WSLParser.InvalidScriptException if the given URL did not
* contain a WSL script valid
* for the current module.
* @exception SecurityException if access to the given URL was denied by
* Java.
*
* @see webtop.wsl.event.WSLPlayerEvent#SCRIPT_LOADED
*/
public void load(URL url) throws IOException,WSLParser.InvalidScriptException {
loadScript(url.openStream());
final String str=url.toString();
int index = Math.max(str.lastIndexOf('/'), str.lastIndexOf('\\'));
script.setTitle(index>=0 ? str.substring(index+1) : str);
postPlayerStateChanged(WSLPlayerEvent.SCRIPT_LOADED);
}
/**
* Loads a script from the file whose name is given. If this call returns
* normally the script was successfully loaded.
*
* @param filename the name of the file from which to read a script.
*
* @exception IOException if the file could not be read.
* @exception WSLParser.InvalidScriptException
* if the file did not contain a WSL script valid for the current module.
* @exception SecurityException if access to the file was denied by Java.
*
* @see webtop.wsl.event.WSLPlayerEvent#SCRIPT_LOADED
*/
public void load(String filename)
throws IOException,WSLParser.InvalidScriptException {
FileInputStream fin = new FileInputStream(filename);
if(!loadScript(fin)) return;
int index=Math.max(filename.lastIndexOf('/'),filename.lastIndexOf('\\'));
if(index>=0) filename=filename.substring(index+1);
script.setTitle(filename);
postPlayerStateChanged(WSLPlayerEvent.SCRIPT_LOADED);
}
/**
* Loads a script from the specified <code>InputStream</code>. If this call
* returns normally the script was successfully loaded.
*
* @param in the stream from which the script is to be loaded.
* @exception WSLParser.InvalidScriptException
* if problems are encountered reading the stream as a script.
*
* @see webtop.wsl.event.WSLPlayerEvent#SCRIPT_LOADED
*/
public void load(InputStream in) throws WSLParser.InvalidScriptException {
if(loadScript(in)) postPlayerStateChanged(WSLPlayerEvent.SCRIPT_LOADED);
}
/**
* Unloads the script that's kept in <code>WSLPlayer</code>. This method
* may only be called while a script is loaded but not playing.
*
* @see webtop.wsl.event.WSLPlayerEvent#SCRIPT_UNLOADED
*/
public void unload() {
//This first test catches the recording state as well
if(!loaded()) throw new IllegalStateException("no script to unload");
if(isPlaying()) throw new IllegalStateException("script busy");
script = null;
scriptNode = null;
postPlayerStateChanged(WSLPlayerEvent.SCRIPT_UNLOADED);
}
/**
* Starts or resumes playback of a previously loaded script. A thread is
* started to play the script. This method is only accessible when a script
* is loaded but not playing, or else playing but paused.
*
* @see webtop.wsl.event.WSLPlayerEvent#PLAYER_STARTED
*/
public void play() {
//This first test catches the recording state as well
if(!loaded()) throw new IllegalStateException("no script to play");
if(isPlaying() && !isPaused()) throw new IllegalStateException("script already playing");
if(!script.isPlayable()) throw new IllegalStateException("script not playable");
if(isPlaying()) { // and thence, paused
synchronized(lock) {
paused=false;
lock.notify();
}
} else { // not playing
playing=true;
postInitialize();
thread=new Thread(this,"WSL playback thread");
thread.start();
}
postPlayerStateChanged(WSLPlayerEvent.PLAYER_STARTED);
}
/**
* Pauses the playback of a script. This method is only accessible while
* playing but not paused.
*
* @see webtop.wsl.event.WSLPlayerEvent#PLAYER_PAUSED
*/
public void pause() {
if(!isPlaying()) throw new IllegalStateException("script not playing");
if(isPaused()) throw new IllegalStateException("script already paused");
paused=true;
thread.interrupt(); // keep it from going on to the next event
postPlayerStateChanged(WSLPlayerEvent.PLAYER_PAUSED);
}
/**
* Prepares <code>WSLPlayer</code> for recording user interactions. It
* first calls <code>WSLModule.toWSLModule()</code> and obtains the current
* viewpoint to obtain the current state of the WebTOP module. This method
* is only accessible when there is no script loaded and recording is not
* already taking place.
*
* @see webtop.wsl.event.WSLPlayerEvent#RECORDER_STARTED
*/
public void record() {
if(loaded() || isRecording()) throw new IllegalStateException("player busy");
recording=true;
script = new WSLScript();
moduleNode = module.toWSLNode();
//initNavigationPanelInfo();
//if(query_view!=null) query_view.setValue(true);
script.addModuleNode(moduleNode);
scriptNode = new WSLNode(WSLScript.SCRIPT_TAG);
script.addScriptNode(scriptNode);
prevRecordTime = System.currentTimeMillis();
postPlayerStateChanged(WSLPlayerEvent.RECORDER_STARTED);
}
/**
* Resets the playback of a script to the beginning of the script. This
* method is only accessible when a script is loaded but not playing.
*
* @see webtop.wsl.event.WSLPlayerEvent#PLAYER_RESET
*/
public void reset() {
//This first test catches the recording state as well
if(!loaded()) throw new IllegalStateException("no script loaded");
if(isPlaying()) throw new IllegalStateException("script busy");
//Should a progress event of 0 be sent here?
//No, because progress events are only meaningful during playback.
postInitialize();
postPlayerStateChanged(WSLPlayerEvent.PLAYER_RESET);
}
/**
* Stops the playback or recording of a script. This method can only be
* called when <code>WSLPlayer</code> is playing or recording a script.
*
* @see webtop.wsl.event.WSLPlayerEvent#PLAYER_STOPPED
* @see webtop.wsl.event.WSLPlayerEvent#RECORDER_STOPPED
*/
public void stop() {
if(isPlaying()) {
//Assert stoppage on the thread
playing=paused=false;
synchronized(lock) {lock.notify();}
while(true) try{thread.join(); break;} catch(InterruptedException e) {}
} else if(isRecording()) {
scriptIndex = 0;
recordAction(WSLScript.SCRIPT_END_TAG, null, null, null);
calculateScriptLength();
recording=false;
postPlayerStateChanged(WSLPlayerEvent.RECORDER_STOPPED);
} else if(loaded()) throw new IllegalStateException("script not active");
else throw new IllegalStateException("no script to stop");
}
//=========
// Options
//=========
/**
* Returns whether viewpoint events are posted. When viewpoint events are
* ignored, the user is allowed to manipulate the viewpoint during the
* playback of a script. Otherwise, the navigation panel is locked during
* playback.
*
* @return <code>true</code> if viewpoint events are posted;
* <code>false</code> otherwise.
*/
public boolean isViewpointEventEnabled() {return viewpointEventEnabled;}
/**
* Sets the option that whether viewpoint events are posted during playback.
* When viewpoint events are enabled, they are posted during playback, and
* the user is not allowed to manipulate the module's viewpoint themselves.
* When viewpoint events are disabled, the user can use the navigation panel
* to manipulate the module's viewpoint during playback.
*
* @param enabled <code>true</code> if viewpoint events are to be enabled;
* <code>false</code> if viewpoint events are to be disabled.
*/
public void setViewpointEventEnabled(boolean enabled) {
viewpointEventEnabled=enabled;
}
//========================
// Informational routines
//========================
/**
* Checks whether a script is loaded. Note that scripts currently being
* recorded are not yet loaded.
*
* @return true if a script is loaded; false otherwise
*/
public boolean loaded() {return script!=null && !isRecording();}
/**
* Checks whether a script is playing.
*
* @return true if this <code>WSLPlayer</code> is playing back a script;
* false otherwise
*/
public boolean isPlaying() {return playing;}
/**
* Checks whether script playback is paused. This can only be the case if a
* script is being played.
*
* @return true if this <code>WSLPlayer</code> is paused during a script;
* false otherwise
*/
public boolean isPaused() {return paused;}
/**
* Checks whether a script is being recorded. Note that this is not the
* case once recording completes.
*
* @return true if a script is being recorded; false otherwise
*/
public boolean isRecording() {return recording;}
/**
* Returns the WSLModule that is tied to WSLPlayer.
*
* @return the WSLModule given this <code>WSLPlayer</code> at construction.
*/
public WSLModule getWSLModule() {return module;}
/**
* Returns the <code>WSLScript</code> instance that <code>WSLPlayer</code>
* keeps in memory.
*
* @return reference to this object's <code>WSLScript</code>;
* <code>null</code> if this object does not currently have a
* <code>WSLScript</code> loaded.
*/
public WSLScript getScript() {return script;}
/**
* Gets the current time in the script being played back.
*
* @return time of the script being played back in milliseconds.
*/
public long getCurrentScriptTime() {return Math.min(scriptT,totalScriptT);}
/**
* Gets the total time of the script kept in <code>WSLPlayer</code>
*
* @return total time of the script in milliseconds.
*/
public long getTotalScriptTime() {return totalScriptT;}
//===================
// Internal routines
//===================
private void calculateScriptLength() {
totalScriptT = 0;
for(int i=0;i<scriptNode.getChildCount();i++)
totalScriptT += scriptNode.getChild(i).getTimeStamp();
}
/*private void initNavigationPanelInfo() {
NamedNode nn = module.getNavigationPanelNode();
if(nn!=null && navPanel_setEnabled==null) {
navPanel_setEnabled =
(EventInSFBool) nn.node.getEventIn("set_enabled");
set_view =
(EventInMFFloat) nn.node.getEventIn("set_view");
set_activeView =
(EventInSFInt32) nn.node.getEventIn("set_activeView");
query_view =
(EventInSFBool) nn.node.getEventIn("query_view");
EAI.getEO(nn,"view_changed",this,new Integer(VIEW_CHANGED),null);
EAI.getEO(nn,"activeView_changed",this,
new Integer(ACTIVEVIEW_CHANGED),null);
EAI.getEO(nn,"queryView_changed",this,
new Integer(QUERYVIEW_CHANGED),null);
}
}*/
/*private void setView(String value) {
if(value==null) throw new NullPointerException("null view");
if(set_view==null) return;
int index=0;
for(int i=0;i<6;i++) {
try {
//Our own tokenizer; should probably actually write a silly
//string-splitter class. (StreamTokenizer doesn't handle scientific
//notation at all.) [Davis]
String next=WTString.delimited(value,index,' ');
index+=next.length()+1;
view[i]=new Float(next.trim()).floatValue();
} catch(NumberFormatException e) {
throw new IllegalArgumentException("bad view: "+value);
}
}
set_view.setValue(view);
}*/
//================
// Thread methods
//================
//Waits until it is next appropriate to dispatch an event, or until the
//playback has been stopped. When this method returns, the playback will
//not be paused.
private void delay() {
if(scriptIndex>=scriptNode.getChildCount()) return; // nothing left!
final long nextEventT=lastEventT+scriptNode.getChild(scriptIndex).getTimeStamp();
while(isPlaying()) {
synchronized(lock) {
if(isPaused()) {
//We treat the pausing as if it were a dispatched event:
lastEventT+=System.currentTimeMillis()-lastEventTime;
scriptT=lastEventT;
while(isPaused())
try{lock.wait();} catch(InterruptedException e) {}
lastEventTime=System.currentTimeMillis();
}
}
if(!isPaused()) {
//Note that scriptT may not == nextEventT when this test fails; this
//will make playback on the whole more accurate.
if(scriptT<nextEventT) {
//This is a bit strange; it amounts to 'always do the time-handling
//stuff, and skip the rest if we were interrupted'.
try {Thread.sleep(Math.min(nextEventT-scriptT,MAX_IDLE));}
catch(InterruptedException e) {continue;}
finally {
scriptT=System.currentTimeMillis()-lastEventTime+lastEventT;
postProgress(); // there perhaps should be a condition on this
}
} else return;
}
}
}
//Dispatches the next event (immediately), if there is one
private void dispatch() {
lastEventTime=System.currentTimeMillis();
if(scriptIndex < scriptNode.getChildCount()) {
lastEventT+=scriptNode.getChild(scriptIndex).getTimeStamp();
final WSLNode action = scriptNode.getChild(scriptIndex);
// if(action.getName().equals(VIEWPOINT_CHANGED)) {
// if(playbackVPEnabled)
// setView(action.getAttributes().getValue(WSLNode.VALUE));
// } else if(action.getName().equals(VIEWPOINT_SELECTED)) {
// if(playbackVPEnabled && set_activeView!=null)
// set_activeView.setValue(action.getAttributes().getIntValue(WSLNode.VALUE,0));
// }
if(!action.getName().equals(WSLScript.SCRIPT_END_TAG) &&
(playbackVPEnabled || (!action.getName().equals(VIEWPOINT_CHANGED) &&
!action.getName().equals(VIEWPOINT_SELECTED))))
postScriptAction(new WSLScriptEvent(this, action, module.getWSLModuleName()));
scriptIndex++;
}
}
/**
* This method is the thread started to play the script. It gradually scans
* through the script and posts script actions at timed intervals. When the
* script is finished, a <code>PLAYER_STOPPED</code> event is posted.
*
* @see webtop.wsl.event.WSLPlayerEvent#PLAYER_STOPPED
*/
public void run() {
//DEBUG:
//ThreadWatch.add(Thread.currentThread());
//We need our own copy so that mid-script changes don't confuse things
playbackVPEnabled=viewpointEventEnabled;
// if(navPanel_setEnabled!=null && playbackVPEnabled)
// navPanel_setEnabled.setValue(false);
scriptIndex=0;
scriptT=0;
lastEventT=0;
lastEventTime=System.currentTimeMillis();
while(scriptIndex<scriptNode.getChildCount()) {
delay();
if(!isPlaying()) break;
dispatch();
}
// if(navPanel_setEnabled!=null && playbackVPEnabled)
// navPanel_setEnabled.setValue(true);
playing=false; // this can be redundant, but is always ok
postPlayerStateChanged(WSLPlayerEvent.PLAYER_STOPPED);
}
//This method needs to go, eventually; NavigationPanelScripter is the way [Davis]
/**
* This method is called by External Authoring Interface (EAI) whenever the
* viewpoint is changed by the user. It records the viewpoint changes
* automatically when a script is being recorded.
*
* @param event the EventOut instance associated with the VRML event fired.
* @param timestamp the time stamp that signifies when the event was fired.
* @param param a custom parameter associated with the VRML event.
*/
// public void callback(EventOut event, double timestamp, Object param) {
// if(!isRecording()) return; // for efficiency
// int mode = ((Integer)param).intValue();
// if(mode == VIEW_CHANGED) {
// float view[] = ((EventOutMFFloat) event).getValue();
// StringBuffer value = new StringBuffer();
// for(int i=0; i<6; i++) {
// value.append(view[i]);
// if(i<5) value.append(' ');
// }
// recordViewpointChanged(value.toString());
// } else if(mode == ACTIVEVIEW_CHANGED) {
// int activeView = ((EventOutSFInt32)event).getValue();
// recordViewpointSelected(String.valueOf(activeView));
// } else if(mode == QUERYVIEW_CHANGED) {
// if(moduleNode!=null) {
// float view[] = ((EventOutMFFloat) event).getValue();
// StringBuffer value = new StringBuffer();
// for(int i=0; i<6; i++) {
// value.append(view[i]);
// if(i<5) value.append(' ');
// }
// WSLNode viewNode = new WSLNode("view");
// viewNode.getAttributes().add(WSLNode.VALUE, value.toString());
// moduleNode.addChild(viewNode);
// }
// }
// }
//========================
// Event Posting Routines
//========================
/**
* Adds an event listener. <code>WSLPlayer</code> only fires events to
* registered event listener, and the interfaces
* (<code>WSLScriptListener</code>, <code>WSLPlayerListener</code>, and/or
* <code>WSLProgressListener</code>) implemented by the class determines
* which types of events it receives.
*
* <p>It is worth noting that it is guaranteed that changes to the listeners
* list of a <code>WSLPlayer</code> made during the dispatch of a
* <code>WSLScriptEvent</code> will not affect the distribution of that
* event. This is to allow the creation or destruction of objects (which
* may be listening to the playback) during the handling of such an event.
*/
public void addListener(Object listener) {
if(listener!=null && !listeners.contains(listener))
listeners.addElement(listener);
}
/**
* Removes an event listener from <code>WSLPlayer</code>'s listener list.
*/
public void removeListener(Object listener) {
listeners.removeElement(listener);
}
private void postProgress() {
WSLProgressEvent event=new WSLProgressEvent(this,getCurrentScriptTime(),
getTotalScriptTime());
for(int i=0; i<listeners.size(); i++)
if(listeners.elementAt(i) instanceof WSLProgressListener)
try {
((WSLProgressListener)listeners.elementAt(i)).progressChanged(event);
} catch(RuntimeException e) {
System.err.println(EXCEPTION_MSG);
e.printStackTrace();
}
}
private void postScriptAction(WSLScriptEvent event) {
//It is a reasonable expectation that new listeners may be added during
//playback (as Java objects are created for module objects represented
//in the script tags). Thus, we work with a copy to avoid
//hard-to-determine behavior with new listeners.
Vector listeners=(Vector)this.listeners.clone(); //shadows class variable
for(int i=0; i<listeners.size(); i++)
if(listeners.elementAt(i) instanceof WSLScriptListener)
try {
((WSLScriptListener)listeners.elementAt(i)).scriptActionFired(event);
} catch(RuntimeException e) {
System.err.println(EXCEPTION_MSG);
e.printStackTrace();
}
}
private void postInitialize() {
// final WSLNode viewNode=moduleNode.getNode("view");
// if(viewNode!=null)
// setView(viewNode.getAttributes().getValue(WSLNode.VALUE));
final WSLScriptEvent event=new WSLScriptEvent(this,script.getModuleNode(),module.getWSLModuleName());
//It is a reasonable expectation that new listeners may be added during
//initialization (as Java objects are created for module objects stored
//in the inititialization tag). Thus, we work with a copy to avoid
//hard-to-determine behavior with new listeners.
Vector listeners=(Vector)this.listeners.clone(); //shadows class variable
for(int i=0; i<listeners.size(); i++)
if(listeners.elementAt(i) instanceof WSLScriptListener)
try {
((WSLScriptListener)listeners.elementAt(i)).initialize(event);
} catch(RuntimeException e) {
System.err.println(EXCEPTION_MSG);
e.printStackTrace();
}
}
private void postPlayerStateChanged(int id) {
WSLPlayerEvent event = new WSLPlayerEvent(this, id);
for(int i=0; i<listeners.size(); i++)
if(listeners.elementAt(i) instanceof WSLPlayerListener)
try {
((WSLPlayerListener)listeners.elementAt(i)).playerStateChanged(event);
} catch(RuntimeException e) {
System.err.println(EXCEPTION_MSG);
e.printStackTrace();
}
}
//====================
// Recording routines
//====================
/**
* Records that the user has added a new object into the WebTOP module (for
* example, a new polarizer in the Polarization module).
*
* @param obj the new object added represented as a <code>WSLNode</code>.
*/
public void recordObjectAdded(final WSLNode obj) {
final WSLNode node=new WSLNode(OBJECT_ADDED);
node.addChild(obj);
record(node);
}
/**
* Records that the user has removed an object from the WebTOP module, for
* example, a polarizer in the Polarization module.
*
* @param id identifier of the object to be removed.
*/
public void recordObjectRemoved(String id) {
recordAction(OBJECT_REMOVED,id,null,null);
}
/**
* Records that the user has performed an action with the Java applet. This
* version of <code>recordActionPerformed()</code> only records actions that
* affects the module as a whole, rather than just affecting a particular
* object, or parameter. For example, when the user clicks on the Reset
* button to reset the WebTOP module to its default state.
*
* @param action name of the action performed.
*/
public void recordActionPerformed(String action) {
recordAction(ACTION_PERFORMED, null, action, null);
}
/**
* Records that the user has entered a value for a particular parameter in
* the Java applet.
*
* @param param the parameter affected.
* @param value the new value of the parameter.
*/
public void recordActionPerformed(String param, String value) {
recordAction(ACTION_PERFORMED, null, param, value);
}
/**
* Records that the user has entered a value for a particular parameter of an
* object in the Java applet. This might be the value of the angle parameter
* of a polarizer in the Polarization module.
*
* @param id identifier of the object affected.
* @param param the parameter affected.
* @param value the new value of the parameter.
*/
public void recordActionPerformed(String id, String param, String value) {
recordAction(ACTION_PERFORMED, id, param, value);
}
/**
* Records that the user has moved the mouse pointer into a VRML widget.
*
* @param id identifier of the object the mouse pointer moves into.
*/
public void recordMouseEntered(String id) {
recordAction(MOUSE_IN,id,null,null);
}
/**
* Records that the user has moved the mouse pointer out of a VRML widget.
*
* @param id identifier of the object the mouse pointer moves out of.
*/
public void recordMouseExited(String id) {
recordAction(MOUSE_OUT,id,null,null);
}
/**
* Records that the user has clicked the mouse button on a VRML widget.
*
* @param param the parameter that the VRML widget associated with.
*/
public void recordMousePressed(String param) {
recordAction(MOUSE_DOWN, null, param, null);
}
/**
* Records that the user has clicked the mouse button on a VRML widget
* associated with a particular object.
*
* @param id the identifier of the object.
* @param param the parameter associated with the VRML widget.
*/
public void recordMousePressed(String id, String param) {
recordAction(MOUSE_DOWN, id, param, null);
}
/**
* Records that the user has released the mouse button from a VRML widget.
*
* @param param the parameter that the VRML widget associated with.
*/
public void recordMouseReleased(String param) {
recordAction(MOUSE_UP, null, param, null);
}
/**
* Records that the user has released the mouse button from a VRML widget
* associated with a certain object.
*
* @param id the identifier of the object.
* @param param the parameter associated with the VRML widget.
*/
public void recordMouseReleased(String id, String param) {
recordAction(MOUSE_UP, id, param, null);
}
/**
* Records that the user has dragged a VRML widget.
*
* @param param the parameter associated with the the VRML widget.
* @param value the new value of the parameter.
*/
public void recordMouseDragged(String param, String value) {
recordAction(MOUSE_DRAG, null, param, value);
}
/**
* Records that the user has dragged a VRML widget associated with a
* particular object.
*
* @param id identifier of the object affected.
* @param param the parameter associated with the VRML widget.
* @param value the new value of the parameter.
*/
public void recordMouseDragged(String id, String param, String value) {
recordAction(MOUSE_DRAG, id, param, value);
}
/**
* Records that the user has changed the viewpoint for the module. This
* method is typically only called by <code>WSLPlayer</code> since it records
* all viewpoint events automatically.
*
* @param value the new viewpoint specified as a six-value String. The
* first three floating-point values specify the rotation in
* each of X, Y, and Z-axis, and the last three floating-point
* values specify pan in the X, Y, and Z directions.
*/
public void recordViewpointChanged(String value) {
recordAction(VIEWPOINT_CHANGED, null, null, value);
}
/**
* Records that the user has selected a preset viewpoint. This method is
* typically only called by <code>WSLPlayer</code> since it records all
* viewpoint events automatically.
*
* @param value the number of the preset viewpoint selected, starting at 0.
*/
public void recordViewpointSelected(String value) {
recordAction(VIEWPOINT_SELECTED, null, null, value);
}
/**
* The most general form of recording method. All user interactions are
* abstracted as action tags with three attributes: <code>id</code>,
* <code>param</code>, and <code>value</code>. The name of the tag
* signifies the type of the user interaction, while its attributes specify
* the object affected (<code>id</code>), the parameter affected
* (<code>param</code>), and the new value of the parameter
* (<code>value</code>). Attributes can be excluded where inapplicable.
* Generally, this method is rarely used externally. Instead, the different
* versions of recording methods specific to different user interactions are
* used.
*
* @param action name of script tag to write.
* @param id target object's identifying string.
* @param param name of changed value.
* @param value new parameter value.
*/
//Should this be public? It allows writing of non-existent action tags... [Davis]
public void recordAction(String action, String id, String param, String value) {
WSLAttributeList atts = new WSLAttributeList();
if(!WTString.isNull(id)) atts.add(WSLNode.TARGET, id);
if(!WTString.isNull(param)) atts.add(WSLNode.PARAMETER, param);
if(!WTString.isNull(value)) atts.add(WSLNode.VALUE, value);
recordAction(action, atts);
}
/**
* Internal generic recording function. Allows the specification of any
* attributes.
*
* @param action name of script tag to write.
* @param atts attributes for the tag.
*/
private void recordAction(String action, WSLAttributeList atts) {
record(new WSLNode(action,atts));
}
/**
* Internal generic recording function. Allows the specificaion of any node
* whatsoever.
*
* @param node the node to record.
*/
//This function is ultimately responsible for the silent returns
private void record(WSLNode node) {
if(isRecording()) {
final long time=System.currentTimeMillis();
node.setTimeStamp(time-prevRecordTime);
scriptNode.addChild(node);
prevRecordTime=time;
}
}
}
|
package com.xy.module.base.helper;
import android.content.Intent;
import android.text.TextPaint;
import android.text.style.ClickableSpan;
import android.view.View;
import com.xy.module.base.BaseActivity;
import com.xy.module.base.bean.ContentValue;
/**
* Created by Administrator on 2017/12/1.
*/
public class ClickSpanHelper<T> extends ClickableSpan {
private Class<T> mClass;
private BaseActivity thisClass;
private int mTextColor;
private boolean isUnderLine;
private ContentValue[] contentValues;
public ClickSpanHelper(BaseActivity thisClass, Class<T> skipClass, int textColor,
boolean isUnderLine , ContentValue... contentValues){
this.thisClass = thisClass;
this.mClass = skipClass;
this.mTextColor = textColor;
this.isUnderLine = isUnderLine;
this.contentValues = contentValues;
}
@Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
ds.setColor(mTextColor);
ds.setUnderlineText(isUnderLine);
}
@Override
public void onClick(View widget) {
Intent intent = new Intent(thisClass,mClass);
if (contentValues!= null){
for (ContentValue value : contentValues) {
if (value.value instanceof String) {
intent.putExtra(value.key, (String) value.value);
} else if (value.value instanceof Integer)
intent.putExtra(value.key, Integer.parseInt(value.value.toString()));
else if (value.value instanceof Boolean) {
intent.putExtra(value.key, Boolean.parseBoolean(value.value.toString()));
}
}
}
thisClass.startActivity(intent);
// thisClass.overridePendingTransition(R.anim.machine_enter,0);
}
}
|
package pl.sda.lottery.lotteries;
public interface Lottery {
int getTicketCost();
String getPrize();
default String getName() {
return this.getClass().getSimpleName();
}
}
|
package com.infohold.ebpp.bill.web.rest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.infohold.core.dao.Page;
import com.infohold.core.exception.BaseException;
import com.infohold.core.manager.GenericManager;
import com.infohold.core.utils.JSONUtils;
import com.infohold.core.utils.StringUtils;
import com.infohold.core.web.MediaTypes;
import com.infohold.core.web.rest.BaseRestController;
import com.infohold.core.web.utils.Result;
import com.infohold.core.web.utils.ResultUtils;
import com.infohold.ebpp.bill.manager.BillInstanceManager;
import com.infohold.ebpp.bill.model.BillInstance;
import com.infohold.ebpp.bill.model.BillType;
import com.infohold.ebpp.bill.model.BizChannel;
import com.infohold.ebpp.bill.model.PayInfo;
@RestController
@RequestMapping("/bill/instance")
public class BillInstanceRestController extends BaseRestController {
@Autowired
private BillInstanceManager billInstanceManager;
@Autowired
private GenericManager<BizChannel, String> bizChannelManager;
@Autowired
private GenericManager<BillType, String> billTypeManager;
/**
* 创建账单
*
* @param data
* @return
*/
@RequestMapping(value = "/create", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
public Result forCreate(@RequestBody String data) {
log.info("创建账单,输入数据为:【" + data + "】");
checkEmpty(data, "输入数据data不能为空!");
BillInstance tbi = JSONUtils.deserialize(data, BillInstance.class);
if (null == tbi) {
throw new BaseException("输入数据为空!");
}
if(StringUtils.isNotBlank(tbi.getBizChannel())){
BizChannel biz = bizChannelManager.get(tbi.getBizChannel());
if (null == biz) {
throw new BaseException("无效的业务渠道bizChannel!");
}
}
if(StringUtils.isNotBlank(tbi.getType())){
BillType bt = billTypeManager.get(tbi.getType());
if (null == bt) {
throw new BaseException("无效的账单类型type!");
}
}
tbi = this.billInstanceManager.create(tbi);
return ResultUtils.renderSuccessResult(tbi);
}
/**
* 批量创建账单
*
* @param data
* @return
*/
@RequestMapping(value = "/batchcreate", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
public String forBatchCreate(@RequestBody String data) {
log.info("批量创建账单,输入数据为:【" + data + "】");
if (StringUtils.isEmpty(data)) {
throw new BaseException("输入数据为空!");
}
JSONObject object = null;
object = JSON.parseObject(data);
JSONArray jas= object.getJSONArray("data");
BillInstance bi = null;
StringBuffer sb = new StringBuffer("{success:'true',data:[");
for(int i=0; i<jas.size(); i++){
Object jo = jas.get(i);
bi = JSON.parseObject(jo.toString(), BillInstance.class);
bi = this.billInstanceManager.create(bi);
sb.append(",{");
sb.append("id:'").append(bi.getId()).append("',");
sb.append("id:'").append(bi.getId()).append("',");
sb.append("id:'").append(bi.getId()).append("',");
sb.append("id:'").append(bi.getId()).append("',");
sb.append("id:'").append(bi.getId()).append("',");
sb.append("id:'").append(bi.getId()).append("',");
sb.append("id:'").append(bi.getId()).append("'}");
}
// tbi
// if (null == tbi) {
// throw new BaseException("输入数据为空!");
// }
//
//
// tbi = this.billInstanceManager.create(tbi);
return "";
}
/**
* 账单基本信息更新
*
* @param data
* @return
*/
@RequestMapping(value = "/{no}", method = RequestMethod.PUT, produces = MediaTypes.JSON_UTF_8)
public Result forUpdate(@PathVariable(value="no") String no, @RequestBody String data) {
log.info("账单基本信息更新,输入数据为:【" + data + "】");
checkEmpty(data, "输入数据data不能为空!");
checkEmpty(no, "流水号no不能为空!");
BillInstance tbi = JSONUtils.deserialize(data, BillInstance.class);
tbi.setNo(no);
if(StringUtils.isNotBlank(tbi.getBizChannel())){
BizChannel biz = bizChannelManager.get(tbi.getBizChannel());
if (null == biz) {
throw new BaseException("无效的业务渠道bizChannel!");
}
}
if(StringUtils.isNotBlank(tbi.getType())){
BillType bt = billTypeManager.get(tbi.getType());
if (null == bt) {
throw new BaseException("无效的账单类型type!");
}
}
BillInstance ret = this.billInstanceManager.update(tbi);
return ResultUtils.renderSuccessResult(ret);
}
/**
* 账单实例状态变更
*
* @param data
* @return
*/
@RequestMapping(value = "/updatestatus/{no}", method = RequestMethod.PUT, produces = MediaTypes.JSON_UTF_8)
public Result forUpdateStatus(@PathVariable(value="no") String no, @RequestBody String data) {
log.info("账单实例状态变更,输入数据为:【" + data + "】");
checkEmpty(data, "输入数据data不能为空!");
checkEmpty(no, "流水号no不能为空!");
BillInstance tbi = JSONUtils.deserialize(data, BillInstance.class);
tbi.setNo(no);
BillInstance ret = this.billInstanceManager.updateStatus(tbi);
return ResultUtils.renderSuccessResult(ret);
}
/**
* 账单实例撤销
*
* @param data
* @return
*/
@RequestMapping(value = "/{no}", method = RequestMethod.DELETE, produces = MediaTypes.JSON_UTF_8)
public Result forAbandon(@PathVariable(value="no") String no) {
log.info("账单实例撤销,输入数据为:【" + no + "】");
checkEmpty(no, "流水号no不能为空!");
BillInstance tbi = new BillInstance();
tbi.setNo(no);
BillInstance ret = this.billInstanceManager.abandon(tbi);
return ResultUtils.renderSuccessResult(ret);
}
/**
* 账单分页查询
*
* @param data
* @return
*/
@SuppressWarnings("unchecked")
@RequestMapping(value = "/query", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
public Page forQuery(@RequestParam(value = "data", defaultValue = "") String data) {
log.info("账单分页查询,输入查询内容为:" + data);
Map<String, Object> params = new HashMap<String, Object>();
if (StringUtils.isEmpty(data)) {
log.info("查询账单信息,输入查询内容为空:");
}else{
params = JSONUtils.deserialize(data, Map.class);
}
return this.billInstanceManager.query(params);
}
/**
* 账单单体查询
*
* @param data
* @return
*/
@RequestMapping(value = "/{no}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
public Result forInfo(@PathVariable("no") String no) {
log.info("账单单体查询,输入no为:【" + no + "】");
checkEmpty(no, "流水号no不能为空!");
BillInstance tbi = this.billInstanceManager.findOneByProp("no", no);
if (null == tbi) {
throw new BaseException("流水号【" + no + "】不存在!");
}
return ResultUtils.renderSuccessResult(tbi);
}
/**
* 支付成功通知接收
*
* @param data
* @return
*/
@RequestMapping(value = "/payInfo/load", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
public Result forPayInfoLoad(@RequestBody String data) {
log.info("支付成功通知接收,输入数据为:【" + data + "】");
checkEmpty(data, "输入数据data不能为空!");
PayInfo pi = null;
List<PayInfo> pis = new ArrayList<PayInfo>();
JSONObject object = null;
JSONArray pis1 = null;
object = JSON.parseObject(data);
pis1= object.getJSONArray("payInfo");
if ( null==pis1) {
throw new BaseException("付款详细信息payInfo不能为空!");
}
//记录PyaInfo公共部分信息
pi = JSON.parseObject(object.toJSONString(), PayInfo.class);
if ( null==pi) {
throw new BaseException("付款信息不能为空!");
}
pis.add(pi);
for(Object obj:pis1){
pi = JSON.parseObject(obj.toString(), PayInfo.class);
if ( null==pi) {
throw new BaseException("付款详细信息payInfo单条信息不能为空!");
}
pis.add(pi);
}
this.billInstanceManager.loadPayInfo(pis );
return ResultUtils.renderSuccessResult();
}
/**
* 批量支付成功通知接收
*
* @param data
* @return
*/
@RequestMapping(value = "/payInfo/batchload", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
public Result forPayInfoBatchLoad(@RequestBody String data) {
log.info("批量支付成功通知接收,输入数据为:【" + data + "】");
if (StringUtils.isEmpty(data)) {
throw new BaseException("输入数据为空!");
}
@SuppressWarnings("unchecked")
HashMap<String, Object> hp = JSONUtils.deserialize(data, HashMap.class);
// int total = (int)hp.get("total");
PayInfo pi = null;
try {
JSONArray jas = (JSONArray)hp.get("data");
for(int i=0; i<jas.size(); i++){
Object o = jas.get(i).toString();
pi = JSONUtils.deserialize(o.toString(), PayInfo.class);
// bid =
if (null != pi) {
// this.billInstanceManager.loadPayInfo(pi, bid);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ResultUtils.renderSuccessResult();
}
private void checkEmpty(String data, String msg){
if (StringUtils.isEmpty(data) || "null".equalsIgnoreCase(data.trim())) {
throw new BaseException(msg);
}
}
}
|
/*
package com.vip.exam.android_concepts;
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.alignminds.ivyplex.contracts.PreviousOrderContract;
import com.alignminds.ivyplex.utilities.ValidationUtil;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class EmailDialogue extends Dialog {
EmailDialogue emailDialoge = new EmailDialogue(PreviousOrderActivity.this);
emailDialoge.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
emailDialoge.setCancelable(false);
emailDialoge.show();
RelativeLayout startShiftCloseBtn;
private Activity home;
EditText sensEmlTxt;
RelativeLayout emailBtn;
public EmailDialogue(Activity home) {
super(home);
this.home = home;
// mView = (PreviousOrderContract.View) home;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.layout_send_email);
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
OnInit();
}
private void OnInit() {
}
@OnClick({R.id.email_btn, R.id.start_shift_close_btn})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.email_btn:
if (ValidationUtil.validateUserEmail(sensEmlTxt.getText().toString(), home)) {
mView.sendEmail(sensEmlTxt.getText().toString());
dismiss();
} else
Toast.makeText(home, "Please enter valid Email", Toast.LENGTH_SHORT).show();
break;
case R.id.start_shift_close_btn:
dismiss();
break;
}
}
}*/
|
/*
* 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.
*/
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author mtech
*/
@WebServlet(urlPatterns = {"/fileupload1"})
public class fileupload1 extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
//String path = "/home/mtech/Desktop/xlsfiles/";
String excelFilePath= "/home/mtech/NetBeansProjects/WebApplication4/src/java/sheet3.xlsx";
String from=request.getParameter("t1");
String to=request.getParameter("t2");
list reader = new list();
List<city> listcity = reader.readcityFromExcelFile(excelFilePath);
for(int i=0;i<listcity.size();i++)
{
if(listcity.get(i).getFrom().equalsIgnoreCase(from) && listcity.get(i).getTo().equalsIgnoreCase(to))
{
out.println("company is:"+listcity.get(i).getCompany()+"<br>Fare is: "+listcity.get(i).getFare()+"<br>time is: "+listcity.get(i).getTime());
break;
}
else
{
for (int j = 0; j <listcity.size() ; j++)
{
if(listcity.get(j).getTo().equalsIgnoreCase(listcity.get(j).getFrom()))
{
if(listcity.get(j).getTo().equalsIgnoreCase(to))
{
// Double b = listcity.get(j).getFare();
out.println("from:" + listcity.get(j).getFrom() + "to:" + listcity.get(i).getTo() + "company is:" + listcity.get(j).getCompany() + "time is:" + listcity.get(j).getTime() + "fare is:" + listcity.get(j).getFare());
// Double c = listcity.get(j).getFare() ;
// Double y = listcity.get(j).getTime();
// Double z = listcity.get(j).getTime() + y;
//
out.println("\nfrom:" + listcity.get(j).getFrom() + "to:" + listcity.get(j).getTo() + "company is:" + listcity.get(j).getCompany() + "time is:" + listcity.get(j).getTime() + "fare is:" + listcity.get(j).getFare() );
}
}
}
}
}
}}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
package org.jetlang.remote.core;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
/**
* User: mrettig
* Date: 4/6/11
* Time: 12:30 PM
*/
public class JavaSerializationReader implements ObjectByteReader<Object> {
public Object readObject(String fromTopic, byte[] buffer, int offset, int length) throws IOException {
ByteArrayInputStream readStream = new ByteArrayInputStream(buffer, offset, length);
try {
return new ObjectInputStream(readStream).readObject();
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
}
|
import java.io.*;
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
static long makingAnagrams(String s1, String s2){
Set<Integer> allChars = (s1 + s2).chars().boxed().collect(Collectors.toSet());
Map<Integer, Long> s1Map = s1.chars().boxed().
collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
Map<Integer, Long> s2Map = s2.chars().boxed().
collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
return allChars.stream().mapToLong(c -> s1Map.getOrDefault(c, 0L) - s2Map.getOrDefault(c, 0L)).
map(Math :: abs).sum();
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String s1 = in.next();
String s2 = in.next();
long result = makingAnagrams(s1, s2);
System.out.println(result);
}
}
|
package tutorial.userService.controller;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import tutorial.userService.exception.UserNotFoundException;
import tutorial.userService.model.User;
import tutorial.userService.repostiory.UserRepository;
@RestController
public class UserController {
@Autowired
private UserRepository userRepository;
@PostMapping("/user")
public ResponseEntity<Void> addUser (@RequestBody User user) {
try {
User createUser = userRepository.save(user);
HttpHeaders headers = new HttpHeaders();
headers.add("id", createUser.getUserId().toString());
return new ResponseEntity<>(headers, HttpStatus.CREATED);
} catch (Exception e) {
return new ResponseEntity<Void>(HttpStatus.EXPECTATION_FAILED);
}
}
@GetMapping("/user/{id}")
public ResponseEntity<User> getUser(@PathVariable ("id") String id) throws UserNotFoundException {
try {
Optional<User> user = userRepository.findById(Long.valueOf(id));
return new ResponseEntity<User>(user.get(), HttpStatus.OK);
} catch (Exception e) {
throw new UserNotFoundException("User Not Found For id: "+ id);
}
}
@PutMapping("/user")
public ResponseEntity<User> update (@RequestBody User user){
try {
User updateUser = userRepository.save(user);
return new ResponseEntity<User>(updateUser, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.EXPECTATION_FAILED);
}
}
@DeleteMapping("user/{id}")
public ResponseEntity<User> deleteUser(@PathVariable("id") String id) {
try {
userRepository.deleteById(Long.valueOf(id));
return new ResponseEntity<>(HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.EXPECTATION_FAILED);
}
}
}
|
package com.buttercell.vaxn.guardian;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.buttercell.vaxn.R;
import com.buttercell.vaxn.common.Common;
import com.buttercell.vaxn.doctor.DoctorRecords;
import com.buttercell.vaxn.model.Record;
import com.buttercell.vaxn.model.User;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.paperdb.Paper;
/**
* A simple {@link Fragment} subclass.
*/
public class PatientRecords extends android.app.Fragment {
private static final String TAG = "PatientRecords";
@BindView(R.id.recordsList)
RecyclerView recordsList;
Unbinder unbinder;
String guardianKey="";
private FirebaseRecyclerAdapter<Record, RecordViewHolder> adapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_patient_records, container, false);
unbinder = ButterKnife.bind(this, view);
return view;
}
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Paper.init(getContext());
if(Paper.book().read("currentUser")!=null)
{
User user=Paper.book().read("currentUser");
if(user.getUserRole().equals("Doctor"))
{
guardianKey=Common.guardian_key;
}
else
{
guardianKey=FirebaseAuth.getInstance().getCurrentUser().getUid();
}
}
Query query = FirebaseDatabase.getInstance().getReference("Users").
child(guardianKey).child("userPatients").
child(Common.patient_key).child("userRecords");
FirebaseRecyclerOptions<Record> options =
new FirebaseRecyclerOptions.Builder<Record>()
.setQuery(query, Record.class)
.build();
adapter = new FirebaseRecyclerAdapter<Record, RecordViewHolder>(options) {
@Override
public RecordViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.record_layout, parent, false);
return new RecordViewHolder(view);
}
@Override
protected void onBindViewHolder(@NonNull RecordViewHolder holder, int position, @NonNull Record model) {
holder.setTestName(model.getTestName());
holder.setTestResults(model.getTestResults());
}
};
recordsList.setHasFixedSize(true);
recordsList.setLayoutManager(new LinearLayoutManager(getActivity()));
recordsList.setAdapter(adapter);
}
public static class RecordViewHolder extends RecyclerView.ViewHolder {
public RecordViewHolder(View itemView) {
super(itemView);
}
public void setTestResults(String results) {
TextView txtTestResult = itemView.findViewById(R.id.txt_test_results);
txtTestResult.setText(results);
}
public void setTestName(String name) {
TextView txtTestName = itemView.findViewById(R.id.txt_test_name);
txtTestName.setText(name);
}
}
@Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
}
@Override
public void onStart() {
super.onStart();
adapter.startListening();
}
@Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
}
|
package com.atguigu.java3;
/*
赋值方式 : 1.默认值 2.显示赋值 3.构造器赋值 4.对象名.方法名 ,对象名.属性名 5.代码块
赋值顺序 : 1 -> 2,5(谁在前面谁先赋值) -> 3 -> 4
*/
public class SetValue {
public static void main(String[] args) {
new Number().show();
}
}
/*
1.执行语句是从上到下依次执行的。
*/
class Number{
//多个代码块:从上到下
{
a = 20;
// b = a + 10; //如果代码块在属性的前面,代码块只能对属性执行赋值操作
}
//多个属性 :从上到下依次执行
//创建对象时: 1.先声明属性 2.再进行赋值操作 :①先看属性前有没有代码块如果有就代码块先操作 ,然后才是显示赋值的操作
int a = 10;
int b = a;
public void show(){
System.out.println(a);
}
}
|
package com.esum.appcommon.util;
public class UtilWeekOfMonth {
private int week;
private String startDate; /* yyyymmdd */
private String endDate;
public UtilWeekOfMonth() { }
public UtilWeekOfMonth(int week, String startDate, String endDate) {
this.week = week;
this.startDate = startDate;
this.endDate = endDate;
}
public int getWeek() {
return this.week;
}
public String getStartDate() {
return this.startDate;
}
public String getEndDate() {
return this.endDate;
}
public void setWeek(int week) {
this.week = week;
}
public void setStartDate(String startDate) {
this.startDate = startDate;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
}
|
package ParkingLotDesign;
/**
* Created by FLK on 4/14/18.
*/
public class ParkingSpot implements IParkingSpace {
private final String id;
private Vehicle parkingVehicle;
private final int size;
private VehicleType vehicleType;
private final ParkingLevel parkingLevel;
public ParkingSpot(final String id, final VehicleType vehicleType, final ParkingLevel parkingLevel){
this.id = id;
this.vehicleType = vehicleType;
parkingVehicle = null;
size = vehicleType.getValue();
this.parkingLevel = parkingLevel;
}
public String getId(){
return id;
}
public int getSize(){
return size;
}
public Vehicle getVehicle(){
return parkingVehicle;
}
public VehicleType getVehicleType(){
return vehicleType;
}
public boolean isEmpty(){
return parkingVehicle == null;
}
public boolean canPark(final Vehicle vehicle){
if(!isEmpty() || vehicle.getSize() > size) return false;
return true;
}
public boolean vehiclePark(final Vehicle vehicle){
if(!canPark(vehicle)) return false;
parkingVehicle = vehicle;
return true;
}
public int getEmptySpotNum() {
return parkingVehicle == null ? 1 : 0;
}
public void vehicleLeavePark(){
parkingVehicle = null;
parkingLevel.vehicleLeavePark(parkingVehicle);
}
}
|
package com.logzc.webzic.repository;
import com.logzc.webzic.annotation.Autowired;
import com.logzc.webzic.annotation.Component;
import com.logzc.webzic.junit4.WebzicJUnit4ClassRunner;
import com.logzc.webzic.repository.dao.UserDaoTest;
import com.logzc.webzic.repository.dao.UserTest;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.sql.SQLException;
import java.util.List;
/**
* Created by lishuang on 2016/10/18.
*/
@Component
@RunWith(WebzicJUnit4ClassRunner.class)
public class DaoTest {
@Autowired
UserDaoTest userDaoTest;
@Test
public void testBasic() throws SQLException {
List<UserTest> userTestList = userDaoTest.queryAll();
for (UserTest u : userTestList) {
System.out.println(u.username);
}
}
@Test
public void testCustom() throws SQLException {
List<UserTest> userTestList = userDaoTest.queryByGender(0);
for (UserTest u : userTestList) {
System.out.println(u.username + " " + u.gender);
}
List<UserTest> userTestList1 = userDaoTest.queryByUsernameAndGender("pengye", 1);
for (UserTest u : userTestList1) {
System.out.println(u.username + " " + u.gender);
}
List<UserTest> userTestList2 = userDaoTest.queryByUsernameOrGender("Johnson", 1);
for (UserTest u : userTestList2) {
System.out.println(u.username + " " + u.gender);
}
}
}
|
@javax.xml.bind.annotation.XmlSchema(namespace = "http://basistam.pl/")
package pl.basistam.client;
|
package ru.job4j.sorting;
import java.util.Comparator;
public class UserAgeSort implements Comparator<User> {
@Override
public int compare(User o1, User o2) {
return o1.getAge().compareTo(o2.getAge());
}
}
|
package br.unitins.app2;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.google.android.material.textfield.TextInputEditText;
public class MainActivity extends AppCompatActivity {
private TextInputEditText edNome;
private TextInputEditText edIdade;
private TextInputEditText edEmail;
private TextInputEditText edTelefone;
private TextInputEditText edCpf;
private TextView textoResultado;
private String nome;
private String idade;
private String email;
private String telefone;
private String cpf;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edNome = findViewById(R.id.editNome);
edIdade = findViewById(R.id.editIdade);
edEmail = findViewById(R.id.editEmail);
edTelefone = findViewById(R.id.editTelefone);
edCpf = findViewById(R.id.editCpf);
textoResultado = findViewById(R.id.textResultado);
if (savedInstanceState != null){
nome = savedInstanceState.getString("sNome");
idade = savedInstanceState.getString("sIdade");
email = savedInstanceState.getString("sEmail");
telefone = savedInstanceState.getString("sTelefone");
cpf = savedInstanceState.getString("sCpf");
textoResultado.setText("nome: " + nome + "\n idade: " + idade + "\n email: " + email +"\n telefone: " + telefone + "\n cpf: " + cpf);
}
}
public void enviar(View view){
nome = edNome.getText().toString();
idade = edIdade.getText().toString();
email = edEmail.getText().toString();
telefone = edTelefone.getText().toString();
cpf = edCpf.getText().toString();
textoResultado.setText("nome: " + nome + "\n idade: " + idade + "\n email: " + email +"\n telefone: " + telefone + "\n cpf: " + cpf);
}
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("sNome", nome);
outState.putString("sIdade", idade);
outState.putString("sEmail", email);
outState.putString("sTelefone", telefone);
outState.putString("sCpf", cpf);
}
@Override
protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
nome = savedInstanceState.getString("sNome");
idade = savedInstanceState.getString("sIdade");
email = savedInstanceState.getString("sEmail");
telefone = savedInstanceState.getString("sTelefone");
cpf = savedInstanceState.getString("sCpf");
}
} |
/**
* Created by Jeffrey on 3/23/2016.
*/
import java.text.DecimalFormat;
public class PrintValues {
private static double equation (double e){
double a = 0.30;
double o = 5.67* Math.pow(10, -8);
double Save = 342;
double partOne = (2*(1-a)*Save);
double partTwo = (o*(2-e));
double prePower = partOne/partTwo;
double fraction = (double) 1/4;
return Math.pow(prePower, fraction);
}
public static void main(String[]args){
DecimalFormat df = new DecimalFormat("0.00E0");
for (double i = 0; i < 1; i=i+0.1){
System.out.println(df.format(equation(i)));
}
}
}
|
package io.ceph.rgw.client.model;
import io.ceph.rgw.client.BucketClient;
import io.ceph.rgw.client.action.ActionFuture;
import io.ceph.rgw.client.action.ActionListener;
/**
* Created by zhuangshuo on 2020/3/16.
*/
public class DeleteBucketRequest extends BaseBucketRequest {
public DeleteBucketRequest(String bucketName) {
super(bucketName);
}
@Override
public String toString() {
return "RemoveBucketRequest{} " + super.toString();
}
public static class Builder extends BaseBucketRequest.Builder<Builder, DeleteBucketRequest, DeleteBucketResponse> {
public Builder(BucketClient client) {
super(client);
}
@Override
public DeleteBucketRequest build() {
return new DeleteBucketRequest(bucketName);
}
@Override
public DeleteBucketResponse run() {
return client.deleteBucket(build());
}
@Override
public ActionFuture<DeleteBucketResponse> execute() {
return client.deleteBucketAsync(build());
}
@Override
public void execute(ActionListener<DeleteBucketResponse> listener) {
client.deleteBucketAsync(build(), listener);
}
}
}
|
package com.comp301.a09nonograms.controller;
import com.comp301.a09nonograms.model.Clues;
import com.comp301.a09nonograms.model.Model;
import com.comp301.a09nonograms.model.ModelImpl;
public class ControllerImpl implements Controller {
ModelImpl CurrentModel;
public ControllerImpl(Model model) {
CurrentModel = (ModelImpl) model;
}
@Override
public Clues getClues() {
return CurrentModel.GetClues();
}
@Override
public boolean isSolved() {
return CurrentModel.isSolved();
}
@Override
public boolean isShaded(int row, int col) {
return CurrentModel.isShaded(row, col);
}
@Override
public boolean isEliminated(int row, int col) {
return CurrentModel.isEliminated(row, col);
}
@Override
public void toggleShaded(int row, int col) {
CurrentModel.toggleCellShaded(row, col);
}
@Override
public void toggleEliminated(int row, int col) {
CurrentModel.toggleCellEliminated(row, col);
}
@Override
public void nextPuzzle() {
if (CurrentModel.getPuzzleIndex() == CurrentModel.getPuzzleCount() - 1) {
CurrentModel.setPuzzleIndex(0);
} else {
CurrentModel.setPuzzleIndex(CurrentModel.getPuzzleIndex() + 1);
}
}
@Override
public void prevPuzzle() {
if (CurrentModel.getPuzzleIndex() == 0) {
CurrentModel.setPuzzleIndex(CurrentModel.getPuzzleCount() - 1);
} else {
CurrentModel.setPuzzleIndex(CurrentModel.getPuzzleIndex() - 1);
}
}
@Override
public void randPuzzle() {
int min = 0;
int max = CurrentModel.getPuzzleCount() - 1;
int currentpuzzle = CurrentModel.getPuzzleIndex();
int random = CurrentModel.getPuzzleIndex();
while (random == currentpuzzle) {
random = (int) Math.floor(Math.random() * (max - min + 1) + min);
}
CurrentModel.setPuzzleIndex(random);
}
@Override
public void clearBoard() {
CurrentModel.clear();
}
@Override
public int getPuzzleIndex() {
return CurrentModel.getPuzzleIndex();
}
@Override
public int getPuzzleCount() {
return CurrentModel.getPuzzleCount();
}
}
|
package subconsciouseye.eyetech.recipes;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.oredict.ShapedOreRecipe;
import net.minecraftforge.oredict.ShapelessOreRecipe;
import subconsciouseye.eyetech.init.Blockz;
import subconsciouseye.eyetech.init.Itemz;
public class RecipesGeneral {
public static void addRecipes()
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(Blockz.blockCopper), "AAA","AAA","AAA",'A',"ingotCopper"));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(Itemz.ingotCopper,9),"blockCopper"));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(Blockz.blockSteel), "AAA","AAA","AAA",'A',"ingotSteel"));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(Itemz.ingotSteel,9),"blockSteel"));
GameRegistry.addSmelting(Items.iron_ingot, new ItemStack(Itemz.ingotSteel), 0.4F);
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(Itemz.pickaxeSteel), "AAA"," B "," B ",'A',"ingotSteel",'B',"stickWood"));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(Itemz.swordSteel), "A","A","B",'A',"ingotSteel",'B',"stickWood"));
}
}
|
package com.GestiondesClub.dao;
import javax.transaction.Transactional;
import org.springframework.data.jpa.repository.JpaRepository;
import com.GestiondesClub.entities.ProgrammeEvent;
public interface ProgrammeEventDao extends JpaRepository<ProgrammeEvent, Long> {
ProgrammeEvent findByLesActionId(long id);
}
|
package DSA.udemy.stack;
public class MyStackLinkedList<E> implements MyStack<E> {
private Node<E> top;
private Node<E> bottom;
private int size;
@Override
public E push(E element) {
Node<E> newNode = new Node<>(element);
if(this.size == 0) {
this.top = newNode;
this.bottom = newNode;
}else {
newNode.next = this.top;
this.top = newNode;
}
this.size++;
return element;
}
@Override
public E pop() {
if(this.top == null) return null;
Node<E> top = this.top;
if(this.size == 1) {
this.top = this.bottom = null;
}
this.top = top.next;
this.size--;
return top.data;
}
@Override
public E peek() {
if(top == null) return null;
return this.top.data;
}
@Override
public int size() {
return this.size;
}
@Override
public boolean isEmpty() {
return this.size == 0;
}
static class Node<E> {
E data;
Node<E> next;
public Node(E data) {
this.data = data;
}
}
}
|
package com.fanfte.java8.test;
import java.util.Collections;
import java.util.List;
/**
* Created by tianen on 2018/9/3
*
* @author fanfte
* @date 2018/9/3
**/
public class LambdaInPractice {
public static void main(String[] args) {
List<Object> list = Collections.emptyList();
List<Object> objects = list.subList(1, list.size());
System.out.println();
}
}
|
package slimeknights.tconstruct.world;
import net.minecraft.block.BlockLeaves;
import net.minecraft.block.BlockSapling;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.client.renderer.block.statemap.IStateMapper;
import net.minecraft.client.renderer.block.statemap.StateMap;
import net.minecraft.client.renderer.color.BlockColors;
import net.minecraft.client.resources.IReloadableResourceManager;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.util.math.BlockPos;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.fml.client.registry.RenderingRegistry;
import slimeknights.tconstruct.common.ClientProxy;
import slimeknights.tconstruct.common.ModelRegisterUtil;
import slimeknights.tconstruct.library.client.renderer.RenderTinkerSlime;
import slimeknights.tconstruct.world.block.BlockSlimeGrass;
import slimeknights.tconstruct.world.block.BlockSlimeGrass.FoliageType;
import slimeknights.tconstruct.world.block.BlockSlimeSapling;
import slimeknights.tconstruct.world.block.BlockTallSlimeGrass;
import slimeknights.tconstruct.world.client.CustomStateMap;
import slimeknights.tconstruct.world.client.SlimeColorizer;
import slimeknights.tconstruct.world.entity.EntityBlueSlime;
public class WorldClientProxy extends ClientProxy {
public static SlimeColorizer slimeColorizer = new SlimeColorizer();
public static Minecraft minecraft = Minecraft.getMinecraft();
@Override
public void preInit() {
((IReloadableResourceManager) minecraft.getResourceManager()).registerReloadListener(slimeColorizer);
// Entities
RenderingRegistry.registerEntityRenderingHandler(EntityBlueSlime.class, RenderTinkerSlime.FACTORY_BlueSlime);
super.preInit();
}
@Override
public void init() {
final BlockColors blockColors = minecraft.getBlockColors();
// slime grass, slime tall grass, and slime leaves
blockColors.registerBlockColorHandler(
(state, access, pos, tintIndex) -> {
FoliageType type = state.getValue(BlockSlimeGrass.FOLIAGE);
return getSlimeColorByPos(pos, type, null);
},
TinkerWorld.slimeGrass, TinkerWorld.slimeGrassTall);
// leaves are a bit shifted, so they have slightly different tone than the grass they accompany
blockColors.registerBlockColorHandler(
(state, access, pos, tintIndex) -> {
FoliageType type = state.getValue(BlockSlimeGrass.FOLIAGE);
return getSlimeColorByPos(pos, type, SlimeColorizer.LOOP_OFFSET);
},
TinkerWorld.slimeLeaves);
// slime vines don't use a foliage color state, so color them directly
blockColors.registerBlockColorHandler(
(state, access, pos, tintIndex) -> getSlimeColorByPos(pos, FoliageType.BLUE, SlimeColorizer.LOOP_OFFSET),
TinkerWorld.slimeVineBlue1, TinkerWorld.slimeVineBlue2, TinkerWorld.slimeVineBlue3);
blockColors.registerBlockColorHandler(
(state, access, pos, tintIndex) -> getSlimeColorByPos(pos, FoliageType.PURPLE, SlimeColorizer.LOOP_OFFSET),
TinkerWorld.slimeVinePurple1, TinkerWorld.slimeVinePurple2, TinkerWorld.slimeVinePurple3);
// item models simply pull the data from the block models, to make things easier for each separate type
minecraft.getItemColors().registerItemColorHandler(
(stack, tintIndex) -> {
IBlockState iblockstate = ((ItemBlock) stack.getItem()).getBlock().getStateFromMeta(stack.getMetadata());
return blockColors.colorMultiplier(iblockstate, null, null, tintIndex);
},
TinkerWorld.slimeGrass, TinkerWorld.slimeGrassTall, TinkerWorld.slimeLeaves,
TinkerWorld.slimeVineBlue1, TinkerWorld.slimeVineBlue2, TinkerWorld.slimeVineBlue3,
TinkerWorld.slimeVinePurple1, TinkerWorld.slimeVinePurple2, TinkerWorld.slimeVinePurple3);
super.init();
}
@Override
public void registerModels() {
// blocks
ModelLoader.setCustomStateMapper(TinkerWorld.slimeGrass, (new StateMap.Builder()).ignore(BlockSlimeGrass.FOLIAGE).build());
ModelLoader.setCustomStateMapper(TinkerWorld.slimeLeaves, (new StateMap.Builder())
.ignore(BlockSlimeGrass.FOLIAGE, BlockLeaves.CHECK_DECAY, BlockLeaves.DECAYABLE).build());
ModelLoader.setCustomStateMapper(TinkerWorld.slimeGrassTall, (new StateMap.Builder()).ignore(BlockSlimeGrass.FOLIAGE).build());
ModelLoader.setCustomStateMapper(TinkerWorld.slimeSapling, (new StateMap.Builder()).ignore(BlockSlimeSapling.STAGE, BlockSapling.TYPE).build());
IStateMapper vineMap = new CustomStateMap("slime_vine");
ModelLoader.setCustomStateMapper(TinkerWorld.slimeVineBlue1, vineMap);
ModelLoader.setCustomStateMapper(TinkerWorld.slimeVinePurple1, vineMap);
vineMap = new CustomStateMap("slime_vine_mid");
ModelLoader.setCustomStateMapper(TinkerWorld.slimeVineBlue2, vineMap);
ModelLoader.setCustomStateMapper(TinkerWorld.slimeVinePurple2, vineMap);
vineMap = new CustomStateMap("slime_vine_end");
ModelLoader.setCustomStateMapper(TinkerWorld.slimeVineBlue3, vineMap);
ModelLoader.setCustomStateMapper(TinkerWorld.slimeVinePurple3, vineMap);
// items
ModelRegisterUtil.registerItemBlockMeta(TinkerWorld.slimeDirt);
// slime grass
Item grass = Item.getItemFromBlock(TinkerWorld.slimeGrass);
for(BlockSlimeGrass.FoliageType type : BlockSlimeGrass.FoliageType.values()) {
for(BlockSlimeGrass.DirtType dirt : BlockSlimeGrass.DirtType.values()) {
String variant = String.format("%s=%s,%s=%s",
BlockSlimeGrass.SNOWY.getName(),
BlockSlimeGrass.SNOWY.getName(false),
BlockSlimeGrass.TYPE.getName(),
BlockSlimeGrass.TYPE.getName(dirt)
);
int meta = TinkerWorld.slimeGrass.getMetaFromState(TinkerWorld.slimeGrass.getDefaultState()
.withProperty(BlockSlimeGrass.TYPE, dirt)
.withProperty(BlockSlimeGrass.FOLIAGE, type));
ModelLoader.setCustomModelResourceLocation(grass, meta, new ModelResourceLocation(grass.getRegistryName(), variant));
}
}
// slime leaves
Item leaves = Item.getItemFromBlock(TinkerWorld.slimeLeaves);
for(BlockSlimeGrass.FoliageType type : BlockSlimeGrass.FoliageType.values()) {
ModelLoader.setCustomModelResourceLocation(leaves, type.getMeta(), new ModelResourceLocation(leaves.getRegistryName(), "normal"));
}
IBlockState state = TinkerWorld.slimeSapling.getDefaultState();
Item sapling = Item.getItemFromBlock(TinkerWorld.slimeSapling);
ItemStack stack = new ItemStack(sapling, 1, TinkerWorld.slimeSapling.getMetaFromState(state.withProperty(BlockSlimeSapling.FOLIAGE, BlockSlimeGrass.FoliageType.BLUE)));
registerItemModelTiC(stack, "slime_sapling_blue");
stack = new ItemStack(sapling, 1, TinkerWorld.slimeSapling.getMetaFromState(state.withProperty(BlockSlimeSapling.FOLIAGE, BlockSlimeGrass.FoliageType.PURPLE)));
registerItemModelTiC(stack, "slime_sapling_purple");
stack = new ItemStack(sapling, 1, TinkerWorld.slimeSapling.getMetaFromState(state.withProperty(BlockSlimeSapling.FOLIAGE, BlockSlimeGrass.FoliageType.ORANGE)));
registerItemModelTiC(stack, "slime_sapling_orange");
for(BlockSlimeGrass.FoliageType foliage : BlockSlimeGrass.FoliageType.values()) {
state = TinkerWorld.slimeGrassTall.getDefaultState();
state = state.withProperty(BlockTallSlimeGrass.FOLIAGE, foliage);
state = state.withProperty(BlockTallSlimeGrass.TYPE, BlockTallSlimeGrass.SlimePlantType.TALL_GRASS);
stack = new ItemStack(TinkerWorld.slimeGrassTall, 1, TinkerWorld.slimeGrassTall.getMetaFromState(state));
registerItemModelTiC(stack, "slime_tall_grass");
state = state.withProperty(BlockTallSlimeGrass.TYPE, BlockTallSlimeGrass.SlimePlantType.FERN);
stack = new ItemStack(TinkerWorld.slimeGrassTall, 1, TinkerWorld.slimeGrassTall.getMetaFromState(state));
registerItemModelTiC(stack, "slime_fern");
}
registerItemModelTiC(new ItemStack(TinkerWorld.slimeVineBlue1), "slime_vine");
registerItemModelTiC(new ItemStack(TinkerWorld.slimeVineBlue2), "slime_vine_mid");
registerItemModelTiC(new ItemStack(TinkerWorld.slimeVineBlue3), "slime_vine_end");
registerItemModelTiC(new ItemStack(TinkerWorld.slimeVinePurple1), "slime_vine");
registerItemModelTiC(new ItemStack(TinkerWorld.slimeVinePurple2), "slime_vine_mid");
registerItemModelTiC(new ItemStack(TinkerWorld.slimeVinePurple3), "slime_vine_end");
}
private int getSlimeColorByPos(BlockPos pos, FoliageType type, BlockPos add) {
if(pos == null) {
return SlimeColorizer.getColorStatic(type);
}
if(add != null) {
pos = pos.add(add);
}
return SlimeColorizer.getColorForPos(pos, type);
}
}
|
/**
*
*/
package eu.fbk.dycapo.activities;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
/**
* @author riccardo
*
*/
public class FastChoice extends Activity implements OnClickListener {
/*
* (non-Javadoc)
*
* @see android.app.Activity#onCreate(android.os.Bundle)
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.setContentView(R.layout.trip);
Button newTrip = (Button) this.findViewById(R.id.newTripButton);
newTrip.setOnClickListener(this);
Button recentTrip = (Button) this.findViewById(R.id.recentTripButton);
recentTrip.setOnClickListener(this);
Button mostTrip = (Button) this.findViewById(R.id.mostTripButton);
mostTrip.setOnClickListener(this);
Button historyTrip = (Button) this.findViewById(R.id.historyTripButton);
historyTrip.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.newTripButton:
Intent intent = new Intent();
intent.setClass(this, TripSettings.class);
intent.putExtras(this.getIntent().getExtras());
this.startActivity(intent);
break;
case R.id.mostTripButton:
break;
case R.id.recentTripButton:
break;
case R.id.historyTripButton:
break;
}
}
}
|
package ir.shayandaneshvar.blog.security;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import ir.shayandaneshvar.blog.exceptions.SpringBlogException;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.io.IOException;
import java.security.*;
import java.security.cert.CertificateException;
@Component
public class JwtProvider {
private KeyStore key;
@PostConstruct
public void init() {
try {
key = KeyStore.getInstance("JKS");
key.load(getClass().getResourceAsStream("/springblog.jks"),
"123456".toCharArray());
} catch (KeyStoreException | IOException | NoSuchAlgorithmException |
CertificateException e) {
e.printStackTrace();
throw new SpringBlogException("An error occurred while loading " +
"the keystore");
}
}
public String generateToken(Authentication auth) {
UserPrincipal principal = (UserPrincipal) auth.getPrincipal();
return Jwts.builder().setSubject(principal.getUsername())
.signWith(getPrivateKey())
.compact();
}
private PrivateKey getPrivateKey() {
try {
return (PrivateKey) key.getKey("springblog",
"123456".toCharArray());
} catch (KeyStoreException | NoSuchAlgorithmException |
UnrecoverableKeyException e) {
throw new SpringBlogException("Exception occurred while " +
"retrieving the private key from the keystore", e);
}
}
public boolean validateToken(String jwt) {
Jwts.parserBuilder().setSigningKey(getPublicKey())
.build()
.parseClaimsJws(jwt);
return true;
}
private PublicKey getPublicKey() {
try {
return key.getCertificate("springblog").getPublicKey();
} catch (KeyStoreException e) {
throw new SpringBlogException("Exception occurred while " +
"retrieving the public key from the keystore", e);
}
}
public String getUsername(String jwt) {
Claims claims = Jwts.parserBuilder()
.setSigningKey(getPublicKey()).build()
.parseClaimsJws(jwt).getBody();
return claims.getSubject();
}
}
|
package egovframework.adm.rep.service.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import egovframework.adm.rep.dao.ReportProfDAO;
import egovframework.adm.rep.service.ReportProfService;
import egovframework.com.utl.fcc.service.EgovStringUtil;
import egovframework.rte.fdl.cmmn.EgovAbstractServiceImpl;
@Service("reportProfService")
public class ReportProfServiceImpl extends EgovAbstractServiceImpl implements ReportProfService{
@Resource(name="reportProfDAO")
private ReportProfDAO reportProfDAO;
public List selectReportProfList(Map<String, Object> commandMap) throws Exception{
return reportProfDAO.selectReportProfList(commandMap);
}
public int insertReportProfData(Map<String, Object> commandMap) throws Exception{
int isOk = 1;
try{
List multiFiles = (ArrayList)commandMap.get("multiFiles");
if( multiFiles != null && multiFiles.size() > 0 ){
for( int i=0; i<multiFiles.size(); i++ ){
commandMap.putAll((Map)multiFiles.get(i));
}
}
reportProfDAO.insertReportProfData(commandMap);
reportProfDAO.insertFilesData(commandMap);
}catch(Exception ex){
isOk = 0;
ex.printStackTrace();
}
return isOk;
}
public Map selectReportProfData(Map<String, Object> commandMap) throws Exception{
return reportProfDAO.selectReportProfData(commandMap);
}
public List selectProfFiles(Map<String, Object> commandMap) throws Exception{
return reportProfDAO.selectProfFiles(commandMap);
}
public int updateReportProfData(Map<String, Object> commandMap) throws Exception{
int isOk = 1;
try{
List multiFiles = (ArrayList)commandMap.get("multiFiles");
if( multiFiles != null && multiFiles.size() > 0 ){
for( int i=0; i<multiFiles.size(); i++ ){
commandMap.putAll((Map)multiFiles.get(i));
}
}
reportProfDAO.updateReportProfData(commandMap);
}catch(Exception ex){
isOk = 0;
ex.printStackTrace();
}
return isOk;
}
public int reportProfWeightUpdateData(Map<String, Object> commandMap) throws Exception{
int isOk = 1;
try{
String[] reportseq = EgovStringUtil.getStringSequence(commandMap, "p_reportseq");
String[] weight = EgovStringUtil.getStringSequence(commandMap, "p_weight");
for( int i=0; i<reportseq.length; i++ ){
commandMap.put("v_reportseq", reportseq[i]);
commandMap.put("v_weight", weight[i]);
reportProfDAO.reportProfWeightUpdateData(commandMap);
}
}catch(Exception ex){
isOk = 0;
ex.printStackTrace();
}
return isOk;
}
public List selectReportQuestionList(Map<String, Object> commandMap) throws Exception{
return reportProfDAO.selectReportQuestionList(commandMap);
}
public Map selectReportQuestionView(Map<String, Object> commandMap) throws Exception{
return reportProfDAO.selectReportQuestionView(commandMap);
}
/**
* 과제 문항 등록
* @param commandMap
* @return
* @throws Exception
*/
public boolean insertTzReportQues(Map<String, Object> commandMap) throws Exception{
boolean isok = false;
try {
Object v_examnum = reportProfDAO.insertTzReportQues(commandMap); //과제 문항 등록
isok = true;
}catch(Exception ex){
ex.printStackTrace();
}
return isok;
}
//과제문항 과정의 문항 조회
public List selectReportQuestionSubjList(Map<String, Object> commandMap) throws Exception{
return reportProfDAO.selectReportQuestionSubjList(commandMap);
}
public Map selectReportProfView(Map<String, Object> commandMap) throws Exception{
return reportProfDAO.selectReportProfView(commandMap);
}
//과제 문항 리스트
public List selectReportQuesList(Map<String, Object> commandMap) throws Exception{
return reportProfDAO.selectReportQuesList(commandMap);
}
//과제 등록
public int insertReportProf(Map<String, Object> commandMap) throws Exception{
int isOk = 0;
//과제 문항
String [] v_param = (String []) commandMap.get("_Array_p_params");
//체크박스 선택여부(1:checked/0:not checked)
String [] v_checkvalue = (String []) commandMap.get("_Array_checkvalue");
try{
List multiFiles = (ArrayList)commandMap.get("multiFiles");
if( multiFiles != null && multiFiles.size() > 0 ){
for( int i=0; i<multiFiles.size(); i++ ){
commandMap.putAll((Map)multiFiles.get(i));
}
//첨부파일
//reportProfDAO.insertReportProf(commandMap);
reportProfDAO.insertFilesData(commandMap);
}
//과제등록
reportProfDAO.insertReportProf(commandMap);
//평가과제문항삭제
reportProfDAO.deleteProjordSheet(commandMap);
if(v_param != null)
{
for ( int i = 0 ; i < v_checkvalue.length; i++ ) {
//v_checkvalue 1인 경우(선택)만 저장을 실행한다.
if(v_checkvalue[i].equals("1"))
{
commandMap.put("v_quesnum", v_param[i]);
//평가과제문항 저장
reportProfDAO.insertProjordSheet(commandMap);
}
}
}
isOk = 1;
}catch(Exception ex){
isOk = 0;
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
ex.printStackTrace();
}
return isOk;
}
//과제 수정
public int updateReportProf(Map<String, Object> commandMap) throws Exception{
int isOk = 0;
//과제 문항
String [] v_param = (String []) commandMap.get("_Array_p_params");
//체크박스 선택여부(1:checked/0:not checked)
String [] v_checkvalue = (String []) commandMap.get("_Array_checkvalue");
try{
List multiFiles = (ArrayList)commandMap.get("multiFiles");
if( multiFiles != null && multiFiles.size() > 0 ){
for( int i=0; i<multiFiles.size(); i++ ){
commandMap.putAll((Map)multiFiles.get(i));
}
//첨부파일
reportProfDAO.insertFilesData(commandMap);
}
if( commandMap.get("p_filedel") != null ){
reportProfDAO.deleteReportProfFiles(commandMap);
}
//과제수정
reportProfDAO.updateReportProf(commandMap);
//평가과제문항삭제
reportProfDAO.deleteProjordSheet(commandMap);
if(v_param != null)
{
for ( int i = 0 ; i < v_checkvalue.length; i++ ) {
//v_checkvalue 1인 경우(선택)만 저장을 실행한다.
if(v_checkvalue[i].equals("1"))
{
commandMap.put("v_quesnum", v_param[i]);
//평가과제문항 저장
reportProfDAO.insertProjordSheet(commandMap);
}
}
}
isOk = 1;
}catch(Exception ex){
isOk = 0;
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
ex.printStackTrace();
}
return isOk;
}
//과제 문항 수정
public int updateTzReportQues(Map<String, Object> commandMap) throws Exception{
int isOk = 0;
try{
//과제수정
reportProfDAO.updateTzReportQues(commandMap);
isOk = 1;
}catch(Exception ex){
isOk = 0;
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
ex.printStackTrace();
}
return isOk;
}
//과제 문항 삭제
public int deleteTzReportQues(Map<String, Object> commandMap) throws Exception{
int isOk = 0;
try{
//과제문항 보기
Map reportQuestionView = reportProfDAO.selectReportQuestionView(commandMap);
String useyn = reportQuestionView.get("useyn").toString();
if(useyn.equals("Y")){
isOk = -1;
return isOk;
}
//과제수정
reportProfDAO.deleteTzReportQues(commandMap);
isOk = 1;
}catch(Exception ex){
isOk = 0;
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
ex.printStackTrace();
}
return isOk;
}
//과제 출제 문항 리스트
public List selectReportQuesSubjseqList(Map<String, Object> commandMap) throws Exception{
return reportProfDAO.selectReportQuesSubjseqList(commandMap);
}
}
|
package com.durgam.guerra.dominio;
import javax.persistence.Entity;
import javax.persistence.PrimaryKeyJoinColumn;
@Entity
@PrimaryKeyJoinColumn(name = "id")
public class RequisitoSimple extends Requisito {
public RequisitoSimple() {
super();
}
public RequisitoSimple(long id, String nombre, String necesidad, String prioridad, String riesgo,
Proyecto proyecto) {
super(id, nombre, necesidad, prioridad, riesgo, proyecto);
}
public Boolean compuesto() {
return Boolean.FALSE;
}
}
|
/*
* Copyright (c) 2013-2014, Neuro4j.org
*
* 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.neuro4j.studio.debug.ui.model;
import org.eclipse.gmf.runtime.diagram.ui.editparts.ShapeNodeEditPart;
import org.eclipse.gmf.runtime.notation.impl.ShapeImpl;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.neuro4j.studio.core.ActionNode;
import org.neuro4j.studio.debug.core.BreakpoinMng;
public class RemoveBreakPointAction implements IObjectActionDelegate {
protected ShapeNodeEditPart selectedElement;
@SuppressWarnings("restriction")
public void run(IAction action) {
if (selectedElement != null)
{
ShapeImpl shape = (ShapeImpl) selectedElement.getModel();
ActionNode node = (ActionNode) shape.getElement();
BreakpoinMng.getInstance().removeNodeFromBreakpoint(node);
}
}
public void selectionChanged(IAction action, ISelection selection) {
selectedElement = null;
if (selection instanceof IStructuredSelection) {
IStructuredSelection structuredSelection = (IStructuredSelection) selection;
if (structuredSelection.getFirstElement() instanceof ShapeNodeEditPart) {
selectedElement = (ShapeNodeEditPart) structuredSelection.getFirstElement();
}
}
}
public void setActivePart(IAction action, IWorkbenchPart targetPart) {
}
}
|
/* SpringTransactionSynchronizationListener.java
Purpose:
Description:
History:
Tue Sep 15 13:55:11 2006, Created by henrichen
Copyright (C) 2006 Potix Corporation. All Rights Reserved.
{{IS_RIGHT
This program is distributed under LGPL Version 2.1 in the hope that
it will be useful, but WITHOUT ANY WARRANTY.
}}IS_RIGHT
*/
package org.zkoss.zkplus.spring;
import org.zkoss.zkplus.util.ThreadLocals;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.UiException;
import org.zkoss.zk.ui.Execution;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.WebApp;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventThreadInit;
import org.zkoss.zk.ui.event.EventThreadResume;
import org.zkoss.zk.ui.event.EventThreadCleanup;
import org.zkoss.zk.ui.util.Configuration;
import org.zkoss.lang.Classes;
import org.zkoss.lang.SystemException;
import org.zkoss.util.logging.Log;
import java.util.Map;
import java.util.HashMap;
import java.lang.reflect.Field;
import java.util.List;
/**
* <p>Listener to make sure each ZK thread got the same ThreadLocal value of the
* spring's org.springframework.transaction.support.TransactionSynchronizationManager;
* especially those thread bound resources.
* </p>
* <p>
* This listener is used with Spring Framework (version 1.2.8+) "thread" bounded
* resources.
*
* <pre><code>
* <listener>
* <description>Spring TransactionSynchronizationManager handler</description>
* <listener-class>org.zkoss.zkplus.spring.SpringTransactionSynchronizationListener</listener-class>
* </listener>
* </code></pre>
* </p>
* <p>Applicable to Spring Framework version 2.x or later</p>
* @author henrichen
*/
public class SpringTransactionSynchronizationListener implements EventThreadInit, EventThreadCleanup, EventThreadResume {
private static final Log log = Log.lookup(SpringTransactionSynchronizationListener.class);
private Object[] _threadLocals = null;
private final boolean _enabled; //whether event thread enabled
public SpringTransactionSynchronizationListener() {
final WebApp app = Executions.getCurrent().getDesktop().getWebApp();
_enabled = app.getConfiguration().isEventThreadEnabled();
}
//-- EventThreadInit --//
public void prepare(Component comp, Event evt) {
if (_enabled) {
getThreadLocals(); //get from servlet thread's ThreadLocal
}
}
public boolean init(Component comp, Event evt) {
if (_enabled) {
setThreadLocals(); //copy to event thread's ThreadLocal
}
return true;
}
//-- EventThreadCleanup --//
public void cleanup(Component comp, Event evt, List errs) {
if (_enabled) {
getThreadLocals(); //get from event thread's ThreadLocal
//we don't handle the exception since the ZK engine will throw it again!
}
}
public void complete(Component comp, Event evt) {
if (_enabled) {
setThreadLocals(); //copy to servlet thread's ThreadLocal
}
}
//-- EventThreadResume --//
public void beforeResume(Component comp, Event evt) {
if (_enabled) {
getThreadLocals(); //get from servlet thread's ThreadLocal
}
}
public void afterResume(Component comp, Event evt) {
if (_enabled) {
setThreadLocals(); //copy to event thread's ThreadLocal
}
}
public void abortResume(Component comp, Event evt){
//do nothing
}
//-- utilities --//
private void getThreadLocals() {
try {
Class cls = Classes.forNameByThread("org.springframework.transaction.support.TransactionSynchronizationManager");
_threadLocals = new Object[7];
_threadLocals[0] = getThreadLocal(cls, "resources").get();
_threadLocals[1] = getThreadLocal(cls, "synchronizations").get();
_threadLocals[2] = getThreadLocal(cls, "currentTransactionName").get();
_threadLocals[3] = getThreadLocal(cls, "currentTransactionReadOnly").get();
_threadLocals[4] = getThreadLocal(cls, "actualTransactionActive").get();
//20070907, Henri Chen: bug 1785457, hibernate3 might not used
try {
cls = Classes.forNameByThread("org.springframework.orm.hibernate3.SessionFactoryUtils");
_threadLocals[5] = getThreadLocal(cls, "deferredCloseHolder").get();
} catch (ClassNotFoundException ex) {
//ignore if hibernate 3 is not used.
}
cls = Classes.forNameByThread("org.springframework.transaction.interceptor.TransactionAspectSupport");
//Spring 1.2.8 and Spring 2.0.x, the ThreadLocal field name has changed, default use 2.0.x
//2.0.x transactionInfoHolder
//1.2.8 currentTransactionInfo
try {
_threadLocals[6] = getThreadLocal(cls, "transactionInfoHolder").get();
} catch (SystemException ex) {
if (ex.getCause() instanceof NoSuchFieldException) {
_threadLocals[6] = getThreadLocal(cls, "currentTransactionInfo").get();
} else {
throw ex;
}
}
} catch (ClassNotFoundException ex) {
throw UiException.Aide.wrap(ex);
}
}
private void setThreadLocals() {
if (_threadLocals != null) {
try {
Class cls = Classes.forNameByThread("org.springframework.transaction.support.TransactionSynchronizationManager");
getThreadLocal(cls, "resources").set(_threadLocals[0]);
getThreadLocal(cls, "synchronizations").set(_threadLocals[1]);
getThreadLocal(cls, "currentTransactionName").set(_threadLocals[2]);
getThreadLocal(cls, "currentTransactionReadOnly").set(_threadLocals[3]);
getThreadLocal(cls, "actualTransactionActive").set(_threadLocals[4]);
//20070907, Henri Chen: bug 1785457, hibernate3 might not used
try {
cls = Classes.forNameByThread("org.springframework.orm.hibernate3.SessionFactoryUtils");
getThreadLocal(cls, "deferredCloseHolder").set(_threadLocals[5]);
} catch (ClassNotFoundException ex) {
//ignore if hibernate 3 is not used.
}
cls = Classes.forNameByThread("org.springframework.transaction.interceptor.TransactionAspectSupport");
//Spring 1.2.8 and Spring 2.0.x, the ThreadLocal field name has changed, default use 2.0.x
//2.0.x transactionInfoHolder
//1.2.8 currentTransactionInfo
try {
getThreadLocal(cls, "transactionInfoHolder").set(_threadLocals[6]);
} catch (SystemException ex) {
if (ex.getCause() instanceof NoSuchFieldException) {
getThreadLocal(cls, "currentTransactionInfo").set(_threadLocals[6]);
} else {
throw ex;
}
}
_threadLocals = null;
} catch (ClassNotFoundException ex) {
throw UiException.Aide.wrap(ex);
}
}
}
private ThreadLocal getThreadLocal(Class cls, String fldname) {
return ThreadLocals.getThreadLocal(cls, fldname);
}
}
|
package com.uniinfo.common.base;
/**
* 返回错误-枚举类
* @author hongzhou.yi
*/
public enum RespError {
//10** OAuth Error
OauthInvalidClient(1001, "无效Client"),
OauthInvalidUidPwd(1002, "用户名或密码有误"),
OauthInvalidCode(1003, "无效code"),
OauthInvalidToken(1004, "无效token"),
//11** Validate Error
ValidateInvalidCode(1104, "无效验证码"),
//9*** System Error
IllegalArgument(9001, "非法参数"),
ObjectNotExist(9002, "对象不存在"),
Unknown(9999, "Unknown");
/////////////////////////////
public int errorCode;
public String errorMsg;
private RespError(int errorCode, String errorMsg){
this.errorCode = errorCode;
this.errorMsg = errorMsg;
}
/**
* 通过code找对应的枚举类型
* @param code
* @return
*/
public static RespError find(int errorCode){
for(RespError e: RespError.values()){
if(e.errorCode==errorCode) return e;
}
return RespError.Unknown;
}
}
|
package com.zjf.myself.codebase.adapter;
import android.app.Activity;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.graphics.Palette;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.zjf.myself.codebase.R;
import java.util.ArrayList;
import java.util.List;
/**
* Created by WangChang on 2016/4/1.
*/
public class WaterFallAdapter extends RecyclerView.Adapter<WaterFallAdapter.BaseViewHolder> {
private ArrayList<String> dataList = new ArrayList<>();
private Resources res;
public void replaceAll(ArrayList<String> list) {
dataList.clear();
if (list != null && list.size() > 0) {
dataList.addAll(list);
}
notifyDataSetChanged();
}
@Override
public WaterFallAdapter.BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new OneViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.win_water_fall_item, parent, false));
}
@Override
public void onBindViewHolder(WaterFallAdapter.BaseViewHolder holder, int position) {
holder.setData(dataList.get(position));
}
@Override
public int getItemCount() {
return dataList != null ? dataList.size() : 0;
}
public class BaseViewHolder extends RecyclerView.ViewHolder {
public BaseViewHolder(View itemView) {
super(itemView);
}
void setData(Object data) {
}
}
private class OneViewHolder extends BaseViewHolder {
private ImageView ivImage;
public OneViewHolder(View view) {
super(view);
ivImage = (ImageView) view.findViewById(R.id.ivImage);
int width = ((Activity) ivImage.getContext()).getWindowManager().getDefaultDisplay().getWidth();
ViewGroup.LayoutParams params = ivImage.getLayoutParams();
//设置图片的相对于屏幕的宽高比
params.width = width/3;
params.height = (int) (200 + Math.random() * 400) ;
ivImage.setLayoutParams(params);
res = itemView.getContext().getResources();
}
@Override
void setData(Object data) {
if (data != null) {
String text = (String) data;
Glide.with(itemView.getContext()).load(text).diskCacheStrategy(DiskCacheStrategy.ALL).placeholder(R.mipmap.ic_launcher).crossFade().into(ivImage);
Bitmap bitmap = BitmapFactory.decodeResource(res,R.mipmap.ic_launcher);
//异步获得bitmap图片颜色值
Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {
@Override
public void onGenerated(Palette palette) {
Palette.Swatch vibrant = palette.getVibrantSwatch();//有活力
Palette.Swatch c = palette.getDarkVibrantSwatch();//有活力 暗色
Palette.Swatch d = palette.getLightVibrantSwatch();//有活力 亮色
Palette.Swatch f = palette.getMutedSwatch();//柔和
Palette.Swatch a = palette.getDarkMutedSwatch();//柔和 暗色
Palette.Swatch b = palette.getLightMutedSwatch();//柔和 亮色
if (vibrant != null) {
int color1 = vibrant.getBodyTextColor();//内容颜色
int color2 = vibrant.getTitleTextColor();//标题颜色
int color3 = vibrant.getRgb();//rgb颜色
ivImage.setBackgroundColor(
vibrant.getRgb());
}
}
});
}
}
}
}
|
package xyz.krakenkat.limitsservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import xyz.krakenkat.limitsservice.configuration.AppConfiguration;
@SpringBootApplication
@EnableDiscoveryClient
@EnableConfigurationProperties(AppConfiguration.class)
public class LimitsServiceApplication {
public static void main(String[] args) {
SpringApplication.run(LimitsServiceApplication.class, args);
}
}
|
package com.proyectogrado.alternativahorario.persistencia;
import com.proyectogrado.alternativahorario.entidades.Sede;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
/**
*
* @author Steven
*/
@Stateless
public class FachadaPersistenciaSede extends AbstractFacade<Sede> implements FachadaPersistenciaSedeLocal {
@PersistenceContext(unitName = "com.proyectogrado.AlternativaHorario_AlternativaHorario-persistencia_ejb_1.0-SNAPSHOTPU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public FachadaPersistenciaSede() {
super(Sede.class);
}
@Override
public Sede findByNombre(String nombre) {
Sede sede = null;
try {
Query query = getEntityManager().createNamedQuery("Sede.findByNombre");
query.setParameter("nombre", nombre);
sede = (Sede) query.getSingleResult();
} catch (Exception e) {
System.out.println("Error buscando Sede por nombre " + e);
}
return sede;
}
}
|
package literals;
public class Constants {
public static final String MAIN_HEADER = "EPAM FRAMEWORK WISHES";
public static final String MAIN_PAGE_TEXT_BELOW_HEADER = "LOREM IPSUM DOLOR SIT AMET, CONSECTETUR ADIPISICING ELIT," +
" SED DO EIUSMOD TEMPOR INCIDIDUNT UT LABORE ET DOLORE MAGNA ALIQUA. UT ENIM AD MINIM VENIAM, " +
"QUIS NOSTRUD EXERCITATION ULLAMCO LABORIS NISI UT ALIQUIP EX EA COMMODO CONSEQUAT DUIS AUTE IRURE DOLOR " +
"IN REPREHENDERIT IN VOLUPTATE VELIT ESSE CILLUM DOLORE EU FUGIAT NULLA PARIATUR.";
}
|
package com.nfschina.aiot.util;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jsoup.Connection;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;
import com.nfschina.aiot.entity.NewsContentEntity;
import com.nfschina.aiot.entity.NewsEntity;
import com.nfschina.aiot.entity.TemperatureEntity;
import android.R.bool;
/**
* 新闻正文分析器,提供新闻正文的页数,给出每一页对应的URL,通过解析html源码构造新闻正文实体并返回
* 爬取中国农村网(http://www.nongcun5.com/news/)
*
* @author xu
*
*/
public class NewsContentParserVillageCom extends NewsParser {
private String Url;
public NewsContentParserVillageCom(String url) {
Url = url;
}
@Override
public String getURL(int page) {
return Url;
}
@Override
public int getPageCount(Document document) {
return 1;
}
@Override
public List<NewsEntity> getNewsEntities(List<Document> documents) {
List<NewsEntity> newsContentEntities = new ArrayList<NewsEntity>();
NewsContentEntity newsContentEntity = new NewsContentEntity();
Document document = documents.get(0);
if (document != null) {
Elements elements = document.select("#title");
if (elements != null) {
newsContentEntity.setTitle(elements.text());
// 匹配时间
String info = document.select("div.info").text();
Pattern pattern = Pattern.compile("[0-9]{4}-[0-9]{2}-[0-9]{2}");
Matcher matcher = pattern.matcher(info);
if (matcher.find()) {
newsContentEntity.setTime(matcher.group(0));
}
// 匹配来源
int indexSource = info.indexOf("来源:") + 3;
int indexEnd = info.indexOf("浏览次数", indexSource);
if (indexEnd == -1 || indexSource == -1) {
return null;
}
newsContentEntity.setSource(info.substring(indexSource, indexEnd));
// 摘要
Elements es = document.select("div.introduce");
newsContentEntity.setSummary(es.get(0).text().substring(5));
// content += NewsTextFormat.getContent(es.get(0).text());
String content = "";
es = document.select("#article");
List<Node> nodes = es.get(0).childNodes();
// needNewParagraph表示是否需要新的段落,0表示上一个段落结束,1表示段落还未结束。当为1并且遇到标签p时,表示在标签外的文字已经结束
int needNewParagraph = 0;
String tmpString = "";
for (Node node : nodes) {
if (node instanceof Element && ((Element) node).tagName().equals("p")) {
if (needNewParagraph == 1) {
content += NewsTextFormat.getContent(tmpString);
}
content += NewsTextFormat.getContent(node.toString());
needNewParagraph = 0;
tmpString = "";
} else {
if (node instanceof Element)
tmpString += ((Element) node).text();
else
tmpString += node.toString();
needNewParagraph = 1;
}
}
if (!tmpString.equals("")) {
content += NewsTextFormat.getContent(tmpString);
}
newsContentEntity.setContent(content);
newsContentEntities.add(newsContentEntity);
}
}
return newsContentEntities;
}
@Override
public Connection addHeader(Connection connection) {
return connection;
}
@Override
public int getPrePageCount() {
return 1;
}
}
|
package org.netpreserve.urlcanon;
class UrlParser {
static ParsedUrl parseUrl(String s) {
ParsedUrl url = new ParsedUrl();
int pos = 0;
int len = s.length();
// leading control chars and spaces
while (pos < len && s.charAt(pos) <= 0x20) pos++;
url.setLeadingJunk(s.substring(0, pos));
// trailing control chars and spaces
while (pos < len && s.charAt(len - 1) <= 0x20) len--;
url.setTrailingJunk(s.substring(len));
// scheme [a-zA-Z] [^:]* :
if (pos < len && ((s.charAt(pos) >= 'a' && s.charAt(pos) <= 'z') || (s.charAt(pos) >= 'A' && s.charAt(pos) <= 'Z'))) {
int schemeStart = pos;
while (pos < len && s.charAt(pos) != ':') pos++;
if (pos < len && s.charAt(pos) == ':') {
url.setScheme(s.substring(schemeStart, pos));
url.setColonAfterScheme(":");
pos++;
} else { // no colon
pos = schemeStart; // backtrack
url.setScheme("");
url.setColonAfterScheme("");
}
} else {
url.setScheme("");
url.setColonAfterScheme("");
}
// pathish [^?#]*
int pathishStart = pos;
while (pos < len && s.charAt(pos) != '#' && s.charAt(pos) != '?') pos++;
parsePathish(url, s, pathishStart, pos);
// query string \? [^#]*
if (pos < len && s.charAt(pos) == '?') {
pos++;
url.setQuestionMark("?");
int queryStart = pos;
while (pos < len && s.charAt(pos) != '#') pos++;
url.setQuery(s.substring(queryStart, pos));
} else {
url.setQuestionMark("");
url.setQuery("");
}
// fragment # .*
if (pos < len && s.charAt(pos) == '#') {
pos++;
url.setHashSign("#");
url.setFragment(s.substring(pos, len));
} else {
url.setHashSign("");
url.setFragment("");
}
return url;
}
static void parsePathish(ParsedUrl url, String s, int pos, int end) {
String cleanScheme = removeTabsAndNewlinesAndLowercase(url.getScheme());
boolean isSpecial = ParsedUrl.SPECIAL_SCHEMES.containsKey(cleanScheme);
boolean isFile = cleanScheme.equals("file");
int slashCount = 0;
// slashes [\\/\r\n\y]*
int slashesStart = pos;
loop: while (pos < end) {
switch (s.charAt(pos)) {
case '\\':
if (!isSpecial) { // special schemes allow backslashes
break loop;
}
// fallthrough
case '/':
if (isFile || !isSpecial) {
if (slashCount == 2) break loop;
slashCount++;
}
// fallthrough
case '\r':
case '\n':
case '\t':
pos++;
continue;
default:
break loop;
}
}
url.setSlashes(s.substring(slashesStart, pos));
if (isFile) {
if (slashCount != 2) {
// no host? treat entire pathish as path
url.setPath(s.substring(slashesStart, end));
url.setSlashes("");
url.setUsername("");
url.setColonBeforePassword("");
url.setPassword("");
url.setAtSign("");
url.setHost("");
url.setColonBeforePort("");
url.setPort("");
return;
}
// host [^/\\]*
int startOfHost = pos;
while (pos < end && s.charAt(pos) != '/' && s.charAt(pos) != '\\') pos++;
url.setHost(s.substring(startOfHost, pos));
url.setUsername("");
url.setColonBeforePassword("");
url.setPassword("");
url.setAtSign("");
url.setColonBeforePort("");
url.setPort("");
} else if (isSpecial) {
// authority [^/\\]*
int startOfAuthority = pos;
while (pos < end && s.charAt(pos) != '/' && s.charAt(pos) != '\\') pos++;
parseAuthority(url, s, startOfAuthority, pos);
} else { // non special scheme
if (!removeTabsAndNewlinesAndLowercase(url.getSlashes()).equals("//")) {
// no double-slash? treat as opaque
url.setPath(s.substring(slashesStart, end));
url.setSlashes("");
url.setUsername("");
url.setColonBeforePassword("");
url.setPassword("");
url.setAtSign("");
url.setHost("");
url.setColonBeforePort("");
url.setPort("");
return;
}
// authority [^/]*
int startOfAuthority = pos;
while (pos < end && s.charAt(pos) != '/') pos++;
parseAuthority(url, s, startOfAuthority, pos);
}
// path [/\\\\] .*
url.setPath(s.substring(pos, end));
}
private static void parseAuthority(ParsedUrl url, String s, int pos, int end) {
// userinfo (.*@)?
int userinfoStart = pos;
int userinfoEnd = -1;
for (int i = pos; i < end; i++) {
if (s.charAt(i) == '@') {
userinfoEnd = i;
}
}
if (userinfoEnd != -1) {
parseUserinfo(url, s, userinfoStart, userinfoEnd);
pos = userinfoEnd + 1;
url.setAtSign("@");
} else { // no userinfo
url.setUsername("");
url.setColonBeforePassword("");
url.setPassword("");
url.setAtSign("");
}
// maybe ipv6 host \[[^]]*\]
int hostStart = pos;
if (pos < end && s.charAt(pos) == '[') {
pos++;
while (pos < end && s.charAt(pos) != ']') pos++;
if (pos < end && s.charAt(pos) == ']') {
pos++;
if (pos < end && s.charAt(pos) != ':') {
// backtrack
pos = hostStart;
}
}
}
// host [^:]*
while (pos < end && s.charAt(pos) != ':') pos++;
url.setHost(s.substring(hostStart, pos));
// port :.*
if (pos < end && s.charAt(pos) == ':') {
pos++;
url.setColonBeforePort(":");
url.setPort(s.substring(pos, end));
} else {
url.setColonBeforePort("");
url.setPort("");
}
}
private static void parseUserinfo(ParsedUrl url, String s, int i, int end) {
// username
int usernameStart = i;
while (i < end && s.charAt(i) != ':') i++;
url.setUsername(s.substring(usernameStart, i));
// password
if (i < end && s.charAt(i) == ':') {
url.setColonBeforePassword(":");
i++;
url.setPassword(s.substring(i, end));
} else {
url.setColonBeforePassword("");
url.setPassword("");
}
}
private static String removeTabsAndNewlinesAndLowercase(String s) {
StringBuilder sb = new StringBuilder(s.length());
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '\t' || c == '\n' || c == '\r') continue;
if (c >= 'A' && c <= 'Z') c += 32; // convert ascii caps to lowercase
sb.append(c);
}
return sb.toString();
}
}
|
package com.toni.programming.service;
import com.toni.programming.data.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class GameService {
private Integer maxPoints = 100;
UserAction userAction = new UserAction();
public static List<Pokemon> pokemonList = new ArrayList<>();
private static Pokemon currentLifeBeing = new Pokemon();
private static List<Actions> pokeActions = new ArrayList<>();
public void addPokemons(Pokemon pokemon){
pokemonList.add(pokemon);
}
public void addActions(Actions actions){
pokeActions.add(actions);
}
public void setPokeActions(List<Actions> pokeActions) {
GameService.pokeActions = pokeActions;
}
public List<Actions> getPokeActions(){
return pokeActions;
}
public List<Pokemon> getPokemonList() {
return pokemonList;
}
public void setPokemonList(List<Pokemon> pokemonList) {
GameService.pokemonList = pokemonList;
}
public Pokemon getCurrentLifeBeing() {
return currentLifeBeing;
}
public void setCurrentLifeBeing(Pokemon currentLifeBeing) {
GameService.currentLifeBeing = currentLifeBeing;
}
public void addPokeActions(List<Actions> actionsList) {
currentLifeBeing.setActions(actionsList);
}
public void doAction (Actions pokeaction){
switch (pokeaction){
case ATTACK:
getCurrentLifeBeing().doAttack();
addActions(pokeaction);
break;
case DEFEND:
getCurrentLifeBeing().doDefend();
addActions(pokeaction);
break;
case ESCAPE:
getCurrentLifeBeing().doEscape();
addActions(pokeaction);
break;
case EAT:
getCurrentLifeBeing().doEat();
addActions(pokeaction);
break;
case FLY:
getCurrentLifeBeing().doFly();
addActions(pokeaction);
break;
case HEAL:
getCurrentLifeBeing().doHeal();
addActions(pokeaction);
break;
case SWIM:
getCurrentLifeBeing().doSwim();
addActions(pokeaction);
break;
case WEAKENED:
getCurrentLifeBeing().doWeakened();
addActions(pokeaction);
break;
case DIG:
getCurrentLifeBeing().doDig();
addActions(pokeaction);
break;
case SLEEP:
getCurrentLifeBeing().doSleep();
addActions(pokeaction);
break;
}
}
public void reset() {
List<Actions> resetList = new ArrayList<>();
getCurrentLifeBeing().setStatus(new Status());
setPokeActions(resetList);
}
}
|
package com.example.mad;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import android.util.Log;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
Uri uri = null;
private static final int READ_REQUEST_CODE=42;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner s1=(Spinner) findViewById(R.id.spinner);
Spinner s2=(Spinner) findViewById(R.id.spinner2);
Button Upload=(Button)findViewById(R.id.button);
Button Convert=(Button)findViewById(R.id.button2);
String FileFormatFrom[]={"docx"};
String FileFormatTo[]={"pdf"};
s1.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, FileFormatFrom));
s2.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, FileFormatTo));
Upload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startSearch();
}
});
Convert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
convertFile();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_about,menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId())
{
case R.id.about:
Intent i=new Intent(MainActivity.this,content.class);
startActivity(i);
return true;
case R.id.contact:
Intent i1=new Intent(MainActivity.this,about.class);
startActivity(i1);
return true;
}
return super.onOptionsItemSelected(item);
}
private void startSearch(){
Intent intent=new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");//Files having MIME data type- fyi this is what he commented in the video
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent,READ_REQUEST_CODE);
}
@Override//Whatever you select after that this method will be called and result will be stored
//in the parameter of onActivityResult having datatype Intent
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==READ_REQUEST_CODE && resultCode== Activity.RESULT_OK){
if(data!=null){
uri=data.getData();
Log.i("Testing", uri.toString());
//Toast.makeText(this, "Uri"+uri, Toast.LENGTH_SHORT).show();
//Toast.makeText(this, "Path"+uri, Toast.LENGTH_SHORT).show();
}
}
}
protected void convertFile() {
if(uri!=null) {
File file = new File(uri.getPath());
String filename = file.getName();
Toast.makeText(this,"File "+filename,Toast.LENGTH_SHORT).show();
int size = (int) file.length();
Log.i("Testing", String.valueOf(size));
byte[] bytes = new byte[size];
try {
BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file));
buf.read(bytes, 0, bytes.length);
buf.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String base64EncodedFile = Base64.encodeToString(bytes, Base64.DEFAULT);
Log.i("Testing", base64EncodedFile);
//callAPI(filename, base64EncodedFile);
callAPI(filename, "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");
}
else {
Toast.makeText(this,"Choose a file", Toast.LENGTH_SHORT).show();
}
}
protected void callAPI(String filename, String base64EncodedFile) {
String URL = "https://v2.convertapi.com/convert/docx/to/pdf?Secret=vQXAaDU4PooP9Ju0"; //TODO Remove secret
JSONObject json = new JSONObject();
try {
JSONArray parametersJSON = new JSONArray();
JSONObject parametersJSONObject = new JSONObject();
parametersJSONObject.put("Name", "File");
JSONObject fileValue = new JSONObject();
fileValue.put("Name", filename);
fileValue.put("Data", base64EncodedFile);
parametersJSONObject.put("FileValue", fileValue);
parametersJSON.put(parametersJSONObject);
json.put("Parameters", parametersJSON);
Log.i("Testing", json.toString());//Make the JSON and send and receive the response and covert from base64
}
catch (JSONException e) {
e.printStackTrace();
}
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.i("Testing", response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
|
package dwz.persistence.mapper;
import java.util.List;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Repository;
import dwz.dal.BaseMapper;
import dwz.persistence.BaseConditionVO;
import sop.persistence.beans.Txn;
import sop.vo.TxnVo;
/**
* @Author: LCF
* @Date: 2020/1/8 17:32
* @Package: dwz.persistence.mapper
*/
@Repository
public interface TxnMapper extends BaseMapper<Txn, Integer> {
List<TxnVo> getTxnListByCondition(BaseConditionVO vo, RowBounds rb);
Integer getTxnListNumByCondition(BaseConditionVO vo);
Integer getCountByFkTxtCode(String txtCode);
Integer insertTxn(Txn txn);
Txn getTxnByFkTxtCode(String fkTxtCode);
Integer updateTxn(Txn txn);
List<TxnVo> getAllTxns();
Integer deleteTxn(String fkTxtCode);
}
|
package net.tanpeng.utils;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* 在做表的时候,需要班上同学的生日,现在已经有身份证了。所以我决定从身份证中截取
* Created by peng.tan on 17/10/8.
*/
public class FindBirthday {
public static void main(String[] args) throws IOException {
Path path = Paths.get("./src/main/java/net/peng/arithmetic/utils/a.txt");
Files.readAllLines(path).forEach(e->{
System.out.println(e.substring(6,14));
});
}
}
|
package lk.vcnet.storemodule.server;
import java.sql.ResultSet;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import lk.vcnet.storemodule.controller.exceptions.OrderException;
import lk.vcnet.storemodule.db.Contracts;
import me.colhh.mysqlmanager.MysqlAdapter;
public class Order {
private String vOID, vSID, vCheck;
private long vDate;
private int vCnt,msgconfirm,vrev;
private ArrayList<Order_Product> order_list = new ArrayList<>();
ResultSet rs=null;
public ArrayList<Order_Product> getOrderList() {
return order_list;
}
public void setOrderProductObjects(String[] pid,int[] qty)
{
Order_Product op;
for(int x=0;x<pid.length;x++)
{
op = new Order_Product();
op.setPID(pid[x]);
op.setQty(qty[x]);
order_list.add(op);
}
}
public String getvOID() {
return vOID;
}
public void setvOID(String vOID) {
this.vOID = vOID;
}
public String getvSID() {
return vSID;
}
public void setvSID(String vSID) {
this.vSID = vSID;
}
public String getvCheck() {
return vCheck;
}
public void setvCheck(String vCheck) {
this.vCheck = vCheck;
}
public long getvDate() {
return vDate;
}
public void setvDate(long vDate) {
this.vDate = vDate;
}
public int getvCnt() {
return vCnt;
}
public void setvCnt(int vCnt) {
this.vCnt = vCnt;
}
public int getVrev() {
return vrev;
}
public void setVrev(int vrev) {
this.vrev = vrev;
}
public ArrayList<Order_Product> getOrder_list() {
return order_list;
}
public void setOrder_list(ArrayList<Order_Product> order_list) {
this.order_list = order_list;
}
public void addOrder(){
try {
String sqladdOrder="Insert into "+Contracts.Order.TABLE_NAME+"values(?,?,?,?,?,?)";
String strnewID = ServerMain.newID(Contracts.Order.TABLE_NAME);
int intnweID =ServerMain.countRecords(Contracts.Order.TABLE_NAME);
MysqlAdapter.executeSql(sqladdOrder,strnewID, vSID, vDate, vCheck, intnweID,0);
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
public void searchOrder(){
try {
vrev=ServerMain.getRev(Contracts.Order.TABLE_NAME,Contracts.Order.TABLE_COLUMN_ID, vOID);
String sqlsearchorder="select * from "+Contracts.Order.TABLE_NAME+" where "+Contracts.Order.TABLE_COLUMN_ID+"=?";
MysqlAdapter.executeSql(sqlsearchorder,vOID);
if(rs.first()){
vOID=rs.getString(1);
vSID=rs.getString(2);
vDate=rs.getLong(3);
vCheck=rs.getString(4);
}
else{
throw new OrderException(OrderException.Exceptions.ORDER_NOT_EXISTING);
}
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
public void updateOrder(){
try {
int chkord=ServerMain.getRev(Contracts.Order.TABLE_NAME, Contracts.Order.TABLE_COLUMN_ID, vOID);
if(vrev==chkord){
chkord=chkord+1;
String sqlupdateorder="update "+Contracts.Order.TABLE_NAME+" set "+Contracts.Order.TABLE_COLUMN_ID+"=?, "+Contracts.Order.TABLE_COLUMN_SUPPLIER_ID_F+"=?, "+Contracts.Order.TABLE_COLUMN_DATE+"=?, "+Contracts.Order.TABLE_COLUMN_CHECK+"=?, where "+Contracts.Order.TABLE_COLUMN_ID+"=?";
MysqlAdapter.executeSql(sqlupdateorder, vSID, vDate, vCheck, vOID);
}
else{
throw new OrderException(OrderException.Exceptions.ORDER_UPDATED);
}
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
public void deletOrder(){
try {
String checkOrder="select "+Contracts.Order.TABLE_COLUMN_ID+" from "+Contracts.Order.TABLE_NAME+" where "+Contracts.Order.TABLE_COLUMN_ID+"=?";
boolean bl=MysqlAdapter.exists(checkOrder,vOID);
if(bl){
String sqldeltorder="delete from "+Contracts.Order.TABLE_NAME+" where "+Contracts.Order.TABLE_COLUMN_ID+"=?";
MysqlAdapter.executeSql(sqldeltorder,vOID);
}
else{
throw new OrderException(OrderException.Exceptions.ORDER_NOT_EXISTING);
}
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
|
package com.resjob.modules.app.service;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.resjob.common.persistence.Page;
import com.resjob.common.service.CrudService;
import com.resjob.modules.app.entity.MemberLogo;
import com.resjob.modules.app.dao.MemberLogoDao;
/**
* 会员头像Service
* @author wupeng
* @version 2016-05-19
*/
@Service
@Transactional(readOnly = true)
public class MemberLogoService extends CrudService<MemberLogoDao, MemberLogo> {
public MemberLogo get(String id) {
return super.get(id);
}
public List<MemberLogo> findList(MemberLogo memberLogo) {
return super.findList(memberLogo);
}
public Page<MemberLogo> findPage(Page<MemberLogo> page, MemberLogo memberLogo) {
return super.findPage(page, memberLogo);
}
@Transactional(readOnly = false)
public void save(MemberLogo memberLogo) {
super.save(memberLogo);
}
@Transactional(readOnly = false)
public void delete(MemberLogo memberLogo) {
super.delete(memberLogo);
}
} |
/**
* Spring Data Elasticsearch repositories.
*/
package com.eikesi.demo.de.repository.search;
|
package mocktest;
import com.github.tomakehurst.wiremock.WireMockServer;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
public class WireMockTest {
public static WireMockServer wireMockServer;
@BeforeAll
public static void BeforeAll() {
wireMockServer = new WireMockServer(wireMockConfig().port(8888));
// wireMockServer = new WireMockServer(); //必须按照以上官网写法
wireMockServer.start();
configureFor("localhost",8888);
}
@Test
public void stubTest () throws InterruptedException {
stubFor(get(urlEqualTo("/my/resource"))
.withHeader("Accept", equalTo("text/xml"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "text/xml")
.withBody("<response>淡看江湖路</response>")));
Thread.sleep(50000);
}
@Test
public void easyMock()throws InterruptedException{
stubFor(get(urlEqualTo("/ceshiren/chuchen"))
.withHeader("Accept",equalTo("text/xml"))
.willReturn(aResponse().withStatus(200)
.withHeader("Content-Type","text/xml")
.withBody("倚楼听风雨")));
Thread.sleep(10000);
reset();
stubFor(get(urlEqualTo("/ceshiren/chuchen"))
.withHeader("Accept",equalTo("text/xml"))
.willReturn(aResponse().withStatus(200)
.withHeader("Content-Type","text/xml")
.withBody("淡看江湖路")));
Thread.sleep(50000);
}
@Test
public void proxyMockTest(){
try {
stubFor(get(urlMatching(".*")).atPriority(10)
.willReturn(aResponse().proxiedFrom("https://ceshiren.com")));
//利用proxy,将指定url替换成本地url
// stubFor(get(urlEqualTo("categories_and_latest")).atPriority(1)
// .willReturn(aResponse().withStatus(503)));
stubFor(get(urlEqualTo("/categories_and_latest")).atPriority(1)
//通过json文件修改指定网页信息
.willReturn(aResponse().withBody(Files.readAllBytes(Paths
.get(WireMockTest.class.getResource("/chuchenmock.json")
.toURI())))));
Thread.sleep(50000);
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void printJsonTest(){
File f = new File(this.getClass().getResource("/chuchenmock.json").getPath());
System.out.println(f);
}
}
|
package com.aof.component.prm.Bill;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
/** @author Hibernate CodeGenerator */
public class ProjectEMS implements Serializable {
/** identifier field */
private Long id;
/** nullable persistent field */
private String type;
/** nullable persistent field */
private String no;
/** nullable persistent field */
private java.util.Date emsDate;
/** nullable persistent field */
private String status;
/** nullable persistent field */
private String note;
/** nullable persistent field */
private java.util.Date createDate;
/** nullable persistent field */
private com.aof.component.domain.party.UserLogin createUser;
/** nullable persistent field */
private com.aof.component.domain.party.Party department;
private Set invoices;
/** full constructor */
public ProjectEMS(Long id,
java.lang.String type,
java.lang.String no,
java.util.Date emsDate,
java.lang.String status,
java.lang.String note,
java.util.Date createDate,
com.aof.component.domain.party.UserLogin createUser,
com.aof.component.domain.party.Party department,
Set invoices) {
this.id = id;
this.type = type;
this.no = no;
this.emsDate = emsDate;
this.status = status;
this.note = note;
this.createDate = createDate;
this.createUser = createUser;
this.department = department;
this.invoices = invoices;
}
/** default constructor */
public ProjectEMS() {
}
/** minimal constructor */
public ProjectEMS(Long id) {
this.id = id;
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public java.lang.String getNo() {
return this.no;
}
public void setNo(java.lang.String no) {
this.no = no;
}
public java.lang.String getStatus() {
return this.status;
}
public void setStatus(java.lang.String status) {
this.status = status;
}
public java.util.Date getCreateDate() {
return this.createDate;
}
public void setCreateDate(java.util.Date createDate) {
this.createDate = createDate;
}
public com.aof.component.domain.party.UserLogin getCreateUser() {
return this.createUser;
}
public void setCreateUser(com.aof.component.domain.party.UserLogin createUser) {
this.createUser = createUser;
}
/**
* @return Returns the emsDate.
*/
public java.util.Date getEmsDate() {
return emsDate;
}
/**
* @param emsDate The emsDate to set.
*/
public void setEmsDate(java.util.Date emsDate) {
this.emsDate = emsDate;
}
/**
* @return Returns the note.
*/
public String getNote() {
return note;
}
/**
* @param note The note to set.
*/
public void setNote(String note) {
this.note = note;
}
/**
* @return Returns the type.
*/
public String getType() {
return type;
}
/**
* @param type The type to set.
*/
public void setType(String type) {
this.type = type;
}
/**
* @return Returns the department.
*/
public com.aof.component.domain.party.Party getDepartment() {
return department;
}
/**
* @param department The department to set.
*/
public void setDepartment(com.aof.component.domain.party.Party department) {
this.department = department;
}
/**
* @return Returns the invoices.
*/
public Set getInvoices() {
return invoices;
}
/**
* @param invoices The invoices to set.
*/
public void setInvoices(Set invoices) {
this.invoices = invoices;
}
public void removeInvoice(ProjectInvoice pi) {
if (invoices != null) {
invoices.remove(pi);
}
}
public void addInvoices(ProjectInvoice pi) {
if (invoices == null) {
invoices = new HashSet();
}
invoices.add(pi);
}
public String toString() {
return new ToStringBuilder(this)
.append("id", getId())
.toString();
}
public boolean equals(Object other) {
if ( !(other instanceof ProjectEMS) ) return false;
ProjectEMS castOther = (ProjectEMS) other;
return new EqualsBuilder()
.append(this.getId(), castOther.getId())
.isEquals();
}
public int hashCode() {
return new HashCodeBuilder()
.append(getId())
.toHashCode();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.