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
e1c28fed906215421b5678ceeb9996fd4d297d32
Java
rngarcia94/Bootcamp
/Spring3-m2/src/main/java/com/metroscuadraos/metrocuadrados/DTO/ResponseDTO.java
UTF-8
404
1.679688
2
[]
no_license
package com.metroscuadraos.metrocuadrados.DTO; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.List; @Data @AllArgsConstructor @NoArgsConstructor public class ResponseDTO { private double metrosCuadrados; private double valor; private HabitacionesDTO habitacionesMasGrade; private List<Double> MetrosCuadradosPorHabitacion; }
true
aba77677c5d14f0f7539862e94f834e23e08e7f4
Java
Leeeast/ArtShow
/app/src/main/java/com/art/huakai/artshow/fragment/FoundTalentsFragment.java
UTF-8
34,671
1.609375
2
[]
no_license
package com.art.huakai.artshow.fragment; import android.graphics.drawable.BitmapDrawable; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.annotation.Nullable; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.PopupWindow; import android.widget.TextView; import android.widget.Toast; import com.art.huakai.artshow.R; import com.art.huakai.artshow.activity.PersonalDetailMessageActivity; import com.art.huakai.artshow.adapter.LookingProfessionalAdapter; import com.art.huakai.artshow.adapter.LookingWorksAdapter; import com.art.huakai.artshow.adapter.SkillChooseAdapter; import com.art.huakai.artshow.adapter.TalentFilterAdapter; import com.art.huakai.artshow.base.BaseFragment; import com.art.huakai.artshow.constant.Constant; import com.art.huakai.artshow.constant.JumpCode; import com.art.huakai.artshow.decoration.GridLayoutItemDecoration; import com.art.huakai.artshow.decoration.LinearItemDecoration; import com.art.huakai.artshow.entity.ChildrenBean; import com.art.huakai.artshow.entity.SkillBean; import com.art.huakai.artshow.entity.TalentBean; import com.art.huakai.artshow.utils.AnimUtils; import com.art.huakai.artshow.utils.LogUtil; import com.art.huakai.artshow.utils.RequestUtil; import com.art.huakai.artshow.utils.ResponseCodeCheck; import com.art.huakai.artshow.utils.SignUtil; import com.art.huakai.artshow.widget.SmartRecyclerview; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TreeMap; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.Unbinder; import okhttp3.Call; public class FoundTalentsFragment extends BaseFragment implements View.OnClickListener, SmartRecyclerview.LoadingListener { @BindView(R.id.ll_complex_ranking) LinearLayout llComplexRanking; @BindView(R.id.ll_city_choose) LinearLayout llSkillChoose; @BindView(R.id.ll_filter) LinearLayout llFilter; @BindView(R.id.iv_loading) ImageView ivLoading; @BindView(R.id.iv_no_content) ImageView ivNoContent; @BindView(R.id.ll_content) LinearLayout llContent; private String TAG = "FoundTalentsFragment"; @BindView(R.id.iv_choose_price) ImageView ivComplexRanking; @BindView(R.id.iv_choose_number) ImageView ivChooseSkill; @BindView(R.id.iv_real_choose) ImageView ivFilter; Unbinder unbinder; @BindView(R.id.recyclerView) SmartRecyclerview recyclerView; @BindView(R.id.tv_whole_ranking) TextView tvComplexRanking; @BindView(R.id.tv_city_choose) TextView tvSkillChoose; @BindView(R.id.tv_real_filter) TextView tvFilter; private ArrayList<TalentBean> talentLists = new ArrayList<TalentBean>(); private LookingProfessionalAdapter lookingWorksAdapter; private LinearLayoutManager linearlayoutManager; private LinearItemDecoration linearItemDecoration; private PopupWindow popupWindow; private LayoutInflater mLayoutInflater; private int complexRankingRule = 0; private int yearPosition = -1; private String collegeName = ""; private int certificationPosition = -1; private int noRequest = -1; private int others = -1; private String skillParentId = ""; private String skillChildId = ""; private int skillChildPosition = -1; private int page = 1; private List<SkillBean> skillBeanList = new ArrayList<SkillBean>(); private boolean isLoading = false; public FoundTalentsFragment() { // Required empty public constructor } private Handler uiHandler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == 0) { ivLoading.setVisibility(View.GONE); llContent.setVisibility(View.VISIBLE); ivNoContent.setVisibility(View.GONE); setData(); } } }; public static FoundTalentsFragment newInstance() { FoundTalentsFragment fragment = new FoundTalentsFragment(); return fragment; } @Override public void initData(@Nullable Bundle bundle) { getList(); getSkillClassify(); } @Override public int getLayoutID() { return R.layout.fragment_found_talents; } @Override public void initView(View rootView) { llComplexRanking.setOnClickListener(this); llSkillChoose.setOnClickListener(this); llFilter.setOnClickListener(this); recyclerView.setLoadingListener(this); AnimUtils.rotate(ivLoading); ivNoContent.setVisibility(View.GONE); llContent.setVisibility(View.GONE); } private void setData() { linearlayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false); linearItemDecoration = new LinearItemDecoration((int) getContext().getResources().getDimension(R.dimen.DIMEN_14PX)); recyclerView.setLayoutManager(linearlayoutManager); lookingWorksAdapter = new LookingProfessionalAdapter(getContext(), talentLists); recyclerView.setAdapter(lookingWorksAdapter); lookingWorksAdapter.setOnItemClickListener(new LookingProfessionalAdapter.OnItemClickListener() { @Override public void onItemClickListener(int position) { if (talentLists.get(position) != null && !TextUtils.isEmpty(talentLists.get(position).getId())) { Bundle bundle = new Bundle(); bundle.putString(PersonalDetailMessageActivity.PARAMS_ID, talentLists.get(position).getId()); invokActivity(getContext(), PersonalDetailMessageActivity.class, bundle, JumpCode.FLAG_REQ_DETAIL_PERSONAL); } } }); } @Override public void setView() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO: inflate a fragment view View rootView = super.onCreateView(inflater, container, savedInstanceState); unbinder = ButterKnife.bind(this, rootView); mLayoutInflater = inflater; return rootView; } @Override public void onDestroyView() { super.onDestroyView(); unbinder.unbind(); } @Override public void onClick(View v) { Log.e(TAG, "onClick: v.getId==" + v.getId()); switch (v.getId()) { case R.id.ll_city_choose: // Toast.makeText(getContext(), "iv_choose_number", Toast.LENGTH_SHORT).show(); // tvComplexRanking.setTextColor(0xff5a4b41); // ivComplexRanking.setImageResource(R.mipmap.arrow_down_icon); tvSkillChoose.setTextColor(0xffe93c2c); ivChooseSkill.setImageResource(R.mipmap.arrow_active); // tvFilter.setTextColor(0xff5a4b41); // ivFilter.setImageResource(R.mipmap.filter_default); showPopuwindow(2); break; case R.id.ll_complex_ranking: tvComplexRanking.setTextColor(0xffe93c2c); ivComplexRanking.setImageResource(R.mipmap.arrow_active); // tvSkillChoose.setTextColor(0xff5a4b41); // ivChooseSkill.setImageResource(R.mipmap.arrow_down_icon); // tvFilter.setTextColor(0xff5a4b41); // ivFilter.setImageResource(R.mipmap.filter_default); showPopuwindow(1); // Toast.makeText(getContext(), "iv_choose_price", Toast.LENGTH_SHORT).show(); break; case R.id.ll_filter: // tvComplexRanking.setTextColor(0xff5a4b41); // ivComplexRanking.setImageResource(R.mipmap.arrow_down_icon); // tvSkillChoose.setTextColor(0xff5a4b41); // ivChooseSkill.setImageResource(R.mipmap.arrow_down_icon); tvFilter.setTextColor(0xffe93c2c); ivFilter.setImageResource(R.mipmap.filter_active); showPopuwindow(3); // Toast.makeText(getContext(), "iv_real_choose", Toast.LENGTH_SHORT).show(); break; } } @Override public void onRefresh() { page = 1; getList(); } @Override public void onLoadMore() { getList(); } private void showPopuwindow(int type) { if (popupWindow == null) { popupWindow = new PopupWindow(); } popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() { @Override public void onDismiss() { if (complexRankingRule != 0) { ivComplexRanking.setImageResource(R.mipmap.arrow_down_active); tvComplexRanking.setTextColor(0xffe93c2c); } else { ivComplexRanking.setImageResource(R.mipmap.arrow_down_icon); tvComplexRanking.setTextColor(0xff5a4b41); } if (!TextUtils.isEmpty(skillChildId)) { ivChooseSkill.setImageResource(R.mipmap.arrow_down_active); tvSkillChoose.setTextColor(0xffe93c2c); } else { ivChooseSkill.setImageResource(R.mipmap.arrow_down_icon); tvSkillChoose.setTextColor(0xff5a4b41); } if (yearPosition != -1 || !TextUtils.isEmpty(collegeName) || certificationPosition != -1) { tvFilter.setTextColor(0xffe93c2c); ivFilter.setImageResource(R.mipmap.filter_active); } else { tvFilter.setTextColor(0xff5a4b41); ivFilter.setImageResource(R.mipmap.filter_default); } } }); popupWindow.setBackgroundDrawable(new BitmapDrawable()); popupWindow.setWidth(WindowManager.LayoutParams.MATCH_PARENT); popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT); popupWindow.setOutsideTouchable(true); popupWindow.setFocusable(true); if (type == 1) { View content = mLayoutInflater.inflate(R.layout.found_talent_whole_ranking_popuwindow_item, null); if (complexRankingRule == 1) { content.findViewById(R.id.iv_one).setVisibility(View.VISIBLE); TextView view = (TextView) content.findViewById(R.id.tv_one); view.setTextColor(0xffe93c2c); } else if (complexRankingRule == 2) { content.findViewById(R.id.iv_two).setVisibility(View.VISIBLE); TextView view = (TextView) content.findViewById(R.id.tv_two); view.setTextColor(0xffe93c2c); } popupWindow.setContentView(content); content.findViewById(R.id.tv_one).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (complexRankingRule == 1) { complexRankingRule = 0; tvComplexRanking.setText("综合排序"); } else { complexRankingRule = 1; tvComplexRanking.setText("年龄由高到低"); } if (popupWindow != null && popupWindow.isShowing()) { popupWindow.dismiss(); } page = 1; getList(); talentLists.clear(); } }); content.findViewById(R.id.tv_two).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (complexRankingRule == 2) { complexRankingRule = 0; tvComplexRanking.setText("综合排序"); } else { complexRankingRule = 2; tvComplexRanking.setText("年龄由低到高"); } if (popupWindow != null && popupWindow.isShowing()) { popupWindow.dismiss(); } page = 1; getList(); talentLists.clear(); } }); } else if (type == 3) { final View content = mLayoutInflater.inflate(R.layout.found_talents_real_filter_popuwindow_item, null); ArrayList<String> stringsone = new ArrayList<String>(); stringsone.add("不限"); stringsone.add("10岁以下"); stringsone.add("10-20岁"); stringsone.add("21-30岁"); stringsone.add("31-45岁"); stringsone.add("46-60岁"); stringsone.add("60岁以上"); RecyclerView recyclerViewone = (RecyclerView) content.findViewById(R.id.rcv_one); final TalentFilterAdapter singleChooseAdapterone = new TalentFilterAdapter(getContext(), stringsone, yearPosition); singleChooseAdapterone.setOnItemClickListener(new TalentFilterAdapter.OnItemClickListener() { @Override public void onItemClick(int position, String url) { yearPosition = position; } }); GridLayoutItemDecoration gridLayoutItemDecorationone = new GridLayoutItemDecoration(2, GridLayoutManager.VERTICAL, 40, 20); recyclerViewone.setItemAnimator(null); GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 2); gridLayoutManager.setOrientation(GridLayoutManager.VERTICAL); recyclerViewone.addItemDecoration(gridLayoutItemDecorationone); recyclerViewone.setLayoutManager(gridLayoutManager); recyclerViewone.setAdapter(singleChooseAdapterone); recyclerViewone.setNestedScrollingEnabled(false); RecyclerView recyclerViewtwo = (RecyclerView) content.findViewById(R.id.rcv_two); ArrayList<String> stringstwo = new ArrayList<String>(); stringstwo.add("不限"); stringstwo.add("中央戏剧学院"); stringstwo.add("北京电影学院"); stringstwo.add("中央戏曲学院"); stringstwo.add("北京舞蹈学院"); stringstwo.add("上海戏剧学院"); stringstwo.add("中国传媒大学"); stringstwo.add("中央音乐学院"); stringstwo.add("解放军艺术学校"); stringstwo.add("其他"); int position = stringstwo.indexOf(collegeName); final TalentFilterAdapter singleChooseAdaptertwo = new TalentFilterAdapter(getContext(), stringstwo, position); singleChooseAdaptertwo.setOnItemClickListener(new TalentFilterAdapter.OnItemClickListener() { @Override public void onItemClick(int position, String name) { collegeName = name; } }); GridLayoutItemDecoration gridLayoutItemDecorationtwo = new GridLayoutItemDecoration(2, GridLayoutManager.VERTICAL, 40, 20); recyclerViewtwo.setItemAnimator(null); GridLayoutManager gridLayoutManagertwo = new GridLayoutManager(getContext(), 2); gridLayoutManagertwo.setOrientation(GridLayoutManager.VERTICAL); recyclerViewtwo.addItemDecoration(gridLayoutItemDecorationtwo); recyclerViewtwo.setLayoutManager(gridLayoutManagertwo); recyclerViewtwo.setAdapter(singleChooseAdaptertwo); recyclerViewtwo.setNestedScrollingEnabled(false); RecyclerView recyclerViewthree = (RecyclerView) content.findViewById(R.id.rcv_three); ArrayList<String> stringsthree = new ArrayList<String>(); stringsthree.add("不限"); stringsthree.add("专业认证"); final TalentFilterAdapter singleChooseAdapterthree = new TalentFilterAdapter(getContext(), stringsthree, certificationPosition); singleChooseAdapterthree.setOnItemClickListener(new TalentFilterAdapter.OnItemClickListener() { @Override public void onItemClick(int position, String url) { certificationPosition = position; } }); GridLayoutItemDecoration gridLayoutItemDecorationthree = new GridLayoutItemDecoration(2, GridLayoutManager.VERTICAL, 40, 20); recyclerViewthree.setItemAnimator(null); GridLayoutManager gridLayoutManagerthree = new GridLayoutManager(getContext(), 2); gridLayoutManagerthree.setOrientation(GridLayoutManager.VERTICAL); recyclerViewthree.addItemDecoration(gridLayoutItemDecorationthree); recyclerViewthree.setLayoutManager(gridLayoutManagerthree); recyclerViewthree.setAdapter(singleChooseAdapterthree); recyclerViewthree.setNestedScrollingEnabled(false); content.findViewById(R.id.but_reset).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (singleChooseAdapterone != null) { yearPosition = -1; singleChooseAdapterone.resetData(); } if (singleChooseAdaptertwo != null) { collegeName = ""; singleChooseAdaptertwo.resetData(); } if (singleChooseAdapterthree != null) { certificationPosition = -1; singleChooseAdapterthree.resetData(); } if (popupWindow != null && popupWindow.isShowing()) { popupWindow.dismiss(); } page = 1; getList(); talentLists.clear(); } }); content.findViewById(R.id.but_sure).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (popupWindow != null && popupWindow.isShowing()) { popupWindow.dismiss(); } page = 1; getList(); talentLists.clear(); } }); popupWindow.setContentView(content); } else if (type == 2) { View content = mLayoutInflater.inflate(R.layout.found_talents_skill_kind_popuwindow_item, null); LinearLayout rl_whole = (LinearLayout) content.findViewById(R.id.rl_whole); final TextView tv_no_request = (TextView) content.findViewById(R.id.tv_no_request); final TextView tv_others = (TextView) content.findViewById(R.id.tv_others); if (noRequest == 0) { tv_no_request.setTextColor(0xffe93c2c); tv_no_request.setBackgroundResource(R.drawable.red_rectang); } else { tv_no_request.setTextColor(0xff9b9b9b); tv_no_request.setBackgroundResource(R.drawable.grey_rectang); } if (others == 0) { tv_others.setTextColor(0xffe93c2c); tv_others.setBackgroundResource(R.drawable.red_rectang); } else { tv_others.setTextColor(0xff9b9b9b); tv_others.setBackgroundResource(R.drawable.grey_rectang); } tv_no_request.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { tvSkillChoose.setText("不限"); others = 0; tv_others.setTextColor(0xffe93c2c); tv_others.setBackgroundResource(R.drawable.red_rectang); tv_no_request.setTextColor(0xff9b9b9b); tv_no_request.setBackgroundResource(R.drawable.grey_rectang); noRequest = -1; skillChildId = ""; skillParentId = ""; skillChildPosition = -1; if (popupWindow != null && popupWindow.isShowing()) { popupWindow.dismiss(); } page = 1; getList(); talentLists.clear(); } }); for (int i = 0; i < skillBeanList.size(); i++) { final List<ChildrenBean> tempChildrenBeans = skillBeanList.get(i).getChildren(); if (tempChildrenBeans == null && tempChildrenBeans.size() == 0) { Log.e(TAG, "showPopuwindow: hahaha00000"); } View view = LayoutInflater.from(getContext()).inflate(R.layout.skill_choose_item, null); TextView tv = (TextView) view.findViewById(R.id.tv_name); RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.rcv); final String tempSkillParentId = skillBeanList.get(i).getId() + ""; boolean tempWhetherChoosen = skillParentId.equals(tempSkillParentId); tv.setText(skillBeanList.get(i).getName()); final SkillChooseAdapter skillChooseAdapter = new SkillChooseAdapter(getContext(), tempChildrenBeans, skillChildPosition, tempWhetherChoosen); skillChooseAdapter.setOnItemClickListener(new SkillChooseAdapter.OnItemClickListener() { @Override public void onItemClick(int position, String url) { skillParentId = tempSkillParentId; skillChildId = tempChildrenBeans.get(position).getId() + ""; tvSkillChoose.setText(tempChildrenBeans.get(position).getName()); skillChildPosition = position; if (popupWindow != null && popupWindow.isShowing()) { popupWindow.dismiss(); } page = 1; getList(); talentLists.clear(); } }); GridLayoutItemDecoration gridLayoutItemDecorationone = new GridLayoutItemDecoration(3, GridLayoutManager.VERTICAL, 40, 20); recyclerView.setItemAnimator(null); GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 3); gridLayoutManager.setOrientation(GridLayoutManager.VERTICAL); recyclerView.addItemDecoration(gridLayoutItemDecorationone); recyclerView.setLayoutManager(gridLayoutManager); recyclerView.setAdapter(skillChooseAdapter); recyclerView.setNestedScrollingEnabled(false); rl_whole.addView(view, i + 2); } popupWindow.setContentView(content); } if (popupWindow != null && !popupWindow.isShowing()) { if (Build.VERSION.SDK_INT < 24) { popupWindow.showAsDropDown(llComplexRanking, 0, getResources().getDimensionPixelSize(R.dimen.DIMEN_1PX)); } else { int[] Location = new int[2]; llComplexRanking.getLocationInWindow(Location); int x = Location[0]; int y = Location[1]; popupWindow.showAtLocation( llComplexRanking, Gravity.NO_GRAVITY, 0, y + llComplexRanking.getHeight() + getResources().getDimensionPixelSize(R.dimen.DIMEN_1PX)); } } } private void getList() { if (isLoading) { return; } isLoading = true; Map<String, String> params = new TreeMap<>(); Log.e(TAG, "getMessage: Constant.URL_GET_CLASSFY_LIST==" + Constant.URL_GET_TALENTS); if (!TextUtils.isEmpty(skillChildId)) { params.put("classifyId", skillChildId); } if (yearPosition == 1) { params.put("ageMax", "10"); } else if (yearPosition == 2) { params.put("ageMin", "10"); params.put("ageMax", "20"); } else if (yearPosition == 3) { params.put("ageMin", "21"); params.put("ageMax", "30"); } else if (yearPosition == 4) { params.put("ageMin", "31"); params.put("ageMax", "45"); } else if (yearPosition == 5) { params.put("ageMin", "46"); params.put("ageMax", "60"); } else if (yearPosition == 6) { params.put("ageMin", "60"); } if (!TextUtils.isEmpty(collegeName) && !collegeName.equals("不限")) { params.put("school", collegeName); } if (complexRankingRule == 1) { params.put("order", "age"); params.put("orderType", "desc"); } else if (complexRankingRule == 2) { params.put("order", "age"); params.put("orderType", "asc"); } params.put("page", page + ""); String sign = SignUtil.getSign(params); params.put("sign", sign); Log.e(TAG, "getList: sign==" + sign); Log.e(TAG, "getList: params==" + params.toString()); RequestUtil.request(true, Constant.URL_GET_TALENTS, params, 110, new RequestUtil.RequestListener() { @Override public void onSuccess(boolean isSuccess, String obj, int code, int id) { isLoading = false; LogUtil.i(TAG, obj); uiHandler.postDelayed(new Runnable() { @Override public void run() { if (page == 1 && talentLists.size() == 0) { ivLoading.setVisibility(View.GONE); llContent.setVisibility(View.GONE); ivNoContent.setVisibility(View.VISIBLE); } } }, 500); if (isSuccess) { if (!TextUtils.isEmpty(obj)) { Log.e(TAG, "onSuccess: obj==" + obj); Gson gson = new Gson(); ArrayList<TalentBean> tempTheatres = new ArrayList<TalentBean>(); // theatres.clear(); tempTheatres = gson.fromJson(obj, new TypeToken<List<TalentBean>>() { }.getType()); if (tempTheatres != null && tempTheatres.size() > 0) { if (talentLists.size() == 0) { if (talentLists.addAll(tempTheatres)) { uiHandler.removeCallbacksAndMessages(null); uiHandler.sendEmptyMessage(0); } page++; } else { if (page == 1) { recyclerView.refreshComplete(); talentLists.clear(); if (talentLists.addAll(tempTheatres)) { uiHandler.sendEmptyMessage(0); } } else { recyclerView.loadMoreComplete(); talentLists.addAll(tempTheatres); if (lookingWorksAdapter != null) { // lookingWorksAdapter.add(tempTheatres); lookingWorksAdapter.notifyDataSetChanged(); } } page++; } } else { if (talentLists.size() == 0) { Toast.makeText(getContext(), "未查询到您筛选的数据", Toast.LENGTH_SHORT).show(); Log.e(TAG, "onSuccess: 首次加载数据失败"); } else { if (page == 1) { Toast.makeText(getContext(), "刷新数据失败", Toast.LENGTH_SHORT).show(); Log.e(TAG, "onSuccess: 刷新数据失败"); recyclerView.refreshComplete(); } else { recyclerView.loadMoreComplete(); Toast.makeText(getContext(), "已无更多数据", Toast.LENGTH_SHORT).show(); Log.e(TAG, "onSuccess: 加载更多数据失败"); } } } Log.e(TAG, "onSuccess: theatres.size==" + talentLists.size()); } else { if (talentLists.size() == 0) { Toast.makeText(getContext(), "未查询到您筛选的数据", Toast.LENGTH_SHORT).show(); Log.e(TAG, "onSuccess: 首次加载数据失败"); } else { if (page == 1) { recyclerView.refreshComplete(); Toast.makeText(getContext(), "刷新数据失败", Toast.LENGTH_SHORT).show(); Log.e(TAG, "onSuccess: 刷新数据失败"); } else { recyclerView.loadMoreComplete(); Toast.makeText(getContext(), "已无更多数据", Toast.LENGTH_SHORT).show(); Log.e(TAG, "onSuccess: 加载更多数据失败"); } } } } else { if (talentLists.size() == 0) { Toast.makeText(getContext(), "未查询到您筛选的数据", Toast.LENGTH_SHORT).show(); Log.e(TAG, "onSuccess: 首次加载数据失败"); ivLoading.setVisibility(View.GONE); llContent.setVisibility(View.GONE); ivNoContent.setVisibility(View.VISIBLE); } else { if (page == 1) { recyclerView.refreshComplete(); Toast.makeText(getContext(), "刷新数据失败", Toast.LENGTH_SHORT).show(); Log.e(TAG, "onSuccess: 刷新数据失败"); } else { recyclerView.loadMoreComplete(); Toast.makeText(getContext(), "已无更多数据", Toast.LENGTH_SHORT).show(); Log.e(TAG, "onSuccess: 加载更多数据失败"); } } ResponseCodeCheck.showErrorMsg(code); } } @Override public void onFailed(Call call, Exception e, int id) { LogUtil.e(TAG, e.getMessage() + "- id = " + id); isLoading = false; if (talentLists.size() == 0) { Toast.makeText(getContext(), "未查询到您筛选的数据", Toast.LENGTH_SHORT).show(); Log.e(TAG, "onSuccess: 首次加载数据失败"); ivLoading.setVisibility(View.GONE); llContent.setVisibility(View.GONE); ivNoContent.setVisibility(View.VISIBLE); } else { if (page == 1) { recyclerView.refreshComplete(); Toast.makeText(getContext(), "刷新数据失败", Toast.LENGTH_SHORT).show(); Log.e(TAG, "onSuccess: 刷新数据失败"); } else { recyclerView.loadMoreComplete(); Toast.makeText(getContext(), "已无更多数据", Toast.LENGTH_SHORT).show(); Log.e(TAG, "onSuccess: 加载更多数据失败"); } } } }); } private void getSkillClassify() { Map<String, String> params = new TreeMap<>(); Log.e(TAG, "getMessage: Constant.URL_GET_CLASSFY_LIST==" + Constant.URL_GET_CLASSFY_LIST); params.put("type", "talent"); String sign = SignUtil.getSign(params); params.put("sign", sign); Log.e(TAG, "getList: sign==" + sign); Log.e(TAG, "getRepertoryClassify: " + params.toString()); RequestUtil.request(true, Constant.URL_GET_CLASSFY_LIST, params, 108, new RequestUtil.RequestListener() { @Override public void onSuccess(boolean isSuccess, String obj, int code, int id) { if (isSuccess) { if (!TextUtils.isEmpty(obj)) { Log.e(TAG, "onSuccess: obj222=" + obj); Gson gson = new Gson(); if (skillBeanList.size() > 0) { skillBeanList.clear(); } skillBeanList = gson.fromJson(obj, new TypeToken<List<SkillBean>>() { }.getType()); Log.e(TAG, "onSuccess: skillBeanList.size==" + skillBeanList.size()); } } else { ResponseCodeCheck.showErrorMsg(code); } } @Override public void onFailed(Call call, Exception e, int id) { LogUtil.e(TAG, e.getMessage() + "- id = " + id); } }); } }
true
33c85565278f669767be74ca6235467202663022
Java
orlof/ecs
/src/main/java/org/megastage/ecs/components/ECSBindTo.java
UTF-8
444
1.90625
2
[]
no_license
package org.megastage.ecs.components; import org.megastage.ecs.messages.ECSMessage; @KryoMessage @AllocateCid public class ECSBindTo extends ECSMessageComponent { private transient int transmittedMaster; public int master; @Override public boolean isDirty() { return transmittedMaster != master; } @Override public ECSMessage transmit() { transmittedMaster = master; return this; } }
true
42453c147d9567bc0bffa113f31c5c6ef35e1584
Java
Steinerghost/Dominion-Java-
/pile.java
UTF-8
210
1.992188
2
[]
no_license
public class pile{ String name; //The name of the cards in the pile int num_cards; //The number of cards in a pile int num_tokens; //The number of tokens in a pile from the embargo card }
true
10c8e617573a32be91a9c2584a6e95e59180d886
Java
Indivikar/Example
/src/ListView/SimpleListView/SimpleListViewDemo.java
UTF-8
4,067
2.828125
3
[]
no_license
package ListView.SimpleListView; import java.util.ArrayList; import java.util.List; import javafx.application.Application; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import javafx.scene.layout.HBox; import javafx.scene.layout.HBoxBuilder; import javafx.scene.layout.TilePane; import javafx.scene.paint.Color; import javafx.stage.Stage; import javafx.util.Callback; public class SimpleListViewDemo extends Application { Stage stage; Scene scene; TilePane root; public static void main(String[] args) { Application.launch(args); } @Override public void start(Stage stage) throws Exception { this.stage = stage; configureScene(); configureStage(); configureHeaderListView(); } private void configureHeaderListView() { ObservableList<ListData> list = getListData(); ListView<ListData> listView = new ListView<ListData>(); listView.setItems(list); listView.setCellFactory(new Callback<ListView<ListData>, ListCell<ListData>>() { @Override public ListCell<ListData> call(ListView<ListData> arg0) { return new ListCell<ListData>() { @Override public void updateItem(ListData item, boolean empty) { super.updateItem(item, empty); if (!isEmpty()) { HBox hb = HBoxBuilder.create().spacing(20).children(new Label(item.getCode()), new Label(item.getDesc())).build(); setGraphic(hb); } } }; } }); listView.setPrefWidth(300); listView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<ListData>() { @Override public void changed(ObservableValue<? extends ListData> paramObservableValue, ListData paramT1, ListData paramT2) { System.out.println("----------------------------> " + paramT2.getCode()); } }); root.getChildren().addAll(listView); } private ObservableList<ListData> getListData() { List<ListData> list = new ArrayList<ListData>(); list.add(new ListData("A", "Apple")); list.add(new ListData("B", "Bread")); list.add(new ListData("C", "Cool Drink")); list.add(new ListData("D", "Drainage")); list.add(new ListData("E", "Encyclopedia")); list.add(new ListData("F", "Father in law")); list.add(new ListData("G", "Goddess")); list.add(new ListData("H", "Helicopter")); list.add(new ListData("I", "IreLand")); list.add(new ListData("J", "Jack n Jill")); list.add(new ListData("K", "Kingston")); list.add(new ListData("L", "Lantern")); list.add(new ListData("M", "Monkey")); list.add(new ListData("N", "Nasiruddin Shah")); list.add(new ListData("O", "Omani")); list.add(new ListData("P", "Pandi")); list.add(new ListData("Q", "Queen")); list.add(new ListData("R", "Rasberrry")); list.add(new ListData("S", "Satthi pandu")); list.add(new ListData("T", "Telangana")); list.add(new ListData("U", "Uranium")); list.add(new ListData("V", "Very good")); list.add(new ListData("W", "Wat is that")); list.add(new ListData("X", "Xenon rays")); list.add(new ListData("Y", "Yatch")); list.add(new ListData("Z", "Zindagi na milegi")); ObservableList<ListData> olist = FXCollections.observableArrayList(); olist.addAll(list); return olist; } private void configureStage() { stage.setTitle("List View Demo"); stage.setWidth(600); stage.setHeight(600); stage.setScene(this.scene); stage.show(); } private void configureScene() { root = new TilePane(); root.autosize(); this.scene = new Scene(root, Color.LINEN); } } class ListData { private String code; private String desc; public ListData(String code, String desc) { super(); this.code = code; this.desc = desc; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } }
true
8f1af6df0a24d78978344ec04454ea1e0b2ab4fd
Java
newkayak12/JPA_REVIEW
/JPA/chapter05/src/main/java/chpater05/pureRelationship/RelationshipMain.java
UTF-8
445
2.921875
3
[]
no_license
package chpater05.pureRelationship; public class RelationshipMain { public static void main(String[] args) { // 순수한 객체 간의 연관 관계 Member member1 = new Member("member1", "회원1"); Member member2 = new Member("member2", "회원2"); Team team1 = new Team("team1", "팀1"); member1.setTeam(team1); member2.setTeam(team1); Team findTeam = member1.getTeam(); } }
true
09db5c095f1199001245269bdca77b94b18d6c75
Java
abbi-gaurav/learning
/AlgorithmsNDS/src/coursera/alg1/lect3/SelectTest.java
UTF-8
524
2.484375
2
[]
no_license
package coursera.alg1.lect3; import org.junit.Assert; import org.junit.Test; import coursera.alg1.lect4.TestHelper; public class SelectTest { @Test public void testSelect(){ Double[] doubles = TestHelper.getArray(1000); Double[] cloned = doubles.clone(); QuickSort<Double> sort = new QuickSort<>(); sort.doSort(doubles); for(int i = 1; i < doubles.length; i *= 7) { Comparable<Double> actual = sort.select(cloned, i); Assert.assertEquals("failed for index["+i+"]",doubles[i], actual); } } }
true
a756701c641af4a43fb27ed6bc077b380119ef48
Java
thetheos/Q3_INFO2
/Exercices/LEPL1402_QueueWithStacks/src/main/java/MyQueue.java
UTF-8
1,108
3.46875
3
[]
no_license
import java.util.Arrays; import java.util.Stack; import java.util.function.Supplier; import java.util.stream.Stream; import static org.junit.Assert.assertEquals; public class MyQueue<E> { Stack<E> s1; Stack<E> s2; private E front; /* * Constructor */ public MyQueue() { s1 = new Stack<>(); s2 = new Stack<>(); this.front = null; } public void enqueue(E elem) { s1.push(elem); } public E dequeue() { return s1.remove(0); } public E peek() { return s1.get(0); } public boolean empty() { return s1.size() == 0; } public static void main(String[] args) { MyQueue<Integer> queue = new MyQueue<>(); Supplier<Integer> rnd = () -> (int) (Math.random() * 100); Integer [] seeds = Stream.generate(rnd).limit(100).toArray(Integer[]::new); Arrays.stream(seeds).forEach(queue::enqueue); for(int i=0; i < 100; i++){ System.out.println("Seed " + seeds[i]); System.out.println("Queue " + queue.dequeue()); } } }
true
9e4740687cf0f23b14e3d6d183dbbebda75b87b3
Java
krmunna01234/ThoughtWorksWorkshop
/src/main/java/com/cricket/Match.java
UTF-8
1,161
3.390625
3
[]
no_license
package com.cricket; import com.cricket.model.Batsman; import com.cricket.model.Bowler; import com.cricket.util.CricketBall; public class Match { public static final int MIN_RUN = 0; public static final int MAX_RUN = 6; public void playMatch(int[] balls, Batsman batsman, Bowler bowler, int target){ int ball = 0; while (ball < balls.length && batsman.getTotalRun() >= target){ batsman.hitRun(); int numberBall = CricketBall.getBall(MIN_RUN, MAX_RUN); System.out.println("Number of ball : " + ball + " Batsman got : " + batsman.getRun() + ", Baller has : " + numberBall); batsman.setBatsmanOut(numberBall); if(batsman.isOut()) { break; } bowler.setTotalBall(numberBall); ball++; } if (batsman.isOut()) { System.out.println("\n Batsman is out"); } if (batsman.getTotalRun() >= target) System.out.println("\nBatsman won the match"); else System.out.println("\nBatsman lost the match"); } }
true
ebce94aa5e166d3b56aa74e36357bd7e00278054
Java
ryankschee/tyche-app
/src/main/java/com/tychees/core/bean/billing/BillingBucketLineBean.java
UTF-8
8,236
1.914063
2
[]
no_license
package com.tychees.core.bean.billing; import java.util.List; import java.util.UUID; import javax.jdo.annotations.IdentityType; import javax.jdo.annotations.PersistenceCapable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import javax.persistence.Transient; import com.tychees.core.bean.BeanSuperClass; @Entity @Table(name="billing_bucket_line_table") @PersistenceCapable(identityType=IdentityType.DATASTORE, detachable="false") public class BillingBucketLineBean extends BeanSuperClass implements java.io.Serializable { private static final long serialVersionUID = 1467880004586236216L; @Transient public List<BillingBucketLineBean> lineList; public BillingBucketLineBean() { this(UUID.randomUUID().toString()); } public BillingBucketLineBean(String id) { super(); this.setId(id); } @Column(name="bucket_id") String bucketId = ""; @Column(name="billing_id") String billingId = ""; @Column(name="billing_no") String billingNo = ""; @Column(name="billing_line_id") String billingLineId = ""; @Column(name="parent_line_id") String parentLineId = ""; @Column(name="component_id") String componentId = ""; @Column(name="item_id") String itemId = ""; @Column(name="item_name") String itemName = ""; @Column(name="item_type") String itemType = ""; @Column(name="item_group_name") String itemGroupName = ""; @Column(name="item_labels") String itemLabels = ""; @Column(name="item_image_url") String itemImageUrl = ""; @Column(name="row_id") String rowId = ""; @Column(name="selected") boolean selected = false; @Column(name="mandatory") boolean mandatory = false; // IF TRUE, this billing line is at mandatory list @Column(name="ignored") boolean ignored = false; // If TRUE, this billing line will not get processed. @Column(name="quantity") double quantity = 0.0; @Column(name="quantity_optional") boolean quantityOptional = false; @Column(name="unit_price_source") String unitPriceSource = ""; @Column(name="default_unit_price") double defaultUnitPrice = 0.0; @Column(name="compound_unit_price") double compoundUnitPrice = 0.0; @Column(name="custom_unit_price") double customUnitPrice = 0.0; @Column(name="compound_unit_cost") double compoundUnitCost = 0.0; @Column(name="item_unit_price") double itemUnitPrice = 0.0; // NEW - Item Unit Price (do not change after billing line created) @Column(name="billable_amount") double billableAmount = 0.0; // NEW - Billable amount: Amount not include tax, and after discount. @Column(name="tax_inclusive") boolean taxInclusive = false; @Column(name="tax_discount_in_percentage") boolean taxDiscountInPercentage = false; @Column(name="tax_discount_in_amount") boolean taxDiscountInAmount = false; @Column(name="tax_amount") double taxAmount = 0.0; @Column(name="tax_percentage") double taxPercentage = 0.0; @Column(name="discount_amount") double discountAmount = 0.0; @Column(name="discount_percentage") double discountPercentage = 0.0; @Column(name="add_to_billing") boolean addToBilling = false; public String getBucketId() { return this.bucketId; } public String getBillingId() { return this.billingId; } public String getBillingNo() { return this.billingNo; } public String getBillingLineId() { return this.billingLineId; } public String getParentLineId() { return this.parentLineId; } public String getComponentId() { return this.componentId; } public String getItemId() { return this.itemId; } public String getItemName() { return this.itemName; } public String getItemType() { return this.itemType; } public String getItemGroupName() { return this.itemGroupName; } public String getItemLabels() { return this.itemLabels; } public String getRowId() { return this.rowId; } public boolean isSelected() { return this.selected; } public boolean isMandatory() { return this.mandatory; } public boolean isIgnored() { return this.ignored; } public double getQuantity() { return this.quantity; } public boolean isQuantityOptional() { return this.quantityOptional; } public String getUnitPriceSource() { return this.unitPriceSource; } public double getDefaultUnitPrice() { return this.defaultUnitPrice; } public double getCustomUnitPrice() { return this.customUnitPrice; } public double getCompoundUnitCost() { return this.compoundUnitCost; } public double getCompoundUnitPrice() { return this.compoundUnitPrice; } public double getItemUnitPrice() { return this.itemUnitPrice; } public double getBillableAmount() { return this.billableAmount; } public boolean isTaxInclusive() { return this.taxInclusive; } public boolean isTaxDiscountInPercentage() { return this.taxDiscountInPercentage; } public boolean isTaxDiscountInAmount() { return this.taxDiscountInAmount; } public double getTaxAmount() { return this.taxAmount; } public double getTaxPercentage() { return this.taxPercentage; } public double getDiscountAmount() { return this.discountAmount; } public double getDiscountPercentage() { return this.discountPercentage; } public boolean isAddToBilling() { return this.addToBilling; } public void setBucketId(String val) { this.bucketId = getSafeString(val); } public void setBillingId(String val) { this.billingId = getSafeString(val); } public void setBillingNo(String val) { this.billingNo = getSafeString(val); } public void setBillingLineId(String val) { this.billingLineId = getSafeString(val); } public void setParentLineId(String val) { this.parentLineId = getSafeString(val); } public void setComponentId(String val) { this.componentId = getSafeString(val); } public void setItemId(String val) { this.itemId = getSafeString(val); } public void setItemName(String val) { this.itemName = getSafeString(val); } public void setItemType(String val) { this.itemType = getSafeString(val); } public void setItemGroupName(String val) { this.itemGroupName = getSafeString(val); } public void setItemLabels(String val) { this.itemLabels = getSafeString(val); } public void setRowId(String val) { this.rowId = getSafeString(val); } public void setSelected(boolean val) { this.selected = val; } public void setMandatory(boolean val) { this.mandatory = val; } public void setIgnored(boolean val) { this.ignored = val; } public void setQuantity(double val) { this.quantity = val; } public void setQuantityOptional(boolean val) { this.quantityOptional = val; } public void setUnitPriceSource(String val) { this.unitPriceSource = getSafeString(val); } public void setDefaultUnitPrice(double val) { this.defaultUnitPrice = val; } public void setCustomUnitPrice(double val) { this.customUnitPrice = val; } public void setCompoundUnitCost(double val) { this.compoundUnitCost = val; } public void setCompoundUnitPrice(double val) { this.compoundUnitPrice = val; } public void setItemUnitPrice(double val) { this.itemUnitPrice = val; } public void setBillableAmount(double val) { this.billableAmount = val; } public void setTaxInclusive(boolean val) { this.taxInclusive = val; } public void setTaxDiscountInPercentage(boolean val) { this.taxDiscountInPercentage = val; } public void setTaxDiscountInAmount(boolean val) { this.taxDiscountInAmount = val; } public void setTaxAmount(double val) { this.taxAmount = val; } public void setTaxPercentage(double val) { this.taxPercentage = val; } public void setDiscountAmount(double val) { this.discountAmount = val; } public void setDiscountPercentage(double val) { this.discountPercentage = val; } public void setAddToBilling(boolean val) { this.addToBilling = val; } @Override public String getBeanName() { return this.getClass().getName(); } @Override public String getDisplayName() { return this.getClass().getName(); } }
true
21479ce102c1a4aeb72d77aa04e39deb14ebf087
Java
alagalah/groupbasedpolicy
/sxp-integration/sxp-ise-adapter/src/test/java/org/opendaylight/groupbasedpolicy/sxp_ise_adapter/impl/GbpIseConfigListenerImplTest.java
UTF-8
5,592
1.507813
2
[]
no_license
/* * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.groupbasedpolicy.sxp_ise_adapter.impl; import com.google.common.collect.Lists; import com.google.common.util.concurrent.Futures; import java.util.Collections; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InOrder; import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; import org.opendaylight.controller.md.sal.binding.api.DataBroker; import org.opendaylight.controller.md.sal.binding.api.DataObjectModification; import org.opendaylight.controller.md.sal.binding.api.DataTreeModification; import org.opendaylight.controller.md.sal.binding.api.WriteTransaction; import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.groupbasedpolicy.sxp.integration.sxp.ise.adapter.model.rev160630.gbp.sxp.ise.adapter.IseHarvestStatus; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.groupbasedpolicy.sxp.integration.sxp.ise.adapter.model.rev160630.gbp.sxp.ise.adapter.IseSourceConfig; import org.opendaylight.yang.gen.v1.urn.opendaylight.sxp.database.rev160308.Sgt; import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; /** * Test for {@link GbpIseConfigListenerImpl}. */ @RunWith(MockitoJUnitRunner.class) public class GbpIseConfigListenerImplTest { private static final SgtInfo SGT_INFO = new SgtInfo(new Sgt(42), "ultimate_group", "uuidOf42"); @Mock private DataBroker dataBroker; @Mock private GbpIseSgtHarvester harvester; @Mock private DataTreeModification<IseSourceConfig> treeModification; @Mock private DataObjectModification<IseSourceConfig> dataModification; @Mock private WriteTransaction wTx; @Mock private IseSourceConfig config; @Mock private EPPolicyTemplateProviderFacade templateProviderFacade; @Captor private ArgumentCaptor<IseContext> iseContextCpt; private GbpIseConfigListenerImpl listener; @Before public void setUp() throws Exception { listener = new GbpIseConfigListenerImpl(dataBroker, harvester, templateProviderFacade); } @Test public void testOnDataTreeChanged_noop() throws Exception { Mockito.when(dataModification.getDataAfter()).thenReturn(null); Mockito.when(treeModification.getRootNode()).thenReturn(dataModification); listener.onDataTreeChanged(Collections.singleton(treeModification)); Mockito.verifyNoMoreInteractions(harvester, dataBroker); } @Test public void testOnDataTreeChanged_succeeded() throws Exception { Mockito.when(dataModification.getDataAfter()).thenReturn(config); Mockito.when(treeModification.getRootNode()).thenReturn(dataModification); Mockito.when(harvester.harvestAll(iseContextCpt.capture())).thenReturn(Futures.immediateFuture(Lists.newArrayList(SGT_INFO))); Mockito.when(wTx.submit()).thenReturn(Futures.immediateCheckedFuture(null)); Mockito.when(dataBroker.newWriteOnlyTransaction()).thenReturn(wTx); listener.onDataTreeChanged(Collections.singleton(treeModification)); listener.close(); Assert.assertSame(config, iseContextCpt.getValue().getIseSourceConfig()); final InOrder inOrder = Mockito.inOrder(harvester, dataBroker, wTx); inOrder.verify(harvester).harvestAll(Matchers.<IseContext>any()); inOrder.verify(dataBroker).newWriteOnlyTransaction(); inOrder.verify(wTx).put(Matchers.eq(LogicalDatastoreType.OPERATIONAL), Matchers.<InstanceIdentifier<IseHarvestStatus>>any(), Matchers.<IseHarvestStatus>any(), Matchers.eq(true)); inOrder.verify(wTx).submit(); inOrder.verifyNoMoreInteractions(); } @Test public void testOnDataTreeChanged_failed() throws Exception { Mockito.when(dataModification.getDataAfter()).thenReturn(config); Mockito.when(treeModification.getRootNode()).thenReturn(dataModification); Mockito.when(harvester.harvestAll(iseContextCpt.capture())).thenReturn(Futures.immediateFailedFuture( new Exception("extremely poor harvestAll occurred"))); Mockito.when(wTx.submit()).thenReturn(Futures.immediateCheckedFuture(null)); Mockito.when(dataBroker.newWriteOnlyTransaction()).thenReturn(wTx); listener.onDataTreeChanged(Collections.singleton(treeModification)); listener.close(); Assert.assertSame(config, iseContextCpt.getValue().getIseSourceConfig()); final InOrder inOrder = Mockito.inOrder(harvester, dataBroker, wTx); inOrder.verify(harvester).harvestAll(Matchers.<IseContext>any()); inOrder.verify(dataBroker).newWriteOnlyTransaction(); inOrder.verify(wTx).put(Matchers.eq(LogicalDatastoreType.OPERATIONAL), Matchers.<InstanceIdentifier<IseHarvestStatus>>any(), Matchers.<IseHarvestStatus>any(), Matchers.eq(true)); inOrder.verify(wTx).submit(); inOrder.verifyNoMoreInteractions(); } }
true
582d52d17896ac2738f3c07921b13ff0c4d94074
Java
lel352/JavaIniciante
/Aula - IDE Eclipse/src/training/cursojava/exercicios/aulas24/Livro.java
UTF-8
268
1.53125
2
[]
no_license
package training.cursojava.exercicios.aulas24; public class Livro { String titulo; String subTitulo; String[] autores; String editora; String formaPublicacao; String genero; String dataLancamento; String isbn; int edicao; int volume; int numeroPaginas; }
true
e3263a0a7f62aa586f9b9ac26b0fcf736352c97f
Java
YLBFDEV/sky-master
/app/src/main/java/com/skytech/moa/model/NewsCommentInfo.java
UTF-8
1,382
2.0625
2
[]
no_license
package com.skytech.moa.model; import java.io.Serializable; /** * Created by Administrator on 2015/6/2. */ public class NewsCommentInfo implements Serializable { //评论id private int _id; //用户id private int uid; //新闻id private int newsId; //用户头像 private String uidPic; //用户姓名 private String name; //用户评论 private String content; //评论时间 private String time; public int get_id() { return _id; } public void set_id(int _id) { this._id = _id; } public int getUid() { return uid; } public void setUid(int uid) { this.uid = uid; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getUidPic() { return uidPic; } public void setUidPic(String uidPic) { this.uidPic = uidPic; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getNewsId() { return newsId; } public void setNewsId(int newsId) { this.newsId = newsId; } }
true
88139f59c65f993c61153d9de9b2fbfb8e938d5d
Java
Dhandapani/gluster-ovirt
/backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/QuotaHelper.java
UTF-8
12,903
1.875
2
[ "Apache-2.0" ]
permissive
package org.ovirt.engine.core.bll; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.ovirt.engine.core.common.PermissionSubject; import org.ovirt.engine.core.common.VdcObjectType; import org.ovirt.engine.core.common.action.PermissionsOperationsParametes; import org.ovirt.engine.core.common.action.VdcActionType; import org.ovirt.engine.core.common.businessentities.ActionGroup; import org.ovirt.engine.core.common.businessentities.DiskImage; import org.ovirt.engine.core.common.businessentities.Quota; import org.ovirt.engine.core.common.businessentities.QuotaEnforcmentTypeEnum; import org.ovirt.engine.core.common.businessentities.QuotaStorage; import org.ovirt.engine.core.common.businessentities.QuotaVdsGroup; import org.ovirt.engine.core.common.businessentities.permissions; import org.ovirt.engine.core.common.businessentities.storage_pool; import org.ovirt.engine.core.common.config.Config; import org.ovirt.engine.core.common.config.ConfigValues; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.dal.VdcBllMessages; import org.ovirt.engine.core.dal.dbbroker.DbFacade; import org.ovirt.engine.core.dao.QuotaDAO; import org.ovirt.engine.core.dao.StorageDomainDAO; import org.ovirt.engine.core.dao.StoragePoolDAO; import org.ovirt.engine.core.dao.VdsGroupDAO; import org.ovirt.engine.core.utils.Pair; import org.ovirt.engine.core.utils.log.Log; import org.ovirt.engine.core.utils.log.LogFactory; public class QuotaHelper { public static final Long UNLIMITED = -1l; public static final Long EMPTY = 0l; private static final Log log = LogFactory.getLog(QuotaHelper.class); private QuotaHelper() { } private static final QuotaHelper quotaHelper = new QuotaHelper(); public static QuotaHelper getInstance() { return quotaHelper; } /** * Returns default quota id if the <code>Data Center</code> is disabled, <BR/> * or the quota id that was send. * @param quotaId * @param storagePoolId * @return */ public Guid getQuotaIdToConsume(Guid quotaId, storage_pool storagePool) { Guid returnedQuotaGuid = quotaId; if (storagePool == null) { log.errorFormat("Storage pool is null, Quota id will be set from the parameter"); } else if (storagePool.getQuotaEnforcementType() == QuotaEnforcmentTypeEnum.DISABLED) { // If storage pool has disabled quota enforcement, then initialize default quota. log.debugFormat("Storage pool quota is disabled, Quota id which will be consume from is the default DC quota"); returnedQuotaGuid = getQuotaDAO() .getDefaultQuotaByStoragePoolId(storagePool.getId()) .getId(); } return returnedQuotaGuid; } public void setDefaultQuotaAsRegularQuota(storage_pool storagePool) { Quota quota = getQuotaDAO().getDefaultQuotaByStoragePoolId(storagePool.getId()); if (quota != null) { quota.setIsDefaultQuota(false); getQuotaDAO().update(quota); } } public List<PermissionSubject> addQuotaPermissionSubject(List<PermissionSubject> quotaPermissionList, storage_pool storagePool, Guid quotaId) { if (storagePool != null && storagePool.getQuotaEnforcementType() != QuotaEnforcmentTypeEnum.DISABLED) { log.debug("Adding validation for consume quota to permission subjects list"); quotaPermissionList.add(new PermissionSubject(quotaId, VdcObjectType.Quota, ActionGroup.CONSUME_QUOTA)); } return quotaPermissionList; } /** * Returns unlimited Quota for storage pool. * * @param storagePool * - The storage pool to create the unlimited Quota for. * @return Boolean value if succeeded or not. */ public Quota getUnlimitedQuota(storage_pool storagePool, boolean isDefaultQuota) { if (storagePool == null || storagePool.getId() == null) { log.error("Unlimited Quota cannot be created, Storage pool is not valid "); return null; } // Set new Quota definition. Quota quota = new Quota(); Guid quotaId = Guid.NewGuid(); quota.setId(quotaId); quota.setStoragePoolId(storagePool.getId()); quota.setQuotaName(getDefaultQuotaName(storagePool)); quota.setDescription("Automatic generated Quota for Data Center " + storagePool.getname()); quota.setThresholdVdsGroupPercentage(Config.<Integer> GetValue(ConfigValues.QuotaThresholdVdsGroup)); quota.setThresholdStoragePercentage(Config.<Integer> GetValue(ConfigValues.QuotaThresholdStorage)); quota.setGraceVdsGroupPercentage(Config.<Integer> GetValue(ConfigValues.QuotaGraceVdsGroup)); quota.setGraceStoragePercentage(Config.<Integer> GetValue(ConfigValues.QuotaGraceStorage)); quota.setIsDefaultQuota(isDefaultQuota); quota.setQuotaVdsGroups(new ArrayList<QuotaVdsGroup>()); quota.setQuotaStorages(new ArrayList<QuotaStorage>()); // Set Quota storage capacity definition. quota.setStorageSizeGB(UNLIMITED); // Set Quota cluster virtual memory definition. quota.setMemSizeMB(UNLIMITED); // Set Quota cluster virtual CPU definition. quota.setVirtualCpu(UNLIMITED.intValue()); return quota; } public String getDefaultQuotaName(storage_pool storagePool) { List<Quota> quotaList = getQuotaDAO().getQuotaByStoragePoolGuid(storagePool.getId()); String quotaDefaultName = "Quota_Def_" + storagePool.getname(); String regexToolPattern = quotaDefaultName + "_[0-9]{1,}$"; int suffixQuotaName = 0; for (Quota quota : quotaList) { String quotaName = quota.getQuotaName(); if (quotaName.contains(quotaDefaultName) && (quotaName.length() == quotaDefaultName.length() && suffixQuotaName == 0)) { suffixQuotaName = 1; } else if (quotaName.matches(regexToolPattern)) { String defaultQuotaString = quotaName.substring(quotaName.lastIndexOf("_") + 1); Integer defaultQuotaNumber = new Integer(defaultQuotaString); if (suffixQuotaName <= defaultQuotaNumber.intValue()) { suffixQuotaName = defaultQuotaNumber.intValue() + 1; } } } return (suffixQuotaName > 0) ? String.format("%1$s_%2$s", quotaDefaultName, suffixQuotaName) : quotaDefaultName; } public boolean checkQuotaValidationForAddEdit(Quota quota, List<String> messages) { if (quota == null) { messages.add(VdcBllMessages.ACTION_TYPE_FAILED_QUOTA_IS_NOT_VALID.toString()); return false; } // Check if quota name exists. if (!checkQuotaNameExisting(quota, messages)) { return false; } // Check quota added is not default quota. if (quota.getIsDefaultQuota()) { messages.add(VdcBllMessages.ACTION_TYPE_FAILED_QUOTA_CAN_NOT_HAVE_DEFAULT_INDICATION.toString()); return false; } // If specific Quota for storage is specified if (!validateQuotaStorageLimitation(quota, messages)) { return false; } if (!validateQuotaVdsGroupLimitation(quota, messages)) { return false; } return true; } /** * Save new <code>Quota</code> with permissions for ad_element_id to consume from. * * @param quota * - The quota to be saved * @param ad_element_id * - The user which will have consume permissions on the quota. */ public void saveQuotaForUser(Quota quota, Guid ad_element_id) { DbFacade.getInstance().getQuotaDAO().save(quota); permissions perm = new permissions(ad_element_id, PredefinedRoles.QUOTA_CONSUMER.getId(), quota.getId(), VdcObjectType.Quota); PermissionsOperationsParametes permParams = new PermissionsOperationsParametes(perm); Backend.getInstance().runInternalAction(VdcActionType.AddPermission, permParams); } /** * Helper method which get as an input disk image list for VM or template and returns a list of quotas and their * desired limitation to be used.<BR/> * * @param diskImages * - The disk image list to be grouped by * @return List of summarized requested size for quota. */ public Map<Pair<Guid, Guid>, Double> getQuotaConsumeMap(Collection<DiskImage> diskImages) { Map<Pair<Guid, Guid>, Double> quotaForStorageConsumption = new HashMap<Pair<Guid, Guid>, Double>(); for (DiskImage disk : diskImages) { Pair<Guid, Guid> quotaForStorageKey = new Pair<Guid, Guid>(disk.getQuotaId(), disk.getstorage_ids().get(0).getValue()); Double storageRequest = quotaForStorageConsumption.get(quotaForStorageKey); if (storageRequest != null) { storageRequest += disk.getsize(); } else { storageRequest = new Double(disk.getsize()); } quotaForStorageConsumption.put(quotaForStorageKey, storageRequest); } return quotaForStorageConsumption; } public boolean checkQuotaNameExisting(Quota quota, List<String> messages) { Quota quotaByName = getQuotaDAO().getQuotaByQuotaName(quota.getQuotaName()); // Check if there is no quota with the same name that already exists. if ((quotaByName != null) && (!quotaByName.getId().equals(quota.getId()))) { messages.add(VdcBllMessages.ACTION_TYPE_FAILED_QUOTA_NAME_ALREADY_EXISTS.toString()); return false; } return true; } /** * Validate Quota storage restrictions. * * @param quota * @param messages * @return */ private static boolean validateQuotaStorageLimitation(Quota quota, List<String> messages) { boolean isValid = true; List<QuotaStorage> quotaStorageList = quota.getQuotaStorages(); if (quotaStorageList != null && !quotaStorageList.isEmpty() && isGlobalLimitExist(quota.getStorageSizeGB())) { messages.add(VdcBllMessages.ACTION_TYPE_FAILED_QUOTA_LIMIT_IS_SPECIFIC_AND_GENERAL.toString()); isValid = false; } return isValid; } /** * Validate Quota vds group restrictions. * * @param quota * - Quota we validate * @param messages * - Messages of can do action. * @return Boolean value if the quota is valid or not. */ private static boolean validateQuotaVdsGroupLimitation(Quota quota, List<String> messages) { boolean isValid = true; List<QuotaVdsGroup> quotaVdsGroupList = quota.getQuotaVdsGroups(); if (quotaVdsGroupList != null && !quotaVdsGroupList.isEmpty()) { boolean isSpecificVirtualCpu = false; boolean isSpecificVirtualRam = false; for (QuotaVdsGroup quotaVdsGroup : quotaVdsGroupList) { if (quotaVdsGroup.getVirtualCpu() != null) { isSpecificVirtualCpu = true; } if (quotaVdsGroup.getMemSizeMB() != null) { isSpecificVirtualRam = true; } } // if the global vds group limit was not specified, then specific limitation must be specified. if ((isGlobalLimitExist(quota.getMemSizeMB()) && isSpecificVirtualRam) || (isGlobalLimitExist(quota.getVirtualCpu()) && isSpecificVirtualCpu)) { messages.add(VdcBllMessages.ACTION_TYPE_FAILED_QUOTA_LIMIT_IS_SPECIFIC_AND_GENERAL.toString()); isValid = false; } } return isValid; } private static boolean isGlobalLimitExist(Object globalStorageLimit) { return globalStorageLimit != null; } /** * @return The VdsGroupDAO */ protected VdsGroupDAO getVdsGroupDao() { return DbFacade.getInstance().getVdsGroupDAO(); } /** * @return The StorageDomainDAO */ protected StorageDomainDAO getStorageDomainDao() { return DbFacade.getInstance().getStorageDomainDAO(); } /** * @return The quotaDAO */ protected QuotaDAO getQuotaDAO() { return DbFacade.getInstance().getQuotaDAO(); } /** * @return The StoragePoolDAO */ protected StoragePoolDAO getStoragePoolDao() { return DbFacade.getInstance().getStoragePoolDAO(); } }
true
1a4b79ea1e79498b7dd18bed9e3b2077283b485f
Java
dasmoth/robin
/src/robin/Window.java
UTF-8
248
2.609375
3
[]
no_license
package robin; public class Window { public String chr; public int min; public int max; public int index; public Window(String chr, int min, int max, int index) { this.chr = chr; this.min = min; this.max = max; this.index = index; } }
true
85f9cf426452c823d173d23866b4340906f4aa10
Java
YanHuiLi/AndroidProj
/TheNews/app/src/main/java/site/yanhui/thenews/SplashActivity.java
UTF-8
4,034
2.40625
2
[]
no_license
package site.yanhui.thenews; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.AnimationSet; import android.view.animation.RotateAnimation; import android.view.animation.ScaleAnimation; import android.widget.ImageView; import android.widget.LinearLayout; import butterknife.BindView; import butterknife.ButterKnife; import site.yanhui.thenews.activity.GuideActivity; import site.yanhui.thenews.activity.MainActivity; import site.yanhui.thenews.others.ConstantValues; import site.yanhui.thenews.utils.SpUtils; /** * create at 2017/9/24 by 17:10 * 作者:Archer * 功能描述: * 闪屏界面的开发,放了三个动画进入到了动画集合。 */ public class SplashActivity extends AppCompatActivity { /* splash的背景图片小马 */ @BindView(R.id.image_view) ImageView imageView; /* 跟布局的id */ @BindView(R.id.SplashRoot) LinearLayout SplashRoot; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); ButterKnife.bind(this); // 旋转动画 RotateAnimation animRotate = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); animRotate.setDuration(1000);// 动画时间 animRotate.setFillAfter(true);// 保持动画结束状态 // 缩放动画 ScaleAnimation animScale = new ScaleAnimation(0, 1, 0, 1, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); animScale.setDuration(1000); animScale.setFillAfter(true);// 保持动画结束状态 // 渐变动画 AlphaAnimation animAlpha = new AlphaAnimation(0, 1); animAlpha.setDuration(2000);// 动画时间 animAlpha.setFillAfter(true);// 保持动画结束状态 //用动画集合运行全部动画 AnimationSet set = new AnimationSet(true); set.addAnimation(animRotate); set.addAnimation(animScale); set.addAnimation(animAlpha); /* 跟布局进入动画的东晓 */ SplashRoot.startAnimation(set); //为动画设置监听事件 set.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { //动画结束,跳转页面. //如果是第一次进入那么就跳转到新手引导界面 //否则就是直接使用 //先从我们的config配置文件中取出对应的sp值,默认是true,如果是false,说明已经登陆过,就不需要在 //进入导航页面了 boolean firstCome = SpUtils.getBoolean(SplashActivity.this, ConstantValues.FIRST_COME, true); Intent intent; if (firstCome) {//如果为真,表示第一次进入 intent = new Intent(getApplicationContext(), GuideActivity.class); //跳转到导航页面以后,把值设置为false 下次就进入了主页面 // SpUtils.putBoolean(getApplicationContext(),ConstantValues.FIRST_COME,false); } else {//为假 intent = new Intent(getApplicationContext(), MainActivity.class); } finish();//结束掉闪屏界面 startActivity(intent); } @Override public void onAnimationRepeat(Animation animation) { } }); } }
true
d7f00b035262fe6513f14b8e6099a8db84474fcb
Java
diego-x/JavaWeb
/src/main/java/diego/server/ShowResult.java
UTF-8
1,902
2.140625
2
[]
no_license
package diego.server; import com.alibaba.fastjson.JSONObject; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.FileInputStream; import java.io.IOException; import java.io.PrintWriter; @WebServlet("/ShowResult") public class ShowResult extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //super.doGet(request, response); request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); PrintWriter writer = response.getWriter(); HttpSession session; try { session = request.getSession(); }catch (Exception e){ response.sendRedirect("/login.jsp"); return; } if(session.getAttribute("isLogin") == null || (boolean)session.getAttribute("isLogin") != true){ response.sendRedirect("/login.jsp"); }else{ JSONObject[] jsonObjects = (JSONObject[]) session.getAttribute("JSONObjectArray"); if( jsonObjects!= null){ writer.println("<title>解析结果</title>"); writer.println(CatchFromWangKeBang.getParseResult(jsonObjects,300)); writer.println("<buttun type=\"button\" onclick=\"location.href='/JsonFileToDb'\">导入数据库</buttun>"); writer.flush(); }else{ writer.println("<script>alert('没有爬取结果!!')</script>"); writer.println("<script>location.href='/wkbCatch';</script>"); writer.flush(); } } } }
true
579a09f8e18abed2c1a15ed80916140a25cc6fa8
Java
jielu/Constellation
/Hadoop/src/edu/gatech/cs6422/BasicBlock.java
UTF-8
1,244
3.234375
3
[]
no_license
package edu.gatech.cs6422; import org.apache.bcel.generic.InstructionHandle; /** * BasicBlock.java * * Represents a BasicBlock by maintaining references * to the start and end InstructionHandles * * Created: Thu Jan 23 18:33:59 2003 * * @author <a href="mailto:anil@cc.gatech.edu">Anil Chawla</a> */ public class BasicBlock { private InstructionHandle startHandle; private InstructionHandle endHandle; /** * Creates a new <code>BasicBlock</code> instance. * * @param startHandle an <code>InstructionHandle</code> value * @param endHandle an <code>InstructionHandle</code> value */ public BasicBlock( InstructionHandle startHandle, InstructionHandle endHandle) { this.startHandle = startHandle; this.endHandle = endHandle; } /** * Returns the InstructionHandle referring to the * start of the basic block. * * @return an <code>InstructionHandle</code> value */ public InstructionHandle getStartHandle() { return startHandle; } /** * Returns the InstructionHandle referring to the * end of the basic block. * * @return an <code>InstructionHandle</code> value */ public InstructionHandle getEndHandle() { return endHandle; } } // BasicBlock
true
7442e9d83863654a1f6a6d4d712ac9703037dbb0
Java
chaserocks/Java-SE
/JAVASEWS/src/com/qspiders/pack1/LinkedList.java
UTF-8
245
1.984375
2
[]
no_license
package com.qspiders.pack1; import java.util.LinkedList; public class LinkedListDemo { public static void main(String[] args) { LinkedList lst=new LinkedList<>(); lst.add(100); lst.add("Hello"); lst.add(true); lst.addFirst(e) } }
true
cd66316685bd4c7e98f6777f6105aee8ccf12d32
Java
cha63506/temp
/api_maven/com.absolute.am.dal/src/main/java/com/absolute/am/dal/IApplicationsHandler.java
UTF-8
1,051
1.90625
2
[]
no_license
/** * Copyright (c) 2015 Absolute Software Corporation, All rights reserved. * Reproduction or transmission in whole or in part, in any form or by any means, * electronic, mechanical or otherwise, is prohibited without the prior written * consent of the copyright owner. */ package com.absolute.am.dal; import java.util.List; import java.util.UUID; import com.absolute.am.dal.model.iOSAppStoreApplications; import com.absolute.am.dal.model.iOSApplications; /** * @author klavin * */ public interface IApplicationsHandler { public enum iconType { thirdPartyApp, book } public iOSApplications getInHouseApplication(long applicationId) throws Exception; public iOSAppStoreApplications getThirdPartyApplication(long applicationId) throws Exception; public byte[] getIcon(long id, iconType type) throws Exception; public UUID[] getInHouseAppUniqueIds(List<Long> inHouseAppIds) throws Exception; public UUID[] getThirdPartyAppUniqueIds(List<Long> thirdPartyAppIds) throws Exception; }
true
9fd44d9e6c34991b3340e0d25d00f0aea4d34da4
Java
ManelBrull/ExpensesManager-rest
/em-persistence/src/main/java/com/mbrull/persistence/repository/BaseRepository.java
UTF-8
667
1.953125
2
[ "MIT" ]
permissive
package com.mbrull.persistence.repository; import java.io.Serializable; import java.util.Optional; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.repository.NoRepositoryBean; import org.springframework.data.repository.Repository; @NoRepositoryBean interface BaseRepository<T, ID extends Serializable> extends Repository<T, ID>, JpaSpecificationExecutor<T> { void delete(T deleted); Page<T> findAll(Pageable pageRequest); Optional<T> findOne(ID id); T save(T persisted); long count(); }
true
46741b395625030651220edfccd4d9a8c7883af9
Java
18226200349/mmalltest
/src/main/java/com/mmall/controller/backend/ProdouctManageController.java
UTF-8
4,876
2.359375
2
[]
no_license
package com.mmall.controller.backend; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.mmall.common.Const; import com.mmall.common.ResponseCode; import com.mmall.common.ServerResponse; import com.mmall.pojo.Product; import com.mmall.pojo.User; import com.mmall.service.IProductService; import com.mmall.service.IUserService; import org.springframework.web.multipart.MultipartFile; @Controller @RequestMapping("/manage/product") public class ProdouctManageController { @Autowired private IUserService iUserService; @Autowired private IProductService iProductService; /** * * @Title: 新增或更新接口 @Description: 新增或更新接口 @param @param session @param @param * product @param @return @return ServerResponse @throws */ @RequestMapping(value = "save.do") @ResponseBody public ServerResponse productSave(HttpSession session, Product product) { User user = (User) session.getAttribute(Const.CURRENT_USER); if (user == null) { return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), "用户未登录,请登录管理员"); } if (iUserService.checkAdminRole(user).isSuccess()) { // 添加增加商品的业务逻辑 return iProductService.saveOrUpdateProduct(product); } else { return ServerResponse.createByErrorMessage("无权限操作"); } } /** * * @Title: 改变商品状态 @Description: TODO @param @param session @param @param * productId @param @param status @param @return @return * ServerResponse @throws */ @RequestMapping(value = "get_sale_status.do") @ResponseBody public ServerResponse setSaleStatus(HttpSession session, Integer productId, Integer status) { User user = (User) session.getAttribute(Const.CURRENT_USER); if (user == null) { return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), "用户未登录,请登录管理员"); } if (iUserService.checkAdminRole(user).isSuccess()) { // 获取商品的状态信息 return iProductService.setSaleStatus(productId, status); } else { return ServerResponse.createByErrorMessage("无权限操作"); } } /** * * @Title: 改变商品状态 @Description: TODO @param @param session @param @param * productId @param @param status @param @return @return * ServerResponse @throws */ @RequestMapping(value = "detail.do") @ResponseBody public ServerResponse getDetail(HttpSession session, Integer productId) { User user = (User) session.getAttribute(Const.CURRENT_USER); if (user == null) { return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), "用户未登录,请登录管理员"); } if (iUserService.checkAdminRole(user).isSuccess()) { // 填充业务 return iProductService.manageProductDetail(productId); } else { return ServerResponse.createByErrorMessage("无权限操作"); } } @RequestMapping(value = "list.do") @ResponseBody public ServerResponse getList(HttpSession session, @RequestParam(value = "pageNum", defaultValue = "1") int pageNum, @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) { User user = (User) session.getAttribute(Const.CURRENT_USER); if (user == null) { return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), "用户未登录,请登录管理员"); } if (iUserService.checkAdminRole(user).isSuccess()) { // 填充动态分页 return iProductService.getProductList(pageNum, pageSize); } else { return ServerResponse.createByErrorMessage("无权限操作"); } } @RequestMapping(value = "search.do") @ResponseBody public ServerResponse productSearch(HttpSession session,String productName,Integer productId, @RequestParam(value = "pageNum", defaultValue = "1") int pageNum, @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) { User user = (User) session.getAttribute(Const.CURRENT_USER); if (user == null) { return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), "用户未登录,请登录管理员"); } if (iUserService.checkAdminRole(user).isSuccess()) { // 填充动态分页 return iProductService.searchProduct(productName,productId,pageNum,pageSize); } else { return ServerResponse.createByErrorMessage("无权限操作"); } } public ServerResponse upload(MultipartFile file, HttpServletRequest request){ String path=request.getSession().getServletContext().getRealPath("upload"); return null; } }
true
8a4bb36cbc6f32f1c093874f46ca994580a9e418
Java
shufanshijie/usercenter
/src/main/test/com/shufan/usercenter/test/TestUCDao.java
UTF-8
3,581
2.109375
2
[]
no_license
package com.shufan.usercenter.test; import haiyan.common.config.PathUtil; import haiyan.common.intf.database.IDBBill; import haiyan.common.intf.database.orm.IDBRecord; import haiyan.common.intf.database.orm.IDBResultSet; import haiyan.orm.database.DBRecord; import java.io.File; import java.util.Properties; import com.shufan.usercenter.common.ContextListener; import com.shufan.usercenter.dao.UCDao; import com.shufan.usercenter.dao.impl.UCDaoImpl; public class TestUCDao { /** * @param args * @throws Throwable */ public static void main(String[] args) throws Throwable { String s = System.getProperty("user.dir"); Properties p = PathUtil.getEnvVars(); p.setProperty("HAIYAN_HOME", s+File.separator+"WebContent"); ContextListener.init(s+File.separator+"WebContent"+File.separator+"WEB-INF"); ContextListener.USE_ES=true; testBill(); System.exit(0); } private static void testUser() { UCDao dao = new UCDaoImpl(null); IDBRecord userRecord = new DBRecord(); userRecord.set("WXID", "123"); userRecord.set("NAME", "呵呵"); userRecord.set("MOBILE", "243125415"); userRecord = dao.addUser(userRecord); System.out.println(userRecord.get("ID")+" name: "+userRecord.get("NAME")); userRecord.set("NAME", "嘿嘿"); userRecord = dao.updateUser(userRecord); System.out.println(userRecord.get("ID")+" name: "+userRecord.get("NAME")); userRecord = dao.selectUserByWXId("123"); System.out.println(userRecord.get("ID")+" name: "+userRecord.get("NAME")); userRecord = dao.selectUserById("aaaaab"); System.out.println(userRecord.get("ID")+" name: "+userRecord.get("NAME")); } private static void testAddr() { UCDao dao = new UCDaoImpl(null); IDBRecord addrRecord = new DBRecord(); addrRecord.set("USERWXID", "123"); addrRecord.set("NAME", "呵呵"); addrRecord.set("MOBILE", "123456"); addrRecord.set("USERID", "aaaaab"); addrRecord.set("PROVINCE", "上海"); addrRecord.set("CITY", "上海"); addrRecord.set("COUNTY", "普陀区"); addrRecord.set("ADDRESS", "中江路天洁大厦6楼"); addrRecord = dao.addAddr(addrRecord); System.out.println(addrRecord.get("ID")+" MOBILE : "+addrRecord.get("MOBILE")); addrRecord.set("MOBILE", "654321"); addrRecord = dao.updateAddr(addrRecord); System.out.println(addrRecord.get("ID")+" MOBILE: "+addrRecord.get("MOBILE")); IDBResultSet result = dao.selectAddrByWXId("123",20,1); if(result.getRecordCount()>0){ System.out.println("数量: " + result.getRecordCount() + " ID: " + result.getRecord(0).get("ID")); }else{ System.out.println("没有找到地址信息"); } } private static void testBill() { UCDao dao = new UCDaoImpl(null); IDBBill bill = dao.selectUserBillById("aaaaab"); System.out.println("BILLID : "+bill.getBillID()); IDBResultSet userSet = bill.getResultSet(0); IDBResultSet addrSet = bill.getResultSet(1); IDBResultSet pointsSet = bill.getResultSet(2); if(userSet.getRecordCount()>0){ System.out.println("数量: " + userSet.getRecordCount() + " USERNAME: " + userSet.getRecord(0).get("NAME")); }else{ System.out.println("没有找到用户信息"); } if(addrSet.getRecordCount()>0){ System.out.println("数量: " + addrSet.getRecordCount() + " NAME: " + addrSet.getRecord(0).get("NAME")); }else{ System.out.println("没有找到地址信息"); } if(pointsSet.getRecordCount()>0){ System.out.println("数量: " + pointsSet.getRecordCount() + " POINTS: " + pointsSet.getRecord(0).get("POINTS")); }else{ System.out.println("没有找到积分信息"); } } }
true
201611476b358f5c4390db93b9470adf019a784a
Java
dabnich/bikeShop
/bikeShop/src/BikeTypes.java
UTF-8
74
1.617188
2
[]
no_license
public enum BikeTypes { XC, Full, Touring, Racing, Track, Stunt, }
true
6d49242bb6bdd940b402d152be5df2f334f52c21
Java
DeanHe/Practice
/LeetCodePractice/src/contest/FindTheWinnerOfTheCircularGame.java
UTF-8
2,180
4.40625
4
[]
no_license
package contest; import java.util.LinkedList; import java.util.Queue; /* There are n friends that are playing a game. The friends are sitting in a circle and are numbered from 1 to n in clockwise order. More formally, moving clockwise from the ith friend brings you to the (i+1)th friend for 1 <= i < n, and moving clockwise from the nth friend brings you to the 1st friend. The rules of the game are as follows: Start at the 1st friend. Count the next k friends in the clockwise direction including the friend you started at. The counting wraps around the circle and may count some friends more than once. The last friend you counted leaves the circle and loses the game. If there is still more than one friend in the circle, go back to step 2 starting from the friend immediately clockwise of the friend who just lost and repeat. Else, the last friend in the circle wins the game. Given the number of friends, n, and an integer k, return the winner of the game. Example 1: Input: n = 5, k = 2 Output: 3 Explanation: Here are the steps of the game: 1) Start at friend 1. 2) Count 2 friends clockwise, which are friends 1 and 2. 3) Friend 2 leaves the circle. Next start is friend 3. 4) Count 2 friends clockwise, which are friends 3 and 4. 5) Friend 4 leaves the circle. Next start is friend 5. 6) Count 2 friends clockwise, which are friends 5 and 1. 7) Friend 1 leaves the circle. Next start is friend 3. 8) Count 2 friends clockwise, which are friends 3 and 5. 9) Friend 5 leaves the circle. Only friend 3 is left, so they are the winner. Example 2: Input: n = 6, k = 5 Output: 1 Explanation: The friends leave in this order: 5, 4, 6, 2, 3. The winner is friend 1. Constraints: 1 <= k <= n <= 500 analysis: simulation queue */ public class FindTheWinnerOfTheCircularGame { public int findTheWinner(int n, int k) { Queue<Integer> q = new LinkedList<>(); for(int i = 1; i <= n; i++){ q.offer(i); } while(q.size() > 1){ int cnt = k - 1; while (cnt > 0){ q.offer(q.poll()); cnt--; } q.poll(); } return q.poll(); } }
true
1d76e247e9b758b2e5f9cf94cd96ad0c0bfa7cd3
Java
RaquelFernandes/ProfissionalSearch
/app/src/main/java/br/iesb/profissionalsearch/Adapter/AreaAtuacaoViewHolder.java
UTF-8
841
2.015625
2
[]
no_license
package br.iesb.profissionalsearch.Adapter; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.TextView; import br.iesb.profissionalsearch.R; /** * Created by 1514290042 on 02/06/2017. */ public class AreaAtuacaoViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { public TextView id; public TextView nome; public AreaAtuacaoViewHolder(View itemView) { super(itemView); this.nome = (TextView) itemView.findViewById(R.id.areaAtuacao_lista_txtNome); this.id = (TextView) itemView.findViewById(R.id.areaAtuacao_lista_txtId); RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) itemView.getLayoutParams(); itemView.setLayoutParams(params); } @Override public void onClick(View v) { } }
true
6991edb927de9368e62b2691b05c57161de9aee6
Java
contento3/Projects
/core/src/main/java/com/contento3/dam/content/library/dao/impl/ContentStorageLibraryMappingDaoHibernateImpl.java
UTF-8
2,520
2.234375
2
[]
no_license
package com.contento3.dam.content.library.dao.impl; import java.util.List; import org.apache.commons.lang.Validate; import org.hibernate.Criteria; import org.hibernate.criterion.Restrictions; import org.springframework.util.CollectionUtils; import com.contento3.common.spring.dao.GenericDaoSpringHibernateTemplate; import com.contento3.dam.content.library.dao.ContentStorageLibraryMappingDao; import com.contento3.dam.content.library.model.ContentStorageLibraryMapping; public class ContentStorageLibraryMappingDaoHibernateImpl extends GenericDaoSpringHibernateTemplate<ContentStorageLibraryMapping, Integer> implements ContentStorageLibraryMappingDao { public ContentStorageLibraryMappingDaoHibernateImpl() { super(ContentStorageLibraryMapping.class); } @Override public ContentStorageLibraryMapping findByLibraryAndContentType( final String libraryName, final String contentType, final Integer accountId) { Validate.notNull(libraryName ,"libraryName cannot be null"); Validate.notNull(accountId ,"accountId cannot be null"); Validate.notNull(contentType ,"contentType cannot be null"); final Criteria criteria = this.getSession() .createCriteria(ContentStorageLibraryMapping.class) .add(Restrictions.eq("contentType", contentType)); criteria.createAlias("library.account","account") .add(Restrictions .eq("account.accountId", accountId)); criteria.createAlias("library","library") .add(Restrictions .eq("library.name", libraryName)); ContentStorageLibraryMapping mapping = null; final List <ContentStorageLibraryMapping> mappingList = criteria.list(); if (!CollectionUtils.isEmpty(mappingList)){ mapping = mappingList.get(0); } return mapping; } @Override public ContentStorageLibraryMapping findByLibraryId( final Integer libraryId, final Integer accountId) { Validate.notNull(libraryId ,"libraryId cannot be null"); Validate.notNull(accountId ,"accountId cannot be null"); final Criteria criteria = this.getSession() .createCriteria(ContentStorageLibraryMapping.class); criteria.createAlias("library.account","account") .add(Restrictions .eq("account.accountId", accountId)); criteria.createAlias("library","library") .add(Restrictions .eq("library.id", libraryId)); ContentStorageLibraryMapping mapping = null; final List <ContentStorageLibraryMapping> mappingList = criteria.list(); if (!CollectionUtils.isEmpty(mappingList)){ mapping = mappingList.get(0); } return mapping; } }
true
2acf1546e65d0c046e56374ba304f38d471c8b05
Java
calvear93/legobot
/src/NXTClaw.java
UTF-8
892
2.765625
3
[]
no_license
import java.io.IOException; import lejos.nxt.Motor; import lejos.nxt.NXTRegulatedMotor; class NXTClaw { private NXTRegulatedMotor arm, claw; private NXTCaterpillar c; private NXTLineSensor l; NXTClaw( NXTCaterpillar x, NXTLineSensor j ) { l = j; c = x; setServos( 120 ); } void capture( ) throws InterruptedException, IOException { down(); if ( l.noLine() ) c.advance(); Thread.sleep( 600 ); hold(); up(); release(); Thread.sleep( 200 ); } void drop( ) throws InterruptedException { down(); release(); up(); Thread.sleep( 200 ); } private void hold( ) { claw.rotateTo( -90 ); } private void release( ) { claw.rotateTo( 0 ); } private void up( ) { arm.rotateTo( 0 ); } private void down( ) { arm.rotateTo( 180 ); } private void setServos( int speed ) { arm = Motor.A; arm.setSpeed( speed ); claw = Motor.B; claw.setSpeed( speed ); } }
true
fa1ab88a911adbc9eda9bbac99849f9e1e5ecdbf
Java
yhlee002/Java_TheJoen
/14exception/src/exception02/ExceptionEx01.java
UTF-8
844
3.671875
4
[]
no_license
package exception02; import java.io.*; public class ExceptionEx01 { public static void main(String[] args) { /* 컴파일 체크를 하는 예외 (IO예외) : Checked Exception * cf. RuntimeException을 상속받은 Exception의 경우 unchecked Exception으로 예외 처리가 강제되지 않음 */ try { System.out.println("예외 발생 코드 위"); FileInputStream fis = new FileInputStream("test.txt"); System.out.println("예외 발생 코드 아래"); //예외 발생시 아래의 코드는 실행 X(try문이 종료되고 catch문이 실행됨) } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("파일을 못찾았을 때 실행됨."); } catch(ArithmeticException e) { System.out.println("test"); } System.out.println("끝"); } }
true
4cdbfe37c44ea25a4ecea8f48117610cb66f96a3
Java
rgonthina1/newplatform
/ext/workflow/testsrc/de/hybris/platform/workflow/interceptors/WorkflowItemAttachmentDefaultCodeInterceptorTest.java
UTF-8
1,770
1.75
2
[]
no_license
/* * [y] hybris Platform * * Copyright (c) 2000-2013 hybris AG * All rights reserved. * * This software is the confidential and proprietary information of hybris * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with hybris. * * */ package de.hybris.platform.workflow.interceptors; import static org.fest.assertions.Assertions.assertThat; import de.hybris.bootstrap.annotations.IntegrationTest; import de.hybris.platform.servicelayer.ServicelayerTest; import de.hybris.platform.servicelayer.model.ModelService; import de.hybris.platform.workflow.WorkflowService; import de.hybris.platform.workflow.model.WorkflowItemAttachmentModel; import de.hybris.platform.workflow.model.WorkflowModel; import javax.annotation.Resource; import org.junit.Before; import org.junit.Test; @IntegrationTest public class WorkflowItemAttachmentDefaultCodeInterceptorTest extends ServicelayerTest { @Resource ModelService modelService; @Resource WorkflowService newestWorkflowService; @Before public void setUp() throws Exception { //given createCoreData(); createDefaultCatalog(); importCsv("/workflow/testdata/workflow_test_data.csv", "windows-1252"); } @Test public void testIfCodeIsNotNull() { final WorkflowItemAttachmentModel itemAttachment = modelService.create(WorkflowItemAttachmentModel.class); final WorkflowModel workflow = newestWorkflowService.getWorkflowForCode("workflow1"); itemAttachment.setWorkflow(workflow); itemAttachment.setItem(workflow); modelService.save(itemAttachment); assertThat(itemAttachment.getCode()).isNotNull(); assertThat(itemAttachment.getCode()).hasSize(6); } }
true
e9fc831a969e2218712b74db4fc6b8b2c39e2ca8
Java
preet0202/Farm-to-Flat
/app/src/main/java/com/example/farmtoflat/GridProductAdapter.java
UTF-8
2,625
2.15625
2
[]
no_license
package com.example.farmtoflat; import android.graphics.Color; 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 com.bumptech.glide.Glide; import com.bumptech.glide.request.RequestOptions; import java.util.List; public class GridProductAdapter extends BaseAdapter { List<HorizontalProductScrollModel_today> mHorizontalProductScrollModel_todayList; public GridProductAdapter(List<HorizontalProductScrollModel_today> horizontalProductScrollModel_todayList) { mHorizontalProductScrollModel_todayList = horizontalProductScrollModel_todayList; } @Override public int getCount() { return mHorizontalProductScrollModel_todayList.size(); } @Override public Object getItem(int i) { return null; } @Override public long getItemId(int i) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { View itemView; ImageView productImage; TextView productTitle; TextView productWeight; TextView productPrice; if(convertView == null){ itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.horizontal_scroll_item_layout1,null); itemView.setElevation(0); itemView.setBackgroundColor(Color.parseColor("#64C34A")); productImage = itemView.findViewById(R.id.horizontal_scroll_layout1_product_image); productTitle = itemView.findViewById(R.id.horizontal_scroll_layout1_product_title); productWeight = itemView.findViewById(R.id.horizontal_scroll_layout1_product_weight); productPrice = itemView.findViewById(R.id.horizontal_scroll_layout1_product_price); //productImage.setImageResource(mHorizontalProductScrollModel_todayList.get(position).getProductImage()); Glide.with(itemView.getContext()).load(mHorizontalProductScrollModel_todayList.get(position).getProductImage()).apply(new RequestOptions().placeholder(R.mipmap.baseline_home_black_18dp)).into(productImage); productTitle.setText(mHorizontalProductScrollModel_todayList.get(position).getProductTitle()); productWeight.setText(mHorizontalProductScrollModel_todayList.get(position).getProductWeight()); productPrice.setText(mHorizontalProductScrollModel_todayList.get(position).getProductPrice()); }else{ itemView = convertView; } return itemView; } }
true
4f4de4e31c74f843ef2663fdcc8142f349df977e
Java
dennisvoliver/minecraft
/net/minecraft/network/packet/c2s/login/LoginKeyC2SPacket.java
UTF-8
1,890
2.390625
2
[]
no_license
package net.minecraft.network.packet.c2s.login; import java.io.IOException; import java.security.PrivateKey; import java.security.PublicKey; import javax.crypto.SecretKey; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.network.NetworkEncryptionUtils; import net.minecraft.network.Packet; import net.minecraft.network.PacketByteBuf; import net.minecraft.network.encryption.NetworkEncryptionException; import net.minecraft.network.listener.ServerLoginPacketListener; public class LoginKeyC2SPacket implements Packet<ServerLoginPacketListener> { private byte[] encryptedSecretKey = new byte[0]; private byte[] encryptedNonce = new byte[0]; public LoginKeyC2SPacket() { } @Environment(EnvType.CLIENT) public LoginKeyC2SPacket(SecretKey secretKey, PublicKey publicKey, byte[] nonce) throws NetworkEncryptionException { this.encryptedSecretKey = NetworkEncryptionUtils.encrypt(publicKey, secretKey.getEncoded()); this.encryptedNonce = NetworkEncryptionUtils.encrypt(publicKey, nonce); } public void read(PacketByteBuf buf) throws IOException { this.encryptedSecretKey = buf.readByteArray(); this.encryptedNonce = buf.readByteArray(); } public void write(PacketByteBuf buf) throws IOException { buf.writeByteArray(this.encryptedSecretKey); buf.writeByteArray(this.encryptedNonce); } public void apply(ServerLoginPacketListener serverLoginPacketListener) { serverLoginPacketListener.onKey(this); } public SecretKey decryptSecretKey(PrivateKey privateKey) throws NetworkEncryptionException { return NetworkEncryptionUtils.decryptSecretKey(privateKey, this.encryptedSecretKey); } public byte[] decryptNonce(PrivateKey privateKey) throws NetworkEncryptionException { return NetworkEncryptionUtils.decrypt(privateKey, this.encryptedNonce); } }
true
667df927fae51aa420998562a7bd2c2b0f6c9db7
Java
Shovkatbva/hr
/src/main/java/az/nakhInternet/hr/service/LoginService.java
UTF-8
180
1.992188
2
[]
no_license
package az.nakhInternet.hr.service; import az.nakhInternet.hr.model.Login; public interface LoginService { Login login(String username, String password) throws Exception; }
true
dd5d5ed5dc1af534065a6d8d145681fa1c6c1a13
Java
erik-schmidt/prog2-pizzashop-project
/src/PizzaShop/Model/Topping.java
UTF-8
761
3.484375
3
[]
no_license
package PizzaShop.Model; /** * Object represents toppings for the pizzas. * Toppings are defined with: * price (in cent) and name. */ public enum Topping { TOMATO(200, "Tomate"), CHILI(300, "Chili"), CHEESE(200, "Käse"), MUSHROOMS(300, "Pilze"), SALAMI(200, "Salami"); private int price; private String name; /** * Creates Topping for pizza with price and name. * @param price * @param name */ Topping(int price, String name) { this.price = price; this.name = name; } /** * @return price of the topping */ public int getPrice() { return price; } /** * @return name of the topping */ public String getName() { return name; } }
true
6ebd6a9a2787446643bfcc04e4d2ea4ae178d244
Java
guptavikash46/Applicant-backend
/src/main/java/Hahn/ApplicationProcess/Aplication/Aufgabe/services/DeleteApplicantService.java
UTF-8
157
1.695313
2
[]
no_license
package Hahn.ApplicationProcess.Aplication.Aufgabe.services; public interface DeleteApplicantService { boolean deleteApplicantById(Integer Id); }
true
ff4c837a0fa6e9499ee21e5b36645042ac15be21
Java
Sublimestyle91/Java_code
/Fibonacchi.java
UTF-8
613
3.234375
3
[]
no_license
package Fibonacchi; public class Fibonacchi { public static void main(String[] args) { // TODO Auto-generated method stub System.out.println(Fibo(5)); System.out.println(Fibo(4)); System.out.println(Fibo(0)); System.out.println(Fibo(1)); System.out.println(Fibo(11)); } public static int Fibo(int index) { int f0 = 0; int f1 = 1; int result = 0; if(index > 2) { index -=1; for(int i = 0; i < index; i++) { result = f0 + f1; f0 = f1; f1 = result; } } else if(index == 1) { result = 1; } return result; } }
true
73b87e08307f7c697d5d2aaaf631a355d9f9f517
Java
tahatopiwala/aws-sdk-java
/aws-java-sdk-servicecatalog/src/main/java/com/amazonaws/services/servicecatalog/package-info.java
UTF-8
1,550
1.828125
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights * Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ /** * <fullname>AWS Service Catalog</fullname> <p> <b>Overview</b> </p> <p> <a href="https://aws.amazon.com/servicecatalog/">AWS Service Catalog</a> allows organizations to create and manage catalogs of IT services that are approved for use on AWS. This documentation provides reference material for the AWS Service Catalog end user API. To get the most out of this documentation, you need to be familiar with the terminology discussed in <a href="http://docs.aws.amazon.com/servicecatalog/latest/userguide/what-is_concepts.html">AWS Service Catalog Concepts</a>.</p> <p> <i>Additional Resources</i> </p> <ul> <li> <p> <a href="http://docs.aws.amazon.com/servicecatalog/latest/adminguide/introduction.html">AWS Service Catalog Administrator Guide</a> </p> </li> <li> <p> <a href="http://docs.aws.amazon.com/servicecatalog/latest/userguide/introduction.html">AWS Service Catalog User Guide</a> </p> </li> </ul> */ package com.amazonaws.services.servicecatalog;
true
dc84e51ed9619a6e6bdaed47b85e8fdacbb0fb33
Java
jmpsc/-Demo-Instagram-FreeDrawing-
/TPDemo/app/src/main/java/com/jc/tpdemo/widgets/IBitmapExporter.java
UTF-8
176
1.71875
2
[]
no_license
package com.jc.tpdemo.widgets; import android.graphics.Bitmap; /** * Created by Jorge on 12-04-2015. */ public interface IBitmapExporter { public Bitmap getBitmap(); }
true
a386112ac6683430a7c21aa56624530372298a4a
Java
motoyuki1979/rumbo-api
/Rumbo/src/main/java/mappers/GetNotificationsMapper.java
UTF-8
775
2.328125
2
[]
no_license
package mappers; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.jdbc.core.RowMapper; import models.GetComments; import models.GetNotifications; public class GetNotificationsMapper implements RowMapper<GetNotifications> { @Override public GetNotifications mapRow(ResultSet rs, int rowNum) throws SQLException { GetNotifications comments = new GetNotifications(); comments.setId(rs.getString("id")); comments.setComment_id(rs.getString("comment_id")); comments.setFrom_user_id(rs.getString("from_user_id")); comments.setMessage(rs.getString("message")); comments.setDatetime(rs.getString("datetime")); comments.setPost_id(rs.getString("post_id")); comments.setType(rs.getString("type")); return comments; } }
true
e61a492cf04933998d22be477a4670be3511877c
Java
myifoo/chorus
/src/test/java/com/platform/chorus/db/FieldModelTests.java
UTF-8
576
1.84375
2
[]
no_license
package com.platform.chorus.db; import com.platform.chorus.cim.model.CIModelService; 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; @RunWith(SpringRunner.class) @SpringBootTest public class FieldModelTests { @Autowired CIModelService service; @Test public void getByOwnerTest() { service.getFields("chorus.Pupil").forEach(System.out::println); } }
true
cd3d3b6dbda685054c7270dd9ac1cad45a8c4f2b
Java
Omer29-create/WinterSemesterJavaDeveloper
/day02_scanner/C3_Scanner3.java
ISO-8859-3
509
3.296875
3
[]
no_license
package day02_scanner; import java.util.Scanner; public class C3_Scanner3 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Lutfen isminizi giriniz"); String name = scan.next(); // Tek kelime alinabilir // Tm satiri alir System.out.println("lutfen soyisminizi giriniz"); String surName = scan.next(); System.out.println(name + " " + surName); scan.close(); } }
true
1f8535a03f6dfb9a6ba31a3fdb4e5a229fd7dbbc
Java
Sirko2097/bankproject
/src/main/java/com/bankproject/model/BankAccount.java
UTF-8
383
2
2
[]
no_license
package com.bankproject.model; import lombok.*; import java.time.LocalDate; @Getter @Setter @AllArgsConstructor @NoArgsConstructor @ToString public class BankAccount { private int accountId; private String type; private Double amountOfMoney; private Double limit; private double percent; private Double debt; private LocalDate expirationDate; }
true
e25f7b914a266a743bfc0e6ac58b1565e3ba33ba
Java
XDean/JavaFX-EX
/src/test/java/xdean/jfxex/bean/ListenerUtilTest.java
UTF-8
1,866
2.421875
2
[ "Apache-2.0" ]
permissive
package xdean.jfxex.bean; import static org.junit.Assert.assertEquals; import static org.junit.Assume.assumeTrue; import static xdean.jfxex.bean.ListenerUtil.weak; import java.lang.ref.WeakReference; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Test; import javafx.beans.property.SetProperty; import javafx.beans.property.SimpleSetProperty; import javafx.collections.FXCollections; public class ListenerUtilTest extends BaseTest { @Test public void testWeak() throws Exception { Object obj = new Object(); WeakReference<Object> weak = new WeakReference<>(obj); ip.addListener(weak(obj, (ob, o) -> here())); ip.addListener(weak(obj, (ob, o, n) -> here())); assertReach(2, () -> ip.set(2)); obj = null; for (int i = 0; i < 10; i++) { System.gc(); Thread.sleep(10); } assumeTrue("Object doesn't collected.", weak.get() == null); assertNotReach(() -> ip.set(3)); } @Test public void testList() throws Exception { AtomicInteger event = new AtomicInteger(0); list.addListener(ListenerUtil.list(b -> b.onAdd(o -> event.set(1)) .onRemoved(o -> event.set(2)) .onChange(o -> event.get()) .onPermutated((ob, o, n) -> event.set(4)) .onUpdated(o -> event.set(5)))); list.addAll(4, 3, 2); assertEquals(1, event.get()); list.remove(1); assertEquals(2, event.get()); } @Test public void testSet() throws Exception { SetProperty<Integer> set = new SimpleSetProperty<>(FXCollections.observableSet(1)); AtomicInteger event = new AtomicInteger(0); set.addListener(ListenerUtil.set(b -> b.onAdd(o -> event.set(1)) .onRemoved(o -> event.set(2)))); set.add(4); assertEquals(1, event.get()); set.remove(1); assertEquals(2, event.get()); } }
true
fffe8aa1c833be3bb8ff64f911ff837000898d46
Java
bobel95/MM-finances-api
/src/main/java/com/mihmih/finances/model/IncomeCategory.java
UTF-8
105
1.726563
2
[]
no_license
package com.mihmih.finances.model; public enum IncomeCategory { MONTHLY, WEEKLY, ONE_TIME }
true
46d68d306c6f8f8c12e3b317bd678fbe571ed409
Java
bellmit/crmtest
/src/java/com/trilogy/app/crm/integration/pc/TechnicalServiceTemplateAdapter.java
UTF-8
3,547
1.921875
2
[]
no_license
package com.trilogy.app.crm.integration.pc; import com.trilogy.app.crm.bean.ui.TechnicalServiceTemplate; import com.trilogy.framework.xhome.context.Context; import com.trilogy.framework.xhome.home.HomeException; import com.trilogy.framework.xlog.log.LogSupport; import com.trilogy.util.crmapi.wsdl.v3_0.api.core.io.common.v1.ErrorMessageList_type0; import com.trilogy.util.crmapi.wsdl.v3_0.api.core.io.common.v1.MessageType; import com.trilogy.util.crmapi.wsdl.v3_0.api.core.io.common.v1.NonVersionEntityStateChangeInput; import com.trilogy.util.crmapi.wsdl.v3_0.api.core.io.common.v1.PcomFaultInfo; import com.trilogy.util.crmapi.wsdl.v3_0.api.pc.io.technicalservice.v1.RfssIOSave; import com.trilogy.util.crmapi.wsdl.v3_0.api.pc.webservices.messages.v1.CreateTechnicalServiceResponse; import com.trilogy.util.crmapi.wsdl.v3_0.api.pc.webservices.messages.v1.ReleaseTechnicalServiceResponse; import com.trilogy.app.crm.integration.pc.TechnicalServiceTemplateSupport; /** * @author Subhasmita Mishra * @since 10.3.4 * */ public class TechnicalServiceTemplateAdapter { public static RfssIOSave adapt(final Context ctx, final TechnicalServiceTemplate techService, RfssIOSave rfss) throws Exception { LogSupport.debug(ctx, "TechnicalServiceTemplateAdapter", "[TechnicalServiceTemplateAdapter.adapt] printing TechnicalServiceTemplate.getID:"+techService.getID()); return TechnicalServiceTemplateSupport.technicalServiceName(ctx, techService, rfss); } public static Object unAdapt(final Context ctx, CreateTechnicalServiceResponse createTechnicalServiceResponse) { LogSupport.debug(ctx, "TechnicalServiceTemplateAdapter", "[TechnicalServiceTemplateAdapter.unAdapt] Start"); return createTechnicalServiceResponse.getStatus().getValue(); } public static NonVersionEntityStateChangeInput adaptState( final Context ctx, final TechnicalServiceTemplate techService, NonVersionEntityStateChangeInput nvesciObj) throws HomeException { LogSupport.debug(ctx, "TechnicalServiceTemplateAdapter", "[TechnicalServiceTemplateAdapter.adaptState] printing TechnicalServiceTemplate.getID:"+techService.getID()); return TechnicalServiceTemplateSupport.releaseTechnicalService( techService, nvesciObj); } public static Object unAdaptState( ReleaseTechnicalServiceResponse rtsresponse) { return rtsresponse.getStatus().getValue(); } public static Object unAdaptError(final Context ctx, CreateTechnicalServiceResponse createTechnicalServiceResponse) { boolean debugEnabled = LogSupport.isDebugEnabled(ctx); if (debugEnabled) { LogSupport.debug(ctx, "TechnicalServiceTemplateAdapter", "[TechnicalServiceTemplateAdapter.unAdaptError] Start"); } String response = ""; PcomFaultInfo faultInfo = new PcomFaultInfo(); ErrorMessageList_type0 errMsgList = new ErrorMessageList_type0(); faultInfo = createTechnicalServiceResponse.getFaultInfo(); errMsgList = faultInfo.getErrorMessageList(); MessageType[] localMessage = errMsgList.getMessage(); for (int i = 0; i < localMessage.length; i++) { response = localMessage[i].getString(); if (debugEnabled) { LogSupport.debug(ctx, "TechnicalServiceTemplateAdapter", "[TechnicalServiceTemplateAdapter.unAdaptError] failure response: " + response); } } LogSupport.info(ctx, "TechnicalServiceTemplateAdapter", "[TechnicalServiceTemplateAdapter.unAdaptError] final response: " + response); return response; } }
true
78510e80ba86a2977a42058af1af840479ec922b
Java
bsef12m510/PlagiarismChecker
/app/src/main/java/com/prepostseo/plagchecker/register/response/RegisterResponse.java
UTF-8
783
2.140625
2
[]
no_license
package com.prepostseo.plagchecker.register.response; public class RegisterResponse { private Integer user_id; private String api_key; private Integer response; private String error; public Integer getUserId() { return user_id; } public String getError() { return error; } public void setError(String error) { this.error = error; } public void setUserId(Integer userId) { this.user_id = userId; } public String getApiKey() { return api_key; } public void setApiKey(String apiKey) { this.api_key = apiKey; } public Integer getResponse() { return response; } public void setResponse(Integer response) { this.response = response; } }
true
152dac365922debd6f761b277aae8420fa47df59
Java
easonlong/eason-test
/src/main/java/com/eason/coding/life/ApplicationContextManager.java
UTF-8
1,287
2.703125
3
[]
no_license
package com.eason.coding.life; import org.apache.log4j.Logger; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.support.ClassPathXmlApplicationContext; public class ApplicationContextManager implements ApplicationContextAware{ private static final Logger LOGGER=Logger.getLogger(ApplicationContextManager.class); private static ApplicationContext context; private static boolean initialized = false; public static void init(String[] contextPath) { if (!initialized) { context = new ClassPathXmlApplicationContext(contextPath); initialized=true; } } public static ApplicationContext getInstance() throws Exception { if (context == null) { throw new Exception("context hasn't been initialized."); } return context; } public static void destroy(){ if(context!=null){ LOGGER.info("destroy the contex..."); context=null; System.exit(1); } } public static Object getBean(String name) throws Exception{ return getInstance().getBean(name); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.context = applicationContext; } }
true
d5806ff2b7b9b282fe5a23514b88b41f062be6d0
Java
proog/spct-f2014
/assignment1/BLIPDeviceMonitoring/src/dk/itu/spct/f2014/pmor/janv/ma01/trigger/MessageReceivedObserver.java
UTF-8
207
1.65625
2
[]
no_license
package dk.itu.spct.f2014.pmor.janv.ma01.trigger; import dk.itu.spct.f2014.pmor.janv.ma01.utils.TriggerMessage; public interface MessageReceivedObserver { public void messageReceived(TriggerMessage m); }
true
55c71426b673943e65c1e84064b6926621595ec9
Java
bellmit/preg-project
/preg-web/src/main/java/com/mnt/preg/examitem/form/DiagnosisPrescriptionForm.java
UTF-8
1,086
1.828125
2
[]
no_license
package com.mnt.preg.examitem.form; import java.util.List; import com.mnt.preg.platform.pojo.DiagnosisPrescriptionPojo; /** * 营养处方 * * @author zcq * @version 1.0 * * 变更履历: * v1.0 2017-10-21 zcq 初版 */ public class DiagnosisPrescriptionForm { /** 诊疗主键 */ private String diagnosisId; /** 补充剂列表 */ private List<DiagnosisPrescriptionPojo> extenderList; /** 营养素补充提示 */ private String extenderHint; public String getExtenderHint() { return extenderHint; } public void setExtenderHint(String extenderHint) { this.extenderHint = extenderHint; } public String getDiagnosisId() { return diagnosisId; } public void setDiagnosisId(String diagnosisId) { this.diagnosisId = diagnosisId; } public List<DiagnosisPrescriptionPojo> getExtenderList() { return extenderList; } public void setExtenderList(List<DiagnosisPrescriptionPojo> extenderList) { this.extenderList = extenderList; } }
true
fa13438b220da1b02d29ac0bf263eb8410a90bad
Java
FuqiX/FAIRDataPoint
/src/test/java/nl/dtls/fairdatapoint/service/metadatametrics/FairMetadataMetricsServiceImplTest.java
UTF-8
2,912
1.90625
2
[ "MIT" ]
permissive
/** * The MIT License * Copyright © 2017 DTL * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /* * 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 nl.dtls.fairdatapoint.service.metadatametrics; import nl.dtls.fairmetadata4j.model.Metric; import nl.dtls.fairdatapoint.BaseIntegrationTest; import nl.dtls.fairdatapoint.utils.MetadataFixtureFilesHelper; import org.eclipse.rdf4j.model.ValueFactory; import org.eclipse.rdf4j.model.impl.SimpleValueFactory; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import java.util.List; import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertThrows; // TODO What is purpose of this class public class FairMetadataMetricsServiceImplTest extends BaseIntegrationTest { private final ValueFactory valueFactory = SimpleValueFactory.getInstance(); @Autowired private FairMetadataMetricsServiceImpl fmMetricsServiceImpl; /** * Test getMetrics with null uri, this test is excepted to throw error */ @Test public void nullMetadataUri() { assertThrows(NullPointerException.class, () -> { fmMetricsServiceImpl.getMetrics(null); }); } /** * This test is excepted to pass */ @Test public void validMetadataUri() { // Map<String, String> metadataMetrics = new HashMap<>(); // metadataMetrics.put("https://purl.org/fair-metrics/FM_F1A", "http://example.com/f1a"); // fmMetricsServiceImpl.setMetadataMetrics(metadataMetrics); List<Metric> m = fmMetricsServiceImpl.getMetrics(valueFactory.createIRI( MetadataFixtureFilesHelper.REPOSITORY_URI)); assertTrue(m.size() > 0); } }
true
5f692b069ac06cdcac86f6debe8c2635530a693b
Java
AH-Liuzy0121/springboot
/src/main/java/com/liuzy/module/bean/User.java
UTF-8
1,732
2.59375
3
[]
no_license
package com.liuzy.module.bean; import java.io.Serializable; /** * @className: User * @package: com.liuzy.module.bean * @describe: 实体类Bean * @auther: liuzhiyong * @date: 2018/4/10 * @time: 下午 7:16 */ public class User implements Serializable{ private Integer id; private java.lang.String userName;//姓名 private java.lang.String phoneNo;//手机号 private java.lang.String certNo;//身份证号 private java.lang.String password;//密码 public User() { } public User(Integer id, String userName, String phoneNo, String certNo, String password) { this.id = id; this.userName = userName; this.phoneNo = phoneNo; this.certNo = certNo; this.password = password; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String name) { this.userName = userName; } public String getPhoneNo() { return phoneNo; } public void setPhoneNo(String phoneNo) { this.phoneNo = phoneNo; } public String getCertNo() { return certNo; } public void setCertNo(String certNo) { this.certNo = certNo; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "id = " + id + ", userName = '" + userName + '\'' + ", phoneNo = '" + phoneNo + '\'' + ", certNo = '" + certNo + '\'' + ", password = '" + password + '\'' ; } }
true
c4be4c09797bcc20c5e00e6745a4db15b16fd7a9
Java
cmFodWx5YWRhdjEyMTA5/smell-and-machine-learning
/ast_results/osmandapp_Osmand/OsmAnd-java/src/main/java/net/osmand/TspAnt.java
UTF-8
11,094
1.632813
2
[]
no_license
// isComment package net.osmand; import net.osmand.data.LatLon; import net.osmand.util.MapUtils; import java.util.ArrayList; import java.util.List; import java.util.Random; // isComment public class isClassOrIsInterface { // isComment // isComment private double isVariable = isDoubleConstant; // isComment private double isVariable = isIntegerConstant; // isComment private double isVariable = isIntegerConstant; // isComment private double isVariable = isDoubleConstant; // isComment private double isVariable = isIntegerConstant; // isComment private double isVariable = isDoubleConstant; // isComment private double isVariable = isDoubleConstant; // isComment // isComment private int isVariable = isIntegerConstant; // isComment public int isVariable = isIntegerConstant; // isComment public int isVariable = isIntegerConstant; private double[][] isVariable = null; private double[][] isVariable = null; private Ant[] isVariable = null; private Random isVariable = new Random(); private double[] isVariable = null; private int isVariable = isIntegerConstant; public int[] isVariable; public double isVariable; // isComment private class isClassOrIsInterface { public int[] isVariable = new int[isNameExpr.isFieldAccessExpr]; // isComment // isComment public boolean[] isVariable = new boolean[isNameExpr.isFieldAccessExpr]; public void isMethod(int isParameter) { isNameExpr[isNameExpr + isIntegerConstant] = isNameExpr; isNameExpr[isNameExpr] = true; } public boolean isMethod(int isParameter) { return isNameExpr[isNameExpr]; } public double isMethod() { double isVariable = isNameExpr[isNameExpr[isNameExpr - isIntegerConstant]][isNameExpr[isIntegerConstant]]; for (int isVariable = isIntegerConstant; isNameExpr < isNameExpr - isIntegerConstant; isNameExpr++) { isNameExpr += isNameExpr[isNameExpr[isNameExpr]][isNameExpr[isNameExpr + isIntegerConstant]]; } return isNameExpr; } public void isMethod() { for (int isVariable = isIntegerConstant; isNameExpr < isNameExpr; isNameExpr++) isNameExpr[isNameExpr] = true; } } // isComment // isComment // isComment public TspAnt isMethod(List<LatLon> isParameter, LatLon isParameter, LatLon isParameter) { boolean isVariable = isNameExpr != null; List<LatLon> isVariable = new ArrayList<LatLon>(); isNameExpr.isMethod(isNameExpr); isNameExpr.isMethod(isNameExpr); if (isNameExpr) { isNameExpr.isMethod(isNameExpr); } isNameExpr = isNameExpr.isMethod(); // isComment isNameExpr = new double[isNameExpr][isNameExpr]; double isVariable = isIntegerConstant; for (int isVariable = isIntegerConstant; isNameExpr < isNameExpr; isNameExpr++) { double isVariable = isIntegerConstant; for (int isVariable = isIntegerConstant; isNameExpr < isNameExpr; isNameExpr++) { double isVariable = isNameExpr.isMethod(isNameExpr.isMethod(isNameExpr.isMethod(isNameExpr), isNameExpr.isMethod(isNameExpr))) + isDoubleConstant; isNameExpr = isNameExpr.isMethod(isNameExpr, isNameExpr); isNameExpr[isNameExpr][isNameExpr] = isNameExpr; } isNameExpr += isNameExpr; } isNameExpr = isNameExpr.isMethod(isNameExpr) + isIntegerConstant; for (int isVariable = isIntegerConstant; isNameExpr < isNameExpr; isNameExpr++) { if (isNameExpr && isNameExpr == isNameExpr - isIntegerConstant) { isNameExpr[isNameExpr][isIntegerConstant] = isDoubleConstant; } else { isNameExpr[isNameExpr][isIntegerConstant] = isNameExpr; } // isComment } isNameExpr = (int) (isNameExpr * isNameExpr); // isComment isNameExpr = new double[isNameExpr][isNameExpr]; isNameExpr = new double[isNameExpr]; isNameExpr = new Ant[isNameExpr]; for (int isVariable = isIntegerConstant; isNameExpr < isNameExpr; isNameExpr++) isNameExpr[isNameExpr] = new Ant(); return this; } // isComment // isComment // isComment // isComment // isComment // isComment // isComment public static double isMethod(final double isParameter, final double isParameter) { final int isVariable = (int) (isNameExpr.isMethod(isNameExpr) >> isIntegerConstant); final int isVariable = (int) (isNameExpr * (isNameExpr - isIntegerConstant) + isIntegerConstant); return isNameExpr.isMethod(((long) isNameExpr) << isIntegerConstant); } // isComment // isComment // isComment private void isMethod(Ant isParameter) { int isVariable = isNameExpr.isFieldAccessExpr[isNameExpr]; double isVariable = isDoubleConstant; for (int isVariable = isIntegerConstant; isNameExpr < isNameExpr; isNameExpr++) if (!isNameExpr.isMethod(isNameExpr)) isNameExpr += isMethod(isNameExpr[isNameExpr][isNameExpr], isNameExpr) * isMethod(isDoubleConstant / isNameExpr[isNameExpr][isNameExpr], isNameExpr); for (int isVariable = isIntegerConstant; isNameExpr < isNameExpr; isNameExpr++) { if (isNameExpr.isMethod(isNameExpr)) { isNameExpr[isNameExpr] = isDoubleConstant; } else { double isVariable = isMethod(isNameExpr[isNameExpr][isNameExpr], isNameExpr) * isMethod(isDoubleConstant / isNameExpr[isNameExpr][isNameExpr], isNameExpr); isNameExpr[isNameExpr] = isNameExpr / isNameExpr; } } } // isComment // isComment // isComment private int isMethod(Ant isParameter) { // isComment if (isNameExpr.isMethod() < isNameExpr) { // isComment int isVariable = isNameExpr.isMethod(isNameExpr - isNameExpr); int isVariable = -isIntegerConstant; for (int isVariable = isIntegerConstant; isNameExpr < isNameExpr; isNameExpr++) { if (!isNameExpr.isMethod(isNameExpr)) isNameExpr++; if (isNameExpr == isNameExpr) return isNameExpr; } } // isComment isMethod(isNameExpr); // isComment double isVariable = isNameExpr.isMethod(); double isVariable = isIntegerConstant; for (int isVariable = isIntegerConstant; isNameExpr < isNameExpr; isNameExpr++) { isNameExpr += isNameExpr[isNameExpr]; if (isNameExpr >= isNameExpr) return isNameExpr; } throw new RuntimeException("isStringConstant"); } // isComment private void isMethod() { // isComment for (int isVariable = isIntegerConstant; isNameExpr < isNameExpr; isNameExpr++) for (int isVariable = isIntegerConstant; isNameExpr < isNameExpr; isNameExpr++) isNameExpr[isNameExpr][isNameExpr] *= isNameExpr; // isComment for (Ant isVariable : isNameExpr) { double isVariable = isNameExpr / isNameExpr.isMethod(); for (int isVariable = isIntegerConstant; isNameExpr < isNameExpr - isIntegerConstant; isNameExpr++) { isNameExpr[isNameExpr.isFieldAccessExpr[isNameExpr]][isNameExpr.isFieldAccessExpr[isNameExpr + isIntegerConstant]] += isNameExpr; } isNameExpr[isNameExpr.isFieldAccessExpr[isNameExpr - isIntegerConstant]][isNameExpr.isFieldAccessExpr[isIntegerConstant]] += isNameExpr; } } // isComment private void isMethod() { // isComment while (isNameExpr < isNameExpr - isIntegerConstant) { for (Ant isVariable : isNameExpr) isNameExpr.isMethod(isMethod(isNameExpr)); isNameExpr++; } } // isComment private void isMethod() { isNameExpr = -isIntegerConstant; for (int isVariable = isIntegerConstant; isNameExpr < isNameExpr; isNameExpr++) { // isComment isNameExpr[isNameExpr].isMethod(); isNameExpr[isNameExpr].isMethod(isNameExpr.isMethod(isNameExpr)); } isNameExpr++; } private void isMethod() { if (isNameExpr == null) { isNameExpr = isNameExpr[isIntegerConstant].isFieldAccessExpr; isNameExpr = isNameExpr[isIntegerConstant].isMethod(); } for (Ant isVariable : isNameExpr) { if (isNameExpr.isMethod() < isNameExpr) { isNameExpr = isNameExpr.isMethod(); isNameExpr = isNameExpr.isFieldAccessExpr.isMethod(); } } } public static String isMethod(int[] isParameter) { String isVariable = "isStringConstant"; for (int isVariable : isNameExpr) isNameExpr = isNameExpr + "isStringConstant" + isNameExpr; return isNameExpr; } public int[] isMethod() { // isComment for (int isVariable = isIntegerConstant; isNameExpr < isNameExpr; isNameExpr++) for (int isVariable = isIntegerConstant; isNameExpr < isNameExpr; isNameExpr++) isNameExpr[isNameExpr][isNameExpr] = isNameExpr; int isVariable = isIntegerConstant; // isComment while (isNameExpr < isNameExpr) { isMethod(); isMethod(); isMethod(); isMethod(); isNameExpr++; } // isComment isNameExpr.isFieldAccessExpr.isMethod("isStringConstant" + (isNameExpr - isNameExpr * isDoubleConstant)); isNameExpr.isFieldAccessExpr.isMethod("isStringConstant" + isMethod(isNameExpr)); return isMethod(isNameExpr.isMethod()); } private static int[] isMethod(int[] isParameter) { int[] isVariable = new int[isNameExpr.isFieldAccessExpr]; int isVariable = isIntegerConstant; for (int isVariable = isIntegerConstant; isNameExpr < isNameExpr.isFieldAccessExpr; isNameExpr++) { if (isNameExpr[isNameExpr] == isIntegerConstant) { isNameExpr = isNameExpr; break; } } for (int isVariable = isIntegerConstant; isNameExpr < isNameExpr.isFieldAccessExpr; isNameExpr++) { isNameExpr[(isNameExpr - isNameExpr + isNameExpr.isFieldAccessExpr) % isNameExpr.isFieldAccessExpr] = isNameExpr[isNameExpr]; } return isNameExpr; } // isComment // isComment // isComment // isComment public static void isMethod(String[] isParameter) { // isComment if (isNameExpr.isFieldAccessExpr < isIntegerConstant) { isNameExpr.isFieldAccessExpr.isMethod("isStringConstant"); return; } TspAnt isVariable = new TspAnt(); // isComment for (; ; ) { isNameExpr.isMethod(); } } }
true
de9ee09a2f14e49a4ced146262bd6bf475cfdb72
Java
ocean-treasures/android
/android-project/app/src/main/java/oceantreasur/es/network/MockOceanTreasuresAPI.java
UTF-8
4,140
2.390625
2
[ "MIT" ]
permissive
package oceantreasur.es.network; import android.content.res.AssetManager; import android.util.Log; import com.google.gson.Gson; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Random; import oceantreasur.es.network.model.CheckAnswerRequest; import oceantreasur.es.network.model.CheckAnswerResponse; import oceantreasur.es.network.model.NextWordResponse; import oceantreasur.es.network.model.Progress; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.mock.BehaviorDelegate; public class MockOceanTreasuresAPI implements OceanTreasuresAPI { private final BehaviorDelegate<OceanTreasuresAPI> delegate; public MockOceanTreasuresAPI(BehaviorDelegate<OceanTreasuresAPI> service) { this.delegate = service; } @Override public Call<NextWordResponse> getNextWord() { NextWordResponse nextWordResponse; String result; String[] jsonFiles = {"json/next_word_response1.json", "json/next_word_response2.json", "json/next_word_response3.json", "json/next_word_response4.json", "json/next_word_response5.json"}; Random random = new Random(); int temp = random.nextInt(5); result = parseData(jsonFiles[temp]); Log.d("RND", temp + ""); Gson gson = new Gson(); nextWordResponse = gson.fromJson(result, NextWordResponse.class); return delegate.returningResponse(nextWordResponse).getNextWord(); } @Override public Call<CheckAnswerResponse> checkAnswer(@Body CheckAnswerRequest body) { CheckAnswerResponse checkAnswerResponse = new CheckAnswerResponse(); HashMap<Integer, String> data = new HashMap<>(); data.put(1, "apple"); data.put(2, "pear"); data.put(3, "banana"); data.put(4, "watermelon"); data.put(6, "avocado"); data.put(7, "apricot"); data.put(8, "cherry"); data.put(9, "grapefruit"); data.put(10, "strawberry"); data.put(11, "mango"); data.put(12, "lemon"); data.put(13, "orange"); data.put(14, "pineapple"); data.put(15, "plum"); data.put(16, "melon"); data.put(17, "raspberry"); data.put(18, "coconut"); data.put(19, "blueberry"); data.put(20, "kiwi"); data.put(21, "pomegranate"); Random random = new Random(); // String result; // // result = parseData("json/check_word_response.json"); // // Gson gson = new Gson(); // checkAnswerResponse = gson.fromJson(result, CheckAnswerResponse.class); checkAnswerResponse.setCorrect(body.getPicId() == body.getWordId()); checkAnswerResponse.setWord(data.get(body.getPicId())); checkAnswerResponse.setProgress(new Progress(10, 10)); return delegate.returningResponse(checkAnswerResponse).checkAnswer(body); } public String parseData(String jsonPath) { StringBuilder result = new StringBuilder(); BufferedReader reader = null; AssetManager assetManager; InputStreamReader inputStreamReader = null; try { assetManager = OceanTreasuresApplication.getInstance().getApplicationContext().getAssets(); inputStreamReader = new InputStreamReader(assetManager.open(jsonPath)); reader = new BufferedReader(inputStreamReader); String line; while((line = reader.readLine()) != null) { result.append(line); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (reader != null) { reader.close(); } if (inputStreamReader != null) { inputStreamReader.close(); } } catch (IOException e) { e.printStackTrace(); } } return result.toString(); } }
true
e4732074d76cfa863908d9d77b79e0b0b235c93b
Java
Levifer/REDO-FLEET
/src/main/java/com/realdolmen/controller/LoginController.java
UTF-8
944
2.234375
2
[]
no_license
package com.realdolmen.controller; import com.realdolmen.domain.employee.Employee; import com.realdolmen.util.LoggerProducer; import org.slf4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; /** * Created by AEIAT46 on 29/10/2014. */ @Controller public class LoginController { @LoggerProducer private Logger logger; @RequestMapping("/login") public String getLoginPage(Model model){ logger.info("getLoginPage"); model.addAttribute("isLoggedIn",false); return "login"; } public String login(Employee employee){ logger.info("Employee:" + employee.getEmail()); if(!employee.getEmail().isEmpty() && !employee.getPassword().isEmpty() && employee.getEmail().endsWith("@realdolmen.com")){ return "yes"; }else{ return "no"; } } }
true
5047aafed40c5e84b1484df551a0145a13bdaba1
Java
SeloSlav/tic-tac-toe
/app/src/main/java/com/martinerlic/tic_tac_toe/adapter/GridRecyclerAdapter.java
UTF-8
9,144
2.75
3
[]
no_license
package com.martinerlic.tic_tac_toe.adapter; import android.content.Context; import android.support.v4.content.ContextCompat; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import com.martinerlic.tic_tac_toe.R; import com.martinerlic.tic_tac_toe.activity.MainActivity; import com.martinerlic.tic_tac_toe.model.Player; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class GridRecyclerAdapter extends RecyclerView.Adapter<GridRecyclerAdapter.ViewHolder> { /* Globals */ private String[] mData; private int mColumns; private Player mPlayer1; private Player mPlayer2; private Context mContext; private LayoutInflater mInflater; private ItemClickListener mClickListener; private List<Integer> mXPositions; private List<Integer> mOPositions; private TextView mPlayerHint; /* Initialize constructor */ public GridRecyclerAdapter(Context context, String[] data, int numColumns, Player player1, Player player2, List<Integer> xPositions, List<Integer> oPositions, TextView playerHint) { this.mInflater = LayoutInflater.from(context); this.mData = data; this.mColumns = numColumns; this.mPlayer1 = player1; this.mPlayer2 = player2; this.mContext = context; this.mXPositions = xPositions; this.mOPositions = oPositions; this.mPlayerHint = playerHint; } /* Inflate cell layout */ @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = mInflater.inflate(R.layout.recyclerview_item, parent, false); /* Set minimum height of each cell by the number of rows in the grid */ int height = parent.getMeasuredHeight() / mColumns; itemView.setMinimumHeight(height); return new ViewHolder(itemView); } /* Bind data to TextView */ @Override public void onBindViewHolder(final ViewHolder viewHolder, int position) { String cell = mData[position]; viewHolder.cellTextView.setText(cell); List<Integer[]> conditionList = new ArrayList<>(); viewHolder.itemView.setOnClickListener(v -> { checkTurn(viewHolder, position); checkCompletionConditions(mXPositions, mOPositions, conditionList); }); } /* Check the current player turn */ private void checkTurn(final ViewHolder viewHolder, int position) { if (!(viewHolder.cellTextView.getText().toString().isEmpty())) { Toast.makeText(mContext, "You cannot select this cell!", Toast.LENGTH_SHORT).show(); } else { if (mPlayer1.isTurn()) { /* Set cell to "X" */ viewHolder.cellTextView.setText(mPlayer1.getTextValue()); /* Set clicked */ viewHolder.cellTextView.setBackgroundColor(ContextCompat.getColor(mContext, R.color.colorPrimary)); mXPositions.add(position); // mOPositions.add(-1); // Toast.makeText(mContext, mXPositions.toString(), Toast.LENGTH_SHORT).show(); mPlayerHint.setText(R.string.player_2_turn); // Indicate that it is Player 2's turn next /* Prepare next turn */ mPlayer1.setTurn(false); mPlayer2.setTurn(true); } else { /* Set cell to "O" */ viewHolder.cellTextView.setText(mPlayer2.getTextValue()); /* Set clicked */ viewHolder.cellTextView.setBackgroundColor(ContextCompat.getColor(mContext, R.color.colorPrimaryDark)); mOPositions.add(position); // mXPositions.add(-1); // Toast.makeText(mContext, mOPositions.toString(), Toast.LENGTH_SHORT).show(); mPlayerHint.setText(R.string.player_1_turn); // Indicate that it is Player 1's turn next /* Prepare next turn */ mPlayer1.setTurn(true); mPlayer2.setTurn(false); } } } private void checkCompletionConditions(List<Integer> mXPositions, List<Integer> mOPositions, List<Integer[]> conditionList) { /* Legend * 0: Top-left * 1: Top-center * 2: Top-right * 3: Middle-left * 4: Middle-center * 5: Middle-right * 6: Bottom-left * 7: Bottom-center * 8: Bottom-right */ /* Win Conditions * * Horizontal Lines * Condition 1: 0, 1, 2 * Condition 2: 3, 4, 5 * Condition 3: 6, 7, 8 * * Vertical Lines * Condition 4: 0, 3, 6 * Condition 5: 1, 4, 7 * Condition 6: 2, 5, 8 * * Diagonal Lines * Condition 7: 0, 4, 8 * Condition 8: 2, 4, 6 */ /* Define the winning conditions */ Integer[] condition1 = {0, 1, 2}; Integer[] condition2 = {3, 4, 5}; Integer[] condition3 = {6, 7, 8}; Integer[] condition4 = {0, 3, 6}; Integer[] condition5 = {1, 4, 7}; Integer[] condition6 = {2, 5, 8}; Integer[] condition7 = {0, 4, 8}; Integer[] condition8 = {2, 4, 6}; /* Add conditions lists to list of lists */ conditionList.add(condition1); conditionList.add(condition2); conditionList.add(condition3); conditionList.add(condition4); conditionList.add(condition5); conditionList.add(condition6); conditionList.add(condition7); conditionList.add(condition8); /* Finally, check if a player has won */ for (Integer[] conditionItem : conditionList) { if (mXPositions.containsAll(Arrays.asList(conditionItem))) { Toast.makeText(mContext, R.string.player_1_wins, Toast.LENGTH_SHORT).show(); clearXValues(); clearOValues(); startNewGame(mPlayer1, mPlayer2); } else //noinspection StatementWithEmptyBody if (mOPositions.containsAll(Arrays.asList(conditionItem))) { Toast.makeText(mContext, R.string.player_2_wins, Toast.LENGTH_SHORT).show(); clearXValues(); clearOValues(); startNewGame(mPlayer2, mPlayer1); } else { // TODO: Tie-condition. If there are no more empty itemViews left, and the above conditions do not hold, show a draw /*if () { Toast.makeText(mContext, R.string.player_2_wins, Toast.LENGTH_SHORT).show(); clearXValues(); clearOValues(); if (mPlayer1.isTurn()) { startNewGame(mPlayer2, mPlayer1); } else { startNewGame(mPlayer1, mPlayer2); } }*/ } } } private void clearOValues() { int size = this.mOPositions.size(); if (size > 0) { for (int i = 0; i < size; i++) { this.mOPositions.remove(0); } this.notifyItemRangeRemoved(0, size); } } private void clearXValues() { int size = this.mXPositions.size(); if (size > 0) { for (int i = 0; i < size; i++) { this.mXPositions.remove(0); } this.notifyItemRangeRemoved(0, size); } } /* Select the player to start the new game, then wipe the board! */ private void startNewGame(Player playerToStart, Player nextPlayer) { ((MainActivity) mContext).initRecyclerView(mData); playerToStart.setTurn(true); nextPlayer.setTurn(false); if (playerToStart.getTextValue().equals("X")) { mPlayerHint.setText(R.string.player_1_turn); } else { mPlayerHint.setText(R.string.player_2_turn); } } /* Item count */ @Override public int getItemCount() { return mData.length; } /* Store cell views */ class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { TextView cellTextView; ViewHolder(View itemView) { super(itemView); cellTextView = (TextView) itemView.findViewById(R.id.textView); } @Override public void onClick(View itemView) { if (mClickListener != null) mClickListener.onItemClick(itemView, getAdapterPosition()); } } /* Get data at click position */ public String getItem(int id) { return mData[id]; } /* Capture click position */ public void setClickListener(ItemClickListener itemClickListener) { this.mClickListener = itemClickListener; } /* Implement method to respond to click events in MainActivity */ public interface ItemClickListener { void onItemClick(View itemView, int position); } }
true
2169f76af57101c23515063ad22346e275d64875
Java
WangXinLong-Long/Success
/app/src/main/java/com/silianchuangye/sumao/success/fragments/myPlasticTrade/companyInformations/firmInfomation/FirmInfoUpdateMVP/model/FirmInfoUpdateCallback.java
UTF-8
465
1.710938
2
[]
no_license
package com.silianchuangye.sumao.success.fragments.myPlasticTrade.companyInformations.firmInfomation.FirmInfoUpdateMVP.model; import com.silianchuangye.sumao.success.fragments.myPlasticTrade.companyInformations.firmInfomation.FirmInfoUpdateMVP.bean.FirmInfoUpdateActivityBean; /** * Created by Administrator on 2016/9/6 0006. */ public interface FirmInfoUpdateCallback { void callbackFirmInfoUpdate(FirmInfoUpdateActivityBean firmInfoUpdateActivityBean); }
true
286668c7049ee48c3f0db854847a1ff75827d20a
Java
ahedeijack/java_apps
/Programacion/Otros/Pruebas xD/PB_18131396_Proyecto_02/src/pkg18131396_p2/PB_18131396_jFPrincipal.java
UTF-8
31,941
2.75
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 pkg18131396_p2; import Utilerias.JTable.ColorCeldas; import java.awt.Color; import java.util.Random; import javax.swing.JLabel; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; public class PB_18131396_jFPrincipal extends javax.swing.JFrame { /** * Creates new form jFramePrincipal */ Cliente [] cInicial = new Cliente[4]; Cliente [] cUltimo = new Cliente[cInicial.length]; Cliente [] dFinal = new Cliente[cUltimo.length]; DefaultTableModel modeloI; Depositos depInicial [] = new Depositos[4]; Depositos depFinal [] = new Depositos[depInicial.length]; Depositos depDep [] = new Depositos[depInicial.length]; String nombre; Depositos sIni; Depositos sFin; Depositos dFin; Random azar; public PB_18131396_jFPrincipal() { initComponents(); modeloI = (DefaultTableModel) jTab1.getModel(); } public void setTotales(DefaultTableModel models, JLabel labIni, JLabel labFin){ Depositos total; Depositos totalDep = new Depositos(); for (int i = 0; i < models.getRowCount(); i++) { total = new Depositos((int)models.getValueAt(i, 1), (int)models.getValueAt(i, 2), (int)models.getValueAt(i, 3), (int)models.getValueAt(i, 4)); totalDep = totalDep.suma(total); } labIni.setText(totalDep.toString()); for (int i = 0; i < models.getRowCount(); i++) { total = new Depositos((int)models.getValueAt(i, 5), (int)models.getValueAt(i, 6), (int)models.getValueAt(i, 7), (int)models.getValueAt(i, 8)); totalDep = totalDep.suma(total); } labFin.setText(totalDep.toString()); } public void OrdenAlfabetico(DefaultTableModel oInicial){ //En el metodo, vamos a crear un PB_18131396_ClaseA, el cual sera nuestro auxiliar para poder //Ordenar las tablas sin perder el orden de los depositos. Cliente ordenadoAlfabetico; for (int i = 0; i < oInicial.getRowCount(); i++) { //sobre el contrsuctor del jFrame creamos un //arreglo de clientes, el cual iremos llenando //con dos arreglos del tipo Depositos, para así //poder registrarlos al respectivo cliente. //El primer deposito se hará obteniendo los valores del //primer table (tabla primer deposito) depInicial[i] = new Depositos((int)oInicial.getValueAt(i, 1), (int)oInicial.getValueAt(i, 2), (int)oInicial.getValueAt(i, 3), (int)oInicial.getValueAt(i, 4)); //El segundo, se llenara a partir de los datos del segundo table o del segundo deposito depFinal[i] = new Depositos((int)oInicial.getValueAt(i, 5), (int)oInicial.getValueAt(i, 6), (int)oInicial.getValueAt(i, 7), (int)oInicial.getValueAt(i, 8)); //Una vez teniendo los datos, el nombre se obtendra del renglon 0 y columna 0 //además de que esto permitira hacer correctamente los ordenamientos mas adelante cInicial[i] = new Cliente((oInicial.getValueAt(i, 0)+""),depInicial[i], depFinal[i]); } for (int i = 0; i < oInicial.getRowCount(); i++) { for (int j = 0; j < oInicial.getColumnCount() && i != j; j++) { //Vamos a recorrer la tabla inicial con un doble for, y ademas vamos a comparar //los nombres de los clientes con uso del CompareTo, y así, con el PB_18131396_ClaseA que creamos //al inicio del metodo "ordenadoAlfabetico", el cual nos hara de auxiliar //podremos ir acomodando los clientes correctamente. if(cInicial[i].getNombre().compareToIgnoreCase(cInicial[(j)].getNombre())<0){ ordenadoAlfabetico = cInicial[i]; cInicial[i] = cInicial[j]; cInicial[j] = ordenadoAlfabetico; } } } //Usaremos un deposito auxiliar, el cual nos servira para rellenar las tablas con la //información ya ordenada. Depositos aux = null; for(int i= 0; i<oInicial.getRowCount(); i++){ oInicial.setValueAt(cInicial[i].getNombre(), i, 0); oInicial.setValueAt(cInicial[i].getDep_inicial().getObolo(), i, 1); oInicial.setValueAt(cInicial[i].getDep_inicial().getDracma(), i, 2); oInicial.setValueAt(cInicial[i].getDep_inicial().getMina(), i, 3); oInicial.setValueAt(cInicial[i].getDep_inicial().getTalento(), i, 4); oInicial.setValueAt(cInicial[i].getDep_final().getObolo(), i, 5); oInicial.setValueAt(cInicial[i].getDep_final().getDracma(), i, 6); oInicial.setValueAt(cInicial[i].getDep_final().getMina(), i, 7); oInicial.setValueAt(cInicial[i].getDep_final().getTalento(), i, 8); aux = cInicial[i].depTotales(); oInicial.setValueAt(aux.getObolo(), i, 9); oInicial.setValueAt(aux.getDracma(), i, 10); oInicial.setValueAt(aux.getMina(), i, 11); oInicial.setValueAt(aux.getTalento(), i, 12); } } public void OrdenDeposito(DefaultTableModel oInicial){ //Aquí haremos el mismo procedimiento que en el ordenamiento alfabetico, al menos hasta llenar el //arreglo de los clientes. Cliente ordenadoAlfabetico; for (int i = 0; i < oInicial.getRowCount(); i++) { depInicial[i] = new Depositos((int)oInicial.getValueAt(i, 1), (int)oInicial.getValueAt(i, 2), (int)oInicial.getValueAt(i, 3), (int)oInicial.getValueAt(i, 4)); depFinal[i] = new Depositos((int)oInicial.getValueAt(i, 5), (int)oInicial.getValueAt(i, 6), (int)oInicial.getValueAt(i, 7), (int)oInicial.getValueAt(i, 8)); cInicial[i] = new Cliente((oInicial.getValueAt(i, 0)+""),depInicial[i], depFinal[i]); } for (int i = 0; i < oInicial.getRowCount(); i++) { for (int j = 0; j < oInicial.getColumnCount() && i != j; j++) { //de igual forma que el alfabetico, vamos a recorrer toda la tabla y la vamos a //reacomodar de modo que el de mayor deposito (convertidos los parametros en obolos) //sea el primero, o en pocas palabras, ascendente (mayor a menor) if(cInicial[i].getDep_final().oboloTotal()>cInicial[j].getDep_final().oboloTotal()){ ordenadoAlfabetico = cInicial[i]; cInicial[i] = cInicial[j]; cInicial[j] = ordenadoAlfabetico; } } } //Ahora aremos uso nuevamente del deposito auxiliar, que servira de igual forma //Para poder rellenar las tablas de manera correcta. Depositos aux = null; for(int i= 0; i<oInicial.getRowCount(); i++){ oInicial.setValueAt(cInicial[i].getNombre(), i, 0); oInicial.setValueAt(cInicial[i].getDep_inicial().getObolo(), i, 1); oInicial.setValueAt(cInicial[i].getDep_inicial().getDracma(), i, 2); oInicial.setValueAt(cInicial[i].getDep_inicial().getMina(), i, 3); oInicial.setValueAt(cInicial[i].getDep_inicial().getTalento(), i, 4); oInicial.setValueAt(cInicial[i].getDep_final().getObolo(), i, 5); oInicial.setValueAt(cInicial[i].getDep_final().getDracma(), i, 6); oInicial.setValueAt(cInicial[i].getDep_final().getMina(), i, 7); oInicial.setValueAt(cInicial[i].getDep_final().getTalento(), i, 8); aux = cInicial[i].depTotales(); oInicial.setValueAt(aux.getObolo(), i, 9); oInicial.setValueAt(aux.getDracma(), i, 10); oInicial.setValueAt(aux.getMina(), i, 11); oInicial.setValueAt(aux.getTalento(), i, 12); } } public void Pintar(JTable pintar){ //Con este metodo, traeremos las 3 tablas para poder colorearlas //de manera simultanea. ColorCeldas celda1 = new ColorCeldas(pintar); //Vamos a creador un arreglo bidimensional el cual de tamaños //le daremos los valores de renglon y columna de la primera tabla. int Marcador [][] = new int [pintar.getRowCount()] [4]; Depositos [] totales = new Depositos[pintar.getRowCount()]; Depositos [] copia = new Depositos[pintar.getRowCount()]; for (int i = 0; i < pintar.getRowCount(); i++) { totales[i] = new Depositos( Integer.parseInt(pintar.getValueAt(i, 9)+""), Integer.parseInt(pintar.getValueAt(i, 10)+""), Integer.parseInt(pintar.getValueAt(i, 11)+""), Integer.parseInt(pintar.getValueAt(i, 12)+"")); copia[i] = totales[i]; } //Creamos estas variables, las cuales tendran la funcion de //localizar la posicion del renglon con mayo o menor información int rma = 0, rme = 0; Depositos comparar = new Depositos(); for (int r = 0; r < Marcador.length; r++) { if (comparar.oboloTotal()>totales[r].oboloTotal()) { rma = 0; } else { comparar = totales[r]; rma = r; } } for (int r = 0; r < Marcador.length; r++) { if (comparar.oboloTotal()<totales[r].oboloTotal()) { rme = 0; } else { comparar = totales[r]; rme = r; } } System.out.println("Mayor: " + rma ); System.out.println("Menor: " + rme ); //Finalmente lo que haremos sera recorrer las columnas de las tablas //Pero solo usaremos las columnas de la primera como indice, ya que tenemos //el mismo valor en todas las tablas //Iremos agregando las celas a pintar, todas con las variables //que anteriormente obtuvimos, y lo unico que cambiara //sera el recorrido de las columnas. for (int i = 0; i < pintar.getRowCount(); i++) { for (int j = 0; j < pintar.getColumnCount(); j++) { if (i == rma) { celda1.addCelda(i, j, Color.GREEN); } if (i == rme) { celda1.addCelda(i, j, Color.RED); } } } celda1.repaint(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane2 = new javax.swing.JScrollPane(); jTable2 = new javax.swing.JTable(); jScrollPane1 = new javax.swing.JScrollPane(); jTab1 = new javax.swing.JTable(); jButInicial = new javax.swing.JButton(); jButDep = new javax.swing.JButton(); jButton4 = new javax.swing.JButton(); jLabel8 = new javax.swing.JLabel(); jButton5 = new javax.swing.JButton(); jButton6 = new javax.swing.JButton(); jLabTotales = new javax.swing.JLabel(); jLabTotalSegundo = new javax.swing.JLabel(); jButton7 = new javax.swing.JButton(); jButLim = new javax.swing.JButton(); jLabel15 = new javax.swing.JLabel(); jLabel16 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); jLabel17 = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); jSpinner1 = new javax.swing.JSpinner(); jLabel2 = new javax.swing.JLabel(); jLabel12 = new javax.swing.JLabel(); jLabTotalInicial = new javax.swing.JLabel(); jTable2.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Cliente", "Talentos", "Dracmas", "Minas", "Talentos" } ) { boolean[] canEdit = new boolean [] { false, false, false, false, false }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jScrollPane2.setViewportView(jTable2); if (jTable2.getColumnModel().getColumnCount() > 0) { jTable2.getColumnModel().getColumn(0).setPreferredWidth(60); jTable2.getColumnModel().getColumn(1).setPreferredWidth(10); jTable2.getColumnModel().getColumn(2).setPreferredWidth(10); jTable2.getColumnModel().getColumn(3).setPreferredWidth(10); jTable2.getColumnModel().getColumn(4).setPreferredWidth(10); } setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setResizable(false); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jTab1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Cliente", "Obolo", "Dracmas", "Minas", "Talentos", "Obolos", "Dracmas", "Minas", "Talentos", "Obolos", "Dracmas", "Minas", "Talentos" } ) { boolean[] canEdit = new boolean [] { false, false, false, false, false, false, false, false, false, false, false, false, false }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jScrollPane1.setViewportView(jTab1); if (jTab1.getColumnModel().getColumnCount() > 0) { jTab1.getColumnModel().getColumn(0).setPreferredWidth(40); jTab1.getColumnModel().getColumn(1).setPreferredWidth(5); jTab1.getColumnModel().getColumn(2).setPreferredWidth(5); jTab1.getColumnModel().getColumn(3).setPreferredWidth(5); jTab1.getColumnModel().getColumn(4).setPreferredWidth(5); jTab1.getColumnModel().getColumn(5).setPreferredWidth(5); jTab1.getColumnModel().getColumn(6).setPreferredWidth(5); jTab1.getColumnModel().getColumn(7).setPreferredWidth(5); jTab1.getColumnModel().getColumn(8).setPreferredWidth(5); jTab1.getColumnModel().getColumn(9).setPreferredWidth(5); jTab1.getColumnModel().getColumn(10).setPreferredWidth(5); jTab1.getColumnModel().getColumn(11).setPreferredWidth(5); jTab1.getColumnModel().getColumn(12).setPreferredWidth(5); } getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 160, 935, 96)); jButInicial.setText("Llenar saldos "); jButInicial.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButInicialActionPerformed(evt); } }); getContentPane().add(jButInicial, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 45, 250, -1)); jButDep.setText("Deposito Total"); jButDep.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButDepActionPerformed(evt); } }); getContentPane().add(jButDep, new org.netbeans.lib.awtextra.AbsoluteConstraints(280, 45, 121, -1)); jButton4.setText("Ejemplo"); jButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton4ActionPerformed(evt); } }); getContentPane().add(jButton4, new org.netbeans.lib.awtextra.AbsoluteConstraints(411, 45, 100, -1)); jLabel8.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel8.setText("Primer Deposit"); getContentPane().add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 140, 290, -1)); jButton5.setText("Pintar + & -"); jButton5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton5ActionPerformed(evt); } }); getContentPane().add(jButton5, new org.netbeans.lib.awtextra.AbsoluteConstraints(280, 95, 121, -1)); jButton6.setText("Orden Alfabetico"); jButton6.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton6ActionPerformed(evt); } }); getContentPane().add(jButton6, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 95, 121, -1)); jLabTotales.setFont(new java.awt.Font("Sitka Subheading", 0, 8)); // NOI18N jLabTotales.setText(" $$"); getContentPane().add(jLabTotales, new org.netbeans.lib.awtextra.AbsoluteConstraints(690, 260, 200, -1)); jLabTotalSegundo.setFont(new java.awt.Font("Sitka Subheading", 0, 8)); // NOI18N jLabTotalSegundo.setText("$$"); getContentPane().add(jLabTotalSegundo, new org.netbeans.lib.awtextra.AbsoluteConstraints(380, 260, 250, 14)); jButton7.setText("Orden Deposito"); jButton7.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton7ActionPerformed(evt); } }); getContentPane().add(jButton7, new org.netbeans.lib.awtextra.AbsoluteConstraints(141, 95, 121, -1)); jButLim.setText("Limpiar"); jButLim.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButLimActionPerformed(evt); } }); getContentPane().add(jButLim, new org.netbeans.lib.awtextra.AbsoluteConstraints(411, 95, 100, -1)); jLabel15.setBackground(new java.awt.Color(51, 255, 51)); jLabel15.setText("Mayor"); jLabel15.setOpaque(true); getContentPane().add(jLabel15, new org.netbeans.lib.awtextra.AbsoluteConstraints(521, 55, 110, 14)); jLabel16.setBackground(new java.awt.Color(255, 0, 0)); jLabel16.setText("Menor"); jLabel16.setOpaque(true); getContentPane().add(jLabel16, new org.netbeans.lib.awtextra.AbsoluteConstraints(521, 75, 110, 14)); jLabel9.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel9.setText("Segundo Deposito"); getContentPane().add(jLabel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(376, 136, 280, -1)); jLabel17.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel17.setText("Depositos Totales"); getContentPane().add(jLabel17, new org.netbeans.lib.awtextra.AbsoluteConstraints(660, 140, 261, -1)); jLabel1.setText("Clientes"); getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(515, 99, -1, -1)); jSpinner1.setModel(new javax.swing.SpinnerNumberModel(0, 0, null, 1)); jSpinner1.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { jSpinner1StateChanged(evt); } }); getContentPane().add(jSpinner1, new org.netbeans.lib.awtextra.AbsoluteConstraints(571, 96, 60, -1)); jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pkg18131396_p2/ASIGNACION.png"))); // NOI18N jLabel2.setOpaque(true); getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(645, 10, 290, 130)); jLabel12.setText("TOTAL:"); getContentPane().add(jLabel12, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 260, 90, -1)); jLabTotalInicial.setFont(new java.awt.Font("Sitka Subheading", 0, 8)); // NOI18N jLabTotalInicial.setText("$$"); getContentPane().add(jLabTotalInicial, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 260, 250, -1)); pack(); }// </editor-fold>//GEN-END:initComponents private void jButInicialActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButInicialActionPerformed // TODO add your handling code here: //Llenamos la primera tabla con la información aleatoria y así poder trabajar de manera más rápida. String [] datos = {"Poncio", "Arquimedes", "Aristoteles", "Socrates", "Platon", "Juan","Pipila","Enrique","Deus"}; jButLim.doClick(); azar = new Random(); Depositos inicial[] = new Depositos[modeloI.getRowCount()]; for (int i = 0; i <= modeloI.getRowCount()-1; i++) { for (int j = 0; j <= modeloI.getColumnCount()-5; j++) { // modeloI.setValueAt(azar.nextInt(10), i, j); // } modeloI.setValueAt(datos[i], i, 0); } for (int i = 1; i <= modeloI.getRowCount()-1; i++) { for (int j = 0; j <= modeloI.getColumnCount()-9; j++) { // // } modeloI.setValueAt(datos[i], i, 0); } for (int i = 0; i < modeloI.getRowCount(); i++) { modeloI.setValueAt(datos[azar.nextInt(datos.length)], i,0); } setTotales(modeloI,jLabTotalInicial, jLabTotalSegundo); jButDep.doClick(); }//GEN-LAST:event_jButInicialActionPerformed private void jButDepActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButDepActionPerformed // TODO add your handling code here: Depositos dInicial, dFinal, dTotal; dFinal = new Depositos(); for (int j = 0; j < modeloI.getRowCount(); j++) { dInicial= new Depositos( Integer.parseInt(""+modeloI.getValueAt(j, 1)), Integer.parseInt(""+modeloI.getValueAt(j, 2)), Integer.parseInt(""+modeloI.getValueAt(j, 3)), Integer.parseInt(""+modeloI.getValueAt(j, 4))); dFinal = new Depositos( Integer.parseInt(""+modeloI.getValueAt(j, 5)), Integer.parseInt(""+modeloI.getValueAt(j, 6)), Integer.parseInt(""+modeloI.getValueAt(j, 7)), Integer.parseInt(""+modeloI.getValueAt(j, 8))); dTotal = dFinal.resta(dInicial); modeloI.setValueAt(dTotal.getObolo(), j, 9); modeloI.setValueAt(dTotal.getDracma(), j, 10); modeloI.setValueAt(dTotal.getMina(), j, 11); modeloI.setValueAt(dTotal.getTalento(), j, 12); // dFin = dFin.suma(dTotal); } }//GEN-LAST:event_jButDepActionPerformed private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed // TODO add your handling code here: //Llenamos las tablas con los ejemplos dados en la asignación. modeloI.setRowCount(4); //Saldo Inicial modeloI.setValueAt("Sócrates", 0, 0); modeloI.setValueAt("Arquimedes", 1, 0); modeloI.setValueAt("Aristoteles", 2, 0); modeloI.setValueAt("Platón", 3, 0); modeloI.setValueAt(5, 0, 1); modeloI.setValueAt(1, 1, 1); modeloI.setValueAt(4, 2, 1); modeloI.setValueAt(3, 3, 1); modeloI.setValueAt(2, 0, 2); modeloI.setValueAt(98, 1, 2); modeloI.setValueAt(73, 2, 2); modeloI.setValueAt(29, 3, 2); modeloI.setValueAt(24, 0, 3); modeloI.setValueAt(57, 1, 3); modeloI.setValueAt(0, 2, 3); modeloI.setValueAt(46, 3, 3); modeloI.setValueAt(10, 0, 4); modeloI.setValueAt(25, 1, 4); modeloI.setValueAt(8, 2, 4); modeloI.setValueAt(18, 3, 4); //Saldo Final modeloI.setValueAt(3, 0, 5); modeloI.setValueAt(0, 1, 5); modeloI.setValueAt(5, 2, 5); modeloI.setValueAt(2, 3, 5); modeloI.setValueAt(68, 0, 6); modeloI.setValueAt(52, 1, 6); modeloI.setValueAt(99, 2, 6); modeloI.setValueAt(71, 3, 6); modeloI.setValueAt(33, 0, 7); modeloI.setValueAt(18, 1, 7); modeloI.setValueAt(26, 2, 7); modeloI.setValueAt(43, 3, 7); modeloI.setValueAt(14, 0, 8); modeloI.setValueAt(37, 1, 8); modeloI.setValueAt(16, 2, 8); modeloI.setValueAt(19, 3, 8); setTotales(modeloI,jLabTotalInicial, jLabTotalSegundo); jButDep.doClick(); }//GEN-LAST:event_jButton4ActionPerformed private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed OrdenAlfabetico(modeloI); //Creamos un metodo el cual le mandaremos como parametros las tres tablas. }//GEN-LAST:event_jButton6ActionPerformed private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed // TODO add your handling code here: OrdenDeposito(modeloI); }//GEN-LAST:event_jButton7ActionPerformed private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed // TODO add your handling code here: Pintar(jTab1); }//GEN-LAST:event_jButton5ActionPerformed private void jButLimActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButLimActionPerformed // TODO add your handling code here: ColorCeldas celda1 = new ColorCeldas(jTab1); for (int i = 0; i < modeloI.getRowCount(); i++) { for (int j = 0; j < modeloI.getColumnCount(); j++) { modeloI.setValueAt("", i, j); celda1.addCelda(i, j, Color.white); } } jLabTotalSegundo.setText(""); jTab1.repaint(); }//GEN-LAST:event_jButLimActionPerformed private void jSpinner1StateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_jSpinner1StateChanged // TODO add your handling code here: modeloI.setRowCount(Integer.parseInt(jSpinner1.getValue()+"")); }//GEN-LAST:event_jSpinner1StateChanged /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimmbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(PB_18131396_jFPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(PB_18131396_jFPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(PB_18131396_jFPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(PB_18131396_jFPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new PB_18131396_jFPrincipal().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButDep; private javax.swing.JButton jButInicial; private javax.swing.JButton jButLim; private javax.swing.JButton jButton4; private javax.swing.JButton jButton5; private javax.swing.JButton jButton6; private javax.swing.JButton jButton7; private javax.swing.JLabel jLabTotalInicial; private javax.swing.JLabel jLabTotalSegundo; private javax.swing.JLabel jLabTotales; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel15; private javax.swing.JLabel jLabel16; private javax.swing.JLabel jLabel17; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JSpinner jSpinner1; private javax.swing.JTable jTab1; private javax.swing.JTable jTable2; // End of variables declaration//GEN-END:variables }
true
08e35404e93c71a1da44ea81c6ff37b76252711c
Java
iyelaoi/java-asm
/asm-master/test/conform/org/objectweb/junit/NameAndTypeTest.java
UTF-8
215
1.875
2
[ "BSD-3-Clause" ]
permissive
package org.objectweb.junit; /** * desc: * author: ljt * time: 2016/5/16 10:28 */ public class NameAndTypeTest { private int x = 10; public int getX() throws Exception{ return x; } }
true
a73f162576b9f5a17a325f3ee3048b2d34345628
Java
abigail830/Diet
/diet-admin/src/main/java/com/diet/admin/message/RequestMsg.java
UTF-8
775
1.882813
2
[]
no_license
package com.diet.admin.message; import com.alibaba.fastjson.JSONObject; import java.io.Serializable; public class RequestMsg implements Serializable { /** * 开始索引,从1开始 */ private int curPage = 1; /** * 最大记录数 */ private int pageSize = 10; private JSONObject params; public int getCurPage() { return curPage; } public void setCurPage(int curPage) { this.curPage = curPage; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public JSONObject getParams() { return params; } public void setParams(JSONObject params) { this.params = params; } }
true
3817ef26030c440093ad707da1ebead4c3193829
Java
PeterJanic/trainingproject_v1.1
/training.project/src/sk/tuke/oop/aliens/DefectiveLight.java
UTF-8
336
2.59375
3
[]
no_license
package sk.tuke.oop.aliens; import java.util.Random; public class DefectiveLight extends Light { @Override public void act() { int random = (int) (Math.random()*20) + 1; if (random == 1){ this.toggle(); } else this.setElectricityFlow(true); } }
true
5621dc75684250f78c8edc4baf8e4a4408e5f4a1
Java
zhongxingyu/Seer
/Diff-Raw-Data/2/2_aab004873aa0856be1dbaf92cf77012c05e0f96d/ApplyButtonPanel/2_aab004873aa0856be1dbaf92cf77012c05e0f96d_ApplyButtonPanel_t.java
UTF-8
5,451
2.203125
2
[]
no_license
package gov.nih.nci.ncicb.cadsr.loader.ui; import java.awt.BorderLayout; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; import gov.nih.nci.ncicb.cadsr.loader.util.RunMode; import gov.nih.nci.ncicb.cadsr.loader.event.ReviewEvent; import gov.nih.nci.ncicb.cadsr.loader.event.ReviewEventType; import gov.nih.nci.ncicb.cadsr.loader.event.ReviewListener; import gov.nih.nci.ncicb.cadsr.loader.ui.tree.ReviewableUMLNode; import gov.nih.nci.ncicb.cadsr.loader.ui.tree.UMLNode; import gov.nih.nci.ncicb.cadsr.loader.ui.event.NavigationEvent; import gov.nih.nci.ncicb.cadsr.loader.ui.event.NavigationListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import gov.nih.nci.ncicb.cadsr.loader.UserSelections; import java.util.ArrayList; import java.util.List; public class ApplyButtonPanel extends JPanel implements ActionListener, PropertyChangeListener { private JCheckBox reviewButton; private JButton applyButton; static final String SAVE = "APPLY", REVIEW = "REVIEW"; private List<ReviewListener> reviewListeners = new ArrayList<ReviewListener>(); private List<PropertyChangeListener> propChangeListeners = new ArrayList<PropertyChangeListener>(); private List<NavigationListener> navigationListeners = new ArrayList<NavigationListener>(); private Editable viewPanel; private ReviewableUMLNode node; private RunMode runMode = null; public ApplyButtonPanel(Editable viewPanel, ReviewableUMLNode node) { this.viewPanel = viewPanel; this.node = node; UserSelections selections = UserSelections.getInstance(); runMode = (RunMode)(selections.getProperty("MODE")); applyButton = new JButton("Apply"); if(runMode.equals(RunMode.Reviewer)) reviewButton = new JCheckBox("<html> Model <br> Owner <br> Verified</html"); else if(runMode.equals(RunMode.Curator)) reviewButton = new JCheckBox("<html>Human<br>Verified</html>"); else { reviewButton = new JCheckBox("<html>Not<br>Available</html>"); reviewButton.setVisible(false); } reviewButton.setSelected(node.isReviewed()); reviewButton.setActionCommand(REVIEW); applyButton.setActionCommand(SAVE); applyButton.addActionListener(this); reviewButton.addActionListener(this); this.add(applyButton); this.add(reviewButton); } void update() { reviewButton.setSelected(node.isReviewed()); } public void propertyChange(PropertyChangeEvent e) { if(e.getPropertyName().equals(SAVE)) { setApplyButtonState((Boolean)e.getNewValue()); } else if(e.getPropertyName().equals(REVIEW)) { reviewButton.setEnabled((Boolean)e.getNewValue()); } } public void addNavigationListener(NavigationListener listener) { navigationListeners.add(listener); } public void actionPerformed(ActionEvent evt) { AbstractButton button = (AbstractButton)evt.getSource(); if(button.getActionCommand().equals(SAVE)) { try { viewPanel.applyPressed(); } catch (ApplyException e){ } // end of try-catch } ReviewEvent event = new ReviewEvent(); event.setUserObject(node); event.setReviewed(reviewButton.isSelected()); if(runMode.equals(RunMode.Reviewer)) { event.setType(ReviewEventType.Owner); } else if (runMode.equals(RunMode.Curator)) { event.setType(ReviewEventType.Curator); } else return; fireReviewEvent(event); if(button.getActionCommand().equals(REVIEW)) { //if item is reviewed go to next item in the tree if(reviewButton.isSelected()) { NavigationEvent goToNext = new NavigationEvent(NavigationEvent.NAVIGATE_NEXT); fireNavigationEvent(goToNext); } } } void init(boolean reviewState) { setApplyButtonState(false); reviewButton.setEnabled(reviewState); } private void fireReviewEvent(ReviewEvent event) { for(ReviewListener l : reviewListeners) l.reviewChanged(event); } public void addReviewListener(ReviewListener listener) { reviewListeners.add(listener); } private void setApplyButtonState(boolean b) { applyButton.setEnabled(b); PropertyChangeEvent evt = new PropertyChangeEvent(this, SAVE, null, b); firePropertyChangeEvent(evt); } private void firePropertyChangeEvent(PropertyChangeEvent evt) { for(PropertyChangeListener l : propChangeListeners) l.propertyChange(evt); } public void addPropertyChangeListener(PropertyChangeListener l) { propChangeListeners.add(l); } public void navigate(NavigationEvent evt) { if(applyButton.isEnabled()) { if(JOptionPane.showConfirmDialog(this, "There are unsaved changes in this concept, would you like to apply the changes now?", "Unsaved Changes", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { try { viewPanel.applyPressed(); } catch (ApplyException e){ } // end of try-catch } else { applyButton.setEnabled(false); } } } private void fireNavigationEvent(NavigationEvent event) { for(NavigationListener l : navigationListeners) l.navigate(event); } }
true
28f4391c4d0db604333749b4078f680a5d7111f3
Java
kuceraf/merchant
/exchange/src/main/java/com/fku/exchange/service/impl/dummy/MockedActiveExchangeService.java
UTF-8
1,703
2.34375
2
[]
no_license
package com.fku.exchange.service.impl.dummy; import com.fku.exchange.domain.ExchangeOrder; import com.fku.exchange.error.MerchantExchangeException; import com.fku.exchange.service.ActiveExchangeService; import com.fku.exchange.service.impl.ExchangeHelper; import lombok.extern.log4j.Log4j2; import org.knowm.xchange.dto.Order; import java.math.BigDecimal; import java.util.UUID; import static com.fku.exchange.service.impl.dummy.Constants.INSTRUMENT_LAST_PRICE; import static com.fku.exchange.service.impl.dummy.Constants.LIMIT_BID_PRICE; @Log4j2 public class MockedActiveExchangeService implements ActiveExchangeService { @Override public ExchangeOrder placeOrder(Order.OrderType orderType, BigDecimal baseCurrencyAmount, BigDecimal limitPrice) throws MerchantExchangeException { log.info("MOCKED - Placing order [orderType:{}, baseCurrencyAmount:{}, limitPrice:{}]", orderType, baseCurrencyAmount, limitPrice); return new ExchangeOrder( UUID.randomUUID().toString(), orderType, limitPrice, baseCurrencyAmount); } @Override public ExchangeOrder placeBuyOrder(BigDecimal currentBidPrice, BigDecimal counterCurrencyAmount) throws MerchantExchangeException { BigDecimal baseCurrencyAmount = ExchangeHelper.calculateBaseCurrencyAmount(counterCurrencyAmount, INSTRUMENT_LAST_PRICE); return placeOrder(Order.OrderType.BID, baseCurrencyAmount, currentBidPrice); } @Override public ExchangeOrder placeBuyOrderAtCurrentPrice(BigDecimal counterCurrencyAmount) throws MerchantExchangeException { return this.placeBuyOrder(LIMIT_BID_PRICE, counterCurrencyAmount); } }
true
31b83d3c7b55c730f0e1b859f1f1933c18ff383c
Java
Skilpad/INF562
/Jcg/Jcg/geometry/Ray_2.java
UTF-8
716
2.703125
3
[]
no_license
package Jcg.geometry; public class Ray_2 implements Ray_interface<Kernel_2> { protected Point_2 p; protected Vector_2 v; public Ray_2(Point_2 p, Vector_2 v) { this.p = p; this.v = v; } public Ray_2(Segment_2 s) { this.p = s.source; this.v = new Vector_2(s.source, s.target); } public Point_2 source() {return p; } public Vector_2 direction() {return v; } public String toString() {return p+" "+v; } public int dimension() { return 2;} public boolean equals(Ray_2 r) { return this.p.equals(r.source()) && GeometricOperations_2.collinear (new Point_2(0,0), new Point_2(v.getX(), v.getY()), new Point_2(r.direction().getX(), r.direction().getY())); } }
true
346353150f5159c6de44d6f5490955b5f6288eac
Java
isabella232/android-sdk-sources-for-api-level-1
/java/security/cert/CRLException.java
UTF-8
681
1.796875
2
[]
no_license
// Decompiled by Jad v1.5.8e2. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://kpdus.tripod.com/jad.html // Decompiler options: packimports(3) fieldsfirst ansi space // Source File Name: CRLException.java package java.security.cert; import java.security.GeneralSecurityException; public class CRLException extends GeneralSecurityException { public CRLException(String msg) { throw new RuntimeException("Stub!"); } public CRLException() { throw new RuntimeException("Stub!"); } public CRLException(String message, Throwable cause) { throw new RuntimeException("Stub!"); } public CRLException(Throwable cause) { throw new RuntimeException("Stub!"); } }
true
b15ceb574bf47a476d2b1f9ee5e7c5acdb33e2e5
Java
ramkurapati/javapracticles
/Core Java/Collections/OldDataStrutures/EnumSetDemo.java
UTF-8
769
3.421875
3
[]
no_license
package OldDataStrutures; import java.util.EnumSet; public class EnumSetDemo { enum courses{Java,C,CPP,ManualTesting,AutomaticTesting}; public static void main(String[] args) { EnumSet<courses> developers=EnumSet.of(courses.Java,courses.C,courses.CPP); EnumSet<courses> testers=EnumSet.of(courses.ManualTesting,courses.AutomaticTesting); if(developers.contains(courses.C)) { System.out.println("C language is present in developers"); } if(!testers.contains(courses.Java)) { System.out.println("java language is not present testers"); } for(courses c:developers) { System.out.println("languages present in developers "+c); } for(courses c:testers) { System.out.println("languages present in testers "+c); } } }
true
b278ec553acd4be9768d84e9311bb5f184478954
Java
azizasm/vue-spring-apps
/backend/src/main/java/com/hokenso/vuespringapps/domain/Challenges.java
UTF-8
2,152
2.578125
3
[]
no_license
package com.hokenso.vuespringapps.domain; import javax.persistence.*; @Entity @Table(name = "challenges") public class Challenges { // PrimaryKey @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String title; private String level; private String link; private String cal; private String author; private String points; private String image; protected Challenges() { } public Challenges(String title, String level, String link, String cal, String author, String points, String image) { this.title = title; this.level = level; this.link = link; this.cal = cal; this.author = author; this.points = points; this.image = image; } @Override public String toString() { return String.format( "Challenges[id=%d, title='%s', level='%s', link='%s', cal='%s', author='%s', points='%s', image='%s']", id, title, level, link, cal, author, points, image); } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getLevel() { return level; } public void setLevel(String level) { this.level = level; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public String getCal() { return cal; } public void setCal(String cal) { this.cal = cal; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getPoints() { return points; } public void setPoints(String points) { this.points = points; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } }
true
f7c8b6dc7160a0709e9602206b727fc69b31a41f
Java
ShijiaYan/PhoenixSim
/photonic_layer/src/People/Meisam/GUI/Utilities/SimulationDataBase.java
UTF-8
9,438
2.546875
3
[]
no_license
package People.Meisam.GUI.Utilities; import People.Meisam.GUI.PhoenixSim.ModulesLibrary.ExportCompleted.ExportCompleted; import People.Meisam.GUI.Utilities.ExportPlot.JavaFXFileChooser.FileChooserFX; import PhotonicElements.Utilities.MathLibraries.MoreMath; import ch.epfl.general_libraries.utils.SimpleMap; import flanagan.io.FileInput; import flanagan.io.FileOutput; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Set; /** * Created by meisam on 6/25/17. * * This class is a map of all the simulation variables that have been created during a specific simulation. * */ public class SimulationDataBase { String dataBaseName = "" ; private Map<String, SimulationVariable> dataBase ; boolean databaseChanged = false ; public SimulationDataBase(){ // initialize data-base map this.dataBase = new SimpleMap<>() ; } public SimulationDataBase(SimulationVariable... var){ // initialize data-base map this.dataBase = new SimpleMap<>() ; // add the arguments to the data base for (SimulationVariable x : var){ dataBase.put(x.getName(), x) ; } } public SimulationDataBase(ArrayList<SimulationVariable> var){ // initialize data-base map this.dataBase = new SimpleMap<>() ; // add the arguments to the data base for (SimulationVariable x : var){ dataBase.put(x.getName(), x) ; } } public void clear(){ dataBase.clear() ; } public Map<String, SimulationVariable> getDataBase(){ return dataBase ; } public String getDataBaseName(){ return dataBaseName ; } public void setDataBaseName(String name){ this.dataBaseName = name ; } public void addNewVariable(SimulationVariable var){ // removeVariable(var); dataBase.put(var.getName(), var) ; } public void addVariableMap(Map<String, String> allParameters){ for(String x : allParameters.keySet()){ double value = Double.parseDouble(allParameters.get(x)) ; if(dataBase.keySet().contains(x)){ dataBase.get(x).appendValue(value); } else{ dataBase.put(x, new SimulationVariable(x, new double[]{value})) ; } } } public ArrayList<SimulationVariable> getVariableList(){ ArrayList<SimulationVariable> list = new ArrayList<>() ; list.clear(); for(String x : dataBase.keySet()){ list.add(dataBase.get(x)) ; } return list ; } public void removeVariable(SimulationVariable var){ if(!dataBase.isEmpty() && dataBase.containsKey(var.getName())){ dataBase.remove(var.getName()) ; } } public void removeVariables(SimulationVariable... var){ for(SimulationVariable x : var){ if(!dataBase.isEmpty() && dataBase.containsKey(x.getName())){ dataBase.remove(x.getName()) ; } } } public boolean isEmpty(){ return dataBase.isEmpty() ; } public boolean variableExists(String varName){ return dataBase.containsKey(varName) ; } public boolean variableExistsFromAlias(String alias){ ArrayList<SimulationVariable> list = getVariableList() ; boolean aliasExists = false ; for(SimulationVariable x : list){ aliasExists = x.getAlias() == alias; } return aliasExists ; } public SimulationVariable getVariable(String varName){ return dataBase.get(varName) ; } public SimulationVariable getVariableFromAlias(String alias){ SimulationVariable var = null ; ArrayList<SimulationVariable> list = getVariableList() ; for(SimulationVariable x : list){ if(x.getAlias() == alias){ var = x ; } } return var ; } public double[] getVariableValues(String varName){ return getVariable(varName).getAllValues() ; } public Set<String> getAllNames(){ return dataBase.keySet() ; } public int getDataBaseSize(){ return dataBase.size() ; } public void show(){ for(String x : dataBase.keySet()){ dataBase.get(x).showFull(); } } public void saveToFile() throws IOException { FileChooserFX fc = new FileChooserFX() ; fc.setExtension("dbsim"); fc.saveFile(); if(fc.getSelectedFile() != null){ String fullPath = fc.getFilePath() ; FileOutput fout = new FileOutput(fullPath, "w") ; for(SimulationVariable x : getVariableList()){ // fout.println(x.getSaveToFileString()); x.printToFile(fout); } fout.close(); System.gc(); new ExportCompleted() ; } } @SuppressWarnings("unused") public void loadFromFile(){ // next making file chooser FileChooserFX fc = new FileChooserFX() ; fc.setExtension("dbsim"); fc.openFile(); if(fc.getSelectedFile() != null){ // first clearing database dataBase.clear(); String fullPath = fc.getFilePath() ; String name, alias, size, type ; double[] values = {} ; // next reading the file FileInput fin = new FileInput(fullPath) ; int M = fin.numberOfLines() ; // 6 is the number of lines for each simulation variable int k=0 ; while(k < M/6){ name = fin.readLine() ; alias = fin.readLine() ; size = fin.readLine() ; type = fin.readLine() ; values = getValuesFromLine(fin.readLine()) ; fin.readLine() ; // simDataBase.addNewVariable(new SimulationVariable(name, alias, values)); dataBase.put(name, new SimulationVariable(name, alias, values)) ; k++ ; } fin.close(); System.gc(); databaseChanged = true ; } else{ databaseChanged = false ; } } @SuppressWarnings("unused") public void loadFromFile(File file){ if(file != null){ // first clearing database dataBase.clear(); String fullPath = file.getAbsolutePath() ; String name, alias, size, type ; double[] values = {} ; // next reading the file FileInput fin = new FileInput(fullPath) ; int M = fin.numberOfLines() ; // 6 is the number of lines for each simulation variable int k=0 ; while(k < M/6){ name = fin.readLine() ; alias = fin.readLine() ; size = fin.readLine() ; type = fin.readLine() ; values = getValuesFromLine(fin.readLine()) ; fin.readLine() ; // simDataBase.addNewVariable(new SimulationVariable(name, alias, values)); dataBase.put(name, new SimulationVariable(name, alias, values)) ; k++ ; } fin.close(); System.gc(); databaseChanged = true ; } else{ databaseChanged = false ; } } public boolean dataBaseChanged(){ return databaseChanged ; } private double[] getValuesFromLine(String valueLine){ double[] values = {} ; List<String> allValues = Arrays.asList(valueLine.trim().split("\t")) ; int M = allValues.size() ; for (String allValue : allValues) { values = MoreMath.Arrays.append(values, Double.parseDouble(allValue)); } return values ; } // @SuppressWarnings("unused") // private String printNames(){ // String st0 = "" ; // for(String x : getAllNames()){ // st0 = x + " " ; // } // return st0 ; // } public SimulationVariable[] getAllVariables(){ int M = getDataBaseSize() ; SimulationVariable[] allVars = new SimulationVariable[M] ; for(int i=0; i<M; i++){ allVars[i] = getVariableList().get(i) ; } return allVars ; } // ************************ for diagnostic purposes ***************** // public static void main(String[] args){ // // step 1: create simulation variables // double[] x = MoreMath.linspace(-10, 10, 3) ; // SimulationVariable varX = new SimulationVariable("X var", x) ; // // double[] y = MoreMath.Arrays.Functions.abs(x) ; // SimulationVariable varY = new SimulationVariable("Y var", y) ; // // double[] z = {0 , 1} ; // SimulationVariable varZ = new SimulationVariable("Z var", z) ; // // // step 2: create simulation data base // SimulationDataBase simData = new SimulationDataBase(varX, varY) ; // simData.show() ; // //// String st = "1.2" + "\t" + "-2.3" ; //// double[] v = simData.getValuesFromLine(st) ; //// System.out.println(st); // //// double[] v = {0 , 2 , 5, 10, 100} ; //// SimulationVariable varV = new SimulationVariable("V var", v) ; //// simData.addNewVariable(varV); //// simData.show(); //// //// simData.clear(); //// simData.show(); //// //// Map<String, String> vars = new HashMap<>() ; //// vars.put("Z var", 3 +"" ) ; //// simData.addVariableMap(vars); //// simData.show(); //// vars.put("Z var", 5 + "") ; //// simData.addVariableMap(vars); //// simData.show(); // } }
true
581815c57af37211406fbe95455801a9559bd55e
Java
vhctrungnq/mlmn
/MLMN-Statistics/src/vn/com/vhc/vmsc2/statistics/dao/WkCellBlkBscDAOImpl.java
UTF-8
3,814
2.21875
2
[]
no_license
package vn.com.vhc.vmsc2.statistics.dao; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport; import vn.com.vhc.vmsc2.statistics.domain.WkCellBlkBsc; public class WkCellBlkBscDAOImpl extends SqlMapClientDaoSupport implements WkCellBlkBscDAO { /** * This method was generated by Apache iBATIS ibator. * This method corresponds to the database table WK_CELL_BLK_BSC * * @ibatorgenerated Tue Jul 05 14:51:42 ICT 2011 */ public WkCellBlkBscDAOImpl() { super(); } /** * This method was generated by Apache iBATIS ibator. * This method corresponds to the database table WK_CELL_BLK_BSC * * @ibatorgenerated Tue Jul 05 14:51:42 ICT 2011 */ public int deleteByPrimaryKey(String bscid, Integer week, Integer year) { WkCellBlkBsc key = new WkCellBlkBsc(); key.setBscid(bscid); key.setWeek(week); key.setYear(year); int rows = getSqlMapClientTemplate().delete("WK_CELL_BLK_BSC.ibatorgenerated_deleteByPrimaryKey", key); return rows; } /** * This method was generated by Apache iBATIS ibator. * This method corresponds to the database table WK_CELL_BLK_BSC * * @ibatorgenerated Tue Jul 05 14:51:42 ICT 2011 */ public void insert(WkCellBlkBsc record) { getSqlMapClientTemplate().insert("WK_CELL_BLK_BSC.ibatorgenerated_insert", record); } /** * This method was generated by Apache iBATIS ibator. * This method corresponds to the database table WK_CELL_BLK_BSC * * @ibatorgenerated Tue Jul 05 14:51:42 ICT 2011 */ public void insertSelective(WkCellBlkBsc record) { getSqlMapClientTemplate().insert("WK_CELL_BLK_BSC.ibatorgenerated_insertSelective", record); } /** * This method was generated by Apache iBATIS ibator. * This method corresponds to the database table WK_CELL_BLK_BSC * * @ibatorgenerated Tue Jul 05 14:51:42 ICT 2011 */ public WkCellBlkBsc selectByPrimaryKey(String bscid, Integer week, Integer year) { WkCellBlkBsc key = new WkCellBlkBsc(); key.setBscid(bscid); key.setWeek(week); key.setYear(year); WkCellBlkBsc record = (WkCellBlkBsc) getSqlMapClientTemplate().queryForObject("WK_CELL_BLK_BSC.ibatorgenerated_selectByPrimaryKey", key); return record; } /** * This method was generated by Apache iBATIS ibator. * This method corresponds to the database table WK_CELL_BLK_BSC * * @ibatorgenerated Tue Jul 05 14:51:42 ICT 2011 */ public int updateByPrimaryKeySelective(WkCellBlkBsc record) { int rows = getSqlMapClientTemplate().update("WK_CELL_BLK_BSC.ibatorgenerated_updateByPrimaryKeySelective", record); return rows; } /** * This method was generated by Apache iBATIS ibator. * This method corresponds to the database table WK_CELL_BLK_BSC * * @ibatorgenerated Tue Jul 05 14:51:42 ICT 2011 */ public int updateByPrimaryKey(WkCellBlkBsc record) { int rows = getSqlMapClientTemplate().update("WK_CELL_BLK_BSC.ibatorgenerated_updateByPrimaryKey", record); return rows; } @SuppressWarnings("unchecked") public List<WkCellBlkBsc> filter(String bscid, Integer startWeek, Integer startYear, Integer endWeek, Integer endYear) { Map<String, String> map = new HashMap<String, String>(); map.put("bscid", bscid); map.put("startWeek", Integer.toString(startWeek)); map.put("endWeek", Integer.toString(endWeek)); map.put("startYear", Integer.toString(startYear)); map.put("endYear", Integer.toString(endYear)); return getSqlMapClientTemplate().queryForList("WK_CELL_BLK_BSC.filter", map); } }
true
06e4821d81c1526621ed1b40227bbfc0cabdb148
Java
un-knower/dataExport
/dgDataExport/src/com/zero/service/StWasRService.java
UTF-8
258
1.53125
2
[]
no_license
package com.zero.service; import java.util.Date; import java.util.List; import com.zero.entity.StWasR; public interface StWasRService extends BaseService<StWasR, Long> { List<StWasR> findList( Date beginDate, Integer first, Integer count); }
true
365ab95d44682610fb4dade7b10bdfbae1473153
Java
emjironal/Proyecto_1_Desarrollo_Apps_Moviles
/BreakFoodApp/app/src/main/java/com/example/sergio/breakfoodapp/MainActivity.java
UTF-8
6,897
1.578125
2
[]
no_license
package com.example.sergio.breakfoodapp; import android.content.Intent; import android.database.ContentObservable; import android.os.StrictMode; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.TextView; import android.widget.Toast; import com.facebook.FacebookSdk; import com.facebook.appevents.AppEventsLogger; import com.facebook.CallbackManager; import com.facebook.FacebookCallback; import com.facebook.FacebookException; import com.example.sergio.breakfoodapp.http.GestorGetRequest; import com.example.sergio.breakfoodapp.http.GestorPostRequest; import com.example.sergio.breakfoodapp.http.LectorHttpResponse; import com.example.sergio.breakfoodapp.model.Restaurant; import com.facebook.login.LoginResult; import com.facebook.login.widget.LoginButton; import com.mixpanel.android.mpmetrics.MixpanelAPI; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private Button btnEnter; private TextView txtSignUp, txtRecuperar; private MixpanelAPI mixpanelAPI; private EditText correo,contrasena; private CallbackManager callbackManager; LoginButton loginButton; public static final String MIXPANEL_TOKEN = "2e8bdc478fb999b0ffdfb0a8b06673ff"; //TODO: Agregar LocatioPicker para esa pantalla @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_inicio); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); FacebookSdk.sdkInitialize(getApplicationContext()); AppEventsLogger.activateApp(this); correo = (EditText)findViewById(R.id.etCorreoInicio); contrasena = (EditText)findViewById(R.id.etContraInicio); mixpanelAPI = MixpanelAPI.getInstance(getApplicationContext(), MIXPANEL_TOKEN); mixpanelAPI.track("Login Activity"); mixpanelAPI.flush(); btnEnter = (Button)findViewById(R.id.btInicioSesion); //apunta mi variable Button al botón del activity btnEnter.setOnClickListener(new View.OnClickListener() { //aquí le agrega el evento que "escucha" el click @Override public void onClick(View v) { inicio(); } }); txtSignUp=(TextView)findViewById(R.id.txtInicioRegistro); txtSignUp.setOnClickListener(signUpListener); txtRecuperar=(TextView)findViewById(R.id.txtInicioRecuperar); txtRecuperar.setOnClickListener(recuperar); callbackManager = CallbackManager.Factory.create(); loginButton = (LoginButton) findViewById(R.id.login_button); loginButton.setReadPermissions("email"); // If using in a fragment //loginButton.setFragment(); // Callback registration loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult loginResult) { goMainScreen(); } @Override public void onCancel() { Toast.makeText(getApplicationContext(), R.string.error_field_required, Toast.LENGTH_SHORT).show(); } @Override public void onError(FacebookException exception) { Toast.makeText(getApplicationContext(), R.string.error_field_required, Toast.LENGTH_SHORT).show(); } }); } private void goMainScreen(){ Intent intent = new Intent(this, BuscadorActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_CLEAR_TASK| Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } protected void onActivityResult(int requestCode, int resultCode, Intent data){ super.onActivityResult(requestCode, resultCode, data); callbackManager.onActivityResult(requestCode,resultCode,data); } @Override protected void onDestroy() { mixpanelAPI.flush(); super.onDestroy(); } public View.OnClickListener signUpListener = new View.OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub startActivity(new Intent(MainActivity.this,RegistroActivity.class)); } }; public void signWithFacebook(View view){ } public View.OnClickListener recuperar = new View.OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub startActivity(new Intent(MainActivity.this,ChangePasswordActivity.class)); } }; public void inicio(){ String url = "https://appetyte.herokuapp.com/android/login"; List<NameValuePair> nameValuePairs = new ArrayList<>(); nameValuePairs.add(new BasicNameValuePair("email", correo.getText().toString())); nameValuePairs.add(new BasicNameValuePair("password", contrasena.getText().toString())); HttpResponse response = GestorPostRequest.postData(url, nameValuePairs); String resultStr = LectorHttpResponse.leer(response); Log.i("resultado", resultStr); if(resultStr.equals("[]")){ Toast.makeText(this, "El usuario no esta registrado", Toast.LENGTH_SHORT).show(); } else { try { JSONArray jsonArray = new JSONArray(resultStr); JSONObject jsonObject = jsonArray.getJSONObject(0); Controller.getInstance().setCorreo(jsonObject.getString("email")); Controller.getInstance().setUserID(jsonObject.getInt("iduser")); Controller.getInstance().setUsername(jsonObject.getString("username")); //Crea el intent (nueva ventana) Intent newScreen = new Intent(MainActivity.this, BuscadorActivity.class); //Inicia la nueva ventana startActivity(newScreen); } catch (JSONException e) { Log.e("Error", e.getMessage()); } } } public void printMessage(String message) { Toast.makeText(getApplicationContext(),message,Toast.LENGTH_LONG).show(); } }
true
06ba2d1548fb58db2402a74268313a9b8e85c966
Java
lyltsh/springBootChapter9
/src/main/java/com/springboot/javaee/chapter9/callable/GuavaFutureDemo.java
UTF-8
1,591
3.421875
3
[]
no_license
package com.springboot.javaee.chapter9.callable; import com.google.common.util.concurrent.*; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; /** * @author: leiyulin * @description: * @date:2018/11/2210:27 PM */ public class GuavaFutureDemo { public static void main(String[] args) throws Exception { long start = System.currentTimeMillis(); ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor()); ListenableFuture<Integer> future = service.submit(new Callable<Integer>() { @Override public Integer call() throws Exception { System.out.println("等待耗时操作....."); timeConsuming(); return 100; } }); Futures.addCallback(future, new FutureCallback<Integer>() { @Override public void onSuccess(Integer result) { System.out.println("计算结果:" + result); } @Override public void onFailure(Throwable t) { System.out.println("异步处理失败," + t); } }); System.out.println("主线程运算耗时:" + (System.currentTimeMillis() - start) + " ms"); new CountDownLatch(1).await();//不让守护线程退出 } private static void timeConsuming() { try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } } }
true
5596fff91204b349719ad1b6c02dc088ea11b02a
Java
marlonhenrys/java-algorithms
/Tis3/src/application/BancoDeDados.java
ISO-8859-2
9,190
2.796875
3
[]
no_license
package application; import java.sql.*; import java.util.ArrayList; import javax.swing.JOptionPane; public class BancoDeDados { private Connection connection = null; private Statement statement = null; private ResultSet resultset = null; private static int logado; private static String secDev, secCli, secDiv, secHist; public void conectar() { String servidor = "jdbc:mysql://localhost:3306/tis?useTimezone=true&serverTimezone=UTC"; String usuario = "root"; String senha = "tis3"; String driver = "com.mysql.cj.jdbc.Driver"; try { Class.forName(driver); this.connection = DriverManager.getConnection(servidor, usuario, senha); this.statement = this.connection.createStatement(); } catch (Exception e) { System.out.println("Erro: " + e.getMessage()); } } public boolean estaConectado() { if (this.connection != null) return true; else return false; } public String getInfunc(String op1) { try { String retorno; this.statement = this.connection.createStatement(); String querry = "SELECT * from funcionario where idFunc = " + logado + ";"; this.resultset = this.statement.executeQuery(querry); if (this.resultset.next()) { retorno = this.resultset.getString(op1); return retorno; } } catch (Exception e) { System.out.println("Erro: " + e.getMessage()); } return null; } public String getInfDev(String op1, String op2) { try { String retorno; this.statement = this.connection.createStatement(); String querry = "SELECT * from devedor where "+op2+" = '" + secDev + "';"; this.resultset = this.statement.executeQuery(querry); if (this.resultset.next()) { retorno = this.resultset.getString(op1); return retorno; } } catch (Exception e) { System.out.println("Erro: " + e.getMessage()); } return null; } public String getInfCli(String op1, String op2) { try { String retorno; this.statement = this.connection.createStatement(); String querry = "SELECT * from cliente where "+op2+" = '" + secCli + "';"; this.resultset = this.statement.executeQuery(querry); if (this.resultset.next()) { retorno = this.resultset.getString(op1); return retorno; } } catch (Exception e) { System.out.println("Erro: " + e.getMessage()); } return null; } public String getInfHist(String op1) { try { String retorno; this.statement = this.connection.createStatement(); String querry = "SELECT * from historico where idhistorico = " + secHist + ";"; this.resultset = this.statement.executeQuery(querry); if (this.resultset.next()) { retorno = this.resultset.getString(op1); return retorno; } } catch (Exception e) { System.out.println("Erro: " + e.getMessage()); } return null; } public String getInfDiv(String op1) { try { String retorno; this.statement = this.connection.createStatement(); String querry = "SELECT * from divida where iddivida = " + secDiv + ";"; this.resultset = this.statement.executeQuery(querry); if (this.resultset.next()) { retorno = this.resultset.getString(op1); return retorno; } } catch (Exception e) { System.out.println("Erro: " + e.getMessage()); } return null; } public ArrayList<String> listarClientes(String coluna, String valor) { try { ArrayList<String> result = new ArrayList<String>(); String querry = "SELECT * from cliente order by idCli"; this.resultset = this.statement.executeQuery(querry); this.statement = this.connection.createStatement(); while (this.resultset.next()) { if (this.resultset.getString("" + coluna + "").equals(valor)) result.add("ID: " + this.resultset.getString("idCli") + "\t\tNome: "+ this.resultset.getString("nomeCli") + "\t\tCPF/CNPJ: " + this.resultset.getString("identidadeCli") + "\t\tTelefone: " + this.resultset.getString("telCli")+ "\t\tE-mail: "+ this.resultset.getString("emailCli")); } return result; } catch (Exception e) { System.out.println("Erro: " + e.getMessage()); } return null; } public ArrayList<String> listarDevedores(String coluna, String valor) { try { ArrayList<String> result = new ArrayList<String>(); String querry = "SELECT * from devedor order by idDev"; this.resultset = this.statement.executeQuery(querry); this.statement = this.connection.createStatement(); while (this.resultset.next()) { if (this.resultset.getString("" + coluna + "").equals(valor)) result.add("ID: " + this.resultset.getString("idDev") + "\t\tNome: "+ this.resultset.getString("nomeDev") + "\t\tCPF/CNPJ: " + this.resultset.getString("identidadeDev") + "\t\tTelefone: " + this.resultset.getString("telDev")+ "\t\tE-mail: "+ this.resultset.getString("emailDev")); } return result; } catch (Exception e) { System.out.println("Erro: " + e.getMessage()); } return null; } public boolean login(String user, String senha) { try { this.statement = this.connection.createStatement(); String querry = "SELECT * from funcionario where usuario = '" + user + "' and senhaFunc = '" + senha + "';"; this.resultset = this.statement.executeQuery(querry); if (this.resultset.next()) { setLogado(this.resultset.getString("idFunc")); return true; } else JOptionPane.showMessageDialog(null, "Usuro ou senha invlidos"); } catch (Exception e) { System.out.println("Erro: " + e.getMessage()); } return false; } public boolean inserirCliente(String nome, String identidade, String email, String tel, String endereco) { try { String querry = "insert into cliente (nomeCli, identidadeCli, emailCli, telCli, endCli) values ('" + nome + "', '" + identidade + "', '" + email + "', '" + tel + "', '" + endereco + "');"; this.statement.executeUpdate(querry); return true; } catch (Exception e) { JOptionPane.showMessageDialog(null, "J existe este cliente."); return false; } } public boolean inserirDevedor(String nome, String identidade, String email, String tel, String endereco) { try { String querry = "insert into devedor (nomeDev, emailDev, telDev, identidadeDev, endDev) values ('" + nome + "', '" + email + "', '" + tel + "', '" + identidade + "', '" + endereco + "');"; this.statement.executeUpdate(querry); return true; } catch (Exception e) { JOptionPane.showMessageDialog(null, "J existe este devedor."); return false; } } public boolean inserirFuncionario(String user, String nome, String senha, int tipo, String cpf) { try { String querry = "insert into funcionario (nomeFunc, senhaFunc, tipoFunc, cpfFunc, usuario) values ('" + nome + "', '" + senha + "', '" + tipo + "', '" + cpf + "', '" + user + "');"; this.statement.executeUpdate(querry); return true; } catch (Exception e) { JOptionPane.showMessageDialog(null, "J existe este usurio."); return false; } } public void alterarCli(String nome, String identidade, String email, String tel, String end, String id) { try { String querry = "update cliente set nomeCli = '" + nome + "', identidadeCli = '" + identidade + "', emailCli = '" + email + "', telCli = '" + tel + "', endCli = '" + end + "' where idCli = " + id + ";"; this.statement.executeUpdate(querry); JOptionPane.showMessageDialog(null, "Atualizado com sucesso"); } catch (Exception e) { System.out.println("Erro: " + e.getMessage()); JOptionPane.showMessageDialog(null, "Erro ao atualizar"); } } public void alterarDev(String nome, String identidade, String email, String tel, String end, String id) { try { String querry = "update devedor set nomeDev = '" + nome + "', identidadeDev = '" + identidade + "', emailDev = '" + email + "', telDev = '" + tel + "', endDev = '" + end + "' where idDev = " + id + ";"; this.statement.executeUpdate(querry); JOptionPane.showMessageDialog(null, "Atualizado com sucesso"); } catch (Exception e) { System.out.println("Erro: " + e.getMessage()); JOptionPane.showMessageDialog(null, "Erro ao atualizar"); } } public void alterarSenha(String user, String novaSenha) { try { String querry = "update funcionario set senhaFunc = '" + novaSenha + "' where usuario = '" + user + "';"; this.statement.executeUpdate(querry); } catch (Exception e) { System.out.println("Erro: " + e.getMessage()); } } public void alterarTipo(String cpf, int novoTipo) { try { String querry = "update funcionario set tipoFunc = '" + novoTipo + "' where cpfFunc = '" + cpf + "';"; this.statement.executeUpdate(querry); } catch (Exception e) { System.out.println("Erro: " + e.getMessage()); } } public static int getLogado() { return logado; } private static void setLogado(String logado) { BancoDeDados.logado = Integer.parseInt(logado); } public static void setSecDev(String secDev) { BancoDeDados.secDev = secDev; } public static void setSecCli(String secCli) { BancoDeDados.secCli = secCli; } // private static void setSecDiv(String secDiv) { // BancoDeDados.secDiv = Integer.parseInt(secDiv); // } // // private static void setSecHist(String secHist) { // BancoDeDados.secHist = Integer.parseInt(secHist); // } }
true
014b957542f4908f204347bf64f362fe081e4426
Java
liu13chao/freeline
/android-studio-plugin/src/models/FreelineStatus.java
UTF-8
2,420
2.203125
2
[ "BSD-3-Clause" ]
permissive
package models; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import utils.FreelineUtil; import utils.LogUtil; import java.io.File; import java.util.Collection; import java.util.Timer; import java.util.TimerTask; /** * Created by pengwei on 2016/10/31. */ public class FreelineStatus { Collection<VirtualFile> gradleBuildFiles; boolean existClasspath = false; private VirtualFile classpathFile; boolean existPlugin = false; private VirtualFile pluginFile; // mac下只有freeline文件夹 + freeline.py , win下有freeline.py + freeline/ + freeline_core/ boolean existFreelineCore = false; public FreelineStatus setClasspathFile(VirtualFile classpathFile) { this.classpathFile = classpathFile; if (classpathFile != null) { existClasspath = true; } return this; } public FreelineStatus setPluginFile(VirtualFile pluginFile) { this.pluginFile = pluginFile; if (pluginFile != null) { existPlugin = true; } return this; } public FreelineStatus setExistFreelineCore(boolean existFreelineCore) { this.existFreelineCore = existFreelineCore; return this; } public boolean isExistClasspath() { return existClasspath; } public VirtualFile getClasspathFile() { return classpathFile; } public boolean isExistPlugin() { return existPlugin; } public VirtualFile getPluginFile() { return pluginFile; } public boolean isExistFreelineCore() { return existFreelineCore; } /** * 是否初始化Freeline * 满足一下三个条件 * 1. 存在classpath 'com.antfortune.freeline:gradle:*' * 2. 存在apply plugin: 'com.antfortune.freeline' * 3. 存在freeline文件夹、freeline.py * * @return */ public boolean hasInitFreeline() { LogUtil.d("existClasspath=%s,existPlugin=%s,existFreelineCore=%s", existClasspath, existPlugin, existFreelineCore); return existClasspath && existPlugin && existFreelineCore; } public Collection<VirtualFile> getGradleBuildFiles() { return gradleBuildFiles; } public FreelineStatus setGradleBuildFiles(Collection<VirtualFile> gradleBuildFiles) { this.gradleBuildFiles = gradleBuildFiles; return this; } }
true
4f6cc22193e28abdeb5df7293c0458c8d4b4e786
Java
madhurimav14/BattleJavaCode
/Dragon.java
UTF-8
271
3.03125
3
[]
no_license
public class Dragon implements Battle{ public String getName() { return "Dragon"; } public String battle(Battle battleWith) { if(battleWith.getName().equals("Dragon")){ return "Tied"; } return battleWith.getName().equals("Wearvolve")?"Lost":"Won"; } }
true
8ceadc79560549a97de6d20327f47e854ca567be
Java
moobsky/spring-abc
/src/main/java/xyz/springabc/web/listener/SessionListener.java
UTF-8
1,031
2.078125
2
[ "MIT" ]
permissive
package xyz.springabc.web.listener; import javax.servlet.http.HttpSessionAttributeListener; import javax.servlet.http.HttpSessionBindingEvent; /** * Application Lifecycle Listener implementation class SessionListener * */ public class SessionListener implements HttpSessionAttributeListener { /** * Default constructor. */ public SessionListener() { // TODO Auto-generated constructor stub } /** * @see HttpSessionAttributeListener#attributeAdded(HttpSessionBindingEvent) */ public void attributeAdded(HttpSessionBindingEvent event) { } /** * @see HttpSessionAttributeListener#attributeRemoved(HttpSessionBindingEvent) */ public void attributeRemoved(HttpSessionBindingEvent event) { // TODO Auto-generated method stub } /** * @see HttpSessionAttributeListener#attributeReplaced(HttpSessionBindingEvent) */ public void attributeReplaced(HttpSessionBindingEvent event) { // TODO Auto-generated method stub } }
true
3e1ca4cfd08b73d875d34b0ff7a32059e9c31531
Java
yulonglong/A-Typist-s-Calendar
/src/com/licensetokil/atypistcalendar/gcal/UtilitiesJUnitTest.java
UTF-8
17,544
2.5
2
[]
no_license
//@author A0097142E package com.licensetokil.atypistcalendar.gcal; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.util.HashMap; import org.junit.Test; import com.google.gson.JsonObject; import com.google.gson.JsonParser; public class UtilitiesJUnitTest { @Test public void test_json_get_noArguments_noAdditionalHeaders() { try { String reply = Utilities.sendJsonHttpsRequest( "https://httpbin.org/get", Utilities.REQUEST_METHOD_GET, Utilities.EMPTY_ADDITIONAL_HEADERS, Utilities.EMPTY_REQUEST_BODY); JsonObject jsonReply = (JsonObject)new JsonParser().parse(reply); assertEquals("http://httpbin.org/get", jsonReply.get("url").getAsString()); assertEquals("{}", jsonReply.get("args").toString()); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void test_json_get_noArguments_withAdditionalHeaders() { try { HashMap<String, String> headers = new HashMap<>(); headers.put("Custom-Header-One", "tree"); headers.put("Custom-Header-Two", "rubber"); String reply = Utilities.sendJsonHttpsRequest( "https://httpbin.org/get", Utilities.REQUEST_METHOD_GET, headers, Utilities.EMPTY_REQUEST_BODY); JsonObject jsonReply = (JsonObject)new JsonParser().parse(reply); assertEquals("http://httpbin.org/get", jsonReply.get("url").getAsString()); assertEquals("tree", jsonReply.getAsJsonObject("headers").get("Custom-Header-One").getAsString()); assertEquals("rubber", jsonReply.getAsJsonObject("headers").get("Custom-Header-Two").getAsString()); assertEquals("{}", jsonReply.get("args").toString()); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void test_json_post_noArguments_noAdditionalHeaders() { try { String reply = Utilities.sendJsonHttpsRequest( "https://httpbin.org/post", Utilities.REQUEST_METHOD_POST, Utilities.EMPTY_ADDITIONAL_HEADERS, Utilities.EMPTY_REQUEST_BODY); JsonObject jsonReply = (JsonObject)new JsonParser().parse(reply); assertEquals("http://httpbin.org/post", jsonReply.get("url").getAsString()); assertEquals("{}", jsonReply.get("args").toString()); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void test_json_post_noArguments_withAdditionalHeaders() { try { HashMap<String, String> headers = new HashMap<>(); headers.put("Custom-Header-One", "tree"); headers.put("Custom-Header-Two", "rubber"); String reply = Utilities.sendJsonHttpsRequest( "https://httpbin.org/post", Utilities.REQUEST_METHOD_POST, headers, Utilities.EMPTY_REQUEST_BODY); JsonObject jsonReply = (JsonObject)new JsonParser().parse(reply); assertEquals("http://httpbin.org/post", jsonReply.get("url").getAsString()); assertEquals("tree", jsonReply.getAsJsonObject("headers").get("Custom-Header-One").getAsString()); assertEquals("rubber", jsonReply.getAsJsonObject("headers").get("Custom-Header-Two").getAsString()); assertEquals("{}", jsonReply.get("args").toString()); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void test_json_post_withArguments_noAdditionalHeaders() { try { JsonObject leveltwo = new JsonObject(); leveltwo.addProperty("leveltwo", "volume"); JsonObject body = new JsonObject(); body.add("levelone", leveltwo); body.addProperty("fire", "water"); String reply = Utilities.sendJsonHttpsRequest( "https://httpbin.org/post", Utilities.REQUEST_METHOD_POST, Utilities.EMPTY_ADDITIONAL_HEADERS, body); JsonObject jsonReply = (JsonObject)new JsonParser().parse(reply); assertEquals("http://httpbin.org/post", jsonReply.get("url").getAsString()); if (!jsonReply.getAsJsonObject("json").equals(body)) { fail("Body not matched."); } } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void test_json_post_withArguments_withAdditionalHeaders() { try { HashMap<String, String> headers = new HashMap<>(); headers.put("Custom-Header-One", "tree"); headers.put("Custom-Header-Two", "rubber"); JsonObject leveltwo = new JsonObject(); leveltwo.addProperty("leveltwo", "volume"); JsonObject body = new JsonObject(); body.add("levelone", leveltwo); body.addProperty("fire", "water"); String reply = Utilities.sendJsonHttpsRequest( "https://httpbin.org/post", Utilities.REQUEST_METHOD_POST, headers, body); JsonObject jsonReply = (JsonObject)new JsonParser().parse(reply); assertEquals("http://httpbin.org/post", jsonReply.get("url").getAsString()); assertEquals("tree", jsonReply.getAsJsonObject("headers").get("Custom-Header-One").getAsString()); assertEquals("rubber", jsonReply.getAsJsonObject("headers").get("Custom-Header-Two").getAsString()); if (!jsonReply.getAsJsonObject("json").equals(body)) { fail("Body not matched."); } } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void test_json_delete_noArguments_noAdditionalHeaders() { try { String reply = Utilities.sendJsonHttpsRequest( "https://httpbin.org/delete", Utilities.REQUEST_METHOD_DELETE, Utilities.EMPTY_ADDITIONAL_HEADERS, Utilities.EMPTY_REQUEST_BODY); JsonObject jsonReply = (JsonObject)new JsonParser().parse(reply); assertEquals("http://httpbin.org/delete", jsonReply.get("url").getAsString()); assertEquals("{}", jsonReply.get("args").toString()); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void test_json_delete_noArguments_withAdditionalHeaders() { try { HashMap<String, String> headers = new HashMap<>(); headers.put("Custom-Header-One", "tree"); headers.put("Custom-Header-Two", "rubber"); String reply = Utilities.sendJsonHttpsRequest( "https://httpbin.org/delete", Utilities.REQUEST_METHOD_DELETE, headers, Utilities.EMPTY_REQUEST_BODY); JsonObject jsonReply = (JsonObject)new JsonParser().parse(reply); assertEquals("http://httpbin.org/delete", jsonReply.get("url").getAsString()); assertEquals("tree", jsonReply.getAsJsonObject("headers").get("Custom-Header-One").getAsString()); assertEquals("rubber", jsonReply.getAsJsonObject("headers").get("Custom-Header-Two").getAsString()); assertEquals("{}", jsonReply.get("args").toString()); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void test_json_put_noArguments_noAdditionalHeaders() { try { String reply = Utilities.sendJsonHttpsRequest( "https://httpbin.org/put", Utilities.REQUEST_METHOD_PUT, Utilities.EMPTY_ADDITIONAL_HEADERS, Utilities.EMPTY_REQUEST_BODY); JsonObject jsonReply = (JsonObject)new JsonParser().parse(reply); assertEquals("http://httpbin.org/put", jsonReply.get("url").getAsString()); assertEquals("{}", jsonReply.get("args").toString()); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void test_json_put_noArguments_withAdditionalHeaders() { try { HashMap<String, String> headers = new HashMap<>(); headers.put("Custom-Header-One", "tree"); headers.put("Custom-Header-Two", "rubber"); String reply = Utilities.sendJsonHttpsRequest( "https://httpbin.org/put", Utilities.REQUEST_METHOD_PUT, headers, Utilities.EMPTY_REQUEST_BODY); JsonObject jsonReply = (JsonObject)new JsonParser().parse(reply); assertEquals("http://httpbin.org/put", jsonReply.get("url").getAsString()); assertEquals("tree", jsonReply.getAsJsonObject("headers").get("Custom-Header-One").getAsString()); assertEquals("rubber", jsonReply.getAsJsonObject("headers").get("Custom-Header-Two").getAsString()); assertEquals("{}", jsonReply.get("args").toString()); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void test_json_put_withArguments_noAdditionalHeaders() { try { JsonObject leveltwo = new JsonObject(); leveltwo.addProperty("leveltwo", "volume"); JsonObject body = new JsonObject(); body.add("levelone", leveltwo); body.addProperty("fire", "water"); String reply = Utilities.sendJsonHttpsRequest( "https://httpbin.org/put", Utilities.REQUEST_METHOD_PUT, Utilities.EMPTY_ADDITIONAL_HEADERS, body); JsonObject jsonReply = (JsonObject)new JsonParser().parse(reply); assertEquals("http://httpbin.org/put", jsonReply.get("url").getAsString()); if (!jsonReply.getAsJsonObject("json").equals(body)) { fail("Body not matched."); } } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void test_json_put_withArguments_withAdditionalHeaders() { try { HashMap<String, String> headers = new HashMap<>(); headers.put("Custom-Header-One", "tree"); headers.put("Custom-Header-Two", "rubber"); JsonObject leveltwo = new JsonObject(); leveltwo.addProperty("leveltwo", "volume"); JsonObject body = new JsonObject(); body.add("levelone", leveltwo); body.addProperty("fire", "water"); String reply = Utilities.sendJsonHttpsRequest( "https://httpbin.org/put", Utilities.REQUEST_METHOD_PUT, headers, body); JsonObject jsonReply = (JsonObject)new JsonParser().parse(reply); assertEquals("http://httpbin.org/put", jsonReply.get("url").getAsString()); assertEquals("tree", jsonReply.getAsJsonObject("headers").get("Custom-Header-One").getAsString()); assertEquals("rubber", jsonReply.getAsJsonObject("headers").get("Custom-Header-Two").getAsString()); if (!jsonReply.getAsJsonObject("json").equals(body)) { fail("Body not matched."); } } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void test_formUrlencoded_post_noArguments_noAdditionalHeaders() { try { String reply = Utilities.sendUrlencodedFormHttpsRequest( "https://httpbin.org/post", Utilities.REQUEST_METHOD_POST, Utilities.EMPTY_ADDITIONAL_HEADERS, Utilities.EMPTY_FORM_PARAMETERS); JsonObject jsonReply = (JsonObject)new JsonParser().parse(reply); assertEquals("http://httpbin.org/post", jsonReply.get("url").getAsString()); assertEquals("{}", jsonReply.get("args").toString()); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void test_formUrlencoded_post_noArguments_withAdditionalHeaders() { try { HashMap<String, String> headers = new HashMap<>(); headers.put("Custom-Header-One", "tree"); headers.put("Custom-Header-Two", "rubber"); String reply = Utilities.sendUrlencodedFormHttpsRequest( "https://httpbin.org/post", Utilities.REQUEST_METHOD_POST, headers, Utilities.EMPTY_FORM_PARAMETERS); JsonObject jsonReply = (JsonObject)new JsonParser().parse(reply); assertEquals("http://httpbin.org/post", jsonReply.get("url").getAsString()); assertEquals("tree", jsonReply.getAsJsonObject("headers").get("Custom-Header-One").getAsString()); assertEquals("rubber", jsonReply.getAsJsonObject("headers").get("Custom-Header-Two").getAsString()); assertEquals("{}", jsonReply.get("args").toString()); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void test_formUrlencoded_post_withArguments_noAdditionalHeaders() { try { HashMap<String, String> parameters = new HashMap<>(); parameters.put("argone", "helloworld"); parameters.put("argtwo", "cs2103t"); String reply = Utilities.sendUrlencodedFormHttpsRequest( "https://httpbin.org/post", Utilities.REQUEST_METHOD_POST, Utilities.EMPTY_ADDITIONAL_HEADERS, parameters); JsonObject jsonReply = (JsonObject)new JsonParser().parse(reply); assertEquals("http://httpbin.org/post", jsonReply.get("url").getAsString()); assertEquals("helloworld", jsonReply.get("form").getAsJsonObject().get("argone").getAsString()); assertEquals("cs2103t", jsonReply.get("form").getAsJsonObject().get("argtwo").getAsString()); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void test_formUrlencoded_post_withArguments_withAdditionalHeaders() { try { HashMap<String, String> headers = new HashMap<>(); headers.put("Custom-Header-One", "tree"); headers.put("Custom-Header-Two", "rubber"); HashMap<String, String> parameters = new HashMap<>(); parameters.put("argone", "helloworld"); parameters.put("argtwo", "cs2103t"); String reply = Utilities.sendUrlencodedFormHttpsRequest( "https://httpbin.org/post", Utilities.REQUEST_METHOD_POST, headers, parameters); JsonObject jsonReply = (JsonObject)new JsonParser().parse(reply); assertEquals("http://httpbin.org/post", jsonReply.get("url").getAsString()); assertEquals("tree", jsonReply.getAsJsonObject("headers").get("Custom-Header-One").getAsString()); assertEquals("rubber", jsonReply.getAsJsonObject("headers").get("Custom-Header-Two").getAsString()); assertEquals("helloworld", jsonReply.get("form").getAsJsonObject().get("argone").getAsString()); assertEquals("cs2103t", jsonReply.get("form").getAsJsonObject().get("argtwo").getAsString()); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void test_formUrlencoded_get_noArguments_noAdditionalHeaders() { try { String reply = Utilities.sendUrlencodedFormHttpsRequest( "https://httpbin.org/get", Utilities.REQUEST_METHOD_GET, Utilities.EMPTY_ADDITIONAL_HEADERS, Utilities.EMPTY_FORM_PARAMETERS); JsonObject jsonReply = (JsonObject)new JsonParser().parse(reply); assertEquals("http://httpbin.org/get", jsonReply.get("url").getAsString()); assertEquals("{}", jsonReply.get("args").toString()); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void test_formUrlencoded_get_noArguments_withAdditionalHeaders() { try { HashMap<String, String> headers = new HashMap<>(); headers.put("Custom-Header-One", "tree"); headers.put("Custom-Header-Two", "rubber"); String reply = Utilities.sendUrlencodedFormHttpsRequest( "https://httpbin.org/get", Utilities.REQUEST_METHOD_GET, headers, Utilities.EMPTY_FORM_PARAMETERS); JsonObject jsonReply = (JsonObject)new JsonParser().parse(reply); assertEquals("http://httpbin.org/get", jsonReply.get("url").getAsString()); assertEquals("tree", jsonReply.getAsJsonObject("headers").get("Custom-Header-One").getAsString()); assertEquals("rubber", jsonReply.getAsJsonObject("headers").get("Custom-Header-Two").getAsString()); assertEquals("{}", jsonReply.get("args").toString()); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void test_formUrlencoded_get_withArguments_noAdditionalHeaders() { try { HashMap<String, String> parameters = new HashMap<>(); parameters.put("argone", "helloworld"); parameters.put("argtwo", "cs2103t"); String reply = Utilities.sendUrlencodedFormHttpsRequest( "https://httpbin.org/get", Utilities.REQUEST_METHOD_GET, Utilities.EMPTY_ADDITIONAL_HEADERS, parameters); JsonObject jsonReply = (JsonObject)new JsonParser().parse(reply); assertEquals("http://httpbin.org/get", jsonReply.get("url").getAsString().substring(0, 22)); assertEquals("helloworld", jsonReply.get("args").getAsJsonObject().get("argone").getAsString()); assertEquals("cs2103t", jsonReply.get("args").getAsJsonObject().get("argtwo").getAsString()); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void test_formUrlencoded_get_withArguments_withAdditionalHeaders() { try { HashMap<String, String> headers = new HashMap<>(); headers.put("Custom-Header-One", "tree"); headers.put("Custom-Header-Two", "rubber"); HashMap<String, String> parameters = new HashMap<>(); parameters.put("argone", "helloworld"); parameters.put("argtwo", "cs2103t"); String reply = Utilities.sendUrlencodedFormHttpsRequest( "https://httpbin.org/get", Utilities.REQUEST_METHOD_GET, headers, parameters); JsonObject jsonReply = (JsonObject)new JsonParser().parse(reply); assertEquals("http://httpbin.org/get", jsonReply.get("url").getAsString().substring(0, 22)); assertEquals("tree", jsonReply.getAsJsonObject("headers").get("Custom-Header-One").getAsString()); assertEquals("rubber", jsonReply.getAsJsonObject("headers").get("Custom-Header-Two").getAsString()); assertEquals("helloworld", jsonReply.get("args").getAsJsonObject().get("argone").getAsString()); assertEquals("cs2103t", jsonReply.get("args").getAsJsonObject().get("argtwo").getAsString()); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } }
true
0055ef537ed54131b0bafdddb4832d1d51fef06a
Java
pokotyamu/BINGO
/src/Bingo/Bingo.java
UTF-8
3,700
3.09375
3
[]
no_license
package Bingo; import java.util.ArrayList; import java.util.Random; class Bingo { ArrayList<BingoBall> bingosetb= new ArrayList(); ArrayList<BingoBall> bingoseti = new ArrayList(); ArrayList<BingoBall> bingosetn = new ArrayList(); ArrayList<BingoBall> bingosetg = new ArrayList(); ArrayList<BingoBall> bingoseto = new ArrayList(); ArrayList allbingonum = new ArrayList(); public Bingo(){ this.newgame(); } Bingo(View vison) { this.newgame(); } private void newgame() { //クリアー bingosetb.clear(); bingoseti.clear(); bingosetn.clear(); bingosetg.clear(); bingoseto.clear(); BingoBall ballb; BingoBall balli; BingoBall balln; BingoBall ballg; BingoBall ballo; for(int i = 1; i < 16; i++){ ballb = new BingoBall(0); balli = new BingoBall(0); balln = new BingoBall(0); ballg = new BingoBall(0); ballo = new BingoBall(0); bingosetb.add(ballb.setBall(i)); bingoseti.add(balli.setBall(i+15)); bingosetn.add(balln.setBall(i+30)); bingosetg.add(ballg.setBall(i+45)); bingoseto.add(ballo.setBall(i+60)); } allbingonum.add(bingosetb); allbingonum.add(bingoseti); allbingonum.add(bingosetn); allbingonum.add(bingosetg); allbingonum.add(bingoseto); } BingoBall getBall(String bingocode) { BingoBall bingoball = new BingoBall(0); while(!bingoball.isHit()){ switch (bingocode){ case "0": bingoball = this.getAllSetBall(); break; case "1": bingoball = this.getBall(0); break; case "2": bingoball = this.getBall(1); break; case "3": bingoball = this.getBall(2); break; case "4": bingoball = this.getBall(3); break; case "5": bingoball = this.getBall(4); break; } } return bingoball; } private BingoBall getBall(int index) { BingoBall ball; ArrayList tempnums = (ArrayList) allbingonum.get(index); Random rnd = new Random(); if(tempnums.isEmpty()){ return new BingoBall(-1); }else{ int ballseed = rnd.nextInt(tempnums.size()); ball = (BingoBall) tempnums.get(ballseed); tempnums.remove(ballseed); allbingonum.set(index, tempnums); ball.setHit(true); } return ball; } private BingoBall getAllSetBall() { Random rnd = new Random(); int bingoseed = rnd.nextInt(allbingonum.size()); ArrayList tempnums = (ArrayList) allbingonum.get(bingoseed); //空か判定して、空だったらやりなおし while(tempnums.isEmpty()){ bingoseed = rnd.nextInt(allbingonum.size()); tempnums = (ArrayList) allbingonum.get(bingoseed); } //空じゃないので、確実にボールを取れる int ballseed = rnd.nextInt(tempnums.size()); BingoBall ball = (BingoBall) tempnums.get(ballseed); tempnums.remove(ballseed); allbingonum.set(bingoseed, tempnums); ball.setHit(true); return ball; } }
true
48dbbccf72a45a85d1c8a4a17c8e4e5842bea057
Java
opensourcejavadeveloper/military_xml_project_miliconvert
/miliconvert/xsmt/trunk/plugins/org.miliconvert.xsmt.mpgt/src/mpia/schema/TypeCaracteristiquesSIO.java
UTF-8
7,544
1.875
2
[]
no_license
/** * <copyright> * </copyright> * * $Id$ */ package mpia.schema; import org.eclipse.emf.ecore.EObject; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Type Caracteristiques SIO</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link mpia.schema.TypeCaracteristiquesSIO#getTypeSIO <em>Type SIO</em>}</li> * <li>{@link mpia.schema.TypeCaracteristiquesSIO#isPrincipal <em>Principal</em>}</li> * <li>{@link mpia.schema.TypeCaracteristiquesSIO#getTrigramme <em>Trigramme</em>}</li> * <li>{@link mpia.schema.TypeCaracteristiquesSIO#getCTE <em>CTE</em>}</li> * <li>{@link mpia.schema.TypeCaracteristiquesSIO#getCE <em>CE</em>}</li> * </ul> * </p> * * @see mpia.schema.SchemaPackage#getTypeCaracteristiquesSIO() * @model annotation="urn:MPIA-schemaInfo entity_Type='AGGREGATED_ENTITY'" * extendedMetaData="name='type_CaracteristiquesSIO' kind='elementOnly'" * @generated */ public interface TypeCaracteristiquesSIO extends EObject { /** * Returns the value of the '<em><b>Type SIO</b></em>' attribute. * The literals are from the enumeration {@link mpia.schema.TypeDictionaryDicoCaracteristiquesSIOTypeSIO}. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Type SIO</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Type SIO</em>' attribute. * @see mpia.schema.TypeDictionaryDicoCaracteristiquesSIOTypeSIO * @see #isSetTypeSIO() * @see #unsetTypeSIO() * @see #setTypeSIO(TypeDictionaryDicoCaracteristiquesSIOTypeSIO) * @see mpia.schema.SchemaPackage#getTypeCaracteristiquesSIO_TypeSIO() * @model unsettable="true" required="true" * extendedMetaData="kind='element' name='TypeSIO'" * @generated */ TypeDictionaryDicoCaracteristiquesSIOTypeSIO getTypeSIO(); /** * Sets the value of the '{@link mpia.schema.TypeCaracteristiquesSIO#getTypeSIO <em>Type SIO</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Type SIO</em>' attribute. * @see mpia.schema.TypeDictionaryDicoCaracteristiquesSIOTypeSIO * @see #isSetTypeSIO() * @see #unsetTypeSIO() * @see #getTypeSIO() * @generated */ void setTypeSIO(TypeDictionaryDicoCaracteristiquesSIOTypeSIO value); /** * Unsets the value of the '{@link mpia.schema.TypeCaracteristiquesSIO#getTypeSIO <em>Type SIO</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isSetTypeSIO() * @see #getTypeSIO() * @see #setTypeSIO(TypeDictionaryDicoCaracteristiquesSIOTypeSIO) * @generated */ void unsetTypeSIO(); /** * Returns whether the value of the '{@link mpia.schema.TypeCaracteristiquesSIO#getTypeSIO <em>Type SIO</em>}' attribute is set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return whether the value of the '<em>Type SIO</em>' attribute is set. * @see #unsetTypeSIO() * @see #getTypeSIO() * @see #setTypeSIO(TypeDictionaryDicoCaracteristiquesSIOTypeSIO) * @generated */ boolean isSetTypeSIO(); /** * Returns the value of the '<em><b>Principal</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Principal</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Principal</em>' attribute. * @see #isSetPrincipal() * @see #unsetPrincipal() * @see #setPrincipal(boolean) * @see mpia.schema.SchemaPackage#getTypeCaracteristiquesSIO_Principal() * @model unsettable="true" dataType="mpia.meta.TypeBoolean" * extendedMetaData="kind='element' name='Principal'" * @generated */ boolean isPrincipal(); /** * Sets the value of the '{@link mpia.schema.TypeCaracteristiquesSIO#isPrincipal <em>Principal</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Principal</em>' attribute. * @see #isSetPrincipal() * @see #unsetPrincipal() * @see #isPrincipal() * @generated */ void setPrincipal(boolean value); /** * Unsets the value of the '{@link mpia.schema.TypeCaracteristiquesSIO#isPrincipal <em>Principal</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isSetPrincipal() * @see #isPrincipal() * @see #setPrincipal(boolean) * @generated */ void unsetPrincipal(); /** * Returns whether the value of the '{@link mpia.schema.TypeCaracteristiquesSIO#isPrincipal <em>Principal</em>}' attribute is set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return whether the value of the '<em>Principal</em>' attribute is set. * @see #unsetPrincipal() * @see #isPrincipal() * @see #setPrincipal(boolean) * @generated */ boolean isSetPrincipal(); /** * Returns the value of the '<em><b>Trigramme</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Trigramme</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Trigramme</em>' attribute. * @see #setTrigramme(String) * @see mpia.schema.SchemaPackage#getTypeCaracteristiquesSIO_Trigramme() * @model dataType="mpia.meta.TypeDataTypeChaine03" * extendedMetaData="kind='element' name='Trigramme'" * @generated */ String getTrigramme(); /** * Sets the value of the '{@link mpia.schema.TypeCaracteristiquesSIO#getTrigramme <em>Trigramme</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Trigramme</em>' attribute. * @see #getTrigramme() * @generated */ void setTrigramme(String value); /** * Returns the value of the '<em><b>CTE</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>CTE</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>CTE</em>' attribute. * @see #setCTE(String) * @see mpia.schema.SchemaPackage#getTypeCaracteristiquesSIO_CTE() * @model dataType="mpia.meta.TypeDataTypeChaine030" required="true" * extendedMetaData="kind='element' name='CTE'" * @generated */ String getCTE(); /** * Sets the value of the '{@link mpia.schema.TypeCaracteristiquesSIO#getCTE <em>CTE</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>CTE</em>' attribute. * @see #getCTE() * @generated */ void setCTE(String value); /** * Returns the value of the '<em><b>CE</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>CE</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>CE</em>' attribute. * @see #setCE(String) * @see mpia.schema.SchemaPackage#getTypeCaracteristiquesSIO_CE() * @model dataType="mpia.meta.TypeDataTypeChaine0100" * extendedMetaData="kind='element' name='CE'" * @generated */ String getCE(); /** * Sets the value of the '{@link mpia.schema.TypeCaracteristiquesSIO#getCE <em>CE</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>CE</em>' attribute. * @see #getCE() * @generated */ void setCE(String value); } // TypeCaracteristiquesSIO
true
bde198e2b2e4e1160bfb70f52ec810e03b3f9ef4
Java
weijiaooaa/XiaoEr-Community
/src/main/java/com/community2/service/UserService.java
UTF-8
428
1.757813
2
[]
no_license
package com.community2.service; import com.community2.mapper.UserMapper; import com.community2.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * @Author weijia * @Date 2019/9/26 13:36 * @Version 1.0 */ public interface UserService { List<User> selectOneByToken(String token); void creatOrUpdate(User user); }
true
cc6813e1bf5405d19a67d6e53324841274c6a9c8
Java
zhoulibo1988/chiguancloud
/cloud_common/src/main/java/com/chigua/cloud/common/result/ResultUtil.java
UTF-8
810
2.46875
2
[]
no_license
package com.chigua.cloud.common.result; /** * * @ClassName: ResultUtil * @Description: 统一返回工具类 * @author Mr.zhou * @date 2018年10月30日 上午11:04:30 * */ public class ResultUtil { //当正确时返回的值 public static Result success(Object data){ Result result = new Result(); result.setCode(HttpStatusEnum.OK.code()); result.setMsg(HttpStatusEnum.OK.reasonPhraseUS()); result.setData(data); return result; } public static Result success(){ return success(null); } //当错误时返回的值 public static Result error(int code,String msg){ Result result = new Result(); result.setCode(code); result.setMsg(msg); return result; } }
true
94f9a666cfcc1143890f53cae3041c6da95f29d5
Java
liuyan731/leetcode
/src/ly/leetcode/LinkedList/Q206ReverseLinkedList.java
WINDOWS-1252
695
3.234375
3
[]
no_license
/* * Q206ReverseLinkedList.java * * Created on: 2016419 * Author: liuyan */ package ly.leetcode.LinkedList; public class Q206ReverseLinkedList { public ListNode reverseList(ListNode head) { if(head == null || head.next == null) { return head; } else { ListNode p = head.next; head.next = null; ListNode q = null; while(p != null) { q = p; p = p.next; q.next = head; head = q; } return q; } } public ListNode reverseList2(ListNode l1, ListNode l2) { if(l1 == null) { return l2; } else { ListNode tmp = l1.next; l1.next = l2; return reverseList2(tmp, l1); } } }
true
161d15575da75ef4576b9849fce0215f8fc3fc05
Java
aoki234/CalcApp
/app/src/main/java/jp/techacademy/jun/aoki/calcapp/MainActivity.java
UTF-8
5,324
2.671875
3
[]
no_license
package jp.techacademy.jun.aoki.calcapp; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.app.AlertDialog; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; public class MainActivity extends AppCompatActivity implements View.OnClickListener { EditText editText1; EditText editText2; Float value3; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btn1 = (Button)findViewById(R.id.button1); Button btn2 = (Button)findViewById(R.id.button2); Button btn3 = (Button)findViewById(R.id.button3); Button btn4 = (Button)findViewById(R.id.button4); btn1.setOnClickListener(this); btn2.setOnClickListener(this); btn3.setOnClickListener(this); btn4.setOnClickListener(this); editText1 = (EditText) findViewById(R.id.editText1); editText2 = (EditText) findViewById(R.id.editText2); } @Override public void onClick(View v) { String variable1 = editText1.getText().toString(); String variable2 = editText2.getText().toString(); if(variable1.isEmpty() || variable2.isEmpty()){ showEmptyAlert(); }else if(variable2.equals("0") && v.getId() == R.id.button4){ //0で割り算した時のエラー showDivisionAlert(); }else{ try{ Float value1 = Float.parseFloat(variable1); Float value2 = Float.parseFloat(variable2); switch (v.getId()) { case R.id.button1: value3 = value1 + value2; break; case R.id.button2: value3 = value1 - value2; break; case R.id.button3: value3 = value1 * value2; break; case R.id.button4: value3 = value1 / value2; break; default: Log.d("javatest","can not calculate"); break; } Intent intent = new Intent(this, SecondActivity.class); intent.putExtra("VALUE3", String.valueOf(value3)); startActivity(intent); }catch (NumberFormatException e){ //.入力時のエラーをキャッチ Log.d("javatest","can not convert float"); showNumericAlert(); } } } private void showEmptyAlert() { // AlertDialog.Builderクラスを使ってAlertDialogの準備をする AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder.setTitle("variable is empty"); alertDialogBuilder.setMessage("Please input variable"); // 肯定ボタンに表示される文字列、押したときのリスナーを設定する alertDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Log.d("UI_PARTS", "OK"); } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } private void showDivisionAlert() { // AlertDialog.Builderクラスを使ってAlertDialogの準備をする AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder.setTitle("Can not calculate in this value"); alertDialogBuilder.setMessage("Please input correct value"); // 肯定ボタンに表示される文字列、押したときのリスナーを設定する alertDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Log.d("UI_PARTS", "OK"); } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } private void showNumericAlert() { // AlertDialog.Builderクラスを使ってAlertDialogの準備をする AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder.setTitle("Can not input this value"); alertDialogBuilder.setMessage("Please input Numeric value"); // 肯定ボタンに表示される文字列、押したときのリスナーを設定する alertDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Log.d("UI_PARTS", "OK"); } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } }
true
deac22410c13d90aec5a000d68f464982a416b2b
Java
Atalaia/NFP121
/revisions_2018/commands/Command.java
UTF-8
809
2.84375
3
[]
no_license
package commands; import conditions.*; import operations.*; public class Command<T,R>{ protected Condition<T> condition; protected Operation<T,R> operation; protected Command<T,R> exception; public void setCondition(Condition<T> condition){ this.condition = condition; } public void setOperation(Operation<T,R> operation){ this.operation = operation; } public void setException(Command<T,R> exception){ this.exception = exception; } public void execute(T t,R r){ try{ if(condition!=null && condition.estSatisfaite(t)){ operation.execute(t,r); } }catch(RuntimeException e){ if(exception!=null) exception.execute(t,r); throw e; } } public void undo(){ } }
true
b0997af74836a01a00ff7a8305f69945693b3d94
Java
RAMASHISHKUMAR/PhoneCallingProject
/app/src/main/java/adapter/ContactsAdapter.java
UTF-8
1,056
2.421875
2
[]
no_license
package adapter; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.ViewGroup; import java.util.List; import modelclass.Contacts; public class ContactsAdapter extends RecyclerView.Adapter<ContactsAdapter.MyViewHolder> { Context context; List<Contacts>contactsList; public ContactsAdapter(List<Contacts>contactsList , Context context){ this.context = context; this.contactsList = contactsList; } @NonNull @Override public ContactsAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { return null; } @Override public void onBindViewHolder(@NonNull ContactsAdapter.MyViewHolder myViewHolder, int i) { } @Override public int getItemCount() { return 0; } public class MyViewHolder extends RecyclerView.ViewHolder { public MyViewHolder(@NonNull View itemView) { super(itemView); } } }
true
69f5d8c52e9f7463126c0c1f52687fae49bd4fd5
Java
ewingcode/ball
/src/main/java/com/ewing/order/core/web/common/RequestJson.java
UTF-8
2,872
2.53125
3
[]
no_license
package com.ewing.order.core.web.common; import java.util.Map; import org.apache.commons.lang.StringUtils; import com.ewing.order.util.GsonUtil; /** * 请求的json * * @author tansonlam * @create 2016年12月28日 * */ public class RequestJson { /** * 签名,根据请求数据和加密方式计算的签名值 */ private String sign; /** * 业务ID */ private String id; /** * 请求的业务方 */ private String clientId; /** * 加密方式 MD5 */ private String encrypt; /** * 请求的数据 */ private Map<String, Object> data; private String dataStr; public RequestJson() { } public RequestJson(String json) { RequestJson requestJson = GsonUtil.getGson().fromJson(json, RequestJson.class); String dataJson = GsonUtil.getGson().toJson(requestJson.getData()); this.dataStr = dataJson; this.clientId = requestJson.getClientId(); this.encrypt = requestJson.encrypt; this.data = requestJson.data; this.id = requestJson.id; this.sign = requestJson.sign; } public String getDataStr() { return dataStr; } public Integer getInteger(String key) { if (StringUtils.isEmpty(key)) return null; if (data.get(key) instanceof String && data.get(key) != null) return Integer.valueOf(data.get(key).toString()); return null; } public String getString(String key) { if (StringUtils.isEmpty(key)) return null; return (String) data.get(key); } public Long getLong(String key) { if (StringUtils.isEmpty(key)) return null; if (data.get(key) instanceof String && data.get(key) != null) return Long.valueOf(data.get(key).toString()); return null; } public Object getObject(String key) { if (StringUtils.isEmpty(key)) return null; return data.get(key); } public Float getFloat(String key) { if (StringUtils.isEmpty(key)) return null; if (data.get(key) instanceof String && data.get(key) != null) return Float.valueOf(data.get(key).toString()); return null; } public <T> T requestJson2Obj(Class<T> clazz) { return GsonUtil.getGson().fromJson(dataStr, clazz); } public static RequestJson newEmpty() { return new RequestJson(); } public String getSign() { return sign; } public void setSign(String sign) { this.sign = sign; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getClientId() { return clientId; } public void setClientId(String clientId) { this.clientId = clientId; } public String getEncrypt() { return encrypt; } public void setEncrypt(String encrypt) { this.encrypt = encrypt; } public Map<String, Object> getData() { return data; } public void setData(Map<String, Object> data) { this.data = data; } /* * public String getData() { return data; } * * public void setData(String data) { this.data = data; } */ }
true
1b07c379a3d535ab2a663932c042b9466b294446
Java
whoschek/hbase-indexer
/hbase-indexer-model/src/main/java/com/ngdata/hbaseindexer/model/api/IndexerLifecycleListener.java
UTF-8
1,619
1.953125
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2013 NGDATA nv * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ngdata.hbaseindexer.model.api; /** * Handles various lifecycle events by the IndexerMaster. So these will not be called on every indexer node. */ public interface IndexerLifecycleListener { /** * Handler for delete events * @param indexerDefinition Definition of indexer in question */ void onDelete(IndexerDefinition indexerDefinition); /** * Handler for subscribe events. This is when the indexer is set to pick up SEP events * @param indexerDefinition Definition of indexer in question */ void onSubscribe(IndexerDefinition indexerDefinition); /** * Handler for unsubscribe events. When the indexer stops listening for SEP events * @param indexerDefinition Definition of indexer in question */ void onUnsubscribe(IndexerDefinition indexerDefinition); /** * Handler for started batch builds. * @param indexerDefinition Definition of indexer in question */ void onBatchBuild(IndexerDefinition indexerDefinition); }
true
b9a22fcaf03886a938b5dc6a78357c438d259c21
Java
Zalizyaka-Ney/handy.storage
/library/src/main/java/handy/storage/Expressions.java
UTF-8
5,428
2.765625
3
[]
no_license
package handy.storage; import java.util.Arrays; import java.util.Collection; import java.util.List; import handy.storage.annotation.Reference; import handy.storage.api.ColumnCondition; import handy.storage.api.Select; import handy.storage.base.QueryParams; import handy.storage.exception.IllegalUsageException; /** * Factory of table expressions. * * @param <T> type of model the table object bound to */ public class Expressions<T> { private final Table ownerTable; private final QueryAdapter queryAdapter; Expressions(Table table) { ownerTable = table; queryAdapter = table.getQueryAdapter(); } /** * Builds a new {@link Expression} for the table, representing a condition * for a column. * * @param column column's name */ public ColumnCondition<Expression> column(String column) { return newColumnExpressionBuilder(column); } /** * Builds a new {@link Expression} for the table, representing a custom * SQLite expression. * * @param rawExpression expression in SQLite syntax */ public Expression raw(String rawExpression) { return new Expression(rawExpression, queryAdapter); } /** * Creates a new {@link Expression} instance limiting the objects <b>not</b> * to be <b>one of the <code>objects</code></b>. * * @throws IllegalUsageException if the table is not bound to a model class or the table has no unique or primary key column */ @SafeVarargs public final Expression exclude(T... objects) { return exclude(Arrays.asList(objects)); } /** * Creates a new {@link Expression} instance limiting the objects <b>not</b> * to be <b>one of the <code>objects</code></b>. * * @throws IllegalUsageException if the table is not bound to a model class or the table has no unique or primary key column */ public Expression exclude(Collection<? extends T> objects) { ColumnInfo uniqueColumn = ownerTable.getUniqueColumnOrThrow(); List<Object> uniqueColumnValues = ownerTable.getColumnValues(objects, uniqueColumn); ColumnInfo.ColumnId uniqueColumnId = uniqueColumn.getColumnId(); return column(uniqueColumnId.getFullName()).notIn(uniqueColumnValues); } /** * Creates a new {@link Expression} instance limiting the objects <b>not</b> * to be <b>in the <code>table</code></b> (selection of values from another * table referencing to this one). This <code>table</code> must be obtained * by calling {@link Table#columnValues(String)} with a name of a column * declared as {@link Reference} to this table as the argument. * * @throws IllegalUsageException if the table has no unique or primary key column */ public Expression exclude(ColumnValuesTable table) { ColumnInfo uniqueColumn = ownerTable.getUniqueColumnOrThrow(); String uniqueColumnName = uniqueColumn.getColumnId().getFullName(); return column(uniqueColumnName).notIn(table); } /** * Creates a new {@link Expression} instance limiting the objects to be * <b>one of the <code>objects</code></b>. * * @throws IllegalUsageException if the table is not bound to a model class or the table has no unique or primary key column */ @SafeVarargs public final Expression oneOf(T... objects) { return oneOf(Arrays.asList(objects)); } /** * Creates a new {@link Expression} instance limiting the objects to be * <b>one of the <code>objects</code></b>. * * @throws IllegalUsageException if the table is not bound to a model class or the table has no unique or primary key column */ public Expression oneOf(Collection<? extends T> objects) { ColumnInfo uniqueColumn = ownerTable.getUniqueColumnOrThrow(); List<Object> uniqueColumnValues = ownerTable.getColumnValues(objects, uniqueColumn); ColumnInfo.ColumnId uniqueColumnId = uniqueColumn.getColumnId(); return column(uniqueColumnId.getFullName()).in(uniqueColumnValues); } /** * Creates a new {@link Expression} instance limiting the objects to be * <b>in the <code>table</code></b> (selection of values from another table * referencing to this one). This <code>table</code> must be obtained by * calling {@link Table#columnValues(String)} with a name of a column * declared as {@link Reference} to this table as the argument. * * @throws IllegalUsageException if the table has no unique or primary key column */ public Expression oneOf(ColumnValuesTable table) { ColumnInfo uniqueColumn = ownerTable.getUniqueColumnOrThrow(); String uniqueColumnName = uniqueColumn.getColumnId().getFullName(); return column(uniqueColumnName).in(table); } Expression oneOf(Select<T> select) { return createExpressionForSelect(select, true); } Expression exclude(Select<T> select) { return createExpressionForSelect(select, false); } private Expression createExpressionForSelect(Select<T> select, boolean including) { ColumnInfo uniqueColumn = ownerTable.getUniqueColumnOrThrow(); String uniqueColumnName = uniqueColumn.getColumnId().getFullName(); QueryParams query = select.asQueryParams(); query.columns(uniqueColumnName); return including ? newColumnExpressionBuilder(uniqueColumnName).inTable(query.toRawSqlQuery()) : newColumnExpressionBuilder(uniqueColumnName).notInTable(query.toRawSqlQuery()); } ColumnExpressionBuilder<Expression> newColumnExpressionBuilder(String column) { return new ColumnExpressionBuilder<Expression>(column, queryAdapter) { @Override Expression complete() { return buildExpression(); } }; } }
true
d8f86f10a6f4385666683d22f3c38bb864d52144
Java
Devcamp1team/Android
/app/src/main/java/com/yapp/no_11/yapp_1team/items/LotteGsonModel.java
UTF-8
2,366
2.234375
2
[ "MIT", "Apache-2.0" ]
permissive
package com.yapp.no_11.yapp_1team.items; import com.google.gson.annotations.SerializedName; /** * Created by HunJin on 2017-09-23. */ public class LotteGsonModel { private @SerializedName("Cinemas") Cinemas cinemases; public Cinemas getCinemases() { return cinemases; } public void setCinemases(Cinemas cinemases) { this.cinemases = cinemases; } public class Cinemas { private @SerializedName("Items") Item[] items; public Item[] getItems() { return items; } public void setItems(Item[] items) { this.items = items; } } public class Item { private @SerializedName("DivisionCode") String divCode; private @SerializedName("DetailDivisionCode") String detailDivCode; private @SerializedName("CinemaID") String id; private @SerializedName("CinemaNameKR") String name; private @SerializedName("SortSequence") String sort; private @SerializedName("Latitude") String lat; private @SerializedName("Longitude") String lng; public String getDivCode() { return divCode; } public void setDivCode(String divCode) { this.divCode = divCode; } public String getDetailDivCode() { return detailDivCode; } public void setDetailDivCode(String detailDivCode) { this.detailDivCode = detailDivCode; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSort() { return sort; } public void setSort(String sort) { this.sort = sort; } public String getLat() { return lat; } public void setLat(String lat) { this.lat = lat; } public String getLng() { return lng; } public void setLng(String lng) { this.lng = lng; } } }
true
3129ce8ae77573eda80409bc152b3659e78f1021
Java
Sari27/DI3ProjetJava
/DI3ProjetJava/src/model/emulator/SearchInEmulator.java
UTF-8
4,090
3.25
3
[]
no_license
package model.emulator; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Hashtable; import java.util.concurrent.CopyOnWriteArrayList; import controller.emulator.Emulator; import model.shared.*; /** * * @brief Abstract class which implements method to search employee or * CheckInOuts in an Emulator. * */ public abstract class SearchInEmulator { /** * @brief Static method which returns true if str1 begin by str2. * @param str1 * @param str2 * @return boolean */ static public boolean areStringsMatching(String str1, String str2) { String str1Temp = str1.toLowerCase(); String str2Temp = str2.toLowerCase(); if (str1Temp.contains(str2Temp)) { for (Integer iterator = 0; iterator < str1Temp.length(); iterator++) { if (str1Temp.startsWith(str2Temp, iterator)) return true; } } return false; } /*********************************************************************/ /************************* RETURN EMPLOYEES **************************/ /*********************************************************************/ /************************ according to check *************************/ // overall /** * @param history * @param beforeCheck * @param afterCheck * @return ArrayList<EmployeeInfo> */ static public ArrayList<EmployeeInfo> searchEmployee(History history, LocalDateTime beforeCheck, LocalDateTime afterCheck) { ArrayList<EmployeeInfo> resultList = new ArrayList<EmployeeInfo>(); Hashtable<EmployeeInfo, CopyOnWriteArrayList<CheckInOut>> totalList = history.getChecksPerEmployee(); for (EmployeeInfo currentEmployeeInfo : totalList.keySet()) { ArrayList<CheckInOut> listChecks = new ArrayList<>(history.getChecksPerEmployee().get(currentEmployeeInfo)); boolean isInto = false; for (Integer iterator = listChecks.size() - 1; iterator >= 0 && !isInto; iterator--) { CheckInOut checkTmp = listChecks.get(iterator); if (checkTmp.getCheckTime().isAfter(beforeCheck) && checkTmp.getCheckTime().isBefore(afterCheck)) { isInto = true; resultList.add(currentEmployeeInfo); } } } return new ArrayList<EmployeeInfo>(resultList); } /************************* according to ID ***************************/ // necessarily only one employee per ID // overall /** * @param history * @param ID * @return EmployeeInfo */ static public EmployeeInfo searchEmployee(History history, Integer ID) { for (EmployeeInfo currentEmployeeInfo : Emulator.getListEmployeeInfo()) { if (currentEmployeeInfo.getID().equals(ID)) { return currentEmployeeInfo; } } return null; } /************************ according to name **************************/ // overall /** * @param history * @param firstname * @param lastname * @return ArrayList<EmployeeInfo> */ static public ArrayList<EmployeeInfo> searchEmployee(History history, String firstname, String lastname) { ArrayList<EmployeeInfo> resultList = new ArrayList<EmployeeInfo>(); for (EmployeeInfo currentEmployeeInfo : Emulator.getListEmployeeInfo()) { if (areStringsMatching(currentEmployeeInfo.getFirstname(), firstname) && areStringsMatching(currentEmployeeInfo.getLastname(), lastname)) { resultList.add(currentEmployeeInfo); } } return new ArrayList<EmployeeInfo>(resultList); } // overall /** * @param history * @param name * @param nName * @return ArrayList<EmployeeInfo> */ static public ArrayList<EmployeeInfo> searchEmployee(History history, String name, Integer nName) { ArrayList<EmployeeInfo> resultList = new ArrayList<EmployeeInfo>(); for (EmployeeInfo currentEmployeeInfo : Emulator.getListEmployeeInfo()) { if ((areStringsMatching(currentEmployeeInfo.getFirstname(), name) && nName == 0) || (areStringsMatching(currentEmployeeInfo.getLastname(), name) && nName == 1)) { resultList.add(currentEmployeeInfo); } } return new ArrayList<EmployeeInfo>(resultList); } }
true
4b9d1a3e65edf6cd1df8a77cec4b8964e4965239
Java
khalilmassoussi/pi
/pi-ifr-ejb/src/main/java/services/BasicOpsRemote.java
UTF-8
618
1.984375
2
[]
no_license
package services; import java.util.List; import javax.ejb.Remote; import persistence.Articles; import persistence.Camp; import persistence.Refugee; @Remote public interface BasicOpsRemote { List<Camp> findCamps(); Boolean userInCamp(int id,Camp c); Long numberOfRefugees(Camp c); Long numberOfMales(Camp c); Long numberOfFemales(Camp c); List refugeesInCamp(Camp c); Long countUsersBySexe(String s); void updateUser(Refugee user); void saveOrUpdateArticle(Articles article); List<Articles> findallArticles(); Articles findArticlesById(int id); void deleteArticle(Articles article); }
true
1fde2e2301b46dac861b9e27c8ee2e61cddbee89
Java
andreyoliferov/job4j
/chapter_011_Collections/src/test/java/set/SimpleSetTest.java
UTF-8
926
2.78125
3
[ "Apache-2.0" ]
permissive
package set; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.testng.Assert.assertTrue; /** * @autor Андрей * @since 16.07.2018 */ public class SimpleSetTest { private SimpleSet<Integer> simpleSet; @BeforeMethod public void startTest() { simpleSet = new SimpleSet<>(); simpleSet.add(1); simpleSet.add(2); } @Test public void whenAddUniq() { assertThat(simpleSet.add(3), is(true)); assertTrue(simpleSet.contains(3)); assertThat(simpleSet.getSize(), is(3)); } @Test public void whenAddUnuniq() { assertThat(simpleSet.add(2), is(false)); assertTrue(simpleSet.contains(2)); assertThat(simpleSet.getSize(), is(2)); } }
true
21885c201b24b37aa462ab1cbb374a53e1708a21
Java
mhzj/zf
/src/main/java/com/service/User_ProjectService.java
UTF-8
249
1.859375
2
[]
no_license
package com.service; import com.entity.User_project; public interface User_ProjectService { public int addUser_Project(User_project user_project); int delUser_Project(int projectid); User_project findByprojectid(int projectid); }
true
3c8285637930c12db978a0d59933669f5c1023cb
Java
Jdruwe/Overtime
/app/src/main/java/adevador/com/overtime/listener/WorkdayListener.java
UTF-8
268
1.789063
2
[]
no_license
package adevador.com.overtime.listener; import java.util.ArrayList; import java.util.Date; import adevador.com.overtime.model.Workday; /** * Created by druweje on 21/10/2014. */ public interface WorkdayListener { public void deleteWorkday(Workday workday); }
true
4c23ace056aeebe5387229bd97f0b5a33e6bcae4
Java
SamuelPaulos/MuM
/FinalProject2/src/ui/loginForm/UserLoginController.java
UTF-8
3,959
2.46875
2
[]
no_license
package ui.loginForm; import java.io.IOException; import javax.swing.JOptionPane; import banking.ui.BankFrm; import creditCard.ui.CardFrm; import framework.dao.StaffDataBase; import framework.entity.Staff; import framework.iterator.Iterator; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.control.PasswordField; import javafx.scene.control.RadioButton; import javafx.scene.control.TextField; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; public class UserLoginController extends Application { private static Stage primaryStage; private static AnchorPane mainLayout; private String staffType; @FXML private Label lblBankCreditSelectionResult; @FXML private RadioButton rdBank; @FXML private RadioButton rdCredit; @FXML private TextField txtUserName; @FXML private PasswordField txtPassword; String bankOrCreditSelected = "bankStaff"; @Override public void start(Stage primaryStage) throws IOException { this.primaryStage = primaryStage; this.primaryStage.setTitle("Login Form"); showMainView(); } // Displays the Login form public void showMainView() throws IOException { FXMLLoader loader = new FXMLLoader(); loader.setLocation(UserLoginController.class.getResource("LoginForm.fxml")); mainLayout = loader.load(); Scene scene = new Scene(mainLayout); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(args); } public void rdBankSelected() { lblBankCreditSelectionResult.setText("Bank Login Form"); bankOrCreditSelected = "bankStaff"; } public void rdCreditSelected() { lblBankCreditSelectionResult.setText("Credit Login Form"); bankOrCreditSelected = "creditStaff"; } // For Login public void btnLoginActionListener(ActionEvent e) { boolean validStaff = false; if (rdBank.isSelected()) { staffType = "bankStaff"; if (authenticateBankStaff()) { new BankFrm().bankMain(); primaryStage.close(); validStaff = true; } } else if (rdCredit.isSelected()) { staffType = "creditStaff"; if (authenticateCreditStaff()) { new CardFrm().creditMain(); primaryStage.close(); validStaff = true; } } if (!validStaff){ JOptionPane.showMessageDialog(null, "Invalid UserName or Password", "Login Failed", JOptionPane.WARNING_MESSAGE); } } private boolean authenticateBankStaff() { String userName = txtUserName.getText(); String password = txtPassword.getText().toString(); boolean authenticated = false; Iterator staffIterator = StaffDataBase.getStaffDBInstance().getIterator(staffType); while(staffIterator.hasNext()){ Staff bs = staffIterator.next(); if (userName.equals(bs.getUsername()) && password.equals(bs.getPassword())) { authenticated = true; break; } } return authenticated; } // Authentication for credit staff private boolean authenticateCreditStaff() { String userName = txtUserName.getText(); String password = txtPassword.getText().toString(); boolean authenticated = false; Iterator staffIterator = StaffDataBase.getStaffDBInstance().getIterator(staffType); while(staffIterator.hasNext()){ Staff bs = staffIterator.next(); if (userName.equals(bs.getUsername()) && password.equals(bs.getPassword())) { authenticated = true; break; } } return authenticated; } // For signing up a staff public void btnRegisterStaffActionListener(ActionEvent e) { new UserRegistration(bankOrCreditSelected); } // Exit the system on click of cancel button public void btnCancelActionListener(ActionEvent e) { System.exit(0); } }
true
39e169f9e64a58ec616ff337c139a4c92789cfba
Java
Wulf000/springBootSwagger
/springboot_swagger/src/main/java/com/example/demo/ServletInitializer.java
UTF-8
782
2.28125
2
[]
no_license
package com.example.demo; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.support.SpringBootServletInitializer; /** * 使用外置的Tomcat启动时需要配置 * @author 走遍千里 * 若打包成war包,则需要配置 * * jar包和war包启动区别 * jar包:执行SpringBootApplication的run方法,启动IOC容器,然后创建嵌入式Servlet容器 * war包:先是启动Servlet服务器,服务器启动Springboot应用(springBootServletInitizer),然后启动IOC容器 */ public class ServletInitializer extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(SpringbootSwaggerApplication.class); } }
true
b89acccc5fb50eeccb061c18f42f1f643a2f3e7a
Java
nan-666/Maven
/src/test/java/hello/baidu.java
UTF-8
742
1.96875
2
[]
no_license
package hello; import org.jmock.Expectations; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class baidu { @Before public void setUp() throws Exception { System.setProperty("webdriver.chrome.driver", "D:/chromedriver_win32/chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("https://zhidao.baidu.com/"); System.out.println("Before"+driver.getTitle()); } @Test public void testIn(WebDriver driver) { driver.get("https://zhidao.baidu.com/"); System.out.println("Test"+driver.getTitle()); } }
true
e6996cfe2a8a7a5a86b8aa4d8fbe0070843a0e57
Java
jeantessier/Mocking
/src/AllTests.java
UTF-8
2,287
2.015625
2
[]
no_license
import junit.framework.TestSuite; public class AllTests { public static TestSuite suite() { TestSuite result = new TestSuite(); result.addTestSuite(Single_EasyMock.class); result.addTestSuite(Single_Mockito.class); result.addTestSuite(Multiple_jMock.class); result.addTestSuite(Multiple_EasyMock.class); result.addTestSuite(Inherited_jMock.class); result.addTestSuite(Inherited_EasyMock.class); result.addTestSuite(Class_jMock.class); result.addTestSuite(ClassExplicit1_jMock.class); result.addTestSuite(ClassExplicit2_jMock.class); result.addTestSuite(Class_EasyMock.class); result.addTestSuite(CacheTest_jMock.class); result.addTestSuite(CacheTest_EasyMock.class); result.addTestSuite(CacheTest_Mockito.class); result.addTestSuite(UserCacheTest_jMock.class); result.addTestSuite(UserCacheTest_EasyMock.class); result.addTestSuite(UserCacheTest_Mockito.class); result.addTestSuite(Simple_jMock.class); result.addTestSuite(Simple_EasyMock.class); result.addTestSuite(MultipleCalls_jMock.class); result.addTestSuite(MultipleCalls_EasyMock.class); result.addTestSuite(IgnoringMethod_jMock.class); result.addTestSuite(IgnoringMethod_EasyMock.class); result.addTestSuite(Innocuous_jMock.class); result.addTestSuite(Innocuous_EasyMock.class); result.addTestSuite(IgnoringObject_jMock.class); result.addTestSuite(IgnoringObject_EasyMock.class); result.addTestSuite(ExactParams_jMock.class); result.addTestSuite(ExactParams_EasyMock.class); result.addTestSuite(FuzzyParams_jMock.class); result.addTestSuite(FuzzyParams_EasyMock.class); result.addTestSuite(SequenceOneMock_jMock.class); result.addTestSuite(SequenceOneMock_EasyMock.class); result.addTestSuite(SequenceTwoMocks_jMock.class); result.addTestSuite(SequenceTwoMocks_EasyMock.class); result.addTestSuite(SideEffect_jMock.class); result.addTestSuite(SideEffect_EasyMock.class); result.addTestSuite(VoidAndReturnType_jMock.class); result.addTestSuite(VoidAndReturnType_EasyMock.class); return result; } }
true
a5e26ae4117ac14f7a29ee055a06522728f6bf00
Java
SowmyaSiteurl/Admin_Loyalty
/app/src/main/java/siteurl/in/admin_loyalty/CalltoVendor.java
UTF-8
2,755
2.203125
2
[]
no_license
package siteurl.in.admin_loyalty; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; import static android.Manifest.permission.CALL_PHONE; public class CalltoVendor extends AppCompatActivity { String Number; public static final int RequestPermissionCode = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.callto_vendor); Number = getIntent().getStringExtra("phonenumber"); // startActivity( new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + Number))); Intent callIntent = new Intent(Intent.ACTION_CALL); callIntent.setData(Uri.parse("tel:" + Number)); if (ActivityCompat.checkSelfPermission(this, CALL_PHONE) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. requestPermission(); return; } callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(callIntent); } private void requestPermission() { ActivityCompat.requestPermissions(CalltoVendor.this, new String[] { CALL_PHONE }, RequestPermissionCode); } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case RequestPermissionCode: if (grantResults.length > 0) { boolean CameraPermission = grantResults[0] == PackageManager.PERMISSION_GRANTED; if (CameraPermission) { Toast.makeText(CalltoVendor.this, "Permission Granted", Toast.LENGTH_LONG).show(); } else { Toast.makeText(CalltoVendor.this, "Permission Denied", Toast.LENGTH_LONG).show(); finish(); } } break; } } @Override protected void onPause() { super.onPause(); finish(); } }
true
0efaa742b26bf0dde2befe7777b5b09cced9cdc1
Java
jaimepizarr/ProyectoDePoo
/src/Entidades/Premio.java
UTF-8
1,072
2.421875
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 Entidades; /** * * @author eljosephavila */ public class Premio { private int puntaje; private String recompensa; private String nivelAlcanzado; public Premio(int puntaje, String recompensa, String nivelAlcanzado) { this.puntaje = puntaje; this.recompensa = recompensa; this.nivelAlcanzado = nivelAlcanzado; } public int getPuntaje() { return puntaje; } public void setPuntaje(int puntaje) { this.puntaje = puntaje; } public String getRecompensa() { return recompensa; } public void setRecompensa(String recompensa) { this.recompensa = recompensa; } public String getNivelAlcanzado() { return nivelAlcanzado; } public void setNivelAlcanzado(String nivelAlcanzado) { this.nivelAlcanzado = nivelAlcanzado; } }
true
c17a18a7888334c1643ea9bc897384145061b434
Java
savansh/FindmePOM
/src/Pages/Addbusinees_Step1.java
UTF-8
4,053
1.90625
2
[]
no_license
package Pages; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.Select; public class Addbusinees_Step1 { //constructor WebDriver driver; public Addbusinees_Step1(WebDriver driver){ this.driver=driver; } @FindBy(id="BusinessBusinessNameEn") public WebElement BusinessNameEn; @FindBy(id="BusinessBusinessNameAr") public WebElement BusinessNameAr; @FindBy(xpath="//*[@id='s2id_headerCategory']") public WebElement clickonCategory; @FindBy(xpath="//*[@id='s2id_autogen1_search']") public WebElement SearchCategory; @FindBy(xpath="//*[@id='BusinessSubcategory0_chosen']/ul") public WebElement opensubcategory; @FindBy(xpath="//*[@id='BusinessSubcategory0_chosen']/ul/li/input") public WebElement searchsubcategory; @FindBy(xpath="BusinessPriceRange") public WebElement PriceRange; @FindBy(name="data[Business][short_desc_en]") public WebElement ShortDescEn; @FindBy(name="data[Business][short_desc_ar]") public WebElement ShortDescAr; @FindBy(id="logo_file") public WebElement logo_file; @FindBy(xpath="//*[@id='imageCropperContailner']/div/div[1]/div[4]/button") public WebElement saveCropImage; @FindBy(id="cover_file") public WebElement coverimage; @FindBy(xpath="//*[@id='file_upload_other_images']") public WebElement otherimages; @FindBy(xpath="//*[@id='menu_file_upload']") public WebElement menufileupload; @FindBy(partialLinkText="Next") public WebElement Nextbutton; public AddBusinessStep2 AddBussss1(String BusinessNameEnglish, String BusinessNameArabic, String categoryname, String subcategorysearch, String price, String ShortDescEnglish, String ShortDescArabic, String logo, String CoverImage, String image1, String image2, String image3, String image4, String image5, String menu1, String menu2, String menu3, String menu4, String menu5) throws Exception { BusinessNameEn.clear(); BusinessNameEn.sendKeys(BusinessNameEnglish); BusinessNameAr.clear(); BusinessNameAr.sendKeys(BusinessNameArabic); clickonCategory.click(); Thread.sleep(2000); SearchCategory.clear(); SearchCategory.sendKeys(categoryname); Thread.sleep(2000); SearchCategory.sendKeys(Keys.ENTER); opensubcategory.click(); Thread.sleep(2000); searchsubcategory.clear(); searchsubcategory.sendKeys(subcategorysearch); Thread.sleep(2000); searchsubcategory.sendKeys(Keys.ENTER); Thread.sleep(2000); //price range driver.findElement(By.id("BusinessPriceRange")).click(); new Select(driver.findElement(By.id("BusinessPriceRange"))).selectByVisibleText("Moderate"); //end //scroll page Thread.sleep(2000); JavascriptExecutor jse = (JavascriptExecutor)driver; jse.executeScript("window.scrollBy(0,250)", ""); //ShortDescEn.clear(); ShortDescEn.sendKeys(ShortDescEnglish); ShortDescAr.clear(); ShortDescAr.sendKeys(ShortDescArabic); logo_file.sendKeys(logo); Thread.sleep(2000); saveCropImage.click(); Thread.sleep(2000); coverimage.sendKeys(CoverImage); Thread.sleep(2000); saveCropImage.click(); Thread.sleep(2000); otherimages.sendKeys(image1); Thread.sleep(7000); otherimages.sendKeys(image2); Thread.sleep(7000); otherimages.sendKeys(image3); Thread.sleep(7000); otherimages.sendKeys(image4); Thread.sleep(7000); otherimages.sendKeys(image5); Thread.sleep(7000); menufileupload.sendKeys(menu1); Thread.sleep(2000); menufileupload.sendKeys(menu2); Thread.sleep(2000); menufileupload.sendKeys(menu3); Thread.sleep(2000); menufileupload.sendKeys(menu4); Thread.sleep(2000); menufileupload.sendKeys(menu5); Thread.sleep(10000); Nextbutton.click(); return PageFactory.initElements(driver, AddBusinessStep2.class); } }
true