text stringlengths 10 2.72M |
|---|
package common;
import raytracer.Ray;
import tuples.Point3f;
import tuples.Vector3f;
public class BoundingBox3D {
public final Vector3f[] bounds = new Vector3f[2];
public BoundingBox3D(float left, float right, float bottom, float top, float near, float far)
{
assert left <= right;
assert bottom <= top;
assert near <= far;
bounds[0] = new Vector3f(left, bottom, near);
bounds[1] = new Vector3f(right, top, far);
}
public BoundingBox3D(Vector3f lbn, Vector3f rtf)
{
bounds[0] = lbn;
bounds[1] = rtf;
}
public boolean isInside(Point3f p)
{
return bounds[0].x < p.x &&
bounds[1].x > p.x &&
bounds[0].y < p.y &&
bounds[1].y > p.y &&
bounds[0].z < p.z &&
bounds[1].z > p.z;
}
public boolean intersect(Ray r, double t0, double t1) {
float tmin, tmax, tymin, tymax, tzmin, tzmax;
tmin = (bounds[r.sign[0]].x - r.eye.x) * r.invDir.x;
tmax = (bounds[1-r.sign[0]].x - r.eye.x) * r.invDir.x;
tymin = (bounds[r.sign[1]].y - r.eye.y) * r.invDir.y;
tymax = (bounds[1-r.sign[1]].y - r.eye.y) * r.invDir.y;
if ( (tmin > tymax) || (tymin > tmax) )
return false;
if (tymin > tmin)
tmin = tymin;
if (tymax < tmax)
tmax = tymax;
tzmin = (bounds[r.sign[2]].z - r.eye.z) * r.invDir.z;
tzmax = (bounds[1-r.sign[2]].z - r.eye.z) * r.invDir.z;
if ( (tmin > tzmax) || (tzmin > tmax) )
return false;
if (tzmin > tmin)
tmin = tzmin;
if (tzmax < tmax)
tmax = tzmax;
return ( (tmin < t1) && (tmax > t0) );
//return true;
}
public static BoundingBox3D combine(BoundingBox3D box1, BoundingBox3D box2)
{
Vector3f lbn1 = box1.bounds[0];
Vector3f rtf1 = box1.bounds[1];
Vector3f lbn2 = box2.bounds[0];
Vector3f rtf2 = box2.bounds[1];
float left = Math.min(lbn1.x, lbn2.x);
float bottom = Math.min(lbn1.y, lbn2.y);
float near = Math.min(lbn1.z, lbn2.z);
float right = Math.max(rtf1.x, rtf2.x);
float top = Math.max(rtf1.y, rtf2.y);
float far = Math.max(rtf1.z, rtf2.z);
// System.out.println("Box 1: " + box1);
// System.out.println("Box 2: " + box2);
// System.out.println("Box : " + new BoundingBox3D(left, right, top, bottom, far, near));
return new BoundingBox3D(left, right, bottom, top, near, far);
}
public Point3f getCenter()
{
return new Point3f( (bounds[0].x+bounds[1].x)/2,
(bounds[0].y+bounds[1].y)/2,
(bounds[0].z+bounds[1].z)/2);
}
@Override
public String toString() {
return bounds[0] + " - " + bounds[1];
}
}
|
package com.gagetalk.gagetalkcustomer.activities_dialog;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import com.gagetalk.gagetalkcommon.network.NetworkPreference;
import com.gagetalk.gagetalkcommon.util.ImageDownloader;
import com.gagetalk.gagetalkcustomer.R;
import com.gagetalk.gagetalkcommon.api.Function;
import com.gagetalk.gagetalkcommon.constant.ConstValue;
import com.gagetalk.gagetalkcommon.constant.ReqUrl;
import com.gagetalk.gagetalkcommon.network.Network;
import com.gagetalk.gagetalkcommon.util.CustomToast;
import com.gagetalk.gagetalkcustomer.api.CustomerFunction;
import com.gagetalk.gagetalkcustomer.api.CustomerNetwork;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import org.json.JSONObject;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import cz.msebera.android.httpclient.Header;
/**
* Created by hyochan on 4/5/15.
*/
public class ProfileImgDialogActivity extends Activity
implements View.OnClickListener{
private static final String TAG = "ProfileImgDialogActivity";
private Activity activity;
private Context context;
private ImageView imgClose;
private ImageView imgProfile;
private Button btnUpdate;
private byte[] byteArray;
private String imgPath;
private Bitmap selectedImage;
// usage of intent onclick listener
private Intent intent;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.profile_img_dialog_activity);
activity = this;
context = this;
imgClose = (ImageView) findViewById(R.id.img_close);
imgProfile = (ImageView) findViewById(R.id.img_profile);
btnUpdate = (Button) findViewById(R.id.btn_update);
Bundle extras = getIntent().getExtras();
Bitmap bmp = extras.getParcelable("imagebitmap");
imgProfile.setImageBitmap(bmp);
imgClose.setOnClickListener(this);
imgProfile.setOnClickListener(this);
btnUpdate.setOnClickListener(this);
}
@Override
public void onBackPressed() {
finish();
overridePendingTransition(0, R.anim.fade_out);
super.onBackPressed();
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.img_close:
onBackPressed();
break;
case R.id.img_profile:
intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivityForResult(intent, ConstValue.REQUEST_PHOTO_ACTIVITY);
break;
case R.id.btn_update:
if(imgPath != null)
reqServerUploadImg();
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent imgReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imgReturnedIntent);
switch(requestCode) {
case ConstValue.REQUEST_PHOTO_ACTIVITY:
if(resultCode == RESULT_OK){
final Uri imageUri = imgReturnedIntent.getData();
imgPath = Function.getInstance(context).getRealPathFromURI(imageUri);
selectedImage = Function.getInstance(context).decodeSampledBitmapFromResource(
imgPath,
imgProfile.getWidth(),
imgProfile.getHeight()
);
imgProfile.setImageBitmap(selectedImage);
}
}
}
private void reqServerUploadImg(){
if(Network.getInstance(context).isNetworkAvailable()) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
/*
// Bitmap src = BitmapFactory.decodeFile("/sdcard/image.jpg", options);
int height=selectedImage.getHeight();
int width=selectedImage.getWidth();
int divideSize = 1;
if(height > 1000 || width > 1000){
divideSize = 2;
}
MyLog.i(TAG, "height : " + height + ", width : " + width);
*/
Bitmap resized = Bitmap.createScaledBitmap(selectedImage,
ConstValue.IMG_SIZE,
ConstValue.IMG_SIZE,
true);
resized.compress(Bitmap.CompressFormat.PNG, 100, stream);
byteArray = stream.toByteArray();
String url = ReqUrl.CustomerAccountTask + ReqUrl.UPDATE;
String imgName = CustomerFunction.getInstance(context).getCusID() + ".png";
RequestParams requestParams = new RequestParams();
requestParams.put("request_param", ConstValue.UPDATE_IMG);
requestParams.put("request_value", imgName);
requestParams.put("image", new ByteArrayInputStream(byteArray), imgName);
Network.getInstance(context).reqPost(activity, url, requestParams, new JsonHttpResponseHandler() {
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
super.onFailure(statusCode, headers, responseString, throwable);
Network.getInstance(context).toastErrorMsg(activity);
}
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
int resultCode = 0;
try {
resultCode = response.getInt("resultCode");
}catch (Exception e){
Function.getInstance(context).logErrorParsingJson(e);
}
int checkResponse = CustomerNetwork.getInstance(context).checkResponse(resultCode, true);
if(checkResponse == ConstValue.RESPONSE_NOT_LOGGED_IN){
onBackPressed();
}
else if (checkResponse == ConstValue.RESPONSE_SUCCESS) {
CustomToast.getInstance(context).createToast(
getResources().getString(R.string.upload_image_success)
);
Intent intent = new Intent();
intent.putExtra("imgArray", byteArray);
setResult(RESULT_OK, intent);
ImageDownloader.getInstance(context).updateCache(
NetworkPreference.getInstance(context).getServerUrl() + ":" + NetworkPreference.getInstance(context).getServerPort() +
"/images/customer/" + CustomerFunction.getInstance(context).getCusID() + ".png"
);
onBackPressed();
}
}
});
} else{
CustomToast.getInstance(context).
createToast(context.getResources().getString(R.string.network_error));
}
}
} |
package org.abrahamalarcon.datastream.service;
import org.abrahamalarcon.datastream.dao.WeatherDAO;
import org.abrahamalarcon.datastream.dom.DatastoreMessage;
import org.abrahamalarcon.datastream.dom.response.DatastoreResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.net.URISyntaxException;
@Service
public class DatastoreService extends BaseService
{
@Autowired WeatherDAO weatherDAO;
public DatastoreResponse pull(DatastoreMessage message, String event) throws URISyntaxException
{
DatastoreResponse response = new DatastoreResponse();
if(StringUtils.isBlank(event))
{
addFieldError(response, "event", "Event cannot be empty");
return response;
}
if(StringUtils.isBlank(message.getCity()))
{
addFieldError(response, "city", "City cannot be empty");
return response;
}
inputValidation(response, message, event);
if(!response.isFailure())
{
String url = "/" + event;
url += "/q";
if(message.getCountry() != null)
{
url+= "/" + message.getCountry();
}
if(message.getCity() != null)
{
url+= "/" + message.getCity();
}
url += ".json";
System.out.println("URL " + url);
response = weatherDAO.get(url);
}
return response;
}
void inputValidation(DatastoreResponse response, DatastoreMessage message, String event)
{
inputValidation(response, message, new String[] {"country", "city"});
inputValidation(response, new Object() { public String getEvent(){ return event; }} , new String[] {"event"});
}
}
|
package algorithms;
//Program to swap numbers without Using temp variable:
public class ExampleSwapNumbers {
public static void main(String[] args) {
int n1 = 3;
int n2 = 5;
System.out.println("Before: " + n1 + " - " + n2);
n1 = n1 + n2;
n2 = n1 - n2;
n1 = n1 - n2;
System.out.println("After: " + n1 + " - " + n2);
}
} |
package com.lihang.multithread.base;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.stream.Stream;
import static java.util.stream.Collectors.toList;
/**
* 多线程的基础实现
*
* @author lih
* @create 2019-04-23-15:32.
*/
public class ThreadBaseImpl {
/**
* 线程的基本实现1, 实现Runnable接口
* 1. 需要实例化一个Thread线程,然后传入我们的MyThread实例
* 2. 当传入一个Runnable target实例时 Thread实例的run将调用target.run()
*/
public static class MyThread implements Runnable {
@Override
public void run() {
System.out.println("线程1");
}
}
/**
* 线程的基本实现2:继承Thread
* 1. Thread本质是一个实现Runnable接口的实例,代表一个线程的实例
* 2. 启动线程是start()方法,该方法是native方法,它将启动一个新线程并执行run()方法
*/
public static class MyThread2 extends Thread {
@Override
public void run() {
System.out.println("线程2");
}
}
public static class MyCallback implements Callable {
private String name;
public MyCallback(String name) {
this.name = name;
}
@Override
public Object call() throws Exception {
return name;
}
}
public static void multi() {
ExecutorService pool = Executors.newFixedThreadPool(10);
List<Future> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Future submit = pool.submit(new MyCallback("MyCallback" + i));
list.add(submit);
}
pool.shutdown();
List<String> collect = list.stream().map(x -> {
try {
return x.get().toString();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return null;
}).collect(toList());
String join = String.join(",", collect);
System.out.println(join);
}
public static void main(String[] args) {
MyThread myThread = new MyThread();
new Thread(myThread).start();
MyThread2 myThread2 = new MyThread2();
myThread2.start();
multi();
}
}
|
package edu.westga.retirement.viewmodel;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import edu.westga.retirement.model.RetirementScenario;
import edu.westga.retirement.model.RetirementYear;
import edu.westga.retirement.model.SavingsYear;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ReadOnlyListProperty;
import javafx.beans.property.ReadOnlyListWrapper;
import javafx.beans.property.ReadOnlyStringProperty;
import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.collections.FXCollections;
/**
* View-Model class for the retirement applicaiont
* @author Kenji Okamoto
* @version 20151123
*
*/
public class RetirementViewModel {
/**
* Max number of presets that can be saved.
*/
public static final int MAX_NUMBER_PRESETS = 10;
private final IntegerProperty currentAge = new SimpleIntegerProperty();
private final IntegerProperty retireAge = new SimpleIntegerProperty();
private final IntegerProperty initialBalance = new SimpleIntegerProperty();
private final IntegerProperty annualContribution = new SimpleIntegerProperty();
private final DoubleProperty appreciationRate = new SimpleDoubleProperty();
private final IntegerProperty socialSecurity = new SimpleIntegerProperty();
private final IntegerProperty retirementSpending = new SimpleIntegerProperty();
private final ReadOnlyListWrapper<SavingsYear> savingsYearsList = new ReadOnlyListWrapper<SavingsYear>();
private final ReadOnlyListWrapper<RetirementYear> retirementYearsList = new ReadOnlyListWrapper<RetirementYear>();
private final ReadOnlyStringWrapper resultMessage = new ReadOnlyStringWrapper();
private RetirementScenario scenario;
private List<Map<String, Number>> presets;
/**
* Create a new View Model
*/
public RetirementViewModel() {
this.savingsYearsList.set(FXCollections.observableArrayList());
this.retirementYearsList.set(FXCollections.observableArrayList());
// Create list of presets and initializes with null values for each preset
this.presets = new ArrayList<Map<String, Number>>();
for (int index = 0; index < MAX_NUMBER_PRESETS; index++) {
this.presets.add(null);
}
}
/**
* Get the current age property
* @return The current age property
*/
public IntegerProperty currentAgeProperty() {
return this.currentAge;
}
/**
* Get the retire age property
* @return The retire age property
*/
public IntegerProperty retireAgeProperty() {
return this.retireAge;
}
/**
* Get the initialBalance property. This is the value of the present retirement savings
* @return The initialBalance property
*/
public IntegerProperty startBalanceProperty() {
return this.initialBalance;
}
/**
* Get the annualContribution property. This is how much is contributed to retirement annualy.
* @return The annualContribution property
*/
public IntegerProperty annualContributionProperty() {
return this.annualContribution;
}
/**
* Get the appreciationRate property. This is the annual percent growth of retirement assets
* @return The appreciationRate property
*/
public DoubleProperty returnRateProperty() {
return this.appreciationRate;
}
/**
* Get the socialSecurity property. This is the expected annual social security income
* @return the socialSecurity property
*/
public IntegerProperty socialSecurityProperty() {
return this.socialSecurity;
}
/**
* Get the retirementSpending property. This the planned annual spending in retirement
* @return the retirementSpending property
*/
public IntegerProperty retirementSpendingProperty() {
return this.retirementSpending;
}
/**
* Get the resultMessage property.
* @return the resultMessage property
*/
public ReadOnlyStringProperty getResultMessageProperty() {
return this.resultMessage.getReadOnlyProperty();
}
/**
* Get a list of the SavingsYears for the scenario
* @return A list of the SavingsYears objects for the scenario
*/
public ReadOnlyListProperty<SavingsYear> getSavingsYearsList() {
return this.savingsYearsList.getReadOnlyProperty();
}
/**
* Get a list of the RetirementYears for the scenario
* @return A list of the RetirementYears objects for the scenario
*/
public ReadOnlyListProperty<RetirementYear> getRetirementYearsList() {
return this.retirementYearsList.getReadOnlyProperty();
}
/**
* Run a retirement scenario using the current field values
*/
public void runScenario() {
int age = this.currentAge.intValue();
int retireAge = this.retireAge.intValue();
int initialBalance = this.initialBalance.intValue();
int contribution = this.annualContribution.intValue();
double appreciationRate = this.appreciationRate.doubleValue();
int socialSecurity = this.socialSecurity.intValue();
int retirementSpending = this.retirementSpending.intValue();
this.scenario = new RetirementScenario(age, retireAge, initialBalance, contribution,
appreciationRate, socialSecurity, retirementSpending);
List<SavingsYear> savingYearsData = this.scenario.getSavingsYears();
this.savingsYearsList.set(FXCollections.observableArrayList(savingYearsData));
List<RetirementYear> retirementYearsData = this.scenario.getRetirementYears();
this.retirementYearsList.set(FXCollections.observableArrayList(retirementYearsData));
this.setResultMessage();
}
/**
* Save the results of the current scenario to a file in csv form
* @param outFile The file to save the csv data to
* Precondition: outFile != null
*/
public void saveToFile(File outFile) {
if (outFile == null) {
throw new IllegalArgumentException("outFile cannot be null");
}
FileWriter writer;
try {
writer = new FileWriter(outFile);
writer.write(this.scenario.toString());
writer.close();
} catch (IOException exceptio) {
this.resultMessage.set("Error writing data to the selected file");
return;
}
this.resultMessage.set("Scenario saved to " + outFile.getName());
}
/**
* Save the current form fields to a preset that can be recalled later
* @param presetNumber The preset number to save to
* Precondition: preset number is between 1 and {@value #MAX_NUMBER_PRESETS}
*/
public void setPreset(int presetNumber) {
if (presetNumber > RetirementViewModel.MAX_NUMBER_PRESETS
|| presetNumber < 1) {
throw new IllegalArgumentException("Preset number must be between 1 and " + RetirementViewModel.MAX_NUMBER_PRESETS);
}
Map<String, Number> preset = new HashMap<String, Number>();
preset.put("currentAge", this.currentAge.getValue());
preset.put("retireAge", this.retireAge.getValue());
preset.put("initialBalance", this.initialBalance.getValue());
preset.put("annualContribution", this.annualContribution.getValue());
preset.put("appreciationRate", this.appreciationRate.getValue());
preset.put("socialSecurity", this.socialSecurity.getValue());
preset.put("retirementSpending", this.retirementSpending.getValue());
this.presets.set(presetNumber - 1, preset);
this.resultMessage.set("Current scenario saved");
}
/**
* Set the scenario parameters to those of a saved preset
* @param presetNumber The preset number to get the parameters from.
* @return false when the preset at the given number has been set, otherwise true
* Precondition: preset number is between 1 and {@value #MAX_NUMBER_PRESETS}
*/
public boolean recallPreset(int presetNumber) {
if (presetNumber > RetirementViewModel.MAX_NUMBER_PRESETS
|| presetNumber < 1) {
throw new IllegalArgumentException("Preset number must be between 1 and " + RetirementViewModel.MAX_NUMBER_PRESETS);
}
Map<String, Number> preset = this.presets.get(presetNumber - 1);
if (preset == null) {
return false;
}
this.currentAge.setValue(preset.get("currentAge"));
this.retireAge.setValue(preset.get("retireAge"));
this.initialBalance.setValue(preset.get("initialBalance"));
this.annualContribution.setValue(preset.get("annualContribution"));
this.appreciationRate.setValue(preset.get("appreciationRate"));
this.socialSecurity.setValue(preset.get("socialSecurity"));
this.retirementSpending.setValue(preset.get("retirementSpending"));
this.runScenario();
this.resultMessage.set("Saved Scenario " + presetNumber + " recalled");
return true;
}
private void setResultMessage() {
int age = this.scenario.getAgeRetirementLastsTo();
String message;
if (age == -1) {
message = "Congragulations. You will still have savings at age " + RetirementScenario.SCENARIO_STOP_AGE;
} else {
message = "You will have enough retirement savings to last to age " + age;
}
this.resultMessage.set(message);
}
}
|
package br.com.transactions.domain.utils;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import br.com.transactions.domain.utils.exception.CardHolderNotFoundException;
@SpringBootTest
@ActiveProfiles("test")
public class CardHolderTest {
@Test
public void shouldReturnCardHolder() {
CardHolder mastercard = CardHolder.getCardHolder("mastercard");
CardHolder elo = CardHolder.getCardHolder("elo");
CardHolder amex = CardHolder.getCardHolder("amex");
CardHolder hipercard = CardHolder.getCardHolder("hipercard");
assertEquals("MASTERCARD", mastercard.name());
assertEquals("ELO", elo.name());
assertEquals("AMEX", amex.name());
assertEquals("HIPERCARD", hipercard.name());
}
@Test(expected = CardHolderNotFoundException.class)
public void shouldReturnCardHolderNotFoundException() {
CardHolder.getCardHolder("bandeira");
}
}
|
package com.aisino.invoice.pygl.po;
import java.util.Date;
/**
* @ClassName: FwkpFpjkc
* @Description:
* @author: ZZc
* @date: 2016年10月10日 下午8:11:29
* @Copyright: 2016 航天信息股份有限公司-版权所有
*
*/
public class FwkpFpjkc {
private int xh;
private String qysb;
private Integer id;
private String xfsh;
private Integer kpjh;
private Integer zdhm;
private Integer fpzl;
private String fpdm;
private Long qshm;
private Long fpfs;
private Long syhm;
private Long syfs;
private Date fssj;
private Date czsj;
private Integer sdzt;
private Integer xjbz;
private String jym;
private String fpxe;
private String qymc;
private String zdmc;
private Integer jsponline;
private String status;//申领状态状态
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Integer getJsponline() {
return jsponline;
}
public void setJsponline(Integer jsponline) {
this.jsponline = jsponline;
}
public String getZdmc() {
return zdmc;
}
public void setZdmc(String zdmc) {
this.zdmc = zdmc;
}
public String getQymc() {
return qymc;
}
public void setQymc(String qymc) {
this.qymc = qymc;
}
public int getXh() {
return xh;
}
public void setXh(int xh) {
this.xh = xh;
}
public String getQysb() {
return qysb;
}
public void setQysb(String qysb) {
this.qysb = qysb;
}
public String getFpxe() {
return fpxe;
}
public void setFpxe(String fpxe) {
this.fpxe = fpxe;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getXfsh() {
return xfsh;
}
public void setXfsh(String xfsh) {
this.xfsh = xfsh == null ? null : xfsh.trim();
}
public Integer getKpjh() {
return kpjh;
}
public void setKpjh(Integer kpjh) {
this.kpjh = kpjh;
}
public Integer getZdhm() {
return zdhm;
}
public void setZdhm(Integer zdhm) {
this.zdhm = zdhm;
}
public Integer getFpzl() {
return fpzl;
}
public void setFpzl(Integer fpzl) {
this.fpzl = fpzl;
}
public String getFpdm() {
return fpdm;
}
public void setFpdm(String fpdm) {
this.fpdm = fpdm == null ? null : fpdm.trim();
}
public Long getQshm() {
return qshm;
}
public void setQshm(Long qshm) {
this.qshm = qshm;
}
public Long getFpfs() {
return fpfs;
}
public void setFpfs(Long fpfs) {
this.fpfs = fpfs;
}
public Long getSyhm() {
return syhm;
}
public void setSyhm(Long syhm) {
this.syhm = syhm;
}
public Long getSyfs() {
return syfs;
}
public void setSyfs(Long syfs) {
this.syfs = syfs;
}
public Date getFssj() {
return fssj;
}
public void setFssj(Date fssj) {
this.fssj = fssj;
}
public Date getCzsj() {
return czsj;
}
public void setCzsj(Date czsj) {
this.czsj = czsj;
}
public Integer getSdzt() {
return sdzt;
}
public void setSdzt(Integer sdzt) {
this.sdzt = sdzt;
}
public Integer getXjbz() {
return xjbz;
}
public void setXjbz(Integer xjbz) {
this.xjbz = xjbz;
}
public String getJym() {
return jym;
}
public void setJym(String jym) {
this.jym = jym == null ? null : jym.trim();
}
@Override
public String toString() {
return "<fwkp_fpjkc id='" + id + "', xfsh='" + xfsh + "', kpjh='" + kpjh
+ "', zdhm='" + zdhm + "', fpzl='" + fpzl + "', fpdm='" + fpdm
+ "', qshm='" + qshm + "', fpfs='" + fpfs + "', syhm='" + syhm
+ "', syfs='" + syfs + "', fssj='" + fssj + "', czsj='" + czsj
+ "', sdzt='" + sdzt + "', xjbz='" + xjbz + "'/>";
}
} |
package com.zjf.myself.codebase.activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import com.zjf.myself.codebase.R;
import com.zjf.myself.codebase.activity.AlgorithmList.DigitalGapAct;
import com.zjf.myself.codebase.activity.AlgorithmList.ListSortAct;
import com.zjf.myself.codebase.activity.AlgorithmList.Person1000Act;
import com.zjf.myself.codebase.activity.AlgorithmList.WeekStepSumAct;
import com.zjf.myself.codebase.adapter.CommonAdaper;
import com.zjf.myself.codebase.adapter.ViewHolder;
import com.zjf.myself.codebase.model.BasicListViewInfo;
import java.util.ArrayList;
import java.util.List;
/**
* <pre>
* author : ZouJianFeng
* e-mail :
* time : 2017/05/16
* desc :
* version: 1.0
* </pre>
*/
public class ListAlgorithmLibraryAct extends BaseAct{
private ListView projectPageList;
private BasicListViewAdapter adaper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.win_exercise_library_list);
projectPageList = (ListView) findViewById(R.id.lvExerciseLibrary);
adaper=new BasicListViewAdapter(this,null,R.layout.item_main);
projectPageList.setAdapter(adaper);
projectPageList.setOnItemClickListener(onItemClickListener);
List<BasicListViewInfo> menuItemList=new ArrayList<BasicListViewInfo>();
menuItemList.add(new BasicListViewInfo(0,"本周步数","",new Intent(this,WeekStepSumAct.class)));
menuItemList.add(new BasicListViewInfo(0,"1000人练习","",new Intent(this,Person1000Act.class)));
menuItemList.add(new BasicListViewInfo(0,"数字间隔","",new Intent(this,DigitalGapAct.class)));
menuItemList.add(new BasicListViewInfo(0,"集合排序","",new Intent(this,ListSortAct.class)));
adaper.addList(menuItemList,true);
}
private AdapterView.OnItemClickListener onItemClickListener=new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
BasicListViewInfo item= (BasicListViewInfo) adapterView.getAdapter().getItem(i);
Intent intent = new Intent(item.getIt());
startActivity(intent);
// Toast.makeText(ListExerciseLibraryAct.this,"您点击了"+item.getTxtLeft(),Toast.LENGTH_SHORT).show();
}
};
static class BasicListViewAdapter extends CommonAdaper {
public BasicListViewAdapter(Context context, List list, int itemLayoutId) {
super(context, list, itemLayoutId);
}
@Override
public void convert(ViewHolder holder, Object item, int position) {
BasicListViewInfo menuItem= (BasicListViewInfo) item;
holder.setImageResource(R.id.imgleft, menuItem.getImgLeft());
holder.setText(R.id.txtLeft,menuItem.getTxtLeft());
holder.setText(R.id.txtRight, menuItem.getTxtRight());
}
}
}
|
package org.jewelry.hashing;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.security.NoSuchAlgorithmException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.*;
import java.util.Arrays;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import org.apache.commons.codec.binary.Base64;
import grandcentral.auth.tokenAuth;
//Owasp stands for one way authentication password salt
public class Owasp {
private static final int ITERATION_NUMBER = 1000;
public Owasp(){
}
/**
* Inserts a new user in the database
* @param con Connection An open connection to a databse
* @param login String The login of the user
* @param password String The password of the user
* @return boolean Returns true if the login and password are ok (not null and length(login)<=100
* @throws SQLException If the database is unavailable
* @throws NoSuchAlgorithmException If the algorithm SHA-1 or the SecureRandom is not supported by the JVM
*/
public boolean createUser(Connection con, String login, String password, String email, String firstname, String lastname, Date dob) throws SQLException, NoSuchAlgorithmException{
PreparedStatement ps =null;
PreparedStatement ps1 =null;
PreparedStatement ps2 =null;
ResultSet rs = null;
try{
if (login!=null&&password!=null&&login.length()<=100){
// Uses a secure Random not a simple Random
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
// Salt generation 64 bits long
byte[] bSalt = new byte[8];
random.nextBytes(bSalt);
// Digest computation
byte[] bDigest = null;
try {
bDigest = getHash(ITERATION_NUMBER,password,bSalt);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String sDigest = null;
try {
sDigest = byteToBase64(bDigest);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String sSalt = null;
try {
sSalt = byteToBase64(bSalt);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ps=con.prepareStatement("INSERT INTO CUSTOMERS (userid,password,email,firstname,lastname,dob,salt) values (?,?,?,?,?,?,?)");
ps.setString(1, login);
ps.setString(2, sDigest);
ps.setString(3, email);
ps.setString(4, firstname);
ps.setString(5, lastname);
ps.setDate(6, dob);
ps.setString(7, sSalt);
ps.executeUpdate();
ps1 = con.prepareStatement("SELECT ID FROM CUSTOMERS WHERE USERID=?");
ps1.setString(1, login);
rs=ps1.executeQuery();
int id = 0;
if(rs.next()){
id = rs.getInt("ID");
}
ps2=con.prepareStatement("INSERT INTO USER_ROLE (id,userid,role) values (?,?,?) ");
ps2.setInt(1, id);
ps2.setString(2, login);
ps2.setString(3, "customer");
ps2.executeUpdate();
return true;
}else{
return false;
}
}finally{
close(ps);
con.close();
}
}
/**
* Authenticates the user with a given login and password
* If password and/or login is null then always returns false.
* If the user does not exist in the database returns false.
* @param con Connection An open connection to a databse
* @param login String The login of the user
* @param password String The password of the user
* @return boolean Returns true if the user is authenticated, false otherwise
* @throws SQLException If the database is inconsistent or unavailable (
* (Two users with the same login, salt or digested password altered etc.)
* @throws NoSuchAlgorithmException If the algorithm SHA-1 is not supported by the JVM
*/
public boolean authenticateUser(String login, String password, Connection con) throws SQLException, NoSuchAlgorithmException{
boolean authenticated = false;
PreparedStatement ps=null;
ResultSet rs=null;
try{
boolean userExist = true;
//INPUT VALIDATION
if(login==null||password==null){
userExist = false;
login ="";
password="";
}
ps = con.prepareStatement("SELECT PASSWORD, SALT FROM CUSTOMERS WHERE USERID=?");
ps.setString(1, login);
rs=ps.executeQuery();
String digest, salt;
if(rs.next()){
digest = rs.getString("PASSWORD");
salt = rs.getString("SALT");
//DATABASE VALIDATION
if(digest == null || salt == null){
throw new SQLException("Database inconsistant Salt or Digested Password altered");
}
//Should not append, because login is the primary key
if(rs.next()){
throw new SQLException("Database inconsistent two CREDENTIALS with the same LOGIN");
}
}else{// TIME RESISTANT ATTACK (Even if the user does not exist the
// Computation time is equal to the time needed for a legitimate user
digest = "000000000000000000000000000=";
salt = "00000000000=";
userExist = false;
}
byte[] bDigest = null;
try {
bDigest = base64ToByte(digest);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] bSalt = null;
try {
bSalt = base64ToByte(salt);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//COMPUTE THE NEW DIGEST
byte[] proposedDigest = getHash(ITERATION_NUMBER, password, bSalt);
return Arrays.equals(proposedDigest, bDigest) && userExist;
}catch(IOException ex){
throw new SQLException("Database inconsistent Salt or Digested Password altered");
}
finally{
close(rs);
close(ps);
con.close();
}
}
public void close(ResultSet rs){
if(rs!=null)
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void close(Statement ps){
if(ps!=null)
try{
ps.close();
} catch(SQLException e){
e.printStackTrace();
}
}
/**
* From a base 64 representation, returns the corresponding byte[]
* @param data String The base64 representation
* @return byte[]
* @throws IOException
* The commented code is the Base64 implementation of Sun's Base64
* We are using apache commons codec
*/
public static byte[] base64ToByte(String data) throws Exception{
//BASE64Decoder decoder = new BASE64Decoder();
//return decoder.decodeBuffer(data);
Base64 decoder = new Base64();
return decoder.decode(data.getBytes());
}
/**
* From a byte[] returns a base 64 representation
* @param data byte[]
* @return String
* @throws IOException
*/
public static String byteToBase64(byte[] data) throws Exception{
Base64 encoder = new Base64();
return new String(encoder.encode(data));
}
/**
* From a password, a number of iterations and a salt,
* returns the corresponding digest
* @param iterationNb int The number of iterations of the algorithm
* @param password String The password to encrypt
* @param salt byte[] The salt
* @return byte[] The digested password
* @throws NoSuchAlgorithmException If the algorithm doesn't exist
* @throws UnsupportedEncodingException
*/
public byte[] getHash(int iterationNb, String password, byte[] salt) throws NoSuchAlgorithmException, UnsupportedEncodingException {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.reset();
digest.update(salt);
byte[] input = digest.digest(password.getBytes("UTF-8"));
for (int i = 0; i < iterationNb; i++) {
digest.reset();
input = digest.digest(input);
}
return input;
}
public static void main(String[] args){
String driver = "org.postgresql.Driver";
try{
Class.forName(driver);
}catch(ClassNotFoundException e){
System.out.println("JDBC Driver class not loaded");
e.printStackTrace();
return;
}
System.out.println("PostgreSQL JDBC Driver Registered!");
String host = "localhost";
String dbName = "new_demo";
int port = 5432;
String postgresURL = "jdbc:postgresql://"+host+":"+port+"/"+dbName;
String usrName = "postgres";
String pwd="postgres";
Connection connection = null;
try{
connection = DriverManager.getConnection(postgresURL,usrName,pwd);
}catch(SQLException e){
System.out.println("Connection failed to the DB");
e.printStackTrace();
return;
}
if (connection != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
}
}
|
public class arrayisstored {
public static void increment(int nums[])
{
nums=new int[5];
for(int i=0;i<nums.length;i++)
{
nums[i]++;
System.out.print(nums);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int arr[]= {3,23,4,13,4,233};
increment(arr);
for(int i=0;i<arr.length;i++)
{
System.out.println(arr);
}
}
}
|
package xml;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
import java.util.ArrayList;
import java.util.List;
@XStreamAlias("Mes")
public class Mes {
private String nomeMes;
@XStreamImplicit
private List<Dias> dias = new ArrayList<>();
public void setNomeMes(String nomeMes) {
this.nomeMes = nomeMes;
}
public void addDias(Dias dias){
this.dias.add(dias);
}
}
|
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class MSTTest {
private static MST mst;static int graph[][];
@BeforeClass
public static void setUpBeforeClass() throws Exception {
mst = new MST();}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Before
public void setUp() throws Exception {
graph = new int[][] {{0, 2, 0, 6, 0}, {2, 0, 3, 8, 5}, {0, 3, 0, 0, 7}, {6, 8, 0, 0, 9}, {0, 5, 7, 9, 0}};
}
@After
public void tearDown() throws Exception {
}
@Test
public void testPrimMST() {
mst.primMST(graph);
}
}
|
package com.dubboagent.context.trace;
/**
* @author chao.cheng
*/
public interface AbstractTrace {
/**
* 查看栈顶span
*
* @return
*/
public AbstractSpan peekSpan();
/**
* 将最新span压入栈顶
*
* @param span
*/
public void pushSpan(AbstractSpan span);
/**
* 获取traceId
*
* @return
*/
public String getTraceId();
/**
* 设置traceId
*
* @param traceId
*/
public void setTraceId(String traceId);
/**
* 以字符串的方式获取spanid列表
* 用"-"线分隔
*
* @return
*/
public String getSpanListStr();
}
|
import java.util.Scanner;
class Anagram
{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter 1st word: ");
String a = in.nextLine();
System.out.print("Enter 2nd word: ");
String b = in.nextLine();
a = a.replaceAll(" ", "");
b = b.replaceAll(" ", "");
a = a.toUpperCase();
b = b.toUpperCase();
char aa[];
aa = a.toCharArray();
for(int i = 0; i < a.length(); i++)
{
b = b.replaceAll(String.valueOf(aa[i]), "");
}
if(b.length() == 0)
System.out.print("Strings are Anagrams");
else
System.out.print("These are NOT Anagrams");
}
} |
package com.dta.test;
class TpJava03 {
public static void main(String args[]){
byte x = 10;
System.out.println(x);
x+= 1000;
System.out.println(x);
}
}
|
package org.restapi.com.messenger.model;
import java.util.Date;
public class Profile {
private long id;
private String profileName;
private String firtName;
private String lastName;
private Date created;
public Profile(long id, String profileName, String firtName, String lastName) {
super();
this.id = id;
this.profileName = profileName;
this.firtName = firtName;
this.lastName = lastName;
created = new Date();
}
public Profile() {
super();
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getProfileName() {
return profileName;
}
public void setProfileName(String profileName) {
this.profileName = profileName;
}
public String getFirtName() {
return firtName;
}
public void setFirtName(String firtName) {
this.firtName = firtName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
}
|
package com.tomaszdebski.decerto.exception;
public class QuoteNotFoundException extends RuntimeException{
public QuoteNotFoundException(Long id) {
super("Could not find quote " + id);
}
}
|
package com.bridgelabz.censusAnalyser.censusADAPTER;
import com.bridgelabz.censusAnalyser.censusDAO.CensusAnalyserDAO;
import com.bridgelabz.censusAnalyser.censusDTO.IndianStateCensusData;
import com.bridgelabz.censusAnalyser.censusDTO.USCensusPOJO;
import com.bridgelabz.censusAnalyser.exception.CensusAnalyserException;
import com.bridgelabz.censusAnalyser.service.CSV_Interface;
import com.bridgelabz.censusAnalyser.service.CsvBuilderFactory;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.stream.StreamSupport;
public abstract class CensusAdepter {
Map<String, CensusAnalyserDAO> csvCensusMap = new HashMap<>();
public abstract Map<String, CensusAnalyserDAO> loadCensusData(String... csvFilePath) throws CensusAnalyserException;
public <E> Map<String, CensusAnalyserDAO> loadCensusData(Class<E> censusCsvClass, String... csvFilePath)
throws CensusAnalyserException {
Map<String, CensusAnalyserDAO> csvCensusMap = new HashMap<>();
try (Reader reader = Files.newBufferedReader(Paths.get(csvFilePath[0]))) {
CSV_Interface csvBuilder = CsvBuilderFactory.createCsvInterface();
Iterator<E> stateCensusIterator = csvBuilder.getCSVfileIterator(reader, censusCsvClass);
Iterable<E> csvIterable = () -> stateCensusIterator;
if (censusCsvClass.getName().contains("IndianStateCensusData")) {
StreamSupport.stream(csvIterable.spliterator(), false)
.map(IndianStateCensusData.class::cast)
.forEach(censusCSV -> csvCensusMap.put(censusCSV.getState(), new CensusAnalyserDAO(censusCSV)));
return csvCensusMap;
} else if (censusCsvClass.getName().contains("USCensusPOJO")) {
StreamSupport.stream(csvIterable.spliterator(), false)
.map(USCensusPOJO.class::cast)
.forEach(censusCSV -> csvCensusMap.put(censusCSV.getState(), new CensusAnalyserDAO(censusCSV)));
return csvCensusMap;
} else {
throw new CensusAnalyserException(CensusAnalyserException.MyException_Type.
NO_SUCH_COUNTRY, "Wrong country name");
}
} catch (NoSuchFileException e) {
throw new CensusAnalyserException(CensusAnalyserException.MyException_Type.
FILE_NOT_FOUND, "Enter a right file name and type");
} catch (RuntimeException e) {
throw new CensusAnalyserException(CensusAnalyserException.MyException_Type.
DELIMITER_INCORECT,"Check delimetr and header");
} catch (Exception e) {
e.printStackTrace();
}
return csvCensusMap;
}
} |
/*
* Copyright 1999-2017 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.druid.sql.dialect.oscar.visitor;
import com.alibaba.druid.DbType;
import com.alibaba.druid.sql.ast.*;
import com.alibaba.druid.sql.ast.expr.*;
import com.alibaba.druid.sql.ast.statement.*;
import com.alibaba.druid.sql.dialect.oracle.ast.clause.*;
import com.alibaba.druid.sql.dialect.oracle.ast.expr.*;
import com.alibaba.druid.sql.dialect.oracle.ast.stmt.*;
import com.alibaba.druid.sql.dialect.oscar.ast.stmt.*;
import java.util.List;
public class OscarPermissionOutputVisitor extends OscarOutputVisitor {
public OscarPermissionOutputVisitor(Appendable appender) {
super(appender);
this.dbType = DbType.oscar;
}
public OscarPermissionOutputVisitor(Appendable appender, boolean parameterized) {
super(appender, parameterized);
this.dbType = DbType.oscar;
}
@Override
public boolean visit(SQLExprTableSource x) {
String catalog = x.getCatalog();
String schema = x.getSchema();
String tableName = x.getTableName();
List<SQLName> columns1 = x.getColumns();
int sourceColumn = x.getSourceColumn();
//SQLExpr sqlExpr = SQLUtils.toSQLExpr("id=3", dbType);
print(" (");
print0(ucase ? "SELECT " : "select ");
print('*');
print0(ucase ? " FROM " : " from ");
printTableSourceExpr(x.getExpr());
//print0(ucase ? " WHERE " : " where ");
//printExpr(sqlExpr);
print(')');
final SQLTableSampling sampling = x.getSampling();
if (sampling != null) {
print(' ');
sampling.accept(this);
}
String alias = x.getAlias();
List<SQLName> columns = x.getColumnsDirect();
if (alias != null) {
print(' ');
if (columns != null && columns.size() > 0) {
print0(ucase ? " AS " : " as ");
}
print0(alias);
}
if (columns != null && columns.size() > 0) {
print(" (");
printAndAccept(columns, ", ");
print(')');
}
for (int i = 0; i < x.getHintsSize(); ++i) {
print(' ');
x.getHints().get(i).accept(this);
}
if (x.getPartitionSize() > 0) {
print0(ucase ? " PARTITION (" : " partition (");
printlnAndAccept(x.getPartitions(), ", ");
print(')');
}
return false;
}
}
|
package org.vincent.chain.test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.BinaryOperator;
import java.util.stream.Stream;
/**
* @author PengRong
* @package org.vincent.chain.test
* @ClassName MainTest.java
* @date 2019/6/30 - 11:42
* @ProjectName JavaAopLearning
* @Description: TODO
*/
public class MainTest {
public static void main(String[] args) {
/**
* 构建一个固定顺序的链 【终端记录——邮件记录——文件记录】
* consoleLogger:终端记录,可以打印所有等级的log信息
* emailLogger:邮件记录,打印功能性问题 FUNCTIONAL_MESSAGE 和 FUNCTIONAL_ERROR 两个等级的信息
* fileLogger:文件记录,打印 WARNING 和 ERROR 两个等级信息
*/
/**
* 创建所有日志级别的日志记录器
*/
/* Logger logger = LoggerManager.consoleLogger(LogLevel.all());
logger = logger.appendNext(LoggerManager.emailLogger(LogLevel.FUNCTIONAL_MESSAGE, LogLevel.FUNCTIONAL_ERROR));
logger = logger.appendNext(LoggerManager.fileLogger(LogLevel.WARNING, LogLevel.ERROR));
// consoleLogger 可以记录所有 level 的信息
logger.message("进入到订单流程,接收到参数,参数内容为 XXOO .", LogLevel.DEBUG);
logger.message("订单记录生成.", LogLevel.INFO);
// consoleLogger 处理完,fileLogger 要继续处理
logger.message("订单详细地址缺失", LogLevel.WARNING);
logger.message("订单省市区信息缺失", LogLevel.ERROR);
// consoleLogger 处理完,emailLogger 继续处理
logger.message("订单短信通知服务失败", LogLevel.FUNCTIONAL_ERROR);
logger.message("订单已派送.", LogLevel.FUNCTIONAL_MESSAGE);*/
/**
* Stream.reduce() with Identity, Accumulator and Combiner 只有用于并发流中才有意义
* Stream是支持并发操作的,为了避免竞争,对于reduce线程都会有独立的result,
* 第三個參數 combiner的作用在于合并每个线程的result得到最终结果。这也说明了了第三个函数参数的数据类型必须为返回数据类型了。
*/
System.out.println("------------------");
ArrayList<Integer> accResult_ = Stream.of(1, 2, 3, 4)
.parallel() // 必须开始并发流才有效果
.reduce(new ArrayList<>(),
new BiFunction<ArrayList<Integer>, Integer, ArrayList<Integer>>() {
@Override
public ArrayList<Integer> apply(ArrayList<Integer> acc, Integer item) {
acc.add(item);
System.out.println("item: " + item);
System.out.println("acc+ : " + acc);
System.out.println("BiFunction");
return acc;
}
}, new BinaryOperator<ArrayList<Integer>>() {
@Override
public ArrayList<Integer> apply(ArrayList<Integer> acc, ArrayList<Integer> item) {
System.out.println("BinaryOperator GG");
acc.addAll(item);
System.out.println("item: GG" + item);
System.out.println("acc+ : GG" + acc);
System.out.println("--------GG");
return acc;
}
});
System.out.println("------------------");
System.out.println("pr accResult_: " + accResult_);
System.out.println("------------------");
// 串行操作 和两个 参数的执行结果一致
List<Integer> list = Arrays.asList(3, 2, 4, 1);
System.out.println(list.stream().reduce(100
, (acc, tmp) -> acc + tmp
, (a, b) -> a + b).intValue()); // out ==> 110
System.out.println("------------------");
// 并行操作
System.out.println(list.stream().parallel().reduce(100
, (acc, tmp) -> acc + tmp
, (a, b) -> a + b).intValue()); // out ==> 410
System.out.println("------------------");
/**
* 分析:
* list集合中四个值并行执行, 分别与初始值100相加后, 再进行合并操作, 即:
* 1)3+100=103, 2+100=102, 4+100=104, 1+100=101
* 2)103+102+104+101=410
*/
List<Integer> list2 = Arrays.asList(5, 6, 7);
/** 并行操作*/
int res = list2.parallelStream().reduce(2, (s1, s2) -> s1 * s2, (p, q) -> p * q);
System.out.println("res1 =" + res);
/** 串行操作 */
System.out.println("res2 =" + list2.stream().reduce(2, (s1, s2) -> s1 * s2, (p, q) -> p * q));
/** 并行操作 每个元素 和 identity =1 相乘,然后累加 =18 (1*5 + 6*1 + 7*1 )*/
res = list2.parallelStream().reduce(2, (s1, s2) -> s1 * s2, (p, q) -> p + q);
System.out.println("res3 =" + res);
/** 串行操作 */
System.out.println("res4 =" + list2.stream().reduce(1, (s1, s2) -> s1 * s2, (p, q) -> p + q));
System.out.println("----------------------------------");
while (true){
System.out.println("123");
}
}
}
|
package android.content;
import java.util.HashMap;
public final class ContentValues implements android.os.Parcelable {
private HashMap<String, Object> map = new HashMap<String, Object>();
public ContentValues() {
}
public ContentValues(int size) {
}
public ContentValues(android.content.ContentValues from) {
}
public boolean equals(java.lang.Object object) {
throw new RuntimeException("Stub!");
}
public int hashCode() {
return map.hashCode();
}
public void put(java.lang.String key, java.lang.String value) {
map.put(key, value);
}
public void putAll(android.content.ContentValues other) {
map.putAll(getMap());
}
public void put(java.lang.String key, java.lang.Byte value) {
map.put(key, value);
}
public void put(java.lang.String key, java.lang.Short value) {
map.put(key, value);
}
public void put(java.lang.String key, java.lang.Integer value) {
map.put(key, value);
}
public void put(java.lang.String key, java.lang.Long value) {
map.put(key, value);
}
public void put(java.lang.String key, java.lang.Float value) {
map.put(key, value);
}
public void put(java.lang.String key, java.lang.Double value) {
map.put(key, value);
}
public void put(java.lang.String key, java.lang.Boolean value) {
map.put(key, value);
}
public void put(java.lang.String key, byte[] value) {
map.put(key, value);
}
public void putNull(java.lang.String key) {
map.put(key, null);
}
public int size() {
return map.size();
}
public void remove(java.lang.String key) {
map.remove(key);
}
public void clear() {
map.clear();
}
public boolean containsKey(java.lang.String key) {
return map.containsKey(key);
}
public java.lang.Object get(java.lang.String key) {
return map.get(key);
}
public java.lang.String getAsString(java.lang.String key) {
return (String)map.get(key);
}
public java.lang.Long getAsLong(java.lang.String key) {
return (Long)map.get(key);
}
public java.lang.Integer getAsInteger(java.lang.String key) {
return (Integer)map.get(key);
}
public java.lang.Short getAsShort(java.lang.String key) {
return (Short)map.get(key);
}
public java.lang.Byte getAsByte(java.lang.String key) {
return (Byte)map.get(key);
}
public java.lang.Double getAsDouble(java.lang.String key) {
return (Double)map.get(key);
}
public java.lang.Float getAsFloat(java.lang.String key) {
return (Float)map.get(key);
}
public java.lang.Boolean getAsBoolean(java.lang.String key) {
return (Boolean)map.get(key);
}
public byte[] getAsByteArray(java.lang.String key) {
return (byte[])map.get(key);
}
public java.util.Set<java.util.Map.Entry<java.lang.String, java.lang.Object>> valueSet() {
return map.entrySet();
}
public int describeContents() {
throw new RuntimeException("Stub!");
}
public void writeToParcel(android.os.Parcel parcel, int flags) {
throw new RuntimeException("Stub!");
}
public java.lang.String toString() {
throw new RuntimeException("Stub!");
}
public HashMap<String, Object> getMap() {
return map;
}
}
|
package automation.homeworkoop2interface;
/**
* @author cosminghicioc
*
*/
public interface PersonWalk {
/**
* Interface method walk
*/
public void walk();
}
|
package pl.com.nur.springsecurityemailverification.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import pl.com.nur.springsecurityemailverification.model.AppUser;
import pl.com.nur.springsecurityemailverification.repository.AppUserRepo;
import pl.com.nur.springsecurityemailverification.service.UserServiceNur;
import javax.servlet.http.HttpServletRequest;
@Controller
public class SecurityApi {
private UserServiceNur userServiceNur;
private AppUserRepo appUserRepo;
public SecurityApi(UserServiceNur userServiceNur) {
this.userServiceNur = userServiceNur;
}
@RequestMapping("/login")
public String login() {
return "login";
}
@RequestMapping("/singup")
public ModelAndView singup(){
return new ModelAndView("registration", "user", new AppUser());
}
@RequestMapping("/register")
public ModelAndView registration(AppUser appUser, HttpServletRequest httpServletRequest){
if (userServiceNur.addUser(appUser, httpServletRequest)){
return new ModelAndView("redirect:/login");
}
else {
return new ModelAndView("registrationerror");
}
}
@RequestMapping("/verifytoken")
public ModelAndView registerUser(String token)
{
if(userServiceNur.verifytoken(token)) {
return new ModelAndView("redirect:/login");
}
else {
return new ModelAndView("redirect:/login");
}
}
@RequestMapping("/verifyadmin")
public ModelAndView registerAdmin(String token)
{
if(userServiceNur.verifytokenAdmin(token)) {
return new ModelAndView("redirect:/login");
}
return new ModelAndView("redirect:/login");
}
}
|
package com.javarush.test.level08.lesson11.home05;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
/* Мама Мыла Раму. Теперь с большой буквы
Написать программу, которая вводит с клавиатуры строку текста.
Программа заменяет в тексте первые буквы всех слов на заглавные.
Вывести результат на экран.
Пример ввода:
мама мыла раму.
Пример вывода:
Мама Мыла Раму.
*/
public class Solution
{
public static void main(String[] args) throws IOException
{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String s = reader.readLine();
//Напишите тут ваш код
String newString = new String();
for (int i = 0; i < s.length(); i++){
char c = s.charAt(i);
if (i == 0) {
newString += Character.toString(c).toUpperCase();
}
else newString += c;
if ((Character.toString(c).equals(" "))&&(i<(s.length()-1))){
if (!Character.toString(s.charAt(i+1)).equals(" ")) {
i++;
newString += Character.toString(s.charAt(i)).toUpperCase();
}
}
}
System.out.print(newString);
}
}
|
package com.socialteinc.socialate;
import android.content.Context;
import android.content.res.TypedArray;
import android.preference.Preference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.SeekBar;
/**
* This class is a custom preference, it will be used to make a settings object,
* it basically listens for any changes in the seekbar and pushes those changes to the Preferences Fragment
* **/
public class seekBarPref extends Preference implements SeekBar.OnSeekBarChangeListener {
private SeekBar mSeekBar;
private int mProgress;
public seekBarPref(Context context) {
this(context, null, 0);
}
public seekBarPref(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public seekBarPref(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setLayoutResource(R.layout.preference_seekbar);
}
@Override
protected void onBindView(View view) {
super.onBindView(view);
mSeekBar = view.findViewById(R.id.seekbar);
mSeekBar.setProgress(mProgress);
mSeekBar.setOnSeekBarChangeListener(this);
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (!fromUser)
return;
setValue(progress);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// not used
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// not used
}
@Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
setValue(restoreValue ? getPersistedInt(mProgress) : (Integer) defaultValue);
}
public void setValue(int value) {
if (shouldPersist()) {
System.out.println("******* persist value: " + value);
persistInt(value);
}
if (value != mProgress) {
mProgress = value;
notifyChanged();
}
}
@Override
protected Object onGetDefaultValue(TypedArray a, int index) {
return a.getInt(index, 0);
}
} |
package com.sozolab.clientserver;
import android.content.Context;
import android.os.Environment;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
public class LocationJson {
Context context;
String path;
String TAG = LocationJson.class.getName();
public LocationJson(Context context){
this.context = context;
path = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "QuuppaData";
createQuuppaFolder();
}
public void createQuuppaFolder() {
try {
File quuppaFolderDir = new File(path);
if (!quuppaFolderDir.exists()) {
quuppaFolderDir.mkdirs();
Log.d(TAG, "Quuppa folder directory : " + path); ///storage/emulated/0/QuuppaData
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void saveJson(String message){
Log.d(TAG, message);
try {
JSONObject jsonObject = new JSONObject(message);
double timeStamp = jsonObject.getDouble("positionTS");
String id = jsonObject.getString("id");
String fileName = id + "_" + String.format("%.0f", timeStamp);
Log.d(TAG, fileName);
String outputFilePath = path + File.separator + fileName + ".json";
File file = new File(outputFilePath);
Writer output = new BufferedWriter(new FileWriter(file));
output.write(jsonObject.toString());
output.close();
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
}
public void readJson(){
try {
String fileName = "1585638748369.json";
File file = new File(path, fileName);
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuilder stringBuilder = new StringBuilder();
String line = bufferedReader.readLine();
while (line != null){
stringBuilder.append(line).append("\n");
line = bufferedReader.readLine();
}
bufferedReader.close();
// This response will have Json Format String
String response = stringBuilder.toString();
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("position");
Log.d(TAG, "Response : " + jsonArray.toString());
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
}
}
|
package com.khenprice.twitter;
/**
* A class representing a Twitter tweet.
*
* @author khenprice
*
*/
public class Tweet {
String text;
int sentiment;
int retweetCount;;
public int getRetweetCount() {
return retweetCount;
}
public void setRetweetCount(int retweetCount) {
this.retweetCount = retweetCount;
}
public Tweet(String text, int retweetCount, int sentiment) {
this.text = text;
this.sentiment = sentiment;
this.retweetCount = retweetCount;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public int getSentiment() {
return sentiment;
}
public void setSentiment(int sentiment) {
this.sentiment = sentiment;
}
public String toString() {
return new String("Text:[" + text + "] | " + "Retweets: ["
+ retweetCount + "] | " + "Sentiment: [" + sentiment + "]");
}
}
|
package com.topeventos.repository;
import com.topeventos.models.Evento;
import org.springframework.data.repository.CrudRepository;
/* CLASSE QUE IMPLEMENTA DA INTERFACE 'CrudRepository' MÉTODOS PARA CRUD(cadastrar, listar, atualizar, deletar) de */
public interface EventoRepository extends CrudRepository<Evento, String> {
// Notacao para buscar código para detalhes evento
Evento findByCodigo(long codigo);
} |
package practise;
public class Program2 extends DemoProgram
{
int i=99;
@Override
protected void increment() {
// TODO Auto-generated method stub
System.out.println(++i);
}
public static void main(String[] args) {
Program2 p=new Program2();
p.increment();
}
}
class DemoProgram
{
int i=5;
protected void increment()
{
System.out.println("i="+"hello");
}
}
|
package com.zeal.common.log;
import android.util.Log;
/**
* Log统一管理类
*
* @author zeal
*
*/
public class Logger {
public static boolean isDebug = true;// 是否需要打印bug,可以在application的onCreate函数里面初始化
private static final String TAG = "zeal";
// 下面四个是默认tag的函数
public static void i(String msg) {
if (isDebug)
Log.i(TAG, TAG + ":" + msg);
}
public static void d(String msg) {
if (isDebug)
Log.d(TAG, TAG + ":" + msg);
}
public static void e(String msg) {
if (isDebug)
Log.e(TAG, TAG + ":" + msg);
}
public static void v(String msg) {
if (isDebug)
Log.v(TAG, TAG + ":" + msg);
}
public static void w(String msg){
if(isDebug){
Log.w(TAG, TAG + ":" + msg);
}
}
//下面是传入类名打印log
public static void i(Class<?> _class,String msg){
if (isDebug)
Log.i(_class.getName(), TAG + ":" + msg);
}
public static void d(Class<?> _class,String msg){
if (isDebug)
Log.d(_class.getName(), TAG + ":" + msg);
}
public static void e(Class<?> _class,String msg){
if (isDebug)
Log.e(_class.getName(), TAG + ":" + msg);
}
public static void v(Class<?> _class,String msg){
if (isDebug)
Log.v(_class.getName(), TAG + ":" + msg);
}
public static void w(Class<?> _class, String msg){
if(isDebug){
Log.w(_class.getName(), TAG + ":" + msg);
}
}
// 下面是传入自定义tag的函数
public static void v(String tag, String msg) {
if (isDebug)
Log.v(tag, TAG + ":" + msg);
}
public static void d(String tag, String msg) {
if (isDebug)
Log.d(tag, TAG + ":" + msg);
}
public static void i(String tag, String msg) {
if (isDebug)
Log.i(tag, TAG + ":" + msg);
}
public static void w(String tag, String msg){
if(isDebug){
Log.w(tag, TAG + ":" + msg);
}
}
public static void e(String tag,
String msg) {
if (isDebug)
Log.e(tag, TAG + ":" + msg);
}
}
|
//
// Decompiled by Procyon v0.5.36
//
package com.davivienda.sara.tablas.edccargue.session;
import java.util.Date;
import java.util.Collection;
import javax.annotation.PostConstruct;
import com.davivienda.sara.tablas.edccargue.servicio.EdcCargueServicio;
import javax.persistence.PersistenceContext;
import javax.persistence.EntityManager;
import javax.ejb.Stateless;
import com.davivienda.sara.entitys.EdcCargue;
import com.davivienda.sara.base.BaseAdministracionTablas;
@Stateless
public class EdcCargueSessionBean extends BaseAdministracionTablas<EdcCargue> implements EdcCargueSessionLocal
{
@PersistenceContext
private EntityManager em;
private EdcCargueServicio EdcCargueServicio;
@PostConstruct
public void postConstructor() {
this.EdcCargueServicio = new EdcCargueServicio(this.em);
super.servicio = this.EdcCargueServicio;
}
@Override
public Collection<EdcCargue> getCicloSnError(final Integer ciclo) throws Exception {
return this.EdcCargueServicio.getCicloSnError(ciclo);
}
@Override
public Collection<EdcCargue> getEDCCarguePorFecha(final Date fechaInicial, final Date fechaFinal) throws Exception {
return this.EdcCargueServicio.getEDCCarguePorFecha(fechaInicial, fechaFinal);
}
@Override
public int borrarCiclo(final Integer codigoCiclo) throws Exception {
return this.EdcCargueServicio.borrarCiclo(codigoCiclo);
}
}
|
package handle;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import entity.Departs;
public class DepartsHandle extends AbstractHandle {
public DepartsHandle() {
super(Departs.class);
}
}
|
/*
* Copyright 2002-2012 Drew Noakes
*
* 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.
*
* More information about this project is available at:
*
* http://drewnoakes.com/code/exif/
* http://code.google.com/p/metadata-extractor/
*/
package com.drew.metadata;
import com.drew.metadata.exif.ExifSubIFDDirectory;
import com.drew.metadata.iptc.IptcDirectory;
import org.junit.Assert;
import org.junit.Test;
/**
* JUnit test case for class Metadata.
*
* @author Drew Noakes http://drewnoakes.com
*/
public class MetadataTest
{
@Test public void testGetDirectoryWhenNotExists()
{
Assert.assertNull(new Metadata().getDirectory(ExifSubIFDDirectory.class));
}
@Test public void testGetOrCreateDirectoryWhenNotExists()
{
Assert.assertNotNull(new Metadata().getOrCreateDirectory(ExifSubIFDDirectory.class));
}
@Test public void testGetDirectoryReturnsSameInstance()
{
Metadata metadata = new Metadata();
Directory directory = metadata.getOrCreateDirectory(ExifSubIFDDirectory.class);
Assert.assertSame(directory, metadata.getDirectory(ExifSubIFDDirectory.class));
}
@Test public void testGetOrCreateDirectoryReturnsSameInstance()
{
Metadata metadata = new Metadata();
Directory directory = metadata.getOrCreateDirectory(ExifSubIFDDirectory.class);
Assert.assertSame(directory, metadata.getOrCreateDirectory(ExifSubIFDDirectory.class));
Assert.assertNotSame(directory, metadata.getOrCreateDirectory(IptcDirectory.class));
}
@Test
public void testHasErrors() throws Exception
{
Metadata metadata = new Metadata();
Assert.assertFalse(metadata.hasErrors());
final ExifSubIFDDirectory directory = metadata.getOrCreateDirectory(ExifSubIFDDirectory.class);
directory.addError("Test Error 1");
Assert.assertTrue(metadata.hasErrors());
}
@Test
public void testGetErrors() throws Exception
{
Metadata metadata = new Metadata();
Assert.assertFalse(metadata.hasErrors());
final ExifSubIFDDirectory directory = metadata.getOrCreateDirectory(ExifSubIFDDirectory.class);
directory.addError("Test Error 1");
Assert.assertTrue(metadata.hasErrors());
}
}
|
package com.springapp.mvc.core.Exception;
/**
* Created by max.lu on 2015/10/19.
*/
public class BusinessProcessException extends RuntimeException {
public BusinessProcessException(String message) {
super(message);
}
public BusinessProcessException(String message, Throwable cause) {
super(message, cause);
}
}
|
package java.com.kaizenmax.taikinys_icl.pojo;
public class RetailerDetailsPojo {
public static final String RETAILERDETAILS_TABLE_NAME = "retailerdetails";
public static final String RETAILERDETAILS_COLUMN_ID = "id";
public static final String RETAILERDETAILS_COLUMN_FIRM_NAME = "firmname";
public static final String RETAILERDETAILS_COLUMN_PROPRIETOR_NAME = "proprietorname";
public static final String RETAILERDETAILS_COLUMN_RETAILER_MOBILE = "retailermobile";
public static final String RETAILERDETAILS_COLUMN_PROMO_FM_ID = "promofmid";
public static final String RETAILERDETAILS_COLUMN_PROMO_MC_ID = "promomcid";
public static final String RETAILERDETAILS_COLUMN_PROMO_DEMOL3Serial_ID = "demol3serialid";
private String firmName;
private String propName;
private String retailerMobile;
public String getFirmName() {
return firmName;
}
public void setFirmName(String firmName) {
this.firmName = firmName;
}
public String getPropName() {
return propName;
}
public void setPropName(String propName) {
this.propName = propName;
}
public String getRetailerMobile() {
return retailerMobile;
}
public void setRetailerMobile(String retailerMobile) {
this.retailerMobile = retailerMobile;
}
}
|
package com.atlassian.theplugin.configuration;
import com.atlassian.theplugin.commons.ServerType;
import com.atlassian.theplugin.commons.cfg.JiraServerCfg;
import com.atlassian.theplugin.commons.cfg.ServerIdImpl;
import com.atlassian.theplugin.commons.jira.JiraServerData;
import com.atlassian.theplugin.commons.jira.api.JiraIssueAdapter;
import junit.framework.TestCase;
public class RecenltyOpenIssuesTest extends TestCase {
private JiraWorkspaceConfiguration conf;
private JiraServerData server;
private JiraIssueAdapter issue1;
private JiraIssueAdapter issue2;
private JiraIssueAdapter issue3;
public void setUp() throws Exception {
conf = new JiraWorkspaceConfiguration();
server = new JiraServerData(new JiraServerCfg(true, "server", new ServerIdImpl(), true, false) {
public ServerType getServerType() {
return null;
}
public JiraServerCfg getClone() {
return null;
}
});
issue1 = new JiraIssueAdapter(server);
issue1.setKey("1");
issue2 = new JiraIssueAdapter(server);
issue2.setKey("2");
issue3 = new JiraIssueAdapter(server);
issue3.setKey("3");
}
public void testEmptyConfiguration() {
assertNotNull(conf.getRecentlyOpenIssuess());
assertEquals(0, conf.getRecentlyOpenIssuess().size());
}
public void testAddRecentlyOpenIssue() {
conf.addRecentlyOpenIssue(issue1);
assertEquals(1, conf.getRecentlyOpenIssuess().size());
assertTrue(conf.getRecentlyOpenIssuess().contains(getRecenltyOpenIssueBean(issue1)));
}
public void testAddRecentlyOpenIssueOrder() {
conf.addRecentlyOpenIssue(issue1);
conf.addRecentlyOpenIssue(issue2);
assertEquals(2, conf.getRecentlyOpenIssuess().size());
assertTrue(conf.getRecentlyOpenIssuess().contains(getRecenltyOpenIssueBean(issue1)));
assertTrue(conf.getRecentlyOpenIssuess().contains(getRecenltyOpenIssueBean(issue2)));
// test order
assertEquals(getRecenltyOpenIssueBean(issue2), conf.getRecentlyOpenIssuess().get(0));
assertEquals(getRecenltyOpenIssueBean(issue1), conf.getRecentlyOpenIssuess().get(1));
}
public void testAddRecenltyOpenIssueLimit() {
conf.addRecentlyOpenIssue(issue1);
conf.addRecentlyOpenIssue(issue2);
for (int i = 0; i < JiraWorkspaceConfiguration.RECENLTY_OPEN_ISSUES_LIMIT - 2; ++i) {
final JiraIssueAdapter issue = new JiraIssueAdapter(server);
issue.setKey("100" + i);
conf.addRecentlyOpenIssue(issue);
}
conf.addRecentlyOpenIssue(issue3);
// check limit
assertEquals(JiraWorkspaceConfiguration.RECENLTY_OPEN_ISSUES_LIMIT, conf.getRecentlyOpenIssuess().size());
// last added issue should be on top
assertEquals(getRecenltyOpenIssueBean(issue3), conf.getRecentlyOpenIssuess().getFirst());
// first added issue should disappear (out of the limit)
assertFalse(conf.getRecentlyOpenIssuess().contains(getRecenltyOpenIssueBean(issue1)));
// issue2 should be at the end
assertEquals(getRecenltyOpenIssueBean(issue2), conf.getRecentlyOpenIssuess().getLast());
}
private IssueRecentlyOpenBean getRecenltyOpenIssueBean(final JiraIssueAdapter issue) {
return new IssueRecentlyOpenBean(issue.getJiraServerData().getServerId(), issue.getKey(), issue.getIssueUrl());
}
}
|
package com.appspot.smartshop.ui.user;
import java.net.URLEncoder;
import java.util.LinkedList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import com.appspot.smartshop.R;
import com.appspot.smartshop.adapter.ProductAdapter;
import com.appspot.smartshop.dom.ProductInfo;
import com.appspot.smartshop.facebook.utils.FacebookUtils;
import com.appspot.smartshop.ui.BaseUIActivity;
import com.appspot.smartshop.utils.DataLoader;
import com.appspot.smartshop.utils.Global;
import com.appspot.smartshop.utils.JSONParser;
import com.appspot.smartshop.utils.RestClient;
import com.appspot.smartshop.utils.SimpleAsyncTask;
import com.appspot.smartshop.utils.URLConstant;
import com.appspot.smartshop.utils.Utils;
public class UserProductListActivity extends BaseUIActivity {
public static final int INTERESTED_PRODUCTS = 0;
public static final int BUYED_PRODUCTS = 1;
public static final int SELLED_PRODUCTS = 2;
private static LinkedList<ProductInfo> products;
private int productsListType = INTERESTED_PRODUCTS;
private String username;
private ProductAdapter adapter;
private ListView listProducts;
private String url;
// set up variable for facebook connection
@Override
protected void onCreatePre() {
setContentView(R.layout.user_product_list);
}
@Override
protected void onCreatePost(Bundle savedInstanceState) {
// get username
username = getIntent().getExtras().getString(Global.PRODUCTS_OF_USER);
// radio buttons
RadioButton rbInterestedProducts = (RadioButton) findViewById(R.id.rbInterestedProducts);
rbInterestedProducts.setChecked(true);
rbInterestedProducts
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
productsListType = INTERESTED_PRODUCTS;
constructUrl();
loadProductsList();
}
}
});
RadioButton rbBuyProducts = (RadioButton) findViewById(R.id.rbBuyProducts);
rbBuyProducts.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
productsListType = BUYED_PRODUCTS;
constructUrl();
loadProductsList();
}
}
});
RadioButton rbSellProducts = (RadioButton) findViewById(R.id.rbSellProducts);
rbSellProducts
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
productsListType = SELLED_PRODUCTS;
constructUrl();
loadProductsList();
}
}
});
// search fields
txtSearch = (EditText) findViewById(R.id.txtSearch);
Button btnSearch = (Button) findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
searchProductsByQuery();
}
});
// products listview
listProducts = (ListView) findViewById(R.id.listUserProducts);
constructUrl();
loadProductsList();
}
protected void searchProductsByQuery() {
String query = URLEncoder.encode(txtSearch.getText().toString());
constructUrl();
url += "&q=" + query;
loadProductsList();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, 0, 0, getString(R.string.return_to_home)).setIcon(R.drawable.home);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == 0) {
Utils.returnHomeActivity(this);
}
return super.onOptionsItemSelected(item);
}
private void constructUrl() {
// construct url
switch (productsListType) {
case INTERESTED_PRODUCTS:
url = String.format(URLConstant.GET_INTERESTED_PRODUCTS_OF_USER,
username);
break;
case BUYED_PRODUCTS:
url = String.format(URLConstant.GET_SELLED_PRODUCTS_OF_USER,
username);
break;
case SELLED_PRODUCTS:
url = String.format(URLConstant.GET_BUYED_PRODUCTS_OF_USER,
username);
break;
}
}
private SimpleAsyncTask task;
private EditText txtSearch;
protected void loadProductsList() {
// load data
task = new SimpleAsyncTask(this, new DataLoader() {
@Override
public void updateUI() {
if (products != null) {
adapter = new ProductAdapter(UserProductListActivity.this,
R.layout.product_list_item, products,new FacebookUtils(UserProductListActivity.this));
adapter.isNormalProductList = false;
listProducts.setAdapter(adapter);
}
}
@Override
public void loadData() {
RestClient.getData(url, new JSONParser() {
@Override
public void onSuccess(JSONObject json) throws JSONException {
JSONArray arr = json.getJSONArray("products");
products = Global.gsonWithHour.fromJson(arr.toString(),
ProductInfo.getType());
}
@Override
public void onFailure(String message) {
// task.cancel(true);
// Toast.makeText(UserProductListActivity.this, message,
// Toast.LENGTH_SHORT);
}
});
}
});
task.execute();
}
}
|
package com.example.demo.dbflute.exbhv.pmbean;
import com.example.demo.dbflute.bsbhv.pmbean.BsUserDataPmb;
/**
* <!-- df:beginClassDescription -->
* The typed parameter-bean of UserData. <span style="color: #AD4747">(typed to list, entity)</span><br>
* This is related to "<span style="color: #AD4747">selectUserData</span>" on TUsersBhv, <br>
* described as "SQL title here.". <br>
* <!-- df:endClassDescription -->
* <p>
* You can implement your original methods here.
* This class remains when re-generating.
* </p>
* @author DBFlute(AutoGenerator)
*/
public class UserDataPmb extends BsUserDataPmb {
}
|
/*
* The contents of this file are subject to the terms
* of the Common Development and Distribution License
* (the "License"). You may not use this file except
* in compliance with the License.
*
* You can obtain a copy of the license at
* https://jwsdp.dev.java.net/CDDLv1.0.html
* See the License for the specific language governing
* permissions and limitations under the License.
*
* When distributing Covered Code, include this CDDL
* HEADER in each file and include the License file at
* https://jwsdp.dev.java.net/CDDLv1.0.html If applicable,
* add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your
* own identifying information: Portions Copyright [yyyy]
* [name of copyright owner]
*/
/*
* $Id: USAddressFactory.java,v 1.1 2005/12/20 15:15:37 rebeccas Exp $
*
* Copyright 2005 Sun Microsystems, Inc. All Rights Reserved.
*
* This software is the proprietary information of Sun Microsystems, Inc.
* Use is subject to license terms.
*
*/
package address;
public class USAddressFactory {
public static USAddress getUSAddress(){
return new USAddress("Mark Baker", "23 Elm St",
"Dayton", "OH", 90952);
}
} |
package testers;
public class GetValue{
public static void main(String[] args){
System.out.println("ABC");
}
public int getInt(int param){
return (param*4);
}
} |
package PACKAGE_NAME;public class Challenge6 {
}
|
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
public class StringUtil {
public static void main(String[] args) throws UnsupportedEncodingException {
byte[] bytes = "熊娃,说啥呢,还用上了敬语,滚粗".getBytes("GBK");
// System.out.print(bytesToHexStr(bytes,bytes.length," "));
// File file = new File("D://ipte.aa");
// System.out.println(file.renameTo(new File("c:/ipte.aa")));
// System.out.println(file.exists()+":"+ file.getName());
Pattern p=Pattern.compile("(?i)^[^/\\\\]*a2b[^/\\\\]*\\.(?:)$",0);
// Pattern p2=Pattern.compile("(?i)^[^/\\\\]*a2b[^/\\\\\\.]*$",0);
System.out.println(p.matcher("11.a2bc342.1..1").matches());
// System.out.println("werer".matches("(?i)^wer1*\\w+$"));
// System.out.println("".replace(',','|'));
}
public static final char[] HEXCHAR = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
public static final Map<Character,Byte> hexCharMap=new HashMap<Character,Byte>();
static{
for(int i=0;i<16;i++){
if(i<10)
hexCharMap.put((char)('0'+i), (byte)i);
else{
hexCharMap.put((char)('a'+i-10), (byte)i);
hexCharMap.put((char)('A'+i-10), (byte)i);
}
}
}
public static final char[] tempChary=new char[2];
public static int ignoreCaseLastIndexOf(String content,int startOffset,String tar){
if(content==null||content.length()==0||tar==null||tar.length()==0) return 0;
char c=tar.charAt(tar.length()-1);
for(int i=startOffset-1;i>=0;i--){
if(equalsIgnoreCase(content.charAt(i), c)){
int j;
for(j=tar.length()-2;j>=0;j--){
if(!equalsIgnoreCase(content.charAt(i+j-tar.length()+1), tar.charAt(j)))
break;
}
if(j==-1){
System.out.println(i);
return i-tar.length()+1;
}
}
}
return -1;
}
public static int ignoreCaseIndexOf(String content,String tar){
if(content==null||content.length()==0||tar==null||tar.length()==0) return 0;
char c=tar.charAt(0);
int length=content.length();
for(int i=0;i<length;i++){
if(equalsIgnoreCase(content.charAt(i), c)){
int j;
for(j=1;j<tar.length();j++){
if(!equalsIgnoreCase(content.charAt(i+j), tar.charAt(j)))
break;
}
if(j==tar.length())
return i;
}
}
return -1;
}
public static boolean equalsIgnoreCase(char c1,char c2){
if(c1==c2) return true;
if(isLetter(c1)&&isLetter(c2)){
int delta=c1-c2;
if(delta==32||delta==-32)
return true;
}
return false;
}
public static boolean isLetter(char c){
return c>=65&&c<=90||c>=97&&c<=122;
}
public static String bytesToHexStr(byte[] bytes,int count ,String space) {
if(count<0) count=0;
if(count>bytes.length) count = bytes.length;
StringBuffer sb = new StringBuffer();
for (int i = 0; i < count; i++) {
sb.append(byteToHexStr(bytes[i])+space);
}
return sb.toString();
}
public static byte[] hexStrToBytes(String hexStr){
hexStr=trimSpaces(hexStr);
if(!isHexStr(hexStr)) return null;
int b1,i;
byte b2;
int length=hexStr.length()/2;
byte[] bytes = new byte[hexStr.length()%2==0?length:length+1];
for(i=1;i<hexStr.length();i+=2){
b2=hexCharMap.get(hexStr.charAt(i));
b1=(hexCharMap.get(hexStr.charAt(i-1))<<4);
bytes[(i-1)/2]=(byte)(b1|b2);
}
if(i==hexStr.length()){
//TODO
bytes[bytes.length-1]=hexCharMap.get(hexStr.charAt(hexStr.length()-1));
}
return bytes;
}
public static boolean isHexStr(String hexStr){
for(int i=0;i<hexStr.length();i++){
if(!hexCharMap.containsKey(hexStr.charAt(i)))
return false;
}
return true;
}
public static String trimSpaces(String str){
return str.replaceAll("\\s", "");
}
/**
*
*
* @param mByte
* @return
*/
public static String byteToHexStr(byte mByte) {
tempChary[0] = HEXCHAR[(mByte >>> 4)&0x0F ];
tempChary[1] = HEXCHAR[mByte & 0X0F];
String s = new String(tempChary);
return s;
}
}
|
/*
* Copyright (c) 2013 MercadoLibre -- All rights reserved
*/
package com.zauberlabs.bigdata.lamdaoa.batch;
import java.util.Date;
/**
* Frag event.
*
*
* @since Aug 23, 2013
*/
public class Frag {
private Date timeStamp;
private String game;
private String fragger;
private String fragged;
public Frag(Date timeStamp, String game, String fragger, String fragged) {
this.timeStamp = timeStamp;
this.game = game;
this.fragger = fragger;
this.fragged = fragged;
}
public Date getTimestamp() {
return timeStamp;
}
public String getGame() {
return game;
}
public String getFragger() {
return fragger;
}
public String getFragged() {
return fragged;
}
}
|
package uppgifterV35;
public class stringReverse {
public static void main(String[] args) {
System.out.println(reverse("Hej JaoK"));
}
public static String reverse(String input) {
if (input.length() == 1) {
return input;
}
else {
return reverse(input.substring(1))+ input.charAt(0);
}
}
} |
package com.ht.event.dao;
import java.util.List;
import com.ht.event.model.User;
import org.springframework.stereotype.Repository;
@Repository
public interface UserDao {
void addUser(User user);
void updateUser(User user);
User getUser(Integer id);
void deleteUser(Integer id);
List<User> getUsers();
}
|
/**
* Sencha GXT 1.0.0-SNAPSHOT - Sencha for GWT
* Copyright (c) 2006-2018, Sencha Inc.
*
* licensing@sencha.com
* http://www.sencha.com/products/gxt/license/
*
* ================================================================================
* Commercial License
* ================================================================================
* This version of Sencha GXT is licensed commercially and is the appropriate
* option for the vast majority of use cases.
*
* Please see the Sencha GXT Licensing page at:
* http://www.sencha.com/products/gxt/license/
*
* For clarification or additional options, please contact:
* licensing@sencha.com
* ================================================================================
*
*
*
*
*
*
*
*
* ================================================================================
* Disclaimer
* ================================================================================
* THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND
* REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE
* IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY,
* FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE AND
* THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING.
* ================================================================================
*/
package com.sencha.gxt.explorer.client.grid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.cell.client.DateCell;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Widget;
import com.sencha.gxt.core.client.GXT;
import com.sencha.gxt.data.shared.ListStore;
import com.sencha.gxt.examples.resources.client.TestData;
import com.sencha.gxt.examples.resources.client.model.Stock;
import com.sencha.gxt.examples.resources.client.model.StockProperties;
import com.sencha.gxt.explorer.client.app.ui.ExampleContainer;
import com.sencha.gxt.explorer.client.model.Example.Detail;
import com.sencha.gxt.state.client.CookieProvider;
import com.sencha.gxt.state.client.GridStateHandler;
import com.sencha.gxt.state.client.StateManager;
import com.sencha.gxt.widget.core.client.ContentPanel;
import com.sencha.gxt.widget.core.client.form.SimpleComboBox;
import com.sencha.gxt.widget.core.client.grid.CellSelectionModel;
import com.sencha.gxt.widget.core.client.grid.ColumnConfig;
import com.sencha.gxt.widget.core.client.grid.ColumnModel;
import com.sencha.gxt.widget.core.client.grid.Grid;
import com.sencha.gxt.widget.core.client.grid.GridSelectionModel;
import com.sencha.gxt.widget.core.client.grid.GridView;
import com.sencha.gxt.widget.core.client.selection.CellSelectionChangedEvent;
import com.sencha.gxt.widget.core.client.selection.CellSelectionChangedEvent.CellSelectionChangedHandler;
@Detail(
name = "Basic Grid (UiBinder)",
category = "Grid",
icon = "basicgriduibinder",
files = "GridUiBinderExample.ui.xml",
classes = {
Stock.class,
StockProperties.class,
TestData.class
},
maxHeight = GridUiBinderExample.MAX_HEIGHT,
maxWidth = GridUiBinderExample.MAX_WIDTH,
minHeight = GridUiBinderExample.MIN_HEIGHT,
minWidth = GridUiBinderExample.MIN_WIDTH
)
public class GridUiBinderExample implements IsWidget, EntryPoint {
protected static final int MAX_HEIGHT = 600;
protected static final int MAX_WIDTH = 800;
protected static final int MIN_HEIGHT = 320;
protected static final int MIN_WIDTH = 480;
private static final StockProperties props = GWT.create(StockProperties.class);
interface MyUiBinder extends UiBinder<ContentPanel, GridUiBinderExample> {
}
private static MyUiBinder uiBinder = GWT.create(MyUiBinder.class);
private ContentPanel panel;
@UiField(provided = true)
ColumnModel<Stock> cm;
@UiField(provided = true)
ListStore<Stock> store;
@UiField
GridView<Stock> view;
@UiField
Grid<Stock> grid;
@UiField
SimpleComboBox<String> typeCombo;
@Override
public Widget asWidget() {
if (panel == null) {
ColumnConfig<Stock, String> nameCol = new ColumnConfig<Stock, String>(props.name(), 50, "Company");
ColumnConfig<Stock, String> symbolCol = new ColumnConfig<Stock, String>(props.symbol(), 75, "Symbol");
ColumnConfig<Stock, Double> lastCol = new ColumnConfig<Stock, Double>(props.last(), 75, "Last");
ColumnConfig<Stock, Double> changeCol = new ColumnConfig<Stock, Double>(props.change(), 75, "Change");
ColumnConfig<Stock, Date> lastTransCol = new ColumnConfig<Stock, Date>(props.lastTrans(), 100, "Last Updated");
final NumberFormat number = NumberFormat.getFormat("0.00");
changeCol.setCell(new AbstractCell<Double>() {
@Override
public void render(Context context, Double value, SafeHtmlBuilder sb) {
String style = "style='color: " + (value < 0 ? "red" : "green") + "'";
String v = number.format(value);
sb.appendHtmlConstant("<span " + style + ">" + v + "</span>");
}
});
lastTransCol.setCell(new DateCell(DateTimeFormat.getFormat("MM/dd/yyyy")));
List<ColumnConfig<Stock, ?>> columns = new ArrayList<ColumnConfig<Stock, ?>>();
columns.add(nameCol);
columns.add(symbolCol);
columns.add(lastCol);
columns.add(changeCol);
columns.add(lastTransCol);
cm = new ColumnModel<Stock>(columns);
store = new ListStore<Stock>(props.key());
store.addAll(TestData.getStocks());
// UiBinder instantiates the widgets
panel = uiBinder.createAndBindUi(this);
typeCombo.add("Row");
typeCombo.add("Cell");
typeCombo.setValue("Row");
// Change selection model on select, not value change which fires on blur
typeCombo.addSelectionHandler(new SelectionHandler<String>() {
@Override
public void onSelection(SelectionEvent<String> event) {
boolean cell = event.getSelectedItem().equals("Cell");
if (cell) {
CellSelectionModel<Stock> c = new CellSelectionModel<Stock>();
c.addCellSelectionChangedHandler(new CellSelectionChangedHandler<Stock>() {
@Override
public void onCellSelectionChanged(CellSelectionChangedEvent<Stock> event) {
}
});
grid.setSelectionModel(c);
} else {
grid.setSelectionModel(new GridSelectionModel<Stock>());
}
}
});
view.setAutoExpandColumn(nameCol);
// Stage manager, load the previous state
GridStateHandler<Stock> state = new GridStateHandler<Stock>(grid);
state.loadState();
}
return panel;
}
@Override
public void onModuleLoad() {
// State manager, initialize the state options
StateManager.get().setProvider(new CookieProvider("/", null, null, GXT.isSecure()));
new ExampleContainer(this)
.setMaxHeight(MAX_HEIGHT)
.setMaxWidth(MAX_WIDTH)
.setMinHeight(MIN_HEIGHT)
.setMinWidth(MIN_WIDTH)
.doStandalone();
}
}
|
package com.pingan.utils;
import java.io.IOException;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pingan.pojo.User;
public class SerializeUtils {
private static JSONObject json = new JSONObject();
private static ObjectMapper objectMapper = new ObjectMapper();
public static Object fstdeserialize(byte[] bytes) {
// try {
return json.parse(bytes);
// return objectMapper.readValue(bytes, User.class);
// } catch (IOException e) {
// e.printStackTrace();
// }
// return null;
}
public static byte[] fstserialize(Object object) {
// try {
byte[] jsonBytes = json.toJSONBytes(object);
return jsonBytes;
// return objectMapper.writeValueAsBytes(object);
// } catch (IOException e) {
// e.printStackTrace();
// }
// return null;
}
public static void main(String[] args) {
User user = new User();
user.setUserName("aaa");
user.setPassword("bbb");
user.setUserId(1);
byte[] bytes = fstserialize(user);
Object fstdeserialize = fstdeserialize(bytes);
User parseObject = json.parseObject(fstdeserialize.toString(), User.class);
System.out.println(parseObject);
}
}
|
package facades;
import entities.Address;
import entities.Person;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
public class PersonFacade implements IPersonFacade {
private static PersonFacade instance;
private static EntityManagerFactory emf;
//Private Constructor to ensure Singleton
private PersonFacade() {
}
/**
*
* @param _emf
* @return an instance of this facade class.
*/
public static PersonFacade getFacade(EntityManagerFactory _emf) {
if (instance == null) {
emf = _emf;
instance = new PersonFacade();
}
return instance;
}
private EntityManager getEntityManager() {
return emf.createEntityManager();
}
@Override
public Person addPerson(String fName, String lName, String phone) { //, String street, String zip, String city
EntityManager em = getEntityManager();
try {
em.getTransaction().begin();
// Address address = addAddress(em, street, zip, city);
Person p = new Person(fName, lName, phone); //, address
// address.addOccupant(p);
// if (address.getId() == null) em.persist(address);
em.persist(p);
em.getTransaction().commit();
return p;
} finally {
em.close();
}
}
// private Address addAddress(EntityManager em, String street, String zip, String city) {
// Address address;
// List<Address> addressResult = em.createQuery("SELECT pa FROM SP4_Person_Address pa "
// + "WHERE pa.street = :street "
// + "AND pa.zip = :zip "
// + "AND pa.city = :city",
// Address.class)
// .setParameter("street", street).setParameter("zip", zip).setParameter("city", city)
// .getResultList();
// if (addressResult.isEmpty()) {
// address = new Address(street, zip, city);
// } else {
// address = addressResult.get(0);
// }
// return address;
// }
@Override
public Person deletePerson(int id) {
EntityManager em = getEntityManager();
try {
Person p = em.find(Person.class, id);
em.getTransaction().begin();
em.remove(p); // throws IllegalArgumentException if p is null, which is caught by Resource
// attemptDeleteAddress(em, p.getAddress());
em.getTransaction().commit();
return p;
} finally {
em.close();
}
}
// private void attemptDeleteAddress(EntityManager em, Address address) {
// List<Address> addressResult = em.createQuery("SELECT pa FROM SP4_Person_Address pa "
// + "WHERE pa.street = :street "
// + "AND pa.zip = :zip "
// + "AND pa.city = :city",
// Address.class)
// .setParameter("street", address.getStreet()).setParameter("zip", address.getZip()).setParameter("city", address.getCity())
// .getResultList();
// address = addressResult.get(0);
// if (address.getOccupants().size() == 1) {
// em.remove(address);
// }
// }
@Override
public Person getPerson(int id) {
EntityManager em = getEntityManager();
try {
Person p = em.find(Person.class, id);
return p;
} finally {
em.close();
}
}
@Override
public List<Person> getAllPersons() {
EntityManager em = getEntityManager();
try {
return em.createQuery("SELECT p FROM SP4_Person p", Person.class).getResultList();
} finally {
em.close();
}
}
@Override
public Person editPerson(Person p) {
EntityManager em = getEntityManager();
try {
em.getTransaction().begin();
em.merge(p);
em.getTransaction().commit();
return p;
} finally {
em.close();
}
}
}
|
package com.duanc.api.admin;
import java.util.List;
import com.duanc.model.base.BaseResources;
import com.duanc.model.base.BaseRole;
public interface AuthcService {
List<BaseRole> getRoles();
List<BaseResources> getResources();
}
|
/*
* Origin of the benchmark:
* repo: https://github.com/diffblue/cbmc.git
* branch: develop
* directory: regression/cbmc-java/boolean2
* The benchmark was taken from the repo: 24 January 2018
*/
public class Main
{
public static void main(String[] args)
{
boolean b=args.length > 2;
boolean result=f(b);
assert result==!b;
}
public static boolean f(boolean b)
{
return !b;
}
}
|
package dk.webbies.tscreate.analysis.declarations.typeCombiner.singleTypeReducers;
import dk.webbies.tscreate.analysis.declarations.typeCombiner.SingleTypeReducerInterface;
import dk.webbies.tscreate.analysis.declarations.types.ClassType;
import dk.webbies.tscreate.analysis.declarations.types.DeclarationType;
import dk.webbies.tscreate.analysis.declarations.types.FunctionType;
import dk.webbies.tscreate.analysis.declarations.typeCombiner.TypeReducer;
/**
* Created by Erik Krogh Kristensen on 18-10-2015.
*/
public class FunctionClassReducer implements SingleTypeReducerInterface<FunctionType, ClassType> {
private final TypeReducer combiner;
public FunctionClassReducer(TypeReducer combiner) {
this.combiner = combiner;
}
@Override
public Class<FunctionType> getAClass() {
return FunctionType.class;
}
@Override
public Class<ClassType> getBClass() {
return ClassType.class;
}
@Override
public DeclarationType reduce(FunctionType functionType, ClassType classType) {
// Same reasoning as in ClassObjectReducer.
return classType;
}
}
|
import java.awt.*;
import java.awt.event.*;
public class ChatClient {
private Frame f;
private TextField tfield;
private TextArea tarea;
private Button bsend;
private Button bquit;
private Choice choice;
private MenuBar mb;
private Menu m1;
private Menu m2;
private MenuItem mi1;
private MenuItem mi2;
private Dialog d;
private Label d1;
private Label d2;
private Label d3;
private Label d4;
private Button db;
public ChatClient() {
f = new Frame("Chat Room");
tfield = new TextField(50);
tarea = new TextArea(10, 50);
bsend = new Button("Send");
bquit = new Button("Quit");
choice = new Choice();
choice.addItem("Superman");
choice.addItem("Daisy");
choice.addItem("Mickey Mouse");
choice.addItem("Piggy");
mb = new MenuBar();
m1 = new Menu("File");
m2 = new Menu("Help");
mi1 = new MenuItem("Quit");
mi2 = new MenuItem("About");
d = new Dialog(f,"About",true);
d1 = new Label("Author: Arkadiusz Galas");
d2 = new Label("Compilation date: 11/9/2017");
d3 = new Label("Version: 1.0.5");
d4 = new Label("Compilation No.: 5");
db = new Button("OK");
}
public void launchFrame() {
f.add(tfield, BorderLayout.SOUTH);
f.add(tarea, BorderLayout.WEST);
d.setLayout(new GridLayout(5,1));
d.add(d1);
d.add(d2);
d.add(d3);
d.add(d4);
d.add(db);
d.pack();
bsend.addActionListener(new SendButtonHandler());
bquit.addActionListener(new QuitButtonHandler());
f.addWindowListener(new CloseWidgetHandler());
tfield.addKeyListener(new EnterButtonHandler());
choice.addItemListener(new ChoiceMenuHandler());
mi1.addActionListener(new QuitMenuHandler());
mi2.addActionListener(new AboutMenuHandler());
d.addWindowListener(new CloseDialogHandler());
db.addActionListener(new DialogButtonHandler());
Panel p1 = new Panel();
p1.add(bsend);
p1.add(bquit);
p1.add(choice);
// Add the button panel to the center
f.add(p1, BorderLayout.CENTER);
//Add menu items and menubar to Frame
m1.add(mi1);
m2.add(mi2);
mb.add(m1);
mb.setHelpMenu(m2);
f.setMenuBar(mb);
f.setSize(528, 252);
f.setVisible(true);
}
class SendButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
String s = choice.getSelectedItem()+": "+tfield.getText() + "\n";
tarea.append(s);
}
}
class QuitButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
class CloseWidgetHandler implements WindowListener {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
public void windowActivated(WindowEvent e) {};
public void windowDeactivated(WindowEvent e) {};
public void windowIconified(WindowEvent e) {};
public void windowDeiconified(WindowEvent e) {};
public void windowClosed(WindowEvent e) {};
public void windowOpened(WindowEvent e) {};
}
class EnterButtonHandler implements KeyListener {
public void keyTyped(KeyEvent e){}
public void keyReleased(KeyEvent e) {};
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
String s = choice.getSelectedItem()+": "+tfield.getText() + "\n";
tarea.append(s);
}
};
}
class ChoiceMenuHandler implements ItemListener {
public void itemStateChanged(ItemEvent ev) {};
}
class QuitMenuHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
class AboutMenuHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {d.setVisible(true);}
}
class CloseDialogHandler implements WindowListener {
public void windowClosing(WindowEvent e) {d.setVisible(false);}
public void windowActivated(WindowEvent e) {};
public void windowDeactivated(WindowEvent e) {};
public void windowIconified(WindowEvent e) {};
public void windowDeiconified(WindowEvent e) {};
public void windowClosed(WindowEvent e) {};
public void windowOpened(WindowEvent e) {};
}
class DialogButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {d.setVisible(false);}
}
public static void main(String[] args) {
ChatClient gui = new ChatClient();
gui.launchFrame();
}
} |
package com.jic.libin.leaderus;
import java.nio.charset.StandardCharsets;
//http://dev.mysql.com/doc/refman/5.7/en/identifiers.html 表名命名标准
public class SQLParse2 {
static final byte CHAR_A = 0x41;
static final byte CHAR_B = 0x42;
static final byte CHAR_C = 0x43;
static final byte CHAR_D = 0x44;
static final byte CHAR_E = 0x45;
static final byte CHAR_F = 0x46;
static final byte CHAR_G = 0x47;
static final byte CHAR_H = 0x48;
static final byte CHAR_I = 0x49;
static final byte CHAR_J = 0x4A;
static final byte CHAR_K = 0x4B;
static final byte CHAR_L = 0x4C;
static final byte CHAR_M = 0x4D;
static final byte CHAR_N = 0x4E;
static final byte CHAR_O = 0x4F;
static final byte CHAR_P = 0x50;
static final byte CHAR_Q = 0x51;
static final byte CHAR_R = 0x52;
static final byte CHAR_S = 0x53;
static final byte CHAR_T = 0x54;
static final byte CHAR_U = 0x55;
static final byte CHAR_V = 0x56;
static final byte CHAR_W = 0x57;
static final byte CHAR_X = 0x58;
static final byte CHAR_Y = 0x59;
static final byte CHAR_Z = 0x5A;
static final byte CHAR_a = 0x61;
static final byte CHAR_b = 0x62;
static final byte CHAR_c = 0x63;
static final byte CHAR_d = 0x64;
static final byte CHAR_e = 0x65;
static final byte CHAR_f = 0x66;
static final byte CHAR_g = 0x67;
static final byte CHAR_h = 0x68;
static final byte CHAR_i = 0x69;
static final byte CHAR_j = 0x6A;
static final byte CHAR_k = 0x6B;
static final byte CHAR_l = 0x6C;
static final byte CHAR_m = 0x6D;
static final byte CHAR_n = 0x6E;
static final byte CHAR_o = 0x6F;
static final byte CHAR_p = 0x70;
static final byte CHAR_q = 0x71;
static final byte CHAR_r = 0x72;
static final byte CHAR_s = 0x73;
static final byte CHAR_t = 0x74;
static final byte CHAR_u = 0x75;
static final byte CHAR_v = 0x76;
static final byte CHAR_w = 0x77;
static final byte CHAR_x = 0x78;
static final byte CHAR_y = 0x79;
static final byte CHAR_z = 0x7A;
static final byte CHAR_DOT = ',';
static int FROM_ID(final byte[] sql, short[] result, int pos, int result_pos) {
int SQLLength = sql.length - 1;
short result_size = 0;
boolean isDot = true;
do {
switch (sql[pos]) {
case CHAR_F:
if (sql[++pos] == CHAR_R && sql[++pos] == CHAR_O && sql[++pos] == CHAR_M &&
(sql[++pos] == 0x20 || sql[pos] == 0x0D || sql[pos] == 0x0A)) {
///////////////////////////////////////////////////////
//下一步代码块
out_finder:
do {
switch (sql[++pos]) {
case 0x20:
case 0x0D:
case 0x0A:
break;
case ')':
//空格 联合union
switch (sql[pos]) {
case 'u':
}
return pos;
case '(':
pos = FROM_ID(sql, result, pos, result_size);
break;
case ',':
isDot = true;
break;
default:
if (isDot) {
//result[result_pos++] = (short) pos;
result_size = 1;
inner_finder:
while (pos < SQLLength) {
switch (sql[++pos]) {
case 0x20:
case 0x0D:
case 0x0A:
if (result_size == 1) {
print(pos, result_size);
}
continue out_finder;
case ',':
isDot = true;
print(pos, result_size);
continue out_finder;
case ')':
break inner_finder;
default:
result_size++;
}
}
// result[result_pos++] = result_size;
isDot = false;
print(pos, result_size);
continue out_finder;
}
}
//下一步代码块
///////////////////////////////////////////
} while (pos < SQLLength);
}
break;
case 0x20:
case 0x0D:
case 0x0A:
//while((sql[++pos]==0x20 || sql[pos]==0x0D || sql[pos]==0x0A) && pos<SQLLength); //飞略换行、空格
pos++;
break;
default:
//while(sql[++pos]!=0x20 && sql[pos]!=0x0D && sql[pos]!=0x0A && pos<SQLLength); //飞略字符串
pos++;
}
} while (pos < SQLLength);
return pos;
}
static void print(int pos, int result_size) {
// System.out.println(pos + " " + result_size);
}
static long RunBench() {
short[] result = new short[128];
// todo:((SELECT a FROM (SELECT a FROM b6,dv)) union (SELECT a FROM sss))"
// todo:栈
// todo:越过字符串
// todo:大小写
// todo:动态解析代码生成器
// todo:函数调用
// tip:sql越长时间越长
// tip:递归好像消耗有点大
byte[] src = "SELECT a FROM a ,ff,(SELECT a FROM bb,(SELECT a FROM ccc,dddd)),eeeee".getBytes(StandardCharsets.UTF_8);//20794
int count = 0;
long start = System.currentTimeMillis();
do {
FROM_ID(src, result, 0, 0);//RAW:3244 3260 KMP:3900 3884 ;两层嵌套sql递归有返回值:10078 三层嵌套sql递归值返回:17893 18033
} while (count++ < 10000 * 10000);
return System.currentTimeMillis() - start;
}
public static void main(String[] args) {
long min = 0;
for (int i = 0; i < 10; i++) {
long cur = RunBench();
if (cur < min || min == 0) {
min = cur;
}
}
System.out.print(min);
}
}
|
package com.mredrock.freshmanspecial.ui;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import com.mredrock.freshmanspecial.R;
import com.mredrock.freshmanspecial.ui.Adapter.Special_2017_DataViewPagerAdapter;
import com.mredrock.freshmanspecial.ui.Fragment.ManAndWoman;
import com.mredrock.freshmanspecial.ui.Fragment.TheHardestObject;
import com.mredrock.freshmanspecial.ui.Fragment.WorkPercent;
import com.mredrock.freshmanspecial.databinding.ActivitySpecial2017DataBinding;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Administrator on 2017/8/3 0003.
*/
public class Special_2017_DataActivity extends FragmentActivity {
private List<Fragment> mFragments;
private Special_2017_DataViewPagerAdapter mDataViewPagerAdapter;
private String[] mTitles = {"男女比例","最难科目","就业比例"};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivitySpecial2017DataBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_special_2017_data);
mFragments = new ArrayList<>();
mFragments.add(new ManAndWoman());
mFragments.add(new TheHardestObject());
mFragments.add(new WorkPercent());
mDataViewPagerAdapter = new Special_2017_DataViewPagerAdapter(getSupportFragmentManager(),mFragments);
mDataViewPagerAdapter.setTitles(mTitles);
binding.dataViewpager.setAdapter(mDataViewPagerAdapter);
binding.dataTabLayout.setTabMode(TabLayout.MODE_FIXED);
binding.dataTabLayout.setupWithViewPager(binding.dataViewpager);
}
}
|
package com.rqhua.demo.lib_annotation_demo;
import android.app.Activity;
import com.rqhua.demo.lib_compile.Constants;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
/**
* Created by Administrator on 2018/6/26.
*/
public class AnnotationDemo {
public static void attach(Activity target) {
// TODO: 2018/6/26 调用生成的类
// 获取 activity 的 Class 对象
Class<? extends Activity> targetCls = target.getClass();
// 获取 activity 的名字
String clsName = targetCls.getName();
try {
// 通过 activity 的 ClassLoader 加载生成的类
Class<?> generatedCls = targetCls.getClassLoader().loadClass(clsName + Constants.fileEnd);
// 找到构造方法
Constructor<?> constructor = generatedCls.getConstructor(targetCls);
if (constructor != null) {
// 创建对象
constructor.newInstance(target);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
} |
package com.gaoshin.onsalelocal.slocal.resource;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.gaoshin.onsalelocal.api.OfferDetailsList;
import com.gaoshin.onsalelocal.slocal.service.SlocalService;
import common.util.web.GenericResponse;
import common.util.web.JerseyBaseResource;
@Path("/ws/slocal")
@Component
public class SlocalResource extends JerseyBaseResource {
@Autowired private SlocalService slocalService;
@Path("seed-city-tasks")
@GET
public GenericResponse seedCityTasks() throws Exception {
slocalService.seedCityTasks();
return new GenericResponse();
}
@Path("deals-by-geo")
@GET
public OfferDetailsList searchOffer(
@QueryParam("lat") float lat,
@QueryParam("lng") float lng,
@QueryParam("radius") int radius,
@QueryParam("offset") @DefaultValue("0") int offset,
@QueryParam("size") @DefaultValue("200") int size
) throws Exception {
return slocalService.searchOffer(lat, lng, radius, offset, size);
}
@Path("geo")
@GET
public GenericResponse geo() {
slocalService.geo();
return new GenericResponse();
}
@Path("ondemand")
@GET
public GenericResponse ondemand(@QueryParam("cityId") String cityId) {
slocalService.ondemand(cityId);
return new GenericResponse();
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jdbc.support;
import java.sql.SQLDataException;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.sql.SQLInvalidAuthorizationSpecException;
import java.sql.SQLNonTransientConnectionException;
import java.sql.SQLRecoverableException;
import java.sql.SQLSyntaxErrorException;
import java.sql.SQLTimeoutException;
import java.sql.SQLTransactionRollbackException;
import java.sql.SQLTransientConnectionException;
import org.junit.jupiter.api.Test;
import org.springframework.dao.CannotAcquireLockException;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.dao.PermissionDeniedDataAccessException;
import org.springframework.dao.PessimisticLockingFailureException;
import org.springframework.dao.QueryTimeoutException;
import org.springframework.dao.RecoverableDataAccessException;
import org.springframework.dao.TransientDataAccessResourceException;
import org.springframework.jdbc.BadSqlGrammarException;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Thomas Risberg
* @author Juergen Hoeller
*/
public class SQLExceptionSubclassTranslatorTests {
@Test
public void exceptionClassTranslation() {
doTest(new SQLDataException("", "", 0), DataIntegrityViolationException.class);
doTest(new SQLFeatureNotSupportedException("", "", 0), InvalidDataAccessApiUsageException.class);
doTest(new SQLIntegrityConstraintViolationException("", "", 0), DataIntegrityViolationException.class);
doTest(new SQLIntegrityConstraintViolationException("", "23505", 0), DuplicateKeyException.class);
doTest(new SQLIntegrityConstraintViolationException("", "23000", 1), DuplicateKeyException.class);
doTest(new SQLIntegrityConstraintViolationException("", "23000", 1062), DuplicateKeyException.class);
doTest(new SQLIntegrityConstraintViolationException("", "23000", 2601), DuplicateKeyException.class);
doTest(new SQLIntegrityConstraintViolationException("", "23000", 2627), DuplicateKeyException.class);
doTest(new SQLInvalidAuthorizationSpecException("", "", 0), PermissionDeniedDataAccessException.class);
doTest(new SQLNonTransientConnectionException("", "", 0), DataAccessResourceFailureException.class);
doTest(new SQLRecoverableException("", "", 0), RecoverableDataAccessException.class);
doTest(new SQLSyntaxErrorException("", "", 0), BadSqlGrammarException.class);
doTest(new SQLTimeoutException("", "", 0), QueryTimeoutException.class);
doTest(new SQLTransactionRollbackException("", "", 0), PessimisticLockingFailureException.class);
doTest(new SQLTransactionRollbackException("", "40001", 0), CannotAcquireLockException.class);
doTest(new SQLTransientConnectionException("", "", 0), TransientDataAccessResourceException.class);
}
@Test
public void fallbackStateTranslation() {
// Test fallback. We assume that no database will ever return this error code,
// but 07xxx will be bad grammar picked up by the fallback SQLState translator
doTest(new SQLException("", "07xxx", 666666666), BadSqlGrammarException.class);
// and 08xxx will be data resource failure (non-transient) picked up by the fallback SQLState translator
doTest(new SQLException("", "08xxx", 666666666), DataAccessResourceFailureException.class);
}
private void doTest(SQLException ex, Class<?> dataAccessExceptionType) {
SQLExceptionTranslator translator = new SQLExceptionSubclassTranslator();
DataAccessException dax = translator.translate("task", "SQL", ex);
assertThat(dax).as("Specific translation must not result in null").isNotNull();
assertThat(dax).as("Wrong DataAccessException type returned").isExactlyInstanceOf(dataAccessExceptionType);
assertThat(dax.getCause()).as("The exact same original SQLException must be preserved").isSameAs(ex);
}
}
|
package instruments;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class GuitarTest {
Guitar guitar;
@Before
public void before(){
guitar = new Guitar(4, GuitarType.BASS, "concrete",
"Guitar", "black", 115, 200, "bring");
}
@Test
public void hasStrings(){
assertEquals(4, guitar.getNumberOfStrings());
}
@Test
public void hasGuitarType(){
assertEquals(GuitarType.BASS, guitar.getGuitarType());
}
@Test
public void hasMaterial(){
assertEquals("concrete", guitar.getMaterial());
}
@Test
public void hasType(){
assertEquals("Guitar", guitar.getType());
}
@Test
public void hasColour(){
assertEquals("black", guitar.getColour());
}
@Test
public void hasMarkupPrice(){
assertEquals(85, guitar.calculateMarkup(), 0.01);
}
@Test
public void canMakeSound(){
assertEquals("bring", guitar.play("bring"));
}
}
|
package com.ut.module_lock.activity;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.example.operation.MyRetrofit;
import com.example.operation.WebSocketHelper;
import com.ut.base.BaseActivity;
import com.ut.base.UIUtils.RouterUtil;
import com.ut.base.UIUtils.SystemUtils;
import com.ut.base.adapter.ListAdapter;
import com.ut.base.common.CommonPopupWindow;
import com.ut.base.dialog.DialogHelper;
import com.ut.database.entity.EnumCollection;
import com.ut.database.entity.LockKey;
import com.ut.module_lock.BR;
import com.ut.module_lock.R;
import com.ut.module_lock.common.Constance;
import com.ut.module_lock.databinding.ActivityKeysManagerBinding;
import com.ut.database.entity.Key;
import com.ut.module_lock.viewmodel.KeyManagerVM;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@Route(path = RouterUtil.LockModulePath.KEY_MANAGER)
public class KeysManagerActivity extends BaseActivity {
private static final int REQUEST_CODE_KEY_INFO = 1121;
private KeyManagerVM kmVM = null;
private ActivityKeysManagerBinding mBinding = null;
private ListAdapter<Key> mAdapter = null;
private List<Key> keyList = new ArrayList<>();
private String mMac = "";
private LockKey lockKey = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBinding = DataBindingUtil.setContentView(this, R.layout.activity_keys_manager);
lockKey = getIntent().getParcelableExtra(Constance.LOCK_KEY);
mMac = lockKey.getMac();
initTitle();
init();
}
private void initTitle() {
initDarkToolbar();
if (lockKey.getUserType() == EnumCollection.UserType.ADMIN.ordinal() || lockKey.getUserType() == EnumCollection.UserType.AUTH.ordinal()) {
initMore(this::popupMoreWindow);
}
setTitle(R.string.func_manage_key);
}
private void init() {
mAdapter = new ListAdapter<Key>(this, R.layout.item_keys_manager, keyList, BR.keyItem) {
@Override
public void handleItem(ViewDataBinding binding, int position) {
kmVM.initKey(keyList.get(position));
ImageView ruleTypeIv = binding.getRoot().findViewById(R.id.tip);
int rId = keyList.get(position).getRuleTypeDrawableId();
ruleTypeIv.setBackgroundResource(rId);
}
};
mBinding.list.setAdapter(mAdapter);
kmVM = ViewModelProviders.of(this).get(KeyManagerVM.class);
kmVM.setMac(mMac);
kmVM.getKeys(mMac).observe(this, (keyItems) -> {
if (keyItems == null) {
keyItems = new ArrayList<>();
}
Collections.sort(keyItems, (o1, o2) -> o1.getStatus() < o2.getStatus() ? -1 : 0);
if (mBinding.list.isLoading()) {
mAdapter.loadDate(keyItems);
mBinding.list.setLoadCompleted();
} else {
mBinding.refreshLayout.setRefreshing(false);
mAdapter.updateDate(keyItems);
mBinding.nodata.setVisibility(keyItems.isEmpty() ? View.VISIBLE : View.GONE);
}
});
mBinding.refreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
android.R.color.holo_green_light, android.R.color.holo_orange_light);
mBinding.refreshLayout.setOnRefreshListener(this::updateData);
mBinding.list.setOnLoadMoreListener(() -> {
loadData();
mBinding.list.postDelayed(() -> {
mBinding.list.setLoadCompleted();
}, 1200L);
});
mBinding.list.setOnItemClickListener((parent, view, position, id) -> {
Key keyItem = keyList.get(position);
if (keyItem.getStatus() != 4) {
keyItem.setMac(mMac);
ARouter.getInstance().build(RouterUtil.LockModulePath.KEY_INFO)
.withInt(Constance.USERTYPE, lockKey.getUserType())
.withSerializable(Constance.KEY_INFO, keyItem)
.navigation(this, REQUEST_CODE_KEY_INFO);
}
});
}
private void popupMoreWindow() {
SystemUtils.setWindowAlpha(this,0.5f);
CommonPopupWindow popupWindow = new CommonPopupWindow(this, R.layout.layout_popup_two_selections,
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT) {
@Override
public void initView() {
if (lockKey.getUserType() == EnumCollection.UserType.ADMIN.ordinal() || lockKey.getUserType() == EnumCollection.UserType.AUTH.ordinal()) {
getView(R.id.item1).setOnClickListener(v -> {
DialogHelper.getInstance()
.setMessage(getString(R.string.lock_clear_all_keys_tips))
.setPositiveButton(getString(R.string.lock_clear), ((dialog, which) -> {
clearKey(lockKey.getMac());
mBinding.refreshLayout.postDelayed(KeysManagerActivity.this::updateData, 500L);
}))
.setNegativeButton(getString(R.string.lock_cancel), null)
.show();
getPopupWindow().dismiss();
});
} else {
getView(R.id.item1).setVisibility(View.GONE);
}
getView(R.id.item2).setOnClickListener(v -> {
sendKey();
getPopupWindow().dismiss();
});
getView(R.id.close_window).setOnClickListener(v -> getPopupWindow().dismiss());
setLightStatusBar();
}
@Override
protected void initWindow() {
super.initWindow();
getPopupWindow().setOnDismissListener(() -> {
SystemUtils.setWindowAlpha(KeysManagerActivity.this,1f);
setDarkStatusBar();
}
);
}
};
popupWindow.showAtLocationWithAnim(mBinding.getRoot(), Gravity.TOP, 0, 0, R.style.animTranslate);
}
private void updateData() {
mBinding.refreshLayout.setRefreshing(true);
kmVM.updateKeyItems();
mBinding.refreshLayout.postDelayed(() -> {
mBinding.refreshLayout.setRefreshing(false);
}, 1200L);
}
private void loadData() {
kmVM.loadKeyItems();
}
private void sendKey() {
ARouter.getInstance().build(RouterUtil.BaseModulePath.SEND_KEY)
.withString(RouterUtil.LockModuleExtraKey.EXTRA_LOCK_SENDKEY_MAC, mMac)
.withInt(RouterUtil.LockModuleExtraKey.EXTRA_LOCK_KEY_USERTYPE, lockKey.getUserType())
.navigation();
}
private void clearKey(String mac) {
kmVM.clearKeys(mac);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
@Override
protected void onResume() {
super.onResume();
updateData();
}
@Override
protected void onWebSocketOpened() {
super.onWebSocketOpened();
updateData();
}
}
|
package com.ledungcobra.entites;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
@Table(name = "CLASS", uniqueConstraints = @UniqueConstraint(name = "UK_CLASS", columnNames = {"CLASS_NAME"}))
@Getter
@Setter
@NoArgsConstructor
@EqualsAndHashCode(onlyExplicitlyIncluded = true, callSuper = false)
public class Class extends BaseEntity
{
@Id
@Column(name = "CLASS_ID")
@EqualsAndHashCode.Include
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "CLASS_NAME")
private String className;
@ManyToOne
@JoinColumn(name = "CREATED_BY", foreignKey = @ForeignKey(name = "FK_CLASS_TEACHING_MANAGER"))
private TeachingManager createdBy;
@OneToMany(mappedBy = "studiedClass", fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST})
private List<StudentAccount> students = new ArrayList<>();
@Override
public String toString()
{
return this.className;
}
}
|
package com.performance.optimization.design.observer;
import org.junit.Test;
/**
* 观察者模式测试
* @author qiaolin
*
*/
public class ObserverTest {
@Test
public void test(){
ConcreteSubject subject = new ConcreteSubject();
subject.attach(new ConcreteObserver());//观察者加入
subject.attach(new ConcreteObserver());//添加观察者
subject.inform();//通知观察者
}
@Test
public void testJDK(){
JdkSubject subject = new JdkSubject();
subject.addObserver(new JdkObserver());
subject.addObserver(new JdkObserver());
//通知所有观察者
subject.notifyObservers(null);
}
}
|
package com.qfc.yft;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import com.ggwork.net.socket.SocketBuild;
import com.qfc.yft.entity.Category;
import com.qfc.yft.entity.Company;
import com.qfc.yft.entity.Series;
import com.qfc.yft.entity.SimpleCompany;
import com.qfc.yft.entity.User;
import com.qfc.yft.entity.listitem.LIIPeople;
import com.qfc.yft.entity.listitem.LIIProduct;
import com.qfc.yft.entity.offline.OfflineData;
import com.qfc.yft.entity.page.QfcPageInfo;
import com.qfc.yft.ui.AllAdapterControl;
import com.qfc.yft.ui.BuildData;
import com.qfc.yft.ui.ConversationListAdapter;
import com.qfc.yft.ui.custom.list.ListAbsAdapter.ListItemImpl;
import com.qfc.yft.utils.JackUtils;
import android.app.NotificationManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
import android.util.SparseArray;
import android.widget.TabHost;
public class YftData {
private static YftData yData;
private YftData(){};
public static YftData data(){
if(yData==null){
yData = new YftData();
}
return yData;
}
public void destroy(){
yData=null;
}
private Map<Integer, Company> companyMap; //<shopId,company>
public Map<Integer, Company> getCompanyMap(){
if(companyMap==null) companyMap = new HashMap<Integer, Company>();
return companyMap;
}
/*
* category
*/
// List<Category> categoryList;
SparseArray< Category> categoryAllMap;
public Category getCategorySecond(int cid) {
if(categoryAllMap==null) return null;
return categoryAllMap.get(cid);
}
public void putCategory(Category cate){
if(categoryAllMap==null) categoryAllMap = new SparseArray< Category>();
categoryAllMap.put(cate.getCateId(), cate);
}
public boolean isCatInited(){
return null!=categoryAllMap&&categoryAllMap.size()>0;
}
/*
* user
*/
private User currentUser,meUser;
public boolean isMe(){
return currentUser==meUser;
}
public void setMeCurrentUser(){
this.currentUser = meUser;
}
public User getCurrentUser() {
return currentUser;
}
public void setMe(User user){
this.meUser = user;
}
public User getMe(){
return meUser;
}
public void setCurrentUser(User currentUser) {
this.currentUser = currentUser;
}
/*
* offline
*/
private SharedPreferences offlinePreference;
private OfflineData offlineData;
public String getOffStr(String key){
String result="";
if(offlinePreference!=null) result = offlinePreference.getString(key, "");
return result;
}
public void setOfflineEnable(boolean enable){
Editor editor = getOffEditor();
if(editor!=null) editor.putBoolean("enable", enable).commit();
}
public boolean isOfflineEnabled(){
SharedPreferences pref = getOffPref();
if(pref!=null){
return pref.getBoolean("enable", false);
}
return false;
}
public SharedPreferences getOffPref(){
return offlinePreference;
}
public void setOffPref(SharedPreferences pref){//mainactivity oncreate inited
this.offlinePreference = pref;
}
public OfflineData getOfflineData(){
if(offlineData==null) {
SharedPreferences pref = getOffPref();
if(pref!=null){
String json = pref.getString(meUser.getShopId()+"", "");
if(!json.isEmpty()){
try {
offlineData = new OfflineData(new JSONObject(json));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
return offlineData;//null?
}
private Editor offlineEditor;
public Editor getOffEditor() {
if(offlineEditor==null&&offlinePreference!=null){
offlineEditor = offlinePreference.edit();
}
return offlineEditor;
}
public void commitOffPref(){
commitOffPref(meUser.getShopId()+"", offlineData.toJsonStr());
}
public boolean commitOffPref(String key,String value){
if(isOffDatCommittable()) return getOffEditor().putString(key, value).commit();
return false;
}
private boolean isOffDatCommittable(){
return offlinePreference!=null&&offlineData!=null&&meUser!=null&&meUser.getShopId()>0;
}
public void setOffline(OfflineData od){
this.offlineData = od;
}
public boolean clearOffPref(){
offlineData=null;
return getOffEditor().clear().commit();
}
/*store*/
SparseArray<LIIProduct> productMap;
SparseArray<LIIPeople> peopleMap;
SparseArray<SimpleCompany> scMap;
public void storeShopById(SimpleCompany lc) {//0318
if(null==scMap) scMap = new SparseArray<SimpleCompany>();
scMap.put(lc.userId, lc);
}
public SimpleCompany getStoredShop(int scuid){
if(null==scMap) return null;
return scMap.get(scuid);
}
public void storeProduct(LIIProduct product) {
if(null==productMap) productMap = new SparseArray<LIIProduct>();
productMap.put(product.getProductId(), product);
}
public LIIProduct getStoredProduct(int pid){
if(null==productMap) return null;
return productMap.get(pid);
}
public void storePerson(LIIPeople peop) {
if(null==peop) return;
if(null==peopleMap) peopleMap = new SparseArray<LIIPeople>();
peopleMap.put(peop.accountId, peop);
}
public LIIPeople getStoredPerson(int pid) {
if(null==peopleMap) return null;
return peopleMap.get(pid);
}
/*host*/
TabHost mTabHost;
public void setHostTab(TabHost mTabHost) {
this.mTabHost = mTabHost;
}
public TabHost getHostTab(){
return mTabHost;
}
//timeout store
private Map<String, QfcPageInfo> pageInfoMap;
private Map<String,Long> pageInfoTimeMap;
public QfcPageInfo getPageInfo(int shopId,int seriesId,int page){//1203
if(pageInfoMap==null||pageInfoTimeMap==null) return null;
String key = getPageInfoKey(shopId, seriesId, page);
Long thatTime = pageInfoTimeMap.get(key);
if(thatTime==null) return null;
if(System.currentTimeMillis()-thatTime>YftValues.TIMEOUT_REQUEST) return null;
return pageInfoMap.get(key);
}
public void addPageInfo(int shopId,int seriesId,int page,QfcPageInfo pi){
if(pi==null) return;
if(pageInfoMap==null) pageInfoMap = new HashMap<String, QfcPageInfo>();
if(pageInfoTimeMap==null) pageInfoTimeMap = new HashMap<String, Long>();
String key = getPageInfoKey(shopId, seriesId, page);
pageInfoMap.put(key, pi);
pageInfoTimeMap.put(key, System.currentTimeMillis());
}
private String getPageInfoKey(int shopId,int sid,int page){
return shopId+"_"+sid+"_"+page;
}
private Map<Integer, List<Series>> allUserSeriesMap;
private Map<Integer,Long> userSeriesTimeMap;
private Map<Integer, List<Series>> getAllUserSeriesMap(){
if(allUserSeriesMap==null) allUserSeriesMap = new HashMap<Integer, List<Series>>();
return allUserSeriesMap;
}
private Map<Integer,Long> getUserSeriesTimeMap(){
if(userSeriesTimeMap==null) userSeriesTimeMap = new HashMap<Integer, Long>();
return userSeriesTimeMap;
}
public List<Series> getSeriesList(int shopId){
Long thatTime = getUserSeriesTimeMap().get(shopId);
if(thatTime==null) return null;
if(System.currentTimeMillis()-thatTime>YftValues.TIMEOUT_REQUEST_10) return null;
return getAllUserSeriesMap().get(shopId);
}
public void putSeriesList(int sid, List<Series> list){
getAllUserSeriesMap().put(sid, list);
getUserSeriesTimeMap().put(sid, System.currentTimeMillis());
}
NotificationManager nm;
public NotificationManager getNotificationManager() {
if(null==nm)nm = (NotificationManager)YftApplication.app(). getSystemService(Context.NOTIFICATION_SERVICE);
return nm;
}
ConversationListAdapter convListAdapter;
public ConversationListAdapter getConvListAdapter() {
if(null==convListAdapter){
convListAdapter = new ConversationListAdapter(YftApplication.app());
//2.AllAdapterControl
AllAdapterControl.getInstance().setConversationlistAdapter(convListAdapter);
//3.buildData
final List<Long> idArrs = BuildData.getInstance().fullConversation(YftApplication.app(), convListAdapter);
new Thread() {
public void run() {
SocketBuild.sendConversation(idArrs);
}
}.start();
}
return convListAdapter;
}
String myChatName;
public void setMyChatName(String userName) {
this.myChatName = userName;
}
public String getMyChatName(){
return myChatName!=null?myChatName:"" ;
}
public boolean hasFZL(){
User user = getMe();
return null!=user&&user.getMemberType()>2;
}
}
|
package com.esum.framework.product.license;
import java.util.Calendar;
import com.esum.framework.common.util.DateUtil;
public class LicenseManager {
private static LicenseValidator validator = new LicenseValidator();
public static void validate(String licenseFilePath, String installPathSysVariable,
String installPathSysValue) throws LicenseException {
validator = new LicenseValidator();
validator.validate(licenseFilePath, installPathSysVariable, installPathSysValue);
}
public static void validate(String licenseString) throws LicenseException {
validator = new LicenseValidator();
validator.validate(licenseString);
}
public static boolean isTrial() {
return validator.getLicense().isTrial();
}
public static int getMaxTpCount(){
if(validator.getLicense().isTrial())
return getProductType().equals(LicenseConstants.PRDUCT_TYPE_XTRUS)?0:3;
return validator.getLicense().getMaxTpCount();
}
public static int getMaxUserCount(){
if(validator.getLicense().isTrial())
return getProductType().equals(LicenseConstants.PRDUCT_TYPE_XTRUS)?0:5;
return validator.getLicense().getMaxUserCount();
}
public static int getMaxRoutingCount(){
if(validator.getLicense().isTrial())
return getProductType().equals(LicenseConstants.PRDUCT_TYPE_XTRUS)?0:2;
return validator.getLicense().getMaxRoutingCount();
}
public static int getMaxComponentCount(){
if(validator.getLicense().isTrial())
return getProductType().equals(LicenseConstants.PRDUCT_TYPE_XTRUS)?0:3;
return validator.getLicense().getMaxComponentCount();
}
public static int getMaxParsingRuleCount(){
if(validator.getLicense().isTrial())
return getProductType().equals(LicenseConstants.PRDUCT_TYPE_XTRUS)?0:2;
return validator.getLicense().getMaxParsingRuleCount();
}
public static String getProductType(){
if(validator.getLicense().isTrial())
return LicenseConstants.PRDUCT_TYPE_XTRUS;
return validator.getLicense().getProductType();
}
public static int getCompanyInternalCount(){
if(validator.getLicense().isTrial())
return getProductType().equals(LicenseConstants.PRDUCT_TYPE_XTRUS)?0:1;
return validator.getLicense().getCompanyInternalCount();
}
public static int getCompanyExternalCount(){
if(validator.getLicense().isTrial())
return getProductType().equals(LicenseConstants.PRDUCT_TYPE_XTRUS)?0:1;
return validator.getLicense().getCompanyExternalCount();
}
public static String getValidTo() {
if(validator.getLicense().isTrial())
return "Trial";
long expireTime = validator.getLicense().getLicenseExpireTime();
if(expireTime==0)
return "UnLimited";
Calendar c = Calendar.getInstance();
c.setTimeInMillis(validator.getLicense().getLicenseExpireTime());
return DateUtil.format("yyyy.MM.dd", c.getTime());
}
}
|
package dao;
import entities.CoffeeOrderItem;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.List;
public interface CoffeeOrderItemDao extends DAO<CoffeeOrderItem> {
/**
* get all records of CoffeeOrderItem from DB for definite CoffeeOrder with id = orderId
*
* @param orderId determines id for CoffeeOrder
* @return a list of all records of CoffeeOrderItem from the database
* for definite CoffeeOrder with id = orderId or
* empty list if there are no entries found.
* @throws SQLException if there is an error connecting to the database
*/
List<CoffeeOrderItem> getAllForOrderId(Serializable orderId) throws SQLException;
}
|
package _DAO;
import java.sql.*;
import _DTO.Member;
public class MemberDAO {
private MemberDAO() {}
private static MemberDAO dao = new MemberDAO();
public static MemberDAO getInstance() {
return dao;
}
public int getIdCheck(String id) {
int col = -1;
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
String sql = "select count(*) from member where u_id = ?";
try {
conn = DBConn.getConnect();
ps = conn.prepareStatement(sql);
ps.setString(1, id);
rs = ps.executeQuery();
if(rs.next()) {
col = rs.getInt(1);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBConn.close(rs);
DBConn.close(ps);
DBConn.close(conn);
}
return col;
}
public void insertMember(Member m) {
Connection conn = null;
PreparedStatement ps = null;
String sql = "insert into member(uno,u_id,u_pw,u_name,u_birth,u_tel,u_address) values(mem_seq.nextval, ?,?,?,?,?,?)";
try {
conn = DBConn.getConnect();
ps = conn.prepareStatement(sql);
ps.setString(1, m.getU_id());
ps.setString(2, m.getU_pw());
ps.setString(3, m.getU_name());
ps.setDate(4, m.getU_birth());
ps.setString(5, m.getU_tel());
ps.setString(6, m.getU_address());
int n = ps.executeUpdate();
if(n != 0) {
DBConn.commit(conn);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBConn.close(ps);
DBConn.close(conn);
}
}
public int loginMember(String id, String pw) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
String sql = "select uno from member where u_id = ? and u_pw = ?";
int uno = 0;
try {
conn = DBConn.getConnect();
ps = conn.prepareStatement(sql);
ps.setString(1, id);
ps.setString(2, pw);
rs = ps.executeQuery();
while (rs.next()) {
uno = rs.getInt(1);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBConn.close(rs);
DBConn.close(ps);
DBConn.close(conn);
}
return uno;
}
public Member getMemberInfo(int uno) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
Member m = new Member();
String sql = "select * from member where uno=?";
try {
conn = DBConn.getConnect();
ps = conn.prepareStatement(sql);
ps.setInt(1, uno);
rs = ps.executeQuery();
while (rs.next()) {
m.setUno(rs.getInt("uno"));
m.setU_id(rs.getString("u_id"));
m.setU_pw(rs.getString("u_pw"));
m.setU_name(rs.getString("u_name"));
m.setU_birth(rs.getDate("u_birth"));
m.setU_tel(rs.getString("u_tel"));
m.setU_address(rs.getString("u_address"));
m.setU_point(rs.getInt("u_point"));
m.setU_grade(rs.getInt("u_grade"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBConn.close(rs);
DBConn.close(ps);
DBConn.close(conn);
}
return m;
}
public int updateMemberInfo(String id, String pw, String tel, String addr) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
int uno = -1;
String sql = "update member set u_pw=?, u_tel=?, u_address=? where u_id=?";
String sql2 = "select uno from member where u_id = ?";
try {
conn = DBConn.getConnect();
ps = conn.prepareStatement(sql);
ps.setString(1,pw);
ps.setString(2,tel);
ps.setString(3,addr);
ps.setString(4,id);
int n = ps.executeUpdate();
ps.close();
ps = conn.prepareStatement(sql2);
ps.setString(1, id);
rs = ps.executeQuery();
while(rs.next()) {
uno = rs.getInt("uno");
}
if(n != 0 && uno != -1) {
DBConn.commit(conn);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBConn.close(ps);
DBConn.close(conn);
}
return uno;
}
} |
package rabbitmq.mq.config;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import rabbitmq.mq.contract.exchange.RabbitmqExchange;
import rabbitmq.mq.contract.queue.RabbitmqQueue;
/**
* 针对服务性rabbitmq配置,如:contract,tenant同时使用contract的交换机,但使用不同的queue队列进行信息发送
* 基本使用的为topic,
* 此处更多是以案例给出
*/
@Configuration
public class ContractExchangeConfig {
// /**
// * 合同广播型
// *
// * @param rabbitAdmin
// * @return
// */
// @Bean
// FanoutExchange contractFanoutExchange(RabbitAdmin rabbitAdmin) {
// FanoutExchange contractFanoutExchange = new FanoutExchange(RabbitmqExchange.CONTRACT_FANOUT);
// rabbitAdmin.declareExchange(contractFanoutExchange);
// return contractFanoutExchange;
// }
/**
* 合同->匹配型 默认:, durable = true, autoDelete = false
*
* @param rabbitAdmin
* @return
*/
@Bean
TopicExchange contractTopicExchangeDurable(RabbitAdmin rabbitAdmin) {
TopicExchange contractTopicExchange = new TopicExchange(RabbitmqExchange.CONTRACT_TOPIC);
rabbitAdmin.declareExchange(contractTopicExchange);
return contractTopicExchange;
}
/**
* 合同直连型
*
* @param rabbitAdmin
* @return
*/
@Bean
DirectExchange contractDirectExchange(RabbitAdmin rabbitAdmin) {
DirectExchange contractDirectExchange = new DirectExchange(RabbitmqExchange.CONTRACT_DIRECT);
rabbitAdmin.declareExchange(contractDirectExchange);
return contractDirectExchange;
}
// @Bean
// Binding bindingExchangeContract(Queue queueContract, FanoutExchange exchange, RabbitAdmin rabbitAdmin) {
// Binding binding = BindingBuilder.bind(queueContract).to(exchange);
// rabbitAdmin.declareBinding(binding);
// return binding;
// }
@Bean
Binding bindingExchangeContract(Queue queueContract, TopicExchange exchange, RabbitAdmin rabbitAdmin) {
Binding binding = BindingBuilder.bind(queueContract).to(exchange).with(RabbitmqQueue.CONTRACE_SELF);
rabbitAdmin.declareBinding(binding);
return binding;
}
@Bean
Binding bindingExchangeContract(Queue queueContract, DirectExchange exchange, RabbitAdmin rabbitAdmin) {
Binding binding = BindingBuilder.bind(queueContract).to(exchange).with(RabbitmqQueue.CONTRACE_SELF);
rabbitAdmin.declareBinding(binding);
return binding;
}
@Bean
Binding bindingExchangeTenant(Queue queueTenant, TopicExchange exchange, RabbitAdmin rabbitAdmin) {
Binding binding = BindingBuilder.bind(queueTenant).to(exchange).with(RabbitmqQueue.CONTRACE_TENANT);
rabbitAdmin.declareBinding(binding);
return binding;
}
@Bean
Binding bindingExchangeTenant(Queue queueTenant, DirectExchange exchange, RabbitAdmin rabbitAdmin) {
Binding binding = BindingBuilder.bind(queueTenant).to(exchange).with(RabbitmqQueue.CONTRACE_TENANT);
rabbitAdmin.declareBinding(binding);
return binding;
}
/**
* 所有关于contract exchange的queue
*
* @param rabbitAdmin
* @return
*/
@Bean
Queue queueContract(RabbitAdmin rabbitAdmin) {
Queue queue = new Queue(RabbitmqQueue.CONTRACE_SELF, true);
rabbitAdmin.declareQueue(queue);
return queue;
}
@Bean
Queue queueTenant(RabbitAdmin rabbitAdmin) {
Queue queue = new Queue(RabbitmqQueue.CONTRACE_TENANT, true);
rabbitAdmin.declareQueue(queue);
return queue;
}
} |
package com.example.marvelapp.comics;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class Creators {
@SerializedName("available")
private Integer available;
@SerializedName("collectionURI")
private String collectionURI;
@SerializedName("creatorItems")
private List<CreatorItem> creatorItems = null;
@SerializedName("returned")
private Integer returned;
public Integer getAvailable() {
return available;
}
public String getCollectionURI() {
return collectionURI;
}
public List<CreatorItem> getCreatorItems() {
return creatorItems;
}
public Integer getReturned() {
return returned;
}
}
|
package com.tyland.musicbox.ui;
import android.animation.ObjectAnimator;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import com.tyland.musicbox.ActionConstant;
import com.tyland.musicbox.R;
import com.tyland.musicbox.model.Lrc;
import com.tyland.musicbox.service.PlayState;
import com.tyland.musicbox.util.Log;
import com.tyland.musicbox.util.PermissionUtils;
import com.tyland.musicbox.util.Utils;
import com.tyland.musicbox.widget.LrcView;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
/**
* Created by tyland on 2018/5/12.
*/
public class PlayingActivity extends BaseActivity implements SeekBar.OnSeekBarChangeListener {
private TextView tvNowPosition;
private TextView tvEndPosition;
private SeekBar sbProgress;
private Button btnStop;
private LrcView mLrcView;
private List<String> lrcPath;
private List<Lrc> lrcs;
private Timer timer;
private ObjectAnimator mRotateAnimator;
private static final String LRC_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "Download";
@Override
protected void setupView() {
setContentView(R.layout.activity_playing);
btnBack = (Button) findViewById(R.id.btn_back);
tvMusicTitle = (TextView) findViewById(R.id.tv_music_title);
ivAlbum = (ImageView) findViewById(R.id.iv_album_music);
tvMusicArtist = (TextView) findViewById(R.id.tv_music_artist);
btnPlay = (Button) findViewById(R.id.btn_play);
btnPrevious = (Button) findViewById(R.id.btn_previous);
btnNext = (Button) findViewById(R.id.btn_next);
tvNowPosition = (TextView) findViewById(R.id.tv_now_positon);
tvEndPosition = (TextView) findViewById(R.id.tv_end_position);
sbProgress = (SeekBar) findViewById(R.id.sb_music_progress);
btnStop = (Button) findViewById(R.id.btn_stop);
mLrcView = (LrcView) findViewById(R.id.tv_music_lyric);
btnStop.setOnClickListener(this);
sbProgress.setOnSeekBarChangeListener(this);
mRotateAnimator = ObjectAnimator.ofFloat(ivAlbum, "rotation", 0.0f, 360.0f);
mRotateAnimator.setDuration(10000);
mRotateAnimator.setInterpolator(new LinearInterpolator());
mRotateAnimator.setRepeatCount(-1);
mRotateAnimator.setRepeatMode(ObjectAnimator.RESTART);
mLrcView.setService(getService());
mLrcView.init();
if (checkSelfPermission(PermissionUtils.CODE_READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
onPermissionGranted(PermissionUtils.CODE_READ_EXTERNAL_STORAGE);
} else {
requestPermission(PermissionUtils.CODE_READ_EXTERNAL_STORAGE);
}
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
tvNowPosition.setText(Utils.timeFormatTommss(progress));
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
protected void onPermissionGranted(int requestCode) {
Log.d("path:" + LRC_PATH);
lrcPath = Utils.getLrcPath(LRC_PATH);
lrcs = new ArrayList<>();
if (lrcPath != null && !lrcPath.isEmpty()) {
for (String path : lrcPath) {
String lrcStr = Utils.readFile(path);
Log.d("lrcStr:" + lrcStr);
Lrc lrc = Utils.parseStr2Lrc(lrcStr);
lrcs.add(lrc);
}
initLrc();
}
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
int progress = sbProgress.getProgress();
getService().setProgress(progress);
}
@Override
protected void refreshView(Intent intent) {
super.refreshView(intent);
if (intent != null && intent.getAction().equals(ActionConstant.ACTION_MUSIC_CHANGE)) {
initLrc();
sbProgress.setProgress(0);
mRotateAnimator.end();
ivAlbum.clearAnimation();
}
sbProgress.setMax((int) getService().getCurrentMusic().getDuration());
if (getService().getPlayState() == PlayState.STOP) {
sbProgress.setProgress(0);
tvNowPosition.setText("00:00");
ivAlbum.clearAnimation();
} else {
sbProgress.setProgress(getService().getCurrentPlayPosition());
tvNowPosition.setText(Utils.timeFormatTommss(getService().getCurrentPlayPosition()));
}
tvEndPosition.setText(Utils.timeFormatTommss(getService().getCurrentMusic().getDuration()));
setTimer();
updateAnim();
}
private void initLrc() {
try {
if (lrcs != null && !lrcs.isEmpty()) {
boolean hasLrc = false;
for (Lrc lrc : lrcs) {
if (getService().getCurrentMusic().getAlbum().equals(lrc.getAlbum()) && getService().getCurrentMusic().getTitle().equals(lrc.getTitle())) {
mLrcView.setLrc(lrc);
hasLrc = true;
break;
}
}
if (!hasLrc) {
Log.d("no lrc....");
mLrcView.setLrc(null);
}
}
} catch (NullPointerException e) {
mLrcView.setLrc(null);
} finally {
mLrcView.init();
}
}
@TargetApi(Build.VERSION_CODES.KITKAT)
private void updateAnim() {
if (getService().getPlayState() == PlayState.PLAYING) {
if (mRotateAnimator.isPaused()) {
mRotateAnimator.resume();
} else {
mRotateAnimator.start();
}
} else if (getService().getPlayState() == PlayState.PAUSE) {
mRotateAnimator.pause();
} else {
mRotateAnimator.end();
}
}
private void setTimer() {
if (timer == null) {
timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
if (getService().getPlayState() == PlayState.PLAYING) {
int progress = sbProgress.getProgress();
progress += 500;
sbProgress.setProgress(progress);
}
}
};
timer.schedule(task, 500, 500);
}
}
@Override
public void onClick(View v) {
super.onClick(v);
switch (v.getId()) {
case R.id.btn_stop:
getService().stop();
break;
case R.id.btn_previous:
case R.id.btn_next:
sbProgress.setProgress(0);
break;
}
}
@Override
protected void setEmptyMusicView() {
super.setEmptyMusicView();
sbProgress.setProgress(0);
tvNowPosition.setText("00:00");
tvEndPosition.setText("00:00");
mRotateAnimator.end();
ivAlbum.clearAnimation();
}
@Override
protected int getDefaultAlbumId() {
return R.drawable.img_default_record;
}
@Override
public void finish() {
super.finish();
mRotateAnimator.end();
ivAlbum.clearAnimation();
}
}
|
package com.GestiondesClub.dto;
import java.util.List;
import com.GestiondesClub.entities.DemandeAffiche;
import com.GestiondesClub.entities.EvenementSponseur;
import com.GestiondesClub.entities.EvenementTarif;
import com.GestiondesClub.entities.ProgrammeEvent;
public interface EventAllAffiche {
Long getId();
NotifOnly getDemandeEvenement();
List<DemandeAffiche> getLesDemandeAffiche();
List<ProgrammeEvent> getLesProgrammes();
List<EvenementSponseur> getLesSponseur();
}
|
/*
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.annotation;
import java.lang.annotation.Annotation;
import java.util.Collection;
import java.util.Iterator;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
/**
* {@link MergedAnnotations} implementation backed by a {@link Collection} of
* {@link MergedAnnotation} instances that represent direct annotations.
*
* @author Phillip Webb
* @since 5.2
* @see MergedAnnotations#of(Collection)
*/
final class MergedAnnotationsCollection implements MergedAnnotations {
private final MergedAnnotation<?>[] annotations;
private final AnnotationTypeMappings[] mappings;
private MergedAnnotationsCollection(Collection<MergedAnnotation<?>> annotations) {
Assert.notNull(annotations, "Annotations must not be null");
this.annotations = annotations.toArray(new MergedAnnotation<?>[0]);
this.mappings = new AnnotationTypeMappings[this.annotations.length];
for (int i = 0; i < this.annotations.length; i++) {
MergedAnnotation<?> annotation = this.annotations[i];
Assert.notNull(annotation, "Annotation must not be null");
Assert.isTrue(annotation.isDirectlyPresent(), "Annotation must be directly present");
Assert.isTrue(annotation.getAggregateIndex() == 0, "Annotation must have aggregate index of zero");
this.mappings[i] = AnnotationTypeMappings.forAnnotationType(annotation.getType());
}
}
@Override
public Iterator<MergedAnnotation<Annotation>> iterator() {
return Spliterators.iterator(spliterator());
}
@Override
public Spliterator<MergedAnnotation<Annotation>> spliterator() {
return spliterator(null);
}
private <A extends Annotation> Spliterator<MergedAnnotation<A>> spliterator(@Nullable Object annotationType) {
return new AnnotationsSpliterator<>(annotationType);
}
@Override
public <A extends Annotation> boolean isPresent(Class<A> annotationType) {
return isPresent(annotationType, false);
}
@Override
public boolean isPresent(String annotationType) {
return isPresent(annotationType, false);
}
@Override
public <A extends Annotation> boolean isDirectlyPresent(Class<A> annotationType) {
return isPresent(annotationType, true);
}
@Override
public boolean isDirectlyPresent(String annotationType) {
return isPresent(annotationType, true);
}
private boolean isPresent(Object requiredType, boolean directOnly) {
for (MergedAnnotation<?> annotation : this.annotations) {
Class<? extends Annotation> type = annotation.getType();
if (type == requiredType || type.getName().equals(requiredType)) {
return true;
}
}
if (!directOnly) {
for (AnnotationTypeMappings mappings : this.mappings) {
for (int i = 1; i < mappings.size(); i++) {
AnnotationTypeMapping mapping = mappings.get(i);
if (isMappingForType(mapping, requiredType)) {
return true;
}
}
}
}
return false;
}
@Override
public <A extends Annotation> MergedAnnotation<A> get(Class<A> annotationType) {
return get(annotationType, null, null);
}
@Override
public <A extends Annotation> MergedAnnotation<A> get(Class<A> annotationType,
@Nullable Predicate<? super MergedAnnotation<A>> predicate) {
return get(annotationType, predicate, null);
}
@Override
public <A extends Annotation> MergedAnnotation<A> get(Class<A> annotationType,
@Nullable Predicate<? super MergedAnnotation<A>> predicate,
@Nullable MergedAnnotationSelector<A> selector) {
MergedAnnotation<A> result = find(annotationType, predicate, selector);
return (result != null ? result : MergedAnnotation.missing());
}
@Override
public <A extends Annotation> MergedAnnotation<A> get(String annotationType) {
return get(annotationType, null, null);
}
@Override
public <A extends Annotation> MergedAnnotation<A> get(String annotationType,
@Nullable Predicate<? super MergedAnnotation<A>> predicate) {
return get(annotationType, predicate, null);
}
@Override
public <A extends Annotation> MergedAnnotation<A> get(String annotationType,
@Nullable Predicate<? super MergedAnnotation<A>> predicate,
@Nullable MergedAnnotationSelector<A> selector) {
MergedAnnotation<A> result = find(annotationType, predicate, selector);
return (result != null ? result : MergedAnnotation.missing());
}
@SuppressWarnings("unchecked")
@Nullable
private <A extends Annotation> MergedAnnotation<A> find(Object requiredType,
@Nullable Predicate<? super MergedAnnotation<A>> predicate,
@Nullable MergedAnnotationSelector<A> selector) {
if (selector == null) {
selector = MergedAnnotationSelectors.nearest();
}
MergedAnnotation<A> result = null;
for (int i = 0; i < this.annotations.length; i++) {
MergedAnnotation<?> root = this.annotations[i];
AnnotationTypeMappings mappings = this.mappings[i];
for (int mappingIndex = 0; mappingIndex < mappings.size(); mappingIndex++) {
AnnotationTypeMapping mapping = mappings.get(mappingIndex);
if (!isMappingForType(mapping, requiredType)) {
continue;
}
MergedAnnotation<A> candidate = (mappingIndex == 0 ? (MergedAnnotation<A>) root :
TypeMappedAnnotation.createIfPossible(mapping, root, IntrospectionFailureLogger.INFO));
if (candidate != null && (predicate == null || predicate.test(candidate))) {
if (selector.isBestCandidate(candidate)) {
return candidate;
}
result = (result != null ? selector.select(result, candidate) : candidate);
}
}
}
return result;
}
@Override
public <A extends Annotation> Stream<MergedAnnotation<A>> stream(Class<A> annotationType) {
return StreamSupport.stream(spliterator(annotationType), false);
}
@Override
public <A extends Annotation> Stream<MergedAnnotation<A>> stream(String annotationType) {
return StreamSupport.stream(spliterator(annotationType), false);
}
@Override
public Stream<MergedAnnotation<Annotation>> stream() {
return StreamSupport.stream(spliterator(), false);
}
private static boolean isMappingForType(AnnotationTypeMapping mapping, @Nullable Object requiredType) {
if (requiredType == null) {
return true;
}
Class<? extends Annotation> actualType = mapping.getAnnotationType();
return (actualType == requiredType || actualType.getName().equals(requiredType));
}
static MergedAnnotations of(Collection<MergedAnnotation<?>> annotations) {
Assert.notNull(annotations, "Annotations must not be null");
if (annotations.isEmpty()) {
return TypeMappedAnnotations.NONE;
}
return new MergedAnnotationsCollection(annotations);
}
private class AnnotationsSpliterator<A extends Annotation> implements Spliterator<MergedAnnotation<A>> {
@Nullable
private final Object requiredType;
private final int[] mappingCursors;
public AnnotationsSpliterator(@Nullable Object requiredType) {
this.mappingCursors = new int[annotations.length];
this.requiredType = requiredType;
}
@Override
public boolean tryAdvance(Consumer<? super MergedAnnotation<A>> action) {
int lowestDistance = Integer.MAX_VALUE;
int annotationResult = -1;
for (int annotationIndex = 0; annotationIndex < annotations.length; annotationIndex++) {
AnnotationTypeMapping mapping = getNextSuitableMapping(annotationIndex);
if (mapping != null && mapping.getDistance() < lowestDistance) {
annotationResult = annotationIndex;
lowestDistance = mapping.getDistance();
}
if (lowestDistance == 0) {
break;
}
}
if (annotationResult != -1) {
MergedAnnotation<A> mergedAnnotation = createMergedAnnotationIfPossible(
annotationResult, this.mappingCursors[annotationResult]);
this.mappingCursors[annotationResult]++;
if (mergedAnnotation == null) {
return tryAdvance(action);
}
action.accept(mergedAnnotation);
return true;
}
return false;
}
@Nullable
private AnnotationTypeMapping getNextSuitableMapping(int annotationIndex) {
AnnotationTypeMapping mapping;
do {
mapping = getMapping(annotationIndex, this.mappingCursors[annotationIndex]);
if (mapping != null && isMappingForType(mapping, this.requiredType)) {
return mapping;
}
this.mappingCursors[annotationIndex]++;
}
while (mapping != null);
return null;
}
@Nullable
private AnnotationTypeMapping getMapping(int annotationIndex, int mappingIndex) {
AnnotationTypeMappings mappings = MergedAnnotationsCollection.this.mappings[annotationIndex];
return (mappingIndex < mappings.size() ? mappings.get(mappingIndex) : null);
}
@Nullable
@SuppressWarnings("unchecked")
private MergedAnnotation<A> createMergedAnnotationIfPossible(int annotationIndex, int mappingIndex) {
MergedAnnotation<?> root = annotations[annotationIndex];
if (mappingIndex == 0) {
return (MergedAnnotation<A>) root;
}
IntrospectionFailureLogger logger = (this.requiredType != null ?
IntrospectionFailureLogger.INFO : IntrospectionFailureLogger.DEBUG);
return TypeMappedAnnotation.createIfPossible(
mappings[annotationIndex].get(mappingIndex), root, logger);
}
@Override
@Nullable
public Spliterator<MergedAnnotation<A>> trySplit() {
return null;
}
@Override
public long estimateSize() {
int size = 0;
for (int i = 0; i < annotations.length; i++) {
AnnotationTypeMappings mappings = MergedAnnotationsCollection.this.mappings[i];
int numberOfMappings = mappings.size();
numberOfMappings -= Math.min(this.mappingCursors[i], mappings.size());
size += numberOfMappings;
}
return size;
}
@Override
public int characteristics() {
return NONNULL | IMMUTABLE;
}
}
}
|
package fr.cea.nabla.interpreter.nodes.job;
import com.oracle.truffle.api.CompilerDirectives;
import com.oracle.truffle.api.dsl.NodeChild;
import com.oracle.truffle.api.dsl.Specialization;
import com.oracle.truffle.api.frame.VirtualFrame;
import com.oracle.truffle.api.instrumentation.GenerateWrapper;
import com.oracle.truffle.api.instrumentation.InstrumentableNode;
import com.oracle.truffle.api.instrumentation.ProbeNode;
import com.oracle.truffle.api.instrumentation.StandardTags;
import com.oracle.truffle.api.instrumentation.Tag;
import com.oracle.truffle.api.nodes.ExplodeLoop;
import com.oracle.truffle.api.nodes.Node;
import com.oracle.truffle.api.nodes.RepeatingNode;
import fr.cea.nabla.interpreter.nodes.expression.NablaExpressionNode;
import fr.cea.nabla.interpreter.nodes.instruction.NablaInstructionNode;
import fr.cea.nabla.interpreter.nodes.instruction.NablaWriteVariableNode;
import fr.cea.nabla.interpreter.values.NV0Bool;
import fr.cea.nabla.interpreter.values.NV0Int;
@GenerateWrapper
// Index is updated at the beginning of the loop, in conformance with the NabLab interpreter.
@NodeChild(value = "indexUpdate", type = NablaWriteVariableNode.class)
@NodeChild(value = "innerJobBlock", type = NablaJobBlockNode.class)
@NodeChild(value = "conditionNode", type = NablaExpressionNode.class)
public abstract class NablaTimeLoopJobRepeatingNode extends Node implements RepeatingNode, InstrumentableNode {
@Child
private NablaInstructionNode copyInstructionNode;
protected NablaTimeLoopJobRepeatingNode(NablaInstructionNode copyInstructionNode) {
this.copyInstructionNode = copyInstructionNode;
}
protected NablaTimeLoopJobRepeatingNode() {
}
/**
* Necessary to avoid errors in generated class.
*/
@Override
public final Object executeRepeatingWithValue(VirtualFrame frame) {
if (executeRepeating(frame)) {
return CONTINUE_LOOP_STATUS;
} else {
return BREAK_LOOP_STATUS;
}
}
@ExplodeLoop
@Specialization
public boolean doLoop(VirtualFrame frame, NV0Int index, Object blockResult, NV0Bool shouldContinue) {
final boolean continueLoop = shouldContinue.isData();
if (CompilerDirectives.injectBranchProbability(0.9, continueLoop)) {
copyInstructionNode.executeGeneric(frame);
}
return continueLoop;
}
@Override
public boolean isInstrumentable() {
return true;
}
@Override
public boolean hasTag(Class<? extends Tag> tag) {
return tag.equals(StandardTags.RootBodyTag.class);
}
@Override
public WrapperNode createWrapper(ProbeNode probe) {
return new NablaTimeLoopJobRepeatingNodeWrapper(this, probe);
}
}
|
package com.lxm.smartbutler.ui;
import android.content.Intent;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import com.lxm.smartbutler.MainActivity;
import com.lxm.smartbutler.R;
import java.util.ArrayList;
import java.util.List;
public class GuideActivity extends AppCompatActivity implements View.OnClickListener{
private ViewPager mViewPager;
private ImageView mSkip;
private ImageView mPagerPoint1,mPagerPoint2,mPagerPoint3;
private List<View> lists = new ArrayList<>();
private View view1,view2,view3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_guide);
initView();
}
private void initView() {
mViewPager = (ViewPager) findViewById(R.id.mViewPager);
view1 = View.inflate(this,R.layout.pager_item_one,null);
view2 = View.inflate(this,R.layout.pager_item_two,null);
view3 = View.inflate(this,R.layout.pager_item_three,null);
((Button) view3.findViewById(R.id.btn_start)).setOnClickListener(this);
lists.add(view1);
lists.add(view2);
lists.add(view3);
mViewPager.setAdapter(new GuideAdapter());
mPagerPoint1 = (ImageView) findViewById(R.id.point_1);
mPagerPoint2 = (ImageView) findViewById(R.id.point_2);
mPagerPoint3 = (ImageView) findViewById(R.id.point_3);
setImagePoint(true,false,false);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
switch (position) {
case 0:
setImagePoint(true,false,false);
mSkip.setVisibility(View.VISIBLE);
break;
case 1:
setImagePoint(false,true,false);
mSkip.setVisibility(View.VISIBLE);
break;
case 2:
setImagePoint(false,false,true);
mSkip.setVisibility(View.GONE);
break;
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
mSkip = (ImageView) findViewById(R.id.btn_skip);
mSkip.setOnClickListener(this);
}
private void setImagePoint(boolean isChecked1, boolean isChecked2, boolean isChecked3) {
if (isChecked1) {
mPagerPoint1.setBackgroundResource(R.drawable.point_on);
} else {
mPagerPoint1.setBackgroundResource(R.drawable.point_off);
}
if (isChecked2) {
mPagerPoint2.setBackgroundResource(R.drawable.point_on);
} else {
mPagerPoint2.setBackgroundResource(R.drawable.point_off);
}
if (isChecked3) {
mPagerPoint3.setBackgroundResource(R.drawable.point_on);
} else {
mPagerPoint3.setBackgroundResource(R.drawable.point_off);
}
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_start:
case R.id.btn_skip:
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
break;
}
}
private class GuideAdapter extends PagerAdapter {
@Override
public int getCount() {
return lists.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
((ViewPager) container).addView(lists.get(position));
return lists.get(position);
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView(lists.get(position));
}
}
}
|
package ca.l5.expandingdev.jsgf;
public class RuleReference implements Expansion {
private String ruleName;
public String getRuleName() {
return ruleName;
}
public void setRuleName(String ruleName) {
this.ruleName = ruleName;
}
public RuleReference(String rr) {
ruleName = rr;
}
@Override
public boolean hasChildren() {
return false;
}
@Override
public boolean hasUnparsedChildren() {
return false;
}
public String getString() {
String s = "<" + ruleName + ">";
return s;
}
}
|
package sg.edu.nus.comp.maple.rossensorsbridge.app.dataObjects;
import android.location.Location;
import org.json.JSONException;
import org.json.JSONObject;
import sg.edu.nus.comp.maple.rossensorsbridge.app.interfaces.JSONifiable;
/**
* Created by Keng Kiat Lim on 12/29/14.
*/
public class LocationData implements JSONifiable {
public static final String stringName = "Location Data";
private final Location mLocation;
public LocationData(Location location) {
this.mLocation = location;
}
@Override
public JSONObject toJSONObject() {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("name", LocationData.stringName);
jsonObject.put("accuracy", this.mLocation.getAccuracy());
jsonObject.put("altitude", this.mLocation.getAltitude());
jsonObject.put("bearing", this.mLocation.getBearing());
jsonObject.put("latitude", this.mLocation.getLatitude());
jsonObject.put("longitude", this.mLocation.getLongitude());
jsonObject.put("speed", this.mLocation.getSpeed());
jsonObject.put("time", this.mLocation.getTime());
} catch (JSONException e) {
e.printStackTrace();
} finally {
return jsonObject;
}
}
public Location getLocation() {
return mLocation;
}
}
|
package com.yevhenchmykhun.filter.gzip;
import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;
public class GzipResponseStream extends ServletOutputStream {
protected ByteArrayOutputStream baos;
protected GZIPOutputStream gzipOutputStream;
protected HttpServletResponse response;
protected ServletOutputStream outputStream;
protected boolean closed;
public GzipResponseStream(HttpServletResponse response) throws IOException {
this.response = response;
outputStream = response.getOutputStream();
baos = new ByteArrayOutputStream();
gzipOutputStream = new GZIPOutputStream(baos);
closed = false;
}
public void close() throws IOException {
if (closed) {
throw new IOException("This output stream has already been closed");
}
gzipOutputStream.finish();
byte[] bytes = baos.toByteArray();
response.addHeader("Content-Length", Integer.toString(bytes.length));
response.addHeader("Content-Encoding", "gzip");
outputStream.write(bytes);
outputStream.flush();
outputStream.close();
closed = true;
}
public void flush() throws IOException {
if (closed) {
throw new IOException("Cannot flush a closed output stream");
}
gzipOutputStream.flush();
}
@Override
public void write(int b) throws IOException {
if (closed) {
throw new IOException("Cannot write to a closed output stream");
}
gzipOutputStream.write((int) b);
}
public void write(byte b[]) throws IOException {
write(b, 0, b.length);
}
public void write(byte b[], int off, int len) throws IOException {
if (closed) {
throw new IOException("Cannot write to a closed output stream");
}
gzipOutputStream.write(b, off, len);
}
public boolean isClosed() {
return closed;
}
public void reset() {
//NOOP
}
@Override
public boolean isReady() {
return false;
}
@Override
public void setWriteListener(WriteListener writeListener) {
//NOOP
}
}
|
package com.zc.pivas.statistics.controller;
import com.google.gson.Gson;
import com.zc.base.common.controller.SdBaseController;
import com.zc.pivas.inpatientarea.bean.InpatientAreaBean;
import com.zc.pivas.inpatientarea.service.InpatientAreaService;
import com.zc.pivas.statistics.service.StaticDoctorService;
import com.zc.pivas.statistics.bean.medicalAdvice.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 不合理医嘱统计控制器
*
* @author jagger
* @version 1.0
*/
@Controller
@RequestMapping(value = "/statistics")
public class StaticDoctorController extends SdBaseController {
@Resource
private StaticDoctorService staticDoctorService;
@Resource
InpatientAreaService inpatientAreaService;
/**
* 不合理医嘱统计页面
*
* @param model
* @param request
* @return
*/
@RequestMapping(value = "/doctorAdvice")
@RequiresPermissions(value = {"PIVAS_MENU_571"})
public String initStaticDoctor(Model model, HttpServletRequest request) {
//医生数据
List<StaticDoctorNameBean> doctorNameList = staticDoctorService.queryDoctorNameList();
model.addAttribute("doctorNameList", doctorNameList);
//病区数据
//List<InpatientAreaBean> inpatientAreaList = inpatientAreaService.queryInpatientAreaAllList();
List<InpatientAreaBean> inpatientAreaList = inpatientAreaService.queryInpatientAreaInAll();
model.addAttribute("inpatientAreaList", inpatientAreaList);
return "pivas/statistics/irrationalDoctorAdvice";
}
/**
* 按医生获取柱状图数据
*
* @param staticDoctorSearch
* @return
*/
@RequestMapping("/queryDoctorAdviceStatusBarData")
@ResponseBody
public String queryDoctorAdviceStatusBarData(StaticDoctorSearchBean staticDoctorSearch) {
StaticDoctorNameStatusBarBean doctorNameStatusBarList = staticDoctorService.queryDoctorNameStatusBar(staticDoctorSearch);
return new Gson().toJson(doctorNameStatusBarList);
}
/**
* 获取医嘱饼图数据
*
* @param staticDoctorSearch
* @return
*/
@RequestMapping("/queryDoctorAdvicePieList")
@ResponseBody
public String queryDoctorAdvicePieList(StaticDoctorSearchBean staticDoctorSearch) {
List<StaticDoctorNamePieBean> doctorNamePieList = staticDoctorService.queryDoctorNamePieList(staticDoctorSearch);
return new Gson().toJson(doctorNamePieList);
}
@RequestMapping("/queryDoctorAdviceStatusPieData")
@ResponseBody
public String queryDoctorAdviceStatusPieData(StaticDoctorSearchBean staticDoctorSearch) {
List<StaticDoctorStatusBean> doctorStatusList = staticDoctorService.queryDoctorNameStatusListByID(staticDoctorSearch);
return new Gson().toJson(doctorStatusList);
}
@RequestMapping("/queryDoctorAdviceDeptStatusBar")
@ResponseBody
public String queryDoctorAdviceDeptStatusBar(StaticDoctorSearchBean staticDoctorSearch) {
StaticDoctorDeptStatusBarBean deptStatusBarList = staticDoctorService.queryDeptStatusBar(staticDoctorSearch);
return new Gson().toJson(deptStatusBarList);
}
@RequestMapping("/queryDoctorAdviceDeptPieList")
@ResponseBody
public String queryDoctorAdviceDeptPieList(StaticDoctorSearchBean staticDoctorSearch) {
List<StaticDoctorDeptPieBean> dctrDeptPieList = staticDoctorService.queryDeptPieList(staticDoctorSearch);
return new Gson().toJson(dctrDeptPieList);
}
@RequestMapping("/queryDoctorAdviceDeptStatusPieList")
@ResponseBody
public String queryDoctorAdviceDeptStatusPieList(StaticDoctorSearchBean staticDoctorSearch) {
List<StaticDoctorStatusBean> deptStatusList = staticDoctorService.queryDeptStatusListByName(staticDoctorSearch);
return new Gson().toJson(deptStatusList);
}
/**
* 导入不合理医嘱点评
*
* @param file
* @return
* @throws IOException
*/
@RequestMapping(value = "/importDianp")
@ResponseBody
public String importDianp(MultipartFile file) throws IOException {
boolean hasError = false;
// 导入发生的错误信息
StringBuffer errorLog = new StringBuffer();
errorLog.append("导入异常日志如下:\n");
Map<String, Object> updateMap = new HashMap<String, Object>();
String fileName = file.getOriginalFilename();
try {
boolean oldVersion = true;
if (fileName.matches("^.+\\.(?i)(xls)$")) {
oldVersion = true;
} else if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
oldVersion = false;
} else {
return buildSuccessJsonMsg(errorLog.toString());
}
Workbook workbook = null;
if (oldVersion) {
// 2003版本Excel(.xls)
workbook = new HSSFWorkbook(file.getInputStream());
} else {
// 2007版本Excel或更高版本(.xlsx)
workbook = new XSSFWorkbook(file.getInputStream());
}
if (null != workbook) {
String operatorLog = "";
for (int m = 0; m < workbook.getNumberOfSheets(); m++) {
Sheet sheet = workbook.getSheetAt(m);
int n = 4;
Row row = null;
if (m != 0) {
n = 1;
}
row = sheet.getRow(n - 1);
// pivas_yz_checkresult id
String id = "";
// 不合理医嘱点评
String dianp = "";
// 根据导入列表数据判断获取的记录异常数据的模板
if (row.getCell(16) != null && "点评".equals(row.getCell(16).toString())) {
for (int i = n; i <= sheet.getLastRowNum(); i++) {
row = sheet.getRow(i);
if (!StringUtils.isEmpty(row.getCell(17).toString())) {
// 点评
dianp = row.getCell(16).toString();
id = row.getCell(17).toString();
if (dianp.getBytes().length > 1024) {
operatorLog =
"第" + String.valueOf(i + 1) + "行" + " 点评内容:" + dianp + " 超长";
errorLog.append(operatorLog).append("\n");
hasError = true;
} else {
updateMap.put("id", id);
updateMap.put("dianp", dianp);
staticDoctorService.updateYzCheckResult(updateMap);
}
}
}
}
}
}
} catch (IOException e) {
throw e;
}
if (hasError) {
return buildFailJsonMsg(errorLog.toString());
} else {
return buildSuccessJsonMsg(messageHolder.getMessage("common.op.success"));
}
}
}
|
package com.kic.Hw;
import java.util.Hashtable;
public class StudentPro {
private Hashtable<String, StudentDTO> ht=new Hashtable<>();
public void add(StudentDTO data) throws Exception
{
String hak=data.getHak();
ht.put(hak, data);
}
public boolean isCheckHak(String str)
{
boolean result= ht.containsKey(str);
return result;
}
}
|
package moe.tristan.easyfxml.samples.helloworld.view;
import javafx.stage.Stage;
import moe.tristan.easyfxml.FxUiManager;
import moe.tristan.easyfxml.api.FxmlNode;
import moe.tristan.easyfxml.samples.helloworld.view.hello.HelloComponent;
public class HelloWorldUiManager extends FxUiManager {
private final HelloComponent helloComponent;
protected HelloWorldUiManager(HelloComponent helloComponent) {
this.helloComponent = helloComponent;
}
/**
* @return the main {@link Stage}'s title you want
*/
@Override
protected String title() {
return "Hello, World!";
}
/**
* @return the component to load as the root view in your main {@link Stage}.
*/
@Override
protected FxmlNode mainComponent() {
return helloComponent;
}
}
|
package com.org.spring.boot.amqp.processor.bridge;
import com.org.spring.boot.amqp.message.alarm.AlarmStatusMessageData;
import com.org.spring.boot.amqp.processor.Event;
import com.org.spring.boot.amqp.processor.Processor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
@Slf4j
@Service
public class AlarmStatusProcessor extends Processor<AlarmStatusMessageData> {
public AlarmStatusProcessor() {
super(AlarmStatusMessageData.class);
}
@Override
public void process(final String message) {
super.process(message);
}
@Override
protected Event buildEvent(final AlarmStatusMessageData alarmStatusMessageData) {
return new Event("device.alarm.status", alarmStatusMessageData.getSerial());
}
}
|
package com.cmi.bache24.ui.fragment.troop;
import android.animation.ObjectAnimator;
import android.animation.TypeEvaluator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.util.Property;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.cmi.bache24.R;
import com.cmi.bache24.data.model.Report;
import com.cmi.bache24.data.model.User;
import com.cmi.bache24.data.remote.ServicesManager;
import com.cmi.bache24.data.remote.interfaces.LoginCallback;
import com.cmi.bache24.data.remote.interfaces.NewReportCallback;
import com.cmi.bache24.data.remote.interfaces.ReportsCallback;
import com.cmi.bache24.ui.activity.ReportDetailActivity;
import com.cmi.bache24.ui.adapter.TroopReportsAdapter;
import com.cmi.bache24.ui.fragment.BaseFragment;
import com.cmi.bache24.util.Constants;
import com.cmi.bache24.util.LatLngInterpolator;
import com.cmi.bache24.util.PreferencesManager;
import com.cmi.bache24.util.Utils;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import java.util.ArrayList;
import java.util.List;
/**
* A placeholder fragment containing a simple view.
*/
public class TroopMainFragment extends BaseFragment implements OnMapReadyCallback,
LocationListener,
View.OnClickListener,
TextWatcher {
private GoogleMap mMap;
private LocationManager mLocationManager;
private Location mMyCurrentLocation;
private ImageView mButtonNewReport;
private Marker mNewReportMarker;
private String mAddressString;
private LatLng mAddressPosition;
private Animation mShowAnimation;
private Animation mHideAnimation;
private User mCurrentUser;
private Button mButtonMap;
private Button mButtonList;
private RelativeLayout mLayoutMap;
private RelativeLayout mLayoutList;
private RecyclerView mReportsList;
private TroopReportsAdapter mReportsAdapter;
private TroopMainFragmentListener mTroopMainFragmentListener;
private LinearLayout mProgressLayout;
private ImageButton searchReportImageButton;
private EditText searchReportEditText;
private static View rootView;
private List<Marker> mMarkerList;
private List<Report> mAllReports;
private ImageView locationButton;
private Marker mMyCurrentLocationMarker;
Context mCurrentActivity;
int REQUEST_LOCATION_PERMISSION_CODE = 342;
List<Report> filteredReports;
public TroopMainFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (rootView != null) {
ViewGroup parent = (ViewGroup) rootView.getParent();
if (parent != null)
parent.removeView(rootView);
}
try {
rootView = inflater.inflate(R.layout.fragment_troop_main, container, false);
} catch (InflateException e) {
}
MapFragment mapFragment = (MapFragment) ((FragmentActivity)mCurrentActivity).getFragmentManager()
.findFragmentById(R.id.map_report);
mButtonMap = (Button) rootView.findViewById(R.id.button_map);
mButtonList = (Button) rootView.findViewById(R.id.button_list);
mLayoutMap = (RelativeLayout) rootView.findViewById(R.id.layout_map);
mLayoutList = (RelativeLayout) rootView.findViewById(R.id.layout_list);
mProgressLayout = (LinearLayout) rootView.findViewById(R.id.progress_layout);
mProgressLayout.setVisibility(View.GONE);
mReportsList = (RecyclerView) rootView.findViewById(R.id.report_list);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mCurrentActivity);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mReportsList.setLayoutManager(linearLayoutManager);
locationButton = (ImageView) rootView.findViewById(R.id.image_location);
searchReportImageButton = (ImageButton) rootView.findViewById(R.id.image_button_search_report);
searchReportEditText = (EditText) rootView.findViewById(R.id.edit_text_report_ticket);
searchReportImageButton.setVisibility(View.GONE);
searchReportEditText.setVisibility(View.GONE);
searchReportEditText.addTextChangedListener(this);
mButtonMap.setOnClickListener(this);
mButtonList.setOnClickListener(this);
locationButton.setOnClickListener(this);
searchReportImageButton.setOnClickListener(this);
mReportsAdapter = new TroopReportsAdapter(mCurrentActivity);
mLocationManager = (LocationManager) mCurrentActivity.getSystemService(Context.LOCATION_SERVICE);
mCurrentUser = PreferencesManager.getInstance().getUserInfo(mCurrentActivity);
mMarkerList = new ArrayList<>();
initalizeMap();
if (mapFragment != null)
mapFragment.getMapAsync(this);
mLayoutMap.setVisibility(View.VISIBLE);
mLayoutList.setVisibility(View.GONE);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
getUserInfo();
}
}, 1000);
return rootView;
}
@Override
public void onResume() {
super.onResume();
searchReportEditText.setText("");
searchReportEditText.setVisibility(View.GONE);
loadReports();
}
@Override
public void onLocationChanged(Location location) {
mMyCurrentLocation = location;
moveToMyCurrentLocation(true);
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
checkLocationPermissions();
loadReports();
}
public void loadReports() {
mReportsAdapter.addAllSections(new ArrayList<Report>());
if (mMap != null)
mMap.clear();
// mReportsAdapter.notifyDataSetChanged();
if (!Utils.getInstance().isInternetAvailable(mCurrentActivity))
return;
mProgressLayout.setVisibility(View.VISIBLE);
mNewReportMarker = null;
ServicesManager.getReportsForTroops(mCurrentUser, new ReportsCallback() {
@Override
public void onReportsCallback(List<Report> reports) {
mProgressLayout.setVisibility(View.GONE);
mAllReports = reports;
showReportsAsMap(reports);
showReportsAsList(reports);
goToMyInitialLocation();
PreferencesManager.getInstance().addReports(mCurrentActivity, reports);
if (reports.size() == 0) {
Toast.makeText(mCurrentActivity, "No hay reportes en espera de solución", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onReportsFail(String message) {
mProgressLayout.setVisibility(View.GONE);
if (mCurrentActivity != null) {
if (message != "") {
Toast.makeText(mCurrentActivity, message, Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void userBanned() {
}
@Override
public void onTokenDisabled() {
Utils.showLoginForBadToken(mCurrentActivity);
}
});
}
private void showReportsAsMap(List<Report> reports) {
if (!isGooglePlayServicesAvailable())
{
return;
}
if (mMap != null)
mMap.clear();
if (mCurrentActivity == null)
return;
if (reports.size() > 0) {
mMarkerList = null;
mMarkerList = new ArrayList<>();
for (int i = 0; i < reports.size(); i++) {
LatLng markerPosition = new LatLng(Double.valueOf(reports.get(i).getLatitude()),
Double.valueOf(reports.get(i).getLongitude()));
Marker marker = mMap.addMarker(new MarkerOptions()
.position(markerPosition)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.pin_reporte_amarillo)));
mMarkerList.add(marker);
}
mMap.setOnMarkerClickListener(null);
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
@Override
public boolean onMarkerClick(Marker marker) {
if (mMarkerList == null)
return false;
if (mMarkerList.size() == 0)
return false;
int position = -1;
for (int i = 0; i < mMarkerList.size(); i++) {
if (mMarkerList.get(i).equals(marker)) {
position = i;
break;
}
}
if (position >= 0)
mTroopMainFragmentListener.onReportSelected(mAllReports.get(position));
return true;
}
});
}
}
private void showReportsAsList(List<Report> reports) {
mReportsAdapter.addAllSections(reports);
mReportsList.setAdapter(mReportsAdapter);
mReportsAdapter.setReportsListener(new TroopReportsAdapter.OnReportsListener() {
@Override
public void onReportClick(Report report) {
mTroopMainFragmentListener.onReportSelected(report);
}
});
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
mCurrentActivity = context;
try{
if (context instanceof Activity) {
mTroopMainFragmentListener = (TroopMainFragmentListener) context;
}
} catch (ClassCastException ex) {
}
}
@Override
public void onClick(View view) {
if (view.getId() == mButtonMap.getId() || view.getId() == mButtonList.getId()) {
boolean isMapSectionVisible = view.getId() == mButtonMap.getId();
mLayoutMap.setVisibility(isMapSectionVisible ? View.VISIBLE : View.GONE);
mLayoutList.setVisibility(isMapSectionVisible ? View.GONE : View.VISIBLE);
mButtonMap.setBackgroundResource(isMapSectionVisible ? R.drawable.btn_activo : R.drawable.btn_inactivo);
mButtonList.setBackgroundResource(isMapSectionVisible ? R.drawable.btn_inactivo : R.drawable.btn_activo);
mButtonMap.setTextColor(ContextCompat.getColor(mCurrentContext, isMapSectionVisible ? R.color.text_color_white : R.color.primary));
mButtonList.setTextColor(ContextCompat.getColor(mCurrentContext, isMapSectionVisible ? R.color.primary : R.color.text_color_white));
searchReportImageButton.setVisibility(isMapSectionVisible ? View.GONE : View.VISIBLE);
searchReportEditText.removeTextChangedListener(this);
searchReportEditText.setText("");
searchReportEditText.addTextChangedListener(this);
searchReportEditText.setVisibility(View.GONE);
loadReports();
}
/*else if (view.getId() == mButtonList.getId()) {
mLayoutMap.setVisibility(View.GONE);
mLayoutList.setVisibility(View.VISIBLE);
mButtonMap.setBackgroundResource(R.drawable.btn_inactivo);
mButtonList.setBackgroundResource(R.drawable.btn_activo);
mButtonMap.setTextColor(getResources().getColor(R.color.primary));
mButtonList.setTextColor(getResources().getColor(R.color.text_color_white));
searchReportImageButton.setVisibility(View.VISIBLE);
searchReportEditText.removeTextChangedListener(this);
searchReportEditText.setText("");
searchReportEditText.addTextChangedListener(this);
searchReportEditText.setVisibility(View.GONE);
loadReports();
} */
else if (view.getId() == locationButton.getId()) {
moveToMyCurrentLocation(true);
} else if (view.getId() == searchReportImageButton.getId()) {
searchReportEditText.setVisibility(View.VISIBLE);
}
}
public void reloadAfterUpdateReport() {
mLayoutMap.setVisibility(View.VISIBLE);
mLayoutList.setVisibility(View.GONE);
mButtonMap.setBackgroundResource(R.drawable.btn_activo);
mButtonList.setBackgroundResource(R.drawable.btn_inactivo);
mButtonMap.setTextColor(getResources().getColor(R.color.text_color_white));
mButtonList.setTextColor(getResources().getColor(R.color.primary));
if (mMap != null)
mMap.clear();
loadReports();
}
public void newReport() {
if (mMyCurrentLocation == null ) {
Toast.makeText(mCurrentActivity, "No se pudo detectar tu ubicación, por favor revisa si la localización se encuentra habilitada", Toast.LENGTH_LONG).show();
return;
}
Intent intentReportDetail = new Intent(mCurrentActivity, ReportDetailActivity.class);
intentReportDetail.putExtra(Constants.EXTRA_NEW_REPORT_LATITUDE, mMyCurrentLocation.getLatitude());
intentReportDetail.putExtra(Constants.EXTRA_NEW_REPORT_LONGITUDE, mMyCurrentLocation.getLongitude());
intentReportDetail.putExtra(Constants.EXTRA_NEW_REPORT_ADDRESS_AS_STRING, mAddressString);
((FragmentActivity)mCurrentActivity).startActivityForResult(intentReportDetail, Constants.REPORT_DETAIL_REQUEST_CODE);
((FragmentActivity)mCurrentActivity).overridePendingTransition(R.anim.enter_from_right, R.anim.enter_from_left);
}
private void animateMarkerToPosition(Marker marker, final LatLng finalPosition, final LatLngInterpolator latLngInterpolator) {
TypeEvaluator<LatLng> typeEvaluator = new TypeEvaluator<LatLng>() {
@Override
public LatLng evaluate(float fraction, LatLng startValue, LatLng endValue) {
return latLngInterpolator.interpolate(fraction, startValue, endValue);
}
};
Property<Marker, LatLng> property = Property.of(Marker.class, LatLng.class, "position");
ObjectAnimator animator = ObjectAnimator.ofObject(marker, property, typeEvaluator, finalPosition);
animator.setDuration(500);
animator.start();
}
private void goToMyInitialLocation() {
if (mMyCurrentLocation != null) {
LatLng latLng = new LatLng(mMyCurrentLocation.getLatitude(), mMyCurrentLocation.getLongitude());
updateMyMarkerPosition(latLng);
CameraPosition newCameraPosition = new CameraPosition(latLng,
18,
mMap.getCameraPosition().tilt,
mMap.getCameraPosition().bearing);
mMap.moveCamera(CameraUpdateFactory.newCameraPosition(newCameraPosition));
}
}
LocationManager locationManager;
boolean isGPSEnabled;
boolean isNetworkEnabled;
boolean canGetLocation;
public Location getLocation() {
try {
locationManager = (LocationManager) mCurrentActivity
.getSystemService(mCurrentActivity.LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
1000,
5, this);
if (locationManager != null) {
mMyCurrentLocation = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
1000,
5, this);
if (locationManager != null) {
mMyCurrentLocation = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
if (mMyCurrentLocation == null) {
mMyCurrentLocation = getDefaultLocation();
/*mMyCurrentLocation = new Location("GPS");
mMyCurrentLocation.setLatitude(19.4339137);
mMyCurrentLocation.setLongitude(-99.1338311);*/
}
return mMyCurrentLocation;
}
private void showDefaultLocation() {
mMyCurrentLocation = getDefaultLocation();
goToMyInitialLocation();
}
private Location getDefaultLocation() {
Location defaultLocation = new Location("GPS");
defaultLocation.setLatitude(19.4339137);
defaultLocation.setLongitude(-99.1338311);
return defaultLocation;
}
private void moveToMyCurrentLocation(boolean animateToMarker) {
if (mMyCurrentLocation != null && mMap != null) {
LatLng latLng = new LatLng(mMyCurrentLocation.getLatitude(), mMyCurrentLocation.getLongitude());
updateMyMarkerPosition(latLng);
if (animateToMarker) {
CameraUpdate location = CameraUpdateFactory.newLatLngZoom(
latLng, mMap.getCameraPosition().zoom);
mMap.animateCamera(location);
}
}
}
private void updateMyMarkerPosition(LatLng latLng) {
deleteMyMarkerPosition();
mMyCurrentLocationMarker = mMap.addMarker(new MarkerOptions()
.position(latLng)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ubicacion)));
}
private void deleteMyMarkerPosition() {
if (mMyCurrentLocationMarker != null) {
mMyCurrentLocationMarker.remove();
mMyCurrentLocationMarker = null;
}
}
private void getUserInfo() {
ServicesManager.getUserInfo(mCurrentUser, new LoginCallback() {
@Override
public void loginSuccess(User userInfo) {
mCurrentUser = userInfo;
if (mTroopMainFragmentListener != null) {
mTroopMainFragmentListener.onUserUpdated(userInfo);
}
}
@Override
public void loginFail(String message) {
}
@Override
public void userBanned() {
}
@Override
public void onTokenDisabled() {
}
});
}
public void cancelReportAttention() {
if (!Utils.getInstance().isInternetAvailable(mCurrentActivity))
return;
PreferencesManager.getInstance().setReportCanceled("TroopMainFragment - cancelReportAttention", mCurrentActivity, true);
mProgressLayout.setVisibility(View.VISIBLE);
Report currentReport = new Report();
currentReport.setTicket(PreferencesManager.getInstance().getReportAttentionTicketValue(mCurrentActivity));
ServicesManager.cancelReportAttention(mCurrentContext, mCurrentUser, currentReport, new NewReportCallback() {
@Override
public void onSuccessRegister(String resultCode, Report reportCompleteInfo) {
}
@Override
public void onSuccessRegisterReport(Report reportCompleteInfo) {
Log.i("ReportStatus", "Reporte restaurado correctamente");
mProgressLayout.setVisibility(View.GONE);
loadReports();
PreferencesManager.getInstance().clearReportAttentionData(mCurrentActivity);
}
@Override
public void onFailRegisterReport(String message) {
Log.i("ReportStatus", "Error al resturar el Reporte");
mProgressLayout.setVisibility(View.GONE);
loadReports();
}
@Override
public void userBanned() {
}
@Override
public void onTokenDisabled() {
}
});
}
private void initalizeMap() {
try {
MapsInitializer.initialize(mCurrentActivity.getApplicationContext());
} catch (Exception ex) {
ex.printStackTrace();
}
}
private boolean isGooglePlayServicesAvailable() {
GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
int status = googleApiAvailability.isGooglePlayServicesAvailable(mCurrentActivity);
if (status != ConnectionResult.SUCCESS) {
// if (googleApiAvailability.isUserResolvableError(status)) {
// googleApiAvailability.getErrorDialog((Activity) mCurrentActivity, status, 2424).show();
// }
return false;
}
return true;
}
private void checkLocationPermissions() {
checkPermissionsForAction(new String[] {
android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_COARSE_LOCATION
},
ACTION_REQUEST_LOCATION,
"Los permisos para ubicación están desactivados");
}
@Override
public void doAllowedStuffWithPermissionGrantedForAction(String action) {
mMyCurrentLocation = getLocation();
goToMyInitialLocation();
}
@Override
public void onPermissionDenied(String message) {
Toast.makeText(mCurrentContext, message, Toast.LENGTH_SHORT).show();
showDefaultLocation();
}
@Override
public void onPermissionDeniedPermanently(String message) {
if (mTroopMainFragmentListener != null) {
mTroopMainFragmentListener.onLocationPermissionDenied();
}
showDefaultLocation();
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if (mAllReports == null) {
return;
}
if (s.toString().length() == 0) {
showReportsAsList(mAllReports);
return;
}
List<Report> filteredReports = getFilteredReports(s.toString());
showReportsAsList(filteredReports);
}
private List<Report> getFilteredReports(String s) {
if (filteredReports == null) {
filteredReports = new ArrayList<>();
} else {
filteredReports.clear();
}
for (int i = 0; i < mAllReports.size(); i++) {
if (mAllReports.get(i).getTicket().toLowerCase().contains(s.toLowerCase())) {
filteredReports.add(mAllReports.get(i));
}
}
return filteredReports;
}
public interface TroopMainFragmentListener {
void onReportSelected(Report report);
void onUserUpdated(User userInfo);
void onLocationPermissionDenied();
}
}
|
package studentmanagementsystem.studentperformance;
import java.io.Serializable;
import java.sql.Connection;
/**
*
* @author dess
*/
public class examsclass implements Serializable{
private String registration_id;
private String cat1;
private String cat2;
private String exam;
private String total;
private String grade;
Connection con=null;
public examsclass()
{}
public examsclass(String Registration_id, String Cat1, String Cat2, String Exam, String Total, String Grade){
this.registration_id=Registration_id;
this.cat1=Cat1;
this.cat2=Cat2;
this.exam=Exam;
this.total=Total;
this.grade=Grade;
}
public String getid()
{
return registration_id;
}
public String getcat1()
{
return cat1;
}
public String getcat2()
{
return cat2;
}
public String getexam()
{
return exam;
}
public String gettotal()
{
return total;
}
public String getgrade()
{
return grade;
}
}
|
package practice.dynamicprogramming;
/*
200. Longest Palindromic Substring
Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
Example
Given the string = "abcdzdcab", return "cdzdc".
Challenge
O(n2) time is acceptable. Can you do it in O(n) time.
*/
public class MlongestPalindrome {
public String longestPalindrome(String s) {
if (s == null) {
return null;
}
if (s.length() == 0) {
return "";
}
int longest = 0;
int mostLeft = -1;
int mostRight = -1;
for (int i = 0; i < s.length(); i++) {
// ERROR: 没考虑单个char的情况。
//for (int j = i + 1; j < s.length(); j++) {
for (int j = i; j < s.length(); j++) {
if (isPalindrome(s, i, j) && longest < j - i + 1) {
longest = j - i + 1;
mostLeft = i;
mostRight = j;
}
}
}
if (longest == 0) {
return "";
} else {
return s.substring(mostLeft, mostRight + 1);
}
}
private boolean isPalindrome(String s, int left, int right) {
while (left <= right && left < s.length() && right >= 0) {
char le = s.charAt(left);
char ri = s.charAt(right);
if (!isValidChar(le)) {
left++;
continue;
}
if (!isValidChar(ri)) {
right--;
continue;
}
if (le == ri) {
left++;
right--;
} else {
return false;
}
}
return true;
}
private boolean isValidChar(char ch) {
if (Character.isDigit(ch) || Character.isLetter(ch)) {
return true;
}
return false;
}
} |
package com.pda.pda_android.adapter.jcjy;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.pda.pda_android.R;
import com.pda.pda_android.activity.apps.detail.jcjydetail.JyDetailActivity;
import com.pda.pda_android.bean.JyBean;
import com.pda.pda_android.db.Entry.AssayBeanListBean;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
public class JyBodyAdapter extends RecyclerView.Adapter<JyBodyAdapter.ViewHolder>{
private Context context;
private LayoutInflater mLayoutInflater;
// private List<AssayBeanListBean> list;
private List<JyBean.DataBean.ListBean> list;
private String name;
public JyBodyAdapter(Context context, List<JyBean.DataBean.ListBean> list,String name) {
this.list = list;
this.context = context;
mLayoutInflater = LayoutInflater.from(context);
this.name=name;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view=mLayoutInflater.inflate(R.layout.jy_body,null);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {
holder.name.setText(name+" 的检查结果");
holder.data.setText(list.get(position).getResult_date());
holder.project.setText(list.get(position).getName());
holder.jy_rootview.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(context,JyDetailActivity.class);
intent.putExtra("name",name);
intent.putExtra("Patient_no",list.get(position).getSqxh());
context.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return list.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
TextView name,project,data;
LinearLayout jy_rootview;
ViewHolder(View itemView) {
super(itemView);
name = itemView.findViewById(R.id.user_name);
project=itemView.findViewById(R.id.project);
data=itemView.findViewById(R.id.data);
jy_rootview=itemView.findViewById(R.id.jy_rootview);
}
}
}
|
package vo;
/**
* Created by guxuelong on 2015/1/4.
*/
public class RuleVo {
private String ruleType;
private String ruleKey;
private String ruleValue;
public String getRuleType() {
return ruleType;
}
public void setRuleType(String ruleType) {
this.ruleType = ruleType;
}
public String getRuleKey() {
return ruleKey;
}
public void setRuleKey(String ruleKey) {
this.ruleKey = ruleKey;
}
public String getRuleValue() {
return ruleValue;
}
public void setRuleValue(String ruleValue) {
this.ruleValue = ruleValue;
}
}
|
package com.cinema.sys.action.util;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.ElementType;
/**
* 用以修饰类
*
* 描述Web模块对应的WebService。例如:<br>@Service(name="用户管理")
* @param name 为模块名称
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Service {
String name() default "";
boolean login() default true;
}
|
package com.somma.asynctasks;
import androidx.appcompat.app.AppCompatActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
public static final String MIS_LOGS = "MIS_LOGS";
protected TextView tvMensaje;
protected ProgressBar pbProgreso;
private String mensajePredeterminado;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvMensaje = findViewById(R.id.tvMensaje);
pbProgreso = (ProgressBar)findViewById(R.id.pbProgreso);
mensajePredeterminado = getResources().getString(R.string.tvMensaje);
}
public void btnProcesarOnClick(View view) {
new TareaProcesarMensaje().execute(mensajePredeterminado);
}
public void btnRestaurarOnClick(View view) {
tvMensaje.setText(mensajePredeterminado);
pbProgreso.setProgress(0);
}
private class TareaProcesarMensaje extends AsyncTask<String, Integer, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
Log.i(MIS_LOGS, "onPreExecute corre en el hilo " + Thread.currentThread().getId());
pbProgreso.setProgress(0);
}
@Override
protected String doInBackground(String... strings) {
Log.i(MIS_LOGS, "doInBackground corre en el hilo " + Thread.currentThread().getId());
String mensaje = strings[0];
int longitudMensaje = mensaje.length();
StringBuilder mensajeProcesado = new StringBuilder();
for (int i = 0; i < longitudMensaje; i++) {
SystemClock.sleep(1000);
char caracter;
if (i % 2 == 0){
caracter = Character.toUpperCase(mensaje.charAt(i));
} else {
caracter = Character.toLowerCase(mensaje.charAt(i));
}
mensajeProcesado.append(caracter);
publishProgress((i + 1) * 100 / longitudMensaje);
}
return mensajeProcesado.toString();
}
@Override
protected void onProgressUpdate(Integer... values) {
if (pbProgreso.getProgress() == 0) {
Log.i(MIS_LOGS, "onProgressUpdate corre en el hilo: " + Thread.currentThread().getId());
}
pbProgreso.setProgress(values[0]);
}
@Override
protected void onPostExecute(String s) {
Log.i(MIS_LOGS, "onPostExecute corre en el hilo: " + Thread.currentThread().getId());
tvMensaje.setText(s);
}
}
}
|
package com.soft863.group5.bbs.dao;
import com.soft863.group5.bbs.entity.Admin;
import java.util.List;
/**
* @author yangjixiang
* @version 1.0
* @date 2019/1/16 9:14
*/
public interface AdminMapper {
/**
* 根据id查询管理员
*/
public Admin queryAdmins(String name);
}
|
package com.example.aakashbasnet.englishpremierleague;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private static final String REQUEST_URL = "https://heisenbug-premier-league-live-scores-v1.p.mashape.com/api/premierleague/table?from=1";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FootballAsyncTask task =new FootballAsyncTask();
task.execute(REQUEST_URL);
}
private class FootballAsyncTask extends AsyncTask<String, Void, ArrayList<PremierLeague>>{
@Override
protected ArrayList<PremierLeague> doInBackground(String... strings) {
ArrayList<PremierLeague> leaguetables = Queryutils.fetchPremierLeagueData(strings[0]);
return leaguetables;
}
protected void onPostExecute(ArrayList<PremierLeague> tables){
//ListView earthquakeListView = (ListView) findViewById(R.id.list);
updateui(tables);
}
}
private void updateui(ArrayList<PremierLeague> tables) {
ListView tableslistview = (ListView) findViewById(R.id.list);
final PremierLeagueAdapter premierleagueadapter = new PremierLeagueAdapter(this,0, tables);
tableslistview.setAdapter(premierleagueadapter);
}
}
|
/*
* Copyright © 2018 www.noark.xyz All Rights Reserved.
*
* 感谢您选择Noark框架,希望我们的努力能为您提供一个简单、易用、稳定的服务器端框架 !
* 除非符合Noark许可协议,否则不得使用该文件,您可以下载许可协议文件:
*
* http://www.noark.xyz/LICENSE
*
* 1.未经许可,任何公司及个人不得以任何方式或理由对本框架进行修改、使用和传播;
* 2.禁止在本项目或任何子项目的基础上发展任何派生版本、修改版本或第三方版本;
* 3.无论你对源代码做出任何修改和改进,版权都归Noark研发团队所有,我们保留所有权利;
* 4.凡侵犯Noark版权等知识产权的,必依法追究其法律责任,特此郑重法律声明!
*/
package xyz.noark.core.ioc;
import xyz.noark.core.annotation.Component;
/**
* 一个被IOC容器所管理的JavaBean定义描述类.
*
* @author 小流氓[176543888@qq.com]
* @since 3.0
*/
public interface BeanDefinition {
/**
* 获取Bean的名称,默认为类全名.
* <p>
* {@link Component @Component}很特别,有自定义名称
*
* @return Bean的名称
*/
String[] getNames();
/**
* 注入属性.
*
* @param making 装配对象缓存
*/
void injection(IocMaking making);
} |
/* Handling unexpected popup windows using try/catch block */
package howtos;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class JavaPopup {
public static WebDriver driver;
public static WebDriverWait wait;
public static JavascriptExecutor jse;
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:/Dev/Tools/drivers/chromedriverJava.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
wait = new WebDriverWait(driver, 30);
jse = (JavascriptExecutor) driver;
bestBuy();
}
public static void bestBuy() {
driver.get("http://bestbuy.com");
// Wait for popup window to display before we can close it
try {
By popupX = By.xpath("//*[@id='abt-email-modal']/div/div/div[1]/button/span");
wait.until(ExpectedConditions.visibilityOfElementLocated(popupX));
driver.findElement(popupX).click();
System.out.println("Closing pop-up...");
} catch (Exception e) {
System.out.println(e.getMessage());
}
// Continue with normal activity
// Scroll down to bottom of page
try {
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
jse.executeScript("window.scrollTo(0, document.body.scrollHeight);");
}
public static void myPalmBeachPost() {
driver.get("http://mypalmbeachpost.com/");
// Close the pop-up if it displays
try {
By popup = By.xpath("//*[@id='pq-passage-quota-welcome']/div[2]/div/header/a");
wait.until(ExpectedConditions.visibilityOfElementLocated(popup));
driver.findElement(popup).click();
} catch (Exception e) {
System.out.println("Popup did not display. Continue after 30 seconds.");
}
// Scroll down to bottom of page
jse.executeScript("window.scrollTo(0, document.body.scrollHeight);");
}
}
|
/*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet.samples.standalone;
import org.junit.jupiter.api.Test;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.test.web.Person;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
/**
* Tests demonstrating the use of request parameters.
*
* @author Rossen Stoyanchev
*/
public class RequestParameterTests {
@Test
public void queryParameter() throws Exception {
standaloneSetup(new PersonController()).build()
.perform(get("/search?name=George").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json"))
.andExpect(jsonPath("$.name").value("George"));
}
@Controller
private class PersonController {
@RequestMapping(value="/search")
@ResponseBody
public Person get(@RequestParam String name) {
Person person = new Person(name);
return person;
}
}
}
|
package com.cs.user;
import java.util.Arrays;
import java.util.List;
/**
* @author Joakim Gottzén
*/
@SuppressWarnings("UnusedDeclaration")
public enum SecurityRole {
SUPER_USER(Access.PLAYER_PAYMENTS_ADMIN, Access.AFFILIATE_PAYMENTS_ADMIN, Access.PLAYER_SETTINGS_ADMIN, Access.PLAYER_PROMOTIONS_ADMIN,
Access.PROMOTION_CAMPAIGNS_ADMIN, Access.PLAYER_CREDITS_ADMIN, Access.GAME_ADMIN),
KEY_OFFICIAL(Access.PLAYER_PAYMENTS_READ, Access.AFFILIATE_PAYMENTS_READ, Access.PLAYER_SETTINGS_READ, Access.PLAYER_PROMOTIONS_READ,
Access.PROMOTION_CAMPAIGNS_READ),
MONEY_LAUNDERING_OFFICIAL(Access.PLAYER_PAYMENTS_READ, Access.AFFILIATE_PAYMENTS_READ, Access.PLAYER_SETTINGS_READ, Access.PLAYER_PROMOTIONS_READ,
Access.PROMOTION_CAMPAIGNS_READ),
MARKETING_MANAGER(Access.PLAYER_PAYMENTS_READ, Access.AFFILIATE_PAYMENTS_WRITE, Access.PLAYER_SETTINGS_READ, Access.PLAYER_PROMOTIONS_WRITE,
Access.PROMOTION_CAMPAIGNS_ADMIN),
CASINO_MANAGER(Access.PLAYER_PAYMENTS_WRITE, Access.AFFILIATE_PAYMENTS_WRITE, Access.PLAYER_SETTINGS_WRITE, Access.PLAYER_PROMOTIONS_ADMIN,
Access.PROMOTION_CAMPAIGNS_ADMIN, Access.GAME_ADMIN),
ONLINE_MARKETING_MANAGER(Access.PLAYER_PAYMENTS_WRITE, Access.AFFILIATE_PAYMENTS_WRITE, Access.PLAYER_SETTINGS_READ, Access.PLAYER_PROMOTIONS_ADMIN,
Access.PROMOTION_CAMPAIGNS_ADMIN),
PAYMENTS_MANAGER(Access.PLAYER_PAYMENTS_ADMIN, Access.AFFILIATE_PAYMENTS_ADMIN, Access.PLAYER_SETTINGS_WRITE, Access.PLAYER_PROMOTIONS_READ,
Access.PROMOTION_CAMPAIGNS_READ, Access.PLAYER_CREDITS_ADMIN),
CUSTOMER_SUPPORT_MANAGER(Access.PLAYER_PAYMENTS_WRITE, Access.AFFILIATE_PAYMENTS_READ, Access.PLAYER_SETTINGS_ADMIN, Access.PLAYER_PROMOTIONS_WRITE,
Access.PROMOTION_CAMPAIGNS_READ, Access.PLAYER_CREDITS_WRITE),
CUSTOMER_SUPPORT_LEADER(Access.PLAYER_PAYMENTS_WRITE, Access.PLAYER_SETTINGS_WRITE, Access.PLAYER_PROMOTIONS_WRITE, Access.PROMOTION_CAMPAIGNS_READ,
Access.PLAYER_CREDITS_WRITE),
CUSTOMER_SUPPORT(Access.PLAYER_PAYMENTS_WRITE, Access.PLAYER_SETTINGS_WRITE, Access.PLAYER_PROMOTIONS_WRITE, Access.PROMOTION_CAMPAIGNS_READ,
Access.PLAYER_CREDITS_WRITE);
private final List<Access> accesses;
SecurityRole(final Access... accesses) {
this.accesses = Arrays.asList(accesses);
}
public List<Access> getAccesses() {
return accesses;
}
public enum Access {
PLAYER_PAYMENTS_ADMIN(AccessLevel.ADMINISTRATOR),
PLAYER_PAYMENTS_WRITE(AccessLevel.WRITE),
PLAYER_PAYMENTS_READ(AccessLevel.READ),
AFFILIATE_PAYMENTS_ADMIN(AccessLevel.ADMINISTRATOR),
AFFILIATE_PAYMENTS_WRITE(AccessLevel.WRITE),
AFFILIATE_PAYMENTS_READ(AccessLevel.READ),
PLAYER_SETTINGS_ADMIN(AccessLevel.ADMINISTRATOR),
PLAYER_SETTINGS_WRITE(AccessLevel.WRITE),
PLAYER_SETTINGS_READ(AccessLevel.READ),
PLAYER_PROMOTIONS_ADMIN(AccessLevel.ADMINISTRATOR),
PLAYER_PROMOTIONS_WRITE(AccessLevel.WRITE),
PLAYER_PROMOTIONS_READ(AccessLevel.READ),
PROMOTION_CAMPAIGNS_ADMIN(AccessLevel.ADMINISTRATOR),
PROMOTION_CAMPAIGNS_WRITE(AccessLevel.WRITE),
PROMOTION_CAMPAIGNS_READ(AccessLevel.READ),
PLAYER_CREDITS_ADMIN(AccessLevel.WRITE),
PLAYER_CREDITS_WRITE(AccessLevel.WRITE),
PLAYER_CREDITS_READ(AccessLevel.READ),
GAME_ADMIN(AccessLevel.ADMINISTRATOR),
GAME_WRITE(AccessLevel.WRITE),
GAME_READ(AccessLevel.READ);
private final AccessLevel accessLevel;
private Access(final AccessLevel accessLevel) {
this.accessLevel = accessLevel;
}
public AccessLevel getAccessLevel() {
return accessLevel;
}
}
public enum AccessLevel {
ADMINISTRATOR, WRITE, READ
}
}
|
package Tetris;
import GameObject.AudioPlayer;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
public class GameThread extends Thread{
private GameArea ga;
private GameForm gf;
private int score;
private int level = 1;
private int scorePerLevel = 3;
public static int highscore;
public AudioPlayer audioPlayer;
public Date startTime;
private int pause = 1000;
private int speedupPerLevel = 100;
public GameThread(GameArea ga, GameForm gf){
this.ga = ga;
this.gf = gf;
gf.audioPlayer.PlayBGM("Tetris BGM.wav");
gf.updateScore(score);
gf.updateLevel(level);
}
@Override
public void run(){
startTime = new Date();
while(true){
ga.spawnBlock(); // method memunculkan blok
// menggerakkan blok tetris ke bawah
while(ga.moveBlockDown()){
try {
Thread.sleep(pause); // jeda gerakan turun tetris
}
catch (InterruptedException ex) {
// to interupt the latest thread
return;
}
}
// game over state
if(ga.isBlockOutOfBounds()){
endGame();
break;
}
// game continue
ga.moveBlockToBackground(); // mengubah block jadi background
score += ga.clearLines(); // menambahkan nilai score saat membersihkan line tetris
gf.updateScore(score); // memanggil method updateScore untuk merubah score
int lvl = score / scorePerLevel + 1;
// update level setiap 3 score
if(lvl > level){
level = lvl;
gf.updateLevel(level);
pause -= speedupPerLevel; // menambah kecepatan game / mengurangi sleep time game
}
}
}
public void endGame(){
// show game over with JOptionPane
gf.audioPlayer.stop();
gf.dispose();
Date endTime = new Date();
long total_game_time = endTime.getTime() - startTime.getTime();
long t_game_h = total_game_time/(60 * 60 * 1000) % 24;
long t_game_m = total_game_time/(60 * 1000) % 60;
long t_game_s = total_game_time/1000 % 60;
//update highscore kalau current score lebih tinggi dari highscore saat sudah game over
if(score > highscore){
FileWriter fileWriter = null;
try {
File high_score_file = new File("tetris_score.txt");
fileWriter = new FileWriter(high_score_file,false);
fileWriter.write(Integer.toString(score)+"\n"+t_game_h+"\n"+t_game_m+"\n"+t_game_s);
fileWriter.close();
} catch (IOException ex) {
Logger.getLogger(Tetris.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
fileWriter.close();
} catch (IOException ex) {
Logger.getLogger(Tetris.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
HighScore(); //update variabel highscore
String waktu = t_game_m+":"+t_game_s;
Tetris.gameOver(score, waktu);
}
//buat set isi dari variable highscore
public void HighScore(){
File high_score_file = new File("tetris_score.txt");
String score;
if(!high_score_file.exists()){
try {
high_score_file.createNewFile();
} catch (IOException ex) {
Logger.getLogger(Tetris.class.getName()).log(Level.SEVERE, null, ex);
}
highscore = 0;
}
else{
try {
Scanner scanner = new Scanner(high_score_file);
while(scanner.hasNextLine()){
score = scanner.nextLine();
highscore = Integer.parseInt(score);
}
scanner.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(Tetris.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
|
package Vista;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
public class VentanaInicioSesion extends javax.swing.JFrame {
///PARA REALIZAR LA CONEXION
private Socket servidor;
private int puerto;
private String host;
private DataInputStream entrada;
private DataOutputStream salida;
//LOGIN DEL APLICATIVO
private String user= new String();
private String password= new String();
private int val=1;
public VentanaInicioSesion(String host, int puerto) {
this.host= host;
this.puerto= puerto;
initComponents();
conexion();
this.setLocationRelativeTo(null);
this.setVisible(true);
this.setResizable(false);
while(val==1){
lecturaDatos();
}
}
public void conexion(){
try {
servidor= new Socket(host, puerto); //CREA EL SOCKET
entrada= new DataInputStream(servidor.getInputStream());
salida=new DataOutputStream(servidor.getOutputStream());
}catch(IOException e) {
val=0;
JOptionPane.showMessageDialog(null, "FALLO EN LA CONEXION CON EL SERVIDOR", "Alerta", JOptionPane.OK_OPTION);
}
}
public void lecturaDatos(){
try {
String respuesta= entrada.readUTF();
if(!respuesta.equals(",")){ //SI LA CONSULTA NO ARROJA RESULTADOS RECIBE UNA ","
int i=respuesta.indexOf(",");
respuesta=respuesta.substring(0,i); //SACA LA CONTRASEÑA DE LO QUE RECIBE
if(respuesta.equals(password)){
activar(); //LLAMA EL METODO QUE INICIALIZA LA NUEVA VENTANA
}
}else{
JOptionPane.showMessageDialog(null, "ERROR DE USUARIO O CONTRASEÑA");
CajonContrasena.setText("");
}
}catch(IOException e) {
val=0; //finaliza la lectura de datos
JOptionPane.showMessageDialog(null, "CONEXION PERDIDA");
}
}
public void activar(){
val=0;
finConexion();
WindowAdmin ventana = new WindowAdmin(this.host, this.puerto); //activa la nueva ventana
}
public void finConexion(){
try {
salida.close();
entrada.close();
servidor.close();
this.dispose();
} catch (IOException ex) {
Logger.getLogger(VentanaInicioSesion.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
CajonUsuario = new javax.swing.JTextField();
CajonContrasena = new javax.swing.JPasswordField();
botonIniciarSesion = new javax.swing.JLabel();
FondoInicioSesion = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setMinimumSize(new java.awt.Dimension(500, 333));
setResizable(false);
setSize(new java.awt.Dimension(500, 333));
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
CajonUsuario.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
CajonUsuario.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CajonUsuarioActionPerformed(evt);
}
});
getContentPane().add(CajonUsuario, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 140, 180, 20));
CajonContrasena.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
getContentPane().add(CajonContrasena, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 200, 180, 20));
botonIniciarSesion.setBackground(new java.awt.Color(18, 146, 195));
botonIniciarSesion.setForeground(new java.awt.Color(255, 255, 255));
botonIniciarSesion.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
botonIniciarSesion.setText("Iniciar sesión");
botonIniciarSesion.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
botonIniciarSesion.setOpaque(true);
botonIniciarSesion.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
botonIniciarSesionMouseClicked(evt);
}
});
getContentPane().add(botonIniciarSesion, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 250, 120, 30));
FondoInicioSesion.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/inicio.png"))); // NOI18N
getContentPane().add(FondoInicioSesion, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, 333));
pack();
}// </editor-fold>//GEN-END:initComponents
private void botonIniciarSesionMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_botonIniciarSesionMouseClicked
// TODO add your handling code here:
try {
user= CajonUsuario.getText();
password= String.valueOf(CajonContrasena.getPassword());
String envio= "SELECT contrasenia FROM LOGIN WHERE codUsuario="+user;
salida.writeUTF(envio);
} catch (IOException ex) {
Logger.getLogger(VentanaInicioSesion.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_botonIniciarSesionMouseClicked
private void CajonUsuarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CajonUsuarioActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_CajonUsuarioActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPasswordField CajonContrasena;
private javax.swing.JTextField CajonUsuario;
private javax.swing.JLabel FondoInicioSesion;
private javax.swing.JLabel botonIniciarSesion;
// End of variables declaration//GEN-END:variables
}
|
package com.cricket.admin_2.cricketerdetails;
import android.view.View;
import com.cricket.admin_2.cricketerdetails.player.Player;
import java.util.ArrayList;
import java.util.List;
/**
* Created by admin_2 on 26/02/2018.
*/
public class PassObject {
View view;
Player player;
ArrayList<Player> srcList;
PassObject(View v, Player i, ArrayList<Player> s) {
view = v;
player = i;
srcList = s;
}
}
|
package uz.zako.example.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import uz.zako.example.entity.Category;
public interface CategoryRepository extends JpaRepository<Category, Long> {
}
|
package common.controller;
//부모클래스 /// 재정의는 하지않되, 공통으로 쓸것적어줌
public abstract class AbstractController
implements Command{
private boolean isRedirect = false;
/*
우리끼리 약속인데
뷰단 페이지(JSP페이지)로 이동시
redirect방법(데이터전달은 없고, 단순히 페이지 이동만 발생)으로
이동시키고자 한다면
isRedirect 변수의 값을 true로 하겠다.
(isRedirect이 기준)
뷰단 페이지(JSP페이지)로 이동시
redirect방법(데이터전달과함께 페이지 이동만 발생)으로
이동시키고자 한다면
isRedirect변수의 값을 false로 하겠다.
*/
private String viewPage;
//뷰단 페이지(jsp페이지) 의 경로명으로 사용되어지는 변수이다.
public boolean isRedirect() {
return isRedirect;
}//리턴타입이 boolean이라면 get이 아니라 is로 나타난다.(get없음)
public void setRedirect(boolean isRedirect) {
this.isRedirect = isRedirect;
}
public String getViewPage() {
return viewPage;
}
public void setViewPage(String viewPage) {
this.viewPage = viewPage;
}
}
|
package juniorvalerav.e15project;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
public class Restablecer extends AppCompatActivity {
private EditText resetPass;
private FirebaseAuth firebaseAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_restablecer);
getSupportActionBar().hide();
firebaseAuth = FirebaseAuth.getInstance();
resetPass = (EditText) findViewById(R.id.restablecer_contrasena);
}
public void ResetPassword(View view) {
String email;
email = resetPass.getText().toString();
SendResetEmail(email);
}
private void SendResetEmail(String email) {
firebaseAuth.sendPasswordResetEmail(email).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
Log.d("RESET_PASSWORD", "resetEmailPassword:onComplete:" + task.isSuccessful());
Toast.makeText(getApplicationContext(), "Email ha sido enviado", Toast.LENGTH_SHORT).show();
goToLogin();
if(!task.isSuccessful()){
Log.w("RESET_PASSWORD", "resetEmailPassword:failed", task.getException());
Toast.makeText(getApplicationContext(), "Error al restablecer contrasena", Toast.LENGTH_SHORT).show();
}
}
});
}
private void goToLogin() {
Intent intento = new Intent(this,Ingreso.class);
intento.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intento);
}
}
|
package com.gxtc.huchuan.ui.deal.deal.dealList;
import android.text.TextUtils;
import com.google.gson.reflect.TypeToken;
import com.gxtc.commlibrary.utils.ErrorCodeUtil;
import com.gxtc.commlibrary.utils.GsonUtil;
import com.gxtc.huchuan.bean.DealListBean;
import com.gxtc.huchuan.bean.DealTypeBean;
import com.gxtc.huchuan.data.deal.DealListRepository;
import com.gxtc.huchuan.helper.RxTaskHelper;
import com.gxtc.huchuan.http.ApiCallBack;
import com.gxtc.huchuan.http.ApiObserver;
import com.gxtc.huchuan.http.ApiResponseBean;
import com.gxtc.huchuan.http.service.DealApi;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
public class DealListPresenter implements DealListContract.Presenter {
private DealListContract.View mView;
private DealListContract.Source mData;
private int start = 0;
public DealListPresenter(DealListContract.View mView) {
this.mView = mView;
this.mView.setPresenter(this);
mData = new DealListRepository();
}
@Override
public void start() {}
@Override
public void destroy() {
mData.destroy();
mView = null;
RxTaskHelper.getInstance().cancelTask(this);
}
@Override
public void getData(final boolean isRefresh, int typeId, List<DealTypeBean> subsMap,
List<DealTypeBean> udefs) {
if (isRefresh) {
start = 0;
} else {
mView.showLoad();
}
HashMap<String, String> map = new HashMap<>();
map.put("start", start + "");
map.put("typeId", typeId + "");
map = fillParam(map,subsMap,udefs);
mData.getData(map, new ApiCallBack<List<DealListBean>>() {
@Override
public void onSuccess(List<DealListBean> data) {
if(mView == null) return;
mView.showLoadFinish();
if (data == null || data.size() == 0) {
mView.showEmpty();
return;
}
if (isRefresh) {
mView.showRefreshFinish(data);
} else {
mView.showData(data);
}
}
@Override
public void onError(String errorCode, String message) {
ErrorCodeUtil.handleErr(mView, errorCode, message);
}
});
}
@Override
public void getType(int id) {
Subscription sub = Observable.concat(DealApi.getInstance().getDealSubType(id),
DealApi.getInstance().getUdefType(id)).observeOn(
AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(
new ApiObserver<ApiResponseBean<List<DealTypeBean>>>(new ApiCallBack() {
List<DealTypeBean> subs;
List<DealTypeBean> udefs;
@Override
public void onCompleted() {
if (subs != null && udefs != null) {
mView.showType(subs, udefs);
}
}
@Override
public void onSuccess(Object data) {
List<DealTypeBean> temp;
if (data instanceof List) {
temp = (List<DealTypeBean>) data;
if (subs == null) {
subs = temp;
} else {
udefs = temp;
}
}
}
@Override
public void onError(String errorCode, String message) {
if(mView == null) return;
mView.showError(message);
}
}));
RxTaskHelper.getInstance().addTask(this,sub);
}
@Override
public void loadMrore(int typeId, List<DealTypeBean> subsMap, List<DealTypeBean> udefs) {
start += 15;
HashMap<String, String> map = new HashMap<>();
map.put("start", start + "");
map.put("typeId", typeId + "");
map = fillParam(map,subsMap,udefs);
mData.getData(map, new ApiCallBack<List<DealListBean>>() {
@Override
public void onSuccess(List<DealListBean> data) {
if (data == null || data.size() == 0) {
start -= 15;
mView.showNoMore();
return;
}
mView.showLoadMore(data);
}
@Override
public void onError(String errorCode, String message) {
if(mView == null) return;
start -= 15;
mView.showError(message);
}
});
}
//过滤数据
@Override
public void filterData(int typeId, List<DealTypeBean> subsMap, List<DealTypeBean> udefs) {
start = 0;
HashMap<String, String> map = new HashMap<>();
map.put("start", start + "");
map.put("typeId", typeId + "");
map = fillParam(map,subsMap,udefs);
mData.getData(map, new ApiCallBack<List<DealListBean>>() {
@Override
public void onSuccess(List<DealListBean> data) {
if(mView == null) return;
if (data == null || data.size() == 0) {
mView.showRefreshFinish(new ArrayList<DealListBean>());
return;
}
mView.showRefreshFinish(data);
}
@Override
public void onError(String errorCode, String message) {
if(mView == null) return;
mView.showError(message);
}
});
}
@Override
public void getPlateDescripte(String tradeTypeId) {
mData.getPlateDescripte(tradeTypeId, new ApiCallBack<Object>() {
@Override
public void onSuccess(Object data) {
if(mView == null) return;
mView.showPlateDescripte(data);
}
@Override
public void onError(String errorCode, String message) {
if(mView == null) return;
mView.showError(message);
}
});
}
private HashMap<String, String> fillParam(HashMap<String, String> map, List<DealTypeBean> subsMap, List<DealTypeBean> udefs) {
if (subsMap != null && udefs != null) {
//子类型ID。多个用逗号拼接。
StringBuffer sb = new StringBuffer();
if(subsMap != null && subsMap.size() > 0){
for (DealTypeBean.TypesBean typeBean : subsMap.get(0).getTypes()) {
if(typeBean.isSelect()){
sb.append(typeBean.getCode()).append(",");
}
}
}
if(sb.length() != 0){
sb.delete(sb.length() - 1,sb.length());
map.put("typeSonId",sb.toString());
}
//查询条件(二维数组json字符串,格式:字段名,查询条件,值) parameter=[["udef1","like","www"],["udef2",">","300"]]。
ArrayList<ArrayList<String>> list2 = new ArrayList<>();
for(DealTypeBean typeBean : udefs){
//0:编辑框,1:城市,2:时间,3,下拉,4,多选,5,单选
int type = typeBean.getUdfType();
if(type == 0 || type == 1 || type == 2){
String content = typeBean.getContent();
if (!TextUtils.isEmpty(content)) {
ArrayList<String> list = new ArrayList<>();
list.add(typeBean.getTradeField());
list.add(typeBean.getChoice());
list.add(content);
list2.add(list);
}
}
if(type == 4 || type == 5){
for(DealTypeBean.TypesBean bean : typeBean.getTypes()){
if(bean.isSelect()){
ArrayList<String> list = new ArrayList<>();
String code = bean.getCode().split(",")[0];
list.add(code);
list.add(bean.getChoice());
list.add(bean.getTitle());
list2.add(list);
}
}
}
}
if(list2.size() != 0){
String param = GsonUtil.objectToJson(list2, new TypeToken<ArrayList<ArrayList<String>>>(){}.getType());
map.put("parameter",param);
}
}
return map;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.