blob_id
stringlengths 40
40
| language
stringclasses 1
value | repo_name
stringlengths 5
132
| path
stringlengths 2
382
| src_encoding
stringclasses 34
values | length_bytes
int64 9
3.8M
| score
float64 1.5
4.94
| int_score
int64 2
5
| detected_licenses
listlengths 0
142
| license_type
stringclasses 2
values | text
stringlengths 9
3.8M
| download_success
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
e3b520a44dcc2f61d8518862242264a144f2e656
|
Java
|
LuisHenriqueCampos/PI_5_Uaps
|
/ProjetiIntegrador5/ProjetiIntegrador5-war/src/java/managedbean/AtribuicaoManagedBean.java
|
UTF-8
| 4,939
| 1.953125
| 2
|
[] |
no_license
|
package managedbean;
import br.com.pi.entidade.Atribuicao;
import br.com.pi.report.ReportAtribuicao;
import br.com.pi.service.IAtribuicaoService;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import javax.servlet.http.HttpServletResponse;
import util.MenssagemUtil;
/**
*
* @author Luis
*/
@Named(value = "atribuicaoManagedBean")
@RequestScoped
public class AtribuicaoManagedBean {
@EJB
private IAtribuicaoService atribuicaoService;
private Atribuicao atribuicao;
private Atribuicao atribuicaoSelecionado;
private ReportAtribuicao reportAtribuicao;
private List<Atribuicao> listaAtribuicao;
private String atPesq;
public AtribuicaoManagedBean(){
atribuicao = new Atribuicao();
reportAtribuicao = new ReportAtribuicao();
atPesq = "";
}
public List<Atribuicao> todos(){
return atribuicaoService.listar();
}
public void novo(){
this.atribuicao = new Atribuicao();
}
public void salvar(){
String erro = atribuicaoService.salvar(atribuicao);
if(erro == null){
MenssagemUtil.addMensagemInfo("Atribuicao salva com sucesso!");
novo();
}else{
MenssagemUtil.addMensagemError(erro);
}
}
public void excluir(){
String erro = atribuicaoService.excluir(atribuicaoSelecionado);
if(erro == null){
MenssagemUtil.addMensagemInfo("Atribuição excluida com sucesso!");
}else{
MenssagemUtil.addMensagemError(erro);
}
}
public void atualizar(){
atribuicao = atribuicaoSelecionado;
}
public void gerarRelatorioFiltrado() throws IOException
{
String caminho = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/");
reportAtribuicao = new ReportAtribuicao();
String erro = reportAtribuicao.gerar(caminho,listarRel());
if (erro == null)
{
ByteArrayOutputStream bytes = reportAtribuicao.getOutput();
HttpServletResponse res = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
res.setContentType("application/pdf");
res.setHeader("Content-disposition", "inline;filename=relatorio.pdf");
res.getOutputStream().write(bytes.toByteArray());
res.getCharacterEncoding();
FacesContext.getCurrentInstance().responseComplete();
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Relatório gerado com sucesso!", null));
}
else
{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, erro, null));
}
}
public List<Atribuicao> listarRel()
{
System.out.println("Entrou");
//pacPesq = pacPesq == null ? "" : pacPesq;
//if(pacPesq.length() == 1)
//{
System.out.println("Entrou no método");
listaAtribuicao = atribuicaoService.listarRel(atPesq);
//listaPaciente = listaPaciente.stream().filter(x -> x.getPessoa().getNome().contains("An")).map(x -> x).collect(Collectors.toList());
//}
/*
else if(pacPesq.length() > 1)
{
return listaPaciente.stream()
.filter(x -> x.getPessoa().getNome().contains(pacPesq))
.map(x -> x).collect(Collectors.toList());
//listaPaciente = listaPaciente.stream().filter(x -> x.getPessoa().getNome().contains(pacPesq)).map(x -> x).collect(Collectors.toList());
}*/
System.out.println("Passou");
for(Atribuicao p : listaAtribuicao)
{
System.out.println("" + p.getIdAtribuicao() + " - " + p.getDescricao());
}
return listaAtribuicao;
}
public Atribuicao getAtribuicao() {
return atribuicao;
}
public void setAtribuicao(Atribuicao atribuicao) {
this.atribuicao = atribuicao;
}
public Atribuicao getAtribuicaoSelecionado() {
return atribuicaoSelecionado;
}
public void setAtribuicaoSelecionado(Atribuicao atribuicaoSelecionado) {
this.atribuicaoSelecionado = atribuicaoSelecionado;
}
public List<Atribuicao> getListaAtribuicao() {
return listaAtribuicao;
}
public void setListaAtribuicao(List<Atribuicao> listaAtribuicao) {
this.listaAtribuicao = listaAtribuicao;
}
public String getAtPesq() {
return atPesq;
}
public void setAtPesq(String pacPesq) {
this.atPesq = pacPesq;
}
}
| true
|
6d6aa174e52f235f48700b56e4cfd464c693171b
|
Java
|
nionate/car_rental_tdd
|
/src/main/java/cl/ubb/agil/dao/ExtraDao.java
|
UTF-8
| 184
| 1.960938
| 2
|
[] |
no_license
|
package cl.ubb.agil.dao;
import java.util.ArrayList;
import cl.ubb.agil.model.Extra;
public interface ExtraDao {
public Extra get(int id);
public ArrayList<Extra> getAll();
}
| true
|
fd94b55b5bb93fda713d2f4d31f4a33c200575d3
|
Java
|
zihun130/yk_20171020
|
/appcodescnUCBrowser_1113/src/main/java/cn/hi321/browser/adapter/GirdViewAdapter.java
|
UTF-8
| 5,255
| 2.140625
| 2
|
[] |
no_license
|
package cn.hi321.browser.adapter;
import android.content.Context;
import android.graphics.Color;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import cn.hi321.browser.config.Constants;
import cn.hi321.browser.controllers.Controller;
import cn.hi321.browser.ui.activities.HomeActivity;
import cn.hi321.browser.utils.UserPreference;
import cn.hi321.browser2.R;
public class GirdViewAdapter extends BaseAdapter {
private int imgRecouse[];
private String title[];
// -------------------
private LayoutInflater inflater;
private Context context;
private int flag = 0;
private int normal ;
public GirdViewAdapter(Context context,int flag) {
this.context = context;
UserPreference.ensureIntializePreference(context);
Controller.getInstance().setPreferences(PreferenceManager.getDefaultSharedPreferences(context));
inflater = LayoutInflater.from(context);
this.flag = flag;
normal = Settings.System.getInt(context.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS, 255);
setData();
}
public void setFlag(int flag){
this.flag = flag;
setData();
}
public int getCount() {
return imgRecouse.length;
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return imgRecouse[position];
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View currentView, ViewGroup arg2) {
currentView = inflater.inflate(R.layout.imagebutton, null);
ImageView imageView = (ImageView) currentView
.findViewById(R.id.imgbtn_img);
TextView textView = (TextView) currentView
.findViewById(R.id.imgbtn_text);
imageView.setBackgroundResource(imgRecouse[position]);
textView.setText(title[position]);
textView.setTextColor(Color.parseColor("#FFFFFF"));
if(HomeActivity.INSTANCE!=null&&HomeActivity.INSTANCE.mCurrentWebView!=null&&HomeActivity.INSTANCE.mCurrentWebView.getUrl()!=null&&HomeActivity.INSTANCE.mCurrentWebView.getUrl().
equals(Constants.URL_ABOUT_START)){//是主�?
if((flag == 0 &&position == 0)||(flag == 0&&position == 2)){
textView.setTextColor(Color.parseColor("#878787"));
}
}
return currentView;
}
private void setData(){
if(flag == 0){ imgRecouse = new int[] { R.drawable.menu_container_add2bookmark_d,
R.drawable.menu_container_bookmark, R.drawable.menu_container_refresh_d,
R.drawable.menu_container_nightmode,
R.drawable.menu_container_download,
R.drawable.rd_menubar_share,
R.drawable.menu_container_fullscreen,
R.drawable.menu_container_exit };
title = new String[] { "加入收藏", "书签/历史", "刷新", "夜间模式", "下载/管理",
"页面分享","全屏模式", "�?��" };// "321账户", R.drawable.menu_container_user_center,
if(HomeActivity.INSTANCE.mCurrentWebView!=null&&HomeActivity.INSTANCE.mCurrentWebView.getUrl()!=null&&HomeActivity.INSTANCE.mCurrentWebView.getUrl().
equals(Constants.URL_ABOUT_START)){//是主�?
imgRecouse[0] = R.drawable.menu_container_add2bookmark_dis;
imgRecouse[2] = R.drawable.menu_container_refresh_dis;
}else{
imgRecouse[0] = R.drawable.menu_container_add2bookmark_d;
imgRecouse[2] = R.drawable.menu_container_refresh_d;
}
boolean isFullScreen = UserPreference.read("fullScreen", false);
//表示全屏
if (isFullScreen) {
imgRecouse[6] = R.drawable.menu_container_exitfullscreen;
title[6] = "�?��全屏";
} else{//表示非全�?
imgRecouse[6] = R.drawable.menu_container_fullscreen;
title[6] = "全屏";
}
if(normal == 255){
//日照模式
imgRecouse[3] = R.drawable.menu_container_daymode;
title[3] = "日照模式";
}else{
//夜间模式
imgRecouse[3] = R.drawable.menu_container_nightmode;
title[3] = "夜间模式";
}
}else{//R.drawable.menu_container_notrace,"无迹浏览",
imgRecouse = new int[] { R.drawable.menu_container_noimagemode_dis,
R.drawable.menu_container_checkupdate, R.drawable.menu_container_page_search_n,
R.drawable.menu_container_setting,R.drawable.menu_container_feedback ,R.drawable.menu_container_user_center_logged};
title = new String[]{ "无图模式", "�?��更新", "页面查找", "设置", "反馈有礼" , "关于" };
//"保存网页", R.drawable.menu_container_savepage_d,R.drawable.menu_container_checkupdate,
boolean hasImage =UserPreference.read(Constants.PREFERENCES_BROWSER_ENABLE_IMAGES, true);// Controller.getInstance().getPreferences().getBoolean(Constants.PREFERENCES_BROWSER_ENABLE_IMAGES, true);
if(hasImage){
//有图模式
imgRecouse[0] = R.drawable.menu_container_noimagemode_dis;
title[0] = "无图模式";
}else{
//无图模式
imgRecouse[0] = R.drawable.menu_container_imagemode_d;
title[0] = "有图模式";
}
}
}
}
| true
|
a5ec501b31c404b1b77032e1d9717e5abaaceb47
|
Java
|
yezonggang/DemoHccc
|
/src/main/java/org/example/model/Teacher.java
|
UTF-8
| 1,112
| 2.78125
| 3
|
[] |
no_license
|
package org.example.model;
import java.util.List;
public class Teacher {
public Teacher(int id, String age, String gender, String name, List<Student> studentList) {
this.id = id;
this.age = age;
this.gender = gender;
this.name = name;
this.studentList = studentList;
}
int id;
String age;
String gender;
String name;
List<Student> studentList;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Student> getStudentList() {
return studentList;
}
public void setStudentList(List<Student> studentList) {
this.studentList = studentList;
}
}
| true
|
8b400d580c0375cf7c6889f1f585879b45ec04c5
|
Java
|
ReidCarlberg/teamclock
|
/teamclock/src/java/com/fivesticks/time/queuedmessages/xwork/MessageModifyAction.java
|
UTF-8
| 6,577
| 1.945313
| 2
|
[] |
no_license
|
/*
* Created on Dec 19, 2004 by REID
*/
package com.fivesticks.time.queuedmessages.xwork;
import com.fivesticks.time.common.delete.DeleteContext;
import com.fivesticks.time.common.delete.DeleteContextFactory;
import com.fivesticks.time.common.util.ValidationHelper;
import com.fivesticks.time.common.xwork.GlobalForwardStatics;
import com.fivesticks.time.common.xwork.SessionContextAwareSupport;
import com.fivesticks.time.queuedmessages.QueuedMessage;
import com.fivesticks.time.queuedmessages.QueuedMessageDeleteCommand;
import com.fivesticks.time.queuedmessages.QueuedMessageServiceDelegate;
import com.fivesticks.time.queuedmessages.QueuedMessageServiceDelegateFactory;
import com.fivesticks.time.useradmin.UserTypeEnum;
/**
* @author REID
*/
public class MessageModifyAction extends SessionContextAwareSupport implements
MessageModifyActionContextAware {
// private SessionContext sessionContext;
private MessageModifyActionContext modifyActionContext;
private Long target;
private String submitMessageSave;
private String submitMessageCancel;
private String submitMessageDelete;
private QueuedMessage queuedMessage;
public String execute() throws Exception {
if (this.getSubmitMessageCancel() != null)
return SUCCESS;
if (this.getSubmitMessageDelete() != null
&& this.getModifyActionContext().getTarget() != null) {
DeleteContext dc = DeleteContextFactory.factory
.build(new QueuedMessageDeleteCommand(this
.getModifyActionContext().getTarget()));
this.getSessionContext().setDeleteContext(dc);
return GlobalForwardStatics.GLOBAL_COMMON_DELETE;
}
QueuedMessageServiceDelegate sd = QueuedMessageServiceDelegateFactory.factory
.build(this.getSessionContext());
//adding
if (this.getTarget() == null && this.getSubmitMessageSave() == null) {
this.getModifyActionContext().setTarget(null);
return INPUT;
}
//modifying
if (this.getTarget() != null) {
this.setQueuedMessage(sd.get(this.getTarget()));
this.getModifyActionContext().setTarget(queuedMessage);
return INPUT;
}
validate();
if (this.hasErrors()) {
return INPUT;
}
decorate(); //handles presave stuff.
sd.add(this.getQueuedMessage());
return SUCCESS;
}
public void validate() {
ValidationHelper help = new ValidationHelper();
if (help.isStringEmpty(this.getQueuedMessage().getFromAddress())) {
this.addFieldError("fromAddress", "From address is missing.");
}
if (help.isStringEmpty(this.getQueuedMessage().getFromName())) {
this.addFieldError("fromName", "From name is missing.");
}
if (help.isStringEmpty(this.getQueuedMessage().getToAddress())) {
this.addFieldError("toAddress", "To address is missing.");
}
if (help.isStringEmpty(this.getQueuedMessage().getToName())) {
this.addFieldError("toName", "To name is missing.");
}
if (help.isStringEmpty(this.getQueuedMessage().getSubject())) {
this.addFieldError("subject", "Subject is missing.");
}
if (help.isStringEmpty(this.getQueuedMessage().getMessage())) {
this.addFieldError("message", "Message is missing.");
}
}
public void decorate() throws Exception {
if (this.getModifyActionContext().getTarget() != null) {
this.getQueuedMessage().setId(
this.getModifyActionContext().getTarget().getId());
}
if (this.getSessionContext().getUserTypeEnum() == UserTypeEnum.STANDARD
|| (this.getQueuedMessage().getModifiedByUsername() == null || this
.getQueuedMessage().getModifiedByUsername().trim()
.length() == 0)) {
this.getQueuedMessage().setModifiedByUsername(
this.getSessionContext().getUser().getUsername());
}
}
/**
* @return Returns the modifyActionContext.
*/
public MessageModifyActionContext getModifyActionContext() {
return modifyActionContext;
}
/**
* @param modifyActionContext
* The modifyActionContext to set.
*/
public void setModifyActionContext(
MessageModifyActionContext modifyActionContext) {
this.modifyActionContext = modifyActionContext;
}
/**
* @return Returns the submitMessageCancel.
*/
public String getSubmitMessageCancel() {
return submitMessageCancel;
}
/**
* @param submitMessageCancel
* The submitMessageCancel to set.
*/
public void setSubmitMessageCancel(String submitMessageCancel) {
this.submitMessageCancel = submitMessageCancel;
}
/**
* @return Returns the submitMessageDelete.
*/
public String getSubmitMessageDelete() {
return submitMessageDelete;
}
/**
* @param submitMessageDelete
* The submitMessageDelete to set.
*/
public void setSubmitMessageDelete(String submitMessageDelete) {
this.submitMessageDelete = submitMessageDelete;
}
/**
* @return Returns the submitMessageSave.
*/
public String getSubmitMessageSave() {
return submitMessageSave;
}
/**
* @param submitMessageSave
* The submitMessageSave to set.
*/
public void setSubmitMessageSave(String submitMessageSave) {
this.submitMessageSave = submitMessageSave;
}
/**
* @return Returns the target.
*/
public Long getTarget() {
return target;
}
/**
* @param target
* The target to set.
*/
public void setTarget(Long target) {
this.target = target;
}
/**
* @return Returns the queuedMessage.
*/
public QueuedMessage getQueuedMessage() {
return queuedMessage;
}
/**
* @param queuedMessage
* The queuedMessage to set.
*/
public void setQueuedMessage(QueuedMessage queuedMessage) {
this.queuedMessage = queuedMessage;
}
}
| true
|
c6ff5b113d7de99588bf927e06c1d9baa1c13381
|
Java
|
wangjiafu5d/RatingFund
|
/src/com/ratingfund/app/fragment/FragmentM.java
|
UTF-8
| 6,882
| 1.890625
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.ratingfund.app.fragment;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.ratingfund.app.R;
import com.ratingfund.app.activity.MainActivity;
import com.ratingfund.app.adapter.ListAdapterB;
import com.ratingfund.app.adapter.ListAdapterM;
import com.ratingfund.app.model.FundA;
import com.ratingfund.app.model.FundM;
import com.ratingfund.app.util.BpriceDiscountComparator;
import com.ratingfund.app.util.CPriceComparator;
import com.ratingfund.app.util.CodeComparator;
import com.ratingfund.app.util.CorrectedIntrestComparator;
import com.ratingfund.app.util.DiscountComparator;
import com.ratingfund.app.util.IndexComparator;
import com.ratingfund.app.util.IndexRisingComparator;
import com.ratingfund.app.util.IntrestRuleComparator;
import com.ratingfund.app.util.PriceLeverageComparator;
import com.ratingfund.app.util.RisingComparator;
import com.ratingfund.app.util.SpriceDiscountComparator;
import com.ratingfund.app.util.TradeMoneyComparator;
import com.ratingfund.app.view.CHScrollView;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.RadioGroup.OnCheckedChangeListener;
public class FragmentM extends Fragment implements OnClickListener{
View view;
public ListView listView;
public ListAdapterM adapterM;
MainActivity main;
boolean sortFlag = false;
int buttonId = 1;
private List<RadioButton> fund_m_radioButton_list;
public RadioGroup m_sortRadioGroup;
public RadioButton fund_m_code_button;
public RadioButton fund_m_rising_button ;
public RadioButton fund_m_tradeMoney_button;
public RadioButton fund_m_sprice_discount_button;
public RadioButton fund_m_bprice_discount_button;
public RadioButton fund_m_checkedButton;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view =inflater.inflate(R.layout.fragment_m, container, false);
fund_m_radioButton_list = new ArrayList<RadioButton>();
listView = (ListView) view.findViewById(R.id.scroll_list_m);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
FundM fundM = main.datasM.get(position);
Intent intent = new Intent("com.ratingfund.app.activity.DetailedActivity.ACTION_START");
intent.putExtra("fund_code", fundM.getFund_code());
startActivity(intent);
}
});
main = (MainActivity) getActivity();
main.mListViewM = listView;
adapterM = new ListAdapterM(main,main.datasM);
main.adapterM = adapterM;
listView.setAdapter(adapterM);
m_sortRadioGroup = (RadioGroup) view.findViewById(R.id.sort_radio_group_m);
fund_m_code_button = (RadioButton) view.findViewById(R.id.fund_m_code_button);
fund_m_rising_button = (RadioButton) view.findViewById(R.id.fund_m_rising_button);
fund_m_tradeMoney_button = (RadioButton) view.findViewById(R.id.fund_m_trademoney_button);
fund_m_sprice_discount_button = (RadioButton) view.findViewById(R.id.fund_m_sprice_discount_button);
fund_m_bprice_discount_button = (RadioButton) view.findViewById(R.id.fund_m_bprice_discount_button);
fund_m_bprice_discount_button.setChecked(false);
fund_m_radioButton_list.add(fund_m_code_button);
fund_m_radioButton_list.add(fund_m_rising_button);
fund_m_radioButton_list.add(fund_m_tradeMoney_button);
fund_m_radioButton_list.add(fund_m_sprice_discount_button);
fund_m_radioButton_list.add(fund_m_bprice_discount_button);
for (RadioButton radioButton : fund_m_radioButton_list) {
radioButton.setOnClickListener(this);
}
m_sortRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
fund_m_checkedButton = (RadioButton) view.findViewById(checkedId);
if (fund_m_checkedButton != null && fund_m_checkedButton.isChecked()) {
for (RadioButton button : fund_m_radioButton_list) {
if (button != null && button != fund_m_checkedButton) {
button.setHovered(false);
button.setChecked(false);
}
}
}
}
});
return view;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.fund_m_code_button:
// sortRadioGroup.clearCheck();
sortFundACode();
sortFlag = !sortFlag;
break;
case R.id.fund_m_rising_button:
sorFundARising();
sortFlag = !sortFlag;
break;
case R.id.fund_m_trademoney_button:
sortFundATradeMoney();
sortFlag = !sortFlag;
break;
case R.id.fund_m_sprice_discount_button:
sortSpriceDiscount();
sortFlag = !sortFlag;
break;
case R.id.fund_m_bprice_discount_button:
sortBpriceDiscount();
sortFlag = !sortFlag;
break;
}
main.m_buttonId = buttonId;
adapterM.notifyDataSetChanged();
}
public void sortFundACode(){
if(buttonId!=1){
sortFlag = true;
}
Collections.sort(main.datasM, new CodeComparator());
setSortArrow(fund_m_code_button);
buttonId = 1;
}
public void sorFundARising(){
if(buttonId!=2){
sortFlag = true;
}
Collections.sort(main.datasM, new RisingComparator());
setSortArrow(fund_m_rising_button);
buttonId = 2;
}
public void sortFundATradeMoney(){
if(buttonId!=3){
sortFlag = true;
}
Collections.sort(main.datasM, new TradeMoneyComparator());
setSortArrow(fund_m_tradeMoney_button);
buttonId = 3;
}
public void sortSpriceDiscount(){
if(buttonId!=4){
sortFlag = true;
}
Collections.sort(main.datasM, new SpriceDiscountComparator());
setSortArrow(fund_m_sprice_discount_button);
buttonId = 4;
}
public void sortBpriceDiscount(){
if(buttonId!=5){
sortFlag = true;
}
Collections.sort(main.datasM, new BpriceDiscountComparator());
setSortArrow(fund_m_bprice_discount_button);
buttonId = 5;
}
public void setSortArrow(RadioButton radioButton){
if(sortFlag){
Collections.reverse(main.datasM);
radioButton.setHovered(false);
}else {
radioButton.setHovered(true);
}
}
public void setSortArrow2(RadioButton radioButton){
if(!sortFlag){
radioButton.setHovered(false);
}else {
radioButton.setHovered(true);
}
}
}
| true
|
4cdcb0a5c3e0fa301314e8999843a155f6f67b9d
|
Java
|
whywuzeng/jingmgouproject
|
/lib/java/com/alimama/mobile/csdk/umupdate/models/c.java
|
UTF-8
| 4,952
| 1.773438
| 2
|
[] |
no_license
|
package com.alimama.mobile.csdk.umupdate.models;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.text.TextUtils;
import com.alimama.mobile.a;
import com.alimama.mobile.csdk.umupdate.a.g;
import org.json.JSONObject;
public class c
{
public static final int a = 0;
public static final int b = 1;
private static final String j = "EXCHANGE_PRELOAD_ADS";
protected String c;
protected String d = "";
protected String e = "";
private final String f = "PROMOTERS_FIRST_PAGE_";
private final String g = "PROMOTERS_NEXT_PAGE_";
private String h = "";
private String i = "";
public JSONObject a(boolean paramBoolean1, long paramLong, boolean paramBoolean2)
{
int k = 0;
try
{
SharedPreferences localSharedPreferences = a.a().c().getSharedPreferences(this.c, 0);
String str1;
if (paramBoolean1)
{
g.b("Request data from first-cache..", new Object[0]);
long l = localSharedPreferences.getLong(this.i, 0L);
if ((System.currentTimeMillis() - Long.valueOf(l).longValue()) / 1000L > 86400L * paramLong - 3600L)
k = 1;
if (k != 0)
{
a();
g.e("Cache data is inactivation...", new Object[0]);
return null;
}
str1 = this.h;
}
while (true)
{
String str2 = localSharedPreferences.getString(str1, null);
if (str2 != null)
{
if (paramBoolean2);
try
{
SharedPreferences.Editor localEditor = localSharedPreferences.edit();
localEditor.remove(str1);
localEditor.commit();
g.c("destroy the used cache data.", new Object[0]);
return new JSONObject(str2);
g.b("Request data from second-cache..", new Object[0]);
str1 = this.d;
}
finally
{
}
}
}
}
catch (Exception localException)
{
localException.printStackTrace();
}
return null;
}
public void a()
{
g.c("remove cache....[" + this.c + "]", new Object[0]);
synchronized (a.a().c().getSharedPreferences(this.c, 0))
{
SharedPreferences.Editor localEditor = ???.edit();
localEditor.remove(this.h);
localEditor.remove(this.d);
localEditor.remove(this.i);
localEditor.commit();
return;
}
}
public void a(int paramInt)
{
SharedPreferences.Editor localEditor = a.a().c().getSharedPreferences(this.c, 0).edit();
localEditor.putInt(this.e, paramInt);
localEditor.commit();
g.b("Save the " + this.e + " " + paramInt, new Object[0]);
}
protected void a(MMEntity paramMMEntity)
{
this.c = ("EXCHANGE_PRELOAD_ADS_" + paramMMEntity.keywords + "_" + paramMMEntity.autofill);
if ((TextUtils.isEmpty(this.e)) || (TextUtils.isEmpty(this.h)) || (TextUtils.isEmpty(this.d)) || (TextUtils.isEmpty(this.i)))
{
if (!TextUtils.isEmpty(paramMMEntity.slotId))
break label203;
paramMMEntity = paramMMEntity.appkey;
if (TextUtils.isEmpty(paramMMEntity))
g.d("No found Slot_id or Appkey!!!!!", new Object[0]);
}
else
{
return;
}
this.e = ("PRELOAD_KEY_" + paramMMEntity);
this.h = ("PROMOTERS_FIRST_PAGE_" + paramMMEntity);
this.d = ("PROMOTERS_NEXT_PAGE_" + paramMMEntity);
this.i = ("PRELOAD_UPDATE_DATE_" + paramMMEntity);
return;
label203: paramMMEntity = paramMMEntity.slotId;
this.e = ("PRELOAD_KEY_" + paramMMEntity);
this.h = ("PROMOTERS_FIRST_PAGE_" + paramMMEntity);
this.d = ("PROMOTERS_NEXT_PAGE_" + paramMMEntity);
this.i = ("PRELOAD_UPDATE_DATE_" + paramMMEntity);
}
public boolean a(boolean paramBoolean, JSONObject paramJSONObject)
{
SharedPreferences localSharedPreferences = a.a().c().getSharedPreferences(this.c, 0);
if (paramJSONObject != null)
{
g.c("save json to cache....", new Object[0]);
try
{
SharedPreferences.Editor localEditor = localSharedPreferences.edit();
localEditor.putLong(this.i, System.currentTimeMillis());
if (paramBoolean)
localEditor.putString(this.h, paramJSONObject.toString());
while (true)
{
localEditor.commit();
return true;
localEditor.putString(this.d, paramJSONObject.toString());
}
}
finally
{
}
}
return false;
}
public int b()
{
return a.a().c().getSharedPreferences(this.c, 0).getInt(this.e, 0);
}
public String c()
{
return this.c;
}
public String d()
{
return this.e;
}
public String e()
{
return this.d;
}
}
/* Location: F:\一周备份\面试apk\希望代码没混淆\jingmgou\jingmgou2\classes-dex2jar.jar
* Qualified Name: com.alimama.mobile.csdk.umupdate.models.c
* JD-Core Version: 0.6.2
*/
| true
|
64ef918c7c36c0a8b4b778d0fbf3afa5f47becdb
|
Java
|
Baefulwrath/RPG_Society
|
/Workspace/RpgSociety/src/ui/Menu.java
|
UTF-8
| 402
| 2.671875
| 3
|
[] |
no_license
|
package ui;
public abstract class Menu extends UIComponent{
public Menu(String title, String id, int tx, int ty, int x, int y, int w, int h){
super(title, id, x, y, w, h);
UICT = UICType.MENU;
TITLEX = tx;
TITLEY = ty;
}
protected int TITLEX = 0;
protected int TITLEY = 0;
public int getTitleX(){
return TITLEX + BOX.x;
}
public int getTitleY(){
return TITLEY + BOX.y;
}
}
| true
|
a257defdb992173205a124f3f945adb18dfb427d
|
Java
|
munaldhakal/token-tokengenerator
|
/src/main/java/com/enfiny/tokens/tokengenerator/controller/ClientController.java
|
UTF-8
| 814
| 2.015625
| 2
|
[] |
no_license
|
package com.enfiny.tokens.tokengenerator.controller;
import com.enfiny.tokens.tokengenerator.request.ClientCreationDto;
import com.enfiny.tokens.tokengenerator.service.ClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("clients")
public class ClientController {
@Autowired
private ClientService clientService;
@RequestMapping(value = "/createClient", method = RequestMethod.POST)
public ResponseEntity<Object> createClient(@RequestBody ClientCreationDto dto) {
clientService.createClient(dto);
return new ResponseEntity<>("Successfully Created", HttpStatus.CREATED);
}
}
| true
|
7b2492b95bccff86e90a872b8e2f59e2fc55ece1
|
Java
|
hibernate/query-validator
|
/src/test/source/test/GoodQueries.java
|
UTF-8
| 8,859
| 2.5625
| 3
|
[
"Apache-2.0"
] |
permissive
|
package test;
import org.hibernate.annotations.processing.CheckHQL;
@CheckHQL(dialect=org.hibernate.dialect.HSQLDialect.class)
public class GoodQueries {
public void goodQueries() {
createQuery("from Person");
// createQuery("from " + "Person" + " order by 1");
createQuery("from test.Person"); //allowed by HQL
createQuery("from Person p where lower(p.name)='gavin'");
createQuery("from Employee p where p.name='gavin' and p.employeeId=111");
createQuery("from Person p join p.address a where a.city='barcelona'");
createQuery("from Person p where p.address.city='barcelona'");
createQuery("from Person p join p.pastAddresses a where a.city='barcelona'");
createQuery("from Person p where p.name in (select p.name from Person p)"); //"in" operator with subquery
createQuery("from Person p where exists (select a from p.pastAddresses a)"); //"exists" operator with correlated subquery
createQuery("select new test.Pair(p,a) from Person p join p.address a"); //"select new"
createQuery("select new test.Pair(p,p.address) from Person p join p.address a"); //"select new"
createQuery("select new test.Pair('',1) from Person p"); //"select new" with literals
createQuery("from Person p where size(p.pastAddresses) = 0"); //JPQL "size()" function
createQuery("from Person p where exists elements(p.pastAddresses)"); //HQL "exists" operator with "elements()" function
createQuery("from Person p where year(p.dob) > 1974"); //HQL "year()" function
createQuery("select cast(p.dob as string) from Person p"); //HQL "cast()" function
createQuery("select e, c, key(c) from Employee e join e.contacts c where key(c) = 'boss'"); //JPQL "key()" operator for Map
createQuery("select e, entry(c) from Employee e join e.contacts c where c.address is null"); //JPQL "entry()" operator for Map
createQuery("select e, value(c) from Employee e join e.contacts c where value(c).address is null"); //JPQL "value()" operator for Map
createQuery("select distinct key(contact) from Employee e join e.contacts contact where length(key(contact))<10 and contact.address is not null and contact.address.city is not null");
createQuery("select substring(note,0,50) from Person p join p.notes note where index(note)<10"); //JPQL "index()" function for List
createQuery("select substring(note,0,50) from Person p join p.notes note where length(note)>3"); //JPQL "length()" function for String
createQuery("from Person p where size(p.notes) > 1"); //JPQL "size()" operator for collections
createQuery("from Person p where '' = minelement(p.notes)"); //HQL "minelement()" function
createQuery("from Person p where '' = maxelement(p.notes)"); //HQL "maxelement()" function
createQuery("from Person p where maxindex(p.notes) > 1"); //HQL "maxindex()" function
createQuery("from Person p where minindex(p.notes) > 1"); //HQL "minindex()" function
createQuery("from Person p where 1 in indices(p.notes)"); //"in" operator with HQL "indices()" function
createQuery("from Person p where '' in elements(p.notes)"); //"in" operator with HQL "elements()" function
createQuery("from Person p where p.notes is empty"); //JPQL "is empty" operator
createQuery("from Person p where p.notes is not empty"); //JPQL "is not empty" operator
createQuery("select e from Employee e join e.contacts c where value(c).address is null");
createQuery("from Person p where type(p) = Employee"); //JPQL "type()" function
createQuery("from Person p where all(select a.city from p.pastAddresses a) = 'barcelona'"); //"all" operator with correlated subquery
createQuery("from Person p where any(select a.city from p.pastAddresses a) = 'barcelona'"); //"any" operator with correlated subquery
createQuery("from Person p where '' = all elements(p.notes)"); //"all" operator with correlated HQL "elements()" function
createQuery("from Person p where 1 < any indices(p.notes)"); //"any" operator with correlated HQL "indices()" function
createQuery("from Employee e where 'boss' = some indices(e.contacts)"); //"some" operator with correlated HQL "indices()" function
createQuery("select p.name, n from Person p join p.notes n where length(n)>0"); //join an element collection
createQuery("from Person p where p.notes[0] is not null"); //HQL list indexing operator
createQuery("from Employee e where e.contacts['boss'] is not null"); //HQL map indexing operator
createQuery("from Employee e where e.contacts['boss'].id = 222"); //HQL map indexing operator
createQuery("from Address add where add.country.code='au'");
createQuery("select p.whatever from Person p where p.whatever is not null");
createQuery("select p.address.country.thing from Person p where p.address.country.thing is null");
createQuery("select p2 from Person p join p.address.country.residents p2"); //join association in embeddable
createQuery("from Person p where p.notes is empty"); //JPQL "is empty" operator for element collection
createQuery("from Person p where p.pastAddresses is empty"); //JPQL "is empty" operator for association
createQuery("from Address a where a.country.residents is empty"); //JPQL "is empty" operator for association in embeddable
createQuery("from Person p where p.address.country.residents is empty"); //JPQL "is empty" operator
createQuery("from Person p where p.address.currentResidents is empty"); //JPQL "is empty" operator
createQuery("select a, c from Address a join a.country c"); //fake join to a component
createQuery("select p, c from Person p join p.address.country c"); //fake join to a component
createQuery("select c.code, c.name from Address a join a.country c"); //fake join to a component
createQuery("select e from Person p join p.emails e");
createQuery("select e.address from Person p join p.emails e");
createQuery("select e from Person p join p.emails e where e.address is not null and length(e.address)>0");
createQuery("from Person p where treat(p.emergencyContact as Employee).employeeId = 2"); //JPQL "treat as" operator
createQuery("from Person p join treat(p.emergencyContact as Employee) c where c.employeeId = 2"); //JPQL "treat as" operator
createQuery("from Employee e join treat(e.contacts as Employee) c where c.employeeId = 2"); //JPQL "treat as" operator
createQuery("from Employee e where e.emergencyContact member of e.contacts"); //JPQL "member of" operator with association
createQuery("from Employee e where e.emergencyContact not member of e.contacts"); //JPQL "not member of" operator with association
createQuery("from Person p where '' member of p.notes"); //JPQL "member of" operator with element collection
createQuery("from Person p where '' not member of p.notes"); //JPQL "not member of" operator with element collection
createQuery("select upper(p.name), year(current_date) from Person p");
createQuery("select upper(p.name), year(current_date) from Person p where year(current_date) = 2019 and upper(p.name) = 'GAVIN'");
createQuery("select nullif(e.name, ''), coalesce(e.employeeId, e.id, e.name) from Employee e"); //JPQL "nullif()" and "coalesce()"
createQuery("select str(p.dob) from Person p"); //HQL "str()" function
createQuery("select cast(p.dob as string) from Person p"); //SQL "cast()" function
createQuery("select extract(month from p.dob), extract(year from p.dob) from Person p"); //SQL "extract()" function
createQuery("select function('bit_length', e.name) from Employee e"); //JPQL "function()" passthrough
// createQuery("from Person p where p.sex = test.Sex.FEMALE"); //TODO: FIX!
// createQuery("from Person p where test.test.Rating.Good = test.test.Rating.Bad"); //TODO: FIX!
createQuery("from Person p where p.name = ?1 and p.id > ?2"); //JPQL positional args
createQuery("from Person p where p.name = :name and p.id >= :minId"); //JPQL named args
// createQuery("from Person p where p.dob = {d '2008-12-31'}");
// createQuery("from Person p where p.dob = date '2008-12-31'");
createQuery("select (local datetime - datetime 1974-03-25 2:30:00) by second");
}
public void okQueries() {
// createQuery("select current_thing from Person"); //warning
createQuery("select func(p.name), year(current_date) from Person p"); //warning
createQuery("from Person p where p.name = function('custom', p.id)"); //warning
}
private static void createQuery(String s) {}
}
| true
|
12d382a5e0c8b67fc1ec58b65a6f09c98b4abba5
|
Java
|
ahandyman/AndroidMusic
|
/app/src/main/java/com/example/jamesmay/androidmusic/PodcastActivity.java
|
UTF-8
| 3,304
| 2.578125
| 3
|
[] |
no_license
|
package com.example.jamesmay.androidmusic;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class PodcastActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_podcast);
// btn 1
Button play1 = (Button) findViewById(R.id.podcast_btn_1);
play1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Now Playing: NPR", Toast.LENGTH_SHORT).show();
}
});
// btn 2
Button play2 = (Button) findViewById(R.id.podcast_btn_2);
play2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Now Playing: Simple Programmer", Toast.LENGTH_SHORT).show();
}
});
// btn 3
Button play3 = (Button) findViewById(R.id.podcast_btn_3);
play3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Now Playing: Android Buffet", Toast.LENGTH_SHORT).show();
}
});
// btn 4
Button play4 = (Button) findViewById(R.id.podcast_btn_4);
play4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Now Playing: This Week in Google", Toast.LENGTH_SHORT).show();
}
});
// btn 5
Button play5 = (Button) findViewById(R.id.podcast_btn_5);
play5.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Now Playing: Codepen Radio", Toast.LENGTH_SHORT).show();
}
});
// btn 6
Button play6 = (Button) findViewById(R.id.podcast_btn_6);
play6.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Now Playing: Small Talk", Toast.LENGTH_SHORT).show();
}
});
// btn 7
Button play7 = (Button) findViewById(R.id.podcast_btn_7);
play7.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Now Playing: Fragmented", Toast.LENGTH_SHORT).show();
}
});
// btn 8
Button play8 = (Button) findViewById(R.id.podcast_btn_8);
play8.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Now Playing: Android Developers Backstage", Toast.LENGTH_SHORT).show();
}
});
}
}
| true
|
c7c20150be84e5c1dd1a1a0e0e3ce1b0c64379d6
|
Java
|
bellmit/zycami-ded
|
/src/main/java/androidx/camera/core/SafeCloseImageReaderProxy.java
|
UTF-8
| 8,183
| 2.09375
| 2
|
[] |
no_license
|
/*
* Decompiled with CFR 0.151.
*
* Could not load the following classes:
* android.view.Surface
*/
package androidx.camera.core;
import android.view.Surface;
import androidx.camera.core.ForwardingImageProxy$OnImageCloseListener;
import androidx.camera.core.ImageProxy;
import androidx.camera.core.SingleCloseImageProxy;
import androidx.camera.core.impl.ImageReaderProxy;
import androidx.camera.core.impl.ImageReaderProxy$OnImageAvailableListener;
import b.a.b.a1;
import b.a.b.b1;
import java.util.concurrent.Executor;
public class SafeCloseImageReaderProxy
implements ImageReaderProxy {
private ForwardingImageProxy$OnImageCloseListener mImageCloseListener;
private final ImageReaderProxy mImageReaderProxy;
private volatile boolean mIsClosed;
private final Object mLock;
private volatile int mOutstandingImages;
private final Surface mSurface;
public SafeCloseImageReaderProxy(ImageReaderProxy imageReaderProxy) {
Object object;
this.mLock = object = new Object();
this.mOutstandingImages = 0;
this.mIsClosed = false;
this.mImageCloseListener = object = new b1(this);
this.mImageReaderProxy = imageReaderProxy;
imageReaderProxy = imageReaderProxy.getSurface();
this.mSurface = imageReaderProxy;
}
/*
* Enabled aggressive block sorting
* Enabled unnecessary exception pruning
* Enabled aggressive exception aggregation
*/
private /* synthetic */ void a(ImageProxy object) {
object = this.mLock;
synchronized (object) {
int n10;
this.mOutstandingImages = n10 = this.mOutstandingImages + -1;
n10 = (int)(this.mIsClosed ? 1 : 0);
if (n10 != 0 && (n10 = this.mOutstandingImages) == 0) {
this.close();
}
return;
}
}
private /* synthetic */ void c(ImageReaderProxy$OnImageAvailableListener imageReaderProxy$OnImageAvailableListener, ImageReaderProxy imageReaderProxy) {
imageReaderProxy$OnImageAvailableListener.onImageAvailable(this);
}
/*
* Enabled aggressive block sorting
* Enabled unnecessary exception pruning
* Enabled aggressive exception aggregation
*/
private ImageProxy wrapImageProxy(ImageProxy object) {
Object object2 = this.mLock;
synchronized (object2) {
if (object != null) {
int n10;
this.mOutstandingImages = n10 = this.mOutstandingImages + 1;
SingleCloseImageProxy singleCloseImageProxy = new SingleCloseImageProxy((ImageProxy)object);
object = this.mImageCloseListener;
singleCloseImageProxy.addOnImageCloseListener((ForwardingImageProxy$OnImageCloseListener)object);
return singleCloseImageProxy;
}
return null;
}
}
/*
* Enabled aggressive block sorting
* Enabled unnecessary exception pruning
* Enabled aggressive exception aggregation
*/
public ImageProxy acquireLatestImage() {
Object object = this.mLock;
synchronized (object) {
Object object2 = this.mImageReaderProxy;
object2 = object2.acquireLatestImage();
return this.wrapImageProxy((ImageProxy)object2);
}
}
/*
* Enabled aggressive block sorting
* Enabled unnecessary exception pruning
* Enabled aggressive exception aggregation
*/
public ImageProxy acquireNextImage() {
Object object = this.mLock;
synchronized (object) {
Object object2 = this.mImageReaderProxy;
object2 = object2.acquireNextImage();
return this.wrapImageProxy((ImageProxy)object2);
}
}
public /* synthetic */ void b(ImageProxy imageProxy) {
this.a(imageProxy);
}
/*
* Enabled aggressive block sorting
* Enabled unnecessary exception pruning
* Enabled aggressive exception aggregation
*/
public void clearOnImageAvailableListener() {
Object object = this.mLock;
synchronized (object) {
ImageReaderProxy imageReaderProxy = this.mImageReaderProxy;
imageReaderProxy.clearOnImageAvailableListener();
return;
}
}
/*
* Enabled aggressive block sorting
* Enabled unnecessary exception pruning
* Enabled aggressive exception aggregation
*/
public void close() {
Object object = this.mLock;
synchronized (object) {
Object object2 = this.mSurface;
if (object2 != null) {
object2.release();
}
object2 = this.mImageReaderProxy;
object2.close();
return;
}
}
public /* synthetic */ void d(ImageReaderProxy$OnImageAvailableListener imageReaderProxy$OnImageAvailableListener, ImageReaderProxy imageReaderProxy) {
this.c(imageReaderProxy$OnImageAvailableListener, imageReaderProxy);
}
/*
* Enabled aggressive block sorting
* Enabled unnecessary exception pruning
* Enabled aggressive exception aggregation
*/
public int getHeight() {
Object object = this.mLock;
synchronized (object) {
ImageReaderProxy imageReaderProxy = this.mImageReaderProxy;
return imageReaderProxy.getHeight();
}
}
/*
* Enabled aggressive block sorting
* Enabled unnecessary exception pruning
* Enabled aggressive exception aggregation
*/
public int getImageFormat() {
Object object = this.mLock;
synchronized (object) {
ImageReaderProxy imageReaderProxy = this.mImageReaderProxy;
return imageReaderProxy.getImageFormat();
}
}
/*
* Enabled aggressive block sorting
* Enabled unnecessary exception pruning
* Enabled aggressive exception aggregation
*/
public int getMaxImages() {
Object object = this.mLock;
synchronized (object) {
ImageReaderProxy imageReaderProxy = this.mImageReaderProxy;
return imageReaderProxy.getMaxImages();
}
}
/*
* Enabled aggressive block sorting
* Enabled unnecessary exception pruning
* Enabled aggressive exception aggregation
*/
public Surface getSurface() {
Object object = this.mLock;
synchronized (object) {
ImageReaderProxy imageReaderProxy = this.mImageReaderProxy;
return imageReaderProxy.getSurface();
}
}
/*
* Enabled aggressive block sorting
* Enabled unnecessary exception pruning
* Enabled aggressive exception aggregation
*/
public int getWidth() {
Object object = this.mLock;
synchronized (object) {
ImageReaderProxy imageReaderProxy = this.mImageReaderProxy;
return imageReaderProxy.getWidth();
}
}
/*
* Enabled aggressive block sorting
* Enabled unnecessary exception pruning
* Enabled aggressive exception aggregation
*/
public void safeClose() {
Object object = this.mLock;
synchronized (object) {
int n10;
this.mIsClosed = n10 = 1;
ImageReaderProxy imageReaderProxy = this.mImageReaderProxy;
imageReaderProxy.clearOnImageAvailableListener();
n10 = this.mOutstandingImages;
if (n10 == 0) {
this.close();
}
return;
}
}
/*
* Enabled aggressive block sorting
* Enabled unnecessary exception pruning
* Enabled aggressive exception aggregation
*/
public void setOnImageAvailableListener(ImageReaderProxy$OnImageAvailableListener imageReaderProxy$OnImageAvailableListener, Executor executor) {
Object object = this.mLock;
synchronized (object) {
ImageReaderProxy imageReaderProxy = this.mImageReaderProxy;
a1 a12 = new a1(this, imageReaderProxy$OnImageAvailableListener);
imageReaderProxy.setOnImageAvailableListener(a12, executor);
return;
}
}
}
| true
|
a43d2821ef0116ad05a23b0c86fa01d8037ff6fb
|
Java
|
jami-i/koppepan
|
/LatticleMultiple/LatticleMultipleTest.java
|
UTF-8
| 597
| 2.765625
| 3
|
[] |
no_license
|
import junit.framework.*;
public class LatticleMultipleTest extends TestCase {
public LatticleMultipleTest(String s) {
super(s);
}
public void test() throws Exception {
LatticleMultiple sundayCount = new LatticleMultiple();
assertTrue(sundayCount.latticlemultiple(1988)); // 4で割り切れるためTrue
// assertTrue(sundayCount.sundaycount(2000)); // 400で割り切れるためTrue
// assertFalse(sundayCount.sundaycount(1959)); // 4で割り切れないためFalse
// assertFalse(sundayCount.isLeapYear(1990)); // 400で割り切れず、100で割り切れるためFalse
}
}
| true
|
a891a64099af6946fb269d3d0403e0a8412020d6
|
Java
|
aruniyer78/sfcustomant
|
/ant-process/src/main/java/task/handler/transformations/RemoveDuplicateElement.java
|
UTF-8
| 3,463
| 2.34375
| 2
|
[] |
no_license
|
package task.handler.transformations;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.apache.commons.lang3.StringUtils;
import org.apache.tools.ant.BuildException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import task.handler.LogWrapper;
/**
* RemoveDuplicateElement
*
* @author xlehmf
*/
@XmlRootElement(name="removeduplicateelement")
public class RemoveDuplicateElement extends Transformation {
private String xpath;
private int distance;
public String getXpath()
{
return xpath;
}
public void setXpath(String xpath)
{
this.xpath = xpath;
}
public int getDistance()
{
return distance;
}
public void setDistance(int distance)
{
this.distance = distance;
}
@Override
public void validate()
{
super.validate();
if (StringUtils.isEmpty(xpath)) {
throw new BuildException("The xpath of the transformation removeduplicateelement must be set.");
}
if (1 > distance) {
throw new BuildException("The distance of the transformation removeduplicateelement must be larger than 0.");
}
}
@Override
public Result applyForDeploy(LogWrapper logWrapper, Document document, Map<String, String> tokenMappings)
{
return apply(logWrapper, document);
}
private Result apply(LogWrapper logWrapper, Document document)
{
Result r = new Result();
XPath xPath = XPathFactory.newInstance().newXPath();
try {
List<Node> nodesToDelete = new ArrayList<>();
Set<String> nodeNames = new HashSet<>();
NodeList nodes = (NodeList)xPath.evaluate(xpath, document.getDocumentElement(), XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); ++i) {
Node n = nodes.item(i);
if (Node.TEXT_NODE != n.getNodeType()) {
throw new BuildException(String.format("The node type selected by xpath %s is not a text node.", xpath));
}
String name = n.getTextContent();
if (nodeNames.contains(name)) {
for (int j=0; j < distance; j++) {
n = n.getParentNode();
}
if (Node.ELEMENT_NODE != n.getNodeType()) {
throw new BuildException(String.format("The node type selected by xpath %s and the distance %d is not an element node.", xpath, distance));
}
nodesToDelete.add(n);
} else {
nodeNames.add(name);
}
}
for (Node n : nodesToDelete) {
logWrapper.log(String.format("Remove duplicate element %s.", n.getNodeName()));
n.getParentNode().removeChild(n);
r.applied();
}
return r;
}
catch (XPathExpressionException e) {
throw new BuildException(String.format("Error reading transformations.xml: %s.", e.getMessage()), e);
}
}
@Override
public Result applyForRetrieve(LogWrapper logWrapper, Document document, Map<String, String> tokenMappings)
{
return apply(logWrapper, document);
}
}
| true
|
d461f0c416e1092660c7d2e8b53921e5505ef9ca
|
Java
|
Rajkumarbhunia/Assignments
|
/ASSIGNMENT_1/MonthOfDays.java
|
UTF-8
| 918
| 3.8125
| 4
|
[] |
no_license
|
//3. Write a program to display number of days in a month? Month Name(String) and year should be taken as input? Leap year should be considered?
import java.util.Scanner;
public class MonthOfDays {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
System.out.println("Write the name of the month: ");
String month=sc.next();
System.out.println("Year: ");
int year=sc.nextInt();
sc.close();
if(!month.equals("february"))
{
if(month.equals("april") || month.equals("june") || month.equals("september") || month.equals("november"))
{
System.out.println("30 days");
}
else
System.out.println("31 days");
}
else if(month.equals("february") && year%400==0 || year%4==0)
{
System.out.println("29 days");
}
else if(month.equals("february"))
{
System.out.println("28 days");
}
else
{
}
}
}
| true
|
644a63e1f72dc563c479cf818ea3181865130750
|
Java
|
occume/t7
|
/WorkOrder1.0/src/com/hy/wo/po/.svn/text-base/User.java.svn-base
|
UTF-8
| 2,082
| 2.34375
| 2
|
[] |
no_license
|
package com.hy.wo.po;
/**
* 最后修改:赵卫东 修改内容:添加防沉迷属性(fcm)
* User
*
* @author 卫东
* @version 创建时间:2009-8-25 上午11:44:37
*/
public class User {
private long userid;
private String username;
private String password;
private String idCard;
private String tel;
private String qq;
private String email;
/**
* 空实例构造方法
*/
public User() {}
/**
* 实例构造方法
* @param userid
* @param username
* @param nickname
* @param gendar
* @param sID
*/
public User(long userid, String username, String nickname, String gendar, String sID) {
this.userid = userid;
this.username = username;
// this.nickname = nickname;
}
/**
* 实例构造方法
* @param userid
* @param username
* @param nickname
* @param gendar
* @param isToken
* @param sID
*/
public User(long userid, String username, String gendar, String sID,
String idCard, String pwdTension, String isTrialUser, String isVIPUser) {
this.userid = userid;
this.username = username;
}
public String getEmail() {
return email;
}
public String getIdCard() {
return idCard;
}
public void setIdCard(String idCard) {
this.idCard = idCard;
}
public void setEmail(String email) {
this.email = email;
}
public long getUserid() {
return userid;
}
public void setUserid(long userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getQq() {
return qq;
}
public void setQq(String qq) {
this.qq = qq;
}
/**
* 为防沉迷状态赋值
*/
}
| true
|
fd4b0b5006c15ffa7299c8f44624a02c79c31e49
|
Java
|
David-Noble-at-work/cosmosdb-benchmark-runner
|
/async-client/src/main/java/com/adobe/platform/core/identity/services/cosmosdb/client/DocumentDbPartitionMetadata.java
|
UTF-8
| 4,073
| 2.25
| 2
|
[] |
no_license
|
package com.adobe.platform.core.identity.services.cosmosdb.client;
import java.util.*;
import java.util.stream.Collectors;
import com.microsoft.azure.cosmosdb.*;
import com.microsoft.azure.cosmosdb.internal.routing.CollectionRoutingMap;
import com.microsoft.azure.cosmosdb.internal.routing.IServerIdentity;
import com.microsoft.azure.cosmosdb.internal.routing.InMemoryCollectionRoutingMap;
import com.microsoft.azure.cosmosdb.internal.routing.*;
import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Helper class to retrieve partition metadata for a given collection. This is used for grouping IDs by partition in
* batch queries
*/
class DocumentDbPartitionMetadata {
Logger logger = LoggerFactory.getLogger(DocumentDbPartitionMetadata.class.getSimpleName());
private String collectionLink;
private CollectionRoutingMap collectionRoutingMap;
private List<String> partitionKeyRangeIds;
private PartitionKeyDefinition partitionKeyDefinition;
public DocumentDbPartitionMetadata(AsyncDocumentClient client, String collectionLink){
this.collectionLink = collectionLink;
reloadMetadata(client);
}
//init
public void reloadMetadata(AsyncDocumentClient client) {
ResourceResponse<DocumentCollection> response =
client.readCollection(this.collectionLink, new RequestOptions()).toBlocking().single();
this.partitionKeyDefinition = response.getResource().getPartitionKey();
this.collectionRoutingMap = this.getCollectionRoutingMap(client, this.collectionLink);
this.partitionKeyRangeIds = this.getCollectionPartitionKeyRangeIds(this.collectionRoutingMap);
}
/**
* Group IDs by partition-range-id
*
* @param ids - A list of IDs. Each ID identifies a document in the collection
* @return - A Map each Keys is a PartitionRangeId and the value is a Set of IDs that fall into this partition range.
*/
public Map<String, Set<String>> groupIdsByPartitionRangeId(List<String> ids) {
Map<String, Set<String>> partitionIdMap = new HashMap<>();
Iterator<String> iter = ids.iterator();
while (iter.hasNext()) {
String id = iter.next();
PartitionKeyInternal partitionKeyValue = PartitionKeyInternal.fromObjectArray(Collections.singletonList(id).toArray(), true);
String effectivePartitionKey = PartitionKeyInternalHelper.getEffectivePartitionKeyString(partitionKeyValue, partitionKeyDefinition);
String partitionRangeId = collectionRoutingMap.getRangeByEffectivePartitionKey(effectivePartitionKey).getId();
partitionIdMap.putIfAbsent(partitionRangeId, new HashSet<>(ids.size() / partitionKeyRangeIds.size()));
partitionIdMap.get(partitionRangeId).add(id);
}
return partitionIdMap;
}
private CollectionRoutingMap getCollectionRoutingMap(AsyncDocumentClient client,String collectionLink){
FeedResponse<PartitionKeyRange> partitionKeyRanges=
client.readPartitionKeyRanges(collectionLink, new FeedOptions()).toBlocking().single();
List<ImmutablePair<PartitionKeyRange, IServerIdentity>> ranges = partitionKeyRanges
.getResults().stream()
.map(r -> new ImmutablePair<PartitionKeyRange, IServerIdentity>(r, new IServerIdentity() {}))
.collect(Collectors.toList());
try {
return InMemoryCollectionRoutingMap.tryCreateCompleteRoutingMap(ranges, collectionLink);
} catch (Exception ex){
throw new RuntimeException("Cannot create complete routing map for collectionLink " + collectionLink, ex);
}
}
private List<String> getCollectionPartitionKeyRangeIds(CollectionRoutingMap collectionRoutingMap) {
Range<String> fullRange = new Range<>(PartitionKeyInternalHelper.MinimumInclusiveEffectivePartitionKey,
PartitionKeyInternalHelper.MaximumExclusiveEffectivePartitionKey, true, false);
return collectionRoutingMap.getOverlappingRanges(fullRange).stream()
.map(PartitionKeyRange::getId)
.collect(Collectors.toList());
}
}
| true
|
06a7dc628528eb5f63f835c510c15eb37462ed94
|
Java
|
LWJGL/lwjgl3
|
/modules/lwjgl/opengl/src/generated/java/org/lwjgl/opengl/ARBInvalidateSubdata.java
|
UTF-8
| 10,274
| 2.28125
| 2
|
[
"LicenseRef-scancode-khronos",
"LGPL-2.0-or-later",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.opengl;
import java.nio.*;
import org.lwjgl.system.*;
/**
* Native bindings to the <a href="https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_invalidate_subdata.txt">ARB_invalidate_subdata</a> extension.
*
* <p>This extension adds a mechanism for an application to tell the GL that the previous contents of a subregion of an image or a range of a buffer may be
* invalidated.</p>
*
* <p>GL implementations often include several memory spaces, each with distinct performance characteristics, and the implementations transparently move
* allocations between memory spaces. With this extension, an application can tell the GL that the contents of a texture or buffer are no longer needed,
* and the implementation can avoid transferring the data unnecessarily.</p>
*
* <p>Examples of when this may be useful include:</p>
*
* <ol>
* <li>invalidating a multisample texture after resolving it into a non-multisample texture.</li>
* <li>invalidating depth/stencil buffers after using them to generate a color buffer.</li>
* <li>invalidating a subregion of a framebuffer rather than clearing it before rendering to it, when the whole subregion will be overwritten.</li>
* <li>invalidating dynamically generated data (e.g. textures written by FBO rendering or CopyTexSubImage, buffers written by transform feedback, etc.)
* after it is no longer needed but before the end of the frame.</li>
* </ol>
*
* <p>It is expected that the situations in which the GL will take advantage of this knowledge and achieve increased performance as a result of its use will
* be implementation-dependent. The first three examples may show benefit on tiled renderers where some data won't need to be copied into or out of on-chip
* memory. The fourth example may show a benefit in multi-GPU systems where some data won't need to be copied between GPUs.</p>
*
* <p>This extension is a superset of the <a href="https://www.khronos.org/registry/OpenGL/extensions/EXT/EXT_discard_framebuffer.txt">EXT_discard_framebuffer</a> extension with the following additions:</p>
*
* <ul>
* <li>The parameters to InvalidateFramebufferEXT are extended for MRT support and Desktop-GL-only buffer enums.</li>
* <li>New functions to invalidate a region of a texture image or buffer object data store.</li>
* </ul>
*
* <p>Requires {@link GL20 OpenGL 2.0}. Promoted to core in {@link GL43 OpenGL 4.3}.</p>
*/
public class ARBInvalidateSubdata {
static { GL.initialize(); }
protected ARBInvalidateSubdata() {
throw new UnsupportedOperationException();
}
// --- [ glInvalidateTexSubImage ] ---
/**
* Invalidates a region of a texture image.
*
* @param texture the name of a texture object a subregion of which to invalidate
* @param level the level of detail of the texture object within which the region resides
* @param xoffset the X offset of the region to be invalidated
* @param yoffset the Y offset of the region to be invalidated
* @param zoffset the Z offset of the region to be invalidated
* @param width the width of the region to be invalidated
* @param height the height of the region to be invalidated
* @param depth the depth of the region to be invalidated
*/
public static void glInvalidateTexSubImage(@NativeType("GLuint") int texture, @NativeType("GLint") int level, @NativeType("GLint") int xoffset, @NativeType("GLint") int yoffset, @NativeType("GLint") int zoffset, @NativeType("GLsizei") int width, @NativeType("GLsizei") int height, @NativeType("GLsizei") int depth) {
GL43C.glInvalidateTexSubImage(texture, level, xoffset, yoffset, zoffset, width, height, depth);
}
// --- [ glInvalidateTexImage ] ---
/**
* Invalidates the entirety of a texture image.
*
* @param texture the name of a texture object to invalidate
* @param level the level of detail of the texture object to invalidate
*/
public static void glInvalidateTexImage(@NativeType("GLuint") int texture, @NativeType("GLint") int level) {
GL43C.glInvalidateTexImage(texture, level);
}
// --- [ glInvalidateBufferSubData ] ---
/**
* Invalidates a region of a buffer object's data store.
*
* @param buffer the name of a buffer object, a subrange of whose data store to invalidate
* @param offset the offset within the buffer's data store of the start of the range to be invalidated
* @param length the length of the range within the buffer's data store to be invalidated
*/
public static void glInvalidateBufferSubData(@NativeType("GLuint") int buffer, @NativeType("GLintptr") long offset, @NativeType("GLsizeiptr") long length) {
GL43C.glInvalidateBufferSubData(buffer, offset, length);
}
// --- [ glInvalidateBufferData ] ---
/**
* Invalidates the content of a buffer object's data store.
*
* @param buffer the name of a buffer object whose data store to invalidate
*/
public static void glInvalidateBufferData(@NativeType("GLuint") int buffer) {
GL43C.glInvalidateBufferData(buffer);
}
// --- [ glInvalidateFramebuffer ] ---
/**
* Unsafe version of: {@link #glInvalidateFramebuffer InvalidateFramebuffer}
*
* @param numAttachments the number of entries in the {@code attachments} array
*/
public static void nglInvalidateFramebuffer(int target, int numAttachments, long attachments) {
GL43C.nglInvalidateFramebuffer(target, numAttachments, attachments);
}
/**
* Invalidate the content some or all of a framebuffer object's attachments.
*
* @param target the target to which the framebuffer is attached. One of:<br><table><tr><td>{@link GL30#GL_FRAMEBUFFER FRAMEBUFFER}</td><td>{@link GL30#GL_DRAW_FRAMEBUFFER DRAW_FRAMEBUFFER}</td><td>{@link GL30#GL_READ_FRAMEBUFFER READ_FRAMEBUFFER}</td></tr></table>
* @param attachments the address of an array identifying the attachments to be invalidated
*/
public static void glInvalidateFramebuffer(@NativeType("GLenum") int target, @NativeType("GLenum const *") IntBuffer attachments) {
GL43C.glInvalidateFramebuffer(target, attachments);
}
/**
* Invalidate the content some or all of a framebuffer object's attachments.
*
* @param target the target to which the framebuffer is attached. One of:<br><table><tr><td>{@link GL30#GL_FRAMEBUFFER FRAMEBUFFER}</td><td>{@link GL30#GL_DRAW_FRAMEBUFFER DRAW_FRAMEBUFFER}</td><td>{@link GL30#GL_READ_FRAMEBUFFER READ_FRAMEBUFFER}</td></tr></table>
*/
public static void glInvalidateFramebuffer(@NativeType("GLenum") int target, @NativeType("GLenum const *") int attachment) {
GL43C.glInvalidateFramebuffer(target, attachment);
}
// --- [ glInvalidateSubFramebuffer ] ---
/**
* Unsafe version of: {@link #glInvalidateSubFramebuffer InvalidateSubFramebuffer}
*
* @param numAttachments the number of entries in the {@code attachments} array
*/
public static void nglInvalidateSubFramebuffer(int target, int numAttachments, long attachments, int x, int y, int width, int height) {
GL43C.nglInvalidateSubFramebuffer(target, numAttachments, attachments, x, y, width, height);
}
/**
* Invalidates the content of a region of some or all of a framebuffer object's attachments.
*
* @param target the target to which the framebuffer is attached. One of:<br><table><tr><td>{@link GL30#GL_FRAMEBUFFER FRAMEBUFFER}</td><td>{@link GL30#GL_DRAW_FRAMEBUFFER DRAW_FRAMEBUFFER}</td><td>{@link GL30#GL_READ_FRAMEBUFFER READ_FRAMEBUFFER}</td></tr></table>
* @param attachments an array identifying the attachments to be invalidated
* @param x the X offset of the region to be invalidated
* @param y the Y offset of the region to be invalidated
* @param width the width of the region to be invalidated
* @param height the height of the region to be invalidated
*/
public static void glInvalidateSubFramebuffer(@NativeType("GLenum") int target, @NativeType("GLenum const *") IntBuffer attachments, @NativeType("GLint") int x, @NativeType("GLint") int y, @NativeType("GLsizei") int width, @NativeType("GLsizei") int height) {
GL43C.glInvalidateSubFramebuffer(target, attachments, x, y, width, height);
}
/**
* Invalidates the content of a region of some or all of a framebuffer object's attachments.
*
* @param target the target to which the framebuffer is attached. One of:<br><table><tr><td>{@link GL30#GL_FRAMEBUFFER FRAMEBUFFER}</td><td>{@link GL30#GL_DRAW_FRAMEBUFFER DRAW_FRAMEBUFFER}</td><td>{@link GL30#GL_READ_FRAMEBUFFER READ_FRAMEBUFFER}</td></tr></table>
* @param x the X offset of the region to be invalidated
* @param y the Y offset of the region to be invalidated
* @param width the width of the region to be invalidated
* @param height the height of the region to be invalidated
*/
public static void glInvalidateSubFramebuffer(@NativeType("GLenum") int target, @NativeType("GLenum const *") int attachment, @NativeType("GLint") int x, @NativeType("GLint") int y, @NativeType("GLsizei") int width, @NativeType("GLsizei") int height) {
GL43C.glInvalidateSubFramebuffer(target, attachment, x, y, width, height);
}
/** Array version of: {@link #glInvalidateFramebuffer InvalidateFramebuffer} */
public static void glInvalidateFramebuffer(@NativeType("GLenum") int target, @NativeType("GLenum const *") int[] attachments) {
GL43C.glInvalidateFramebuffer(target, attachments);
}
/** Array version of: {@link #glInvalidateSubFramebuffer InvalidateSubFramebuffer} */
public static void glInvalidateSubFramebuffer(@NativeType("GLenum") int target, @NativeType("GLenum const *") int[] attachments, @NativeType("GLint") int x, @NativeType("GLint") int y, @NativeType("GLsizei") int width, @NativeType("GLsizei") int height) {
GL43C.glInvalidateSubFramebuffer(target, attachments, x, y, width, height);
}
}
| true
|
e633aba1c1d6408ca1794dd3a584fe02379ecf01
|
Java
|
chintan0539/Java-projects
|
/core java/Multiplication.java
|
UTF-8
| 418
| 3.34375
| 3
|
[] |
no_license
|
//WAP to print multiplication table of a given no.
import java.io.*;
import java.lang.*;
import java.util.*;
class Multiplication
{
public static void main(String args[])
{
int a,i;
Scanner sc=new Scanner(System.in);
System.out.println("enter a no=");
a=sc.nextInt();
i=1;
while(i<11)
{
System.out.println(a+"*"+i+"="+(a*i));
i=(i+1);
}
}
}
| true
|
3d62e277dfe402ee4c00ed800cf69e8af276957c
|
Java
|
suveng/sys_user
|
/src/main/java/my/suveng/sys_user/dao/mongo/UserRepository.java
|
UTF-8
| 226
| 1.570313
| 2
|
[] |
no_license
|
package my.suveng.sys_user.dao.mongo;
import my.suveng.sys_user.model.domain.User;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface UserRepository extends MongoRepository<User,String> {
}
| true
|
b6515cc4e369edb8ff33dc4f31a8ae0dd4ce68e0
|
Java
|
zs512/NewsManuscript
|
/NewsManuscript/src/com/exceptions/departmentManage/DepartmentCheckBeforeUpdException.java
|
UTF-8
| 294
| 1.898438
| 2
|
[] |
no_license
|
package com.exceptions.departmentManage;
/**
* Created by ruanqx on 2015/5/29.
*/
public class DepartmentCheckBeforeUpdException extends Exception{
public DepartmentCheckBeforeUpdException(){}
public DepartmentCheckBeforeUpdException(String message){
super(message);
}
}
| true
|
61684b5868ff6ccc8cbce0e32d8e5250d9ad8d61
|
Java
|
subpavel/multiprocessor_java_2015
|
/multiprocessor/task1_dining_philosophers/src/ru/sbtmipt/Table.java
|
UTF-8
| 3,102
| 3.140625
| 3
|
[] |
no_license
|
package ru.sbtmipt;
public class Table {
/*Two conditions of the forks*/
private enum ForkState {
DIRTY, CLEAN
}
private final int n;
private volatile ForkState[] forkStates;
/*Owners of the forks*/
private volatile int[] forks;
/*Waiting flags for the philosophers' forks*/
private volatile boolean[][] philWaiting;
/*Numbers of food intakes*/
private long[] philCounters;
public Table(int n) {
this.n = n;
forks = new int[n];
philCounters = new long[n];
forkStates = new ForkState[n];
philWaiting = new boolean[n][2];
for (int i = 0; i < n; i++) {
forkStates[i] = ForkState.DIRTY;
forks[i] = Math.min(i, (i + 1) % n);
}
}
public void pickUpForks(int philId) {
int rightFork = philId;
int leftFork = (philId + 1) % n;
while (true) {
// exit if the philosopher has both forks
if (forks[rightFork] == philId && forks[leftFork] == philId) {
break;
}
// trying to get the right fork
if (forks[rightFork] != philId && forkStates[rightFork] == ForkState.DIRTY) {
forkStates[rightFork] = ForkState.CLEAN;
forks[rightFork] = philId;
} else {
// if failed, let others know
philWaiting[philId][0] = true;
}
// trying to get the left fork
if (forks[leftFork] != philId && forkStates[leftFork] == ForkState.DIRTY) {
forkStates[leftFork] = ForkState.CLEAN;
forks[leftFork] = philId;
} else {
// if failed, let others know
philWaiting[philId][1] = true;
}
}
// no more waiting
philWaiting[philId][0] = false;
philWaiting[philId][1] = false;
philCounters[philId]++;
}
public void putDownForks(int philId) {
int rightFork = philId;
int leftFork = (philId + 1) % n;
int rightId = philId == 0 ? n - 1 : philId - 1;
int leftId = (philId + 1) % n;
// set the forks' states to dirty so that others could use them
forkStates[rightFork] = ForkState.DIRTY;
forkStates[leftFork] = ForkState.DIRTY;
// if another philosopher is waiting for this fork, he gets it
// the fork is cleaned before sending
if (philWaiting[rightId][0]) { // the right neighbor's left fork
forkStates[rightFork] = ForkState.CLEAN;
forks[rightFork] = rightId;
}
if (philWaiting[leftId][1]) { // the left neighbor's right fork
forkStates[leftFork] = ForkState.CLEAN;
forks[leftFork] = leftId;
}
}
public void printCounters() {
System.out.println("------------------");
System.out.println("Counters:");
for (int i = 0; i < philCounters.length; i++) {
long counter = philCounters[i];
System.out.println(i + " : " + counter);
}
}
}
| true
|
8420f879f86f9f6a39e5f633676b07ade761c472
|
Java
|
kkzfl22/microservice-set
|
/oauth2/web-client/oauthcode-webclient/src/main/java/com/liujun/microservice/oauth2/client/webclient/controller/MainPageController.java
|
UTF-8
| 4,316
| 2.21875
| 2
|
[] |
no_license
|
package com.liujun.microservice.oauth2.client.webclient.controller;
import com.liujun.microservice.oauth2.client.webclient.auth.AuthorizationCodeTokenService;
import com.liujun.microservice.oauth2.client.webclient.auth.AuthorizationTokenService;
import com.liujun.microservice.oauth2.client.webclient.auth.OAuthToken;
import com.liujun.microservice.oauth2.client.webclient.repository.AdapterUserInfo;
import com.liujun.microservice.oauth2.client.webclient.repository.AuthUserRepository;
import com.liujun.microservice.oauth2.client.webclient.security.WebClientUserDetails;
import com.liujun.microservice.oauth2.client.webclient.user.AuthWebclientUser;
import com.liujun.microservice.oauth2.client.webclient.user.Entry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;
import java.net.URI;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
/**
* 控制请求类操作
*
* @author liujun
* @version 0.0.1
*/
@Controller
public class MainPageController {
/** 授权码请求 */
@Autowired private AuthorizationCodeTokenService authCodeService;
@Autowired private AuthorizationTokenService tokenService;
@Autowired private AuthUserRepository userRepository;
/**
* 去主页
*
* @return
*/
@GetMapping("/")
public String home() {
return "index";
}
@GetMapping("/mainpage")
public ModelAndView mainPage() {
// 从请求中获取用户信息
WebClientUserDetails userDetails =
(WebClientUserDetails)
SecurityContextHolder.getContext().getAuthentication().getPrincipal();
AuthWebclientUser authUser = userDetails.getAuthWebClientUser();
// 如果当前还没有用户信息,需要发起auth流程获取授权码并得到用户信息
if (null == authUser.getAccessToken()) {
// 1,获取授权码
String authEndpoint = authCodeService.getAuthorizationEndpoint();
return new ModelAndView("redirect:" + authEndpoint);
}
authUser.setEntries(Arrays.asList(new Entry("entry 1"), new Entry("entry 2")));
ModelAndView mainView = new ModelAndView("mainpage");
mainView.addObject("user", authUser);
getUserInfo(mainView, authUser.getAccessToken());
return mainView;
}
private void getUserInfo(ModelAndView mainPage, String token) {
RestTemplate restTemplate = new RestTemplate();
MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
headers.add("Authorization", "Bearer " + token);
String endpoint = "http://localhost:8080/data/getUserInfo";
RequestEntity<Object> request =
new RequestEntity<>(headers, HttpMethod.GET, URI.create(endpoint));
ResponseEntity<AdapterUserInfo> userInfoRsp =
restTemplate.exchange(request, AdapterUserInfo.class);
if (userInfoRsp.getStatusCode().is2xxSuccessful()) {
mainPage.addObject("adapterUser", userInfoRsp.getBody());
} else {
throw new RuntimeException("it was not possible to retrieve user profile");
}
}
@GetMapping("/callback")
public ModelAndView callBack(String code, String state) {
// 从请求中获取用户信息
WebClientUserDetails userDetails =
(WebClientUserDetails)
SecurityContextHolder.getContext().getAuthentication().getPrincipal();
AuthWebclientUser authUser = userDetails.getAuthWebClientUser();
// 通过授权码获取token
OAuthToken token = tokenService.getToken(code);
authUser.setAccessToken(token.getAccessToken());
// 设置有效期
Calendar calInstance = Calendar.getInstance();
calInstance.setTime(new Date(Long.parseLong(token.getExpiresIn())));
authUser.setAccessTokenValidity(calInstance);
// 保存token
userRepository.save(authUser);
return new ModelAndView("redirect:/mainpage");
}
}
| true
|
924af82867d4c69f3d3ce8eab30d3dff79f50af3
|
Java
|
johan-smc/Proyecto-Ambulancias-POO
|
/edu/javeriana/ambulancias/negocio/comparatorCodigoServicio.java
|
UTF-8
| 267
| 2.4375
| 2
|
[] |
no_license
|
package co.edu.javeriana.ambulancias.negocio;
import java.util.Comparator;
public class comparatorCodigoServicio implements Comparator<Servicio> {
public int compare(Servicio servi1,Servicio servi2){
return (int) (servi1.getCodigo()-servi2.getCodigo());
}
}
| true
|
efd5ca2e5776812b0f51250f25ced933cd7c4d42
|
Java
|
linuxcwork/dfsfsf
|
/src/Function/GetNearbyFriendPosition.java
|
UTF-8
| 11,104
| 2.03125
| 2
|
[] |
no_license
|
package Function;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
import com.sun.corba.se.spi.orbutil.fsm.Guard.Result;
import base.PersonalInformation;
public class GetNearbyFriendPosition extends HttpServlet {
private PersonalInformation personalInformation = null;
protected Connection register_cnn = null;
private String register_driverName = null;
//private String register_url = null;
private Connection connect = null;
/**
* Constructor of the object.
*/
public GetNearbyFriendPosition() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.flush();
out.close();
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
@SuppressWarnings("static-access")
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Statement statement = null;
Map<Integer, Object> map = new HashMap<Integer, Object>();
System.out.println(request.getParameter("latitude")+":"+request.getParameter("longitude"));
String latitude = request.getParameter("latitude");
String longitude = request.getParameter("longitude");
String requestcode = request.getParameter("requestcode");
String userid = request.getParameter("userid");
System.out.println(requestcode.length());
if (requestcode == null && latitude == null && longitude == null && userid == null) {
return;
}
try {
statement = connect.createStatement();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (requestcode.equals("getposition")){
try {
ResultSet resultSet = statement.executeQuery("SELECT * FROM userposition WHERE latitude<"+latitude+" && latitude>"+latitude+" && longitude<"+longitude+" && longitude>"+longitude+";");
while (resultSet.next()){
int i = 0;
map.put(i,resultSet.getString(i));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//out.append(map);
} else if (requestcode.equals("syncposition")) {
try {
statement.execute("CREATE TABLE IF NOT EXISTS userposition ("+
personalInformation.iDString+" VARCHAR(24) NOT NULL,"+
personalInformation.LATITUDE+" VARCHAR(34) NOT NULL,"+
personalInformation.lONGITUDEString+" VARCHAR(34) NOT NULL"+
");");
ResultSet resultset = statement.executeQuery("SELECT * FROM userposition WHERE id='"+userid+"';");
if(resultset.next()){
Boolean retBoolean = statement.execute("UPDATE userposition SET latitude='"+latitude+"',longitude='"+
longitude+"' WHERE id='"+userid+"';");
} else {
statement.execute("INSERT INTO userposition (id,latitude,longitude) VALUES ("+
userid+","+
latitude+","+
longitude+");");
}
//System.out.println(retBoolean);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*// 1. 创建配置工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
// 2. 根据配置工厂创建解析请求中文件上传内容的解析器
ServletFileUpload upload = new ServletFileUpload(factory);
// 3. 判断当前请求是不是多段提交
if (!upload.isMultipartContent(request)) {
throw new RuntimeException("不是多段提交!");
}
try {
// 4. 解析request对象,将已经分割过的内容放进了List
List<FileItem> list = upload.parseRequest(request);
if (list != null) {
for (FileItem fileItem : list) {
// 判断当前段是普通字段还是文件,这个方法是判断普通段
if (fileItem.isFormField()) {
// 获得name属性对应的值,这里是username
String fname = fileItem.getFieldName();
// 获得键对应的值
String value = fileItem.getString("utf-8");
System.out.println(fname + "=>"+value );
// 否则就是文件了
} else {
// 获得name属性对应的值,这里是username
String fname = fileItem.getFieldName();
//获取路径名
String value = fileItem.getName();
//取到最后一个反斜杠。
int start = value.lastIndexOf("\\");
//截取上传文件的 字符串名字。+1是去掉反斜杠。
String filename = value.substring(start+1);
request.setAttribute(fname, filename);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("/yyyy/MM/dd/");
String datePath = simpleDateFormat.format(new Date()); // 解析成 /2017/04/15/ 的样子, 注意这是三个文件夹
String wholePath = "D:/upload"+datePath;
第三方提供的方法直接写到文件中。
* item.write(new File(path,filename));
//收到写到接收的文件中。
OutputStream out1 = new FileOutputStream(new File(wholePath,filename));
InputStream in = fileItem.getInputStream();
int length = 0;
byte[] buf = new byte[1024];
System.out.println("获取文件总量的容量:"+ fileItem.getSize());
while((length = in.read(buf))!=-1){
out1.write(buf,0,length);
}
in.close();
out1.close();
// 获得文件上传段中,文件的流
InputStream in = fileItem.getInputStream();
// 使用用户上传的文件名来保存文件的话,文件名可能重复。
// 所以保存文件之前,要保证文件名不会重复。使用UUID生成随机字符串
String fileName = UUID.randomUUID().toString();
System.out.println(fileName);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("/yyyy/MM/dd/");
String datePath = simpleDateFormat.format(new Date()); // 解析成 /2017/04/15/ 的样子, 注意这是三个文件夹
String wholePath = "D:/upload"+datePath;
// 字节输出流,用以保存文件,也不需要后缀名,因为我们只是保存用户的数据,不需要查看他们的数据。待用户想下载的时候,再加上后缀名
File dir = new File(wholePath);
// mkdirs可以建立多级目录。即使所有层级的目录都不存在。这些文件夹都会创建,比如我们事先并没有创建在D盘创建upload和2017等这些文件夹
// mkdir只能用于父级目录已经存在的情况下使用,在已存在的父级目录下再新建一级。只能一级!比如File("D:\\upload\\2017\\04")。且D:\\upload\\2017是已经存在的。父级 目录存且只新建一级。故file.makedir()返回true成功创建。
// 但是File("D:\\upload\\2017\\04\\15")且D:\\upload\\2017存在,但不存在15文件夹。因为父级目录不存在所以创建失败返回false
if (!dir.exists()) {
dir.mkdirs();
}
FileOutputStream fos = new FileOutputStream(wholePath+fileName);
// 将输入流复制到输出流中
IOUtils.copy(in, fos);
fos.close();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}*/
out.append("dddddddddddddddddddddddd");
out.flush();
out.close();
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init(ServletConfig config) throws ServletException {
// Put your code here
personalInformation = new PersonalInformation();
// Put your code here
register_driverName=config.getInitParameter("driverName");
//register_url=config.getInitParameter("url");
try {
Class.forName("com.mysql.jdbc.Driver");
//register_cnn = DriverManager.getConnection(register_url);
} catch(Exception e) {
System.out.println("取得数据库连接错误:"+e.getMessage());
}
try {
connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/user","root","123456");
//连接URL为 jdbc:mysql//服务器地址/数据库名 ,后面的2个参数分别是登陆用户名和密码
System.out.println("Success connect Mysql server!");
}
catch (Exception e) {
System.out.print("get data error!");
e.printStackTrace();
}
}
}
| true
|
309d9241c55cf2ddc37b9e7e4a659d9ec5ad02a5
|
Java
|
shamikarora/LeetCodeSolutions
|
/src/main/java/test/leetcode/solutions/TwoSum.java
|
UTF-8
| 597
| 3.015625
| 3
|
[] |
no_license
|
package test.leetcode.solutions;
import java.util.HashMap;
import java.util.Map;
public class TwoSum {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
if(nums == null || nums.length == 0)
return result;
Map<Integer, Integer> map = new HashMap<>();
for(int i=0; i<nums.length; i++){
if(map.containsKey(nums[i])){
result[0] = map.get(nums[i]);
result[1] = i+1;
break;
}
else
map.put(target-nums[i], i+1);
}
return result;
}
}
| true
|
1f8532771126f4d189d0e61753e63fd3d0548514
|
Java
|
Jiahao-Zhang/LeetCode
|
/math/NO728SelfDividingNumbers.java
|
UTF-8
| 715
| 2.953125
| 3
|
[] |
no_license
|
package pers.jiahao.leetcode.math;
import java.util.ArrayList;
import java.util.List;
public class NO728SelfDividingNumbers {
public List<Integer> selfDividingNumbers(int left, int right) {
List<Integer> list = new ArrayList<>();
for(int i = left;i<=right;i++){
if(i%10==0){
continue;
}
int number = i;
while(number>0){
int divider = number%10;
if(divider==0||i%divider!=0){
break;
}
number = number/10;
}
if(number==0){
list.add(i);
}
}
return list;
}
}
| true
|
f1dc94d03aae6facbb2fbdf0994782a1f5117dc3
|
Java
|
manoramu/com.eqs.test.automation.ecommerce
|
/src/main/java/stepdefinition/ListProductStepDef.java
|
UTF-8
| 6,477
| 2.40625
| 2
|
[] |
no_license
|
package stepdefinition;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.Reporter;
import io.cucumber.java.After;
import io.cucumber.java.Before;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import runner.TestRunner;
public class ListProductStepDef {
protected WebDriver driver = TestRunner.getDriver();
private void addToCart(String xPathOfItemToAdd) {
WebElement element = driver.findElement(By.xpath(xPathOfItemToAdd + "/ancestor::li[contains(@class,'ajax_block_product')]//a[contains(@class,'ajax_add_to_cart_button')]"));
this.clickHiddenElement(element);
}
private void clickHiddenElement(WebElement element) {
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].click();", element);
}
@Given("^User is loaded into the home page (.*)$")
public void user_is_loaded_into_the_home_page(String URL) {
driver.get(URL);
}
@Given("^Navigate to the page (.*)$")
public void navigate_to_the_page(String URL) {
driver.navigate().to(URL);
}
@When("^Add the product with 20% discount$")
public void add_the_product_with_discount() {
this.addToCart("//ul[contains(@class,'product_list') and contains(@class,'active')]//div[contains(@class, 'right-block')]//span[contains(@class,'price-percent-reduction') and contains(text(),'-20%')]");
}
@When("^Click on the logo$")
public void click_on_the_logo() {
driver.findElement(By.cssSelector("img.logo")).click();
}
@Then("^Print the name of the products$")
public void print_the_name_of_the_products() {
List<WebElement> list = driver.findElements(By.cssSelector("ul.product_list.active a.product-name"));
list.stream().forEach(webElement -> {
System.out.println(webElement.getText());
Reporter.log(webElement.getText() + "<br>");
});
}
@Then("^Sort the given products based on Price$")
public void sort_the_given_products_based_on_price() {
List<WebElement> priceListElementBeforeSort = driver.findElements(By.cssSelector("div.right-block span.price.product-price"));
List<Float> priceListOnSort = new ArrayList<Float>();
priceListElementBeforeSort.stream().forEach(webElement -> {
priceListOnSort.add(Float.parseFloat(webElement.getText().replace("$", "")));
});
priceListOnSort.sort(Comparator.naturalOrder());
Select dropdown = new Select(driver.findElement(By.cssSelector("select#selectProductSort.selectProductSort.form-control")));
dropdown.selectByVisibleText("Price: Lowest first");
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//ul[contains(@class,'product_list')]//img[contains(@src,'loader')]")));
List<WebElement> priceListElementAfterSort = driver.findElements(By.cssSelector("div.right-block span.price.product-price"));
List<Float> priceListAfterSort = new ArrayList<Float>();
priceListElementAfterSort.stream().forEach(webElement -> {
priceListAfterSort.add(Float.parseFloat(webElement.getText().replace("$", "")));
});
Assert.assertEquals(priceListAfterSort, priceListOnSort);
}
@Then("^Verifying the product is added to the cart$")
public void verifying_the_product_is_added_to_the_cart() {
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions
.visibilityOfElementLocated(By.cssSelector("div.layer_cart_product h2")));
String message = element.getText();
Assert.assertEquals("Product successfully added to your shopping cart", message);
}
@Then("^Toggle between colors and verify$")
public void toggle_between_colors_and_verify() {
HashMap<String,String> colorUrlMap = new HashMap<String,String>();
colorUrlMap.put("Black", "http://automationpractice.com/img/p/1/5/15-large_default.jpg");
colorUrlMap.put("Orange", "http://automationpractice.com/img/p/1/4/14-large_default.jpg");
colorUrlMap.put("Blue", "http://automationpractice.com/img/p/1/3/13-large_default.jpg");
colorUrlMap.put("Yellow", "http://automationpractice.com/img/p/1/2/12-large_default.jpg");
colorUrlMap.forEach((key, value) -> {
driver.findElement(By.xpath("//ul[@id='color_to_pick_list']//a[contains(@name,'" + key + "')]")).click();
Assert.assertEquals(value,driver.findElement(By.cssSelector("div#image-block img#bigpic")).getAttribute("src"));
System.out.println(key + "-->" + driver.findElement(By.cssSelector("div#image-block img#bigpic")).getAttribute("src"));
});
}
@Then("^Verify loading of homepage$")
public void verify_loading_of_homepage()
{
Assert.assertEquals(driver.getCurrentUrl(), "http://automationpractice.com/index.php");
}
@Then("^Add to the cart the same product 5 times$")
public void add_to_the_cart_the_same_product_5_times() throws InterruptedException
{
if(driver.findElement(By.cssSelector("span.ajax_cart_quantity")).getText() != "0") {
this.go_to_cart();
Thread.sleep(2000);
driver.findElement(By.cssSelector("i.icon-trash")).click();
Thread.sleep(1000);
this.click_on_the_logo();
Thread.sleep(3000);
}
for(Integer i = 0; i < 5; i++) {
this.addToCart("//ul[contains(@class,'product_list') and contains(@class,'active')]//div[contains(@class, 'right-block')]//span[contains(@class,'product-price') and contains(text(),'$50.99')]");
this.verifying_the_product_is_added_to_the_cart();
driver.findElement(By.cssSelector("div.button-container span.continue")).click();
Thread.sleep(1000);
}
}
@When("^Go to cart$")
public void go_to_cart()
{
driver.findElement(By.cssSelector("div.shopping_cart a[title='View my shopping cart']")).click();
}
@Then("^Verify the price match$")
public void verify_the_price_match()
{
Float actualTotalPrice = Float.parseFloat(driver.findElement(By.cssSelector("#total_product")).getText().replace("$", ""));
Float expectedTotalPrice = (float) 254.95;
Assert.assertEquals(actualTotalPrice, expectedTotalPrice);
}
// @After()
// public void closeBrowser() {
// driver.quit();
// }
}
| true
|
9f95f6a83d1bca058a878ab37d270e87244a53a6
|
Java
|
OldStreet1/talent-ecosystem
|
/talent-client9092/src/main/java/com/street/mapper/EnterprideMapper.java
|
UTF-8
| 1,077
| 1.945313
| 2
|
[] |
no_license
|
package com.street.mapper;
import com.street.bean.Enterprise;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* @version 1.0
* @author: OldStreetHong
* @date: 2021/7/27 09:08
* @desc:
*/
@Repository
public interface EnterprideMapper {
//企业注册
int addEnterpride(Enterprise enterprise);
//查询企业是否存在
List<Enterprise> queryEnterpride(String enterprise_acc);
//企业登陆
List<Enterprise> enterprideLogin(Enterprise enterprise);
// 热门企业查询
List<Enterprise> HotEnterprise();
//查询企业坐标
String queryEnterpriseCoordinate(String enterprise_name);
//企业信息
List<Enterprise> queryEnterprideData(String enterprise_acc);
//充钱
int increaseEnterprideBalance(@Param("enterprise_account_balance") String enterprise_account_balance,
@Param("enterprise_acc")String enterprise_acc);
//企业信息
List<Enterprise> queryEnterprideIntro(String enterprise_name);
}
| true
|
0ddcda8809c6a0fbfee4eebb10d4768c3fd20d1c
|
Java
|
Oshi41/RandomContent
|
/src/main/java/dash/dashmode/screen/InfiniteFurnaceScreenHandler.java
|
UTF-8
| 4,585
| 2.1875
| 2
|
[
"MIT"
] |
permissive
|
package dash.dashmode.screen;
import dash.dashmode.item.IUpgrade;
import dash.dashmode.registry.DashScreens;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.Inventory;
import net.minecraft.inventory.SimpleInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.recipe.AbstractCookingRecipe;
import net.minecraft.recipe.RecipeType;
import net.minecraft.recipe.book.RecipeBookCategory;
import net.minecraft.screen.AbstractFurnaceScreenHandler;
import net.minecraft.screen.ArrayPropertyDelegate;
import net.minecraft.screen.PropertyDelegate;
import net.minecraft.screen.ScreenHandlerType;
import net.minecraft.screen.slot.FurnaceOutputSlot;
import net.minecraft.screen.slot.Slot;
public class InfiniteFurnaceScreenHandler extends AbstractFurnaceScreenHandler {
public InfiniteFurnaceScreenHandler(int syncId, PlayerInventory playerInventory) {
this(syncId, playerInventory, new SimpleInventory(6), new ArrayPropertyDelegate(4));
}
public InfiniteFurnaceScreenHandler(int syncId, PlayerInventory playerInventory, Inventory infiniteFurnaceBlockEntity, PropertyDelegate propertyDelegate) {
this(DashScreens.InfiniteFurnace, RecipeType.SMELTING, RecipeBookCategory.FURNACE, syncId, playerInventory, infiniteFurnaceBlockEntity, propertyDelegate);
}
private InfiniteFurnaceScreenHandler(ScreenHandlerType<?> type, RecipeType<? extends AbstractCookingRecipe> recipeType, RecipeBookCategory recipeBookCategory, int syncId, PlayerInventory playerInventory, Inventory inventory, PropertyDelegate propertyDelegate) {
super(type, recipeType, recipeBookCategory, syncId, playerInventory, inventory, propertyDelegate);
slots.clear();
this.addSlot(new Slot(inventory, 0, 56, 17));
this.addSlot(new CustomSlot(inventory, 1, 56, 53).enabled(false).with(x -> false));
this.addSlot(new FurnaceOutputSlot(playerInventory.player, inventory, 2, 116, 35));
for (int i = 0; i < 3; i++) {
this.addSlot(new CustomSlot(inventory, 3 + i, 152, 18 * (i + 1)).with(stack -> stack.getItem() instanceof IUpgrade));
}
int l;
for (l = 0; l < 3; ++l) {
for (int k = 0; k < 9; ++k) {
this.addSlot(new Slot(playerInventory, k + l * 9 + 9, 8 + k * 18, 84 + l * 18));
}
}
for (l = 0; l < 9; ++l) {
this.addSlot(new Slot(playerInventory, l, 8 + l * 18, 142));
}
}
@Environment(EnvType.CLIENT)
@Override
public int getCraftingSlotCount() {
return 6;
}
@Override
public ItemStack transferSlot(PlayerEntity player, int index) {
int lastFurnaceSlotIndex = 6;
int maxIndex = slots.size();
int hotBarSlots = maxIndex - 9;
ItemStack itemStack = ItemStack.EMPTY;
Slot slot = this.slots.get(index);
if (slot != null && slot.hasStack()) {
ItemStack itemStack2 = slot.getStack();
itemStack = itemStack2.copy();
// from furnace slots
if (index < lastFurnaceSlotIndex) {
if (!this.insertItem(itemStack2, lastFurnaceSlotIndex, maxIndex, true)) {
return ItemStack.EMPTY;
}
} else {
if (isSmeltable(itemStack2)) {
if (!this.insertItem(itemStack2, 0, 1, false)) {
return ItemStack.EMPTY;
}
} else if (itemStack2.getItem() instanceof IUpgrade) {
if (!this.insertItem(itemStack2, 3, lastFurnaceSlotIndex, false)) {
return ItemStack.EMPTY;
}
} else if (index < hotBarSlots) {
if (!this.insertItem(itemStack2, hotBarSlots, maxIndex, false)) {
return ItemStack.EMPTY;
}
} else if (index < maxIndex && !this.insertItem(itemStack2, lastFurnaceSlotIndex, hotBarSlots, false)) {
return ItemStack.EMPTY;
}
}
if (itemStack2.isEmpty()) {
slot.setStack(ItemStack.EMPTY);
} else {
slot.markDirty();
}
if (itemStack2.getCount() == itemStack.getCount()) {
return ItemStack.EMPTY;
}
slot.onTakeItem(player, itemStack2);
}
return itemStack;
}
}
| true
|
d4bc8048e0c6aac25edeafe43081ceb44c68cfec
|
Java
|
sosogngngn/Study-in-National-Education
|
/국비지원교육 16일차/inherit_casting/Person.java
|
UTF-8
| 164
| 2.578125
| 3
|
[] |
no_license
|
package p06.inherit_casting;
//Class간의 형변환은 상속이 전제
public class Person {
int a = 10;
void method(){
System.out.println("Person");
}
}
| true
|
0bb237b3206fc44ccd2781577026166fc0c108d7
|
Java
|
goponenkoev/GradCitNotification
|
/src/main/java/com/gradcit/notification/messaging/MessageHandler.java
|
UTF-8
| 847
| 2.203125
| 2
|
[] |
no_license
|
package com.gradcit.notification.messaging;
import com.gradcit.notification.model.Notification;
import com.gradcit.notification.service.NotificationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;
@Service
public class MessageHandler {
private final Logger logger = LoggerFactory.getLogger(MessageHandler.class);
private final NotificationService notificationService;
public MessageHandler(NotificationService notificationService) {
this.notificationService = notificationService;
}
@KafkaListener(topics = "notifications")
public void handleMessage(Notification notification) {
logger.info("Consumed notification: {}", notification);
notificationService.sendNotification(notification);
}
}
| true
|
749db64f2bac124c40ce209d7b499eed518f0cbd
|
Java
|
Danielyao0312/Backend-system-key-algorithms
|
/160-Intersection-of-Two-Linked-Lists/solution.java
|
UTF-8
| 1,017
| 3.375
| 3
|
[] |
no_license
|
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode pa = headA, pb = headB;
int lenA = getLen(headA);
int lenB = getLen(headB);
int dislen = Math.abs(lenA - lenB);
for (int i = 0; i < dislen; i++) {
if (lenA > lenB) {
pa = pa.next;
} else {
pb = pb.next;
}
}
while (pa != null && pb != null) {
if(pa.val == pb.val) break;
pa = pa.next;
pb = pb.next;
}
return pa;
}
private int getLen(ListNode head) {
int len = 0;
while (head != null) {
head = head.next;
len ++;
}
return len;
}
}
| true
|
b046e983cb17e4dd138f54ef215f04d9ebecbd0f
|
Java
|
SuttyRead/FtlTemplate
|
/src/test/java/com/ua/sutty/hibernate/repository/impl/UserServiceTest.java
|
UTF-8
| 5,854
| 2.34375
| 2
|
[] |
no_license
|
package com.ua.sutty.hibernate.repository.impl;
import com.ua.sutty.spring.app.Application;
import com.ua.sutty.spring.domain.Role;
import com.ua.sutty.spring.domain.User;
import com.ua.sutty.spring.service.UserService;
import org.dbunit.DataSourceDatabaseTester;
import org.dbunit.IDatabaseTester;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSetBuilder;
import org.dbunit.operation.DatabaseOperation;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.sql.DataSource;
import java.sql.Date;
import static org.junit.Assert.assertEquals;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class UserServiceTest {
@Autowired
private DataSource dataSource;
@Autowired
private UserService userService;
private IDatabaseTester iDatabaseTester;
@Before
public void loadProperties() throws Exception {
IDataSet iDataSet = new FlatXmlDataSetBuilder()
.build(Thread.currentThread().getContextClassLoader()
.getResourceAsStream("dataset.xml"));
iDatabaseTester = new DataSourceDatabaseTester(dataSource);
iDatabaseTester.setSetUpOperation(DatabaseOperation.CLEAN_INSERT);
iDatabaseTester.setDataSet(iDataSet);
iDatabaseTester.onSetup();
}
@Test(expected = NullPointerException.class)
public void testCreateNull() {
userService.save(null);
}
@Test(expected = NullPointerException.class)
public void testUpdateNull() {
userService.save(null);
}
@Test(expected = NullPointerException.class)
public void testRemoveNull() {
userService.delete(null);
}
@Test(expected = NullPointerException.class)
public void testFindByEmailNull() {
userService.findUserByEmail(null);
}
@Test(expected = NullPointerException.class)
public void testFindByLoginNull() {
userService.findUserByLogin(null);
}
@Test
public void findUserByLogin() throws Exception {
User user = userService.findUserByEmail("secondUser@gmail.com");
assertEquals("User after findByLogin must coincide with role in data base",
user.getLogin(), iDatabaseTester.getDataSet()
.getTable("user").getValue(1, "login"));
assertEquals("User after findByLogin must coincide with role in data base",
user.getEmail(), iDatabaseTester.getDataSet()
.getTable("user").getValue(1, "email"));
}
@Test
public void findByEmail() throws Exception {
User user = userService.findUserByEmail("firstUser@gmail.com");
assertEquals("User after findByEmail must coincide with role in data base",
user.getLogin(), iDatabaseTester.getDataSet().getTable("user")
.getValue(0, "login"));
assertEquals("User after findByLogin must coincide with role in data base",
user.getEmail(), iDatabaseTester.getDataSet()
.getTable("user").getValue(0, "email"));
}
@Test
public void findById() throws Exception {
User user = userService.findUserById(1L);
assertEquals("User after findByEmail must coincide with role in data base",
user.getLogin(), iDatabaseTester.getDataSet()
.getTable("user").getValue(0, "login"));
assertEquals("User after findByLogin must coincide with role in data base",
user.getEmail(), iDatabaseTester.getDataSet()
.getTable("user").getValue(0, "email"));
}
@Test
public void testSave() throws Exception {
User user = User.builder()
.login("fourth")
.password("fourth")
.email("fourth@gmail.com")
.firstName("fourth")
.lastName("fourth")
.birthday(new Date(System.currentTimeMillis()))
.role(new Role(1L, "USER"))
.build();
userService.save(user);
assertEquals(4, iDatabaseTester.getConnection().createDataSet().getTable("user").getRowCount());
assertEquals(user.getLogin(), iDatabaseTester.getConnection().createDataSet().getTable("user").getValue(3, "login"));
assertEquals(user.getEmail(), iDatabaseTester.getConnection().createDataSet().getTable("user").getValue(3, "email"));
}
@Test
public void testDelete() throws Exception {
User someUser = User.builder()
.id(1L)
.login("firstUser")
.password("123")
.email("firstUser@gmail.com")
.firstName("first")
.lastName("user")
.birthday(Date.valueOf("1999-4-6"))
.role(new Role(1L, "USER"))
.build();
userService.delete(someUser);
assertEquals(2, iDatabaseTester.getConnection().createDataSet().getTable("user").getRowCount());
}
@Test
public void testUpdate() throws Exception {
User someUser = User.builder()
.id(2L)
.login("secondUser")
.password("123")
.email("secondUser@gmail.com")
.firstName("second")
.lastName("user")
.birthday(Date.valueOf("2000-1-28"))
.role(new Role(2L, "ADMIN"))
.build();
someUser.setLogin("modifiedLogin");
userService.save(someUser);
assertEquals(someUser, userService.findUserById(someUser.getId()));
assertEquals(3, iDatabaseTester.getConnection().getRowCount("user"));
}
}
| true
|
c2e77381b68372a23b438f27d57471aa357066d8
|
Java
|
cha63506/CompSecurity
|
/Shopping/poshmark_source/src/com/poshmark/notifications/PMNotificationManager.java
|
UTF-8
| 5,998
| 1.679688
| 2
|
[] |
no_license
|
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.poshmark.notifications;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import com.poshmark.application.PMApplication;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
// Referenced classes of package com.poshmark.notifications:
// PMPartyAlarmBroadcastReciever, PMFiredNotifications, PMNotificationListener
public class PMNotificationManager
{
public class PMBroadcastReciever extends BroadcastReceiver
{
PMNotificationListener listener;
final PMNotificationManager this$0;
public void onReceive(Context context, Intent intent)
{
if (listener != null)
{
listener.handleNotification(intent);
}
}
public PMBroadcastReciever()
{
this$0 = PMNotificationManager.this;
super();
listener = null;
}
public PMBroadcastReciever(PMNotificationListener pmnotificationlistener)
{
this$0 = PMNotificationManager.this;
super();
listener = null;
listener = pmnotificationlistener;
}
}
static Map listeners = new HashMap();
static PMNotificationManager notificationManager = null;
PMPartyAlarmBroadcastReciever alarmBroadcastReceiver;
public PMNotificationManager()
{
alarmBroadcastReceiver = new PMPartyAlarmBroadcastReciever();
PMApplication.getContext().registerReceiver(alarmBroadcastReceiver, new IntentFilter("com.poshmark.intents.PARTY_ALARM"));
}
public static void cancelDelayedNotification(int i)
{
Object obj = new Intent(PMApplication.getContext(), com/poshmark/notifications/PMPartyAlarmBroadcastReciever);
((Intent) (obj)).setAction("com.poshmark.intents.PARTY_ALARM");
obj = PendingIntent.getBroadcast(PMApplication.getContext(), i, ((Intent) (obj)), 0x10000000);
((AlarmManager)PMApplication.getContext().getSystemService("alarm")).cancel(((PendingIntent) (obj)));
}
public static void fireDelayedNotification(String s, Bundle bundle, long l)
{
Intent intent = new Intent(PMApplication.getContext(), com/poshmark/notifications/PMPartyAlarmBroadcastReciever);
intent.putExtra("FRAGMENT_DATA", bundle);
intent.setAction(s);
int i = (new Random()).nextInt();
s = PendingIntent.getBroadcast(PMApplication.getContext(), i, intent, 0x10000000);
((AlarmManager)PMApplication.getContext().getSystemService("alarm")).set(0, l, s);
PMFiredNotifications.saveFiredNotification(i);
}
public static void fireNotification(String s)
{
s = new Intent(s);
LocalBroadcastManager.getInstance(PMApplication.getContext()).sendBroadcast(s);
}
public static void fireNotification(String s, Bundle bundle)
{
s = new Intent(s);
s.putExtra("RESULT", bundle);
LocalBroadcastManager.getInstance(PMApplication.getContext()).sendBroadcast(s);
}
public static PMNotificationManager getNotificationManager()
{
if (notificationManager == null)
{
notificationManager = new PMNotificationManager();
}
return notificationManager;
}
public void registerForEvent(String s, PMNotificationListener pmnotificationlistener)
{
if (!listeners.containsKey(pmnotificationlistener))
{
HashMap hashmap = new HashMap();
PMBroadcastReciever pmbroadcastreciever = new PMBroadcastReciever(pmnotificationlistener);
hashmap.put(s, pmbroadcastreciever);
LocalBroadcastManager.getInstance(PMApplication.getContext()).registerReceiver(pmbroadcastreciever, new IntentFilter(s));
listeners.put(pmnotificationlistener, hashmap);
} else
{
Map map = (Map)listeners.get(pmnotificationlistener);
if (!map.containsKey(s))
{
pmnotificationlistener = new PMBroadcastReciever(pmnotificationlistener);
LocalBroadcastManager.getInstance(PMApplication.getContext()).registerReceiver(pmnotificationlistener, new IntentFilter(s));
map.put(s, pmnotificationlistener);
return;
}
}
}
public void unRegisterForEvent(String s, PMNotificationListener pmnotificationlistener)
{
if (listeners.containsKey(pmnotificationlistener))
{
pmnotificationlistener = (Map)listeners.get(pmnotificationlistener);
PMBroadcastReciever pmbroadcastreciever = (PMBroadcastReciever)pmnotificationlistener.get(s);
if (pmbroadcastreciever != null)
{
LocalBroadcastManager.getInstance(PMApplication.getContext()).unregisterReceiver(pmbroadcastreciever);
pmnotificationlistener.remove(s);
}
}
}
public void unregisterAllEvents(PMNotificationListener pmnotificationlistener)
{
if (listeners.containsKey(pmnotificationlistener))
{
for (Iterator iterator = ((Map)listeners.get(pmnotificationlistener)).values().iterator(); iterator.hasNext(); iterator.remove())
{
PMBroadcastReciever pmbroadcastreciever = (PMBroadcastReciever)iterator.next();
LocalBroadcastManager.getInstance(PMApplication.getContext()).unregisterReceiver(pmbroadcastreciever);
}
listeners.remove(pmnotificationlistener);
}
}
}
| true
|
ef3c23eadb79b3f7a01610a0f6363abc3397bad2
|
Java
|
saka1029/Deep.Learning
|
/src/main/java/deep/learning/C3/C3_4_3層ニューラルネットワークの実装.java
|
UTF-8
| 3,576
| 2.5
| 2
|
[] |
no_license
|
package deep.learning.C3;
import static org.junit.Assert.*;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.ops.transforms.Transforms;
import deep.learning.common.Util;
public class C3_4_3層ニューラルネットワークの実装 {
@Test
public void C3_4_2_各層における信号伝達の実装() {
INDArray X = Nd4j.create(new double[] {1.0, 0.5});
INDArray W1 = Nd4j.create(new double[][] {{0.1, 0.3, 0.5}, {0.2, 0.4, 0.6}});
INDArray B1 = Nd4j.create(new double[] {0.1, 0.2, 0.3});
assertArrayEquals(new int[] {2, 3}, W1.shape());
assertArrayEquals(new int[] {1, 2}, X.shape());
assertArrayEquals(new int[] {1, 3}, B1.shape());
INDArray A1 = X.mmul(W1).add(B1);
INDArray Z1 = Transforms.sigmoid(A1);
assertEquals("[0.30,0.70,1.10]", Util.string(A1));
assertEquals("[0.57,0.67,0.75]", Util.string(Z1));
INDArray W2 = Nd4j.create(new double[][] {{0.1, 0.4}, {0.2, 0.5}, {0.3, 0.6}});
INDArray B2 = Nd4j.create(new double[] {0.1, 0.2});
assertArrayEquals(new int[] {1, 3}, Z1.shape());
assertArrayEquals(new int[] {3, 2}, W2.shape());
assertArrayEquals(new int[] {1, 2}, B2.shape());
INDArray A2 = Z1.mmul(W2).add(B2);
INDArray Z2 = Transforms.sigmoid(A2);
assertEquals("[0.52,1.21]", Util.string(A2));
assertEquals("[0.63,0.77]", Util.string(Z2));
INDArray W3 = Nd4j.create(new double[][] {{0.1, 0.3}, {0.2, 0.4}});
INDArray B3 = Nd4j.create(new double[] {0.1, 0.2});
INDArray A3 = Z2.mmul(W3).add(B3);
// ND4JにはTransformsクラスにidentity(INDArray)メソッドが用意されています。
INDArray Y = Transforms.identity(A3);
assertEquals("[0.32,0.70]", Util.string(A3));
assertEquals("[0.32,0.70]", Util.string(Y));
// Y.equals(A3)は真となります。
assertEquals(A3, Y);
}
public static Map<String, INDArray> init_network() {
Map<String, INDArray> network = new HashMap<>();
network.put("W1", Nd4j.create(new double[][] {{0.1, 0.3, 0.5}, {0.2, 0.4, 0.6}}));
network.put("b1", Nd4j.create(new double[] {0.1, 0.2, 0.3}));
network.put("W2", Nd4j.create(new double[][] {{0.1, 0.4}, {0.2, 0.5}, {0.3, 0.6}}));
network.put("b2", Nd4j.create(new double[] {0.1, 0.2}));
network.put("W3", Nd4j.create(new double[][] {{0.1, 0.3}, {0.2, 0.4}}));
network.put("b3", Nd4j.create(new double[] {0.1, 0.2}));
return network;
}
public static INDArray forward(Map<String, INDArray> network, INDArray x) {
INDArray W1 = network.get("W1");
INDArray W2 = network.get("W2");
INDArray W3 = network.get("W3");
INDArray b1 = network.get("b1");
INDArray b2 = network.get("b2");
INDArray b3 = network.get("b3");
INDArray a1 = x.mmul(W1).add(b1);
INDArray z1 = Transforms.sigmoid(a1);
INDArray a2 = z1.mmul(W2).add(b2);
INDArray z2 = Transforms.sigmoid(a2);
INDArray a3 = z2.mmul(W3).add(b3);
INDArray y = Transforms.identity(a3);
return y;
}
@Test
public void C3_4_3_実装のまとめ() {
Map<String, INDArray> network = init_network();
INDArray x = Nd4j.create(new double[] {1.0, 0.5});
INDArray y = forward(network, x);
assertEquals("[0.32,0.70]", Util.string(y));
}
}
| true
|
bc7f8c6b9310cd86d965f620d4ec90bbd689e21f
|
Java
|
Abanoub-Emil/MenuApp
|
/app/src/main/java/com/champion/bero/menuapp/UI/Welcome/Presenter/WelcomePresenter.java
|
UTF-8
| 2,906
| 2.078125
| 2
|
[] |
no_license
|
package com.champion.bero.menuapp.UI.Welcome.Presenter;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import com.bumptech.glide.Glide;
import com.champion.bero.menuapp.Model.APIKey;
import com.champion.bero.menuapp.Model.Data;
import com.champion.bero.menuapp.Model.MenuList;
import com.champion.bero.menuapp.Model.MyResponse;
import com.champion.bero.menuapp.Model.Restaurant;
import com.champion.bero.menuapp.RetrofitWrapper.API;
import com.champion.bero.menuapp.RetrofitWrapper.APIHelper;
import com.champion.bero.menuapp.RetrofitWrapper.APIHelperImpl;
import com.champion.bero.menuapp.RetrofitWrapper.RetrofitClientInstance;
import com.champion.bero.menuapp.UI.Welcome.Activities.WelcomeActivity;
import com.champion.bero.menuapp.UI.Welcome.Activities.WelcomeActivityInt;
import java.sql.SQLOutput;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* Created by Champion on 23-Sep-18.
*/
public class WelcomePresenter implements WelcomePresenterInt, APIHelper.OnRequestFinishedListener {
WelcomeActivityInt welcomeActivity;
Restaurant restaurant;
List<MenuList> menuList;
Data data;
APIHelper apiHelper = new APIHelperImpl();
public WelcomePresenter(WelcomeActivityInt welcomeActivity) {
this.welcomeActivity = welcomeActivity;
}
public void requestData(boolean isEnglish) {
try {
apiHelper.getData(new Callback<MyResponse>() {
@Override
public void onResponse(Call<MyResponse> call, Response<MyResponse> response) {
data = response.body().getData();
Bundle myBundle = new Bundle();
myBundle.putSerializable("data", data);
welcomeActivity.setBundle(myBundle);
welcomeActivity.setRestaurantImage(data.getRestaurant().getImage());
System.out.println(data.getRestaurant().getTitle());
}
@Override
public void onFailure(Call<MyResponse> call, Throwable t) {
}
},isEnglish);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onSuccess(Data data) {
}
// public ConfirmOrderFragment() {
// // Required empty public constructor
// }
//
// public static ConfirmOrderFragment newInstance(Bundle extras, RideMapFragment.OverlayInteractor overlayInteractor) {
// ConfirmOrderFragment fragment = new ConfirmOrderFragment();
// fragment.setArguments(extras);
// fragment.overlayInteractor = overlayInteractor;
// return fragment;
// }
}
| true
|
ae1cae7869715e2af00845010f23df806c9f905d
|
Java
|
Nazdorovye/JavaIII
|
/Seminar0201/src/main/java/models/MyNode.java
|
UTF-8
| 211
| 2.53125
| 3
|
[] |
no_license
|
package models;
public class MyNode<T> {
public MyNode<T> prev = null;
public MyNode<T> next = null;
public T value = null;
public MyNode() {}
public MyNode(T value) {
this.value = value;
}
}
| true
|
d05bf95a4a44b31eaafbb55aab89a0c08cd8af72
|
Java
|
xiaohanfeidao/spring-cloud-alibaba-dubbo
|
/provider/provider-ums-service/src/main/java/com/ums/service/fallback/UmsAdminServiceFallback.java
|
UTF-8
| 661
| 2.21875
| 2
|
[] |
no_license
|
package com.ums.service.fallback;
import com.ums.domain.UmsAdmin;
import lombok.extern.java.Log;
/**
* dubbo熔断
*
* @author tallon
* @version v1.0.0
* @date 2020-05-04 11:35
*/
@Log
public class UmsAdminServiceFallback {
/**
* 熔断方法
*
* @param username {@code String} 用户名
* @param ex {@code Throwable} 异常信息
* @return {@link UmsAdmin} 熔断后的固定结果
*/
public static UmsAdmin getByUsernameFallback(String username, Throwable ex) {
log.warning("Invoke getByUsernameFallback: " + ex.getClass().getTypeName());
ex.printStackTrace();
return null;
}
}
| true
|
6a606351c2489ca7e7cbe870052b5e8d708f8813
|
Java
|
weedkiller/CommonPlatform2
|
/工具/Picturepark.SDK.Playground-master/Picturepark.SDK.Playground-master/playground/java-client/src/main/java/io/swagger/client/model/MetadataError.java
|
UTF-8
| 5,061
| 1.9375
| 2
|
[] |
no_license
|
/*
* Web API Swagger specification
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 1.0.0
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package io.swagger.client.model;
import java.util.Objects;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
/**
* MetadataError
*/
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-10-04T14:36:42.044Z")
public class MetadataError {
@SerializedName("errorType")
private String errorType = null;
@SerializedName("lineNumber")
private Integer lineNumber = null;
@SerializedName("linePosition")
private Integer linePosition = null;
@SerializedName("path")
private String path = null;
@SerializedName("message")
private String message = null;
@SerializedName("schemaId")
private String schemaId = null;
public MetadataError errorType(String errorType) {
this.errorType = errorType;
return this;
}
/**
* Get errorType
* @return errorType
**/
@ApiModelProperty(value = "")
public String getErrorType() {
return errorType;
}
public void setErrorType(String errorType) {
this.errorType = errorType;
}
public MetadataError lineNumber(Integer lineNumber) {
this.lineNumber = lineNumber;
return this;
}
/**
* Get lineNumber
* @return lineNumber
**/
@ApiModelProperty(required = true, value = "")
public Integer getLineNumber() {
return lineNumber;
}
public void setLineNumber(Integer lineNumber) {
this.lineNumber = lineNumber;
}
public MetadataError linePosition(Integer linePosition) {
this.linePosition = linePosition;
return this;
}
/**
* Get linePosition
* @return linePosition
**/
@ApiModelProperty(required = true, value = "")
public Integer getLinePosition() {
return linePosition;
}
public void setLinePosition(Integer linePosition) {
this.linePosition = linePosition;
}
public MetadataError path(String path) {
this.path = path;
return this;
}
/**
* Get path
* @return path
**/
@ApiModelProperty(value = "")
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public MetadataError message(String message) {
this.message = message;
return this;
}
/**
* Get message
* @return message
**/
@ApiModelProperty(value = "")
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public MetadataError schemaId(String schemaId) {
this.schemaId = schemaId;
return this;
}
/**
* Get schemaId
* @return schemaId
**/
@ApiModelProperty(value = "")
public String getSchemaId() {
return schemaId;
}
public void setSchemaId(String schemaId) {
this.schemaId = schemaId;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MetadataError metadataError = (MetadataError) o;
return Objects.equals(this.errorType, metadataError.errorType) &&
Objects.equals(this.lineNumber, metadataError.lineNumber) &&
Objects.equals(this.linePosition, metadataError.linePosition) &&
Objects.equals(this.path, metadataError.path) &&
Objects.equals(this.message, metadataError.message) &&
Objects.equals(this.schemaId, metadataError.schemaId);
}
@Override
public int hashCode() {
return Objects.hash(errorType, lineNumber, linePosition, path, message, schemaId);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class MetadataError {\n");
sb.append(" errorType: ").append(toIndentedString(errorType)).append("\n");
sb.append(" lineNumber: ").append(toIndentedString(lineNumber)).append("\n");
sb.append(" linePosition: ").append(toIndentedString(linePosition)).append("\n");
sb.append(" path: ").append(toIndentedString(path)).append("\n");
sb.append(" message: ").append(toIndentedString(message)).append("\n");
sb.append(" schemaId: ").append(toIndentedString(schemaId)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| true
|
a9065bd1fc2fd8feac3fb020013fff26d1ddc6b9
|
Java
|
ElitonMaymone/Exercicio-aula4
|
/src/main/java/br/com/db1/ExemploEnum.java
|
UTF-8
| 482
| 2.359375
| 2
|
[] |
no_license
|
package br.com.db1;
import br.com.db1.type.TipoLogradouro;
public class ExemploEnum {
public static void main(String[] args) {
System.out.println(TipoLogradouro.RUA.getdescricaoLogradouro());
System.out.println(TipoLogradouro.PRACA.getdescricaoLogradouro());
System.out.println(TipoLogradouro.AVENIDA.getdescricaoLogradouro());
System.out.println(TipoLogradouro.FAZENDA.getdescricaoLogradouro());
System.out.println(TipoLogradouro.FAZENDA.getsiglaLogradouro());
}
}
| true
|
0e0b9e008be8cf03368fedb2b85d8a7b32a9540f
|
Java
|
javaarchjdr/JPO
|
/src/test/java/org/jpo/gui/ThumbnailControllerTest.java
|
UTF-8
| 1,864
| 2.125
| 2
|
[] |
no_license
|
package org.jpo.gui;
import org.jpo.gui.swing.Thumbnail;
import org.junit.Test;
import javax.swing.*;
import java.awt.*;
import java.lang.reflect.InvocationTargetException;
import java.util.logging.Level;
import java.util.logging.Logger;
import static junit.framework.TestCase.assertNotNull;
import static org.junit.Assume.assumeFalse;
/*
Copyright (C) 2017-2019 Richard Eigenmann.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or any later version. This program is distributed
in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details. You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
The license is in gpl.txt.
See http://www.gnu.org/copyleft/gpl.html for the details.
*/
/**
*
* @author Richard Eigenmann
*/
public class ThumbnailControllerTest {
@Test
public void testConstructor() {
assumeFalse( GraphicsEnvironment.isHeadless() );
try {
SwingUtilities.invokeAndWait( () -> {
final Thumbnail thumbnail = new Thumbnail();
assertNotNull( thumbnail );
final ThumbnailController thumbnailController = new ThumbnailController( thumbnail, 350 );
assertNotNull( thumbnailController );
} );
} catch ( final InterruptedException | InvocationTargetException ex ) {
Logger.getLogger( ThumbnailControllerTest.class.getName() ).log( Level.SEVERE, null, ex );
}
}
}
| true
|
13eed7b40067dbbca27dba00263768045f79d0f0
|
Java
|
1123Javayanglei/myJava
|
/src/com/Algorithms/Part1/jiChuBianChengMoXing1_1/BinarrySearch_1_1_10/binarySearch.java
|
UTF-8
| 1,592
| 3.421875
| 3
|
[] |
no_license
|
package com.Algorithms.Part1.jiChuBianChengMoXing1_1.BinarrySearch_1_1_10;
import edu.princeton.cs.algs4.StdOut;
import java.lang.management.MemoryType;
import java.util.Arrays;
public class binarySearch {
public static int BinarySearch(int[] array, int target) { //array 有序数组 target 查找值 复杂度 O long(N)
int start = 0; // 查找范围起点
int end = array.length - 1; //查找范围终点
int mid; //查找范围的中位数
while (start <= end) {
// mid=(start+end)/2;
mid = start + (end - start) / 2; // 查找范围缩小一半
/*
若start和end过大 会溢出 变加为减
解决办法: mid=start+(end-start)
*/
if (target < array[mid]) { //查找的值小于a[mid] 就在左边查找
end = mid - 1;
} else if (target > array[mid]) { //查找的值大于a[mid] 就在右边查找
start = mid + 1;
} else {
return mid; //查找的值等于a[mid] 返回mid
}
}
return -1; //没找到返回 -1
}
public static void main(String[] args) {
int N = 10;
System.out.println("long(N)的复杂度:" + Math.log(N));
int[] array = new int[N];
for (int i = 0; i < N; i++) {
array[i] = i;
}
Arrays.sort(array); //要查找的数组必须是有序的
System.out.println("排序后:" + Arrays.toString(array));
System.out.println(BinarySearch(array, 8));
}
}
| true
|
643c0f2e632bc2daff9f550076f4e14b6ebbbd1c
|
Java
|
langebrake/TestRep
|
/MMT/src/model/pluginmanager/PluginManager.java
|
UTF-8
| 2,655
| 2.4375
| 2
|
[] |
no_license
|
package model.pluginmanager;
import java.io.File;
import java.lang.reflect.Method;
import java.net.URI;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import dev.Plugin;
public class PluginManager {
private static LinkedList<PluginHierarchyElement> plugins;
public static LinkedList<URLClassLoader> classes;
/**
* adds
*
* @param menu
*/
public static LinkedList<PluginHierarchyElement> getPluginList() {
return plugins;
}
@SuppressWarnings("unchecked")
private static void loadPlugins(File dir,
LinkedList<PluginHierarchyElement> appendList) throws Exception {
for (File file : dir.listFiles()) {
if (file.isDirectory()) {
Subgroup s = new Subgroup(file.getName());
appendList.add(s);
loadPlugins(file, s);
} else if (file.getName().toLowerCase().endsWith(".jar")) {
PluginManager.addPath(file.getPath());
String path = file.getPath();
JarFile jar = new JarFile(path);
String interfaceVersion = jar.getManifest().getMainAttributes().getValue("MMTPluginInterfaceVersion");
if(interfaceVersion != null && interfaceVersion.equals(Plugin.INTERFACE_VERSION)){
Enumeration<JarEntry> en = jar.entries();
URL[] urls = { new URL("jar:file:" + path + "!/") };
URLClassLoader cl = URLClassLoader.newInstance(urls);
classes.add(cl);
while (en.hasMoreElements()) {
JarEntry je = en.nextElement();
if (je.isDirectory() || !je.getName().endsWith(".class")) {
continue;
}
String className = je.getName().substring(0,
je.getName().length() - 6);
className = className.replace('/', '.');
Class<?> c = cl.loadClass(className);
if (c.getSuperclass() == Plugin.class) {
appendList.add(new Loadable(
(Class<? extends Plugin>) c, jar.getManifest()
.getMainAttributes()));
} else {
}
}
}
jar.close();
}
}
}
public static void loadPlugins() throws Exception {
plugins = new LinkedList<PluginHierarchyElement>();
classes = new LinkedList<URLClassLoader>();
File f = new File("./plugin");
loadPlugins(f, plugins);
}
public static void addPath(String s) throws Exception {
File f = new File(s);
URI u = f.toURI();
URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader
.getSystemClassLoader();
Class<URLClassLoader> urlClass = URLClassLoader.class;
Method method = urlClass.getDeclaredMethod("addURL",
new Class[] { URL.class });
method.setAccessible(true);
method.invoke(urlClassLoader, new Object[] { u.toURL() });
}
}
| true
|
b749ebfcb64e73ee15032f7f13fde03e01e106ee
|
Java
|
mayl666/cloud_tv
|
/cloudplatform-webportal-sdk-rds/src/main/java/com/letv/portal/task/gce/service/impl/TaskGceContainer1CreateServiceImpl.java
|
UTF-8
| 2,378
| 1.945313
| 2
|
[] |
no_license
|
package com.letv.portal.task.gce.service.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.letv.common.result.ApiResultObject;
import com.letv.portal.enumeration.MclusterStatus;
import com.letv.portal.model.HostModel;
import com.letv.portal.model.gce.GceCluster;
import com.letv.portal.model.gce.GceContainer;
import com.letv.portal.model.task.TaskResult;
import com.letv.portal.model.task.service.IBaseTaskService;
import com.letv.portal.python.service.IGcePythonService;
import com.letv.portal.service.gce.IGceContainerService;
@Service("taskGceContainer1CreateService")
public class TaskGceContainer1CreateServiceImpl extends BaseTask4GceServiceImpl implements IBaseTaskService{
@Autowired
private IGcePythonService gcePythonService;
@Autowired
private IGceContainerService gceContainerService;
private final static Logger logger = LoggerFactory.getLogger(TaskGceContainer1CreateServiceImpl.class);
@Override
public TaskResult execute(Map<String, Object> params) throws Exception {
TaskResult tr = super.execute(params);
if(!tr.isSuccess())
return tr;
//执行业务
List<GceContainer> containers = super.getContainers(params);
GceContainer container = containers.get(0);
ApiParam apiParam = super.getApiParam(container, ManageType.MANAGER, container.getMgrBindHostPort());
GceCluster cluster = super.getGceCluster(params);
Map<String,String> map = new HashMap<String,String>();
map.put("clusterName", cluster.getClusterName());
map.put("dataNodeName", container.getContainerName());
map.put("dataNodeIp", apiParam.getIp());
map.put("dataNodeExternalPort", apiParam.getPort());
ApiResultObject resultObject =this.gcePythonService.createContainer1(map,apiParam.getIp(),apiParam.getPort(),cluster.getAdminUser(),cluster.getAdminPassword());
tr = analyzeRestServiceResult(resultObject);
if(tr.isSuccess()) {
Map data = (Map) ((Map)transToMap(resultObject.getResult()).get("response")).get("data");
container.setContainerUuid((String)data.get("uuid"));
this.gceContainerService.updateBySelective(container);
}
tr.setParams(params);
return tr;
}
}
| true
|
5527cc1d61864485a7218910baa2922eeccc4f8b
|
Java
|
slj1014/blog
|
/src/main/java/com/slj/blog/entity/Article.java
|
UTF-8
| 3,187
| 2.296875
| 2
|
[] |
no_license
|
package com.slj.blog.entity;
import java.io.Serializable;
public class Article implements Serializable {
private static final long serialVersionUID = 1L;
//id
private Integer articleId;
//创建时间
private Long articleCreate;
//修改时间
private Long articleUpdate;
//标题
private String articleTitle;
//内容
private String articleContent;
//简单描述(截取文章前150个文字)
private String articleDes;
//类别
private Integer articleCategory;
//类型(0:原创,1:引用)
private Integer articleType;
//引用连接
private String articleUrl;
//文章图片连接
private String articleImage;
//阅读数
private Integer articleRead;
//用户ID
private Integer userId;
//新增字段
private String articleCreateStr;
public String getArticleCreateStr() {
return articleCreateStr;
}
public void setArticleCreateStr(String articleCreateStr) {
this.articleCreateStr = articleCreateStr;
}
public Integer getArticleId() {
return articleId;
}
public void setArticleId(Integer articleId) {
this.articleId = articleId;
}
public Long getArticleCreate() {
return articleCreate;
}
public void setArticleCreate(Long articleCreate) {
this.articleCreate = articleCreate;
}
public Long getArticleUpdate() {
return articleUpdate;
}
public void setArticleUpdate(Long articleUpdate) {
this.articleUpdate = articleUpdate;
}
public String getArticleTitle() {
return articleTitle;
}
public void setArticleTitle(String articleTitle) {
this.articleTitle = articleTitle;
}
public String getArticleContent() {
return articleContent;
}
public void setArticleContent(String articleContent) {
this.articleContent = articleContent;
}
public String getArticleImage() {
return articleImage;
}
public void setArticleImage(String articleImage) {
this.articleImage = articleImage;
}
public Integer getArticleCategory() {
return articleCategory;
}
public void setArticleCategory(Integer articleCategory) {
this.articleCategory = articleCategory;
}
public Integer getArticleType() {
return articleType;
}
public void setArticleType(Integer articleType) {
this.articleType = articleType;
}
public String getArticleUrl() {
return articleUrl;
}
public void setArticleUrl(String articleUrl) {
this.articleUrl = articleUrl;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getArticleDes() {
return articleDes;
}
public void setArticleDes(String articleDes) {
this.articleDes = articleDes;
}
public Integer getArticleRead() {
return articleRead;
}
public void setArticleRead(Integer articleRead) {
this.articleRead = articleRead;
}
@Override
public String toString() {
return "Article [articleId=" + articleId + ", articleCreate=" + articleCreate + ", articleUpdate="
+ articleUpdate + ", articleTitle=" + articleTitle + ", articleContent=" + articleContent
+ ", articleDes=" + articleDes + ", articleCategory=" + articleCategory + ", articleType=" + articleType
+ ", articleUrl=" + articleUrl + ", articleImage=" + articleImage + ", userId=" + userId + "]";
}
}
| true
|
6ab4130ff69bc7e9d82e067cc63125d8cbe97307
|
Java
|
ulinka/tbcnn-attention
|
/github_code_index/java/10/0.java
|
UTF-8
| 1,285
| 3.390625
| 3
|
[] |
no_license
|
import java.util.Scanner;
public class Problems {
public static void main(String args[]) {
Scanner stdin = new Scanner(System.in);
System.out.println("Enter n, then values: ");
int n = Integer.parseInt(stdin.nextLine());
String input = stdin.nextLine();
String[] splitIn = input.split(" ");
int t;
int swapCount = 0;
int passCount = 1;
int[] intValues = new int[n];
for (int k = 0; k < n; k++) {
intValues[k] = Integer.parseInt(splitIn[k]);
}
/////////////////////////////
while (!sortCheck(intValues, n)) {
for (int i = 0; i < n - 1; i++) {
if (intValues[i] > intValues[i + 1]) {
swapCount++;
t = intValues[i];
intValues[i] = intValues[i + 1];
intValues[i + 1] = t;
}
}
passCount++;
}
System.out.println(passCount + " " + swapCount);
}
private static boolean sortCheck(int[] intValues, int n) {
boolean check = true;
for(int j=0; j<n-1; j++) {
if(intValues[j]>intValues[j+1]) {
check = false;
}
}
return check;
}
}
| true
|
9e2818f69fbb44cd1107b030ec02ade0c423b012
|
Java
|
ElyashivS/ADSS_Group_E
|
/dev/src/main/java/PresentationLayer/Transport/OptionMenus/DeliveriesOptionsMenu.java
|
UTF-8
| 9,346
| 2.828125
| 3
|
[] |
no_license
|
package PresentationLayer.Transport.OptionMenus;
import BusinessLayer.Workers_Transport.DeliveryPackage.DeliveryFacade;
import PresentationLayer.CommandLineInterface;
import PresentationLayer.Option;
import PresentationLayer.OptionsMenu;
import PresentationLayer.Workers.DataTransferObjects.QualificationsDTO;
import java.sql.Time;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
public class DeliveriesOptionsMenu extends OptionsMenu {
private final DeliveryFacade deliveryFacade = DeliveryFacade.getInstance();
public DeliveriesOptionsMenu(CommandLineInterface parentCLI) {
super(parentCLI);
int i = 1;
options.put(i++, new Option("Create New Delivery", this::createNewDelivery, QualificationsDTO.LogisticsManager));
options.put(i++, new Option("Delete Delivery", this::deleteDelivery, QualificationsDTO.LogisticsManager));
options.put(i++, new Option("Change Delivery Date", this::changeDate, QualificationsDTO.LogisticsManager));
options.put(i++, new Option("Change Delivery Time", this::changeTime, QualificationsDTO.LogisticsManager));
options.put(i++, new Option("Change Delivery Weight", this::changeWeight, QualificationsDTO.LogisticsManager));
options.put(i++, new Option("Change Truck for Delivery", this::changeTruck, QualificationsDTO.LogisticsManager));
options.put(i++, new Option("Change Driver for Delivery", this::changeDriver, QualificationsDTO.LogisticsManager));
options.put(i++, new Option("Add Order and Location", this::addOrder, QualificationsDTO.LogisticsManager));
options.put(i++, new Option("Remove Order and Location", this::removeOrder, QualificationsDTO.LogisticsManager));
options.put(i++, new Option("Change Status", this::changeStatus, QualificationsDTO.LogisticsManager));
options.put(i++, new Option("Display Deliveries", this::displayDeliveries));
options.put(i, new Option("Back", this::back));
}
private void createNewDelivery() {
String id, deliveryDate, s2;
Date date;
int s1;
List<Integer> targetLocations = new ArrayList<>();
List<Integer> orders = new ArrayList<>();
System.out.println("to create delivery details please first enter target locations," +
"\nto finish please enter -1");
s1 = in.nextInt();
while(s1!=-1)
{
targetLocations.add(s1);
s1 = in.nextInt();
}
System.out.println("to create delivery details please first enter orders," +
"\nto finish please enter -1");
s1 = in.nextInt();
while(s1!=-1)
{
orders.add(s1);
s1 = in.nextInt();
}
System.out.println("please enter delivery id");
id=in.next();
System.out.println("please enter delivery day:");
LocalDate localDate;
try{
do {
System.out.println("delivery day must be next week date");
deliveryDate = in.next();
date = new SimpleDateFormat("dd/MM/yyyy").parse(deliveryDate);
localDate=convertToLocalDateViaSqlDate(date);
}
while (!isDayNextWeek(localDate));
System.out.println("please enter leaving time (must be between 08:00-23:00):");
String ss1 = in.next();
Time newTime1 = Time.valueOf(ss1);
System.out.println("please enter: driver id," +
"\nsource location, truck id");
String name1 = in.next();
int loc = in.nextInt();
s2 = in.next();
deliveryFacade.createDelivery(id, date, newTime1, name1, loc, targetLocations, s2, orders);
}
catch (Exception e){
System.out.println(e.getMessage() + "\nYou entered wrong details please try again");
}
}
private void deleteDelivery() {
String id;
System.out.println("please enter the delivery id that you want to erase from the system");
id = in.next();
try{
deliveryFacade.removeDelivery(id);
}
catch (Exception e){
System.out.println(e.getMessage() + "\nYou entered wrong details please try again");
}
}
private void changeDate() {
String id, deliveryDate;
Date date;
System.out.println("please enter the delivery id and the new delivery day");
id = in.next();
deliveryDate = in.next();
try{
date = new SimpleDateFormat("dd/MM/yyyy").parse(deliveryDate);
deliveryFacade.updateDeliveryDate(id, date);
}
catch (Exception e){
System.out.println(e.getMessage() + "\nYou entered wrong details please try again");
}
}
private void changeTime() {
String id;
System.out.println("please enter the delivery id and the new delivery leaving time");
id = in.next();
String d = in.next();
Time newTime = Time.valueOf(d);
try{
deliveryFacade.updateLeavingTime(id, newTime);
}
catch (Exception e){
System.out.println(e.getMessage() + "\nYou entered wrong details please try again");
}
}
private void changeWeight() {
String id;
double totalWeight;
System.out.println("please enter delivery id, new weight of delivery");
id = in.next();
totalWeight = in.nextDouble();
try{
deliveryFacade.updateWeight(id, totalWeight);
}
catch (Exception e){
System.out.println(e.getMessage() + "\nYou entered wrong details please try again");
}
}
private void changeTruck() {
String id;
System.out.println("please enter delivery id, truck id");
id = in.next();
String tid = in.next();
try{
deliveryFacade.updateTruckId(id, tid);
}
catch (Exception e){
System.out.println(e.getMessage() + "\nYou entered wrong details please try again");
}
}
private void changeDriver() {
String id;
System.out.println("please enter delivery id, driver id");
id = in.next();
String temp = in.next();
try{
deliveryFacade.updateDriverId(id, temp);
}
catch (Exception e){
System.out.println(e.getMessage() + "\nYou entered wrong details please try again");
}
}
private void addOrder() {
String id;
int s1;
System.out.println("please enter delivery id, location id, order id");
id = in.next();
s1 = in.nextInt();
int ss2 = in.nextInt();
try{
deliveryFacade.addOrderAndLocation(id, s1, ss2);
}
catch (Exception e){
System.out.println(e.getMessage() + "\nYou entered wrong details please try again");
}
}
private void removeOrder() {
String id;
int s1;
System.out.println("please enter delivery id, location id, order id");
id = in.next();
s1 = in.nextInt();
int sss2 = in.nextInt();
try{
deliveryFacade.removeOrderAndLocation(id, s1, sss2);
}
catch (Exception e){
System.out.println(e.getMessage() + "\nYou entered wrong details please try again");
}
}
private void changeStatus() {
String id;
System.out.println("please enter delivery id, new delivery status that could be" +
"\nInTransit or Delivered");
id = in.next();
String sta= in.next();
try{
deliveryFacade.updateStatus(id, sta);
}
catch (Exception e){
System.out.println(e.getMessage() + "\nYou entered wrong details please try again");
}
}
private void displayDeliveries() {
try{
deliveryFacade.printDeliveries();
}
catch (Exception e){
System.out.println(e.getMessage() + "\nYou entered wrong details please try again");
}
}
public static LocalDate convertToLocalDateViaSqlDate(Date dateToConvert) {
return new java.sql.Date(dateToConvert.getTime()).toLocalDate();
}
public static boolean isDayNextWeek(LocalDate day){
LocalDate upcomingSunday=LocalDate.now();
switch (upcomingSunday.getDayOfWeek().getValue()){
case 1:
upcomingSunday=upcomingSunday.plusDays(6);
break;
case 2:
upcomingSunday=upcomingSunday.plusDays(5);
break;
case 3:
upcomingSunday=upcomingSunday.plusDays(4);
break;
case 4:
upcomingSunday=upcomingSunday.plusDays(3);
break;
case 5:
upcomingSunday=upcomingSunday.plusDays(2);
break;
case 6:
upcomingSunday=upcomingSunday.plusDays(1);
break;
case 7:
break;
}
LocalDate Nextsunday=upcomingSunday.plusDays(7);
return day.isBefore(Nextsunday)&&(day.isAfter(upcomingSunday)||day.isEqual(upcomingSunday)) ? true : false;
}
}
| true
|
18bf878bbb8a7a2148fe8146f32bdf172a501bbe
|
Java
|
cloudfoundry/cf-java-client
|
/integration-test/src/test/java/org/cloudfoundry/uaa/IdentityZonesTest.java
|
UTF-8
| 6,359
| 1.867188
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2013-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.cloudfoundry.uaa;
import org.cloudfoundry.AbstractIntegrationTest;
import org.cloudfoundry.uaa.identityzones.CreateIdentityZoneRequest;
import org.cloudfoundry.uaa.identityzones.CreateIdentityZoneResponse;
import org.cloudfoundry.uaa.identityzones.DeleteIdentityZoneRequest;
import org.cloudfoundry.uaa.identityzones.GetIdentityZoneRequest;
import org.cloudfoundry.uaa.identityzones.GetIdentityZoneResponse;
import org.cloudfoundry.uaa.identityzones.ListIdentityZonesRequest;
import org.cloudfoundry.uaa.identityzones.ListIdentityZonesResponse;
import org.cloudfoundry.uaa.identityzones.UpdateIdentityZoneRequest;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import java.time.Duration;
import java.util.concurrent.TimeoutException;
public final class IdentityZonesTest extends AbstractIntegrationTest {
@Autowired
private UaaClient uaaClient;
@Test
public void create() {
String identityZoneName = this.nameFactory.getIdentityZoneName();
String subdomainName = this.nameFactory.getDomainName();
this.uaaClient.identityZones()
.create(CreateIdentityZoneRequest.builder()
.subdomain(subdomainName)
.name(identityZoneName)
.build())
.then(requestListIdentityZones(this.uaaClient))
.flatMapIterable(ListIdentityZonesResponse::getIdentityZones)
.filter(resource -> identityZoneName.equals(resource.getName()))
.as(StepVerifier::create)
.expectNextCount(1)
.expectComplete()
.verify(Duration.ofMinutes(5));
}
@Test
public void delete() {
String identityZoneName = this.nameFactory.getIdentityZoneName();
String subdomainName = this.nameFactory.getDomainName();
getIdentityZoneId(this.uaaClient, identityZoneName, subdomainName)
.flatMap(identityZoneId -> this.uaaClient.identityZones()
.delete(DeleteIdentityZoneRequest.builder()
.identityZoneId(identityZoneId)
.build()))
.then(requestListIdentityZones(this.uaaClient))
.flatMapIterable(ListIdentityZonesResponse::getIdentityZones)
.filter(resource -> identityZoneName.equals(resource.getName()))
.as(StepVerifier::create)
.expectComplete()
.verify(Duration.ofMinutes(5));
}
@Test
public void get() {
String identityZoneName = this.nameFactory.getIdentityZoneName();
String subdomainName = this.nameFactory.getDomainName();
getIdentityZoneId(this.uaaClient, identityZoneName, subdomainName)
.flatMap(identityZoneId -> this.uaaClient.identityZones()
.get(GetIdentityZoneRequest.builder()
.identityZoneId(identityZoneId)
.build()))
.map(GetIdentityZoneResponse::getName)
.as(StepVerifier::create)
.expectNext(identityZoneName)
.expectComplete()
.verify(Duration.ofMinutes(5));
}
@Test
public void list() {
String identityZoneName = this.nameFactory.getIdentityZoneName();
String subdomainName = this.nameFactory.getDomainName();
requestCreateIdentityZone(this.uaaClient, identityZoneName, subdomainName)
.then(this.uaaClient.identityZones()
.list(ListIdentityZonesRequest.builder()
.build()))
.flatMapIterable(ListIdentityZonesResponse::getIdentityZones)
.filter(resource -> identityZoneName.equals(resource.getName()))
.as(StepVerifier::create)
.expectNextCount(1)
.expectComplete()
.verify(Duration.ofMinutes(5));
}
@Test
public void update() {
String identityZoneName = this.nameFactory.getIdentityZoneName();
String baseSubdomainName = this.nameFactory.getDomainName();
String newSubdomainName = this.nameFactory.getDomainName();
getIdentityZoneId(this.uaaClient, identityZoneName, baseSubdomainName)
.flatMap(identityZoneId -> this.uaaClient.identityZones()
.update(UpdateIdentityZoneRequest.builder()
.identityZoneId(identityZoneId)
.name(identityZoneName)
.subdomain(newSubdomainName)
.build()))
.then(requestListIdentityZones(this.uaaClient))
.flatMapIterable(ListIdentityZonesResponse::getIdentityZones)
.filter(resource -> newSubdomainName.equals(resource.getSubdomain()))
.as(StepVerifier::create)
.expectNextCount(1)
.expectComplete()
.verify(Duration.ofMinutes(5));
}
private static Mono<String> getIdentityZoneId(UaaClient uaaClient, String identityZoneName, String subdomainName) {
return requestCreateIdentityZone(uaaClient, identityZoneName, subdomainName)
.map(CreateIdentityZoneResponse::getId);
}
private static Mono<CreateIdentityZoneResponse> requestCreateIdentityZone(UaaClient uaaClient, String identityZoneName, String subdomainName) {
return uaaClient.identityZones()
.create(CreateIdentityZoneRequest.builder()
.subdomain(subdomainName)
.name(identityZoneName)
.build());
}
private static Mono<ListIdentityZonesResponse> requestListIdentityZones(UaaClient uaaClient) {
return uaaClient.identityZones()
.list(ListIdentityZonesRequest.builder()
.build());
}
}
| true
|
2835bfb1dc0025ffd0b0d089b7e6465f5dfb0124
|
Java
|
bohan2345/LeetcodeSolutions
|
/src/test/java/linkedlist/RemoveLinkedListElementsTest.java
|
UTF-8
| 535
| 2.5
| 2
|
[] |
no_license
|
package linkedlist;
import org.junit.Test;
import utils.LinkedListUtils;
import utils.ListNode;
import static org.junit.Assert.assertEquals;
/**
* <p>
* Created by Bohan Zheng on 2/9/2016.
*
* @author Bohan Zheng
*/
public class RemoveLinkedListElementsTest {
@Test
public void test() {
RemoveLinkedListElements test = new RemoveLinkedListElements();
ListNode head = LinkedListUtils.constructLinkedList(1, 2, 1, 4, 1);
assertEquals("2,4", LinkedListUtils.serialize(test.removeElements(head, 1)));
}
}
| true
|
42815d30fb2064b8dc65e5f5ab91333e7a43ef83
|
Java
|
wuyanshen/aispringcloud
|
/configclient/src/main/java/com/southwind/ConfigclientApplication.java
|
UTF-8
| 416
| 1.5625
| 2
|
[] |
no_license
|
package com.southwind;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author wuyanshen
* @date 2020-02-05 11:51 下午
* @discription 启动类
*/
@SpringBootApplication
public class ConfigclientApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigclientApplication.class, args);
}
}
| true
|
68380d0ed7a77bf764e38c804d8c68e0560b2e18
|
Java
|
EasyFlight/ezfl-api
|
/src/main/java/com/easyflight/flight/repository/FlightsRepository.java
|
UTF-8
| 442
| 1.59375
| 2
|
[] |
no_license
|
package com.easyflight.flight.repository;
import com.easyflight.flight.entity.Flight;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.querydsl.QueryDslPredicateExecutor;
import org.springframework.stereotype.Repository;
/**
* Created by johnson on 6/22/17.
*/
@Repository
public interface FlightsRepository extends MongoRepository<Flight, String> , QueryDslPredicateExecutor<Flight> {
}
| true
|
0469835f5b128a6eff5f4157961ff6d6c435f02a
|
Java
|
sonvt1710/swagger-parser
|
/modules/swagger-parser-v3/src/test/java/io/swagger/v3/parser/test/AnchorTest.java
|
UTF-8
| 5,822
| 2.203125
| 2
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
package io.swagger.v3.parser.test;
import io.swagger.v3.core.util.Json;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.parser.OpenAPIV3Parser;
import io.swagger.v3.parser.core.models.ParseOptions;
import io.swagger.v3.parser.core.models.SwaggerParseResult;
import io.swagger.v3.parser.util.DeserializationUtils;
import org.testng.annotations.Test;
import java.util.Arrays;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
public class AnchorTest {
@Test
public void testIssue146() {
String yaml = "openapi: 3.0.0\n" +
"servers: []\n" +
"info:\n" +
" version: 0.0.1\n" +
" title: API\n" +
"x-types:\n" +
" OperationType: &OperationType\n" +
" - registration\n" +
"# Describe your paths here\n" +
"paths:\n" +
" /checker:\n" +
" get:\n" +
" parameters:\n" +
" - name: operations\n" +
" in: query\n" +
" schema:\n" +
" type: array\n" +
" items:\n" +
" type: string\n" +
" enum: *OperationType\n" +
" default:\n" +
" - registration\n" +
" responses:\n" +
" '200':\n" +
" description: OK\n" +
" content:\n" +
" '*/*':\n" +
" schema:\n" +
" $ref: '#/components/schemas/OperationType'\n" +
"components:\n" +
" schemas:\n" +
" OperationType:\n" +
" type: string\n" +
" enum: *OperationType";
SwaggerParseResult result = new OpenAPIV3Parser().readContents(yaml,null,null);
Schema model = result.getOpenAPI().getComponents().getSchemas().get("OperationType");
assertEquals(model.getEnum(), Arrays.asList("registration"));
}
@Test
public void testCycle() {
String yaml = "a:\n" +
" a1: &a1\n" +
" a2: \n" +
" - a3\n" +
" - a4\n" +
" a5: \n" +
" - *a1";
SwaggerParseResult result = new OpenAPIV3Parser().readContents(yaml,null,null);
assertEquals(Json.pretty(result.getOpenAPI()), "null");
}
@Test
public void testIssue998() throws Exception{
//DeserializationUtils.getOptions().setMaxYamlDepth(5000);
SwaggerParseResult result = new OpenAPIV3Parser().readLocation("./issue_998.yaml",null,null);
assertNull(result.getOpenAPI());
}
@Test
public void testIssue998Billion() throws Exception{
DeserializationUtils.getOptions().setMaxYamlReferences(100000L);
String yaml = "a: &a [\"lol\",\"lol\",\"lol\",\"lol\",\"lol\",\"lol\",\"lol\",\"lol\",\"lol\"]\n" +
"b: &b [*a,*a,*a,*a,*a,*a,*a,*a,*a]\n" +
"c: &c [*b,*b,*b,*b,*b,*b,*b,*b,*b]\n" +
"d: &d [*c,*c,*c,*c,*c,*c,*c,*c,*c]\n" +
"e: &e [*d,*d,*d,*d,*d,*d,*d,*d,*d]\n" +
"f: &f [*e,*e,*e,*e,*e,*e,*e,*e,*e]\n" +
"g: &g [*f,*f,*f,*f,*f,*f,*f,*f,*f]\n" +
"h: &h [*g,*g,*g,*g,*g,*g,*g,*g,*g]\n" +
"i: &i [*h,*h,*h,*h,*h,*h,*h,*h,*h]";
String yaml2 = "a: &a [\"lol\",\"lol\",\"lol\",\"lol\",\"lol\",\"lol\",\"lol\",\"lol\",\"lol\"]\n" +
"b: &b [*a,*a,*a,*a,*a,*a,*a,*a,*a]\n" +
"c: &c [*b,*b,*b,*b,*b,*b,*b,*b,*b]\n" +
"d: &d [*c,*c,*c,*c,*c,*c,*c,*c,*c]\n" +
"e: &e [*d,*d,*d,*d,*d,*d,*d,*d,*d]\n" +
"f: &f [*e,*e,*e,*e,*e,*e,*e,*e,*e]\n" +
"g: &g [*f,*f,*f,*f,*f,*f,*f,*f,*f]\n" +
"h: &h [*g,*g,*g,*g,*g,*g,*g,*g,*g]";
String yaml3 = "a: &a [\"lol\"]\n" +
"b: &b [*a,*a]\n" +
"c: &c [*b,*b]";
OpenAPI result = new OpenAPIV3Parser().readContents(yaml,null,null).getOpenAPI();
assertEquals(Json.pretty(result), "null");
result = new OpenAPIV3Parser().readContents(yaml2,null,null).getOpenAPI();
assertEquals(Json.pretty(result), "null");
DeserializationUtils.getOptions().setMaxYamlReferences(10000000L);
}
@Test
public void testBillionLaughProtectionSnakeYaml() {
ParseOptions opts = new ParseOptions();
opts.setResolve(true);
SwaggerParseResult result = new OpenAPIV3Parser().readLocation("billion_laughs_snake_yaml.yaml",null,opts);
assertNotNull(result.getOpenAPI().getComponents().getSchemas().get("a1"));
assertEquals(result.getOpenAPI().getComponents().getSchemas().get("a1").getEnum().get(0), "AA1");
assertNotNull(result.getOpenAPI().getComponents().getSchemas().get("c1"));
assertEquals(((Schema)result.getOpenAPI().getComponents().getSchemas().get("c1").getProperties().get("a")).getEnum().get(0), "AA1");
DeserializationUtils.getOptions().setMaxYamlAliasesForCollections(50);
DeserializationUtils.getOptions().setYamlAllowRecursiveKeys(false);
result = new OpenAPIV3Parser().readLocation("billion_laughs_snake_yaml.yaml",null,opts);
DeserializationUtils.getOptions().setMaxYamlAliasesForCollections(Integer.MAX_VALUE);
DeserializationUtils.getOptions().setYamlAllowRecursiveKeys(true);
}
}
| true
|
3d4f51e2df73a98eff80afa9318a671b7f6c9f76
|
Java
|
santos-gabriel/scm
|
/src/controllers/CtrlProdutosCompra.java
|
UTF-8
| 477
| 1.664063
| 2
|
[] |
no_license
|
/*
* 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 controllers;
import dao.ProdutosCompraDao;
import modelo.ProdutosCompra;
/**
*
* @author Gabriel
*/
public abstract class CtrlProdutosCompra {
public static void Inserir(ProdutosCompra prProdutosCompra){
ProdutosCompraDao.Inserir(prProdutosCompra);
}
}
| true
|
59f4165ab5f55ece63fb415c2252f4108df86ac0
|
Java
|
fallin123/yingsuo
|
/seal/src/main/java/cn/yingsuo/im/ui/activity/SearchFriendActivity.java
|
UTF-8
| 10,349
| 1.671875
| 2
|
[
"MIT"
] |
permissive
|
package cn.yingsuo.im.ui.activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import cn.yingsuo.im.App;
import cn.yingsuo.im.R;
import cn.yingsuo.im.SealAppContext;
import cn.yingsuo.im.SealConst;
import cn.yingsuo.im.SealUserInfoManager;
import cn.yingsuo.im.db.Friend;
import cn.yingsuo.im.server.network.async.AsyncTaskManager;
import cn.yingsuo.im.server.network.http.HttpException;
import cn.yingsuo.im.server.response.FriendInvitationResponse;
import cn.yingsuo.im.server.response.GetUserInfoByPhoneResponse;
import cn.yingsuo.im.server.response.UserInfoResponse;
import cn.yingsuo.im.server.utils.CommonUtils;
import cn.yingsuo.im.server.utils.NToast;
import cn.yingsuo.im.server.widget.DialogWithYesOrNoUtils;
import cn.yingsuo.im.server.widget.LoadDialog;
import cn.yingsuo.im.server.widget.SelectableRoundedImageView;
import cn.yingsuo.im.ui.adapter.AddFrendSearchAdapter;
public class SearchFriendActivity extends BaseActivity {
private static final int CLICK_CONVERSATION_USER_PORTRAIT = 1;
private static final int SEARCH_PHONE = 10;
private static final int ADD_FRIEND = 11;
private EditText mEtSearch;
private LinearLayout searchItem;
private RecyclerView frendResultRv;
private Button searchBtn;
private TextView searchName;
private SelectableRoundedImageView searchImage;
private String mPhone;
private String addFriendMessage;
private String mFriendId;
private String mUid;
private AddFrendSearchAdapter addFrendSearchAdapter;
private List<UserInfoResponse> searchFrendList;
private Friend mFriend;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
setTitle((R.string.search_friend));
searchBtn = (Button) findViewById(R.id.add_frend_search_btn);
mEtSearch = (EditText) findViewById(R.id.search_edit);
searchItem = (LinearLayout) findViewById(R.id.search_result);
searchName = (TextView) findViewById(R.id.search_name);
searchImage = (SelectableRoundedImageView) findViewById(R.id.search_header);
searchBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mPhone = mEtSearch.getText().toString().trim();
if ("".equals(mPhone)) {
NToast.longToast(SearchFriendActivity.this, "搜索内容不能为空");
return;
}
hintKbTwo();
LoadDialog.show(mContext);
request(SEARCH_PHONE, true);
}
});
initResultRecyclerView();
}
private void initResultRecyclerView() {
frendResultRv = (RecyclerView) findViewById(R.id.add_frend_result_rv);
addFrendSearchAdapter = new AddFrendSearchAdapter(this);
searchFrendList = new ArrayList<>();
frendResultRv.setAdapter(addFrendSearchAdapter);
frendResultRv.setLayoutManager(new LinearLayoutManager(this));
addFrendSearchAdapter.notifyList(searchFrendList);
addFrendSearchAdapter.setOnItemClickListener(new AddFrendSearchAdapter.OnItemClickListener() {
@Override
public void onItemClick(int position) {
mFriendId = searchFrendList.get(position).getId();
if (isFriendOrSelf(mFriendId)) {
Intent intent = new Intent(SearchFriendActivity.this, UserDetailActivity.class);
intent.putExtra("friend", mFriend);
intent.putExtra("type", CLICK_CONVERSATION_USER_PORTRAIT);
startActivity(intent);
SealAppContext.getInstance().pushActivity(SearchFriendActivity.this);
return;
}
DialogWithYesOrNoUtils.getInstance().showEditDialog(mContext, getString(R.string.add_text), getString(R.string.add_friend), new DialogWithYesOrNoUtils.DialogCallBack() {
@Override
public void executeEvent() {
}
@Override
public void updatePassword(String oldPassword, String newPassword) {
}
@Override
public void executeEditEvent(String editText) {
if (!CommonUtils.isNetworkConnected(mContext)) {
NToast.shortToast(mContext, R.string.network_not_available);
return;
}
addFriendMessage = editText;
if (TextUtils.isEmpty(editText)) {
addFriendMessage = "我是" + getSharedPreferences("config", MODE_PRIVATE).getString(SealConst.SEALTALK_LOGIN_NAME, "");
}
UserInfoResponse userInfoResponse = App.getUserInfoResponse();
if (null != userInfoResponse) {
mUid = userInfoResponse.getId();
}
if (!TextUtils.isEmpty(mFriendId)) {
LoadDialog.show(mContext);
request(ADD_FRIEND);
} else {
NToast.shortToast(mContext, "id is null");
}
}
});
}
});
}
@Override
public Object doInBackground(int requestCode, String id) throws HttpException {
switch (requestCode) {
case SEARCH_PHONE:
return action.getUserInfoFromPhone(mPhone);
case ADD_FRIEND:
return action.sendFriendInvitation(mUid, mFriendId);
}
return super.doInBackground(requestCode, id);
}
@Override
public void onSuccess(int requestCode, Object result) {
if (result != null) {
switch (requestCode) {
case SEARCH_PHONE:
final GetUserInfoByPhoneResponse userInfoByPhoneResponse = (GetUserInfoByPhoneResponse) result;
if (userInfoByPhoneResponse.getCode() == 1) {
LoadDialog.dismiss(mContext);
searchFrendList = userInfoByPhoneResponse.getRes();
if (null != searchFrendList) {
addFrendSearchAdapter.notifyList(searchFrendList);
}
} else if (userInfoByPhoneResponse.getCode() == 120) {
LoadDialog.dismiss(mContext);
searchFrendList.clear();
if (null != searchFrendList) {
addFrendSearchAdapter.notifyList(searchFrendList);
}
NToast.shortToast(mContext, userInfoByPhoneResponse.getMsg());
} else {
LoadDialog.dismiss(mContext);
NToast.shortToast(mContext, userInfoByPhoneResponse.getMsg());
}
break;
case ADD_FRIEND:
FriendInvitationResponse fres = (FriendInvitationResponse) result;
if (fres.getCode() == 1) {
NToast.shortToast(mContext, getString(R.string.request_success));
LoadDialog.dismiss(mContext);
} else {
NToast.shortToast(mContext, fres.getMsg());
LoadDialog.dismiss(mContext);
}
break;
}
}
}
@Override
public void onFailure(int requestCode, int state, Object result) {
switch (requestCode) {
case ADD_FRIEND:
NToast.shortToast(mContext, "你们已经是好友");
LoadDialog.dismiss(mContext);
break;
case SEARCH_PHONE:
if (state == AsyncTaskManager.HTTP_ERROR_CODE || state == AsyncTaskManager.HTTP_NULL_CODE) {
super.onFailure(requestCode, state, result);
} else {
NToast.shortToast(mContext, "用户不存在");
}
LoadDialog.dismiss(mContext);
break;
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
hintKbTwo();
finish();
return super.onOptionsItemSelected(item);
}
private void hintKbTwo() {
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
if (imm.isActive() && getCurrentFocus() != null) {
if (getCurrentFocus().getWindowToken() != null) {
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
}
private boolean isFriendOrSelf(String id) {
String inputPhoneNumber = mEtSearch.getText().toString().trim();
SharedPreferences sp = getSharedPreferences("config", MODE_PRIVATE);
String selfPhoneNumber = sp.getString(SealConst.SEALTALK_LOGING_PHONE, "");
if (inputPhoneNumber != null) {
if (inputPhoneNumber.equals(selfPhoneNumber)) {
mFriend = new Friend(sp.getString(SealConst.SEALTALK_LOGIN_ID, ""),
sp.getString(SealConst.SEALTALK_LOGIN_NAME, ""),
Uri.parse(sp.getString(SealConst.SEALTALK_LOGING_PORTRAIT, "")));
return true;
} else {
mFriend = SealUserInfoManager.getInstance().getFriendByID(id);
if (mFriend != null) {
return true;
}
}
}
return false;
}
}
| true
|
e4cf936c298ddf026a38aac86d36301c468c5248
|
Java
|
DariushN/HuffmanEncoder
|
/A3COMP352/src/Tree.java
|
UTF-8
| 1,096
| 3.53125
| 4
|
[] |
no_license
|
public class Tree{
static class Node {
protected char character;
protected int data;
protected int characterFrequency;
protected Node leftChild;
protected Node rightChild;
protected int position;
protected Node parent;
Node(final char ch, int freq, Node left, Node right,int position) {
this.character = ch;
this.characterFrequency = freq;
this.leftChild = left;
this.rightChild = right;
data='\0';
this.position=position;
}
public Node(int data) {
this.data = data;
leftChild = null;
rightChild = null;
parent=null;
character='\0';
characterFrequency='\0';
}
boolean isLeaf() {
return leftChild == null && rightChild == null;
}
public void print(){
System.out.println(character+" and "+characterFrequency+" freq");
}
}
public Node root;
public Tree(){
this.root = null;
}
}
| true
|
4e795170c2f9c0ee1d5ef04002674bf6de3b4340
|
Java
|
lsclgr/Tutor-Virtual
|
/dao/AlternativaDAO.java
|
UTF-8
| 3,276
| 2.875
| 3
|
[] |
no_license
|
package dao;
import ferramentas.FabricaConexao;
import ferramentas.LoggerCustomizado;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import modelo.Alternativa;
public class AlternativaDAO {
//private static Logger log = LoggerCustomizado.criaLog(AlternativaDAO.class.getName());
/**
* Método que recupera uma alternativa pelo seu id.
*
* @author Iago Izidorio Lacerda
* @param idAlternativa int - id da alternativa que você vai recuperar.
* @return Alternativa - alternativa recuperada.
*/
public static Alternativa buscaAlternativaId(int idAlternativa) {
Alternativa a = null;
try (Connection conexao = FabricaConexao.criaConexao()) {
String sql = "select * from alternativa where alternativa.id = ?";
PreparedStatement x = conexao.prepareStatement(sql);
x.setInt(1, idAlternativa);
ResultSet info = x.executeQuery();
info.next();
a = new Alternativa(info.getString("enunciado"), info.getString("dica"), info.getInt("id"), info.getInt("id_questao"));
} catch (SQLException ex) {
System.out.println("Erro na execução da sql - buscaAlternativaId.");
//log.log(Level.FINE, null, ex);
}finally{
FabricaConexao.encerraConexao();
}
return a;
}
public static List<Alternativa> buscaAlternativasQuestao(int idQuestao) {
List<Alternativa> listaAlternativas = new ArrayList<>();
try (Connection conexao = FabricaConexao.criaConexao()) {
String sql = "select * from alternativa where alternativa.id_questao = ?";
PreparedStatement x = conexao.prepareStatement(sql);
x.setInt(1, idQuestao);
ResultSet info = x.executeQuery();
while (info.next()) {
Alternativa a = new Alternativa(info.getString("enunciado"), info.getString("dica"), info.getInt("id"), info.getInt("id_questao"));
listaAlternativas.add(a);
System.out.println(a.toString());
//log.log(Level.FINE, a.toString());
}
} catch (SQLException ex) {
System.out.println("Erro na execução da sql - buscaAlternativasQuestao.");
//ex.printStackTrace();
//log.log(Level.FINE, null, ex);
//log.log(Level.FINE, "Erro na execução da sql - buscaAlternativasQuestao.");
}finally{
FabricaConexao.encerraConexao();
}
return listaAlternativas;
}
public static boolean cadastraAlternativas(List<Alternativa> alternativas) {
try (Connection conexao = FabricaConexao.criaConexao()) {
} catch (SQLException ex) {
System.out.println("Erro na execução da sql - cadastraAlternativas.");
//log.log(Level.FINE, "Erro na execução da sql - cadastraAlternativas.");
}finally{
FabricaConexao.encerraConexao();
}
return false;
}
}
| true
|
2c9c8f83e384ff6cdc93cf3f859cb1e0848f2fa5
|
Java
|
soltrix/JavaCoreProfessional
|
/JavaCoreProfessional_Solodkov_homework3/src/main/java/ru/solodkov/javacoreprofessional/App.java
|
UTF-8
| 2,625
| 3.09375
| 3
|
[] |
no_license
|
package ru.solodkov.javacoreprofessional;
import java.io.*;
import java.util.*;
public class App {
public static void main(String[] args) {
// task 1
fileStream();
// task 2
sequenceStream();
// task 3
readBook();
}
private static void fileStream() {
File file = new File("task1hw3.txt");
try (FileInputStream into = new FileInputStream(file)) {
byte[] bw = new byte[50];
into.read(bw);
System.out.println(Arrays.toString(bw));
} catch (IOException e) {
e.printStackTrace();
}
}
private static void sequenceStream() {
try (FileInputStream in1 = new FileInputStream("task2hw3_1.txt");
FileInputStream in2 = new FileInputStream("task2hw3_2.txt");
FileInputStream in3 = new FileInputStream("task2hw3_3.txt");
FileInputStream in4 = new FileInputStream("task2hw3_4.txt");
FileInputStream in5 = new FileInputStream("task2hw3_5.txt");
FileOutputStream out = new FileOutputStream("task2hw3_out.txt")) {
ArrayList<InputStream> al = new ArrayList<>();
al.add(in1);
al.add(in2);
al.add(in3);
al.add(in4);
al.add(in5);
Enumeration<InputStream> e = Collections.enumeration(al);
SequenceInputStream seq = new SequenceInputStream(e);
int rb;
while ((rb = seq.read()) != -1) {
out.write(rb);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void readBook() {
Scanner sc = new Scanner(System.in);
File file = new File("Thinking in Java 4th Edition.txt");
int pageLength = 1800;
int pages = (int) file.length()/pageLength;
byte[] buffer = new byte[pageLength];
System.out.println("В книге " + pages + " страниц");
System.out.println("Введите номер страницы, которую Вы хотите прочитать:");
int page = 0;
do {
System.out.print(pages);
page = sc.nextInt();
if (page > 0)
try (RandomAccessFile acces = new RandomAccessFile(file, "r")) {
acces.seek((page - 1) * pageLength);
acces.read(buffer);
System.out.print(new String(buffer));
} catch (IOException ex) {
ex.printStackTrace();
}
} while (page != 0);
}
}
| true
|
f9726916d2d3f533a2140ed10e11fe4359266a38
|
Java
|
JiaoPengJob/TechPro
|
/DrivingTest/app/src/main/java/cn/hongjitech/vehicle/activity/TestActivity.java
|
UTF-8
| 1,842
| 2.171875
| 2
|
[] |
no_license
|
package cn.hongjitech.vehicle.activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import butterknife.ButterKnife;
import butterknife.InjectView;
import cn.hongjitech.vehicle.R;
public class TestActivity extends BaseActivity {
@InjectView(R.id.bt_carInfoTest)
Button bt_carInfoTest;
@InjectView(R.id.bt_serialportTest)
Button bt_serialportTest;
@InjectView(R.id.bt_examInfoTest)
Button bt_examInfoTest;
private Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_test);
ButterKnife.inject(TestActivity.this);
initListener();
}
/**
* 加载点击事件监听函数
*/
private void initListener() {
bt_carInfoTest.setOnClickListener(new ClickListener());
bt_serialportTest.setOnClickListener(new ClickListener());
bt_examInfoTest.setOnClickListener(new ClickListener());
}
/**
* 声明点击事件监听类
*/
class ClickListener implements View.OnClickListener {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bt_carInfoTest:
intent = new Intent(TestActivity.this, CarDataActivity.class);
startActivity(intent);
break;
case R.id.bt_serialportTest:
intent = new Intent(TestActivity.this, TestDrivesActivity.class);
startActivity(intent);
break;
case R.id.bt_examInfoTest:
break;
}
}
}
}
| true
|
3a12eaeab3e3546fbdf5a4e71e67a57f64eac848
|
Java
|
projeto-aplicado/PointStorePA3
|
/front-end-android/PointStore/app/src/main/java/br/com/pointstore/HistoricoCompras.java
|
UTF-8
| 3,547
| 1.960938
| 2
|
[] |
no_license
|
package br.com.pointstore;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import br.com.pointstore.Adapter.ListaDeComprasAdapter;
import br.com.pointstore.Adapter.ListaDeVendasAdapter;
import br.com.pointstore.Adapter.Vendas3;
import br.com.pointstore.Adapter.Vendas4;
import br.com.pointstore.model.Vendas;
import rest.VendasService;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;
public class HistoricoCompras extends AppCompatActivity {
private ListView listviewdecompras;
private ArrayList<Vendas4> listaDeCompras = new ArrayList<>();
private VendasService mVendasService;
private String idUsuario;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_historico_compras);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://10.0.3.2")
.addConverterFactory(JacksonConverterFactory.create())
.build();
this.mVendasService = retrofit.create(VendasService.class);
Bundle bundle = getIntent().getExtras();
idUsuario = bundle.getString("id_usuario");
listviewdecompras = (ListView) findViewById(R.id.listviewdecompras);
Call<List<Vendas4>> listarTodasComprasUsuario = mVendasService.listarTodasComprasUsuario(idUsuario);
listarTodasComprasUsuario.enqueue(new Callback<List<Vendas4>>() {
@Override
public void onResponse(Call<List<Vendas4>> call, Response<List<Vendas4>> response) {
listaDeCompras = (ArrayList<Vendas4>) response.body();
if(listaDeCompras.isEmpty()){
AlertDialog.Builder adb = new AlertDialog.Builder(HistoricoCompras.this);
adb.setTitle("ATENÇÃO !");
adb.setMessage("Seu histórico de compras está vazio!");
adb.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
//Toast.makeText(HistoricoCompras.this, "Você clicou no botão Ok", Toast.LENGTH_SHORT).show();
Intent finalizarCompra = new Intent(HistoricoCompras.this, ListarAnunciosActivity.class);
startActivity(finalizarCompra);
}
});
adb.show();
}else {
final ListaDeComprasAdapter adaptadorListaResponse =
new ListaDeComprasAdapter(HistoricoCompras.this,
R.layout.adapter_view_compras_layout,listaDeCompras);
listviewdecompras.setAdapter(adaptadorListaResponse);
}
}
@Override
public void onFailure(Call<List<Vendas4>> call, Throwable t) {
String TAG_E = "Erro na Requisição";
Log.v(TAG_E, ""+t);
Toast.makeText(getApplication(), "ERRO "+t,
Toast.LENGTH_LONG).show();
}
});
}
}
| true
|
51028ceeff5060986fbe07f1523a2a361fe3733f
|
Java
|
cutting-dsa/karuna-pages
|
/src/test/java/com/karuna/pages/review/service/ReviewServiceImplementationTest.java
|
UTF-8
| 4,686
| 2.21875
| 2
|
[] |
no_license
|
package com.karuna.pages.review.service;
import com.karuna.pages.category.model.Category;
import com.karuna.pages.listing.model.Listing;
import com.karuna.pages.listing.repository.ListingRepository;
import com.karuna.pages.review.model.Review;
import com.karuna.pages.review.repository.ReviewRepository;
import com.karuna.pages.role.model.Role;
import com.karuna.pages.user.model.AppUser;
import org.junit.Assert;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
@ExtendWith(SpringExtension.class)
public class ReviewServiceImplementationTest {
@Mock
ReviewRepository reviewRepository;
@Mock
ListingRepository listingRepository;
@InjectMocks
ReviewServiceImplementation reviewService;
private Listing stubListing(){
Category category1 = new Category(1L,"Education",1);
Role role = new Role(2L,"User");
List<Role> roleList = new ArrayList<>();
roleList.add(role);
AppUser appUser = new AppUser(1L,"Ruvimbom","Ruvimbo","Ruvimbo","Ruvimbom",1,roleList);
Listing listing = new Listing(1L,"Jefferson",1,"someAddress",123.2,321.1,"banner.png","icon.png",0,1,appUser,category1,null);
return listing;
}
private Review stubReview(){
Role role = new Role(2L,"User");
List<Role> roleList = new ArrayList<>();
roleList.add(role);
AppUser appUser = new AppUser(1L,"Ruvimbom","Ruvimbo","Ruvimbo","Ruvimbom",1,roleList);
Review review = new Review(1L,"This is my comment",4,1,appUser,stubListing());
return review;
}
@Test
void getAllReviewTest() {
List<Review> reviewList = new ArrayList<>();
reviewList.add(stubReview());
when(reviewRepository.findAllByStatus(anyInt())).thenReturn(reviewList);
Collection<Review> reviews = reviewService.getAllReview();
Assert.assertEquals(reviewList.size(), reviews.size());
ArrayList<Review> actualResult = new ArrayList<>(reviews);
Assert.assertEquals(reviewList.get(0).getComment(), actualResult.get(0).getComment());
verify(reviewRepository, times(1)).findAllByStatus(1);
}
@Test
void getAllReviewsByListingTest() {
List<Review> reviewList = new ArrayList<>();
reviewList.add(stubReview());
when(reviewRepository.findAllByListingAndStatus(any(Listing.class),anyInt())).thenReturn(reviewList);
Collection<Review> reviews = reviewService.getAllReviewsByListing(stubListing());
Assert.assertEquals(reviewList.size(), reviews.size());
ArrayList<Review> actualResult = new ArrayList<>(reviews);
Assert.assertEquals(reviewList.get(0).getComment(), actualResult.get(0).getComment());
verify(reviewRepository, times(1)).findAllByListingAndStatus(any(Listing.class),anyInt());
}
@Test
void getReviewTest() {
when(reviewRepository.getReviewById(anyLong())).thenReturn(stubReview());
Review actualResult = reviewService.getReview(1L);
Assertions.assertEquals("This is my comment",actualResult.getComment());
Assertions.assertEquals(1,actualResult.getStatus());
}
@Test
void saveReviewTest() {
List<Review> reviewList = new ArrayList<>();
reviewList.add(stubReview());
when(listingRepository.getListingById(anyLong())).thenReturn(stubListing());
when(reviewRepository.getReviewById(anyLong())).thenReturn(stubReview());
when(reviewRepository.findAllByListingAndStatus(any(Listing.class),anyInt())).thenReturn(reviewList);
reviewService.saveReview(stubReview());
verify(reviewRepository, times(1)).save(any(Review.class));
}
@Test
void editReviewTest() {
when(reviewRepository.getReviewById(anyLong())).thenReturn(stubReview());
reviewService.editReview(1L,stubReview());
verify(reviewRepository, times(1)).save(any(Review.class));
}
@Test
void deleteReviewTest() {
when(reviewRepository.getReviewById(anyLong())).thenReturn(stubReview());
when(reviewRepository.save(any(Review.class))).thenReturn(stubReview());
Review expected = reviewService.deleteReview(1L);
Assertions.assertEquals(0,expected.getStatus());
verify(reviewRepository, times(1)).getReviewById(1L);
}
}
| true
|
edde0015ef399414ee650dc8fa5d84420c72dce8
|
Java
|
chengjingming060241/bllc
|
/gizwits-lease-master/gizwits-lease-service/src/main/java/com/gizwits/lease/device/service/impl/DeviceLaunchAreaServiceImpl.java
|
UTF-8
| 18,384
| 1.8125
| 2
|
[] |
no_license
|
package com.gizwits.lease.device.service.impl;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.gizwits.boot.dto.Pageable;
import com.gizwits.boot.enums.DeleteStatus;
import com.gizwits.boot.exceptions.SysExceptionEnum;
import com.gizwits.boot.exceptions.SystemException;
import com.gizwits.boot.sys.entity.SysUser;
import com.gizwits.boot.sys.service.SysRoleService;
import com.gizwits.boot.sys.service.SysUserService;
import com.gizwits.boot.utils.*;
import com.gizwits.lease.config.CommonSystemConfig;
import com.gizwits.lease.device.dao.DeviceLaunchAreaDao;
import com.gizwits.lease.device.entity.Device;
import com.gizwits.lease.device.entity.DeviceLaunchArea;
import com.gizwits.lease.device.entity.dto.*;
import com.gizwits.lease.device.service.DeviceLaunchAreaService;
import com.gizwits.lease.device.service.DeviceService;
import com.gizwits.lease.device.vo.DeviceLaunchAreaCountVo;
import com.gizwits.lease.event.NameModifyEvent;
import com.gizwits.lease.event.OperatorStatusChangeEvent;
import com.gizwits.lease.exceptions.LeaseExceEnums;
import com.gizwits.lease.exceptions.LeaseException;
import com.gizwits.lease.manager.dto.AgentForUpdateDto;
import com.gizwits.lease.manager.entity.Agent;
import com.gizwits.lease.manager.entity.Operator;
import com.gizwits.lease.product.service.ProductDataPointService;
import com.gizwits.lease.user.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import sun.management.resources.agent;
import static org.hibernate.validator.internal.util.Contracts.assertNotNull;
/**
* <p>
* 设备投放点表 服务实现类
* </p>
*
* @author yinhui
* @since 2017-07-12
*/
@Service
public class DeviceLaunchAreaServiceImpl extends ServiceImpl<DeviceLaunchAreaDao, DeviceLaunchArea> implements DeviceLaunchAreaService {
protected Logger logger = LoggerFactory.getLogger("LEASE_LOGGER");
@Autowired
private SysUserService sysUserService;
@Autowired
private DeviceService deviceService;
@Autowired
private SysRoleService sysRoleService;
@Override
public boolean addDeviceLaunchArea(DeviceLaunchArea deviceLaunchArea) {
SysUser sysUser = sysUserService.getCurrentUserOwner();
deviceLaunchArea.setSysUserId(sysUser.getId());
deviceLaunchArea.setSysUserName(sysUser.getUsername());
deviceLaunchArea.setOwnerId(sysUser.getId());
deviceLaunchArea.setUtime(new Date());
deviceLaunchArea.setCtime(new Date());
String name = deviceLaunchArea.getName();
if (ParamUtil.isNullOrEmptyOrZero(name)) {
throw new SystemException(SysExceptionEnum.ILLEGAL_PARAM.getCode(), SysExceptionEnum.ILLEGAL_PARAM.getMessage());
}
return insert(deviceLaunchArea);
}
private String getPictureUrl(MultipartFile file) {
String pictureUrl = "";
if (file != null) {
try {
if (!file.getOriginalFilename().contains(".")) {
LeaseException.throwSystemException(LeaseExceEnums.PICTURE_SUFFIX_ERROR);
}
if (!PictureUtils.checkFile(file.getOriginalFilename())) {
LeaseException.throwSystemException(LeaseExceEnums.PICTURE_SUFFIX_ERROR);
}
String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
String newFilename = UUID.randomUUID() + suffix;
//这里暂时注释掉
// File newFile = new File(SysConfigUtils.get(CommonSystemConfig.class).getLaunchAreaImagePath() + newFilename);
File newFile = new File("G:\\data\\lease\\files\\launch-area\\images\\" + newFilename);
File dir = newFile.getParentFile();
if (!dir.exists()) {
dir.mkdirs();
}
//这里暂时注释掉
file.transferTo(newFile);
pictureUrl = SysConfigUtils.get(CommonSystemConfig.class).getLaunchAreaImageURL() + newFilename;
} catch (Exception ex) {
logger.error("==============>图片上传失败,原因:" + ex);
ex.printStackTrace();
LeaseException.throwSystemException(LeaseExceEnums.UPLOAD_ERROR);
}
}
return pictureUrl;
}
@Override
public String deleteDeviceLaunchAreas(List<Integer> areaId) {
SysUser current = sysUserService.getCurrentUserOwner();
List<Integer> userIds = sysUserService.resolveSysUserAllSubAdminIds(current);
List<String> fails = new LinkedList<>();
StringBuffer sb = new StringBuffer();
List<DeviceLaunchArea> deviceLaunchAreas = selectList(new EntityWrapper<DeviceLaunchArea>().eq("is_deleted", DeleteStatus.NOT_DELETED.getCode()).in("id", areaId));
for (DeviceLaunchArea deviceLaunchArea : deviceLaunchAreas) {
//判断是否拥有删除投放点的权限,能删除在列表看到的所有数据,防止调用接口乱删
if (userIds.contains(deviceLaunchArea.getSysUserId())) {
EntityWrapper<Device> entityWrapper1 = new EntityWrapper<>();
entityWrapper1.eq("launch_area_id", deviceLaunchArea.getId()).eq("is_deleted", DeleteStatus.NOT_DELETED.getCode());
if (deviceService.selectCount(entityWrapper1) <= 0) {
deviceLaunchArea.setIsDelete(DeleteStatus.DELETED.getCode());
deviceLaunchArea.setUtime(new Date());
updateById(deviceLaunchArea);
} else {
fails.add(deviceLaunchArea.getName());
}
} else {
fails.add(deviceLaunchArea.getName());
}
}
switch (fails.size()) {
case 0:
sb.append("删除成功");
break;
case 1:
sb.append("您欲删除的仓库[" + fails.get(0) + "]已有设备,请先转移设备并重试。");
break;
case 2:
sb.append("您欲删除的仓库[" + fails.get(0) + "],[" + fails.get(1) + "]已有设备,请先转移设备并重试。");
break;
default:
sb.append("您欲删除的仓库[" + fails.get(0) + "],[" + fails.get(1) + "]等已有设备,请先转移设备并重试。");
break;
}
return sb.toString();
}
@Override
public DeviceLaunchArea selectById(Integer id) {
return selectOne(new EntityWrapper<DeviceLaunchArea>().eq("id", id).eq("is_deleted", DeleteStatus.NOT_DELETED.getCode()));
}
@Override
public boolean updateDeviceLaunchArea( DeviceLaunchArea deviceLaunchArea) {
DeviceLaunchArea oldLaunch = getLaunchAreaInfoById(deviceLaunchArea.getId());
if (ParamUtil.isNullOrEmptyOrZero(oldLaunch)) {
LeaseException.throwSystemException(LeaseExceEnums.ENTITY_NOT_EXISTS);
}
String oldName = oldLaunch.getName();
deviceLaunchArea.setUtime(new Date());
String name = deviceLaunchArea.getName();
if (ParamUtil.isNullOrEmptyOrZero(name)) {
throw new SystemException(SysExceptionEnum.ILLEGAL_PARAM.getCode(), SysExceptionEnum.ILLEGAL_PARAM.getMessage());
}
boolean flag = updateById(deviceLaunchArea);
if (!oldName.equals(name)) {
NameModifyEvent<Integer> nameModifyEvent = new NameModifyEvent<Integer>(oldLaunch, oldLaunch.getId(), oldName, name);
publishEvent(nameModifyEvent);
}
return flag;
}
private void publishEvent(NameModifyEvent<Integer> nameModifyEvent) {
CommonEventPublisherUtils.publishEvent(nameModifyEvent);
}
public Page<DeviceLaunchAreaListDto> getDeviceLaunchAreaListPage(Pageable<DeviceLaunchAreaQueryDto> pageable) {
return getDeviceLaunchAreaListDtoPage(pageable, new Page<>(), new EntityWrapper<>());
}
@Override
public Page<DeviceLaunchAreaListDto> getUnAllotDeviceLaunchAreaListPage(Pageable<DeviceLaunchAreaQueryDto> pageable) {
Page<DeviceLaunchArea> page = new Page<>();
// page.setOrderByField("utime");
List<Integer> userIds = sysUserService.resolveSysUserAllSubAdminIds(sysUserService.getCurrentUserOwner());
EntityWrapper<DeviceLaunchArea> entityWrapper = new EntityWrapper<>();
entityWrapper.eq("status", 1)
.eq("is_deleted", DeleteStatus.NOT_DELETED.getCode())
.in("owner_id", userIds);
entityWrapper.orderBy("utime", false);
BeanUtils.copyProperties(pageable, page);
Page<DeviceLaunchArea> page1 = selectPage(page, entityWrapper);
Page<DeviceLaunchAreaListDto> result = new Page<>();
BeanUtils.copyProperties(page1, result);
List<DeviceLaunchAreaListDto> deviceLaunchAreaListDtoList = new ArrayList<>();
for (DeviceLaunchArea dla : page1.getRecords()) {
DeviceLaunchAreaListDto deviceLaunchAreaListDto = new DeviceLaunchAreaListDto();
deviceLaunchAreaListDto.setDeviceLaunchArea(dla);
Integer count = deviceService.countDeviceByDeviceLaunchAreaId(dla.getId());
deviceLaunchAreaListDto.setDeviceCount(count);
deviceLaunchAreaListDtoList.add(deviceLaunchAreaListDto);
}
result.setRecords(deviceLaunchAreaListDtoList);
return result;
}
private Page<DeviceLaunchAreaListDto> getDeviceLaunchAreaListDtoPage(Pageable<DeviceLaunchAreaQueryDto> pageable, Page<DeviceLaunchArea> page
, EntityWrapper<DeviceLaunchArea> wrapper) {
BeanUtils.copyProperties(pageable, page);
//修改时间
if (pageable.getQuery().getUpTimeStart()!=null && pageable.getQuery().getUpTimeEnd()!=null){
wrapper.between("utime",pageable.getQuery().getUpTimeStart(),pageable.getQuery().getUpTimeEnd());
}
Page<DeviceLaunchArea> deviceLaunchAreas = selectPage(page, QueryResolverUtils.parse(pageable.getQuery(), wrapper));
Page<DeviceLaunchAreaListDto> result = new Page<>();
BeanUtils.copyProperties(pageable, result);
List<Integer> userIds = sysUserService.resolveSysUserAllSubAdminIds(sysUserService.getCurrentUserOwner());
List<DeviceLaunchAreaListDto> deviceLaunchAreaListDtoList = new ArrayList<>();
for (DeviceLaunchArea dla : deviceLaunchAreas.getRecords()) {
DeviceLaunchAreaListDto deviceLaunchAreaListDto = new DeviceLaunchAreaListDto();
deviceLaunchAreaListDto.setDeviceLaunchArea(dla);
// Integer count = deviceService.countDeviceByDeviceLaunchAreaId(dla.getId());
// deviceLaunchAreaListDto.setDeviceCount(count);
deviceLaunchAreaListDto.setCurrentOwner(deviceService.resolveOwner(dla.getOwnerId()));
if (userIds.contains(dla.getOwnerId())) {
deviceLaunchAreaListDto.setCanModify(true);
}
deviceLaunchAreaListDtoList.add(deviceLaunchAreaListDto);
}
result.setRecords(deviceLaunchAreaListDtoList);
result.setTotal(deviceLaunchAreas.getTotal());
result.setCurrent(pageable.getCurrent());
return result;
}
/**
* if (CollectionUtils.isNotEmpty(deviceLaunchAreas.getRecords())) {
* result.setRecords(new ArrayList<>(deviceLaunchAreas.getRecords().size()));
* deviceLaunchAreas.getRecords().forEach(item -> {
*
* DeviceLaunchAreaListDto dto = new DeviceLaunchAreaListDto(item);
*
* result.getRecords().add(dto);
* result.setTotal(deviceLaunchAreas.getTotal());
* result.setCurrent(pageable.getCurrent());
* });
* }
* @param name
* @return
*/
@Override
public boolean deviceLaunchAreaIsExist(String name) {
EntityWrapper<DeviceLaunchArea> entityWrapper = new EntityWrapper<>();
entityWrapper.in("sys_user_id", sysUserService.resolveOwnerAccessableUserIds(sysUserService.getCurrentUser()))
.eq("name", name)
.eq("is_deleted", DeleteStatus.NOT_DELETED.getCode())
.eq("status", 1);
DeviceLaunchArea deviceLaunchArea = selectOne(entityWrapper);
return !ParamUtil.isNullOrEmptyOrZero(deviceLaunchArea);
}
public DeviceLaunchArea getLaunchAreaInfoById(Integer launchaAreaId) {
EntityWrapper<DeviceLaunchArea> entityWrapper = new EntityWrapper<>();
entityWrapper.eq("id", launchaAreaId).eq("is_deleted", 0);
return selectOne(entityWrapper);
}
@Override
public boolean checkIfBinded(Integer id) {
DeviceLaunchArea deviceLaunchArea = getLaunchAreaInfoById(id);
if (Objects.isNull(deviceLaunchArea)) {
return false;
}
return ParamUtil.isNullOrEmptyOrZero(deviceLaunchArea.getOperatorId());
}
@Override
public boolean change(DeviceLaunchAreaQueryDto dto) {
assertNotNull(dto.getIds());
boolean result = false;
for (Integer areaId : dto.getIds()) {
DeviceLaunchArea deviceLaunchArea = selectById(areaId);
if (Objects.isNull(deviceLaunchArea)) {
LeaseException.throwSystemException(LeaseExceEnums.ENTITY_NOT_EXISTS);
}
deviceLaunchArea.setStatus(dto.getStatus());
deviceLaunchArea.setUtime(new Date());
result = updateById(deviceLaunchArea);
}
return result;
}
@Override
public Pageable<DeviceLaunchAreaQueryDto> setParam(Pageable<QueryForCreatorDto> data) {
Pageable<DeviceLaunchAreaQueryDto> pageable = new Pageable<>();
BeanUtils.copyProperties(data, pageable, "query");
pageable.setQuery(new DeviceLaunchAreaQueryDto());
if (Objects.isNull(data.getQuery()) || Objects.isNull(data.getQuery().getCreatorId())) {
LeaseException.throwSystemException(LeaseExceEnums.PARAMS_ERROR);
}
pageable.getQuery().setAccessableUserIds(Collections.singletonList(data.getQuery().getCreatorId()));
return pageable;
}
@Override
public MJDeviceLaunchAreaDetail detail(Integer launchAreaId) {
DeviceLaunchArea launchArea = getLaunchAreaInfoById(launchAreaId);
if (Objects.isNull(launchArea)) {
LeaseException.throwSystemException(LeaseExceEnums.DEVICE_LAUNCH_AREA_NOT_EXIST);
}
MJDeviceLaunchAreaDetail deviceLaunchAreaDetail = new MJDeviceLaunchAreaDetail(launchArea);
List<Integer> userIds = sysUserService.resolveOwnerAccessableUserIds(sysUserService.getCurrentUserOwner());
if (userIds.contains(launchArea.getSysUserId())) {
deviceLaunchAreaDetail.setIsModify(1);
}
return deviceLaunchAreaDetail;
}
@Override
public List<DeviceMaintainerDto> getDeviceMaintainerDtos() {
SysUser sysUser = sysUserService.getCurrentUserOwner();
List<DeviceMaintainerDto> deviceMaintainers = new ArrayList<>();
// 找到维护人员角色id
Integer roleId = sysRoleService.getRoleIdBySysUserId(sysUser.getId());
if (!ParamUtil.isNullOrEmptyOrZero(roleId)) {
List<SysUser> maintainUsers = sysUserService.getUsersByRoleId(roleId);
for (SysUser user : maintainUsers) {
DeviceMaintainerDto deviceMaintainerDto = new DeviceMaintainerDto();
deviceMaintainerDto.setId(user.getId());
deviceMaintainerDto.setName(user.getUsername());
deviceMaintainers.add(deviceMaintainerDto);
}
}
return deviceMaintainers;
}
@Override
public List<DeviceLaunchAreaCountVo> areaListManager() {
SysUser user = sysUserService.getCurrentUser();
logger.info("维护人员id=" + user.getId());
EntityWrapper<DeviceLaunchArea> entityWrapper = new EntityWrapper<>();
entityWrapper.eq("maintainer_id", user.getId()).eq("is_deleted", DeleteStatus.NOT_DELETED.getCode());
List<DeviceLaunchAreaCountVo> countVos = new ArrayList<>();
selectList(entityWrapper).forEach(item -> {
DeviceLaunchAreaCountVo countVo = new DeviceLaunchAreaCountVo();
countVo.setDeviceLaunchAreaId(item.getId());
countVo.setAreaName(item.getName());
countVo.setDeviceCount(countDevice(item.getId()));
countVos.add(countVo);
});
return countVos;
}
private Integer countDevice(Integer deviceLaunchAreaId) {
return deviceService.selectCount(new EntityWrapper<Device>().eq("launch_area_id", deviceLaunchAreaId).eq("is_deleted", DeleteStatus.NOT_DELETED.getCode()));
}
@Override
public List<String> getDeviceSnoByMaintainerId(Integer maintainerId) {
EntityWrapper<DeviceLaunchArea> entityWrapper = new EntityWrapper<>();
entityWrapper.eq("maintainer_id", maintainerId).eq("is_deleted", DeleteStatus.NOT_DELETED.getCode());
List<Integer> ids = selectList(entityWrapper).stream().map(DeviceLaunchArea::getId).collect(Collectors.toList());
List<String> sno = new ArrayList<>();
if (!ParamUtil.isNullOrEmptyOrZero(ids)) {
sno = deviceService.selectList(new EntityWrapper<Device>().in("launch_area_id", ids).eq("is_deleted", DeleteStatus.NOT_DELETED.getCode()))
.stream().map(Device::getSno).collect(Collectors.toList());
}
return sno;
}
@Override
public List<DeviceLaunchArea> getListByMaintainerId(Integer maintainerId) {
Wrapper wrapper = new EntityWrapper<DeviceLaunchArea>();
wrapper.eq("maintainer_id", maintainerId).eq("is_deleted", DeleteStatus.NOT_DELETED.getCode());
return selectList(wrapper);
}
}
| true
|
c5c99238c653847d331b236a9b07cb01abe38ef9
|
Java
|
bhavanareddy30/online-quiz-services
|
/src/main/java/com/screening/quiz/services/model/Answers.java
|
UTF-8
| 1,114
| 2.25
| 2
|
[] |
no_license
|
package com.screening.quiz.services.model;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.util.Date;
@Entity
@Table(name = "answers")
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
public class Answers {
@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
private String id;
private String userId;
private String questionId;
private String question;
private Date createdDateTime;
private Date updatedDateTime;
@Lob
private byte[] response;
private String responseText;
public Answers(String userId, String questionId, String question, byte[] response, String responseText) {
this.userId = userId;
this.questionId = questionId;
this.question = question;
this.response = response;
this.responseText = responseText;
this.createdDateTime = new Date();
this.updatedDateTime = new Date();
}
}
| true
|
09112d9f2a1f2b8030488ec0ae72541bba8ac2b6
|
Java
|
rakibsarwer/IoT-Arduino-Robotics
|
/F64KYQOIUOHOYLM/source/de/bezier/data/sql/SQL.java
|
UTF-8
| 39,429
| 2.34375
| 2
|
[] |
no_license
|
package de.bezier.data.sql;
import processing.core.*;
import de.bezier.data.sql.mapper.*;
import java.io.*;
import java.sql.*;
import java.lang.reflect.*;
import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;
/**
* <h1>SQL library for Processing 2+</h1>
*
* Since v 0.2.0 it has some ORM like features, see
* <ul>
* <li><a href="#setFromRow(java.lang.Object)">setFromRow(Object)</a></li>
* <li><a href="#saveToDatabase(java.lang.Object)">saveToDatabase(Object)</a></li>
* <li><a href="#insertUpdateInDatabase(java.lang.String, java.lang.String[], java.lang.Object[])">insertUpdateIntoDatabase(String,Object[],Object[])</a></li>
* </ul>
*
* Links:<ul>
* <li>http://www.mysql.com/products/connector/j/</li>
* <li>http://java.sun.com/products/jdbc/</li>
* <li>http://www.toxi.co.uk/blog/2007/07/using-javadb-and-db4o-in-processing.htm</li>
* <li>http://www.tom-carden.co.uk/2007/07/30/a-quick-note-on-using-sqlite-in-processing/</li>
* </ul>
*
* @author Florian Jenett - mail@florianjenett.de
*
* created: 07.05.2005 - 12:46 Uhr
* modified: fjenett 20121217
*/
abstract public class SQL
{
PApplet papplet;
public String server;
public String database;
public String url;
public String user;
protected String pass;
public String driver = "";
public String type = "";
private int driverMinorVersion = -1;
private int driverMajorVersion = -1;
public java.sql.Connection connection;
public String previousQuery;
public java.sql.Statement statement;
public java.sql.ResultSet result;
private boolean DEBUG = true;
private HashMap<ResultSet,String[]> columnNamesCache;
private NameMapper mapper;
private HashMap<Class,String> classToTableMap;
protected ArrayList<String> tableNames;
/**
* Do not use this contructor.
*/
public SQL ()
{
System.out.println(
"SQL(): Please use this constructor\n"+
"\tSQL ( String _serv, String _db, String _u, String _p, PApplet _pa )"
);
mapper = new de.bezier.data.sql.mapper.UnderScoreToCamelCaseMapper();
}
/**
* You should not directly use the SQL.class instead use the classes for your database type.
*/
public SQL ( PApplet _pa, String _db )
{
this.user = "";
this.pass = "";
this.server = "";
String f = _pa.dataPath(_db);
File ff = new File(f);
if ( !ff.exists() || !ff.canRead() )
{
f = _pa.sketchPath( _db );
ff = new File(f);
if ( !ff.exists() || !ff.canRead() )
{
f = _db;
ff = new File(f);
if ( !ff.exists() || !ff.canRead() )
{
System.err.println(
"Sorry can't find any file named " + _db +
" make sure it exists and the path is correct."
);
}
}
}
_pa.println( "Using this database: " + f );
this.database = f;
this.url = "jdbc:" + type + ":" + database;
this.papplet = _pa;
papplet.registerDispose( this );
mapper = new de.bezier.data.sql.mapper.UnderScoreToCamelCaseMapper();
}
/**
* You should not directly use the SQL.class instead use the classes for your database type.
*/
public SQL ( PApplet _pa, String _serv, String _db, String _u, String _p )
{
this.server = _serv;
this.database = _db;
this.url = "jdbc:" + type + "://" + server + "/" + database;
this.user = _u;
this.pass = _p;
this.papplet = _pa;
papplet.registerDispose( this );
mapper = new de.bezier.data.sql.mapper.UnderScoreToCamelCaseMapper();
}
/**
* Turn some debugging on/off.
*
* @param yesNo Turn it on or off
*/
public void setDebug ( boolean yesNo )
{
DEBUG = yesNo;
}
/**
* Get current debugging setting
*
* @param yesNo Turn it on or off
*/
public boolean getDebug ()
{
return DEBUG;
}
/**
* Open the database connection with the parameters given in the contructor.
*/
public boolean connect()
{
if ( driver == null || driver.equals("") ||
type == null || type.equals("") )
{
System.out.println( "SQL.connect(): You have to set a driver and type first." );
return false;
}
// TODO: need to add mechanisms for different connection types and parameters, see:
// http://jdbc.postgresql.org/documentation/83/connect.html
try
{
Class.forName(driver);
connection = java.sql.DriverManager.getConnection(url, user, pass);
}
catch (ClassNotFoundException e)
{
System.out.println( "SQL.connect(): Could not find the database driver ( "+driver+" ).\r" );
if (DEBUG) e.printStackTrace();
return false;
}
catch (java.sql.SQLException e)
{
System.out.println( "SQL.connect(): Could not connect to the database ( "+url+" ).\r" );
if (DEBUG) e.printStackTrace();
return false;
}
getTableNames();
try {
Driver jdbcDriver = java.sql.DriverManager.getDriver( url );
if ( jdbcDriver != null ) {
driverMinorVersion = jdbcDriver.getMinorVersion();
driverMajorVersion = jdbcDriver.getMajorVersion();
if ( DEBUG ) System.out.println( "Using driver " + getDriverVersion() );
}
} catch ( SQLException sqle ) {
sqle.printStackTrace();
}
return true;
}
/**
* Return the version of the currently active JDBC driver
*
* @return String The version of the current driver
*/
public String getDriverVersion ()
{
if ( connection == null ) {
System.out.println( "SQL.getDriverVersion(): you need to connect() first" );
return null;
} else if ( driver == null || driver.equals("") ) {
System.out.println( "SQL.getDriverVersion(): no driver specified ... or it is null" );
return null;
}
return driver + " " + driverMajorVersion + "." + driverMinorVersion;
}
private void preQueryOrExecute ()
{
result = null;
}
/**
* Execute a SQL command on the open database connection.
*
* @param _sql The SQL command to execute
*/
public void execute ( String _sql )
{
preQueryOrExecute();
query( _sql, false );
}
/**
* Execute a SQL command on the open database connection.
* Arguments are passed to String.format() first.
*
* @param _sql SQL command as pattern for String.format()
* @param args Zero or more objects to be passed to String.format()
*
* @see <a href="http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax">Format syntax</a>
* @see java.lang.String#format(java.lang.String,java.lang.Object...)
*/
public void execute ( String _sql, Object ... args )
{
preQueryOrExecute();
if ( args == null || args.length == 0 ) queryOrExecute( _sql, false );
Method meth = null;
try {
meth = String.class.getMethod(
"format",
String.class,
java.lang.reflect.Array.newInstance(Object.class,0).getClass()
);
} catch ( Exception ex ) {
ex.printStackTrace();
return;
}
// Object[] args2 = new Object[args.length+1];
// args2[0] = _sql;
// System.arraycopy( args, 0, args2, 1, args.length );
String sql2 = null;
try {
sql2 = (String)meth.invoke( null, _sql, args );
} catch ( Exception ex ) {
if (DEBUG) ex.printStackTrace();
}
queryOrExecute( sql2, false );
}
/**
* Issue a query on the open database connection
*
* @param _sql SQL command to execute for the query
*/
public void query ( String _sql )
{
preQueryOrExecute();
queryOrExecute( _sql, true );
}
/**
* Issue a query on the open database connection.
* Arguments are passed to String.format() first.
*
* @param _sql SQL command as pattern for String.format()
* @param args Zero or more objects to be passed to String.format()
*
* @see <a href="http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax">Format syntax</a>
* @see java.lang.String#format(java.lang.String,java.lang.Object...)
*/
public void query ( String _sql, Object ... args )
{
preQueryOrExecute();
if ( args == null || args.length == 0 ) queryOrExecute( _sql, true );
Method meth = null;
try {
meth = String.class.getMethod(
"format",
String.class,
java.lang.reflect.Array.newInstance(Object.class,0).getClass()
);
} catch ( Exception ex ) {
ex.printStackTrace();
return;
}
String sql2 = null;
try {
sql2 = (String)meth.invoke( null, _sql, args );
} catch ( Exception ex ) {
if (DEBUG) ex.printStackTrace();
}
queryOrExecute( sql2, true );
}
/**
* Query implemenbtation called by execute() / query()
*/
private void queryOrExecute ( String _sql, boolean keep )
{
if ( connection == null )
{
System.out.println( "SQL.query(): You need to connect() first." );
return;
}
previousQuery = _sql;
try
{
if ( statement == null )
{
statement = connection.createStatement();
}
boolean hasResults = statement.execute( _sql );
if ( keep && hasResults )
{
this.result = statement.getResultSet();
}
}
catch ( java.sql.SQLException e )
{
System.out.println( "SQL.query(): java.sql.SQLException.\r" );
if (DEBUG) {
System.out.println( _sql );
e.printStackTrace();
}
}
}
/**
* Check if more results (rows) are available. This needs to be called before any results can be retrieved.
*
* @return boolean true if more results are available, false otherwise
*/
public boolean next ()
{
if ( result == null )
{
System.out.println( "SQL.next(): You need to query() something first." );
return false;
}
try
{
return result.next();
}
catch ( java.sql.SQLException e )
{
System.out.println( "SQL.next(): java.sql.SQLException.\r" );
if ( DEBUG ) e.printStackTrace();
}
return false;
}
/**
* Get names of available tables in active database,
* needs to be implemented per db adapter.
*
* @return String[] The table names
*/
abstract public String[] getTableNames ();
/**
* Returns an array with the column names of the last request.
*
* @return String[] the column names of last result or null
*/
public String[] getColumnNames ()
{
String[] colNames = null;
if ( result == null )
{
System.out.println( "SQL.getColumnNames(): You need to query() something first." );
return null;
}
// if ( columnNamesCache == null )
// columnNamesCache = new HashMap<ResultSet,String[]>();
//
// colNames = columnNamesCache.get( result );
// if ( colNames != null ) return colNames;
java.sql.ResultSetMetaData meta = null;
try {
meta = result.getMetaData();
} catch ( SQLException sqle ) {
if (DEBUG) sqle.printStackTrace();
return null;
}
if ( meta != null )
{
try {
colNames = new String[ meta.getColumnCount() ];
for ( int i = 1, k = meta.getColumnCount(); i <= k; i++ )
{
colNames[i-1] = meta.getColumnName( i );
}
} catch ( SQLException sqle ) {
if (DEBUG) sqle.printStackTrace();
return null;
}
}
// columnNamesCache.clear();
// columnNamesCache.put( result, colNames );
return colNames;
}
/**
* Get connection. ... in case you want to do JDBC stuff directly.
*
* @return java.sql.Connection The connection
*/
public java.sql.Connection getConnection ()
{
return connection;
}
/**
* Read an integer value from the specified field.
* Represents an INT / INTEGER type:
* http://java.sun.com/j2se/1.3/docs/guide/jdbc/getstart/mapping.html
* "8.9.6 Conversions by ResultSet.getXXX Methods"
*
* @param _field The name of the field
* @return int Value of the field or 0
*/
public int getInt ( String _field )
{
// TODO: 0 does not seem to be a good return value for a numeric field to indicate failure
// same goes for other numeric fields
if ( result == null )
{
System.out.println( "SQL.getInt(): You need to query() something first." );
return 0;
}
try
{
return result.getInt( _field );
}
catch ( java.sql.SQLException e )
{
System.out.println( "SQL.getInt(): java.sql.SQLException.\r" );
if (DEBUG) e.printStackTrace();
}
return 0;
}
/**
* Read an integer value from the specified field.
* Represents an INT / INTEGER type:
* http://java.sun.com/j2se/1.3/docs/guide/jdbc/getstart/mapping.html
* "8.9.6 Conversions by ResultSet.getXXX Methods"
*
* @param _column The column index of the field to read
* @return int Value of the field or 0
*/
public int getInt ( int _column )
{
if ( result == null )
{
System.out.println( "SQL.getInt(): You need to query() something first." );
return 0;
}
try
{
return result.getInt( _column );
}
catch ( java.sql.SQLException e )
{
System.out.println( "SQL.getInt(): java.sql.SQLException.\r" );
if (DEBUG) e.printStackTrace();
}
return 0;
}
/**
* Read a long value from the specified field.
* Represents a BIGINT type:
* http://java.sun.com/j2se/1.3/docs/guide/jdbc/getstart/mapping.html
* "8.9.6 Conversions by ResultSet.getXXX Methods"
*
* @param _field The name of the field
* @return long Value of the field or 0
*/
public long getLong ( String _field )
{
if ( result == null )
{
System.out.println( "SQL.getLong(): You need to query() something first." );
return 0;
}
try
{
return result.getLong( _field );
}
catch ( java.sql.SQLException e )
{
System.out.println( "SQL.getLong(): java.sql.SQLException.\r" );
if (DEBUG) e.printStackTrace();
}
return 0;
}
/**
* Read a long value from the specified field.
* Represents a BIGINT type:
* http://java.sun.com/j2se/1.3/docs/guide/jdbc/getstart/mapping.html
* "8.9.6 Conversions by ResultSet.getXXX Methods"
*
* @param _column The column index of the field
* @return long Value of the field or 0
*/
public long getLong ( int _column )
{
if ( result == null )
{
System.out.println( "SQL.getLong(): You need to query() something first." );
return 0;
}
try
{
return result.getLong( _column );
}
catch ( java.sql.SQLException e )
{
System.out.println( "SQL.getLong(): java.sql.SQLException.\r" );
if (DEBUG) e.printStackTrace();
}
return 0;
}
/**
* Read a float value from the specified field.
* Represents a REAL type:
* http://java.sun.com/j2se/1.3/docs/guide/jdbc/getstart/mapping.html
* "8.9.6 Conversions by ResultSet.getXXX Methods"
*
* @param _field The name of the field
* @return float Value of the field or 0
*/
public float getFloat ( String _field )
{
if ( result == null )
{
System.out.println( "SQL.getFloat(): You need to query() something first." );
return 0.0f;
}
try
{
return result.getFloat( _field );
}
catch ( java.sql.SQLException e )
{
System.out.println( "SQL.getFloat(): java.sql.SQLException.\r" );
if (DEBUG) e.printStackTrace();
}
return 0.0f;
}
/**
* Read a float value from the specified field.
* Represents a REAL type:
* http://java.sun.com/j2se/1.3/docs/guide/jdbc/getstart/mapping.html
* "8.9.6 Conversions by ResultSet.getXXX Methods"
*
* @param _column The index of the column of the field
* @return float Value of the field or 0
*/
public float getFloat ( int _column )
{
if ( result == null )
{
System.out.println( "SQL.getFloat(): You need to query() something first." );
return 0.0f;
}
try
{
return result.getFloat( _column );
}
catch ( java.sql.SQLException e )
{
System.out.println( "SQL.getFloat(): java.sql.SQLException.\r" );
if (DEBUG) e.printStackTrace();
}
return 0.0f;
}
/**
* Read a double value from the specified field.
* Represents FLOAT and DOUBLE types:
* http://java.sun.com/j2se/1.3/docs/guide/jdbc/getstart/mapping.html
* "8.9.6 Conversions by ResultSet.getXXX Methods"
*
* @param _field The name of the field
* @return double Value of the field or 0
*/
public double getDouble ( String _field )
{
if ( result == null )
{
System.out.println( "SQL.getDouble(): You need to query() something first." );
return 0.0;
}
try
{
return result.getDouble( _field );
}
catch ( java.sql.SQLException e )
{
System.out.println( "SQL.getDouble(): java.sql.SQLException.\r" );
if (DEBUG) e.printStackTrace();
}
return 0.0;
}
/**
* Read a double value from the specified field.
* Represents FLOAT and DOUBLE types:
* http://java.sun.com/j2se/1.3/docs/guide/jdbc/getstart/mapping.html
* "8.9.6 Conversions by ResultSet.getXXX Methods"
*
* @param _column The column index of the field
* @return double Value of the field or 0
*/
public double getDouble ( int _column )
{
if ( result == null )
{
System.out.println( "SQL.getDouble(): You need to query() something first." );
return 0.0;
}
try
{
return result.getDouble( _column );
}
catch ( java.sql.SQLException e )
{
System.out.println( "SQL.getDouble(): java.sql.SQLException.\r" );
if (DEBUG) e.printStackTrace();
}
return 0.0;
}
/**
* Read a java.math.BigDecimal value from the specified field.
* Represents DECIMAL and NUMERIC types:
* http://java.sun.com/j2se/1.3/docs/guide/jdbc/getstart/mapping.html
* "8.9.6 Conversions by ResultSet.getXXX Methods"
*
* @param _field The name of the field
* @return java.math.BigDecimal Value of the field or null
*/
public java.math.BigDecimal getBigDecimal ( String _field )
{
if ( result == null )
{
System.out.println( "SQL.getBigDecimal(): You need to query() something first." );
return null;
}
try
{
return result.getBigDecimal( _field );
}
catch ( java.sql.SQLException e )
{
System.out.println( "SQL.getBigDecimal(): java.sql.SQLException.\r" );
if (DEBUG) e.printStackTrace();
}
return null;
}
/**
* Read a java.math.BigDecimal value from the specified field.
* Represents DECIMAL and NUMERIC types:
* http://java.sun.com/j2se/1.3/docs/guide/jdbc/getstart/mapping.html
* "8.9.6 Conversions by ResultSet.getXXX Methods"
*
* @param _column The column index of the field
* @return java.math.BigDecimal Value of the field or null
*/
public java.math.BigDecimal getBigDecimal ( int _column )
{
if ( result == null )
{
System.out.println( "SQL.getBigDecimal(): You need to query() something first." );
return null;
}
try
{
return result.getBigDecimal( _column );
}
catch ( java.sql.SQLException e )
{
System.out.println( "SQL.getBigDecimal(): java.sql.SQLException.\r" );
if (DEBUG) e.printStackTrace();
}
return null;
}
/**
* Read a boolean value from the specified field.
* Represents BIT type:
* http://java.sun.com/j2se/1.3/docs/guide/jdbc/getstart/mapping.html
* "8.9.6 Conversions by ResultSet.getXXX Methods"
*
* @param _field The name of the field
* @return boolean Value of the field or 0
*/
public boolean getBoolean ( String _field )
{
if ( result == null )
{
System.out.println( "SQL.getBoolean(): You need to query() something first." );
return false;
}
try
{
return result.getBoolean( _field );
}
catch ( java.sql.SQLException e )
{
System.out.println( "SQL.getBoolean(): java.sql.SQLException.\r" );
if (DEBUG) e.printStackTrace();
}
return false;
}
/**
* Read a boolean value from the specified field.
* Represents BIT type:
* http://java.sun.com/j2se/1.3/docs/guide/jdbc/getstart/mapping.html
* "8.9.6 Conversions by ResultSet.getXXX Methods"
*
* @param _column The column index of the field
* @return boolean Value of the field or 0
*/
public boolean getBoolean ( int _column )
{
if ( result == null )
{
System.out.println( "SQL.getBoolean(): You need to query() something first." );
return false;
}
try
{
return result.getBoolean( _column );
}
catch ( java.sql.SQLException e )
{
System.out.println( "SQL.getBoolean(): java.sql.SQLException.\r" );
if (DEBUG) e.printStackTrace();
}
return false;
}
/**
* Read a String value from the specified field.
* Represents VARCHAR and CHAR types:
* http://java.sun.com/j2se/1.3/docs/guide/jdbc/getstart/mapping.html
* "8.9.6 Conversions by ResultSet.getXXX Methods"
*
* @param _field The name of the field
* @return String Value of the field or null
*/
public String getString ( String _field )
{
if ( result == null )
{
System.out.println( "SQL.getString(): You need to query() something first." );
return null;
}
try
{
return result.getString( _field );
}
catch ( java.sql.SQLException e )
{
System.out.println( "SQL.getString(): java.sql.SQLException.\r" );
if (DEBUG) e.printStackTrace();
}
return null;
}
/**
* Read a String value from the specified field.
* Represents VARCHAR and CHAR types:
* http://java.sun.com/j2se/1.3/docs/guide/jdbc/getstart/mapping.html
* "8.9.6 Conversions by ResultSet.getXXX Methods"
*
* @param _column The column index of the field
* @return String Value of the field or null
*/
public String getString ( int _column )
{
if ( result == null )
{
System.out.println( "SQL.getString(): You need to query() something first." );
return null;
}
try
{
return result.getString( _column );
}
catch ( java.sql.SQLException e )
{
System.out.println( "SQL.getString(): java.sql.SQLException.\r" );
if (DEBUG) e.printStackTrace();
}
return null;
}
/**
* Read a java.sql.Date value from the specified field.
* Represents DATE type:
* http://java.sun.com/j2se/1.3/docs/guide/jdbc/getstart/mapping.html
* "8.9.6 Conversions by ResultSet.getXXX Methods"
*
* @param _field The name of the field
* @return java.sql.Date Value of the field or null
*/
public java.sql.Date getDate ( String _field )
{
if ( result == null )
{
System.out.println( "SQL.getDate(): You need to query() something first." );
return null;
}
try
{
return result.getDate( _field );
}
catch ( java.sql.SQLException e )
{
System.out.println( "SQL.getDate(): java.sql.SQLException.\r" );
if (DEBUG) e.printStackTrace();
}
return null;
}
/**
* Read a java.sql.Date value from the specified field.
* Represents DATE type:
* http://java.sun.com/j2se/1.3/docs/guide/jdbc/getstart/mapping.html
* "8.9.6 Conversions by ResultSet.getXXX Methods"
*
* @param _column The column index of the field
* @return java.sql.Date Value of the field or null
*/
public java.sql.Date getDate ( int _column )
{
if ( result == null )
{
System.out.println( "SQL.getDate(): You need to query() something first." );
return null;
}
try
{
return result.getDate( _column );
}
catch ( java.sql.SQLException e )
{
System.out.println( "SQL.getDate(): java.sql.SQLException.\r" );
if (DEBUG) e.printStackTrace();
}
return null;
}
/**
* Read a java.sql.Time value from the specified field.
* Represents TIME type:
* http://java.sun.com/j2se/1.3/docs/guide/jdbc/getstart/mapping.html
* "8.9.6 Conversions by ResultSet.getXXX Methods"
*
* @param _field The name of the field
* @return java.sql.Time Value of the field or null
*/
public java.sql.Time getTime ( String _field )
{
if ( result == null )
{
System.out.println( "SQL.getTime(): You need to query() something first." );
return null;
}
try
{
return result.getTime( _field );
}
catch ( java.sql.SQLException e )
{
System.out.println( "SQL.getTime(): java.sql.SQLException.\r" );
if (DEBUG) e.printStackTrace();
}
return null;
}
/**
* Read a java.sql.Time value from the specified field.
* Represents TIME type:
* http://java.sun.com/j2se/1.3/docs/guide/jdbc/getstart/mapping.html
* "8.9.6 Conversions by ResultSet.getXXX Methods"
*
* @param _column The column index of the field
* @return java.sql.Time Value of the field or null
*/
public java.sql.Time getTime ( int _column )
{
if ( result == null )
{
System.out.println( "SQL.getTime(): You need to query() something first." );
return null;
}
try
{
return result.getTime( _column );
}
catch ( java.sql.SQLException e )
{
System.out.println( "SQL.getTime(): java.sql.SQLException.\r" );
if (DEBUG) e.printStackTrace();
}
return null;
}
/**
* Read a java.sql.Timestamp value from the specified field.
* Represents TIMESTAMP type:
* http://java.sun.com/j2se/1.3/docs/guide/jdbc/getstart/mapping.html
* "8.9.6 Conversions by ResultSet.getXXX Methods"
*
* @param _field The name of the field
* @return java.sql.Timestamp Value of the field or null
*/
public java.sql.Timestamp getTimestamp ( String _field )
{
if ( result == null )
{
System.out.println( "SQL.getTimestamp(): You need to query() something first." );
return null;
}
try
{
return result.getTimestamp( _field );
}
catch ( java.sql.SQLException e )
{
System.out.println( "SQL.getTimestamp(): java.sql.SQLException.\r" );
if (DEBUG) e.printStackTrace();
}
return null;
}
/**
* Read a java.sql.Timestamp value from the specified field.
* Represents TIMESTAMP type:
* http://java.sun.com/j2se/1.3/docs/guide/jdbc/getstart/mapping.html
* "8.9.6 Conversions by ResultSet.getXXX Methods"
*
* @param _column The column index of the field
* @return java.sql.Timestamp Value of the field or null
*/
public java.sql.Timestamp getTimestamp ( int _column )
{
if ( result == null )
{
System.out.println( "SQL.getTimestamp(): You need to query() something first." );
return null;
}
try
{
return result.getTimestamp( _column );
}
catch ( java.sql.SQLException e )
{
System.out.println( "SQL.getTimestamp(): java.sql.SQLException.\r" );
if (DEBUG) e.printStackTrace();
}
return null;
}
/**
* Read a value from the specified field to hav it returned as an object.
*
* @param _field The name of the field
* @return Object Value of the field or null
*/
public Object getObject ( String _field )
{
if ( result == null )
{
System.out.println( "SQL.getObject(): You need to query() something first." );
return null;
}
try
{
return result.getObject( _field );
}
catch ( java.sql.SQLException e )
{
System.out.println( "SQL.getObject(): java.sql.SQLException.\r" );
if (DEBUG) e.printStackTrace();
}
return null;
}
/**
* Read a value from the specified field to hav it returned as an object.
*
* @param _column The column index of the field
* @return Object Value of the field or null
*/
public Object getObject ( int _column )
{
if ( result == null )
{
System.out.println( "SQL.getObject(): You need to query() something first." );
return null;
}
try
{
return result.getObject( _column );
}
catch ( java.sql.SQLException e )
{
System.out.println( "SQL.getObject(): java.sql.SQLException.\r" );
if (DEBUG) e.printStackTrace();
}
return null;
}
/**
* Close the database connection
*/
public void close()
{
dispose();
}
/**
* Callback function for PApplet.registerDispose()
*
* @see processing.core.PApplet.registerDispose(java.lang.Object)
*/
public void dispose ()
{
if ( result != null )
{
try
{
result.close();
}
catch ( java.sql.SQLException e ) { ; }
result = null;
}
if ( statement != null )
{
try
{
statement.close();
}
catch ( java.sql.SQLException e ) { ; }
statement = null;
}
if ( connection != null )
{
try
{
connection.close();
}
catch ( java.sql.SQLException e ) { ; }
connection = null;
}
}
/**
* Generate an escaped String for a given Object
*
* @param object the Object to escape
* @return String the ecaped String representation of the Object
*/
public String escape ( Object o )
{
return "\"" + o.toString().replaceAll("\"","\\\"") + "\"";
}
/**
* Set the current NameMapper
*
* @param mapper the name mapper
* @see de.bezier.data.sql.mapper.NameMapper
*/
public void setNameMapper ( NameMapper mapper )
{
this.mapper = mapper;
}
/**
* Get the current NameMapper
*
* @see de.bezier.data.sql.mapper.NameMapper
*/
public NameMapper getNameMapper ()
{
return mapper;
}
/**
* <p>Highly experimental ...<br />
* tries to map column names to public fields or setter methods
* in the given object.</p>
*
* <p>Use like so:
* <pre>
* db.query("SELECT name, id, sometime FROM table");
*
* while ( db.next() ) {
* SomeObject obj = new SomeObject();
* db.setFromRow(obj);
* // obj.name is now same as db.getString("name"), etc.
* }
* </pre></p>
*
* <p>SomeObject might look like:
* <pre>
* class SomeObject {
* public String name;
* public int id;
* Date sometime;
* }
* </pre></p>
*
* @param object The object to populate from the currently selected row
*/
public void setFromRow ( Object object )
{
if ( object == null ) {
System.err.println( "SQL.rowToObject(): Handing in null won't cut it." );
return;
}
if ( result == null ) {
System.err.println( "SQL.rowToObject(): You need to query() something first!" );
return;
}
String[] colNames = getColumnNames();
if ( colNames == null )
{
System.err.println(
"SQL.rowToObject(): uh-oh something went wrong: unable to get column names." );
return;
}
if ( colNames.length > 0 )
{
Class klass = null;
try {
klass = Class.forName("DeBezierDataSQL");
} catch ( Exception e ) {
if (DEBUG) e.printStackTrace();
}
if ( klass != null ) {
Method meth = null;
try {
meth = klass.getMethod(
"setFromRow",
new Class[]{ SQL.class, Object.class }
);
} catch ( Exception e ) {
if (DEBUG) e.printStackTrace();
}
// System.out.println( meth );
// System.out.println( meth.getParameterTypes() );
if ( meth != null ) {
try {
meth.invoke( null, this, object );
} catch ( Exception e ) {
if (DEBUG) e.printStackTrace();
}
}
}
}
}
/**
* Convert a field name to a setter name: fieldName -> setFieldName().
*/
public String nameToSetter ( String name )
{
if ( name == null ) return name;
if ( name.length() == 0 ) return null;
return "set" + name.substring(0,1).toUpperCase() + name.substring(1);
}
/**
* Convert a field name to a getter name: fieldName -> getFieldName().
*/
public String nameToGetter ( String name )
{
if ( name == null ) return name;
if ( name.length() == 0 ) return null;
return "get" + name.substring(0,1).toUpperCase() + name.substring(1);
}
/**
* Set a table name for a class.
*/
public void registerTableNameForClass ( String name, Object classOrObject )
{
if ( name == null || name.equals("") || classOrObject == null ) return;
Class klass = null;
if ( classOrObject.getClass() != Class.class )
klass = classOrObject.getClass();
else
klass = (Class)classOrObject;
if ( classToTableMap == null )
classToTableMap = new HashMap<Class,String>();
classToTableMap.put( klass, name );
if (DEBUG) System.out.println( String.format(
"Class \"%s\" is now mapped to table \"%s\"", klass.getName(), name
));
}
/**
* Take an object, try to find table name from object name (or look it up),
* get fields and getters from object and pass that on to
* insertUpdateIntoDatabase(table, columns, values).
*
* @param object Object The object to save to db
*
* @see #insertUpdateInDatabase(java.lang.String, java.lang.String[], java.lang.Object[])
*/
public void saveToDatabase ( Object object )
{
if ( object == null ) return;
// Find the table name
String tableName = null;
if ( classToTableMap == null )
classToTableMap = new HashMap<Class,String>();
tableName = classToTableMap.get(object.getClass());
if ( tableName != null )
saveToDatabase( tableName, object );
else
{
Class klass = object.getClass();
tableName = klass.getName();
for ( char c : new char[]{'$','.'} )
{
int indx = tableName.lastIndexOf(c);
if ( indx >= 0 ) {
tableName = tableName.substring(indx+1);
}
}
if ( mapper != null ) {
tableName = mapper.backward(tableName);
}
registerTableNameForClass( tableName, klass );
saveToDatabase( tableName, object );
}
}
/**
* Takes a table name and an object and tries to construct a set of
* columns names from fields and getters found in the object. After
* the values are fetched from the object all is passed to
* insertUpdateIntoDatabase().
*
* @param tableName String The name of the table
* @param object Object The object to look at
*
* @see #insertUpdateInDatabase(java.lang.String, java.lang.String[], java.lang.Object[])
*/
public void saveToDatabase ( String tableName, Object object )
{
if ( object == null ) return;
String[] tableNames = getTableNames();
if ( !java.util.Arrays.asList(tableNames).contains(tableName) ) {
System.err.println(String.format(
"saveToDatabase(): table '%s' not found in database '%s'", tableName, database
));
return;
}
String[] colNames = getColumnNames();
String[] fieldNames = new String[colNames.length];
if ( mapper != null )
{
for ( int i = 0; i < colNames.length; i++ )
{
//System.out.println(colNames[i]);
fieldNames[i] = mapper.forward(colNames[i]);
//System.out.println(fieldNames[i]);
}
}
Class klass = object.getClass();
Field[] fields = new Field[colNames.length];
Method[] getters = new Method[colNames.length];
for ( int i = 0; i < colNames.length; i++ )
{
String fieldName = fieldNames[i];
String colName = colNames[i];
Field f = null;
try {
f = klass.getField(fieldName);
if ( f == null ) {
f = klass.getField(colName);
}
} catch ( Exception e ) {
if (DEBUG) e.printStackTrace();
}
if ( f != null ) {
// try {
// values[i] = f.get(object);
// } catch ( Exception e ) {
// if (DEBUG) e.printStackTrace();
// }
fields[i] = f;
}
else
{
if (DEBUG) System.out.println( "Field not found, trying setter method" );
String getterName = nameToGetter(fieldName);
Method getter = null;
try {
getter = klass.getMethod(
getterName, new Class[0]
);
} catch ( Exception e ) {
if (DEBUG) e.printStackTrace();
}
// try {
// values[i] = getter.invoke(object);
// } catch ( Exception e ) {
// if (DEBUG) e.printStackTrace();
// }
getters[i] = getter;
}
if ( fields[i] == null && getters[i] == null ) {
System.err.println(String.format(
"Unable to get a field or getter for column '%s'", colName
));
return;
}
}
Object[] values = null;
Class clazz = null;
try {
clazz = Class.forName("DeBezierDataSQL");
} catch ( Exception e ) {
if (DEBUG) e.printStackTrace();
}
if ( klass != null ) {
Method meth = null;
try {
meth = clazz.getMethod(
"getValuesFromObject",
new Class[]{ SQL.class, Field[].class, Method[].class, Object.class }
);
} catch ( Exception e ) {
if (DEBUG) e.printStackTrace();
}
// System.out.println( meth );
// System.out.println( meth.getParameterTypes() );
if ( meth != null ) {
try {
values = (Object[])meth.invoke( null, this, fields, getters, object );
} catch ( Exception e ) {
if (DEBUG) e.printStackTrace();
}
}
}
if ( values != null )
{
insertUpdateInDatabase( tableName, colNames, values );
}
else
{
System.err.println("saveToDatabase() : trouble, trouble!!");
}
}
/**
* Insert or update a bunch of values in the database. If the given table has a
* primary key the entry will be updated if it already existed.
*
* @param tableName String The name of the table
* @param columnNames String[] The names of the columns to fill or update
* @param values Object[] The values to instert or update
*/
public void insertUpdateInDatabase ( String tableName, String[] columnNames, Object[] values )
{
HashMap<Object, Object> valuesKeys = new HashMap<Object,Object>();
for ( int i = 0; i < values.length; i++ )
{
valuesKeys.put(columnNames[i], values[i]);
}
HashMap<String, Object> primaryKeys = null;
try {
DatabaseMetaData meta = connection.getMetaData();
ResultSet rs = meta.getPrimaryKeys(null, null, tableName);
while ( rs.next() )
{
if ( primaryKeys == null )
primaryKeys = new HashMap<String, Object>();
String columnName = rs.getString("COLUMN_NAME");
primaryKeys.put(columnName, valuesKeys.get(columnName));
valuesKeys.remove(columnName);
}
} catch ( SQLException sqle ) {
sqle.printStackTrace();
}
//System.out.println(valuesKeys);
//System.out.println(primaryKeys);
String cols = "";
String patt = "";
HashMap<Object, Integer> valueIndices = new HashMap<Object, Integer>();
int i = 1;
for ( Map.Entry e : valuesKeys.entrySet() )
{
cols += ( i > 1 ? " , " : "" ) + e.getKey();
patt += ( i > 1 ? " , " : "" ) + "?";
valueIndices.put( e.getKey(), i );
i++;
}
String sql = null, opts = null;
HashMap<Object, Integer> primaryIndices = null;
if ( primaryKeys == null || primaryKeys.size() == 0 ) {
sql = "INSERT INTO " + tableName + " ( " + cols + " ) VALUES ( " + patt + " )";
} else {
primaryIndices = new HashMap<Object, Integer>();
opts = " WHERE ";
int p = 1;
for ( Map.Entry e : primaryKeys.entrySet() ) {
opts += (p > 1 ? " , " : "") + e.getKey() + " = ? ";
primaryIndices.put( e.getKey(), p );
p++;
}
//System.out.println( opts );
String sqlFind = "SELECT * FROM "+tableName+" "+opts;
//System.out.println( sqlFind );
try {
PreparedStatement psFind = connection.prepareStatement( sqlFind );
for ( Map.Entry e : primaryKeys.entrySet() ) {
psFind.setString( primaryIndices.get(e.getKey()), e.getValue().toString() );
}
result = psFind.executeQuery();
boolean found = next();
psFind.close();
if ( !found ) {
if (DEBUG) System.out.println(String.format(
"No entry with %s found in table '%s'", primaryKeys.toString(), tableName
));
int k = 1, m = valueIndices.size();
for ( Map.Entry e : primaryKeys.entrySet() ) {
cols += ( m > 0 ? " , " : "" ) + e.getKey();
patt += ( m > 0 ? " , " : "" ) + "?";
valuesKeys.put( e.getKey(), e.getValue() );
valueIndices.put( e.getKey(), m+k );
k++;
}
sql = "INSERT INTO " + tableName + " ( " + cols + " ) VALUES ( " + patt + " )";
primaryKeys = null;
}
else
{
cols = "";
for ( Map.Entry e : valuesKeys.entrySet() )
{
cols += ( cols.equals("") ? "" : " , " ) + e.getKey() + " = " + "?";
}
sql = "UPDATE "+tableName+" SET " + cols + " " + opts;
}
} catch ( java.sql.SQLException sqle ) {
sqle.printStackTrace();
}
}
if (DEBUG) System.out.println( sql );
try {
PreparedStatement ps = connection.prepareStatement( sql );
for ( Map.Entry e : valuesKeys.entrySet() )
{
ps.setString( valueIndices.get(e.getKey()), e.getValue()+"" );
}
if ( primaryKeys != null )
{
for ( Map.Entry e : primaryKeys.entrySet() )
{
ps.setString( valueIndices.size()+primaryIndices.get(e.getKey()), e.getValue()+"" );
}
}
ps.executeUpdate();
ps.close();
} catch ( java.sql.SQLException sqle ) {
sqle.printStackTrace();
}
}
}
| true
|
d7a953de9a6bf7a5c3c494bceb1345d9697abeda
|
Java
|
SamirGanbarli/ResumeApp
|
/src/main/java/com/company/controller/SkillController.java
|
UTF-8
| 2,249
| 2.34375
| 2
|
[] |
no_license
|
package com.company.controller;
import java.util.ArrayList;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import com.company.model.Skill;
import com.company.model.User;
import com.company.repository.SkillRepository;
import com.company.repository.UserRepository;
@Controller
public class SkillController {
@Autowired
private SkillRepository skillRepo;
@Autowired
private UserRepository userRepo;
//==================================
//----------------------------------
public String getskillname(int id) {
Skill s = skillRepo.getById(id);
String sname = s.getSkillName();
return sname;
}
public String getuserunsur(int id) {
User u = userRepo.getById(id);
String uname = u.getName();
String usurname = u.getSurname();
String unsur = uname + " " + usurname;
return unsur;
}
public String getuseremail(int id) {
User u = userRepo.getById(id);
String s = u.getEmail();
return "Email: "+s.toLowerCase();
}
public String getuserphone(int id) {
User u = userRepo.getById(id);
String s = u.getPhone();
return "Phone: "+s;
}
public String getusertitle(int id) {
User u = userRepo.getById(id);
String s = u.getTitle();
return s;
}
public String getuserloc(int id) {
User u = userRepo.getById(id);
String s = u.getLocation();
return s;
}
public String getuserlink(int id) {
User u = userRepo.getById(id);
String s = u.getLinkedin();
return s;
}
//----------------------------------------
//========================================
@GetMapping("/")
public String res(Model model) {
for (int i = 1; i <= 8; i++) {
String skname = getskillname(i);
model.addAttribute("s" + i + "name", skname);
}
model.addAttribute("unsur", getuserunsur(1));
model.addAttribute("uemail", getuseremail(1));
model.addAttribute("uphone", getuserphone(1));
model.addAttribute("utitle", getusertitle(1));
model.addAttribute("ulocation", getuserloc(1));
model.addAttribute("ulinkedin", getuserlink(1));
return "res";
}
}
| true
|
bc7e9f57ff05ea618a0cd53cc231722ce76dfd7b
|
Java
|
kevin8299/AlgorithmStudy
|
/src/com/leetcode/number_of_islands/Solution_UF.java
|
UTF-8
| 3,298
| 3
| 3
|
[] |
no_license
|
package com.leetcode.number_of_islands;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;
/**
* Created by Administrator on 2016/4/19.
*/
public class Solution_UF {
public int numIslands(char[][] grid) {
if(grid == null || grid.length == 0 || grid[0].length == 0) return 0;
int[] dx = {1, 0, -1, 0};
int[] dy = {0, 1, 0, -1};
int row = grid.length;
int col = grid[0].length;
boolean[][] v = new boolean[row][col];
for(int i = 0; i < row; i++)
for(int j = 0; j < col; j++)
v[i][j] = false;
Queue<Node> q = new LinkedList<>();
UF uf = new UF(row * col);
for(int i = 0; i < row; i++)
for(int j = 0; j < col; j++){
if(!v[i][j] && grid[i][j] == '1')
q.add(new Node(i, j));
while(q.size() > 0){
Node n = q.poll();
v[n.x][n.y] = true;
for(int k = 0; k < 4; k++) {
int x = n.x + dx[k];
int y = n.y + dy[k];
if (x >= 0 && x < row && y >= 0 && y < col && !v[x][y] && grid[x][y] == '1') {
q.add(new Node(x, y));
uf.union(x * col + y, n.x * col + n.y);
}
}
}
}
for(int i = 0; i < row; i++)
for(int j = 0; j < col; j++)
//System.out.println(i + " " + j);
if (grid[i][j] == '0')
uf.ids[i * col + j] = -1;
Set<Integer> num = new HashSet<>();
for(int i = 0; i < row * col; i++)
num.add(uf.ids[i]);
return num.size() - 1;
}
class Node{
int x, y;
Node(int a, int b){
x = a;
y = b;
}
}
class UF {
int[] ids;
int[] sz;
UF(int n) {
ids = new int[n];
sz = new int[n];
for (int i = 0; i < n; i++) {
ids[i] = i;
sz[i] = 1;
}
}
int root(int i) {
while (i != ids[i]) {
ids[i] = ids[ids[i]];
i = ids[i];
}
return i;
}
public void union(int p, int q) {
int pr = root(p);
int qr = root(q);
if (pr == qr)
return;
if (sz[pr] > sz[qr]) {
ids[qr] = pr;
sz[pr] += sz[qr];
} else {
ids[pr] = qr;
sz[qr] += sz[pr];
}
}
public boolean find(int p, int q) {
return root(p) == root(q);
}
}
class UF_Slow{
int[] ids;
UF_Slow(int n){
ids = new int[n];
for(int i = 0; i < ids.length; i++)
ids[i] = i;
}
void union(int x, int y){
int xId = ids[x];
int yId = ids[y];
for(int i = 0; i < ids.length; i++)
if(ids[i] == xId) ids[i] = yId;
}
boolean find(int x, int y){
return ids[x] == ids[y];
}
}
}
| true
|
e3af5ee8b4c9162344072ec393d83c4f7d68ff00
|
Java
|
jamesdlow/simple-rtf-writer
|
/SimpleRTFWriter/src/com/itseasy/rtf/text/PageDefinition.java
|
ISO-8859-1
| 3,066
| 3.15625
| 3
|
[] |
no_license
|
package com.itseasy.rtf.text;
import com.itseasy.rtf.RtfUtil;
/**
* Definiert die Seitenmae eines RTFDocuments. Neben der Seitengre werden auch die Seitenrnder
* gespeichert. ber die Methode <code>getVisibleLineSize()</code> erhlt man die Gre des
* Schreibbereichs einer Zeile.
*
* @version 0.2.0 31.05.2008
* @author James Low
*/
public class PageDefinition {
// Variablen
private PageSize papersize;
private int margright;
private int margleft;
private int margtop;
private int margbottom;
private int columns;
private int margcolumns;
/**
* Erzeugt eine Seitendefinition in Default (Gre = DIN_A4, Seitenrnder = 2 cm)
*/
public PageDefinition() {
this(PageSize.DIN_A4, 20, 20, 20, 20);
}
/**
* Erzeugt eine Seitendefinition mit der Papiergre und den Seitenrndern (in Millimeter).
*
* @param ps - Papiergre
* @param marginleft - Seitenrand links
* @param marginright - Seitenrand rechts
* @param margintop - Seitenrand oben
* @param marginbottom - Seitenrand unten
*/
public PageDefinition(PageSize ps, double marginleft, double marginright, double margintop, double marginbottom) {
this(ps, marginleft, marginright, margintop, marginbottom, 1, 20);
}
/**
* Erzeugt eine Seitendefinition mit der Papiergre und den Seitenrndern (in Millimeter).
*
* @param ps - Papiergre
* @param marginleft - Seitenrand links
* @param marginright - Seitenrand rechts
* @param margintop - Seitenrand oben
* @param marginbottom - Seitenrand unten
* @param columns - Number columns
* @param margincolumns - Seitenrand columns
*/
public PageDefinition(PageSize ps, double marginleft, double marginright, double margintop, double marginbottom, int columns, double margincolumns) {
this.papersize = ps;
this.margleft = RtfUtil.getTwipFromMillimeter(marginleft);
this.margright = RtfUtil.getTwipFromMillimeter(marginright);
this.margtop = RtfUtil.getTwipFromMillimeter(margintop);
this.margbottom = RtfUtil.getTwipFromMillimeter(marginbottom);
this.columns = columns;
this.margcolumns = RtfUtil.getTwipFromMillimeter(margincolumns);
}
/**
* Gibt den RTF String zurck, welcher dieses Element mit RTF Steuerzeichen definiert.
*
* @return RTF String
*/
public String getRtfContent() {
return "\\paperw" + papersize.getWidth() + "\\paperh" + papersize.getHeight()
+ "\\margl" + margleft + "\\margr" + margright + "\\margt" + margtop + "\\margb" + margbottom
+ "\\cols" + columns + "\\colsx"+ margcolumns;
}
/**
* Gibt die Gre des mglichen Schreibbereiches einer Zeile in Millimetern zurck.
*
* @return - Schreibbare Zeilenbreite in Millimetern
*/
public double getVisibleLineSize() {
return RtfUtil.getMillimeterFromTwip(papersize.getWidth() - margleft - margright);
}
}
| true
|
948dbcdf11d9eb60b545fc54d06773364b526fe3
|
Java
|
zuoyy/dev
|
/modules/src/main/java/com/zuoyy/modules/system/service/impl/MenuServiceImpl.java
|
UTF-8
| 4,015
| 2.25
| 2
|
[] |
no_license
|
package com.zuoyy.modules.system.service.impl;
import com.zuoyy.common.enums.StatusEnum;
import com.zuoyy.modules.system.domain.Menu;
import com.zuoyy.modules.system.repository.MenuRepository;
import com.zuoyy.modules.system.service.MenuService;
import com.zuoyy.modules.common.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements MenuService {
@Autowired
private MenuRepository menuRepository;
/**
* 获取排序最大值
* @param pid 父菜单ID
*/
@Override
public Integer getSortMax(String pid){
return menuRepository.findSortMax(pid);
}
/**
* 根据菜单对象的Example判断是否存在
* @param menu 菜单对象
*/
@Override
public Menu getByMenuToExample(Menu menu) {
return menuRepository.findOne(Example.of(menu)).orElse(null);
}
/**
* 获取菜单列表数据
*/
@Override
public List<Menu> getListBySortOk() {
Sort sort = new Sort(Sort.Direction.ASC, "type", "sort");
return menuRepository.findAllByStatus(sort, StatusEnum.OK.code);
}
/**
* 根据父级菜单ID获取本级全部菜单
* @param pid 父菜单ID
* @param notId 需要排除的菜单ID
*/
@Override
public List<Menu> getListByPid(String pid, String notId){
Sort sort = new Sort(Sort.Direction.ASC, "sort");
return menuRepository.findByPidAndIdNotAndStatus(sort, pid, notId,StatusEnum.OK.code);
}
@Override
public List<Menu> getListByType(int type) {
Sort sort = new Sort(Sort.Direction.ASC, "sort");
return menuRepository.findByTypeAndStatus(sort,type,StatusEnum.OK.code);
}
@Override
public List<Menu> getListByPidAndType(String pid, int type) {
Sort sort = new Sort(Sort.Direction.ASC, "sort");
return menuRepository.findByPidAndTypeAndStatus(sort,pid,type,StatusEnum.OK.code);
}
@Override
public Menu findByPerms(String perms) {
return menuRepository.findByPermsAndStatus(perms,StatusEnum.OK.code);
}
@Override
public boolean repeatByPerms(Menu menu) {
String id = "";
if(!StringUtils.isEmpty(menu.getId())){
id = menu.getId();
}
return menuRepository.findByPermsAndIdNot(menu.getPerms(), id) != null;
}
@Override
public List<Menu> getListByPid(String pid) {
Sort sort = new Sort(Sort.Direction.ASC, "sort");
return menuRepository.findByPid(sort, pid);
}
/**
* 状态(启用,冻结,删除)/批量状态处理
*/
@Override
@Transactional
public Boolean updateStatus(StatusEnum statusEnum, List<String> ids){
// 获取与之关联的所有菜单
Set<Menu> treeMenus = new HashSet<>();
List<Menu> menus = menuRepository.findByIdIn(ids);
menus.forEach(menu -> {
treeMenus.add(menu);
treeMenus.addAll(menuRepository.findByPidsLikeAndStatus("%[" + menu.getId() + "]%", menu.getStatus()));
});
treeMenus.forEach(menu -> {
// 删除菜单状态时,同时更新角色的权限
if(statusEnum == StatusEnum.DELETE){
/*menu.getRoles().forEach(role -> {
role.getMenus().remove(menu);
});*/
// 非规范的Jpa操作,直接采用SQL语句
menuRepository.cancelRoleJoin(menu.getId());
}
// 更新关联的所有菜单状态
menu.setStatus(statusEnum.code);
});
return treeMenus.size() > 0;
}
}
| true
|
172ef6c9eeb66769f79d7782a33b0425aeb3bf1a
|
Java
|
tuorao/hanium
|
/src/kr/co/makeit/hanium/rest/Parser.java
|
UTF-8
| 1,516
| 2.46875
| 2
|
[] |
no_license
|
package kr.co.makeit.hanium.rest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
public class Parser {
String result, line;
public String PostParse (ArrayList<NameValuePair> post, String url) {
result = "";
line = null;
DefaultHttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
/* 타임아웃 설정 */
HttpParams httpParams = client.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
HttpConnectionParams.setSoTimeout(httpParams, 3000);
HttpResponse httpResponse;
try {
/* POST 파라미터를 UTF-8로 저장 */
UrlEncodedFormEntity encodedFormEntity = new UrlEncodedFormEntity(post, "UTF-8");
httpPost.setEntity(encodedFormEntity);
httpResponse = client.execute(httpPost);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
while((line = bufferedReader.readLine()) != null){
result += line;
}
return result;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
| true
|
65bf08dae0e3a30d4f942505a11c89b8f8c32a74
|
Java
|
Nanging/pet-care
|
/PetC/src/main/java/com/stu/petc/beans/ShareCommenter.java
|
UTF-8
| 1,059
| 2.234375
| 2
|
[] |
no_license
|
package com.stu.petc.beans;
import java.io.Serializable;
import java.sql.Timestamp;
public class ShareCommenter implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Integer commenter;
private String username;
private String comment;
private Timestamp comment_date;
public Integer getCommenter() {
return commenter;
}
public void setCommenter(Integer commenter) {
this.commenter = commenter;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public Timestamp getComment_date() {
return comment_date;
}
public void setComment_date(Timestamp comment_date) {
this.comment_date = comment_date;
}
@Override
public String toString() {
return "ShareCommenter [commenter=" + commenter + ", username=" + username + ", comment=" + comment
+ ", comment_date=" + comment_date + "]";
}
}
| true
|
cdb36dc7621e5cc89b3dde36f643fd2c53ed8414
|
Java
|
gatsza/GreenBay
|
/src/test/java/org/gfa/greenbay/unit/UserServiceTest.java
|
UTF-8
| 1,225
| 2.21875
| 2
|
[] |
no_license
|
package org.gfa.greenbay.unit;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.when;
import java.util.Optional;
import org.gfa.greenbay.models.User;
import org.gfa.greenbay.repositories.UserRepository;
import org.gfa.greenbay.security.JwtUtilService;
import org.gfa.greenbay.services.UserServiceImpl;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
public class UserServiceTest {
@InjectMocks
UserServiceImpl userService;
@Mock
private JwtUtilService jwtUtilService;
@Mock
private UserRepository userRepository;
@Test
public void generateTokenTest_returnToken_rightValue() {
String testUsername = "username";
User testUser = new User();
Optional<User> testUserOptional = Optional.of(new User());
String testToken = "token";
when(userRepository.findUserByUsername(testUsername)).thenReturn(testUserOptional);
when(jwtUtilService.generateToken(testUser)).thenReturn(testToken);
assertEquals("token", userService.generateToken("username"));
}
}
| true
|
5c915c84964ea952946234be168ab0deb043c9b0
|
Java
|
t1anist/SSMLearning
|
/Chapter10SetUpSpringBean/src/com/chapter10/AnnotationMain.java
|
UTF-8
| 558
| 2.265625
| 2
|
[] |
no_license
|
package com.chapter10;
import com.chapter10.annotation.pojo.PojoConfig;
import com.chapter10.annotation.pojo.Role;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class AnnotationMain {
public static void main(String args[]){
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(PojoConfig.class);
Role role = applicationContext.getBean(Role.class);
System.out.println(role.getId());
}
}
| true
|
1dcb3d69b98c93ec9f38369da9a8b58eae246f7f
|
Java
|
supachawal/JavaProgramming
|
/codeforces/src/P348A_Mafia_CORRECT.java
|
UTF-8
| 890
| 3.0625
| 3
|
[] |
no_license
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
/*
* Input
7
9 7 7 8 8 7 8
Output
10
Answer
9
Input
10
94 96 91 95 99 94 96 92 95 99
Output
100
Answer
106
*/
public class P348A_Mafia_CORRECT {
private static BufferedReader br;
private static PrintWriter pw;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(System.out);
int i, n = Integer.parseInt(br.readLine());
String[] splitted = br.readLine().split("\\s+");
long maxValue = 0;
long sum = 0;
for (i = 0; i < n; i++) {
long num = Long.parseLong(splitted[i]);
maxValue = Math.max(maxValue, num);
sum += num;
}
long answer = Math.max(maxValue, (sum + n - 2) / (n - 1) /* round-up */);
pw.printf("%d\n", answer);
pw.close();
}
}
| true
|
ff81f3dacb82d64c5159e2216f5eea2ef68471c2
|
Java
|
ziewkaa/WARSZTATY_6_CRM
|
/src/main/java/pl/coderslab/crm/service/ProjectService.java
|
UTF-8
| 334
| 1.898438
| 2
|
[] |
no_license
|
package pl.coderslab.crm.service;
import pl.coderslab.crm.entity.Project;
import java.util.List;
public interface ProjectService {
Project findProjectByGivenId(Long id);
List<Project> findAllProjectsOrderByCreatedDesc();
List<Project> findTop5ProjectsOrderByCreatedDesc();
void saveProject(Project project);
}
| true
|
ad40e3af89c576db46af5b1874aa1b63771efcee
|
Java
|
mkbiltek/SOR
|
/libSOR/src/org/uddi/subr_v3/ObjectFactory.java
|
UTF-8
| 1,834
| 1.960938
| 2
|
[] |
no_license
|
package org.uddi.subr_v3;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlElementDecl;
import javax.xml.bind.annotation.XmlRegistry;
import javax.xml.namespace.QName;
/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the org.uddi.subr_v3 package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {
private final static QName _NotifySubscriptionListener_QNAME = new QName("urn:uddi-org:subr_v3", "notify_subscriptionListener");
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.uddi.subr_v3
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {@link NotifySubscriptionListener }
*
*/
public NotifySubscriptionListener createNotifySubscriptionListener() {
return new NotifySubscriptionListener();
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link NotifySubscriptionListener }{@code >}}
*
*/
@XmlElementDecl(namespace = "urn:uddi-org:subr_v3", name = "notify_subscriptionListener")
public JAXBElement<NotifySubscriptionListener> createNotifySubscriptionListener(NotifySubscriptionListener value) {
return new JAXBElement<NotifySubscriptionListener>(_NotifySubscriptionListener_QNAME, NotifySubscriptionListener.class, null, value);
}
}
| true
|
ad00754928cd144424a5fc5127149d6e17c47bd8
|
Java
|
allaallala/wings_maven
|
/src/test/java/edu/msstate/nsparc/wings/integration/tests/participant/editProfile/TC_31_02_EP_General_Resume_View.java
|
UTF-8
| 1,462
| 2.28125
| 2
|
[] |
no_license
|
package edu.msstate.nsparc.wings.integration.tests.participant.editProfile;
import edu.msstate.nsparc.wings.integration.constants.Constants;
import edu.msstate.nsparc.wings.integration.forms.home.ParticipantHomePage;
import edu.msstate.nsparc.wings.integration.forms.participant.participantSS.participantSSDetails.BaseParticipantSsDetailsForm;
import edu.msstate.nsparc.wings.integration.models.participant.Participant;
import edu.msstate.nsparc.wings.integration.steps.BaseNavigationSteps;
import edu.msstate.nsparc.xray.info.TestCase;
/**
* In this test, we check if sections in the resume view are displayed correctly and can be edited.
* Created by a.vnuchko on 30.10.2016.
*/
@TestCase(id = "WINGS-11160")
public class TC_31_02_EP_General_Resume_View extends TC_31_01_EP_General_Standard_View {
public void main() {
Participant participant = precondition();
logStep("Log in to the System");
BaseNavigationSteps.loginParticipant();
logStep("Navigate to My Profile");
ParticipantHomePage homePage = new ParticipantHomePage(Constants.PARTICIPANT_SS);
homePage.openMyProfile();
logStep("Click [Resume View] button");
BaseParticipantSsDetailsForm detailPage = new BaseParticipantSsDetailsForm(participant);
detailPage.clickResumeView();
logResult("Resume view is opened. Every section can be edited from here.");
detailPage.checkButtonsResumeView();
}
}
| true
|
9f09c44e87bc760a4057503ae3ba3aca809374f1
|
Java
|
xushaomin/apple-id
|
/apple-id-jdbc/src/main/java/com/appleframework/id/JdbcIdGenerator.java
|
UTF-8
| 10,155
| 2.296875
| 2
|
[] |
no_license
|
package com.appleframework.id;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import javax.sql.DataSource;
import org.apache.commons.dbcp2.BasicDataSource;
import org.springframework.dao.DeadlockLoserDataAccessException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.SingleConnectionDataSource;
import com.appleframework.id.exception.IdException;
/**
* This id generator utilizes JDBC to generate serial IDs.
*
* <p>
* Persistency: IDs generated by this id-generator are persistent (assuming the
* database backend runs in persistent mode).
* </p>
*
* @author Thanh Nguyen <btnguyen2k@gmail.com>
* @since 0.3.0
*/
public class JdbcIdGenerator extends SerialIdGenerator implements IdentityGenerator {
/**
* Helper method to obtain {@link JdbcIdGenerator}.
*
* @param zkConnString
* @return
*/
public static JdbcIdGenerator getInstance(final String jdbcDriver, final String jdbcUrl,
final String jdbcUser, final String jdbcPassword, final String jdbcTableName) {
try {
// final HashCodeBuilder hcb = new HashCodeBuilder(19, 81);
// hcb.append(jdbcDriver).append(jdbcUrl).append(jdbcUser).append(jdbcPassword)
// .append(jdbcTableName);
// final String hashKey = String.valueOf(hcb.hashCode()) + "-" +
// jdbcUrl + "-" + jdbcUser
// + "-" + jdbcTableName;
final StringBuffer key = new StringBuffer();
key.append(jdbcUrl).append("|").append(jdbcUser).append("|").append(jdbcPassword)
.append("|").append(jdbcTableName);
JdbcIdGenerator idGen = (JdbcIdGenerator) idGenerators.get(key.toString(),
new Callable<SerialIdGenerator>() {
@Override
public SerialIdGenerator call() throws Exception {
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName(jdbcDriver);
ds.setUrl(jdbcUrl);
ds.setUsername(jdbcUser);
ds.setPassword(jdbcPassword);
JdbcIdGenerator idGen = new JdbcIdGenerator();
idGen.setTableName(jdbcTableName).setDataSource(ds).init();
return idGen;
}
});
return idGen;
} catch (ExecutionException e) {
return null;
}
}
private DataSource dataSource;
private String tableName;
private String sqlInsert, sqlUpdate, sqlSelect, sqlUpdateSet;
private String colName = "id_name";
private String colValue = "id_value";
public DataSource getDataSource() {
return dataSource;
}
public JdbcIdGenerator setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
return this;
}
public String getTableName() {
return tableName;
}
public JdbcIdGenerator setTableName(String tableName) {
this.tableName = tableName;
return this;
}
private Connection connection() throws SQLException {
return dataSource.getConnection();
}
private JdbcTemplate jdbcTemplate(Connection conn) {
return new JdbcTemplate(new SingleConnectionDataSource(conn, true));
}
/**
* {@inheritDoc}
*/
@Override
public JdbcIdGenerator init() {
super.init();
sqlInsert = MessageFormat.format("INSERT INTO {0} ({1}, {2}) VALUES (?, 0)", tableName,
colName, colValue);
sqlUpdate = MessageFormat.format("UPDATE {0} SET {2}={2}+1 WHERE {1}=?", tableName,
colName, colValue);
sqlUpdateSet = MessageFormat.format("UPDATE {0} SET {2}=? WHERE {1}=?", tableName, colName,
colValue);
sqlSelect = MessageFormat.format("SELECT {2} FROM {0} WHERE {1}=?", tableName, colName,
colValue);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public void destroy() {
super.destroy();
}
private boolean _update(final JdbcTemplate jdbcTemplate, final String namespace,
final int numRetries, final int maxRetries) {
try {
int status = jdbcTemplate.update(sqlUpdate, namespace);
return status > 0;
} catch (DeadlockLoserDataAccessException dle) {
if (numRetries > maxRetries) {
throw dle;
} else {
return _update(jdbcTemplate, namespace, numRetries + 1, maxRetries);
}
}
}
/**
* @since 0.4.0
*/
private boolean _updateSet(final JdbcTemplate jdbcTemplate, final String namespace,
final long value, final int numRetries, final int maxRetries) {
try {
int status = jdbcTemplate.update(sqlUpdateSet, value, namespace);
return status > 0;
} catch (DeadlockLoserDataAccessException dle) {
if (numRetries > maxRetries) {
throw dle;
} else {
return _updateSet(jdbcTemplate, namespace, value, numRetries + 1, maxRetries);
}
}
}
private final static Long ZERO = new Long(0);
private Long _select(final JdbcTemplate jdbcTemplate, final String namespace,
final int numRetries, final int maxRetries) {
try {
Long result = jdbcTemplate.queryForObject(sqlSelect, Long.class, namespace);
return result;
} catch (EmptyResultDataAccessException e) {
return ZERO;
} catch (DeadlockLoserDataAccessException dle) {
if (numRetries > maxRetries) {
throw dle;
} else {
return _select(jdbcTemplate, namespace, numRetries + 1, maxRetries);
}
}
}
private boolean _insert(JdbcTemplate jdbcTemplate, final String namespace,
final int numRetries, final int maxRetries) {
try {
int status = jdbcTemplate.update(sqlInsert, namespace);
return status > 0;
} catch (DeadlockLoserDataAccessException dle) {
if (numRetries > maxRetries) {
throw dle;
} else {
return _insert(jdbcTemplate, namespace, numRetries + 1, maxRetries);
}
} catch (DuplicateKeyException e) {
return true;
}
}
/**
* @since 0.3.3
*/
private long nextId(final String namespace, final boolean firstRun) {
// normal case: update & get the value
try {
Connection conn = connection();
if (conn != null) {
try {
conn.setAutoCommit(false);
JdbcTemplate jdbcTemplate = jdbcTemplate(conn);
if (_update(jdbcTemplate, namespace, 0, 3)) {
Long result = _select(jdbcTemplate, namespace, 0, 3);
conn.commit();
return result != null ? result.longValue() : 0;
}
} catch (SQLException e) {
conn.rollback();
throw e;
} finally {
conn.close();
}
} else {
return -1;
}
} catch (SQLException e) {
throw new IdException.OperationFailedException(e);
}
if (!firstRun) {
throw new IdException.OperationFailedException();
}
// first update failed, the row does not exist in db table, try to
// insert it
try {
Connection conn = connection();
if (conn != null) {
try {
conn.setAutoCommit(true);
JdbcTemplate jdbcTemplate = jdbcTemplate(conn);
_insert(jdbcTemplate, namespace, 0, 3);
} finally {
conn.close();
}
}
} catch (SQLException e) {
throw new IdException.OperationFailedException(e);
}
// try to get next id again, once
return nextId(namespace, false);
}
/**
* {@inheritDoc}
*/
@Override
public long nextId(final String namespace) {
return nextId(namespace, true);
}
/**
* {@inheritDoc}
*/
@Override
public long currentId(final String namespace) {
try {
Connection conn = connection();
if (conn != null) {
try {
conn.setAutoCommit(true);
JdbcTemplate jdbcTemplate = jdbcTemplate(conn);
Long result = _select(jdbcTemplate, namespace, 0, 3);
return result != null ? result.longValue() : 0;
} finally {
conn.close();
}
} else {
return -1;
}
} catch (SQLException e) {
throw new IdException.OperationFailedException(e);
}
}
/**
* {@inheritDoc}
*
* @since 0.4.0
*/
@Override
public boolean setValue(final String namespace, final long value) {
try {
Connection conn = connection();
if (conn != null) {
try {
conn.setAutoCommit(true);
JdbcTemplate jdbcTemplate = jdbcTemplate(conn);
return _updateSet(jdbcTemplate, namespace, value, 0, 3);
} finally {
conn.close();
}
} else {
return false;
}
} catch (SQLException e) {
throw new IdException.OperationFailedException(e);
}
}
}
| true
|
e8026f02f0c0d316296795eb4d09d0ca06821483
|
Java
|
KTSNVT-TIM1/Projekat
|
/Backend/src/test/java/ktsnvt/tim1/services/UserServiceUnitTests.java
|
UTF-8
| 7,489
| 2.171875
| 2
|
[] |
no_license
|
package ktsnvt.tim1.services;
import ktsnvt.tim1.DTOs.ChangePasswordDTO;
import ktsnvt.tim1.DTOs.UserDTO;
import ktsnvt.tim1.exceptions.EntityNotValidException;
import ktsnvt.tim1.mappers.UserMapper;
import ktsnvt.tim1.model.User;
import ktsnvt.tim1.repositories.UserRepository;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@ActiveProfiles("test")
public class UserServiceUnitTests {
@Autowired
private UserService userService;
@MockBean
private UserRepository userRepositoryMocked;
@MockBean
private PasswordEncoder passwordEncoderMocked;
@MockBean
private UserMapper userMapperMocked;
private void setUpPrincipal(User user) {
Authentication authentication = Mockito.mock(Authentication.class);
SecurityContext securityContext = Mockito.mock(SecurityContext.class);
Mockito.when(securityContext.getAuthentication()).thenReturn(authentication);
Mockito.when(authentication.getPrincipal()).thenReturn(user);
SecurityContextHolder.setContext(securityContext);
}
@Test
void editUser_userIdIsNull_entityNotValidExceptionThrown(){
User user = new User();
setUpPrincipal(user);
UserDTO editedUser = new UserDTO(null, "Petar", "Petrovic", "KtsNvt1+", "ppetrovic@gmail.com", true);
assertThrows(EntityNotValidException.class, () -> userService.editUser(editedUser));
}
@Test
void editUser_notAllowedUser_entityNotValidExceptionThrown(){
User user = new User();
user.setId(2L);
setUpPrincipal(user);
Long id = 1L;
UserDTO editedUser = new UserDTO(id,"Petar", "Petrovic", "KtsNvt1+", "ppetrovic@gmail.com", true );
assertThrows(EntityNotValidException.class, () -> userService.editUser(editedUser));
}
@Test
void editUser_userEmailChanged_entityNotValidExceptionThrown(){
Long id = 1L;
User user = new User(id,"Petar", "Petrovic", "KtsNvt1+", "ppetrovic@gmail.com", true );
setUpPrincipal(user);
UserDTO editedUser = new UserDTO(id,"Petar", "Petrovic", "KtsNvt1+", "ppetrovic1@gmail.com", true );
Mockito.when(userRepositoryMocked.findById(id)).thenReturn(Optional.of(user));
assertThrows(EntityNotValidException.class, () -> userService.editUser(editedUser));
}
@Test
void editUser_userExists_userReturned() throws EntityNotValidException{
Long id = 1L;
User user = new User(id,"Petar", "Petrovic", "$2y$12$FDOJQfuSrC7UAvBaUaX7UuP9NwZcZGI2joxQcHlzjEMXJBr57XAX6", "ppetrovic@gmail.com", true );;
setUpPrincipal(user);
UserDTO editedDTO = new UserDTO(id,"Petar", "Petrovic", "KtsNvt1++", "ppetrovic@gmail.com", true );
User newUser = new User(id,"Petar", "Petrovic", "$2y$12$y87u8NVCv7wFEcN9kmhvQeJuqfUP3RXbZz2xKhc94aMs6OrXKZYtW", "ppetrovic@gmail.com", true );
UserDTO returnedDTO = new UserDTO(id,"Petar", "Petrovic", null, "ppetrovic@gmail.com", true );
Mockito.when(passwordEncoderMocked.encode(editedDTO.getPassword())).thenReturn("$2y$12$y87u8NVCv7wFEcN9kmhvQeJuqfUP3RXbZz2xKhc94aMs6OrXKZYtW\n");
Mockito.when(userRepositoryMocked.save(user)).thenReturn(newUser);
Mockito.when(userMapperMocked.toDTO(newUser)).thenReturn(returnedDTO);
UserDTO editedUser = userService.editUser(editedDTO);
assertEquals(editedDTO.getId(), editedUser.getId());
assertEquals(editedDTO.getEmail(), editedUser.getEmail());
assertEquals(editedDTO.getFirstName(), editedUser.getFirstName());
assertEquals(editedDTO.getLastName(), editedUser.getLastName());
assertNull(editedUser.getPassword());
assertEquals(editedDTO.getVerified(), editedUser.getVerified());
verify(passwordEncoderMocked, times(1)).encode(editedDTO.getPassword());
verify(userRepositoryMocked, times(1)).save(user);
verify(userMapperMocked, times(1)).toDTO(newUser);
}
@Test
void changePassword_incorrectOldPassword_entityNotValidExceptionThrown(){
User user = new User();
user.setPassword("$2y$12$YATuOt2bcLaly5c0aMLx/e5l.wg6fLHmicF.Uj02Pl0tmRtCqk6NC");
setUpPrincipal(user);
ChangePasswordDTO changePasswordDTO = new ChangePasswordDTO("123", "KtsNvtTim1+", "KtsNvtTim1+");
Mockito.when(passwordEncoderMocked.matches(changePasswordDTO.getOldPassword(), user.getPassword())).thenReturn(false);
assertThrows(EntityNotValidException.class, () -> userService.changePassword(changePasswordDTO));
verify(passwordEncoderMocked, times(1)).matches(changePasswordDTO.getOldPassword(), user.getPassword());
}
@Test
void changePassword_passwordsDontMatch_entityNotValidExceptionThrown(){
User user = new User();
user.setPassword("$2a$04$Vbug2lwwJGrvUXTj6z7ff.97IzVBkrJ1XfApfGNl.Z695zqcnPYra");
setUpPrincipal(user);
ChangePasswordDTO changePasswordDTO = new ChangePasswordDTO("123", "KtsNvtTim1+", "KtsNvtTim1++");
Mockito.when(passwordEncoderMocked.matches(changePasswordDTO.getOldPassword(), user.getPassword())).thenReturn(true);
assertThrows(EntityNotValidException.class, () -> userService.changePassword(changePasswordDTO));
verify(passwordEncoderMocked, times(1)).matches(changePasswordDTO.getOldPassword(), user.getPassword());
}
@Test
void changePassword_passwordsOk_true() throws EntityNotValidException {
Long id = 1L;
String password = "$2y$12$YVTUQqw5VcyZTrH7rP7k/.iZsZxA8RK93szRmf.xUk9Cm0XzFl0dG";
String newPassword = "$2y$12$Gx9OessyeXO4.dZrP9uSsuaTUG2XJqdLWPzC0x1vF7DcoyTSgNBbi";
User user = new User(id,"Petar", "Petrovic", password, "ppetrovic@gmail.com", true );;
setUpPrincipal(user);
ChangePasswordDTO changePasswordDTO = new ChangePasswordDTO("123", "KtsNvtTim1+", "KtsNvtTim1+");
User newUser = new User(id,"Petar", "Petrovic", newPassword, "ppetrovic@gmail.com", true );
Mockito.when(passwordEncoderMocked.matches(changePasswordDTO.getOldPassword(), password)).thenReturn(true);
Mockito.when(passwordEncoderMocked.encode(changePasswordDTO.getPassword())).thenReturn(newPassword);
Mockito.when(userRepositoryMocked.save(user)).thenReturn(newUser);
boolean success = userService.changePassword(changePasswordDTO);
assertTrue(success);
verify(passwordEncoderMocked, times(1)).matches(changePasswordDTO.getOldPassword(), password);
verify(passwordEncoderMocked, times(1)).encode(changePasswordDTO.getPassword());
verify(userRepositoryMocked, times(1)).save(user);
}
}
| true
|
015bbaa2dd3c463b27e105eefc51b2265d8082e7
|
Java
|
avsilva/daam-2016
|
/PinPointHint/app/src/main/java/pt/iscte/daam/pinpointhint/MainActivity.java
|
UTF-8
| 793
| 1.921875
| 2
|
[] |
no_license
|
package pt.iscte.daam.pinpointhint;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().hide();
}
public void showRegistar(View v){
Intent regIntent = new Intent(this, RegistrationActivity.class);
startActivity(regIntent);
}
public void showLogin(View v){
Intent loginIntent = new Intent (this, LoginActivity.class);
startActivity(loginIntent);
}
}
| true
|
4e00243557a9aa9a2155d6d82a376701b1e698a8
|
Java
|
Churritosjesus/Chromecast-Reverse-Engineering
|
/chromecast-app-reverse-engineering/src/from-androguard-dad-broken-but-might-help/alk.java
|
UTF-8
| 1,503
| 1.890625
| 2
|
[] |
no_license
|
private a
private b
private synthetic android.widget.Spinner c
private synthetic all d
private synthetic java.lang.String e
public alk(com.google.android.apps.chromecast.app.DebugActivity p2, android.widget.Spinner p3, all p4, String p5)
{
this.c = p3;
this.d = p4;
this.e = p5;
this.a = 0;
this.b = this.c.getSelectedItemPosition();
return;
}
public final void onItemSelected(android.widget.AdapterView p4, android.view.View p5, int p6, long p7)
{
if ((this.a) || (p6 == this.b)) {
this.a = 0;
} else {
int v0_4 = com.google.android.apps.chromecast.app.DebugActivity.a(((String) p4.getItemAtPosition(p6)), this.d.c());
String[] v2_3 = this.d.d();
if (v0_4 < 0) {
v0_4 = 0;
}
int v0_5 = v2_3[v0_4];
if (!this.e.equals(v0_5)) {
this.d.a(v0_5);
}
if (android.text.TextUtils.isEmpty(v0_5)) {
int v0_9 = com.google.android.apps.chromecast.app.DebugActivity.a(this.d.a(), this.d.d());
if (v0_9 >= 0) {
this.a = 1;
this.c.setSelection(v0_9);
}
}
}
this.b = this.c.getSelectedItemPosition();
return;
}
public final void onNothingSelected(android.widget.AdapterView p1)
{
return;
}
| true
|
75767eee0a617c1d64b3994cb1a808e7f070c78f
|
Java
|
dhanin/Simple-Chatty-Bot
|
/Problems/The (un)-ordered sequence/src/Main.java
|
UTF-8
| 2,063
| 3.078125
| 3
|
[] |
no_license
|
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int input1 = 0;
int input2 = 0;
int temp = 0;
boolean stateChange = false;
int preState = 0;
int startState = 0;
if (scanner.hasNext()) {
input1 = scanner.nextInt();
}
if (scanner.hasNext()) {
input2 = scanner.nextInt();
if (input2 == 0) {
System.out.println(true);
return;
} else { //define start state
preState = input2 - input1 == 0 ? 0 : input2 - input1 > 0 ? 1 : -1;
if (preState != 0)
startState = preState;
}
}
temp = input2;
while (scanner.hasNext())
{
int input3 = scanner.nextInt();
if (input3 == 0)
{
break;
}
int currentState = 0;
if (startState == 0)
{
currentState = input3 - temp == 0 ? 0 : input3 - temp > 0 ? 1 : -1;
if (currentState == 0)
{
temp = input3;
continue;
}
else
{
startState = currentState;
temp = input3;
continue;
}
}
else
{
currentState = input3 - temp == 0 ? 0 : input3 - temp > 0 ? 1 : -1;
if (currentState == 0)
{
temp = input3;
continue;
}
else if (currentState == startState)
{
temp = input3;
continue;
}
else
{
System.out.println(false);
return;
}
}
}
System.out.println(true);
}
}
| true
|
d1ba944badd92c8dfec35399934f28a95607b1a9
|
Java
|
LP1991/architech-study
|
/leetcode/src/main/java/priv/primo/disruptor/DisruptorMainTest.java
|
UTF-8
| 3,742
| 2.421875
| 2
|
[] |
no_license
|
/********************** 版权声明 *************************
* 文件名: DisruptorMainTest.java
* 包名: priv.primo.disruptor
* 版权: 杭州华量软件 architectstudy
* 职责:
********************************************************
*
* 创建者:Primo 创建时间:2019/8/15
* 文件版本:V1.0
*
*******************************************************/
package priv.primo.disruptor;
import com.lmax.disruptor.*;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;
import com.lmax.disruptor.util.DaemonThreadFactory;
import java.nio.ByteBuffer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class DisruptorMainTest {
public static final EventFactory<Node> EVENT_FACTORY = new EventFactory<Node>()
{
public Node newInstance()
{
return new Node(1);
}
};
private static final ExecutorService executor = Executors.newSingleThreadExecutor(DaemonThreadFactory.INSTANCE);
private static final RingBuffer<Node> ringBuffer = RingBuffer.createMultiProducer(EVENT_FACTORY, 32);
private static final SequenceBarrier sequenceBarrier = ringBuffer.newBarrier();
{
ringBuffer.addGatingSequences(new NoOpEventProcessor(ringBuffer).getSequence());
}
public static final EventTranslatorTwoArg<String, Integer, String> TRANSLATOR =
new EventTranslatorTwoArg<String, Integer, String>()
{
@Override
public void translateTo(String event, long sequence, Integer arg0, String arg1)
{
event = event.concat("2222").concat(arg1);
}
};
private static final EventTranslatorOneArg<Node, Integer> transOne = (Node event, long sequence, Integer arg0) ->{
event.val += arg0;
};
private static class ValueEntry{
}
public static void main(String[] args) throws InterruptedException, TimeoutException, AlertException {
// assertEquals(SingleProducerSequencer.INITIAL_CURSOR_VALUE, ringBuffer.getCursor());
System.out.println(ringBuffer.getCursor());
String expectedEvent = String.valueOf(2071);
ringBuffer.publishEvent(transOne,1);
long sequence = sequenceBarrier.waitFor(0);
System.out.println("sequence:"+sequence);
Node event = ringBuffer.get(sequence);
System.out.println("event:"+event.val);
System.out.println(ringBuffer.getCursor());
}
public void crud(){
// RingBuffer生产工厂,初始化RingBuffer的时候使用
EventFactory<String> factory = new EventFactory<String>() {
@Override
public String newInstance() {
return new String("1");
}
};
RingBuffer<String> ringBuffer = RingBuffer.createSingleProducer(factory, 16,new BlockingWaitStrategy());
SequenceBarrier sequenceBarrier = ringBuffer.newBarrier();
AggregateEventHandler handler = new AggregateEventHandler();
BatchEventProcessor<String> processor = new BatchEventProcessor<>(ringBuffer,sequenceBarrier,handler);
ringBuffer.addGatingSequences(processor.getSequence());
new Thread(processor).run();
ByteBuffer bb = ByteBuffer.allocate(8);
for (int i = 0; i < 10; i++) {
bb.putLong(0,i);
ringBuffer.publishEvent((event, seq, buffer) -> event.concat("111"),bb);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Node {
int val;
public Node(int val) {
this.val = val;
}
}
| true
|
e10dfb55b8443a875811163932b0e04ca04a8a08
|
Java
|
jasondellaluce/Mitro
|
/src/mitro/model/VoceOperazioneLog.java
|
UTF-8
| 415
| 2.34375
| 2
|
[] |
no_license
|
package mitro.model;
import java.time.LocalDateTime;
public class VoceOperazioneLog extends VoceLog {
private String operazione;
public VoceOperazioneLog(LocalDateTime dataOra, String operazione) {
super(dataOra);
this.operazione = operazione;
}
public String getOperazione() {
return operazione;
}
@Override
public String getContenuto() {
return getOperazione();
}
}
| true
|
faf130313c71f6cc07c3b8bf65e1894551716cc9
|
Java
|
RanranHe/CS4500_Movie-Website
|
/Movie_Website/cs4500-spring2018-team34/src/main/java/edu/northeastern/cs4500/repositories/CustomerRepository.java
|
UTF-8
| 455
| 2.125
| 2
|
[] |
no_license
|
package edu.northeastern.cs4500.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface CustomerRepository extends JpaRepository<Customer, Integer> {
List<Customer> findByUsername(String username);
List<Customer> findByUsernameLike(String username);
Customer findById(Integer id);
List<Customer> findByIdIn(List<Integer> ids);
boolean existsByUsername(String username);
}
| true
|
1405e1711e7d56a44887c3b51b64fa3d5fdeffde
|
Java
|
haoranle/lymm
|
/src/com/lymm/service/UsersService.java
|
UTF-8
| 459
| 2.140625
| 2
|
[] |
no_license
|
package com.lymm.service;
import com.lymm.dao.UsersDAO;
import com.lymm.impl.UsersDAOImpl;
/**
* Created by ${Seek} on 2017/3/28
*/
public class UsersService {
private UsersDAO usersDAO = new UsersDAOImpl();
/**
* 验证用户登录方法
* @param userName
* @param password
* @return
*/
public boolean login(String userName, String password) {
if (usersDAO.getUsers(userName, password) != null) {
return true;
}
return false;
}
}
| true
|
7c97782c1f783cb85fe379bac0bc2892df013e39
|
Java
|
jonathanmccann/code-eval
|
/java/easy/roman-numerals/Main.java
|
UTF-8
| 980
| 3.234375
| 3
|
[] |
no_license
|
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main (String[] args) throws IOException {
File file = new File(args[0]);
BufferedReader in = new BufferedReader(new FileReader(file));
String line = null;
while ((line = in.readLine()) != null) {
long numeral = Long.valueOf(line);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < _romanNumeralValues.length; i++) {
long numberOfNumerals = numeral / _romanNumeralValues[i];
for (int j = 0; j < numberOfNumerals; j++) {
sb.append(_romanNumerals[i]);
}
numeral = numeral % _romanNumeralValues[i];
}
System.out.println(sb.toString());
}
}
private static String[] _romanNumerals = {
"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"
};
private static int[] _romanNumeralValues = {
1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1
};
}
| true
|
e582b6d50da43fd22f7c8c03ea8bd04e559ff124
|
Java
|
dowsam/rebirth-persistence
|
/src/main/java/cn/com/rebirth/persistence/dao/BaseDao.java
|
UTF-8
| 7,875
| 2.109375
| 2
|
[] |
no_license
|
/*
* Copyright (c) 2005-2012 www.summall.com.cn All rights reserved
* Info:summall-persistence BaseDao.java 2012-2-10 15:42:04 l.xue.nong$$
*/
package cn.com.rebirth.persistence.dao;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.persistence.Query;
import org.apache.commons.lang3.Validate;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;
import cn.com.rebirth.commons.Page;
import cn.com.rebirth.commons.PageRequest;
import cn.com.rebirth.commons.PageRequest.Order;
/**
* The Class BaseDao.
*
* @author l.xue.nong
*/
@Repository
public class BaseDao extends BaseJpaDao {
/** The Constant DEFAULT_ALIAS. */
public static final String DEFAULT_ALIAS = "x";
/**
* Find page.
*
* @param <T> the generic type
* @param pageRequest the page request
* @param qlString the ql string
* @param values the values
* @return the page
*/
@SuppressWarnings("unchecked")
public <T> Page<T> findPage(final PageRequest pageRequest, String qlString, final Object... values) {
Validate.notNull(pageRequest, "pageRequest不能为空");
Page<T> page = new Page<T>(pageRequest);
if (pageRequest.isCountTotal()) {
long totalCount = countqlResult(qlString, values);
page.setTotalItems(totalCount);
}
if (pageRequest.getSort() != null) {
qlString = setOrderParameterToql(removeOrders(qlString), pageRequest);
}
Query q = createQuery(qlString, values);
setPageParameterToQuery(q, pageRequest);
List<T> result = q.getResultList();
page.setResult(result);
return page;
}
/**
* Find page.
*
* @param <T> the generic type
* @param pageRequest the page request
* @param hql the hql
* @param values the values
* @return the page
*/
@SuppressWarnings("unchecked")
public <T> Page<T> findPage(final PageRequest pageRequest, String hql, final Map<String, ?> values) {
Validate.notNull(pageRequest, "page不能为空");
Page<T> page = new Page<T>(pageRequest);
if (pageRequest.isCountTotal()) {
long totalCount = countqlResult(hql, values);
page.setTotalItems(totalCount);
}
if (pageRequest.getSort() != null) {
hql = setOrderParameterToql(removeOrders(hql), pageRequest);
}
Query q = createQuery(hql, values);
setPageParameterToQuery(q, pageRequest);
List<T> result = q.getResultList();
page.setResult(result);
return page;
}
/**
* Sets the page parameter to query.
*
* @param q the q
* @param pageRequest the page request
* @return the query
*/
protected Query setPageParameterToQuery(Query q, PageRequest pageRequest) {
q.setFirstResult(pageRequest.getOffset());
q.setMaxResults(pageRequest.getPageSize());
return q;
}
/**
* Sets the order parameter toql.
*
* @param qlString the ql string
* @param pageRequest the page request
* @return the string
*/
private String setOrderParameterToql(String qlString, PageRequest pageRequest) {
StringBuilder builder = new StringBuilder(qlString);
builder.append(" order by");
for (Order order : pageRequest.getSort()) {
builder.append(String.format(" %s.%s %s,", DEFAULT_ALIAS, order.getProperty(), order.getDirection().name()));
}
builder.deleteCharAt(builder.length() - 1);
return builder.toString();
}
/**
* Countql result.
*
* @param qlString the ql string
* @param values the values
* @return the long
*/
private long countqlResult(String qlString, Object... values) {
String countql = prepareCountql(qlString);
try {
Long count = findUnique(countql, values);
return count;
} catch (Exception e) {
throw new RuntimeException("hql can't be auto count, hql is:" + countql, e);
}
}
/**
* Find.
*
* @param <X> the generic type
* @param queryString the query string
* @param values the values
* @return the list
*/
@SuppressWarnings("unchecked")
public <X> List<X> find(final String queryString, final Object... values) {
return createQuery(queryString, values).getResultList();
}
/**
* Find.
*
* @param <X> the generic type
* @param queryString the query string
* @param values the values
* @return the list
*/
@SuppressWarnings("unchecked")
public <X> List<X> find(final String queryString, final Map<String, ?> values) {
return createQuery(queryString, values).getResultList();
}
/**
* Find unique.
*
* @param <X> the generic type
* @param queryString the query string
* @param values the values
* @return the x
*/
@SuppressWarnings("unchecked")
public <X> X findUnique(final String queryString, final Object... values) {
return (X) createQuery(queryString, values).getSingleResult();
}
/**
* Find unique.
*
* @param <X> the generic type
* @param queryString the query string
* @param values the values
* @return the x
*/
@SuppressWarnings("unchecked")
public <X> X findUnique(final String queryString, final Map<String, ?> values) {
return (X) createQuery(queryString, values).getSingleResult();
}
/**
* Batch execute.
*
* @param hql the hql
* @param values the values
* @return the int
*/
public int batchExecute(final String hql, final Object... values) {
return createQuery(hql, values).executeUpdate();
}
/**
* Batch execute.
*
* @param hql the hql
* @param values the values
* @return the int
*/
public int batchExecute(final String hql, final Map<String, ?> values) {
return createQuery(hql, values).executeUpdate();
}
/**
* Checks if is property unique.
*
* @param <T> the generic type
* @param entityClass the entity class
* @param propertyName the property name
* @param newValue the new value
* @param oldValue the old value
* @return true, if is property unique
*/
public <T> boolean isPropertyUnique(final Class<T> entityClass, final String propertyName, final Object newValue,
final Object oldValue) {
if (newValue == null || newValue.equals(oldValue)) {
return true;
}
Object object = findUniqueBy(entityClass, propertyName, newValue);
return (object == null);
}
/**
* Creates the query.
*
* @param queryString the query string
* @param values the values
* @return the query
*/
private Query createQuery(final String queryString, final Object... values) {
Assert.hasText(queryString, "queryString不能为空");
Query query = this.em.createQuery(queryString);
if (values != null) {
for (int i = 1; i <= values.length; i++) {
query.setParameter(i, values[i - 1]);
}
}
return query;
}
/**
* Creates the query.
*
* @param queryString the query string
* @param values the values
* @return the query
*/
private Query createQuery(final String queryString, final Map<String, ?> values) {
Assert.hasText(queryString, "queryString不能为空");
Query query = em.createQuery(queryString);
if (values != null) {
for (Map.Entry<String, ?> entry : values.entrySet()) {
query.setParameter(entry.getKey(), entry.getValue());
}
}
return query;
}
/**
* Prepare countql.
*
* @param qlString the ql string
* @return the string
*/
private String prepareCountql(String qlString) {
String countHql = "select count (*) " + removeSelect(removeOrders(qlString));
return countHql;
}
/**
* Removes the select.
*
* @param ql the ql
* @return the string
*/
private static String removeSelect(String ql) {
int beginPos = ql.toLowerCase().indexOf("from");
return ql.substring(beginPos);
}
/**
* Removes the orders.
*
* @param ql the hql
* @return the string
*/
private static String removeOrders(String ql) {
Pattern p = Pattern.compile("order\\s*by[\\w|\\W|\\s|\\S]*", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(ql);
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, "");
}
m.appendTail(sb);
return sb.toString();
}
}
| true
|
3f4049ff230a9335757bfd73cfa4c5a35bb48730
|
Java
|
amiman/IPhoneSMSReader
|
/src/Controller/IPhoneSMSReaderMain.java
|
UTF-8
| 1,109
| 2.421875
| 2
|
[] |
no_license
|
package Controller;
import java.io.IOException;
import Controller.Model.Model;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.ListView;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
public class IPhoneSMSReaderMain extends Application {
private AnchorPane mainLayout;
private Model model;
@Override
public void start(Stage primaryStage) {
try {
// Load root layout from fxml file.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(IPhoneSMSReader.class.getResource("View/MainView.fxml"));
mainLayout = (AnchorPane) loader.load();
// Show the scene containing the root layout.
Scene scene = new Scene(mainLayout);
primaryStage.setScene(scene);
primaryStage.show();
// Create model
model = new Model(scene,primaryStage);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
| true
|
0c9ac94fa12617b37acd089b210abe51c15495de
|
Java
|
Freitas26/DevWeb2019.2
|
/ProjetoDevWeb/src/java/DAO/AvaliacaoDAO.java
|
UTF-8
| 5,720
| 2.578125
| 3
|
[] |
no_license
|
/*
* 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 DAO;
import modelos.Avaliacao;
import java.util.ArrayList;
import java.util.List;
import modelos.Produto;
import java.sql.*;
import codigo.Database;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Usuario
*/
public class AvaliacaoDAO {
public List<Avaliacao> getAvaliacoes() {
ArrayList<Avaliacao> avaliacoes = new ArrayList<>();
Connection conn=Database.getConnection();
try {
Statement select = conn.createStatement();
ResultSet resp = select.executeQuery("select * from avaliacoes");
while(resp.next()){
Avaliacao aval = new Avaliacao();
aval.setUserId(resp.getInt("UserID"));
aval.setIdProduto(resp.getInt("idProduto"));
aval.setNota(resp.getInt("Nota"));
avaliacoes.add(aval);
}
select.close();
resp.close();
} catch (SQLException ex) {
Logger.getLogger(AvaliacaoDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return avaliacoes;
}
public List<Avaliacao> getAvaliacoesByProduto(int id) {
ArrayList<Avaliacao> avaliacoes = new ArrayList<>();
Connection conn=Database.getConnection();
try {
Statement select = conn.createStatement();
PreparedStatement ps = conn.prepareStatement("select * from avaliacoes where idProduto = ?");
ps.setInt(1, id);
ResultSet resp = ps.executeQuery();
while(resp.next()){
Avaliacao aval = new Avaliacao();
aval.setUserId(resp.getInt("UserID"));
aval.setIdProduto(resp.getInt("idProduto"));
aval.setNota(resp.getInt("Nota"));
avaliacoes.add(aval);
}
select.close();
resp.close();
} catch (SQLException ex) {
Logger.getLogger(AvaliacaoDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return avaliacoes;
}
public Avaliacao getAvaliacao(int id,int idUser) {
try {
Connection conn=Database.getConnection();
PreparedStatement ps = conn.prepareStatement("SELECT * FROM `avaliacoes` WHERE idProduto=? and UserID=?");
ps.setInt(1, id);
ps.setInt(2,idUser);
ResultSet resp = ps.executeQuery();
if (resp.next()) {// found
Avaliacao aval = new Avaliacao();
aval.setUserId(resp.getInt("UserID"));
aval.setIdProduto(resp.getInt("idProduto"));
aval.setNota(resp.getInt("Nota"));
return aval;
}
conn.close();
} catch (Exception ex) {
System.out.println("Error in check() -->" + ex.getMessage());
}
return null;
}
public void addAvaliacao(Avaliacao aval) {
try {
Connection conn=Database.getConnection();
PreparedStatement preparedStatement = conn.prepareStatement("insert into avaliacoes(UserID, idProduto, Nota) values (?, ?, ?)");
// Parameters start with 1
preparedStatement.setInt(1, aval.getUserId());
preparedStatement.setInt(2, aval.getIdProduto());
preparedStatement.setInt(3, aval.getNota());
preparedStatement.executeUpdate();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void deleteAvaliacao(int id,int idUser) {
try {
Connection conn=Database.getConnection();
PreparedStatement preparedStatement = conn.prepareStatement("delete from avaliacao where idProduto = ?, UserID=?");
preparedStatement.setInt(1, id);
preparedStatement.setInt(2,idUser);
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void updateAvaliacao(Avaliacao aval) {
try {
Connection conn=Database.getConnection();
PreparedStatement preparedStatement = conn.prepareStatement("update avaliacoes set Nota=?"
+ " where idProduto = ?, UserID=?");
preparedStatement.setInt(1, aval.getNota());
preparedStatement.setInt(2, aval.getIdProduto());
preparedStatement.setInt(3, aval.getUserId());
preparedStatement.executeUpdate();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public double mediaAvaliacoes(int idProd){
Connection conn=Database.getConnection();
Double media=0.0;
try {
Statement select = conn.createStatement();
PreparedStatement ps = conn.prepareStatement("select AVG(Nota) from avaliacoes where idProduto = ?");
ps.setInt(1, idProd);
ResultSet resp = ps.executeQuery();
while(resp.next()){
media=resp.getDouble("AVG(Nota)");
}
select.close();
resp.close();
} catch (SQLException ex) {
Logger.getLogger(AvaliacaoDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return media;
}
}
| true
|
97858d931276f7f62c696fe34a712b7e4a70cb1a
|
Java
|
grain-2/gui
|
/chap08/src/book/demo/ListDemo.java
|
UTF-8
| 1,733
| 3.171875
| 3
|
[
"Apache-2.0"
] |
permissive
|
package book.demo;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.SWT;
import org.eclipse.jface.viewers.ListViewer;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
public class ListDemo {
protected Shell shell;
/**
* Launch the application.
* @param args
*/
public static void main(String[] args) {
try {
ListDemo window = new ListDemo();
window.open();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Open the window.
*/
public void open() {
Display display = Display.getDefault();
createContents();
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
/**
* Create contents of the window.
*/
protected void createContents() {
shell = new Shell();
shell.setSize(450, 300);
shell.setText("SWT Application");
List list = new List(shell, SWT.BORDER);
list.setBounds(30, 27, 89, 189);
ListViewer listViewer = new ListViewer(shell, SWT.BORDER | SWT.V_SCROLL);
List list_1 = listViewer.getList();
list_1.setBounds(189, 27, 112, 157);
listViewer.setLabelProvider(new LabelProvider(){
@Override
public String getText(Object element) {
// TODO 自动生成的方法存根
return (String)element;
}
});
listViewer.setContentProvider(new ArrayContentProvider(){
@Override
public Object[] getElements(Object inputElement) {
// TODO 自动生成的方法存根
String[] objs = (String[])inputElement;
return objs;
}
});
listViewer.setInput(new String[]{"1","2","3","4","5"});
}
}
| true
|
2121b2cd23b7cc4603ea21d9215c5fcaae9e17c3
|
Java
|
Lor3nzoMartinez/CSC143
|
/Proj_Collections/src/lists/ArrayList.java
|
UTF-8
| 2,830
| 3.5
| 4
|
[] |
no_license
|
package lists;
import java.util.Iterator;
@SuppressWarnings("unchecked")
public class ArrayList<T> implements List<T> {
private int size;
private T[] element;
public static int DEFAULT_CAPACITY = 3;
public static int NOT_FOUND = -1;
public ArrayList() {
this(DEFAULT_CAPACITY);
}
public ArrayList(int holder) {
this.element = ((T[]) new Object[holder]);
size = 0;
}
public void add(T value) {
if (element.length < this.size + 1) {
element = copyOf(element, size + 1);
}
element[size++] = value;
}
public void add(int index, T value) {
if (element.length < this.size + 1) {
element = copyOf(element, size + 1);
size++;
}
for (int i = index; i < this.size; i++) {
T temp = element[i];
element[i] = value;
value = temp;
}
}
private void checkIndex(int index) {
if (index > 0 && index < size) {
System.out.println("isValid");
} else {
throw new IndexOutOfBoundsException();
}
}
public void clear() {
for (int i = 0; i < element.length; i++) {
this.size--;
}
}
public boolean contains(T value) {
for (int i = 0; i < element.length; i++) {
if (element[i] == value) {
return true;
}
}
return false;
}
public T[] copyOf(T[] data, int length) {
T[] newArray = (T[]) new Object[length];
for (int i = 0; i < newArray.length - 1; i++) {
newArray[i] = data[i];
}
if (data.length > newArray.length) {
newArray[newArray.length - 1] = data[data.length - 1];
}
return newArray;
}
public void ensureCapacity(int capacity) {
//TODO
}
public T get(int index) {
return this.element[index];
}
public int indexOf(T value) {
for (int i = 0; i < this.size; i++) {
if (element[i] == value) {
return i;
}
}
return -1;
}
public boolean isEmpty() {
if (size == 0) {
return true;
}
return false;
}
public void remove(int index) {
for (int i = index; i < this.size - 1; i++) {
element[i] = element[i + 1];
}
this.size--;
element = copyOf(element, size);
}
public void set(int index, T value) {
if (index > 0 && index < size) {
element[index] = value;
}
}
public int size() {
return this.size;
}
public String toString() {
int counter = 0;
System.out.print("[");
while (size - 1 > counter) {
System.out.print(element[counter] + ",");
counter++;
}
return element[size] + "]";
}
public class ArrayIterator implements Iterator<T> {
private int index;
private boolean ableToRemove;
public ArrayIterator(ArrayList<T> list) {
this.index = 0;
this.ableToRemove = false;
}
@Override
public boolean hasNext() {
return (index <= size);
}
@Override
public T next() {
index++;
return get(index - 1);
}
public void remove() {
if (ableToRemove) {
ArrayList.this.remove(index - 1);
index--;
}
}
}
}
| true
|
eec49a9d74cae190dd04045d7e01a20d402fa370
|
Java
|
burtbeckwith/dialog
|
/src/java/org/open_t/dialog/CustomPropertyEditorRegistrar.java
|
UTF-8
| 398
| 1.6875
| 2
|
[] |
no_license
|
package org.open_t.dialog;
import java.util.Date;
import org.codehaus.groovy.grails.web.binding.*;
import org.springframework.beans.*;
public class CustomPropertyEditorRegistrar implements PropertyEditorRegistrar {
public void registerCustomEditors(PropertyEditorRegistry registry) {
registry.registerCustomEditor(Date.class, new DateTimePropertyEditor("yyyy-MM-dd'T'HH:mm"));
}
}
| true
|
ed93edb75b15b3f284f04e88555c85fb8f8d0da9
|
Java
|
ckusk92/Don-t-Wreck-My-House
|
/src/main/java/learn/dontWreckMyHouse/ui/MainMenuOption.java
|
UTF-8
| 1,072
| 2.78125
| 3
|
[] |
no_license
|
package learn.dontWreckMyHouse.ui;
public enum MainMenuOption {
EXIT(0, "Exit"),
VIEW_RESERVATIONS_FOR_HOST(1, "View Reservations for Host"),
MAKE_A_RESERVATION(2, "Make a Reservation"),
EDIT_A_RESERVATION(3, "Edit a Reservation"),
CANCEL_A_RESERVATION(4, "Cancel a Reservation"),
ADD_A_GUEST(5, "Add a Guest"),
EDIT_A_GUEST(6, "Edit a Guest"),
DELETE_A_GUEST(7, "Delete a Guest"),
ADD_A_HOST(8, "Add a Host"),
EDIT_A_HOST(9, "Edit a Host"),
DELETE_A_HOST(10, "Delete a Host");
private int value;
private String message;
private MainMenuOption(int value, String message) {
this.value = value;
this.message = message;
}
public static MainMenuOption fromValue(int value) {
for (MainMenuOption option : MainMenuOption.values()) {
if (option.getValue() == value) {
return option;
}
}
return EXIT;
}
public int getValue() {
return value;
}
public String getMessage() {
return message;
}
}
| true
|
3b685a55e2399da4a4db3f8db3849ac40f092303
|
Java
|
indrptra/Simple-App
|
/app/src/main/java/com/indrap/simple_app/MainActivity.java
|
UTF-8
| 6,079
| 2.078125
| 2
|
[] |
no_license
|
package com.indrap.simple_app;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener, View.OnFocusChangeListener{
EditText txtin,txtout;
Button btn1,btn2,btn3,btn4,btn5,btn6,btn7,btn8,btn9,btn0;
ImageButton btnsip,btndel,btnclear;
TextView tvj;
String txtfoc = "income";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
txtin = (EditText)findViewById(R.id.txt_income);
txtout = (EditText)findViewById(R.id.txt_outcome);
btn0 = (Button)findViewById(R.id.btn_0);
btn1 = (Button)findViewById(R.id.btn_1);
btn2 = (Button)findViewById(R.id.btn_2);
btn3 = (Button)findViewById(R.id.btn_3);
btn4 = (Button)findViewById(R.id.btn_4);
btn5 = (Button)findViewById(R.id.btn_5);
btn6 = (Button)findViewById(R.id.btn_6);
btn7 = (Button)findViewById(R.id.btn_7);
btn8 = (Button)findViewById(R.id.btn_8);
btn9 = (Button)findViewById(R.id.btn_9);
//btnsip = (ImageButton)findViewById(R.id.btn_ok);
btndel = (ImageButton)findViewById(R.id.btn_del);
btnclear = (ImageButton)findViewById(R.id.btn_clear);
btn0.setOnClickListener(this);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
btn4.setOnClickListener(this);
btn5.setOnClickListener(this);
btn6.setOnClickListener(this);
btn7.setOnClickListener(this);
btn8.setOnClickListener(this);
btn9.setOnClickListener(this);
//btnsip.setOnClickListener(this);
btndel.setOnClickListener(this);
btnclear.setOnClickListener(this);
txtin.setOnFocusChangeListener(this);
txtout.setOnFocusChangeListener(this);
txtin.setInputType(InputType.TYPE_NULL);
txtout.setInputType(InputType.TYPE_NULL);
tvj = (TextView) findViewById(R.id.tv_jawab);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab_ok);
fab.setOnClickListener(this);
/* int start =txtin.getSelectionStart(); //this is to get the the cursor position
String s = "Some string";
txtin.getText().insert(start, s); //this will get the text and insert the String s into the current position*/
}
@Override
public void onClick(View v)
{
String txtisi = "";
switch (v.getId())
{
case R.id.btn_0:
txtisi = "0";
break;
case R.id.btn_1:
txtisi = "1";
break;
case R.id.btn_2:
txtisi = "2";
break;
case R.id.btn_3:
txtisi = "3";
break;
case R.id.btn_4:
txtisi = "4";
break;
case R.id.btn_5:
txtisi = "5";
break;
case R.id.btn_6:
txtisi = "6";
break;
case R.id.btn_7:
txtisi = "7";
break;
case R.id.btn_8:
txtisi = "8";
break;
case R.id.btn_9:
txtisi = "9";
break;
case R.id.btn_del:
if(txtfoc.equals("income")){
txtin.setText("");}
else{
txtout.setText("");}
break;
case R.id.btn_clear:
if(txtfoc.equals("income")){
if(txtin.length() > 0){
txtin.setText(txtin.getText().toString().substring(0, txtin.length() - 1));}}
else{
if(txtout.length() > 0){
txtout.setText(txtout.getText().toString().substring(0, txtout.length() - 1));}
}
break;
case R.id.fab_ok:
if(!txtin.getText().toString().isEmpty() && !txtout.getText().toString().isEmpty())
tvj.setText(String.valueOf(Integer.valueOf(txtin.getText().toString()) - Integer.valueOf(txtout.getText().toString())));
else
tvj.setText("");
break;
}
if(txtfoc.equals("income")){
txtin.setText(txtin.getText() + txtisi);
}else{
txtout.setText(txtout.getText() + txtisi);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onFocusChange(View v, boolean hasFocus) {
switch(v.getId()){
case R.id.txt_income:
txtfoc="income";
break;
case R.id.txt_outcome:
txtfoc="outcome";
break;
}
}
}
| true
|
41765e957e1c19d10443e4c058cc853680a1a9a9
|
Java
|
aprasain234/springsecurity
|
/SpringSecirityProject/src/main/java/com/ashish/secureapp/MyUserDetailsService.java
|
UTF-8
| 791
| 2.234375
| 2
|
[] |
no_license
|
package com.ashish.secureapp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
@Configuration
public class MyUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository repo;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = repo.findByUsername(username);
if(user==null)
throw new UsernameNotFoundException("User not found");
return new UserPrincipal(user);
}
}
| true
|
e89b10baa82901b5a943ecbef61176232725a682
|
Java
|
basavarajdhanashetti/oms-app
|
/oms-application/oms-domain/src/main/java/com/bsd/oms/process/PurchaseItem.java
|
UTF-8
| 1,735
| 2.3125
| 2
|
[] |
no_license
|
package com.bsd.oms.process;
public class PurchaseItem implements java.io.Serializable {
static final long serialVersionUID = 1L;
private long id;
private long category;
private long subCategory;
private long productId;
private Product product;
private int quantity;
private String description;
private double unitPrice;
private double discount;
private double salePrice;
public PurchaseItem(){
}
public long getCategory() {
return category;
}
public void setCategory(long category) {
this.category = category;
}
public long getSubCategory() {
return subCategory;
}
public void setSubCategory(long subCategory) {
this.subCategory = subCategory;
}
public long getProductId() {
return productId;
}
public void setProductId(long productId) {
this.productId = productId;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public double getUnitPrice() {
return unitPrice;
}
public void setUnitPrice(double unitPrice) {
this.unitPrice = unitPrice;
}
public double getDiscount() {
return discount;
}
public void setDiscount(double discount) {
this.discount = discount;
}
public double getSalePrice() {
return salePrice;
}
public void setSalePrice(double salePrice) {
this.salePrice = salePrice;
}
}
| true
|
2c054075f188e4a1ae11c2ccd67ae7bcdfc4a1f1
|
Java
|
WeiChaoMeng/jiaoke_project
|
/jiaoke-web/src/main/java/com/jiaoke/controller/oa/BackstageManagementController.java
|
UTF-8
| 17,609
| 2.109375
| 2
|
[] |
no_license
|
package com.jiaoke.controller.oa;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jiake.utils.JsonHelper;
import com.jiaoke.oa.bean.Department;
import com.jiaoke.oa.bean.Permission;
import com.jiaoke.oa.bean.RoleInfo;
import com.jiaoke.oa.bean.UserInfo;
import com.jiaoke.oa.service.DepartmentService;
import com.jiaoke.oa.service.PermissionService;
import com.jiaoke.oa.service.RoleInfoService;
import com.jiaoke.oa.service.UserInfoService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 后台管理
*
* @author lihui
* @version 1.0
* @date 2019/1/24 13:55
*/
@Controller
@RequestMapping(value = "/backstageManagement")
public class BackstageManagementController {
@Resource
private UserInfoService userInfoService;
@Resource
private PermissionService permissionService;
@Resource
private RoleInfoService roleInfoService;
@Resource
private DepartmentService departmentService;
/**
* 获取当前登录用户信息
*
* @return userInfo
*/
private UserInfo getCurrentUser() {
return (UserInfo) SecurityUtils.getSubject().getPrincipal();
}
/**
* 加载用户数据
*
* @param page page
* @return list
*/
@RequestMapping(value = "/userManager")
@ResponseBody
public String userManager(int page) {
PageHelper.startPage(page, 12);
List<UserInfo> userInfoList = userInfoService.selectAll();
PageInfo<UserInfo> pageInfo = new PageInfo<>(userInfoList);
return JsonHelper.toJSONString(pageInfo);
}
/**
* 根据名字筛选
*
* @param page page
* @param username username
* @return list
*/
@RequestMapping(value = "/usernameFilter")
@ResponseBody
public String usernameFilter(int page, String username) {
PageHelper.startPage(page, 12);
List<UserInfo> userInfoList = userInfoService.usernameFilter(username);
PageInfo<UserInfo> pageInfo = new PageInfo<>(userInfoList);
return JsonHelper.toJSONString(pageInfo);
}
/**
* 查询用户是否存在
*
* @param username username
* @return y/n
*/
@RequestMapping(value = "/checkUsername")
@ResponseBody
public String checkUsername(String username) {
UserInfo userInfo = userInfoService.checkUsername(username);
if (null == userInfo) {
return "false";
} else {
return "true";
}
}
/**
* 跳转用户管理页面
*
* @return jsp
*/
@RequestMapping(value = "/toUserManager")
public String toUserManager(Model model, int page) {
List<Department> departmentList = departmentService.selectAll();
List<RoleInfo> roleInfoList = roleInfoService.selectAll();
model.addAttribute("roleInfoList", roleInfoList);
model.addAttribute("departmentList", JsonHelper.toJSONString(departmentList));
//当前页(默认为1)
model.addAttribute("currentPage", JsonHelper.toJSONString(page));
return "oa/backstage/user";
}
/**
* 添加用户
*
* @param userInfo userInfo
* @return success/error
*/
@RequestMapping(value = "/add")
@ResponseBody
public String add(UserInfo userInfo) {
if (userInfoService.insertSelective(userInfo) != 1) {
return "error";
}
return "success";
}
/**
* 跳转修改
*
* @param id id
* @return userInfo
*/
@RequestMapping(value = "/toEdit")
@ResponseBody
public String toEdit(Integer id) {
UserInfo userInfo = userInfoService.selectByPrimaryKey(id);
return JsonHelper.toJSONString(userInfo);
}
/**
* 绑定角色
*
* @param id id
* @return userInfo
*/
@RequestMapping(value = "/toBinding")
@ResponseBody
public String toBinding(Integer id) {
Map<String, Object> map = userInfoService.bindingInfo(id);
return JsonHelper.toJSONString(map);
}
/**
* 提交绑定角色
*
* @param array 角色
* @return userInfo
*/
@RequestMapping(value = "/binding")
@ResponseBody
public String binding(Integer userId, String[] array) {
if (userInfoService.updateRolePermission(userId, array) < 0) {
return "error";
}
return "success";
}
/**
* 提交修改用户
*
* @param userInfo userInfo
* @return 影响行数
*/
@RequestMapping(value = "/edit")
@ResponseBody
public String edit(UserInfo userInfo) {
if (userInfoService.updateUserInfo(userInfo) < 0) {
return "error";
}
return "success";
}
/**
* 删除用户
*
* @param id id
* @return 影响行数
*/
@RequestMapping(value = "/delete")
@ResponseBody
public String delete(Integer id) {
if (userInfoService.deleteByPrimaryKey(id) != 1) {
return "error";
} else {
return "success";
}
}
/**
* 批量删除用户
*
* @param ids ids
* @return int
*/
@RequestMapping(value = "/batchDeleteUser")
@ResponseBody
public String batchDeleteUser(@RequestParam(value = "ids[]") String[] ids) {
if (userInfoService.batchDeleteUser(ids) >= 0) {
return "success";
} else {
return "error";
}
}
/**
* 修改密码
*
* @param password password
* @return int
*/
@RequestMapping(value = "/modifyPassword")
@ResponseBody
public String modifyPassword(String password) {
//当前登录人ID
Integer id = getCurrentUser().getId();
if (userInfoService.updatePasswordById(id, password) != 1) {
SecurityUtils.getSubject().logout();
return "error";
} else {
return "success";
}
}
/**--------------------------角色管理--------------------------------*/
/**
* 跳转角色管理页面
*
* @return jsp
*/
@RequestMapping(value = "/toRoleManager")
public String toRoleManager(Model model, int page) {
List<Permission> permissionList = permissionService.selectAll();
//权限列表
model.addAttribute("permissionList", JsonHelper.toJSONString(permissionList));
//当前页(默认为1)
model.addAttribute("currentPage", JsonHelper.toJSONString(page));
// return "oa/backstage/oa_role_management";
return "oa/backstage/role";
}
/**
* 加载角色数据
*
* @param page page
* @return list
*/
@RequestMapping(value = "/roleManager")
@ResponseBody
public String roleManager(int page) {
PageHelper.startPage(page, 12);
List<RoleInfo> roleInfoList = roleInfoService.selectAll();
PageInfo<RoleInfo> pageInfo = new PageInfo<>(roleInfoList);
return JsonHelper.toJSONString(pageInfo);
}
/**
* 角色名字筛选
*
* @param page page
* @param name 角色名
* @return list
*/
@RequestMapping(value = "/roleNameFilter")
@ResponseBody
public String roleNameFilter(int page, String name) {
PageHelper.startPage(page, 12);
List<RoleInfo> roleInfoList = roleInfoService.roleNameFilter(name);
PageInfo<RoleInfo> pageInfo = new PageInfo<>(roleInfoList);
return JsonHelper.toJSONString(pageInfo);
}
/**
* 添加角色信息
*
* @param roleInfo roleInfo
* @return s/e
*/
@RequestMapping(value = "/addRoleInfo")
@ResponseBody
public String addRoleInfo(RoleInfo roleInfo) {
if (roleInfoService.insertSelective(roleInfo) > 0) {
return "success";
}
return "error";
}
/**
* 检查角色名是否被占用
*
* @param name name
* @return t/f
*/
@RequestMapping(value = "/checkRoleName")
@ResponseBody
public String checkRoleName(String name) {
RoleInfo roleInfo = roleInfoService.checkRoleName(name);
if (null == roleInfo) {
return "false";
} else {
return "true";
}
}
/**
* 查询已绑定权限
*
* @param id id
* @return roleInfo
*/
@RequestMapping(value = "/toBindingPower")
@ResponseBody
public String toBindingPower(Integer id) {
Map<String, Object> map = new HashMap<>(16);
List<Permission> permissionList = roleInfoService.bindingInfo(id);
map.put("data", permissionList);
return JsonHelper.toJSONString(map);
}
/**
* 提交绑定角色
*
* @param array 角色
* @return userInfo
*/
@RequestMapping(value = "/bindingPower")
@ResponseBody
public String bindingPower(Integer roleId, String[] array) {
if (roleInfoService.updateRolePermission(roleId, array) < 0) {
return "error";
}
return "success";
}
/**
* 删除角色
*
* @param id id
* @return 影响行数
*/
@RequestMapping(value = "/deleteRole")
@ResponseBody
public String deleteRole(Integer id) {
if (roleInfoService.deleteByPrimaryKey(id) >= 0) {
return "success";
}
return "error";
}
/**
* 修改-获取角色信息
*
* @param id id
* @return userInfo
*/
@RequestMapping(value = "/toRoleEdit")
@ResponseBody
public String toRoleEdit(Integer id) {
RoleInfo roleInfo = roleInfoService.selectByPrimaryKey(id);
return JsonHelper.toJSONString(roleInfo);
}
/**
* 更新角色信息及权限
*
* @param roleId 角色id
* @return success/error
*/
@RequestMapping(value = "/roleEdit")
@ResponseBody
public String roleEdit(Integer roleId, String description) {
if (roleInfoService.updateRole(roleId, description) < 0) {
return "error";
}
return "success";
}
/**
* 批量删除角色
*
* @param ids ids
* @return int
*/
@RequestMapping(value = "/batchDeleteRole")
@ResponseBody
public String batchDeleteRole(@RequestParam(value = "ids[]") String[] ids) {
if (roleInfoService.batchDeleteRole(ids) >= 0) {
return "success";
} else {
return "error";
}
}
/**--------------------------权限管理--------------------------------*/
/**
* 跳转权限管理页面
*
* @return jsp
*/
@RequestMapping(value = "/toPermissionManager")
public String toPermissionManager() {
return "oa/backstage/permission";
}
/**
* 加载权限数据
*
* @return list
*/
@ResponseBody
@RequestMapping(value = "/permissionManager")
public String permissionsData() {
HashMap<String, Object> map = new HashMap<>(16);
List<Permission> permissionList = permissionService.selectAll();
map.put("data", permissionList);
return JsonHelper.toJSONString(map);
}
/**
* 权限名字筛选
*
* @param page page
* @param permissionName 权限名
* @return list
*/
@RequestMapping(value = "/permissionFilter")
@ResponseBody
public String permissionNameFilter(int page, String permissionName) {
PageHelper.startPage(page, 15);
List<Permission> permissionList = permissionService.permissionNameFilter(permissionName);
PageInfo<Permission> pageInfo = new PageInfo<>(permissionList);
return JsonHelper.toJSONString(pageInfo);
}
/**--------------部门管理------------------*/
/**
* 跳转部门管理页面
*
* @return jsp
*/
@RequestMapping(value = "/toDepartmentManager")
public String toDepartmentManager(Model model, int page) {
List<UserInfo> userInfoList = userInfoService.selectIdAndNicknameAndDepartment();
List<Department> departmentList = departmentService.selectKeyAndName();
model.addAttribute("userInfoList", JsonHelper.toJSONString(userInfoList));
model.addAttribute("departmentList", JsonHelper.toJSONString(departmentList));
model.addAttribute("currentPage", JsonHelper.toJSONString(page));
// return "oa/backstage/oa_department_management";
return "oa/backstage/department";
}
/**
* 加载部门数据
*
* @param page page
* @return list
*/
@RequestMapping(value = "/departmentManager")
@ResponseBody
public String departmentManager(int page) {
PageHelper.startPage(page, 12);
List<Department> departmentList = departmentService.selectAll();
PageInfo<Department> pageInfo = new PageInfo<>(departmentList);
return JsonHelper.toJSONString(pageInfo);
}
/**
* 部门名字筛选
*
* @param page page
* @param departmentName 部门名称
* @return list
*/
@RequestMapping(value = "/departmentFilter")
@ResponseBody
public String departmentFilter(int page, String departmentName) {
PageHelper.startPage(page, 12);
List<Department> departmentList = departmentService.departmentNameFilter(departmentName);
PageInfo<Department> pageInfo = new PageInfo<>(departmentList);
return JsonHelper.toJSONString(pageInfo);
}
/**
* 添加部门
*
* @param departmentName departmentName
* @return s/e
*/
@RequestMapping(value = "/addDepartment")
@ResponseBody
public String addDepartment(String departmentName) {
if (departmentService.insertSelective(departmentName) > 0) {
return "success";
}
return "error";
}
/**
* 检查部门名是否被占用
*
* @param departmentName departmentName
* @return t/f
*/
@RequestMapping(value = "/checkDepartmentName")
@ResponseBody
public String checkDepartmentName(String departmentName) {
Department department = departmentService.checkDepartmentName(departmentName);
if (null == department) {
return "false";
} else {
return "true";
}
}
/**
* 删除部门
*
* @param id id
* @return 影响行数
*/
@RequestMapping(value = "/deleteDepartment")
@ResponseBody
public String deleteDepartment(Integer id) {
if (departmentService.deleteByPrimaryKey(id) >= 0) {
return "success";
}
return "error";
}
/**
* 批量删除部门
*
* @param ids ids
* @return int
*/
@RequestMapping(value = "/batchDeleteDepartment")
@ResponseBody
public String batchDeleteDepartment(@RequestParam(value = "ids[]") String[] ids) {
if (departmentService.batchDeleteDepartment(ids) >= 0) {
return "success";
} else {
return "error";
}
}
/**
* 修改-获取部门信息
*
* @param id id
* @return userInfo
*/
@RequestMapping(value = "/toDepartmentEdit")
@ResponseBody
public String toDepartmentEdit(Integer id) {
Department department = departmentService.selectByPrimaryKey(id);
return JsonHelper.toJSONString(department);
}
/**
* 更新角色信息及权限
*
* @param id id
* @param departmentName departmentName
* @return success/error
*/
@RequestMapping(value = "/departmentEdit")
@ResponseBody
public String departmentEdit(Integer id, String departmentName) {
if (departmentService.updateDepartmentName(id, departmentName) < 0) {
return "error";
}
return "success";
}
/**
* 绑定部门负责人
*
* @param id id
* @return success/error
*/
@RequestMapping(value = "/bindingDepartmentPrincipal")
@ResponseBody
public String bindingDepartmentPrincipal(Integer id, String principal) {
if (departmentService.bindingDepartmentPrincipal(id, principal) < 0) {
return "error";
}
return "success";
}
/**
* 绑定部门负责人(多个)
*
* @param array 角色
* @return userInfo
*/
@RequestMapping(value = "/bindingMultiplePrincipal")
@ResponseBody
public String bindingMultiplePrincipal(Integer id, String[] array) {
String principal = StringUtils.join(array, ",");
if (departmentService.bindingDepartmentPrincipal(id, principal) < 0) {
return "error";
}
return "success";
}
/**
* 绑定部门主管领导
*
* @param id id
* @return success/error
*/
@RequestMapping(value = "/bindingDepartmentSupervisor")
@ResponseBody
public String bindingDepartmentHead(Integer id, String supervisor) {
if (departmentService.bindingDepartmentSupervisor(id, supervisor) < 0) {
return "error";
}
return "success";
}
}
| true
|
ccf8d3159b1695f71b638a0ac9551f16cda1bad6
|
Java
|
mkulisic/EPICS_Pothole_Detector
|
/src/org/tensorflow/demo/TFliteYoloDetector.java
|
UTF-8
| 12,402
| 2.078125
| 2
|
[] |
no_license
|
package org.tensorflow.demo;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.os.SystemClock;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicYuvToRGB;
import android.renderscript.Type;
import android.util.Log;
import org.json.JSONException;
import org.tensorflow.lite.Interpreter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
public class TFliteYoloDetector {
private final Interpreter tfLite;
RenderScript rs;
private final List<Double> anchors;
private ByteBuffer input;
private int[] intValues;
private float[][][][] output;
private static final List<Double> ANCHORS = new ArrayList<>(Arrays.asList(0.57273, 0.677385, 1.87446, 2.06253, 3.33843, 5.47434, 7.88282, 3.52778, 9.77052, 9.16828));
private final int INP_IMG_WIDTH;
private final int INP_IMG_HEIGHT;
private final int NUM_BOXES_PER_BLOCK;
private final int NUM_CLASSES;
private final int gridWidth;
private final int gridHeight;
private final int blockSize;
private final int MAX_RESULTS;
private final double THRESHOLD;
private final double OVERLAP_THRESHOLD;
/** Tag for the {@link Log}. */
private static final String TAG = "YoloDetector";
TFliteYoloDetector(
RenderScript rs,
ByteBuffer modalData,
int BLOCK_SIZE,
int IMG_WIDTH,
int IMG_HEIGHT,
int NUM_CLASS,
int NUM_BOXES,
int MAX_R,
double THRESH,
double OVERLAP_THRESH,
int NUM_CHANNELS) throws IOException, JSONException {
tfLite = new Interpreter(modalData);
/** Initialize Input Buffer based on meta as Byte Buffer**/
blockSize = BLOCK_SIZE;
//Map net = (Map) meta.get("net");
INP_IMG_WIDTH = IMG_WIDTH;
INP_IMG_HEIGHT = IMG_HEIGHT;
NUM_CLASSES = NUM_CLASS;
NUM_BOXES_PER_BLOCK = NUM_BOXES;
MAX_RESULTS = MAX_R;
THRESHOLD= THRESH ;
OVERLAP_THRESHOLD = OVERLAP_THRESH;
input = ByteBuffer.allocateDirect(
4 * (int) 1 * INP_IMG_WIDTH * INP_IMG_HEIGHT * (int) NUM_CHANNELS);
input.order(ByteOrder.nativeOrder());
intValues = new int[INP_IMG_WIDTH * INP_IMG_HEIGHT];
gridWidth = INP_IMG_WIDTH / blockSize;
gridHeight = INP_IMG_HEIGHT / blockSize;
output = new float[1][13][13][30];
/** Get Meta Data for post processing **/
anchors = ANCHORS;
this.rs = rs;
Log.d(TAG, "Created a Tensorflow Lite Yolo Detector.");
}
public List<Map<String, Object>> detect(Bitmap image){
if (tfLite == null) {
Log.e(TAG, "Image classifier has not been initialized; Skipped.");
return null;
}
convertBitmapToByteBuffer(image);
// Here's where the magic happens!!!
long startTime = SystemClock.uptimeMillis();
tfLite.run(input, output);
long endTime = SystemClock.uptimeMillis();
Log.d(TAG, "Timecost to run model inference: " + Long.toString(endTime - startTime));
return postProcess(output[0]);
}
public List<Map<String, Object>> postProcess(final float[][][] output) {
// Find the best detections.
PriorityQueue<Map<String, Object>> priorityQueue = new PriorityQueue<>(1, new PredictionComparator());
for (int y = 0; y < gridHeight; ++y) {
for (int x = 0; x < gridWidth; ++x) {
for (int b = 0; b < NUM_BOXES_PER_BLOCK; ++b) {
final int offset = (NUM_CLASSES + 5) * b;
final float confidence = expit(output[y][x][offset + 4]);
int detectedClass = -1;
float maxClass = 0;
final float[] classes = new float[NUM_CLASSES];
for (int c = 0; c < NUM_CLASSES; ++c) {
classes[c] = output[x][y][offset + 5 + c];
}
softmax(classes);
for (int c = 0; c < NUM_CLASSES; ++c) {
if (classes[c] > maxClass) {
detectedClass = c;
maxClass = classes[c];
}
}
final float confidenceInClass = maxClass * confidence;
if (confidenceInClass > THRESHOLD) {
Map<String, Object> prediction = new HashMap<>();
prediction.put("classIndex",detectedClass);
prediction.put("confidence",confidenceInClass);
final float xPos = (x + expit(output[y][x][offset + 0])) * blockSize;
final float yPos = (y + expit(output[y][x][offset + 1])) * blockSize;
final float w = (float) (Math.exp(output[y][x][offset + 2]) * anchors.get(2 * b + 0)) * blockSize;
final float h = (float) (Math.exp(output[y][x][offset + 3]) * anchors.get(2 * b + 1)) * blockSize;
Map<String, Float> rectF = new HashMap<>();
rectF.put("left", Math.max(0, xPos - w / 2)); // left should have lower value as right
rectF.put("top", Math.max(0, yPos - h / 2)); // top should have lower value as bottom
rectF.put("right",Math.min(INP_IMG_WIDTH- 1, xPos + w / 2));
rectF.put("bottom",Math.min(INP_IMG_HEIGHT - 1, yPos + h / 2));
prediction.put("rect",rectF);
priorityQueue.add(prediction);
}
}
}
}
final List<Map<String, Object>> predictions = new ArrayList<>();
Map<String, Object> bestPrediction = priorityQueue.poll();
predictions.add(bestPrediction);
for (int i = 0; i < Math.min(priorityQueue.size(), MAX_RESULTS); ++i) {
Map<String, Object> prediction = priorityQueue.poll();
boolean overlaps = false;
for (Map<String, Object> previousPrediction : predictions) {
float intersectProportion = 0f;
Map<String, Float> primary = (Map<String, Float>) previousPrediction.get("rect");
Map<String, Float> secondary = (Map<String, Float>) prediction.get("rect");
if (primary.get("left") < secondary.get("right") && primary.get("right") > secondary.get("left")
&& primary.get("top") < secondary.get("bottom") && primary.get("bottom") > secondary.get("top")) {
float intersection = Math.max(0, Math.min(primary.get("right"), secondary.get("right")) - Math.max(primary.get("left"), secondary.get("left"))) *
Math.max(0, Math.min(primary.get("bottom"), secondary.get("bottom")) - Math.max(primary.get("top"), secondary.get("top")));
float main = Math.abs(primary.get("right") - primary.get("left")) * Math.abs(primary.get("bottom") - primary.get("top"));
intersectProportion= intersection / main;
}
overlaps = overlaps || (intersectProportion > OVERLAP_THRESHOLD);
}
if (!overlaps) {
predictions.add(prediction);
}
}
return predictions;
}
private float expit(final float x) {
return (float) (1. / (1. + Math.exp(-x)));
}
private void softmax(final float[] vals) {
float max = Float.NEGATIVE_INFINITY;
for (final float val : vals) {
max = Math.max(max, val);
}
float sum = 0.0f;
for (int i = 0; i < vals.length; ++i) {
vals[i] = (float) Math.exp(vals[i] - max);
sum += vals[i];
}
for (int i = 0; i < vals.length; ++i) {
vals[i] = vals[i] / sum;
}
}
private class PredictionComparator implements Comparator<Map<String, Object>> {
@Override
public int compare(final Map<String, Object> prediction1, final Map<String, Object> prediction2) {
return Float.compare((float)prediction2.get("confidence"), (float)prediction1.get("confidence"));
}
}
/** Writes Image data into a {@code ByteBuffer}. */
private void convertBitmapToByteBuffer(Bitmap bitmap) {
if (input == null) {
return;
}
input.rewind();
bitmap.getPixels(intValues, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());
// Convert the image to floating point.
int pixel = 0;
long startTime = SystemClock.uptimeMillis();
for (int i = 0; i < INP_IMG_WIDTH; ++i) {
for (int j = 0; j < INP_IMG_HEIGHT; ++j) {
final int val = intValues[pixel++];
int IMAGE_MEAN = 128;
float IMAGE_STD = 128.0f;
input.putFloat((((val >> 16) & 0xFF)- IMAGE_MEAN)/ IMAGE_STD);
input.putFloat((((val >> 8) & 0xFF)- IMAGE_MEAN)/ IMAGE_STD);
input.putFloat((((val) & 0xFF)- IMAGE_MEAN)/ IMAGE_STD);
}
}
long endTime = SystemClock.uptimeMillis();
Log.d(TAG, "Timecost to put values into ByteBuffer: " + Long.toString(endTime - startTime));
}
public Bitmap getBitmap(HashMap image){
Bitmap bitmap = Bitmap.createScaledBitmap(yuv420toBitMap(image), 416, 416, true);
int width = bitmap.getWidth();
int height = bitmap.getHeight();
Matrix matrix = new Matrix();
matrix.postRotate((Integer)image.get("rotation"));
return Bitmap.createBitmap(bitmap , 0, 0, width, height, matrix, true);
}
public Bitmap yuv420toBitMap(final HashMap image) {
int w = (int) image.get("width");
int h = (int) image.get("height");
ArrayList<Map> planes = (ArrayList) image.get("planes");
byte[] data = yuv420toNV21(w, h, planes);
Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
ScriptIntrinsicYuvToRGB yuvToRgbIntrinsic = ScriptIntrinsicYuvToRGB.create(rs, Element.U8_4(rs));
Type.Builder yuvType = new Type.Builder(rs, Element.U8(rs)).setX(data.length);
Allocation in = Allocation.createTyped(rs, yuvType.create(), Allocation.USAGE_SCRIPT);
in.copyFrom(data);
Type.Builder rgbaType = new Type.Builder(rs, Element.RGBA_8888(rs)).setX(w).setY(h);
Allocation out = Allocation.createTyped(rs, rgbaType.create(), Allocation.USAGE_SCRIPT);
yuvToRgbIntrinsic.setInput(in);
yuvToRgbIntrinsic.forEach(out);
out.copyTo(bitmap);
return bitmap;
}
public byte[] yuv420toNV21(int width,int height, ArrayList<Map> planes){
byte[] yBytes = (byte[]) planes.get(0).get("bytes"),
uBytes= (byte[]) planes.get(1).get("bytes"),
vBytes= (byte[]) planes.get(2).get("bytes");
final int color_pixel_stride =(int) planes.get(1).get("bytesPerPixel");
ByteArrayOutputStream outputbytes = new ByteArrayOutputStream();
try {
outputbytes.write(yBytes);
outputbytes.write(vBytes);
outputbytes.write(uBytes);
} catch (IOException e) {
e.printStackTrace();
}
byte[] data = outputbytes.toByteArray();
final int y_size = yBytes.length;
final int u_size = uBytes.length;
final int data_offset = width * height;
for (int i = 0; i < y_size; i++) {
data[i] = (byte) (yBytes[i] & 255);
}
for (int i = 0; i < u_size / color_pixel_stride; i++) {
data[data_offset + 2 * i] = vBytes[i * color_pixel_stride];
data[data_offset + 2 * i + 1] = uBytes[i * color_pixel_stride];
}
return data;
}
}
| true
|
7937e1efbdb51ecafbdc1a176ec7e9543392c821
|
Java
|
Aaronel10/Chess
|
/src/chess/pieces/Rook.java
|
UTF-8
| 3,244
| 3.125
| 3
|
[] |
no_license
|
package chess.pieces;
import chess.Team;
import chess.board.Board;
import chess.board.BoardUtils;
import chess.board.Move;
import chess.board.Tile;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class Rook extends Piece{
// rook is very similar to bishop because both move in straight lines all you need to change is the vector direction
private final static int[] possible_vector_moves = {-8, -1, 1, 8};
public Rook(int piecePosition, Team pieceTeam) {
super(piecePosition, pieceTeam, Piece_Type.ROOK, true);
}
public Rook(final int piecePosition, final Team pieceTeam, final boolean isFirstMove){
super(piecePosition, pieceTeam, Piece_Type.ROOK, isFirstMove);
}
@Override
public Collection<Move> calculateLegalMoves(Board board) {
List<Move> legalMoves = new ArrayList<>();
int possibleCoordinate;
for(int candidateMoveOffset:possible_vector_moves)
{
possibleCoordinate = this.piecePosition;
while(BoardUtils.isValidTileDestination(possibleCoordinate)){
if(isFirstColumnException(possibleCoordinate, candidateMoveOffset) ||
isEighthColumnException(possibleCoordinate, candidateMoveOffset))
{
break;
}
possibleCoordinate += candidateMoveOffset;
if(BoardUtils.isValidTileDestination(possibleCoordinate))
{
final Tile possibleTileDestination = board.getTile(possibleCoordinate);
if(!possibleTileDestination.isTileOccupied())
{// tile to move to is empty so add it to legal moves list
legalMoves.add(new Move.MajorMove(board, this, possibleCoordinate));
} else
{
Piece pieceAtDestination = possibleTileDestination.getPiece();
Team pieceTeam = pieceAtDestination.getPieceTeam();
if(this.pieceTeam != pieceTeam)
{
legalMoves.add(new Move.AttackingMove(board, this, possibleCoordinate, pieceAtDestination));
}
break; // this break is to stop checking any further tiles if theres already a piece in the way
}
}
}
}
return Collections.unmodifiableList(legalMoves);
}
// two column exceptions where algorithm fails
private static boolean isFirstColumnException(int currentPosition, int candidateOffset)
{
return BoardUtils.FIRST_COLUMN[currentPosition] && (candidateOffset == -1);
}
private static boolean isEighthColumnException(int currentPosition, int candidateOffset)
{
return BoardUtils.EIGHTH_COLUMN [currentPosition] && (candidateOffset == 1);
}
@Override
public String toString() {
return Piece.Piece_Type.ROOK.toString();
}
@Override
public Rook movePiece(Move move) {
return new Rook(move.getDestinationCoordinate(), move.getMovedPiece().getPieceTeam());
}
}
| true
|
c6b3bdb75a625110ad98ba79049967e44d3abd07
|
Java
|
atay2000/SimpleGraphLib
|
/SimpleGraphLib/test/graphlib/GraphPathFindTest.java
|
UTF-8
| 2,633
| 2.765625
| 3
|
[] |
no_license
|
package graphlib;
import static org.junit.Assert.*;
import org.junit.Test;
public class GraphPathFindTest {
@Test
public void testPathFindDir() {
IGraph<MyGraphVertex> g = new DirectedGraph<MyGraphVertex>();
MyGraphVertex mgv1 = new MyGraphVertex(1, "vertex1");
MyGraphVertex mgv2 = new MyGraphVertex(2, "vertex2");
MyGraphVertex mgv3 = new MyGraphVertex(3, "vertex3");
MyGraphVertex mgv4 = new MyGraphVertex(4, "vertex4");
MyGraphVertex mgv5 = new MyGraphVertex(5, "vertex5");
MyGraphVertex mgv6 = new MyGraphVertex(6, "vertex6");
MyGraphVertex mgv7 = new MyGraphVertex(7, "vertex7");
MyGraphVertex mgv8 = new MyGraphVertex(8, "vertex8");
g.addEdge(mgv1, mgv2);
g.addEdge(mgv1, mgv3);
g.addEdge(mgv2, mgv6);
g.addEdge(mgv3, mgv4);
g.addEdge(mgv3, mgv5);
g.addEdge(mgv3, mgv7);
g.addEdge(mgv5, mgv1);
var path = g.getPath(mgv1, mgv7);
assertEquals(path.size(), 2);
path = g.getPath(mgv7, mgv1);
assertNull(path);
path = g.getPath(mgv1, mgv1);
assertEquals(path.size(), 3);
path = g.getPath(mgv6, mgv7);
assertNull(path);
path = g.getPath(mgv8, mgv1);
assertNull(path);
path = g.getPath(mgv8, mgv8);
assertNull(path);
}
@Test
public void testPathFindUndir() {
IGraph<MyGraphVertex> g = new UndirectedGraph<MyGraphVertex>();
MyGraphVertex mgv1 = new MyGraphVertex(1, "vertex1");
MyGraphVertex mgv2 = new MyGraphVertex(2, "vertex2");
MyGraphVertex mgv3 = new MyGraphVertex(3, "vertex3");
MyGraphVertex mgv4 = new MyGraphVertex(4, "vertex4");
MyGraphVertex mgv5 = new MyGraphVertex(5, "vertex5");
MyGraphVertex mgv6 = new MyGraphVertex(6, "vertex6");
MyGraphVertex mgv7 = new MyGraphVertex(7, "vertex7");
MyGraphVertex mgv8 = new MyGraphVertex(8, "vertex8");
g.addEdge(mgv1, mgv2);
g.addEdge(mgv1, mgv3);
g.addEdge(mgv2, mgv6);
g.addEdge(mgv3, mgv4);
g.addEdge(mgv3, mgv5);
g.addEdge(mgv3, mgv7);
g.addEdge(mgv5, mgv1);
var path = g.getPath(mgv1, mgv7);
assertEquals(path.size(), 2);
path = g.getPath(mgv7, mgv1);
assertEquals(path.size(), 2);
path = g.getPath(mgv1, mgv1);
assertEquals(path.size(), 2);
path = g.getPath(mgv6, mgv7);
assertEquals(path.size(), 4);
path = g.getPath(mgv8, mgv1);
assertNull(path);
path = g.getPath(mgv8, mgv8);
assertNull(path);
}
}
| true
|