text
stringlengths 10
2.72M
|
|---|
package com.smxknife.mybatis._01_xml;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import java.sql.Statement;
/**
* @author smxknife
* 2021/6/23
*/
@Intercepts({
// 这里的Signature定义的是拦截哪个类的哪个方法,比如这里拦截的是Executor类型,方法是query
@Signature(type = ResultSetHandler.class, method = "handleResultSets", args = {Statement.class})
})
public class ResultSetHandlerPlugin implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
final Object proceed = invocation.proceed();
if (proceed != null) {
System.out.println("ResultSetHandler intercept | " + proceed.getClass());
}
return proceed;
}
@Override
public Object plugin(Object target) {
if (ResultSetHandler.class.isAssignableFrom(target.getClass())) {
System.out.println("ResultSetHandler plugin target | " + target.getClass());
final Object plugin = Interceptor.super.plugin(target);
System.out.println("ResultSetHandler plugin plugin | " + plugin.getClass());
return plugin;
} else {
return target;
}
}
}
|
package org.cap.dao;
import java.util.List;
import org.cap.model.Product;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
@Repository("productDbDao")
@Transactional
public interface IProductDbDao extends JpaRepository<Product, Integer>{
public List<Product> findByquantity(int quantity);
public List<Product> findByquantityAndPrice(int quantity,double price);
public List<Product> findByproductNameContaining(String productName);
}
|
package com.coding.java.lambda.part01;
/**
* Created by scq on 2018-07-26 11:11:17
*/
@FunctionalInterface
public interface MyPredicate<T> {
public boolean test(T t);
}
|
import java.util.Scanner;
public class Problem5_10 {
public static void main(String[] args) {
final int NUMBERS_PER_LINE = 10;
int count = 0 ;
for(int i = 100 ; i<= 1000;i++) {
//Test if number is divisible by 5 and 6
if( i % 5 == 0 && i % 6 == 0) {
count ++; // increment count
//Test if numbers per line is 10
if(count % NUMBERS_PER_LINE == 0)
System.out.println(i);
else
System.out.print(i + " ");
}
}
}
}
/*(Find numbers divisible by 5 and 6) Write a program that
displays all the numbers from 100 to 1,000, ten per line,
that are divisible by 5 and 6. Numbers are separated by exactly one space. */
|
package com.lotto.app;
import org.apache.log4j.Logger;
import com.lotto.app.ServiceLocator;
import com.lotto.model.LottoResult;
import com.lotto.services.LottoService;
public class LottoApp {
private static Logger logger = Logger.getLogger(LottoApp.class);
private static LottoResult lottoResult;
public static void main(String[] args) {
lottoResult = new LottoResult();
try {
LottoService lottoService = ServiceLocator.getLottoService();
lottoResult = lottoService.jouerLotto();
System.out.print(
lottoResult.getFirstTirage() + lottoResult.getSecondTirage() + lottoResult.getThirdTirage());
} catch (Exception e) {
logger.error("Une erreur est survenue : " + e.getMessage());
}
}
}
|
package com.qcwp.carmanager.enumeration;
import com.qcwp.carmanager.R;
/**
* Created by qyh on 2017/1/3.
*/
public enum ProfessionalTestEnum {
HectometerAccelerate(2),
KilometersAccelerate(5),
KilometersBrake(6),
Noise(7),
Unknown(0);
private final int value;
ProfessionalTestEnum(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
|
package com.project.loginservice.service;
import com.project.loginservice.pojo.BuyerSignupPojo;
public interface BuyerSignupService {
BuyerSignupPojo validateBuyersignup(BuyerSignupPojo buyerSignupPojo);
BuyerSignupPojo getBuyer(Integer id);
}
|
package com.example.rashapp;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
public class Collect_Data extends AppCompatActivity implements SensorEventListener {
public static String ops[] ={"Select","Weaving","Lanechanging","Sudden Braking"};
Spinner sp;
Button b,b1,b2;
Sensor accelerometer;
SensorManager sm;
private SensorManager sensorManager;
// private Sensor accelerometer;
private float deltaXMax = 0;
private float deltaYMax = 0;
private float deltaZMax = 0;
private float deltaX = 0;
private float deltaY = 0;
private float deltaZ = 0;
boolean flag =false;
private float vibrateThreshold = 0;
public Vibrator v;
private float lastX, lastY, lastZ;
String data="",type= "";
Vibrator vibrator;
MediaPlayer mediaPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_collect__data);
sp = (Spinner) findViewById(R.id.sp);
b = (Button) findViewById(R.id.button);
b1 = (Button) findViewById(R.id.button1);
b2=(Button)findViewById(R.id.btnTV);
ArrayAdapter<String> adapterCategory = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,ops);
adapterCategory.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(adapterCategory);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
if (sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null) {
// success! we have an accelerometer
accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
vibrateThreshold = accelerometer.getMaximumRange() / 2;
} else {
// fai! we dont have an accelerometer!
}
vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
//initialize vibration
v = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
((Button) findViewById(R.id.button)).setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View arg0, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN){
// start the thread
Log.d(">>","Touched");
type=sp.getSelectedItem().toString();
flag =true;
return true;
} else if(event.getAction() == MotionEvent.ACTION_UP){
// stop the thread
Log.d(">>","Released");
flag =false;
new update_loc().execute();
return true;
}
return false;
}
});
((Button) findViewById(R.id.button1)).setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View arg0, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN){
// start the thread
Log.d(">>","Touched");
b2.setVisibility(View.INVISIBLE);
flag =true;
return true;
} else if(event.getAction() == MotionEvent.ACTION_UP){
// stop the thread
Log.d(">>","Released");
flag =false;
new update_loc1().execute();
return true;
}
return false;
}
});
}
private class update_loc extends AsyncTask<Void, String, String>
{
@Override
public String doInBackground(Void... Void)
{
JSONObject jsn = new JSONObject();
String response = "";
try {
URL url = new URL(Global.url +"train_data");
jsn.put("type", type);
jsn.put("data", data);
response = HttpClientConnection.getData(url,jsn);
Log.d("Response",""+response);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch(JSONException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
return response;
}
@Override
protected void onPostExecute(String s) {
if(s.endsWith("null"))
{
s=s.substring(0,s.length()-4);
}
Toast.makeText(getApplicationContext(),s, Toast.LENGTH_LONG).show();
data="";
}
}
private class update_loc1 extends AsyncTask<Void, String, String>
{
@Override
public String doInBackground(Void... Void)
{
JSONObject jsn = new JSONObject();
String response = "";
try {
URL url = new URL(Global.url +"predict_data");
jsn.put("data", data);
response = HttpClientConnection.getData(url,jsn);
Log.d("Response",""+response);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch(JSONException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
return response;
}
@Override
protected void onPostExecute(String s) {
if(s.endsWith("null"))
{
s=s.substring(0,s.length()-4);
}
if(!s.equalsIgnoreCase(""))
{
b2.setVisibility(View.VISIBLE);
b2.setText(s);
Toast.makeText(getApplicationContext(),s, Toast.LENGTH_LONG).show();
if (Build.VERSION.SDK_INT >= 26) {
vibrator.vibrate(VibrationEffect.createOneShot(4000, VibrationEffect.DEFAULT_AMPLITUDE));
} else {
vibrator.vibrate(4000);
}
mediaPlayer = MediaPlayer.create(Collect_Data.this, R.raw.m);
mediaPlayer.start();
// data="";
}
}
}
@Override
public void onSensorChanged(SensorEvent event) {
//This is done to prevent multiple values above threshold being registered as multiple potholes
long actualTime = event.timestamp;
// get the change of the x,y,z values of the accelerometer
deltaX = Math.abs(lastX - event.values[0]);
deltaY = Math.abs(lastY - event.values[1]);
deltaZ = Math.abs(lastZ - event.values[2]);
// if the change is below 2, it is just plain noise
if (deltaX < 2)
deltaX = 0;
if (deltaY < 2)
deltaY = 0;
if ((deltaZ >vibrateThreshold) || (deltaY > vibrateThreshold) || (deltaZ > vibrateThreshold)) {
v.vibrate(50);
}
if(flag==true) {
Log.d("moves", deltaX + "#" + deltaY + "#" + deltaZ + "");
data+=deltaX + "#" + deltaY + "#" + deltaZ + "\n";
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
//onResume() register the accelerometer for listening the events
protected void onResume() {
super.onResume();
sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
//onPause() unregister the accelerometer for stop listening the events
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
}
|
package yincheng.gggithub.provider.viewholder;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.format.Formatter;
import android.view.View;
import android.view.ViewGroup;
import java.text.NumberFormat;
import butterknife.BindView;
import yincheng.gggithub.R;
import yincheng.gggithub.helper.InputHelper;
import yincheng.gggithub.helper.LinkParserHelper;
import yincheng.gggithub.helper.ParseDateFormat;
import yincheng.gggithub.library.recyclerview.BaseRecyclerAdapter;
import yincheng.gggithub.library.recyclerview.BaseViewHolder;
import yincheng.gggithub.mvp.model.Repo;
import yincheng.gggithub.view.widget.AvatarLayout;
import yincheng.gggithub.view.widget.FontTextView;
public class ReposViewHolder extends BaseViewHolder<Repo> {
@BindView(R.id.title) FontTextView title;
@BindView(R.id.date) FontTextView date;
@BindView(R.id.stars) FontTextView stars;
@BindView(R.id.forks) FontTextView forks;
@BindView(R.id.language) FontTextView language;
@BindView(R.id.size) FontTextView size;
@Nullable @BindView(R.id.avatarLayout) AvatarLayout avatarLayout;
// @BindString(R.string.forked) String forked;
// @BindString(R.string.private_repo) String privateRepo;
// @BindColor(R.color.material_indigo_700) int forkColor;
// @BindColor(R.color.material_grey_700) int privateColor;
private boolean isStarred;
private boolean withImage;
private ReposViewHolder(@NonNull View itemView, @Nullable BaseRecyclerAdapter adapter, boolean
isStarred, boolean withImage) {
super(itemView, adapter);
this.isStarred = isStarred;
this.withImage = withImage;
}
public static ReposViewHolder newInstance(ViewGroup viewGroup, BaseRecyclerAdapter adapter,
boolean isStarred, boolean withImage) {
if (withImage) {
return new ReposViewHolder(getView(viewGroup, R.layout.item_repo_searched), adapter,
isStarred, true);
} else {
return new ReposViewHolder(getView(viewGroup, R.layout.item_repo_searched_noimage),
adapter, isStarred, false);
}
}
@Override public void bind(@NonNull Repo repo) {
if (repo.isFork() && !isStarred) {
// title.setText(SpannableBuilder.builder()
// .append(" " + forked + " ", new LabelSpan(forkColor))
// .append(" ")
// .append(repo.getName(), new LabelSpan(Color.TRANSPARENT)));
title.setText("fasdfa");
} else if (repo.isPrivateX()) {
// title.setText(SpannableBuilder.builder()
// .append(" " + privateRepo + " ", new LabelSpan(privateColor))
// .append(" ")
// .append(repo.getName(), new LabelSpan(Color.TRANSPARENT)));
title.setText("wodeshijie");
} else {
title.setText(!isStarred ? repo.getName() : repo.getFull_name());
}
if (withImage) {
String avatar = repo.getOwner() != null ? repo.getOwner().getAvatar_url() : null;
String login = repo.getOwner() != null ? repo.getOwner().getLogin() : null;
boolean isOrg = repo.getOwner() != null && repo.getOwner().isSite_admin();
if (avatarLayout != null) {
avatarLayout.setVisibility(View.VISIBLE);
avatarLayout.setUrl(avatar, login, isOrg, LinkParserHelper.isEnterprise(repo
.getHtml_url()));
}
}
long repoSize = repo.getSize() > 0 ? (repo.getSize() * 1000) : repo.getSize();
size.setText(Formatter.formatFileSize(size.getContext(), repoSize));
NumberFormat numberFormat = NumberFormat.getNumberInstance();
stars.setText(numberFormat.format(repo.getStargazers_count()));
forks.setText(numberFormat.format(repo.getForks()));
date.setText(ParseDateFormat.getTimeAgo(repo.getUpdated_at()));
if (!InputHelper.isEmpty(repo.getLanguage())) {
language.setText(repo.getLanguage());
// language.setTextColor(ColorsProvider.getColorAsColor(repo.getLanguage(), language
// .getContext()));
language.setVisibility(View.VISIBLE);
} else {
language.setTextColor(Color.BLACK);
language.setVisibility(View.GONE);
language.setText("");
}
}
}
|
/*
* created 09.01.2006
*
* Copyright 2009, ByteRefinery
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* $Id$
*/
package com.byterefinery.rmbench.test;
import com.byterefinery.rmbench.external.IDDLFormatter;
import com.byterefinery.rmbench.external.IDDLGenerator;
import com.byterefinery.rmbench.external.IDDLScript;
import com.byterefinery.rmbench.external.IDDLScript.Statement;
/**
* a test formatter that just writes statements through
*
* @author cse
*/
public class DDLFormatter implements IDDLFormatter {
public static final class Factory implements IDDLFormatter.Factory {
public IDDLFormatter createFormatter(IDDLGenerator generator) {
return new DDLFormatter();
}
}
public void format(Statement statement, String terminator, IDDLScript.Writer writer) {
writer.print(statement.getString());
writer.println();
}
}
|
package com.phplogin.sidag.gcm;
import android.app.IntentService;
import android.content.Intent;
import android.util.Log;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;
import java.io.IOException;
/**
* Created by Siddhant on 11/14/2015.
*/
public class RegistrationIntentService extends IntentService {
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* @param name Used to name the worker thread, important only for debugging.
*/
private static final String name = "RegistrationService";
public RegistrationIntentService() {
super(name);
}
public void onCreate(){
super.onCreate();
}
@Override
protected void onHandleIntent(Intent intent) {
InstanceID instanceID = InstanceID.getInstance(this);
try {
String token = instanceID.getToken("939133146521",
GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
Log.d("token", "Token: " + token);
} catch (IOException e) {
e.printStackTrace();
}
}
private void sendTokenToServer(String token){
}
}
|
package com.asen.android.lib.permissions.core;
/**
* 权限监测的监听调用
*
* @author Asen
* @version v2.0
* @email [email protected]
* @date 2017/5/16 13:26
*/
public interface OnCheckPermissionListener {
/**
* 成功授予权限时回调
*/
public void permissionGranted();
}
|
package com.sales.entity;
import java.util.Date;
public class SalesOrderDetailEntity {
private Integer salesDetailId;
private Integer salesOrderId;
private Integer productId;
private String productName;
private String productSpu;
private String customCode;
private Integer productDetailId;
private String productSku;
private String colorName;
private String sizeName;
private String productBarcode;
private Integer productQuantity;
private Integer salesPackageQuantity;
private Double productPrice;
private Double productTotalPrice;
private Double productDiscount;
private Integer storeId;
private String salesDetailRemark;
private Date createTime;
private Date updateTime;
public Integer getSalesDetailId() {
return salesDetailId;
}
public void setSalesDetailId(Integer salesDetailId) {
this.salesDetailId = salesDetailId;
}
public Integer getSalesOrderId() {
return salesOrderId;
}
public void setSalesOrderId(Integer salesOrderId) {
this.salesOrderId = salesOrderId;
}
public Integer getProductId() {
return productId;
}
public void setProductId(Integer productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName == null ? null : productName.trim();
}
public String getProductSpu() {
return productSpu;
}
public void setProductSpu(String productSpu) {
this.productSpu = productSpu == null ? null : productSpu.trim();
}
public String getCustomCode() {
return customCode;
}
public void setCustomCode(String customCode) {
this.customCode = customCode == null ? null : customCode.trim();
}
public Integer getProductDetailId() {
return productDetailId;
}
public void setProductDetailId(Integer productDetailId) {
this.productDetailId = productDetailId;
}
public String getProductSku() {
return productSku;
}
public void setProductSku(String productSku) {
this.productSku = productSku == null ? null : productSku.trim();
}
public String getColorName() {
return colorName;
}
public void setColorName(String colorName) {
this.colorName = colorName == null ? null : colorName.trim();
}
public String getSizeName() {
return sizeName;
}
public void setSizeName(String sizeName) {
this.sizeName = sizeName == null ? null : sizeName.trim();
}
public String getProductBarcode() {
return productBarcode;
}
public void setProductBarcode(String productBarcode) {
this.productBarcode = productBarcode == null ? null : productBarcode.trim();
}
public Integer getProductQuantity() {
return productQuantity;
}
public void setProductQuantity(Integer productQuantity) {
this.productQuantity = productQuantity;
}
public Integer getSalesPackageQuantity() {
return salesPackageQuantity;
}
public void setSalesPackageQuantity(Integer salesPackageQuantity) {
this.salesPackageQuantity = salesPackageQuantity;
}
public Double getProductPrice() {
return productPrice;
}
public void setProductPrice(Double productPrice) {
this.productPrice = productPrice;
}
public Double getProductTotalPrice() {
return productTotalPrice;
}
public void setProductTotalPrice(Double productTotalPrice) {
this.productTotalPrice = productTotalPrice;
}
public Double getProductDiscount() {
return productDiscount;
}
public void setProductDiscount(Double productDiscount) {
this.productDiscount = productDiscount;
}
public Integer getStoreId() {
return storeId;
}
public void setStoreId(Integer storeId) {
this.storeId = storeId;
}
public String getSalesDetailRemark() {
return salesDetailRemark;
}
public void setSalesDetailRemark(String salesDetailRemark) {
this.salesDetailRemark = salesDetailRemark == null ? null : salesDetailRemark.trim();
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
}
|
import java.util.*;
class kmax {
public static void main(String args[]) {
int j,i,n,k,max;
Scanner in=new Scanner(System.in);
n=in.nextInt();
int[] a=new int[n];
for(i=0;i<n;i++) {
a[i]=in.nextInt();
}
k=in.nextInt();
for(i=0;i<a.length-k;i++) {
max=a[i];
for(j=1;j<k;j++) {
if(a[i+j] > max)
max=a[i+j];
}System.out.print(max + " ");
}
}}
|
public class whackAmoleRunner {
public static void main(String[] args) {
whackAmole wam=new whackAmole();
wam.makeButtons();
}
}
|
/**
* MOTECH PLATFORM OPENSOURCE LICENSE AGREEMENT
*
* Copyright (c) 2010-11 The Trustees of Columbia University in the City of
* New York and Grameen Foundation USA. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of Grameen Foundation USA, Columbia University, or
* their respective contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY GRAMEEN FOUNDATION USA, COLUMBIA UNIVERSITY
* AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRAMEEN FOUNDATION
* USA, COLUMBIA UNIVERSITY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.motechproject.server.omod.web.controller;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.motechproject.server.service.ContextService;
import org.motechproject.server.omod.web.model.WebModelConverter;
import org.motechproject.server.omod.web.model.WebPatient;
import org.motechproject.server.svc.RegistrarBean;
import org.motechproject.server.util.MotechConstants;
import org.motechproject.ws.ContactNumberType;
import org.motechproject.ws.Gender;
import org.motechproject.ws.MediaType;
import org.openmrs.Patient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
@Controller
@RequestMapping("/module/motechmodule/pregnancy")
@SessionAttributes("pregnancy")
public class PregnancyController {
private static Log log = LogFactory.getLog(PregnancyController.class);
private WebModelConverter webModelConverter;
@Autowired
@Qualifier("registrarBean")
private RegistrarBean registrarBean;
private ContextService contextService;
@Autowired
public void setContextService(ContextService contextService) {
this.contextService = contextService;
}
public void setRegistrarBean(RegistrarBean registrarBean) {
this.registrarBean = registrarBean;
}
@Autowired
public void setWebModelConverter(WebModelConverter webModelConverter) {
this.webModelConverter = webModelConverter;
}
@InitBinder
public void initBinder(WebDataBinder binder) {
String datePattern = "dd/MM/yyyy";
SimpleDateFormat dateFormat = new SimpleDateFormat(datePattern);
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(
dateFormat, true, datePattern.length()));
String timePattern = MotechConstants.TIME_FORMAT_DELIVERY_TIME;
SimpleDateFormat timeFormat = new SimpleDateFormat(timePattern);
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, "timeOfDay",
new CustomDateEditor(timeFormat, true, timePattern.length()));
binder
.registerCustomEditor(String.class, new StringTrimmerEditor(
true));
}
@RequestMapping(method = RequestMethod.GET)
public void viewForm(@RequestParam(required = false) Integer id,
ModelMap model) {
}
@ModelAttribute("pregnancy")
public WebPatient getWebPregnancy(@RequestParam(required = false) Integer id) {
WebPatient result = new WebPatient();
if (id != null) {
Patient patient = contextService.getPatientService().getPatient(id);
if (patient != null) {
webModelConverter.patientToWeb(patient, result);
}
}
return result;
}
@RequestMapping(method = RequestMethod.POST)
public String submitForm(@ModelAttribute("pregnancy") WebPatient pregnancy,
Errors errors, ModelMap model, SessionStatus status) {
log.debug("Register New Pregnancy on Existing Patient");
Patient patient = null;
if (pregnancy.getId() != null) {
patient = registrarBean.getPatientById(pregnancy.getId());
if (patient == null) {
errors.reject("motechmodule.id.notexist");
}
} else {
errors.reject("motechmodule.id.required");
}
if (!Gender.FEMALE.equals(pregnancy.getSex())) {
errors.reject("motechmodule.sex.female.required");
}
if (registrarBean.getActivePregnancy(pregnancy.getId()) != null) {
errors.reject("motechmodule.Pregnancy.active");
}
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "dueDate",
"motechmodule.dueDate.required");
if (pregnancy.getDueDate() != null) {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, 9);
if (pregnancy.getDueDate().after(calendar.getTime())) {
errors.rejectValue("dueDate",
"motechmodule.dueDate.overninemonths");
}
}
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "dueDateConfirmed",
"motechmodule.dueDateConfirmed.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "enroll",
"motechmodule.enroll.required");
if (Boolean.TRUE.equals(pregnancy.getEnroll())) {
if (!Boolean.TRUE.equals(pregnancy.getConsent())) {
errors.rejectValue("consent", "motechmodule.consent.required");
}
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "phoneType",
"motechmodule.phoneType.required");
if (pregnancy.getPhoneType() == ContactNumberType.PERSONAL
|| pregnancy.getPhoneType() == ContactNumberType.HOUSEHOLD) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors,
"phoneNumber", "motechmodule.phoneNumber.required");
}
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "mediaType",
"motechmodule.mediaType.required");
if (pregnancy.getPhoneType() == ContactNumberType.PUBLIC
&& pregnancy.getMediaType() != null
&& pregnancy.getMediaType() != MediaType.VOICE) {
errors.rejectValue("mediaType", "motechmodule.mediaType.voice");
}
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "language",
"motechmodule.language.required");
if (pregnancy.getMediaType() == MediaType.TEXT
&& pregnancy.getLanguage() != null
&& !pregnancy.getLanguage().equals("en")) {
errors.rejectValue("language", "motechmodule.language.english");
}
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "interestReason",
"motechmodule.interestReason.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "howLearned",
"motechmodule.howLearned.required");
}
if (pregnancy.getPhoneNumber() != null
&& !pregnancy.getPhoneNumber().matches(
MotechConstants.PHONE_REGEX_PATTERN)) {
errors.rejectValue("phoneNumber",
"motechmodule.phoneNumber.invalid");
}
validateTextLength(errors, "phoneNumber", pregnancy.getPhoneNumber(),
MotechConstants.MAX_STRING_LENGTH_OPENMRS);
if (!errors.hasErrors()) {
registrarBean.registerPregnancy(patient, pregnancy.getDueDate(),
pregnancy.getDueDateConfirmed(), pregnancy.getEnroll(),
pregnancy.getConsent(), pregnancy.getPhoneNumber(),
pregnancy.getPhoneType(), pregnancy.getMediaType(),
pregnancy.getLanguage(), pregnancy.getDayOfWeek(),
pregnancy.getTimeOfDay(), pregnancy.getInterestReason(),
pregnancy.getHowLearned());
model.addAttribute("successMsg",
"motechmodule.Pregnancy.register.success");
status.setComplete();
return "redirect:/module/motechmodule/viewdata.form";
}
return "/module/motechmodule/pregnancy";
}
void validateTextLength(Errors errors, String fieldname, String fieldValue,
int lengthLimit) {
if (fieldValue != null && fieldValue.length() > lengthLimit) {
errors.rejectValue(fieldname, "motechmodule.string.maxlength",
new Integer[] { lengthLimit },
"Specified text is longer than max characters.");
}
}
}
|
package tsubulko.entity;
import tsubulko.entity.Person;
import lombok.*;
import java.util.Date;
import java.util.LinkedList;
@Data
public class Employee extends Person {
public enum Education {
None,
Middle,
Hight;
}
private double salary;
private int experiense;
// private LinkedList<String> workPlaces;
private Education education;
public Employee(int id,Birth dateOfBirth, String name, String surname, Sex sex, String email, Adress adress,Position position, double salary, int experiense, Education education) {
super(id,dateOfBirth, name, surname, sex, email, adress, position);
this.salary = salary;
this.experiense = experiense;
// this.workPlaces = workPlaces;
this.education = education;
}
public Employee() {
}
}
|
package com.parkinglot;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.*;
public class AttendantTest {
@Test
public void ShouldParkWhenSpacesAreAvailable() throws Exception{
ParkingLot availableLot = mock(ParkingLot.class);
List<ParkingLot> allLots = new ArrayList<ParkingLot>();
allLots.add(availableLot);
Attendant attendant = new Attendant(allLots);
Parkable car = mock(Parkable.class);
when(availableLot.isSpaceAvailable()).thenReturn(true);
attendant.attendantPark(car);
verify(availableLot).park(car);
}
@Test
public void ShouldBeAllowedToParkInAvailableLotWhenOneLotIsFull() throws Exception{
ParkingLot fullLot = mock(ParkingLot.class);
Parkable car= mock(Parkable.class);
ParkingLot availableLot = mock(ParkingLot.class);
List<ParkingLot> allLots = new ArrayList<ParkingLot>();
allLots.add(fullLot);
allLots.add(availableLot);
Attendant attendant = new Attendant(allLots);
Parkable anotherCar = mock(Parkable.class);
when(fullLot.isSpaceAvailable()).thenReturn(false);
when(availableLot.isSpaceAvailable()).thenReturn(true);
attendant.attendantPark(anotherCar);
verify(availableLot).park(anotherCar);
}
@Test
public void ShouldNotBeAllowedToParkWhenAllLotsFull() throws Exception{
ParkingLot fullLot = mock(ParkingLot.class);
ParkingLot availableLot = mock(ParkingLot.class);
List<ParkingLot> allLots = new ArrayList<ParkingLot>();
allLots.add(fullLot);
allLots.add(availableLot);
Attendant attendant = new Attendant(allLots);
Parkable car = mock(Parkable.class);
when(fullLot.isSpaceAvailable()).thenReturn(false);
when(availableLot.isSpaceAvailable()).thenReturn(false);
assertThrows(AllParkingLotsFullException.class, () ->
attendant.attendantPark(car));
}
}
|
package jawale.ankita.stateslistproject;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class StatesAdapter extends RecyclerView.Adapter<StatesAdapter.StateViewHolder> {
public interface ListItemClickListener{
void onListItemClick(int position);
}
private String[] stateLists;
ListItemClickListener itemClickListener;
public StatesAdapter(String[] stateLists,ListItemClickListener itemClickListener) {
this.stateLists = stateLists;
this.itemClickListener = itemClickListener;
}
@NonNull
@Override
public StateViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
Boolean attachViewImmediatelyToParent = false;
View singleItemLayout = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item,parent,attachViewImmediatelyToParent);
StateViewHolder myViewHolder = new StateViewHolder(singleItemLayout);
return myViewHolder;
}
@Override
public void onBindViewHolder(@NonNull StatesAdapter.StateViewHolder holder, int position) {
holder.textToShow.setText(stateLists[position]);
}
@Override
public int getItemCount() {
return stateLists.length;
}
public class StateViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView textToShow;
public StateViewHolder(View itemView) {
super(itemView);
textToShow = (TextView) itemView.findViewById(R.id.text_view);
textToShow.setOnClickListener(this);
}
@Override
public void onClick(View v) {
itemClickListener.onListItemClick(getAdapterPosition());
}
}
}
|
package com.briup.apps.zhaopin.bean;
public class City {
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column zp_city.id
*
* @mbg.generated Wed Dec 11 22:10:15 CST 2019
*/
private Long id;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column zp_city.name
*
* @mbg.generated Wed Dec 11 22:10:15 CST 2019
*/
private String name;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column zp_city.province_id
*
* @mbg.generated Wed Dec 11 22:10:15 CST 2019
*/
private Long provinceId;
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column zp_city.id
*
* @return the value of zp_city.id
*
* @mbg.generated Wed Dec 11 22:10:15 CST 2019
*/
public Long getId() {
return id;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column zp_city.id
*
* @param id the value for zp_city.id
*
* @mbg.generated Wed Dec 11 22:10:15 CST 2019
*/
public void setId(Long id) {
this.id = id;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column zp_city.name
*
* @return the value of zp_city.name
*
* @mbg.generated Wed Dec 11 22:10:15 CST 2019
*/
public String getName() {
return name;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column zp_city.name
*
* @param name the value for zp_city.name
*
* @mbg.generated Wed Dec 11 22:10:15 CST 2019
*/
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column zp_city.province_id
*
* @return the value of zp_city.province_id
*
* @mbg.generated Wed Dec 11 22:10:15 CST 2019
*/
public Long getProvinceId() {
return provinceId;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column zp_city.province_id
*
* @param provinceId the value for zp_city.province_id
*
* @mbg.generated Wed Dec 11 22:10:15 CST 2019
*/
public void setProvinceId(Long provinceId) {
this.provinceId = provinceId;
}
}
|
/*
* Copyright (c) 2010, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.jar.JarFile;
import java.util.jar.JarInputStream;
import java.util.jar.JarOutputStream;
import au.net.zeus.util.jar.Pack200;
/*
* @test
* @bug 6985763
* @summary verify that proper exceptions are thrown
* @compile -XDignore.symbol.file Utils.java TestExceptions.java
* @run main TestExceptions
* @author ksrini
*/
public class TestExceptions {
static final File testJar = new File("test.jar");
static final File testPackFile = new File("test.pack");
static void init() {
Utils.jar("cvf", testJar.getAbsolutePath(), ".");
JarFile jf = null;
try {
jf = new JarFile(testJar);
Utils.pack(jf, testPackFile);
} catch (IOException ioe) {
throw new Error("Initialization error", ioe);
} finally {
Utils.close(jf);
}
}
// a test that closes the input jarFile.
static void pack200Test1() {
PackTestInput ti = null;
// setup the scenario
try {
ti = new PackTestInput(new JarFile(testJar), new ByteArrayOutputStream());
} catch (Exception e) {
throw new Error("Initialization error", e);
} finally {
Utils.close(ti.getJarFile());
}
// test the scenario
try {
System.out.println(ti);
Pack200.Packer p = Pack200.newPacker();
p.pack(ti.getJarFile(), ti.getOutputStream());
} catch (Exception e) {
ti.checkException(e);
} finally {
if (ti != null) {
ti.close();
}
}
}
// test the Pack200.pack(JarFile, OutputStream);
static void pack200Test2() {
List<PackTestInput> tlist = new ArrayList<PackTestInput>();
try {
// setup the test scenarios
try {
tlist.add(new PackTestInput((JarFile)null, null));
tlist.add(new PackTestInput(new JarFile(testJar), null));
tlist.add(new PackTestInput((JarFile)null, new ByteArrayOutputStream()));
} catch (Exception e) {
throw new Error("Initialization error", e);
}
// test the scenarios
for (PackTestInput ti : tlist) {
System.out.println(ti);
try {
Pack200.Packer p = Pack200.newPacker();
p.pack(ti.getJarFile(), ti.getOutputStream());
} catch (Exception e) {
ti.checkException(e);
}
}
} finally { // clean up
for (TestInput ti : tlist) {
if (ti != null) {
ti.close();
}
}
}
}
// test the Pack200.pack(JarInputStream, OutputStream);
static void pack200Test3() {
List<PackTestJarInputStream> tlist = new ArrayList<PackTestJarInputStream>();
try {
// setup the test scenarios
try {
tlist.add(new PackTestJarInputStream((JarInputStream)null, null));
tlist.add(new PackTestJarInputStream((JarInputStream)null,
new ByteArrayOutputStream()));
tlist.add(new PackTestJarInputStream(
new JarInputStream(new FileInputStream(testJar)), null));
} catch (Exception e) {
throw new Error("Initialization error", e);
}
for (PackTestJarInputStream ti : tlist) {
System.out.println(ti);
try {
Pack200.Packer p = Pack200.newPacker();
p.pack(ti.getJarInputStream(), ti.getOutputStream());
} catch (Exception e) {
ti.checkException(e);
}
}
} finally { // clean up
for (PackTestJarInputStream ti : tlist) {
if (ti != null) {
ti.close();
}
}
}
}
// test the Pack200.unpack(InputStream, OutputStream);
static void unpack200Test1() {
List<UnpackTestInput> tlist = new ArrayList<UnpackTestInput>();
try {
// setup the test scenarios
try {
tlist.add(new UnpackTestInput((InputStream)null, null));
tlist.add(new UnpackTestInput(new FileInputStream(testPackFile),
null));
tlist.add(new UnpackTestInput((InputStream) null,
new JarOutputStream(new ByteArrayOutputStream())));
} catch (Exception e) {
throw new Error("Initialization error", e);
}
// test the scenarios
for (UnpackTestInput ti : tlist) {
System.out.println(ti);
try {
Pack200.Unpacker unpacker = Pack200.newUnpacker();
unpacker.unpack(ti.getInputStream(), ti.getJarOutputStream());
} catch (Exception e) {
ti.checkException(e);
}
}
} finally { // clean up
for (TestInput ti : tlist) {
if (ti != null) {
ti.close();
}
}
}
}
// test the Pack200.unpack(File, OutputStream);
static void unpack200Test2() {
List<UnpackTestFileInput> tlist = new ArrayList<UnpackTestFileInput>();
try {
// setup the test scenarios
try {
tlist.add(new UnpackTestFileInput((File)null, null));
tlist.add(new UnpackTestFileInput(testPackFile, null));
tlist.add(new UnpackTestFileInput((File)null,
new JarOutputStream(new ByteArrayOutputStream())));
} catch (Exception e) {
throw new Error("Initialization error", e);
}
// test the scenarios
for (UnpackTestFileInput ti : tlist) {
System.out.println(ti);
try {
Pack200.Unpacker unpacker = Pack200.newUnpacker();
unpacker.unpack(ti.getInputFile(), ti.getJarOutputStream());
} catch (Exception e) {
ti.checkException(e);
}
}
} finally { // clean up
for (TestInput ti : tlist) {
if (ti != null) {
ti.close();
}
}
}
}
public static void main(String... args) throws IOException {
init();
pack200Test1();
pack200Test2();
pack200Test3();
unpack200Test1();
Utils.cleanup();
}
// containers for test inputs and management
static abstract class TestInput {
private final Object in;
private final Object out;
final boolean shouldNPE;
final String testname;
public TestInput(String name, Object in, Object out) {
this.testname = name;
this.in = in;
this.out = out;
shouldNPE = (in == null || out == null);
}
@Override
public String toString() {
StringBuilder outStr = new StringBuilder(testname);
outStr.append(", input:").append(in);
outStr.append(", output:").append(this.out);
outStr.append(", should NPE:").append(shouldNPE);
return outStr.toString();
}
void close() {
if (in != null && (in instanceof Closeable)) {
Utils.close((Closeable) in);
}
if (out != null && (out instanceof Closeable)) {
Utils.close((Closeable) out);
}
}
void checkException(Throwable t) {
if (shouldNPE) {
if (t instanceof NullPointerException) {
System.out.println("Got expected exception");
return;
} else {
throw new RuntimeException("Expected NPE, but got ", t);
}
}
if (t instanceof IOException) {
System.out.println("Got expected exception");
return;
} else {
throw new RuntimeException("Expected IOException but got ", t);
}
}
}
static class PackTestInput extends TestInput {
public PackTestInput(JarFile jf, OutputStream out) {
super("PackTestInput", jf, out);
}
JarFile getJarFile() {
return (JarFile) super.in;
}
OutputStream getOutputStream() {
return (OutputStream) super.out;
}
};
static class PackTestJarInputStream extends TestInput {
public PackTestJarInputStream(JarInputStream in, OutputStream out) {
super("PackTestJarInputStream", in, out);
}
JarInputStream getJarInputStream() {
return (JarInputStream) super.in;
}
OutputStream getOutputStream() {
return (OutputStream) super.out;
}
};
static class UnpackTestInput extends TestInput {
public UnpackTestInput(InputStream in, JarOutputStream out) {
super("UnpackTestInput", in, out);
}
InputStream getInputStream() {
return (InputStream) super.in;
}
JarOutputStream getJarOutputStream() {
return (JarOutputStream) super.out;
}
};
static class UnpackTestFileInput extends TestInput {
public UnpackTestFileInput(File in, JarOutputStream out) {
super("UnpackTestInput", in, out);
}
File getInputFile() {
return (File) super.in;
}
JarOutputStream getJarOutputStream() {
return (JarOutputStream) super.out;
}
};
}
|
package jvm_test;
import sun.misc.Launcher;
import java.net.URL;
/**
* Description: 查看Bootstrap ClassLoader加载的jar或class文件
*
* @author Baltan
* @date 2019-05-30 17:16
*/
public class Test2 {
public static void main(String[] args) {
URL[] urls = Launcher.getBootstrapClassPath().getURLs();
for (int i = 0; i < urls.length; i++) {
System.out.println(urls[i].toExternalForm());
}
System.out.println("---------------------------------------------");
System.out.println(System.getProperty("sun.boot.class.path"));
}
}
|
package org.apache.commons.net.examples.mail;
import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Locale;
class Utils {
static String getPassword(String username, String password) throws IOException {
if ("-".equals(password)) {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
password = in.readLine();
} else if ("*".equals(password)) {
Console con = System.console();
if (con != null) {
char[] pwd = con.readPassword("Password for " + username + ": ", new Object[0]);
password = new String(pwd);
} else {
throw new IOException("Cannot access Console");
}
} else if (password.equals(password.toUpperCase(Locale.ROOT))) {
String tmp = System.getenv(password);
if (tmp != null)
password = tmp;
}
return password;
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\org\apache\commons\net\examples\mail\Utils.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
|
package project;
public class Order {
private Customer customer;
private Employee employee;
private Meal meal;
private int workRemaining;
public Order(Customer customer, Employee employee, Meal meal) {
this.customer = customer;
this.employee = employee;
this.meal = meal;
// Round down the work amount
double work = meal.getWorkAmount() * employee.getPerformance();
this.workRemaining = (int) work;
}
public Customer getCustomer() {
return this.customer;
}
public Employee getEmployee() {
return this.employee;
}
public Meal getMeal() {
return this.meal;
}
public int getWorkRemaining() {
return this.workRemaining;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public void setMeal(Meal meal) {
this.meal = meal;
}
public void work () {
this.workRemaining--;
}
}
|
package edu.wpi.cs.justice.cardmaker;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import org.json.simple.JSONObject;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import com.amazonaws.services.lambda.runtime.RequestStreamHandler;
import com.google.gson.Gson;
import edu.wpi.cs.justice.cardmaker.db.ElementDAO;
import edu.wpi.cs.justice.cardmaker.http.ListImageResponse;
/** List all the image urls existing in our RDS
*
* @author justice509
*/
public class ListImageHandler implements RequestStreamHandler {
public LambdaLogger logger = null;
/** Load the images in RDS if exists
*
* @return list of urls for images
* @throws Exception
*/
ArrayList<String> getImages() throws Exception {
if (logger != null) {
logger.log("in getImages");
}
ElementDAO dao = new ElementDAO();
return dao.getAllImage();
}
/**
*
* @param input
* @param output
* @param context
* @throws IOException
*/
@Override
public void handleRequest(InputStream input, OutputStream output, Context context) throws IOException {
logger = context.getLogger();
logger.log("Loading Java Lambda handler to list all cards");
JSONObject headerJson = new JSONObject();
headerJson.put("Content-Type", "application/json"); // not sure if needed anymore?
headerJson.put("Access-Control-Allow-Methods", "GET,POST,DELETE,OPTIONS");
headerJson.put("Access-Control-Allow-Origin", "*");
JSONObject responseJson = new JSONObject();
responseJson.put("headers", headerJson);
ListImageResponse response;
try {
ArrayList<String> list = getImages();
response = new ListImageResponse(list, 200);
} catch (Exception e) {
response = new ListImageResponse(e.getMessage(), 403);
}
// compute proper response
responseJson.put("body", new Gson().toJson(response));
responseJson.put("statusCode", response.statusCode);
logger.log("end result:" + responseJson.toJSONString());
logger.log(responseJson.toJSONString());
OutputStreamWriter writer = new OutputStreamWriter(output, "UTF-8");
writer.write(responseJson.toJSONString());
writer.close();
}
}
|
package com.zen.model.manage.service.impl;
import com.zen.model.manage.bean.Feature;
import com.zen.model.manage.dto.ModelInfoDto;
import com.zen.model.manage.service.ManageService;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.xml.bind.ValidationException;
import java.util.ArrayList;
import java.util.Arrays;
import static org.junit.jupiter.api.Assertions.*;
/**
* @Author: morris
* @Date: 2020/6/12 9:01
* @description
* @reviewer
*/
@RunWith(SpringRunner.class)
@SpringBootTest
class ManageServiceImplTest {
@Autowired
private ManageService manageService;
@Test
void createModel() {
ModelInfoDto modelInfoDto = new ModelInfoDto();
Feature feature = new Feature("gender","int","25");
Feature feature1 = new Feature("gender","int","26");
Feature feature2 = new Feature("region","string","深圳");
ArrayList<Feature> features = new ArrayList<>();
features.add(feature);
features.add(feature1);
features.add(feature2);
modelInfoDto.setHdfsPath("hdfs://master:9000/input/article1234");
modelInfoDto.setModelType("mLeap");
modelInfoDto.setWarmUpFeature(features);
manageService.createModel(modelInfoDto);
}
@Test
void updateModel() throws ValidationException {
ModelInfoDto modelInfoDto = new ModelInfoDto();
Feature feature = new Feature("gender","int","25");
Feature feature1 = new Feature("gender","int","26");
Feature feature2 = new Feature("region","string","深圳");
ArrayList<Feature> features = new ArrayList<>();
features.add(feature);
features.add(feature1);
features.add(feature2);
modelInfoDto.setToken("602874adfe37587c");
modelInfoDto.setHdfsPath("hdfs://master:9000/input/article");
modelInfoDto.setModelType("mLeap");
modelInfoDto.setWarmUpFeature(features);
System.out.println(manageService.updateModel(modelInfoDto));
}
@Test
void offlineModel() {
System.out.printf(manageService.offlineModel("602874adfe37587c"));
}
@Test
void rollbackModel() {
manageService.rollbackModel("602874adfe37587c");
}
@Test
void deleteModel() {
System.out.println(manageService.deleteModel("602874adfe37587c", 2));
}
}
|
package net.sf.ardengine.rpg.multiplayer;
import com.google.gson.JsonObject;
import net.sf.ardengine.rpg.multiplayer.messages.*;
import net.sf.ardengine.rpg.multiplayer.network.INetwork;
/**
* Handles client game logic.
*/
public abstract class AClientCore extends ANetworkCore {
/**How many states is client delayed after server*/
public static final int CLIENT_LAGGED_STATES = 3;
private static final int CLIENT_LAG = 100;
private static final long CURRENT_TIME_INDEFINITE = -1;
private long updateTimeStamp = CURRENT_TIME_INDEFINITE;
private final JsonMessageHandler joinHandler = (JsonMessage message) -> {
handlers.remove(JoinResponseMessage.TYPE);
if(JoinResponseMessage.isOK(message)){
prepareClient();
}else{
throw new RuntimeException(JoinResponseMessage.getReason(message));
}
};
private final JsonMessageHandler joinFinished = (JsonMessage message) -> {
startPlaying();
};
private final JsonMessageHandler deltaStateHandler = (JsonMessage message) -> {
INetworkedNode node = synchronizedNodes.get(message.getTargetNodeID());
if(node != null){
updateStateIfNotLate(node, message);
}
};
private final JsonMessageHandler stateHandler = (JsonMessage message) -> {
INetworkedNode node = reconstructFromState(message.getContent());
if(node!= null && !synchronizedNodes.containsKey(node.getID())){
addNode(node);
}
};
/**
* @param network Responsible for communicating with other clients
*/
protected AClientCore(INetwork network) {
super(network);
handlers.put(DeltaStateMessage.TYPE, deltaStateHandler);
join();
}
private void join(){
network.sendBroadcastMessage(new JoinRequestMessage().toString());
handlers.put(JoinResponseMessage.TYPE, joinHandler);
handlers.put(StateMessage.TYPE, stateHandler);
handlers.put(ClientReadyMessage.TYPE, joinFinished);
}
/**
* Method for client, where he can exchange with server additional info
* before obtaining game data from server.
*
* METHOD HAS TO END WITH:JoinRequestMessage
* network.sendBroadcastMessage(new ClientPreparedMessage().toString());
*/
protected abstract void prepareClient();
/**
* Automatically called when server sends signal,
* that client is synchronized.
*/
protected abstract void startPlaying();
@Override
protected final void updateCoreLogic(long delta, int passedFrames) {
if(updateTimeStamp != CURRENT_TIME_INDEFINITE) updateTimeStamp+= delta;
synchronizedNodes.values().forEach((INetworkedNode iNetworkedNode) -> {
iNetworkedNode.triggerState(actualIndex, actualFrame);
});
updateClientLogic(passedFrames);
}
/**
* Automatically called every game loop,
* method for client related logic
* @param passedFrames frames passed since last update
*/
protected abstract void updateClientLogic(int passedFrames);
private void updateStateIfNotLate(INetworkedNode node, JsonMessage message){
long messageTimestamp = message.getValueAsLong(JsonMessage.TIMESTAMP);
int messageIndex = message.getValueAsInt(DeltaStateMessage.STATE_INDEX);
if(updateTimeStamp == CURRENT_TIME_INDEFINITE){ //initialize timestamp on start
updateTimeStamp = messageTimestamp - CLIENT_LAG;
initIndex(messageIndex);
}
if(serverIndexDifference(messageIndex) > CLIENT_LAGGED_STATES){
updateStateIndex(ANetworkCore.FRAMES_PER_STATE);
}
// If datagram arrived too late, we have to drop it
if(messageTimestamp >= updateTimeStamp){
node.receiveState(message);
}
}
protected int serverIndexDifference(int serverIndex){
if(serverIndex >= actualIndex){
return serverIndex - actualIndex;
}else{
return serverIndex + INetworkedNode.StoredStates.STATES_BUFFER_SIZE - actualIndex;
}
}
private void initIndex(int serverIndex){
actualIndex = serverIndex - 2;
if(actualIndex < 0){
actualIndex = INetworkedNode.StoredStates.STATES_BUFFER_SIZE - serverIndex;
}else if(actualIndex >= INetworkedNode.StoredStates.STATES_BUFFER_SIZE){
while(actualIndex >= INetworkedNode.StoredStates.STATES_BUFFER_SIZE){
actualIndex -= INetworkedNode.StoredStates.STATES_BUFFER_SIZE;
}
}
}
/**
* Called automatically by client when joining game.
* Method for user to create/synchronize nodes and add them to Game.
* @param state Complete state of node returned by INetworkedNode.getJSONState()
* @return reconstructed networked node
*/
protected abstract INetworkedNode reconstructFromState(JsonObject state);
}
|
package com.qgbase.netty;
/**
* @author : Winner
* @name :
* @date : 2019/5/13 0013
* @desc :
*/
public class Constant {
public static final short CMD_HEAD = (short) 29130;
public static final short CHECK_CODE = (short) 26;
public static Integer onOff = 0;
}
|
package domain;
public enum DeveloperType {
LAZY, EXPERIENCED, JUNIOR
}
|
package com.exercises.mmn12;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/**
* @author Ori Ben Nun
*/
class Segment1Test {
@Test
void getPoLeft() {
Segment1 segment1 = new Segment1(new Point(2,4), new Point(6,0));
assertEquals(4,segment1.getPoLeft().getY(), 0.01);
assertEquals(2,segment1.getPoLeft().getX(), 0.01);
}
@Test
void getPoRight() {
Segment1 segment1 = new Segment1(new Point(2,4), new Point(6,0));
Segment1 segment2 = new Segment1(2,4, 6,0);
assertEquals(2, segment2.getPoLeft().getX(), 0.01);
assertEquals(4, segment2.getPoLeft().getY(), 0.01);
assertEquals(6, segment2.getPoRight().getX(), 0.01);
assertEquals(4, segment2.getPoRight().getY(), 0.01);
assertEquals(true, segment1.equals(segment2));
}
@Test
void getLength() {
Segment1 segment1 = new Segment1(new Point(2,4), new Point(6,4));
assertEquals(4,segment1.getLength(), 0.01);
Segment1 segment2 = new Segment1(new Point(2,4), new Point(2,6));
assertEquals(0,segment2.getLength(), 0.01);
}
@Test
void testToString() {
Segment1 segment1 = new Segment1(new Point(3,4), new Point(5,4));
assertEquals("(3.0,4.0)---(5.0,4.0)",segment1.toString());
}
@Test
void testEquals() {
Segment1 segment1 = new Segment1(new Point(3,4), new Point(5,4));
Segment1 segment2 = new Segment1(new Point(3,4), new Point(5,4));
Segment1 segment3 = new Segment1(new Point(3,5), new Point(5,4));
assertEquals(true, segment1.equals(segment2));
assertEquals(false, segment1.equals(segment3));
}
@Test
void isAbove() {
Segment1 segment1 = new Segment1(new Point(5,4), new Point(5,4));
Segment1 segment2 = new Segment1(new Point(5,4), new Point(5,4));
Segment1 segment3 = new Segment1(new Point(3,2), new Point(5,4));
assertEquals(false, segment1.isAbove(segment2));
assertEquals(true, segment1.isAbove(segment3));
}
@Test
void isUnder() {
Segment1 segment1 = new Segment1(new Point(5,4), new Point(5,4));
Segment1 segment2 = new Segment1(new Point(5,4), new Point(5,4));
Segment1 segment3 = new Segment1(new Point(3,2), new Point(5,4));
assertEquals(false, segment1.isUnder(segment2));
assertEquals(false, segment1.isUnder(segment3));
assertEquals(true, segment3.isUnder(segment1));
}
@Test
void isLeft() {
Segment1 segment1 = new Segment1(new Point(6,15), new Point(8,1024));
Segment1 segment2 = new Segment1(new Point(4,15), new Point(6,4));
Segment1 segment3 = new Segment1(new Point(2,108), new Point(4,4));
assertEquals(false, segment1.isLeft(segment2));
assertEquals(false, segment1.isLeft(segment3));
assertEquals(false, segment1.isLeft(segment1));
assertEquals(false, segment2.isLeft(segment3));
assertEquals(false, segment2.isLeft(segment1));
assertEquals(true, segment3.isLeft(segment1));
assertEquals(false, segment3.isLeft(segment3));
}
@Test
void isRight() {
Segment1 segment1 = new Segment1(new Point(6,15), new Point(8,1024));
Segment1 segment2 = new Segment1(new Point(4,15), new Point(6,4));
Segment1 segment3 = new Segment1(new Point(2,108), new Point(4,4));
Segment1 segment4 = new Segment1(segment1);
assertEquals(false, segment1.isRight(segment2));
assertEquals(true, segment1.isRight(segment3));
assertEquals(true, segment4.isRight(segment3));
assertEquals(false, segment4.isRight(segment1));
assertEquals(false, segment1.isRight(segment1));
assertEquals(false, segment2.isRight(segment3));
assertEquals(false, segment2.isRight(segment1));
assertEquals(false, segment3.isRight(segment1));
assertEquals(false, segment3.isRight(segment3));
}
@Test
void moveHorizontal() {
Segment1 segment1 = new Segment1(new Point(6,15), new Point(8,1024));
Segment1 segment2 = new Segment1(new Point(4,15), new Point(6,4));
Segment1 segment3 = new Segment1(new Point(2,108), new Point(4,4));
Segment1 segment4 = new Segment1(segment1);
assertEquals(false, segment1.isRight(segment2));
assertEquals(true, segment1.isRight(segment3));
assertEquals(true, segment4.isRight(segment3));
assertEquals(false, segment4.isRight(segment1));
assertEquals(false, segment1.isRight(segment1));
assertEquals(false, segment2.isRight(segment3));
assertEquals(false, segment2.isRight(segment1));
assertEquals(false, segment3.isRight(segment1));
assertEquals(false, segment3.isRight(segment3));
segment4.moveHorizontal(10);
assertEquals(true, segment4.isRight(segment3));
assertEquals(true, segment4.isRight(segment1));
assertEquals(false, segment4.isRight(segment4));
segment1.moveHorizontal(10);
assertEquals(false, segment4.isRight(segment1));
assertEquals(false, segment4.isLeft(segment1));
segment1.moveHorizontal(-10);
segment4.moveHorizontal(-10);
assertEquals(false, segment4.isRight(segment1));
assertEquals(false, segment4.isRight(segment2));
assertEquals(false, segment4.isLeft(segment1));
Segment1 segment5 = new Segment1(new Point(4,15), new Point(6,4));
Segment1 segment6 = new Segment1(segment5);
segment5.moveHorizontal(-4.5);
assertEquals(true, segment5.equals(segment6));
segment5.moveHorizontal(-3.5);
assertEquals(false, segment5.equals(segment6));
assertEquals(true, segment5.isLeft(segment6));
Segment1 segment7 = new Segment1(new Point(0,0), new Point(0,4));
assertEquals(true, segment5.isRight(segment7));
assertEquals(true, segment7.isLeft(segment5));
}
@Test
void moveVertical() {
Segment1 segment1 = new Segment1(new Point(6,15), new Point(8,1024));
Segment1 segment2 = new Segment1(segment1);
segment1.moveVertical(-100);
segment1.moveHorizontal(-100);
segment2.moveHorizontal(-100);
assertEquals(true, segment1.equals(segment2));
assertEquals(false, segment2.isAbove(segment1));
segment1.moveVertical(-10);
assertEquals(false, segment1.equals(segment2));
assertEquals(true, segment1.isUnder(segment2));
segment2.moveVertical(1500);
segment1.moveVertical(150);
assertEquals(false, segment1.equals(segment2));
assertEquals(false, segment1.isAbove(segment2));
assertEquals(true, segment1.isUnder(segment2));
assertEquals(true, segment2.isAbove(segment1));
}
@Test
void changeSize() {
Segment1 segment1 = new Segment1(new Point(3,10), new Point(6,10));
segment1.changeSize(-2);
assertEquals(1, segment1.getLength(), 0.01);
assertEquals(4, segment1.getPoRight().getX(), 0.01);
segment1.changeSize(-2);
assertEquals(1, segment1.getLength(), 0.01);
assertEquals(4, segment1.getPoRight().getX(), 0.01);
segment1.changeSize(10);
assertEquals(11, segment1.getLength(), 0.01);
assertEquals(14, segment1.getPoRight().getX(), 0.01);
assertEquals(3, segment1.getPoLeft().getX(), 0.01);
segment1.changeSize(-11);
assertEquals(0, segment1.getLength());
assertEquals(3, segment1.getPoRight().getX(), 0.01);
assertEquals(3, segment1.getPoLeft().getX(), 0.01);
segment1.changeSize(-0.1);
assertEquals(0, segment1.getLength());
assertEquals(3, segment1.getPoRight().getX(), 0.01);
assertEquals(3, segment1.getPoLeft().getX(), 0.01);
segment1.changeSize(0.1);
assertEquals(0.1, segment1.getLength(), 0.01);
assertEquals(3.1, segment1.getPoRight().getX(), 0.01);
assertEquals(3, segment1.getPoLeft().getX(), 0.01);
}
@Test
void pointOnSegment() {
Segment1 segment1 = new Segment1(new Point(3,10), new Point(6,10));
Point point1 = new Point(2,7);
assertEquals(false, segment1.pointOnSegment(point1));
point1.move(1,3);
assertEquals(true, segment1.pointOnSegment(point1));
point1.move(2,0);
assertEquals(true, segment1.pointOnSegment(point1));
point1.move(2,0);
assertEquals(false, segment1.pointOnSegment(point1));
point1.move(-1,1);
assertEquals(false, segment1.pointOnSegment(point1));
point1.move(0,-1);
assertEquals(true, segment1.pointOnSegment(point1));
assertEquals(true, segment1.pointOnSegment(segment1.getPoLeft()));
assertEquals(true, segment1.pointOnSegment(segment1.getPoRight()));
segment1.moveVertical(10);
assertEquals(false, segment1.pointOnSegment(point1));
assertEquals(true, segment1.pointOnSegment(segment1.getPoLeft()));
assertEquals(true, segment1.pointOnSegment(segment1.getPoRight()));
}
@Test
void isBigger() {
Segment1 segment1 = new Segment1(new Point(3,10), new Point(6,10));
Segment1 segment2 = new Segment1(new Point(3,10), new Point(6,10));
assertEquals(false, segment1.isBigger(segment1));
assertEquals(false, segment1.isBigger(segment2));
segment2.changeSize(0.5);
assertEquals(true, segment2.isBigger(segment1));
segment1.moveHorizontal(500);
assertEquals(true, segment2.isBigger(segment1));
segment1.changeSize(0.5);
assertEquals(false, segment2.isBigger(segment1));
assertEquals(false, segment1.isBigger(segment2));
segment1.changeSize(0.5);
assertEquals(true, segment1.isBigger(segment2));
}
@Test
void overlap() {
Segment1 segment1 = new Segment1(new Point(3,10), new Point(6,10));
Segment1 segment2 = new Segment1(new Point(3,80), new Point(6,50));
assertEquals(3, segment1.overlap(segment2), 0.01);
assertEquals(3, segment1.overlap(segment1), 0.01);
segment2.moveHorizontal(1);
assertEquals(2, segment1.overlap(segment2), 0.01);
segment2.changeSize(-2);
assertEquals(1, segment1.overlap(segment2), 0.01);
segment1.changeSize(-1);
assertEquals(1, segment1.overlap(segment2), 0.01);
segment1.changeSize(-1);
assertEquals(0, segment1.overlap(segment2), 0.01);
Segment1 segment3 = new Segment1(segment1);
segment3.moveVertical(1024);
assertEquals(segment1.getLength(), segment1.overlap(segment3), 0.01);
segment3.changeSize(-1);
assertEquals(segment1.getLength() -1, segment1.overlap(segment3), 0.01);
segment3.moveHorizontal(1);
assertEquals(segment1.getLength() -1, segment1.overlap(segment3), 0.01);
Segment1 segment4 = new Segment1(new Point(3,4), new Point(5,4));
Segment1 segment5 = new Segment1(new Point(0,2), new Point(2,4));
Segment1 segment6 = new Segment1(new Point(1,1), new Point(4,1));
Segment1 segment7 = new Segment1(new Point(1,10), new Point(4,10));
assertEquals(1, segment6.overlap(segment4), 0.01);
assertEquals(1, segment6.overlap(segment5), 0.01);
assertEquals(segment7.getLength(), segment7.overlap(segment6), 0.01);
segment7.changeSize(10);
assertEquals(segment6.getLength(), segment7.overlap(segment6), 0.01);
segment7.moveHorizontal(100);
assertEquals(0, segment7.overlap(segment6), 0.01);
}
@Test
void trapezePerimeter() {
Segment1 segment1 = new Segment1(new Point(1,1), new Point(4,1));
Segment1 segment2 = new Segment1(new Point(1,2), new Point(4,2));
assertEquals(3 + 3 + 1 + 1, segment1.trapezePerimeter(segment2));
segment2.moveVertical(10);
assertEquals(3 + 3 + 1 + 1 + 20, segment1.trapezePerimeter(segment2), 0.01);
segment1.changeSize(2);
assertEquals(3 + 3 + 1 + 1 + 20 + 2, segment1.trapezePerimeter(segment2), .5);
segment1.changeSize(2);
assertEquals(3 + 3 + 1 + 1 + 20 + 2 + 2, segment1.trapezePerimeter(segment2), 1);
segment1.moveHorizontal(1);
assertEquals(3 + 3 + 1 + 1 + 20 + 2 + 2 + 1, segment1.trapezePerimeter(segment2), .5);
segment2.moveVertical(100);
assertEquals(3 + 3 + 1 + 1 + 20 + 2 + 2 + 1 + 200, segment1.trapezePerimeter(segment2), 1);
}
@Test
void arielTest(){
ArielSeg1Tester.main();
}
@Test
void teachersTester() {
System.out.println("============ Testing class Segment1 =============");
Segment1 s11 = new Segment1(1.0 , 2.0, 3.0, 4.0);
Segment1 s12 = new Segment1(1.0 , 2.0, 3.0, 4.0);
if (!s11.equals(s12))
System.out.println("Check your equals method in class Segment1");
Point p3 = new Point(5.0, 6.0);
Point p4 = new Point(7.0, 8.0);
Segment1 s13 = new Segment1(p3, p4);
Segment1 s14 = new Segment1(s12);
Point p5 = s11.getPoLeft();
p5 = s11.getPoRight();
double d1 = s11.getLength();
if (s11.toString().indexOf('@') != -1)
System.out.println("Check your toString method in class Segment1");
boolean b1 = s11.isAbove(s12);
b1 = s11.isUnder(s12);
b1 = s11.isLeft(s12);
b1 = s11.isRight(s12);
s11.moveHorizontal(1.0);
s11.moveVertical(1.0);
s11.changeSize(1.0);
b1 = s11.pointOnSegment(p3);
b1 = s11.isBigger(s12);
d1 = s11.overlap(s12);
d1 = s11.trapezePerimeter(s12);
System.out.println("============ Testing class Segment1 Done =============");
}
}
|
import com.thinking.machines.loyalty.dao.*;
import com.thinking.machines.loyalty.interfaces.*;
class GetCityByNameTestCase
{
public static void main(String data[])
{
try
{
CityDAOInterface cityDAOInterface=new CityDAO();
CityInterface cityInterface=cityDAOInterface.getByName(data[0]);
System.out.println(cityInterface.getCode());
System.out.println(cityInterface.getName());
System.out.println(cityInterface.getState());
System.out.println(cityInterface.getCountry());
}
catch(Exception e)
{
System.out.println(e);
}
}
}
|
package com.paleimitations.schoolsofmagic.common.data.books;
import com.mojang.blaze3d.systems.RenderSystem;
import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.client.renderer.IRenderTypeBuffer;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
public class BookElement {
public int page, subpage;
public float x, y;
public BookElement(float x, float y, int page, int subpage) {
this.page = page;
this.subpage = subpage;
this.x = x;
this.y = y;
}
@OnlyIn(Dist.CLIENT)
public boolean shouldDraw(float mouseX, float mouseY, int x, int y, boolean isGUI, int subpage, int page) {
return subpage == this.subpage && page == this.page;
}
@OnlyIn(Dist.CLIENT)
public void drawElement(float mouseX, float mouseY, int x, int y, float zLevel, boolean isGUI, int subpage, int page) {
}
@OnlyIn(Dist.CLIENT)
public void drawElement(float mouseX, float mouseY, int x, int y, float zLevel, boolean isGUI, int subpage, int page, IRenderTypeBuffer buffer) {
this.drawElement(mouseX, mouseY, x, y, zLevel, isGUI, subpage, page);
}
@OnlyIn(Dist.CLIENT)
public void drawTexturedModalRect(int x, int y, int textureX, int textureY, int width, int height, float zLevel) {
Tessellator tessellator = Tessellator.getInstance();
BufferBuilder bufferbuilder = tessellator.getBuilder();
bufferbuilder.begin(7, DefaultVertexFormats.POSITION_TEX);
bufferbuilder.vertex(x + 0, y + height, zLevel).uv((float)(textureX + 0) * 0.00390625F, (float)(textureY + height) * 0.00390625F).endVertex();
bufferbuilder.vertex(x + width, y + height, zLevel).uv((float)(textureX + width) * 0.00390625F, (float)(textureY + height) * 0.00390625F).endVertex();
bufferbuilder.vertex(x + width, y + 0, zLevel).uv((float)(textureX + width) * 0.00390625F, (float)(textureY + 0) * 0.00390625F).endVertex();
bufferbuilder.vertex(x + 0, y + 0, zLevel).uv((float)(textureX + 0) * 0.00390625F, (float)(textureY + 0) * 0.00390625F).endVertex();
tessellator.end();
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.udea.session;
import com.udea.Carro;
import com.udea.Cliente;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
/**
*
* @author Santiago
*/
@Stateless
public class ClienteFacade extends AbstractFacade<Cliente> implements ClienteFacadeLocal {
@PersistenceContext(unitName = "com.udea_Laboratorio2-ejb_ejb_1.0-SNAPSHOTPU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public ClienteFacade() {
super(Cliente.class);
}
@Override
public Cliente getClienteById(int idCliente) {
Query q = em.createNamedQuery("Cliente.findByCedula");
return (Cliente) q.getSingleResult();
}
@Override
public void registrar(final int cedula, String password, String nombre, String ciudad, String telefono, String email) {
Cliente c = new Cliente();
c.setCedula(cedula);
c.setPassword(password);
c.setNombre(nombre);
c.setCiudad(ciudad);
c.setTelefono(telefono);
c.setEmail(email);
em.persist(c);
}
@Override
public boolean checkLogin(int cedula, String password) {
Query q =em.createQuery("select a from Cliente a"
+ " where a.cedula=:cedula and a.password=:password");
q.setParameter("cedula", cedula);
q.setParameter("password", password);
return q.getResultList().size()>0;
}
@Override
public List<Cliente> getCliente() {
Query q = em.createNamedQuery("Cliente.findAll");
return q.getResultList();
}
@Override
public List<Cliente> getClientes() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
|
package ec.app.fixedpoint;
import ec.util.*;
import ec.*;
import ec.gp.*;
import xfp.trees.*;
public class ExprData extends GPData {
public CExpr x; // return value
// copy content to other AffineData
public void copyTo(final GPData gpd) {
((ExprData) gpd).x = x;
}
}
|
package com.rolandopalermo.facturacion.ec.common.util;
import java.util.HashMap;
public class Constantes {
/**
* Utility classes should not have a public constructor.
*/
private Constantes() {
}
public static final String API_DOC_ANEXO_1 = "Ver ficha técnica - Anexo 1";
@SuppressWarnings("serial")
public static final HashMap<String, String> FORMAS_PAGO_MAP = new HashMap<String, String>() {
{
put("01", "SIN UTILIZACION DEL SISTEMA FINANCIERO");
put("15", "COMPENSACIÓN DE DEUDAS");
put("16", "TARJETA DE DÉBITO");
put("17", "DINERO ELECTRÓNICO");
put("18", "TARJETA PREPAGO");
put("19", "TARJETA DE CRÉDITO");
put("20", "OTROS CON UTILIZACION DEL SISTEMA FINANCIERO");
put("21", "ENDOSO DE TÍTULOS");
}
};
}
|
package com.puti.pachong.service.wenda.impl;
import com.puti.pachong.entity.http.HttpRequest;
import com.puti.pachong.http.HttpRestRequest;
import com.puti.pachong.service.wenda.IAutoWendaService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.net.URLEncoder;
import java.util.Date;
@Service
public class ZhihuService implements IAutoWendaService {
private String urlTemp = "https://www.zhihu.com/api/v4/search_v3?t=general&q=%s&correction=1&offset=0&limit=20&lc_idx=0&show_all_topics=0";
@Autowired
private HttpRestRequest restRequest;
@Override
@SneakyThrows
public String answer(String question) {
HttpRequest httpRequest = HttpRequest.defaultGetRequest(String.format(urlTemp, question));
httpRequest.getHeaders().put("referer", "https://www.zhihu.com/search?type=content&q=" + URLEncoder.encode(question, "utf-8"));
httpRequest.getHeaders().put("cookie", "_xsrf=cI9eZEtE5NPwXNz3A5XVxFIY36x7halv; _zap=69563ced-3661-4a7c-ba3a-13fba0632161; d_c0=\"AIDVfzOAJRGPTvHJ5vQFoh1blPCmnYr5sI0=|1587354411\"; Hm_lvt_98beee57fd2ef70ccdd5ca52b9740c49=1587353214,1587353220,1587353279,1587354412; _ga=GA1.2.1311183132.1587354412; _gid=GA1.2.1382588795.1587354412; capsion_ticket=\"2|1:0|10:1587364010|14:capsion_ticket|44:ODJjMTZjNTY2MmVlNDdlZDg1MzM1ZjEwMmFkZWIwN2I=|4195dc89e78601ab1296ef5371544834e3deb1e5c94fc3f3c82c8064c2016bc5\"; z_c0=\"2|1:0|10:1587364042|4:z_c0|92:Mi4xZXFZaURRQUFBQUFBZ05WX000QWxFU1lBQUFCZ0FsVk55bzZLWHdCY3NSa2xjSF9nMEF0QkZWMW5xekduRTdrTThR|cc1f8b948e4fd6b929fb95c7aee8d25566c579808fb2dc5567839af2bc63fd90\"; unlock_ticket=\"AABpKRl3gQ4mAAAAYAJVTdJHnV4HWa3Ov0Y4RWX1UkTlxA1oeXrzCg==\"; Hm_lpvt_98beee57fd2ef70ccdd5ca52b9740c49=1587365138; KLBRSID=b33d76655747159914ef8c32323d16fd|" + (new Date().getTime()) + "|1587363957");
String response = restRequest.request(httpRequest);
return response;
}
}
|
package BlockchainUtil;
import proto.BlockchainService;
import java.util.*;
public class Block {
private BlockMeta metaData;
List<BlockchainService.Transaction> transactionList = new ArrayList<BlockchainService.Transaction>();
List<BlockchainService.Balance> balanceList = new ArrayList<BlockchainService.Balance>();
public List<BlockchainService.Transaction> getTransactionList() {
return this.transactionList;
}
public int getCreatedBy() {
return this.metaData.getCreatedBy();
}
public int getId() {
return this.metaData.getId();
}
public void setList(List<BlockchainService.Transaction> list) {
this.transactionList = list;
}
public String toString(){
StringBuilder blockString = new StringBuilder(String.format("Block: %d - CreateBy: %d ", this.getId(), this.getCreatedBy()));
for (BlockchainService.Transaction t: this.transactionList){
blockString.append(String.format("[%d->%d: %s], ", t.getSourceClient(), t.getDestClient(), t.getAmount()));
}
return blockString.toString();
}
public Block(Block b) {
this.metaData = new BlockMeta(b.getId(), b.getCreatedBy());
this.transactionList = new ArrayList<>(b.getTransactionList());
}
public Block(BlockchainService.Block blockMsg) {
this.metaData = new BlockMeta(blockMsg.getId(), blockMsg.getCreatedBy());
this.transactionList = new ArrayList<>(blockMsg.getTransactionsList());
}
public Block(List<BlockchainService.Transaction> transactionList, int createdBy) {
this.metaData = new BlockMeta(createdBy);
this.transactionList = new ArrayList<>(transactionList);
}
}
|
package GUIModule;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
public class ActionResultsReport implements ActionListener {
public ArrayList<ArrayList<String>> previousResult;
public JTable table;
public ActionResultsReport(JTable table, ArrayList<ArrayList<String>> previousResult) {
this.previousResult = previousResult;
this.table = table;
}
public void actionPerformed(ActionEvent e) {
int [] indexes;
indexes = table.getSelectedRows();
if (indexes.length==0){
// TODO: Сделать вывод сообщения с подсказкой в диалоговом окне
return;
}
if(indexes[0]>=previousResult.size()){
return;
}
new ResultsWindow(previousResult.get(indexes[0]));
}
}
|
package pro.javatar.security.acl;
import org.springframework.security.acls.domain.BasePermission;
import org.springframework.security.acls.domain.GrantedAuthoritySid;
import org.springframework.security.acls.domain.PrincipalSid;
import org.springframework.security.acls.model.Permission;
import org.springframework.security.acls.model.Sid;
import java.io.Serializable;
public interface AclManager {
/**
* Add a permission for the given object
*
* @param clazz Domain class
* @param identifier Id from the given domain
* @param sid Security Identifier, could be a {@link PrincipalSid} or a {@link GrantedAuthoritySid}
* @param permission The permission based on {@link BasePermission}
*/
<T> void addPermission(Class<T> clazz, Serializable identifier, Sid sid, Permission permission);
/**
* Grant a permission for the given object
*
* @param clazz Domain class
* @param identifier Id from the given domain
* @param sid Security Identifier, could be a {@link PrincipalSid} or a {@link GrantedAuthoritySid}
* @param permission The permission based on {@link BasePermission}
*/
<T> void grantPermission(Class<T> clazz, Serializable identifier, Sid sid, Permission permission);
/**
* Remove a permission from the given object
*
* @param clazz Domain class
* @param identifier Id from the given domain
* @param sid Security Identifier, could be a {@link PrincipalSid} or a {@link GrantedAuthoritySid}
* @param permission The permission based on {@link BasePermission}
*/
<T> void removePermission(Class<T> clazz, Serializable identifier, Sid sid, Permission permission);
/**
* Check whether the given object has permission
*
* @param clazz Domain class
* @param identifier Id from the given domain
* @param sid Security Identifier, could be a {@link PrincipalSid} or a {@link GrantedAuthoritySid}
* @param permission The permission based on {@link BasePermission}
* @return true or false
*/
<T> boolean isPermissionGranted(Class<T> clazz, Serializable identifier, Sid sid, Permission permission);
}
|
package com.goldgov.dygl.module.portal.webservice.examrecord.web;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.goldgov.dygl.ShConstant;
import com.goldgov.dygl.cache.SpyMemcachedImpl;
import com.goldgov.dygl.module.partyMemberDuty.duty.service.IDutyService;
import com.goldgov.dygl.module.partyMemberInfo.service.IPartyMemberService_AJ;
import com.goldgov.dygl.module.partymember.service.IPartyMemberService_AA;
import com.goldgov.dygl.module.partymemberrated.exam.domain.Exam;
import com.goldgov.dygl.module.partymemberrated.exam.service.IExamService;
import com.goldgov.dygl.module.partymemberrated.rated.services.IPartyMemberRatedService;
import com.goldgov.dygl.module.partyorganization.service.PartyOrgMemberCountBean;
import com.goldgov.dygl.module.partyorganization.service.PartyOrganization;
import com.goldgov.dygl.module.portal.webservice.examrecord.domain.ExamPercentageBean;
import com.goldgov.dygl.module.portal.webservice.examrecord.service.ExamrecordQuery;
import com.goldgov.dygl.module.portal.webservice.examrecord.service.IExamrecordService;
import com.goldgov.gtiles.core.security.AuthorizedDetails;
import com.goldgov.gtiles.core.web.GoTo;
import com.goldgov.gtiles.core.web.OperatingType;
import com.goldgov.gtiles.core.web.UserHolder;
import com.goldgov.gtiles.core.web.annotation.ModelQuery;
import com.goldgov.gtiles.core.web.annotation.ModuleOperating;
import com.goldgov.gtiles.core.web.annotation.ModuleResource;
import com.goldgov.gtiles.module.user.service.User;
@RequestMapping("/module/exam/examrecord")
@Controller("examrecordController")
@ModuleResource(name="同步考试系统数据表")
public class ExamrecordController {
public static final String PAGE_BASE_PATH = "portal/webservice/examrecord/web/pages/";
@Autowired
@Qualifier("examrecordServiceImpl")
private IExamrecordService examrecordService;
@Autowired
@Qualifier("partyMemberRatedService")
private IPartyMemberRatedService partyMemberRatedService;
@Autowired
@Qualifier("dutyServiceImpl")
private IDutyService dutyService;
@Autowired
@Qualifier("examServiceImpl")
private IExamService examService;
@Autowired
@Qualifier("propertiesReader")
private Properties prop;
@Autowired
@Qualifier("PartyMemberServiceImpl_AJ")
private IPartyMemberService_AJ partyMemberServiceImpl_AJ;
@Autowired
@Qualifier("partyMemberService_AA")
private IPartyMemberService_AA partyMemberService_AA;
/**
* 集团总部和子分公司考试排行榜
* @param query
* @param request
* @param model
* @return
* @throws Exception
*/
@SuppressWarnings("unchecked")
@RequestMapping("/findInfoList")
@ModuleOperating(name="信息查询",type=OperatingType.FindList)
public String findList(@ModelQuery("query") ExamrecordQuery query,HttpServletRequest request,Model model) throws Exception{
AuthorizedDetails details = (AuthorizedDetails)UserHolder.getUserDetails();
User user = (User) details.getCustomDetails(ShConstant.USER_INFO);
// PartyMemberInfoDuty memberInfo = dutyService.findInfoMemberInfo(user.getEntityID()); //个人信息
// PartyMemberRated rated = partyMemberRatedService.getTheLatestPublishedRatedId();//评价Id 查询
PartyOrganization currentOrganzation = (PartyOrganization) details.getCustomDetails(ShConstant.CURRENT_PARTY_ORGANZATION);
// //查询党员的pm_aa_id
// List<Map<String, Object>> pmList = partyMemberService_AA.findInfoByUserId(user.getEntityID());
// Map<String, Object> map = pmList.get(0);
// String aaid = map.get("AA_ID").toString();
//
// //根据党员的pm_aa_id查询照片ID
// String photoID = null;
// Map<String,Object> mapph=partyMemberServiceImpl_AJ.findInfoByAAID(aaid);
// if(mapph!=null&&mapph.get("AJ1")!=null){
// photoID=mapph.get("AJ1").toString();
// }
Exam exam = examService.findExamInfo();
query.setLoginId(user.getEntityID());
if(exam!=null){
query.setExamId(exam.getExamPaperId());
query.setSearchPaperid(exam.getExamPaperId());
}
ExamPercentageBean findexamInfo = examrecordService.findexamInfo(query);
// query.setSearchRatedId(rated.getRatedId());
//子分公司
if(query.getSearchOrgId()==null){
query.setSearchOrgId("-1");
}
query.setSearchNoOrgId("8a00122b4941a4bf01496f804b544a52");
String key = "examPaihangbang"+query.getSearchOrgId()+query.getSearchNoOrgId()+query.getExamId();
List<ExamPercentageBean> resultList= SpyMemcachedImpl.get(key);
if(resultList==null){
resultList = examrecordService.findPercentageList(query);
SpyMemcachedImpl.put(key,resultList, 3600*12);
}
query.setResultList(resultList);
//集团总部
query.setSearchOrgId("8a00122b4941a4bf01496f804b544a52");
query.setSearchNoOrgId(null);
key = "examPaihangbang2"+query.getSearchOrgId()+query.getExamId();
List<ExamPercentageBean> resultListjitun= SpyMemcachedImpl.get(key);
if(resultListjitun==null){
resultListjitun = examrecordService.findPercentageList(query);
SpyMemcachedImpl.put(key,resultListjitun, 3600*12);
}
String el = prop.getProperty("el.domain");
model.addAttribute("el", el);
model.addAttribute("findexamInfo", findexamInfo);
model.addAttribute("exam", exam);
model.addAttribute("user", user);
// model.addAttribute("photoID", photoID);
model.addAttribute("currentOrganzation", currentOrganzation);
model.addAttribute("resultListjitun", resultListjitun);
return new GoTo(this).sendPage("examindex.ftl");
}
@RequestMapping("/findBinList")
public String findPieList(Model model,HttpServletRequest request) throws Exception{
String pieType = request.getParameter("pieType");
List<PartyOrgMemberCountBean> list = new ArrayList<PartyOrgMemberCountBean>();
ExamrecordQuery query=new ExamrecordQuery();
Exam exam = examService.findExamInfo();
query.setExamId(exam.getExamPaperId());
if(pieType.equals("qjt")){
query.setSearchOrgId("-1");
}else if(pieType.equals("jt")){
query.setSearchOrgId("8a00122b4941a4bf01496f804b544a52");
query.setSearchNoOrgId(null);
}else if(pieType.equals("zfg")){
query.setSearchOrgId("-1");
query.setSearchNoOrgId("8a00122b4941a4bf01496f804b544a52");
}
Integer pmcount = 0;
Integer examcount = 0;
String key="findBinList_"+query.getExamId()+query.getSearchOrgId()+query.getSearchNoOrgId();
list=SpyMemcachedImpl.get(key);
if(list==null){
list=new ArrayList<PartyOrgMemberCountBean>();
List<ExamPercentageBean> resultListjitun = examrecordService.findPercentageList(query);
if(resultListjitun!=null&&resultListjitun.size()>0){
for (ExamPercentageBean examPercentageBean : resultListjitun) {
pmcount += examPercentageBean.getPmcount();
examcount += examPercentageBean.getExamcount();
}
}
Double pcount = (Double.valueOf(examcount)/Double.valueOf(pmcount)*100);
PartyOrgMemberCountBean bean = new PartyOrgMemberCountBean();
bean.setY(pcount);
bean.setCount(examcount);
bean.setName("已参与");
list.add(bean);
PartyOrgMemberCountBean bean1 = new PartyOrgMemberCountBean();
bean1.setY(100-pcount);
bean1.setName("未参与");
bean1.setCount(pmcount-examcount);
list.add(bean1);
SpyMemcachedImpl.put(key,list,3600*12);
}
model.addAttribute("dataList", list);
return "";
}
public static void main(String[] args) {
System.out.println(4/20*100);
}
}
|
public class Rational {
//instance variables
private int numerator;
private int denominator;
// constructors
public Rational(int numerator) {
this(numerator, 1);
}
public Rational(int numerator, int denominator) {
if(denominator < 0){
denominator = -1*denominator;
numerator = -1*numerator;
}
this.numerator = numerator;
this.denominator = denominator;
reduce();
}
//returns the numerator
public int getNumerator() {
return numerator;
}
//returns the denominator
public int getDenominator() {
return denominator;
}
//adds this Rational and other
public Rational plus(Rational other) {
//returns this Rational plus the other Rational
int newDenominator = denominator * other.denominator;
int newNumerator = numerator * other.denominator;
int newOtherNumerator = other.numerator * denominator;
int sum = newNumerator + newOtherNumerator;
return new Rational(sum, newDenominator);
}
//adds Rational a and Rational b
public static Rational plus(Rational a, Rational b) {
return a.plus(b); //cals the plus method to add Rational a with Rational b
}
// Transforms this number into its reduced form
private void reduce() {
if(numerator ==0){
denominator =1;
}
else{
int reduced = gcd(Math.abs(numerator), denominator); //find the greatest commom divisor of the numerator and denominator
numerator = numerator/reduced; //divide the numerator by this gcd
denominator = denominator/reduced; //divide the denminator by this gcd
}
}
// Euclid's algorithm for calculating the greatest common divisor
private int gcd(int a, int b) {
while (a != b)
if (a > b)
a = a - b;
else
b = b - a;
return a;
}
//compares other to this Rational
public int compareTo(Rational other) {
int thisNewNum = other.denominator * numerator;
int otherNewNum = other.numerator * denominator;
return thisNewNum - otherNewNum;
}
//checks if this Rational equals other
public boolean equals(Rational other) {
if(numerator == other.numerator && denominator == other.denominator){
return true;
}
return false;
}
//returns a string representation of the fraction (ex. 1/2)
public String toString() {
return numerator + "/" + denominator; //returns the fraction in string form
}
}
|
package com.meti.asset;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class DefaultBuilder implements AssetBuilder {
@Override
public Asset build(File file) throws IOException {
FileReader reader = new FileReader(file);
//might be a bit memory intensive
ArrayList<Integer> integerList = new ArrayList<>();
int b;
while ((b = reader.read()) != -1) {
integerList.add(b);
}
int[] array = new int[integerList.size()];
for (int i = 0; i < array.length; i++) {
array[i] = integerList.get(i);
}
return new ByteAsset(array);
}
}
|
package com.vinmein.foodiehuts.login.di;
import com.vinmein.foodiehuts.components.ResourceProvider;
import com.vinmein.foodiehuts.components.data.Prefs;
import com.vinmein.foodiehuts.components.Navigator;
import com.vinmein.foodiehuts.di.PerActivity;
import com.vinmein.foodiehuts.login.LoginActivity;
import com.vinmein.foodiehuts.login.presenters.LoginPresenter;
import dagger.Module;
import dagger.Provides;
@Module
public class LoginActivityModule {
private LoginActivity activity;
public LoginActivityModule(LoginActivity activity) {
this.activity = activity;
}
@Provides
@PerActivity
public LoginPresenter loginPresenter(Navigator navigator,
ResourceProvider provider, Prefs prefs) {
return new LoginPresenter(navigator, provider, prefs);
}
@Provides
@PerActivity
public Navigator navigator() {
return new Navigator(activity);
}
}
|
package com.xm.user.domain;
import java.util.Date;
/**
* Created by xm on 2017/2/21.
*/
public class Blog {
private int id;
private String title;
private String author;
private String content;
private Date updateTime;
private String blogCatalog;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getBlogCatalog() {
return blogCatalog;
}
public void setBlogCatalog(String blogCatalog) {
this.blogCatalog = blogCatalog;
}
}
|
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Login extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String un=request.getParameter("username");
try{
System.out.println("1");
Class.forName("com.mysql.jdbc.Driver");
System.out.println("2");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","");
//PreparedStatement ps=con.prepareStatement("select f_name from user_info where username = '"+un+"'");
//ps.setString(1,n);
System.out.println(un);
//int i=ps.executeUpdate();
//if(i>0)
request.setAttribute("username", un);
System.out.print("successfully img retrieved...");
request.getRequestDispatcher("Login_Pass.jsp").forward(request,response);
}catch (Exception e2) {System.out.println(e2);}
out.close();
}
}
|
package com.liu.Class;
import java.io.Serializable;
public class leave implements Serializable{
private String leaveId;
private int leaveVin;
private int position;
public String getLeaveId() {
return leaveId;
}
public void setLeaveId(String leaveId) {
this.leaveId = leaveId;
}
public int getPosition() {
return position;
}
public void setPosition(int position) {
this.position = position;
}
public int getLeaveVin() {
return leaveVin;
}
public void setLeaveVin(int leaveVin) {
this.leaveVin = leaveVin;
}
}
|
package testSel.testSelVal;
import java.util.ArrayList;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class genericMethod {
WebDriver driver;
public genericMethod(WebDriver driver) {
this.driver=driver;
}
public WebElement getElement(String locator,String type) {
type=type.toLowerCase();
if (type.equals("id")) {
return this.driver.findElement(By.id(locator));
}else {
System.out.println("Invalid locator type");
return null;
}
}
public List<WebElement> getElementList(String locator,String type) {
type=type.toLowerCase();
List<WebElement> ElementList=new ArrayList<WebElement>();
if (type.equals("xpath")) {
ElementList= this.driver.findElements(By.xpath(locator));
}else {
System.out.println("Invalid locator type");
}
if (ElementList.isEmpty()) {
System.out.println("Element not found");
}else {
System.out.println("Element found");
}
return ElementList;
}
}
|
/*
* Copyright (C) 2019-2023 Hedera Hashgraph, LLC
*
* 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.hedera.mirror.test.e2e.acceptance.props;
import java.util.ArrayList;
import java.util.List;
import lombok.Data;
@Data
public class MirrorNetworkNode {
private String description;
private String fileId;
private String memo;
private String nodeAccountId;
private long nodeId;
private String nodeCertHash;
private String publicKey;
private List<MirrorServiceEndpoint> serviceEndpoints = new ArrayList<>();
private TimestampRange timestamp;
@Data
public static class MirrorServiceEndpoint {
private String ipAddressV4;
private int port;
}
}
|
package syncAlgorithm;
import java.util.Hashtable;
public class TreeAndPathEntryTable {
private FileTree tree;
private Hashtable<String, FileEntry> pathEntryTable;
public FileTree getTree() {
return tree;
}
public Hashtable<String, FileEntry> getPathEntryTable() {
return pathEntryTable;
}
public TreeAndPathEntryTable(FileTree tree,
Hashtable<String, FileEntry> pathEntryTable) {
this.tree = tree;
this.pathEntryTable = pathEntryTable;
}
}
|
package database;
import agenda.DB_AgendaManagement;
import document.DB_DocumentManagement;
import org.junit.After;
import org.junit.Before;
import request.DB_RequestManagement;
import user.DB_UserManagement;
import voting.DB_VotingManagement;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Paths;
public abstract class DatabaseTests {
private URI path;
private DB_UserManagement generalUserDB;
private DB_AgendaManagement agendaDB;
private DB_DocumentManagement documentDB;
private DB_RequestManagement requestDB;
private DB_VotingManagement votingDB;
@Before
public void init() throws IOException {
String path = "testdb/database.db";
this.generalUserDB = new DB_UserManager(path);
this.agendaDB = new DB_AgendaManager(path);
this.documentDB = new DB_DocumentManager(path);
this.requestDB = new DB_RequestManager(path);
this.votingDB = new DB_VotingManager(path);
}
@After
public void cleanup() {
path = Paths.get("testdb/database.db").toUri();
new File(path).delete();
}
protected DB_UserManagement getGeneralUserDB() {
return this.generalUserDB;
}
protected DB_AgendaManagement getAgendaDB() {
return this.agendaDB;
}
protected DB_DocumentManagement getDocumentDB() {
return this.documentDB;
}
protected DB_RequestManagement getRequestDB() {
return this.requestDB;
}
protected DB_VotingManagement getVotingDB() {
return this.votingDB;
}
}
|
package com.ssm.wechatpro.controller;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ssm.wechatpro.object.InputObject;
import com.ssm.wechatpro.object.OutputObject;
import com.ssm.wechatpro.service.WechatAdminRoleMenuService;
@Controller
public class WechatAdminRoleMenuController {
@Resource
private WechatAdminRoleMenuService wechatAdminRoleMenuService;
@RequestMapping("post/WechatAdminRoleMenuController/selectRoleByMenuId")
@ResponseBody
public void selectRoleByMenuId(InputObject inputObject,OutputObject outputObject) throws Exception{
wechatAdminRoleMenuService.selectRoleByMenuId(inputObject, outputObject);
}
}
|
package Question4;
public class main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
StackArray<Integer> stack = new StackArray<Integer>();
boolean expansionRule = false;
for(int i = 0; i< 30000; i++)
{
if(expansionRule)
stack.setExpansionRule('c');
else
stack.setExpansionRule('d');
long startTime = System.currentTimeMillis();
stack.push(i);
long finishTime = System.currentTimeMillis();
//stack.truncate();
if(i%100 == 0)
{
if(finishTime - startTime > 0)
System.out.println(finishTime-startTime + " " + i + " " + expansionRule);
expansionRule = !expansionRule;
}
}
/*System.out.println(stack.isEmpty());
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
stack.push(6);
stack.push(7);
stack.push(8);
stack.push(9);
stack.push(10);
stack.truncate();
stack.push(11);
stack.push(12);
stack.truncate();
/*System.out.println(stack.size());
System.out.println(stack.peek());
System.out.println(stack.pop());
System.out.println(stack.isEmpty());
System.out.println(stack.pop());
/*System.out.println(stack.isEmpty());
stack.truncate();/*
/*System.out.println(stack.pop());
System.out.println(stack.isEmpty());
System.out.println(stack.pop());
System.out.println(stack.isEmpty());
//System.out.println(stack.pop());
System.out.println(stack.isEmpty());
System.out.println(stack.size());*/
}
}
|
import java.time.LocalDate;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// put your code here
Scanner scanner = new Scanner(System.in);
int year = scanner.nextInt();
int month = scanner.nextInt();
int minus = scanner.nextInt();
System.out.println(LocalDate.of(year, month + 1, 1).
minusDays(minus));
}
}
|
package nb.queryDomain;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
public class CreditAccPriceHistory implements Serializable {
private Date date;
private BigDecimal acceptedPrice;
public CreditAccPriceHistory() {
}
public CreditAccPriceHistory(Date date, BigDecimal acceptedPrice) {
this.date = date;
this.acceptedPrice = acceptedPrice;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public BigDecimal getAcceptedPrice() {
return acceptedPrice;
}
public void setAcceptedPrice(BigDecimal acceptedPrice) {
this.acceptedPrice = acceptedPrice;
}
}
|
package zuoshen.array;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class 子数组中0和1个数相等的最长子数组长度 {
public static int sub_sum0(int[]arr){
if(arr==null||arr.length==0){
return 0;
}
for (int i = 0; i <arr.length ; i++) {
arr[i]=arr[i]==0?-1:arr[i];
}
Map<Integer,Integer> map=new HashMap<>();
int sum=0;
int max=0;
map.put(0,-1);
for (int i = 0; i <arr.length ; i++) {
sum+=arr[i];
if(map.containsKey(sum)){
max=Math.max(i-map.get(sum),max);
}
if(!map.containsKey(sum)){
map.put(sum,i);
}
}
return max;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
while (sc.hasNext()){
int n=sc.nextInt();
int[]arr=new int[n];
for (int i = 0; i <n ; i++) {
arr[i]=sc.nextInt();
}
System.out.println(sub_sum0(arr));
}
}
}
|
package mashup.spring.elegant.search.application;
|
package org.dempsay.demo.freemaker.api;
/**
* A Sample immutable
*
* @author shawn
*
*/
public class Sample {
public final String data;
protected Sample(final SampleBuilder builder) {
this.data = builder.data;
}
public static String data(final Sample sample) {
return sample.data;
}
}
|
package Estruturas;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
/**
* Estrutura que representa uma palavra e suas ocorrências em vários documentos.
* Possui um String texto que representa a palavra em sí e um HashMap onde a
* chave é o id do documento e o valor um contador de ocorrências da palavra em
* um documento.
*
* @author Lucas
*/
public class PalavraMap implements InterfacePalavra {
private String texto;
private final HashMap<Integer, Integer> documentos;
/**
* Construtor: cria um novo HashMap insere uma nova key.
*/
public PalavraMap(String texto, int id_documento) {
this.texto = texto;
this.documentos = new HashMap<>();
this.documentos.put(id_documento, 1);
}
/**
* Caso a lista de pares já contenha aquele documento, incrementa o
* contador. Caso contrário insere um novo nó.
*/
public void insere(int id_documento) {
Integer v = this.documentos.get(id_documento);
if (v == null) {
this.documentos.put(id_documento, 1);
} else {
this.documentos.put(id_documento, v + 1);
}
// if (this.documentos.containsKey(id_documento)) {
// this.documentos.put(id_documento, documentos.get(id_documento) + 1);
// } else {
// this.documentos.put(id_documento, 1);
// }
}
/*
* Retorna a palavra em sí;
*/
public String getTexto() {
return texto;
}
public HashMap<Integer, Integer> getDocumentos() {
return documentos;
}
/**
* Compara se dois objetos Palavra são iguais. A condição é a string palavra
* que ambos contém ser a mesma, independente do HashMap.
*/
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final PalavraMap other = (PalavraMap) obj;
return Objects.equals(this.texto, other.texto);
}
/**
* Imprime todos os documentos do HashMap.
*/
public void imprimePares() {
System.out.println("A palavra " + this.texto + " foi encontrada nos seguintes documentos:");
for (Map.Entry<Integer, Integer> i : this.documentos.entrySet()) {
System.out.print(i.getKey() + " - ");
}
System.out.println();
}
/**
* Retorna o numero de documentos em que a palavra ocorre
*/
public int numeroDocumentos() {
if (this.documentos != null) {
return this.documentos.size();
}
return 0;
}
/**
* Retorna o numero de ocorrencias da palavra no documento
*/
public int numeroOcorrenciasPalavraNoDocumento(int id_documento) {
return this.documentos.get(id_documento);
}
/**
* Retorna um iterator para percorrer a estrutura
*/
public Iterator getIterator() {
if (this.documentos == null || this.documentos.isEmpty()) {
return null;
}
return this.documentos.entrySet().iterator();
}
@Override
public int hashCode() {
int hash = 7;
hash = 67 * hash + Objects.hashCode(this.texto);
return hash;
}
}
|
package br.com.pizzaria.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import br.com.pizzaria.dao.PizzaDAO;
import br.com.pizzaria.entidades.Item;
import br.com.pizzaria.entidades.Pizza;
import br.com.pizzaria.parser.PizzaParser;
@RestController
@RequestMapping("/pizzas")
public class PizzaController {
@Autowired
private PizzaDAO dao;
@RequestMapping(method = RequestMethod.GET)
public List<Item> carregarTodas() {
return PizzaParser.fromPizzas(dao.carregarTodos(Pizza.class));
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public Pizza obterPizza(@PathVariable long id) {
Pizza pizza = dao.obter(Pizza.class, id);
return pizza;
}
}
|
package basics;
import org.openqa.selenium.WebDriver;
import util.Commons;
/**
Req:
open the browser and Hit the URL "https://gmail.com" using the Java
Steps:
-------
1.Provide the driver software location ""C:\\chromedriver.exe" to the System.
Create the web driver Object using the driver software.
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
2.Open the URL
driver.get("https://www.gmail.com");
3.close the browser
driver.quit()
*/
public class Ex4Comm {
public static void main(String[] args) throws InterruptedException {
WebDriver driver = Commons.getChromeDriver();
//open the url
driver.get("http://www.google.com");
Thread.sleep(5000);
// close the browser
driver.quit();
}
public static void main1(String[] args) {
WebDriver driver = Commons.getDriver();
driver.get("http://www.google.com");
driver.close();
}
}
|
package com.mobica.rnd.parking.parkingbetests;
import com.mobica.rnd.parking.parkingbetests.support.TestSuiteData;
import com.mobica.rnd.parking.parkingbetests.support.RestAssuredProcessor;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.PostConstruct;
/**
* Created by int_eaja on 2017-07-26.
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@TestPropertySource("classpath:application-test.properties")
public class Issue_6_ParkingConfigurationTest {
private static final String ISSUE_NAME = "6-ParkingConfiguration";
@Autowired
private RestAssuredProcessor processor;
private TestSuiteData suiteData;
@PostConstruct
public void setUp() {
suiteData = new TestSuiteData(processor.getBaseURL(), ISSUE_NAME);
}
@Test
public void parking_configuration_success_test() {
suiteData.createTestCaseExecutor("parking_configuration_success")
.performTests(processor, suiteData);
}
@Test
public void parking_configuration_with_correct_boundary_values_success_test() {
suiteData.createTestCaseExecutor("parking_configuration_with_correct_boundary_values_success")
.performTests(processor, suiteData);
}
@Test
public void parking_configuration_without_capacity_failure_test() {
suiteData.createTestCaseExecutor("parking_configuration_without_capacity_failure")
.performTests(processor, suiteData);
}
@Test
public void parking_configuration_without_name_failure_test() {
suiteData.createTestCaseExecutor("parking_configuration_without_name_failure")
.performTests(processor, suiteData);
}
@Test
public void parking_configuration_with_capacity_not_as_a_number_value_failure_test() {
suiteData.createTestCaseExecutor("parking_configuration_with_capacity_not_as_a_number_value_failure")
.performTests(processor, suiteData);
}
@Test
public void parking_configuration_with_capacity_too_long_length_failure_test() {
suiteData.createTestCaseExecutor("parking_configuration_with_capacity_too_long_length_failure")
.performTests(processor, suiteData);
}
@Test
public void parking_configuration_with_capacity_too_long_not_numerical_length_failure_test() {
suiteData.createTestCaseExecutor("parking_configuration_with_capacity_too_long_not_numerical_length_failure")
.performTests(processor, suiteData);
}
@Test
public void parking_configuration_with_name_too_long_length_failure_test() {
suiteData.createTestCaseExecutor("parking_configuration_with_name_too_long_length_failure")
.performTests(processor, suiteData);
}
@Test
public void parking_configuration_with_incorrect_boundary_values_failure_test() {
suiteData.createTestCaseExecutor("parking_configuration_with_incorrect_boundary_values_failure")
.performTests(processor, suiteData);
}
}
|
package primeiros_exercicios;
import java.util.Date;
import java.util.Scanner;
public class NumerosPrimos {
public static void main(String[] args) {
int a;
boolean primo=true;
Scanner valor = new Scanner(System.in);
System.out.print("Digite um numero: ");
a = valor.nextInt();
if (a <= 0) {
System.out.println("Digito errado");
System.out.print("digite um valor valido: ");
a = valor.nextInt();
}
for (int i = 2; i <a; i++) {
if (a % i == 0) {
primo = false;
break;
}
}
if (primo==true){
System.out.println("e primo");
} else {
System.out.println("nao e primo");
}
}
}
|
package com.youthchina.controller.user;
import com.youthchina.annotation.ResponseBodyDTO;
import com.youthchina.controller.DomainCRUDController;
import com.youthchina.domain.zhongyang.Gender;
import com.youthchina.domain.zhongyang.User;
import com.youthchina.dto.Response;
import com.youthchina.dto.StatusDTO;
import com.youthchina.dto.security.ModifiedUserDTO;
import com.youthchina.dto.security.UserDTO;
import com.youthchina.dto.util.InfluenceDTO;
import com.youthchina.exception.zhongyang.exception.ClientException;
import com.youthchina.exception.zhongyang.exception.ForbiddenException;
import com.youthchina.exception.zhongyang.exception.InternalStatusCode;
import com.youthchina.exception.zhongyang.exception.NotFoundException;
import com.youthchina.service.DomainCRUDService;
import com.youthchina.service.application.CompanyCURDService;
import com.youthchina.service.application.JobService;
import com.youthchina.service.application.JobServiceImpl;
import com.youthchina.service.community.*;
import com.youthchina.service.user.StudentService;
import com.youthchina.service.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.Timestamp;
/**
* Created by zhongyangwu on 11/8/18.
*/
@RestController
@RequestMapping("${web.url.prefix}/users/**")
public class UserController extends DomainCRUDController<User, Integer> {
private final StudentService studentService;
private final AttentionService attentionService;
private final EssayService essayService;
private final QuestionService questionService;
private final VideoService videoService;
private final AnswerService answerService;
private final JobService jobService;
private final BriefReviewService briefReviewService;
private final CompanyCURDService companyCURDService;
private final InfluenceService influenceService;
private UserService userService;
private String url;
@Autowired
public UserController(UserService userService, @Value("${web.url.prefix}") String prefix, StudentService studentService, AttentionServiceImpl attentionService, EssayServiceImpl essayService, QuestionServiceImpl questionService, VideoServiceImpl videoService, AnswerServiceImpl answerService, JobServiceImpl jobService, BriefReviewService briefReviewService, CompanyCURDService companyCURDService
, InfluenceService influenceService) {
this.userService = userService;
this.url = prefix + "/users/";
this.studentService = studentService;
this.attentionService = attentionService;
this.essayService = essayService;
this.questionService = questionService;
this.videoService = videoService;
this.answerService = answerService;
this.jobService = jobService;
this.briefReviewService = briefReviewService;
this.companyCURDService = companyCURDService;
this.influenceService = influenceService;
}
@GetMapping("/{id}")
public ResponseEntity<?> findUser(@PathVariable Integer id, @AuthenticationPrincipal User user) throws ForbiddenException, NotFoundException {
if (user.getId().equals(id)) {
return get(id);
} else {
throw new ForbiddenException();
}
}
@GetMapping("/{id}/influence")
public ResponseEntity<?> getMyInfluence(@PathVariable Integer id, @AuthenticationPrincipal User user) throws ForbiddenException {
if (user.getId().equals(id)) {
Integer influence = influenceService.getUserInfluence(id);
return ResponseEntity.ok(new Response(new InfluenceDTO(influence), new StatusDTO(200, "success")));
} else {
throw new ForbiddenException();
}
}
@PatchMapping("/{id}")
@ResponseBodyDTO(UserDTO.class)
public ResponseEntity<?> modifyUser(@PathVariable Integer id, @AuthenticationPrincipal User user, @RequestBody @Valid ModifiedUserDTO body) throws ClientException, ForbiddenException, NotFoundException {
// Role control
if (id.equals(user.getId())) {
if (body.getGender() != null) {
try {
Gender gender = Gender.valueOf(body.getGender());
user.setGender(gender);
} catch (IllegalArgumentException ex) {
throw new ClientException("gender must be MALE, FEMALE or OTHER");
}
}
user.setFirstName(body.getFirstName() == null ? user.getFirstName() : body.getFirstName());
user.setLastName(body.getLastName() == null ? user.getLastName() : body.getLastName());
user.setAvatarUrl(body.getAvatarUrl() == null ? user.getAvatarUrl() : body.getAvatarUrl());
user.setDateOfBirth(body.getDateOfBirth() == null ? user.getDateOfBirth() : new Timestamp(body.getDateOfBirth()));
User resultUser = userService.update(user);
return ResponseEntity.ok(new Response(resultUser));
} else {
throw new ForbiddenException(InternalStatusCode.ACCESS_DENY);
}
}
@Override
protected DomainCRUDService<User, Integer> getService() {
return this.userService;
}
@Override
protected URI getUriForNewInstance(Integer id) throws URISyntaxException {
return new URI(this.url + id);
}
}
|
package Bank;
public class ClientsAccount {
Branch branch;
Account account;
Client client;
}
|
/*
* 2012-3 Red Hat Inc. and/or its affiliates and other contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.overlord.rtgov.epn;
import static org.junit.Assert.*;
import java.io.Serializable;
import org.junit.Test;
import org.overlord.rtgov.epn.AbstractEPNManager;
import org.overlord.rtgov.epn.EPNContainer;
import org.overlord.rtgov.epn.EventList;
import org.overlord.rtgov.epn.Network;
import org.overlord.rtgov.epn.NetworkListener;
import org.overlord.rtgov.epn.Node;
import org.overlord.rtgov.epn.Notification;
import org.overlord.rtgov.epn.NotificationType;
import org.overlord.rtgov.epn.Subscription;
import org.overlord.rtgov.epn.testdata.TestEvent1;
import org.overlord.rtgov.epn.testdata.TestEvent2;
import org.overlord.rtgov.epn.testdata.TestEventProcessorA;
import org.overlord.rtgov.epn.testdata.TestNotificationListener;
public class AbstractEPNManagerTest {
private static final String SUBJECT1 = "SUBJECT1";
private static final String DUMMY_SUBJECT = "DummySubject";
private static final String N1 = "N1";
private static final String N2 = "N2";
private static final String N3 = "N3";
private static final String TEST_NETWORK = "TestNetwork";
private static final String TEST_SUBJECT1 = "TestSubject1";
private static final String TEST_SUBJECT2 = "TestSubject2";
private static final String VER1 = "1";
private static final String VER2 = "2";
protected AbstractEPNManager getManager() {
return(new AbstractEPNManager() {
public void publish(String subject,
java.util.List<? extends java.io.Serializable> events) throws Exception {
}
public EPNContainer getContainer() {
return null;
}
});
}
@Test
public void testRegisterNetworkIncorrectRootNodeName() {
Network net=new Network();
net.setName(TEST_NETWORK);
// Root should be incorrect, to test exception
Subscription sub=new Subscription();
sub.setNodeName(N2);
sub.setSubject(TEST_SUBJECT1);
net.getSubscriptions().add(sub);
Node n1=new Node();
n1.setName(N1);
n1.setEventProcessor(new TestEventProcessorA());
net.getNodes().add(n1);
AbstractEPNManager mgr=getManager();
try {
mgr.register(net);
fail("Network registration should fail due to missing or incorrect root node");
} catch(Exception e) {
}
}
@Test
public void testRegisterInvalidNetwork() {
Network net=new Network();
AbstractEPNManager mgr=getManager();
try {
mgr.register(net);
fail("Network registration should fail due to validation issues");
} catch(Exception e) {
}
}
@Test
public void testNetworkListenerNotified() {
Network net=new Network();
net.setName(TEST_NETWORK);
net.setVersion(VER1);
Node n1=new Node();
n1.setName(N1);
n1.setEventProcessor(new TestEventProcessorA());
net.getNodes().add(n1);
AbstractEPNManager mgr=getManager();
TestNetworkListener l=new TestNetworkListener();
mgr.addNetworkListener(l);
if (l._registered.size() != 0) {
fail("No networks should be registered");
}
if (l._unregistered.size() != 0) {
fail("No networks should be unregistered");
}
try {
mgr.register(net);
} catch(Exception e) {
fail("Failed: "+e);
}
if (l._registered.size() != 1) {
fail("1 network should be registered: "+l._registered.size());
}
if (l._unregistered.size() != 0) {
fail("Still no networks should be unregistered");
}
try {
mgr.unregister(net.getName(), net.getVersion());
} catch(Exception e) {
fail("Failed: "+e);
}
if (l._registered.size() != 1) {
fail("Still 1 network should be registered: "+l._registered.size());
}
if (l._unregistered.size() != 1) {
fail("1 network should be unregistered: "+l._unregistered.size());
}
}
@Test
public void testRegisterNetworkNodeNoEventProcessor() {
Network net=new Network();
net.setName(TEST_NETWORK);
//net.setRootNodeName(N1);
Node n1=new Node();
n1.setName(N1);
net.getNodes().add(n1);
AbstractEPNManager mgr=getManager();
try {
mgr.register(net);
fail("Network registration should fail due to node with missing event processor");
} catch(Exception e) {
}
}
@Test
public void testNetworkAndNodeLookup() {
Network net=new Network();
net.setName(TEST_NETWORK);
net.setVersion(VER1);
//net.setRootNodeName(N1);
Node n1=new Node();
n1.setName(N1);
n1.setEventProcessor(new TestEventProcessorA());
net.getNodes().add(n1);
Node n2=new Node();
n2.setName(N2);
n2.setEventProcessor(new TestEventProcessorA());
net.getNodes().add(n2);
Node n3=new Node();
n3.setName(N3);
n3.setEventProcessor(new TestEventProcessorA());
net.getNodes().add(n3);
AbstractEPNManager mgr=getManager();
try {
mgr.register(net);
} catch(Exception e) {
fail("Failed to register network: "+e);
}
if (mgr.getNetwork(TEST_NETWORK, null) != net) {
fail("Failed to find test network");
}
try {
if (mgr.getNode(TEST_NETWORK, null, N1) != n1) {
fail("Failed to find node n1");
}
if (mgr.getNode(TEST_NETWORK, null, N2) != n2) {
fail("Failed to find node n2");
}
if (mgr.getNode(TEST_NETWORK, null, N3) != n3) {
fail("Failed to find node n3");
}
} catch(Exception e) {
fail("Failed to find node");
}
}
@Test
public void testRegisterNotificationListenerNotifyProcessed() {
Network net=new Network();
net.setName(TEST_NETWORK);
net.setVersion(VER1);
TestEventProcessorA tep=new TestEventProcessorA();
Node n1=new Node();
n1.setName(N1);
n1.setEventProcessor(tep);
Notification not1=new Notification();
not1.setSubject(SUBJECT1);
not1.setType(NotificationType.Processed);
n1.getNotifications().add(not1);
net.getNodes().add(n1);
AbstractEPNManager mgr=getManager();
try {
mgr.register(net);
TestNotificationListener nl=new TestNotificationListener();
mgr.addNotificationListener(SUBJECT1, nl);
TestNotificationListener anothernl=new TestNotificationListener();
mgr.addNotificationListener(DUMMY_SUBJECT, anothernl);
TestEvent1 te1=new TestEvent1(2);
TestEvent2 te2=new TestEvent2(5);
java.util.List<Serializable> elList=new java.util.ArrayList<Serializable>();
EventList el=new EventList(elList);
elList.add(te1);
elList.add(te2);
tep.retry(te2);
EventList retries=mgr.process(net, n1, null, el, 3);
if (retries == null) {
fail("Retries is null");
}
if (retries.size() != 1) {
fail("Retries should have 1 event: "+retries.size());
}
if (!retries.contains(te2)) {
fail("Retries did not contain te2");
}
if (nl.getEntries().size() != 1) {
fail("Notification listener should have 1 processed event: "+nl.getEntries().size());
}
if (!nl.getEntries().get(0).getEvents().contains(te1)) {
fail("Processed Event te1 should have been processed");
}
if (!nl.getEntries().get(0).getSubject().equals(SUBJECT1)) {
fail("Processed Event subject name incorrect");
}
if (anothernl.getEntries().size() > 0) {
fail("Should be no entries in other listener");
}
} catch(Exception e) {
e.printStackTrace();
fail("Failed with exception: "+e);
}
}
@Test
public void testRegisterNotificationListenerDontNotifyProcessed() {
Network net=new Network();
net.setName(TEST_NETWORK);
net.setVersion(VER1);
TestEventProcessorA tep=new TestEventProcessorA();
Node n1=new Node();
n1.setName(N1);
n1.setEventProcessor(tep);
Notification not1=new Notification();
not1.setSubject(SUBJECT1);
not1.setType(NotificationType.Results);
n1.getNotifications().add(not1);
net.getNodes().add(n1);
AbstractEPNManager mgr=getManager();
try {
mgr.register(net);
TestNotificationListener nl=new TestNotificationListener();
mgr.addNotificationListener(SUBJECT1, nl);
TestNotificationListener anothernl=new TestNotificationListener();
mgr.addNotificationListener(DUMMY_SUBJECT, anothernl);
TestEvent1 te1=new TestEvent1(2);
TestEvent2 te2=new TestEvent2(5);
java.util.List<Serializable> elList=new java.util.ArrayList<Serializable>();
EventList el=new EventList(elList);
elList.add(te1);
elList.add(te2);
tep.retry(te2);
EventList retries=mgr.process(net, n1, null, el, 3);
if (retries == null) {
fail("Retries is null");
}
if (retries.size() != 1) {
fail("Retries should have 1 event: "+retries.size());
}
if (!retries.contains(te2)) {
fail("Retries did not contain te2");
}
if (nl.getEntries().size() != 0) {
fail("Node listener should have 0 processed event: "+nl.getEntries().size());
}
if (anothernl.getEntries().size() > 0) {
fail("Should be no entries in other listener");
}
} catch(Exception e) {
e.printStackTrace();
fail("Failed with exception: "+e);
}
}
@Test
public void testRegisterMultipleNetworkVersions() {
Network net1=new Network();
net1.setName(TEST_NETWORK);
net1.setVersion(VER1);
Subscription sub1=new Subscription();
sub1.setNodeName(N1);
sub1.setSubject(TEST_SUBJECT1);
net1.getSubscriptions().add(sub1);
TestEventProcessorA tep=new TestEventProcessorA();
Node n1=new Node();
n1.setName(N1);
n1.setEventProcessor(tep);
net1.getNodes().add(n1);
Network net2=new Network();
net2.setName(TEST_NETWORK);
net2.setVersion(VER2);
Subscription sub2=new Subscription();
sub2.setNodeName(N2);
sub2.setSubject(TEST_SUBJECT2);
net2.getSubscriptions().add(sub2);
Node n2=new Node();
n2.setName(N2);
n2.setEventProcessor(tep);
net2.getNodes().add(n2);
AbstractEPNManager mgr=getManager();
try {
mgr.register(net1);
// Check if network subscribed to subject
java.util.List<Network> res1=mgr.getNetworksForSubject(TEST_SUBJECT1);
if (res1 == null) {
fail("Network list is null");
}
if (res1.size() != 1) {
fail("Network list should have 1 entry: "+res1.size());
}
if (res1.get(0) != net1) {
fail("Network should be net1");
}
mgr.register(net2);
// Refresh subject list
res1 = mgr.getNetworksForSubject(TEST_SUBJECT1);
if (res1 != null) {
fail("List for subject1 should now be null");
}
// Check if network subscribed to subject
java.util.List<Network> res2=mgr.getNetworksForSubject(TEST_SUBJECT2);
if (res2 == null) {
fail("Network list2 is null");
}
if (res2.size() != 1) {
fail("Network list2 should have 1 entry: "+res2.size());
}
if (res2.get(0) != net2) {
fail("Network should be net2");
}
// Finally check that unsubscribing the current version will reinstate the old subjects
mgr.unregister(net2.getName(), net2.getVersion());
res2 = mgr.getNetworksForSubject(TEST_SUBJECT2);
if (res2 != null) {
fail("List for subject2 should now be null");
}
res1 = mgr.getNetworksForSubject(TEST_SUBJECT1);
if (res1 == null) {
fail("List for subject1 should now be available again");
}
if (res1.size() != 1) {
fail("Network list1 should have 1 entry again: "+res1.size());
}
if (res1.get(0) != net1) {
fail("Network should be net1 again");
}
} catch(Exception e) {
fail("Failed with exception: "+e);
}
}
public class TestNetworkListener implements NetworkListener {
protected java.util.List<Network> _registered=new java.util.ArrayList<Network>();
protected java.util.List<Network> _unregistered=new java.util.ArrayList<Network>();
public void registered(Network network) {
_registered.add(network);
}
public void unregistered(Network network) {
_unregistered.add(network);
}
}
}
|
package raktar;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Raktar {
private List<Termek> termekek;
private List<Szett> szettek;
public Raktar() {
termekek = new ArrayList<>();
szettek = new ArrayList<>();
}
public int termekekSzama() {
return termekek.size();
}
public int szettekSzama() {
return szettek.size();
}
public Termek getTermek(int index) {
if (termekek.size() > 0) {
if (termekek.size()-1 <= index) {
return termekek.get(index);
}
}
return null;
}
public Szett getSzett(int index) {
if (szettek.size() > 0) {
if (szettek.size()-1 <= index) {
return szettek.get(index);
}
}
return null;
}
public Termek termekKeres(int azonosito) {
for (int i = 0; i < termekek.size(); i++) {
if (azonosito == termekek.get(i).getAzonosito()) {
return termekek.get(i);
}
return null;
}
return null;
}
public void termekBeolvas(String fNev) throws FileNotFoundException, IOException {
BufferedReader br = new BufferedReader(new FileReader(fNev));
String line = br.readLine();
// termekek = new ArrayList<Termek>();
termekek.add(Termek.createTermek(line));
while (line != null) {
if (Termek.createTermek(line) != null) {
for (int i = 0; i < termekek.size(); i++) {
if (Termek.createTermek(line).getAzonosito() == getTermek(i).getAzonosito()) { // nullpointerex...
br.readLine();
}
}
termekek.add(Termek.createTermek(line));
}
line = br.readLine();
}
}
public void szettBeolvas(String fNev) throws FileNotFoundException, IOException {
BufferedReader br = new BufferedReader(new FileReader(fNev));
String line = br.readLine();
while (line != null) {
// String[] tmp = line.split(",");
// Szett.ar = arKiszamol(termekKeres(Integer.parseInt(tmp[2])).getAr());
szettek.add(Szett.createSzett(line));
line = br.readLine();
}
}
@Override public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < termekek.size(); i++) {
sb.append(termekek.get(i).toString()).append("/n");
}
for (int j = 0; j < szettek.size(); j++) {
sb.append(szettek.get(j).toString()).append("/n");
}
return sb.toString();
}
}
|
package com.osce.server.portal;
import com.osce.entity.SysParam;
import com.osce.enums.SysParamEnum;
import com.osce.result.Result;
import com.osce.server.security.rsa.RsaKeyPairQueue;
import com.osce.server.utils.ImageCodeUtil;
import com.osce.server.utils.ParamUtil;
import com.sm.open.care.core.enums.YesOrNo;
import com.sm.open.care.core.utils.rsa.RsaKeyPair;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;
/**
* @ClassName: IndexController
* @Description: 首页控制器跳转
*/
@Controller
public class LoginController extends BaseController {
private static final Logger LOGGER = LoggerFactory.getLogger(LoginController.class);
/**
* 用户业务错误信息显示的常量变量名
*/
private static final String ERROR_MSG = "errorMsg";
/**
* rsa公钥常量变量名
*/
private static final String PUBLIC_KEY = "publicKey";
@Resource(name = "rsaKeyPairQueue")
private RsaKeyPairQueue rsaKeyPairQueue;
@Resource
private ImageCodeUtil imageCodeUtil;
@Resource
private ParamUtil paramUtil;
/**
* 网站名称
*/
@Value("${website.name}")
private String websiteName;
@Value("${website.copyright}")
private String websiteCopyright;
@Value("${website.approve}")
private String websiteApprove;
@RequestMapping(value = "/login")
public String home(Model model, HttpServletRequest request) {
this.setModelAttr(model, request);
model.addAttribute("websiteName", websiteName);
model.addAttribute("websiteCopyright", websiteCopyright);
model.addAttribute("websiteApprove", websiteApprove);
SysParam sysParam = paramUtil.getParamInfo(SysParamEnum.VISITOR_SWITCH.getCode());
model.addAttribute(SysParamEnum.VISITOR_SWITCH.getCode(),
sysParam != null ? sysParam.getParamValue() : YesOrNo.NO.getCode());
return "login";
}
@RequestMapping(value = "/login/{errorMsg}")
public String homeError(@PathVariable String errorMsg, Model model, HttpServletRequest request) {
if (StringUtils.isNotBlank(errorMsg)) {
model.addAttribute(ERROR_MSG, new String(Base64.decodeBase64(errorMsg)));
} else {
model.addAttribute(ERROR_MSG, "");
}
model.addAttribute("websiteName", websiteName);
model.addAttribute("websiteCopyright", websiteCopyright);
model.addAttribute("websiteApprove", websiteApprove);
this.setModelAttr(model, request);
return "login";
}
private void setModelAttr(Model model, HttpServletRequest request) {
RsaKeyPair keyPair;
try {
keyPair = rsaKeyPairQueue.takeQueue(request);
model.addAttribute(PUBLIC_KEY, keyPair.getPublicKey());
} catch (InterruptedException e) {
logger.error("进入首页时,rsa公私钥队列相关操作异常", e);
}
}
@RequestMapping(value = "login/verificationCode", method = RequestMethod.GET)
@ResponseBody
public String loginVerificationCode(HttpServletRequest request, HttpServletResponse response) {
// 禁止图像缓存。
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg");
// 将图像输出到Servlet输出流中。
try {
ServletOutputStream sos = response.getOutputStream();
ImageIO.write(imageCodeUtil.getImage(request), "jpeg", sos);
sos.close();
} catch (IOException e) {
LOGGER.error("LoginController-loginVerificationCode error: {}", e);
}
return null;
}
@RequestMapping("/loginScanCode")
@ResponseBody
public Result loginScanCode(HttpServletRequest request) {
Result result = new Result(true, null, null);
try {
String authKey = UUID.randomUUID().toString().replaceAll("-", "");
//生产二维码信息至redis
//二维码信息(qr地址+uuid)
request.getSession().setAttribute("authKey", authKey);
} catch (Exception e) {
String errMsg = StringUtils.isBlank(e.getMessage()) ? e.getMessage() : "登录失败!";
LOGGER.error("LoginController-loginScanCode error: {},e: {}", errMsg, e);
result.change(false, errMsg, errMsg);
}
return result;
}
@RequestMapping("/loginTimeout")
public String loginTimeout(HttpServletRequest request) {
return "pages/common/loginTimeout";
}
}
|
package com.veveup.dao;
import com.veveup.domain.User;
import java.util.List;
public interface UserDao {
/**
* 查找所有用户
*
* @return
*/
List<User> findAll();
/**
* 通过传入name获得用户实例
*
* @param name
* @return
*/
User findUserByName(String name);
/**
* 保存新用户
*/
void insertUser(User user);
/**
* 传入一个更改过的用户实例 通过uid更新用户信息 可以更改name和password、email
*
* @param user
*/
void updateUserByUser(User user);
}
|
package com.oracle.demosjon.demojson;
import java.sql.Connection;
import oracle.soda.OracleCollection;
import oracle.soda.OracleCursor;
import oracle.soda.OracleDatabase;
import oracle.soda.OracleDocument;
import oracle.soda.rdbms.OracleRDBMSClient;
public class SodaController {
private Connection conn;
public SodaController(Connection conn) {
this.conn = conn;
}
public void doSodaWork() {
try {
OracleRDBMSClient cl = new OracleRDBMSClient();
OracleDatabase db = cl.getDatabase(conn);
// Create a collection with the name "MyJSONCollection".
OracleCollection col = db.admin().createCollection("MyJSONCollection");
// Create a JSON document.
OracleDocument doc = db.createDocumentFromString("{ \"name\" : \"Borja\" }");
// Insert the document into a collection, and get back its
// auto-generated key.
System.out.println("Before inserting document");
String k = col.insertAndGet(doc).getKey();
// Find a document by its key. The following line
// fetches the inserted document from the collection
// by its unique key, and prints out the document's content
System.out.println("Inserted content:" + col.find().key(k).getOne().getContentAsString() + "with Key: "+ k);
// Find all documents in the collection matching a query-by-example (QBE).
// The following lines find all JSON documents in the collection that have
// a field "name" that starts with "A".
OracleDocument f = db.createDocumentFromString("{\"name\" : { \"$startsWith\" : \"A\" }}");
OracleCursor c = col.find().filter(f).getCursor();
while (c.hasNext()) {
// Get the next document.
OracleDocument resultDoc = c.next();
// Print the document key and content.
System.out.println("Key: " + resultDoc.getKey());
System.out.println("Content: " + resultDoc.getContentAsString());
}
} catch (Exception e) {
System.out.println(e);
}
}
}
|
package ru.itis.javalab.repositories;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.stereotype.Repository;
import ru.itis.javalab.models.Post;
import ru.itis.javalab.models.User;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* created: 19-11-2020 - 0:24
* project: 07. Fremarker
*
* @author dinar
* @version v0.1
*/
@Repository
public class PostRepositoryJdbcTemplateImpl implements CrudPostRepository {
// language=SQL
private static final String SQL_SELECT_BY_ID =
"select * " +
"from post " +
"where id = ?";
// language=SQL
private static final String SQL_SELECT_BY_USER_ID =
"select * " +
"from post " +
"where user_id = ?";
// language=SQL
private static final String SQL_SELECT_ALL =
"select * " +
"from post";
// language=SQL
private static final String SQL_INSERT_POST =
"insert into post(user_id, time, place, description, people, file_name) " +
"values (?, ?, ?, ?, ?, ?)";
// language=SQL
private static final String SQL_UPDATE_POST =
"update post " +
"set place = :place, description = :description, people = :people " +
"where id = :id";
// language=SQL
private static final String SQL_DELETE_POST =
"delete from post " +
"where id = ?";
// language=SQL
private static final String SQL_SELECT_BY_FILENAME =
"select * " +
"from post " +
"where file_name = ?";
private final SimpleJdbcInsert simpleJdbcInsert;
private final JdbcTemplate jdbcTemplate;
private final NamedParameterJdbcTemplate namedParameterJdbcTemplate;
private final RowMapper<Post> rowMapper = (resultSet, i) -> Post.builder()
.id(resultSet.getLong("id"))
.user((User) resultSet.getObject("user_id"))
.time(resultSet.getTimestamp("time"))
.place(resultSet.getString("place"))
.description(resultSet.getString("description"))
.people(resultSet.getString("people"))
.fileName(resultSet.getString("file_name"))
.build();
public PostRepositoryJdbcTemplateImpl(SimpleJdbcInsert simpleJdbcInsert,
JdbcTemplate jdbcTemplate,
NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
this.simpleJdbcInsert = simpleJdbcInsert;
this.jdbcTemplate = jdbcTemplate;
this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
}
@Override
public List<Post> findAllByUserId(Long id) {
return jdbcTemplate.query(SQL_SELECT_BY_USER_ID, rowMapper, id);
}
@Override
public Optional<Post> findById(Long id) {
Post post;
try {
post = jdbcTemplate.queryForObject(SQL_SELECT_BY_ID, rowMapper, id);
} catch (DataAccessException e) {
return Optional.empty();
}
return Optional.ofNullable(post);
}
@Override
public Optional<Post> findByFileName(String fileName) {
Post post;
try {
post = jdbcTemplate.queryForObject(SQL_SELECT_BY_FILENAME, rowMapper, fileName);
} catch (DataAccessException e) {
return Optional.empty();
}
return Optional.ofNullable(post);
}
@Override
public Long save(Post entity) {
simpleJdbcInsert.withTableName("post")
.usingColumns(
"user_id",
"time",
"place",
"description",
"people",
"file_name")
.usingGeneratedKeyColumns("id");
Map<String, Object> map = new HashMap<>();
map.put("user_id", entity.getUser());
map.put("time", entity.getTime());
map.put("place", entity.getPlace());
map.put("description", entity.getDescription());
map.put("people", entity.getPeople());
map.put("file_name", entity.getFileName());
return (Long) simpleJdbcInsert.executeAndReturnKey(map);
}
@Override
public List<Post> findAll() {
return jdbcTemplate.query(SQL_SELECT_ALL, rowMapper);
}
@Override
public void update(Post entity) {
Map<String, String> map = new HashMap<>();
map.put("id", String.valueOf(entity.getId()));
map.put("place", entity.getPlace());
map.put("description", entity.getDescription());
map.put("people", entity.getPeople());
namedParameterJdbcTemplate.update(SQL_UPDATE_POST, map);
}
@Override
public void delete(Post entity) {
jdbcTemplate.update(SQL_DELETE_POST, entity.getId());
}
}
|
package com.jk.jkproject.net.im.info;
import android.app.Activity;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.View;
import com.jk.jkproject.R;
import com.jk.jkproject.ui.msg.IUploadProgress;
import com.jk.jkproject.utils.Constants;
import com.jk.jkproject.utils.DateUtils;
import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import java.util.UUID;
/**
* @author zhoujiyu
* @Description 消息列表中的消息实体
* @date 2015-2-5
*/
public class MessageEntity implements Serializable, Observer {
private static final long serialVersionUID = 1L;
public static final int STATUS_NOT = 0;
public static final int STATUS_SUCCESS = 1;
public static final int STATUS_FAILED = 2;
public static final int STATUS_LOADING = 3;
private boolean IsSend = false;
public long SessionId;
private long UserID;// 用户ID
private long FromID; // 发送者
private long ToID; // 接收者
private long SmsID;// 服务器自己会话内消息编号
private long SmsKey; // 服务器消息池会话的唯一编号
private String MsgID; // 客户端对所有消息的唯一编号(UUID) 主要是设置状态的消息唯一编号
private long GroupID;// 群IDz
// add by xiaosong.xu
private String thumbPath = null; // 本地小图路径
private String thumbUrl = null; // 小图url
private String imagePath = null; // 本地大图路径
private String imageUrl = null; // 大图URL
private int photoType =0; //0是相册 1 是实景相机 2是瞬间照片
private int progress = 0;
private String voicePath = null;
private String voiceUrl = null;
private int voiceTime = 0;
private int mediaDownloadStatus = 0;//0代表未下载,1代表未读,2代表已读
private int oldProgress = 0;
// end by xiaosong.xu
private String Text;// 聊天内容
private General.ETextType TextType = General.ETextType.ETT_TEXT;
private General.EChatType ChatType = General.EChatType.ECT_NORMAL;
// ECT_NORMAL = 1;正常聊天
// ECT_SYSTEM = 2;系统聊天
// ECT_READSTATE = 3;聊天消息已读状态设置
// ECT_PRODUCT = 4;产品消息
// ECT_GROUP = 5;群聊
private long Time;// 时间
private int MessageState = Constants.MESSAGE_STATE_LOADDING;
// 是发送中,1是送达,2是已阅,3是发送失败,4是对方发过来接受成功的消息
private String savePath = null; // 图片或语音保存路径
private String url = null; // 图片或语音链接
private int displayType = Constants.MSG_DISPLAY_TYPE_NORMAL; // 消息显示类型 0气泡, 1系统浮框 ,2居中显示,3是系统打分图文混排
private int playTime = 0; // 语音播放时长
private boolean resend = false;
private int action; // 发过来的消息协议编号
private String errDes;// 消息发送失败的原因
private List<Long> StateSmsKeyID; // 设置状态的消息唯一编号
private String sTime;
private String systemHint;
private int snapState;//0是瞬间图片未看 1是是瞬间图片看了
/** 上传状态 */
private int mUploadStatus = STATUS_NOT;
/** 上传进度(数字) */
private int mProgress;
/** 气泡索引(id)*/
private String bubble;
//add by zjy
//livechat
public MessageEntity() {
String msg = UUID.randomUUID().toString();
setMsgID(msg);
}
public long getUserID() {
return UserID;
}
public void setUserID(long userID) {
UserID = userID;
}
public long getFromID() {
return FromID;
}
public void setFromID(long fromID) {
FromID = fromID;
}
public long getSmsID() {
return SmsID;
}
public void setSmsID(long smsID) {
SmsID = smsID;
}
public String getText() {
return Text;
}
public void setText(String text) {
Text = text;
}
public long getTime() {
return Time;
}
public void setTime(long time) {
Time = time;
sTime = DateUtils.getMsgItemTime(time);
}
public long getSmsKey() {
return SmsKey;
}
public void setSmsKey(long smsKey) {
SmsKey = smsKey;
}
public long getGroupID() {
return GroupID;
}
public void setGroupID(long groupID) {
GroupID = groupID;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
public General.ETextType getTextType() {
return TextType;
}
public void setTextType(General.ETextType textType) {
TextType = textType;
}
public General.EChatType getChatType() {
return ChatType;
}
public void setChatType(General.EChatType chatType) {
ChatType = chatType;
}
public long getToID() {
return ToID;
}
public void setToID(long toID) {
ToID = toID;
}
public int getMessageState() {
return MessageState;
}
public void setMessageState(int messageState) {
MessageState = messageState;
}
public long getSessionId() {
return IsSend ? ToID : FromID;
}
public boolean isIsSend() {
return IsSend;
}
public void setIsSend(boolean isSend) {
IsSend = isSend;
}
public String getSavePath() {
return savePath;
}
public void setSavePath(String savePath) {
this.savePath = savePath;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public int getDisplayType() {
return displayType;
}
public void setDisplayType(int displayType) {
this.displayType = displayType;
}
public int getPlayTime() {
return playTime;
}
public void setPlayTime(int playTime) {
this.playTime = playTime;
}
public boolean isResend() {
return resend;
}
public void setResend(boolean resend) {
this.resend = resend;
}
public void setSessionId(long sessionId) {
SessionId = sessionId;
}
public String getMsgID() {
return MsgID;
}
public void setMsgID(String msgID) {
MsgID = msgID;
}
public String getUUID() {
String uuid = UUID.randomUUID().toString();
return uuid;
}
public int getAction() {
return action;
}
public void setAction(int action) {
this.action = action;
}
public String getErrDes() {
return errDes;
}
public void setErrDes(String errDes) {
this.errDes = errDes;
}
public List<Long> getStateSmsKeyID() {
return StateSmsKeyID;
}
public void setStateSmsKeyID(List<Long> stateSmsKeyID) {
StateSmsKeyID = stateSmsKeyID;
}
public String getThumbPath() {
return thumbPath;
}
public void setThumbPath(String thumbPath) {
this.thumbPath = thumbPath;
}
public String getThumbUrl() {
return thumbUrl;
}
public void setThumbUrl(String thumbUrl) {
this.thumbUrl = thumbUrl;
}
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
@Override
public void update(Observable observable, Object data) {
}
public int getProgress() {
return progress;
}
public void setProgress(int progress) {
this.progress = progress;
}
public String getVoicePath() {
return voicePath;
}
public void setVoicePath(String voicePath) {
this.voicePath = voicePath;
}
public String getVoiceUrl() {
return voiceUrl;
}
public void setVoiceUrl(String voiceUrl) {
this.voiceUrl = voiceUrl;
}
public int getVoiceTime() {
return voiceTime;
}
public void setVoiceTime(int voiceTime) {
this.voiceTime = voiceTime;
}
public int getOldProgress() {
return oldProgress;
}
public void setOldProgress(int oldProgress) {
this.oldProgress = oldProgress;
}
public int getMediaDownloadStatus() {
return mediaDownloadStatus;
}
public void setMediaDownloadStatus(int mediaDownloadStatus) {
this.mediaDownloadStatus = mediaDownloadStatus;
}
public String getsTime() {
return sTime;
}
public void setsTime(String sTime) {
this.sTime = sTime;
}
public int getSnapState() {
return snapState;
}
public void setSnapState(int snapState) {
this.snapState = snapState;
}
public String getSystemHint() {
return systemHint;
}
public void setSystemHint(String systemHint) {
this.systemHint = systemHint;
}
public int getPhotoType() {
return photoType;
}
public void setPhotoType(int photoType) {
this.photoType = photoType;
}
public String getBubble() {
return bubble;
}
public void setBubble(String bubble) {
this.bubble = bubble;
}
public int getmUploadStatus() {
return mUploadStatus;
}
public void setmUploadStatus(int mUploadStatus) {
this.mUploadStatus = mUploadStatus;
}
public int getmProgress() {
return mProgress;
}
public void setmProgress(int progress) {
this.mProgress = progress;
}
private SparseArray<WeakReference<IUploadProgress>> callbacks = new SparseArray<>();
public synchronized void addProgressViews(IUploadProgress... progressViews) {
for (IUploadProgress callback : progressViews) {
if (callback instanceof View) {
View view = (View) callback;
Object obj = view.getTag(R.id.upload_id);
if (obj != null && !TextUtils.isEmpty((CharSequence) obj)) {
callbacks.put(callback.hashCode(), new WeakReference<IUploadProgress>(callback));
} else {
throw new RuntimeException("the callback must setTag and use R.id.upload_id as the key");
}
} else {
throw new RuntimeException("the callback isn't the instance of View!");
}
}
}
public void notifyProgress() {
notifyProgress(null);
}
public synchronized void notifyProgress(Activity activity) {
int size;
if (callbacks != null && (size = callbacks.size()) > 0) {
for (int i = 0; i < size; i++) {
final IUploadProgress callback = callbacks.valueAt(i).get();
if (callback == null) {
callbacks.removeAt(i);
i--;
size--;
} else {
if (callback instanceof View) {
final View v = (View) callback;
final Object u = v.getTag(R.id.upload_id);
if (u != null) {
if (u.equals(MsgID)) {
Runnable run = new Runnable() {
@Override
public void run() {
if (u.equals(v.getTag(R.id.upload_id))) {
callback.showStatus(MessageEntity.this);
callback.showProgress(mProgress);
}
}
};
if (activity == null) {
v.post(run);
} else {
activity.runOnUiThread(run);
}
} else {
callbacks.removeAt(i);
i--;
size--;
}
} else {
callbacks.removeAt(i);
i--;
size--;
}
} else {
callbacks.removeAt(i);
i--;
size--;
}
}
}
}
}
}
|
package spi.movieorganizer.repository;
import spi.movieorganizer.controller.tmdb.ITMDBController;
import spi.movieorganizer.controller.tmdb.TMDBController;
import spi.movieorganizer.controller.usermovie.IUserMovieController;
import spi.movieorganizer.controller.usermovie.UserMovieController;
import spi.movieorganizer.display.MovieOrganizerClient;
import spi.movieorganizer.display.MovieOrganizerClient.ActionExecutor;
public class MovieOrganizerControllerRepository {
private final ITMDBController tmdbController;
private final IUserMovieController userMovieController;
public MovieOrganizerControllerRepository(final MovieOrganizerClient session) {
this.tmdbController = new TMDBController(session, new ActionExecutor());
this.userMovieController = new UserMovieController(session, new ActionExecutor());
}
public ITMDBController getTmdbController() {
return this.tmdbController;
}
public IUserMovieController getUserMovieController() {
return this.userMovieController;
}
}
|
package org.browsexml.timesheetjob.dao.hibernate;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.browsexml.timesheetjob.dao.FulltimeAgreementDao;
import org.browsexml.timesheetjob.model.FulltimeAgreements;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
public class FulltimeAgreementDaoHibernate extends HibernateDaoSupport implements FulltimeAgreementDao {
private static Log log = LogFactory.getLog(FulltimeAgreementDaoHibernate.class);
public void removeFulltimeAgreement(Integer id) throws DataIntegrityViolationException {
FulltimeAgreements job = getHibernateTemplate().load(FulltimeAgreements.class, id);
long count = getHoursWorkedCount(job.getPeople().getPeopleId(), job.getJob().getDepartment());
if (count == 0) {
log.debug("delete");
getHibernateTemplate().delete(job);
}
else {
log.debug("THROW");
throw new DataIntegrityViolationException("The person has already punched in to this job");
}
}
@Override
public Long getHoursWorkedCount(String peopleId, String department) {
log.debug("getHoursWorkedCount " + peopleId + " " + department);
String strQuery = "select count(*) " +
"from HoursWorked "
+ "where peopleId = :people and job.department = :department ";
HibernateTemplate ht = getHibernateTemplate();
Session s = ht.getSessionFactory().getCurrentSession();
Query sqlQuery = s.createQuery(strQuery);
log.debug("HERE");
sqlQuery.setParameter("people", peopleId);
log.debug("HERE1");
sqlQuery.setParameter("department", "" + department);
log.debug("HERE2");
Long ret = null;
try {
ret = (Long) sqlQuery.uniqueResult();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
log.debug("HERE 3 -- count = " + ret);
return ret;
}
public void saveFulltimeAgreement(FulltimeAgreements agreement) {
Session s = getHibernateTemplate().getSessionFactory().getCurrentSession();
log.debug("Fulltime save or update ");
s.saveOrUpdate(agreement);
log.debug("Fulltime save or update DONE ");
}
public FulltimeAgreements getFulltimeAgreement(Integer id) {
return (FulltimeAgreements) getHibernateTemplate().get(FulltimeAgreements.class, id);
}
public List<FulltimeAgreements> getFulltimeAgreements(Integer people) {
String strQuery =
"from FulltimeAgreements a " +
"where a.people.id = :people";
List<FulltimeAgreements> ret = null;
HibernateTemplate ht = getHibernateTemplate();
Session s = ht.getSessionFactory().getCurrentSession();
Query sqlQuery = s.createQuery(strQuery).setParameter("people", people);
ret = (List<FulltimeAgreements>) sqlQuery.list();
return ret;
}
}
|
package capitulo08;
public class DateAndTimeTest {
public static void main(String[] args) {
DateAndTime Time1 = new DateAndTime (0,0,0,1,1,1);
DateAndTime Time2 = new DateAndTime (11,30,0,26,05,1998);
DateAndTime Time3 = new DateAndTime (18,57,0,21,12,2020);
DateAndTime Time4 = new DateAndTime (23,59,59,1,12,2000);
DateAndTime Time5 = new DateAndTime (23,59,59,31,12,2020);
displayTime("Data 1:", Time1);
Time1.Tick();
displayTime("Data 1 depois do primeiro Tick:", Time1);
displayTime("Data 2:", Time2);
Time2.Tick();
displayTime("Data 2 depois do primeiro Tick:", Time2);
displayTime("Data 3:", Time3);
Time3.Tick();
displayTime("Data 3 depois do primeiro Tick:", Time3);
displayTime("Data 4:", Time4);
Time4.Tick();
displayTime("Data 4 depois do primeiro Tick:", Time4);
displayTime("Data 5:", Time5);
Time5.Tick();
displayTime("Data 5 depois do primeiro Tick:", Time5);
}
private static void displayTime(String header, DateAndTime t) {
System.out.printf("%s%n%s%n", header, t.toUniversalString());
}
}
|
package it.polimi.se2019;
import it.polimi.se2019.model.GameBoard;
import it.polimi.se2019.model.deck.Deck;
import it.polimi.se2019.model.deck.Decks;
import it.polimi.se2019.model.deck.EmptyDeckException;
import it.polimi.se2019.model.grabbable.*;
import it.polimi.se2019.model.map.UnknownMapTypeException;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Eugenio Ostrovan
*/
public class TestDeck {
@Test
public void testDrawShouldFailEmptyDeck() {
List<Grabbable> list = new ArrayList<>();
Deck<Grabbable> testDeck = new Deck<Grabbable>(list);
try {
testDeck.draw();
fail("Exception was not raised");
}
catch (EmptyDeckException exception){
// Test Passed
}
}
@Test
public void testDrawShouldReturnItem() {
List<Grabbable> list = new ArrayList<>();
Grabbable elements;
Ammo element = new Ammo(1,2,3);
Grabbable returnedElement;
elements = element;
list.add(elements);
Deck<Grabbable> testDeck = new Deck<Grabbable>(list);
try {
returnedElement = testDeck.draw();
if (returnedElement.equals(element)){
// Test Passed
}
else {
fail("Draw should return exactly the same item passed in constructor");
}
}
catch (EmptyDeckException exception){
fail("Raised EmptyDeckException on a nonempty deck");
}
}
/**
* Assuming testDrawShouldReturnItem was successfully passed, otherwise
* this test may return false results
*/
@Test
public void testDiscardNoShuffle() {
List<Grabbable> list = new ArrayList<>();
Grabbable els1;
Grabbable els2;
Ammo element = new Ammo(1,2,3);
Grabbable returnedElement;
els1 = element;
els2 = element;
list.add(els1);
list.add(els2);
Deck<Grabbable> testDeck = new Deck<Grabbable>(list);
try {
returnedElement = testDeck.draw();
testDeck.discard(returnedElement);
if (returnedElement.equals(els1)){
if (testDeck.draw().equals(els2)){
// Test Passed
}
else {
fail("Deck Was Shuffled while it had still some elements available");
}
}
else if (returnedElement.equals(els2)){
if (testDeck.draw().equals(els1)){
// Test Passed
}
else {
fail("Deck Was Shuffled while it had still some elements available");
}
}
else {
fail("Something not insert in deck was returned");
}
}
catch (EmptyDeckException exception){
fail("Raised EmptyDeckException on a nonempty deck");
}
}
/**
* Assuming testDrawShouldReturnItem was successfully passed, otherwise
* this test may return false results
*/
@Test
public void testDiscardWithShuffle() {
List<Grabbable> list = new ArrayList<>();
Grabbable elements;
Ammo element = new Ammo(1,2,3);
Grabbable returnedElement1 = null;
Grabbable returnedElement2 = null;
elements = element;
list.add(elements);
Deck<Grabbable> testDeck = new Deck<Grabbable>(list);
try {
returnedElement1 = testDeck.draw();
testDeck.discard(returnedElement1);
try {
returnedElement2 = testDeck.draw();
} catch (EmptyDeckException exception) {
fail("You must shuffle the deck when it is empty");
}
if (returnedElement2.equals(elements)) {
// Test Passed
} else {
fail("Deck was not shuffled");
}
}
catch(EmptyDeckException exception){
fail("The deck is empty.");
}
}
@Test
public void testDraw() throws UnknownMapTypeException {
GameBoard gameBoard = new GameBoard(0);
Decks decks = gameBoard.getDecks();
assertTrue(decks != null);
Weapon weapon = decks.drawWeapon();
assertTrue(weapon != null);
AmmoTile ammoTile = decks.drawAmmoTile();
assertTrue(ammoTile != null);
PowerUpCard powerUpCard = decks.drawPowerUp();
assertTrue(powerUpCard != null);
}
}
|
package core;
import java.util.*;
public class Group extends Potato {
// Map of all members of group and each member's influence on group
private Set<Person> foundingMembers;
private HashMap<Person, Double> personInfluenceHashMap;
/** Constructs a core.Group at a Point location
* @param location: Point
*/
public Group(Coordinate location, List<Person> foundingMembers) {
super(location);
personInfluenceHashMap = new HashMap<>();
this.foundingMembers = new HashSet<>(foundingMembers);
}
/** Adds a core.Person to the personInfluenceHashMap, unless core.Potato is not an instance of core.Person
*
* @param potato
* @param influence
* @throws ClassCastException
*/
@Override
public void addInfluence(Potato potato, Double influence) {
try {
personInfluenceHashMap.put((Person)potato, influence);
} catch (ClassCastException e) {
System.out.println(e);
}
}
/** Checks to see whether founding members of two group are the same
*
* @param person1
* @param person2
* @returns true when founding members of two groups are the same
*/
public boolean sameFounders(Person person1, Person person2) {
List<Person> list = new ArrayList<>();
list.add(person1);
list.add(person2);
Set<Person> set = new HashSet<>(list);
return this.foundingMembers.equals(set);
}
/** Calculates the value off all traits within a group
*
* @param attributes
* @return average value for given trait for all members in the group
*/
public double calculateGroupTraits(PersonAttributes attributes) {
double traitValue = 0;
double count = 0;
for (Person p : personInfluenceHashMap.keySet()) {
traitValue += p.getTraitValue(attributes);
count++;
}
return traitValue / count;
}
/** Calculates the influence of a group by taking the average influences of all people in the group
*
* @return
*/
public double calculateInfluenceAvg(PersonAttributes attributes) {
double sum = 0;
double count = 0;
//finds the product of the attribute of a person and their influence on the group
for (Person p : personInfluenceHashMap.keySet()) {
sum += p.getTraitValue(attributes) * personInfluenceHashMap.get(p);
count++;
}
return sum / count;
}
/** Like calculateInfluenceAvg, except no averaging occurs
*
* @param attributes
* @return
*/
public double calculateInfluenceTot(PersonAttributes attributes) {
double sum = 0;
//finds the product of the attribute of a person and their influence on the group
for (Person p : personInfluenceHashMap.keySet()) {
sum += p.getTraitValue(attributes) * personInfluenceHashMap.get(p);
}
return sum;
}
public HashMap<Person, Double> getMap() {
return personInfluenceHashMap;
}
}
|
package com.airline.airline.airlinereseservation.pojos;
import java.util.Date;
public class BookingRequest {
public Long id;
public String username;
public String flightFrom;
public String flightTo;
public Date dateOfFlight;
public Long passengerId;
}
|
/*
* Copyright 2017 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.imtl.BlueKare.Activity.AR;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.ColorStateList;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.RectF;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.opengl.Matrix;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.curvsurf.fsweb.FindSurfaceRequester;
import com.curvsurf.fsweb.RequestForm;
import com.curvsurf.fsweb.ResponseForm;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.button.MaterialButtonToggleGroup;
import com.google.android.material.snackbar.Snackbar;
import com.google.ar.core.ArCoreApk;
import com.google.ar.core.Camera;
import com.google.ar.core.Config;
import com.google.ar.core.Frame;
import com.google.ar.core.PointCloud;
import com.google.ar.core.Session;
import com.google.ar.core.exceptions.CameraNotAvailableException;
import com.google.ar.core.exceptions.UnavailableApkTooOldException;
import com.google.ar.core.exceptions.UnavailableArcoreNotInstalledException;
import com.google.ar.core.exceptions.UnavailableDeviceNotCompatibleException;
import com.google.ar.core.exceptions.UnavailableSdkTooOldException;
import com.google.ar.core.exceptions.UnavailableUserDeclinedInstallationException;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.GeoPoint;
import com.hluhovskyi.camerabutton.CameraButton;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import edu.imtl.BlueKare.Activity.MainActivity;
import edu.imtl.BlueKare.R;
import edu.imtl.BlueKare.Renderer.BackgroundRenderer;
import edu.imtl.BlueKare.Renderer.ObjectRenderer;
import edu.imtl.BlueKare.Renderer.PointCloudRenderer;
import edu.imtl.BlueKare.Renderer.TempRendererSet.GLSupport;
import edu.imtl.BlueKare.Renderer.TempRendererSet.RendererForDebug;
import edu.imtl.BlueKare.Utils.MatrixUtil;
import edu.imtl.BlueKare.Utils.PointCollector;
import edu.imtl.BlueKare.Utils.PointUtil;
import edu.imtl.BlueKare.Utils.VectorCal;
import edu.imtl.BlueKare.helpers.CameraPermissionHelper;
import edu.imtl.BlueKare.helpers.DisplayRotationHelper;
import edu.imtl.BlueKare.helpers.FullScreenHelper;
import edu.imtl.BlueKare.tensorflow.Classifier;
import edu.imtl.BlueKare.tensorflow.YoloV4Classifier;
import static android.location.LocationManager.GPS_PROVIDER;
import static android.location.LocationManager.NETWORK_PROVIDER;
import static java.lang.Integer.parseInt;
import static java.lang.String.valueOf;
public class ArActivity extends AppCompatActivity implements GLSurfaceView.Renderer, SensorEventListener {
/*********************** 건들 일 없는 것 ***********************/
private static final String TAG = ArActivity.class.getSimpleName();
private GLSurfaceView surfaceView;
private String[] REQUIRED_PERMISSSIONS = {Manifest.permission.CAMERA};
private final int PERMISSION_REQUEST_CODE = 0; // PROTECTION_NORMAL
private DisplayRotationHelper displayRotationHelper;
private boolean installRequested;
private final BackgroundRenderer backgroundRenderer = new BackgroundRenderer();
private final ObjectRenderer virtualObject = new ObjectRenderer();
/*************************************************************/
/************************* AR Core 용 *************************/
private Session session;
private Frame frame;
/*************************************************************/
/************************* 인터페이스용 ************************/
private View arLayout;
private Button popup = null; /* <-- 이 버튼은 머임 ?*/
private Button exit = null;
private CameraButton recBtn = null;
private BottomSheet bottomSheet = null;
MaterialButtonToggleGroup toggle = null;
private Button dbhButton = null;
private Button heightButton = null;
private Button typeButton = null;
TextView dhbText = null;
TextView heightText = null;
TextView typeText = null;
PopupActivity popupActivity = null;
/*************************************************************/
/************************* point 처리 *************************/
private PointCloudRenderer pointCloudRenderer = new PointCloudRenderer();
private PointCollector collector = null;
/*************************************************************/
/************************* findSurf **************************/
private Thread httpTh;
private Thread treeRec;
private static final String REQUEST_URL = "https://developers.curvsurf.com/FindSurface/cylinder";
private static final String REQUEST_URL_Plane = "https://developers.curvsurf.com/FindSurface/plane"; // Plane searching server address
/*************************************************************/
/************************** 탐지된 물체 ************************/
private CylinderVars cylinderVars = null;
private Plane plane;
float curHeight = 0.0f;
float treeHeight = 0.0f;
/*************************************************************/
/************************** 최종결과 **************************/
String teamname = "teamname", username;
String landmark = "landmark";
String height = "";
String dbh = "";
String treeType = "";
/*************************************************************/
/************************* 보여주기용 **************************/
private int angle = -3; // treearium 글씨 돌아감
private float[] modelMatrix = new float[16];
RendererForDebug renderer = new RendererForDebug();
float[] treeBottom = null;
float[] treeTanTop = new float[4];
/*************************************************************/
/************************* bool 값 ***************************/
boolean isPlaneFound; /* findSurf 로 땅을 찾았음 */
// boolean isProcessDone; /* 모든게 끝나서 넘어갈 준비가 됨 */
boolean isCylinderDone = false;
boolean isHeightDone = false;
Mode currentMode = Mode.isFindingCylinder;
private boolean isRecording = false;
private boolean isStaticView = false;
private boolean drawSeedState = false;
public boolean heightForTheFirstTime = true;
/*************************************************************/
/************************* firebase **************************/
FirebaseAuth mFirebaseAuth;
FirebaseFirestore fstore;
String userID;
LocationManager locationManager;
String latitude, longitude;
public static GeoPoint locationA;
/*************************************************************/
/************************** 수종인식 ***************************/
private boolean treeRecog = false;
private boolean surfToBitmap = false;
private Classifier detector;
private Bitmap croppedBitmap = null;
public static final float MINIMUM_CONFIDENCE_TF_OD_API = 0.5f;
private enum DetectorMode {
TF_OD_API;
}
private void initBox() {
try {
detector =
YoloV4Classifier.create(
getAssets(),
TF_OD_API_MODEL_FILE,
TF_OD_API_LABELS_FILE,
TF_OD_API_IS_QUANTIZED);
} catch (final IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Classifier could not be initialized", Toast.LENGTH_SHORT).show();
finish();
}
}
private static final int TF_OD_API_INPUT_SIZE = 416;
private static final boolean TF_OD_API_IS_QUANTIZED = false;
private static final String TF_OD_API_MODEL_FILE = "yolov4-tiny-416-treearium.tflite";
private static final String TF_OD_API_LABELS_FILE = "file:///android_asset/name.txt";
private static final DetectorMode MODE = DetectorMode.TF_OD_API;
/*************************************************************/
/*************************** GYRO ****************************/
private static SensorManager mSensorManager;
private Sensor mGravity, mGeomagnetic, mLinearAcceleration;
float[] fGravity, fGeo, fLinear;
/*************************************************************/
// 1 : dbh, 2 : height, 3 : type
public void checkToggleType(int num) {
dbhButton.setBackgroundTintList(ColorStateList.valueOf(getResources().getColor(num == 1 ? R.color.filters_buttons : R.color.colorWhite)));
heightButton.setBackgroundTintList(ColorStateList.valueOf(getResources().getColor(num == 2 ? R.color.filters_buttons : R.color.colorWhite)));
typeButton.setBackgroundTintList(ColorStateList.valueOf(getResources().getColor(num == 3 ? R.color.filters_buttons : R.color.colorWhite)));
}
private static final int REQUEST_LOCATION = 1;
// Temporary matrix allocated here to reduce number of allocations for each frame.
private final float[] anchorMatrix = new float[16];
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_GRAVITY) {
fGravity = event.values;
}
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
fGeo = event.values;
}
if (event.sensor.getType() == Sensor.TYPE_LINEAR_ACCELERATION) {
fLinear = event.values;
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
// when touch after point_cloud gathering finished.
View.OnTouchListener surfaceViewTouchListener = new View.OnTouchListener() {
@SuppressLint({"ClickableViewAccessibility", "DefaultLocale"})
@Override
public boolean onTouch(View v, MotionEvent event) {
{
if (collector != null && collector.filterPoints != null) {
float tx = event.getX();
float ty = event.getY();
// ray 생성
float[] ray = screenPointToWorldRay(tx, ty, frame);
float[] rayOrigin = new float[]{ray[3], ray[4], ray[5]};
Camera camera = frame.getCamera();
float[] projmtx = new float[16];
camera.getProjectionMatrix(projmtx, 0, 0.1f, 100.0f);
final float unitRadius = (float) (0.8 / Math.max(projmtx[0], projmtx[5]));
drawSeedState = true;
FloatBuffer targetPoints = collector.filterPoints;
targetPoints.rewind();
// pick the point that is closest to the ray
int pickIndex = PointUtil.pickPoint(targetPoints, ray, rayOrigin);
float[] seedPoint = PointUtil.getSeedPoint();
float seedZLength = ray[0] * (seedPoint[0] - rayOrigin[0]) + ray[1] * (seedPoint[1] - rayOrigin[1]) + ray[2] * (seedPoint[2] - rayOrigin[2]);
seedZLength = Math.abs(seedZLength);
Log.d("UnitRadius__", Float.toString(unitRadius));
Log.d("seedZLength__", Float.toString(seedZLength));
float roiRadius = unitRadius * seedZLength / 2;
Log.d("UnitRadius", roiRadius + " " + /*RMS*/roiRadius * 0.2f + " " + roiRadius * 0.4f);
if (pickIndex >= 0 && !Thread.currentThread().isInterrupted()) {
switch (currentMode) {
// if user is trying to measure dbh
case isFindingCylinder:
// make a thread to find a cylinder
httpTh = new Thread(() -> {
isCylinderDone = false;
RequestForm rf = new RequestForm();
rf.setPointBufferDescription(targetPoints.capacity() / 4, 16, 0); //pointcount, pointstride, pointoffset
rf.setPointDataDescription(roiRadius * 0.2f, roiRadius * 0.4f); //accuracy, meanDistance
rf.setTargetROI(pickIndex, roiRadius);//seedIndex,touchRadius
rf.setAlgorithmParameter(RequestForm.SearchLevel.NORMAL, RequestForm.SearchLevel.NORMAL);//LatExt, RadExp
FindSurfaceRequester fsr = new FindSurfaceRequester(REQUEST_URL, true);
// Request Find Surface
try {
Log.d("CylinderFinder", "request");
targetPoints.rewind();
ResponseForm resp = fsr.request(rf, targetPoints);
if (resp != null && resp.isSuccess()) {
ResponseForm.CylinderParam param = resp.getParamAsCylider();
// Normal Vector should be [0, 1, 0]
float[] tmp = new float[]{param.b[0] - param.t[0], param.b[1] - param.t[1], param.b[2] - param.t[2]};
float dist = (float) Math.sqrt(tmp[0] * tmp[0] + tmp[1] * tmp[1] + tmp[2] * tmp[2]);
tmp[0] /= dist;
tmp[1] /= dist;
tmp[2] /= dist;
if (tmp[1] < 0) {
tmp[0] = -tmp[0];
tmp[1] = -tmp[1];
tmp[2] = -tmp[2];
Log.d("tmp", "바뀜");
}
// making a model_matrix based on cylinder's geometric information
modelMatrix[4] = tmp[0];
modelMatrix[5] = tmp[1];
modelMatrix[6] = tmp[2];
float[] centerPose = new float[]{(param.b[0] + param.t[0]) / 2, (param.b[1] + param.t[1]) / 2, (param.b[2] + param.t[2]) / 2};
modelMatrix[12] = centerPose[0];
modelMatrix[13] = centerPose[1];
modelMatrix[14] = centerPose[2];
float[] x = MatrixUtil.crossMatrix(modelMatrix[4], modelMatrix[5], modelMatrix[6],
rayOrigin[0], rayOrigin[1], rayOrigin[2]);
modelMatrix[0] = x[0];
modelMatrix[1] = x[1];
modelMatrix[2] = x[2];
float[] z = MatrixUtil.crossMatrix(modelMatrix[0], modelMatrix[1], modelMatrix[2],
modelMatrix[4], modelMatrix[5], modelMatrix[6]);
modelMatrix[8] = z[0];
modelMatrix[9] = z[1];
modelMatrix[10] = z[2];
Log.d("modelMatrix: ", modelMatrix[0] + " " + modelMatrix[4] + " " + modelMatrix[8] + " " + modelMatrix[12]);
Log.d("modelMatrix: ", modelMatrix[1] + " " + modelMatrix[5] + " " + modelMatrix[9] + " " + modelMatrix[13]);
Log.d("modelMatrix: ", modelMatrix[2] + " " + modelMatrix[6] + " " + modelMatrix[10] + " " + modelMatrix[14]);
Log.d("modelMatrix: ", modelMatrix[3] + " " + modelMatrix[7] + " " + modelMatrix[11] + " " + modelMatrix[15]);
cylinderVars = new CylinderVars(param.r, tmp, centerPose, param.b, param.t);
Log.d("CylinderFinder", "request success code: " + parseInt(valueOf(resp.getResultCode())) +
", Radius: " + param.r + ", Normal Vector: " + Arrays.toString(tmp) +
", RMS: " + resp.getRMS());
Log.d("Cylinder", valueOf(cylinderVars.getDbh()));
if (cylinderVars.getDbh() > 0.0f) {
isCylinderDone = true;
}
// if cylinder is built without any errors, bottom_sheet pops out
if (isCylinderDone) {
runOnUiThread(() -> {
Snackbar.make(arLayout, "Cylinder Found", Snackbar.LENGTH_LONG).show();
landmark = "일월저수지";
dbh = String.format("%.2f", cylinderVars.getDbh() * 200);
buildTextView();
currentMode = Mode.isFindingHeight;
if (heightForTheFirstTime) {
popupActivity.startDialog(R.layout.activity_popup2);
heightForTheFirstTime = false;
}
toggle.check(R.id.heightButton);
checkToggleType(2);
resetArActivity(false);
bottomSheet.setAlertText(1);
bottomSheet.setTeamName(teamname);
bottomSheet.setDbhSize(dbh);
bottomSheet.setTreeHeight(height);
bottomSheet.setTreeLandMark(landmark);
bottomSheet.setConfirmButton(fstore, locationA);
bottomSheet.setTreeType(ArActivity.this, treeType);
bottomSheet.show();
});
}
drawSeedState = false;
collector = null;
} else {
Log.d("CylinderFinder", "request fail");
}
} catch (Exception e) {
e.printStackTrace();
}
});
httpTh.start();
break;
// if user is trying to find height, and plane has found
case isFindingHeight:
// make thread like one above
httpTh = new Thread(() -> {
RequestForm rf = new RequestForm();
rf.setPointBufferDescription(targetPoints.capacity() / 4, 16, 0); //pointcount, pointstride, pointoffset
rf.setPointDataDescription(0.05f, 0.01f); //accuracy, meanDistance
rf.setTargetROI(pickIndex, 0.05f);//seedIndex,touchRadius
rf.setAlgorithmParameter(RequestForm.SearchLevel.NORMAL, RequestForm.SearchLevel.NORMAL);//LatExt, RadExp
FindSurfaceRequester fsr = new FindSurfaceRequester(REQUEST_URL_Plane, true);
// Request Find Surface
try {
Log.d("PlaneFinder", "request");
targetPoints.rewind();
ResponseForm resp = fsr.request(rf, targetPoints);
if (resp != null && resp.isSuccess()) {
ResponseForm.PlaneParam param = resp.getParamAsPlane();
plane = new Plane(
param.ll, param.lr, param.ur, param.ul, camera.getPose().getZAxis()
);
plane.normal[0] = 0.0f;
plane.normal[1] = 1.0f;
plane.normal[2] = 0.0f;
// using orthogonal formula
treeBottom = new float[4];
if (cylinderVars != null) {
float[] p1_to_p3 = new float[]{
plane.ll[0] - cylinderVars.top[0],
plane.ll[1] - cylinderVars.top[1],
plane.ll[2] - cylinderVars.top[2]
};
float[] p1_to_p2 = new float[]{
cylinderVars.bottom[0] - cylinderVars.top[0],
cylinderVars.bottom[1] - cylinderVars.top[1],
cylinderVars.bottom[2] - cylinderVars.top[2]
};
float n_p1_p3 = VectorCal.inner(plane.normal, p1_to_p3);
float n_p1_p2 = VectorCal.inner(plane.normal, p1_to_p2);
float const_u = n_p1_p3 / n_p1_p2;
float[] p = new float[]{
cylinderVars.top[0] + const_u * p1_to_p2[0],
cylinderVars.top[1] + const_u * p1_to_p2[1],
cylinderVars.top[2] + const_u * p1_to_p2[2],
};
treeBottom[0] = p[0];
treeBottom[1] = p[1];
treeBottom[2] = p[2];
treeBottom[3] = 1.0f;
// our new normal
float[] bot_to_top = new float[]{
cylinderVars.top[0] - cylinderVars.bottom[0],
cylinderVars.top[1] - cylinderVars.bottom[1],
cylinderVars.top[2] - cylinderVars.bottom[2]
};
plane.normal[0] = bot_to_top[0];
plane.normal[1] = bot_to_top[1];
plane.normal[2] = bot_to_top[2];
isPlaneFound = true;
} else {
// if user is trying to find height, and plane hasn't found
runOnUiThread(new Runnable() {
@Override
public void run() {
Snackbar.make(arLayout, "나무의 밑동을 터치", Snackbar.LENGTH_SHORT).show();
}
});
// doing same thing that has been done when finding cylinder
surfaceView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent motionEvent) {
float tx = motionEvent.getX();
float ty = motionEvent.getY();
float[] ray = screenPointToWorldRay(tx, ty, frame);
float a = plane.normal[0], b = plane.normal[1], c = plane.normal[2];
float d = -a * plane.ll[0] - b * plane.ll[1] - c * plane.ll[2];
float a1 = (a * a) + (b * b) + (c * c);
double planeConstant = java.lang.Math.sqrt(a1);
double distance = Math.abs((a * ray[0]) + (b * ray[1]) + (c * ray[2]) + d) / planeConstant;
float cosTheta = (float) Math.abs(
(a * ray[3] + b * ray[4] + c * ray[5])
/
(Math.sqrt(a1) * Math.sqrt(ray[3] * ray[3] + ray[4] * ray[4] + ray[5] * ray[5]))
);
double vecSize = distance / cosTheta;
treeBottom[0] = (float) (ray[0] + ray[3] * vecSize);
treeBottom[1] = (float) (ray[1] + ray[4] * vecSize);
treeBottom[2] = (float) (ray[2] + ray[5] * vecSize);
treeBottom[3] = 1.0f;
isPlaneFound = true;
return false;
}
});
}
} else {
Log.d("PlaneFinder", "request fail");
}
} catch (Exception e) {
e.printStackTrace();
}
});
httpTh.start();
break;
}
}
// when failed to find plane
ArActivity.this.runOnUiThread(() -> {
Snackbar.make(arLayout, "Please Wait...", Snackbar.LENGTH_LONG).show();
try {
httpTh.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
if (currentMode == Mode.isFindingHeight) {
Snackbar.make(arLayout, "Plane " + (isPlaneFound ? "Found" : "Not Found"), Snackbar.LENGTH_SHORT).show();
} else {
Snackbar.make(arLayout, "PickSeed Again", Snackbar.LENGTH_LONG).show();
}
});
}
}
return false;
}
};
// reset this activity
@SuppressLint("ClickableViewAccessibility")
public void resetArActivity(boolean needToDeleteCylinder) {
isPlaneFound = false;
isHeightDone = false;
if (needToDeleteCylinder) {
isCylinderDone = false;
cylinderVars = null;
}
collector = null;
surfaceView.setOnTouchListener(surfaceViewTouchListener);
}
// when create, initiate things that has to be initiated.
@SuppressLint({"ClickableViewAccessibility", "DefaultLocale"})
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ar);
Intent intent = getIntent();
ArrayList<String> recieve = intent.getStringArrayListExtra("treeInfo");
// 이런식으로 intentd에 스트링배열루다가 넘겨서 하나하나 그냥 스트링에 입력하면 댐
// if (recieve != null) {
// teamname = recieve.get(0);
// }
// initiating stuffs...
arLayout = findViewById(R.id.arLayout);
popup = (Button) findViewById(R.id.popup);
exit = (Button) findViewById(R.id.delete);
recBtn = (CameraButton) findViewById(R.id.recBtn);
surfaceView = (GLSurfaceView) findViewById(R.id.surfaceview);
displayRotationHelper = new DisplayRotationHelper(/*context=*/ this);
toggle = (MaterialButtonToggleGroup) findViewById(R.id.toggleGroup);
dbhButton = (Button) findViewById(R.id.dbhButton);
heightButton = (Button) findViewById(R.id.heightButton);
typeButton = (Button) findViewById(R.id.typeButton);
dhbText = (TextView) findViewById(R.id.dbhText);
heightText = (TextView) findViewById(R.id.heightText);
typeText = (TextView) findViewById(R.id.typeText);
dhbText.setWidth(dbhButton.getWidth());
heightText.setWidth(heightButton.getWidth());
typeText.setWidth(typeButton.getWidth());
// Set up renderer.
surfaceView.setPreserveEGLContextOnPause(true);
surfaceView.setEGLContextClientVersion(2);
surfaceView.setEGLConfigChooser(8, 8, 8, 8, 16, 0); // Alpha used for plane blending.
surfaceView.setRenderer(this);
surfaceView.setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);
surfaceView.setWillNotDraw(false);
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mGravity = mSensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY);
mGeomagnetic = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
mLinearAcceleration = mSensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);
modelMatrix[3] = 0.0f;
modelMatrix[7] = 0.0f;
modelMatrix[11] = 0.0f;
modelMatrix[15] = 1.0f;
//firebase
mFirebaseAuth = FirebaseAuth.getInstance();
fstore = FirebaseFirestore.getInstance();
userID = mFirebaseAuth.getCurrentUser().getUid();
fstore.collection("users").document(userID).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
teamname = (String) document.getData().get("Team");
//teamname = (String) document.getData().get("fName");
//document.getString("Team")
if (document.exists()) {
Log.d(TAG, "DocumentSnapshot data: " + document.getData());
} else {
Log.d(TAG, "No such document");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
//Intent intent = new Intent(ArActivity.this, PopupActivity.class);
//startActivityForResult(intent, 1);
popupActivity = new PopupActivity(ArActivity.this);
popupActivity.startDialog(R.layout.activity_popup);
installRequested = false;
LocationManager nManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(
ArActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
ArActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
} else {
Location locationGPS = nManager.getLastKnownLocation(GPS_PROVIDER);
if (locationGPS != null) {
double lat = locationGPS.getLatitude();
double longi = locationGPS.getLongitude();
//location = new GeoPoint(lat, longi);
} else {
Toast.makeText(this, "Unable to find location.", Toast.LENGTH_SHORT).show();
}
}
GPSSListener gpsListener = new GPSSListener();
long minTime = 1000;
float minDistance = 0;
nManager.requestLocationUpdates(NETWORK_PROVIDER, minTime, minDistance, gpsListener);
nManager.requestLocationUpdates(GPS_PROVIDER, minTime, minDistance, gpsListener);
buildTextView();
checkToggleType(1);
// initiating the 3 buttons that is on top of this activity
toggle.check(R.id.dbhButton);
toggle.addOnButtonCheckedListener((group, checkedID, isChecked) -> {
if (isChecked) {
switch (checkedID) {
// change current mode and reset
case R.id.dbhButton:
currentMode = Mode.isFindingCylinder;
resetArActivity(true);
checkToggleType(1);
break;
case R.id.heightButton:
currentMode = Mode.isFindingHeight;
if (heightForTheFirstTime) {
popupActivity.startDialog(R.layout.activity_popup2);
heightForTheFirstTime = false;
}
resetArActivity(false);
checkToggleType(2);
break;
case R.id.typeButton:
checkToggleType(3);
break;
}
} else {
if (group.getCheckedButtonId() == -1) {
group.check(checkedID);
}
}
});
popup.setOnClickListener(v -> {
popupActivity.startDialog(currentMode == Mode.isFindingCylinder ? R.layout.activity_popup : R.layout.activity_popup2);
});
exit.setOnClickListener(v -> {
startActivity(new Intent(ArActivity.this, MainActivity.class));
finish();
});
bottomSheet = new BottomSheet();
bottomSheet.init(ArActivity.this, new BottomSheetDialog(
ArActivity.this, R.style.BottomSheetDialogTheme
));
// initiating record button
recBtn.setOnClickListener(v -> {
double distance = 0.1f;
// to give bottom_sheet information
if (isPlaneFound) {
treeHeight = curHeight;
isHeightDone = true;
runOnUiThread(() -> {
Snackbar.make(arLayout, "Height Found", Snackbar.LENGTH_LONG).show();
landmark = "일월저수지";
height = String.format("%.2f", treeHeight);
buildTextView();
toggle.check(R.id.typeButton);
});
// 수종 인식: GLSurfaceView to Bitmap
surfToBitmap = true;
// test.setImageBitmap(croppedBitmap); // 디버깅용
// 인식 시작
treeRec = new Thread(() -> {
while (surfToBitmap) {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
final List<Classifier.Recognition> results = detector.recognizeImage(croppedBitmap);
final List<Classifier.Recognition> mappedRecognitions = new LinkedList<>();
for (final Classifier.Recognition result : results) {
final RectF location = result.getLocation();
if (location != null && result.getConfidence() >= MINIMUM_CONFIDENCE_TF_OD_API) {
result.setLocation(location);
mappedRecognitions.add(result);
}
}
if (mappedRecognitions.size() > 0) {
Log.d("treeRecognization", "success");
Log.d("treeRecognization", mappedRecognitions.get(0).getTitle());
treeType = mappedRecognitions.get(0).getTitle();
switch (treeType) {
case "Maple":
treeType = "단풍";
break;
case "Ginkgo":
treeType = "은행";
break;
default:
treeType = "기타";
break;
}
buildTextView();
} else {
Log.d("treeRecognization", "fail");
}
treeRecog = false;
});
treeRec.start();
////////////////////////////////
if (isHeightDone) {
// setting bottom_sheet information, and make it pop
runOnUiThread(() -> {
try {
treeRec.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
bottomSheet.setAlertText(2);
bottomSheet.setTeamName(teamname);
bottomSheet.setDbhSize(dbh);
bottomSheet.setTreeHeight(height);
bottomSheet.setTreeLandMark(landmark);
bottomSheet.setConfirmButton(fstore, locationA);
bottomSheet.setTreeType(this, treeType);
bottomSheet.show();
});
}
} else {
// when pressed again, turn of recording mode
isRecording = !isRecording;
if (isRecording) {
collector = new PointCollector();
Snackbar.make(arLayout, "Collecting", Snackbar.LENGTH_LONG).show();
isStaticView = false;
} else {
(new Thread(() -> {
if (ArActivity.this.collector != null) {
ArActivity.this.collector.filterPoints = ArActivity.this.collector.doFilter();
ArActivity.this.surfaceView.queueEvent(() -> {
pointCloudRenderer.update(ArActivity.this.collector.filterPoints);
isStaticView = true;
});
ArActivity.this.runOnUiThread(() -> {
Snackbar.make(arLayout, "Collecting Finished", Snackbar.LENGTH_LONG).show();
});
}
})).start();
}
}
});
resetArActivity(true);
surfaceView.setOnTouchListener(surfaceViewTouchListener);
// require permissions
for (String permission : REQUIRED_PERMISSSIONS) {
if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, REQUIRED_PERMISSSIONS, PERMISSION_REQUEST_CODE);
}
}
initBox();
}
void buildTextView() {
dhbText.setText(dbh);
heightText.setText(height);
typeText.setText(treeType);
}
@Override
public void onConfigurationChanged(@NonNull Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
@Override
protected void onResume() {
// (nothing special.. only things that needs to be done)
super.onResume();
mSensorManager.registerListener(this, mGravity, SensorManager.SENSOR_DELAY_UI);
mSensorManager.registerListener(this, mGeomagnetic, SensorManager.SENSOR_DELAY_UI);
mSensorManager.registerListener(this, mLinearAcceleration, SensorManager.SENSOR_DELAY_UI);
if (session == null) {
Exception exception = null;
String message = null;
try {
switch (ArCoreApk.getInstance().requestInstall(this, !installRequested)) {
case INSTALL_REQUESTED:
installRequested = true;
return;
case INSTALLED:
break;
}
// ARCore requires camera permissions to operate. If we did not yet obtain runtime
// permission on Android M and above, now is a good time to ask the user for it.
if (!CameraPermissionHelper.hasCameraPermission(this)) {
CameraPermissionHelper.requestCameraPermission(this);
return;
}
// Create the session.
session = new Session(this);
// ARCore 세부 설정
Config config = new Config(session);
config.setLightEstimationMode(Config.LightEstimationMode.DISABLED);
config.setPlaneFindingMode(Config.PlaneFindingMode.DISABLED);
config.setFocusMode(Config.FocusMode.AUTO);
session.configure(config); // Update Configuration
} catch (UnavailableArcoreNotInstalledException
| UnavailableUserDeclinedInstallationException e) {
message = "Please install ARCore";
exception = e;
} catch (UnavailableApkTooOldException e) {
message = "Please update ARCore";
exception = e;
} catch (UnavailableSdkTooOldException e) {
message = "Please update this app";
exception = e;
} catch (UnavailableDeviceNotCompatibleException e) {
message = "This device does not support AR";
exception = e;
} catch (Exception e) {
message = "Failed to create AR session";
exception = e;
}
if (message != null) {
//messageSnackbarHelper.showError(this, message);
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
Log.e(TAG, "Exception creating session", exception);
return;
}
}
// Note that order matters - see the note in onPause(), the reverse applies here.
try {
session.resume();
} catch (CameraNotAvailableException e) {
//messageSnackbarHelper.showError(this, "Camera not available. Try restarting the app.");
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
session = null;
return;
}
surfaceView.onResume();
displayRotationHelper.onResume();
}
@Override
public void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
if (session != null) {
// Note that the order matters - GLSurfaceView is paused first so that it does not try
// to query the session. If Session is paused before GLSurfaceView, GLSurfaceView may
// still call session.update() and get a SessionPausedException.
displayRotationHelper.onPause();
surfaceView.onPause();
session.pause();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] results) {
super.onRequestPermissionsResult(requestCode, permissions, results);
if (!CameraPermissionHelper.hasCameraPermission(this)) {
Toast.makeText(this, "Camera permission is needed to run this application", Toast.LENGTH_LONG)
.show();
if (!CameraPermissionHelper.shouldShowRequestPermissionRationale(this)) {
// Permission denied with checking "Do not ask again".
CameraPermissionHelper.launchPermissionSettings(this);
}
finish();
}
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
FullScreenHelper.setFullScreenOnWindowFocusChanged(this, hasFocus);
}
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
GLES20.glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
// Prepare the rendering objects. This involves reading shaders, so may throw an IOException.
try {
// Create the texture and pass it to ARCore session to be filled during update().
backgroundRenderer.createOnGlThread(/*context=*/ this);
pointCloudRenderer.createOnGlThread(/*context=*/ this);
virtualObject.createOnGlThread(/*context=*/ this, "models/cylinder_r.obj", "models/treearium.png");
virtualObject.setMaterialProperties(0.0f, 2.0f, 0.5f, 6.0f);
virtualObject.setBlendMode(ObjectRenderer.BlendMode.AlphaBlending);
renderer.createOnGlThread(this);
} catch (IOException e) {
Log.e(TAG, "Failed to read an asset file", e);
}
}
@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
displayRotationHelper.onSurfaceChanged(width, height);
GLES20.glViewport(0, 0, width, height);
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onDrawFrame(GL10 gl) {
// Clear screen to notify driver it should not load any pixels from previous frame.
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);
if (session == null) {
return;
}
// Notify ARCore session that the view size changed so that the perspective matrix and
// the video background can be properly adjusted.
displayRotationHelper.updateSessionIfNeeded(session);
try {// Obtain the current frame from ARSession. When the configuration is set to
// UpdateMode.BLOCKING (it is by default), this will throttle the rendering to the
// camera framerate.
session.setCameraTextureName(backgroundRenderer.getTextureId());
frame = session.update();
Camera camera = frame.getCamera();
// If frame is ready, render camera preview image to the GL surface.
backgroundRenderer.draw(frame);
if (pointCloudRenderer == null) return;
// Get projection matrix.
// Get camera matrix and draw.
// Get multiple of proj matrix and view matrix
float[] projmtx = new float[16];
float[] viewmtx = new float[16];
float[] vpMatrix = new float[16];
camera.getProjectionMatrix(projmtx, 0, 0.1f, 100.0f);
camera.getViewMatrix(viewmtx, 0);
Matrix.multiplyMM(vpMatrix, 0, projmtx, 0, viewmtx, 0);
// Compute lighting from average intensity of the image.
// The first three components are color scaling factors.
// The last one is the average pixel intensity in gamma space.
final float[] colorCorrectionRgba = new float[4];
frame.getLightEstimate().getColorCorrection(colorCorrectionRgba, 0);
// draw gathered point_clouds while recording
if (!isStaticView) {
PointUtil.resetSeedPoint();
try (PointCloud pointCloud = frame.acquirePointCloud()) {
if (isRecording && collector != null) {
collector.doCollect(pointCloud);
}
pointCloudRenderer.update(pointCloud);
pointCloudRenderer.draw(viewmtx, projmtx);
}
} else {
pointCloudRenderer.draw(viewmtx, projmtx);
if (drawSeedState && PointUtil.getSeedPoint() != null) {
float[] seedPoint = PointUtil.getSeedPoint();
pointCloudRenderer.draw_seedPoint(vpMatrix, seedPoint);
}
}
// when cylinder is found, draw small cylinder
if (isCylinderDone) {
if (cylinderVars != null) {
GLES20.glEnable(GLES20.GL_CULL_FACE);
//Matrix.setIdentityM(modelMatrix, 0);
Matrix.rotateM(modelMatrix, 0, angle, 0, 1, 0);
//angle++;
virtualObject.updateModelMatrix(modelMatrix, cylinderVars.getDbh(), 0.05f, cylinderVars.getDbh());
virtualObject.draw(viewmtx, projmtx, colorCorrectionRgba);
GLES20.glDisable(GLES20.GL_CULL_FACE);
}
}
// when finding height, draw a line based on phone's angle
if (currentMode == Mode.isFindingHeight) {
if (isPlaneFound) {
if (treeBottom != null && !isHeightDone) {
float width = this.surfaceView.getMeasuredWidth();
float height = this.surfaceView.getMeasuredHeight();
float[] ray = screenPointToWorldRay(width / 2.0f, height / 2.0f, frame);
float[] rayVec = new float[]{ray[3], ray[4], ray[5]};
float[] bigPlaneVec = VectorCal.outer(rayVec, VectorCal.outer(plane.normal, rayVec));
// applying orthogonal formula
float u = ((bigPlaneVec[0] * (ray[0] - treeBottom[0])) + (bigPlaneVec[1] * (ray[1] - treeBottom[1])) + (bigPlaneVec[2] * (ray[2] - treeBottom[2])))
/
((bigPlaneVec[0] * plane.normal[0]) + (bigPlaneVec[1] * plane.normal[1]) + (bigPlaneVec[2] * plane.normal[2]));
curHeight = (float) java.lang.Math.sqrt(
u * plane.normal[0] * u * plane.normal[0]
+ u * plane.normal[1] * u * plane.normal[1]
+ u * plane.normal[2] * u * plane.normal[2]
);
treeTanTop = new float[]{
treeBottom[0] + u * plane.normal[0], treeBottom[1] + u * plane.normal[1], treeBottom[2] + u * plane.normal[2], 1.0f
};
}
float[] tmp = new float[]{
treeBottom[0], treeBottom[1], treeBottom[2], 1.0f,
treeTanTop[0], treeTanTop[1], treeTanTop[2], 1.0f
};
renderer.pointDraw(GLSupport.makeFloatBuffer(treeBottom), vpMatrix, Color.valueOf(Color.CYAN), 30.0f);
renderer.lineDraw(GLSupport.makeFloatBuffer(tmp), vpMatrix, Color.valueOf(Color.RED), 30.0f);
}
}
} catch (Throwable t) {
// Avoid crashing the application due to unhandled exceptions.
Log.e(TAG, "Exception on the OpenGL thread", t);
}
// 수종 인식: GLSurfaceView to croppedBitmap
if (surfToBitmap) {
int width = surfaceView.getWidth();
int height = surfaceView.getHeight();
int screenshotSize = width * height;
ByteBuffer bb = ByteBuffer.allocateDirect(screenshotSize * 4);
bb.order(ByteOrder.nativeOrder());
gl.glReadPixels(0, 0, width, height, GL10.GL_RGBA,
GL10.GL_UNSIGNED_BYTE, bb);
int pixelsBuffer[] = new int[screenshotSize];
bb.asIntBuffer().get(pixelsBuffer);
bb = null;
croppedBitmap = Bitmap.createBitmap(width, height,
Bitmap.Config.RGB_565);
croppedBitmap.setPixels(pixelsBuffer, screenshotSize - width, -width, 0,
0, width, height);
pixelsBuffer = null;
short sBuffer[] = new short[screenshotSize];
ShortBuffer sb = ShortBuffer.wrap(sBuffer);
croppedBitmap.copyPixelsToBuffer(sb);
// Making created bitmap (from OpenGL points) compatible with
// Android bitmap
for (int i = 0; i < screenshotSize; ++i) {
short v = sBuffer[i];
sBuffer[i] = (short) (((v & 0x1f) << 11) | (v & 0x7e0) | ((v & 0xf800) >> 11));
}
sb.rewind();
croppedBitmap.copyPixelsFromBuffer(sb);
// resize
croppedBitmap = Bitmap.createScaledBitmap(croppedBitmap,
TF_OD_API_INPUT_SIZE, TF_OD_API_INPUT_SIZE, true);
surfToBitmap = false;
treeRecog = true;
}
}
// not used.
public static double haversine(double lat1, double lon1, double lat2, double lon2) {
final double R = 6372.8; // In kilometers
double dLat = Math.toRadians(lat2 - lat1);
double dLon = Math.toRadians(lon2 - lon1);
lat1 = Math.toRadians(lat1);
lat2 = Math.toRadians(lat2);
double a = Math.pow(Math.sin(dLat / 2), 2) + Math.pow(Math.sin(dLon / 2), 2) * Math.cos(lat1) * Math.cos(lat2);
double c = 2 * Math.asin(Math.sqrt(a));
return R * c;
}
float[] screenPointToWorldRay(float xPx, float yPx, Frame frame) {
// ray[0~2] : camera pose
// ray[3~5] : Unit vector of ray
float[] ray_clip = new float[4];
ray_clip[0] = 2.0f * xPx / surfaceView.getMeasuredWidth() - 1.0f;
// +y is up (android UI Y is down):
ray_clip[1] = 1.0f - 2.0f * yPx / surfaceView.getMeasuredHeight();
ray_clip[2] = -1.0f; // +z is forwards (remember clip, not camera)
ray_clip[3] = 1.0f; // w (homogenous coordinates)
// multiply inverse proj, inverse view, to get world coordinate
float[] ProMatrices = new float[32]; // {proj, inverse proj}
frame.getCamera().getProjectionMatrix(ProMatrices, 0, 0.1f, 100.0f);
Matrix.invertM(ProMatrices, 16, ProMatrices, 0);
float[] ray_eye = new float[4];
Matrix.multiplyMV(ray_eye, 0, ProMatrices, 16, ray_clip, 0);
ray_eye[2] = -1.0f;
ray_eye[3] = 0.0f;
float[] out = new float[6];
float[] ray_wor = new float[4];
float[] ViewMatrices = new float[32];
frame.getCamera().getViewMatrix(ViewMatrices, 0);
Matrix.invertM(ViewMatrices, 16, ViewMatrices, 0);
Matrix.multiplyMV(ray_wor, 0, ViewMatrices, 16, ray_eye, 0);
float size = (float) Math.sqrt(ray_wor[0] * ray_wor[0] + ray_wor[1] * ray_wor[1] + ray_wor[2] * ray_wor[2]);
out[3] = ray_wor[0] / size;
out[4] = ray_wor[1] / size;
out[5] = ray_wor[2] / size;
out[0] = frame.getCamera().getPose().tx();
out[1] = frame.getCamera().getPose().ty();
out[2] = frame.getCamera().getPose().tz();
return out;
}
private class GPSSListener implements LocationListener {
@Override
public void onLocationChanged(Location location2) {
Double latitude = location2.getLatitude();
Double longitude = location2.getLongitude();
//LatLng onLop=new LatLng(latitude,longitude);
locationA = new GeoPoint(latitude, longitude);
String message = "내 위치 -> Latitude : " + latitude + "\nLongitude:" + longitude;
Log.d("Map", message);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
}
}
class Plane {
public float[] ll, lr, ul, ur;
public float[] normal = null;
public Plane(float[] ll, float[] lr, float[] ur, float[] ul, float[] z_dir) {
this.ll = ll;
this.lr = lr;
this.ul = ul;
this.ur = ur;
normal = new float[3];
this.calNormal();
this.checkNormal(z_dir);
}
protected void calNormal() {
// Calculate normal vector
float[] vec1 = {lr[0] - ll[0], lr[1] - ll[1], lr[2] - ll[2]};
float[] vec2 = {ul[0] - ll[0], ul[1] - ll[1], ul[2] - ll[2]};
this.normal = VectorCal.outer(vec1, vec2);
VectorCal.normalize(this.normal);
}
public void checkNormal(float[] z_dir) {
if (z_dir[0] * normal[0] + z_dir[1] * normal[1] + z_dir[2] * normal[2] >= 0) return;
normal[0] = -normal[0];
normal[1] = -normal[1];
normal[2] = -normal[2];
}
}
enum Mode {
isFindingCylinder,
isFindingHeight
}
|
package com.samal.springaop;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.function.Supplier;
public interface BeanBSupplier extends Supplier<BeanB> {
// @Autowired
// default void register(BeanA beanA) {
// System.out.println("via setter: A >> SupB" + getIndex());
// System.out.println("SupB" + getIndex() + ": " + this.getClass().getSimpleName());
// beanA.register(getIndex(), this);
// }
int getIndex();
}
|
package com.clay.claykey.model;
import android.os.Bundle;
import com.clay.claykey.constant.BundleConstant;
import com.clay.claykey.constant.ParseConstants;
import com.clay.claykey.model.listener.ServiceFinishedListener;
import com.clay.claykey.object.dto.LoginResult;
import com.clay.claykey.object.parse.Door;
import com.parse.LogInCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseRelation;
import com.parse.ParseUser;
import java.util.List;
/**
* Created by Mina Fayek on 1/15/2016.
*/
public class LoginService extends BaseService {
public LoginService(ServiceFinishedListener serviceFinishedListener) {
super(serviceFinishedListener);
}
@Override
public void startService(Bundle b) {
if (b != null) {
String username = b.getString(BundleConstant.LOGIN_USERNAME);
String password = b.getString(BundleConstant.LOGIN_PASSWORD);
ParseUser.logInInBackground(username, password, new LogInCallback() {
@Override
public void done(ParseUser parseUser, ParseException e) {
LoginResult result = new LoginResult();
result.setUser(parseUser);
serviceFinishedListener.onServiceFinished(result);
}
});
}
}
}
|
package at.jku.isse.ecco.webdev.test;
import at.jku.isse.ecco.webdev.HelloWorldApplication;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.IOException;
public class WebDevTest {
@Test(groups = {"integration", "webdev"})
public void WebDev_Test() {
HelloWorldApplication.main(new String[]{});
}
@BeforeTest(alwaysRun = true)
public void beforeTest() {
System.out.println("BEFORE");
}
@AfterTest(alwaysRun = true)
public void afterTest() {
System.out.println("AFTER");
}
}
|
package io.github.liuzm.distribute.common;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* @author lxyq
*/
public class Message implements Serializable{
/**
*
*/
private static final long serialVersionUID = -3549947862637908997L;
private String name;
private String category;
private String price;
private String rating;
private String url;
private String image;
private Set<String> related;
public Message() {
}
public Message(String name, String category, String price, String rating, String url, String image) {
this.name = name;
this.category = category;
this.price = price;
this.rating = rating;
this.url = url;
this.image = extractImage(image);
this.related = new HashSet<String>();
}
public String getName() {
return name;
}
public String getCategory() {
return category;
}
public String getPrice() {
return price;
}
public String getRating() {
return rating;
}
public String getUrl() {
return url;
}
/*
* don't use directly, just to please object mapper
*/
public Set<String> getRelated() {
return related;
}
public void addRelated(Set<String> related) {
for (Iterator<String> iterator = related.iterator(); iterator.hasNext();) {
this.addRelated(iterator.next());
}
}
public void addRelated(String related) {
this.related.add(extractUrl(related));
}
public void setName(String name) {
this.name = name;
}
public void setCategory(String category) {
this.category = category;
}
public void setUrl(String url) {
this.url = url;
}
public String getImage() {
return image;
}
@Override
public int hashCode() {
return this.url.hashCode();
}
@Override
public boolean equals(Object arg) {
if (arg != null && arg instanceof Message) {
if (((Message) arg).url.equals(this.url)) {
return true;
} else {
return false;
}
}
return super.equals(arg);
}
@Override
public String toString() {
return String.format("name: %s category: %s image: %s url: %s", name, category, image, url);
}
public static String extractCode(String urlParameter) {
int l = urlParameter.lastIndexOf("/dp/");
if (l >= 0) {
// create new to release big
return new String(urlParameter.substring(l + 4));
}
return null;
}
public static String extractUrl(String urlParameter) {
int l = urlParameter.indexOf("com/");
if (l > 0) {
// create new to release big
return new String(urlParameter.substring(l + 4));
}
return null;
}
public static String extractImage(String imageUrl) {
int l = imageUrl.indexOf("/images/");
if (l > 0) {
// create new to release big
return new String(imageUrl.substring(l + 8));
}
return null;
}
}
|
package commands;
import interfaces.Command;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import org.apache.log4j.Logger;
import output.DisplaySystem;
/**
* @author Ksiona
* CommandProcessor
*/
public class CommandProcessor {
private static final String INVITATION_TO_PRINT = "> ";
private static final String EMPTY_STRING = "";
private static final String KEY_COMMAND_END = "/";
private static final Logger log = Logger.getLogger(CommandProcessor.class);
private List<CommandLoader<?>> commands;
private static DisplaySystem ds;
private static String consoleEncoding;
private Scanner scanner;
private CommandParser parser;
private HelpCommand hp;
private CommandProcessor() {
this.ds = DisplaySystem.getInstance();
commands = new ArrayList<>();
commands.add(new CommandLoader<>(TrackCommand.class));
commands.add(new CommandLoader<>(GenreCommand.class));
commands.add(new CommandLoader<>(SearchCommand.class));
commands.add(new CommandLoader<>(ExitCommand.class));
this.hp = new HelpCommand(commands);
this.scanner = new Scanner(System.in, consoleEncoding);
}
class CommandLoader<T extends Command> {
Class<? extends T> commandClass;
public CommandLoader(Class<? extends T> commandClass) {
this.commandClass = commandClass;
}
@SuppressWarnings("unchecked")
T getInstance() {
T instance = null;
try {
Method method = commandClass.getMethod("getInstance", null);
instance = (T) method.invoke(method, null);
} catch (IllegalAccessException | IllegalArgumentException
| InvocationTargetException | NoSuchMethodException | SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//T instance = commandClass.newInstance();
return instance;
}
}
private static class SingletonHolder {
private static final CommandProcessor INSTANCE = new CommandProcessor();
}
public static CommandProcessor getInstance(String consoleEncoding) {
CommandProcessor.consoleEncoding = consoleEncoding;
return SingletonHolder.INSTANCE;
}
public void execute() {
try{
boolean result = true;
do {
boolean isFinded = false;
ds.DisplaySymbols(INVITATION_TO_PRINT);
String fullCommand = EMPTY_STRING;
String line;
do {
line = scanner.nextLine();
fullCommand += line;
}while (!line.contains(KEY_COMMAND_END));
if (fullCommand == null || EMPTY_STRING.equals(fullCommand)) {
continue;
}
parser = new CommandParser(fullCommand);
if (parser.command == null || EMPTY_STRING.equals(parser.command)) {
continue;
}
if (parser.command.equalsIgnoreCase(hp.getName())){
result = hp.execute(parser.args);
isFinded = true;
}else
for(CommandLoader<?> cl:commands){
Command cmd = (Command)cl.getInstance();
if(cmd.getName().equalsIgnoreCase(parser.command)){
result = cmd.execute(parser.args);
isFinded = true;
break;
}
}
if(!isFinded)
ds.DisplayMessage(Command.COMMAND_NOT_FOUND);
} while (result);
}catch(RuntimeException e){
ds.DisplayError(e);
log.warn(e.getMessage(), e);
}finally{
scanner.close();
}
}
}
|
package com.giwook.algorithm.lesson4_countingElements;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
/**
*
* @author 93Hong on 2020-09-06
*
*/
public class PermCheck {
public int solution(int[] A) {
// write your code in Java SE 8
Set<Integer> integers = new HashSet<>();
for (int i : A) {
if (i > A.length)
return 0;
if (integers.contains(i))
return 0;
integers.add(i);
}
return 1;
}
}
|
package com.example.thetravlendar;
import android.app.SearchManager;
import android.content.ContentValues;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import static com.example.thetravlendar.Utils.Utility.hideKeyboard;
public class AddEventActivity extends AppCompatActivity implements
DatePickerFragment.DateDialogListener, StartTimePickerFragment.TimeDialogListener,
EndTimePickerFragment.TimeDialogListener, ModeOfTransportationFragment.MODDialogListener {
private static final String TAG = "AddToDatabase";
private static final String REQUIRED = "Required";
private String Date;
private static final String DIALOG_TIME = "AddEventActivity.TimeDialog";
private static final String DIALOG_DATE = "AddEventActivity.DateDialog";
private static final String DIALOG_MOD = "AddEventActivity.";
private String ename;
LinearLayout layout;
Button buttonSaveEvent;
EditText editEventName;
EditText editEventDate;
EditText editEventStart;
EditText editEventEnd;
EditText editEventAddress;
EditText editEventCity;
EditText editEventState;
EditText editEventZipCode;
EditText editEventMOD;
EditText editEventNote;
EditText editEventLocation;
ImageView imageAddLocation;
private DatabaseReference mUserRef, mEventRef;
private FirebaseAuth mAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("testing", "addNote - oncreate");
setContentView(R.layout.activity_add_event);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
buttonSaveEvent = findViewById(R.id.addEventButton);
editEventName = findViewById(R.id.event_name);
editEventDate = findViewById(R.id.event_date);
editEventStart = findViewById(R.id.event_start_time);
editEventEnd = findViewById(R.id.event_end_time);
editEventAddress = findViewById(R.id.event_address);
editEventCity = findViewById(R.id.event_city);
editEventState = findViewById(R.id.event_state);
editEventZipCode = findViewById(R.id.event_zip_code);
editEventMOD = findViewById(R.id.event_mod);
editEventNote = findViewById(R.id.event_note);
editEventLocation = findViewById(R.id.event_location);
imageAddLocation = findViewById(R.id.event_add_location);
mAuth = FirebaseAuth.getInstance();
mUserRef = FirebaseDatabase.getInstance().getReference();
mEventRef = FirebaseDatabase.getInstance().getReference().child("events");
layout = (LinearLayout) findViewById(R.id.act_add_event);
//accepts the date from the calendar activity and sets date text field
Intent intent = getIntent();
Date = intent.getExtras().getString("sendingDate");
editEventDate.setText(Date);
toolbar.setNavigationIcon(R.drawable.ic_arrow_back_black_24dp);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),CalendarActivity.class));
}
});
layout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
hideKeyboard(v,getApplicationContext());
return false;
}
});
editEventDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DatePickerFragment dialog = new DatePickerFragment();
dialog.show(getSupportFragmentManager(), DIALOG_DATE);
}
});
editEventStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
StartTimePickerFragment dialog = new StartTimePickerFragment();
dialog.show(getSupportFragmentManager(),DIALOG_TIME);
}
});
editEventEnd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EndTimePickerFragment dialog = new EndTimePickerFragment();
dialog.show(getSupportFragmentManager(),DIALOG_TIME);
}
});
editEventMOD.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ModeOfTransportationFragment dialog = new ModeOfTransportationFragment();
dialog.show(getSupportFragmentManager(), DIALOG_MOD);
}
});
buttonSaveEvent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
submitEvent();
}
});
editEventLocation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
imageAddLocation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
/*displayToast(getString(R.string.Test1));
Intent myIntent = new Intent(AddEventActivity.this,MapsActivity.class);
startActivity(myIntent);*/
}
});
// For Maps Activity
Bundle extras = getIntent().getExtras();
if (extras != null) {
String street = extras.getString("street");
String city = extras.getString("city");
String state = extras.getString("state");
String zip = extras.getString("zip");
String name = extras.getString("name");
String travel = extras.getString("time");
//The key argument here must match that used in the other activity
editEventAddress.setText(street);
editEventCity.setText(city);
editEventState.setText(state);
editEventZipCode.setText(zip);
editEventLocation.setText(name);
editEventNote.setText(travel);
}
}
public void displayToast(String message) {
Toast.makeText(getApplicationContext(), message,
Toast.LENGTH_SHORT).show();
}
private void submitEvent() {
final String name = editEventName.getText().toString();
final String date = editEventDate.getText().toString();
System.out.println("Date = " + date);
final String startTime = editEventStart.getText().toString();
final String endTime = editEventEnd.getText().toString();
final String address = editEventAddress.getText().toString();
final String city = editEventCity.getText().toString();
final String state = editEventState.getText().toString();
final String zip = editEventZipCode.getText().toString();
final String mod = editEventMOD.getText().toString();
final String note = editEventNote.getText().toString();
final String location = editEventLocation.getText().toString();
//Query query = mEventRef.orderByChild("start_time").
/*Calendar calfordDate = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMM-yyyy");
String saveCurrentDate = currentDate.format(calfordDate.getTime());
//Calendar calfordTime = Calendar.getInstance();
SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm");
String saveCurrentTime = currentTime.format(calfordDate.getTime());
//String eventRandom = saveCurrentDate + saveCurrentTime;*/
if (TextUtils.isEmpty(name)) {
editEventName.setError(REQUIRED);
return;
}
if (TextUtils.isEmpty(date)) {
editEventDate.setError(REQUIRED);
return;
}
if (TextUtils.isEmpty(startTime)) {
editEventStart.setError(REQUIRED);
return;
}
if (TextUtils.isEmpty(endTime)) {
editEventEnd.setError(REQUIRED);
return;
}
final String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
mUserRef.child("users").child(userId)
.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
DatabaseReference pushKey = mEventRef.push();
String key = pushKey.getKey();
HashMap<String, Object> eventMap = new HashMap<>();
eventMap.put("uid", userId);
eventMap.put("name", name);
eventMap.put("date", date);
eventMap.put("startTime", startTime);
eventMap.put("endTime", endTime);
eventMap.put("address", address);
eventMap.put("city", city);
eventMap.put("state", state);
eventMap.put("zip", zip);
eventMap.put("location", location);
eventMap.put("mod", mod);
eventMap.put("note", note);
eventMap.put("uid_name", userId + "_" + name);
eventMap.put("uid_date", userId + "_" + date);
eventMap.put("uid_startTime", userId + "_" + startTime);
eventMap.put("uid_endTime", userId + "_" + endTime);
eventMap.put("uid_address", userId + "_" + address);
eventMap.put("uid_city", userId + "_" + city);
eventMap.put("uid_state", userId + "_" + state);
eventMap.put("uid_zip", userId + "_" + zip);
eventMap.put("uid_location", userId + "_" + location);
eventMap.put("uid_mod", userId + "_" + mod);
eventMap.put("uid_note", userId + "_" + note);
//eventMap.put("startTime", startTime);
eventMap.put("uid_date_startTime", userId + "_" + date + "_" + startTime);
eventMap.put("uid_date_endTime", userId + "_" + date + "_" + endTime);
//HashMap<String, Object> childUpdates = new HashMap<>();
//childUpdates.put("/users/" + userId + "/" + key + "/", eventMap);
//mUserRef.updateChildren(childUpdates);
mEventRef.child(key).updateChildren(eventMap).addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if (task.isSuccessful()) {
SendUserToCalendarActivity();
Toast.makeText(AddEventActivity.this, "new event updated.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(AddEventActivity.this, "error occurred updating event", Toast.LENGTH_SHORT).show();
}
}
});
}
//startActivity(new Intent(AddEventActivity.this, CalendarActivity.class));
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void SendUserToCalendarActivity() {
Intent intent = new Intent(AddEventActivity.this, CalendarActivity.class);
startActivity(intent);
}
public String formatDate(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd yyyy");
String hireDate = sdf.format(date);
return hireDate;
}
@Override
public void onFinishMODDialog(String mod){
editEventMOD.setText(mod);
}
@Override
public void onFinishDateDialog(Date date){
editEventDate.setText(formatDate(date));
}
@Override
public void onFinishStartDialog(String time) {
Toast.makeText(this, "Selected Time : "+ time, Toast.LENGTH_SHORT).show();
editEventStart.setText(time);
}
@Override
public void onFinishEndDialog(String time) {
Toast.makeText(this, "Selected Time : "+ time, Toast.LENGTH_SHORT).show();
editEventEnd.setText(time);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_calendar, menu);
final SearchView searchView = (SearchView) MenuItemCompat
.getActionView(menu.findItem(R.id.action_search));
SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// action with ID action_refresh was selected
case R.id.action_account_settings:
Toast.makeText(this, "Refresh selected", Toast.LENGTH_SHORT)
.show();
Intent intent = new Intent(this, AccountSettingsActivity.class);
startActivity(intent);
break;
// action with ID action_settings was selected
case R.id.action_search:
Toast.makeText(this, "Settings selected", Toast.LENGTH_SHORT)
.show();
break;
default:
break;
}
return true;
}
private void toastMessage(String message){
Toast.makeText(this,message,Toast.LENGTH_SHORT).show();
}
/*@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
//savedInstanceState.putInt(STATE_SCORE, currentScore);
//savedInstanceState.putInt(STATE_LEVEL, currentLevel);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putString("EventName", editEventName.getText().toString());
}
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy
super.onRestoreInstanceState(savedInstanceState);
// Restore state members from saved instance
//currentScore = savedInstanceState.getInt(STATE_SCORE);
//currentLevel = savedInstanceState.getInt(STATE_LEVEL);
editEventName.setText(savedInstanceState.getString("EventName"));
}*/
@Override
public void onPause() {
super.onPause();
}
@Override
public void onResume() {
super.onResume();
}
@Override
public void onStart(){
super.onStart();
//editEventName.setText(ename);
}
@Override
public void onStop() {
super.onStop();
//ename = editEventName.getText().toString();
}
}
|
package application;
import java.util.Locale;
import java.util.Scanner;
import entities.Triangle;
public class Program {
public static void main(String[] args) {
double xA, xB, xC, yA, yB, yC;
Locale.setDefault(Locale.US);
Scanner scan = new Scanner(System.in);
Triangle x, y;
x = new Triangle();
y = new Triangle();
System.out.println("Enter the measures of triangle X: ");
xA = scan.nextDouble();
xB = scan.nextDouble();
xC = scan.nextDouble();
System.out.println("Enter the measures of triangle Y: ");
yA = scan.nextDouble();
yB = scan.nextDouble();
yC = scan.nextDouble();
double areaX = x.area(); // Colocar abre e fecha parenteses para indicar que estamos chamando o método.
double areaY = y.area();
System.out.printf("Triangle X area: %.4f\n", areaX);
System.out.printf("Triangle Y area: %.4f\n", areaY);
if (areaX > areaY)
System.out.println("Larger area X");
else
System.out.println("Larger area Y");
scan.close();
}
}
|
import java.util.ArrayList;
import java.util.List;
public class Scrabble {
public Integer calculateScore(String letters){
int score = 0;
for (int i =0; i < letters.length(); i++) {
if(letters.charAt(i) == 'a' || letters.charAt(i) == 'e' ){
score += 1;
}
if(letters.charAt(i) == 'z' || letters.charAt(i) == 'q' ){
score += 10;
}
}
return score;
}
}
|
package com.tencent.mm.wallet_core.ui;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
class EditHintView$9 implements OnClickListener {
final /* synthetic */ EditHintView uYF;
EditHintView$9(EditHintView editHintView) {
this.uYF = editHintView;
}
public final void onClick(DialogInterface dialogInterface, int i) {
EditHintView.p(this.uYF).dismiss();
}
}
|
package ljx.com.ashin.jms;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
/**
*
* Created by AshinLiang on 2017/10/24.
*/
public class JmsProducerTopi {
public static void main(String[] args) {
//创建工厂
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://127.0.0.1:61616");
try {
//创建连接
Connection connection = connectionFactory.createConnection();
//开启连接
connection.start();
//创建会话
Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
//创建主题
Destination destination = session.createTopic("My-topic");
//创建生产者
MessageProducer producer = session.createProducer(destination);
for (int i = 0; i < 3; i++) {
MapMessage message = session.createMapMessage();
message.setStringProperty("key"+i,"value"+i);
producer.send(message);
}
session.commit();
session.close();
connection.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
}
|
package com.puxtech.reuters.rfa.Common;
import java.util.*;
import org.apache.mina.core.future.WriteFuture;
import org.apache.mina.core.service.IoServiceStatistics;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.puxtech.reuters.rfa.Publisher.TCPServerByMina;
import com.puxtech.reuters.rfa.RelayServer.QuoteEventOffSetHandler;
public class ServerMonitor implements Runnable{
private static final List<IoSession> sessionList = new ArrayList<IoSession>();
private static final Logger monitorLog = LoggerFactory.getLogger("moniter");
public static void appendSession(IoSession session){
if(session != null){
session.setAttribute("futureList", Collections.synchronizedList(new ArrayList<WriteFuture>()));
synchronized (sessionList) {
sessionList.add(session);
}
}
}
public static List<IoSession> getSessionList(){
return sessionList;
}
@Override
public void run() {
monitorLog.info("服务监控开始...");
while(true){
try {
synchronized (sessionList) {
int sessionCount = sessionList.size();
monitorLog.info("当前连接数:" + sessionCount);
List<IoSession> closedSessions = new ArrayList<IoSession>();
for(int i = 0; i < sessionCount; i++){
List<WriteFuture> futureList = new ArrayList<WriteFuture>();
List<WriteFuture> futureListTemp = (List<WriteFuture>) sessionList.get(i).getAttribute("futureList");
futureList.addAll(futureListTemp);
monitorLog.info("*******************连接 " + (i + 1) + "开始*******************");
monitorLog.info("当前连接状态: " + (sessionList.get(i).isConnected() ? "正常" : "关闭"));
if(!sessionList.get(i).isConnected()){
closedSessions.add(sessionList.get(i));
}else{
monitorLog.info("客户端地址: " + sessionList.get(i).getRemoteAddress().toString());
monitorLog.info("当前传输状态: " + (sessionList.get(i).isWriterIdle() ? "空闲" : "正常"));
monitorLog.info("当前发送队列消息数:" + sessionList.get(i).getScheduledWriteMessages());
monitorLog.info("当前发送队列大小:" + sessionList.get(i).getScheduledWriteBytes());
monitorLog.info("连接建立时间:" + sessionList.get(i).getCreationTime());
monitorLog.info("最近一次IO时间:" + sessionList.get(i).getLastIoTime());
monitorLog.info("最近一次空闲时间:" + sessionList.get(i).getLastWriterIdleTime());
}
List<WriteFuture> doneFutures = new ArrayList<WriteFuture>();
int j = 0;
for(WriteFuture future : futureList){
if(future.isDone()){
doneFutures.add(future);
//发送操作完成
if(!future.isWritten()){
//发送失败
Throwable error = future.getException();
if(error != null){
monitorLog.info("*******************发送异常 " + j++ + "*******************");
StackTraceElement[] elements = error.getStackTrace();
StringBuffer sb = new StringBuffer();
sb.append("Cause by " + error.getClass().getName() + " :" + error.getMessage() + "\r\n");
for(StackTraceElement element : elements){
sb.append(element.getClassName() + element.getMethodName() + "(" + element.getFileName() + ":" + element.getLineNumber() + ")\r\n");
}
monitorLog.info(sb.toString());
monitorLog.info("*****************************************************");
}
}
}
}
synchronized (futureListTemp) {
futureListTemp.removeAll(doneFutures);
}
monitorLog.info("*******************连接 " + i + "结束*******************");
}
sessionList.removeAll(closedSessions);
}
Map offsetMap = QuoteEventOffSetHandler.getOffsetMap();
if(offsetMap != null){
monitorLog.info("**************************偏移量监控开始**************************");
synchronized (offsetMap) {
for(Object key : offsetMap.keySet()){
monitorLog.info("合约代码:" + key);
monitorLog.info("偏移量:" + offsetMap.get(key).toString());
}
}
monitorLog.info("**************************偏移量监控结束**************************");
}
} catch (Exception e) {
monitorLog.info("监控过程发生异常!", e);
} finally {
try {
Thread.sleep(Configuration.getInstance().getMonitorInterval());
} catch (InterruptedException e) {
monitorLog.info("monitor sleep been Interrupted !");
}
}
// IoServiceStatistics statistics = TCPServerByMina.getStatistics();
}
}
}
|
import java.util.Stack;
public class TelaInicial extends javax.swing.JFrame {
/**
* Creates new form TelaInicial
*/
public TelaInicial() {
initComponents();
a_estrela.setVisible(false);
algoritmo_genetico.setVisible(false);
}
/**
* 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() {
tempo_final = new javax.swing.JLabel();
btn_algoritmo_genetico = new javax.swing.JButton();
btn_a_estrela = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
algoritmo_genetico = new javax.swing.JPanel();
tamanho_tabuleiro = new javax.swing.JTextField();
tamanho_populacao = new javax.swing.JTextField();
taxa_mutacao = new javax.swing.JTextField();
evolucao = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
btn_executar_genetico = new javax.swing.JButton();
tempo_execucao_genetico = new javax.swing.JTextField();
jLabel8 = new javax.swing.JLabel();
a_estrela = new javax.swing.JPanel();
jLabel6 = new javax.swing.JLabel();
tamanho_tabuleiro_1 = new javax.swing.JTextField();
btn_executar_a = new javax.swing.JButton();
tempo_execucao_a = new javax.swing.JTextField();
jLabel7 = new javax.swing.JLabel();
tempo_final.setText("Tempo de execução: ");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
btn_algoritmo_genetico.setText("Algoritmo Genético");
btn_algoritmo_genetico.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_algoritmo_geneticoActionPerformed(evt);
}
});
btn_a_estrela.setText("A*");
btn_a_estrela.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_a_estrelaActionPerformed(evt);
}
});
jLabel1.setText("Escolha o algoritmo:");
algoritmo_genetico.setBorder(javax.swing.BorderFactory.createTitledBorder("Algoritmo Genético"));
tamanho_tabuleiro.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tamanho_tabuleiroActionPerformed(evt);
}
});
jLabel2.setText("Tamanho Tabuleiro");
jLabel3.setText("Tamanho População");
jLabel4.setText("Taxa de mutação");
jLabel5.setText("Evolução");
btn_executar_genetico.setText("Executar");
btn_executar_genetico.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_executar_geneticoActionPerformed(evt);
}
});
tempo_execucao_genetico.setEditable(false);
jLabel8.setText("Tempo de execução (ms):");
javax.swing.GroupLayout algoritmo_geneticoLayout = new javax.swing.GroupLayout(algoritmo_genetico);
algoritmo_genetico.setLayout(algoritmo_geneticoLayout);
algoritmo_geneticoLayout.setHorizontalGroup(
algoritmo_geneticoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(algoritmo_geneticoLayout.createSequentialGroup()
.addContainerGap()
.addGroup(algoritmo_geneticoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tempo_execucao_genetico)
.addComponent(tamanho_tabuleiro)
.addComponent(tamanho_populacao)
.addComponent(taxa_mutacao)
.addComponent(evolucao)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, algoritmo_geneticoLayout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(btn_executar_genetico, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(algoritmo_geneticoLayout.createSequentialGroup()
.addGroup(algoritmo_geneticoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4)
.addComponent(jLabel2)
.addComponent(jLabel3)
.addComponent(jLabel5)
.addComponent(jLabel8))
.addGap(0, 84, Short.MAX_VALUE)))
.addContainerGap())
);
algoritmo_geneticoLayout.setVerticalGroup(
algoritmo_geneticoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(algoritmo_geneticoLayout.createSequentialGroup()
.addGap(5, 5, 5)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tamanho_tabuleiro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tamanho_populacao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(taxa_mutacao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(evolucao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 23, Short.MAX_VALUE)
.addComponent(jLabel8)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(tempo_execucao_genetico, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btn_executar_genetico)
.addContainerGap())
);
a_estrela.setBorder(javax.swing.BorderFactory.createTitledBorder("A*"));
jLabel6.setText("Tamanho Tabuleiro");
btn_executar_a.setText("Executar");
btn_executar_a.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_executar_aActionPerformed(evt);
}
});
tempo_execucao_a.setEditable(false);
tempo_execucao_a.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tempo_execucao_aActionPerformed(evt);
}
});
jLabel7.setText("Tempo de execução (ms):");
javax.swing.GroupLayout a_estrelaLayout = new javax.swing.GroupLayout(a_estrela);
a_estrela.setLayout(a_estrelaLayout);
a_estrelaLayout.setHorizontalGroup(
a_estrelaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(a_estrelaLayout.createSequentialGroup()
.addContainerGap()
.addGroup(a_estrelaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tamanho_tabuleiro_1)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, a_estrelaLayout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(btn_executar_a, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(tempo_execucao_a)
.addGroup(a_estrelaLayout.createSequentialGroup()
.addGroup(a_estrelaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel6)
.addComponent(jLabel7))
.addGap(0, 43, Short.MAX_VALUE)))
.addContainerGap())
);
a_estrelaLayout.setVerticalGroup(
a_estrelaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(a_estrelaLayout.createSequentialGroup()
.addGap(6, 6, 6)
.addComponent(jLabel6)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tamanho_tabuleiro_1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel7)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(tempo_execucao_a, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btn_executar_a)
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel1)
.addComponent(btn_algoritmo_genetico, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btn_a_estrela, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(44, 44, 44)
.addComponent(a_estrela, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 26, Short.MAX_VALUE)
.addComponent(algoritmo_genetico, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(23, 23, 23))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(a_estrela, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(btn_algoritmo_genetico, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(25, 25, 25)
.addComponent(btn_a_estrela, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(algoritmo_genetico, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btn_algoritmo_geneticoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_algoritmo_geneticoActionPerformed
algoritmo_genetico.setVisible(true);
}//GEN-LAST:event_btn_algoritmo_geneticoActionPerformed
private void tamanho_tabuleiroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tamanho_tabuleiroActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_tamanho_tabuleiroActionPerformed
private void btn_a_estrelaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_a_estrelaActionPerformed
a_estrela.setVisible(true);
}//GEN-LAST:event_btn_a_estrelaActionPerformed
private void btn_executar_geneticoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_executar_geneticoActionPerformed
//Tabuleiro Algoritmo Genetico
int populacao = Integer.parseInt(this.tamanho_populacao.getText());
int taxa_mutacao = Integer.parseInt(this.taxa_mutacao.getText());
int evolucao = Integer.parseInt(this.evolucao.getText());
int tabuleiro = Integer.parseInt(this.tamanho_tabuleiro.getText());
TabuleiroInterface tabuleiroGenetico1 = new TabuleiroInterface(tabuleiro,2);
tabuleiroGenetico1.setTitle("Algoritmo Genetico");
AlgoritmoGenetico ag = new AlgoritmoGenetico(populacao, taxa_mutacao, tabuleiro);
tabuleiroGenetico1.mostrarSolucaoAlgoritmoGenetico(ag.pegaTabuleiro());
long start_genetico = System.currentTimeMillis();
ag.evoluir(evolucao);
long elapsed_genetico = System.currentTimeMillis() - start_genetico;
tabuleiroGenetico1.mostrarSolucaoAlgoritmoGenetico(ag.pegaTabuleiro());
this.tempo_execucao_genetico.setText(String.valueOf(elapsed_genetico));
}//GEN-LAST:event_btn_executar_geneticoActionPerformed
private void btn_executar_aActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_executar_aActionPerformed
int tabuleiro = Integer.parseInt(this.tamanho_tabuleiro_1.getText());
TabuleiroInterface tabuleiroEstrela = new TabuleiroInterface(tabuleiro,1);
tabuleiroEstrela.setTitle("A*");
long start_A = System.currentTimeMillis();
No solucaoAEstrela = tabuleiroEstrela.buscaAEstrela();
long elapsed_A = System.currentTimeMillis() - start_A;
Stack<EstadoTabuleiro> passosAEstrela = new Stack();
while(solucaoAEstrela != null) {
passosAEstrela.push(solucaoAEstrela.getEstadoTabuleiro());
solucaoAEstrela = solucaoAEstrela.getPai();
}
tabuleiroEstrela.mostrarSolucao(passosAEstrela);
this.tempo_execucao_a.setText(String.valueOf(elapsed_A));
}//GEN-LAST:event_btn_executar_aActionPerformed
private void tempo_execucao_aActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tempo_execucao_aActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_tempo_execucao_aActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(TelaInicial.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(TelaInicial.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(TelaInicial.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(TelaInicial.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new TelaInicial().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel a_estrela;
private javax.swing.JPanel algoritmo_genetico;
private javax.swing.JButton btn_a_estrela;
private javax.swing.JButton btn_algoritmo_genetico;
private javax.swing.JButton btn_executar_a;
private javax.swing.JButton btn_executar_genetico;
private javax.swing.JTextField evolucao;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JTextField tamanho_populacao;
private javax.swing.JTextField tamanho_tabuleiro;
private javax.swing.JTextField tamanho_tabuleiro_1;
private javax.swing.JTextField taxa_mutacao;
private javax.swing.JTextField tempo_execucao_a;
private javax.swing.JTextField tempo_execucao_genetico;
private javax.swing.JLabel tempo_final;
// End of variables declaration//GEN-END:variables
}
|
package de.johni0702.minecraft.gui.versions.forge;
import de.johni0702.minecraft.gui.utils.EventRegistrations;
import de.johni0702.minecraft.gui.versions.MatrixStack;
import de.johni0702.minecraft.gui.versions.callbacks.InitScreenCallback;
import de.johni0702.minecraft.gui.versions.callbacks.OpenGuiScreenCallback;
import de.johni0702.minecraft.gui.versions.callbacks.PostRenderScreenCallback;
import de.johni0702.minecraft.gui.versions.callbacks.PreTickCallback;
import de.johni0702.minecraft.gui.versions.callbacks.RenderHudCallback;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen;
import net.minecraftforge.client.event.GuiOpenEvent;
import net.minecraftforge.client.event.GuiScreenEvent;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.fml.common.eventhandler.EventPriority;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent;
import java.util.List;
public class EventsAdapter extends EventRegistrations {
public static GuiScreen getScreen(GuiScreenEvent event) {
//#if MC>=10904
return event.getGui();
//#else
//$$ return event.gui;
//#endif
}
public static List<GuiButton> getButtonList(GuiScreenEvent.InitGuiEvent event) {
//#if MC>=10904
return event.getButtonList();
//#else
//$$ return event.buttonList;
//#endif
}
@SubscribeEvent
public void preGuiInit(GuiScreenEvent.InitGuiEvent.Pre event) {
InitScreenCallback.Pre.EVENT.invoker().preInitScreen(getScreen(event));
}
@SubscribeEvent
public void onGuiInit(GuiScreenEvent.InitGuiEvent.Post event) {
InitScreenCallback.EVENT.invoker().initScreen(getScreen(event), getButtonList(event));
}
@SubscribeEvent(priority = EventPriority.LOWEST)
public void onGuiClosed(GuiOpenEvent event) {
OpenGuiScreenCallback.EVENT.invoker().openGuiScreen(
//#if MC>=10904
event.getGui()
//#else
//$$ event.gui
//#endif
);
}
public static float getPartialTicks(RenderGameOverlayEvent event) {
//#if MC>=10904
return event.getPartialTicks();
//#else
//$$ return event.partialTicks;
//#endif
}
public static float getPartialTicks(GuiScreenEvent.DrawScreenEvent.Post event) {
//#if MC>=10904
return event.getRenderPartialTicks();
//#else
//$$ return event.renderPartialTicks;
//#endif
}
@SubscribeEvent
public void onGuiRender(GuiScreenEvent.DrawScreenEvent.Post event) {
PostRenderScreenCallback.EVENT.invoker().postRenderScreen(new MatrixStack(), getPartialTicks(event));
}
// Even when event was cancelled cause Lunatrius' InGame-Info-XML mod cancels it and we don't actually care about
// the event (i.e. the overlay text), just about when it's called.
@SubscribeEvent(receiveCanceled = true)
public void renderOverlay(RenderGameOverlayEvent.Text event) {
RenderHudCallback.EVENT.invoker().renderHud(new MatrixStack(), getPartialTicks(event));
}
@SubscribeEvent
public void tickOverlay(TickEvent.ClientTickEvent event) {
if (event.phase == TickEvent.Phase.START) {
PreTickCallback.EVENT.invoker().preTick();
}
}
}
|
package com.smxknife.energy.services.alarm.infras.converter;
import com.smxknife.energy.services.alarm.infras.entity.AlarmRuleMeta;
import com.smxknife.energy.services.alarm.spi.domain.AlarmRule;
import org.mapstruct.Mapper;
import org.mapstruct.Mappings;
import java.util.List;
/**
* @author smxknife
* 2021/5/17
*/
@Mapper(componentModel = "spring")
public interface AlarmRuleConverter {
@Mappings({})
AlarmRule fromMeta(AlarmRuleMeta meta);
@Mappings({})
List<AlarmRule> fromMetas(List<AlarmRuleMeta> metas);
@Mappings({})
AlarmRuleMeta toMeta(AlarmRule alarmRule);
}
|
package com.licyun.util;
import com.licyun.model.User;
import com.licyun.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
/**
* Created by 李呈云
* Description:
* 2016/10/9.
*/
@Component
public class UploadImg {
@Autowired
private UserService userService;
public void uploadimg(MultipartFile file, User user, String rootPath){
// 上传目录
File uploadRootDir = new File(rootPath);
// 创建文件夹
if (!uploadRootDir.exists()) {
uploadRootDir.mkdirs();
}
String name = file.getOriginalFilename();
if(name != ""){
String imgurl = rootPath + File.separator + user.getImgUrl();
File imgFile = new File(imgurl);
imgFile.delete();
}
user.setImgUrl(name);
userService.updateUser(user);
System.out.println("Client File Name = " + name);
if (name != null && name.length() > 0) {
try {
byte[] bytes = file.getBytes();
// 创建跨平台的路径
File serverFile = new File(uploadRootDir.getAbsolutePath()
+ File.separator + name);
// 创建输入,输出流
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(serverFile));
stream.write(bytes);
stream.close();
System.out.println("Write file: " + serverFile);
} catch (Exception e) {
System.out.println("Error Write file: " + name);
}
}
}
}
|
/*
* UserEntityJsonAdapter.java
* This file was last modified at 2018.12.03 20:05 by Victor N. Skurikhin.
* $Id$
* This is free and unencumbered software released into the public domain.
* For more information, please refer to <http://unlicense.org>
*/
package ru.otus.adapters.json;
import ru.otus.adapters.DataSetAdapter;
import ru.otus.models.UserEntity;
import javax.json.bind.adapter.JsonbAdapter;
public class UserEntityJsonAdapter
implements JsonbAdapter<UserEntity, String>, DataSetAdapter<UserEntity>
{
/**
* The marshall method is convert the UserEntity object to JSON.
*
* @param user the UserEntity object to JSON.
* @return JSON String.
* @throws Exception
*/
@Override
public String adaptToJson(UserEntity user) throws Exception
{
return marshalAdapter(user);
}
/**
* The unmarshall method is convert the JSON String to UserEntity object.
*
* @param s the JSON String.
* @return UserEntity object.
* @throws Exception
*/
@Override
public UserEntity adaptFromJson(String s) throws Exception
{
return unmarshalAdapter(s, UserEntity.class);
}
}
/* vim: syntax=java:fileencoding=utf-8:fileformat=unix:tw=78:ts=4:sw=4:sts=4:et
*/
//EOF
|
/**
* MOTECH PLATFORM OPENSOURCE LICENSE AGREEMENT
*
* Copyright (c) 2010-11 The Trustees of Columbia University in the City of
* New York and Grameen Foundation USA. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of Grameen Foundation USA, Columbia University, or
* their respective contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY GRAMEEN FOUNDATION USA, COLUMBIA UNIVERSITY
* AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRAMEEN FOUNDATION
* USA, COLUMBIA UNIVERSITY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.motechproject.server.omod.tasks;
import org.junit.*;
import org.motechproject.server.messaging.impl.MessageSchedulerImpl;
import org.motechproject.server.model.*;
import org.motechproject.server.model.MessageStatus;
import org.motechproject.server.model.ghana.Facility;
import org.motechproject.server.omod.MotechModuleActivator;
import org.motechproject.server.service.MotechService;
import org.motechproject.server.svc.RegistrarBean;
import org.motechproject.server.util.MotechConstants;
import org.motechproject.ws.*;
import org.openmrs.Obs;
import org.openmrs.Patient;
import org.openmrs.PatientIdentifierType;
import org.openmrs.api.context.Context;
import org.openmrs.scheduler.TaskDefinition;
import org.openmrs.test.BaseModuleContextSensitiveTest;
import org.openmrs.test.SkipBaseSetup;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class NotificationTaskTest extends BaseModuleContextSensitiveTest {
static MotechModuleActivator activator;
@BeforeClass
public static void setUpClass() throws Exception {
activator = new MotechModuleActivator();
}
@AfterClass
public static void tearDownClass() throws Exception {
activator = null;
}
@Before
public void setup() throws Exception {
// Perform same steps as BaseSetup (initializeInMemoryDatabase,
// executeDataSet, authenticate), except load custom XML dataset
initializeInMemoryDatabase();
// Created from org.openmrs.test.CreateInitialDataSet
// using 1.4.4-createdb-from-scratch-with-demo-data.sql
// Removed all empty short_name="" from concepts
// Added missing description to relationship_type
// Removed all patients and related patient/person info (id 2-500)
// Removed all concepts except those in sqldiff
executeDataSet("initial-openmrs-dataset.xml");
// Includes Motech data added in sqldiff
executeDataSet("motech-dataset.xml");
authenticate();
activator.startup();
}
@After
public void tearDown() throws Exception {
activator.shutdown();
}
@Test
@SkipBaseSetup
public void testSingleNotify() {
try {
Context.openSession();
Context.authenticate("admin", "test");
RegistrarBean registrarBean = Context.getService(MotechService.class)
.getRegistrarBean();
// Register Mother and Child
Date date = new Date();
Integer motherMotechId = 1234649;
Facility facility = registrarBean.getFacilityById(11117);
registrarBean.registerPatient(RegistrationMode.USE_PREPRINTED_ID,
motherMotechId, RegistrantType.PREGNANT_MOTHER,
"motherfirstName", "mothermiddleName", "motherlastName",
"motherprefName", date, false, Gender.FEMALE, true,
"mothernhis", date, null, null, facility, "Address", "1111111111",
date, true, true, true, ContactNumberType.PERSONAL,
MediaType.TEXT, "language", DayOfWeek.MONDAY, date,
InterestReason.CURRENTLY_PREGNANT, HowLearned.FRIEND, null);
Integer childMotechId = 1234654;
registrarBean.registerPatient(RegistrationMode.USE_PREPRINTED_ID,
childMotechId, RegistrantType.CHILD_UNDER_FIVE,
"childfirstName", "childmiddleName", "childlastName",
"childprefName", date, false, Gender.FEMALE, true,
"childnhis", date, null, null, facility, "Address", "1111111111",
null, null, false, false, ContactNumberType.PERSONAL,
MediaType.TEXT, "language", DayOfWeek.MONDAY, date,
InterestReason.FAMILY_FRIEND_PREGNANT, HowLearned.FRIEND,
null);
// Check Mother and Child registered successfully
assertEquals(4, Context.getPatientService().getAllPatients().size());
ArrayList<PatientIdentifierType> patientIdTypeList = new ArrayList<PatientIdentifierType>();
patientIdTypeList.add(Context.getPatientService()
.getPatientIdentifierTypeByName(
MotechConstants.PATIENT_IDENTIFIER_MOTECH_ID));
List<Patient> motherMatchingPatients = Context.getPatientService()
.getPatients("motherfirstName motherlastName",
motherMotechId.toString(), patientIdTypeList, true);
assertEquals(1, motherMatchingPatients.size());
// Verify Mother's Pregnancy exists
Patient mother = motherMatchingPatients.get(0);
Obs pregnancyObs = registrarBean.getActivePregnancy(mother
.getPatientId());
assertNotNull("Pregnancy Obs does not exist", pregnancyObs);
List<Patient> childMatchingPatients = Context.getPatientService()
.getPatients("childfirstName childlastName",
childMotechId.toString(), patientIdTypeList, true);
assertEquals(1, childMatchingPatients.size());
Patient child = childMatchingPatients.get(0);
// Add Test Message Definition, Enrollment and Scheduled Message
String messageKey = "Test Definition";
String messageKeyA = "Test DefinitionA";
String messageKeyB = "Test DefinitionB";
String messageKeyC = "Test DefinitionC";
MessageDefinition messageDefinition = new MessageDefinition(
messageKey, 2L, MessageType.INFORMATIONAL);
MessageDefinition messageDefinitionA = new MessageDefinition(
messageKeyA, 3L, MessageType.INFORMATIONAL);
MessageDefinition messageDefinitionB = new MessageDefinition(
messageKeyB, 4L, MessageType.INFORMATIONAL);
MessageDefinition messageDefinitionC = new MessageDefinition(
messageKeyC, 5L, MessageType.INFORMATIONAL);
Context.getService(MotechService.class).saveMessageDefinition(
messageDefinition);
Context.getService(MotechService.class).saveMessageDefinition(
messageDefinitionA);
Context.getService(MotechService.class).saveMessageDefinition(
messageDefinitionB);
Context.getService(MotechService.class).saveMessageDefinition(
messageDefinitionC);
MessageProgramEnrollment enrollment = new MessageProgramEnrollment();
enrollment.setStartDate(new Date());
enrollment.setProgram("Fake Program Name");
enrollment.setPersonId(child.getPatientId());
Context.getService(MotechService.class)
.saveMessageProgramEnrollment(enrollment);
// Schedule message 5 seconds in future
Date scheduledMessageDate = new Date(
System.currentTimeMillis() + 5 * 1000);
MessageSchedulerImpl messageScheduler = new MessageSchedulerImpl();
messageScheduler.setRegistrarBean(registrarBean);
messageScheduler.scheduleMessages(messageKey, messageKeyA,
messageKeyB, messageKeyC, enrollment, scheduledMessageDate,
date);
} finally {
Context.closeSession();
}
NotificationTask task = new NotificationTask();
TaskDefinition taskDef = new TaskDefinition();
taskDef.setRepeatInterval(30L);
task.initialize(taskDef);
task.execute();
try {
Context.openSession();
// Verify Message Status updated on Scheduled Message Attempt
List<ScheduledMessage> scheduledMessages = Context.getService(
MotechService.class).getAllScheduledMessages();
assertEquals(3, scheduledMessages.size());
// Results are ordered oldest first
// Oldest/last message with current date should be pending
// Newer/first messages with later date should not be pending
for (int i = 0; i < 3; i++) {
List<Message> messageAttempts = scheduledMessages.get(i)
.getMessageAttempts();
assertEquals(1, messageAttempts.size());
Message message = messageAttempts.get(0);
assertNotNull("Message attempt date is null", message
.getAttemptDate());
if (i == 0) {
assertEquals(MessageStatus.ATTEMPT_PENDING, message
.getAttemptStatus());
} else {
assertEquals(MessageStatus.SHOULD_ATTEMPT, message
.getAttemptStatus());
}
}
} finally {
Context.closeSession();
}
}
}
|
package com.bozhong.lhdataaccess.application;
import com.bozhong.lhdataaccess.client.common.constants.ServiceErrorEnum;
import com.bozhong.lhdataaccess.client.domain.core.Result;
/**
* 一个请求上下文
*
* @author bin
* @create 2018-04-27 下午5:13
**/
public class Context<P, M> {
private P param;
private Result<M> result;
public Context(P param, Result<M> result) {
this.param = param;
this.result = result;
}
public Result<M> getResult() {
return result;
}
public P getParam() {
return param;
}
public void setResultModule(M m) {
result.setModule(m);
}
public void setResult(Result<M> result) {
this.result = result;
}
public void setServiceError(ServiceErrorEnum serviceError) {
result.setServiceError(serviceError);
}
}
|
package com.tencent.mm.ipcinvoker.extension;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.Parcelable.Creator;
public class XParcelableWrapper implements Parcelable {
public static final Creator<XParcelableWrapper> CREATOR = new 1();
public f dne;
/* synthetic */ XParcelableWrapper(byte b) {
this();
}
private XParcelableWrapper() {
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel parcel, int i) {
if (this.dne != null) {
parcel.writeInt(1);
parcel.writeString(this.dne.getClass().getName());
this.dne.f(parcel);
return;
}
parcel.writeInt(0);
}
}
|
import java.io.IOException;
import java.util.Scanner;
public class SwitchStringFile {
private Scanner scanner;
private String switchchoise;
public String SwitchString(){
WorkStrings workStrings = new WorkStrings(new Scanner(System.in));
workStrings.scanner();
do {
System.out.println("What do you want to do whit strings?\n1 - reverse string \n2 - del spacing in the begiging and in the end " +
"\n3 - del spacing by chars in the begiging and in the end \n4 - case format \n5 - get substring\n6 - exit");
scanner = new Scanner( System.in );
switchchoise = scanner.nextLine();
switch (switchchoise) {
case "1":
workStrings.reverse();
break;
case "2":
workStrings.format();
break;
case "3":
workStrings.format1();
break;
case "4":
workStrings.caseFormat();
break;
case "5":
workStrings.substring();
break;
case "6":
break;
default:
System.out.println( "What?" );
break;
}
} while (!switchchoise.equals( "6" ));
return null;
}
public String SwitchFile() throws IOException {
Files files = new Files();
do {
System.out.println( "What do you want to do whit files?\n1 - write one string in file \n2 - write many strings in file " +
"\n3 - create a new dirrectory \n4 - delete dirrectory \n5 - exit" );
scanner = new Scanner( System.in );
switchchoise = scanner.nextLine();
switch (switchchoise) {
case "1":
files.writeInFileOneString();
break;
case "2":
files.writeInFileManyStrings();
break;
case "3":
files.createDirr();
break;
case "4":
files.delDirr();
break;
case "5":
break;
default:
System.out.println( "What?" );
break;
}
}while (!switchchoise.equals( "5" ));
return null;
}
}
|
package br.com.helpdev.quaklog.processor.parser.objects;
import br.com.helpdev.quaklog.processor.parser.ParseObject;
import lombok.Builder;
import lombok.Data;
import lombok.NonNull;
@Data
@Builder
public class ClientBeginParseObParser implements ParseObject {
@NonNull
private String gameTime;
@NonNull
private Integer id;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.