text
stringlengths 10
2.72M
|
|---|
package com.tencent.mm.app;
import android.util.Base64;
import com.tencent.mm.sdk.platformtools.CrashMonitorForJni.a;
import com.tencent.mm.sdk.platformtools.ad;
import com.tencent.mm.sdk.platformtools.d;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.xweb.WebView;
import java.util.Locale;
class k$1 implements a {
k$1() {
}
public final String va() {
StringBuilder stringBuilder = new StringBuilder();
String processName = ad.getProcessName();
if (processName != null && (processName.contains(":tools") || processName.contains(":appbrand"))) {
stringBuilder.append("\n");
processName = WebView.getCrashExtraMessage(ad.getContext());
if (processName != null && processName.length() > 0) {
processName = processName + String.format(Locale.US, "client_version:%s;", new Object[]{d.CLIENT_VERSION});
if (processName.length() > 8192) {
processName = processName.substring(processName.length() - 8192);
}
stringBuilder.append("#qbrowser.crashmsg=" + Base64.encodeToString(processName.getBytes(), 2));
x.v("MicroMsg.MMCrashReporter", "header #qbrowser.crashmsg=%s", new Object[]{processName});
}
}
return stringBuilder.toString();
}
}
|
package rjm.romek.awscourse.verifier.ec2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.amazonaws.services.ec2.model.Instance;
import rjm.romek.awscourse.service.EC2Service;
@Service
public class EC2TypeVerifier extends EC2Verifier {
private static final String ATTRIBUTE_NAME = "instanceType";
@Autowired
public EC2TypeVerifier(EC2Service ec2Service) {
super(ec2Service, ATTRIBUTE_NAME);
}
@Override
protected String getInstanceAttributeValue(Instance instance) {
return instance.getInstanceType();
}
}
|
package basic;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class Exercise14Test {
@Test
public void test_findNum() {
assertEquals(new Exercise14().findNum(), "153 370 371 407 1634 8208 9474 54748 92727 93084 ");
}
}
|
package user;
import java.sql.Connection;
import java.sql.PreparedStatement;
import util.DatabaseUtil;
public class UserDAO {
public int join(String userID, String userPassword) {
String SQL = "INSERT INTO USER VALUES (?, ?)";
try {
Connection conn = DatabaseUtil.getInstance().getConnection();
PreparedStatement pstmt = conn.prepareStatement(SQL);
pstmt.setString(1, userID);
pstmt.setString(2, userPassword);
pstmt.executeUpdate();
pstmt.close();
conn.close();
return 1;
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
}
|
package com.scholanova.ecommerce.cart.entity;
import com.scholanova.ecommerce.product.entity.Product;
import javax.persistence.*;
@Entity(name = "cart_item")
public class CartItem {
@Id
@GeneratedValue
private Long id;
@Column
private int quantity;
@OneToOne(cascade = CascadeType.ALL)
private Product product;
public CartItem() {
}
public static CartItem create(Product product, int quantity){
CartItem cartItem = new CartItem();
cartItem.setProduct(product);
cartItem.setQuantity(quantity);
return cartItem;
}
public Long getId() {return id;}
public void setId(Long id) {
this.id = id;
}
public int getQuantity() {return quantity;}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public Product getProduct() {return product;}
public void setProduct(Product product) {
this.product = product;
}
}
|
import java.io.FileNotFoundException;
import java.sql.SQLOutput;
public class AccountCreator implements AccountService {
protected String accountInfo;
protected String accountInfo2;
protected int subTotal;
protected int subTotal2;
FileCreator fileCreator = new FileCreator();
@Override
public void withdraw(int accountId, int amount) throws NotEnoughMoneyException, UnknownAccountException, FileNotFoundException {
accountInfo = fileCreator.findAccountInFile(accountId);
if (accountInfo == null) {
throw new UnknownAccountException();
}
System.out.println("Изымать (баланс до снятия): " + accountInfo);
String words[] = accountInfo.split(" ");
if (amount > Integer.parseInt(words[1])) {
throw new NotEnoughMoneyException();
}
subTotal = Integer.parseInt(words[1]) - amount;
System.out.println("Итоговый баланс: " + subTotal);
fileCreator.updateAccountInFile(accountId, subTotal);
System.out.println("Информация зафиксирована");
}
@Override
public void balance(int accountId) throws UnknownAccountException, FileNotFoundException {
accountInfo = fileCreator.findAccountInFile(accountId);
if (accountInfo == null) {
throw new UnknownAccountException();
}
System.out.println("Баланс: " + accountInfo);
}
@Override
public void deposit(int accountId, int amount) throws UnknownAccountException, FileNotFoundException {
accountInfo = fileCreator.findAccountInFile(accountId);
System.out.println("Id и баланс до зачисления: " + accountInfo);
String words[] = accountInfo.split(" ");
subTotal = Integer.parseInt(words[1]) + amount;
System.out.println("Итоговый баланс: " + subTotal);
fileCreator.updateAccountInFile(accountId, subTotal);
System.out.println("Информация зафиксирована");
}
@Override
public void transfer(int from, int to, int amount) throws NotEnoughMoneyException, UnknownAccountException, FileNotFoundException {
accountInfo = fileCreator.findAccountInFile(from);
if (accountInfo == null) {
throw new NotEnoughMoneyException();
}
System.out.println("ИД и баланс до списания: " + accountInfo);
String words[] = accountInfo.split(" ");
if (amount > Integer.parseInt(words[1])) {
throw new NotEnoughMoneyException();
}
subTotal = Integer.parseInt(words[1]) - amount;
fileCreator.updateAccountInFile(from, subTotal);
accountInfo2 = fileCreator.findAccountInFile(to);
if (accountInfo2 == null) {
throw new UnknownAccountException();
}
System.out.println("ИД и баланс до зачисления: " + accountInfo2);
String words2[] = accountInfo2.split(" ");
subTotal2 = Integer.parseInt(words2[1])+ amount;
fileCreator.updateAccountInFile(to, subTotal2);
System.out.println("Информация зафиксирована");
System.out.println("First: "+ from + " "+ subTotal);
System.out.println("Second: "+ to + " "+ subTotal2);
}
}
|
package com.chenlei.client_3.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.client.OAuth2RestOperations;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails;
/**
* @Author: 陈磊
* @Date: 2018/7/11
* @Description:
*/
@Configuration
public class AuthorizationClientConfig {
@Bean
@ConfigurationProperties(prefix = "security.oauth2.client")
public ClientCredentialsResourceDetails getClientCredentialsResourceDetails() {
return new ClientCredentialsResourceDetails();
}
@Bean
public OAuth2RestOperations oAuth2RestOperations() {
return new OAuth2RestTemplate(getClientCredentialsResourceDetails());
}
}
|
package pomocneKlase;
public class DodjelaVoznje {
//TODO: Ovdje implementirati kompletan algoritam za dodjelu vožnje vozačima
}
|
package Game;
import java.util.Scanner;
import java.lang.Math;
import java.awt.event.KeyEvent;
public class BotChat {
String[][] chatBot = {
//-------------------ΑΠΑΝΤΑΕΙ ΣΤΟΝ ΧΑΙΡΕΤΙΣΜΟ----------------------------------//
{"hi", "HI", "hI", "hello", "Hello", "hola", "Halooo", "halo", "hey", "HEY"},
{"hi , how you doing ??", "hey", "hello", "Nice day , aha??"},
//-------------------ΑΠΑΝΤΑΕΙ ΣΤΟ ΤΙ ΚΑΝΕΙΣ----------------------------------//
{"how are you", "how you doing?", "how are you?", "How are you", "are you ok", "are you ok ?"},
{"i am fine, you?", "all good ,thanks god", "nahh good", "i am doing fine ,you?"},
//--------------------τα default του αν δν βρει καποια απαντησει--------------//
{"are you mad ???", "you must take a cure IMMEDIATLY!!!", "you are out of your mind", "....."}
};
public void answering() {
//---EDW PAIRNOUME TO INPUT KAI VGAZOUME TA ! , ? , . --------
Scanner input = new Scanner(System.in);
String quote;
int possitionMatch = 0; //Se pia omada apantiseon psaxnoume
byte response = 0; // 0 psaxnei 1 dn vrethike tipota 2 vrikame tin apantisei
do{
System.out.print("-->YOU:\t");
quote = input.next();
while (response == 0) {
if (inArray(quote.toLowerCase(), chatBot[possitionMatch * 2])) {
response = 2;
int random = (int) Math.floor(Math.random() * chatBot[(possitionMatch * 2) + 1].length);
System.out.println("-->Bot\t" + chatBot[possitionMatch * 2][random]);
}
possitionMatch++;
if (possitionMatch * 2 == chatBot.length - 1 && response == 0) {
response = 1;
}
if (response == 1) {
int random = (int) Math.floor(Math.random() * chatBot[chatBot.length - 1].length);
System.out.println("-->Bot:\t" + chatBot[possitionMatch * 2][random]);
}
System.out.println("\n");
}
}while (!quote.equals("bye"));
}
public boolean inArray(String in,String[] str)
{
boolean match = false;
for(int i=0;i<str.length;i++)
{
if(str[i].equals(in))
{
match=true;
}
}
return match;
}
}
|
package it.unive.dagg.phases;
import it.unive.dagg.Game;
import it.unive.interfaces.Player;
/**
* Concept of Phase: a Player's activity with a starting point and an ending point.
* @author Gregory Sech
*/
public abstract class AbstractPhase implements it.unive.interfaces.Phase{
private final Player chief;
public AbstractPhase(Player chief) {
this.chief = chief;
}
/**
* @return "owner" of the phase.
*/
@Override
public Player getChief(){
return chief;
}
/**
* Phase's starting point.
*/
protected void phaseStart(){
Game.getInstance().getPhaseObserver().phaseStarted(this);
}
/**
* Phase's ending point.
*/
protected void phaseEnd(){
Game.getInstance().getPhaseObserver().phaseEnded(this);
}
/**
* Override this for a specific activity
*/
protected void activity(){
}
/**
* Phase's life cycle.
*/
@Override
public final void phaseRun(){
phaseStart();
activity();
phaseEnd();
}
}
|
package observer.design.pattern.example;
public class ObserverTest {
public static void main(String[] args) {
WeatherStation weatherStation = new WeatherStation(33);
TVChannel observer1 = new TVChannel();
Newspapers observer2 = new Newspapers();
weatherStation.addObserver(observer1);
weatherStation.addObserver(observer2);
weatherStation.setTemperature(30);
weatherStation.removeObserver(observer1);
weatherStation.setTemperature(35);
}
}
|
package net.sf.ardengine.rpg.multiplayer.messages;
/**
* Send automatically by client to synchronize with game.
*/
public class JoinRequestMessage extends JsonMessage{
/**Type of message sent automatically by client to synchronize with game.*/
public static final String TYPE = "player-join-request";
public JoinRequestMessage(){
super(TYPE, null, null);
}
}
|
package com.example.makemytrip.apiClient;
import com.example.makemytrip.response.FlightResponseDTO;
import com.example.makemytrip.response.OfferResponseDTO;
import com.example.makemytrip.response.ResponseDTO;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;
public interface ApiClient {
@GET("Sumit19jan/ced8c956cddf46b48b865dac577e0289/raw/12df743b7f402507ea45cc7fc34aa9d4fa1acfb5/hotel_json")
Call<ResponseDTO> getHotelResponse();
@GET("Sumit19jan/198820137e591df00376b76ac046a13b/raw/fd730eb6f9464ce3bd919468a4156996a86f1228/flightGist")
Call<List<FlightResponseDTO>> getFlightResponse();
@GET("Sumit19jan/6cbbf39ed036e9bafd507236a0eaa581/raw/670e0378e12597219102aeac659af374766081ed/offersApi")
Call<List<OfferResponseDTO>> getOffers();
}
|
package com.fatosajvazi;
public class Main {
public static void main(String[] args) {
// write your code here
System.out.println(isPalindrome(-1221));
}
public static boolean isPalindrome(int number) {
boolean isPalindrome = false;
int initialNumber = Math.abs(number);
String palindrome = "";
while (Math.abs(number) > 0){
palindrome = palindrome + Math.abs(number) % 10;
System.out.println("Palindrome " + palindrome);
number = Math.abs(number) / 10;
System.out.println("Number " + number);
}
if (initialNumber == Integer.parseInt(palindrome)){
isPalindrome = true;
}
return isPalindrome;
}
}
|
package com.yoghourt.wolfcoder.sample;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.yoghourt.wolfcoder.shrinkmenu.ShrinkMenu;
import com.yoghourt.wolfcoder.shrinkmenu.utils.ViewUtils;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ShrinkMenu menu = (ShrinkMenu) findViewById(R.id.menu);
menu.addMenuImage(new int[]{R.drawable.person,
R.drawable.connection, R.drawable.message,
R.drawable.home});
menu.setMenuIcon(R.drawable.plus);
menu.setup();
menu.setOnClickListener(new ShrinkMenu.ShrinkMenuOnClickListener() {
@Override
public void onMenuClick(View view) {
if(view.getTag().equals(ViewUtils.getViewTag(0))) {
Toast.makeText(MainActivity.this,"you click the first menuIcon",Toast.LENGTH_SHORT)
.show();
}else if(view.getTag().equals(ViewUtils.getViewTag(1))) {
Toast.makeText(MainActivity.this,"you click the second menuIcon",Toast.LENGTH_SHORT)
.show();
}else if(view.getTag().equals(ViewUtils.getViewTag(2))) {
Toast.makeText(MainActivity.this,"you click the third menuIcon",Toast.LENGTH_SHORT)
.show();
}else if(view.getTag().equals(ViewUtils.getViewTag(3))) {
Toast.makeText(MainActivity.this,"you click the forth menuIcon",Toast.LENGTH_SHORT)
.show();
}
}
});
}
}
|
package LC400_600.LC500_550;
import LeetCodeUtils.TreeNode;
import java.util.ArrayList;
import java.util.List;
public class LC515_Find_Largest_Value_In_Each_Tree_Row {
public List<Integer> largestValues(TreeNode root) {
List<Integer> result = new ArrayList<>();
if (root != null) dfs(0, result, root);
return result;
}
public void dfs(int level, List<Integer> ans, TreeNode node) {
if (ans.size() <= level) {
ans.add(node.val);
} else {
if (ans.get(level) < node.val) {
ans.set(level, node.val);
}
}
if (node.left != null) dfs(1 + level, ans, node.left);
if (node.right != null) dfs(1 + level, ans, node.right);
}
}
|
package com.okellosoftwarez.modelfarm;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.Manifest;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.okellosoftwarez.modelfarm.models.Products;
import com.squareup.picasso.Picasso;
import java.net.InetAddress;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public static final int IMAGE_REQUEST = 1, CAMERA_REQUEST = 2;
private static final int PERMISSION_CODE = 1000;
EditText etName, etLocation, etPrice, etCapacity, etPhone, etMail;
Button chooseBtn, takeBtn, uploadBtn, changeBtn, changePhoto;
ImageView addImage;
Uri image_uri;
Products product;
String sName, sPhone, sEmail, sLocation, sPrice, sCapacity, editKey, receivedImage, sRatings, sVoters, sComments;
String newName, newPhone, newEmail, newLocation, newPrice, newCapacity, newRatings, newVoters;
private StorageReference storageReference;
private DatabaseReference databaseReference;
private ProgressBar mProgress;
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.tool);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
setTitle("New Product");
storageReference = FirebaseStorage.getInstance().getReference("Products");
databaseReference = FirebaseDatabase.getInstance().getReference("Products");
product = new Products();
etName = findViewById(R.id.et_addName);
etLocation = findViewById(R.id.et_addLocation);
etPrice = findViewById(R.id.et_addPrice);
etCapacity = findViewById(R.id.et_addCapacity);
etPhone = findViewById(R.id.et_addPhone);
etMail = findViewById(R.id.et_addEmail);
chooseBtn = findViewById(R.id.choosePhoto);
takeBtn = findViewById(R.id.takePhoto);
uploadBtn = findViewById(R.id.upload);
changePhoto = findViewById(R.id.updatePhoto);
changeBtn = findViewById(R.id.uploadChanges);
addImage = findViewById(R.id.addImage);
mProgress = findViewById(R.id.progressBar);
chooseBtn.setOnClickListener(this);
takeBtn.setOnClickListener(this);
editProductDetails(toolbar);
}
private void editProductDetails(Toolbar toolbar) {
if (getIntent().hasExtra("editKey")) {
editKey = getIntent().getStringExtra("editKey");
setTitle("Edit Product");
changePhoto.setVisibility(View.VISIBLE);
chooseBtn.setVisibility(View.INVISIBLE);
takeBtn.setVisibility(View.INVISIBLE);
changeBtn.setVisibility(View.VISIBLE);
uploadBtn.setVisibility(View.INVISIBLE);
if (getIntent().hasExtra("editImage")) {
receivedImage = getIntent().getStringExtra("editImage");
Picasso.get().load(receivedImage).placeholder(R.drawable.back_image)
.fit().centerCrop().into(addImage);
image_uri = Uri.parse(receivedImage);
if (getIntent().hasExtra("editName")) {
sName = getIntent().getStringExtra("editName");
etName.setText(sName);
if (getIntent().hasExtra("editLocation")) {
sLocation = getIntent().getStringExtra("editLocation");
etLocation.setText(sLocation);
if (getIntent().hasExtra("editPrice")) {
sPrice = getIntent().getStringExtra("editPrice");
etPrice.setText(sPrice);
if (getIntent().hasExtra("editCapacity")) {
sCapacity = getIntent().getStringExtra("editCapacity");
etCapacity.setText(sCapacity);
if (getIntent().hasExtra("editMail")) {
sEmail = getIntent().getStringExtra("editMail");
etMail.setText(sEmail);
if (getIntent().hasExtra("editPhone")) {
sPhone = getIntent().getStringExtra("editPhone");
etPhone.setText(sPhone);
changePhoto.setOnClickListener(this);
changeBtn.setOnClickListener(this);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent changeIntent = new Intent(getApplicationContext(), personalProducts.class);
startActivity(changeIntent);
}
});
}
}
}
}
}
}
}
} else {
uploadBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
receiveEntries();
}
});
}
}
private void updatingDetails() {
if (getIntent().hasExtra("editRatings") && getIntent().hasExtra("editVoters") && getIntent().hasExtra("editComments")) {
sRatings = getIntent().getStringExtra("editRatings");
sVoters = getIntent().getStringExtra("editVoters");
sComments = getIntent().getStringExtra("editComments");
// etName.setText(sName);
}else {
sRatings = Integer.toString(0);
sVoters = Integer.toString(0);
sComments = "No Comments";
}
newName = etName.getText().toString().trim();
newLocation = etLocation.getText().toString().trim();
newPrice = etPrice.getText().toString().trim();
newCapacity = etCapacity.getText().toString().trim();
newEmail = etMail.getText().toString().trim();
newPhone = etPhone.getText().toString().trim();
if (Integer.valueOf(newPrice) < 1) {
Toast.makeText(this, "Please Enter a Valid Price", Toast.LENGTH_SHORT).show();
} else {
if (Integer.valueOf(newCapacity) < 1) {
Toast.makeText(this, "Please Enter a Valid Capacity", Toast.LENGTH_SHORT).show();
} else {
SharedPreferences pref = getApplicationContext().getSharedPreferences("Preferences", 0);
String phoneNo = pref.getString("phone", null);
final DatabaseReference updateRef = FirebaseDatabase.getInstance().getReference("personalProducts").child(phoneNo);
String image = image_uri.toString();
if (image.startsWith("https")) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
mProgress.setProgress(0);
}
}, 500);
// Products updatedProduct = new Products(newName, newPhone, newLocation, receivedImage, newPrice, newCapacity, newEmail);
// Products updatedProduct = new Products(newName, newPhone, newLocation, receivedImage, newPrice, newCapacity, newEmail, sRatings, sVoters);
Products updatedProduct = new Products(newName, newPhone, newLocation, receivedImage, newPrice, newCapacity, newEmail, sRatings, sVoters, sComments);
updateRef.child(editKey).setValue(updatedProduct);
databaseReference.child(editKey).setValue(updatedProduct);
mProgress.setProgress(100);
} else {
if (image_uri != null) {
StorageReference updatePhotoReference = storageReference.child(System.currentTimeMillis() + "."
+ getFileExtension(image_uri));
UploadTask uploadUpdateTask = updatePhotoReference.putFile(image_uri);
Toast.makeText(this, "UP " + uploadUpdateTask, Toast.LENGTH_SHORT).show();
uploadUpdateTask.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
// Handle unsuccessful uploads
Toast.makeText(MainActivity.this, "Fail Changing Photo..." + exception.getMessage(), Toast.LENGTH_LONG).show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(final UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(MainActivity.this, "Success Changing Photo...", Toast.LENGTH_LONG).show();
if (taskSnapshot.getMetadata() != null) {
if (taskSnapshot.getMetadata().getReference() != null) {
Task<Uri> resultUpdate = taskSnapshot.getStorage().getDownloadUrl();
resultUpdate.addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
Toast.makeText(MainActivity.this, "Complete...", Toast.LENGTH_LONG).show();
String newImage = uri.toString();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
mProgress.setProgress(0);
}
}, 500);
Toast.makeText(MainActivity.this, "Upload Successful..." + newImage, Toast.LENGTH_SHORT).show();
// Products updatedProduct = new Products(newName, newPhone, newLocation, newImage, newPrice, newCapacity, newEmail, sRatings, sVoters);
Products updatedProduct = new Products(newName, newPhone, newLocation, newImage, newPrice, newCapacity, newEmail, sRatings, sVoters, sComments);
updateRef.child(editKey).setValue(updatedProduct);
databaseReference.child(editKey).setValue(updatedProduct);
backToMain(editKey);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(MainActivity.this, "Database Fail...", Toast.LENGTH_SHORT).show();
}
});
}
}
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
@Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
mProgress.setProgress((int) progress);
}
});
}
}
}
}
}
private void backToMain(String key) {
Intent backIntent = new Intent(this, Products_view.class);
backIntent.putExtra("phone", product.getPhone());
backIntent.putExtra("name", product.getName());
backIntent.putExtra("location", product.getLocation());
backIntent.putExtra("price", product.getPrice());
backIntent.putExtra("capacity", product.getCapacity());
backIntent.putExtra("mail", product.getEmail());
backIntent.putExtra("image", product.getImage());
backIntent.putExtra("key", key);
startActivity(backIntent);
}
private void receiveEntries() {
sName = etName.getText().toString().trim();
sLocation = etLocation.getText().toString().trim();
sPrice = etPrice.getText().toString().trim();
sCapacity = etCapacity.getText().toString().trim();
sPhone = etPhone.getText().toString().trim();
sEmail = etMail.getText().toString().trim();
checkFields();
}
private void checkFields() {
if (sName.isEmpty() || sLocation.isEmpty() || sPrice.isEmpty() || sCapacity.isEmpty() || sPhone.isEmpty() || sEmail.isEmpty() || image_uri == null) {
Toast.makeText(this, "Missing Fields...", Toast.LENGTH_SHORT).show();
} else {
if (Integer.valueOf(sPrice) < 1) {
Toast.makeText(this, "Please Enter a Valid Price", Toast.LENGTH_SHORT).show();
} else {
if (Integer.valueOf(sCapacity) < 1) {
Toast.makeText(this, "Please Enter a Valid Capacity", Toast.LENGTH_SHORT).show();
} else {
if (isNetworkConnected()) {
// if (isInternetAvailable()){
uploadDetails();
}
// else {
// Toast.makeText(MainActivity.this, R.string.No_internet, Toast.LENGTH_LONG).show();
// }
// }
else {
Toast.makeText(MainActivity.this, R.string.No_network, Toast.LENGTH_LONG).show();
}
}
}
}
}
private void uploadDetails() {
Toast.makeText(this, "Start Uploading....", Toast.LENGTH_LONG).show();
if (image_uri != null) {
okelloModel();
} else {
Toast.makeText(this, "Empty Uri...", Toast.LENGTH_SHORT).show();
}
Toast.makeText(this, "End Uploading....", Toast.LENGTH_LONG).show();
}
private void okelloModel() {
Toast.makeText(this, "Start okello....", Toast.LENGTH_LONG).show();
StorageReference photoReference = storageReference.child(System.currentTimeMillis() + "."
+ getFileExtension(image_uri));
UploadTask uploadTask = photoReference.putFile(image_uri);
Toast.makeText(this, "UP " + uploadTask, Toast.LENGTH_SHORT).show();
// Register observers to listen for when the download is done or if it fails
uploadTask.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
// Handle unsuccessful uploads
Toast.makeText(MainActivity.this, "Fail...okello", Toast.LENGTH_SHORT).show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(final UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(MainActivity.this, "Success...okello", Toast.LENGTH_LONG).show();
if (taskSnapshot.getMetadata() != null) {
if (taskSnapshot.getMetadata().getReference() != null) {
Task<Uri> result = taskSnapshot.getStorage().getDownloadUrl();
result.addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
Toast.makeText(MainActivity.this, "Proceed...", Toast.LENGTH_LONG).show();
String sImage = uri.toString();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
mProgress.setProgress(0);
}
}, 500);
Toast.makeText(MainActivity.this, "Upload Successful..." + sImage, Toast.LENGTH_SHORT).show();
product = new Products(sName, sPhone, sLocation, sImage, sPrice, sCapacity, sEmail, Integer.toString(0), Integer.toString(0), "No Comments");
// product = new Products(sName, sPhone, sLocation, sImage, sPrice, sCapacity, sEmail, Integer.toString(0), Integer.toString(0));
// product = new Products(sName, sPhone, sLocation, sImage, sPrice, sCapacity, sEmail);
String key = databaseReference.push().getKey();
product.setID(key);
databaseReference.child(key).setValue(product);
Toast.makeText(MainActivity.this, "Success Key retention...", Toast.LENGTH_LONG).show();
backToMain(key);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(MainActivity.this, "Database Fail...", Toast.LENGTH_SHORT).show();
}
});
}
}
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
@Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
mProgress.setProgress((int) progress);
}
});
}
private String getFileExtension(Uri uri) {
ContentResolver contentResolver = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
String extension = mime.getExtensionFromMimeType(contentResolver.getType(uri));
return extension;
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.takePhoto:
// Take a photo using the camera
takePhoto();
break;
case R.id.choosePhoto:
// Choose a photo from gallery
choosingPhoto();
break;
case R.id.updatePhoto:
chooserPhoto();
break;
case R.id.uploadChanges:
if (isNetworkConnected()) {
updatingDetails();
} else {
Toast.makeText(this, R.string.No_network, Toast.LENGTH_SHORT).show();
}
break;
}
}
private void chooserPhoto() {
Intent chooseIntent = new Intent();
chooseIntent.setType("image/*");
chooseIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(chooseIntent, IMAGE_REQUEST);
}
private void choosingPhoto() {
Intent chooseIntent = new Intent();
chooseIntent.setType("image/*");
chooseIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(chooseIntent, IMAGE_REQUEST);
}
private void takePhoto() {
// if system OS is greater than Marshmallow require Permissions at run time
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED ||
checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
// Permissions not enabled so request for them
String[] permissions = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permissions, PERMISSION_CODE);
} else {
// Permission already granted
openCamera();
}
} else {
// For OS lesser than Marshmallow
openCamera();
}
}
private void openCamera() {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "NEW PICTURE");
values.put(MediaStore.Images.Media.DESCRIPTION, "From The Camera");
image_uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
// Camera Intent
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// This Method is called when user selects either allow or deny in the pop up notification
switch (requestCode) {
case PERMISSION_CODE: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission from pop up was granted
openCamera();
} else {
// Permission from pop up was denied
Toast.makeText(this, "Permission Denied ...", Toast.LENGTH_SHORT).show();
}
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_REQUEST) {
addImage.setImageURI(image_uri);
Toast.makeText(this, "Photo loaded...", Toast.LENGTH_SHORT).show();
} else if (requestCode == IMAGE_REQUEST) {
image_uri = data.getData();
Picasso.get().load(image_uri).into(addImage);
}
}
}
// This method checks whether mobile is connected to internet and returns true if connected:
public boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected();
}
// This method actually checks if device is connected to internet(There is a possibility it's connected to a network but not to internet).
public boolean isInternetAvailable() {
try {
InetAddress ipAddr = InetAddress.getByName("google.com");
return !ipAddr.equals("");
} catch (Exception e) {
return false;
}
}
}
|
package com.acme.orderserver.repository;
import com.acme.orderserver.model.Order;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
public interface OrderRepository extends JpaRepository<Order, Long> {
@Query(value = "from Order o where o.address like %:search%")
Page<Order> findAllSearch(final Pageable pageable, @Param("search") String search);
}
|
package uo.sdi.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import uo.sdi.model.types.UserStatus;
/**
* An implementation of the DTO pattern
*
* @author alb
*/
@Entity
@Table(name = "TUsers")
public class User implements Serializable {
private static final long serialVersionUID = 5461745400344675866L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String login;
private String email;
private String password;
private Boolean isAdmin = false;
@Enumerated(EnumType.STRING)
private UserStatus status = UserStatus.ENABLED;
@OneToMany(mappedBy="user")
public List<Category> categories = new ArrayList<>();
@OneToMany(mappedBy="user")
public List<Task> tasks = new ArrayList<>();
public void setIsAdmin(Boolean isAdmin) {
this.isAdmin = isAdmin;
}
public Long getId() {
return id;
}
public User setId(Long id) {
this.id = id;
return this;
}
public String getLogin() {
return login;
}
public User setLogin(String login) {
this.login = login;
return this;
}
public String getEmail() {
return email;
}
public User setEmail(String email) {
this.email = email;
return this;
}
public String getPassword() {
return password;
}
public User setPassword(String password) {
this.password = password;
return this;
}
public Boolean getIsAdmin() {
return isAdmin;
}
public List<Category> getCategories() {
return new ArrayList<>(categories);
}
public List<Task> getTasks() {
return new ArrayList<>(tasks);
}
public List<Task> _getTasks() {
return tasks;
}
@Override
public String toString() {
return "UserDto [id=" + id + ", login=" + login + ", email=" + email
+ ", password=" + password + ", isAdmin=" + isAdmin + "]";
}
public UserStatus getStatus() {
return status;
}
public User setStatus(UserStatus status) {
this.status = status;
return this;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((email == null) ? 0 : email.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((isAdmin == null) ? 0 : isAdmin.hashCode());
result = prime * result + ((login == null) ? 0 : login.hashCode());
result = prime * result
+ ((password == null) ? 0 : password.hashCode());
result = prime * result + ((status == null) ? 0 : status.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (email == null) {
if (other.email != null)
return false;
} else if (!email.equals(other.email))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (isAdmin == null) {
if (other.isAdmin != null)
return false;
} else if (!isAdmin.equals(other.isAdmin))
return false;
if (login == null) {
if (other.login != null)
return false;
} else if (!login.equals(other.login))
return false;
if (password == null) {
if (other.password != null)
return false;
} else if (!password.equals(other.password))
return false;
if (status != other.status)
return false;
return true;
}
}
|
package com.tencent.mrs.a;
import android.text.TextUtils;
import com.tencent.mars.app.AppLogic;
import com.tencent.matrix.d.b;
import com.tencent.matrix.mrs.core.MatrixReport;
import com.tencent.matrix.mrs.core.MrsCallback;
import com.tencent.mm.kernel.g;
import com.tencent.mm.sdk.f.e;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mrs.a.c.AnonymousClass2;
import java.util.HashMap;
import java.util.Iterator;
public final class a implements MrsCallback {
private HashMap<String, Boolean> uZS = new HashMap();
public final void onMrsReportDataReady(byte[] bArr) {
b.i("Matrix.MrsCallbackImp", "onMrsReportDataReady, try to report mars", new Object[0]);
if (bArr == null) {
b.e("Matrix.ReportMrsUpload", "report mrs date is null", new Object[0]);
} else {
e.post(new AnonymousClass2(bArr), "ReportMrsUpload");
}
}
public final boolean onRequestGetMrsStrategy(byte[] bArr) {
try {
if (g.Eg().Dx()) {
synchronized (this) {
if (b.isRunning()) {
x.i("Matrix.MrsCallbackImp", "NetSceneGetMrsStrategy is already running, just return");
return false;
}
x.i("Matrix.MrsCallbackImp", "onRequestGetMrsStrategy, try to request mrs strategy");
g.Eh().dpP.a(new b(bArr), 0);
return true;
}
}
x.e("Matrix.MrsCallbackImp", "onRequestGetMrsStrategy, account not ready");
return false;
} catch (Exception e) {
x.e("Matrix.MrsCallbackImp", "error: " + e.getMessage());
return false;
}
}
public final void onStrategyNotify(String str, boolean z) {
b.i("Matrix.MrsCallbackImp", "onStrategyNotify, strategy: %s, isReportProcess; %b", str, Boolean.valueOf(z));
if (!com.tencent.matrix.a.isInstalled() || !MatrixReport.isInstalled()) {
return;
}
if (MatrixReport.with().isDebug()) {
b.i("Matrix.MrsCallbackImp", "onStrategyNotify, matrix will report all for debug mode", new Object[0]);
return;
}
this.uZS.clear();
HashMap hashMap = this.uZS;
if (TextUtils.isEmpty(str) || hashMap == null) {
b.e("Matrix.MatrixUtil", "changeStrategyToMap, input params is illegal", new Object[0]);
} else {
for (String split : str.split(";")) {
String[] split2 = split.split(",", 2);
if (split2.length != 2) {
b.e("Matrix.MatrixUtil", "changeStrategyToMap, strategy format is illegal, value: %s", split);
} else {
hashMap.put(split2[0].trim(), Boolean.valueOf(split2[1].trim().equals("1")));
}
}
}
Iterator it = com.tencent.matrix.a.tg().boT.iterator();
while (it.hasNext()) {
com.tencent.matrix.b.b bVar = (com.tencent.matrix.b.b) it.next();
String tag = bVar.getTag();
if (this.uZS.containsKey(tag)) {
boolean booleanValue = ((Boolean) this.uZS.get(tag)).booleanValue();
if (booleanValue) {
int i;
if (bVar.status == 4) {
i = 1;
} else {
i = 0;
}
if (i != 0) {
b.w("Matrix.MrsCallbackImp", "matrix strategy change, try to turn on plugin %s", tag);
bVar.start();
}
}
if (!booleanValue && bVar.tw()) {
b.w("Matrix.MrsCallbackImp", "matrix strategy change, try to turn off plugin %s", tag);
bVar.stop();
}
}
}
}
public final String getPublicSharePath() {
return AppLogic.getAppFilePath() + "/mrs/";
}
}
|
package com.codebind;
import java.util.*;
public class Calculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(true)
{
System.out.println("Enter your choice 1.Addition,2.Subtraction,3.Multiplication,4.Division,5.exit");
int choice = sc.nextInt();
int num1 = 0;
int num2 = 0;
if(choice!=5)
{
System.out.println("Enter two numbers to perform your operation:");
num1 = sc.nextInt();
num2 = sc.nextInt();
}
switch(choice) {
case 1:
add obj1 = new add();
System.out.println("After adding"+num1+" "+num2+"the result is"+obj1.addition(num1,num2));
break;
case 2:
Subtract obj2 = new Subtract();
System.out.println("After subtracting"+num1+" "+num2+"the result is"+obj2.sub(num1,num2));
break;
case 3:
Multiplication obj3 = new Multiplication();
System.out.println("After multiplication"+num1+" "+num2+"the result is"+obj3.multiply(num1,num2));
break;
case 4:
Division obj4 = new Division();
System.out.println("After dividing"+num1+" "+num2+"the result is"+obj4.divide(num1,num2));
break;
case 5:
System.exit(0);
}
}
}
}
|
package com.netease.course.dao;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Repository;
import com.netease.course.entity.User;
@Repository
public interface UserDao {
@Insert("insert into `user` (`userName`,`userPassword`) values (#{username},#{password})")
public void addUser(User user);
@Update("update `user` set `userName`=#{username} ,`userPassword`=#{password} where `userName` = #{username}")
public void update(User user);
@Results({
@Result(property = "username", column = "userName"),
@Result(property = "password", column = "userPassword")
})
@Select ("select * from `user` where userName=#{username}")
public User select(@Param("username") String username);
}
|
package work.allwens.unionbbs.unionbbs.dao;
import work.allwens.unionbbs.unionbbs.entity.Comment;
import java.sql.Timestamp;
import java.util.List;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
@Component
@Transactional
public class CommentDao extends AbstractDao<Comment> {
public List<Comment> getByPage(long pid, int index) {
// 查找帖子id为pid的第index页评论
return getJdbcTemplate().query(
"SELECT comments.id,uname,uavatar,ccontent,cdate FROM comments JOIN users WHERE comments.uid = users.id AND comments.pid = ? ORDER BY cdate LIMIT 10 OFFSET ?;",
this.rowMapper, pid, 10 * (index - 1));
}
public long getTotalPage(long pid) {
long count = getJdbcTemplate().queryForObject("SELECT COUNT(*) FROM comments WHERE comments.pid=?;", Long.class,
pid);
return (long) Math.ceil((double) count / 10);
}
public void newComment(long uid, long pid, String content, boolean updatePost) {
// updatePost用于指定是否更新Post
var time = new Timestamp(System.currentTimeMillis());
getJdbcTemplate().update("INSERT INTO comments(uid,pid,ccontent,cdate) VALUES (?,?,?,?);", uid, pid, content,
time);
if (updatePost) {
getJdbcTemplate().update("UPDATE posts SET pdate = ?,pcomment=pcomment+1 WHERE posts.id = ?;", time, pid);
}
}
}
|
package com.statistic.app.model;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "records")
public class DataWrapper {
private List<Data> data;
@XmlElement(name = "data")
public List<Data> getData() {
return data;
}
public void setData(List<Data> data) {
this.data = data;
}
}
|
package com.tencent.mm.protocal.c;
import com.tencent.mm.bk.a;
public final class avz extends a {
public String hbL;
public String hcS;
public int iwE;
public int rQA;
public String rYV;
public String rhg;
public String rul;
public int rxW;
protected final int a(int i, Object... objArr) {
int fQ;
if (i == 0) {
f.a.a.c.a aVar = (f.a.a.c.a) objArr[0];
aVar.fT(1, this.iwE);
if (this.hcS != null) {
aVar.g(2, this.hcS);
}
if (this.rhg != null) {
aVar.g(3, this.rhg);
}
if (this.rul != null) {
aVar.g(4, this.rul);
}
if (this.hbL != null) {
aVar.g(5, this.hbL);
}
aVar.fT(6, this.rQA);
aVar.fT(7, this.rxW);
if (this.rYV != null) {
aVar.g(8, this.rYV);
}
return 0;
} else if (i == 1) {
fQ = f.a.a.a.fQ(1, this.iwE) + 0;
if (this.hcS != null) {
fQ += f.a.a.b.b.a.h(2, this.hcS);
}
if (this.rhg != null) {
fQ += f.a.a.b.b.a.h(3, this.rhg);
}
if (this.rul != null) {
fQ += f.a.a.b.b.a.h(4, this.rul);
}
if (this.hbL != null) {
fQ += f.a.a.b.b.a.h(5, this.hbL);
}
fQ = (fQ + f.a.a.a.fQ(6, this.rQA)) + f.a.a.a.fQ(7, this.rxW);
if (this.rYV != null) {
return fQ + f.a.a.b.b.a.h(8, this.rYV);
}
return fQ;
} else if (i == 2) {
f.a.a.a.a aVar2 = new f.a.a.a.a((byte[]) objArr[0], unknownTagHandler);
for (fQ = a.a(aVar2); fQ > 0; fQ = a.a(aVar2)) {
if (!super.a(aVar2, this, fQ)) {
aVar2.cJS();
}
}
return 0;
} else if (i != 3) {
return -1;
} else {
f.a.a.a.a aVar3 = (f.a.a.a.a) objArr[0];
avz avz = (avz) objArr[1];
switch (((Integer) objArr[2]).intValue()) {
case 1:
avz.iwE = aVar3.vHC.rY();
return 0;
case 2:
avz.hcS = aVar3.vHC.readString();
return 0;
case 3:
avz.rhg = aVar3.vHC.readString();
return 0;
case 4:
avz.rul = aVar3.vHC.readString();
return 0;
case 5:
avz.hbL = aVar3.vHC.readString();
return 0;
case 6:
avz.rQA = aVar3.vHC.rY();
return 0;
case 7:
avz.rxW = aVar3.vHC.rY();
return 0;
case 8:
avz.rYV = aVar3.vHC.readString();
return 0;
default:
return -1;
}
}
}
}
|
package org.litespring.beans;
/**
* Created by xusheng on 2019/1/3.
*/
public interface BeanDefinition {
String SCOPE_SINGLETON = "singleton";
String SCOPE_PROTOTYPE = "prototype";
String SCOPE_DEFAULT = "";
/**
* 是否单例
* @return
*/
boolean isSingleton();
/**
* 是否多例
* @return
*/
boolean isPrototype();
/**
* 获取Bean的作用域
* @return
*/
String getScope();
/**
* 设置Bean的作用域
* @param scope
*/
void setScope(String scope);
/**
* 获取Bean的全路径名
* @return
*/
String getBeanClassName();
}
|
package com.enter4ward.math;
import java.util.ArrayList;
import java.util.HashMap;
// TODO: Auto-generated Javadoc
/**
* The Class Space.
*/
public class Space {
private static final Vector3 TEMP_LENGTH = new Vector3();
private static final int LEFT = 0;
private static final int RIGHT = 1;
private static final int CENTER = 2;
private static HashMap<Vector3, Vector3> lengths = new HashMap<Vector3, Vector3>();
private static int LENS = 0;
private float minSize;
private Node root;
private static Vector3 recycle(final Vector3 v) {
Vector3 r = lengths.get(v);
if (r == null) {
r = new Vector3(v);
lengths.put(r, r);
++LENS;
}
return r;
}
/**
* The Class Node.
*/
public class Node extends BoundingBox {
/**
* The container.
*/
private ArrayList<Object> container;
/**
* The parent.
*/
private Node parent, left, right, center;
/**
* Instantiates a new space node.
*/
public Node() {
super(new Vector3(0), new Vector3(minSize * 3));
this.parent = null;
}
/**
* Instantiates a new space node.
*
* @param parent the parent
* @param min the min
* @param len the len
*/
private Node(Node parent, Vector3 min, Vector3 len) {
super(min, len);
this.parent = parent;
}
/**
* Instantiates a new space node.
*
* @param node the node
* @param i the i
* @param min the min
* @param len the len
*/
private Node(Node node, int i, Vector3 min, Vector3 len) {
super(min, len);
switch (i) {
case LEFT:
left = node;
break;
case CENTER:
center = node;
break;
case RIGHT:
right = node;
break;
default:
break;
}
node.parent = this;
}
private int getIndex(float value, float length, float radius) {
if (value >= radius) {
return LEFT;
} else if (-value >= radius) {
return RIGHT;
} else if (Math.abs(value) + radius <= length * .25f) {
return CENTER;
}
return -1;
}
/**
* Contains index.
*
* @param sphere the sphere
* @return the int
*/
private int getContainingNodeIndex(final BoundingSphere sphere) {
final float sr = sphere.getRadius();
final float lenX = getLengthX();
final float lenY = getLengthY();
final float lenZ = getLengthZ();
if (lenX >= lenY && lenX >= lenZ) {
final float dist = getCenterX() - sphere.getX();
return getIndex(dist, lenX, sr);
} else if (lenY >= lenZ) {
final float dist = getCenterY() - sphere.getY();
return getIndex(dist, lenY, sr);
} else {
final float dist = getCenterZ() - sphere.getZ();
return getIndex(dist, lenZ, sr);
}
}
/**
* Container add.
*
* @param obj the obj
*/
private void containerAdd(final Object obj) {
if (container == null)
container = new ArrayList<Object>(1);
container.add(obj);
container.trimToSize();
}
/**
* Container remove.
*
* @param obj the obj
*/
private void containerRemove(final Object obj) {
if (container != null) {
container.remove(obj);
if (container.size() == 0) {
container = null;
}
}
}
public boolean contains(final Object obj) {
if (container != null) {
return container.contains(obj);
}
return false;
}
/**
* Container size.
*
* @return the int
*/
public int containerSize() {
return container == null ? 0 : container.size();
}
/*
* (non-Javadoc)
*
* @see com.enter4ward.math.BoundingBox#toString()
*/
public String toString() {
return super.toString();
}
/**
* Builds the.
*
* @param i the i
* @return the space node
*/
private Node build(final int i) {
final float lenX = getLengthX();
final float lenY = getLengthY();
final float lenZ = getLengthZ();
if (lenX >= lenY && lenX >= lenZ) {
final Vector3 len = recycle(TEMP_LENGTH.set(lenX * 0.5f, lenY,
lenZ));
if (i == LEFT) {
return new Node(this, getMin(), len);
} else if (i == RIGHT) {
return new Node(this, new Vector3(getMin()).addX(lenX / 2),
len);
} else {
return new Node(this, new Vector3(getMin()).addX(lenX / 4),
len);
}
} else if (lenY >= lenZ) {
final Vector3 len = recycle(TEMP_LENGTH.set(lenX, lenY * 0.5f,
lenZ));
if (i == LEFT) {
return new Node(this, getMin(), len);
} else if (i == RIGHT) {
return new Node(this, new Vector3(getMin()).addY(lenY / 2),
len);
} else {
return new Node(this, new Vector3(getMin()).addY(lenY / 4),
len);
}
} else {
final Vector3 len = recycle(TEMP_LENGTH.set(lenX, lenY,
lenZ * 0.5f));
if (i == LEFT) {
return new Node(this, getMin(), len);
} else if (i == RIGHT) {
return new Node(this, new Vector3(getMin()).addZ(lenZ / 2),
len);
} else {
return new Node(this, new Vector3(getMin()).addZ(lenZ / 4),
len);
}
}
}
/**
* Gets the child.
*
* @param i the i
* @return the child
*/
private Node getChild(int i) {
switch (i) {
case LEFT:
if (left == null) {
left = build(i);
}
return left;
case CENTER:
if (center == null) {
center = build(i);
}
return center;
case RIGHT:
if (right == null) {
right = build(i);
}
return right;
default:
break;
}
return null;
}
/**
* Child.
*
* @param i the i
* @return the node
*/
private Node child(int i) {
switch (i) {
case LEFT:
return left;
case CENTER:
return center;
case RIGHT:
return right;
default:
break;
}
return null;
}
/**
* Expand.
*
* @param obj the obj
* @return the space node
*/
private Node expandAux(final BoundingSphere obj) {
final float lenX = getLengthX();
final float lenY = getLengthY();
final float lenZ = getLengthZ();
if (lenX < lenY && lenX < lenZ) {
final Vector3 len = recycle(TEMP_LENGTH.set(lenX * 2, lenY,
lenZ));
if (obj.getX() >= getCenterX()) {
return new Node(this, LEFT, getMin(), len);
} else {
return new Node(this, RIGHT,
new Vector3(getMin()).addX(-lenX), len);
}
} else if (lenY < lenZ) {
final Vector3 len = recycle(TEMP_LENGTH.set(lenX, lenY * 2,
lenZ));
if (obj.getY() >= getCenterY()) {
return new Node(this, LEFT, getMin(), len);
} else {
return new Node(this, RIGHT,
new Vector3(getMin()).addY(-lenY), len);
}
} else {
final Vector3 len = recycle(TEMP_LENGTH.set(lenX, lenY,
lenZ * 2));
if (obj.getZ() >= getCenterZ()) {
return new Node(this, LEFT, getMin(), len);
} else {
return new Node(this, RIGHT,
new Vector3(getMin()).addZ(-lenZ), len);
}
}
}
/**
* Can split.
*
* @return true, if successful
*/
private boolean canSplit() {
// if(containerSize()==0)
// return false;
return left != null || right != null || center != null
|| getLengthX() > minSize || getLengthY() > minSize || getLengthZ() > minSize;
}
/**
* Iterate.
*
* @param frustum the frustum
* @param handler the handler
*/
private void handleVisibleObjects(final BoundingFrustum frustum,
final VisibleObjectHandler handler) {
handler.onObjectVisible(this);
if (container != null) {
for (Object obj : container) {
handler.onObjectVisible(obj);
}
}
int intersections = 0;
for (int i = 0; i < 3; ++i) {
Node node = child(i);
if (node != null
&& (intersections == 2 || frustum.contains(node) != ContainmentType.Disjoint)) {
++intersections;
node.handleVisibleObjects(frustum, handler);
}
}
}
/**
* Removes the.
*
* @param obj the obj
*/
protected void remove(final Object obj) {
containerRemove(obj);
Node node = this;
while (node != null) {
node.clearChildren();
node = node.parent;
}
}
/**
* Clear child.
*/
protected void clearChildren() {
if (left != null && left.isEmpty()) {
left = null;
}
if (right != null && right.isEmpty()) {
right = null;
}
if (center != null && center.isEmpty()) {
center = null;
}
}
/**
* Update.
*
* @param sph the sph
* @return the node
*/
private Node getBestParentNode(BoundingSphere sph) {
Node node = this;
while (node != null) {
node.clearChildren();
if (node.containsSphere(sph)) {
break;
} else {
node = node.parent;
}
}
return node;
}
/**
* Expand.
*
* @param obj the obj
* @return the node
*/
private Node expand(final BoundingSphere obj) {
Node node = this;
while (!node.containsSphere(obj)) {
node.clearChildren();
node = node.expandAux(obj);
}
return node;
}
/**
* Iterate.
*
* @param sph the sph
* @param handler the handler
*/
private void handleObjectCollisions(final BoundingSphere sph,
final ObjectCollisionHandler handler) {
if (container != null) {
for (Object obj : container) {
handler.onObjectCollision(obj);
}
}
int intersections = 0;
for (int i = 0; i < 3; ++i) {
Node node = child(i);
if (node != null
&& (intersections == 2 || node.contains(sph) != ContainmentType.Disjoint)) {
++intersections;
node.handleObjectCollisions(sph, handler);
}
}
}
/**
* Insert.
*
* @param sph the sph
* @return the space node
*/
private Node getBestChildNode(final BoundingSphere sph) {
Node node = this;
// insertion
while (true) {
if (node.canSplit()) {
int i = node.getContainingNodeIndex(sph);
if (i < 0) {
break;
}
node = node.getChild(i);
} else {
break;
}
}
return node;
}
/**
* Handle ray collisions.
*
* @param space the space
* @param ray the ray
* @param handler the handler
*/
private IntersectionInfo handleRayCollisions(final Space space, final Ray ray,
final RayCollisionHandler handler) {
final float len = ray.getDirection().length();
IntersectionInfo result = null;
if (container != null) {
for (Object obj : container) {
IntersectionInfo r = handler.onObjectCollision(space, ray, obj);
if (r != null && (result == null || r.distance < result.distance)) {
result = r;
}
}
}
int intersections = 0;
for (int i = 0; i < 3; ++i) {
Node node = child(i);
Float idist = null;
if (node != null
&& (intersections == 2
|| node.contains(ray.getPosition()) != ContainmentType.Disjoint || ((idist = ray
.intersects(node)) != null && idist <= len))) {
++intersections;
if (idist == null) {
idist = 0f;
}
IntersectionInfo r = node.handleRayCollisions(space, ray, handler);
if (r != null && (result == null || r.distance < result.distance)) {
result = r;
}
}
}
return result;
}
/**
* Checks if is empty.
*
* @return true, if is empty
*/
private boolean isEmpty() {
return containerSize() == 0
&& (left == null && center == null && right == null);
}
/**
* Compress.
*
* @return the node
*/
private Node compress() {
Node node = this;
while (true) {
if (node.containerSize() == 0) {
boolean emptyLeft = node.left == null;
boolean emptyCenter = node.center == null;
boolean emptyRight = node.right == null;
if (emptyLeft && emptyCenter && !emptyRight) {
node = node.right;
} else if (emptyLeft && !emptyCenter && emptyRight) {
node = node.center;
} else if (!emptyLeft && emptyCenter && emptyRight) {
node = node.left;
} else {
break;
}
} else {
break;
}
}
node.parent = null;
return node;
}
/*
* public boolean handleRayCollisions(Space space, Ray ray,
* RayCollisionHandler handler) { float len =
* ray.getDirection().length(); boolean ret = false; if (container !=
* null) { IntersectionInfo closestInfo = null; BoundingSphere
* closestObject = null; for (Object obj2 : container) { Float idist =
* ray.intersects(obj2); if ((idist != null && idist < len) ||
* obj2.contains(ray.getPosition())) { IntersectionInfo info =
* handler.closestTriangle(obj2, ray); if (closestInfo == null ||
* info.distance < closestInfo.distance) { closestInfo = info;
* closestObject = obj2; } } } if (closestInfo != null) { ret |=
* handler.onObjectCollision(space, ray, closestObject, closestInfo); }
* } if (child != null) { int intersections = 0; for (int i = 0; i < 3;
* ++i) { SpaceNode node = child[i]; Float idist = null; if (node !=
* null && node.count > 0 && (intersections == 2 ||
* node.contains(ray.getPosition()) != ContainmentType.Disjoint ||
* ((idist = ray .intersects(node)) != null && idist <= len))) {
* ++intersections; if (idist == null) { idist = 0f; } //
* System.out.println("#"+node+"#"+ray+"#"+idist+"#"+handler); ret |=
* node.handleRayCollisions(space, ray, handler); } } } return ret; }
*/
}
/**
* Instantiates a new space.
*/
public Space(float minSize) {
this.minSize = minSize;
root = new Node();
}
public Node insert(final BoundingSphere sph, final Object obj) {
root = root.expand(sph);
final Node node = root.getBestChildNode(sph);
node.containerAdd(obj);
root = root.compress();
return node;
}
public Node update(final BoundingSphere sph, Node node, final Object obj) {
if (!node.containsSphere(sph)) {
node.containerRemove(obj);
node = node.getBestParentNode(sph);
if (node == null) {
node = root = root.expand(sph);
}
node = node.getBestChildNode(sph);
node.containerAdd(obj);
root = root.compress();
}
return node;
}
public void handleVisibleObjects(BoundingFrustum frustum,
VisibleObjectHandler handler) {
if (root != null) {
root.handleVisibleObjects(frustum, handler);
}
}
public void handleObjectCollisions(final BoundingSphere sphere,
final ObjectCollisionHandler handler) {
if (root != null) {
root.handleObjectCollisions(sphere, handler);
}
}
public IntersectionInfo handleRayCollisions(final Ray ray,
final RayCollisionHandler handler) {
if (root != null) {
return root.handleRayCollisions(this, ray, handler);
}
return null;
}
}
|
//299. Bulls and Cows
class Solution {
public String getHint(String secret, String guess) {
String s = new String();
int bull = 0;
int cows = 0;
int count = 0;
Map<Character, Integer>
secMap = new HashMap();
Map<Character, Integer>
guessMap = new HashMap();
int len = secret.length();
for (int i = 0; i < len; i++)
{
if(secret.charAt(i) == guess.charAt(i))
{
++bull;
}
else
{
if(secMap.containsKey(guess.charAt(i)))
{
count = secMap.get(guess.charAt(i));
count -= 1;
if(count == 0)
secMap.remove(guess.charAt(i));
else
secMap.put(guess.charAt(i), count);
cows++;
}
else
{
guessMap.put(guess.charAt(i), guessMap.getOrDefault(guess.charAt(i), 0) + 1);
}
if(guessMap.containsKey(secret.charAt(i)))
{
count = guessMap.get(secret.charAt(i));
count -= 1;
if(count == 0)
guessMap.remove(secret.charAt(i));
else
guessMap.put(secret.charAt(i), count);
cows++;
}
else
{
secMap.put(secret.charAt(i), secMap.getOrDefault(secret.charAt(i), 0) + 1);
}
}
}
s = s.concat(String.valueOf(bull) + "A" + String.valueOf(cows) + "B");
return s;
}
}
|
/**
* OpenKM, Open Document Management System (http://www.openkm.com)
* Copyright (c) 2006-2015 Paco Avila & Josep Llort
*
* No bytes were intentionally harmed during the development of this application.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.openkm.util;
import java.io.File;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class EnvironmentDetector {
private static Logger log = LoggerFactory.getLogger(EnvironmentDetector.class);
private static final String JBOSS_PROPERTY = "jboss.home.dir";
private static final String TOMCAT_PROPERTY = "catalina.home";
private static final String CUSTOM_HOME_PROPERTY = "openkm.custom.home";
private static final String OS_LINUX = "linux";
private static final String OS_WINDOWS = "windows";
private static final String OS_MAC = "mac os";
/**
* Guess the application server home directory
*/
public static String getServerHomeDir() {
// Try custom environment variable
String dir = System.getProperty(CUSTOM_HOME_PROPERTY);
if (dir != null) {
log.debug("Using custom home: {}", dir);
return dir;
}
// Try JBoss
dir = System.getProperty(JBOSS_PROPERTY);
if (dir != null) {
log.debug("Using JBoss: {}", dir);
return dir;
}
// Try Tomcat
dir = System.getProperty(TOMCAT_PROPERTY);
if (dir != null) {
log.debug("Using Tomcat: {}", dir);
return dir;
}
// Otherwise GWT hosted mode
dir = System.getProperty("user.dir") + "/src/test/resources";
log.debug("Using default dir: {}", dir);
return dir;
}
/**
* Get server log directory
*/
public static String getServerLogDir() {
// Try JBoss
String dir = System.getProperty(JBOSS_PROPERTY);
if (dir != null) {
return dir + "/server/default/log";
}
// Try Tomcat
dir = System.getProperty(TOMCAT_PROPERTY);
if (dir != null) {
return dir + "/logs";
}
return "";
}
/**
* Detect if running in JBoss
*/
public static boolean isServerJBoss() {
return System.getProperty(JBOSS_PROPERTY) != null;
}
/**
* Detect if running in Tomcat
*/
public static boolean isServerTomcat() {
return !isServerJBoss() && System.getProperty(TOMCAT_PROPERTY) != null;
}
/**
* Guess JNDI base
*/
public static String getServerJndiBase() {
if (isServerJBoss()) return "java:/";
else if (isServerTomcat()) return "java:/comp/env/";
else return "";
}
/**
* Guess the system wide temporary directory
*/
public static String getTempDir() {
String dir = System.getProperty("java.io.tmpdir");
if (dir != null) {
return dir;
} else {
return "";
}
}
/**
* Guess the system null device
*/
public static String getNullDevice() {
String os = System.getProperty("os.name").toLowerCase();
if (os.contains(OS_LINUX) || os.contains(OS_MAC)) {
return "/dev/null";
} else if (os.contains(OS_WINDOWS)) {
return "NUL:";
} else {
return null;
}
}
/**
* Execute application launcher
*/
public static void executeLauncher(String file) throws IOException {
String os = System.getProperty("os.name").toLowerCase();
if (os.contains(OS_LINUX)) {
if (new File("/usr/bin/xdg-open").canExecute()) {
Runtime.getRuntime().exec(new String[] { "/usr/bin/xdg-open", file });
} else if (new File("/usr/bin/kde-open").canExecute()) {
Runtime.getRuntime().exec(new String[] { "/usr/bin/kde-open", file });
} else {
throw new IOException("Linux flavour not supported");
}
} else if (os.contains(OS_MAC)) {
Runtime.getRuntime().exec(new String[] { "open", file });
} else if (os.contains(OS_WINDOWS)) {
Runtime.getRuntime().exec("rundll32 SHELL32.DLL,ShellExec_RunDLL \"" + file + "\"");
} else {
throw new IOException("Environment not supported");
}
}
/**
* Guess if running in Windows
*/
public static boolean isWindows() {
String os = System.getProperty("os.name").toLowerCase();
return os.contains(OS_WINDOWS);
}
/**
* Guess if running in Linux
*/
public static boolean isLinux() {
String os = System.getProperty("os.name").toLowerCase();
return os.contains(OS_LINUX);
}
/**
* Guess if running in Mac
*/
public static boolean isMac() {
String os = System.getProperty("os.name").toLowerCase();
return os.contains(OS_MAC);
}
/**
* Test if is running in application server
*/
public static boolean inServer() {
return isServerJBoss() || isServerTomcat();
}
/**
* Get user home
*/
public static String getUserHome() {
return System.getProperty("user.home");
}
/**
* Guess OpenOffice / LibreOffice directory
*/
public static String detectOpenOfficePath() {
if (isLinux()) {
// Try LibreOffice
File dir = new File("/usr/lib/libreoffice");
if (dir.exists() && dir.isDirectory()) {
log.info("Using LibreOffice from: " + dir);
return dir.getAbsolutePath();
}
// Try LibreOffice (CentOS 64 bits)
dir = new File("/usr/lib64/libreoffice");
if (dir.exists() && dir.isDirectory()) {
log.info("Using LibreOffice from: " + dir);
return dir.getAbsolutePath();
}
// Try OpenOffice
dir = new File("/usr/lib/openoffice");
if (dir.exists() && dir.isDirectory()) {
log.info("Using OpenOffice from: " + dir);
return dir.getAbsolutePath();
}
// Try OpenOffice (CentOS 64 bits)
dir = new File("/usr/lib64/openoffice");
if (dir.exists() && dir.isDirectory()) {
log.info("Using OpenOffice from: " + dir);
return dir.getAbsolutePath();
}
// Otherwise none
return "";
} else {
return "";
}
}
/**
* Guess convert application
*/
public static String detectImagemagickConvert() {
if (isLinux()) {
File app = new File("/usr/bin/convert");
if (app.exists() && app.isFile()) {
return app.getAbsolutePath();
} else {
return "";
}
} if (isWindows()) {
File app = new File(getServerHomeDir() + "\\bin\\convert.exe");
if (app.exists() && app.isFile()) {
return app.getAbsolutePath();
} else {
return "";
}
} else {
return "";
}
}
/**
* Guess pdfimages application
*/
public static String detectPdfImages() {
final String params = "-j -f ${firstPage} -l ${lastPage} ${fileIn} ${imageRoot}";
if (isLinux()) {
File app = new File("/usr/bin/pdfimages");
if (app.exists() && app.isFile()) {
return app.getAbsolutePath() + " " + params;
} else {
app = new File(getServerHomeDir() + "/bin/pdfimages");
if (app.exists() && app.isFile()) {
return app.getAbsolutePath() + " " + params;
} else {
return "";
}
}
} if (isWindows()) {
File app = new File(getServerHomeDir() + "\\bin\\pdfimages.exe");
if (app.exists() && app.isFile()) {
return app.getAbsolutePath() + " " + params;
} else {
return "";
}
} else {
return "";
}
}
/**
* Guess pdf2swf application
*/
public static String detectSwftoolsPdf2Swf() {
final String params = "-f -T 9 -t -s storeallcharacters ${fileIn} -o ${fileOut}";
if (isLinux()) {
File app = new File(getServerHomeDir() + "/bin/pdf2swf");
if (app.exists() && app.isFile()) {
return app.getAbsolutePath() + " " + params;
} else {
return "";
}
} if (isWindows()) {
File app = new File(getServerHomeDir() + "\\bin\\pdf2swf.exe");
if (app.exists() && app.isFile()) {
return app.getAbsolutePath() + " " + params;
} else {
return "";
}
} else {
return "";
}
}
/**
* Guess gs application
*/
public static String detectGhostscript() {
if (isLinux()) {
File app = new File("/usr/bin/gs");
if (app.exists() && app.isFile()) {
return app.getAbsolutePath();
} else {
return "";
}
} if (isWindows()) {
File app = new File(getServerHomeDir() + "\\bin\\gswin32c.exe");
if (app.exists() && app.isFile()) {
return app.getAbsolutePath();
} else {
return "";
}
} else {
return "";
}
}
}
|
package com.lsz.service;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
/**
* Created by ex-lingsuzhi on 2018/3/30.
*/
@Service
public class RedisService {
@Cacheable(value="user-key")
public String getStr(){
System.out.println("call getStr");
return "service str";
}
}
|
/**
* CommonFramework
*
* Copyright (C) 2017 Black Duck Software, Inc.
* http://www.blackducksoftware.com/
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.blackducksoftware.tools.commonframework.standard.trackable;
import static org.junit.Assert.*;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.blackducksoftware.tools.commonframework.standard.trackable.Trackable;
import com.blackducksoftware.tools.commonframework.standard.trackable.TrackableRunner;
// TODO: Auto-generated Javadoc
/**
* The Class TrackableRunnerTest.
*/
public class TrackableRunnerTest {
/** The Constant MAX_TOLERABLE_SILENCE. */
private static final int MAX_TOLERABLE_SILENCE = 7;
/**
* Sets the up before class.
*
* @throws Exception
* the exception
*/
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
/**
* Tear down after class.
*
* @throws Exception
* the exception
*/
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
/**
* Test healthy worker.
*
* @throws Throwable
* the throwable
*/
@Test
public void testHealthyWorker() throws Throwable {
int percentCompleted = 0;
// Create and configure the worker object
HealthyWorkerMock worker = new HealthyWorkerMock();
worker.setConfiguration("Worker Configuration");
assertEquals("Worker Configuration", worker.getConfiguration());
// Create a TrackableRunner to run the worker object
TrackableRunner workerRunner = new TrackableRunner(worker);
// Start the work
workerRunner.startTrackable();
// Periodically ask the runner for progress info
for (int i = 0; i < 100; i++) {
try {
Thread.sleep(10L);
} catch (InterruptedException e) {
fail("Sleep interrupted.");
}
percentCompleted = workerRunner.getProgress();
if (percentCompleted >= 100) {
break;
}
}
assertEquals(100, percentCompleted);
}
/**
* Test shy worker.
*
* @throws Throwable
* the throwable
*/
@Test
public void testShyWorker() throws Throwable {
int percentCompleted = 0;
// Create and configure the worker object
Trackable worker = new ShyWorkerMock();
// Create a TrackableRunner to run the worker object
TrackableRunner workerRunner = new TrackableRunner(worker);
workerRunner.setMaxSilence(15); // Allows a 50% buffer
// Start the work
workerRunner.startTrackable();
// Periodically ask the runner for progress info
for (int i = 0; i < 12; i++) {
try {
Thread.sleep(10L);
} catch (InterruptedException e) {
fail("Sleep interrupted.");
}
percentCompleted = workerRunner.getProgress();
if (percentCompleted >= 100) {
break;
}
}
assertEquals(100, percentCompleted);
}
/**
* Test unresponsive worker.
*
* @throws Throwable
* the throwable
*/
@Test
public void testUnresponsiveWorker() throws Throwable {
int percentCompleted = 0;
// Create and configure the worker object
Trackable worker = new UnresponsiveWorkerMock();
// Create a TrackableRunner to run the worker object
TrackableRunner workerRunner = new TrackableRunner(worker);
workerRunner.setMaxSilence(MAX_TOLERABLE_SILENCE);
// Start the work
workerRunner.startTrackable();
// Periodically ask the runner for progress info
int tryCount;
Exception exceptionThrown = null;
for (tryCount = 1; tryCount <= 100; tryCount++) {
try {
Thread.sleep(10L);
} catch (InterruptedException e) {
fail("Sleep interrupted.");
}
try {
percentCompleted = workerRunner.getProgress();
} catch (RuntimeException e) {
exceptionThrown = e;
assertEquals("No response from worker in "
+ MAX_TOLERABLE_SILENCE + " tries.", e.getMessage());
break;
}
if (percentCompleted >= 100) {
break;
}
}
assertEquals(0, percentCompleted); // This worker makes no progress
assertNotNull(exceptionThrown);
assertEquals(MAX_TOLERABLE_SILENCE + 1, tryCount); // if we didn't
// detect worker's
// death, we've
// failed
}
/**
* Test suicidal worker.
*
* @throws Throwable
* the throwable
*/
@Test
public void testSuicidalWorker() throws Throwable {
// Create and configure the worker object
Trackable worker = new SuicidalWorkerMock();
// Create a TrackableRunner to run the worker object
TrackableRunner workerRunner = new TrackableRunner(worker);
// Start the work
workerRunner.startTrackable();
Thread.sleep(500L);
assertFalse(workerRunner.isAlive()); // This worker should be dead
// This should throw the suicidal worker's null pointer exception
try {
workerRunner.getProgress();
fail("WorkerTerminatedException not thrown");
} catch (RuntimeException e) {
assertEquals(
"java.lang.NullPointerException: SuicidalWorkerMock committing suicide.",
e.getMessage());
}
}
}
|
package org.spring.fom.support.task.pool;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.nio.file.FileSystems;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 负责监听配置变化,更新和提高poolMap中的pool
*
* @author shanhm1991@163.com
*
*/
public final class PoolManager {
protected static final Logger LOG = LoggerFactory.getLogger(PoolManager.class);
private static final ConcurrentMap<String,Pool<?>> poolMap = new ConcurrentHashMap<String,Pool<?>>();
private static final List<Pool<?>> poolRemoved = new ArrayList<Pool<?>>();
private static AtomicInteger removeCount = new AtomicInteger(0);
public static void listen(File poolXml){
load(poolXml);//确保在加载启动任务前已经加载过pool
new Listener(poolXml).start();
new Monitor().start();
}
public static Pool<?> get(String poolName) {
return poolMap.get(poolName);
}
private static void remve(String name){
Pool<?> pool = poolMap.remove(name);
if(pool != null){
pool.name = "removed-" + removeCount.incrementAndGet() + "-" + name;
LOG.warn("rename pool[" + name + "] -> pool[" + pool.name + "]");
poolRemoved.add(pool);
}
}
private static void remveAll(){
Iterator<String> it = poolMap.keySet().iterator();
while(it.hasNext()){
String name = it.next();
remve(name);
}
}
/**
* Listener单线程调用
* @param file
*/
@SuppressWarnings("rawtypes")
private static void load(File file){
SAXReader reader = new SAXReader();
reader.setEncoding("UTF-8");
LOG.info("load pool: " + file);
Document doc = null;
try{
doc = reader.read(new FileInputStream(file));
}catch(Exception e){
LOG.error("", e);
remveAll();
return;
}
Element pools = doc.getRootElement();
Iterator it = pools.elementIterator("pool");
Set<String> nameSet = new HashSet<String>();
while (it.hasNext()) {
Element ePool = (Element) it.next();
String name = ePool.attributeValue("name");
String clazz = ePool.attributeValue("class");
if(name == null){
LOG.warn("no name, pool[" + name + "] init failed.");
continue;
}
if(nameSet.contains(name)){
LOG.warn("pool[" + name + "] already exist, init canceled.");
continue;
}
if(clazz == null){
LOG.warn("no class, pool[" + name + "] init failed.");
remve(name);
continue;
}
Pool pool = poolMap.get(name);
if(pool != null){
if(pool.getClass().getName().equals(clazz)){
try {
pool.load(ePool);
nameSet.add(name);
} catch (Exception e) {
LOG.error("pool[" + name + "] init failed.", e);
remve(name);
}
continue;
}else{
remve(name);
}
}
try {
Class<?> poolClass = Class.forName(clazz);
Constructor ct = poolClass.getDeclaredConstructor(String.class);
ct.setAccessible(true);
pool = (Pool)ct.newInstance(name);
pool.load(ePool);
nameSet.add(name);
poolMap.put(name, pool);
} catch (Exception e) {
LOG.error("pool[" + name + "] init failed.", e);
}
}
LOG.info("loaded pools=" + poolMap.keySet());
}
private static class Listener extends Thread {
private final File poolXml;
public Listener(File poolXml) {
this.setName("pool-listener");
this.setDaemon(true);
this.poolXml = poolXml;
}
@Override
public void run() {
String parentPath = poolXml.getParent();
String name = poolXml.getName();
WatchService watch = null;
try {
watch = FileSystems.getDefault().newWatchService();
Paths.get(parentPath).register(watch, StandardWatchEventKinds.ENTRY_MODIFY);
} catch (IOException e) {
LOG.error("pool listen failed", e);
return;
}
WatchKey key = null;
while(true){
try {
key = watch.take();
} catch (InterruptedException e) {
return;
}
for(WatchEvent<?> event : key.pollEvents()){
if(StandardWatchEventKinds.ENTRY_MODIFY == event.kind()){
String eventName = event.context().toString();
if(name.equals(eventName)){
load(poolXml);
}
}
}
key.reset();
}
}
}
private static class Monitor extends Thread {
private static final long DELAY = 15 * 1000;
private static final int UNIT = 100;
private int cleanTimes = 0;
public Monitor() {
this.setName("pool-monitor");
this.setDaemon(true);
}
@Override
public void run() {
while(true){
try {
sleep(DELAY);
} catch (InterruptedException e) {
//should never happened
}
Iterator<Pool<?>> it = poolRemoved.iterator();
while(it.hasNext()){
Pool<?> pool = it.next();
pool.clean();
if(pool.getLocalAlives() == 0){
it.remove();
}
}
for(Pool<?> pool : poolMap.values()){
if(pool.aliveTimeOut == 0){
continue;
}
pool.clean();
}
StringBuilder builder = new StringBuilder(", Details=[");
for(Pool<?> pool : poolMap.values()){
builder.append(pool.name + ":" + pool.getLocalAlives() + "; ");
}
for(Pool<?> pool : poolRemoved){
builder.append(pool.name + "(removed):" + pool.getLocalAlives() + "; ");
}
String detail = builder.append("]").toString();
if(cleanTimes++ % UNIT == 0){
LOG.info("Total=" + Pool.getAlives() + detail);
}
}
}
}
}
|
/**
* Engine / Context
*/
package edu.self.engine;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.Transparency;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Context Class
*/
public abstract class Context {
/**
* Debug
*/
private static final Logger debug = Logger.getLogger(Context.class.getName());
/**
* Components
*/
public BufferedImage buffer;
public Graphics2D canvas;
public List<Entity> entities;
public List<Collision> collisions;
public Context redirect;
/**
* Properties
*/
public boolean active;
public int width;
public int height;
/**
* Engine
*/
protected Engine engine;
/**
* Constructor
*/
public Context(Engine engine) {
debug.setLevel(Level.INFO);
buffer = null;
canvas = null;
entities = new ArrayList<Entity>();
collisions = new ArrayList<Collision>();
redirect = null;
active = true;
width = engine.config.getInt("renderer.native.width");
height = engine.config.getInt("renderer.native.height");
this.engine = engine;
}
/**
* Context Methods
*/
// Startup and Shutdown
public void starts() {
start();
for(Entity entity : entities) {
entity.start();
}
}
public void stops() {
stop();
for(Entity entity : entities) {
entity.stop();
}
}
// Logic
public void thinks(double interval) {
think(interval);
for(Entity entity : entities) {
entity.think(interval);
}
}
// Physics
public void updates(double interval) {
for(Entity entity : entities) {
entity.applyVelocity(interval);
}
collisions.clear();
for(Entity a : entities) {
for(Entity b : entities) {
if(a == b || !a.coplanar(b)) {
continue;
}
boolean duplicate = false;
for(Collision collision : collisions) {
if((a == collision.a() && b == collision.b()) || (a == collision.b() && b == collision.a())) {
duplicate = true;
break;
}
}
if(duplicate) {
continue;
}
Collision collision = new Collision(a, b);
if(collision.collides()) {
collisions.add(collision);
}
}
}
for(Entity entity : entities) {
entity.applyForces();
entity.applyAcceleration(interval);
}
for(Collision collision : collisions) {
collision.collide();
}
update(interval);
for(Entity entity : entities) {
entity.update(interval);
}
}
// Rendering
public void renders(double interpolation) {
buffer = new BufferedImage(width, height, Transparency.TRANSLUCENT);
canvas = (Graphics2D)buffer.createGraphics();
canvas.setBackground(engine.renderer.background);
canvas.clearRect(0, 0, (int)buffer.getWidth(), (int)buffer.getHeight());
render(interpolation);
for(Entity entity : entities) {
entity.render(interpolation);
}
canvas.dispose();
}
/**
* Abstract Methods
*/
// Startup and Shutdown
public abstract void start();
public abstract void stop();
// Logic, Physics, and Rendering
public abstract void think(double interval);
public abstract void update(double interval);
public abstract void render(double interpolation);
}
|
package com.example.monapplicationtd3.data;
import com.example.monapplicationtd3.presentation.model.RestPokemonResponse;
import retrofit2.Call;
import retrofit2.http.GET;
public interface PokeApi {
@GET("/api/v2/nature")
Call<RestPokemonResponse> getPokemonResponse();
}
|
package org.example.cayenne.persistent.auto;
import java.util.List;
import org.apache.cayenne.CayenneDataObject;
import org.apache.cayenne.exp.Property;
import org.example.cayenne.persistent.Invoice;
/**
* Class _Contact was generated by Cayenne.
* It is probably a good idea to avoid changing this class manually,
* since it may be overwritten next time code is regenerated.
* If you need to make any customizations, please use subclass.
*/
public abstract class _Contact extends CayenneDataObject {
private static final long serialVersionUID = 1L;
public static final String ID_PK_COLUMN = "id";
public static final Property<String> EMAIL = Property.create("email", String.class);
public static final Property<String> LAST_NAME = Property.create("lastName", String.class);
public static final Property<String> NAME = Property.create("name", String.class);
public static final Property<List<Invoice>> INVOICES = Property.create("invoices", List.class);
public void setEmail(String email) {
writeProperty("email", email);
}
public String getEmail() {
return (String)readProperty("email");
}
public void setLastName(String lastName) {
writeProperty("lastName", lastName);
}
public String getLastName() {
return (String)readProperty("lastName");
}
public void setName(String name) {
writeProperty("name", name);
}
public String getName() {
return (String)readProperty("name");
}
public void addToInvoices(Invoice obj) {
addToManyTarget("invoices", obj, true);
}
public void removeFromInvoices(Invoice obj) {
removeToManyTarget("invoices", obj, true);
}
@SuppressWarnings("unchecked")
public List<Invoice> getInvoices() {
return (List<Invoice>)readProperty("invoices");
}
}
|
package cn.izouxiang.dao;
import cn.izouxiang.domain.CFRecord;
import cn.izouxiang.dao.base.BaseMongoDao;
public interface CFRecordDao extends BaseMongoDao<CFRecord> {
}
|
package it.polito.tdp.bar.model;
public class Model {
private Simulator sim;
public Model() {
sim = new Simulator();
sim.run();
}
public int getClienti() {
return sim.getClienti();
}
public int getClientiSoddisfatti() {
return sim.getClientiSoddisfatti();
}
public int getClientiInsoddisfatti() {
return sim.getClientiInsoddisfatti();
}
}
|
package org.mybatis.spring.datasource;
import static java.lang.reflect.Proxy.newProxyInstance;
import static org.apache.ibatis.reflection.ExceptionUtil.unwrapThrowable;
import static org.mybatis.spring.SqlSessionUtils.closeSqlSession;
import static org.mybatis.spring.SqlSessionUtils.getSqlSession;
import static org.mybatis.spring.SqlSessionUtils.isSqlSessionTransactional;
import static org.springframework.util.Assert.notNull;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.exceptions.PersistenceException;
import org.apache.ibatis.executor.BatchResult;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.MyBatisExceptionTranslator;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.dao.support.PersistenceExceptionTranslator;
/**
* 多数据源sqlsessiontemplate配置
*
* @author lindezhi 2016年7月19日 下午5:59:26
*/
public class SimpleSqlSessionTemplate extends SqlSessionTemplate {
/**
* 默认SqlSessionFactory
*/
private final SqlSessionFactory defaultSqlSessionFactory;
/**
* 执行器类型,方便创建sqlsession
*/
private final ExecutorType executorType;
/**
* sqlSession代理对象
*/
private final SqlSession sqlSessionProxy;
/**
* Mysql异常转换器
*/
private final PersistenceExceptionTranslator exceptionTranslator;
/**
* 可以选择的SqlSessionfactory列表
*/
private Map<String, SqlSessionFactory> targetSqlSessionFactory = new HashMap<String, SqlSessionFactory>();
/**
* Constructs a Spring managed SqlSession with the {@code SqlSessionFactory} provided as an argument.
*
* @param sqlSessionFactory
*/
public SimpleSqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
this(sqlSessionFactory, sqlSessionFactory.getConfiguration().getDefaultExecutorType());
}
public SimpleSqlSessionTemplate(SqlSessionFactory sqlSessionFactory,Map<String, SqlSessionFactory> targetSqlSessionFactory) {
this(sqlSessionFactory, sqlSessionFactory.getConfiguration().getDefaultExecutorType());
this.targetSqlSessionFactory = targetSqlSessionFactory;
}
/**
* Constructs a Spring managed SqlSession with the {@code SqlSessionFactory} provided as an argument and the given
* {@code ExecutorType} {@code ExecutorType} cannot be changed once the {@code SimpleSqlSessionTemplate} is
* constructed.
*
* @param sqlSessionFactory
* @param executorType
*/
public SimpleSqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType) {
this(sqlSessionFactory, executorType, new MyBatisExceptionTranslator(sqlSessionFactory.getConfiguration().getEnvironment()
.getDataSource(), true));
}
/**
* Constructs a Spring managed {@code SqlSession} with the given {@code SqlSessionFactory} and {@code ExecutorType}.
* A custom {@code SQLExceptionTranslator} can be provided as an argument so any {@code PersistenceException} thrown
* by MyBatis can be custom translated to a {@code RuntimeException} The {@code SQLExceptionTranslator} can also be
* null and thus no exception translation will be done and MyBatis exceptions will be thrown
*
* @param sqlSessionFactory
* @param executorType
* @param exceptionTranslator
*/
public SimpleSqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType,
PersistenceExceptionTranslator exceptionTranslator) {
super(sqlSessionFactory);
notNull(sqlSessionFactory, "Property 'sqlSessionFactory' is required");
notNull(executorType, "Property 'executorType' is required");
this.defaultSqlSessionFactory = sqlSessionFactory;
this.executorType = executorType;
this.exceptionTranslator = exceptionTranslator;
this.sqlSessionProxy = (SqlSession) newProxyInstance(SqlSessionFactory.class.getClassLoader(), new Class[] { SqlSession.class },
new SqlSessionInterceptor());
}
/**
* sqlSessionFactory获取
*/
public SqlSessionFactory getSqlSessionFactory() {
String contextType = DataSourceContextHolder.getContextType();
if (contextType == null) {
return defaultSqlSessionFactory;
}
SqlSessionFactory sessionFactory = this.targetSqlSessionFactory.get(contextType);
if (sessionFactory != null) {
return sessionFactory;
} else {
return defaultSqlSessionFactory;
}
}
public ExecutorType getExecutorType() {
return this.executorType;
}
public PersistenceExceptionTranslator getPersistenceExceptionTranslator() {
return this.exceptionTranslator;
}
/**
* {@inheritDoc}
*/
public <T> T selectOne(String statement) {
return this.sqlSessionProxy.<T> selectOne(statement);
}
/**
* {@inheritDoc}
*/
public <T> T selectOne(String statement, Object parameter) {
return this.sqlSessionProxy.<T> selectOne(statement, parameter);
}
/**
* {@inheritDoc}
*/
public <K, V> Map<K, V> selectMap(String statement, String mapKey) {
return this.sqlSessionProxy.<K, V> selectMap(statement, mapKey);
}
/**
* {@inheritDoc}
*/
public <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey) {
return this.sqlSessionProxy.<K, V> selectMap(statement, parameter, mapKey);
}
/**
* {@inheritDoc}
*/
public <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey, RowBounds rowBounds) {
return this.sqlSessionProxy.<K, V> selectMap(statement, parameter, mapKey, rowBounds);
}
/**
* {@inheritDoc}
*/
public <E> List<E> selectList(String statement) {
return this.sqlSessionProxy.<E> selectList(statement);
}
/**
* {@inheritDoc}
*/
public <E> List<E> selectList(String statement, Object parameter) {
return this.sqlSessionProxy.<E> selectList(statement, parameter);
}
/**
* {@inheritDoc}
*/
public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
return this.sqlSessionProxy.<E> selectList(statement, parameter, rowBounds);
}
/**
* {@inheritDoc}
*/
public void select(String statement, ResultHandler handler) {
this.sqlSessionProxy.select(statement, handler);
}
/**
* {@inheritDoc}
*/
public void select(String statement, Object parameter, ResultHandler handler) {
this.sqlSessionProxy.select(statement, parameter, handler);
}
/**
* {@inheritDoc}
*/
public void select(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler) {
this.sqlSessionProxy.select(statement, parameter, rowBounds, handler);
}
/**
* {@inheritDoc}
*/
public int insert(String statement) {
return this.sqlSessionProxy.insert(statement);
}
/**
* {@inheritDoc}
*/
public int insert(String statement, Object parameter) {
return this.sqlSessionProxy.insert(statement, parameter);
}
/**
* {@inheritDoc}
*/
public int update(String statement) {
return this.sqlSessionProxy.update(statement);
}
/**
* {@inheritDoc}
*/
public int update(String statement, Object parameter) {
return this.sqlSessionProxy.update(statement, parameter);
}
/**
* {@inheritDoc}
*/
public int delete(String statement) {
return this.sqlSessionProxy.delete(statement);
}
/**
* {@inheritDoc}
*/
public int delete(String statement, Object parameter) {
return this.sqlSessionProxy.delete(statement, parameter);
}
/**
* {@inheritDoc}
*/
public <T> T getMapper(Class<T> type) {
return getConfiguration().getMapper(type, this);
}
/**
* {@inheritDoc}
*/
public void commit() {
throw new UnsupportedOperationException("Manual commit is not allowed over a Spring managed SqlSession");
}
/**
* {@inheritDoc}
*/
public void commit(boolean force) {
throw new UnsupportedOperationException("Manual commit is not allowed over a Spring managed SqlSession");
}
/**
* {@inheritDoc}
*/
public void rollback() {
throw new UnsupportedOperationException("Manual rollback is not allowed over a Spring managed SqlSession");
}
/**
* {@inheritDoc}
*/
public void rollback(boolean force) {
throw new UnsupportedOperationException("Manual rollback is not allowed over a Spring managed SqlSession");
}
/**
* {@inheritDoc}
*/
public void close() {
throw new UnsupportedOperationException("Manual close is not allowed over a Spring managed SqlSession");
}
/**
* {@inheritDoc}
*/
public void clearCache() {
this.sqlSessionProxy.clearCache();
}
/**
* {@inheritDoc}
*
*/
public Configuration getConfiguration() {
return this.defaultSqlSessionFactory.getConfiguration();
}
/**
* {@inheritDoc}
*/
public Connection getConnection() {
return this.sqlSessionProxy.getConnection();
}
/**
* {@inheritDoc}
*
* @since 1.0.2
*
*/
public List<BatchResult> flushStatements() {
return this.sqlSessionProxy.flushStatements();
}
/**
* Proxy needed to route MyBatis method calls to the proper SqlSession got from Spring's Transaction Manager It also
* unwraps exceptions thrown by {@code Method#invoke(Object, Object...)} to pass a {@code PersistenceException} to
* the {@code PersistenceExceptionTranslator}.
*/
private class SqlSessionInterceptor implements InvocationHandler {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
SqlSession sqlSession = getSqlSession(SimpleSqlSessionTemplate.this.getSqlSessionFactory(),
SimpleSqlSessionTemplate.this.executorType, SimpleSqlSessionTemplate.this.exceptionTranslator);
try {
Object result = method.invoke(sqlSession, args);
if (!isSqlSessionTransactional(sqlSession, SimpleSqlSessionTemplate.this.getSqlSessionFactory())) {
// force commit even on non-dirty sessions because some databases require
// a commit/rollback before calling close()
sqlSession.commit(true);
}
return result;
} catch (Throwable t) {
Throwable unwrapped = unwrapThrowable(t);
if (SimpleSqlSessionTemplate.this.exceptionTranslator != null && unwrapped instanceof PersistenceException) {
// release the connection to avoid a deadlock if the translator is no loaded. See issue #22
closeSqlSession(sqlSession, SimpleSqlSessionTemplate.this.getSqlSessionFactory());
sqlSession = null;
Throwable translated = SimpleSqlSessionTemplate.this.exceptionTranslator
.translateExceptionIfPossible((PersistenceException) unwrapped);
if (translated != null) {
unwrapped = translated;
}
}
throw unwrapped;
} finally {
if (sqlSession != null) {
closeSqlSession(sqlSession, SimpleSqlSessionTemplate.this.getSqlSessionFactory());
}
}
}
}
public void setTargetSqlSessionFactory(Map<String, SqlSessionFactory> targetSqlSessionFactory) {
this.targetSqlSessionFactory = targetSqlSessionFactory;
}
}
|
package com.wentongwang.mysports.views.activity.newscomment;
import com.wentongwang.mysports.base.BasePresenter;
import com.wangwentong.sports_api.model.CommentInfo;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Administrator on 2017/3/28.
*/
public class NewsCommentPresenter extends BasePresenter<NewsCommentView>{
private List<CommentInfo> itemList;
//the comment of news for testing
public void getComments() {
itemList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
CommentInfo item = new CommentInfo("content" + i, i);
itemList.add(item);
}
//获取到list数据后调用view去填充数据
view.fillComments(itemList);
}
}
|
package com.wind.s06;
import java.util.ArrayList;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ApplicationConfig {
@Bean
public Family family() {
Family family = new Family("그레고리펙", "오드리햅번");
family.setBrotherName("발리");
return family;
}
}
|
package com.stark.design23.responsibility;
/**
* Created by Stark on 2018/1/17.
* 警告输出
*/
public class WarnLogPrinter extends AbstractLogPrinter {
public WarnLogPrinter() {
this.level = AbstractLogPrinter.WARN;
}
public void log(String msg) {
System.out.println("info: " + msg);
}
}
|
package com.space.service;
import com.space.controller.ShipOrder;
import com.space.model.Ship;
import com.space.model.ShipType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestParam;
import javax.sql.DataSource;
import java.sql.ResultSet;
import java.util.*;
/**
В методе findAll используются JdbcTemplate, NamedParameterJdbcTemplate и DAO для изучения темы. Вся остальная работа с данными через Spring Data.
*/
@Component
public class ShipDaoService implements ShipDao{
//Класс JdbcTemplate выполняет SQL-запросы, выполняет итерации по ResultSet и извлекает вызываемые значения, обновляет инструкции и вызовы процедур, “ловит” исключения и транслирует их в исключения, определённые в пакете org.springframwork.dao
private JdbcTemplate template;
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
//DataSource - sql интерфейс, его объекты предоставляют нам connection.
@Autowired //чтобы бин dataSource автоматически вставился
public ShipDaoService(DataSource dataSource) {
this.template = new JdbcTemplate(dataSource);
this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
}
private Map<Long, Ship> shipsMap = new HashMap<>();
//RowMapper - это специальный объект, который отображает строки ResultSet,
//который пришел к нам из бд, в объекты джава.
private RowMapper<Ship> shipRowMapper
= (ResultSet resultSet, int i) -> {
Long id = resultSet.getLong("id");
if (!shipsMap.containsKey(id)) {
String name = resultSet.getString("name");
String planet = resultSet.getString("planet");
ShipType shipType = ShipType.valueOf(resultSet.getString("shipType"));
Date prodDate = resultSet.getDate("prodDate");
Boolean isUsed = resultSet.getBoolean("isUsed");
Double speed = resultSet.getDouble("speed");
Integer crewSize = resultSet.getInt("crewSize");
Double rating = resultSet.getDouble("rating");
Ship ship = new Ship(id, name, planet, shipType, prodDate, isUsed, speed, crewSize, rating);
shipsMap.put(id, ship);
}
return shipsMap.get(id);
};
@Override
public List<Ship> findAll(@RequestParam(value = "name", required = false) Optional<String> name,
@RequestParam(value = "planet", required = false) Optional<String> planet,
@RequestParam(value = "shipType", required = false) Optional<ShipType> shipType,
@RequestParam(value = "after", required = false) Optional<Long> after,
@RequestParam(value = "before", required = false) Optional<Long> before,
@RequestParam(value = "isUsed", required = false) Optional<Boolean> isUsed,
@RequestParam(value = "minSpeed", required = false) Optional<Double> minSpeed,
@RequestParam(value = "maxSpeed", required = false) Optional<Double> maxSpeed,
@RequestParam(value = "minCrewSize", required = false) Optional<Integer> minCrewSize,
@RequestParam(value = "maxCrewSize", required = false) Optional<Integer> maxCrewSize,
@RequestParam(value = "minRating", required = false) Optional<Double> minRating,
@RequestParam(value = "maxRating", required = false) Optional<Double> maxRating) throws Exception{
String sqlSelectByFilters = " SELECT * FROM ship where name like :name and planet like :planet " +
" and prodDate between :after and :before " +
" and speed between :minSpeed and :maxSpeed " +
" and crewSize between :minCrewSize and :maxCrewSize " +
" and rating between :minRating and :maxRating ";
Date dateAfter = new GregorianCalendar(2800, 0 , 1).getTime();
Date dateBefore = new GregorianCalendar(3019, 11 , 31).getTime();
Date beforeNew = before.isPresent() ? new Date(before.get() -3600001L) : new Date(dateBefore.getTime());
MapSqlParameterSource mapFilters = new MapSqlParameterSource();
mapFilters.addValue("name", "%" + name.orElse("") + "%");
mapFilters.addValue("planet", "%" + planet.orElse("") + "%");
mapFilters.addValue("after", new Date(after.orElse(dateAfter.getTime())));
mapFilters.addValue("before", beforeNew);
mapFilters.addValue("minSpeed", minSpeed.orElse(0.01));
mapFilters.addValue("maxSpeed", maxSpeed.orElse(0.99));
mapFilters.addValue("minCrewSize", minCrewSize.orElse(1));
mapFilters.addValue("maxCrewSize", maxCrewSize.orElse(9999));
mapFilters.addValue("minRating", minRating.orElse(0.0));
mapFilters.addValue("maxRating", maxRating.orElse(80.0));
List<Ship> ships = namedParameterJdbcTemplate.query(sqlSelectByFilters, mapFilters, shipRowMapper);
shipsMap.clear();
if(shipType.isPresent())
for (int i = 0; i < ships.size(); i++) {
if(!ships.get(i).getShipType().equals(shipType.get())) {
ships.remove(i);
i--;
}
}
if(isUsed.isPresent())
for (int i = 0; i < ships.size(); i++) {
if(!ships.get(i).getUsed().equals(isUsed.get())) {
ships.remove(i);
i--;
}
}
return ships;
}
public void getOrderShipList (List<Ship> list, ShipOrder order) {
if (order.equals(ShipOrder.ID)) {
list.sort(new Comparator<Ship>() {
@Override
public int compare(Ship ship1, Ship ship2) {
if(ship1.getId() - ship2.getId() > 0) return 1;
if(ship1.getId() - ship2.getId() < 0) return -1;
else return 0;
}
});
}
else if (order.equals(ShipOrder.SPEED)) {
list.sort(new Comparator<Ship>() {
@Override
public int compare(Ship ship1, Ship ship2) {
if(ship1.getSpeed() - ship2.getSpeed() > 0) return 1;
if(ship1.getSpeed() - ship2.getSpeed() < 0) return -1;
else return 0;
}
});
}
else if (order.equals(ShipOrder.DATE)) {
list.sort(new Comparator<Ship>() {
@Override
public int compare(Ship ship1, Ship ship2) {
if(ship1.getProdDate().getTime() - ship2.getProdDate().getTime() > 0) return 1;
if(ship1.getProdDate().getTime() - ship2.getProdDate().getTime() < 0) return -1;
else return 0;
}
});
}
else if (order.equals(ShipOrder.RATING)){
list.sort(new Comparator<Ship>() {
@Override
public int compare(Ship ship1, Ship ship2) {
if(ship1.getRating() - ship2.getRating() > 0) return 1;
if(ship1.getRating() - ship2.getRating() < 0) return -1;
else return 0;
}
});
}
}
@Override
public List<Ship> findAllOnPage(List<Ship> ships, Integer pageNumber, Integer pageSize) {
List<Ship> result = new ArrayList<>();
int skip = pageNumber * pageSize;
for (int i = skip; i < Math.min(skip + pageSize, ships.size()); i++) {
result.add(ships.get(i));
}
return result;
}
@Override
public void save(Ship model) {}
@Override
public void update(Ship model) {}
@Override
public void delete(Integer id) {}
@Override
public List<Ship> findAll() {
return null;
}
}
|
package com.rc.portal.service.impl;
import java.sql.SQLException;
import com.rc.portal.service.IShortBuyManager;
import com.rc.portal.vo.TShortBuy;
public class ShortBuyManagerImpl implements IShortBuyManager {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
@Override
public TShortBuy getShortBuyGooods() throws SQLException {
// TODO Auto-generated method stub
return null;
}
}
|
package com.mathpar.students.ukma.Morenets.MPI_2;
import mpi.*;
import java.util.Random;
public class MPI_2_2 {
public static void main(String[] args) throws MPIException {
MPI.Init(args);
final Intracomm WORLD = MPI.COMM_WORLD;
WORLD.barrier();
final int arraySize = Integer.parseInt(args[0]);
double[] array = new double[arraySize];
final int myRank = WORLD.getRank();
final int msgTag = 3000;
if (myRank == 0) {
for (int i = 0; i < arraySize; ++i) {
array[i] = new Random().nextDouble();
System.out.println("a[" + i + "]= " + array[i]);
}
for (int procNum = 1; procNum < WORLD.getSize(); ++procNum)
WORLD.send(array, arraySize, MPI.DOUBLE, procNum, msgTag);
System.out.println("Proc num " + myRank +" Array sent\n");
} else {
WORLD.recv(array, arraySize, MPI.DOUBLE, 0, msgTag);
for (int i = 0; i < arraySize; ++i)
System.out.println("a[" + i + "]= " + array[i]);
System.out.println("Proc num " + myRank +" Array received\n");
}
MPI.Finalize();
}
}
/*
Command: mpirun -np 3 java -cp out/production/MPI.2.2 MPI_2_2 5
Output:
a[0]= 0.7453919044010927
a[1]= 0.29248519683239405
a[2]= 0.4728562004208485
a[3]= 0.6875779943440042
a[4]= 0.9819462549482042
Proc num 0 Array sent
a[0]= 0.7453919044010927
a[1]= 0.29248519683239405
a[2]= 0.4728562004208485
a[3]= 0.6875779943440042
a[4]= 0.9819462549482042
a[0]= 0.7453919044010927
a[1]= 0.29248519683239405
a[2]= 0.4728562004208485
a[3]= 0.6875779943440042
a[4]= 0.9819462549482042
Proc num 1 Array received
Proc num 2 Array received
*/
|
package com.demo.rewardsprogram.controller;
import java.text.ParseException;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
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.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.demo.rewardsprogram.exception.ResourceNotFoundException;
import com.demo.rewardsprogram.model.Transaction;
import com.demo.rewardsprogram.model.TransactionRequest;
import com.demo.rewardsprogram.model.TransactionResponse;
import com.demo.rewardsprogram.service.TransactionService;
@RestController
@RequestMapping("/api")
public class RewardsProgramController {
@Autowired
TransactionService transactionService;
@GetMapping(value="/transaction",produces=MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public List<Transaction> getAllTransactions() {
return transactionService.getAllTransactions();
}
@GetMapping(value="/rewards/{customerId}/{fromDate}/{toDate}",produces=MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public TransactionResponse getTotalRewardsInrange(@PathVariable Long customerId,@PathVariable String fromDate,@PathVariable String toDate) throws ParseException {
return transactionService.getTotalRewardsInrange(customerId,fromDate,toDate);
}
@GetMapping(value="/transaction/{customerId}/{fromDate}/{toDate}",produces=MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public List<Transaction> getRewardsInrange(@PathVariable Long customerId,@PathVariable String fromDate,@PathVariable String toDate) throws ParseException {
return transactionService.getRewardsInrange(customerId,fromDate,toDate);
}
@PostMapping(value="/transaction",produces=MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Transaction createTransaction(@Valid @RequestBody TransactionRequest transactionRequest) {
return transactionService.createTransaction(transactionRequest);
}
@GetMapping(value="/transaction/{id}",produces=MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Transaction getTransactionById(@PathVariable(value = "id") Long transactionId) {
return transactionService.getTransactionById(transactionId)
.orElseThrow(() -> new ResourceNotFoundException("Transaction", "id", transactionId));
}
@PutMapping(value="/transaction/{id}",produces=MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Transaction updateTransaction(@PathVariable(value = "id") Long transactionId,
@Valid @RequestBody TransactionRequest transactionDetails) {
Transaction updatedTransaction = transactionService.updateTransaction(transactionId,transactionDetails);
return updatedTransaction;
}
@DeleteMapping(value="/transaction/{id}",produces=MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ResponseEntity<?> deleteTransaction(@PathVariable(value = "id") Long transactionId) {
transactionService.deleteTransaction(transactionId);
return ResponseEntity.ok().build();
}
}
|
package kyle.game.besiege.battle;
import kyle.game.besiege.Destination;
import kyle.game.besiege.Faction;
import kyle.game.besiege.Kingdom;
import kyle.game.besiege.StrictArray;
import kyle.game.besiege.army.Army;
import kyle.game.besiege.location.Location;
import kyle.game.besiege.party.Party;
import kyle.game.besiege.party.Soldier;
// Represents a battle between two or more parties.
// Battles are in "real-time" and should support adding parties to one of the two sides (attackers and defenders).
// If a battle involves the player, a PlayerBattle is used to represent the battle. This special type of battle interface
// behaves as if the battle takes place instantaneously.
// If a player interrupts an ongoing battle, they will convert it into a PlayerBattle. If a player leaves a PlayerBattle,
// it is converted back into a normal battle.
// Once a non-player army enters a battle, it is essentially *passing control* of itself to the battle. Depending on the
// battle implementation, it may be destroyed or retreat without control over that.
public interface Battle {
// TODO remove all armies, just use parties.
// Adds the given playerPartyPanel to the list of attackers. Disables the army until they leave the battle or are destroyed.
// Returns true if playerPartyPanel was added successfully, false otherwise.
public boolean addToAttackers(Army army);
//
// // Adds the given playerPartyPanel to the list of defenders. Disables the army until they leave the battle or are destroyed.
// // Returns true if playerPartyPanel was added successfully, false otherwise.
public boolean addToDefenders(Army army);
public StrictArray<Party> getAttackingParties();
public StrictArray<Party> getDefendingParties();
public StrictArray<Party> getAttackingPartiesRetreated();
public StrictArray<Party> getDefendingPartiesRetreated();
public boolean shouldJoinAttackers(Army army);
public boolean shouldJoinDefenders(Army army);
// Returns a double in [0, 1] representing the current battle balance for the defenders.
// E.g. 0.9 means defenders are doing very well.
public double getBalanceDefenders();
// Sets an advantage for the defenders, in [0, 1]
public void setDefensiveAdvantage(double advantage);
// Note that this should not change throughout the duration of the battle.
public Faction getAttackingFactionOrNull();
// Note that this should not change
public Faction getDefendingFactionOrNull();
public float getAttackingAtk();
public float getDefendingAtk();
// Run one round of battle simulation
public void simulate(float delta);
// If the given army is in this battle, force it to retreat.
public void forceRetreat(Army army);
public void forceRetreatAllAttackers();
// Force a casualty of the given soldier. Used mostly by battlestage.
public void casualty(Soldier soldier, boolean atkDead);
public boolean playerAttacking();
public boolean playerDefending();
public boolean isOver();
public boolean didAttackersWin();
VictoryManager getVictoryManager();
}
|
package lotto.step1;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.junit.jupiter.api.Assertions.*;
class ValidationTest {
@Test
@DisplayName("빈 문자열 이나 null 을 입력했을 때 boolean 값 확인")
void checkEmptyAndNull() {
Validation validation = new Validation("");
assertThat(validation.checkEmptyAndNull()).isTrue();
}
@Test
@DisplayName("빈 문자열 이나 null 을 입력했을 때 boolean 값 확인 2")
void checkEmptyAndNull2() {
Validation validation = new Validation(null);
assertThat(validation.checkEmptyAndNull()).isTrue();
}
@Test
@DisplayName("문자열로 숫자 하나를 입력 했는지 검증 하는 테스트")
void onlyNumberTest() {
Validation validation = new Validation("3");
assertThat(validation.checkOnlyNumber()).isTrue();
}
@Test
@DisplayName("문자열로 숫자 하나를 입력 했는지 검증 하는 테스트2")
void onlyNumberTest2() {
Validation validation = new Validation("s");
assertThat(validation.checkOnlyNumber()).isFalse();
}
@Test
@DisplayName("음수를 포함했을 때 예외처리 하는 테스트")
void isNegativeNumber() {
Calculator calculator = new Calculator("-1,2,4");
assertThatThrownBy(() -> calculator.isNegativeNumber("-1")).isInstanceOf(RuntimeException.class);
}
}
|
package ba.bitcamp.vjezbe.db;
import java.sql.*;
public class Insert {
private static Connection createConnection(String baseName) {
try {
return DriverManager.getConnection("jdbc:sqlite:" + baseName);
} catch (SQLException e) {
return null;
}
}
public static void main(String[] args) {
Connection db = null;
db = createConnection("bitbase.db");
if (db == null) {
System.err.println("Not connected");
System.exit(1);
}
String sql = "insert into users values(?, 'bttalic5', '123456789');";
try {
Statement stmt = db.createStatement();
stmt.execute(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package com.bingo.code.example.design.composite.nodesign;
import java.util.*;
/**
* ��϶�������������϶������Ҷ�Ӷ���
*/
public class Composite {
/**
* ������¼������������϶���
*/
private Collection<Composite> childComposite = new ArrayList<Composite>();
/**
* ������¼����������Ҷ�Ӷ���
*/
private Collection<Leaf> childLeaf = new ArrayList<Leaf>();
/**
* ��϶��������
*/
private String name = "";
/**
* ���췽����������϶��������
* @param name ��϶��������
*/
public Composite(String name){
this.name = name;
}
/**
* ����϶�����뱻��������������϶���
* @param c ����������������϶���
*/
public void addComposite(Composite c){
this.childComposite.add(c);
}
/**
* ����϶�����뱻��������Ҷ�Ӷ���
* @param leaf ����������Ҷ�Ӷ���
*/
public void addLeaf(Leaf leaf){
this.childLeaf.add(leaf);
}
/**
* �����϶�������Ľṹ
* @param preStr ǰ����Ҫ�ǰ��ղ㼶ƴ�ӵĿո�ʵ���������
*/
public void printStruct(String preStr){
//�Ȱ��Լ����ȥ
System.out.println(preStr+"+"+this.name);
//Ȼ�����һ���ո�ʾ�������һ���ո�����Լ�������Ҷ�Ӷ���
preStr+=" ";
for(Leaf leaf : childLeaf){
leaf.printStruct(preStr);
}
//�����ǰ������Ӷ�����
for(Composite c : childComposite){
//�ݹ����ÿ���Ӷ���
c.printStruct(preStr);
}
}
}
|
/*
* Copyright 2013 JBoss Inc
*
* 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.overlord.rtgov.ui.client.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.jboss.errai.common.client.api.annotations.Portable;
import org.jboss.errai.databinding.client.api.Bindable;
/**
* Models the full details of a service.
*
* @author eric.wittmann@redhat.com
*/
@Portable
@Bindable
public class ServiceBean implements Serializable {
private static final long serialVersionUID = ServiceBean.class.hashCode();
private String serviceId;
private QName name;
private QName application;
private String serviceInterface;
private List<ReferenceSummaryBean> references = new ArrayList<ReferenceSummaryBean>();
private String serviceGraph = "...";
/**
* Constructor.
*/
public ServiceBean() {
}
/**
* @return the serviceId
*/
public String getServiceId() {
return serviceId;
}
/**
* @return the name
*/
public QName getName() {
return name;
}
/**
* @return the application
*/
public QName getApplication() {
return application;
}
/**
* @return the serviceInterface
*/
public String getServiceInterface() {
return serviceInterface;
}
/**
* @return the references
*/
public List<ReferenceSummaryBean> getReferences() {
return references;
}
/**
* @return the serviceGraph
*/
public String getServiceGraph() {
return serviceGraph;
}
/**
* @param references the references to set
*/
public void setReferences(List<ReferenceSummaryBean> references) {
this.references = references;
}
/**
* @param serviceId the serviceId to set
*/
public void setServiceId(String serviceId) {
this.serviceId = serviceId;
}
/**
* @param name the name to set
*/
public void setName(QName name) {
this.name = name;
}
/**
* @param application the application to set
*/
public void setApplication(QName application) {
this.application = application;
}
/**
* @param serviceInterface the serviceInterface to set
*/
public void setServiceInterface(String serviceInterface) {
this.serviceInterface = serviceInterface;
}
/**
* @param serviceGraph the serviceGraph to set
*/
public void setServiceGraph(String serviceGraph) {
this.serviceGraph = serviceGraph;
}
}
|
package de.jmda.gen.java;
import javax.validation.constraints.NotNull;
import de.jmda.gen.CompoundGenerator;
public interface MethodHeaderGenerator extends CompoundGenerator
{
MethodModifiersGenerator getModifiersGenerator();
@NotNull TypeNameGenerator getTypeNameGenerator();
@NotNull MethodDetailsGenerator getMethodDetailsGenerator();
/**
* @NotNull
* @return non null modifiers generator
*/
MethodModifiersGenerator demandModifiersGenerator();
void setModifiersGenerator(MethodModifiersGenerator generator);
void setTypeNameGenerator(@NotNull TypeNameGenerator generator);
void setMethodDetailsGenerator(@NotNull MethodDetailsGenerator generator);
}
|
package com.tencent.mm.pluginsdk.permission;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.support.v4.app.a;
class a$1 implements OnClickListener {
final /* synthetic */ Activity mr;
final /* synthetic */ int ms;
final /* synthetic */ String qBf;
a$1(Activity activity, String str, int i) {
this.mr = activity;
this.qBf = str;
this.ms = i;
}
public final void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
a.a(this.mr, new String[]{this.qBf}, this.ms);
}
}
|
package com.tencent.mm.plugin.record.b;
import com.tencent.mm.bt.h.d;
class n$3 implements d {
n$3() {
}
public final String[] xb() {
return com.tencent.mm.plugin.record.a.d.diD;
}
}
|
package SocialNetwork;
/*
* @author Tiago Guerreiro
* @author Bernardo Borda d'Agua
*/
public class PersonClass implements Person {
// VARIAVEIS
private String status,name,email;
private People friendList;
private Timeline timeline;
// CONSTRUTOR
public PersonClass(String name, String email, String status){
this.status = status;
this.email = email;
this.name = name;
friendList = new PeopleClass(People.FRIEND_LIST_SIZE);
timeline = new TimelineClass();
}
@Override
public void addFriend(Person friend){
friendList.add(friend);
}
@Override
public String getName(){
return name;
}
@Override
public String getStatus(){
return status;
}
@Override
public String getEmail(){
return email;
}
@Override
public void setStatus(String status){
this.status = status;
}
@Override
public boolean checkFriend(String name){
friendList.initializeIterator();
boolean found = false;
while(friendList.hasNext() && !found){
found = friendList.next().getName().equals(name);
}
return found;
}
@Override
public People getFriendList(){
return friendList;
}
public void addPost(String post, String author){
timeline.add(post,author);
}
public Timeline getTimeline(){
return timeline;
}
}
|
package net.minecraft.client.gui.chat;
import net.minecraft.util.text.ChatType;
import net.minecraft.util.text.ITextComponent;
public interface IChatListener {
void func_192576_a(ChatType paramChatType, ITextComponent paramITextComponent);
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\client\gui\chat\IChatListener.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
|
package com.tencent.mm.plugin.label.ui;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.tencent.mm.R;
import com.tencent.mm.ab.e;
import com.tencent.mm.ab.l;
import com.tencent.mm.model.au;
import com.tencent.mm.model.c;
import com.tencent.mm.plugin.report.service.h;
import com.tencent.mm.sdk.e.j;
import com.tencent.mm.sdk.e.m.b;
import com.tencent.mm.sdk.platformtools.ag;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.storage.ad;
import com.tencent.mm.ui.base.n.d;
import com.tencent.mm.ui.contact.s;
import com.tencent.mm.ui.widget.b.a;
import com.tencent.smtt.sdk.TbsReaderView$ReaderCallback;
import java.util.ArrayList;
import java.util.HashMap;
public class ContactLabelManagerUI extends ContactLabelBaseUI implements OnCreateContextMenuListener, OnItemClickListener, e, d {
private ListView CU;
private int OD;
private int hpr = 0;
private int hps = 0;
private a hql;
private View imD;
private b kBa = b.kBp;
private View kBb;
private View kBc;
private a kBd;
private ArrayList<ad> kBe = new ArrayList();
private HashMap<Integer, Integer> kBf = new HashMap();
private boolean kBg = true;
private OnClickListener kBh = new 6(this);
private j.a kBi = new 7(this);
private b kBj = new 8(this);
private ag mHandler = new ag() {
public final void handleMessage(Message message) {
x.d("MicroMsg.Label.ContactLabelManagerUI", "handleMessage:%d", new Object[]{Integer.valueOf(message.what)});
switch (message.what) {
case TbsReaderView$ReaderCallback.HIDDEN_BAR /*5001*/:
ContactLabelManagerUI.this.ge(false);
return;
case TbsReaderView$ReaderCallback.SHOW_BAR /*5002*/:
ContactLabelManagerUI.this.FE(ContactLabelManagerUI.this.getString(R.l.app_waiting));
return;
case TbsReaderView$ReaderCallback.COPY_SELECT_TEXT /*5003*/:
ContactLabelManagerUI.this.aYM();
return;
default:
return;
}
}
};
static /* synthetic */ void b(ContactLabelManagerUI contactLabelManagerUI) {
if (contactLabelManagerUI.kBe == null || contactLabelManagerUI.kBe.isEmpty()) {
h.mEJ.h(11347, new Object[]{Integer.valueOf(1), Integer.valueOf(0)});
} else {
h.mEJ.h(11347, new Object[]{Integer.valueOf(1), Integer.valueOf(1)});
}
x.i("MicroMsg.Label.ContactLabelManagerUI", "dz[dealAddLabel]");
Intent intent = new Intent();
intent.putExtra("list_attr", s.s(s.ukF, 1024));
intent.putExtra("list_type", 1);
intent.putExtra("titile", contactLabelManagerUI.getString(R.l.label_add_member));
intent.putExtra("show_too_many_member", false);
intent.putExtra("scene", 5);
com.tencent.mm.bg.d.b(contactLabelManagerUI, ".ui.contact.SelectContactUI", intent, 7001);
}
protected final int getLayoutId() {
return R.i.contact_label_manager_ui;
}
protected final void initView() {
this.OD = com.tencent.mm.bp.a.ad(this.mController.tml, R.f.NormalTextSize);
setMMTitle(getString(R.l.label_all_title));
addTextOptionMenu(0, getString(R.l.label_new_short), new 9(this));
setBackBtn(new OnMenuItemClickListener() {
public final boolean onMenuItemClick(MenuItem menuItem) {
ContactLabelManagerUI.this.finish();
return false;
}
});
this.kBd = new a(this);
this.imD = findViewById(R.h.label_main);
this.kBb = findViewById(R.h.label_empty);
this.kBc = findViewById(R.h.label_new_btn);
this.kBc.setOnClickListener(this.kBh);
this.CU = (ListView) findViewById(R.h.label_list);
this.hql = new a(this);
this.CU.setOnTouchListener(new 11(this));
this.CU.setOnItemLongClickListener(new 12(this));
this.CU.setAdapter(this.kBd);
this.CU.setOnItemClickListener(this);
}
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
initView();
au.Em().H(new 13(this));
com.tencent.mm.plugin.label.e.aYJ().c(this.kBi);
}
protected void onResume() {
au.DF().a(636, this);
au.HU();
c.FR().a(this.kBj);
ge(true);
super.onResume();
}
protected void onPause() {
au.DF().b(636, this);
au.HU();
c.FR().b(this.kBj);
super.onPause();
}
protected void onDestroy() {
com.tencent.mm.plugin.label.e.aYJ().d(this.kBi);
super.onDestroy();
}
public void onItemClick(AdapterView<?> adapterView, View view, int i, long j) {
if (this.kBd != null && i >= 0) {
ad rM = this.kBd.rM(i);
if (rM != null) {
String str = rM.field_labelID;
String str2 = rM.field_labelName;
Intent intent = new Intent();
intent.putExtra("label_id", str);
intent.putExtra("label_name", str2);
intent.setClass(this, ContactLabelEditUI.class);
startActivity(intent);
if (!bi.oW(str)) {
return;
}
if (this.kBe == null || this.kBe.isEmpty()) {
h.mEJ.h(11347, new Object[]{Integer.valueOf(1), Integer.valueOf(0)});
return;
}
h.mEJ.h(11347, new Object[]{Integer.valueOf(1), Integer.valueOf(1)});
}
}
}
public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenuInfo contextMenuInfo) {
int i = ((AdapterContextMenuInfo) contextMenuInfo).position;
if (this.kBd != null && i >= 0) {
ad rM = this.kBd.rM(i);
if (rM != null) {
contextMenu.setHeaderTitle(com.tencent.mm.pluginsdk.ui.d.j.a(view.getContext(), rM.field_labelName));
contextMenu.add(0, 0, 0, getString(R.l.app_delete));
contextMenu.add(0, 1, 1, getString(R.l.app_edit));
}
}
super.onCreateContextMenu(contextMenu, view, contextMenuInfo);
}
public void onMMMenuItemSelected(MenuItem menuItem, int i) {
int i2 = ((AdapterContextMenuInfo) menuItem.getMenuInfo()).position;
if (this.kBd != null && i2 >= 0) {
ad rM = this.kBd.rM(i2);
switch (i) {
case 0:
com.tencent.mm.ui.base.h.a(this, getString(R.l.label_delete_confirm), "", getString(R.l.app_delete), getString(R.l.app_cancel), new 2(this, rM), new 3(this));
return;
case 1:
Intent intent = new Intent();
intent.setClass(this, ContactLabelEditUI.class);
intent.putExtra("label_id", rM.field_labelID);
intent.putExtra("label_name", rM.field_labelName);
startActivity(intent);
return;
default:
return;
}
}
}
public final void a(int i, int i2, String str, l lVar) {
x.i("MicroMsg.Label.ContactLabelManagerUI", "cpan[onSceneEnd]errType:%d errCode:%d errMsg:%s", new Object[]{Integer.valueOf(i), Integer.valueOf(i2), str});
switch (lVar.getType()) {
case 636:
if (i == 0 && i2 == 0) {
FI(((com.tencent.mm.plugin.label.b.b) lVar).kAF);
return;
}
x.w("MicroMsg.Label.ContactLabelManagerUI", "cpan[onSceneEnd] delete fail.");
aYR();
return;
default:
x.w("MicroMsg.Label.ContactLabelManagerUI", "unknow type.");
return;
}
}
private synchronized void ge(boolean z) {
x.d("MicroMsg.Label.ContactLabelManagerUI", "loading%s", new Object[]{String.valueOf(z)});
if (z && this.mHandler != null) {
this.mHandler.sendEmptyMessageDelayed(TbsReaderView$ReaderCallback.SHOW_BAR, 400);
}
au.Em().H(new 4(this, z));
}
protected void onActivityResult(int i, int i2, Intent intent) {
x.i("MicroMsg.Label.ContactLabelManagerUI", "dz[onActivityResult] requestCode:%d resultCode:%d", new Object[]{Integer.valueOf(i), Integer.valueOf(i2)});
if (i2 == -1) {
switch (i) {
case 7001:
String stringExtra = intent.getStringExtra("Select_Contact");
x.i("MicroMsg.Label.ContactLabelManagerUI", "dz[onActivityResult] %s", new Object[]{stringExtra});
if (!bi.oW(stringExtra)) {
Intent intent2 = new Intent();
intent2.setClass(this, ContactLabelEditUI.class);
intent2.putExtra("Select_Contact", stringExtra);
startActivity(intent2);
break;
}
break;
}
super.onActivityResult(i, i2, intent);
}
}
private void FI(String str) {
if (com.tencent.mm.plugin.label.e.aYJ().jy(str)) {
aYM();
ge(false);
return;
}
x.w("MicroMsg.Label.ContactLabelManagerUI", "cpan[doDeleteContactLabel] fail.");
aYR();
}
private void aYR() {
aYM();
zK(getString(R.l.del_label_failed_msg));
}
}
|
package com.google.android.gms.wearable.internal;
import com.google.android.gms.common.api.k.b;
abstract class an$a<T> extends a {
private b<T> beS;
public an$a(b<T> bVar) {
this.beS = bVar;
}
public final void aq(T t) {
b bVar = this.beS;
if (bVar != null) {
bVar.ad(t);
this.beS = null;
}
}
}
|
package com.wisape.android.fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.facebook.drawee.view.SimpleDraweeView;
import com.freshdesk.mobihelp.Mobihelp;
import com.freshdesk.mobihelp.MobihelpConfig;
import com.wisape.android.R;
import com.wisape.android.util.FrescoFactory;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
/**
* @author Duke
*/
public class MainMenuFragment extends BaseFragment {
@InjectView(R.id.sdv_user_head_image)
SimpleDraweeView sdvUserHeadImage;
@InjectView(R.id.tv_name)
TextView tvName;
@InjectView(R.id.tv_mail)
TextView tvMail;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_menu, null, false);
ButterKnife.inject(this, rootView);
init();
return rootView;
}
private void init() {
FrescoFactory.bindImageFromUri(sdvUserHeadImage, "http://static.6yoo.com/yuyan/cms/d/qinsmoon/market/4ad/2015-06-03/b84729802bdc351165bda6f545ce9b93.jpg");
}
@Override
public void onDestroyView() {
super.onDestroyView();
ButterKnife.reset(this);
}
@OnClick(R.id.help_center)
public void onHelpCenterClick(View view){
String domain = getString(R.string.mobihelp_config_domain),
appId = getString(R.string.mobihelp_config_appId),
appSecret = getString(R.string.mobihelp_config_appSecret);
Mobihelp.init(getActivity(), new MobihelpConfig(domain,appId,appSecret));
//Mobihelp.clearUserData(getActivity());
Mobihelp.showSupport(getActivity());
}
}
|
package in.conceptarchitect.collections;
public interface ReturnableAction<I, O> extends Action<I> {
default O result() {
return null;
}
}
|
package page;
public class Shipping {
} // end class Shipping
|
package com.mes.old.meta;
// Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final
import java.util.Date;
/**
* BOperationLink generated by hbm2java
*/
public class BOperationLink implements java.io.Serializable {
private BOperationLinkId id;
private String operlinkuid;
private String notes;
private String creator;
private Date createtime;
private String changer;
private Date changetime;
private String changereason;
private String parentforopuid;
public BOperationLink() {
}
public BOperationLink(BOperationLinkId id, String operlinkuid) {
this.id = id;
this.operlinkuid = operlinkuid;
}
public BOperationLink(BOperationLinkId id, String operlinkuid, String notes, String creator, Date createtime,
String changer, Date changetime, String changereason, String parentforopuid) {
this.id = id;
this.operlinkuid = operlinkuid;
this.notes = notes;
this.creator = creator;
this.createtime = createtime;
this.changer = changer;
this.changetime = changetime;
this.changereason = changereason;
this.parentforopuid = parentforopuid;
}
public BOperationLinkId getId() {
return this.id;
}
public void setId(BOperationLinkId id) {
this.id = id;
}
public String getOperlinkuid() {
return this.operlinkuid;
}
public void setOperlinkuid(String operlinkuid) {
this.operlinkuid = operlinkuid;
}
public String getNotes() {
return this.notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public String getCreator() {
return this.creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public Date getCreatetime() {
return this.createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
public String getChanger() {
return this.changer;
}
public void setChanger(String changer) {
this.changer = changer;
}
public Date getChangetime() {
return this.changetime;
}
public void setChangetime(Date changetime) {
this.changetime = changetime;
}
public String getChangereason() {
return this.changereason;
}
public void setChangereason(String changereason) {
this.changereason = changereason;
}
public String getParentforopuid() {
return this.parentforopuid;
}
public void setParentforopuid(String parentforopuid) {
this.parentforopuid = parentforopuid;
}
}
|
package com.tencent.mm.ui;
import com.tencent.mm.sdk.platformtools.ah;
class aa$8 implements Runnable {
final /* synthetic */ aa toC;
aa$8(aa aaVar) {
this.toC = aaVar;
}
public final void run() {
this.toC.tox = true;
ah.M(this.toC.toy);
ah.A(this.toC.toy);
}
}
|
package BOJ;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
public class Q2108 {
static int n;
static int[] nums;
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out))) {
n = Integer.parseInt(br.readLine());
nums = new int[n];
for (int i = 0; i < n; i++)
nums[i] = Integer.parseInt(br.readLine());
Arrays.sort(nums);
bw.write(String.valueOf(getAvg()) + "\n");
bw.write(String.valueOf(getCenter()) + "\n");
bw.write(String.valueOf(getMode()) + "\n");
bw.write(String.valueOf(getRange()) + "\n");
} catch (Exception e) {
e.printStackTrace();
}
}
static int getRange() {
return nums[n - 1] - nums[0];
}
static int getMode() {
ArrayList<Integer> list = new ArrayList<Integer>();
int[] count = new int[8001];
int result = 0;
int max = 0;
for (int target : nums)
count[4000 + target]++;
for (int i = 0; i < 8001; i++) {
if (count[i] != 0 && max < count[i]) {
max = count[i];
list.clear();
list.add(i - 4000);
} else if (count[i] != 0 && max == count[i])
list.add(i - 4000);
}
if (list.size() == 1)
result = list.get(0);
else {
Collections.sort(list);
result = list.get(1);
}
return result;
}
static int getCenter() {
return n % 2 == 0 ? nums[n / 2 + 1] : nums[n / 2];
}
static int getAvg() {
double sum = 0;
for (int target : nums)
sum += target;
return (int) Math.round(sum / n);
}
}
|
package fr.gtm.proxibanque.modele;
import javax.persistence.Entity;
import javax.persistence.OneToOne;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
/**
* Classe du domaine metier: Gerant. Le gerant herite directement de la classe
* conseiller et par la classe conseiller de la classe personne. Le gerant
* dispose de deux attributs qui lui sont propres: l'agence dans laquelle il
* travaille et la liste de conseillers sous ses ordres.
*
* @author Xavier Deboudt, Thomas Duval, Romain Sadoine, Jean Mathorel
*
*/
@Component
@Scope(value = "prototype")
@Entity
public class Gerant extends Conseiller {
/**
* attribut de la classe gerant : une agence associe
*
*/
private static final long serialVersionUID = 1L;
@OneToOne(mappedBy = "gerant")
private Agence agence;
/**
*
* @param nom
* Le nom du gerant
* @param prenom
* Le prenom du gerant
* @param civilite
* Le sexe du client
* @param email
* L'adresse email du client
* @param agence
* L'agence du client
*/
public Gerant(String nom, String prenom, String civilite, String email, Agence agence) {
super(nom, prenom, civilite, email, agence);
super.getAuthentification().setRole("gerant");
}
/**
*
* @param agence
*/
public Gerant(Agence agence) {
super();
this.agence = agence;
}
/**
* constructeur par defaut
*/
public Gerant() {
super();
}
}
|
package net.lax1dude.cs50_final_project.client.renderer.opengl;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import org.lwjgl.system.MemoryUtil;
public class EaglTessellator {
public final ByteBuffer vertexBuffer;
public final ByteBuffer indexBuffer;
private final int bytesPerVertex;
private final int vertexLimit;
private int vertexId;
private boolean throwOnOverflow;
private boolean destroyed = false;
public EaglTessellator(int bytesPerVertex, int vertexLimit, int indexLimit) {
this.bytesPerVertex = bytesPerVertex;
this.vertexLimit = vertexLimit;
throwOnOverflow = false;
vertexBuffer = MemoryUtil.memAlloc(bytesPerVertex * vertexLimit).order(ByteOrder.nativeOrder());
indexBuffer = indexLimit > 0 ? MemoryUtil.memAlloc((vertexLimit > 65536) ? (4 * indexLimit) : (2 * indexLimit)).order(ByteOrder.nativeOrder()) : null;
}
public final EaglTessellator reset() {
vertexId = 0;
vertexBuffer.clear();
if(indexBuffer != null) indexBuffer.clear();
return this;
}
public final EaglTessellator throwOnOverflow(boolean yes) {
this.throwOnOverflow = yes;
return this;
}
private static final void throwOverflow() {
throw new ArrayIndexOutOfBoundsException("Tessellator vertex limit reached");
}
public final EaglTessellator put_float(float p1) {
if(vertexId < vertexLimit) {
vertexBuffer.putFloat(p1);
}else if(throwOnOverflow) {
throwOverflow();
}
return this;
}
public final EaglTessellator put_vec2f(float p1, float p2) {
if(vertexId < vertexLimit) {
vertexBuffer.putFloat(p1);
vertexBuffer.putFloat(p2);
}else if(throwOnOverflow) {
throwOverflow();
}
return this;
}
public final EaglTessellator put_vec3f(float p1, float p2, float p3) {
if(vertexId < vertexLimit) {
vertexBuffer.putFloat(p1);
vertexBuffer.putFloat(p2);
vertexBuffer.putFloat(p3);
}else if(throwOnOverflow) {
throwOverflow();
}
return this;
}
public final EaglTessellator put_vec4f(float p1, float p2, float p3, float p4) {
if(vertexId < vertexLimit) {
vertexBuffer.putFloat(p1);
vertexBuffer.putFloat(p2);
vertexBuffer.putFloat(p3);
vertexBuffer.putFloat(p4);
}else if(throwOnOverflow) {
throwOverflow();
}
return this;
}
public final EaglTessellator put_int(int p1) {
if(vertexId < vertexLimit) {
vertexBuffer.putInt(p1);
}else if(throwOnOverflow) {
throwOverflow();
}
return this;
}
public final EaglTessellator put_vec2i(int p1, int p2) {
if(vertexId < vertexLimit) {
vertexBuffer.putInt(p1);
vertexBuffer.putInt(p2);
}else if(throwOnOverflow) {
throwOverflow();
}
return this;
}
public final EaglTessellator put_vec3i(int p1, int p2, int p3) {
if(vertexId < vertexLimit) {
vertexBuffer.putInt(p1);
vertexBuffer.putInt(p2);
vertexBuffer.putInt(p3);
}else if(throwOnOverflow) {
throwOverflow();
}
return this;
}
public final EaglTessellator put_vec4i(int p1, int p2, int p3, int p4) {
if(vertexId < vertexLimit) {
vertexBuffer.putInt(p1);
vertexBuffer.putInt(p2);
vertexBuffer.putInt(p3);
vertexBuffer.putInt(p4);
}else if(throwOnOverflow) {
throwOverflow();
}
return this;
}
public final EaglTessellator put_vec2s(short p1, short p2) {
if(vertexId < vertexLimit) {
vertexBuffer.putShort(p1);
vertexBuffer.putShort(p2);
}else if(throwOnOverflow) {
throwOverflow();
}
return this;
}
// https://stackoverflow.com/questions/6162651/half-precision-floating-point-in-java
public static final int toHalfFloat(float fval) {
int fbits = Float.floatToIntBits(fval);
int sign = fbits >>> 16 & 0x8000; // sign only
int val = (fbits & 0x7fffffff) + 0x1000; // rounded value
if (val >= 0x47800000) // might be or become NaN/Inf
{ // avoid Inf due to rounding
if ((fbits & 0x7fffffff) >= 0x47800000) { // is or must become NaN/Inf
if (val < 0x7f800000) // was value but too large
return sign | 0x7c00; // make it +/-Inf
return sign | 0x7c00 | // remains +/-Inf or NaN
(fbits & 0x007fffff) >>> 13; // keep NaN (and Inf) bits
}
return sign | 0x7bff; // unrounded not quite Inf
}
if (val >= 0x38800000) // remains normalized value
return sign | val - 0x38000000 >>> 13; // exp - 127 + 15
if (val < 0x33000000) // too small for subnormal
return sign; // becomes +/-0
val = (fbits & 0x7fffffff) >>> 23; // tmp exp for subnormal calc
return sign | ((fbits & 0x7fffff | 0x800000) // add subnormal bit
+ (0x800000 >>> val - 102) // round depending on cut off
>>> 126 - val); // div by 2^(1-(exp-127+15)) and >> 13 | exp=0
}
public final EaglTessellator put_vec4s(short p1, short p2, short p3, short p4) {
if(vertexId < vertexLimit) {
vertexBuffer.putShort(p1);
vertexBuffer.putShort(p2);
vertexBuffer.putShort(p3);
vertexBuffer.putShort(p4);
}else if(throwOnOverflow) {
throwOverflow();
}
return this;
}
public final EaglTessellator put_vec2hf(float p1, float p2) {
if(vertexId < vertexLimit) {
vertexBuffer.putShort((short)toHalfFloat(p1));
vertexBuffer.putShort((short)toHalfFloat(p2));
}else if(throwOnOverflow) {
throwOverflow();
}
return this;
}
public final EaglTessellator put_vec4hf(float p1, float p2, float p3, float p4) {
if(vertexId < vertexLimit) {
vertexBuffer.putShort((short)toHalfFloat(p1));
vertexBuffer.putShort((short)toHalfFloat(p2));
vertexBuffer.putShort((short)toHalfFloat(p3));
vertexBuffer.putShort((short)toHalfFloat(p4));
}else if(throwOnOverflow) {
throwOverflow();
}
return this;
}
public final EaglTessellator put_vec4b(byte p1, byte p2, byte p3, byte p4) {
if(vertexId < vertexLimit) {
vertexBuffer.put(p1);
vertexBuffer.put(p2);
vertexBuffer.put(p3);
vertexBuffer.put(p4);
}else if(throwOnOverflow) {
throwOverflow();
}
return this;
}
public final int endVertex() {
if(vertexId < vertexLimit) {
vertexBuffer.position((vertexId + 1) * bytesPerVertex);
return vertexId++;
}else if(throwOnOverflow) {
throwOverflow();
}
return 0;
}
public final int vertexesRemaining() {
return vertexId - vertexLimit;
}
public final int indexesRemaining() {
if(vertexBuffer.capacity() > 65536) {
return indexBuffer.remaining() / 4;
}else {
return indexBuffer.remaining() / 2;
}
}
public final EaglTessellator addToIndex(int vertexId) {
if(indexBuffer == null) throw new IllegalStateException("this tessellator does not have an index buffer");
if(vertexBuffer.capacity() > 65536) {
if(indexBuffer.remaining() >= 4) {
indexBuffer.putInt(vertexId);
}else {
throw new ArrayIndexOutOfBoundsException("index buffer is full");
}
}else {
if(indexBuffer.remaining() >= 2) {
indexBuffer.putShort((short)vertexId);
}else {
throw new ArrayIndexOutOfBoundsException("index buffer is full");
}
}
return this;
}
public final EaglTessellator draw(EaglVertexArray array, int drawMode) {
EaglVertexBuffer b = array.buffers[0];
vertexBuffer.flip();
if(b.getBufferSize() < vertexBuffer.remaining()) {
b.upload(vertexBuffer, false);
}else {
b.uploadSub(0, vertexBuffer);
}
EaglIndexBuffer ib = array.indexBuffer;
if(indexBuffer != null && ib != null) {
indexBuffer.flip();
if(ib.getBufferSize() < indexBuffer.remaining()) {
ib.upload(indexBuffer, false);
}else {
ib.uploadSub(0, indexBuffer);
}
}
array.draw(drawMode, 0, vertexId);
reset();
return this;
}
public final EaglTessellator uploadVertexes(EaglVertexBuffer buf, boolean once) {
if(vertexBuffer.limit() == vertexBuffer.capacity()) {
vertexBuffer.flip();
}
buf.upload(vertexBuffer, once);
return this;
}
public final EaglTessellator uploadIndexes(EaglIndexBuffer buf, boolean once) {
if(indexBuffer != null) {
if(indexBuffer.limit() == indexBuffer.capacity()) {
indexBuffer.flip();
}
buf.upload(indexBuffer, once);
}
return this;
}
public void destroy() {
if(!destroyed) {
MemoryUtil.memFree(vertexBuffer);
if(indexBuffer != null) MemoryUtil.memFree(indexBuffer);
destroyed = true;
}
}
public void finalize() {
if(!destroyed) {
EaglContext.log.warn("Tessellator {} leaked memory", this.toString());
MemoryUtil.memFree(vertexBuffer);
if(indexBuffer != null) MemoryUtil.memFree(indexBuffer);
destroyed = true;
}
}
}
|
package www.movieapp;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import www.movieapp.Constant.Constant;
import www.movieapp.MovieDatabase.MovieContract;
import www.movieapp.adapter.MovieReviewAdapter;
import www.movieapp.adapter.MovieTrailerAdapter;
import www.movieapp.module.MovieDBJsonParse;
import www.movieapp.module.MovieReviewDB;
import www.movieapp.module.MovieTrailerDB;
import www.movieapp.utilities.NetworkUtils;
/**
* Created by amy on 11/5/2017.
*/
public class MovieDetailedView extends AppCompatActivity {
TextView textViewMovieTitle,textViewMovieRating,textViewMovieSynopsis,textViewMovieReleaseDate;
ImageView imageViewMoviePoster;
Context context;
String movieImagePath,movieTitle,movieSynopsis,movieRating,movieReleaseDate,movieID;
public static String apiKey = "?api_key=" + Constant.API_KEY;
MovieTrailerAdapter movieTrailerAdapter;
MovieReviewAdapter movieReviewAdapter;
List<MovieReviewDB> movieReviewsDBs;
List<MovieTrailerDB> movieTrailerDBs;
RecyclerView movieReview, movieTrailer;
Button buttonFav;
boolean FavMovie=false;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initObjects();
readMovieData();
loadMovieData();
checkFavMovie(movieID);
String ReviewsUrl =Constant.END_POINT+"movie/" + movieID + "/reviews" + apiKey;
String TrailerUrl = Constant.END_POINT+"movie/" + movieID + "/videos" + apiKey;
loadMovieTrailerData(TrailerUrl);
laodMovieReviewData(ReviewsUrl);
}
public void initObjects() {
setContentView(R.layout.activity_movie_details);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
context = this;
textViewMovieRating=(TextView)findViewById(R.id.text_view_rating);
textViewMovieReleaseDate=(TextView)findViewById(R.id.text_view_release_date);
textViewMovieTitle=(TextView)findViewById(R.id.text_view_title);
textViewMovieSynopsis=(TextView)findViewById(R.id.text_view_synopsis);
imageViewMoviePoster=(ImageView) findViewById(R.id.iv_poster);
movieTrailer=(RecyclerView)findViewById(R.id.rv_movie_trailers);
movieReview=(RecyclerView)findViewById(R.id.rv_reviews);
buttonFav=(Button)findViewById(R.id.fav_button);
LinearLayoutManager layoutManager = new LinearLayoutManager(context, LinearLayout.HORIZONTAL, false);
movieTrailer.setLayoutManager(layoutManager);
LinearLayoutManager layoutManager1 = new LinearLayoutManager(this);
movieReview.setLayoutManager(layoutManager1);
}
public void readMovieData()
{
Bundle bundle=getIntent().getExtras();
if(bundle!=null)
{
movieID=bundle.getString(Constant.MOVIE_ID);
movieTitle=bundle.getString(Constant.MOVIE_TITLE);
movieRating=bundle.getString(Constant.MOVIE_RATING);
movieImagePath=bundle.getString(Constant.MOVIE_IMAGE_POSTER);
movieSynopsis=bundle.getString(Constant.MOVIE_SYNOPSIS);
movieReleaseDate=bundle.getString(Constant.MOVIE_ReleaseDate);
}
else
{
}
}
public void loadMovieData() {
textViewMovieRating.setText(movieRating+"/10");
textViewMovieTitle.setText(movieTitle);
textViewMovieReleaseDate.setText(movieReleaseDate);
textViewMovieSynopsis.setText(movieSynopsis);
Picasso.with(context).load(Constant.POSTER_PATH + movieImagePath).into(imageViewMoviePoster);
}
public void loadMovieTrailerData(String movieTrailerUrl) {
URL url = NetworkUtils.buildUrl(movieTrailerUrl);
new RequestMovieTrailer().execute(url);
}
class RequestMovieTrailer extends AsyncTask<URL, Void, String> {
@Override
protected String doInBackground(URL... urls) {
String movieTrailerResponseData = null;
URL url = urls[0];
try {
movieTrailerResponseData = NetworkUtils.getResponseFromMovieDb(url);
} catch (IOException e) {
e.printStackTrace();
Log.d("ErrorInTrailer", e.getMessage());
}
return movieTrailerResponseData;
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
protected void onPostExecute(String movieResponseData) {
super.onPostExecute(movieResponseData);
if (movieResponseData != null) {
loadMovieTrailerAdapter(movieResponseData);
}
}
}
private void loadMovieTrailerAdapter(String movieResponsePosterData) {
movieTrailerDBs = MovieDBJsonParse.parseMovieTrailerStringToJson(movieResponsePosterData);
movieTrailerAdapter = new MovieTrailerAdapter(context, movieTrailerDBs);
movieTrailer.setAdapter(movieTrailerAdapter);
}
public void laodMovieReviewData(String movieReviewsUrl) {
URL url = NetworkUtils.buildUrl(movieReviewsUrl);
new RequestMovieReviewdata().execute(url);
}
class RequestMovieReviewdata extends AsyncTask<URL, Void, String> {
@Override
protected String doInBackground(URL... urls) {
String movieReviewsResponseData = null;
URL url = urls[0];
try {
movieReviewsResponseData = NetworkUtils.getResponseFromMovieDb(url);
} catch (IOException e) {
e.printStackTrace();
movieReviewsResponseData = e.getMessage();
}
return movieReviewsResponseData;
}
protected void onPostExecute(String movieResponsePosterData) {
super.onPostExecute(movieResponsePosterData);
Log.d("Data", movieResponsePosterData);
if (movieResponsePosterData != null) {
loadMovieReviewAdapter(movieResponsePosterData);
}
}
private void loadMovieReviewAdapter(String movieResponsePosterData) {
movieReviewsDBs = MovieDBJsonParse.parseMovieReviewStringToJson(movieResponsePosterData);
movieReviewAdapter = new MovieReviewAdapter(context, movieReviewsDBs);
movieReview.setAdapter(movieReviewAdapter);
}
}
private void checkFavMovie(String id) {
Uri uri = MovieContract.MovieEntry.CONTENT_URI;
final String[] projection = MovieContract.MovieEntry.MOVIE_COLUMNS;
Boolean check=false;
Cursor cursor=getContentResolver().query(uri,projection,"movie_id=?",new String[]{movieID},null);
if(cursor.moveToFirst())
{
check=true;
}
if (check) {
buttonFav.setBackground(getResources().getDrawable(R.drawable.ic_wished) );
FavMovie = true;
} else {
buttonFav.setBackground(getResources().getDrawable(R.drawable.ic_wish) );
FavMovie = false;
}
}
public void AddFavList(View view)
{
if (FavMovie) {
deleteFromFavList(movieID);
} else {
insertToFavList();
// Toast.makeText(context, "ID="+db.addMovie(movie), Toast.LENGTH_SHORT).show();
}
checkFavMovie(movieID);
}
private void insertToFavList() {
ContentValues contentValues = new ContentValues();
contentValues.put(MovieContract.MovieEntry.COLUMN_TITLE, movieTitle);
contentValues.put(MovieContract.MovieEntry.COLUMN_POSTER_PATH, movieImagePath);
contentValues.put(MovieContract.MovieEntry.COLUMN_SYNOPSIS, movieSynopsis);
contentValues.put(MovieContract.MovieEntry.COLUMN_RATING, movieRating);
contentValues.put(MovieContract.MovieEntry.COLUMN_RELEASE_DATE, movieReleaseDate);
contentValues.put(MovieContract.MovieEntry.COLUMN_MOVIE_ID, movieID);
Uri uri = getContentResolver().insert(MovieContract.MovieEntry.CONTENT_URI, contentValues);
Log.v("Inserting Error", uri.toString());
if (uri != null) {
Toast.makeText(getBaseContext(), uri.toString(), Toast.LENGTH_LONG).show();
}
}
private void deleteFromFavList(String movieId) {
Uri uri = MovieContract.MovieEntry.CONTENT_URI;
// uri = uri.buildUpon().appendPath(movieId).build();
int taskDeleted = getContentResolver().delete(uri, "movie_id=?",
new String[]{movieId});
Toast.makeText(getApplicationContext(),"Deleted="+taskDeleted,Toast.LENGTH_LONG).show();
Log.v("Deleting Error", String.valueOf(taskDeleted));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
finish();
return true;
}
}
|
package com.example.android.popmovies.ViewModels;
import android.app.Application;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MutableLiveData;
import android.os.AsyncTask;
import com.example.android.popmovies.RoomDatabase.FavoriteMovieDao;
import com.example.android.popmovies.RoomDatabase.FavoriteMovieEntry;
import com.example.android.popmovies.RoomDatabase.FavoriteMovieRoomDatabase;
import java.util.List;
public class FavoriteMovieRepository implements AsyncResult {
private final FavoriteMovieDao mFavoriteMovieDao;
private final LiveData<List<FavoriteMovieEntry>> mAllMoviesByPopularity;
private final LiveData<List<FavoriteMovieEntry>> mAllMoviesByHighestRated;
private final MutableLiveData<List<FavoriteMovieEntry>> mSearchResults = new MutableLiveData<>();
FavoriteMovieRepository(Application application) {
FavoriteMovieRoomDatabase db = FavoriteMovieRoomDatabase.getInstance(application);
mFavoriteMovieDao = db.favoriteMovieDao();
mAllMoviesByPopularity = mFavoriteMovieDao.loadAllMoviesByPopularity();
mAllMoviesByHighestRated = mFavoriteMovieDao.loadAllMoviesByUserRating();
}
public void insertFavoriteMovie(FavoriteMovieEntry newFavoriteEntry) {
new queryAsyncTask.insertFavoriteMovieAsyncTask(mFavoriteMovieDao).execute(newFavoriteEntry);
}
public void deleteFavoriteMovie(String name) {
new queryAsyncTask.deleteFavoriteMovieAsyncTask(mFavoriteMovieDao).execute(name);
}
public void findFavoriteMovie(String name) {
queryAsyncTask task = new queryAsyncTask(mFavoriteMovieDao);
task.delegate = this;
task.execute(name);
}
public LiveData<List<FavoriteMovieEntry>> getAllMoviesByPopularity() {
return mAllMoviesByPopularity;
}
public LiveData<List<FavoriteMovieEntry>> getAllMoviesByHighestRated() {
return mAllMoviesByHighestRated;
}
public MutableLiveData<List<FavoriteMovieEntry>> getSearchResults() {
return mSearchResults;
}
@Override
public void asyncFinished (List<FavoriteMovieEntry> results){
mSearchResults.setValue(results);
}
private static class queryAsyncTask extends
AsyncTask<String, Void, List<FavoriteMovieEntry>> {
private final FavoriteMovieDao asyncTaskDao;
private FavoriteMovieRepository delegate = null;
queryAsyncTask(FavoriteMovieDao dao) {
asyncTaskDao = dao;
}
@Override
protected List<FavoriteMovieEntry> doInBackground(final String... params) {
return asyncTaskDao.loadMovieById(params[0]);
}
@Override
protected void onPostExecute(List<FavoriteMovieEntry> result) {
delegate.asyncFinished(result);
}
private static class insertFavoriteMovieAsyncTask extends AsyncTask<FavoriteMovieEntry, Void, Void> {
private final FavoriteMovieDao asyncTaskDao;
insertFavoriteMovieAsyncTask(FavoriteMovieDao dao) {
asyncTaskDao = dao;
}
@Override
protected Void doInBackground(final FavoriteMovieEntry... params) {
asyncTaskDao.insertMovie(params[0]);
return null;
}
}
private static class deleteFavoriteMovieAsyncTask extends AsyncTask<String, Void, Void> {
private final FavoriteMovieDao asyncTaskDao;
deleteFavoriteMovieAsyncTask(FavoriteMovieDao dao) {
asyncTaskDao = dao;
}
@Override
protected Void doInBackground(final String... params) {
asyncTaskDao.deleteMovie(params[0]);
return null;
}
}
}
}
|
package com.example.camerates.myapplication;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.NumberPicker;
import android.widget.Toast;
public class AddEditNoteActivity extends AppCompatActivity {
EditText titleEditText;
EditText descriptionEditText;
NumberPicker periorityNumberPicker;
public static final String KEY_EXTRA_TITLE = "com.example.camerates.myapplication.note_title";
public static final String KEY_EXTRA_DESCRIPTION = "com.example.camerates.myapplication.note_description";
public static final String KEY_EXTRA_PERIORTY = "com.example.camerates.myapplication.note_periorty";
public static final String KEY_EXTRA_ID = "com.example.camerates.myapplication.note_id";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_note);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_close);
titleEditText = findViewById(R.id.edit_text_title);
descriptionEditText = findViewById(R.id.edit_text_descripion);
periorityNumberPicker = findViewById(R.id.number_picker_periorty);
periorityNumberPicker.setMinValue(1);
periorityNumberPicker.setMaxValue(10);
Intent intent = getIntent();
if (intent.hasExtra(KEY_EXTRA_ID)) {
setTitle("Edit Note");
titleEditText.setText(intent.getStringExtra(KEY_EXTRA_TITLE));
descriptionEditText.setText(intent.getStringExtra(KEY_EXTRA_DESCRIPTION));
periorityNumberPicker.setValue(intent.getIntExtra(KEY_EXTRA_PERIORTY, 1));
} else {
setTitle("Add Note");
}
}
private void saveNote() {
String title = titleEditText.getText().toString();
String description = descriptionEditText.getText().toString();
int periorty = periorityNumberPicker.getValue();
if (title.trim().isEmpty() || description.trim().isEmpty()) {
Toast.makeText(this, "Please insert note title and description", Toast.LENGTH_SHORT).show();
return;
} else {
Intent data = new Intent();
data.putExtra(KEY_EXTRA_TITLE, title);
data.putExtra(KEY_EXTRA_DESCRIPTION, description);
data.putExtra(KEY_EXTRA_PERIORTY, periorty);
int id = getIntent().getIntExtra(KEY_EXTRA_ID, -1);
if (id != -1) {
data.putExtra(KEY_EXTRA_ID, id);
}
setResult(RESULT_OK, data);
finish();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.add_note_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.save_note:
saveNote();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
|
package com.wllfengshu.mysql.execute;
import com.wllfengshu.mysql.exception.CustomException;
import com.wllfengshu.mysql.model.dto.ExecutePlanDTO;
import com.wllfengshu.mysql.model.entity.ResultSet;
import com.wllfengshu.mysql.storage.StorageEngine;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
/**
* 执行器
*
* 作用:
* 1、选择存储引擎
* 2、操作存储引擎(CURD)
*/
@Slf4j
@Configuration
@RequiredArgsConstructor
public class Executor {
@NonNull
private ExecuteHandler executeHandler;
public ResultSet start(ExecutePlanDTO executePlanDTO) throws CustomException {
StorageEngine storageEngine = executeHandler.chooseStorage(executePlanDTO);
return executeHandler.execute(executePlanDTO, storageEngine);
}
}
|
package spring.learning.es.service;
import java.io.IOException;
import java.util.List;
import javax.annotation.PostConstruct;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import spring.learning.es.helper.ElasticsearchIndices;
import spring.learning.es.helper.Utils;
@Service
@Slf4j
@RequiredArgsConstructor
public class IndexService {
private final List<String> INDICES_TO_CREATE =
List.of(ElasticsearchIndices.PRODUCT_INDEX);
private final RestHighLevelClient client;
@Value("${es.indices-mappings-path}")
private String ES_INDICES_MAPPINGS_PATH;
@Value("${es.indices-mappings-extension}")
private String ES_INDICES_MAPPINGS_EXTENSION;
@Value("${es.indices-settings-path}")
private String ES_INDICES_SETTINGS_PATH;
@PostConstruct
public void tryToCreateIndecies() {
recreateIndices(false);
}
public void recreateIndices(boolean deleteExisting) {
String settings = loadSettings();
for (String indexName : INDICES_TO_CREATE) {
try {
boolean indexExists = client
.indices()
.exists(new GetIndexRequest(indexName),
RequestOptions.DEFAULT);
if (indexExists) {
if (!deleteExisting)
continue;
client.indices().delete(
new DeleteIndexRequest(indexName),
RequestOptions.DEFAULT);
}
final String mappings = loadMappins(indexName);
if (settings == null || mappings == null) {
log.error("Failed to create index with name '{}'",
indexName);
continue;
}
// be careful, since elastic 7.x,
// use org.elasticsearch.client.indices.CreateIndexRequest
// not the one from ...admin.action...
// otherwise, weird errors may occur with no indication of why!
final CreateIndexRequest createIndexRequest =
new CreateIndexRequest(indexName);
createIndexRequest.settings(settings, XContentType.JSON);
createIndexRequest.mapping(mappings, XContentType.JSON);
client.indices().create(createIndexRequest,
RequestOptions.DEFAULT);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
private String loadSettings() {
String settings = Utils.loadAsString(ES_INDICES_SETTINGS_PATH);
if (settings == null) {
log.error("Failed to load ES settings");
return null;
}
return settings;
}
private String loadMappins(String indexName) {
String mappings = Utils.loadAsString(
ES_INDICES_MAPPINGS_PATH
+ indexName
+ ES_INDICES_MAPPINGS_EXTENSION);
if (mappings == null) {
log.error("Failed to load mappings for index with name '{}'",
indexName);
return null;
}
return mappings;
}
}
|
/**
* @author Javier Medina Quero && Mª Dolores Ruiz Lozano
* Code generated GNU GENERAL PUBLIC LICENSE
*/
package MessageBt;
import java.io.IOException;
import javax.bluetooth.*;
import java.util.*;
//Clase que explorar el ambiente para encontrar dispositivos Bt
// que sean capaces de recibir mensajes.
public class ExplorerReceiverMessageBt implements Runnable{
public ExplorerReceiverMessageBt(){
(new Thread(this)).start();
}
//Lanza la hebra
boolean configured=false;
Object lock=new Object();
public void run(){
synchronized(lock){
this.explorer();
configured=true;
lock.notifyAll();
}
}
//Exclusion Mutua
private void waitConfigured(){
synchronized(lock){
try {
if (!configured) {
lock.wait();
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
/**
* @return Nombre de los receptores de mensajes bt
*/
public String [] getRemoteNames(){
waitConfigured();
String [] ret=new String [services.devices.size()];
int i=0;
for(Enumeration devicesE = services.devices.elements();devicesE.hasMoreElements();i++){
ServiceRecord deviceR = (ServiceRecord)(devicesE.nextElement());
try {
ret[i] = deviceR.getHostDevice().getFriendlyName(true);
} catch (IOException ex) {
ret[i] ="unknown";
ex.printStackTrace();
}
}
return ret;
}
/**
* @return Estructuras para enviarle un mensaje facilemente
*/
public SenderMessageBt [] getRemoteClient(){
waitConfigured();
System.out.println("Return clients # "+services.devices.size());
SenderMessageBt [] ret=new SenderMessageBt [services.devices.size()];
int i=0;
for(Enumeration devicesE = services.devices.elements();devicesE.hasMoreElements();i++){
ServiceRecord deviceR = (ServiceRecord)(devicesE.nextElement());
ret[i] = new SenderMessageBt(deviceR.getConnectionURL(0, false));
}
return ret;
}
/**
* @param pos un determinado cliente
* @return Estructura para enviarle un mensaje facilemente
*/
public SenderMessageBt getRemoteClient(int pos){
waitConfigured();
SenderMessageBt [] ret=new SenderMessageBt [services.devices.size()];
int i=0;
for(Enumeration devicesE = services.devices.elements();devicesE.hasMoreElements()&&i<=pos;i++){
if(i==pos){
ServiceRecord deviceR = (ServiceRecord)(devicesE.nextElement());
return new SenderMessageBt(deviceR.getConnectionURL(0, false));
}
}
return null;
}
SearcherDeviceMessageServerBt devices;
SearcherServiceMessageServerBt services;
// Exploramos y buscamos las propiedades de los receptores de mensajes
private void explorer(){
try{
DiscoveryAgent agent=myLocalDevice.getLocalDevice().getDiscoveryAgent();
System.out.println("Exploring devices...");
devices = new SearcherDeviceMessageServerBt();
synchronized(devices){
agent.startInquiry(ReceiverMessageBt.type, devices);
try {devices.wait(); } catch(InterruptedException e){System.out.println(e.toString());}
}
System.out.println("Finded devices : #"+devices.cached_devices.size());
services = new SearcherServiceMessageServerBt();
UUID[] u = new UUID[]{new UUID( ReceiverMessageBt.UUID, false )};
int attrbs[] = { 0x0100 };
for(Enumeration devicesE= devices.cached_devices.elements();devicesE.hasMoreElements();){
RemoteDevice deviceR = (RemoteDevice)(devicesE.nextElement());
System.out.println("#");
synchronized(services) {
// out.println("\n"+"Buscando Servicio en Device "+device.getBluetoothAddress());
agent.searchServices(attrbs, u, deviceR, services);
try {services.wait();} catch(InterruptedException e){System.out.println("\n"+e.toString());}
}//syncronizes
}//for
}catch(Exception ex){
ex.printStackTrace();
}
}//explorer
//Buscador de dispositivos
static class SearcherDeviceMessageServerBt implements DiscoveryListener {
public Vector cached_devices;
public SearcherDeviceMessageServerBt() {
cached_devices = new Vector();
}
public void deviceDiscovered( RemoteDevice btDevice, DeviceClass cod ) {
System.out.println("Descovered Device"+btDevice);
int major = cod.getMajorDeviceClass();
if( ! cached_devices.contains( btDevice ) )
cached_devices.addElement( btDevice );
}
public void inquiryCompleted( int discType ) {
System.out.println("Inquiry complete");
synchronized(this){ this.notify(); }
}
public void servicesDiscovered( int transID, ServiceRecord[] servRecord ) {}
public void serviceSearchCompleted( int transID, int respCode ) {}
}
//Buscador de propiedades del receptor de mensajes
static class SearcherServiceMessageServerBt implements DiscoveryListener {
public Vector devices;
public SearcherServiceMessageServerBt(){
devices=new Vector();
}
public void servicesDiscovered( int transID, ServiceRecord[] servRecord ) {
devices.addElement(servRecord[0]);
System.out.println("We found Service #"+servRecord[0]);
}
public void serviceSearchCompleted( int transID, int respCode ) {
synchronized( this ){ this.notify();}
}
public void deviceDiscovered( RemoteDevice btDevice, DeviceClass cod ){}
public void inquiryCompleted( int discType ){}
}
}
|
package de.jmda.app.cgol.xy.fx.cdi;
import de.jmda.fx.cdi.FXView;
public class MainView extends FXView
{
@Override public MainViewController getController()
{
return (MainViewController) super.getController();
}
public MainViewService getService() { return getController(); }
}
|
package com.appc.report.controller;
import basic.common.core.exception.BaseException;
import basic.common.core.utils.NameUtils;
import com.alibaba.druid.pool.DruidDataSource;
import com.appc.framework.mybatis.executor.criteria.Criteria;
import com.appc.framework.mybatis.executor.criteria.EntityCriteria;
import com.appc.framework.mybatis.route.DBContextHolder;
import com.appc.report.common.enums.CollectionType;
import com.appc.report.common.enums.DataSourseType;
import com.appc.report.common.enums.EncodingType;
import com.appc.report.common.enums.FillterType;
import com.appc.report.common.helper.JdbcUrlHelper;
import com.appc.report.dto.PageDto;
import com.appc.report.model.DataCollection;
import com.appc.report.model.DataSource;
import com.appc.report.service.DataCollectionService;
import com.appc.report.service.DataSourceService;
import com.appc.report.service.DynamicDataSourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
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.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Controller
@RequestMapping("/data")
public class DataController {
@Autowired
private DataSourceService dataSourceService;
@Autowired
private DataCollectionService dataCollectionService;
@Autowired
private List<DruidDataSource> dataSources;
@Autowired
private DynamicDataSourceService dynamicDataSourceService;
@RequestMapping(value = "source", method = RequestMethod.GET)
public ModelAndView source(@RequestParam(required = false) Long id) {
ModelAndView mv = new ModelAndView("data/data-source");
if (id != null) mv.addObject("source", dataSourceService.getById(id));
mv.addObject("dataSourseTypes", DataSourseType.values());
mv.addObject("encodingTypes", EncodingType.values());
return mv;
}
@RequestMapping(value = "testDataSource", method = RequestMethod.POST)
@ResponseBody
public boolean testDataSource(DataSource dataSource) {
if (!checkDataSource(dataSource)) {
return false;
} else {
try {
JdbcUrlHelper jdbcUrlHelper = DataSourseType.getTypeByCode(dataSource.getSourceType()).getJdbcUrlHelper();
Class.forName(DataSourseType.getTypeByCode(dataSource.getSourceType()).getJdbcDriver());
DriverManager.getConnection(jdbcUrlHelper.toJdbcUrl(dataSource), dataSource.getDataUsername(), dataSource.getDataPassword());
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
@RequestMapping(value = "importLocalDataSource", method = RequestMethod.GET)
@ResponseBody
public void importLocalDataSource() {
List<DataSource> dataSourceList = new ArrayList<>();
for (DruidDataSource druidDataSource : dataSources) {
DataSource dataSource = new DataSource();
dataSource.setDataUsername(druidDataSource.getUsername());
dataSource.setDataPassword(druidDataSource.getPassword());
try {
Connection connection = druidDataSource.getConnection();
String sourceType = connection.getMetaData().getDatabaseProductName();
DataSourseType dbType = DataSourseType.getTypeByCode(sourceType);
dataSource.setSourceType(sourceType);
assert dbType != null;
dbType.getJdbcUrlHelper().loadUrl(druidDataSource.getUrl(), dataSource);
dataSource.setSourceName("当前数据源");
dataSource.setCreateTime(new Date());
druidDataSource.discardConnection(connection);
druidDataSource.removeAbandoned();
if (!checkDataSource(dataSource)) {
continue;
}
dataSourceList.add(dataSource);
} catch (Exception e) {
e.printStackTrace();
}
}
if (!CollectionUtils.isEmpty(dataSourceList)) dataSourceService.insertBatch(dataSourceList);
}
private boolean checkDataSource(DataSource dataSource) {
if (StringUtils.isEmpty(dataSource.getSourceType())) {
if (dataSourceService.getEntityCount(EntityCriteria.build().eq("parent_id", dataSource.getSourceIp())) > 0) {
}
} else {
}
DataSource queryDataSource = dataSourceService.getEntity(EntityCriteria.build()
.eq("source_type", dataSource.getSourceType())
.eq("source_ip", dataSource.getSourceIp())
.eq("source_port", dataSource.getSourcePort())
.eq("data_name", dataSource.getDataName())
.eq("data_username", dataSource.getDataUsername())
.eq("data_password", dataSource.getDataPassword()));
return queryDataSource == null || queryDataSource.getSourceId().equals(dataSource.getSourceId());
}
@RequestMapping(value = "source", method = RequestMethod.DELETE)
@ResponseBody
public void sourceDelete(@RequestParam Long... ids) {
for (Long id : ids) {
dataSourceService.deleteById(id);
}
}
@RequestMapping(value = "source", method = RequestMethod.POST)
public ModelAndView sourcePost(DataSource dataSource) {
ModelAndView mv = new ModelAndView("data/data-source");
if (dataSource.getSourceId() != null) {
dataSourceService.updateById(dataSource);
} else {
dataSource.setCreateTime(new Date());
dataSourceService.insert(dataSource);
}
mv.addObject("success", true);
return mv;
}
@RequestMapping(value = "source-list", method = RequestMethod.GET)
public ModelAndView sourceList() {
ModelAndView mv = new ModelAndView("data/data-source-list");
mv.addObject("dataSourseTypes", DataSourseType.values());
return mv;
}
@RequestMapping(value = "querySource", method = RequestMethod.GET)
@ResponseBody
public PageDto querySource(@RequestParam int page,
@RequestParam int limit,
@RequestParam(required = false) String sourceName,
@RequestParam(required = false) String sourceType,
@RequestParam(required = false) String sort,
@RequestParam(required = false) String order) {
Sort sortObj = null;
if (!StringUtils.isEmpty(order)) {
if (!StringUtils.isEmpty(sort)) {
sort = NameUtils.toUnderlineName(sort);
}
sortObj = new Sort(new Sort.Order(Sort.Direction.fromString(order), sort));
}
Pageable pageable = new PageRequest(page - 1, limit, sortObj);
Criteria criteria = EntityCriteria.build();
if (!StringUtils.isEmpty(sourceName)) {
criteria.like("source_name", sourceName);
}
if (!StringUtils.isEmpty(sourceType)) {
criteria.eq("source_type", sourceType);
}
Page<DataSource> rules = dataSourceService.getEntityListForPage(criteria, pageable);
return PageDto.create(rules.getTotalElements(), rules.getContent());
}
@RequestMapping(value = "collection-list", method = RequestMethod.GET)
public ModelAndView regionList() {
ModelAndView mv = new ModelAndView("data/data-collection-list");
mv.addObject("fillterTypes", FillterType.values());
return mv;
}
@RequestMapping(value = "queryCollection", method = RequestMethod.POST)
@ResponseBody
public List<DataCollection> queryCollection(@RequestParam(required = false) Integer id) {
if (id == null) {
return dataCollectionService.getEntityList(EntityCriteria.build().isNull("parent_id"));
} else {
return dataCollectionService.getEntityList(EntityCriteria.build().eq("parent_id", id));
}
}
@RequestMapping(value = "collection", method = RequestMethod.GET)
public ModelAndView region(@RequestParam(required = false) Long id, @RequestParam(required = false) Long parentId) {
ModelAndView mv = new ModelAndView("data/data-collection");
mv.addObject("collectionTypes", CollectionType.values());
mv.addObject("dataSources", dataSourceService.getEntityList());
DataCollection collection = dataCollectionService.getById(id);
if (collection != null) {
mv.addObject("collection", collection);
mv.addObject("parentCollection", dataCollectionService.getById(collection.getParentId()));
} else {
mv.addObject("parentCollection", dataCollectionService.getById(parentId));
}
return mv;
}
@RequestMapping(value = "collection", method = RequestMethod.POST)
public ModelAndView regionPost(DataCollection collection) {
ModelAndView mv = new ModelAndView("data/data-collection");
if ("sql".equals(collection.getCollectionType()) && !checkSql(collection)) {
throw new BaseException("020006");
}
dataCollectionService.save(collection);
mv.addObject("success", true);
mv.addObject("collectionId", collection.getParentId());
return mv;
}
@RequestMapping(value = "collection", method = RequestMethod.DELETE)
@ResponseBody
public void regionDelete(@RequestParam Long id) {
if (dataCollectionService.getEntityCount(EntityCriteria.build().eq("parent_id", id)) > 0) {
throw new BaseException("020005");
} else {
dataCollectionService.deleteById(id);
}
}
@RequestMapping(value = "getCollections", method = RequestMethod.GET)
@ResponseBody
public List getCollections(@RequestParam Long id, @RequestParam(required = false, defaultValue = "") String type) {
CollectionType collectionType = CollectionType.getTypeByCode(type);
if (CollectionType.TABLE.equals(collectionType) || CollectionType.VIEW.equals(collectionType)) {
dynamicDataSourceService.putDataSource(id);
try {
DruidDataSource dataSource = (DruidDataSource) DBContextHolder.getDataSource();
Connection connection = dataSource.getConnection();
List columns = dynamicDataSourceService.loadDBTable(connection, type);
dataSource.discardConnection(connection);
dataSource.removeAbandoned();
return columns;
} catch (Exception e) {
e.printStackTrace();
return null;
}
} else {
return null;
}
}
@RequestMapping(value = "getCollectionData", method = {RequestMethod.GET, RequestMethod.POST})
@ResponseBody
public PageDto getCollectionData(@RequestParam Integer id, @RequestParam int page,
@RequestParam int limit,
@RequestParam(required = false) String sort,
@RequestParam(required = false) String order,
@RequestParam(required = false) String columnName,
@RequestParam(required = false) Integer fillterType,
@RequestParam(required = false) String queryValue,
@RequestParam(required = false) String queryValue2) {
Sort sortObj = null;
if (!StringUtils.isEmpty(order)) {
sortObj = new Sort(new Sort.Order(Sort.Direction.fromString(order), sort));
}
Criteria criteria = EntityCriteria.build();
if (!StringUtils.isEmpty(columnName) && fillterType != null) {
FillterType type = FillterType.getTypeByCode(fillterType);
if (type != null) {
type.buildCriteria(criteria, columnName, StringUtils.isEmpty(queryValue2) ? queryValue : new String[]{queryValue, queryValue2});
}
}
DataCollection dataCollection = dataCollectionService.getById(id);
dynamicDataSourceService.putDataSource(dataCollection.getSourceId());
Pageable pageable = new PageRequest(page - 1, limit, sortObj);
Page result = dynamicDataSourceService.getCollectionData(dataCollection, criteria, pageable);
return PageDto.create(result.getTotalElements(), result.getContent());
}
@RequestMapping(value = "getCollectionStructure", method = RequestMethod.GET)
@ResponseBody
public List getCollectionStructure(@RequestParam Integer id) {
DataCollection dataCollection = dataCollectionService.getById(id);
dynamicDataSourceService.putDataSource(dataCollection.getSourceId());
try {
DruidDataSource dataSource = (DruidDataSource) DBContextHolder.getDataSource();
Connection connection = dataSource.getConnection();
List columns = null;
if ("sql".equals(dataCollection.getCollectionType())) {
columns = dynamicDataSourceService.loadSqlColumn(connection, dataCollection.getCollectionValue());
} else {
columns = dynamicDataSourceService.loadDBColumn(connection, dataCollection.getCollectionValue());
}
dataSource.discardConnection(connection);
dataSource.removeAbandoned();
return columns;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
private Boolean checkSql(DataCollection dataCollection) {
dynamicDataSourceService.putDataSource(dataCollection.getSourceId());
try {
DruidDataSource dataSource = (DruidDataSource) DBContextHolder.getDataSource();
Connection connection = dataSource.getConnection();
List columns = dynamicDataSourceService.loadSqlColumn(connection, dataCollection.getCollectionValue());
dataSource.discardConnection(connection);
dataSource.removeAbandoned();
DBContextHolder.putDataSource("local");
return !columns.isEmpty();
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
}
|
package com.ojas.rpo.security.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class CandidateStatusCounts {
private String statuscount;
private String bdmReqStatus;
public String getBdmReqStatus() {
return bdmReqStatus;
}
public void setBdmReqStatus(String bdmReqStatus) {
this.bdmReqStatus = bdmReqStatus;
}
private String candidateStatus;
private String recruitername;
private String id;
private String nameOfRequirement;
private String clientname;
public String getClientname() {
return clientname;
}
public void setClientname(String clientname) {
this.clientname = clientname;
}
public String getStatuscount() {
return statuscount;
}
public void setStatuscount(String statuscount) {
this.statuscount = statuscount;
}
public String getCandidateStatus() {
return candidateStatus;
}
public void setCandidateStatus(String candidateStatus) {
this.candidateStatus = candidateStatus;
}
public String getRecruitername() {
return recruitername;
}
public void setRecruitername(String recruitername) {
this.recruitername = recruitername;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getNameOfRequirement() {
return nameOfRequirement;
}
public void setNameOfRequirement(String nameOfRequirement) {
this.nameOfRequirement = nameOfRequirement;
}
}
|
package trotro.tv.trotrotv.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;
import trotro.tv.trotrotv.R;
import trotro.tv.trotrotv.model.Vehicle;
/**
* Created by michael.dugah on 3/15/2018.
*/
public class VehicleListAdapter extends ArrayAdapter<Vehicle> {
private final List<Vehicle> values;
private final Context context;
public VehicleListAdapter(Context context, List<Vehicle> values) {
super(context, -1, values);
this.context = context;
this.values = values;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.list_stations, parent, false);
Button button = (Button) rowView.findViewById(R.id.button);
button.setText(values.get(position).getVehicle());
return rowView;
}
private String dateFormat(String date) {
SimpleDateFormat sdf = new SimpleDateFormat("EEEEEE dd-MMM-yyyy", Locale.getDefault());
try {
return sdf.format(Date.valueOf(date));
} catch (Exception ex) {
return date;
}
}
}
|
package com.jp.mood.controller;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.jp.commom.result.ResultHandle;
import com.jp.commom.util.DateUtil;
import com.jp.commom.util.UUidUtil;
import com.jp.mood.biz.MoodBiz;
import com.jp.mood.po.MoodPo;
@Controller
public class MoodController {
@Resource
private MoodBiz biz;
@RequestMapping(value="/addMoodPo.do")
public @ResponseBody ResultHandle addMoodPo(MoodPo po){
ResultHandle result=new ResultHandle();
po.setCreateTime(DateUtil.getTimeMiao());
if(po.getMood_id()==null||"".equals(po.getMood_id())){
po.setMood_id(UUidUtil.getUUid());
}
try{
int num=biz.addMoodPo(po);
if(num>0){
result.setCode("0");
result.setMessage("新增成功!");
}else{
result.setCode("1");
result.setMessage("新增失败!");
}
}catch (Exception e){
e.printStackTrace();
result.setCode("1");
result.setMessage("新增失败!");
}
return result;
}
@RequestMapping(value="/deleteMoodById.do")
public @ResponseBody ResultHandle deleteMoodById(MoodPo po){
ResultHandle result=new ResultHandle();
try{
int num=biz.deleteMoodById(po);
if(num>0){
result.setCode("0");
result.setMessage("删除成功!");
}else{
result.setCode("1");
result.setMessage("删除失败!");
}
}catch (Exception e){
result.setCode("1");
result.setMessage("删除失败!");
}
return result;
}
@RequestMapping(value="/updateMoodById.do")
public @ResponseBody ResultHandle updateMoodById(MoodPo po){
ResultHandle result=new ResultHandle();
try{
int num=biz.updateMoodById(po);
if(num>0){
result.setCode("0");
result.setMessage("更新成功!");
}else{
result.setCode("1");
result.setMessage("更新失败!");
}
}catch (Exception e){
result.setCode("1");
result.setMessage("更新失败!");
}
return result;
}
@RequestMapping(value="/getMoodList.do")
public @ResponseBody List<MoodPo> getList(MoodPo po){
List<MoodPo> list=null;
try{
System.out.println(biz.getCount(po));
list=biz.getList(po);
}catch (Exception e){
e.printStackTrace();
}
return list;
}
}
|
package br.com.ecommerce.pages.retaguarda.cadastros.produtos;
import static br.com.ecommerce.config.DriverFactory.getDriver;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import br.com.ecommerce.config.BasePage;
import br.com.ecommerce.util.Log;
import br.com.ecommerce.util.Utils;
public class PageAdicionarUnidadeProduto extends BasePage {
public PageAdicionarUnidadeProduto() {
PageFactory.initElements(getDriver(), this);
}
@FindBy(xpath = "//h1")
private WebElement titleAdicionarUnidade;
@FindBy(xpath = "//label[text()='Código:']")
private WebElement labelCodigo;
@FindBy(xpath = "//label[text()='Cor:']")
private WebElement labelCor;
@FindBy(xpath = "//label[text()='Tamanho:']")
private WebElement labelTamanho;
@FindBy(id = "product_unit_color_id")
private WebElement comboCor;
@FindBy(id = "product_unit_size_id")
private WebElement comboTamanho;
@FindBy(id = "product_unit_code")
private WebElement inputCodigo;
@FindBy(name = "commit")
private WebElement btSalvar;
@FindBy(xpath = "//a[text()='Cancelar']")
private WebElement btCancelar;
@FindBy(xpath = "//*[@id='main-content']/section/div[2]['×']")
private WebElement msgSucesso;
public void adicionarUnidadeAoProduto(String codigo, String cor, String tamanho){
aguardarElementoVisivel(btSalvar);
Log.info("Adicionando unidade ao produto...");
preencherCampo(inputCodigo, codigo);
selecionarValorComboTexto(comboCor, cor);
selecionarValorComboTexto(comboTamanho, tamanho);
click(btSalvar);
validaMsgInclusao();
}
public String getCorDisponivel(){
List<WebElement> listaDeCores = getAllElementosCombo(comboCor);
String indiceCor = Utils.geraNumeroEntre(1, listaDeCores.size());
return getTextElement(getDriver().findElement(By.xpath(" //*[@id='product_unit_color_id']/option["+indiceCor+"]")));
}
public String getTamanhoDisponivel(){
List<WebElement> listaDeTamanhos = getAllElementosCombo(comboTamanho);
String indiceTamanho = Utils.geraNumeroEntre(1, listaDeTamanhos.size());
return getTextElement(getDriver().findElement(By.xpath(" //*[@id='product_unit_size_id']/option["+indiceTamanho+"]")));
}
public void validaMsgInclusao(){
Log.info("Validando mensagem de feedback de inclusão...");
aguardarElementoVisivel(msgSucesso);
Utils.assertEquals(getTextElement(msgSucesso).replace("×", "").trim(), "Registro criado com Sucesso!");
Log.info("Mensagem de feedback validada.");
}
public void verificarOrtografiaPageAdicionarUnidadeProduto(){
Log.info("Verificando ortografia da página de unidade de produtos...");
Utils.assertEquals(getTextElement(titleAdicionarUnidade), "Adicionar Unidade de Produto");
Utils.assertEquals(getTextElement(labelCodigo) , "Código:");
Utils.assertEquals(getTextElement(labelCor) , "Cor:");
Utils.assertEquals(getTextElement(labelTamanho) , "Tamanho:");
Utils.assertEquals(getTextElement(btCancelar) , "Cancelar");
Utils.assertEquals(getTextValueAtributo(btSalvar) , "Salvar");
Log.info("Ortografia validada com sucesso.");
}
}
|
package com.company.item.repository.constants;
public interface ItemConstants {
String SCHEMA = "public";
String TABLE = "item";
String SCHEMA_TABLE = SCHEMA + "." + TABLE;
String PREFIX = TABLE + "_";
String SKU = PREFIX + "sku";
String NAME = PREFIX + "name";
String UNIT_ID = PREFIX + "unitid";
String UNIT_PRICE = PREFIX + "unitprice";
}
|
package Utilities;
public class UitlityFunctions {
}
|
package org.ah.minecraft.armour.utils;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.ChatColor;
import org.bukkit.Color;
import org.bukkit.Material;
import org.bukkit.craftbukkit.v1_12_R1.inventory.CraftItemStack;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.LeatherArmorMeta;
import net.minecraft.server.v1_12_R1.NBTTagCompound;
import net.minecraft.server.v1_12_R1.NBTTagInt;
import net.minecraft.server.v1_12_R1.NBTTagList;
import net.minecraft.server.v1_12_R1.NBTTagString;
public class ArmourUtil {
private static final Color GREEN = Color.fromRGB(0, 150, 20);
private static final Color GRAY = Color.fromRGB(100, 100, 100);
private static final Color AQUA = Color.AQUA;
private static final Color JET = Color.fromRGB(125, 22, 162);
private ArmourUtil() {
}
public static void removeXP(Player p, int ammount) {
float a = ammount / 100;
if (p.getExp() - a > 0) {
p.setExp(p.getExp() - a);
} else {
if (p.getExp() > 0) {
a = a - p.getExp();
p.setLevel(p.getLevel() - 1);
p.setExp(1.0f - a);
} else {
p.setExp(0.99f);
p.setLevel(p.getLevel() - 1);
}
}
}
public static boolean checkForJetBoots(Player p) {
ItemStack boots = p.getInventory().getBoots();
if ((boots != null) && (boots.hasItemMeta())) {
ItemMeta itemMeta = boots.getItemMeta();
return ("Jet Boots".equals(itemMeta.getDisplayName())) && ((itemMeta instanceof LeatherArmorMeta))
&& (new Integer(4).equals(boots.getEnchantments().get(Enchantment.DURABILITY))) && (JET.equals(((LeatherArmorMeta) itemMeta).getColor()));
}
return false;
}
public static ItemStack createJetBoots() {
ItemStack boots = new ItemStack(Material.LEATHER_BOOTS);
LeatherArmorMeta meta = (LeatherArmorMeta) boots.getItemMeta();
meta.setDisplayName("Jet Boots");
List<String> lores = new ArrayList();
lores.add(ChatColor.WHITE + "Sneak will make you fly. But fast.");
lores.add(ChatColor.WHITE + " ");
lores.add(ChatColor.GRAY + "Set: " + ChatColor.YELLOW + "AIR");
lores.add(ChatColor.GRAY + "Tier ?");
meta.setLore(lores);
meta.setColor(JET);
meta.addItemFlags(new ItemFlag[] { ItemFlag.HIDE_ATTRIBUTES });
boots.setItemMeta(meta);
boots.addUnsafeEnchantment(Enchantment.DURABILITY, 4);
// boots = ArmourUtil.addEpicArmourAttributes(boots);
return boots;
}
public static boolean compare(org.bukkit.inventory.ItemStack one, org.bukkit.inventory.ItemStack two) {
if (one != null && two != null) {
try {
if (one.getType() == two.getType()) {
if (one.hasItemMeta() && two.hasItemMeta()) {
if (one.getItemMeta().getDisplayName().equals(two.getItemMeta().getDisplayName())) {
if (one.getItemMeta().getItemFlags().equals(two.getItemMeta().getItemFlags())) {
return true;
}
}
return false;
} else {
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return false;
}
public static org.bukkit.inventory.ItemStack addArmourAttributes(org.bukkit.inventory.ItemStack i) {
net.minecraft.server.v1_12_R1.ItemStack nmsStack = CraftItemStack.asNMSCopy(i);
NBTTagCompound compound = nmsStack.getTag();
if (compound == null) {
compound = new NBTTagCompound();
nmsStack.setTag(compound);
compound = nmsStack.getTag();
}
NBTTagList modifiers = new NBTTagList();
NBTTagCompound healthboost = new NBTTagCompound();
healthboost.set("AttributeName", new NBTTagString("generic.armor"));
healthboost.set("Name", new NBTTagString("generic.armor"));
healthboost.set("Amount", new NBTTagInt(5));
healthboost.set("Operation", new NBTTagInt(0));
healthboost.set("UUIDLeast", new NBTTagInt(905983));
healthboost.set("UUIDMost", new NBTTagInt(18915));
if (i.getType().toString().contains("HELM")) {
healthboost.set("Slot", new NBTTagString("head"));
} else if (i.getType().toString().contains("CHEST")) {
healthboost.set("Slot", new NBTTagString("chest"));
}
if (i.getType().toString().contains("LEG")) {
healthboost.set("Slot", new NBTTagString("legs"));
}
if (i.getType().toString().contains("BOOT")) {
healthboost.set("Slot", new NBTTagString("feet"));
}
modifiers.add(healthboost);
compound.set("AttributeModifiers", modifiers);
nmsStack.setTag(compound);
i = CraftItemStack.asBukkitCopy(nmsStack);
return i;
}
public static org.bukkit.inventory.ItemStack addEpicArmourAttributes(org.bukkit.inventory.ItemStack i) {
net.minecraft.server.v1_12_R1.ItemStack nmsStack = CraftItemStack.asNMSCopy(i);
NBTTagCompound compound = nmsStack.getTag();
if (compound == null) {
compound = new NBTTagCompound();
nmsStack.setTag(compound);
compound = nmsStack.getTag();
}
NBTTagList modifiers = new NBTTagList();
NBTTagCompound healthboost = new NBTTagCompound();
healthboost.set("AttributeName", new NBTTagString("generic.armor"));
healthboost.set("Name", new NBTTagString("generic.armor"));
healthboost.set("Amount", new NBTTagInt(20));
healthboost.set("Operation", new NBTTagInt(0));
healthboost.set("UUIDLeast", new NBTTagInt(905983));
healthboost.set("UUIDMost", new NBTTagInt(18915));
if (i.getType().toString().contains("HELM")) {
healthboost.set("Slot", new NBTTagString("head"));
} else if (i.getType().toString().contains("CHEST")) {
healthboost.set("Slot", new NBTTagString("chest"));
}
if (i.getType().toString().contains("LEG")) {
healthboost.set("Slot", new NBTTagString("legs"));
}
if (i.getType().toString().contains("BOOT")) {
healthboost.set("Slot", new NBTTagString("feet"));
}
modifiers.add(healthboost);
compound.set("AttributeModifiers", modifiers);
nmsStack.setTag(compound);
i = CraftItemStack.asBukkitCopy(nmsStack);
return i;
}
public static boolean checkForBouncerBoots(Player p) {
org.bukkit.inventory.ItemStack boots = p.getInventory().getBoots();
if ((boots != null) && (boots.hasItemMeta())) {
ItemMeta itemMeta = boots.getItemMeta();
return ((ChatColor.DARK_PURPLE + "Bouncer Boots").equals(itemMeta.getDisplayName())) && ((itemMeta instanceof LeatherArmorMeta))
&& (GREEN.equals(((LeatherArmorMeta) itemMeta).getColor()));
}
return false;
}
public static org.bukkit.inventory.ItemStack createBouncerBoots() {
org.bukkit.inventory.ItemStack boots = new org.bukkit.inventory.ItemStack(Material.LEATHER_BOOTS);
LeatherArmorMeta meta = (LeatherArmorMeta) boots.getItemMeta();
meta.setDisplayName(ChatColor.DARK_PURPLE + "Bouncer Boots");
List<String> lores = new ArrayList();
lores.add(ChatColor.GREEN + "Bouncer Boots");
lores.add(ChatColor.DARK_GREEN + "Bounce around with these on!");
meta.setLore(lores);
meta.setColor(GREEN);
boots.setItemMeta(meta);
boots.addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 3);
return boots;
}
public static org.bukkit.inventory.ItemStack createLightEssence() {
org.bukkit.inventory.ItemStack item = new org.bukkit.inventory.ItemStack(Material.QUARTZ, 1);
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(ChatColor.WHITE + "" + ChatColor.MAGIC + "!!!" + ChatColor.RESET + ChatColor.WHITE + "Light Essence" + ChatColor.MAGIC + "!!!");
List<String> lores = new ArrayList();
lores.add(ChatColor.WHITE + "" + ChatColor.MAGIC + "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
lores.add(ChatColor.WHITE + "" + ChatColor.MAGIC + "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
lores.add(ChatColor.WHITE + "" + ChatColor.MAGIC + "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
lores.add(ChatColor.WHITE + "" + ChatColor.MAGIC + "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
lores.add(ChatColor.WHITE + "" + ChatColor.MAGIC + "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
lores.add(ChatColor.WHITE + "" + ChatColor.MAGIC + "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
meta.setLore(lores);
meta.addItemFlags(new ItemFlag[] { ItemFlag.HIDE_ENCHANTS });
item.setItemMeta(meta);
item.addUnsafeEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 3);
return item;
}
public static org.bukkit.inventory.ItemStack createDarkEssence() {
org.bukkit.inventory.ItemStack item = new org.bukkit.inventory.ItemStack(Material.COAL, 1, (short) 1);
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(ChatColor.BLACK + "" + ChatColor.MAGIC + "!!!" + ChatColor.RESET + ChatColor.BLACK + "Dark Essence" + ChatColor.MAGIC + "!!!");
List<String> lores = new ArrayList();
lores.add(ChatColor.BLACK + "" + ChatColor.MAGIC + "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
lores.add(ChatColor.BLACK + "" + ChatColor.MAGIC + "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
lores.add(ChatColor.BLACK + "" + ChatColor.MAGIC + "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
lores.add(ChatColor.BLACK + "" + ChatColor.MAGIC + "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
lores.add(ChatColor.BLACK + "" + ChatColor.MAGIC + "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
lores.add(ChatColor.BLACK + "" + ChatColor.MAGIC + "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
meta.setLore(lores);
meta.addItemFlags(new ItemFlag[] { ItemFlag.HIDE_ENCHANTS });
item.setItemMeta(meta);
item.addUnsafeEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 3);
return item;
}
public static boolean checkForWariorHelmet(Player p) {
org.bukkit.inventory.ItemStack helmet = p.getInventory().getHelmet();
if ((helmet != null) && (helmet.hasItemMeta())) {
ItemMeta itemMeta = helmet.getItemMeta();
return ("Warrior Helmet".equals(itemMeta.getDisplayName())) && ((itemMeta instanceof LeatherArmorMeta));
}
return false;
}
public static org.bukkit.inventory.ItemStack createWariorHelmet() {
org.bukkit.inventory.ItemStack helmet = new org.bukkit.inventory.ItemStack(Material.LEATHER_HELMET);
LeatherArmorMeta meta = (LeatherArmorMeta) helmet.getItemMeta();
meta.setDisplayName("Warrior Helmet");
List<String> lores = new ArrayList();
lores.add(ChatColor.BLACK + "Worn by the mighty skeleton warriors.");
meta.setLore(lores);
helmet.setItemMeta(meta);
helmet.addUnsafeEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 5);
return helmet;
}
public static boolean checkForRiderLeggings(Player p) {
org.bukkit.inventory.ItemStack boots = p.getInventory().getLeggings();
if ((boots != null) && (boots.hasItemMeta())) {
ItemMeta itemMeta = boots.getItemMeta();
return ((ChatColor.DARK_PURPLE + "Chaser Leggings").equals(itemMeta.getDisplayName())) && ((itemMeta instanceof LeatherArmorMeta))
&& (Color.MAROON.equals(((LeatherArmorMeta) itemMeta).getColor()));
}
return false;
}
public static org.bukkit.inventory.ItemStack createRiderLeggings() {
org.bukkit.inventory.ItemStack boots = new org.bukkit.inventory.ItemStack(Material.LEATHER_LEGGINGS);
LeatherArmorMeta meta = (LeatherArmorMeta) boots.getItemMeta();
meta.setDisplayName(ChatColor.DARK_PURPLE + "Chaser Leggings");
List<String> lores = new ArrayList();
lores.add(ChatColor.DARK_AQUA + "Zoom around with these bad boys and sprint to unlock their full power!");
meta.setLore(lores);
meta.setColor(Color.MAROON);
boots.setItemMeta(meta);
return boots;
}
public static boolean checkHoldingWarpBow(Player p) {
org.bukkit.inventory.ItemStack bow = p.getItemInHand();
if ((bow != null) && (bow.hasItemMeta())) {
ItemMeta itemMeta = bow.getItemMeta();
return ((ChatColor.DARK_PURPLE + "Warp Bow").equals(itemMeta.getDisplayName())) && (bow.getType() == Material.BOW);
}
return false;
}
public static org.bukkit.inventory.ItemStack createWarpBow() {
org.bukkit.inventory.ItemStack bow = new org.bukkit.inventory.ItemStack(Material.BOW);
ItemMeta meta = bow.getItemMeta();
meta.setDisplayName(ChatColor.DARK_PURPLE + "Warp Bow");
List<String> lores = new ArrayList();
lores.add(ChatColor.LIGHT_PURPLE + "Warp Bow");
lores.add(ChatColor.LIGHT_PURPLE + "Shoot to teleport!");
meta.setLore(lores);
bow.setItemMeta(meta);
bow.addUnsafeEnchantment(Enchantment.ARROW_DAMAGE, 20);
return bow;
}
public static org.bukkit.inventory.ItemStack createAquaBoots() {
org.bukkit.inventory.ItemStack boots = new org.bukkit.inventory.ItemStack(Material.LEATHER_BOOTS);
LeatherArmorMeta meta = (LeatherArmorMeta) boots.getItemMeta();
meta.setDisplayName(ChatColor.DARK_AQUA + "Auqatic Boots");
List<String> lores = new ArrayList();
lores.add(ChatColor.AQUA + "Worn by the aquatic sea monsters.");
meta.setLore(lores);
meta.addEnchant(Enchantment.DEPTH_STRIDER, 16, true);
meta.addEnchant(Enchantment.DURABILITY, 16, true);
meta.setColor(AQUA);
boots.setItemMeta(meta);
return boots;
}
public static org.bukkit.inventory.ItemStack createAquaPants() {
org.bukkit.inventory.ItemStack boots = new org.bukkit.inventory.ItemStack(Material.LEATHER_LEGGINGS);
LeatherArmorMeta meta = (LeatherArmorMeta) boots.getItemMeta();
meta.setDisplayName(ChatColor.DARK_AQUA + "Auqatic Pants");
List<String> lores = new ArrayList();
lores.add(ChatColor.AQUA + "Worn by the aquatic sea monsters.");
meta.setLore(lores);
meta.addEnchant(Enchantment.DURABILITY, 16, true);
meta.setColor(AQUA);
boots.setItemMeta(meta);
return boots;
}
public static org.bukkit.inventory.ItemStack createAquaShirt() {
org.bukkit.inventory.ItemStack boots = new org.bukkit.inventory.ItemStack(Material.LEATHER_CHESTPLATE);
LeatherArmorMeta meta = (LeatherArmorMeta) boots.getItemMeta();
meta.setDisplayName(ChatColor.DARK_AQUA + "Auqatic Shirt");
List<String> lores = new ArrayList();
lores.add(ChatColor.AQUA + "Worn by the aquatic sea monsters.");
meta.setLore(lores);
meta.addEnchant(Enchantment.DURABILITY, 16, true);
meta.setColor(AQUA);
boots.setItemMeta(meta);
return boots;
}
}
|
package com.wang.java8;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/*
* java8新特性
*/
public class Java8Tester {
/**
* @param args
*/
public static void main(String[] args) {
List<String> list1 = new ArrayList<String>();
List<Car> li = new ArrayList<Car>();
list1.add("baidu");
list1.add("sina");
list1.add("tencent");
list1.add("alibaba");
List<String> list2 = new ArrayList<String>();
list2.add("baidu");
list2.add("sina");
list2.add("tencent");
list2.add("alibaba");
Java8Tester java8Tester = new Java8Tester();
System.out.println("java8test******");
java8Tester.java8Sort(list1);
System.out.println(list1);
System.out.println("java7test*******");
java8Tester.java7Sort(list2);
System.out.println(list2);
}
private void java7Sort(List<String> list) {
Collections.sort(list, new Comparator<String>() {
public int compare(String name1,String name2){
return name1.compareTo(name2);
}
});
}
private void java8Sort(List<String> names){
//Lambda表达式实例化Comparator接口(函数式接口),函数式接口只能声明抽象方法
//int compareTo(String anotherString){} 传入两个参数,返回一个int值
Collections.sort(names, (a,b)->a.compareTo(b));
}
}
|
package entity;
// Generated Sep 3, 2019 7:58:03 PM by Hibernate Tools 3.6.0
import java.util.Date;
/**
* ShopInformation generated by hbm2java
*/
public class ShopInformation implements java.io.Serializable {
private int shopInformationId;
private String logoTop;
private String slogan;
private String shopImage;
private String shopDescription;
private String founderImage;
private String founderQuote;
private String contactEmail;
private String contactPhone;
private String contactAddress;
private Date created;
private boolean isDisabled;
private String logoBottom;
public ShopInformation() {
}
public ShopInformation(int shopInformationId, String logoTop, String slogan, String contactEmail, String contactPhone, String contactAddress, Date created, boolean isDisabled) {
this.shopInformationId = shopInformationId;
this.logoTop = logoTop;
this.slogan = slogan;
this.contactEmail = contactEmail;
this.contactPhone = contactPhone;
this.contactAddress = contactAddress;
this.created = created;
this.isDisabled = isDisabled;
}
public ShopInformation(int shopInformationId, String logoTop, String slogan, String shopImage, String shopDescription, String founderImage, String founderQuote, String contactEmail, String contactPhone, String contactAddress, Date created, boolean isDisabled, String logoBottom) {
this.shopInformationId = shopInformationId;
this.logoTop = logoTop;
this.slogan = slogan;
this.shopImage = shopImage;
this.shopDescription = shopDescription;
this.founderImage = founderImage;
this.founderQuote = founderQuote;
this.contactEmail = contactEmail;
this.contactPhone = contactPhone;
this.contactAddress = contactAddress;
this.created = created;
this.isDisabled = isDisabled;
this.logoBottom = logoBottom;
}
public int getShopInformationId() {
return this.shopInformationId;
}
public void setShopInformationId(int shopInformationId) {
this.shopInformationId = shopInformationId;
}
public String getLogoTop() {
return this.logoTop;
}
public void setLogoTop(String logoTop) {
this.logoTop = logoTop;
}
public String getSlogan() {
return this.slogan;
}
public void setSlogan(String slogan) {
this.slogan = slogan;
}
public String getShopImage() {
return this.shopImage;
}
public void setShopImage(String shopImage) {
this.shopImage = shopImage;
}
public String getShopDescription() {
return this.shopDescription;
}
public void setShopDescription(String shopDescription) {
this.shopDescription = shopDescription;
}
public String getFounderImage() {
return this.founderImage;
}
public void setFounderImage(String founderImage) {
this.founderImage = founderImage;
}
public String getFounderQuote() {
return this.founderQuote;
}
public void setFounderQuote(String founderQuote) {
this.founderQuote = founderQuote;
}
public String getContactEmail() {
return this.contactEmail;
}
public void setContactEmail(String contactEmail) {
this.contactEmail = contactEmail;
}
public String getContactPhone() {
return this.contactPhone;
}
public void setContactPhone(String contactPhone) {
this.contactPhone = contactPhone;
}
public String getContactAddress() {
return this.contactAddress;
}
public void setContactAddress(String contactAddress) {
this.contactAddress = contactAddress;
}
public Date getCreated() {
return this.created;
}
public void setCreated(Date created) {
this.created = created;
}
public boolean isIsDisabled() {
return this.isDisabled;
}
public void setIsDisabled(boolean isDisabled) {
this.isDisabled = isDisabled;
}
public String getLogoBottom() {
return this.logoBottom;
}
public void setLogoBottom(String logoBottom) {
this.logoBottom = logoBottom;
}
}
|
package com.zkyq.spiderJson.dao;
import com.zkyq.spiderJson.modle.TGirls;
import com.zkyq.spiderJson.modle.Zhilian;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface TGirlsRepository extends JpaRepository<TGirls, Long> {
List<TGirls> findByTitle(String title);
}
|
/*
* FileName: IExcelBuilder.java
* Description:
* Company: 南宁超创信息工程有限公司
* Copyright: ChaoChuang (c) 2005
* History: 2005-6-30 (jyb) 1.0 Create
*/
package com.spower.basesystem.excel.service;
import javax.servlet.http.HttpServletResponse;
/**
* @author Jyb
* @version 1.0 2005-6-30
*/
public interface IExcelBuilder {
/**
* 生成Excel对象
* @param response @see HttpServletResponse
* @param command 值对象
* @throws Exception @see Exception
*/
void makeExcel(HttpServletResponse response, Object command)
throws Exception;
}
|
package Task2;
public class Lorry extends Car {
private double liftingCapacity;
@Override
void start() {
System.out.println(carClass+ " поехал");
}
@Override
void stop() {
System.out.println(carClass+ " остановился");
}
@Override
void printInfo() {
System.out.println("Модель: " + carModel);
System.out.println("Класс: " + carClass);
System.out.println("Вес: " + weight + " кг");
System.out.println("Грузоподъемность: "+ liftingCapacity + " кг");
System.out.println("Мощность двигателя: " + engine.getPower() + " л/с" );
System.out.println("Производитель: " + engine.getManufacturer());
}
public double getLiftingCapacity() {
return liftingCapacity;
}
public void setLiftingCapacity(double liftingCapacity) {
this.liftingCapacity = liftingCapacity;
}
}
|
package ru.task.codemark.model;
import com.sun.istack.NotNull;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import java.util.Objects;
import java.util.Set;
/**
* Базовая сущность Пользователи
* согласно ТЗ:
* "Атрибуты пользователя - Имя, Логин (первичный ключ),
* Пароль (шифровать пароль в рамках тестового задания не требуется, это просто строка)."
* связь согласно заданию выбрана ManyToMany
*
*/
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "users")
public class User {
@Id
@Getter
@NotNull
private String login;
@NotNull
@Getter
@Setter
@Column(name = "name")
private String name;
@NotNull
@Getter
@Setter
@Column(name = "password")
private String password;
@Getter
@Setter
@ManyToMany
@JoinTable(name = "roles_users",
joinColumns = {@JoinColumn(name = "users_login")}, inverseJoinColumns = {@JoinColumn(name = "roles_id")})
private Set<Role> roles;
public static User of(String name, String password, String login) {
User user = new User();
user.login = login;
user.name = name;
user.password = password;
return user;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
User user = (User) o;
return Objects.equals(login, user.login);
}
@Override
public int hashCode() {
return Objects.hash(login);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("User{");
sb.append("login='").append(login).append('\'');
sb.append(", name='").append(name).append('\'');
sb.append(", password='").append(password).append('\'');
sb.append(", role=").append(roles);
sb.append('}');
return sb.toString();
}
}
|
package com.liufeng.domian.dto.base;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.NotBlank;
@Data
@ApiModel(description = "共用分页类")
public class BasePageQuery {
@ApiModelProperty(value = "显示第几页")
private Integer pageNum;
@ApiModelProperty(value = "每页显示多少数据")
private Integer pageSize;
}
|
package pl.finsys.innerBeansExample;
public class Order {
private Client client;
public Order(Client client) {
this.client = client;
}
public void setClient(Client client) {
this.client = client;
}
public Client getClient() {
return client;
}
@Override
public String toString() {
return "Customer [client=" + client + "]";
}
}
|
package HashMap;
import java.util.HashMap;
public class MaxPoints_149 {
/*149. 直线上最多的点数*/
/*
HashMap来保存斜率以及相同斜率的点数;
注意斜率为0有正零和负零的区别;
考虑除数为0的情况;
当出现相同点时另外计数;
*/
public int maxPoints(int[][] points) {
if(points.length == 0 || points.length == 1){
return points.length;
}
HashMap<Double,Integer> map = new HashMap<>();
int res = 0, cur = 1, same = 0;
for(int i = 0; i < points.length - 1; i++){
for(int j = i + 1; j < points.length; j++){
double d;
if(points[i][0] - points[j][0] == 0 && points[i][1] - points[j][1] == 0){
same++;
}else{
if(points[i][0] == points[j][0]){
d = 0;
}else if(points[i][1] - points[j][1] != 0){
d = (double)(points[i][0] - points[j][0]) / (points[i][1] - points[j][1]);
}else{
d = points[i][1];
}
if(!map.containsKey(d)){
map.put(d,2);
}else{
map.put(d,map.get(d) + 1);
}
}
}
for(Double d : map.keySet()){
if(map.get(d) > cur){
cur = map.get(d);
}
}
res = Math.max(res,cur + same);
cur = 1;
same = 0;
map.clear();
}
return res;
}
}
|
package cs3500.animator.model.feature;
import java.util.List;
import java.util.Map;
import cs3500.animator.model.featuremotion.FeatureMotion;
import cs3500.animator.model.featurestate.FeatureState;
/**
* An interface to represent all operations that must be supported by a Feature of a given
* animation. A Feature is synonymous with a shape. A Feature is intended to encapsulate the entire
* set of motions for any given shape and all of the states encapsulated in those motions.
*/
public interface Feature {
/**
* Gets the name of this Feature.
*
* @return the name of this Feature.
*/
String getName();
/**
* Builds a FeatureMotion corresponding to the type of this Feature according to the
* specifications of the inputted parameters.
*
* @param t1 The starting tick of the motion to be returned.
* @param x1 The x position of the starting state of the motion to be returned.
* @param y1 The y position of the starting state of the motion to be returned.
* @param w1 The width of the starting state of the the motion to be returned.
* @param h1 The height of the starting state of the motion to be returned.
* @param r1 The R value of the color of the starting state of the motion to be returned.
* @param g1 The G value of the color of the starting state of the motion to be returned.
* @param b1 The B value of the color of the starting state of the motion to be returned.
* @param t2 The ending tick of the motion to be returned.
* @param x2 The x position of the ending state of the motion to be returned.
* @param y2 The y position of the ending state of the motion to be returned.
* @param w2 The width of the ending state of the the motion to be returned.
* @param h2 The height of the ending state of the motion to be returned.
* @param r2 The R value of the color of the ending state of the motion to be returned.
* @param g2 The G value of the color of the ending state of the motion to be returned.
* @param b2 The B value of the color of the ending state of the motion to be returned.
* @return A properly constructed FeatureMotion.
*/
FeatureMotion buildMotion(int whenAdded, int t1, int x1, int y1, int w1, int h1, int r1, int g1,
int b1, int t2,
int x2, int y2, int w2, int h2, int r2, int g2, int b2);
/**
* Gets the tick that this Feature disappears at.
*
* @return an int representing the tick the Feature disappears at.
*/
int getDisappearAt();
/**
* Gets the tick that this Feature appears at.
*
* @return the tick this Feature appears at.
*/
int getAppearAt();
/**
* Sets the fields of this Feature according to the inputted list of FeatureMotion.
*
* @param motionList list of FeatureMotion
*/
void setAllButName(List<FeatureMotion> motionList);
/**
* Gets the list of FeatureMotion that is stored in this Feature.
*
* @return list of FeatureMotion
*/
List<FeatureMotion> getListOfFeatureMotions();
/**
* Returns the type of this Feature. For example, if the shape is a rectangle, this method wil
* return "rect".
*
* @return a String representing the type of this Feature.
*/
String getType();
/**
* This method adds the specified motion to the set of motions for this shape.
*
* @param motion the motion to add.
*/
void addMotion(FeatureMotion motion);
/**
* This method removes the specified motion from the set of motions for this shape.
*
* @param motion the motion to return
*/
void removeMotion(FeatureMotion motion);
/**
* Returns true if this AnimationComponent is visible during the provided tick.
*
* @param tick represents the current tick of the animation
* @return true if visible
*/
boolean isVisible(int tick);
/**
* Removes the keyFrame from this Feature at the given tick.
*
* @param tick represents the tick of the keyFrame that is to be removed.
*/
void removeKeyFrame(int tick);
/**
* Adds a keyFrame to this Feature.
*
* @param state represents the keyFrame to be added.
* @param tick represents the tick of the keyFrame to be added.
*/
void addKeyFrame(FeatureState state, int tick);
/**
* Gets a map holding keyFrames for this Feature.
*
* @return Map where Integer represents tick and FeatureState represents keyFrame
*/
Map<Integer, FeatureState> getKeyFrameMap();
}
|
package shapes;
import java.io.IOException;
public class Square extends Rectangle {
double side;
public Square(double s) throws IOException{
super(s, s);
}
public double getSide(){
return this.side;
}
public void setSide(double s){
this.side = s;
}
public double perimeter() {
return super.perimeter();
}
@Override
public String toString(){
return "Square{line=" + getSide() +"} perimeter = " + perimeter() + "\n" ;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (this.getClass() != obj.getClass())
return false;
Square other = (Square) obj;
if (this.side != other.side)
return false;
if (perimeter() != other.perimeter())
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = (int) (prime * result + side);
result = (int) (prime * result + perimeter());
return result;
}
}
|
package jc.sugar.JiaHui.jmeter.sampler;
import jc.sugar.JiaHui.jmeter.*;
import org.apache.jmeter.sampler.TestAction;
import java.util.HashMap;
import java.util.Map;
import static org.apache.jorphan.util.Converter.getInt;
import static org.apache.jorphan.util.Converter.getString;
@JMeterElementMapperFor(value = JMeterElementType.TestAction, testGuiClass = JMeterElement.TestAction)
public class TestActionMapper extends AbstractJMeterElementMapper<TestAction> {
public static final String WEB_ACTION = "action";
public static final String WEB_TARGET = "target";
public static final String WEB_DURATION = "duration";
private TestActionMapper(TestAction element, Map<String, Object> attributes) {
super(element, attributes);
}
public TestActionMapper(Map<String, Object> attributes){
this(new TestAction(), attributes);
}
public TestActionMapper(TestAction element){
this(element, new HashMap<>());
}
@Override
public TestAction fromAttributes() {
element.setAction(getInt(attributes.get(WEB_ACTION)));
element.setTarget(getInt(attributes.get(WEB_TARGET)));
element.setDuration(getString(attributes.get(WEB_DURATION)));
return element;
}
@Override
public Map<String, Object> toAttributes() {
attributes.put(WEB_CATEGORY, JMeterElementCategory.Sampler);
attributes.put(WEB_TYPE, JMeterElementType.TestAction);
attributes.put(WEB_ACTION, element.getAction());
attributes.put(WEB_TARGET, element.getTarget());
attributes.put(WEB_DURATION, element.getDurationAsString());
return attributes;
}
}
|
package mnm.mods.tabbychat.core.api;
public class AddonException extends Exception {
private static final long serialVersionUID = 2253686906805675035L;
public AddonException(String string, Throwable t) {
super(string, t);
}
public AddonException(Throwable t) {
super(t);
}
public AddonException(String string) {
super(string);
}
}
|
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.io.*;
import java.awt.*;
import javax.imageio.*;
import javax.swing.*;
public class Cropp
{
public static void main(String[] args) {
new Cropp();
}
public Cropp() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new CropPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class CropPane extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
private BufferedImage background;
private Rectangle cropBounds;
public CropPane() {
try {
background = ImageIO.read(new File("Temp_0.jpg"));
} catch (IOException exp) {
exp.printStackTrace();
}
MouseHandler handler = new MouseHandler();
addMouseListener((MouseListener) handler);
addMouseMotionListener((MouseMotionListener) handler);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(background.getWidth(), background.getHeight());
}
protected Rectangle getCropBounds() {
Rectangle actualBounds = null;
if (cropBounds != null) {
int x = cropBounds.x;
int y = cropBounds.y;
int width = cropBounds.width;
int height = cropBounds.height;
if (width < 0) {
x += width;
width -= (width * 2);
}
if (height < 0) {
y += height;
height -= (height * 2);
}
actualBounds = new Rectangle(x, y, width, height);
System.out.println(actualBounds);
}
return actualBounds;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
if (background != null) {
int x = (getWidth() - background.getWidth()) / 2;
int y = (getHeight() - background.getHeight()) / 2;
g2d.drawImage(background, x, y, this);
}
Rectangle drawCrop = getCropBounds();
if (drawCrop != null) {
Color color = UIManager.getColor("List.selectionBackground");
g2d.setColor(color);
Composite composite = g2d.getComposite();
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
g2d.fill(drawCrop);
g2d.setComposite(composite);
g2d.draw(drawCrop);
}
}
public class MouseHandler extends MouseAdapter
{
@Override
public void mouseReleased(MouseEvent e)
{
BufferedImage bff = background.getSubimage(cropBounds.x, cropBounds.y, cropBounds.width, cropBounds.height);
JLabel picLabel = new JLabel(new ImageIcon(bff));
int YesNo = JOptionPane.showConfirmDialog(null, picLabel, "About", JOptionPane.YES_NO_OPTION);
if (YesNo == JOptionPane.YES_OPTION)
{
File outputfile = new File("image.jpg");
try
{
ImageIO.write(bff, "jpg", outputfile);
}
catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
cropBounds = null;
repaint();
// JPanel p = (JPanel)(e.getSource());
// p.getF
System.exit(0);
}
}
@Override
public void mousePressed(MouseEvent e) {
cropBounds = new Rectangle();
cropBounds.setLocation(e.getPoint());
repaint();
}
@Override
public void mouseDragged(MouseEvent e) {
if (cropBounds != null) {
Point p = e.getPoint();
int width = p.x - cropBounds.x;
int height = p.y - cropBounds.y;
cropBounds.setSize(width, height);
repaint();
}
}
}
}
}
|
package corgi.hub.core.mqtt.service;
import corgi.hub.core.mqtt.bean.MqttStoreMessage;
import corgi.hub.core.mqtt.bean.RetainedMessage;
import corgi.hub.core.mqtt.bean.Subscription;
import corgi.hub.core.mqtt.common.IMatchingCondition;
import corgi.hub.core.mqtt.event.MqttEvent;
import corgi.hub.core.mqtt.event.MqttPublishEvent;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Set;
/**
* Created by Terry LIANG on 2016/12/24.
*/
public interface IStorageService {
void storeRetainedMessage(String topic, byte[] message, int qos);
Collection<RetainedMessage> searchMatchingRetainedMessage(IMatchingCondition condition);
///////////////////////////////////////////////////////////////////////
void addSubscription(Subscription newSubscription);
void removeSubscriptionByClientId(String clientId);
void removeSubscription(String clientId, String topic);
List<Subscription> retrieveAllSubscriptions();
List<Subscription> retrieveSubscriptionsByClientId(String clientId);
List<Subscription> retrieveSubscriptionByTopic(String topic);
Subscription retrieveSubscription(String clientId, String topic);
void updateSubscription(Subscription subscription);
///////////////////////////////////////////////////////////////////////
MqttStoreMessage addStoreMessage(MqttPublishEvent mqttPublishEvent);
List<MqttStoreMessage> retrieveStoreMessage(String topic);
MqttStoreMessage retrieveStoreMessage(long msgId);
void removeStoreMessage(String clientId, int msgId, String topic);
void removeStoreMessage(long storeMsgId);
void ackStoreMessage(String clientId, long storeMsgId);
boolean alreadyAck(String clientId, long storeMsgId);
List<MqttStoreMessage> retrieveUnackStoreMessage(String clientId, String topic);
List<MqttEvent> retrieveOutdatedPublishMessage(long lifecycle);
///////////////////////////////////////////////////////////////////////
void storePublishedMessage(MqttEvent mqttEvent);
void removePublishedMessage(String publishKey);
void removePublishedMessageByClientId(String clientId);
MqttEvent retrievePublishedMessage(String publishKey);
List<MqttEvent> retrivePublishedMessageByClientId(String clientId);
List<MqttEvent> retrievePublishedMessageByBatch(int batchSize);
///////////////////////////////////////////////////////////////////////
void loggingNotifyEvent(long storeMsgId);
void registerNodeInfo();
int getOnlineNodeCount();
void ackNotifyEvent(long storeMsgId);
Set<Long> getUnackNotifyEventWithPeriodInSecond(int totalOnlineAcker, int period);
}
|
package com.josie.annotation.enable;
import java.lang.annotation.*;
/**
* @Author:Josie Zhu
* @Description:启用切面拦截
* @Date:Create in 12:51 2018/10/11
*/
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface EnableAspcetProxy {
}
|
package com.laurenelder.aquapharm;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
public class PlantsFragment extends Fragment {
Context context;
LinearLayout linearLayout;
String tag = "PLANTS FRAGMENT";
ImageView plantPic;
ImageView annualTemp;
ImageView winterTemp;
ImageView springTemp;
ImageView summerTemp;
ImageView fallTemp;
TextView plantEdible;
int spinnerViewPosition = 0;
// Interface to PlantsActivity methods
public interface OnSelected {
public ArrayList<String> getData(int pos);
public ArrayList<Double> getTemps();
}
private OnSelected parentActivity;
@Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
context = getActivity();
if(activity instanceof OnSelected) {
parentActivity = (OnSelected) activity;
} else {
throw new ClassCastException((activity.toString()) + "Did not impliment onSelected interface");
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View plantsView = inflater.inflate(R.layout.activity_plants, container);
context = getActivity();
// Get and set UI elements
plantPic = (ImageView)plantsView.findViewById(R.id.plantImage);
annualTemp = (ImageView)plantsView.findViewById(R.id.plantOverallColor);
winterTemp = (ImageView)plantsView.findViewById(R.id.plantWinterColor);
springTemp = (ImageView)plantsView.findViewById(R.id.plantSpringColor);
summerTemp = (ImageView)plantsView.findViewById(R.id.plantSummerColor);
fallTemp = (ImageView)plantsView.findViewById(R.id.plantFallColor);
plantEdible = (TextView)plantsView.findViewById(R.id.plantEatable);
linearLayout = (LinearLayout) plantsView.findViewById(R.id.linearLayout);
// Set background image transparency
linearLayout.getBackground().setAlpha(85);
// Set spinner adapter
Spinner plantsSpinner = (Spinner) plantsView.findViewById(R.id.plantSpinner);
List<String> plants = new ArrayList<String>();
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(context,
android.R.layout.simple_spinner_item, plants);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
plantsSpinner.setAdapter(spinnerAdapter);
plants.add("Angel Face");
plants.add("Azaleas");
plants.add("Bell Peppers");
plants.add("Bird of Paradise");
plants.add("Blackberries");
plants.add("Blueberries");
plants.add("Broccoli");
plants.add("Brussel Spouts");
plants.add("Cabbage");
plants.add("Carnations");
plants.add("Celery");
plants.add("Cherries");
plants.add("Chives");
plants.add("Collard Greens");
plants.add("Cucumbers");
plants.add("Daffodils");
plants.add("Daisies");
plants.add("Eggplant");
plants.add("Garlic");
plants.add("Geranium");
plants.add("Grapes");
plants.add("Green Beans");
plants.add("Hibiscus");
plants.add("Iris");
plants.add("Jalapeno Peppers");
plants.add("Kiwi Fruit");
plants.add("Lettuce");
plants.add("Lima Beans");
plants.add("Onions");
plants.add("Peas");
plants.add("Pineapple");
plants.add("Pumpkin");
plants.add("Raspberries");
plants.add("Roses");
plants.add("Spinach");
plants.add("Squash");
plants.add("Strawberries");
plants.add("Tomatoes");
plants.add("Watermelon");
spinnerAdapter.notifyDataSetChanged();
// Update UI elements based on spinner selection
plantsSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
spinnerViewPosition = position;
String imageName = parentActivity.getData(position).get(3).toString();
imageName = imageName.substring(0, imageName.length() - 4);
Log.i(tag, imageName);
int resID = getResources().getIdentifier(imageName, "raw", "com.laurenelder.aquapharm");
plantPic.setImageResource(resID);
if (parentActivity.getData(position).get(4).toString().matches("yes")) {
plantEdible.setText("Edible");
} else {
plantEdible.setText("Uneatable");
}
updateColors();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
return plantsView;
}
// updateColors method compensates for temperature shifts and sets the color icons respectively.
public void updateColors() {
ArrayList<Integer> temps = new ArrayList<Integer>();
for (int z = 0; z < 10; z++) {
Integer value = parentActivity.getTemps().get(z).intValue();
temps.add(value);
// Log.i(tag, String.valueOf(parentActivity.getTemps().get(z)));
// Log.i(tag, value.toString());
}
Log.i(tag, parentActivity.getData(spinnerViewPosition).get(1).toString());
// Annual Field
if (temps.get(0) > Integer.parseInt(parentActivity.getData(spinnerViewPosition).get(1).toString()) - 5 &&
temps.get(1) < Integer.parseInt(parentActivity.getData(spinnerViewPosition).get(2).toString()) + 5) {
annualTemp.setBackgroundResource(R.color.green);
Log.i(tag, "Color should be green");
}
if (temps.get(0) > Integer.parseInt(parentActivity.getData(spinnerViewPosition).get(1).toString()) - 10 ||
temps.get(1) < Integer.parseInt(parentActivity.getData(spinnerViewPosition).get(2).toString()) + 10) {
if (temps.get(0) < Integer.parseInt(parentActivity.getData(spinnerViewPosition).get(1).toString()) - 5 ||
temps.get(1) > Integer.parseInt(parentActivity.getData(spinnerViewPosition).get(2).toString()) + 5) {
annualTemp.setBackgroundResource(R.color.yellow);
Log.i(tag, "Color should be yellow");
}
}
if (temps.get(0) < Integer.parseInt(parentActivity.getData(spinnerViewPosition).get(1).toString()) - 10 ||
temps.get(1) > Integer.parseInt(parentActivity.getData(spinnerViewPosition).get(2).toString()) + 10) {
annualTemp.setBackgroundResource(R.color.red);
Log.i(tag, "Color should be red");
}
// Winter Field
if (temps.get(2) > Integer.parseInt(parentActivity.getData(spinnerViewPosition).get(1).toString()) - 5 &&
temps.get(3) < Integer.parseInt(parentActivity.getData(spinnerViewPosition).get(2).toString()) + 5) {
winterTemp.setBackgroundResource(R.color.green);
Log.i(tag, "Color should be green");
}
if (temps.get(2) > Integer.parseInt(parentActivity.getData(spinnerViewPosition).get(1).toString()) - 10 ||
temps.get(3) < Integer.parseInt(parentActivity.getData(spinnerViewPosition).get(2).toString()) + 10) {
if (temps.get(2) < Integer.parseInt(parentActivity.getData(spinnerViewPosition).get(1).toString()) - 5 ||
temps.get(3) > Integer.parseInt(parentActivity.getData(spinnerViewPosition).get(2).toString()) + 5) {
winterTemp.setBackgroundResource(R.color.yellow);
Log.i(tag, "Color should be yellow");
}
}
if (temps.get(2) < Integer.parseInt(parentActivity.getData(spinnerViewPosition).get(1).toString()) - 10 ||
temps.get(3) > Integer.parseInt(parentActivity.getData(spinnerViewPosition).get(2).toString()) + 10) {
winterTemp.setBackgroundResource(R.color.red);
Log.i(tag, "Color should be red");
}
// Spring Field
if (temps.get(4) > Integer.parseInt(parentActivity.getData(spinnerViewPosition).get(1).toString()) - 5 &&
temps.get(5) < Integer.parseInt(parentActivity.getData(spinnerViewPosition).get(2).toString()) + 5) {
springTemp.setBackgroundResource(R.color.green);
Log.i(tag, "Color should be green");
}
if (temps.get(4) > Integer.parseInt(parentActivity.getData(spinnerViewPosition).get(1).toString()) - 10 ||
temps.get(5) < Integer.parseInt(parentActivity.getData(spinnerViewPosition).get(2).toString()) + 10) {
if (temps.get(4) < Integer.parseInt(parentActivity.getData(spinnerViewPosition).get(1).toString()) - 5 ||
temps.get(5) > Integer.parseInt(parentActivity.getData(spinnerViewPosition).get(2).toString()) + 5) {
springTemp.setBackgroundResource(R.color.yellow);
Log.i(tag, "Color should be yellow");
}
}
if (temps.get(4) < Integer.parseInt(parentActivity.getData(spinnerViewPosition).get(1).toString()) - 10 ||
temps.get(5) > Integer.parseInt(parentActivity.getData(spinnerViewPosition).get(2).toString()) + 10) {
springTemp.setBackgroundResource(R.color.red);
Log.i(tag, "Color should be red");
}
// Summer Field
if (temps.get(6) > Integer.parseInt(parentActivity.getData(spinnerViewPosition).get(1).toString()) - 5 &&
temps.get(7) < Integer.parseInt(parentActivity.getData(spinnerViewPosition).get(2).toString()) + 5) {
summerTemp.setBackgroundResource(R.color.green);
Log.i(tag, "Color should be green");
}
if (temps.get(6) > Integer.parseInt(parentActivity.getData(spinnerViewPosition).get(1).toString()) - 10 ||
temps.get(7) < Integer.parseInt(parentActivity.getData(spinnerViewPosition).get(2).toString()) + 10) {
if (temps.get(6) < Integer.parseInt(parentActivity.getData(spinnerViewPosition).get(1).toString()) - 5 ||
temps.get(7) > Integer.parseInt(parentActivity.getData(spinnerViewPosition).get(2).toString()) + 5) {
summerTemp.setBackgroundResource(R.color.yellow);
Log.i(tag, "Color should be yellow");
}
}
if (temps.get(6) < Integer.parseInt(parentActivity.getData(spinnerViewPosition).get(1).toString()) - 10 ||
temps.get(7) > Integer.parseInt(parentActivity.getData(spinnerViewPosition).get(2).toString()) + 10) {
summerTemp.setBackgroundResource(R.color.red);
Log.i(tag, "Color should be red");
}
// Fall Field
if (temps.get(8) > Integer.parseInt(parentActivity.getData(spinnerViewPosition).get(1).toString()) - 5 &&
temps.get(9) < Integer.parseInt(parentActivity.getData(spinnerViewPosition).get(2).toString()) + 5) {
fallTemp.setBackgroundResource(R.color.green);
Log.i(tag, "Color should be green");
}
if (temps.get(8) > Integer.parseInt(parentActivity.getData(spinnerViewPosition).get(1).toString()) - 10 ||
temps.get(9) < Integer.parseInt(parentActivity.getData(spinnerViewPosition).get(2).toString()) + 10) {
if (temps.get(8) < Integer.parseInt(parentActivity.getData(spinnerViewPosition).get(1).toString()) - 5 ||
temps.get(9) > Integer.parseInt(parentActivity.getData(spinnerViewPosition).get(2).toString()) + 5) {
fallTemp.setBackgroundResource(R.color.yellow);
Log.i(tag, "Color should be yellow");
}
}
if (temps.get(8) < Integer.parseInt(parentActivity.getData(spinnerViewPosition).get(1).toString()) - 10 ||
temps.get(9) > Integer.parseInt(parentActivity.getData(spinnerViewPosition).get(2).toString()) + 10) {
fallTemp.setBackgroundResource(R.color.red);
Log.i(tag, "Color should be red");
}
}
}
|
package ro.redeul.google.go.lang.parser.parsing.declarations;
import com.intellij.lang.PsiBuilder;
import com.intellij.psi.tree.TokenSet;
import ro.redeul.google.go.lang.parser.GoElementTypes;
import ro.redeul.google.go.lang.parser.GoParser;
import static ro.redeul.google.go.lang.parser.parsing.util.ParserUtils.advance;
import static ro.redeul.google.go.lang.parser.parsing.util.ParserUtils.getToken;
import static ro.redeul.google.go.lang.parser.parsing.util.ParserUtils.lookAhead;
import static ro.redeul.google.go.lang.parser.parsing.util.ParserUtils.skipComments;
import static ro.redeul.google.go.lang.parser.parsing.util.ParserUtils.skipNLS;
import static ro.redeul.google.go.lang.parser.parsing.util.ParserUtils.wrapError;
/**
* @author Mihai Claudiu Toader <mtoader@gmail.com>
* Date: 7/20/11
*/
public class NestedDeclarationParser implements GoElementTypes {
public static final TokenSet DECLARATION_END = TokenSet.create(oSEMI,
pRPAREN,
wsNLS);
public static void parseNestedOrBasicDeclaration(PsiBuilder builder,
GoParser parser,
DeclarationParser declarationParser) {
if (lookAhead(builder, pLPAREN)) {
advance(builder);
do {
skipNLS(builder);
declarationParser.parse(builder, parser);
skipComments(builder);
if (!builder.eof() &&
!DECLARATION_END.contains(builder.getTokenType())) {
wrapError(builder,
"semicolon.or.newline.or.closed.parenthesis.expected");
} else {
getToken(builder, oSEMI);
skipNLS(builder);
}
} while (!lookAhead(builder, pRPAREN) && !builder.eof());
advance(builder);
} else {
declarationParser.parse(builder, parser);
}
}
public interface DeclarationParser {
void parse(PsiBuilder builder, GoParser parser);
}
}
|
package com.services.utils.Date;
import org.apache.commons.lang3.time.DateUtils;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.TreeMap;
/**
* @author wang
**/
public class WorkTimeUtil {
/**
* 工作日历
*/
private static Map<String, WorkCalendar> workCalendar = new TreeMap<String, WorkCalendar>();
/**
* 每天的工作开始时间 和 结束时间
*/
private static Calendar dayWorkStart = Calendar.getInstance();
private static Calendar dayWorkEnd = Calendar.getInstance();
static {
try {
//初始化工作时间
dayWorkStart.setTime(new SimpleDateFormat("HH:mm:ss").parse("09:00:00"));
dayWorkEnd.setTime(new SimpleDateFormat("HH:mm:ss").parse("18:00:00"));
//初始化工作日历
workCalendar.put("201701", new WorkCalendar(2017, 1, "2,3,4,5,6,9,10,11,12,13,16,17,18,19,20,23,24,25,26,27,30,31"));
workCalendar.put("201702", new WorkCalendar(2017, 2, "1,2,3,6,7,8,9,10,13,14,15,16,17,20,21,22,23,24,27,28"));
workCalendar.put("201703", new WorkCalendar(2017, 3, "1,2,3,6,7,8,9,10,13,14,15,16,17,20,21,22,23,24,27,28,29,30,31"));
workCalendar.put("201704", new WorkCalendar(2017, 4, "3,4,5,6,7,10,11,12,13,14,17,18,19,20,21,24,25,26,27,28"));
workCalendar.put("201705", new WorkCalendar(2017, 5, "1,2,3,4,5,8,9,10,11,12,15,16,17,18,19,22,23,24,25,26,29,30,31"));
workCalendar.put("201706", new WorkCalendar(2017, 6, "1,2,5,6,7,8,9,12,13,14,15,16,19,20,21,22,23,26,27,28,29,30"));
workCalendar.put("201707", new WorkCalendar(2017, 7, "3,4,5,6,7,10,11,12,13,14,17,18,19,20,21,24,25,26,27,28,31"));
workCalendar.put("201708", new WorkCalendar(2017, 8, "1,2,3,4,7,8,9,10,11,14,15,16,17,18,21,22,23,24,25,28,29,30,31"));
workCalendar.put("201709", new WorkCalendar(2017, 9, "1,4,5,6,7,8,11,12,13,14,15,18,19,20,21,22,25,26,27,28,29"));
workCalendar.put("201710", new WorkCalendar(2017, 10, "2,3,4,5,6,9,10,11,12,13,16,17,18,19,20,23,24,25,26,27,30,31"));
workCalendar.put("201711", new WorkCalendar(2017, 11, "1,2,3,6,7,8,9,10,13,14,15,16,17,20,21,22,23,24,27,28,29,30"));
workCalendar.put("201712", new WorkCalendar(2017, 12, "1,4,5,6,7,8,11,12,13,14,15,18,19,20,21,22,25,26,27,28,29"));
workCalendar.put("201801", new WorkCalendar(2018, 1, "1,2,3,4,5,8,9,10,11,12,15,16,17,18,19,22,23,24,25,26,29,30,31"));
workCalendar.put("201802", new WorkCalendar(2018, 2, "1,2,5,6,7,8,9,12,13,14,15,16,19,20,21,22,23,26,27,28"));
workCalendar.put("201803", new WorkCalendar(2018, 3, "1,2,5,6,7,8,9,12,13,14,15,16,19,20,21,22,23,26,27,28,29,30"));
workCalendar.put("201804", new WorkCalendar(2018, 4, "2,3,4,5,6,9,10,11,12,13,16,17,18,19,20,23,24,25,26,27,30"));
workCalendar.put("201805", new WorkCalendar(2018, 5, "1,2,3,4,7,8,9,10,11,14,15,16,17,18,21,22,23,24,25,28,29,30,31"));
workCalendar.put("201806", new WorkCalendar(2018, 6, "1,4,5,6,7,8,11,12,13,14,15,18,19,20,21,22,25,26,27,28,29"));
workCalendar.put("201807", new WorkCalendar(2018, 7, "2,3,4,5,6,9,10,11,12,13,16,17,18,19,20,23,24,25,26,27,30,31"));
workCalendar.put("201808", new WorkCalendar(2018, 8, "1,2,3,6,7,8,9,10,13,14,15,16,17,20,21,22,23,24,27,28,29,30,31"));
workCalendar.put("201809", new WorkCalendar(2018, 9, "3,4,5,6,7,10,11,12,13,14,17,18,19,20,21,24,25,26,27,28"));
workCalendar.put("201810", new WorkCalendar(2018, 10, "1,2,3,4,5,8,9,10,11,12,15,16,17,18,19,22,23,24,25,26,29,30,31"));
workCalendar.put("201811", new WorkCalendar(2018, 11, "1,2,5,6,7,8,9,12,13,14,15,16,19,20,21,22,23,26,27,28,29,30"));
workCalendar.put("201812", new WorkCalendar(2018, 12, "3,4,5,6,7,10,11,12,13,14,17,18,19,20,21,24,25,26,27,28,31"));
} catch (ParseException e) {
e.printStackTrace();
}
}
/**
* 计算指定工时之后的日期
*
* @param date
* @param workHourTime
* @return
* @throws ParseException
*/
public Date getAddWorkHourDate(Date date, Double workHourTime) throws ParseException {
Calendar c = Calendar.getInstance();
c.setTime(date);
Calendar origin = (Calendar) c.clone();
// 如果当天是工作日 则将日期定位到工作日起始时间,并加上当日已过的工时
if (isWorkDay(c)) {
locationWorkStart(c);
workHourTime += (double) workMillis(c, origin) / (60 * 60 * 1000);
} else {// 如果当日不是工作日
// 定位到工作日 开始时间
locationWorkDate(c);
}
// 计算一共多少个工作日
double days = (workHourTime * 60 * 60 * 1000L) / getDayWorkMillis();
// 整数天
int day = (int) days;
// 小时数
double hours = (days - day) * getDayWorkMillis() / (60 * 60 * 1000);
for (int i = 0; i < day; i++) {
addWorkDay(c);
}
if (hours > 0) {
c.set(Calendar.HOUR_OF_DAY, dayWorkStart.get(Calendar.HOUR_OF_DAY) + (int) hours);
c.set(Calendar.MINUTE, (int) (dayWorkStart.get(Calendar.MINUTE) + (hours - (int) hours) * 60));
c.set(Calendar.SECOND, dayWorkStart.get(Calendar.SECOND));
}
return c.getTime();
}
/**
* 计算2个时间之间的工时(工作日 工作时)
*
* @param startDate
* @param endDate
* @return
* @throws ParseException
*/
public Double countWorkTime(Date startDate, Date endDate) throws ParseException {
Calendar startTime = Calendar.getInstance();
startTime.setTime(startDate);
Calendar endTime = Calendar.getInstance();
endTime.setTime(endDate);
BigDecimal hours = new BigDecimal((double) countTotalMillis(startTime, endTime) / (60 * 60 * 1000));
return hours.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
}
/**
* 计算2个日期之间的全部工时-毫秒数
*
* @param startTime
* @param endTime
* @return
* @throws ParseException
*/
private long countTotalMillis(Calendar startTime, Calendar endTime) throws ParseException {
long workMillis = 0;
if (!DateUtils.isSameDay(startTime, endTime)) {// 跨天
// 相差天数
Integer diffWorkDay = countWorkDayDiff(startTime, endTime);
workMillis += diffWorkDay * getDayWorkMillis();
// 加上起始天的工时
if (isWorkDay(startTime)) {
workMillis += workMillis(startTime, dayWorkEnd);
}
// 加上结束天的工时
if (isWorkDay(endTime)) {
workMillis += workMillis(dayWorkStart, endTime);
}
} else {// 同一天
if (isWorkDay(startTime)) {
workMillis += workMillis(startTime, endTime);
}
}
return workMillis;
}
/**
* 2个日期之间相差的天数(工作日)
*
* @param startTime
* @param endTime
* @return
*/
private Integer countWorkDayDiff(Calendar startTime, Calendar endTime) {
int workDays = 0;
Calendar start = (Calendar) startTime.clone();
start.add(Calendar.DAY_OF_YEAR, 1);
Calendar end = (Calendar) endTime.clone();
end.add(Calendar.DAY_OF_YEAR, -1);
if (start.before(end)) {
if (!sameMonth(start, end)) {// 不同月份
// 开始日期当月
workDays += workDayMonth(start, start.get(Calendar.DAY_OF_MONTH), start.getActualMaximum(Calendar.DATE));
start.add(Calendar.MONTH, 1);
start.set(Calendar.DAY_OF_MONTH, 1);
while (!sameMonth(start, end)) {
WorkCalendar current = findCalendar(start.get(Calendar.YEAR), start.get(Calendar.MONTH));
workDays += current.listDays().size();
start.add(Calendar.MONTH, 1);
}
// 截止日期当月
workDays += workDayMonth(start, 1, end.get(Calendar.DAY_OF_MONTH));
} else {// 同一个月份
workDays += workDayMonth(start, start.get(Calendar.DAY_OF_MONTH), end.get(Calendar.DAY_OF_MONTH));
}
}
return workDays < 0 ? 0 : workDays;
}
/**
* 计算当天2个时间之间的工时
*
* @param endTime
* @return
*/
private long workMillis(Calendar startTime, Calendar endTime) {
Calendar start = cloneCalendarAndSetDate(startTime);
Calendar end = cloneCalendarAndSetDate(endTime);
long millis = Math.min(dayWorkEnd.getTimeInMillis(), end.getTimeInMillis()) - Math.max(dayWorkStart.getTimeInMillis(), start.getTimeInMillis());
return millis > 0 ? millis : 0;
}
/**
* 一个工作日内工作的毫秒数
*
* @return
* @throws ParseException
*/
private long getDayWorkMillis() {
return dayWorkEnd.getTimeInMillis() - dayWorkStart.getTimeInMillis();
}
/**
* 计算当月工作日天数
*
* @param start
* @param end
* @return
*/
private int workDayMonth(Calendar c, Integer start, Integer end) {
int workDays = 0;
WorkCalendar month = findCalendar(c.get(Calendar.YEAR), c.get(Calendar.MONTH));
for (int i = start; i <= end; i++) {
if (month.listDays().contains(String.valueOf(i))) {
workDays += 1;
}
}
return workDays;
}
/**
* 查看某一天是否是工作日
*
* @param c
* @return
*/
public boolean isWorkDay(Calendar c) {
WorkCalendar workCalendar = findCalendar(c.get(Calendar.YEAR), c.get(Calendar.MONTH));
return workCalendar.listDays().contains(String.valueOf(c.get(Calendar.DAY_OF_MONTH)));
}
/**
* 设置比较日期为同一天
*
* @param time
*/
private Calendar cloneCalendarAndSetDate(Calendar time) {
Calendar c = (Calendar) time.clone();
c.set(dayWorkStart.get(Calendar.YEAR), dayWorkStart.get(Calendar.MONTH), dayWorkStart.get(Calendar.DAY_OF_MONTH));
return c;
}
/**
* 是否是同一个月
*
* @param startTime
* @param endTime
* @return
*/
private boolean sameMonth(Calendar startTime, Calendar endTime) {
return startTime.get(Calendar.YEAR) == endTime.get(Calendar.YEAR) && startTime.get(Calendar.MONTH) == endTime.get(Calendar.MONTH);
}
/**
* 将日期定位到下一个工作日 开始时间
*
* @param c
*/
private void locationWorkDate(Calendar c) {
if (!isWorkDay(c)) {
c.add(Calendar.DAY_OF_MONTH, 1);
locationWorkDate(c);
} else {
locationWorkStart(c);
}
}
/**
* 将时间定在当天 工作时开始时间
*
* @param c
*/
private void locationWorkStart(Calendar c) {
c.set(Calendar.HOUR_OF_DAY, dayWorkStart.get(Calendar.HOUR_OF_DAY));
c.set(Calendar.MINUTE, dayWorkStart.get(Calendar.MINUTE));
c.set(Calendar.SECOND, dayWorkStart.get(Calendar.SECOND));
}
/**
* 加一个工作日
*
* @param c
*/
private void addWorkDay(Calendar c) {
c.add(Calendar.DAY_OF_MONTH, 1);
if (!isWorkDay(c)) {
addWorkDay(c);
}
}
/**
* 查询工作日历
*
* @param year
* @param month
* @return
*/
private WorkCalendar findCalendar(Integer year, Integer month) {
month = month + 1;
String key = String.valueOf(year);
if (month < 10) {
key += "0";
}
key += month;
WorkCalendar calendar = workCalendar.get(key);
if (calendar == null) {
throw new RuntimeException(String.format("%s年%s月的工作日历不存在", year, month));
}
return calendar;
}
}
|
package com.tencent.mm.plugin.sns.model;
public final class am {
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.