text
stringlengths 10
2.72M
|
|---|
//package p1.sad.P1.MultiLine;
public class KeyNumber {
public static final int UP = 1;
public static final int DOWN = 2;
public static final int RIGHT = 3;
public static final int LEFT = 4;
public static final int END = 5;
public static final int BEGIN = 6;
public static final int INSERT = 7;
public static final int DELETE = 8;
//public static final int MOUSE = 9;
public static final int ENTER = 13;
public static final int BACKSPACE = 127;
public static final String doRESET = "\u001b[1000A\u001b[1000D";
public static final String doDELETE = "\u001b[2J";
}
|
package com.tencent.mm.plugin.exdevice.e;
import com.tencent.mm.bk.a;
public abstract class i extends a {
public d ixi;
}
|
package com.ovi.prescription.service;
import com.ovi.prescription.domain.Admin;
import com.ovi.prescription.exception.AdminEmailException;
import com.ovi.prescription.exception.LoginException;
import com.ovi.prescription.payload.request.RegistrationRequest;
import com.ovi.prescription.payload.response.AdminResponse;
import com.ovi.prescription.repository.AdminRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
@Service
public class AdminService implements UserDetailsService {
@Autowired
AdminRepository adminRepository;
@Autowired
PasswordEncoder passwordEncoder;
@Override
public UserDetails loadUserByUsername(String email) {
Admin adminEntity = adminRepository.findByEmail(email);
if (adminEntity == null) {
throw new LoginException(email);
}
return new User(adminEntity.getEmail(), adminEntity.getPassword(), new ArrayList<>());
}
public AdminResponse save(RegistrationRequest registrationRequest) throws AdminEmailException {
if (adminRepository.existsByEmail(registrationRequest.getEmail())) {
throw new AdminEmailException("User email is already exist");
}
Admin admin = new Admin();
BeanUtils.copyProperties(registrationRequest, admin);
admin.setPassword(passwordEncoder.encode(admin.getPassword()));
admin = adminRepository.save(admin);
AdminResponse adminResponse = new AdminResponse();
BeanUtils.copyProperties(admin, adminResponse);
return adminResponse;
}
public AdminResponse getUserInfo(String email) throws AdminEmailException {
AdminResponse adminResponse = new AdminResponse();
Admin user = adminRepository.findByEmail(email);
if (user ==null) throw new AdminEmailException("User not Found");
BeanUtils.copyProperties(user, adminResponse);
return adminResponse;
}
}
|
package com.example.onlineshop.view.fragments;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.onlineshop.R;
import com.example.onlineshop.model.Product;
import com.example.onlineshop.view.Adapter.ProductListSubCategoryAdapter;
import com.example.onlineshop.view.activities.EndlessRecyclerViewScrollListener;
import com.example.onlineshop.viewmodel.SearchViewModel;
import com.example.onlineshop.viewmodel.ViewPagerCategViewModel;
import java.util.ArrayList;
import java.util.List;
public class DetailListCategoryFragment extends VisibleFragment {
private static final String ARG_CATEGORY_NAME = "Arg categoryName";
private static final String ARG_CATEGORY_ID = "Arg categoryId";
private RecyclerView mRecyclerView;
private ProductListSubCategoryAdapter mAdapter;
private List<Product> mProductList = new ArrayList<>();
private ViewPagerCategViewModel mViewModel;
private String mCategoryName;
private int mCategoryId;
private EndlessRecyclerViewScrollListener mEndlessRecyclVScrollListener;
private int mPageNumber = 1;
public DetailListCategoryFragment() {
// Required empty public constructor
}
public static DetailListCategoryFragment newInstance(int categoryId, String categoryName) {
DetailListCategoryFragment fragment = new DetailListCategoryFragment();
Bundle args = new Bundle();
args.putString(ARG_CATEGORY_NAME, categoryName);
args.putInt(ARG_CATEGORY_ID, categoryId);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mCategoryName = getArguments().getString(ARG_CATEGORY_NAME);
mCategoryId = getArguments().getInt(ARG_CATEGORY_ID);
}
mViewModel = ViewModelProviders.of(this).get(ViewPagerCategViewModel.class);
mViewModel.getListProMutableLiveData(mCategoryName, mCategoryId).observe(this, new Observer<List<Product>>() {
@Override
public void onChanged(List<Product> list) {
mProductList = list;
setupAdapter();
}
});
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_detail_list_category, container, false);
init(view);
return view;
}
private void init(View view) {
mRecyclerView = view.findViewById(R.id.recycler_view_detail_list_category);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
mRecyclerView.setLayoutManager(linearLayoutManager);
mEndlessRecyclVScrollListener = new EndlessRecyclerViewScrollListener(linearLayoutManager) {
@Override
public void onLoadMore(int page, int totalItemsCount, RecyclerView view) {
mPageNumber++;
loadNextDataFromApi(mPageNumber);
// mEndlessRecyclVScrollListener.resetState();
}
};
mRecyclerView.addOnScrollListener(mEndlessRecyclVScrollListener);
}
private void loadNextDataFromApi(int offset) {
mViewModel.getListProByPageMutableLiveData(mCategoryName,mCategoryId,offset).observe(this, list -> {
mProductList.addAll(list);
setupAdapter();
});
}
private void setupAdapter() {
if (isAdded()) {
mAdapter = new ProductListSubCategoryAdapter(getContext(), mProductList);
mRecyclerView.setAdapter(mAdapter);
}
}
}
|
package com.rc.portal.vo;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.rc.app.framework.webapp.model.BaseModel;
public class TLxAnnouncementExample extends BaseModel{
protected String orderByClause;
protected List oredCriteria;
public TLxAnnouncementExample() {
oredCriteria = new ArrayList();
}
protected TLxAnnouncementExample(TLxAnnouncementExample example) {
this.orderByClause = example.orderByClause;
this.oredCriteria = example.oredCriteria;
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public List getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
}
public static class Criteria {
protected List criteriaWithoutValue;
protected List criteriaWithSingleValue;
protected List criteriaWithListValue;
protected List criteriaWithBetweenValue;
protected Criteria() {
super();
criteriaWithoutValue = new ArrayList();
criteriaWithSingleValue = new ArrayList();
criteriaWithListValue = new ArrayList();
criteriaWithBetweenValue = new ArrayList();
}
public boolean isValid() {
return criteriaWithoutValue.size() > 0
|| criteriaWithSingleValue.size() > 0
|| criteriaWithListValue.size() > 0
|| criteriaWithBetweenValue.size() > 0;
}
public List getCriteriaWithoutValue() {
return criteriaWithoutValue;
}
public List getCriteriaWithSingleValue() {
return criteriaWithSingleValue;
}
public List getCriteriaWithListValue() {
return criteriaWithListValue;
}
public List getCriteriaWithBetweenValue() {
return criteriaWithBetweenValue;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteriaWithoutValue.add(condition);
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
Map map = new HashMap();
map.put("condition", condition);
map.put("value", value);
criteriaWithSingleValue.add(map);
}
protected void addCriterion(String condition, List values, String property) {
if (values == null || values.size() == 0) {
throw new RuntimeException("Value list for " + property + " cannot be null or empty");
}
Map map = new HashMap();
map.put("condition", condition);
map.put("values", values);
criteriaWithListValue.add(map);
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
List list = new ArrayList();
list.add(value1);
list.add(value2);
Map map = new HashMap();
map.put("condition", condition);
map.put("values", list);
criteriaWithBetweenValue.add(map);
}
public Criteria andIdIsNull() {
addCriterion("id is null");
return this;
}
public Criteria andIdIsNotNull() {
addCriterion("id is not null");
return this;
}
public Criteria andIdEqualTo(Long value) {
addCriterion("id =", value, "id");
return this;
}
public Criteria andIdNotEqualTo(Long value) {
addCriterion("id <>", value, "id");
return this;
}
public Criteria andIdGreaterThan(Long value) {
addCriterion("id >", value, "id");
return this;
}
public Criteria andIdGreaterThanOrEqualTo(Long value) {
addCriterion("id >=", value, "id");
return this;
}
public Criteria andIdLessThan(Long value) {
addCriterion("id <", value, "id");
return this;
}
public Criteria andIdLessThanOrEqualTo(Long value) {
addCriterion("id <=", value, "id");
return this;
}
public Criteria andIdIn(List values) {
addCriterion("id in", values, "id");
return this;
}
public Criteria andIdNotIn(List values) {
addCriterion("id not in", values, "id");
return this;
}
public Criteria andIdBetween(Long value1, Long value2) {
addCriterion("id between", value1, value2, "id");
return this;
}
public Criteria andIdNotBetween(Long value1, Long value2) {
addCriterion("id not between", value1, value2, "id");
return this;
}
public Criteria andCententIsNull() {
addCriterion("centent is null");
return this;
}
public Criteria andCententIsNotNull() {
addCriterion("centent is not null");
return this;
}
public Criteria andCententEqualTo(String value) {
addCriterion("centent =", value, "centent");
return this;
}
public Criteria andCententNotEqualTo(String value) {
addCriterion("centent <>", value, "centent");
return this;
}
public Criteria andCententGreaterThan(String value) {
addCriterion("centent >", value, "centent");
return this;
}
public Criteria andCententGreaterThanOrEqualTo(String value) {
addCriterion("centent >=", value, "centent");
return this;
}
public Criteria andCententLessThan(String value) {
addCriterion("centent <", value, "centent");
return this;
}
public Criteria andCententLessThanOrEqualTo(String value) {
addCriterion("centent <=", value, "centent");
return this;
}
public Criteria andCententLike(String value) {
addCriterion("centent like", value, "centent");
return this;
}
public Criteria andCententNotLike(String value) {
addCriterion("centent not like", value, "centent");
return this;
}
public Criteria andCententIn(List values) {
addCriterion("centent in", values, "centent");
return this;
}
public Criteria andCententNotIn(List values) {
addCriterion("centent not in", values, "centent");
return this;
}
public Criteria andCententBetween(String value1, String value2) {
addCriterion("centent between", value1, value2, "centent");
return this;
}
public Criteria andCententNotBetween(String value1, String value2) {
addCriterion("centent not between", value1, value2, "centent");
return this;
}
public Criteria andWeightIsNull() {
addCriterion("weight is null");
return this;
}
public Criteria andWeightIsNotNull() {
addCriterion("weight is not null");
return this;
}
public Criteria andWeightEqualTo(Integer value) {
addCriterion("weight =", value, "weight");
return this;
}
public Criteria andWeightNotEqualTo(Integer value) {
addCriterion("weight <>", value, "weight");
return this;
}
public Criteria andWeightGreaterThan(Integer value) {
addCriterion("weight >", value, "weight");
return this;
}
public Criteria andWeightGreaterThanOrEqualTo(Integer value) {
addCriterion("weight >=", value, "weight");
return this;
}
public Criteria andWeightLessThan(Integer value) {
addCriterion("weight <", value, "weight");
return this;
}
public Criteria andWeightLessThanOrEqualTo(Integer value) {
addCriterion("weight <=", value, "weight");
return this;
}
public Criteria andWeightIn(List values) {
addCriterion("weight in", values, "weight");
return this;
}
public Criteria andWeightNotIn(List values) {
addCriterion("weight not in", values, "weight");
return this;
}
public Criteria andWeightBetween(Integer value1, Integer value2) {
addCriterion("weight between", value1, value2, "weight");
return this;
}
public Criteria andWeightNotBetween(Integer value1, Integer value2) {
addCriterion("weight not between", value1, value2, "weight");
return this;
}
public Criteria andAnnouncementTypeIsNull() {
addCriterion("announcement_type is null");
return this;
}
public Criteria andAnnouncementTypeIsNotNull() {
addCriterion("announcement_type is not null");
return this;
}
public Criteria andAnnouncementTypeEqualTo(Integer value) {
addCriterion("announcement_type =", value, "announcementType");
return this;
}
public Criteria andAnnouncementTypeNotEqualTo(Integer value) {
addCriterion("announcement_type <>", value, "announcementType");
return this;
}
public Criteria andAnnouncementTypeGreaterThan(Integer value) {
addCriterion("announcement_type >", value, "announcementType");
return this;
}
public Criteria andAnnouncementTypeGreaterThanOrEqualTo(Integer value) {
addCriterion("announcement_type >=", value, "announcementType");
return this;
}
public Criteria andAnnouncementTypeLessThan(Integer value) {
addCriterion("announcement_type <", value, "announcementType");
return this;
}
public Criteria andAnnouncementTypeLessThanOrEqualTo(Integer value) {
addCriterion("announcement_type <=", value, "announcementType");
return this;
}
public Criteria andAnnouncementTypeIn(List values) {
addCriterion("announcement_type in", values, "announcementType");
return this;
}
public Criteria andAnnouncementTypeNotIn(List values) {
addCriterion("announcement_type not in", values, "announcementType");
return this;
}
public Criteria andAnnouncementTypeBetween(Integer value1, Integer value2) {
addCriterion("announcement_type between", value1, value2, "announcementType");
return this;
}
public Criteria andAnnouncementTypeNotBetween(Integer value1, Integer value2) {
addCriterion("announcement_type not between", value1, value2, "announcementType");
return this;
}
public Criteria andCreateDtIsNull() {
addCriterion("create_dt is null");
return this;
}
public Criteria andCreateDtIsNotNull() {
addCriterion("create_dt is not null");
return this;
}
public Criteria andCreateDtEqualTo(Date value) {
addCriterion("create_dt =", value, "createDt");
return this;
}
public Criteria andCreateDtNotEqualTo(Date value) {
addCriterion("create_dt <>", value, "createDt");
return this;
}
public Criteria andCreateDtGreaterThan(Date value) {
addCriterion("create_dt >", value, "createDt");
return this;
}
public Criteria andCreateDtGreaterThanOrEqualTo(Date value) {
addCriterion("create_dt >=", value, "createDt");
return this;
}
public Criteria andCreateDtLessThan(Date value) {
addCriterion("create_dt <", value, "createDt");
return this;
}
public Criteria andCreateDtLessThanOrEqualTo(Date value) {
addCriterion("create_dt <=", value, "createDt");
return this;
}
public Criteria andCreateDtIn(List values) {
addCriterion("create_dt in", values, "createDt");
return this;
}
public Criteria andCreateDtNotIn(List values) {
addCriterion("create_dt not in", values, "createDt");
return this;
}
public Criteria andCreateDtBetween(Date value1, Date value2) {
addCriterion("create_dt between", value1, value2, "createDt");
return this;
}
public Criteria andCreateDtNotBetween(Date value1, Date value2) {
addCriterion("create_dt not between", value1, value2, "createDt");
return this;
}
public Criteria andStatusIsNull() {
addCriterion("status is null");
return this;
}
public Criteria andStatusIsNotNull() {
addCriterion("status is not null");
return this;
}
public Criteria andStatusEqualTo(Integer value) {
addCriterion("status =", value, "status");
return this;
}
public Criteria andStatusNotEqualTo(Integer value) {
addCriterion("status <>", value, "status");
return this;
}
public Criteria andStatusGreaterThan(Integer value) {
addCriterion("status >", value, "status");
return this;
}
public Criteria andStatusGreaterThanOrEqualTo(Integer value) {
addCriterion("status >=", value, "status");
return this;
}
public Criteria andStatusLessThan(Integer value) {
addCriterion("status <", value, "status");
return this;
}
public Criteria andStatusLessThanOrEqualTo(Integer value) {
addCriterion("status <=", value, "status");
return this;
}
public Criteria andStatusIn(List values) {
addCriterion("status in", values, "status");
return this;
}
public Criteria andStatusNotIn(List values) {
addCriterion("status not in", values, "status");
return this;
}
public Criteria andStatusBetween(Integer value1, Integer value2) {
addCriterion("status between", value1, value2, "status");
return this;
}
public Criteria andStatusNotBetween(Integer value1, Integer value2) {
addCriterion("status not between", value1, value2, "status");
return this;
}
public Criteria andIsDeleteIsNull() {
addCriterion("is_delete is null");
return this;
}
public Criteria andIsDeleteIsNotNull() {
addCriterion("is_delete is not null");
return this;
}
public Criteria andIsDeleteEqualTo(Integer value) {
addCriterion("is_delete =", value, "isDelete");
return this;
}
public Criteria andIsDeleteNotEqualTo(Integer value) {
addCriterion("is_delete <>", value, "isDelete");
return this;
}
public Criteria andIsDeleteGreaterThan(Integer value) {
addCriterion("is_delete >", value, "isDelete");
return this;
}
public Criteria andIsDeleteGreaterThanOrEqualTo(Integer value) {
addCriterion("is_delete >=", value, "isDelete");
return this;
}
public Criteria andIsDeleteLessThan(Integer value) {
addCriterion("is_delete <", value, "isDelete");
return this;
}
public Criteria andIsDeleteLessThanOrEqualTo(Integer value) {
addCriterion("is_delete <=", value, "isDelete");
return this;
}
public Criteria andIsDeleteIn(List values) {
addCriterion("is_delete in", values, "isDelete");
return this;
}
public Criteria andIsDeleteNotIn(List values) {
addCriterion("is_delete not in", values, "isDelete");
return this;
}
public Criteria andIsDeleteBetween(Integer value1, Integer value2) {
addCriterion("is_delete between", value1, value2, "isDelete");
return this;
}
public Criteria andIsDeleteNotBetween(Integer value1, Integer value2) {
addCriterion("is_delete not between", value1, value2, "isDelete");
return this;
}
public Criteria andSendDtIsNull() {
addCriterion("send_dt is null");
return this;
}
public Criteria andSendDtIsNotNull() {
addCriterion("send_dt is not null");
return this;
}
public Criteria andSendDtEqualTo(Date value) {
addCriterion("send_dt =", value, "sendDt");
return this;
}
public Criteria andSendDtNotEqualTo(Date value) {
addCriterion("send_dt <>", value, "sendDt");
return this;
}
public Criteria andSendDtGreaterThan(Date value) {
addCriterion("send_dt >", value, "sendDt");
return this;
}
public Criteria andSendDtGreaterThanOrEqualTo(Date value) {
addCriterion("send_dt >=", value, "sendDt");
return this;
}
public Criteria andSendDtLessThan(Date value) {
addCriterion("send_dt <", value, "sendDt");
return this;
}
public Criteria andSendDtLessThanOrEqualTo(Date value) {
addCriterion("send_dt <=", value, "sendDt");
return this;
}
public Criteria andSendDtIn(List values) {
addCriterion("send_dt in", values, "sendDt");
return this;
}
public Criteria andSendDtNotIn(List values) {
addCriterion("send_dt not in", values, "sendDt");
return this;
}
public Criteria andSendDtBetween(Date value1, Date value2) {
addCriterion("send_dt between", value1, value2, "sendDt");
return this;
}
public Criteria andSendDtNotBetween(Date value1, Date value2) {
addCriterion("send_dt not between", value1, value2, "sendDt");
return this;
}
}
}
|
package com.hnam.androiddagger.di.ChatComponent;
import android.content.Context;
import com.hnam.androiddagger.database.ChatService;
import com.hnam.androiddagger.database.DBService;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
/**
* Created by nampham on 12/25/18.
*/
@Module
public class ChatModule {
@Provides
@ChatScope
ChatService provideChatService() {
return new ChatService();
}
}
|
package com.tencent.mm.modelvideo;
import com.tencent.mm.ab.l;
import com.tencent.mm.compatible.util.g;
import com.tencent.mm.modelvideo.x.a;
import com.tencent.mm.sdk.platformtools.x;
class x$a$2 implements Runnable {
final /* synthetic */ l bFp;
final /* synthetic */ int bFq;
final /* synthetic */ int bFr;
final /* synthetic */ a eoz;
x$a$2(a aVar, l lVar, int i, int i2) {
this.eoz = aVar;
this.bFp = lVar;
this.bFq = i;
this.bFr = i2;
}
public final void run() {
int i;
String str;
a.KF();
String str2;
if (this.bFp.getType() == 150) {
a.b(this.eoz);
str2 = ((d) this.bFp).fileName;
x.eoq = str2;
int i2 = ((d) this.bFp).retCode;
a.c(this.eoz);
i = i2;
str = str2;
} else if (this.bFp.getType() == 149) {
a.d(this.eoz);
a.e(this.eoz);
if (this.bFp instanceof g) {
str2 = ((g) this.bFp).fileName;
i = ((g) this.bFp).retCode;
str = str2;
} else if (this.bFp instanceof h) {
i = 0;
str = ((h) this.bFp).fileName;
} else {
i = 0;
str = null;
}
} else {
x.e("MicroMsg.VideoService", "onSceneEnd Error SceneType:" + this.bFp.getType());
a.Ty();
return;
}
long j = 0;
if (!(str == null || this.eoz.bFf.get(str) == null)) {
j = ((g.a) this.eoz.bFf.get(str)).Ad();
this.eoz.bFf.remove(str);
}
x.d("MicroMsg.VideoService", "onSceneEnd SceneType:" + this.bFp.getType() + " errtype:" + this.bFq + " errCode:" + this.bFr + " retCode:" + i + " file:" + str + " time:" + j);
if (this.bFq == 3 && i != 0) {
a.f(this.eoz);
} else if (this.bFq != 0) {
a.a(this.eoz, 0);
}
x.d("MicroMsg.VideoService", "onSceneEnd inCnt:" + a.KD() + " stop:" + a.g(this.eoz) + " running:" + a.h(this.eoz) + " recving:" + a.i(this.eoz) + " sending:" + a.j(this.eoz));
if (a.g(this.eoz) > 0) {
a.a(this.eoz);
} else if (!(a.j(this.eoz) || a.i(this.eoz))) {
a.k(this.eoz);
}
a.Ty();
}
public final String toString() {
return super.toString() + "|onSceneEnd";
}
}
|
package com.example.news_kor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class NewsUtil {
private static Retrofit retrofit = null;
public static NewsInterface getApiInterface() {
if(retrofit == null) {
//Retrofit 데이터가 존재한다면 Gson을 처리하고 BASE_URL을 통해 서버에서 데이터를 받아올 수 있도록 Build
retrofit = new Retrofit.Builder().baseUrl(NewsInterface.BASE_URL).addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit.create(NewsInterface.class);
}
}
|
package org.fuusio.api.rest.volley;
import android.util.Base64;
import com.android.volley.toolbox.HurlStack;
import com.squareup.okhttp.CertificatePinner;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.OkUrlFactory;
import org.fuusio.api.util.StringToolkit;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.CertificateException;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
/**
* {@link UrlStack} extends {@link HurlStack} for implementing certificate pinning and for
* replacing the deprecated HTTP client with {@link OkHttpClient} from Square.
*/
public class UrlStack extends HurlStack {
private static final String PREFIX_SHA1 = "sha1/";
private final OkUrlFactory mUrlFactory;
private OkHttpClient mHttpClient;
public UrlStack() {
mHttpClient = createHttpClient();
mUrlFactory = new OkUrlFactory(mHttpClient);
setupCertificatePinning();
}
protected static OkHttpClient createHttpClient() {
return new OkHttpClient();
}
@Override
protected HttpURLConnection createConnection(final URL url) throws IOException {
return mUrlFactory.open(url);
}
protected String getHostName() {
return null;
}
protected String[] getPublicKeys() {
return null;
}
private static OkHttpClient getUnsafeOkHttpClient() {
try {
// Create a trust manager that does not validate certificate chains
final TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
@Override
public void checkClientTrusted(final java.security.cert.X509Certificate[] chain, final String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(final java.security.cert.X509Certificate[] chain, final String authType) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
}
};
// Install the all-trusting trust manager
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
// Create an ssl socket factory with our all-trusting manager
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
final OkHttpClient httpClient = createHttpClient();
httpClient.setSslSocketFactory(sslSocketFactory);
httpClient.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
return httpClient;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
protected void setupCertificatePinning() {
final String hostName = getHostName();
final String[] publicKeys = getPublicKeys();
if (!StringToolkit.isEmpty(hostName) && publicKeys != null && publicKeys.length > 0) {
final CertificatePinner.Builder builder = new CertificatePinner.Builder();
for (int i = 0; i < publicKeys.length; i++) {
final byte[] bytes = hexStringToBytes(publicKeys[i]);
builder.add(hostName, PREFIX_SHA1 + Base64.encodeToString(bytes, Base64.DEFAULT));
}
final CertificatePinner certificatePinner = builder.build();
mUrlFactory.client().setCertificatePinner(certificatePinner);
}
}
private byte[] hexStringToBytes(final String hexString) {
final byte[] bytes = new byte[hexString.length() / 2];
int index = 0;
for (int i = 0; i < bytes.length; i++) {
bytes[i] = (byte) ((Character.digit(hexString.charAt(index++), 16) << 4) + Character.digit(hexString.charAt(index++), 16));
}
return bytes;
}
}
|
package fr.cg95.cvq.service.importer.impl;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.anupam.csv.CSVParser;
import net.sf.anupam.csv.CSVParserFactory;
import net.sf.anupam.csv.exceptions.CSVOException;
import org.apache.log4j.Logger;
import fr.cg95.cvq.exception.CvqException;
import fr.cg95.cvq.security.annotation.Context;
import fr.cg95.cvq.security.annotation.ContextPrivilege;
import fr.cg95.cvq.security.annotation.ContextType;
import fr.cg95.cvq.service.importer.ICsvImportProviderService;
import fr.cg95.cvq.service.importer.ICsvParserService;
/**
* Implementation of the {@link ICsvParserService} service.
*
* @author Benoit Orihuela (bor@zenexity.fr)
*/
public class CsvParserService implements ICsvParserService {
private static Logger logger = Logger.getLogger(CsvParserService.class);
private Map<String, ICsvImportProviderService> registeredImporters
= new HashMap<String, ICsvImportProviderService>();
@Override
@Context(types = {ContextType.ADMIN}, privilege = ContextPrivilege.NONE)
public void parseData(String importerName, byte[] csvData)
throws CvqException {
ICsvImportProviderService csvImportProviderService =
registeredImporters.get(importerName);
if (csvImportProviderService == null) {
logger.error("parseData() no importer called " + importerName
+ " found !");
throw new CvqException("parseData() no importer called "
+ importerName + " found !");
} else {
logger.debug("parseData() found importer " + importerName);
}
List<Object> parsedObjects = new ArrayList<Object>();
try {
StringReader xmlMappingReader =
new StringReader(new String(csvImportProviderService.getXmlMappingData()));
StringReader formatterConfigurationReader = null;
if (csvImportProviderService.getFormatterConfigurationData() != null)
formatterConfigurationReader =
new StringReader(new String(csvImportProviderService.getFormatterConfigurationData()));
final CSVParserFactory factory =
new CSVParserFactory(xmlMappingReader, formatterConfigurationReader);
StringReader csvReader = new StringReader(new String(csvData));
final CSVParser parser = factory.getCSVParser(importerName, csvReader);
for (Object bean : parser) {
parsedObjects.add(bean);
}
parser.close();
} catch (CSVOException ce) {
logger.error("CSVO exception : " + ce.getLocalizedMessage());
throw new CvqException("CSVO exception : "
+ ce.getLocalizedMessage());
}
csvImportProviderService.importData(parsedObjects);
}
/**
* Set the importers that will be available on current instance.
*/
public void setImporters(List<Object> importers) {
for (Object o : importers) {
if (o instanceof ICsvImportProviderService) {
ICsvImportProviderService csvImportProviderService =
(ICsvImportProviderService) o;
this.registeredImporters.put(csvImportProviderService.getLabel(),
csvImportProviderService);
logger.debug("CSV plugin " + csvImportProviderService.getLabel() + " added");
} else {
logger.error("Wrong object added to importers property " + o);
}
}
}
}
|
package com.zetwerk.app.zetwerk.apputils;
/**
* Created by varun.am on 19/01/19
*/
public class FirebaseConstants {
public static final String ZETWERK = "zetwerk";
public static final String LAST_EMPLOYEE = "last_employee";
public static final String EMPLOYEES = "employees";
public static final String PHOTOS = "photos";
}
|
import java.util.Map;
import com.skyley.skstack_ip.api.SKDevice;
import com.skyley.skstack_ip.api.SKEventListener;
import com.skyley.skstack_ip.api.SKUtil;
import com.skyley.skstack_ip.api.skenums.SKEventNumber;
import com.skyley.skstack_ip.api.skenums.SKEventType;
import com.skyley.skstack_ip.api.skenums.SKScanMode;
import com.skyley.skstack_ip.api.skevents.SKEEdScan;
import com.skyley.skstack_ip.api.skevents.SKEPanDesc;
import com.skyley.skstack_ip.api.skevents.SKEvent;
import com.skyley.skstack_ip.api.skevents.SKGeneralEvent;
public class ScanTest implements SKEventListener {
private SKDevice device1; // Coordinator
private SKDevice device2;
private SKEventListener oldListener1 = null;
private SKEventListener oldListener2 = null;
private boolean isScanning;
public ScanTest(SKDevice device1, SKDevice device2) {
this.device1 = device1;
this.device2 = device2;
oldListener1 = device1.getSKEventListener();
oldListener2 = device2.getSKEventListener();
device1.setSKEventListener(this);
device2.setSKEventListener(this);
isScanning = false;
}
private void waitScan() {
isScanning = true;
while (isScanning) {
SKUtil.pause(1000);
}
}
public void doTest() {
device1.resetStack();
device2.resetStack();
System.out.println("ED Scan.");
device1.scanChannel(SKScanMode.ED_SCAN, "FFFFFFFF", (byte)6, "0");
waitScan();
System.out.println("Set Channel and PAN ID.");
device1.setChannel((byte)0x24);
device1.setPanID(0x1234);
device1.setBeaconResponseOn();
System.out.println("Active Scan with IE.");
device2.scanChannel(SKScanMode.ACTIVE_SCAN_WITH_IE, "FFFFFFFF", (byte)6, "0");
waitScan();
device2.setParingID("SCANTEST");
System.out.println("Set ParingID SCANTEST");
System.out.println("Acitve Scan with IE.");
device2.scanChannel(SKScanMode.ACTIVE_SCAN_WITH_IE, "FFFFFFFF", (byte)6, "0");
waitScan();
System.out.println("Active Scan without IE.");
device2.scanChannel(SKScanMode.ACTIVE_SCAN_WITHOUT_IE, "FFFFFFFF", (byte)6, "0");
waitScan();
device1.setSKEventListener(oldListener1);
device2.setSKEventListener(oldListener2);
}
@Override
public void eventNotified(String port, SKEventType type, SKEvent event) {
// TODO 自動生成されたメソッド・スタブ
switch (type) {
case EEDSCAN:
System.out.println("EEDSCAN");
System.out.println("Port: " + port);
SKEEdScan eedscan = (SKEEdScan)event;
for (Map.Entry<Byte, Short> entry : eedscan.getEdLevel().entrySet()) {
System.out.println("ch:" + entry.getKey() + " rssi:" + entry.getValue());
}
break;
case EPANDESC:
System.out.println("EPANDESC");
System.out.println("Port: " + port);
SKEPanDesc epandesc = (SKEPanDesc)event;
System.out.println("Channel:" + epandesc.getChannel());
System.out.println("ChannelPage:" + epandesc.getChannelPage());
System.out.println("Pan ID:" + epandesc.getPanID());
System.out.println("Address:" + epandesc.getAddress());
System.out.println("LQI:" + epandesc.getLQI());
System.out.println("Pair ID:" + epandesc.getPairID());
break;
case EVENT:
SKGeneralEvent gevent = (SKGeneralEvent)event;
short number = gevent.getEventNumber();
System.out.println("Event: " + SKEventNumber.getEventName(number));
System.out.println("Port: " + port);
System.out.println("number=" + number);
System.out.println("sender=" + gevent.getSenderAddress());
if (number == SKEventNumber.ED_SCAN_DONE.getNumber() ||
number == SKEventNumber.ACTIVE_SCAN_DONE.getNumber()) {
isScanning = false;
}
break;
default:
break;
}
}
}
|
package com.example.userportal.service;
import com.example.userportal.domain.Order;
import com.example.userportal.service.dto.OrderDTO;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
public interface OrderService {
List<OrderDTO> findAll();
List<OrderDTO> findAllByCustomerId(int customerId);
List<OrderDTO> findAllCurrentCustomerOrders();
Order saveOrder(Order order);
@Transactional
void saveOrderAndCleanShoppingCart(Order order, int customerId);
OrderDTO findById(int id);
OrderDTO updateOrderStatus(int orderId, int statusId);
}
|
package com.example.factory.presenter.contact;
import com.example.common.factory.presenter.BaseContract;
import com.example.factory.model.card.UserCard;
/**
* 关注的契约(接口定义)
* Created by bowen on 2018/3/26.
*/
public interface FollowContract {
// 任务调度者
interface Presenter extends BaseContract.Presenter{
// 关注一个人
void follow(String id);
}
interface View extends BaseContract.View<Presenter>{
// 成功的情况下返回一个用户的信息
void onFollowSucceed(UserCard userCard);
}
}
|
package com.gildedrose;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class BrieItemTest {
@Test
public void brieItemDegradation_1_Day_Elapsed() {
Item[] items = new Item[] { new Item("Aged Brie", 10, 20) };
GildedRose app = new GildedRose(items);
for (int i=0; i < 1; i++) {
app.updateQuality();
}
assertEquals(21, app.items[0].quality);
}
}
|
package com.company.entity;
public abstract class Engine {
private String model;
private double volume;
private int power;
private EnginesType enginesType;
public abstract void start();
public abstract void stop();
}
|
package io.github.qyvlik.iostnode.response.contract;
import com.alibaba.fastjson.annotation.JSONField;
import io.github.qyvlik.iostnode.response.tx.AmountLimit;
import java.util.List;
public class ABI {
@JSONField(name = "name")
private String name;
@JSONField(name = "args")
private List<String> args;
@JSONField(name = "amount_limit")
private List<AmountLimit> amountLimit;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getArgs() {
return args;
}
public void setArgs(List<String> args) {
this.args = args;
}
public List<AmountLimit> getAmountLimit() {
return amountLimit;
}
public void setAmountLimit(List<AmountLimit> amountLimit) {
this.amountLimit = amountLimit;
}
@Override
public String toString() {
return "ABI{" +
"name='" + name + '\'' +
", args=" + args +
", amountLimit=" + amountLimit +
'}';
}
}
|
package view;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.*;
import entity.*;
import service.*;
import java.io.*;
/**
* 修改菜品信息面板
* @author 乐家良
*
*/
public class UpdataMenuPanel extends JPanel implements ActionListener,
ItemListener, ChangeListener, KeyListener {
private JLabel jLabel;
private JLabel jLabel1;
private JLabel jLabel2;
private JLabel jLabel3;
private JComboBox box;
private DefaultComboBoxModel dcm;
private JButton button;
private JButton button2;
private JTextField jTextField;
private FileNameExtensionFilter filter;
private JTextField jTextField3;
private JRadioButton jRadioButton1;
private JRadioButton jRadioButton2;
private JRadioButton jRadioButton3;
private JRadioButton jRadioButton4;
private JLabel _jLabel;
private JLabel _jLabel1;
private JLabel _jLabel2;
private JLabel _jLabel3;
private JComboBox _box;
private DefaultComboBoxModel _dcm;
private JButton _button;
private JButton _button2;
private JTextField _jTextField;
private JTextField _jTextField3;
private JRadioButton _jRadioButton1;
private JRadioButton _jRadioButton2;
private JRadioButton _jRadioButton3;
private JRadioButton _jRadioButton4;
private JLabel __jLabel;
private JLabel __jLabel1;
private JLabel __jLabel2;
private JLabel __jLabel3;
private JComboBox __box;
private DefaultComboBoxModel __dcm;
private JButton __button;
private JButton __button2;
private JTextField __jTextField;
private JTextField __jTextField3;
private JRadioButton __jRadioButton1;
private JRadioButton __jRadioButton2;
private JRadioButton __jRadioButton3;
private JRadioButton __jRadioButton4;
private JLabel ___jLabel;
private JLabel ___jLabel1;
private JLabel ___jLabel2;
private JLabel ___jLabel3;
private JComboBox ___box;
private DefaultComboBoxModel ___dcm;
private JButton ___button;
private JButton ___button2;
private JTextField ___jTextField;
private JTextField ___jTextField3;
private JRadioButton ___jRadioButton1;
private JRadioButton ___jRadioButton2;
private JRadioButton ___jRadioButton3;
private JRadioButton ___jRadioButton4;
private ButtonGroup buttonGroup1;
private ButtonGroup _buttonGroup1;
private ButtonGroup __buttonGroup1;
private ButtonGroup ___buttonGroup1;
private JTabbedPane tab;
private JPanel jPanel = new JPanel();
private JPanel jPanel1 = new JPanel();
private JPanel jPanel2 = new JPanel();
private JPanel jPanel3 = new JPanel();
private JButton button3;
private JButton _button3;
private JButton __button3;
private JButton ___button3;
private JTextField jTextField2;
private JTextField _jTextField2;
private JTextField __jTextField2;
private JTextField ___jTextField2;
private MenuService menuService = new MenuService();
private JFileChooser fileChooser;
private File file;
private boolean flag = false;
private MenuInfo _menuInfo = new MenuInfo();
public UpdataMenuPanel() {
this.setSize(500, 500);
this.setLayout(null);
this.init();
this.bindData();
}
public void init() {
jPanel.setLayout(null);
jPanel1.setLayout(null);
jPanel2.setLayout(null);
jPanel3.setLayout(null);
jPanel.setBackground(new Color(201, 186, 131));
jPanel1.setBackground(new Color(201, 186, 131));
jPanel2.setBackground(new Color(201, 186, 131));
jPanel3.setBackground(new Color(201, 186, 131));
jPanel.setSize(480, 480);
jPanel1.setSize(480, 480);
jPanel2.setSize(480, 480);
jPanel3.setSize(480, 480);
this.button3 = new JButton("添加图片");
this.button3.setBounds(70, 350, 100, 40);
this.jTextField2 = new JTextField();
this.jTextField2.setBounds(250, 350, 100, 40);
this.jTextField2.setOpaque(false);
this.jTextField2.setEditable(false);
this._button3 = new JButton("添加图片");
this._button3.setBounds(70, 350, 100, 40);
this._jTextField2 = new JTextField();
this._jTextField2.setBounds(250, 350, 100, 40);
this._jTextField2.setOpaque(false);
this._jTextField2.setEditable(false);
this.__button3 = new JButton("添加图片");
this.__button3.setBounds(70, 350, 100, 40);
this.__jTextField2 = new JTextField();
this.__jTextField2.setBounds(250, 350, 100, 40);
this.__jTextField2.setOpaque(false);
this.__jTextField2.setEditable(false);
this.___button3 = new JButton("添加图片");
this.___button3.setBounds(70, 350, 100, 40);
this.___jTextField2 = new JTextField();
this.___jTextField2.setBounds(250, 350, 100, 40);
this.___jTextField2.setOpaque(false);
this.___jTextField2.setEditable(false);
this.filter = new FileNameExtensionFilter("所有图片文件", "png", "gif",
"ico", "tif", "tiff", "jpg", "jpeg", "jpe", "jfif", "bmp",
"dib");
this.jLabel = new JLabel("菜名:");
this.jLabel.setBounds(50, 50, 40, 40);
this.jLabel1 = new JLabel("菜名:");
this.jLabel1.setBounds(50, 120, 40, 40);
this.jLabel2 = new JLabel("价格:");
this.jLabel2.setBounds(50, 190, 40, 40);
this.jLabel3 = new JLabel("类型:");
this.jLabel3.setBounds(50, 260, 40, 40);
this.jTextField = new JTextField();
this.jTextField.setBounds(100, 120, 200, 40);
this.button = new JButton("修改");
this.button.setBounds(70, 400, 100, 40);
this.button2 = new JButton("重置");
this.button2.setBounds(250, 400, 100, 40);
this.jTextField3 = new JTextField();
this.jTextField3.setBounds(100, 190, 200, 40);
this.jRadioButton1 = new JRadioButton("小炒");
this.jRadioButton1.setBounds(100, 260, 70, 40);
this.jRadioButton2 = new JRadioButton("火锅");
this.jRadioButton2.setBounds(170, 260, 70, 40);
this.jRadioButton3 = new JRadioButton("汤");
this.jRadioButton3.setBounds(240, 260, 70, 40);
this.jRadioButton4 = new JRadioButton("饮品");
this.jRadioButton4.setBounds(310, 260, 70, 40);
this.jTextField3.setOpaque(false);
this.jRadioButton1.setOpaque(false);
this.jRadioButton2.setOpaque(false);
this.jRadioButton3.setOpaque(false);
this.jRadioButton4.setOpaque(false);
this.box = new JComboBox();
this.box.setBounds(100, 50, 200, 40);
this.dcm = new DefaultComboBoxModel();
this.buttonGroup1 = new ButtonGroup();
this.box.setModel(dcm);
this.buttonGroup1.add(jRadioButton1);
this.buttonGroup1.add(jRadioButton2);
this.buttonGroup1.add(jRadioButton3);
this.buttonGroup1.add(jRadioButton4);
this.tab = new JTabbedPane(JTabbedPane.LEFT);
this.jPanel.add(jLabel);
this.jPanel.add(jLabel1);
this.jPanel.add(jLabel2);
this.jPanel.add(jLabel3);
this.jPanel.add(jTextField);
this.jPanel.add(jTextField3);
this.jPanel.add(jRadioButton1);
this.jPanel.add(jRadioButton2);
this.jPanel.add(jRadioButton3);
this.jPanel.add(jRadioButton4);
this.jPanel.add(button);
this.jPanel.add(button2);
this.jPanel.add(box);
this._jLabel = new JLabel("菜名:");
this._jLabel.setBounds(50, 50, 40, 40);
this._jLabel1 = new JLabel("菜名:");
this._jLabel1.setBounds(50, 120, 40, 40);
this._jLabel2 = new JLabel("价格:");
this._jLabel2.setBounds(50, 190, 40, 40);
this._jLabel3 = new JLabel("类型:");
this._jLabel3.setBounds(50, 260, 40, 40);
this._jTextField = new JTextField();
this._jTextField.setBounds(100, 120, 200, 40);
this._button = new JButton("修改");
this._button.setBounds(70, 400, 100, 40);
this._button2 = new JButton("重置");
this._button2.setBounds(250, 400, 100, 40);
this._jTextField3 = new JTextField();
this._jTextField3.setBounds(100, 190, 200, 40);
this._jRadioButton1 = new JRadioButton("小炒");
this._jRadioButton1.setBounds(100, 260, 70, 40);
this._jRadioButton2 = new JRadioButton("火锅");
this._jRadioButton2.setBounds(170, 260, 70, 40);
this._jRadioButton3 = new JRadioButton("汤");
this._jRadioButton3.setBounds(240, 260, 70, 40);
this._jRadioButton4 = new JRadioButton("饮品");
this._jRadioButton4.setBounds(310, 260, 70, 40);
this._jTextField3.setOpaque(false);
this._jRadioButton1.setOpaque(false);
this._jRadioButton2.setOpaque(false);
this._jRadioButton3.setOpaque(false);
this._jRadioButton4.setOpaque(false);
this._box = new JComboBox();
this._box.setBounds(100, 50, 200, 40);
this._dcm = new DefaultComboBoxModel();
this._buttonGroup1 = new ButtonGroup();
this._box.setModel(_dcm);
this._buttonGroup1.add(_jRadioButton1);
this._buttonGroup1.add(_jRadioButton2);
this._buttonGroup1.add(_jRadioButton3);
this._buttonGroup1.add(_jRadioButton4);
this.jPanel1.add(_jLabel);
this.jPanel1.add(_jLabel1);
this.jPanel1.add(_jLabel2);
this.jPanel1.add(_jLabel3);
this.jPanel1.add(_jTextField);
this.jPanel1.add(_jTextField3);
this.jPanel1.add(_jRadioButton1);
this.jPanel1.add(_jRadioButton2);
this.jPanel1.add(_jRadioButton3);
this.jPanel1.add(_jRadioButton4);
this.jPanel1.add(_button);
this.jPanel1.add(_button2);
this.jPanel1.add(_box);
this.__jLabel = new JLabel("菜名:");
this.__jLabel.setBounds(50, 50, 40, 40);
this.__jLabel1 = new JLabel("菜名:");
this.__jLabel1.setBounds(50, 120, 40, 40);
this.__jLabel2 = new JLabel("价格:");
this.__jLabel2.setBounds(50, 190, 40, 40);
this.__jLabel3 = new JLabel("类型:");
this.__jLabel3.setBounds(50, 260, 40, 40);
this.__jTextField = new JTextField();
this.__jTextField.setBounds(100, 120, 200, 40);
this.__button = new JButton("修改");
this.__button.setBounds(70, 400, 100, 40);
this.__button2 = new JButton("重置");
this.__button2.setBounds(250, 400, 100, 40);
this.__jTextField3 = new JTextField();
this.__jTextField3.setBounds(100, 190, 200, 40);
this.__jRadioButton1 = new JRadioButton("小炒");
this.__jRadioButton1.setBounds(100, 260, 70, 40);
this.__jRadioButton2 = new JRadioButton("火锅");
this.__jRadioButton2.setBounds(170, 260, 70, 40);
this.__jRadioButton3 = new JRadioButton("汤");
this.__jRadioButton3.setBounds(240, 260, 70, 40);
this.__jRadioButton4 = new JRadioButton("饮品");
this.__jRadioButton4.setBounds(310, 260, 70, 40);
this.__jTextField3.setOpaque(false);
this.__jRadioButton1.setOpaque(false);
this.__jRadioButton2.setOpaque(false);
this.__jRadioButton3.setOpaque(false);
this.__jRadioButton4.setOpaque(false);
this.__box = new JComboBox();
this.__box.setBounds(100, 50, 200, 40);
this.__dcm = new DefaultComboBoxModel();
this.__buttonGroup1 = new ButtonGroup();
this.__box.setModel(__dcm);
this.__buttonGroup1.add(__jRadioButton1);
this.__buttonGroup1.add(__jRadioButton2);
this.__buttonGroup1.add(__jRadioButton3);
this.__buttonGroup1.add(__jRadioButton4);
this.___jLabel = new JLabel("菜名:");
this.___jLabel.setBounds(50, 50, 40, 40);
this.___jLabel1 = new JLabel("菜名:");
this.___jLabel1.setBounds(50, 120, 40, 40);
this.___jLabel2 = new JLabel("价格:");
this.___jLabel2.setBounds(50, 190, 40, 40);
this.___jLabel3 = new JLabel("类型:");
this.___jLabel3.setBounds(50, 260, 40, 40);
this.___jTextField = new JTextField();
this.___jTextField.setBounds(100, 120, 200, 40);
this.___button = new JButton("修改");
this.___button.setBounds(70, 400, 100, 40);
this.___button2 = new JButton("重置");
this.___button2.setBounds(250, 400, 100, 40);
this.___jTextField3 = new JTextField();
this.___jTextField3.setBounds(100, 190, 200, 40);
this.___jRadioButton1 = new JRadioButton("小炒");
this.___jRadioButton1.setBounds(100, 260, 70, 40);
this.___jRadioButton2 = new JRadioButton("火锅");
this.___jRadioButton2.setBounds(170, 260, 70, 40);
this.___jRadioButton3 = new JRadioButton("汤");
this.___jRadioButton3.setBounds(240, 260, 70, 40);
this.___jRadioButton4 = new JRadioButton("饮品");
this.___jRadioButton4.setBounds(310, 260, 70, 40);
this.___jTextField3.setOpaque(false);
this.___jRadioButton1.setOpaque(false);
this.___jRadioButton2.setOpaque(false);
this.___jRadioButton3.setOpaque(false);
this.___jRadioButton4.setOpaque(false);
this.___box = new JComboBox();
this.___box.setBounds(100, 50, 200, 40);
this.___dcm = new DefaultComboBoxModel();
this.___buttonGroup1 = new ButtonGroup();
this.___box.setModel(___dcm);
this.___buttonGroup1.add(___jRadioButton1);
this.___buttonGroup1.add(___jRadioButton2);
this.___buttonGroup1.add(___jRadioButton3);
this.___buttonGroup1.add(___jRadioButton4);
this.jTextField.setOpaque(false);
this._jTextField.setOpaque(false);
this.__jTextField.setOpaque(false);
this.___jTextField.setOpaque(false);
this.button.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.button2.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.button3.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.jLabel.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.jLabel1.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.jLabel2.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.jLabel3.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.jTextField3.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.jRadioButton1.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.jRadioButton2.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.jRadioButton3.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.jRadioButton4.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.jTextField.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.jTextField2.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.button.setForeground(new Color(92, 167, 186));
this.button2.setForeground(new Color(92, 167, 186));
this.button3.setForeground(new Color(92, 167, 186));
this.jLabel.setForeground(new Color(92, 167, 186));
this.jLabel1.setForeground(new Color(92, 167, 186));
this.jLabel2.setForeground(new Color(92, 167, 186));
this.jLabel3.setForeground(new Color(92, 167, 186));
this.jTextField3.setForeground(new Color(92, 167, 186));
this.jRadioButton1.setForeground(new Color(92, 167, 186));
this.jRadioButton2.setForeground(new Color(92, 167, 186));
this.jRadioButton3.setForeground(new Color(92, 167, 186));
this.jRadioButton4.setForeground(new Color(92, 167, 186));
this.jTextField.setForeground(new Color(92, 167, 186));
this.jTextField2.setForeground(new Color(92, 167, 186));
this._button.setFont(new Font("华文行楷", Font.PLAIN, 14));
this._button2.setFont(new Font("华文行楷", Font.PLAIN, 14));
this._button3.setFont(new Font("华文行楷", Font.PLAIN, 14));
this._jLabel.setFont(new Font("华文行楷", Font.PLAIN, 14));
this._jLabel1.setFont(new Font("华文行楷", Font.PLAIN, 14));
this._jLabel2.setFont(new Font("华文行楷", Font.PLAIN, 14));
this._jLabel3.setFont(new Font("华文行楷", Font.PLAIN, 14));
this._jTextField3.setFont(new Font("华文行楷", Font.PLAIN, 14));
this._jRadioButton1.setFont(new Font("华文行楷", Font.PLAIN, 14));
this._jRadioButton2.setFont(new Font("华文行楷", Font.PLAIN, 14));
this._jRadioButton3.setFont(new Font("华文行楷", Font.PLAIN, 14));
this._jRadioButton4.setFont(new Font("华文行楷", Font.PLAIN, 14));
this._jTextField.setFont(new Font("华文行楷", Font.PLAIN, 14));
this._jTextField2.setFont(new Font("华文行楷", Font.PLAIN, 14));
this._button.setForeground(new Color(92, 167, 186));
this._button2.setForeground(new Color(92, 167, 186));
this._button3.setForeground(new Color(92, 167, 186));
this._jLabel.setForeground(new Color(92, 167, 186));
this._jLabel1.setForeground(new Color(92, 167, 186));
this._jLabel2.setForeground(new Color(92, 167, 186));
this._jLabel3.setForeground(new Color(92, 167, 186));
this._jTextField3.setForeground(new Color(92, 167, 186));
this._jRadioButton1.setForeground(new Color(92, 167, 186));
this._jRadioButton2.setForeground(new Color(92, 167, 186));
this._jRadioButton3.setForeground(new Color(92, 167, 186));
this._jRadioButton4.setForeground(new Color(92, 167, 186));
this._jTextField.setForeground(new Color(92, 167, 186));
this._jTextField2.setForeground(new Color(92, 167, 186));
this.__button.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.__button2.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.__button3.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.__jLabel.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.__jLabel1.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.__jLabel2.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.__jLabel3.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.__jTextField3.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.__jRadioButton1.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.__jRadioButton2.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.__jRadioButton3.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.__jRadioButton4.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.__jTextField.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.__jTextField2.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.__button.setForeground(new Color(92, 167, 186));
this.__button2.setForeground(new Color(92, 167, 186));
this.__button3.setForeground(new Color(92, 167, 186));
this.__jLabel.setForeground(new Color(92, 167, 186));
this.__jLabel1.setForeground(new Color(92, 167, 186));
this.__jLabel2.setForeground(new Color(92, 167, 186));
this.__jLabel3.setForeground(new Color(92, 167, 186));
this.__jTextField3.setForeground(new Color(92, 167, 186));
this.__jRadioButton1.setForeground(new Color(92, 167, 186));
this.__jRadioButton2.setForeground(new Color(92, 167, 186));
this.__jRadioButton3.setForeground(new Color(92, 167, 186));
this.__jRadioButton4.setForeground(new Color(92, 167, 186));
this.__jTextField.setForeground(new Color(92, 167, 186));
this.__jTextField2.setForeground(new Color(92, 167, 186));
this.___button.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.___button2.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.___button3.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.___jLabel.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.___jLabel1.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.___jLabel2.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.___jLabel3.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.___jTextField3.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.___jRadioButton1.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.___jRadioButton2.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.___jRadioButton3.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.___jRadioButton4.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.___jTextField.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.___jTextField2.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.___button.setForeground(new Color(92, 167, 186));
this.___button2.setForeground(new Color(92, 167, 186));
this.___button3.setForeground(new Color(92, 167, 186));
this.___jLabel.setForeground(new Color(92, 167, 186));
this.___jLabel1.setForeground(new Color(92, 167, 186));
this.___jLabel2.setForeground(new Color(92, 167, 186));
this.___jLabel3.setForeground(new Color(92, 167, 186));
this.___jTextField3.setForeground(new Color(92, 167, 186));
this.___jRadioButton1.setForeground(new Color(92, 167, 186));
this.___jRadioButton2.setForeground(new Color(92, 167, 186));
this.___jRadioButton3.setForeground(new Color(92, 167, 186));
this.___jRadioButton4.setForeground(new Color(92, 167, 186));
this.___jTextField.setForeground(new Color(92, 167, 186));
this.___jTextField2.setForeground(new Color(92, 167, 186));
this.jPanel.add(button3);
this.jPanel.add(jTextField2);
this.jPanel1.add(_button3);
this.jPanel1.add(_jTextField2);
this.jPanel2.add(__button3);
this.jPanel2.add(__jTextField2);
this.jPanel2.add(__jLabel);
this.jPanel2.add(__jLabel1);
this.jPanel2.add(__jLabel2);
this.jPanel2.add(__jLabel3);
this.jPanel2.add(__jTextField);
this.jPanel2.add(__jTextField3);
this.jPanel2.add(__jRadioButton1);
this.jPanel2.add(__jRadioButton2);
this.jPanel2.add(__jRadioButton3);
this.jPanel2.add(__jRadioButton4);
this.jPanel2.add(__button);
this.jPanel2.add(__button2);
this.jPanel2.add(__box);
this.jPanel3.add(___button3);
this.jPanel3.add(___jTextField2);
this.jPanel3.add(___jLabel);
this.jPanel3.add(___jLabel1);
this.jPanel3.add(___jLabel2);
this.jPanel3.add(___jLabel3);
this.jPanel3.add(___jTextField);
this.jPanel3.add(___jTextField3);
this.jPanel3.add(___jRadioButton1);
this.jPanel3.add(___jRadioButton2);
this.jPanel3.add(___jRadioButton3);
this.jPanel3.add(___jRadioButton4);
this.jPanel3.add(___button);
this.jPanel3.add(___button2);
this.jPanel3.add(___box);
this.tab.add(jPanel, "小炒");
this.tab.add(jPanel1, "火锅");
this.tab.add(jPanel2, "汤");
this.tab.add(jPanel3, "饮品");
this.tab.setBounds(0, 0, this.getWidth(), this.getHeight());
this.add(tab);
this.button.addActionListener(this);
this.button2.addActionListener(this);
this.button3.addActionListener(this);
this._button.addActionListener(this);
this._button2.addActionListener(this);
this._button3.addActionListener(this);
this.__button.addActionListener(this);
this.__button2.addActionListener(this);
this.__button3.addActionListener(this);
this.___button.addActionListener(this);
this.___button2.addActionListener(this);
this.___button3.addActionListener(this);
this.box.addItemListener(this);
this._box.addItemListener(this);
this.__box.addItemListener(this);
this.___box.addItemListener(this);
this.tab.addChangeListener(this);
this.jTextField3.addKeyListener(this);
this._jTextField3.addKeyListener(this);
this.__jTextField3.addKeyListener(this);
this.___jTextField3.addKeyListener(this);
}
public void bindData() {
this.dcm.addElement("--请选择--");
this._dcm.addElement("--请选择--");
this.__dcm.addElement("--请选择--");
this.___dcm.addElement("--请选择--");
this.jTextField.setText("--请选择菜名--");
this._jTextField.setText("--请选择菜名--");
this.__jTextField.setText("--请选择菜名--");
this.___jTextField.setText("--请选择菜名--");
this.jTextField2.setText("非必须添加项");
this._jTextField2.setText("非必须添加项");
this.__jTextField2.setText("非必须添加项");
this.___jTextField2.setText("非必须添加项");
MenuInfo menuInfo = new MenuInfo();
ArrayList<MenuInfo> menuList = (ArrayList<MenuInfo>) menuService
.getMenInfoList(menuInfo);
for (MenuInfo m : menuList) {
if (m.getM_type().equals("小炒")) {
this.dcm.addElement(m.getM_name());
}
if (m.getM_type().equals("火锅")) {
this._dcm.addElement(m.getM_name());
}
if (m.getM_type().equals("汤")) {
this.__dcm.addElement(m.getM_name());
}
if (m.getM_type().equals("饮品")) {
this.___dcm.addElement(m.getM_name());
}
}
}
public void clearElement() {
this.dcm.removeAllElements();
this._dcm.removeAllElements();
this.buttonGroup1.clearSelection();
this._buttonGroup1.clearSelection();
this.__buttonGroup1.clearSelection();
this.___buttonGroup1.clearSelection();
this.__dcm.removeAllElements();
this.___dcm.removeAllElements();
this.jTextField.setText("--请选择桌名--");
this._jTextField.setText("--请选择桌名--");
this.__jTextField.setText("--请选择桌名--");
this.___jTextField.setText("--请选择桌名--");
this.jTextField2.setText("非必须添加项");
this._jTextField2.setText("非必须添加项");
this.__jTextField2.setText("非必须添加项");
this.___jTextField2.setText("非必须添加项");
this.jTextField3.setText("");
this._jTextField3.setText("");
this.__jTextField3.setText("");
this.___jTextField3.setText("");
this.file = null;
this._menuInfo.setM_name(null);
this.flag = false;
this.bindData();
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if (e.getActionCommand().equals("添加图片")) {
this.fileChooser = new JFileChooser();
this.fileChooser.setAcceptAllFileFilterUsed(false);
this.fileChooser.setFileFilter(filter);
this.fileChooser.showOpenDialog(null);
this.file = this.fileChooser.getSelectedFile();
if (file != null) {
this.jTextField2.setText(this.file.getName());
this._jTextField2.setText(this.file.getName());
this.__jTextField2.setText(this.file.getName());
this.___jTextField2.setText(this.file.getName());
}
}
if (e.getActionCommand().trim().equals("修改")) {
if (this._menuInfo.getM_name() != null) {
MenuInfo newMenuInfo = new MenuInfo();
if (this.jRadioButton1.isSelected()) {
newMenuInfo.setM_type(this.jRadioButton1.getText());
}
if (this.jRadioButton2.isSelected()) {
newMenuInfo.setM_type(this.jRadioButton2.getText());
}
if (this.jRadioButton3.isSelected()) {
newMenuInfo.setM_type(this.jRadioButton3.getText());
}
if (this.jRadioButton4.isSelected()) {
newMenuInfo.setM_type(this.jRadioButton4.getText());
}
if (this._jRadioButton1.isSelected()) {
newMenuInfo.setM_type(this.jRadioButton1.getText());
}
if (this._jRadioButton2.isSelected()) {
newMenuInfo.setM_type(this.jRadioButton2.getText());
}
if (this._jRadioButton3.isSelected()) {
newMenuInfo.setM_type(this.jRadioButton3.getText());
}
if (this._jRadioButton4.isSelected()) {
newMenuInfo.setM_type(this.jRadioButton4.getText());
}
if (this.__jRadioButton1.isSelected()) {
newMenuInfo.setM_type(this.jRadioButton1.getText());
}
if (this.__jRadioButton2.isSelected()) {
newMenuInfo.setM_type(this.jRadioButton2.getText());
}
if (this.__jRadioButton3.isSelected()) {
newMenuInfo.setM_type(this.jRadioButton3.getText());
}
if (this.__jRadioButton4.isSelected()) {
newMenuInfo.setM_type(this.jRadioButton4.getText());
}
if (this.___jRadioButton1.isSelected()) {
newMenuInfo.setM_type(this.jRadioButton1.getText());
}
if (this.___jRadioButton2.isSelected()) {
newMenuInfo.setM_type(this.jRadioButton2.getText());
}
if (this.___jRadioButton3.isSelected()) {
newMenuInfo.setM_type(this.jRadioButton3.getText());
}
if (this.___jRadioButton4.isSelected()) {
newMenuInfo.setM_type(this.jRadioButton4.getText());
}
MenuInfo menuInfo1 = menuService.getMenInfoList(this._menuInfo)
.get(0);
if (menuInfo1.getM_type().equals("小炒")) {
newMenuInfo.setM_name(this.jTextField.getText());
if (!this.jTextField3.getText().equals("")) {
newMenuInfo.setM_price(Double
.parseDouble(this.jTextField3.getText()));
flag = true;
} else {
JOptionPane.showMessageDialog(this, "请输入价格");
flag = false;
}
}
if (menuInfo1.getM_type().equals("火锅")) {
newMenuInfo.setM_name(this._jTextField.getText());
if (!this._jTextField3.getText().equals("")) {
newMenuInfo.setM_price(Double
.parseDouble(this._jTextField3.getText()));
flag = true;
} else {
JOptionPane.showMessageDialog(this, "请输入价格");
flag = false;
}
}
if (menuInfo1.getM_type().equals("汤")) {
newMenuInfo.setM_name(this.__jTextField.getText());
if (!this.__jTextField3.getText().equals("")) {
newMenuInfo.setM_price(Double
.parseDouble(this.__jTextField3.getText()));
flag = true;
} else {
JOptionPane.showMessageDialog(this, "请输入价格");
flag = false;
}
}
if (menuInfo1.getM_type().equals("饮品")) {
newMenuInfo.setM_name(this.___jTextField.getText());
if (!this.___jTextField3.getText().equals("")) {
newMenuInfo.setM_price(Double
.parseDouble(this.___jTextField3.getText()));
flag = true;
} else {
JOptionPane.showMessageDialog(this, "请输入价格");
flag = false;
}
}
if (!newMenuInfo.getM_name().equals("") && flag == true) {
MenuInfo findMenuInfo = new MenuInfo();
findMenuInfo.setM_name(newMenuInfo.getM_name());
if (menuService.getMenInfoList(findMenuInfo).size() == 0
|| newMenuInfo.getM_name().equals(
this._menuInfo.getM_name())) {
if (file != null) {
try {
FileInputStream fileInputStream = new FileInputStream(
file);
BufferedInputStream bufferedInputStream = new BufferedInputStream(
fileInputStream);
FileOutputStream fileOutputStream = new FileOutputStream(
"images/" + newMenuInfo.getM_name()
+ ".jpg", false);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(
fileOutputStream);
byte[] b = new byte[1024];
if (menuService.updataMenu(newMenuInfo,
_menuInfo) > 0) {
JOptionPane.showMessageDialog(this, "修改成功");
try {
int count = bufferedInputStream.read(b,
0, 1024);
while (count > 0) {
bufferedOutputStream.write(b, 0,
count);
count = bufferedInputStream.read(b,
0, 1024);
}
bufferedOutputStream.close();
this.clearElement();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
JOptionPane.showMessageDialog(this, "配图成功");
} else {
JOptionPane.showMessageDialog(this,
"发生了一个未知错误,请联系开发者");
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} else {
if (menuService.updataMenu(newMenuInfo, _menuInfo) > 0) {
JOptionPane.showMessageDialog(this, "修改成功");
this.clearElement();
}
JOptionPane.showMessageDialog(this, "没有进行配图");
}
} else {
JOptionPane.showMessageDialog(this, "新的菜品名称与其他现有名称冲突了");
}
} else if (newMenuInfo.getM_name().equals("")) {
JOptionPane.showMessageDialog(this, "请输入修改后的菜名");
}
} else {
JOptionPane.showMessageDialog(this, "请选择菜品!");
}
}
if (e.getActionCommand().trim().equals("重置")) {
this.clearElement();
}
}
@Override
public void stateChanged(ChangeEvent e) {
// TODO Auto-generated method stub
this.clearElement();
}
@Override
public void itemStateChanged(ItemEvent e) {
// TODO Auto-generated method stub
int index = 0;
index = e.getStateChange();
if (index == 1) {
if (!e.getItem().toString().equals("--请选择--")) {
_menuInfo.setM_name(e.getItem().toString());
MenuInfo menuInfo1 = menuService.getMenInfoList(this._menuInfo)
.get(0);
if (menuInfo1.getM_type().equals("小炒")) {
this.jTextField.setText(menuInfo1.getM_name());
this.jTextField3.setText(Double.toString(menuInfo1
.getM_price()));
this.jRadioButton1.setSelected(true);
}
if (menuInfo1.getM_type().equals("火锅")) {
this._jTextField.setText(menuInfo1.getM_name());
this._jTextField3.setText(Double.toString(menuInfo1
.getM_price()));
this._jRadioButton2.setSelected(true);
}
if (menuInfo1.getM_type().equals("汤")) {
this.__jTextField.setText(menuInfo1.getM_name());
this.__jTextField3.setText(Double.toString(menuInfo1
.getM_price()));
this.__jRadioButton3.setSelected(true);
}
if (menuInfo1.getM_type().equals("饮品")) {
this.___jTextField.setText(menuInfo1.getM_name());
this.___jTextField3.setText(Double.toString(menuInfo1
.getM_price()));
this.___jRadioButton4.setSelected(true);
}
} else {
this.buttonGroup1.clearSelection();
this._buttonGroup1.clearSelection();
this.__buttonGroup1.clearSelection();
this.___buttonGroup1.clearSelection();
this.jTextField.setText("--请选择菜品--");
this._jTextField.setText("--请选择菜品--");
this.__jTextField.setText("--请选择菜品--");
this.___jTextField.setText("--请选择菜品--");
this.jTextField2.setText("非必须添加项");
this._jTextField2.setText("非必须添加项");
this.__jTextField2.setText("非必须添加项");
this.___jTextField2.setText("非必须添加项");
this.jTextField3.setText("");
this._jTextField3.setText("");
this.__jTextField3.setText("");
this.___jTextField3.setText("");
this.file = null;
this._menuInfo.setM_name(null);
this.flag = false;
}
}
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
int keyChar = e.getKeyChar();
if (!this.jTextField3.getText().equals("")
&& this.jTextField3.getText().indexOf(".") < 0) {
if (keyChar == '.'
|| (keyChar >= KeyEvent.VK_0 && keyChar <= KeyEvent.VK_9)) {
} else {
e.consume(); // 关键,屏蔽掉非法输入
}
} else if (!this._jTextField3.getText().equals("")
&& this._jTextField3.getText().indexOf(".") < 0) {
if (keyChar == '.'
|| (keyChar >= KeyEvent.VK_0 && keyChar <= KeyEvent.VK_9)) {
} else {
e.consume(); // 关键,屏蔽掉非法输入
}
} else if (!this.__jTextField3.getText().equals("")
&& this.__jTextField3.getText().indexOf(".") < 0) {
if (keyChar == '.'
|| (keyChar >= KeyEvent.VK_0 && keyChar <= KeyEvent.VK_9)) {
} else {
e.consume(); // 关键,屏蔽掉非法输入
}
} else if (!this.___jTextField3.getText().equals("")
&& this.___jTextField3.getText().indexOf(".") < 0) {
if (keyChar == '.'
|| (keyChar >= KeyEvent.VK_0 && keyChar <= KeyEvent.VK_9)) {
} else {
e.consume(); // 关键,屏蔽掉非法输入
}
} else {
if (keyChar >= KeyEvent.VK_0 && keyChar <= KeyEvent.VK_9) {
} else {
e.consume(); // 关键,屏蔽掉非法输入
}
}
}
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
}
|
package com.atn.app.webservices;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import com.atn.app.datamodels.NonAtnVenueData;
import com.atn.app.utils.HttpUtility;
import com.atn.app.webservices.WebserviceType.ServiceType;
public class NonAtnFavoriteWebservice extends WebserviceBase
{
private static final String FAVORITE_API = "/favoritebar";
private static final String UNFAVORITE_API = "/unfavoritebar";
private NonAtnFavoriteWebserviceListener mFavoriteWebserviceListener;
private NonAtnVenueData venueData;
private ServiceType nonAtnFavServiceType;
public NonAtnFavoriteWebservice()
{
super(HttpUtility.BASE_SERVICE_URL + FAVORITE_API);
setRequestType(RequestType.POST);
setWebserviceType(ServiceType.NON_ATN_FAVORITE);
setWebserviceListener(mWebserviceListener);
venueData = new NonAtnVenueData();
}
public void setNonAtnFavoriteWebserviceListener(NonAtnFavoriteWebserviceListener listener)
{
mFavoriteWebserviceListener = listener;
}
private WebserviceListener mWebserviceListener = new WebserviceListener()
{
@Override
public void onSetUrlError(ServiceType serviceType, Exception ex)
{
if(serviceType == ServiceType.NON_ATN_FAVORITE || serviceType == ServiceType.NON_ATN_UNFAVORITE)
{
if(mFavoriteWebserviceListener != null)
{
mFavoriteWebserviceListener.onFailed(WebserviceError.URL_ERROR, ex.getMessage());
}
}
}
@Override
public void onServiceResult(ServiceType serviceType, String result)
{
if(serviceType == ServiceType.NON_ATN_FAVORITE || serviceType == ServiceType.NON_ATN_UNFAVORITE)
{
if(mFavoriteWebserviceListener != null)
{
mFavoriteWebserviceListener.onSuccess(nonAtnFavServiceType, getParsedData(result));
}
}
}
@Override
public void onServiceError(ServiceType serviceType, int errorCode, String errorMessage)
{
if(serviceType == ServiceType.NON_ATN_FAVORITE || serviceType == ServiceType.NON_ATN_UNFAVORITE)
{
if(mFavoriteWebserviceListener != null)
{
mFavoriteWebserviceListener.onFailed(errorCode, errorMessage);
}
}
}
@Override
public void onNoInternet(ServiceType serviceType, Exception ex)
{
if(serviceType == ServiceType.NON_ATN_FAVORITE || serviceType == ServiceType.NON_ATN_UNFAVORITE)
{
if(mFavoriteWebserviceListener != null)
{
mFavoriteWebserviceListener.onFailed(WebserviceError.INTERNET_ERROR, ex.getMessage());
}
}
}
};
/**
* Returns non-registerd venue details with venue id that is favorited. These details is used to store venue
* details in database and same details will be used to unfavorite venue or delete venue from database.
*
* @param response to parse.
* @return NonAtnVenueData with venue id.
*/
private NonAtnVenueData getParsedData(String response)
{
try
{
JSONObject dataObject = new JSONObject(response);
if(!dataObject.isNull(NonAtnVenueData.VENUE_ID))
{
venueData.setVenueId(dataObject.getString(NonAtnVenueData.VENUE_ID));
}
return venueData;
}
catch (JSONException e)
{
return null;
}
}
/**
* Return synchronous web service response from the server. This should be called within the background
* thread.
*
* @return web service response.
*/
public WebserviceResponse setFavoriteVenueSync(NonAtnVenueData venueData)
{
try
{
setUrl(HttpUtility.BASE_SERVICE_URL + FAVORITE_API);
setRequestType(RequestType.POST);
setWebserviceType(ServiceType.NON_ATN_FAVORITE);
nonAtnFavServiceType = ServiceType.NON_ATN_FAVORITE;
ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair(NonAtnVenueData.USER_ID, venueData.getUserId()));
nameValuePair.add(new BasicNameValuePair(NonAtnVenueData.VENUE_NAME, venueData.getVenueName()));
nameValuePair.add(new BasicNameValuePair(NonAtnVenueData.VENUE_LAT, venueData.getVenueLat()));
nameValuePair.add(new BasicNameValuePair(NonAtnVenueData.VENUE_LNG, venueData.getVenueLng()));
nameValuePair.add(new BasicNameValuePair(NonAtnVenueData.VENUE_ADDRESS, venueData.getVenueAddress()));
nameValuePair.add(new BasicNameValuePair(NonAtnVenueData.FS_VENUE_ID, venueData.getVenueFsId()));
if(venueData.getVenueDescription() != null)
nameValuePair.add(new BasicNameValuePair(NonAtnVenueData.VENUE_DESCRIPTION, venueData.getVenueDescription()));
if(venueData.getVenueFsLink() != null)
nameValuePair.add(new BasicNameValuePair(NonAtnVenueData.FS_VENUE_LINK, venueData.getVenueFsLink()));
if(venueData.getInstaLocId() != null)
nameValuePair.add(new BasicNameValuePair(NonAtnVenueData.INSTA_LOCATION_ID, venueData.getInstaLocId()));
setPostData(nameValuePair);
}
catch (Exception e)
{
e.printStackTrace();
}
return doRequestSynch();
}
/**
* Asynchronously calls the web service to get the registered ATN venues. Response of this web service can
* be captured from web service listener.
*/
public void setFavoriteVenue(NonAtnVenueData venueData)
{
try
{
setUrl(HttpUtility.BASE_SERVICE_URL + FAVORITE_API);
setRequestType(RequestType.POST);
setWebserviceType(ServiceType.NON_ATN_FAVORITE);
nonAtnFavServiceType = ServiceType.NON_ATN_FAVORITE;
ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair(NonAtnVenueData.USER_ID, venueData.getUserId()));
nameValuePair.add(new BasicNameValuePair(NonAtnVenueData.VENUE_NAME, venueData.getVenueName()));
nameValuePair.add(new BasicNameValuePair(NonAtnVenueData.VENUE_LAT, venueData.getVenueLat()));
nameValuePair.add(new BasicNameValuePair(NonAtnVenueData.VENUE_LNG, venueData.getVenueLng()));
nameValuePair.add(new BasicNameValuePair(NonAtnVenueData.VENUE_ADDRESS, venueData.getVenueAddress()));
nameValuePair.add(new BasicNameValuePair(NonAtnVenueData.FS_VENUE_ID, venueData.getVenueFsId()));
if(venueData.getVenueDescription() != null)
nameValuePair.add(new BasicNameValuePair(NonAtnVenueData.VENUE_DESCRIPTION, venueData.getVenueDescription()));
if(venueData.getVenueFsLink() != null)
nameValuePair.add(new BasicNameValuePair(NonAtnVenueData.FS_VENUE_LINK, venueData.getVenueFsLink()));
if(venueData.getInstaLocId() != null)
nameValuePair.add(new BasicNameValuePair(NonAtnVenueData.INSTA_LOCATION_ID, venueData.getInstaLocId()));
setPostData(nameValuePair);
doRequestAsync();
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* Return synchronous web service response from the server. This should be called within the background
* thread.
*
* @return web service response.
*/
public WebserviceResponse setUnFavoriteVenueSync(String userId, String venueId)
{
try
{
venueData.setVenueId(venueId);
setUrl(HttpUtility.BASE_SERVICE_URL + UNFAVORITE_API);
setRequestType(RequestType.POST);
setWebserviceType(ServiceType.NON_ATN_UNFAVORITE);
nonAtnFavServiceType = ServiceType.NON_ATN_UNFAVORITE;
ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair(NonAtnVenueData.USER_ID, userId));
nameValuePair.add(new BasicNameValuePair(NonAtnVenueData.VENUE_ID, venueId));
setPostData(nameValuePair);
}
catch (Exception e)
{
e.printStackTrace();
}
return doRequestSynch();
}
/**
* Asynchronously calls the web service to get the registered ATN venues. Response of this web service can
* be captured from web service listener.
*/
public void setUnFavoriteVenue(String userId, String venueId)
{
try {
venueData.setVenueId(venueId);
setUrl(HttpUtility.BASE_SERVICE_URL + UNFAVORITE_API);
setRequestType(RequestType.POST);
setWebserviceType(ServiceType.NON_ATN_UNFAVORITE);
nonAtnFavServiceType = ServiceType.NON_ATN_UNFAVORITE;
ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair(NonAtnVenueData.USER_ID,userId));
nameValuePair.add(new BasicNameValuePair(NonAtnVenueData.VENUE_ID,venueId));
setPostData(nameValuePair);
doRequestAsync();
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package org.sang.controller;
import org.sang.bean.RespBean;
import org.sang.bean.User;
import org.sang.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
/**
* Created by albert on 2019/12/20.
*/
@Controller
public class LoginRegController {
@Autowired
UserService userService;
@RequestMapping("/login_error")
@ResponseBody
public RespBean loginError() {
System.out.println("sahf");
return new RespBean("error", "登录失败sfg!");
}
@RequestMapping("/login_success")
@ResponseBody
public RespBean loginSuccess() {
return new RespBean("success", "登录成功s!");
}
/**
* 如果自动跳转到这个页面,说明用户未登录,返回相应的提示即可
* <p>
* 如果要支持表单登录,可以在这个方法中判断请求的类型,进而决定返回JSON还是HTML页面
*
* @return
*/
@RequestMapping("/login_page")
public RespBean loginPage() {
return new RespBean("error", "尚未登录,请登录!");
}
}
|
package com.vilio.ppms.dao.common;
import com.vilio.ppms.pojo.common.SystemRoute;
public interface SystemRouteMapper {
int deleteByPrimaryKey(Long id);
int insert(SystemRoute record);
int insertSelective(SystemRoute record);
SystemRoute selectByPrimaryKey(Long id);
int updateByPrimaryKeySelective(SystemRoute record);
int updateByPrimaryKey(SystemRoute record);
}
|
package com.gym.appointments.Model;
import java.util.List;
import java.util.UUID;
public class AlphabetSoup {
int w;
int h;
boolean ltr = true; //Por defecto true
boolean rtl; //Por defecto false
boolean ttb = true; //Por defecto true
boolean btt; //Por defecto false
boolean d; //Por defecto false
int c = 1; //Categoria, Por defecto Todas las palabras
SopaDePalabras sopaDePalabras;
List<Ubicacion> ubicaciones;
public AlphabetSoup() {
}
public AlphabetSoup( int w, int h, boolean ltr, boolean rtl, boolean ttb, boolean btt, boolean d, int c, SopaDePalabras sopaDePalabras, List<Ubicacion> ubicaciones) {
this.w = w;
this.h = h;
this.ltr = ltr;
this.rtl = rtl;
this.ttb = ttb;
this.btt = btt;
this.d = d;
this.c = c;
this.sopaDePalabras = sopaDePalabras;
this.ubicaciones = ubicaciones;
}
public int getW() {
return w;
}
public void setW(int w) {
this.w = w;
}
public int getH() {
return h;
}
public void setH(int h) {
this.h = h;
}
public boolean isLtr() {
return ltr;
}
public void setLtr(boolean ltr) {
this.ltr = ltr;
}
public boolean isRtl() {
return rtl;
}
public void setRtl(boolean rtl) {
this.rtl = rtl;
}
public boolean isTtb() {
return ttb;
}
public void setTtb(boolean ttb) {
this.ttb = ttb;
}
public boolean isBtt() {
return btt;
}
public void setBtt(boolean btt) {
this.btt = btt;
}
public boolean isD() {
return d;
}
public void setD(boolean d) {
this.d = d;
}
public int getC() {
return c;
}
public void setC(int c) {
this.c = c;
}
public CategoriasPalabras getCategoriasPalabrasByOrdinal(){
if(CategoriasPalabras.TODAS_LAS_PALABRAS.ordinal() + 1 == this.c){
return CategoriasPalabras.TODAS_LAS_PALABRAS;
}else if(CategoriasPalabras.ANIMALES.ordinal() + 1 == this.c){
return CategoriasPalabras.ANIMALES;
}else if(CategoriasPalabras.NATURALEZA.ordinal() + 1 == this.c){
return CategoriasPalabras.NATURALEZA;
}else if(CategoriasPalabras.FIGURAS.ordinal() + 1 == this.c){
return CategoriasPalabras.FIGURAS;
}else if(CategoriasPalabras.HOGAR.ordinal() + 1 == this.c){
return CategoriasPalabras.HOGAR;
}else if(CategoriasPalabras.FAMILIA.ordinal() + 1 == this.c){
return CategoriasPalabras.FAMILIA;
}else if(CategoriasPalabras.PAISES.ordinal() + 1 == this.c){
return CategoriasPalabras.PAISES;
}else if(CategoriasPalabras.CIUDADES.ordinal() + 1 == this.c){
return CategoriasPalabras.CIUDADES;
}else if(CategoriasPalabras.DEPORTE.ordinal() + 1 == this.c){
return CategoriasPalabras.DEPORTE;
}else if(CategoriasPalabras.PROFESIONES.ordinal() + 1 == this.c){
return CategoriasPalabras.PROFESIONES;
}else{
return CategoriasPalabras.COLORES;
}
}
public SopaDePalabras getSopaDePalabras() {
return sopaDePalabras;
}
public void setSopaDePalabras(SopaDePalabras sopaDePalabras) {
this.sopaDePalabras = sopaDePalabras;
}
public List<Ubicacion> getUbicaciones() {
return ubicaciones;
}
public void setUbicaciones(List<Ubicacion> ubicaciones) {
this.ubicaciones = ubicaciones;
}
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs;
import java.io.IOException;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.LinkedList;
import java.util.List;
import java.util.HashSet;
import java.util.Set;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.RemoteIterator;
import org.apache.hadoop.hdfs.protocol.LocatedBlock;
import org.apache.hadoop.hdfs.protocol.LocatedBlocks;
import org.apache.hadoop.hdfs.tools.DFSck;
import org.apache.hadoop.util.ToolRunner;
public abstract class RaidDFSUtil {
/**
* Returns the corrupt blocks in a file.
*/
public static List<LocatedBlock> corruptBlocksInFile(
DistributedFileSystem dfs, String path, long offset, long length)
throws IOException {
List<LocatedBlock> corrupt = new LinkedList<LocatedBlock>();
LocatedBlocks locatedBlocks =
getBlockLocations(dfs, path, offset, length);
for (LocatedBlock b: locatedBlocks.getLocatedBlocks()) {
if (b.isCorrupt() ||
(b.getLocations().length == 0 && b.getBlockSize() > 0)) {
corrupt.add(b);
}
}
return corrupt;
}
public static LocatedBlocks getBlockLocations(
DistributedFileSystem dfs, String path, long offset, long length)
throws IOException {
return dfs.getClient().namenode.getBlockLocations(path, offset, length);
}
/**
* Make successive calls to listCorruptFiles to obtain all
* corrupt files.
*/
public static String[] getCorruptFiles(DistributedFileSystem dfs)
throws IOException {
Set<String> corruptFiles = new HashSet<String>();
RemoteIterator<Path> cfb = dfs.listCorruptFileBlocks(new Path("/"));
while (cfb.hasNext()) {
corruptFiles.add(cfb.next().toUri().getPath());
}
return corruptFiles.toArray(new String[corruptFiles.size()]);
}
}
|
package com.isystk.sample.batch.jobs.importMst;
import com.isystk.sample.batch.listener.BaseJobExecutionListener;
public class ImportMstJobListener extends BaseJobExecutionListener {
@Override
protected String getBatchId() {
return "BATCH_002";
}
@Override
protected String getBatchName() {
return "マスタデータ取り込み";
}
}
|
package org.opentosca.core.model.artifact.directory.impl;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.opentosca.core.model.artifact.directory.AbstractDirectory;
import org.opentosca.core.model.artifact.file.AbstractFile;
import org.opentosca.core.model.artifact.file.impl.CSARFile;
import org.opentosca.core.model.csar.id.CSARID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Represents a directory in a CSAR.<br />
* Provides methods for browsing and getting the meta data of the directory by
* using the local stored meta data of the CSAR.<br />
* <br />
* Copyright 2013 IAAS University of Stuttgart<br />
* <br />
*
* @author Rene Trefft - rene.trefft@developers.opentosca.org
*
*/
public class CSARDirectory extends AbstractDirectory {
private final static Logger LOG = LoggerFactory.getLogger(CSARDirectory.class);
/**
* CSAR ID of CSAR that contains this directory.
*/
private final CSARID CSAR_ID;
/**
* Files and directories in this directory.
*/
private final Set<Path> DIRECTORIES;
private final Map<Path, String> FILE_TO_STORAGE_PROVIDER_ID_MAP;
/**
* Creates a {@link CSARDirectory} without any include / exclude patterns
* which have to be considered. Besides, the directory not represents a file
* artifact (reference of a file artifact points to a file).
*
* @param path - relative path to CSAR root of this directory. An empty
* string means the root.
* @param csarID of CSAR that contains this directory.
* @param directories - directories in this directory (recursively). Each
* directory must be given relative to the CSAR root.
* @param fileToStorageProviderIDMap - file to storage provider ID mapping
* of all files in this directory (recursively). Each file path
* must be given relative to the CSAR root.
*/
public CSARDirectory(String directoryPath, CSARID csarID, Set<Path> directories, Map<Path, String> fileToStorageProviderIDMap) {
// no patterns, so we pass empty sets (immutable to avoid unnecessary
// object creations)
this(directoryPath, Collections.<String> emptySet(), Collections.<String> emptySet(), csarID, directories, fileToStorageProviderIDMap, false);
}
/**
* Creates a {@link CSARDirectory}.
*
* @param path - relative path to CSAR root of this directory. An empty
* string means the root.
* @param includePatterns to include only certain files in this directory.
* @param excludePatterns to exclude certain files from this directory.
* @param csarID of CSAR that contains this directory.
* @param directories - directories in this directory (recursively). Each
* directory must be given relative to the CSAR root.
* @param fileArtifact - {@code true} if this directory represents a file
* artifact (directory contains only the file at the artifact
* reference), otherwise {@code false}.
* @param fileToStorageProviderIDMap - file to storage provider ID mapping
* of files in this directory (recursively). Each file must be
* given relative to the CSAR root.
*/
public CSARDirectory(String directoryPath, Set<String> includePatterns, Set<String> excludePatterns, CSARID csarID, Set<Path> directories, Map<Path, String> fileToStorageProviderIDMap, boolean fileArtifact) {
super(directoryPath, includePatterns, excludePatterns, fileArtifact);
this.FILE_TO_STORAGE_PROVIDER_ID_MAP = fileToStorageProviderIDMap;
this.CSAR_ID = csarID;
this.DIRECTORIES = directories;
}
@Override
protected AbstractFile getFileNotConsiderPatterns(String relPathOfFile) {
Path relPathOfFileToCSARRoot = Paths.get(this.getPath()).resolve(relPathOfFile);
if (!this.isFileArtifact()) {
for (Map.Entry<Path, String> fileToStorageProviderIDEntry : this.FILE_TO_STORAGE_PROVIDER_ID_MAP.entrySet()) {
Path file = fileToStorageProviderIDEntry.getKey();
String fileStorageProviderID = fileToStorageProviderIDEntry.getValue();
// found file to get
if (file.equals(relPathOfFileToCSARRoot)) {
return new CSARFile(file.toString(), this.CSAR_ID, fileStorageProviderID);
}
}
} else {
// If it's a file artifact we know directly that the one file in the
// Map is the file of the artifact.
for (Map.Entry<Path, String> fileToStorageProviderIDEntry : this.FILE_TO_STORAGE_PROVIDER_ID_MAP.entrySet()) {
Path file = fileToStorageProviderIDEntry.getKey();
String fileStorageProviderID = fileToStorageProviderIDEntry.getValue();
return new CSARFile(file.toString(), this.CSAR_ID, fileStorageProviderID);
}
}
return null;
}
@Override
protected Set<AbstractFile> getFilesNotConsiderPatterns() {
Set<AbstractFile> csarFiles = new HashSet<AbstractFile>();
if (!this.isFileArtifact()) {
Path directoryReferenceAsPath = Paths.get(this.getPath());
for (Map.Entry<Path, String> fileToStorageProviderIDEntry : this.FILE_TO_STORAGE_PROVIDER_ID_MAP.entrySet()) {
Path file = fileToStorageProviderIDEntry.getKey();
Path fileParent = file.getParent();
String fileStorageProviderID = fileToStorageProviderIDEntry.getValue();
// the second condition only applies if the file is in
// the CSAR root, because a file in root has no parent
if (directoryReferenceAsPath.equals(fileParent) || (fileParent == null)) {
csarFiles.add(new CSARFile(file.toString(), this.CSAR_ID, fileStorageProviderID));
}
}
} else {
csarFiles.add(this.getFileNotConsiderPatterns(""));
}
return csarFiles;
}
@Override
public AbstractDirectory getDirectory(String relPathOfDirectory) {
// If it's a file artifact we have no directories and can directly
// return null
if (!this.isFileArtifact()) {
Path relPathOfDirectoryToCSARRoot = Paths.get(this.getPath()).resolve(relPathOfDirectory);
AbstractDirectory directory = this.getDirectory(relPathOfDirectoryToCSARRoot);
if (directory != null) {
CSARDirectory.LOG.debug("Directory \"{}\" relative to \"{}\" was found.", relPathOfDirectory, this.getPath());
} else {
CSARDirectory.LOG.warn("Directory \"{}\" relative to \"{}\" was not found.", relPathOfDirectory, this.getPath());
}
return directory;
}
return null;
}
/**
* @param relPathOfDirectoryToCSARRoot - directory path relative to CSAR
* root.
* @return {@link AbstractDirectory} of directory
* {@code relPathOfDirectoryToCSARRoot}. If it not exists
* {@code null}.
*/
private AbstractDirectory getDirectory(Path relPathOfDirectoryToCSARRoot) {
// directories in directory to get
Set<Path> directoriesInDirectory = new HashSet<Path>();
for (Path directory : this.DIRECTORIES) {
if (directory.startsWith(relPathOfDirectoryToCSARRoot)) {
directoriesInDirectory.add(directory);
}
}
// directory to get exists
if (!directoriesInDirectory.isEmpty()) {
// files in directory to get
Map<Path, String> fileToStorageProviderIDMapOfDirectory = new HashMap<Path, String>();
for (Map.Entry<Path, String> fileToStorageProviderID : this.FILE_TO_STORAGE_PROVIDER_ID_MAP.entrySet()) {
Path file = fileToStorageProviderID.getKey();
String fileStorageProviderID = fileToStorageProviderID.getValue();
if (file.startsWith(relPathOfDirectoryToCSARRoot)) {
fileToStorageProviderIDMapOfDirectory.put(file, fileStorageProviderID);
}
}
// remove the directory to get (it's not IN the directory)
directoriesInDirectory.remove(relPathOfDirectoryToCSARRoot);
return new CSARDirectory(relPathOfDirectoryToCSARRoot.toString(), this.getIncludePatterns(), this.getExcludePatterns(), this.CSAR_ID, directoriesInDirectory, fileToStorageProviderIDMapOfDirectory, false);
}
return null;
}
@Override
public Set<AbstractDirectory> getDirectories() {
Set<AbstractDirectory> csarDirectories = new HashSet<AbstractDirectory>();
// If it's a file artifact we have no directories and can directly
// return an empty set.
if (!this.isFileArtifact()) {
Path directoryReferenceAsPath = Paths.get(this.getPath());
for (Path directory : this.DIRECTORIES) {
Path directoryParent = directory.getParent();
// the second condition only applies if this directory is in
// the CSAR root, because a directory in root has no parent
if (directoryReferenceAsPath.equals(directoryParent) || (directoryParent == null)) {
csarDirectories.add(this.getDirectory(directory));
}
}
}
return csarDirectories;
}
@Override
public String getName() {
Path directoryPath = Paths.get(this.getPath());
return directoryPath.getFileName().toString();
}
/**
* @return {@inheritDoc} It's the relative path to CSAR root.
*/
@Override
public String getPath() {
return super.getPath();
}
}
|
package com.rofour.baseball.service.manager.impl;
import com.rofour.baseball.controller.model.UserManagerLogModel;
import com.rofour.baseball.dao.manager.bean.UserManagerLogBean;
import com.rofour.baseball.dao.manager.mapper.UserManagerLogMapper;
import com.rofour.baseball.service.manager.UserManagerLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Created by Administrator on 2016-05-30.
*/
@Service("userManagerLog")
public class UserManagerLogIml implements UserManagerLog {
@Autowired
@Qualifier("userManagerLogMapper")
private UserManagerLogMapper dao;
public void insert(UserManagerLogBean LogModel) {
dao.insert(LogModel);
dao.insertRemark(LogModel);
}
public List<UserManagerLogBean> getLogs(UserManagerLogModel LogModel) {
return dao.getLogs(LogModel);
}
public int getLogsCount(UserManagerLogModel LogModel) {
return dao.getLogsCount(LogModel);
}
}
|
package com.peng.pp_app_sdk.utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.RecyclerView;
import android.util.LruCache;
import android.widget.ImageView;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashSet;
import java.util.Set;
/**
* Created on 2015/12/23 0023.
* Author wangpengpeng
* Email 1678173987@qq.com
* Description 加载网络图片并缓存的工具类
* 在ImageLoader 中有两种加载网络图片的方式,第一种是通过httpConnection然后通过handler通知主ui进行更新但是这种不能进行缓存,不推荐使用
* 第二种是通过Asynctask异步任务的方式进行加载网络图片,并使用lruCache进行缓存,,在此加载的时候进行判断如果内存中有相应Key 的bitmap流则进行加载内存中的bitmap流
* 如果没有的话进行
*/
public class ImageLoader {
////第一步加载网络图片的先从网络上面加载返回图片的输入流
//
// /**
// *
// * @param urlPath 网络地址的url
// * @return
// * @throws IOException
// */
// private static InputStream getUrlInputStream(String urlPath) {
//
// try {
// URL url = null;
// url = new URL(urlPath);
// HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// InputStream inputStream = new BufferedInputStream(conn.getInputStream());
// //加载完输入流之后进行断开网络连接
// conn.disconnect();
// if (inputStream != null) {
// return inputStream;
// } else {
// Log.i("input", "输入流对象为空");
// }
// } catch (MalformedURLException e) {
// e.printStackTrace();
// } catch (IOException e) {
// e.printStackTrace();
// }
//
// return null;
// }
//
// /**
// * 第二步使用从网络加载的输入流
// * @param urlStr
// * @return
// * @throws IOException
// */
// private Bitmap getBitmapFromUrl(String urlStr){
// //先实例化一个bitmap
// Bitmap bitmap;
// //实例化一个输入流
// InputStream inputStream = null;
// inputStream=getUrlInputStream(urlStr);
// bitmap= BitmapFactory.decodeStream(inputStream);
// return bitmap;
//}
private ImageView view;
private String viewUrl;
private Set<ImageAsyncTask> tasks;
private LruCache<String, Bitmap> lruCache;
private RecyclerView recyclerView;
/**
* 在主页中进行加载图片
*/
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (view.getTag().equals(viewUrl)) {
view.setImageBitmap((Bitmap) msg.obj);
}
}
};
/**
* 可以用此构造器调用handler机制加载图片,不需要缓存的
*/
public ImageLoader() {
}
/**
* 当使用ImageLoader的时候直接进行
*
* @param context
* @param view
* @param viewUrl
*/
public ImageLoader(Context context, ImageView view, String viewUrl) {
lruCache = new LruCache<String, Bitmap>((int) (Runtime.getRuntime().maxMemory() / 4)) {
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getByteCount();
}
};
tasks = new HashSet<>();
}
/**
* 把消息传到主线程
*
* @param view image的对象
* @param url iamge 的地址
*/
public void showImage(ImageView view, final String url) {
this.view = view;
this.viewUrl = url;
new Thread(new Runnable() {
@Override
public void run() {
Bitmap bitmap = getBitmapFromUrl(url);
Message message = Message.obtain();
message.obj = bitmap;
handler.sendMessage(message);
}
}).start();
}
/**
* 将指定的url图片加载输出bitmap流
*
* @param urlStr url地址
* @return 返回bitmap
*/
private Bitmap getBitmapFromUrl(String urlStr) {
Bitmap bitmap;
InputStream inputStream = null;
try {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
inputStream = new BufferedInputStream(conn.getInputStream());
if (inputStream != null) {
bitmap = BitmapFactory.decodeStream(inputStream);
conn.disconnect();
return bitmap;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
/**
* 使用AsyncTask继续加载图片,适用于大量的图片,可以继续缓存
*/
private class ImageAsyncTask extends AsyncTask<String, Void, Bitmap> {
String url;//请求网址
LruCache<String, Bitmap> lruCache;//缓存对象
ImageView image;
public ImageAsyncTask(ImageView imageView, String url, LruCache<String, Bitmap> lruCache) {
this.lruCache = lruCache;
this.url = url;
this.image = imageView;
}
/**
* 执行异步任务操作,在这个方法里面执行异步任务
*
* @param params
* @return
*/
@Override
protected Bitmap doInBackground(String... params) {
url = params[0];
//如果有进度条则在此调用
// publishProgress();
//从url中请求得到一个bitmap流
Bitmap bitmap = getBitmapFromUrl(url);
//然后把bitmap流加载到内存中去
addBitmapToCache(url, bitmap);
return null;
}
/**
* 主要负责进度条更新,如果需要调用则在doInBackground()中调用publishProgress()
*
* @param values
*/
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
/**
* 异步加载完成之后系统自动调用,在此更新UI
*
* @param bitmap
*/
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
// ImageView imageView = (ImageView) recyclerView.findViewWithTag(url);
if (image != null && bitmap != null) {
image.setImageBitmap(bitmap);
tasks.remove(this);//执行玩异步任务之后移除回收
}
}
}
public void addBitmapToCache(String url, Bitmap bitmap) {
//如果从内存中加载出来的为空则重新放进内存中去
if (getBitmapFromCache(url) == null) {
lruCache.put(url, bitmap);
}
}
public Bitmap getBitmapFromCache(String url) {
return lruCache.get(url);
}
public void cancelAlltasks() {
if (tasks == null || tasks.isEmpty()) {
return;
} else {
for (ImageAsyncTask task : tasks) {
task.cancel(true);
}
}
}
public void loadImageByAsyncTask(ImageView view, String urlStr) {
ImageAsyncTask imageAsyncTask = new ImageAsyncTask(view, urlStr, lruCache);
Bitmap bitmap = this.getBitmapFromCache(urlStr);//先从缓存中读取
//如果不等于空的话则即设置view
if (bitmap != null) {
view.setImageBitmap(bitmap);
} else {
imageAsyncTask.execute(urlStr);
}
}
}
|
package com.tencent.mm.pluginsdk.ui;
public interface VoiceInputFooter$a {
void cdA();
void kF(boolean z);
}
|
package com.udacity.sandwichclub;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import com.udacity.sandwichclub.model.Sandwich;
import com.udacity.sandwichclub.utils.JsonUtils;
public class DetailActivity extends AppCompatActivity {
public static final String EXTRA_POSITION = "extra_position";
private static final int DEFAULT_POSITION = -1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
final ImageView ingredientsIv = findViewById(R.id.image_iv);
Intent intent = getIntent();
if (intent == null) {
closeOnError();
}
int position = intent.getIntExtra(EXTRA_POSITION, DEFAULT_POSITION);
if (position == DEFAULT_POSITION) {
// EXTRA_POSITION not found in intent
closeOnError();
return;
}
String[] sandwiches = getResources().getStringArray(R.array.sandwich_details);
String json = sandwiches[position];
Sandwich sandwich = JsonUtils.parseSandwichJson(json);
if (sandwich == null) {
// Sandwich data unavailable
closeOnError();
return;
}
populateUI(sandwich);
Picasso.with(this)
.load(sandwich.getImage())
.placeholder(R.drawable.progress_animation)
.into(ingredientsIv, new Callback() {
@Override
public void onSuccess() {
int imageHeight = (int) getResources().getDimension(R.dimen.sandwich_image);
ingredientsIv.setScaleType(ImageView.ScaleType.CENTER_CROP);
ingredientsIv.getLayoutParams().height = imageHeight;
}
@Override
public void onError() {
ingredientsIv.setImageResource(R.drawable.onloaderror);
}
});
setTitle(sandwich.getMainName());
onStop();
onRestart();
}
private void closeOnError() {
finish();
Toast.makeText(this, R.string.detail_error_message, Toast.LENGTH_SHORT).show();
}
private void populateUI(Sandwich sandwich) {
TextView placeOriginTextView = findViewById(R.id.origin_tv);
TextView alsoKnownTextView = findViewById(R.id.also_known_tv);
TextView descriptionTextView = findViewById(R.id.description_tv);
TextView ingredientsTextView = findViewById(R.id.ingredients_tv);
placeOriginTextView.setText(sandwich.getPlaceOfOrigin());
StringBuffer sb = new StringBuffer();
for (String name : sandwich.getAlsoKnownAs()) {
sb.append(name + ", ");
}
alsoKnownTextView.setText(sb.length() <= 0 ? "" : sb.substring(0, sb.length() - 2));
descriptionTextView.setText(sandwich.getDescription());
sb = new StringBuffer();
for (String name : sandwich.getIngredients()) {
sb.append(name + "\n");
}
ingredientsTextView.setText(sb.toString());
}
}
|
package com.services.rabbitmq;
import com.services.rabbitmq.model.ExchangeType;
import com.services.rabbitmq.receiver.MessageReceiver;
import java.io.IOException;
/**
* 广播消息接收
*/
public abstract class SubscribeMessageReceiver extends MessageReceiver {
/**
* 广播方式接收队列
*
* @param queue_name 队列名
* @param exchange_name 交换机名
*/
protected SubscribeMessageReceiver(String queue_name, String exchange_name) throws IOException {
super(queue_name, exchange_name, null, ExchangeType.FANOUT);
}
}
|
package com.example.coronapp;
import com.example.coronapp.entity.Humain;
import com.example.coronapp.enumeration.EtatDeSante;
import com.example.coronapp.enumeration.Nom;
import com.example.coronapp.repository.IHumainRepo;
import com.example.coronapp.service.HumainService;
import com.example.coronapp.utils.HunainUtils;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.Arrays;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest
public class HunainServiceTest {
@Autowired
private HumainService humainService;
@Autowired
private IHumainRepo humainRepo;
@Test
public void soigneTousLeMondeTest(){
Humain jacques = Humain.builder()
.nom(Nom.JACQUES)
.etat(EtatDeSante.MALADE)
.build();
Humain paulette = Humain.builder()
.nom(Nom.PAULETTE)
.etat(EtatDeSante.MALADE)
.build();
List<Humain> humains = Arrays.asList(jacques, paulette);
humainRepo.saveAll(humains);
humains.forEach(humain -> humain.setEtat(EtatDeSante.SAIN));
assertThat(humainService.soignerToutLeMonde())
.usingFieldByFieldElementComparator()
.containsExactlyInAnyOrder(humains.toArray(new Humain[0]));
assertThat(humainRepo.findAll())
.usingFieldByFieldElementComparator()
.containsExactlyInAnyOrder(humains.toArray(new Humain[0]));
}
}
|
package example.mail.sendgrid;
import com.sendgrid.*;
import example.api.v1.Email;
import example.mail.EmailService;
import example.mail.MailController;
import io.micronaut.context.annotation.Requires;
import io.micronaut.context.annotation.Value;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Singleton;
import java.io.IOException;
@Singleton
@Requires(property = "sendgrid.api-key")
public class SendGridEmailService implements EmailService {
private static final Logger log = LoggerFactory.getLogger(MailController.class);
@Value("${sendgrid.api-key}")
String apiKey;
@Value("${sendgrid.from-email}")
String fromEmail;
protected Content contentOfEmail(Email email) {
if ( email.getTextBody() != null ) {
return new Content("text/plain", email.getTextBody());
}
if ( email.getHtmlBody() != null ) {
return new Content("text/html", email.getHtmlBody());
}
return null;
}
@Override
public void send(Email email) {
Personalization personalization = new Personalization();
personalization.setSubject(email.getSubject());
com.sendgrid.Email to = new com.sendgrid.Email(email.getRecipient());
personalization.addTo(to);
if ( email.getCc() != null ) {
for ( String cc : email.getCc() ) {
com.sendgrid.Email ccEmail = new com.sendgrid.Email();
ccEmail.setEmail(cc);
personalization.addCc(ccEmail);
}
}
if ( email.getBcc() != null ) {
for ( String bcc : email.getBcc() ) {
com.sendgrid.Email bccEmail = new com.sendgrid.Email();
bccEmail.setEmail(bcc);
personalization.addBcc(bccEmail);
}
}
Mail mail = new Mail();
com.sendgrid.Email from = new com.sendgrid.Email();
from.setEmail(fromEmail);
mail.setFrom(from);
mail.addPersonalization(personalization);
Content content = contentOfEmail(email);
mail.addContent(content);
SendGrid sg = new SendGrid(apiKey);
Request request = new Request();
try {
request.setMethod(Method.POST);
request.setEndpoint("mail/send");
request.setBody(mail.build());
Response response = sg.api(request);
log.info("Status Code: {}", String.valueOf(response.getStatusCode()));
log.info("Body: {}", response.getBody());
for ( String key : response.getHeaders().keySet()) {
String value = response.getHeaders().get(key);
log.info("Response Header {} => {}", key, value);
}
} catch (IOException ex) {
log.error(ex.getMessage());
}
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.gossip.examples;
import java.io.IOException;
import java.util.Scanner;
import org.apache.gossip.manager.GossipManager;
public class StandAloneNodeStandAloneExample extends BaseStandAloneExample {
private static boolean WILL_READ = false;
public static void main(String[] args) throws InterruptedException, IOException {
// udp://localhost:5400 0 udp://localhost:10000 0
//netstat -aon|findstr "5400"
// tasklist|findstr "2720"
String[] paraURL1 = {"udp://localhost:5400","0","udp://localhost:5400","0"};
String[] paraURL2 = {"udp://localhost:5401","1","udp://localhost:5400","0"};
String[] paraURL3 = {"udp://localhost:5402","2","udp://localhost:5400","0"};
String[] paraURL4 = {"udp://localhost:5403","3","udp://localhost:5400","0"};
System.out.println("StandAloneNode - 请输入启动节点列表编号");
Scanner scanner = new Scanner(System.in);
String[] paraURL = null;
int optionNum = scanner.nextInt();
switch (optionNum){
case 1:{
paraURL = paraURL1;
break;
}
case 2:{
paraURL = paraURL2;
break;
}
case 3:{
paraURL = paraURL3;
break;
}
default:{
paraURL = paraURL4;
}
}
System.out.println(String.format("%d号节点开始运行 -- port = %s , id = %s"
, optionNum,paraURL[0].substring(paraURL[0].length()-4,paraURL[0].length()),paraURL[1]));
StandAloneNodeStandAloneExample example = new StandAloneNodeStandAloneExample(paraURL);
example.exec(WILL_READ);
}
StandAloneNodeStandAloneExample(String[] paraURL) {
paraURL = super.checkArgsForClearFlag(paraURL);
super.initGossipManager(paraURL);
}
@Override
void printValues(GossipManager gossipService) {
}
}
|
package server.rest.controllers;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import server.model.HRPositionRole;
import server.rest.responses.HRPositionRoleResponse;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class HRPositionRoleControllerTest {
HRPositionRoleController hrPositionRoleController;
@BeforeEach
public void initController() {
hrPositionRoleController = new HRPositionRoleController();
}
@Test
void viewHRPositionsTest(){
ArrayList<HRPositionRole> roles = new ArrayList<HRPositionRole>();
try {
roles = hrPositionRoleController.getHRRoles();
} catch (SQLException e) {
fail(e.getMessage());
}
assertFalse(roles.isEmpty());
}
}
|
package com.xp;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import com.launchdarkly.eventsource.EventHandler;
import com.launchdarkly.eventsource.EventSource;
/**
* @author Neeraj Sidhaye
*/
public class SseClient {
public static void main(String[] args) throws InterruptedException {
EventHandler eventHandler = new ClientEventHandler();
String url = String.format("http://localhost:8080/subscribe");
EventSource.Builder builder = new EventSource.Builder(eventHandler, URI.create(url));
try (EventSource eventSource = builder.build()) {
eventSource.setReconnectionTimeMs(60000);
eventSource.start();
TimeUnit.MINUTES.sleep(10);
}
}
public Map<String, String> subscribeClient(String uuid) throws InterruptedException {
EventHandler eventHandler = new ClientEventHandler();
String url = String.format("http://localhost:8080/subscribe");
EventSource.Builder builder = new EventSource.Builder(eventHandler, URI.create(url));
System.out.println("client establishing connection");
try (EventSource eventSource = builder.build()) {
eventSource.setReconnectionTimeMs(3000);
eventSource.start();
TimeUnit.SECONDS.sleep(5);
}
System.out.println("execution success");
return new HashMap() {{put("status", "success");}};
}
}
|
package com.aifurion.track.entity.VO;
/**
* @author :zzy
* @description:TODO
* @date :2021/5/2 16:47
*/
public class NoticeVO {
private String userId;
private String title;
private String pushUserName;
public NoticeVO() {
}
public NoticeVO(String userId, String title, String pushUserName) {
this.userId = userId;
this.title = title;
this.pushUserName = pushUserName;
}
@Override
public String toString() {
return "NoticeVO{" +
"userId='" + userId + '\'' +
", title='" + title + '\'' +
", pushUserName='" + pushUserName + '\'' +
'}';
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPushUserName() {
return pushUserName;
}
public void setPushUserName(String pushUserName) {
this.pushUserName = pushUserName;
}
}
|
public class BarkingDog {
public static void main(String[] args) {
System.out.println(shouldWakeUp(true,1));
System.out.println(shouldWakeUp(false,2));
System.out.println(shouldWakeUp(true,0));
System.out.println(shouldWakeUp(true,-1));
}
public static boolean shouldWakeUp(boolean barking, int hourOfDay){
boolean shouldWakeUp = false;
if (hourOfDay > 23 || hourOfDay < 0){
shouldWakeUp = false;
}
else if(barking && (hourOfDay < 8 || hourOfDay > 22)){
shouldWakeUp = true;
}
return shouldWakeUp;
}
}
|
package com.example.finalproject;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
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.database.Query;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class Display extends AppCompatActivity {
DatabaseReference reference;
ListView listView;
UserList adapter;
FirebaseAuth firebaseAuth;
FirebaseUser user;
List<UserData> userlist;
String data;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display);
reference=FirebaseDatabase.getInstance().getReference("User");
listView=(ListView)findViewById(R.id.listViewUser);
userlist=new ArrayList<>();
firebaseAuth= FirebaseAuth.getInstance();
user=firebaseAuth.getCurrentUser();
data =user.getEmail().toString().trim();
}
@Override
protected void onStart() {
super.onStart();
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
userlist.clear();
String id =reference.getKey();
for(DataSnapshot usersnapshot:dataSnapshot.getChildren()){
UserData userData = usersnapshot.getValue(UserData.class);
if((userData.email).equals(data)) {
Log.d("TAG", "this is email login:-" + userData.email);
Log.d("TAG", "this is email:-" + data);
userlist.add(userData);
}
}
UserList adapter=new UserList(Display.this,userlist);
listView.setAdapter(adapter);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}
|
package com.ibeiliao.pay.impl.thirdpay.wxpay;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import com.ibeiliao.platform.commons.utils.encrypt.EncryptUtil;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 微信支付相关工具类
*
* @author liuying 2016年9月30日
*
*/
public class WxpayUtils {
private static Logger logger = LoggerFactory.getLogger(WxpayUtils.class);
/**
* 成功
*/
private static final String SUCCESS = "success";
/**
* 通信返回码
*/
private static final String RETURN_CODE = "return_code";
/**
* 业务返回码
*/
private static final String RESULT_CODE = "result_code";
/**
* 通信返回结果
*/
private static final String RETURN_MSG = "return_msg";
/**
* 业务返回错误码
*/
private static final String ERR_CODE = "err_code";
/**
* 业务返回错误信息
*/
private static final String ERR_CODE_DES = "err_code_des";
/**
* 签名
*/
private static final String SIGN = "sign";
/**
* 将参数按照k-v格式生成MD5签名
*
* @param params
* @return
*/
public static String generateMD5Sign(Map<String, String> params, String key) {
StringBuffer sb = new StringBuffer();
for (Entry<String, String> entry : params.entrySet()) {
String k = entry.getKey();
String v = entry.getValue();
if (StringUtils.isNotBlank(v) && !k.equals("sign")
&& !k.equals("key")) {
sb.append(k + "=" + v + "&");
}
}
sb.append("key=" + key);
logger.info(sb.toString());
return EncryptUtil.getMD5(sb.toString()).toLowerCase();
}
/**
* 按照微信支付要求生成XML格式的参数字符串
*
* @param params
* @return
*/
public static String getRequestXml(Map<String, String> params) {
StringBuffer sb = new StringBuffer();
sb.append("<xml>");
for (Entry<String, String> entry : params.entrySet()) {
String k = entry.getKey();
String v = (String) entry.getValue();
if ("attach".equalsIgnoreCase(k) || "body".equalsIgnoreCase(k)
|| "sign".equalsIgnoreCase(k)) {
sb.append("<" + k + ">" + "<![CDATA[" + v + "]]></" + k + ">");
} else {
sb.append("<" + k + ">" + v + "</" + k + ">");
}
}
sb.append("</xml>");
return sb.toString();
}
/**
* 解析微信返回的XML信息
*
* @param strxml
* @return
*/
public static Map<String, String> parseXml(String strxml) {
strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");
if (StringUtils.isBlank(strxml)) {
return null;
}
Map<String, String> m = new HashMap<String, String>();
InputStream in = null;
try {
in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(in);
Element root = doc.getRootElement();
List<Element> list = root.getChildren();
Iterator<Element> it = list.iterator();
while (it.hasNext()) {
Element e = (Element) it.next();
String k = e.getName();
String v = "";
List<Element> children = e.getChildren();
if (children.isEmpty()) {
v = e.getTextNormalize();
} else {
v = getChildrenText(children);
}
m.put(k, v);
}
} catch (Exception e) {
logger.error("解析微信返回的XML信息异常: " + strxml, e);
} finally {
IOUtils.closeQuietly(in);
}
return m;
}
private static String getChildrenText(List<Element> children) {
StringBuffer sb = new StringBuffer();
if (!children.isEmpty()) {
Iterator<Element> it = children.iterator();
while (it.hasNext()) {
Element e = (Element) it.next();
String name = e.getName();
String value = e.getTextNormalize();
List<Element> list = e.getChildren();
sb.append("<" + name + ">");
if (!list.isEmpty()) {
sb.append(getChildrenText(list));
}
sb.append(value);
sb.append("</" + name + ">");
}
}
return sb.toString();
}
/**
* 检查微信返回信息通信结果
*
* @param resultMap
*
* @return true,通信成功
*/
private static boolean checkReturn(Map<String, String> resultMap) {
String code = resultMap.get(RETURN_CODE);
if (!code.equalsIgnoreCase(SUCCESS)) {
String errMsg = resultMap.get(RETURN_MSG);
logger.error("微信接口通信异常,msg:{}", errMsg);
return false;
}
return true;
}
/**
* 检查微信返回信息业务结果
*
* @param resultMap
*
* @return true,成功
*/
public static boolean checkResult(Map<String, String> resultMap) {
// 先检查return_code
boolean succeed = checkReturn(resultMap);
if (!succeed) {
return false;
}
String code = resultMap.get(RESULT_CODE);
if (!code.equalsIgnoreCase(SUCCESS)) {
String errCode = resultMap.get(ERR_CODE);
String errMsg = resultMap.get(ERR_CODE_DES);
logger.error("微信支付接口业务结果错误,errCode:{},errMsg:{}", errCode, errMsg);
return false;
}
return true;
}
/**
* 检查微信回调接口结果
*
* @param resultMap
*
* @return true,返回状态码为success并且签名验证通过
*/
public static boolean validatePayNotify(Map<String, String> resultMap,
String key) {
// 检查返回结果
boolean succeed = checkReturn(resultMap);
if (!succeed) {
logger.error("微信支付回调接口异常,支付接口调用失败。");
return false;
}
Map<String, String> treeMap = new TreeMap<>();
treeMap.putAll(resultMap);
// 检查签名
String sign = treeMap.get(SIGN);
String localSign = generateMD5Sign(treeMap, key);
if (!sign.equalsIgnoreCase(localSign)) {
logger.error("微信支付回调接口异常,签名验证失败。");
return false;
}
return true;
}
}
|
package javax.vecmath;
import java.io.Serializable;
public class Point4d extends Tuple4d implements Serializable {
static final long serialVersionUID = 1733471895962736949L;
public Point4d(double x, double y, double z, double w) {
super(x, y, z, w);
}
public Point4d(double[] p) {
super(p);
}
public Point4d(Point4d p1) {
super(p1);
}
public Point4d(Point4f p1) {
super(p1);
}
public Point4d(Tuple4f t1) {
super(t1);
}
public Point4d(Tuple4d t1) {
super(t1);
}
public Point4d(Tuple3d t1) {
super(t1.x, t1.y, t1.z, 1.0D);
}
public Point4d() {}
public final void set(Tuple3d t1) {
this.x = t1.x;
this.y = t1.y;
this.z = t1.z;
this.w = 1.0D;
}
public final double distanceSquared(Point4d p1) {
double dx = this.x - p1.x;
double dy = this.y - p1.y;
double dz = this.z - p1.z;
double dw = this.w - p1.w;
return dx * dx + dy * dy + dz * dz + dw * dw;
}
public final double distance(Point4d p1) {
double dx = this.x - p1.x;
double dy = this.y - p1.y;
double dz = this.z - p1.z;
double dw = this.w - p1.w;
return Math.sqrt(dx * dx + dy * dy + dz * dz + dw * dw);
}
public final double distanceL1(Point4d p1) {
return Math.abs(this.x - p1.x) + Math.abs(this.y - p1.y) +
Math.abs(this.z - p1.z) + Math.abs(this.w - p1.w);
}
public final double distanceLinf(Point4d p1) {
double t1 = Math.max(Math.abs(this.x - p1.x), Math.abs(this.y - p1.y));
double t2 = Math.max(Math.abs(this.z - p1.z), Math.abs(this.w - p1.w));
return Math.max(t1, t2);
}
public final void project(Point4d p1) {
double oneOw = 1.0D / p1.w;
p1.x *= oneOw;
p1.y *= oneOw;
p1.z *= oneOw;
this.w = 1.0D;
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\javax\vecmath\Point4d.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
|
package mop.main.java.backend.services;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import mop.main.java.backend.services.responses.MovieFinderResponse;
import mop.main.java.backend.utilities.Log;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.logging.log4j.Logger;
public class MovieFinderService {
private static final Logger log = Log.getLog(MovieFinderService.class);
private final Gson jsonConverter;
public MovieFinderService() {
jsonConverter = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
.create();
}
public MovieFinderResponse requestMovie(String title, String year) throws IOException {
if(title == null || title.equals("")) {
log.error("Unable to request movie from null or empty title.");
throw new IllegalArgumentException("title");
}
String requestUrl = this.constructRequestUrl(title, year);
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet request = new HttpGet(requestUrl);
StringBuilder jsonResponse = new StringBuilder();
try (CloseableHttpResponse response = httpclient.execute(request)) {
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String inputLine;
while ((inputLine = reader.readLine()) != null) {
jsonResponse.append(inputLine);
}
reader.close();
}
return jsonConverter.fromJson(jsonResponse.toString(), MovieFinderResponse.class);
}
private String constructRequestUrl(String title, String year) {
String requestFriendlyTitle = title.replaceAll(" ", "+"); // spaces in a title should be replaced with '+'
if(year == null) {
year = "";
}
String baseUrl = "http://www.omdbapi.com/";
return baseUrl + "?" + "t=" + requestFriendlyTitle + "&" + "y=" + year + "&" + "plot=short" + "&" + "r=json";
}
}
|
/**
* A class to handle the 'Check Out' option of the Main Menu.
*/
public class CheckOutOption implements Option {
private String name;
private BookLister bookLister;
public CheckOutOption(String name, BookLister bookLister) {
this.name = name;
this.bookLister = bookLister;
}
@Override
public String name() {
return name;
}
@Override
public void run() {
bookLister.checkOut();
}
}
|
package com.tencent.mm.plugin.sns.ui;
import com.tencent.mm.modelgeo.Addr;
import com.tencent.mm.modelgeo.b.a;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
class LocationWidget$3 implements a {
final /* synthetic */ LocationWidget nOH;
LocationWidget$3(LocationWidget locationWidget) {
this.nOH = locationWidget;
}
public final void b(Addr addr) {
x.i("MicroMsg.LocationWidget", "get info %s", new Object[]{addr.toString()});
if (LocationWidget.e(this.nOH)) {
LocationWidget.f(this.nOH);
if (bi.oW(LocationWidget.g(this.nOH))) {
LocationWidget.a(this.nOH, addr.dRJ);
LocationWidget.f(this.nOH);
}
}
}
}
|
package com.thinker.vdongthinker.ui.fragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import java.util.ArrayList;
public class FragmentController {
private static boolean isReload; //避免重复加载
public static FragmentController controller ;
private final FragmentManager fm;
private int contentId;
public static ArrayList<Fragment> fgList;
public static FragmentController getInstance (FragmentActivity mActivity , int contentId , boolean isReload,ArrayList<Fragment> fgList){
FragmentController.isReload = isReload;
FragmentController.fgList = fgList;
if(controller == null){
controller = new FragmentController(mActivity ,contentId) ;
}
return controller ;
}
public FragmentController(FragmentActivity mActivity, int contentId) {
this.contentId = contentId ;
fm = mActivity.getSupportFragmentManager();
initFragment();
}
/*加载四个模块*/
private void initFragment() {
// fgList = new ArrayList<>();
if(!isReload){
// fgList.add(new FragmentIndex()) ;
// fgList.add(new FragmentCourse()) ;
// fgList.add(new FragmentAgency()) ;
// fgList.add(new DFragment()) ;
FragmentTransaction ft = fm.beginTransaction();
for(int i = 0 ;i<fgList.size() ;i++){
ft.add(contentId ,fgList.get(i) ,String.valueOf(i)) ;
}
ft.commit() ;
}else {
for(int i = 0 ;i<5 ;i++){
fgList.add(fm.findFragmentByTag(String.valueOf(i))) ;
}
}
}
/*展示某个模块*/
public void showFragment(int position){
hideFragment() ;
Fragment fragment = fgList.get(position);
FragmentTransaction ft = fm.beginTransaction();
ft.show(fragment) ;
ft.commitAllowingStateLoss() ;
}
/*隐藏某一个模块*/
public void hideFragment(){
FragmentTransaction ft = fm.beginTransaction();
for(Fragment fragment : fgList){
if(fragment!=null){
ft.hide(fragment) ;
}
}
ft.commitAllowingStateLoss() ;
}
}
|
package com.kunsoftware.controller.manager;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.kunsoftware.bean.JsonBean;
import com.kunsoftware.bean.OrdersTravelRequestBean;
import com.kunsoftware.controller.BaseController;
import com.kunsoftware.entity.Orders;
import com.kunsoftware.entity.OrdersTravelList;
import com.kunsoftware.exception.KunSoftwareException;
import com.kunsoftware.service.OrdersService;
import com.kunsoftware.service.OrdersTravelService;
@Controller
@RequestMapping("/manager/orderstravel")
public class OrdersTravelController extends BaseController {
private static Logger logger = LoggerFactory.getLogger(OrdersTravelController.class);
@Autowired
private OrdersTravelService service;
@Autowired
private OrdersService ordersService;
@RequestMapping("/list")
public String listOrdersTravel(ModelMap model,Integer ordersId) throws KunSoftwareException {
logger.info("客人名单列表");
Orders orders = ordersService.selectByPrimaryKey(ordersId);
List<OrdersTravelList> list = service.getOrdersTravelListAll(ordersId);
model.addAttribute("retList", list);
model.addAttribute("orders", orders);
return "manager/orderstravel/orderstravel-list";
}
@RequestMapping("/add")
public String addOrdersTravel(ModelMap model,Integer ordersId) throws KunSoftwareException {
logger.info("添加客人名单");
Orders orders = ordersService.selectByPrimaryKey(ordersId);
model.addAttribute("orders", orders);
return "manager/orderstravel/orderstravel-add";
}
@RequestMapping(value="/add.json")
@ResponseBody
public JsonBean addOrdersTravel(@RequestParam(value = "orderstravelFile", required = false) MultipartFile file,OrdersTravelRequestBean requestBean) throws KunSoftwareException {
logger.info("保存客人名单");
requestBean.setFile(file);
OrdersTravelList entity = service.insert(requestBean);
JsonBean jsonBean = new JsonBean();
jsonBean.put("id", entity.getId());
jsonBean.setMessage("操作成功");
return jsonBean;
}
@RequestMapping("/edit")
public String editOrdersTravel(ModelMap model,Integer id) throws KunSoftwareException {
logger.info("编辑客人名单");
OrdersTravelList entity = service.selectByPrimaryKey(id);
Orders orders = ordersService.selectByPrimaryKey(entity.getOrdersId());
model.addAttribute("entity", entity);
model.addAttribute("orders", orders);
return "manager/orderstravel/orderstravel-edit";
}
@RequestMapping(value="/edit.json")
@ResponseBody
public JsonBean editOrdersTravel(@RequestParam(value = "orderstravelImageFile", required = false) MultipartFile file,OrdersTravelRequestBean requestBean,Integer id) throws KunSoftwareException {
logger.info("编辑保存客人名单");
requestBean.setFile(file);
service.updateByPrimaryKey(requestBean,id);
JsonBean jsonBean = new JsonBean();
jsonBean.setMessage("操作成功");
return jsonBean;
}
@RequestMapping(value="/del.json")
@ResponseBody
public JsonBean delOrdersTravel(Integer[] id) throws KunSoftwareException {
logger.info("删除客人名单");
service.deleteByPrimaryKey(id);
JsonBean jsonBean = new JsonBean();
jsonBean.setMessage("操作成功");
return jsonBean;
}
}
|
package com.tencent.mm.protocal.c;
import f.a.a.b;
import f.a.a.c.a;
import java.util.LinkedList;
public final class bee extends bhp {
public long cfh;
public int kLd;
public int kLe;
public String kLf;
public String kLg;
public String kLh;
public int qYf;
public int sbd;
public int sbe;
public int sbf;
public long sbg;
public long sbh;
public LinkedList<alo> sbi = new LinkedList();
public String sbj;
public String sbk;
public String sbl;
public int sbm;
public int sbn;
public String sbo;
protected final int a(int i, Object... objArr) {
int fS;
byte[] bArr;
if (i == 0) {
a aVar = (a) objArr[0];
if (this.six == null) {
throw new b("Not all required fields were included: BaseResponse");
}
if (this.six != null) {
aVar.fV(1, this.six.boi());
this.six.a(aVar);
}
aVar.T(2, this.cfh);
aVar.fT(3, this.sbf);
aVar.T(4, this.sbg);
aVar.fT(5, this.qYf);
aVar.T(6, this.sbh);
aVar.fT(9, this.kLe);
aVar.d(10, 8, this.sbi);
if (this.kLf != null) {
aVar.g(11, this.kLf);
}
if (this.sbj != null) {
aVar.g(12, this.sbj);
}
if (this.sbk != null) {
aVar.g(13, this.sbk);
}
if (this.sbl != null) {
aVar.g(14, this.sbl);
}
aVar.fT(15, this.sbm);
if (this.kLh != null) {
aVar.g(16, this.kLh);
}
aVar.fT(17, this.sbn);
if (this.kLg != null) {
aVar.g(18, this.kLg);
}
aVar.fT(19, this.sbe);
aVar.fT(20, this.kLd);
aVar.fT(21, this.sbd);
if (this.sbo == null) {
return 0;
}
aVar.g(22, this.sbo);
return 0;
} else if (i == 1) {
if (this.six != null) {
fS = f.a.a.a.fS(1, this.six.boi()) + 0;
} else {
fS = 0;
}
fS = ((((((fS + f.a.a.a.S(2, this.cfh)) + f.a.a.a.fQ(3, this.sbf)) + f.a.a.a.S(4, this.sbg)) + f.a.a.a.fQ(5, this.qYf)) + f.a.a.a.S(6, this.sbh)) + f.a.a.a.fQ(9, this.kLe)) + f.a.a.a.c(10, 8, this.sbi);
if (this.kLf != null) {
fS += f.a.a.b.b.a.h(11, this.kLf);
}
if (this.sbj != null) {
fS += f.a.a.b.b.a.h(12, this.sbj);
}
if (this.sbk != null) {
fS += f.a.a.b.b.a.h(13, this.sbk);
}
if (this.sbl != null) {
fS += f.a.a.b.b.a.h(14, this.sbl);
}
fS += f.a.a.a.fQ(15, this.sbm);
if (this.kLh != null) {
fS += f.a.a.b.b.a.h(16, this.kLh);
}
fS += f.a.a.a.fQ(17, this.sbn);
if (this.kLg != null) {
fS += f.a.a.b.b.a.h(18, this.kLg);
}
fS = ((fS + f.a.a.a.fQ(19, this.sbe)) + f.a.a.a.fQ(20, this.kLd)) + f.a.a.a.fQ(21, this.sbd);
if (this.sbo != null) {
fS += f.a.a.b.b.a.h(22, this.sbo);
}
return fS;
} else if (i == 2) {
bArr = (byte[]) objArr[0];
this.sbi.clear();
f.a.a.a.a aVar2 = new f.a.a.a.a(bArr, unknownTagHandler);
for (fS = com.tencent.mm.bk.a.a(aVar2); fS > 0; fS = com.tencent.mm.bk.a.a(aVar2)) {
if (!super.a(aVar2, this, fS)) {
aVar2.cJS();
}
}
if (this.six != null) {
return 0;
}
throw new b("Not all required fields were included: BaseResponse");
} else if (i != 3) {
return -1;
} else {
f.a.a.a.a aVar3 = (f.a.a.a.a) objArr[0];
bee bee = (bee) objArr[1];
int intValue = ((Integer) objArr[2]).intValue();
LinkedList IC;
int size;
f.a.a.a.a aVar4;
boolean z;
switch (intValue) {
case 1:
IC = aVar3.IC(intValue);
size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
bArr = (byte[]) IC.get(intValue);
com.tencent.mm.bk.a flVar = new fl();
aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (z = true; z; z = flVar.a(aVar4, flVar, com.tencent.mm.bk.a.a(aVar4))) {
}
bee.six = flVar;
}
return 0;
case 2:
bee.cfh = aVar3.vHC.rZ();
return 0;
case 3:
bee.sbf = aVar3.vHC.rY();
return 0;
case 4:
bee.sbg = aVar3.vHC.rZ();
return 0;
case 5:
bee.qYf = aVar3.vHC.rY();
return 0;
case 6:
bee.sbh = aVar3.vHC.rZ();
return 0;
case 9:
bee.kLe = aVar3.vHC.rY();
return 0;
case 10:
IC = aVar3.IC(intValue);
size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
bArr = (byte[]) IC.get(intValue);
alo alo = new alo();
aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (z = true; z; z = alo.a(aVar4, alo, com.tencent.mm.bk.a.a(aVar4))) {
}
bee.sbi.add(alo);
}
return 0;
case 11:
bee.kLf = aVar3.vHC.readString();
return 0;
case 12:
bee.sbj = aVar3.vHC.readString();
return 0;
case 13:
bee.sbk = aVar3.vHC.readString();
return 0;
case 14:
bee.sbl = aVar3.vHC.readString();
return 0;
case 15:
bee.sbm = aVar3.vHC.rY();
return 0;
case 16:
bee.kLh = aVar3.vHC.readString();
return 0;
case 17:
bee.sbn = aVar3.vHC.rY();
return 0;
case 18:
bee.kLg = aVar3.vHC.readString();
return 0;
case 19:
bee.sbe = aVar3.vHC.rY();
return 0;
case 20:
bee.kLd = aVar3.vHC.rY();
return 0;
case 21:
bee.sbd = aVar3.vHC.rY();
return 0;
case 22:
bee.sbo = aVar3.vHC.readString();
return 0;
default:
return -1;
}
}
}
}
|
package com.cjava.spring.controller;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.cjava.spring.entity.Articulo;
import com.cjava.spring.entity.Cliente;
import com.cjava.spring.entity.Empleado;
import com.cjava.spring.service.Carrito;
import com.cjava.spring.entity.CarritoItem;
import com.cjava.spring.service.ServiceFactory;
import com.cjava.spring.util.Constantes;
import com.cjava.spring.util.WebUtil;
@Controller
@Scope("request")
public class VentaController implements Serializable {
// Empleado
// List<Empleado> empleados;
@Autowired
ServiceFactory serviceFactory;
private FacesContext facesContext;
private FacesMessage facesMessage;
private String paginaResultado;
Empleado empleado;
// Venta
private Long idCliente;
private Long idArticulo;
private Double precio = 0.0;
private Long cant = 1L;
private Double subtotal = 0.0;
private List<SelectItem> articulos;
private List<SelectItem> clientes;
@Autowired
Carrito carrito;
// private Carrito carrito;
public VentaController() {
System.out.println("ventaController");
facesContext = WebUtil.getFacesContextCurrentInstance();
System.out.println(facesContext);
empleado = new Empleado();
}
public Carrito getCarrito() {
return carrito;
}
public Double getSubtotal() {
return subtotal;
}
public Empleado getEmpleado() {
if(carrito.getEmpleado() == null)
return empleado;
else
return serviceFactory.getEmpleadoService().obtener(carrito.getEmpleado());
}
public void setEmpleado(Empleado empleado) {
this.empleado = empleado;
}
public Long getCant() {
return cant;
}
public void setCant(Long cant) {
this.cant = cant;
}
public Double getPrecio() {
return precio;
}
public void setPrecio(Double precio) {
this.precio = precio;
}
public Long getIdCliente() {
return idCliente;
}
public void setIdCliente(Long idCliente) {
this.idCliente = idCliente;
}
public Long getIdArticulo() {
return idArticulo;
}
public void setIdArticulo(Long idArticulo) {
this.idArticulo = idArticulo;
}
public String login() {
empleado = serviceFactory.getEmpleadoService().buscarLogin(empleado);
if (empleado == null) {
facesMessage = new FacesMessage(FacesMessage.SEVERITY_ERROR,
WebUtil.getMensaje("validacion.login.incorrecto"),
Constantes.VACIO);
paginaResultado = "login";
} else {
facesMessage = new FacesMessage(FacesMessage.SEVERITY_INFO,
WebUtil.getMensaje("validacion.login.correcto",
empleado.getNombre()), Constantes.VACIO);
WebUtil.keepMessages();
paginaResultado = "/paginas/modulos/principal/ventas"
+ Constantes.REDIRECT_JSF;
carrito.setEmpleado(empleado.getId());
}
facesContext.addMessage(null, facesMessage);
// facesContext.
return paginaResultado;
}
public List<SelectItem> getClientes() {
if (clientes == null) {
try {
clientes = new ArrayList<SelectItem>();
List<Cliente> lista = serviceFactory.getClienteService().listar();
for (Cliente c : lista) {
SelectItem op = new SelectItem();
op.setValue(c.getId());
op.setLabel(c.getNombre());
clientes.add(op);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return clientes;
}
public List<SelectItem> getArticulos() {
if (articulos == null) {
try {
articulos = new ArrayList<SelectItem>();
List<Articulo> lista = serviceFactory.getArticuloService().listar();
for (Articulo a : lista) {
SelectItem op = new SelectItem();
op.setValue(a.getId());
op.setLabel(a.getNombre());
articulos.add(op);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return articulos;
}
public void setArticulos(List<SelectItem> articulos) {
this.articulos = articulos;
}
public void setClientes(List<SelectItem> clientes) {
this.clientes = clientes;
}
public String doSalir() {
carrito.clear();
carrito.setEmpleado(null);
return "/paginas/modulos/seguridad/login";
}
public void modificarPrecio(ValueChangeEvent event) {
try {
Long idArt = (Long) event.getNewValue();
Articulo a = serviceFactory.getArticuloService().obtener(idArt);
precio = a.getPrecio();
subtotal = precio * cant;
} catch (Exception e) {
precio = 0.0;
}
}
public void modificarCantidad(ValueChangeEvent event) {
try {
Long c = (Long) event.getNewValue();
subtotal = precio * c;
} catch (Exception e) {
precio = 0.0;
}
}
public String doAgregarItem(){
try {
Articulo a = serviceFactory.getArticuloService().obtener(idArticulo);
CarritoItem item = new CarritoItem();
item.setId(a.getId());
item.setCodigo(a.getCodigo());
item.setNombre(a.getNombre());
item.setPrecio(a.getPrecio());
item.setCant(cant);
item.setSubtotal(item.getPrecio() * item.getCant());
carrito.add(item);
} catch (Exception e) {
}
return "ventas";
}
public String doEliminarItem( Long id ) {
carrito.remove(id);
return "ventas";
}
public String doGrabar(){
paginaResultado = "ventas";
try {
carrito.setCliente(idCliente);
// carrito.setEmpleado(empleado.getId());
serviceFactory.getVentaService().grabarVenta(carrito);
Cliente cliente = serviceFactory.getClienteService().obtener(idCliente);
if (cliente.getTipo().equals("natural"))
paginaResultado = "/paginas/modulos/principal/boleta";
if (cliente.getTipo().equals("juridica"))
paginaResultado = "/paginas/modulos/principal/factura";
// carrito.clear();
} catch (Exception e) {
e.printStackTrace();
}
return paginaResultado;
}
public String doVolver(){
carrito.clear();
return "/paginas/modulos/principal/ventas";
}
}
|
/*
* MIT License
*
* Copyright (c) 2019 Bayu Dwiyan Satria
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.bayudwiyansatria.environment.apache.spark;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.rdd.RDD;
import java.util.List;
public class SparkUtils extends Spark {
public double[][] javaRDD_to_double(JavaRDD<String> data) {
List<String> newData = data.collect();
double[][] doubleData = new double[newData.size()][newData.get(0).split(",").length];
for(int i=0; i<newData.size(); i++){
String[] array = newData.get(i).split(",");
for (int j = 0; j < array.length; j++) {
doubleData[i][j] = Double.parseDouble(array[j]);
}
}
return doubleData;
}
public int[][] javaRDD_to_int(JavaRDD<String> data){
return new com.bayudwiyansatria.utils.Utils().double_to_int(this.javaRDD_to_double(data));
}
public RDD<?> javaRDD_to_rdd(JavaRDD<?> data){
return data.rdd();
}
public String[] ParseSparkArguments(String[] Argument){
String SparkMaster = Argument[1];
if(SparkMaster.equals("yarn")){
this.setDeployMode("cluster");
} else if(SparkMaster.contains("local")){
setDeployMode("client");
} else {
setDeployMode(getDeployMode());
}
setSparkConfiguration();
return getSparkConfiguration();
}
public void SparkOptimizeConfiguration(){
setExecutorMemory("4g");
setDriverMemory("1g");
setExecutorCores("5");
setDriverCores("1");
setNumExecutors("3");
}
}
|
package com.company.oop_final_challenge;
public class HealthyBurger extends BaseBurger {
private String addition5;
private String addition6;
public HealthyBurger(String meat, int burgerCost) {
super("Healthy burger","Brown rye bread roll", meat, burgerCost);
}
@Override
public void printListadded() {
super.printListadded();
if(getAddition5() != null){
System.out.println("Added " + getAddition5());
}
if(getAddition6() != null){
System.out.println("Added " + getAddition6());
}
}
@Override
public void getBurgerTotal() {
super.getBurgerTotal();
}
public String getAddition5() {
return addition5;
}
public void setAddition5(String addition5) {
addAdditionToCost();
this.addition5 = addition5;
System.out.println("You're added a " + addition5 + " now burger cost is: " + super.getTotal());
}
public String getAddition6() {
return addition6;
}
public void setAddition6(String addition6) {
addAdditionToCost();
this.addition6 = addition6;
System.out.println("You're added a " + addition6 + " now burger cost is: " + super.getTotal());
}
}
|
package pattern_test.state;
/**
* Description:
*
* @author Baltan
* @date 2019-04-04 14:38
*/
public class StopState implements State {
@Override
public void action(LightState lightState) {
System.out.println("红灯:停车等候");
lightState.setLight(Light.GREEN);
System.out.println("绿灯:准备通行");
}
}
|
package littleservantmod.client.gui.inventory;
import org.lwjgl.opengl.GL11;
import littleservantmod.LittleServantMod;
import littleservantmod.entity.EntityLittleServant;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.translation.I18n;
public class LabelText extends GuiLSMButton {
ResourceLocation texture = new ResourceLocation(LittleServantMod.MOD_ID, "textures/guis/container/labels.png");
EntityLittleServant servant;
private boolean isNormal = false;
public LabelText(GuiServantBase gui, int buttonId, int x, int y, EntityLittleServant servant) {
super(gui, buttonId, x, y, 97, 20, "");
this.servant = servant;
}
public boolean isNormal() {
return isNormal;
}
public LabelText setNormal(boolean isNormal) {
this.isNormal = isNormal;
return this;
}
@Override
public void drawButton(Minecraft mc, int mouseX, int mouseY, float partialTicks) {
this.preDrawButton();
if (this.visible) {
if (this.visible) {
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glEnable(GL11.GL_DEPTH_TEST);
GlStateManager.enableBlend();
GlStateManager.tryBlendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ZERO);
GlStateManager.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA);
mc.renderEngine.bindTexture(this.texture);
int yOfset = !isNormal ? 3 : 3 + 26;
if (!this.enabled) yOfset += 26;
this.drawTexturedModalRect(this.x, this.y, 29, yOfset, this.width, this.height);
GlStateManager.color(1.0F, 1.0F, 1.0F);
int j = 14737632;
if (isNormal) j = 4210752;
if (!this.enabled) j = 14737632;
if (isNormal) {
mc.fontRenderer.drawString(getLabelText(), this.x + 6, this.y + 7, j);
} else {
this.drawString(mc.fontRenderer, getLabelText(), this.x + 6, this.y + 7, j);
}
GL11.glDisable(GL11.GL_DEPTH_TEST);
}
/*
FontRenderer fontrenderer = mc.fontRenderer;
mc.getTextureManager().bindTexture(texture);
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
this.hovered = mouseX >= this.x && mouseY >= this.y && mouseX < this.x + this.width && mouseY < this.y + this.height;
int i = this.getHoverState(this.hovered);
GL11.glEnable(GL11.GL_DEPTH_TEST);
//GlStateManager.enableBlend();
//GlStateManager.tryBlendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ZERO);
//GlStateManager.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA);
this.drawTexturedModalRect(this.x, this.y, 29, 3, this.width, this.height);
//this.drawTexturedModalRect(this.x + this.width / 2, this.y, 200 - this.width / 2, 46 + i * 20, this.width / 2, this.height);
this.mouseDragged(mc, mouseX, mouseY);
int j = 14737632;
/*
if (packedFGColour != 0) {
j = packedFGColour;
} else if (!this.enabled) {
j = 10526880;
} else if (this.hovered) {
j = 16777120;
}*/
/*
GL11.glDisable(GL11.GL_DEPTH_TEST);
String displayString2 = this.servant.getProfession().getProfessionDisplayName(servant);
//this.drawCenteredString(fontrenderer, displayString2, this.x + 6, this.y + 10, j);
this.drawString(fontrenderer, displayString2, this.x + 6, this.y + 10, j);
*/
}
}
public void preDrawButton() {
}
public String getLabelText() {
return this.servant.getProfession().getProfessionDisplayName(servant);
}
@Override
protected void renderHoveredToolTip(int mouseX, int mouseY) {
gui.drawHoveringText(I18n.translateToLocal(getHoveredToolTip()), mouseX, mouseY);
}
protected String getHoveredToolTip() {
return "tooltip.change_profession.name";
}
}
|
package random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
import static random.InterruptDuringIntrinsicLockHeld.latch;
public class InterruptDuringIntrinsicLockHeld {
final static CountDownLatch latch = new CountDownLatch(1);
public static void main(String[] args) throws InterruptedException {
final Foo foo = new Foo();
final Thread thread = new Thread(() -> {
try {
foo.intrinsicLock();
} catch (InterruptedException e) {
System.out.println("interrupted");
}
foo.isLockReleased();
});
thread.start();
latch.await();
thread.interrupt();
}
}
class Foo {
synchronized void intrinsicLock() throws InterruptedException {
System.out.println(this + " entered");
latch.countDown();
new Semaphore(0).acquire();
System.out.println("After Interrupted");
}
synchronized void isLockReleased() {
System.out.println("Yes, the Semaphore acquire has been interrupted and the synchronized method released its lock");
}
}
|
package com.e6soft.activiti.service;
import java.io.IOException;
import org.codehaus.jackson.JsonProcessingException;
import com.e6soft.activiti.controllers.form.FlowModelForm;
public interface FlowModelService {
public String saveFlowModel(FlowModelForm flowModelForm);
public FlowModelForm modifyFlowModelForm(String id);
public String publishFlowModel(String id) throws JsonProcessingException, IOException;
public void deleteFlowModel(String id,Integer delDeployment);
public boolean checkFlowModel(FlowModelForm flowModelForm);
}
|
package com.company;
/**
* Created by isa on 9/14/15.
*/
public class Calculator {
private int divisor;
private float value;
public void add(String valueAsString) {
float valueAsFloat = transformValueFromStringToInt(valueAsString);
value += valueAsFloat;
}
private float transformValueFromStringToInt(String valueAsString) {
return Float.parseFloat(valueAsString);
}
public void setDivisor(int divisor) {
this.divisor = divisor;
}
public float calculateAverage() {
return value/divisor;
}
}
|
package com.tenjava.entries.Ad237.t3.event.events;
import com.tenjava.entries.Ad237.t3.RandomEvents;
import com.tenjava.entries.Ad237.t3.event.RandomEvent;
import com.tenjava.entries.Ad237.t3.utils.EntityUtils;
import org.bukkit.entity.LivingEntity;
import org.bukkit.event.EventHandler;
import org.bukkit.event.entity.CreatureSpawnEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
public class RandomName extends RandomEvent {
private static Random rand = new Random();
private ArrayList<String> firstHalf = new ArrayList<String>();
public RandomName(RandomEvents plugin) {
super(plugin, "random-name");
firstHalf.addAll(Arrays.asList("Ultimate", "Super", "Stupid", "Badass", "Raging", "Scary", "Bob the "));
}
@EventHandler
public void onSpawn(CreatureSpawnEvent event) {
if(!isEnabled()) {
return;
}
if(shouldHappen()) {
LivingEntity entity = event.getEntity();
String randomWord = firstHalf.get(rand.nextInt(firstHalf.size()));
randomWord += EntityUtils.getName(entity);
entity.setCustomName(randomWord);
entity.setCustomNameVisible(true);
}
}
}
|
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
class ReminderTask extends TimerTask {
//Class Objects
Task taskToRemind;
Timer taskAlarm;
Date alarmTime;
//@author A0112898U
/**
* Constructor for Reminder Task.
*
* @param inTask The task to use to construct a ReminderTask Object
* @param inDate The reminder date of the task
*/
public ReminderTask(Task inTask, Date inDate) {
taskToRemind = inTask;
alarmTime = inDate;
}
//@author A0112898U
/**
* Getter function to get the defined task.
*
* @return the task for this ReminderTask
*/
public Task getTask() {
return taskToRemind;
}
//@author A0112898U
/**
* API Function to edit a task
*
* @param editedTask The edited task to be updated to
*/
public void editTask(Task editedTask) {
taskToRemind = new Task(editedTask);
alarmTime = new Date(editedTask.getReminder());
}
//@author A0112898U
/**
* Indicate the action to do when the alarm goes off
* for the scheduled reminder for this task
*
* * This is a default function to have in order to be
* * scheduled into timer.schedule.
*/
public void run() {
new Notification("Reminder: \n" + taskToRemind.getName(),
taskToRemind.getDescription(),
"Due on " + taskToRemind.getFormattedDeadline(),
"", "").display();
}
//@author A0112898U
/**
* Stops the alarm that have been scheduled.
*/
public void stopAlarm () {
taskAlarm.cancel();
}
//@author A0112898U
/**
* Schedules the alarm time for the task.
*/
public void scheduleAlarm() {
taskAlarm = new Timer();
taskAlarm.schedule(new ReminderTask(taskToRemind, alarmTime),
alarmTime);
}
}
|
package Lesson3;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
guessNumber();
oneMoreTime();
}
public static void guessNumber() {
int guessNum = (int) (Math.random() * 10);
Scanner sc = new Scanner(System.in);
System.out.println("Угадай число от 0 до 9\nНа это у Вас есть всего 3 попытки!");
int step = 1, maxStep = 3;
do {
System.out.println("Введите число:");
int number = sc.nextInt();
System.out.println("Вы ввели число " + number);
if (number == guessNum) {
System.out.println("Ура, Вы угадали!");
break;
} else if (step == maxStep) {
System.out.println("Вы проиграли!\nПравильный ответ " + guessNum);
break;
} else if (number > guessNum) {
System.out.println("Вы ввели слишком большое число.\nУ вас осталось " + (maxStep - step) + " попыток.");
step++;
} else if (number < guessNum) {
System.out.println("Вы ввели слишком маленькое число.\nУ вас осталось " + (maxStep - step) + " попыток.");
step++;
}
}
while (step <= maxStep);
}
public static void oneMoreTime() {
Scanner sc = new Scanner(System.in);
System.out.println("Повторить игру еще раз? 1 – да / 0 – нет");
int oneMoreTime = sc.nextInt();
if (oneMoreTime == 1) {
guessNumber();
oneMoreTime();
} else {
System.out.println("Игра окончена");
}
}
}
|
package ua.project.protester.service;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ua.project.protester.model.Environment;
import ua.project.protester.repository.EnvironmentRepository;
import ua.project.protester.utils.Page;
import ua.project.protester.utils.Pagination;
import java.util.List;
import java.util.Optional;
@Service
@RequiredArgsConstructor
public class EnvironmentService {
private final EnvironmentRepository repository;
@Transactional
public Optional<Environment> findById(Long id) {
return repository.findEnvironmentById(id);
}
@Transactional
public Environment save(Environment environment) {
return repository.saveEnvironment(environment);
}
@Transactional
public Environment update(Environment environment) {
return repository.updateEnvironment(environment);
}
@Transactional
public List<Environment> findAll(Long projectId) {
return repository.findAll(projectId);
}
@Transactional
public void delete(Long id) {
repository.deleteEnvironmentById(id);
}
@Transactional
public Page<Environment> findAllPaginatedByProjectId(Pagination pagination, Long projectId) {
return new Page<>(
repository.findAll(pagination, projectId),
repository.count(pagination, projectId)
);
}
}
|
/*
* 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 TallerPoo;
public class CTI extends Cuidado {
private Hospital cti;
public CTI(Persona p) {
super(4, p);
// this.cti = cti;
}
}
|
package com.czy.demos.springbootbetterretry.config.CustomAnnotationRetry;
import java.lang.annotation.*;
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CustomRetryAnnotation {
//重试次数
int retryTimes() default 5;
}
|
package com.diozero.sampleapps;
/*-
* #%L
* Organisation: diozero
* Project: diozero - Sample applications
* Filename: ShiftRegisterTest.java
*
* This file is part of the diozero project. More information about this project
* can be found at https://www.diozero.com/.
* %%
* Copyright (C) 2016 - 2023 diozero
* %%
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
* #L%
*/
import org.tinylog.Logger;
import com.diozero.devices.LED;
import com.diozero.devices.OutputShiftRegister;
import com.diozero.devices.PwmLed;
import com.diozero.util.Diozero;
import com.diozero.util.SleepUtil;
public class ShiftRegisterTest {
public static void main(String[] args) {
// White wire (SER pin 14)
int data_gpio = 22;
// int data_gpio = 4;
// Purple wire (SRCLK pin 11)
int clock_gpio = 17;
// int clock_gpio = 6;
// Brown wire (RCLK pin 12)
int latch_gpio = 27;
// int latch_gpio = 5;
int delay_ms = 500;
try (OutputShiftRegister osr = new OutputShiftRegister(data_gpio, clock_gpio,
latch_gpio, 8)) {
for (int i = 0; i < 3; i++) {
Logger.info("All on");
for (int pin = 0; pin < 8; pin++) {
osr.setBufferedValue(pin, true);
}
osr.flush();
SleepUtil.sleepMillis(delay_ms);
Logger.info("Alternate");
for (int pin = 0; pin < 8; pin++) {
osr.setBufferedValue(pin, (pin % 2) == 0);
}
osr.flush();
SleepUtil.sleepMillis(delay_ms);
Logger.info("Alternate opposite");
for (int pin = 0; pin < 8; pin++) {
osr.setBufferedValue(pin, (pin % 2) == 1);
}
osr.flush();
SleepUtil.sleepMillis(delay_ms);
Logger.info("One by one");
for (int pin = 0; pin < 8; pin++) {
Logger.info("pin {}", Integer.valueOf(pin));
/*-
for (int x = 0; x < 8; x++) {
osr.setBufferedValue(x, pin == x);
}
osr.flush();
*/
osr.setValues(0, (byte) (1 << pin));
SleepUtil.sleepMillis(delay_ms);
}
Logger.info("All off");
for (int pin = 0; pin < 8; pin++) {
osr.setBufferedValue(pin, false);
}
osr.flush();
SleepUtil.sleepMillis(delay_ms);
}
for (int i = 1; i < 4; i++) {
try (LED led = new LED(osr, i)) {
Logger.info("LED {} on", Integer.valueOf(i));
led.on();
SleepUtil.sleepMillis(delay_ms);
Logger.info("LED {} off", Integer.valueOf(i));
led.off();
SleepUtil.sleepMillis(delay_ms);
Logger.info("LED {} blink", Integer.valueOf(i));
led.blink(0.25f, 0.25f, 4, false);
}
}
int pwm_num = 1;
try (PwmLed pwm_led = new PwmLed(osr, pwm_num)) {
for (float f = 0; f < 1; f += 0.05f) {
Logger.info("PWM {} value {#,###.##}", Integer.valueOf(pwm_num), Float.valueOf(f));
pwm_led.setValue(f);
SleepUtil.sleepMillis(150);
}
for (float f = 1; f >= 0; f -= 0.05f) {
Logger.info("PWM {} value {#,###.##}", Integer.valueOf(pwm_num), Float.valueOf(f));
pwm_led.setValue(f);
SleepUtil.sleepMillis(150);
}
}
} finally {
Diozero.shutdown();
}
}
}
|
package com.build.bamboo.plugins;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import com.atlassian.bamboo.collections.ActionParametersMap;
import com.atlassian.bamboo.task.AbstractTaskConfigurator;
import com.atlassian.bamboo.task.TaskDefinition;
import com.atlassian.bamboo.utils.error.ErrorCollection;
import com.opensymphony.xwork.TextProvider;
public class VeracodeUploadConfigurator extends AbstractTaskConfigurator
{
private TextProvider textProvider;
@NotNull
@Override
public Map<String, String> generateTaskConfigMap(@NotNull final ActionParametersMap params, @Nullable final TaskDefinition previousTaskDefinition)
{
final Map<String, String> config = super.generateTaskConfigMap(params, previousTaskDefinition);
config.put("api_username", params.getString("api_username"));
config.put("api_password", params.getString("api_password"));
config.put("app_id", params.getString("app_id"));
config.put("app_platform", params.getString("app_platform"));
config.put("build_id", params.getString("build_id"));
config.put("source_file", params.getString("source_file"));
return config;
}
@Override
public void populateContextForCreate(@NotNull final Map<String, Object> context)
{
super.populateContextForCreate(context);
context.put("api_username", "${bamboo.capability.veracode.username}");
context.put("api_password", "${bamboo.capability.veracode.password}");
context.put("build_id", "${bamboo.repository.revision.number}");
}
@Override
public void populateContextForEdit(@NotNull final Map<String, Object> context, @NotNull final TaskDefinition taskDefinition)
{
super.populateContextForEdit(context, taskDefinition);
context.put("api_username", taskDefinition.getConfiguration().get("api_username"));
context.put("api_password", taskDefinition.getConfiguration().get("api_password"));
context.put("app_id", taskDefinition.getConfiguration().get("app_id"));
context.put("app_platform", taskDefinition.getConfiguration().get("app_platform"));
context.put("build_id", taskDefinition.getConfiguration().get("build_id"));
context.put("source_file", taskDefinition.getConfiguration().get("source_file"));
}
@Override
public void populateContextForView(@NotNull final Map<String, Object> context, @NotNull final TaskDefinition taskDefinition)
{
super.populateContextForView(context, taskDefinition);
context.put("api_username", taskDefinition.getConfiguration().get("api_username"));
context.put("api_password", taskDefinition.getConfiguration().get("api_password"));
context.put("app_id", taskDefinition.getConfiguration().get("app_id"));
context.put("app_platform", taskDefinition.getConfiguration().get("app_platform"));
context.put("build_id", taskDefinition.getConfiguration().get("build_id"));
context.put("source_file", taskDefinition.getConfiguration().get("source_file"));
}
@Override
public void validate(@NotNull final ActionParametersMap params, @NotNull final ErrorCollection errorCollection)
{
super.validate(params, errorCollection);
final String apiUserValue = params.getString("api_username");
final String apiPasswordValue = params.getString("api_password");
final String appIdValue = params.getString("app_id");
final String appPlatformValue = params.getString("app_platform");
final String buildIdValue = params.getString("build_id");
final String sourceFileValue = params.getString("source_file");
if (StringUtils.isEmpty(apiUserValue))
{
errorCollection.addError("api_username", textProvider.getText("myfirstplugin.api_username.error"));
}
if (StringUtils.isEmpty(apiPasswordValue))
{
errorCollection.addError("api_password", textProvider.getText("myfirstplugin.api_password.error"));
}
if (StringUtils.isEmpty(appIdValue))
{
errorCollection.addError("app_id", textProvider.getText("myfirstplugin.app_id.error"));
}
if (StringUtils.isEmpty(appPlatformValue))
{
errorCollection.addError("app_platform", textProvider.getText("myfirstplugin.app_platform.error"));
}
if (StringUtils.isEmpty(buildIdValue))
{
errorCollection.addError("build_id", textProvider.getText("myfirstplugin.build_id.error"));
}
if (StringUtils.isEmpty(sourceFileValue))
{
errorCollection.addError("source_file", textProvider.getText("myfirstplugin.source_file.error"));
}
}
public void setTextProvider(final TextProvider textProvider)
{
this.textProvider = textProvider;
}
}
|
package com.smxknife.java.ex20;
import java.util.Arrays;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author smxknife
* 2018-12-03
*/
public class ParallelDemo2 {
public static void main(String[] args) {
ExecutorService service2 = Executors.newFixedThreadPool(10);
ExecutorService service = Executors.newFixedThreadPool(1);
CompletableFuture[] completableFutures = Arrays.asList(1, 2, 3, 4, 5).stream().map(i -> CompletableFuture.supplyAsync(() -> {
System.out.println(">>>>> " + i);
return i;
}, service).thenApply(ii -> {
CompletableFuture[] futures = Arrays.asList(100, 200, 300, 400).stream().map(jj -> CompletableFuture.supplyAsync(() -> {
System.out.println("current i = " + ii + ", current value = " + jj + "Thread : " + Thread.currentThread().getName());
return jj;
})).toArray(CompletableFuture[]::new);
CompletableFuture.allOf(futures).join();
// Arrays.asList(100, 200, 300, 400).stream().other().forEach(jj -> {
// System.out.println("current i = " + ii + ", current value = " + jj + "Thread : " + Thread.currentThread().getName());
// });
return ii;
})).toArray(CompletableFuture[]::new);
CompletableFuture.allOf(completableFutures).join();
System.out.println("finish");
}
}
|
package practice;
import java.util.ArrayList;
import java.util.List;
/* 戦士の会心の一撃!
ヒットポイント:100
遊び人は、ただ遊んでいるだけだった!
ヒットポイント:0 */
public class Chapter14 {
public static void main(String[] args) {
List<Character> party = new ArrayList<Character>();
// プログラムを作成
// インスタンスをaddメソッドで追加する
party.add(new Soldier());
party.add(new Playboy());
Chapter14.partyAttack(party);
}
public static void partyAttack(List<Character> party) {
for (Character character : party) {
int hp = character.attack();
System.out.println("ヒットポイント:" + hp);
}
}
}
|
package sevenkyu.twotoone;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class TwoToOneTest {
TwoToOne twoToOne;
@BeforeEach
void init() {
twoToOne = new TwoToOne();
}
@Test
void longest_shouldConcatInputStrings() {
// given
String string = "abc";
String otherString = "def";
String expected = "abcdef";
// when
String output = twoToOne.longest(string, otherString);
// then
assertThat(output).isEqualTo(expected);
}
@Test
void longest_shouldSortLetters() {
// given
String string = "string";
String otherString = "key";
String expected = "egiknrsty";
// when
String output = twoToOne.longest(string, otherString);
// then
assertThat(output).isEqualTo(expected);
}
@Test
void longest_shouldFilterDuplicates() {
// given
String string = "lessdangerousthancoding";
String otherString = "loopingisfunbutdangerous";
String expected = "abcdefghilnoprstu";
// when
String output = twoToOne.longest(string, otherString);
// then
assertThat(output).isEqualTo(expected);
}
}
|
package Ejemplos;
import java.util.ArrayList;
public class Data {
public static int findLargest(ArrayList<Integer> nums){
int largest = nums.get(0);
for (int number : nums) {
if (number > largest){
largest = number;
}
}
return largest;
}
}
|
package dh.geometry.regions;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import dh.geometry.OurPoint;
import dh.geometry.OurPolygon;
public class TestPointInPolygon {
@Test
public void testFirstPolygon() {
OurPolygon polygon = new OurPolygon(new OurPoint(1, 1), new OurPoint(3,
5), new OurPoint(6, 2), new OurPoint(9, 6),
new OurPoint(10, 0), new OurPoint(4, 2), new OurPoint(5, -2));
assertTrue(polygon.hasPoint(new OurPoint(3, 4)));
assertTrue(polygon.hasPoint(new OurPoint(3, 1)));
assertFalse(polygon.hasPoint(new OurPoint(3, -2)));
assertFalse(polygon.hasPoint(new OurPoint(5, 4)));
assertFalse(polygon.hasPoint(new OurPoint(5, 1)));
assertFalse(polygon.hasPoint(new OurPoint(5, -2)));
assertFalse(polygon.hasPoint(new OurPoint(7, 4)));
assertTrue(polygon.hasPoint(new OurPoint(7, 1)));
assertFalse(polygon.hasPoint(new OurPoint(7, -2)));
}
@Test
public void testSecondPolygon() {
OurPolygon polygon = new OurPolygon(new OurPoint(2, 3), new OurPoint(3,
2), new OurPoint(1, 0), new OurPoint(0, 1), new OurPoint(0, 2));
assertFalse(polygon.hasPoint(new OurPoint(0, 0)));
assertTrue(polygon.hasPoint(new OurPoint(1, 1)));
assertTrue(polygon.hasPoint(new OurPoint(2, 2)));
assertFalse(polygon.hasPoint(new OurPoint(2.5, 2.5)));
assertFalse(polygon.hasPoint(new OurPoint(3, 3)));
}
}
|
package cn.gz3create.module_ad.vip;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import com.ifmvo.togetherad.core.helper.AdHelperReward;
import com.ifmvo.togetherad.core.listener.RewardListener;
import java.util.HashMap;
import java.util.Map;
import androidx.annotation.NonNull;
import cn.gz3create.module_ad.AdProviderType;
import cn.gz3create.module_ad.TogetherAdAlias;
import cn.gz3create.module_ad.view.AdDialog;
public class VipDialog extends AdDialog {
private String alias = TogetherAdAlias.AD_REWARD;
private Map<String, Integer> ratioMap;
private RewardListener listener;
public VipDialog(@NonNull Activity activity) {
super(activity);
ratioMap = new HashMap<>();
ratioMap.put(AdProviderType.GDT.getType(), 0);
ratioMap.put(AdProviderType.CSJ.getType(), 1);
ratioMap.put(AdProviderType.BAIDU.getType(), 0);
}
private OnVIPClickListener onVIPClickListener;
private AdHelperReward adHelperReward;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
//必须先调用这个方法
public void loadAd(String alias, Map<String, Integer> ratioMap, @NonNull RewardListener listener) {
if (alias != null && !alias.isEmpty()) {
this.alias = alias;
}
if (ratioMap != null && ratioMap.size() > 0) {
this.ratioMap = ratioMap;
}
this.listener = listener;
if (adHelperReward == null) {
adHelperReward = new AdHelperReward(activity, this.alias, this.ratioMap, listener);
}
adHelperReward.load();
}
@Override
protected void initView() {
super.initView();
close.setVisibility(View.VISIBLE);
setMessage("此功能为VIP专享,您可以开通VIP或者观看一段广告获得使用权");
setNegtive("查看广告");
setPositive("取消");
setOnClickBottomListener(new OnClickBottomListener() {
@Override
public void onPositiveClick() {
if (onVIPClickListener != null) {
onVIPClickListener.onClick();
}
dismiss();
}
@Override
public void onNegtiveClick() {
adHelperReward.show();
dismiss();
}
});
}
public void setOnVIPClickListener(OnVIPClickListener onVIPClickListener) {
this.onVIPClickListener = onVIPClickListener;
}
public interface OnVIPClickListener {
/**
* 点击开通VIP按钮事件
*/
void onClick();
}
@Override
public void dismiss() {
super.dismiss();
if (adHelperReward == null) {
adHelperReward = new AdHelperReward(activity, alias, ratioMap, listener);
}
adHelperReward.load();
}
}
|
package graph.types;
import java.util.Date;
public abstract class PublicTransportNode implements IsoVertex {
// Attributes
private String name = "";
private int id = 0;
protected Date time = null;
private String tripId = "";
private int stopSequence = 0;
public PublicTransportNode(Date time, String tripId, int stopSequence) {
this.time = time;
this.tripId = tripId;
this.stopSequence = stopSequence;
}
/**
* @param lat Latitude
* @param lon Longitude
* @param name Name of the node
* @param id Id of the node
* @param time Time of the node
* @param tripId Id of the trip
* @param stopSequence Number of stop in the trip
*/
public PublicTransportNode(String name, int id, Date time, String tripId, int stopSequence) {
this.name = name;
this.id = id;
this.time = time;
this.tripId = tripId;
this.stopSequence = stopSequence;
}
/**
*
* @return Attribute time
*/
public Date getTime() {
return time;
}
/**
*
* @param time Set a new time
*/
public void setTime(Date time) {
this.time = time;
}
/**
*
* @return TripId of the node
*/
public String getTripId() {
return tripId;
}
/**
* @param tripId set a new trip ID
*/
public void setTripId(String tripId) {
this.tripId = tripId;
}
/**
* @return the stopSequence
*/
public int getStopSequence() {
return stopSequence;
}
/**
* @param stopSequence the stopSequence to set
*/
public void setStopSequence(int stopSequence) {
this.stopSequence = stopSequence;
}
/**
* Method for sorting lists of VrsNodes
*
* @param otherNode Other VrsNode
* @return Integer for sorting
*/
public int compareTo(PublicTransportNode otherNode) {
if (this.time.before(otherNode.time))
return -1;
if (this.time.after(otherNode.time))
return 1;
if (this.getId() < otherNode.getId())
return -1;
if (this.getId() > otherNode.getId())
return 1;
return 0;
}
@Override
public int compareTo(IsoVertex otherVertex) {
if (otherVertex.getClass() == PublicTransportNode.class || otherVertex.getClass() == ArrivalNode.class
|| otherVertex.getClass() == TransferNode.class) {
return this.compareTo((PublicTransportNode) otherVertex);
}
if (this.id < otherVertex.getId()) {
return -1;
} else if (this.id > otherVertex.getId()) {
return 1;
}
return 0;
}
@Override
public String getName() {
return this.name;
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public int getId() {
return this.id;
}
@Override
public void setId(int id) {
this.id = id;
}
}
|
package com.example.healthmanage.bean.recyclerview;
public class DoctorRecyclerView {
}
|
package com.prudential.car.dao.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Car {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String model;
private int remainCount;
private int version;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getRemainCount() {
return remainCount;
}
public void setRemainCount(int remainCount) {
this.remainCount = remainCount;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
}
|
import java.io.*;
import java.util.*;
import java.awt.*;
import javax.servlet.*;
import javax.servlet.http.*;
import activities.db.*;
public class eliminarReserva extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)throws IOException, ServletException{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("GET Request. No Form Data Posted");
}
public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException{
String nia = req.getParameter("id").toString();
try{
DBInteraction db=new DBInteraction();
db.delReserva(nia);
req.getRequestDispatcher("adminReservas.html").include(req, res);
db.close();
}catch (Exception e){
}
}//doPost end
}//class end
|
package org.XuJiaLe.dao;
import java.util.List;
import org.XuJiaLe.model.MessageBean;
public interface MessageDao {
/**
* 向数据库插入消息,并插入接收者与信息的关系
* @param receiverId
* @param message
* @return
*/
public int insertOne(long receiverId,MessageBean message);
/**
* 查询用户的所有消息
* @param receiverId
* @return
*/
public List<MessageBean> select(int read, long receiverId);
/**
* 更新消息的阅读状态
* @param receiverId
* @param messageId
* @return
*/
public int updateRead(long receiverId,long messageId);
}
|
package com.tencent.mm.plugin.aa.ui;
import android.content.Intent;
import com.tencent.mm.plugin.aa.a.a;
import com.tencent.mm.plugin.report.service.h;
class LaunchAAUI$16 implements a$a {
final /* synthetic */ LaunchAAUI eDS;
LaunchAAUI$16(LaunchAAUI launchAAUI) {
this.eDS = launchAAUI;
}
public final void We() {
this.eDS.startActivity(new Intent(this.eDS, AAQueryListUI.class));
if (LaunchAAUI.b(this.eDS) == a.ezD) {
h.mEJ.h(13721, new Object[]{Integer.valueOf(5), Integer.valueOf(1)});
return;
}
h.mEJ.h(13721, new Object[]{Integer.valueOf(5), Integer.valueOf(2)});
}
}
|
package br.com.bytebank.financas.teste;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import br.com.bytebank.financas.modelo.Movimentacao;
import br.com.bytebank.financas.util.JPAUtil;
public class TesteJPQL {
public static void main(String[] args) {
EntityManager em = JPAUtil.getEntityManager();
em.getTransaction().begin();
String jpql = "select m from Movimentacao m join m.listaDeContas mc "
+ "where mc.numero = :pContaNumero";
Query query = em.createQuery(jpql);
query.setParameter("pContaNumero", 5201);
List<Movimentacao> resultados = query.getResultList();
resultados.forEach(c -> System.out.println(c.getTipo() + " - " + c.getValor()) );
em.getTransaction().commit();
em.close();
}
}
|
package dh.geometry.closestPoints;
import java.util.ArrayList;
import dh.geometry.OurPoint;
public class ClosestPointsFinder {
public OurPoint[] getClosestPoints(OurPoint[] allPoints) {
/*
* Check ob das übergebene Array vielleicht nur 0,1,2 Elemente
* beinhaltet. Falls zwei Punkte enthalten sind werden diese
* zurückgegegeben. Ansonsten null.
*/
if (allPoints.length < 2) {
return null;
} else if (allPoints.length == 2) {
if (allPoints[0] != null && allPoints[1] != null) {
return allPoints;
} else {
return null;
}
}
/*
* In folgendem Array sollen nachher die dichtesten zwei Punkte
* übergeben werden.
*/
OurPoint[] closestPoints = null;
/*
* Das folgende Array beinhaltet die Punktemenge nach x sortiert.
*/
OurPoint[] sortedByX = sortByX(allPoints);
/*
* Aufruf der Rekursion für die komplette Punktemenge
*/
closestPoints = getClosestPointsRecursive(sortedByX, 0,
sortedByX.length - 1);
return closestPoints;
}
private OurPoint[] getClosestPointsRecursive(OurPoint[] sortedByX, int i,
int j) {
OurPoint[] closestPoints = null;
/*
* Check, ob nur keine, einer, zwei oder 3 Punkt(e) vorhanden sind. Bei
* zwei gib diese zurück. Bei drei suche die kürzeste Distanz in extra
* Methode. Ansonsten null.
*/
if (j - i < 1) {
return null;
} else if (j - i == 1) {
closestPoints = new OurPoint[] { sortedByX[i], sortedByX[j] };
return closestPoints;
} else if (j - i == 2) {
try {
OurPoint[] threePoints = new OurPoint[] { sortedByX[i],
sortedByX[i + 1], sortedByX[j] };
return getClosestFromThree(threePoints);
} catch (Exception e) {
e.printStackTrace();
}
}
// Teilungsindex bestimmen
int mid = (i + j) / 2;
// Aufruf Rekursion für die linke Hälfte
OurPoint[] closestPointsLeft = getClosestPointsRecursive(sortedByX, i,
mid);
// Aufruf Rekursion für die rechte Hälfte
OurPoint[] closestPointsRight = getClosestPointsRecursive(sortedByX,
mid + 1, j);
double distanceLeft;
double distanceRight;
// Nachbereitende Analyse nach der Rekursion
if (closestPointsLeft != null) {
distanceLeft = closestPointsLeft[0]
.getDistance(closestPointsLeft[1]);
} else {
distanceLeft = Double.MAX_VALUE;
}
if (closestPointsRight != null) {
distanceRight = closestPointsRight[0]
.getDistance(closestPointsRight[1]);
} else {
distanceRight = Double.MAX_VALUE;
}
double distance = (distanceLeft < distanceRight) ? distanceLeft
: distanceRight;
closestPoints = (distanceLeft < distanceRight) ? closestPointsLeft
: closestPointsRight;
// Die Entfernungen checken, die die Grenze überschreiten:
// Linke Grenze des Rechten Bereichs:
double right = sortedByX[mid].getX() + distance;
// Rechte Grenze des Linken Bereichs:
double left = sortedByX[mid + 1].getX() - distance;
// Alle Punkte des Linken Bereichs suchen, die in Frage kommen:
OurPoint[] pointsLeft = getCriticalPointsIndexMinus(sortedByX,
Math.max(left, sortedByX[i].getX()), sortedByX[mid + 1].getX(),
mid, i);
// Alle Punkte des Rechten Bereichs suchen, die in Frage kommen:
OurPoint[] pointsRight = getCriticalPointsIndexPlus(sortedByX,
sortedByX[mid].getX(), Math.min(right, sortedByX[j].getX()),
mid, j);
// Kürzeren Abstand zwischen 2 Punkten aus dem linken und rechten
// Teilbereich suchen
OurPoint[] evenCloser = lookForCloser(pointsLeft, pointsRight, distance);
if (evenCloser != null) {
closestPoints = evenCloser;
}
return closestPoints;
}
/*
* Hier wird aus zwei benachbarten Punktemengen nach einem Punktepaar
* gesucht, dessen Distanz kleiner als distance ist. Falls keines gefunden
* wird: return null
*/
private OurPoint[] lookForCloser(OurPoint[] pointsLeft,
OurPoint[] pointsRight, double distance) {
OurPoint p1 = null;
OurPoint p2 = null;
double newDistance = Double.MAX_VALUE;
for (OurPoint point1 : pointsLeft) {
for (OurPoint point2 : pointsRight) {
/*
* durch die if Abfragen wird überprüft, ob die Distanz
* überhaupt komplett errechnet werden muss, oder es schon
* offensichtlich ist, dass dieses Punktepaar die Distanz nicht
* unterbietet
*/
if ((Math.abs(point1.getX() - point2.getX()) < distance)
|| (Math.abs(point1.getY() - point2.getY()) < distance)) {
if (point1.getDistance(point2) < distance
&& point1.getDistance(point2) < newDistance) {
p1 = point1;
p2 = point2;
newDistance = point1.getDistance(point2);
}
}
}
}
if (p1 != null && p2 != null) {
OurPoint[] gotCloser = { p1, p2 };
return gotCloser;
} else {
return null;
}
}
/*
* Hier werden Punkte auf der rechten Seite der Grenze gesucht, die so nah
* an der Grenze sind, dass sie vielleicht die momentane Minimaldistanz
* unterbieten können in Verbindung mit einem Punkt der linken Seite.
*/
private OurPoint[] getCriticalPointsIndexPlus(OurPoint[] sortedByX,
double left, double right, int mid, int maxIndex) {
ArrayList<OurPoint> points = new ArrayList<OurPoint>();
getCriticalPointsRecursiveIndexPlus(sortedByX, left, right, mid + 1,
points, maxIndex);
Object[] array = points.toArray();
OurPoint[] result = new OurPoint[array.length];
for (int i = 0; i < array.length; i++) {
result[i] = (OurPoint) array[i];
}
return result;
}
/*
* Hier werden Punkte auf der linken Seite der Grenze gesucht, die so nah an
* der Grenze sind, dass sie vielleicht die momentane Minimaldistanz
* unterbieten können in Verbindung mit einem Punkt der rechten Seite.
*/
private OurPoint[] getCriticalPointsIndexMinus(OurPoint[] sortedByX,
double left, double right, int mid, int minIndex) {
ArrayList<OurPoint> points = new ArrayList<OurPoint>();
if (sortedByX[mid].getX() >= left && sortedByX[mid].getX() <= right) {
if (!points.contains(sortedByX[mid])) {
points.add(sortedByX[mid]);
}
}
getCriticalPointsRecursiveIndexMinus(sortedByX, left, right, mid - 1,
points, minIndex);
Object[] array = points.toArray();
OurPoint[] result = new OurPoint[array.length];
for (int i = 0; i < array.length; i++) {
result[i] = (OurPoint) array[i];
}
return result;
}
/*
* Hier werden Punkte auf der rechten Seite der Grenze gesucht, die so nah
* an der Grenze sind, dass sie vielleicht die momentane Minimaldistanz
* unterbieten können in Verbindung mit einem Punkt der linken Seite.
* Rekursionsmethode. Geht immer einen Schritt weiter nach rechts im Array,
* bis man außerhalb der Grenzen ist.
*/
private void getCriticalPointsRecursiveIndexPlus(OurPoint[] sortedByX,
double left, double right, int index, ArrayList<OurPoint> points,
int maxIndex) {
if (sortedByX[index].getX() <= right && index <= maxIndex) {
if (!points.contains(sortedByX[index])) {
points.add(sortedByX[index]);
}
if (index + 1 < sortedByX.length) {
getCriticalPointsRecursiveIndexPlus(sortedByX, left, right,
index + 1, points, maxIndex);
}
}
}
/*
* Hier werden Punkte auf der linken Seite der Grenze gesucht, die so nah an
* der Grenze sind, dass sie vielleicht die momentane Minimaldistanz
* unterbieten können in Verbindung mit einem Punkt der rechten Seite.
* Rekursionsmethode. Geht immer einen Schritt weiter nach links im Array,
* bis man außerhalb der Grenzen ist.
*/
private void getCriticalPointsRecursiveIndexMinus(OurPoint[] sortedByX,
double left, double right, int index, ArrayList<OurPoint> points,
int minIndex) {
if (sortedByX[index].getX() >= left && index >= minIndex) {
if (!points.contains(sortedByX[index])) {
points.add(sortedByX[index]);
}
if (index - 1 >= 0) {
getCriticalPointsRecursiveIndexMinus(sortedByX, left, right,
index - 1, points, minIndex);
}
}
}
/*
* Liefert die beiden Punkte mit kürzester Distanz aus einer Menge von drei
* Punkten.
*/
private OurPoint[] getClosestFromThree(OurPoint[] threePoints)
throws Exception {
if (threePoints.length != 3) {
throw new Exception("Something went wrong here.");
}
double d1 = threePoints[0].getDistance(threePoints[1]);
double d2 = threePoints[1].getDistance(threePoints[2]);
double d3 = threePoints[2].getDistance(threePoints[0]);
OurPoint[] closest = new OurPoint[2];
if (d1 <= d2 && d1 <= d3) {
closest[0] = threePoints[0];
closest[1] = threePoints[1];
} else if (d2 <= d1 && d2 <= d3) {
closest[0] = threePoints[1];
closest[1] = threePoints[2];
} else {
closest[0] = threePoints[2];
closest[1] = threePoints[0];
}
return closest;
}
/*
* Die folgenden Methoden dienen nur zur Sortierung der Punkte. Einmal nach
* X und einmal nach Y Koordinaten.
*/
public OurPoint[] sortByX(OurPoint[] allPoints) {
OurPoint[] toSortByX = allPoints.clone();
quicksortByX(toSortByX, 0, toSortByX.length - 1);
return toSortByX;
}
private void quicksortByX(OurPoint[] toSortByX, int low, int high) {
int i = low, j = high;
OurPoint pivot = toSortByX[low + (high - low) / 2];
while (i <= j) {
while (toSortByX[i].getX() < pivot.getX()) {
i++;
}
while (toSortByX[j].getX() > pivot.getX()) {
j--;
}
if (i <= j) {
exchange(toSortByX, i, j);
i++;
j--;
}
}
if (low < j)
quicksortByX(toSortByX, low, j);
if (i < high)
quicksortByX(toSortByX, i, high);
}
public OurPoint[] sortByY(OurPoint[] allPoints) {
OurPoint[] toSortByY = allPoints.clone();
quicksortByY(toSortByY, 0, toSortByY.length - 1);
return toSortByY;
}
private void quicksortByY(OurPoint[] toSortByY, int low, int high) {
int i = low, j = high;
OurPoint pivot = toSortByY[low + (high - low) / 2];
while (i <= j) {
while (toSortByY[i].getY() < pivot.getY()) {
i++;
}
while (toSortByY[j].getY() > pivot.getY()) {
j--;
}
if (j <= j) {
exchange(toSortByY, i, j);
i++;
j--;
}
}
if (low < j)
quicksortByY(toSortByY, low, j);
if (i < high)
quicksortByY(toSortByY, i, high);
}
private void exchange(OurPoint[] points, int i, int j) {
OurPoint temp = points[i];
points[i] = points[j];
points[j] = temp;
}
/*
* Test der Methoden.
*/
public static void main(String[] args) {
OurPoint p1 = new OurPoint(1, 2);
OurPoint p2 = new OurPoint(5, 6);
OurPoint p3 = new OurPoint(5, 2);
OurPoint p4 = new OurPoint(4, 8);
OurPoint p5 = new OurPoint(1, 20);
OurPoint p6 = new OurPoint(4, 19);
OurPoint p7 = new OurPoint(4, 22);
OurPoint p8 = new OurPoint(3, 16);
OurPoint p9 = new OurPoint(0, 0);
OurPoint p10 = new OurPoint(2, 34);
OurPoint p11 = new OurPoint(2, 33);
OurPoint p12 = new OurPoint(20, 20);
OurPoint[] points = { p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12 };
ClosestPointsFinder cpf = new ClosestPointsFinder();
OurPoint[] result = cpf.getClosestPoints(points);
for (OurPoint p : result) {
System.out.println(p);
}
}
}
|
package ae.teletronics.cache.examples.dbversioncache;
import java.util.HashMap;
import java.util.Map;
import ae.teletronics.cache.ChangingValueAndLevelMultiCache;
import ae.teletronics.cache.Pair;
import com.google.common.base.Function;
import com.google.common.base.Supplier;
import com.google.common.cache.CacheBuilder;
public class StringStringOptimisticLockingDBWithKeyStartsWithCache extends KeyValueOptimisticLockingDBWithPluggableCache<String, String, StringValueContainer> {
public static class CacheValue {
private boolean complete;
private Map<String, StringValueContainer> keySuffixToValueMap;
public CacheValue() {
complete = false;
keySuffixToValueMap = new HashMap<String, StringValueContainer>();
}
public boolean isComplete() {
return complete;
}
public void setComplete() {
complete = true;
}
public Map<String, StringValueContainer> getKeySuffixToValueMap() {
return keySuffixToValueMap;
}
}
public class KeyStartsWithCache implements Cache<String, String, StringValueContainer> {
private static final String SPLIT = "!";
private final ChangingValueAndLevelMultiCache<String, CacheValue> innerCache;
private KeyStartsWithCache(int cachesSize, int[] levelSplitAfter) {
com.google.common.cache.Cache<String, CacheValue> innerInnerCache = CacheBuilder.newBuilder().maximumSize(cachesSize).build();
ChangingValueAndLevelMultiCache.Builder<String, CacheValue> innerCacheBuilder = ChangingValueAndLevelMultiCache.builder();
innerCacheBuilder
.cache(innerInnerCache)
.defaultModifier(new Function<CacheValue, CacheValue>() {
@Override
public CacheValue apply(CacheValue input) {
return input;
}
})
.levelCalculator(new ChangingValueAndLevelMultiCache.BiFunction<String, CacheValue, Integer>() {
@Override
public Integer apply(String key, CacheValue cacheValue) {
return cacheValue.getKeySuffixToValueMap().size();
}
});
int currentLevelIntervalStart = 0;
for (int currentLevelIntervalEnd : levelSplitAfter) {
innerInnerCache = CacheBuilder.newBuilder().maximumSize(cachesSize).build();
innerCacheBuilder.addCache(innerInnerCache, currentLevelIntervalStart, currentLevelIntervalEnd, "Inner Cache " + currentLevelIntervalStart + "-" + currentLevelIntervalEnd + " size");
currentLevelIntervalStart = currentLevelIntervalEnd+1;
}
innerCache = innerCacheBuilder.build();
}
@Override
public void put(final String key, final StoreRequest<String, StringValueContainer> storeRequest) throws AlreadyExistsException, DoesNotAlreadyExistException, VersionConflictException {
put(key, storeRequest, false);
}
protected void put(final String key, final StoreRequest<String, StringValueContainer> storeRequest, final boolean putInStore) throws AlreadyExistsException, DoesNotAlreadyExistException, VersionConflictException {
try {
final Pair<String, String> splittedKey = splitKey(key);
innerCache.modify(splittedKey._1,
new Supplier<CacheValue>() {
@Override
public CacheValue get() {
return new CacheValue();
}
},
new Function<CacheValue, CacheValue>() {
@Override
public CacheValue apply(CacheValue input) {
try {
// Taking advantage of the fact that the cache itself is synchronizing on key - usable if we also just add to store in that synch block
StringValueContainer newValue = versionCheck(key, storeRequest);
if (putInStore) store.put(key, newValue);
input.getKeySuffixToValueMap().put(splittedKey._2, newValue);
return input;
} catch (Exception e) {
throw (e instanceof RuntimeException)?((RuntimeException)e):new RuntimeException(e);
}
}
}, true);
} catch (RuntimeException e) {
Throwable cause = e.getCause();
if (cause instanceof AlreadyExistsException) throw (AlreadyExistsException)cause;
if (cause instanceof DoesNotAlreadyExistException) throw (DoesNotAlreadyExistException)cause;
if (cause instanceof VersionConflictException) throw (VersionConflictException)cause;
throw e;
}
}
@Override
public StringValueContainer get(String key) {
final Pair<String, String> splittedKey = splitKey(key);
CacheValue cacheValue = innerCache.getIfPresent(splittedKey._1);
if (cacheValue != null) return cacheValue.getKeySuffixToValueMap().get(splittedKey._2);
return null;
}
@Override
public Long getVersion(String key) {
StringValueContainer valueContainer = get(key);
return (valueContainer != null)?valueContainer.getVersion():null;
}
private Pair<String, String> splitKey(String key) {
int splitIndex = key.indexOf(SPLIT);
if (splitIndex < 0) return new Pair<String, String>(key, null);
return new Pair<String, String>(key.substring(0, splitIndex), key.substring(splitIndex + SPLIT.length()));
}
}
public StringStringOptimisticLockingDBWithKeyStartsWithCache(int cacheSize, int[] levelSplitAfter) {
super();
initialize(new KeyStartsWithCache(cacheSize, levelSplitAfter));
}
@Override
// Taking advantage of the fact that the cache itself is synchronizing on key - usable if we also just add to store in that synch block
protected Object getSynchObject(String key) {
return null;
}
@Override
protected void putImpl(String key, StoreRequest<String, StringValueContainer> storeRequest) throws AlreadyExistsException, DoesNotAlreadyExistException, VersionConflictException {
// Taking advantage of the fact that the cache itself is synchronizing on key - usable if we also just add to store in that synch block
((KeyStartsWithCache)cache).put(key, storeRequest, true);
}
public Map<String, StringValueContainer> getAllWithKeyStartingWith(final String keyStart) {
CacheValue cacheValue = ((KeyStartsWithCache)cache).innerCache.modify(keyStart,
new Supplier<CacheValue>() {
@Override
public CacheValue get() {
CacheValue newCacheValue = new CacheValue();
newCacheValue.getKeySuffixToValueMap().putAll(getAllFromStore(keyStart, null));
newCacheValue.setComplete();
return newCacheValue;
}
},
new Function<CacheValue, CacheValue>() {
@Override
public CacheValue apply(CacheValue input) {
if (!input.isComplete()) {
input.getKeySuffixToValueMap().putAll(getAllFromStore(keyStart, input.getKeySuffixToValueMap()));
input.setComplete();
}
return input;
}
}, true);
// Simulate that the client does not receive the same object as the database tries to return to it
// because the object is sent over a network
return cloneMapStringStringValueContainer(cacheValue.getKeySuffixToValueMap());
}
private Map<String, StringValueContainer> getAllFromStore(String keyStart, Map<String, StringValueContainer> dontGet) {
Map<String, StringValueContainer> result = new HashMap<String, StringValueContainer>();
for (Map.Entry<String, StringValueContainer> entry : store.entrySet()) {
Pair<String, String> splittedEntryKey = ((KeyStartsWithCache)cache).splitKey(entry.getKey());
if (keyStart.equals(splittedEntryKey._1) && (dontGet == null || !dontGet.containsKey(splittedEntryKey._2))) {
result.put(splittedEntryKey._2, entry.getValue());
}
}
return result;
}
private Map<String, StringValueContainer> cloneMapStringStringValueContainer(Map<String, StringValueContainer> toBeCloned) {
if (toBeCloned == null) return null;
Map<String, StringValueContainer> clone = new HashMap<String, StringValueContainer>(toBeCloned.size());
for (Map.Entry<String, StringValueContainer> entry : toBeCloned.entrySet()) {
clone.put(new String(entry.getKey()), entry.getValue().clone());
}
return clone;
}
}
|
package com.accolite.msaumanagement.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.accolite.msaumanagement.model.UserLogin;
import com.accolite.msaumanagement.service.LoginService;
import java.security.Principal;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
@RestController
@Validated
public class LoginController {
private static final Logger logger = LogManager.getLogger(LoginController.class);
@Autowired
LoginService service;
@GetMapping("/login")
public ResponseEntity<Map<String,String>> login(@RequestParam("username")String username, @RequestParam("password")String password) throws Exception {
logger.info("Accessing the Login mapping");
return ResponseEntity.ok(service.auth(username, password));
}
@PostMapping("/register")
public ResponseEntity<Map<String,String>> register(@RequestBody UserLogin user) throws Exception {
logger.info("Accessing the Register mapping");
return ResponseEntity.ok(service.register(user));
}
}
|
package com.ssm.wechatpro.service.impl;
import io.goeasy.GoEasy;
import io.goeasy.publish.GoEasyError;
import io.goeasy.publish.PublishListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Service;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.github.miemiedev.mybatis.paginator.domain.PageList;
import com.ssm.wechatpro.dao.WechatUserMapper;
import com.ssm.wechatpro.object.InputObject;
import com.ssm.wechatpro.object.OutputObject;
import com.ssm.wechatpro.service.WechatUserService;
import com.ssm.wechatpro.util.DateUtil;
import com.wechat.service.GetUserList;
import com.wechat.service.GetUserMationService;
@Service
public class WechatUserServiceImpl implements WechatUserService {
@Resource
WechatUserMapper wechatUserMapper;
/***
* 查询所有用户信息
* @amparam inputObject
* @par outputObject
* @throws Exception
*/
@Override
public void selectAllWechatUser(InputObject inputObject,OutputObject outputObject) throws Exception {
Map<String, Object> params = inputObject.getParams();
if(params.get("nickname")!=null){
String nickname = Base64.encodeBase64String(params.get("nickname").toString().getBytes("utf-8"));;
params.put("nickname", "%"+nickname+"%");
}
int page = Integer.parseInt(params.get("offset").toString()) / Integer.parseInt(params.get("limit").toString());
page++;
int limit = Integer.parseInt(params.get("limit").toString());
List<Map<String, Object>> beans = wechatUserMapper.selectWechatUser(params, new PageBounds(page, limit));
PageList<Map<String, Object>> abilityInfoPageList = (PageList<Map<String, Object>>) beans;
int total = abilityInfoPageList.getPaginator().getTotalCount();
outputObject.setBeans(beans);
outputObject.settotal(total);
}
/***
* 插入用户信息
* @amparam inputObject
* @par outputObject
* @throws Exception
*/
@Override
public void insertWechatUser(InputObject inputObject, final OutputObject outputObject) throws Exception {
Map<String,Object> map = inputObject.getLogParams();
List<String> beans = GetUserList.getRequest();
List<Map<String, Object>> beansed = wechatUserMapper.selectWechatOpenid();
List<Map<String,Object>> params = new ArrayList<Map<String,Object>>();
int numUpdate = Integer.parseInt(inputObject.getParams().get("numUpdate").toString());
GoEasy goEasy = new GoEasy("BC-c5e986fba5d14d38b2b2c5b4b072fc8c");
goEasy.publish(map.get("adminNo").toString(),"系统开始检测,请等待", new PublishListener(){
@Override
public void onSuccess() {
}
@Override
public void onFailed(GoEasyError error) {
outputObject.setreturnMessage("消息发布失败, 错误编码:" + error.getCode() + " 错误信息: " + error.getContent());
}
});
for(int i=0;i<beansed.size();i++)
{
if(beans.contains(beansed.get(i).get("openid").toString())){
beans.remove(beansed.get(i).get("openid").toString());
}
}
List<Map<String, Object>> users = new ArrayList<>();
int beansSize = beans.size();
while(!beans.isEmpty()){
for(int j = 0;j < 100 && !beans.isEmpty();j++){
Map<String,Object> param = new HashMap<String, Object>();
param.put("openid", beans.get(0));
param.put("lang", "zh_CN");
params.add(param);
beans.remove(0);
}
users.addAll(GetUserMationService.getRequest(params));
goEasy.publish(map.get("adminNo").toString(),"检测成功100条用户信息,剩余"+beans.size()+"条用户信息未检测", new PublishListener(){
@Override
public void onSuccess() {
}
@Override
public void onFailed(GoEasyError error) {
outputObject.setreturnMessage("消息发布失败, 错误编码:" + error.getCode() + " 错误信息: " + error.getContent());
}
});
params.clear();
if(beans.size()<(beansSize-numUpdate)){
break;
}else{
if(!users.isEmpty()){
wechatUserMapper.insertAllWechatUser(users);
users.clear();
}
}
}
if(beansSize<100&&!users.isEmpty()){
wechatUserMapper.insertAllWechatUser(users);
}
goEasy.publish(map.get("adminNo").toString(),"数据库插入完成", new PublishListener(){
@Override
public void onSuccess() {
}
@Override
public void onFailed(GoEasyError error) {
outputObject.setreturnMessage("消息发布失败, 错误编码:" + error.getCode() + " 错误信息: " + error.getContent());
}
});
}
/***
* 取消订阅
* @amparam inputObject
* @par outputObject
* @throws Exception
*/
@Override
public void unsubscribe(String openid) throws Exception {
Map<String,Object> map = new HashMap<String, Object>();
map.put("openid", openid);
map.put("subscribe", 0);
System.out.println(map);
wechatUserMapper.updateWechatSubscribe(map);
}
/***
* 订阅
* @amparam inputObject
* @par outputObject
* @throws Exception
*/
@Override
public void subscribe(String openid) throws Exception {
Map<String,Object> map = new HashMap<String, Object>();
map.put("openid", openid);
Map<String, Object> bean = wechatUserMapper.selectWechatSubscribe(map);
if(bean!=null){
if(bean.get("subscribe").equals("0")){
map.put("subscribe", "1");
wechatUserMapper.updateWechatSubscribe(map);
}
}else{
map = GetUserMationService.getRequest1(openid);
wechatUserMapper.insertWechatUser(map);
}
}
/***
* 修改WechatUser的位置信息
* @amparam inputObject
* @par outputObject
* @throws Exception
*/
@Override
public void updateWechatUserLocation(Map<String, Object> map) throws Exception {
wechatUserMapper.updateWechatUserLoaction(map);
}
/***
* 获取微信用户信息
* @amparam inputObject
* @par outputObject
* @throws Exception
*/
@Override
public void selectLatitudeAndLongtitude(InputObject inputObject,OutputObject outputObject) throws Exception {
Map<String,Object> map = inputObject.getWechatLogParams();//获取openid
outputObject.setBean(map);
}
/***
* 更新用户信息
* @amparam inputObject
* @par outputObject
* @throws Exception
*/
@Override
public void updateWechatUserMassage(Map<String, Object> map)throws Exception {
Map<String,Object> user = GetUserMationService.getRequest1(map.get("openid").toString());
user.remove("wechatIntegral");
map.putAll(user);
Map<String,Object> loginUser = new HashMap<>();
loginUser.put("loginPhone", map.get("wechatNowUser"));
loginUser.put("createTime", DateUtil.getTimeAndToString());
loginUser.put("loginIdentity", 0);
loginUser.put("loginState", 1);
loginUser.put("loginType", 1);
loginUser.put("loginScore", map.get("wechatIntegral"));
loginUser.put("membershipCardId", map.get("membershipCardId"));
wechatUserMapper.insertMWechatLoginUser(loginUser);
map.put("wechatLoginId", loginUser.get("id"));
wechatUserMapper.updateWechatUser(map);
}
/**
* 判断当前用户的地理位置是否与上次登录的位置相同
*/
@Override
public Map<String, Object> selectLation(Map<String, Object> map)
throws Exception {
Map<String, Object> params = wechatUserMapper.selectLation(map);
return params;
}
}
|
/**
*
*/
package com.github.taylorchen1993.mixtureOfGaussian.code;
import java.awt.Rectangle;
import org.jzy3d.chart.Chart;
import org.jzy3d.chart.ChartLauncher;
import org.jzy3d.chart.controllers.keyboard.camera.CameraKeyController;
import org.jzy3d.colors.Color;
import org.jzy3d.colors.ColorMapper;
import org.jzy3d.colors.colormaps.ColorMapRainbow;
import org.jzy3d.global.Settings;
import org.jzy3d.maths.Coord3d;
import org.jzy3d.maths.Range;
import org.jzy3d.plot3d.builder.Builder;
import org.jzy3d.plot3d.builder.Mapper;
import org.jzy3d.plot3d.builder.concrete.OrthonormalGrid;
import org.jzy3d.plot3d.primitives.Scatter;
import org.jzy3d.plot3d.primitives.Shape;
import org.jzy3d.plot3d.rendering.canvas.Quality;
import Jama.Matrix;
/**
* @author TaylorChen
*
*/
public class Plot3D {
/**
* 高斯混合模型函数
*/
private Mapper mapper=new Mapper() {
@Override
public double f(double arg0, double arg1) {
return 0;
}
};
/////////////////////////////////////////////////////////////////////////样本点//////////////
/**
* 所有样本点
*/
private Scatter scatter=new Scatter();
/**
* 样本点的颜色
*/
private float scatterColor= 0.25f;
/**
* 样本点的宽度
*/
private float scatterWidth = 5f;
//////////////////////////////////////////////////////////////////////////图形////////////
/**
* 显示出的图形
*/
private Chart chart= new Chart(Quality.Advanced, "awt");
/**
* 图形的范围
*/
private Range chartRange = new Range(0, 200);
/**
* 显示窗口的大小
*/
private Rectangle DEFAULT_WINDOW = new Rectangle(0,0,600,600);
/**
* 图形的连续性
*/
private int chartSteps=1;
//////////////////////////////////////////////////////////////////////////////////////
public Mapper getMapper() {
return mapper;
}
public float getScatterColor() {
return scatterColor;
}
public void setScatterColor(float scatterColor) {
this.scatterColor = scatterColor;
}
public float getScatterWidth() {
return scatterWidth;
}
public void setScatterWidth(float scatterWidth) {
this.scatterWidth = scatterWidth;
}
public Range getChartRange() {
return chartRange;
}
public void setChartRange(Range chartRange) {
this.chartRange = chartRange;
}
public Rectangle getDEFAULT_WINDOW() {
return DEFAULT_WINDOW;
}
public void setDEFAULT_WINDOW(Rectangle dEFAULT_WINDOW) {
DEFAULT_WINDOW = dEFAULT_WINDOW;
}
public int getChartSteps() {
return chartSteps;
}
public void setChartSteps(int chartSteps) {
this.chartSteps = chartSteps;
}
public void setMapper(Mapper mapper) {
this.mapper = mapper;
}
public Scatter getScatter() {
return scatter;
}
public void setScatter(Scatter scatter) {
this.scatter = scatter;
}
public Chart getChart() {
return chart;
}
public void setChart(Chart chart) {
this.chart = chart;
}
public Plot3D(Mapper mapper, Scatter scatter, Chart chart) {
super();
this.mapper = mapper;
this.scatter = scatter;
this.chart = chart;
}
// ***************************根据mapper构造函数********************************************************
/**
* 根据mapper生成plot3D对象
* @param mapper
*/
public Plot3D(Mapper mapper) {
this.mapper=mapper;
setScatter();
setChart();
}
private void setChart() {
//添加所有样本点
chart.getScene().add(scatter);
//添加函数图像
Shape surface = Builder.buildOrthonormal(new OrthonormalGrid(chartRange, chartSteps, chartRange, chartSteps), mapper);
surface.setColorMapper(new ColorMapper(new ColorMapRainbow(), surface.getBounds().getZmin(), surface.getBounds().getZmax(), new Color(1, 1, 1, .5f)));
surface.setFaceDisplayed(true);
surface.setWireframeDisplayed(false);
chart.getScene().getGraph().add(surface);
chart.addController(new CameraKeyController());
}
private void setScatter() {
float x;
float y;
float z;
Coord3d[] points = new Coord3d[Samples.getCount()];
Color[] colors = new Color[Samples.getCount()];
//遍历所有样本
for (int i = 0; i < Samples.getCount(); i++) {
Matrix iterSample=Samples.getNthSample(i);
x = ((Double)iterSample.get(i, 0)).floatValue();
y = ((Double)iterSample.get(i, 1)).floatValue();
z = ((Double)mapper.f(x, y)).floatValue();
points[i] = new Coord3d(x, y, z);
colors[i] = new Color(x, y, z, scatterColor);
}
scatter = new Scatter(points, colors, scatterWidth);
}
//////////////////////////////////////////////////////////////////////////////////////////
/**
* 显示图像
*/
public void show() {
Settings.getInstance().setHardwareAccelerated(true);
ChartLauncher.instructions();
ChartLauncher.openChart(chart, getDEFAULT_WINDOW(), "");
}
}
|
import java.util.Scanner;
//import java.util.Character;
//import java.util.
public class PasswordChecking{
public static void main(String[] args)
{
int min=8;
int max=12;
int digit=0;
int upCount=0;
int loCount=0;
int special=0;
String password;
Scanner sc=new Scanner(System.in);
System.out.println("Enter your password ");
password=sc.nextLine();
if(password.length()>=min && password.length()<=max)
{
for(int i=0;i<password.length();i++)
{
char c=password.charAt(i);
if(Character.isUpperCase(c))
upCount++;
if(Character.isLowerCase(c))
loCount++;
if(Character.isDigit(c))
digit++;
if(c>=33&&c<=46 || c==64)
special++;
}
if(upCount>0 && loCount>0 && special>0 && digit>0)
System.out.println("Password is good ");
else
System.out.println("Invalid Password ");
}
if(password.length()<min)
{
for(int i=0;i<password.length();i++)
{
char c=password.charAt(i);
if(Character.isLowerCase(c))
loCount++;
if(Character.isUpperCase(c))
upCount++;
}
if(loCount>0 && upCount==0){
System.out.println("Password have to contain atleast " +min+" characters");
System.out.println("There should be atleast one Upper case");
System.out.println("There should be atleast one Digit");
System.out.println("There should be atleast one Special chracter");
}
}
if(password.length()<min && upCount>0)
{
for(int i=0;i<password.length();i++)
{
char c=password.charAt(i);
if(Character.isLowerCase(c))
loCount++;
if(Character.isUpperCase(c))
upCount++;
}
if(loCount>0 && upCount>0)
{
System.out.println("Password have to contain atleast " +min+" characters");
System.out.println("There should be atleast one Digit");
System.out.println("There should be atleast one Special chracter");
}
}
//TODO.......
}
}
|
package ch14.ex14_04;
public class Main {
private static int value = 0;
public synchronized static void add(int val) {
value += val;
System.out.println("Val: " + value + " Thread name: " + Thread.currentThread().getName());
}
public static void main(String[] args) {
Runnable hoge = new Test();
new Thread(hoge).start();
}
}
|
package jie.android.ip.executor;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import jie.android.ip.executor.CommandConsts.ActType;
import jie.android.ip.executor.CommandConsts.CommandType;
import jie.android.ip.executor.CommandConsts.EmptyType;
public class CommandSet {
public static class Command {
private final CommandType type;
private final Object param1;
private final Object param2;
public Command(CommandType type, Object param1, Object param2) {
this.type = type;
this.param1 = param1;
this.param2 = param2;
}
public String getParamAsString(int index) {
if (index == 0) {
if (param1 == null) {
return null;
}
return param1.toString();
} else {
if (param2 == null) {
return null;
}
return param2.toString();
}
}
public int getParamAsInt(int index, int defaultValue) {
if (index == 0) {
if (param1 == null) {
return defaultValue;
}
return ((Integer)param1).intValue();
} else {
if (param2 == null) {
return defaultValue;
}
return ((Integer)param2).intValue();
}
}
public Object getParam(int index) {
return (index == 0) ? param1 : param2;
}
public CommandType getType() {
return type;
}
public boolean isEmpty() {
return type == CommandType.EMPTY;
}
}
// public static class CommandQueue extends LinkedList<Command> {
// }
public static class CommandQueue extends ArrayList<Command> {
}
private HashMap<Integer, CommandQueue> functionSet = new HashMap<Integer, CommandQueue>();
public static CommandQueue makeCommandQueue() {
return new CommandSet.CommandQueue();
}
public static Command makeCommand(CommandType type) {
return new CommandSet.Command(type, null, null);
}
public static Command makeCommand(CommandType type, Object param1) {
return new CommandSet.Command(type, param1, null);
}
public static Command makeCommand(CommandType type, Object param1, Object param2) {
return new CommandSet.Command(type, param1, param2);
}
public void put(int func, CommandQueue cmds) {
functionSet.put(func, cmds);
}
public final CommandQueue get(int func) {
return functionSet.get(func);
}
private final Document transToXmlDocument() {
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.newDocument();
//comment
//CommandSet
Element cmdset = doc.createElement("CommandSet");
for (Entry<Integer, CommandQueue> e : functionSet.entrySet()) {
CommandQueue que = e.getValue();
if (que.size() == 0) {
continue;
}
Element func = doc.createElement("Function");
func.setAttribute("id", e.getKey().toString());
func.setAttribute("size", String.valueOf(que.size()));
//for (int i = que.size() - 1; i >= 0; -- i) {
for (int i = 0; i < que.size(); ++ i) {
Command cmd = que.get(i);
if (!cmd.isEmpty()) {
Element c = doc.createElement("Command");
c.setAttribute("idx", String.valueOf(i));
c.setAttribute("type", cmd.getType().getTitle());
if (cmd.getParam(0) != null) {
c.setAttribute("p1", cmd.getParamAsString(0));
}
if (cmd.getParam(1) != null) {
c.setAttribute("p2", cmd.getParamAsString(1));
}
func.appendChild(c);
}
}
cmdset.appendChild(func);
}
Element root = doc.createElement("IP-Command-Format");
root.appendChild(cmdset);
doc.appendChild(root);
return doc;
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (TransformerFactoryConfigurationError e1) {
e1.printStackTrace();
}
return null;
}
public boolean saveToFile(final String file) {
final Document doc = transToXmlDocument();
if (doc != null) {
try {
Transformer trans = TransformerFactory.newInstance().newTransformer();
trans.transform(new DOMSource(doc), new StreamResult(new File(file)));
return true;
} catch (TransformerConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerFactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return false;
}
public final String saveToString() {
final Document doc = transToXmlDocument();
if (doc != null) {
try {
Transformer trans = TransformerFactory.newInstance().newTransformer();
final StringWriter sw = new StringWriter();
trans.transform(new DOMSource(doc), new StreamResult(sw));
return sw.toString();
} catch (TransformerConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerFactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
public int calcScore() {
int ret = 0;
for (int f = 0; f < functionSet.size(); ++ f) {
final CommandQueue que = functionSet.get(f);
if (que == null || que.size() == 0) {
break;
}
for (int i = 0; i < que.size(); ++ i) {
final Command cmd = que.get(i);
if (cmd == null || (cmd.isEmpty() && cmd.getParam(0) == EmptyType.ACT)) {
break;
}
ret += cmd.getType().getScore();
}
}
return (ret != 0 ? ret : -1);
}
public static final CommandSet loadFromFile(final String file) {
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(new File(file));
if (doc != null) {
return loadFromXmlDocument(doc);
}
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static final CommandSet loadFromString(final String xml) {
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
ByteArrayInputStream is = new ByteArrayInputStream(xml.getBytes());
Document doc = builder.parse(is);
if (doc != null) {
return loadFromXmlDocument(doc);
}
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private static final CommandSet loadFromXmlDocument(final Document doc) {
NodeList func = doc.getElementsByTagName("Function");
if (func == null || func.getLength() == 0) {
return null;
}
final CommandSet cmdset = new CommandSet();
for (int i = 0; i < func.getLength(); ++ i) {
addFunction(cmdset, func.item(i));
}
return cmdset;
}
private static void addFunction(CommandSet cmdset, Node func) {
int id = Integer.valueOf(func.getAttributes().getNamedItem("id").getNodeValue()).intValue();
int size = Integer.valueOf(func.getAttributes().getNamedItem("size").getNodeValue()).intValue();
NodeList cmd = ((Element)func).getElementsByTagName("Command");// .getChildNodes();
if (cmd == null || cmd.getLength() == 0) {
return;
}
CommandSet.CommandQueue cmdq = CommandSet.makeCommandQueue();
int idx = 0;
for (int i = 0; i < cmd.getLength(); ++ i, ++ idx) {
NamedNodeMap attr = cmd.item(i).getAttributes();
int pos = Integer.valueOf(attr.getNamedItem("idx").getNodeValue()).intValue();
while (idx < pos) {
int p1 = (idx % 2 == 0) ? EmptyType.CHECK.getId() : EmptyType.ACT.getId(); // Integer.valueOf(attr.getNamedItem("p1").getNodeValue()).intValue();
cmdq.add(CommandSet.makeCommand(CommandType.EMPTY, p1));
++ idx;
}
final String type = attr.getNamedItem("type").getNodeValue();
if (type.equals(CommandType.ACT.getTitle())) {
int p1 = Integer.valueOf(attr.getNamedItem("p1").getNodeValue()).intValue();
if (p1 == ActType.MOVE_LEFT.getId() || p1 == ActType.MOVE_RIGHT.getId()) { //move
int p2 = Integer.valueOf(attr.getNamedItem("p2").getNodeValue()).intValue();
cmdq.add(CommandSet.makeCommand(CommandType.ACT, p1, p2));
} else if (p1 == ActType.ACTION.getId()) { // action
cmdq.add(CommandSet.makeCommand(CommandType.ACT, p1));
}
} else if (type.equals(CommandType.CHECK.getTitle())) {
int p1 = Integer.valueOf(attr.getNamedItem("p1").getNodeValue()).intValue();
int p2 = Integer.valueOf(attr.getNamedItem("p2").getNodeValue()).intValue();
cmdq.add(CommandSet.makeCommand(CommandType.CHECK, p1, p2));
} else if (type.equals(CommandType.CALL.getTitle())) {
int p1 = Integer.valueOf(attr.getNamedItem("p1").getNodeValue()).intValue();
cmdq.add(CommandSet.makeCommand(CommandType.CALL, p1));
} else if (type.equals(CommandType.EMPTY.getTitle())) {
int p1 = Integer.valueOf(attr.getNamedItem("p1").getNodeValue()).intValue();
cmdq.add(CommandSet.makeCommand(CommandType.EMPTY, p1));
} else {
//
}
}
while (idx < size) {
int p1 = (idx % 2 == 0) ? EmptyType.CHECK.getId() : EmptyType.ACT.getId(); // Integer.valueOf(attr.getNamedItem("p1").getNodeValue()).intValue();
cmdq.add(CommandSet.makeCommand(CommandType.EMPTY, p1));
++ idx;
}
if (cmdq.size() > 0) {
cmdset.put(id, cmdq);
}
}
}
|
package game.app.services.impl;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.ConversionService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import game.app.dtos.request.ShopDto;
import game.app.dtos.response.GameResponse;
import game.app.dtos.response.ShopResponse;
import game.app.entities.Game;
import game.app.entities.Shop;
import game.app.exceptions.GameKONotFoundException;
import game.app.helper.ShopHelper;
import game.app.repositories.ShopRepository;
import game.app.services.ShopService;
@Service
@Transactional
public class ShopServiceImpl implements ShopService{
@Autowired
private ShopRepository shopRepository;
@Autowired
private ShopHelper shopHelper;
@Autowired
private ConversionService converter;
//PARA GUARDAR LA TIENDA EN LA BBDD
@Override
public ShopResponse addShop(ShopDto shopDto) {
System.out.println("Añadiendo tienda a la bbdd");
Shop shopNew = shopHelper.convertShopRequestToShop(shopDto);
Optional<Shop> updatedShop = shopRepository.findByDireccion(shopDto.getDireccion());
if(updatedShop.isPresent()) {
System.out.println("Ya existe esta tienda en la bbdd");
Shop shop = shopRepository.saveAndFlush(updatedShop.get());
System.out.println(shop.getDireccion());
return new ShopResponse();
}
System.out.println("Añadida la tienda en la bbdd");
shopRepository.save(shopNew);
return new ShopResponse();
}
//PARA BUSCARLA TIENDA POR ID
@Override
public ShopResponse getShop(Long id) {
Optional<Shop> shop = shopRepository.findById(id);
if(shop.isPresent()) {
return converter.convert(shop.get(),ShopResponse.class);
}
else {
throw new GameKONotFoundException();
}
}
//PARA ELIMINAR UNA TIENDA
@Override
public ShopResponse deleteShop(Long id) {
System.out.println("Eliminando tienda de la bbdd");
Optional<Shop> shop = shopRepository.findById(id);
if(shop.isPresent()) {
shopRepository.deleteById(id);
}
else {
//habria que crear una excepcion para tienda
throw new GameKONotFoundException();
}
System.out.println("Tienda eliminada con exito de la bbdd");
return converter.convert(shop.get(),ShopResponse.class);
}
}
|
/**
*
*/
package com.community.controller.account;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.broadleafcommerce.common.web.controller.BroadleafAbstractController;
import org.broadleafcommerce.core.catalog.domain.Product;
import org.broadleafcommerce.core.catalog.service.CatalogService;
import org.broadleafcommerce.core.order.domain.NullOrderImpl;
import org.broadleafcommerce.core.order.domain.Order;
import org.broadleafcommerce.core.order.service.OrderService;
import org.broadleafcommerce.core.order.service.call.OrderItemRequestDTO;
import org.broadleafcommerce.core.order.service.exception.AddToCartException;
import org.broadleafcommerce.core.pricing.service.exception.PricingException;
import org.broadleafcommerce.core.web.order.CartState;
import org.broadleafcommerce.profile.core.domain.Customer;
import org.broadleafcommerce.profile.web.core.CustomerState;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.bridgegap.course.Program;
import com.bridgegap.profile.BridgeGapCustomer;
/**
* @author naveen.k.ganachari
*
*/
@Controller
@RequestMapping("/bridgegap-register")
public class BridgeGapAddToCartController extends BroadleafAbstractController {
@Resource(name = "blCatalogService")
protected CatalogService catalogService;
@Resource(name = "blOrderService")
protected OrderService orderService;
@RequestMapping(method = RequestMethod.GET)
public String registerBG(HttpServletRequest request, HttpServletResponse response, Model model, RedirectAttributes attributes) {
String lView = null;
Customer lCustomer = CustomerState.getCustomer();
if (lCustomer != null) {
BridgeGapCustomer lBgCustomer = (BridgeGapCustomer) lCustomer;
if (!lBgCustomer.isLoggedIn()) {
lView = "/authentication/login";
} else if ("student".equalsIgnoreCase(lBgCustomer.getAccountType())) {
if (lBgCustomer.getPrograms() != null && !lBgCustomer.getPrograms().isEmpty()) {
for (Program lProgram : lBgCustomer.getPrograms()) {
if (lProgram.getName().equalsIgnoreCase("Bridge gap solutions for students")) {
lView = "redirect:/program";
attributes.addAttribute("programId", lProgram.getId());
}
}
} else {
List<Product> lProducts = catalogService.findProductsByName("Bridge Gap Solution For Students");
if (lProducts != null) {
Product lBGProduct = lProducts.get(0);
Order cart = CartState.getCart();
if (cart == null || cart instanceof NullOrderImpl) {
cart = orderService.createNewCartForCustomer(CustomerState.getCustomer(request));
}
try {
if (cart.getItemCount() == 0) {
OrderItemRequestDTO lOrderItem = new OrderItemRequestDTO(lBGProduct.getId(), 1);
cart = orderService.addItem(cart.getId(), lOrderItem, false);
cart = orderService.save(cart, true);
}
lView = "redirect:/cart";
} catch (AddToCartException e) {
e.printStackTrace();
} catch (PricingException e) {
e.printStackTrace();
}
}
}
}
}
return lView;
}
}
|
package com.library.bexam.entity;
import com.library.bexam.form.ClassForm;
import com.library.bexam.form.PeriodForm;
import com.library.bexam.form.SubjectForm;
import java.util.List;
/**
* 用户实体
* @author caoqian
* @date 20181213
*/
public class UserEntity {
private int userId;
//年龄
private int age;
//性别,0:男;1:女
private int gender;
//用户类型,0:超级管理员;1:管理员;2:老师
private int type;
//删除状态,0:未删除,1:已删除
private int status;
//科目
private int subjectId;
//科目名称
private String subjectName;
//用户名
private String userName;
//真实姓名
private String userRealName;
//用户密码
private String userPwd;
//手机号
private String mobile;
//头像地址
private String headPath;
//用户token
private String token;
//学段id
private int periodId;
//学段名称
private String periodName;
//创建时间
private String createTime;
private SubjectForm subjectEntity;
private PeriodForm periodEntity;
private List<ClassForm> classList;
public UserEntity() {
}
public UserEntity(int userId, int age, int gender, int type, int status ,int subjectId , String subjectName,String userName,
String userRealName, String userPwd, String mobile, String headPath, String token, String createTime) {
this.userId = userId;
this.age = age;
this.gender = gender;
this.type = type;
this.status = status;
this.subjectId=subjectId;
this.subjectName=subjectName;
this.userName = userName;
this.userRealName = userRealName;
this.userPwd = userPwd;
this.mobile = mobile;
this.headPath = headPath;
this.token = token;
this.createTime = createTime;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getGender() {
return gender;
}
public void setGender(int gender) {
this.gender = gender;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public int getSubjectId() {
return subjectId;
}
public void setSubjectId(int subjectId) {
this.subjectId = subjectId;
}
public String getSubjectName() {
return subjectName;
}
public void setSubjectName(String subjectName) {
this.subjectName = subjectName;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserRealName() {
return userRealName;
}
public void setUserRealName(String userRealName) {
this.userRealName = userRealName;
}
public String getUserPwd() {
return userPwd;
}
public void setUserPwd(String userPwd) {
this.userPwd = userPwd;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getHeadPath() {
return headPath;
}
public void setHeadPath(String headPath) {
this.headPath = headPath;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public SubjectForm getSubjectEntity() {
return subjectEntity;
}
public void setSubjectEntity(SubjectForm subjectEntity) {
this.subjectEntity = subjectEntity;
}
public int getPeriodId() {
return periodId;
}
public void setPeriodId(int periodId) {
this.periodId = periodId;
}
public String getPeriodName() {
return periodName;
}
public void setPeriodName(String periodName) {
this.periodName = periodName;
}
public PeriodForm getPeriodEntity() {
return periodEntity;
}
public void setPeriodEntity(PeriodForm periodEntity) {
this.periodEntity = periodEntity;
}
public List<ClassForm> getClassList() {
return classList;
}
public void setClassList(List<ClassForm> classList) {
this.classList = classList;
}
}
|
package cucumber.runner;
import io.cucumber.junit.CucumberOptions;
import org.junit.runner.RunWith;
import io.cucumber.junit.Cucumber;
@RunWith(Cucumber.class)
@CucumberOptions(features = "classpath:features/auto.feature",
glue = "cucumber.stepDefinitions.gherkin",
plugin = {"pretty", "html:target/reportsJunit"},
tags = {"@all"},
strict = true,
monochrome = true,
dryRun = false)
public class RunnerTest {
}
|
package com.tencent.mm.plugin.appbrand.jsapi.f.a;
import com.tencent.mm.plugin.appbrand.compat.a.b;
import com.tencent.mm.plugin.appbrand.compat.a.b.i;
import com.tencent.mm.plugin.appbrand.jsapi.f.a.d.1;
import com.tencent.mm.plugin.appbrand.r.b.b.a;
class c$8 implements Runnable {
final /* synthetic */ double dSw;
final /* synthetic */ double dSx;
final /* synthetic */ double dSz;
final /* synthetic */ c fTi;
final /* synthetic */ a fTo;
c$8(c cVar, double d, double d2, a aVar, double d3) {
this.fTi = cVar;
this.dSw = d;
this.dSx = d2;
this.fTo = aVar;
this.dSz = d3;
}
public final void run() {
if (this.fTi.fSW == null) {
return;
}
double d;
if (this.fTi.fSY == null) {
this.fTi.fSY = new d(this.fTi.context);
d dVar = this.fTi.fSY;
b bVar = this.fTi.fSW;
double d2 = this.dSw;
d = this.dSx;
i ady = bVar.ady();
ady.A(0.5f, 0.5f);
ady.h(d2, d);
ady.bF(dVar);
dVar.fTv = bVar.a(ady);
return;
}
d dVar2 = this.fTi.fSY;
double d3 = this.dSw;
d = this.dSx;
a aVar = this.fTo;
double d4 = this.dSz;
if (dVar2.fTR == -1.0d && dVar2.fTS == -1.0d) {
dVar2.fTR = d3;
dVar2.fTP = d3;
dVar2.fTS = d;
dVar2.fTQ = d;
} else {
dVar2.fTR = dVar2.fTP;
dVar2.fTS = dVar2.fTQ;
dVar2.fTQ = d;
dVar2.fTP = d3;
}
if (!(dVar2.fTR == -1.0d || dVar2.fTS == -1.0d)) {
dVar2.fTW = e.a(dVar2.fTS, dVar2.fTR, d, d3, aVar, d4);
}
if (dVar2.fTU == 900.0f || dVar2.fTT == 900.0f) {
float i = (float) e.i(d3, d);
dVar2.fTT = i;
dVar2.fTU = i;
} else {
dVar2.fTU = dVar2.fTT;
dVar2.fTT = (float) e.i(d3, d);
}
if (dVar2.fTv != null) {
dVar2.fTv.b(new 1(dVar2, d3, d));
}
}
}
|
package com.suntiago.network.network.iot;
/**
* Created by zy on 2018/3/14.
*/
public interface IOTClient {
/**
* 发送消息
*/
void send(String msg);
/**
* 发送消息
*/
void sendRrpc(String msg, long msgid);
void setReceiveCallback(IOTCallback iotCallback);
// void connect();
// void disconnect();
/*网络状态自检*/
void checkConnect();
}
|
package com.tencent.mm.plugin.fts.a.d;
import android.content.Context;
import android.view.View;
import com.tencent.mm.plugin.fts.a.d.a.a;
import java.util.List;
public abstract class b implements e {
public Context context;
public com.tencent.mm.plugin.fts.a.d.e.b jsY;
public int jsZ;
public b(Context context, com.tencent.mm.plugin.fts.a.d.e.b bVar, int i) {
this.context = context;
this.jsY = bVar;
this.jsZ = i;
}
public static boolean bk(List<? extends Object> list) {
if (list == null || list.size() <= 0) {
return false;
}
return true;
}
public boolean a(View view, a aVar, boolean z) {
return false;
}
}
|
package com.define.common.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Component
class WebConfigurer implements WebMvcConfigurer {
@Autowired
UploadConfig uploadConfig;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/files/**").addResourceLocations("file:///" + uploadConfig.getUploadPath());
}
}
|
//package Arrays.1d;
import java.util.Scanner;
public class largestno {
public static void main(String[] args){
Scanner scan=new Scanner(System.in);
//int n=scan.nextInt();
String s=scan.nextLine();
String [] stringarr=s.split(" ");
//check eacj sring length and make all of them sa me length by adding xeroes
int maxElementLength=largestelement(stringarr);
}
public static int largestelement(String[]arr){
int max=0;
for (String string : arr) {
if(string.length()>max){
max=string.length();
}
}
return max;
}
public static int greatest (String[] srr){
String ans="";
int count=0;
while (count<=srr.length-1){
for(int items=0;items<=srr.length-1;items++){
}
count++;
}
}
}
|
package com.trust.demo;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.List;
/**
* Created by Trust on 2017/7/26.
*/
public class MainControllViewPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> mList;
public void setmList(List<Fragment> mList) {
this.mList = mList;
}
public MainControllViewPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
return mList.get(position);
}
@Override
public int getCount() {
return mList != null ? mList.size():0;
}
@Override
public CharSequence getPageTitle(int position) {
if(position == 0){
return "ui";
}else{
return "code";
}
}
}
|
package ink.zhaibo.cat.visual.monitor;
import de.codecentric.boot.admin.server.config.EnableAdminServer;
import org.springframework.boot.SpringApplication;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.turbine.EnableTurbine;
/**
* @Author zhaibo
* @Description Hystrix-Dashboard
* @Date 2018/9/13
*/
@EnableAdminServer
@EnableTurbine
@EnableDiscoveryClient
@SpringCloudApplication
public class CatMonitorApplication {
public static void main(String[] args) {
SpringApplication.run(CatMonitorApplication.class, args);
}
}
|
package com.canby.decorator.model.ingredients;
import com.canby.decorator.model.Food;
/**
* Created by acanby on 14/10/2014.
*/
public class Lettuce extends IngredientDecorator {
public Lettuce(Food food) {
super(food);
}
@Override
public String getDescription() {
return super.getDescription() + ", Lettuce";
}
@Override
public Double cost() {
return food.cost(); // ain't no cost on lettuce
}
}
|
package resources;
import javafx.stage.Stage;
import java.util.concurrent.TimeUnit;
public final class Utilities {
// Initial stage given by JavaFX
private static Stage primaryStage;
// Returns milliseconds in Minute:Second format
public static String formatMilliseconds(long milliseconds)
{
long minutes = TimeUnit.MILLISECONDS.toMinutes(milliseconds);
long seconds = TimeUnit.MILLISECONDS.toSeconds(milliseconds - TimeUnit.MINUTES.toMillis(minutes));
return String.format("%02d:%02d", minutes, seconds);
}
public static Stage getPrimaryStage() { return primaryStage; }
public static void setPrimaryStage(Stage stage) { primaryStage = stage; }
}
|
package ru.otus.gwt.client.widget;
/*
* Created by VSkurikhin at autumn 2018.
*/
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.uibinder.client.UiTemplate;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.*;
import ru.otus.gwt.client.Inside;
import ru.otus.gwt.client.service.InsideServiceAsync;
import ru.otus.gwt.shared.Emp;
import javax.inject.Inject;
import static ru.otus.gwt.client.gin.ApplicationInjector.INSTANCE;
public class AddView extends Composite implements IsWidget
{
@UiTemplate("AddView.ui.xml")
public interface AddViewUiBinder extends UiBinder<VerticalPanel, AddView> {
}
@UiField
TextBox firstNameTextField;
@UiField
TextBox secondNameTextField;
@UiField
TextBox surNameTextField;
@UiField
TextBox jobTextField;
@UiField
TextBox cityTextField;
@UiField
TextBox ageTextField;
@UiField
HorizontalPanel firstNamePanel;
@UiField
HorizontalPanel secondNamePanel;
@UiField
HorizontalPanel surNamePanel;
@UiField
HorizontalPanel jobPanel;
@UiField
HorizontalPanel cityPanel;
@UiField
HorizontalPanel agePanel;
private Inside inside;
private InsideServiceAsync service;
@Override
public Widget asWidget()
{
return getWidget();
}
@UiHandler("submit")
void clickHandler(ClickEvent evt)
{
Emp emp = new Emp(
0, firstNameTextField.getValue(), secondNameTextField.getValue(), surNameTextField.getValue(),
jobTextField.getValue(), cityTextField.getValue(), ageTextField.getValue()
);
service.addNewEmp(emp, new AsyncCallback<Void>() {
@Override
public void onFailure(Throwable caught) {
Window.alert(caught.getLocalizedMessage());
}
@Override
public void onSuccess(Void result) {
inside.refresh();
inside.showDataGrid();
}
});
}
private static AddViewUiBinder ourUiBinder = INSTANCE.getAddViewUiBinder();
@Inject
public AddView(InsideServiceAsync service, Inside inside) {
initWidget(ourUiBinder.createAndBindUi(this));
this.service = service;
this.inside = inside;
}
}
/* vim: syntax=java:fileencoding=utf-8:fileformat=unix:tw=78:ts=4:sw=4:sts=4:et
*/
//EOF
|
package com.takshine.wxcrm.domain;
import com.takshine.wxcrm.model.ResourceModel;
/**
* 资料模型
* @author zhihe
*
*/
public class Resource extends ResourceModel {
}
|
package com.example.ktc.Adapter;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.ktc.GiaoDien.ChiTietThongTinChamBai;
import com.example.ktc.Model.TTChamBai;
import com.example.ktc.R;
import java.util.ArrayList;
import java.util.Locale;
public class CustomApdapterTTChamBai extends ArrayAdapter {
Context context;
int resource;
ArrayList<TTChamBai> data;
ArrayList<TTChamBai> data_DS;
public CustomApdapterTTChamBai(Context context, int resource, ArrayList<TTChamBai> data) {
super(context, resource);
this.context = context;
this.resource = resource;
this.data = data;
this.data_DS = new ArrayList<TTChamBai>();
this.data_DS.addAll(data);
}
@Override
public int getCount() {
return data.size();
}
private static class Holder {
ImageView imgHinh;
ImageView imgDetail;
TextView tvSoPhieu;
TextView tvSoBai;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
Holder holder = null;
if (view == null) {
holder = new Holder();
view = LayoutInflater.from(context).inflate(resource, null);
holder.imgHinh = view.findViewById(R.id.imgSach);
holder.imgDetail = view.findViewById(R.id.imgDetail);
holder.tvSoPhieu = view.findViewById(R.id.tvSoPhieu);
holder.tvSoBai = view.findViewById(R.id.tvSoBai);
view.setTag(holder);
} else
holder = (Holder) view.getTag();
final TTChamBai ttChamBai = data.get(position);
if(ttChamBai.getMaMonHoc().equals("AR1")){
holder.imgHinh.setImageResource(R.drawable.android2);
}
if(ttChamBai.getMaMonHoc().equals("AR2")){
holder.imgHinh.setImageResource(R.drawable.android);
}
if(ttChamBai.getMaMonHoc().equals("AR3")){
holder.imgHinh.setImageResource(R.drawable.sach);
}
holder.tvSoPhieu.setText("Số phiếu: " + ttChamBai.getSoPhieu());
// int chiPhi = Integer.parseInt(monHoc.getChiPhi());
// DecimalFormat dcfPercent = new DecimalFormat("###,###,###");
// String strPercent = dcfPercent.format(chiPhi);
holder.tvSoBai.setText("Số bài: " + ttChamBai.getSoBai());
holder.imgDetail.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent((Activity) context, ChiTietThongTinChamBai.class);
Bundle bundle = new Bundle();
bundle.putString("ma", ttChamBai.getMaMonHoc());
intent.putExtras(bundle);
bundle.putString("sophieu", ttChamBai.getSoPhieu());
intent.putExtras(bundle);
((Activity) context).startActivity(intent);
}
});
return view;
}
//filter
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
data.clear();
if (charText.length() == 0) {
data.addAll(data_DS);
} else {
for (TTChamBai model : data_DS) {
if (model.getMaMonHoc().toLowerCase(Locale.getDefault())
.contains(charText) || model.getSoPhieu().toLowerCase(Locale.getDefault())
.contains(charText) || model.getSoBai().toLowerCase(Locale.getDefault())
.contains(charText) ){
data.add(model);
}
}
}
notifyDataSetChanged();
}
}
|
/**
* @Title: OfficeMapper.java
* @package com.rofour.baseball.dao.officemanage.mapper
* @Project: baseball-yeah
* ──────────────────────────────────
* Copyright (c) 2016, 指端科技.
*/
package com.rofour.baseball.dao.officemanage.mapper;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Named;
import com.rofour.baseball.controller.model.office.OfficeQueryInfo;
import com.rofour.baseball.dao.officemanage.bean.*;
/**
* @ClassName: OfficeMapper
* @Description 职务管理mapper
* @author WJ
* @date 2016年10月12日 下午2:12:05
*
*/
@Named("officeMapper")
public interface OfficeMapper {
/**
*
* @Description: 查询全部记录
* @return List<OfficeBean>
*
*/
List<OfficeBean> queryAll(OfficeQueryInfo info);
/**
*
* @Description: 查询全部记录
* @return List<OfficeBean>
*
*/
List<OfficeBean> queryAllPuser(OfficeQueryInfo info);
/**
* 查询CEO,COO总数
*/
int getTotal(OfficeQueryInfo info);
/**
* 查询小派总数
*/
int queryAllPuserTotal(OfficeQueryInfo info);
/**
* @Description 统计属下的小派
* @param userId
* @return Integer 返回类型
**/
Integer queryUserTotal(Long userId);
/**
* @Description 统计属下的小派和COO
* @param userId
* @return Integer 返回类型
**/
Integer queryUserAndCOOTotal(Long userId);
/**
* @Description 统计属下的商户和COO
* @param @param userId
**/
Integer queryStoreAndCOOTotal(Long userId);
/**
* @Description 统计属下的商户
* @param @param userId
**/
Integer queryStoreTotal(Long userId);
/**
* @Description 更新p_user中角色类型
* @param userId
**/
int updateRoleType(Long userId);
/**
* @Description 更新p_user中CEO
* @param userId
**/
int updatePuserCEO(Long userId);
/**
* @Description 更新p_user中COO
* @param userId
**/
int updatePuserCOO(Long userId);
/**
* @Description 更新tb_store_exp中COO
* @param userId
**/
int updateStoreCOO(Long userId);
/**
* @Description 更新tb_store_exp中CEO
* @param userId
**/
int updateStoreCEO(Long userId);
/**
* @Description 更新审核状态
* @param map
**/
int updateAuditState(HashMap<String, Object> map);
/**
* @Description 根据uid查询
* @param userId
**/
OfficeDetailBean queryByUserId(Long userId);
/**
* @Description 根据uid查询属下的小派
* @param OfficeQueryInfo
**/
List<OfficeBean> queryAttached(OfficeQueryInfo info);
/**
* @Description 根据uid查询属下的商户
* @param OfficeQueryInfo
**/
List<OfficeStoreBean> queryAttachedStores(OfficeQueryInfo info);
/**
*
* @Description 删除属下的小派
* @param map
*
*/
int deletePuserBoss(Map<String,Object> map);
/**
* @Description 删除属下的商户
* @param map
**/
int deleteStoreBoss(Map<String, Object> map);
/**
* @Description 增加小派,支持批量
* @param map
**/
int addPuserBoss(Map<String, Object> map);
/**
* @Description 更新小派角色信息
* @param map
**/
int updatePacketRole(HashMap<String, Object> map);
/**
* @Description 获取职务审核记录
**/
List<OfficeAuditInfo> getOfficeAudit(OfficeQueryInfo queryInfo);
/**
* @Description 获取职务审核记录条数
**/
int getOfficeAuditCount(OfficeQueryInfo queryInfo);
/**
* @Description 获取职务审核记录
**/
OfficeAuditBean getOfficeAuditById(Long auditId);
List<OfficeBean> selectSameCollegeCEO(Map<String, String> map);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.