blob_id
stringlengths
40
40
__id__
int64
225
39,780B
directory_id
stringlengths
40
40
path
stringlengths
6
313
content_id
stringlengths
40
40
detected_licenses
sequence
license_type
stringclasses
2 values
repo_name
stringlengths
6
132
repo_url
stringlengths
25
151
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
70
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
7.28k
689M
star_events_count
int64
0
131k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
23 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
40.4M
gha_stargazers_count
int32
0
112k
gha_forks_count
int32
0
39.4k
gha_open_issues_count
int32
0
11k
gha_language
stringlengths
1
21
gha_archived
bool
2 classes
gha_disabled
bool
1 class
content
stringlengths
7
4.37M
src_encoding
stringlengths
3
16
language
stringclasses
1 value
length_bytes
int64
7
4.37M
extension
stringclasses
24 values
filename
stringlengths
4
174
language_id
stringclasses
1 value
entities
list
contaminating_dataset
stringclasses
0 values
malware_signatures
sequence
redacted_content
stringlengths
7
4.37M
redacted_length_bytes
int64
7
4.37M
alphanum_fraction
float32
0.25
0.94
alpha_fraction
float32
0.25
0.94
num_lines
int32
1
84k
avg_line_length
float32
0.76
99.9
std_line_length
float32
0
220
max_line_length
int32
5
998
is_vendor
bool
2 classes
is_generated
bool
1 class
max_hex_length
int32
0
319
hex_fraction
float32
0
0.38
max_unicode_length
int32
0
408
unicode_fraction
float32
0
0.36
max_base64_length
int32
0
506
base64_fraction
float32
0
0.5
avg_csv_sep_count
float32
0
4
is_autogen_header
bool
1 class
is_empty_html
bool
1 class
shard
stringclasses
16 values
5cffbae791dbf480d5bfe400cfbb736d00058bff
11,811,160,132,079
6fd6cf7e654d2521e0aacbab4ac02af06b670edc
/app/src/main/java/com/sxy/healthcare/me/OrderFragment.java
d5995d439084941a1440cf3d46758d94461771b3
[]
no_license
Streamduo/healthcare
https://github.com/Streamduo/healthcare
453222ce3b62efc63666f6ab73c555bfa29607d9
3a42d07d1e938d61bae4b293cdbadb2878045cf2
refs/heads/master
2020-04-01T07:11:48.552000
2018-12-02T13:21:12
2018-12-02T13:21:12
152,980,235
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sxy.healthcare.me; import android.annotation.SuppressLint; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.annotation.Nullable; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.text.TextUtils; import android.widget.Toast; import com.google.gson.Gson; import com.google.gson.JsonObject; import com.jude.easyrecyclerview.EasyRecyclerView; import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter; import com.sxy.healthcare.R; import com.sxy.healthcare.base.BaseFragment; import com.sxy.healthcare.base.Constants; import com.sxy.healthcare.common.net.ApiServiceFactory; import com.sxy.healthcare.common.utils.LogUtils; import com.sxy.healthcare.common.utils.NetUtils; import com.sxy.healthcare.common.utils.ThreeDesUtils; import com.sxy.healthcare.common.utils.ToastUtils; import com.sxy.healthcare.me.activity.OrderDetailActivity; import com.sxy.healthcare.me.activity.ReserveDetailActivity; import com.sxy.healthcare.me.adapter.OrderAdapter; import com.sxy.healthcare.me.bean.BookingBean; import com.sxy.healthcare.me.bean.OrderBean; import com.sxy.healthcare.me.bean.OrderResponse; import com.sxy.healthcare.me.bean.PayResult; import com.sxy.healthcare.me.event.CancelEvent; import com.sxy.healthcare.me.event.PayEvent; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import io.reactivex.Observer; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.Disposable; import io.reactivex.schedulers.Schedulers; import okhttp3.RequestBody; import static com.sxy.healthcare.me.adapter.OrderAdapter.SDK_PAY_FLAG; public class OrderFragment extends BaseFragment implements RecyclerArrayAdapter.OnLoadMoreListener, SwipeRefreshLayout.OnRefreshListener, RecyclerArrayAdapter.OnNoMoreListener { private static final String TAG = OrderFragment.class.getSimpleName(); @BindView(R.id.rc_order) EasyRecyclerView rcOrder; OrderAdapter orderAdapter; private List<OrderBean> orderBeans = new ArrayList<>(); private Disposable orderDis; private int pageSize = 20; private int pageNo = 1; private int total = 0; private boolean isMore = true; private int orderType = 0; @SuppressLint("HandlerLeak") private Handler mHandler = new Handler() { @SuppressWarnings("unused") public void handleMessage(Message msg) { switch (msg.what) { case SDK_PAY_FLAG: { PayResult payResult = new PayResult((String) msg.obj); /** * 同步返回的结果必须放置到服务端进行验证(验证的规则请看https://doc.open.alipay.com/doc2/ * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665& * docType=1) 建议商户依赖异步通知 */ String resultInfo = payResult.getResult();// 同步返回需要验证的信息 String resultStatus = payResult.getResultStatus(); // 判断resultStatus 为“9000”则代表支付成功,具体状态码代表含义可参考接口文档 if (TextUtils.equals(resultStatus, "9000")) { Toast.makeText(getContext(), "支付成功", Toast.LENGTH_SHORT).show(); orderAdapter.hideDialog(); pageNo = 1; getOrders(orderType); } else { // 判断resultStatus 为非"9000"则代表可能支付失败 // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认,最终交易是否成功以服务端异步通知为准(小概率状态) if (TextUtils.equals(resultStatus, "8000")) { Toast.makeText(getContext(), "支付结果确认中", Toast.LENGTH_SHORT).show(); } else { // 其他值就可以判断为支付失败,包括用户主动取消支付,或者系统返回的错误 Toast.makeText(getContext(), "支付失败", Toast.LENGTH_SHORT).show(); } } break; } default: break; } } }; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_order); EventBus.getDefault().register(this); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } @Override protected void initViews() { super.initViews(); orderAdapter = new OrderAdapter(getActivity(), getActivity().getSupportFragmentManager(), mHandler); rcOrder.setAdapter(orderAdapter); rcOrder.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false)); orderAdapter.setMore(R.layout.view_more, this); orderAdapter.setNoMore(R.layout.view_no_more, this); rcOrder.setRefreshListener(this); orderAdapter.pauseMore(); // final Intent intent = new Intent(getActivity(),OrderDetailActivity.class); orderAdapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() { @Override public void onItemClick(int position) { if (null != orderBeans) { /* intent.putExtra(Constants.EXTRA_ORDER,orderBeans.get(position)); startActivity(intent);*/ Intent intent; if ("2".equals(orderBeans.get(position).getOrderType())) { intent = new Intent(getContext(), ReserveDetailActivity.class); BookingBean bookingBean = new BookingBean(); bookingBean.setBookNo(orderBeans.get(position).getOrderId()); intent.putExtra("reserveBean", bookingBean); } else { intent = new Intent(getContext(), OrderDetailActivity.class); intent.putExtra(Constants.EXTRA_ORDER, orderBeans.get(position)); } startActivity(intent); } } }); } @Override protected void initDatas() { super.initDatas(); orderType = getArguments().getInt("orderType"); getOrders(orderType); } /** * 我的订单 */ private void getOrders(int type) { if (!NetUtils.isNetworkAvailable(getActivity().getApplicationContext())) { ToastUtils.shortToast(getActivity().getApplicationContext(), "当前网络不可用~"); return; } final JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("pageSize", pageSize); jsonObject.addProperty("pageNo", pageNo); jsonObject.addProperty("statusType", type); LogUtils.d(TAG, "jsonObject=" + jsonObject.toString()); String param = null; try { param = ThreeDesUtils.encryptThreeDESECB(jsonObject.toString(), sharedPrefsUtil.getString(Constants.USER_SECRET_KEY, "")); } catch (Exception e) { e.printStackTrace(); } destroyDis(); JSONObject jsonObject1 = new JSONObject(); try { jsonObject1.put("token", sharedPrefsUtil.getString(Constants.USER_TOKEN, "")); jsonObject1.put("param", param); } catch (JSONException e) { e.printStackTrace(); } RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), jsonObject1.toString()); ApiServiceFactory.getStringApiService() .getOrders(body) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<String>() { @Override public void onSubscribe(Disposable d) { orderDis = d; } @Override public void onNext(String stringResponse) { try { String result = ThreeDesUtils.decryptThreeDESECB(stringResponse.toString(), sharedPrefsUtil.getString(Constants.USER_SECRET_KEY, "")); LogUtils.d(TAG, "result=" + result); Gson gson = new Gson(); OrderResponse response = gson.fromJson(result, OrderResponse.class); if (response.isSuccess()) { if (null != response.getData().getOrdersMainVos() && response.getData() .getOrdersMainVos() .size() > 0) { if (pageNo == 1) { orderBeans.clear(); orderBeans.addAll(response.getData().getOrdersMainVos()); } else { orderBeans.addAll(response.getData().getOrdersMainVos()); } orderAdapter.clear(); orderAdapter.addAll(orderBeans); LogUtils.d(TAG, "size=" + orderAdapter.getAllData() .size() + ",orderbean.size=" + orderBeans .size()); pageNo = pageNo + 1; } else { if (pageNo == 1) { orderBeans.clear(); orderAdapter.clear(); } } total = response.getData().getCount(); } else { ToastUtils.shortToast(getActivity().getApplicationContext(), response.getMsg()); } } catch (Exception e) { e.printStackTrace(); } } @Override public void onError(Throwable e) { e.printStackTrace(); ToastUtils.shortToast(getContext().getApplicationContext(), "获取失败~"); } @Override public void onComplete() { } }); } private void destroyDis() { if (null != orderDis && !orderDis.isDisposed()) { orderDis.dispose(); } } @Subscribe(threadMode = ThreadMode.MAIN) public void Event(PayEvent payEvent) { pageNo = 1; getOrders(orderType); } @Subscribe(threadMode = ThreadMode.MAIN) public void Event(CancelEvent cancelEvent) { pageNo = 1; getOrders(orderType); } @Override public void onDestroy() { super.onDestroy(); destroyDis(); EventBus.getDefault().unregister(this); } @Override public void onRefresh() { pageNo = 1; getOrders(orderType); } @Override public void onLoadMore() { LogUtils.d(TAG, "[onLoadMore] pageNo=" + pageNo); // if(isMore){ if (orderAdapter.getCount() < total) { getOrders(orderType); } // } } @Override public void onNoMoreShow() { } @Override public void onNoMoreClick() { } }
UTF-8
Java
13,031
java
OrderFragment.java
Java
[]
null
[]
package com.sxy.healthcare.me; import android.annotation.SuppressLint; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.annotation.Nullable; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.text.TextUtils; import android.widget.Toast; import com.google.gson.Gson; import com.google.gson.JsonObject; import com.jude.easyrecyclerview.EasyRecyclerView; import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter; import com.sxy.healthcare.R; import com.sxy.healthcare.base.BaseFragment; import com.sxy.healthcare.base.Constants; import com.sxy.healthcare.common.net.ApiServiceFactory; import com.sxy.healthcare.common.utils.LogUtils; import com.sxy.healthcare.common.utils.NetUtils; import com.sxy.healthcare.common.utils.ThreeDesUtils; import com.sxy.healthcare.common.utils.ToastUtils; import com.sxy.healthcare.me.activity.OrderDetailActivity; import com.sxy.healthcare.me.activity.ReserveDetailActivity; import com.sxy.healthcare.me.adapter.OrderAdapter; import com.sxy.healthcare.me.bean.BookingBean; import com.sxy.healthcare.me.bean.OrderBean; import com.sxy.healthcare.me.bean.OrderResponse; import com.sxy.healthcare.me.bean.PayResult; import com.sxy.healthcare.me.event.CancelEvent; import com.sxy.healthcare.me.event.PayEvent; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import io.reactivex.Observer; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.Disposable; import io.reactivex.schedulers.Schedulers; import okhttp3.RequestBody; import static com.sxy.healthcare.me.adapter.OrderAdapter.SDK_PAY_FLAG; public class OrderFragment extends BaseFragment implements RecyclerArrayAdapter.OnLoadMoreListener, SwipeRefreshLayout.OnRefreshListener, RecyclerArrayAdapter.OnNoMoreListener { private static final String TAG = OrderFragment.class.getSimpleName(); @BindView(R.id.rc_order) EasyRecyclerView rcOrder; OrderAdapter orderAdapter; private List<OrderBean> orderBeans = new ArrayList<>(); private Disposable orderDis; private int pageSize = 20; private int pageNo = 1; private int total = 0; private boolean isMore = true; private int orderType = 0; @SuppressLint("HandlerLeak") private Handler mHandler = new Handler() { @SuppressWarnings("unused") public void handleMessage(Message msg) { switch (msg.what) { case SDK_PAY_FLAG: { PayResult payResult = new PayResult((String) msg.obj); /** * 同步返回的结果必须放置到服务端进行验证(验证的规则请看https://doc.open.alipay.com/doc2/ * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665& * docType=1) 建议商户依赖异步通知 */ String resultInfo = payResult.getResult();// 同步返回需要验证的信息 String resultStatus = payResult.getResultStatus(); // 判断resultStatus 为“9000”则代表支付成功,具体状态码代表含义可参考接口文档 if (TextUtils.equals(resultStatus, "9000")) { Toast.makeText(getContext(), "支付成功", Toast.LENGTH_SHORT).show(); orderAdapter.hideDialog(); pageNo = 1; getOrders(orderType); } else { // 判断resultStatus 为非"9000"则代表可能支付失败 // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认,最终交易是否成功以服务端异步通知为准(小概率状态) if (TextUtils.equals(resultStatus, "8000")) { Toast.makeText(getContext(), "支付结果确认中", Toast.LENGTH_SHORT).show(); } else { // 其他值就可以判断为支付失败,包括用户主动取消支付,或者系统返回的错误 Toast.makeText(getContext(), "支付失败", Toast.LENGTH_SHORT).show(); } } break; } default: break; } } }; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_order); EventBus.getDefault().register(this); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } @Override protected void initViews() { super.initViews(); orderAdapter = new OrderAdapter(getActivity(), getActivity().getSupportFragmentManager(), mHandler); rcOrder.setAdapter(orderAdapter); rcOrder.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false)); orderAdapter.setMore(R.layout.view_more, this); orderAdapter.setNoMore(R.layout.view_no_more, this); rcOrder.setRefreshListener(this); orderAdapter.pauseMore(); // final Intent intent = new Intent(getActivity(),OrderDetailActivity.class); orderAdapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() { @Override public void onItemClick(int position) { if (null != orderBeans) { /* intent.putExtra(Constants.EXTRA_ORDER,orderBeans.get(position)); startActivity(intent);*/ Intent intent; if ("2".equals(orderBeans.get(position).getOrderType())) { intent = new Intent(getContext(), ReserveDetailActivity.class); BookingBean bookingBean = new BookingBean(); bookingBean.setBookNo(orderBeans.get(position).getOrderId()); intent.putExtra("reserveBean", bookingBean); } else { intent = new Intent(getContext(), OrderDetailActivity.class); intent.putExtra(Constants.EXTRA_ORDER, orderBeans.get(position)); } startActivity(intent); } } }); } @Override protected void initDatas() { super.initDatas(); orderType = getArguments().getInt("orderType"); getOrders(orderType); } /** * 我的订单 */ private void getOrders(int type) { if (!NetUtils.isNetworkAvailable(getActivity().getApplicationContext())) { ToastUtils.shortToast(getActivity().getApplicationContext(), "当前网络不可用~"); return; } final JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("pageSize", pageSize); jsonObject.addProperty("pageNo", pageNo); jsonObject.addProperty("statusType", type); LogUtils.d(TAG, "jsonObject=" + jsonObject.toString()); String param = null; try { param = ThreeDesUtils.encryptThreeDESECB(jsonObject.toString(), sharedPrefsUtil.getString(Constants.USER_SECRET_KEY, "")); } catch (Exception e) { e.printStackTrace(); } destroyDis(); JSONObject jsonObject1 = new JSONObject(); try { jsonObject1.put("token", sharedPrefsUtil.getString(Constants.USER_TOKEN, "")); jsonObject1.put("param", param); } catch (JSONException e) { e.printStackTrace(); } RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), jsonObject1.toString()); ApiServiceFactory.getStringApiService() .getOrders(body) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<String>() { @Override public void onSubscribe(Disposable d) { orderDis = d; } @Override public void onNext(String stringResponse) { try { String result = ThreeDesUtils.decryptThreeDESECB(stringResponse.toString(), sharedPrefsUtil.getString(Constants.USER_SECRET_KEY, "")); LogUtils.d(TAG, "result=" + result); Gson gson = new Gson(); OrderResponse response = gson.fromJson(result, OrderResponse.class); if (response.isSuccess()) { if (null != response.getData().getOrdersMainVos() && response.getData() .getOrdersMainVos() .size() > 0) { if (pageNo == 1) { orderBeans.clear(); orderBeans.addAll(response.getData().getOrdersMainVos()); } else { orderBeans.addAll(response.getData().getOrdersMainVos()); } orderAdapter.clear(); orderAdapter.addAll(orderBeans); LogUtils.d(TAG, "size=" + orderAdapter.getAllData() .size() + ",orderbean.size=" + orderBeans .size()); pageNo = pageNo + 1; } else { if (pageNo == 1) { orderBeans.clear(); orderAdapter.clear(); } } total = response.getData().getCount(); } else { ToastUtils.shortToast(getActivity().getApplicationContext(), response.getMsg()); } } catch (Exception e) { e.printStackTrace(); } } @Override public void onError(Throwable e) { e.printStackTrace(); ToastUtils.shortToast(getContext().getApplicationContext(), "获取失败~"); } @Override public void onComplete() { } }); } private void destroyDis() { if (null != orderDis && !orderDis.isDisposed()) { orderDis.dispose(); } } @Subscribe(threadMode = ThreadMode.MAIN) public void Event(PayEvent payEvent) { pageNo = 1; getOrders(orderType); } @Subscribe(threadMode = ThreadMode.MAIN) public void Event(CancelEvent cancelEvent) { pageNo = 1; getOrders(orderType); } @Override public void onDestroy() { super.onDestroy(); destroyDis(); EventBus.getDefault().unregister(this); } @Override public void onRefresh() { pageNo = 1; getOrders(orderType); } @Override public void onLoadMore() { LogUtils.d(TAG, "[onLoadMore] pageNo=" + pageNo); // if(isMore){ if (orderAdapter.getCount() < total) { getOrders(orderType); } // } } @Override public void onNoMoreShow() { } @Override public void onNoMoreClick() { } }
13,031
0.528199
0.523598
335
36.632835
29.767248
124
false
false
0
0
0
0
0
0
0.555224
false
false
4
55834c0242fe065b82e0e4a6ee1136e84094448d
21,990,232,620,193
b57a612311043eb25720bab4018b29f7c3d21050
/src/com/ceair/cuss/checkin/service/CussCheckinLogService.java
97c440368a54d3b2e6e801f023cd4bcd52435bc1
[]
no_license
yjw0112/httpinvoke
https://github.com/yjw0112/httpinvoke
25015f4fcc7229dd38383987eafec688544224e9
1e0b958a6a607706711d206e659ff05ff8a7721e
refs/heads/master
2016-09-05T19:58:33.350000
2014-07-15T05:24:27
2014-07-15T05:24:27
20,489,859
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * China Eastern Airlines. * Copyright (c) 1999-2014 All Rights Reserved. */ package com.ceair.cuss.checkin.service; import java.util.List; import java.util.Map; import cn.sh.cares.core.pagination.OrderablePagination; import com.ceair.cuss.checkin.entity.CussCheckinLog; /** * 应用-旅客(值机)操作日志Service接口.kiosk值机(或里程查询等其他操作)的失败与成功操作记录集. * @author 徐正 * @version $Id: CussCheckinLogService.java, v 0.1 2014-3-13 上午10:16:16 徐正 Exp $ */ public interface CussCheckinLogService { /** * 分页查询值机操作日志. * @param pagination * @param params * @return */ public List<CussCheckinLog> queryCussCheckinLogs(OrderablePagination pagination, Map<String, Object> params); /** * 查询全部值机操作日志. * @param params * @return */ public List<CussCheckinLog> queryAllCussCheckinLogs(Map<String, Object> params); /** * 保存值机操作日志. * @param cussCheckinLog */ public void doSaveCussCheckinLog(CussCheckinLog cussCheckinLog); /** * 逻辑删除值机操作日志. * @param cussCheckinLogId */ public void doDeleteCussCheckinLog(Long cussCheckinLogId); /** * 逻辑删除多条值机操作日志. * @param cussCheckinLogIds */ public void doDeleteCussCheckinLogs(Long[] cussCheckinLogIds); }
UTF-8
Java
1,435
java
CussCheckinLogService.java
Java
[ { "context": "vice接口.kiosk值机(或里程查询等其他操作)的失败与成功操作记录集.\n * @author 徐正\n * @version $Id: CussCheckinLogService.java, v 0.", "end": 356, "score": 0.9993374347686768, "start": 354, "tag": "NAME", "value": "徐正" }, { "context": "heckinLogService.java, v 0.1 2014-3-13 上午10:16:16 徐正 Exp $\n */\npublic interface CussCheckinLogService ", "end": 431, "score": 0.9973674416542053, "start": 429, "tag": "NAME", "value": "徐正" } ]
null
[]
/** * China Eastern Airlines. * Copyright (c) 1999-2014 All Rights Reserved. */ package com.ceair.cuss.checkin.service; import java.util.List; import java.util.Map; import cn.sh.cares.core.pagination.OrderablePagination; import com.ceair.cuss.checkin.entity.CussCheckinLog; /** * 应用-旅客(值机)操作日志Service接口.kiosk值机(或里程查询等其他操作)的失败与成功操作记录集. * @author 徐正 * @version $Id: CussCheckinLogService.java, v 0.1 2014-3-13 上午10:16:16 徐正 Exp $ */ public interface CussCheckinLogService { /** * 分页查询值机操作日志. * @param pagination * @param params * @return */ public List<CussCheckinLog> queryCussCheckinLogs(OrderablePagination pagination, Map<String, Object> params); /** * 查询全部值机操作日志. * @param params * @return */ public List<CussCheckinLog> queryAllCussCheckinLogs(Map<String, Object> params); /** * 保存值机操作日志. * @param cussCheckinLog */ public void doSaveCussCheckinLog(CussCheckinLog cussCheckinLog); /** * 逻辑删除值机操作日志. * @param cussCheckinLogId */ public void doDeleteCussCheckinLog(Long cussCheckinLogId); /** * 逻辑删除多条值机操作日志. * @param cussCheckinLogIds */ public void doDeleteCussCheckinLogs(Long[] cussCheckinLogIds); }
1,435
0.67917
0.660814
54
22.203703
25.485203
113
false
false
0
0
0
0
0
0
0.259259
false
false
4
a8bac51b98f86e3e5e38a6cba791f88438f08ecc
14,216,341,804,382
de7d213f88af6d2c89fe2de483fa4b11f1a634b6
/VehicleInvetoryService/src/main/java/com/visu/vehicleInventory/controller/VehicleInventoryController.java
9f8fc010214ffa1ab53e6e5e078ec5f8ec6fd64e
[]
no_license
Visu451/vehicle-inventory
https://github.com/Visu451/vehicle-inventory
5032da14886beb3d1544a84031fdb599acf41db9
b2385378eebb643c8d89b4a761e61e81e12286dd
refs/heads/master
2020-03-20T11:54:38.589000
2018-06-18T06:28:45
2018-06-18T06:28:45
137,415,793
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.visu.vehicleInventory.controller; import java.util.List; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.visu.vehicleInventory.model.Vehicle; import com.visu.vehicleInventory.repository.VehicleInvetoryRepository; @RestController @RequestMapping("/vehicleInventory") public class VehicleInventoryController { public static final Logger logger = LoggerFactory.getLogger(VehicleInventoryController.class); @Autowired VehicleInvetoryRepository repository; @GetMapping("/findAll") public ResponseEntity<List<Vehicle>> findAll() { List<Vehicle> vehicles = repository.findAll(); if (vehicles.isEmpty()) { return new ResponseEntity<List<Vehicle>>(HttpStatus.NO_CONTENT); //HttpStatus.NOT_FOUND } return new ResponseEntity<List<Vehicle>>(vehicles, HttpStatus.OK); } @GetMapping("/findById") public ResponseEntity<?> fetchVehicleById(@RequestParam("id") Long id) { Optional<Vehicle> vehicle = repository.findById(id); if (!vehicle.isPresent()) { return new ResponseEntity<List<Vehicle>>(HttpStatus.NOT_FOUND); } return new ResponseEntity<Vehicle>(vehicle.get(), HttpStatus.OK); } @GetMapping("/findByName") public ResponseEntity<List<Vehicle>> fetchVehicleByName(@RequestParam("name") String name) { List<Vehicle> vehicles = repository.findByName(name); if (!vehicles.isEmpty()) { return new ResponseEntity<List<Vehicle>>(HttpStatus.NOT_FOUND); } return new ResponseEntity<List<Vehicle>>(vehicles, HttpStatus.OK); } @PostMapping("/addVehicle") public ResponseEntity<?> createVehicle(@RequestBody Vehicle vehicle) { List<Vehicle> v = repository.findByNameAndYearAndMakeAndModelAndModeOfTravel(vehicle.getName(), vehicle.getYear(), vehicle.getMake(), vehicle.getModel(), vehicle.getModeOfTravel()); if (null != v && !v.isEmpty()) { logger.error("Unable to create. A vehicle with the same details already exists", vehicle.toString()); return new ResponseEntity<String>("Unable to create. A vehicle with the same details already exists", HttpStatus.CONFLICT); } repository.save(vehicle); return new ResponseEntity<Vehicle>(HttpStatus.CREATED); } @PutMapping("/updateVehicle") public ResponseEntity<?> updateVehicleById(@RequestParam("id") Long id, @RequestBody Vehicle vehicle) { Optional<Vehicle> v = repository.findById(id); if (!v.isPresent()) { logger.error("Unable to update. A vehicle with id"+ id +" does not exist"); return ResponseEntity.notFound().build(); } vehicle.setId(id); repository.save(vehicle); return ResponseEntity.ok().build(); } @DeleteMapping("/deleteVehicle") public ResponseEntity<?> deleteVehicle(@RequestParam("id") Long id) { Optional<Vehicle> v = repository.findById(id); if (!v.isPresent()) { logger.error("Unable to delete. A vehicle with id"+ id +" does not exist"); return ResponseEntity.notFound().build(); } repository.deleteById(id); return ResponseEntity.ok().build(); } @DeleteMapping("/deleteLastAddedVehicle") public ResponseEntity<?> deleteVehicle() { Optional<Vehicle> v = repository.findFirstByOrderByCreatedAtDesc(); if (!v.isPresent()) { logger.error("Unable to delete. No vehicles found."); return ResponseEntity.noContent().build(); } repository.deleteById(v.get().getId()); return ResponseEntity.ok().build(); } }
UTF-8
Java
4,134
java
VehicleInventoryController.java
Java
[]
null
[]
package com.visu.vehicleInventory.controller; import java.util.List; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.visu.vehicleInventory.model.Vehicle; import com.visu.vehicleInventory.repository.VehicleInvetoryRepository; @RestController @RequestMapping("/vehicleInventory") public class VehicleInventoryController { public static final Logger logger = LoggerFactory.getLogger(VehicleInventoryController.class); @Autowired VehicleInvetoryRepository repository; @GetMapping("/findAll") public ResponseEntity<List<Vehicle>> findAll() { List<Vehicle> vehicles = repository.findAll(); if (vehicles.isEmpty()) { return new ResponseEntity<List<Vehicle>>(HttpStatus.NO_CONTENT); //HttpStatus.NOT_FOUND } return new ResponseEntity<List<Vehicle>>(vehicles, HttpStatus.OK); } @GetMapping("/findById") public ResponseEntity<?> fetchVehicleById(@RequestParam("id") Long id) { Optional<Vehicle> vehicle = repository.findById(id); if (!vehicle.isPresent()) { return new ResponseEntity<List<Vehicle>>(HttpStatus.NOT_FOUND); } return new ResponseEntity<Vehicle>(vehicle.get(), HttpStatus.OK); } @GetMapping("/findByName") public ResponseEntity<List<Vehicle>> fetchVehicleByName(@RequestParam("name") String name) { List<Vehicle> vehicles = repository.findByName(name); if (!vehicles.isEmpty()) { return new ResponseEntity<List<Vehicle>>(HttpStatus.NOT_FOUND); } return new ResponseEntity<List<Vehicle>>(vehicles, HttpStatus.OK); } @PostMapping("/addVehicle") public ResponseEntity<?> createVehicle(@RequestBody Vehicle vehicle) { List<Vehicle> v = repository.findByNameAndYearAndMakeAndModelAndModeOfTravel(vehicle.getName(), vehicle.getYear(), vehicle.getMake(), vehicle.getModel(), vehicle.getModeOfTravel()); if (null != v && !v.isEmpty()) { logger.error("Unable to create. A vehicle with the same details already exists", vehicle.toString()); return new ResponseEntity<String>("Unable to create. A vehicle with the same details already exists", HttpStatus.CONFLICT); } repository.save(vehicle); return new ResponseEntity<Vehicle>(HttpStatus.CREATED); } @PutMapping("/updateVehicle") public ResponseEntity<?> updateVehicleById(@RequestParam("id") Long id, @RequestBody Vehicle vehicle) { Optional<Vehicle> v = repository.findById(id); if (!v.isPresent()) { logger.error("Unable to update. A vehicle with id"+ id +" does not exist"); return ResponseEntity.notFound().build(); } vehicle.setId(id); repository.save(vehicle); return ResponseEntity.ok().build(); } @DeleteMapping("/deleteVehicle") public ResponseEntity<?> deleteVehicle(@RequestParam("id") Long id) { Optional<Vehicle> v = repository.findById(id); if (!v.isPresent()) { logger.error("Unable to delete. A vehicle with id"+ id +" does not exist"); return ResponseEntity.notFound().build(); } repository.deleteById(id); return ResponseEntity.ok().build(); } @DeleteMapping("/deleteLastAddedVehicle") public ResponseEntity<?> deleteVehicle() { Optional<Vehicle> v = repository.findFirstByOrderByCreatedAtDesc(); if (!v.isPresent()) { logger.error("Unable to delete. No vehicles found."); return ResponseEntity.noContent().build(); } repository.deleteById(v.get().getId()); return ResponseEntity.ok().build(); } }
4,134
0.7373
0.736817
105
37.371429
32.33493
182
false
false
0
0
0
0
0
0
0.8
false
false
4
610f204ca537a186e79cd37a0e09fa34b1ad3708
19,026,705,188,784
a16b649c30e4c6793383ce6ea58b509e2296ede8
/app/src/main/java/wgz/com/cx_ga_project/activity/FullscreenActivity.java
c28d3658fcb988c095365abee20d5ac32efb1eaa
[]
no_license
ultranumblol/CX_GA_Project2
https://github.com/ultranumblol/CX_GA_Project2
a9c865d948a77f1ccc53c6da1d64a80a376de367
666601cee1db6b5fc59c452b170a5c1cc46e02a9
refs/heads/master
2020-12-06T18:54:52.172000
2017-01-10T03:43:58
2017-01-10T03:43:58
67,773,637
0
0
null
false
2017-01-10T03:43:59
2016-09-09T06:45:52
2016-09-09T07:08:39
2017-01-10T03:43:59
41,202
0
0
0
Java
null
null
package wgz.com.cx_ga_project.activity; import android.annotation.SuppressLint; import android.graphics.Bitmap; import android.os.Bundle; import android.os.Handler; import android.support.v7.app.ActionBar; import android.view.MotionEvent; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.bumptech.glide.request.animation.GlideAnimation; import com.bumptech.glide.request.target.SimpleTarget; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; import java.util.Hashtable; import butterknife.Bind; import butterknife.ButterKnife; import wgz.com.cx_ga_project.R; import wgz.com.cx_ga_project.app; import wgz.com.cx_ga_project.base.BaseActivity; import wgz.com.cx_ga_project.base.Constant; import wgz.com.cx_ga_project.util.SPUtils; import wgz.com.cx_ga_project.util.SomeUtil; /** * 我的二维码页面 * An example full-screen activity that shows and hides the system UI (i.e. * status bar and navigation/system bar) with user interaction. */ public class FullscreenActivity extends BaseActivity { /** * Whether or not the system UI should be auto-hidden after * {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds. */ private static final boolean AUTO_HIDE = true; private static final int QR_HEIGHT = 280; private static final int QR_WIDTH = 280; /** * If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after * user interaction before hiding the system UI. */ private static final int AUTO_HIDE_DELAY_MILLIS = 3000; /** * Some older devices needs a small delay between UI widget updates * and a change of the status and navigation bar. */ private static final int UI_ANIMATION_DELAY = 300; private final Handler mHideHandler = new Handler(); @Bind(R.id.fullscreen_content) ImageView mContentView; @Bind(R.id.fullscreen_content_controls) LinearLayout mControlsView; private final Runnable mHidePart2Runnable = new Runnable() { @SuppressLint("InlinedApi") @Override public void run() { // Delayed removal of status and navigation bar // Note that some of these constants are new as of API 16 (Jelly Bean) // and API 19 (KitKat). It is safe to use them, as they are inlined // at compile-time and do nothing on earlier devices. mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION); } }; private final Runnable mShowPart2Runnable = new Runnable() { @Override public void run() { // Delayed display of UI elements ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.show(); } mControlsView.setVisibility(View.VISIBLE); } }; private boolean mVisible; private final Runnable mHideRunnable = () -> hide(); /** * Touch listener to use for in-layout UI controls to delay hiding the * system UI. This is to prevent the jarring behavior of controls going away * while interacting with activity UI. */ private final View.OnTouchListener mDelayHideTouchListener = (view, motionEvent) -> { if (AUTO_HIDE) { delayedHide(AUTO_HIDE_DELAY_MILLIS); } return false; }; @Override public int getLayoutId() { return R.layout.activity_fullscreen; } @Override public void initView() { setTitle("我的二维码"); getSupportActionBar().setDisplayHomeAsUpEnabled(true); mVisible = true; // Set up the user interaction to manually show or hide the system UI. mContentView.setOnClickListener(view -> toggle()); createQRImage("警员:"+ SPUtils.get(app.getApp().getApplicationContext(), Constant.USERNAME, "未知")+"\n"+"部门:"+SomeUtil.getDepartName()); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Trigger the initial hide() shortly after the activity has been // created, to briefly hint to the user that UI controls // are available. delayedHide(100); } private void toggle() { if (mVisible) { hide(); } else { show(); } } private void hide() { // Hide UI first ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.hide(); } mControlsView.setVisibility(View.GONE); mVisible = false; // Schedule a runnable to remove the status and navigation bar after a delay mHideHandler.removeCallbacks(mShowPart2Runnable); mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY); } @SuppressLint("InlinedApi") private void show() { // Show the system bar mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION); mVisible = true; // Schedule a runnable to display UI elements after a delay mHideHandler.removeCallbacks(mHidePart2Runnable); mHideHandler.postDelayed(mShowPart2Runnable, UI_ANIMATION_DELAY); } /** * Schedules a call to hide() in [delay] milliseconds, canceling any * previously scheduled calls. */ private void delayedHide(int delayMillis) { mHideHandler.removeCallbacks(mHideRunnable); mHideHandler.postDelayed(mHideRunnable, delayMillis); } public void createQRImage(String url) { try { //判断URL合法性 if (url == null || "".equals(url) || url.length() < 1) { return; } Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>(); hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); //图像数据转换,使用了矩阵转换 BitMatrix bitMatrix = new QRCodeWriter().encode(url, BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT, hints); int[] pixels = new int[QR_WIDTH * QR_HEIGHT]; //下面这里按照二维码的算法,逐个生成二维码的图片, //两个for循环是图片横列扫描的结果 for (int y = 0; y < QR_HEIGHT; y++) { for (int x = 0; x < QR_WIDTH; x++) { if (bitMatrix.get(x, y)) { pixels[y * QR_WIDTH + x] = 0xff000000; } else { pixels[y * QR_WIDTH + x] = 0xffffffff; } } } //生成二维码图片的格式,使用ARGB_8888 Bitmap bitmap = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT, Bitmap.Config.ARGB_8888); bitmap.setPixels(pixels, 0, QR_WIDTH, 0, 0, QR_WIDTH, QR_HEIGHT); //显示到一个ImageView上面 mContentView.setImageBitmap(bitmap); /*SimpleTarget target = new SimpleTarget<Bitmap>(280,280) { @Override public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) { mContentView.setImageBitmap(resource); } };*/ /*Glide.with(this) .load(bitmap) .diskCacheStrategy(DiskCacheStrategy.ALL) .dontAnimate() .into(mContentView);*/ } catch (WriterException e) { e.printStackTrace(); } } }
UTF-8
Java
8,293
java
FullscreenActivity.java
Java
[]
null
[]
package wgz.com.cx_ga_project.activity; import android.annotation.SuppressLint; import android.graphics.Bitmap; import android.os.Bundle; import android.os.Handler; import android.support.v7.app.ActionBar; import android.view.MotionEvent; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.bumptech.glide.request.animation.GlideAnimation; import com.bumptech.glide.request.target.SimpleTarget; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; import java.util.Hashtable; import butterknife.Bind; import butterknife.ButterKnife; import wgz.com.cx_ga_project.R; import wgz.com.cx_ga_project.app; import wgz.com.cx_ga_project.base.BaseActivity; import wgz.com.cx_ga_project.base.Constant; import wgz.com.cx_ga_project.util.SPUtils; import wgz.com.cx_ga_project.util.SomeUtil; /** * 我的二维码页面 * An example full-screen activity that shows and hides the system UI (i.e. * status bar and navigation/system bar) with user interaction. */ public class FullscreenActivity extends BaseActivity { /** * Whether or not the system UI should be auto-hidden after * {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds. */ private static final boolean AUTO_HIDE = true; private static final int QR_HEIGHT = 280; private static final int QR_WIDTH = 280; /** * If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after * user interaction before hiding the system UI. */ private static final int AUTO_HIDE_DELAY_MILLIS = 3000; /** * Some older devices needs a small delay between UI widget updates * and a change of the status and navigation bar. */ private static final int UI_ANIMATION_DELAY = 300; private final Handler mHideHandler = new Handler(); @Bind(R.id.fullscreen_content) ImageView mContentView; @Bind(R.id.fullscreen_content_controls) LinearLayout mControlsView; private final Runnable mHidePart2Runnable = new Runnable() { @SuppressLint("InlinedApi") @Override public void run() { // Delayed removal of status and navigation bar // Note that some of these constants are new as of API 16 (Jelly Bean) // and API 19 (KitKat). It is safe to use them, as they are inlined // at compile-time and do nothing on earlier devices. mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION); } }; private final Runnable mShowPart2Runnable = new Runnable() { @Override public void run() { // Delayed display of UI elements ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.show(); } mControlsView.setVisibility(View.VISIBLE); } }; private boolean mVisible; private final Runnable mHideRunnable = () -> hide(); /** * Touch listener to use for in-layout UI controls to delay hiding the * system UI. This is to prevent the jarring behavior of controls going away * while interacting with activity UI. */ private final View.OnTouchListener mDelayHideTouchListener = (view, motionEvent) -> { if (AUTO_HIDE) { delayedHide(AUTO_HIDE_DELAY_MILLIS); } return false; }; @Override public int getLayoutId() { return R.layout.activity_fullscreen; } @Override public void initView() { setTitle("我的二维码"); getSupportActionBar().setDisplayHomeAsUpEnabled(true); mVisible = true; // Set up the user interaction to manually show or hide the system UI. mContentView.setOnClickListener(view -> toggle()); createQRImage("警员:"+ SPUtils.get(app.getApp().getApplicationContext(), Constant.USERNAME, "未知")+"\n"+"部门:"+SomeUtil.getDepartName()); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Trigger the initial hide() shortly after the activity has been // created, to briefly hint to the user that UI controls // are available. delayedHide(100); } private void toggle() { if (mVisible) { hide(); } else { show(); } } private void hide() { // Hide UI first ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.hide(); } mControlsView.setVisibility(View.GONE); mVisible = false; // Schedule a runnable to remove the status and navigation bar after a delay mHideHandler.removeCallbacks(mShowPart2Runnable); mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY); } @SuppressLint("InlinedApi") private void show() { // Show the system bar mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION); mVisible = true; // Schedule a runnable to display UI elements after a delay mHideHandler.removeCallbacks(mHidePart2Runnable); mHideHandler.postDelayed(mShowPart2Runnable, UI_ANIMATION_DELAY); } /** * Schedules a call to hide() in [delay] milliseconds, canceling any * previously scheduled calls. */ private void delayedHide(int delayMillis) { mHideHandler.removeCallbacks(mHideRunnable); mHideHandler.postDelayed(mHideRunnable, delayMillis); } public void createQRImage(String url) { try { //判断URL合法性 if (url == null || "".equals(url) || url.length() < 1) { return; } Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>(); hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); //图像数据转换,使用了矩阵转换 BitMatrix bitMatrix = new QRCodeWriter().encode(url, BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT, hints); int[] pixels = new int[QR_WIDTH * QR_HEIGHT]; //下面这里按照二维码的算法,逐个生成二维码的图片, //两个for循环是图片横列扫描的结果 for (int y = 0; y < QR_HEIGHT; y++) { for (int x = 0; x < QR_WIDTH; x++) { if (bitMatrix.get(x, y)) { pixels[y * QR_WIDTH + x] = 0xff000000; } else { pixels[y * QR_WIDTH + x] = 0xffffffff; } } } //生成二维码图片的格式,使用ARGB_8888 Bitmap bitmap = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT, Bitmap.Config.ARGB_8888); bitmap.setPixels(pixels, 0, QR_WIDTH, 0, 0, QR_WIDTH, QR_HEIGHT); //显示到一个ImageView上面 mContentView.setImageBitmap(bitmap); /*SimpleTarget target = new SimpleTarget<Bitmap>(280,280) { @Override public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) { mContentView.setImageBitmap(resource); } };*/ /*Glide.with(this) .load(bitmap) .diskCacheStrategy(DiskCacheStrategy.ALL) .dontAnimate() .into(mContentView);*/ } catch (WriterException e) { e.printStackTrace(); } } }
8,293
0.614767
0.607853
232
33.909481
26.172102
141
false
false
0
0
0
0
0
0
0.538793
false
false
4
dc4832bcfe9023d9cf17ff61ce78fd6288f69fc4
20,615,843,077,100
31e5a2c1e49c063ef2d2829e34f76519c3e0c81d
/5IAS/TPSIT/DizioServlet/src/app/Definizione.java
bef3dd5fbe73aec012ffdd95e75b291f686ecffc
[]
no_license
firegardenn/School
https://github.com/firegardenn/School
94035c5c917958444153309aed859aacfe69e5e5
e991e218da815f928fc6430513a4fb09e2ad680c
refs/heads/master
2020-11-27T12:01:25.824000
2019-12-21T18:19:44
2019-12-21T18:19:44
229,430,238
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package app; public class Definizione{ public String parola; public String sinonimo; public String contrario; public Definizione( String parola, String sinonimo, String contrario) { this.parola = parola; this.sinonimo = sinonimo; this.contrario = contrario; } public Definizione( String parola) { this.parola = parola; } public String getParola() { return this.parola; } public String getSinonimo() { return this.sinonimo; } public String getContrario() { return this.contrario; } public void setParola(String parola) { this.parola = parola; } public void setContrario( String contrario) { this.contrario=contrario; } public void setSinonimo( String sinonimo) { this.sinonimo=sinonimo; } public String stampaDef(){ return this.getParola() + " --> sinonimi: " + this.getSinonimo() + "; contrari : " + this.getContrario(); } }
UTF-8
Java
1,002
java
Definizione.java
Java
[]
null
[]
package app; public class Definizione{ public String parola; public String sinonimo; public String contrario; public Definizione( String parola, String sinonimo, String contrario) { this.parola = parola; this.sinonimo = sinonimo; this.contrario = contrario; } public Definizione( String parola) { this.parola = parola; } public String getParola() { return this.parola; } public String getSinonimo() { return this.sinonimo; } public String getContrario() { return this.contrario; } public void setParola(String parola) { this.parola = parola; } public void setContrario( String contrario) { this.contrario=contrario; } public void setSinonimo( String sinonimo) { this.sinonimo=sinonimo; } public String stampaDef(){ return this.getParola() + " --> sinonimi: " + this.getSinonimo() + "; contrari : " + this.getContrario(); } }
1,002
0.61976
0.61976
37
26.108109
22.158867
113
false
false
0
0
0
0
0
0
0.486486
false
false
4
d8efc3235c576d37354cbdd5c09f033e47220ce8
29,772,713,353,362
c61aa74d6eb0528df7006722e6a3538c7c8d2286
/SprinIbatis/src/com/ibatis/poc/controller/Login.java
2e6db19fe1d7ae06eaa2595dac562288253f1932
[]
no_license
venkatesh-buddy/SpringHibernateEg
https://github.com/venkatesh-buddy/SpringHibernateEg
514fca98b088fede0eb24291f408f132d227f7d0
d42cbf6b94d335da94bb07d1d53848301b520326
refs/heads/master
2020-05-04T13:55:02.551000
2014-06-27T07:14:11
2014-06-27T07:14:11
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ibatis.poc.controller; import java.util.Iterator; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.jasper.tagplugins.jstl.core.Redirect; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.ibatis.poc.user.daoImplementation.UserDAOImplementation; import com.ibatis.poc.user.model.UserModel; @Controller @RequestMapping("/*") public class Login { private String path; @Autowired public UserDAOImplementation userImplementation; public UserModel userModel; public Login() { path = "/"; } @RequestMapping(value ="index.do", method=RequestMethod.GET) public ModelAndView getLoginPage(HttpServletRequest request, HttpServletResponse response){ ModelAndView mv = new ModelAndView(path + "index"); /*List<UserModel> model = userImplementation.listUsers(); System.out.println("MODLfE***"+model.size()); for(UserModel md: model){ System.out.println("user***"+md.getUserName()); }*/ /*Iterator<UserModel> it = model.iterator(); while(it.hasNext()){ System.out.println("itere***"+it.next().getUserName()); } System.out.println("ni****"+model); for(int i=0; i< model.size(); ++i){ UserModel u = model.get(i); System.out.println("user name***"+u.getUserName()); }*/ /*UserModel userValidate = userImplementation.getValidUser(""); System.out.println("from ibatis***"+userValidate.getUserName()+"**** password***"+userValidate.getPassword());*/ // Mar 24 2013 /*System.out.println("in login action is"); List<UserModel> userValidate = userImplementation.getListUser(""); for(UserModel modelList:userValidate){ System.out.println("User ID****"+modelList.getUserId()); }*/ return mv; } @RequestMapping(value ="index.do", method =RequestMethod.POST) public ModelAndView postLogin(@ModelAttribute("userModel") UserModel userModel, HttpServletRequest request, HttpServletResponse response){ ModelAndView mv; System.out.println("post method***"); int validateCount = userImplementation.getValidUser(userModel); System.out.println("validateCount***"+validateCount); if(validateCount <= 0){ System.out.println("failed****"); mv = new ModelAndView(path + "index"); mv.addObject("status", "failed"); } else { mv = new ModelAndView("redirect:project/index.do"); } return mv; } }
UTF-8
Java
2,689
java
Login.java
Java
[]
null
[]
package com.ibatis.poc.controller; import java.util.Iterator; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.jasper.tagplugins.jstl.core.Redirect; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.ibatis.poc.user.daoImplementation.UserDAOImplementation; import com.ibatis.poc.user.model.UserModel; @Controller @RequestMapping("/*") public class Login { private String path; @Autowired public UserDAOImplementation userImplementation; public UserModel userModel; public Login() { path = "/"; } @RequestMapping(value ="index.do", method=RequestMethod.GET) public ModelAndView getLoginPage(HttpServletRequest request, HttpServletResponse response){ ModelAndView mv = new ModelAndView(path + "index"); /*List<UserModel> model = userImplementation.listUsers(); System.out.println("MODLfE***"+model.size()); for(UserModel md: model){ System.out.println("user***"+md.getUserName()); }*/ /*Iterator<UserModel> it = model.iterator(); while(it.hasNext()){ System.out.println("itere***"+it.next().getUserName()); } System.out.println("ni****"+model); for(int i=0; i< model.size(); ++i){ UserModel u = model.get(i); System.out.println("user name***"+u.getUserName()); }*/ /*UserModel userValidate = userImplementation.getValidUser(""); System.out.println("from ibatis***"+userValidate.getUserName()+"**** password***"+userValidate.getPassword());*/ // Mar 24 2013 /*System.out.println("in login action is"); List<UserModel> userValidate = userImplementation.getListUser(""); for(UserModel modelList:userValidate){ System.out.println("User ID****"+modelList.getUserId()); }*/ return mv; } @RequestMapping(value ="index.do", method =RequestMethod.POST) public ModelAndView postLogin(@ModelAttribute("userModel") UserModel userModel, HttpServletRequest request, HttpServletResponse response){ ModelAndView mv; System.out.println("post method***"); int validateCount = userImplementation.getValidUser(userModel); System.out.println("validateCount***"+validateCount); if(validateCount <= 0){ System.out.println("failed****"); mv = new ModelAndView(path + "index"); mv.addObject("status", "failed"); } else { mv = new ModelAndView("redirect:project/index.do"); } return mv; } }
2,689
0.735961
0.732986
79
33.037975
26.693499
116
false
false
0
0
0
0
0
0
1.860759
false
false
4
3fbdc32df6316d0fdcea2fc96ef23047a5fc4159
22,952,305,284,375
8b5ac42163fadb4d8d9e59c7b8206380e0c704ef
/app/src/main/java/com/yunduansing/app/ui/activity/WelcomeActivity.java
22e738deefb9b8030672457b5db19fc0e439a0ca
[]
no_license
yunduansing/app
https://github.com/yunduansing/app
501b04a6f78672a4c75a67be608fea951439a0ba
87d57f775f76755a33e7669d428119c60948397e
refs/heads/master
2017-12-01T09:02:22.168000
2016-08-14T14:27:56
2016-08-14T14:27:56
63,771,291
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yunduansing.app.ui.activity; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.Window; import com.yunduansing.app.R; import org.xutils.view.annotation.ContentView; @ContentView(R.layout.activity_welcome) public class WelcomeActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); } }
UTF-8
Java
496
java
WelcomeActivity.java
Java
[]
null
[]
package com.yunduansing.app.ui.activity; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.Window; import com.yunduansing.app.R; import org.xutils.view.annotation.ContentView; @ContentView(R.layout.activity_welcome) public class WelcomeActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); } }
496
0.778226
0.77621
19
25.105263
21.098503
56
false
false
0
0
0
0
0
0
0.421053
false
false
4
8c448506264969fe3f842b51457429e6bb4cd5b9
33,973,191,329,487
0e9f79b56a35170792572581cf050cc72ad4cee2
/app/src/main/java/com/tribe/app/presentation/mvp/view/ProfileMVPView.java
d0257569f5266dd6634de69d13121b8a877a9e62
[]
no_license
madaaf/tribe
https://github.com/madaaf/tribe
b9b29d1437b475f43ba0427ddc1bd1c5984f77b9
f60ea60d92aea30eb405acae187a58f82fa71a76
refs/heads/master
2021-09-26T18:02:23.998000
2018-04-13T01:16:38
2018-04-13T01:23:04
155,593,186
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tribe.app.presentation.mvp.view; import com.tribe.app.domain.entity.Room; public interface ProfileMVPView extends UpdateUserMVPView { void goToLauncher(); void onCreateRoom(Room room); }
UTF-8
Java
207
java
ProfileMVPView.java
Java
[]
null
[]
package com.tribe.app.presentation.mvp.view; import com.tribe.app.domain.entity.Room; public interface ProfileMVPView extends UpdateUserMVPView { void goToLauncher(); void onCreateRoom(Room room); }
207
0.78744
0.78744
10
19.700001
21.40584
59
false
false
0
0
0
0
0
0
0.4
false
false
4
c612a9cf4bb9def4a959c4fe899ae5983d723120
33,973,191,330,575
740a1f7b181ebb3adb65d84efea8b7a0951fabaf
/CommonLib/src/main/java/com/puhui/lib/base/IBaseView.java
fb198abf4e1e2feccbf043624ad417b184c47b0c
[]
no_license
tangjian211085/ESKY
https://github.com/tangjian211085/ESKY
e64839fb18c597f94cbda13597681d0f50a15a42
d60afea2df8423aa288b07a5d9a63564de866914
refs/heads/master
2020-05-27T08:45:42.221000
2019-06-04T23:38:16
2019-06-04T23:38:16
188,552,847
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.puhui.lib.base; import android.content.Context; public interface IBaseView { void showToast(String content); Context getContext(); BaseActivity getActivity(); void startLoading(); void stopLoading(); }
UTF-8
Java
240
java
IBaseView.java
Java
[]
null
[]
package com.puhui.lib.base; import android.content.Context; public interface IBaseView { void showToast(String content); Context getContext(); BaseActivity getActivity(); void startLoading(); void stopLoading(); }
240
0.708333
0.708333
15
15
14.179798
35
false
false
0
0
0
0
0
0
0.466667
false
false
4
340b46a88316555620b71802448d726c9a087131
35,777,077,585,420
b63d55f6d629373a0881b8c37ee4bdd51ecf0f8f
/assesment-backend/src/main/java/fse/assesment/assignment/repository/UserRepository.java
a9ba2302958e61fb37a7d226ca5efb888097bec5
[]
no_license
javedsheikh713/Final-Assessment
https://github.com/javedsheikh713/Final-Assessment
67df4beb6a18629a208e97fd6725e06af5d60e67
2b8709d38708298d89bc3499b2b92f7e79bf0208
refs/heads/master
2023-01-09T16:10:02.896000
2019-12-28T07:37:36
2019-12-28T07:37:36
230,556,170
0
0
null
false
2023-01-07T13:14:01
2019-12-28T04:06:37
2019-12-28T07:37:57
2023-01-07T13:14:00
29,755
0
0
29
JavaScript
false
false
package fse.assesment.assignment.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import fse.assesment.assignment.entity.User; public interface UserRepository extends JpaRepository<User, Long> { public User findByEmployeeId(String employeeId); public List<User> findByFirstNameContaining(String searchText); public User findByTaskId(long taskId); }
UTF-8
Java
407
java
UserRepository.java
Java
[]
null
[]
package fse.assesment.assignment.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import fse.assesment.assignment.entity.User; public interface UserRepository extends JpaRepository<User, Long> { public User findByEmployeeId(String employeeId); public List<User> findByFirstNameContaining(String searchText); public User findByTaskId(long taskId); }
407
0.823096
0.823096
15
26.133333
26.257359
67
false
false
0
0
0
0
0
0
0.8
false
false
4
3315d97406178fe3f8ddb6c6d02cfd307e4e60e2
18,167,711,689,367
281cf20e83b6d4b6af45cedb0cf2ac99f8163209
/src/main/java/com/intive/patronative/repository/UserSearchRepositoryImpl.java
3a1a47703920272aca04a59789f004b16573bc14
[]
no_license
intive/patronage21-java
https://github.com/intive/patronage21-java
f55709cefda25934159990f91babe4afd72b24a4
bf93333fd3eb1e9404c4892c2104a32728851218
refs/heads/main
2023-06-04T22:49:59.908000
2021-06-25T16:55:29
2021-06-25T16:55:29
348,709,951
5
2
null
false
2021-06-25T16:25:04
2021-03-17T12:56:48
2021-06-24T15:29:04
2021-06-25T16:25:03
260
2
2
0
Java
false
false
package com.intive.patronative.repository; import com.intive.patronative.dto.UserSearchDTO; import com.intive.patronative.dto.profile.UserRole; import com.intive.patronative.dto.profile.UserStatus; import com.intive.patronative.repository.model.Role; import com.intive.patronative.repository.model.Status; import com.intive.patronative.repository.model.TechnologyGroup; import com.intive.patronative.repository.model.User; import lombok.AllArgsConstructor; import org.springframework.stereotype.Repository; import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.Expression; import javax.persistence.criteria.Join; import javax.persistence.criteria.JoinType; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import java.util.ArrayList; import java.util.Collections; import java.util.List; import static org.apache.commons.lang3.StringUtils.SPACE; @AllArgsConstructor @Repository public class UserSearchRepositoryImpl implements UserSearchRepository { private final EntityManager entityManager; @Override public List<User> findAllUsers(final UserSearchDTO userSearchDTO) { if (userSearchDTO == null) { return Collections.emptyList(); } final var criteriaBuilder = entityManager.getCriteriaBuilder(); final var criteriaQuery = criteriaBuilder.createQuery(User.class); final var root = criteriaQuery.from(User.class); criteriaQuery.select(root); final List<Predicate> predicates = buildPredicates(userSearchDTO, criteriaBuilder, root); criteriaQuery.where(predicates.toArray(new Predicate[]{})); final var typedQuery = entityManager.createQuery(criteriaQuery); return typedQuery.getResultList(); } private List<Predicate> buildPredicates(final UserSearchDTO userSearchDTO, final CriteriaBuilder criteriaBuilder, final Root<User> root) { final List<Predicate> predicates = new ArrayList<>(); if (userSearchDTO.getRole() != null) { predicates.add(createRoleByNamePredicate(userSearchDTO.getRole(), criteriaBuilder, root)); } if (userSearchDTO.getStatus() != null) { predicates.add(createStatusByNamePredicate(userSearchDTO.getStatus(), criteriaBuilder, root)); } if (userSearchDTO.getTechnologyGroup() != null) { predicates.add(createTechnologyGroupByNamePredicate(userSearchDTO.getTechnologyGroup(), criteriaBuilder, root)); } if (userSearchDTO.getOther() != null) { predicates.add(createOtherPredicate(userSearchDTO.getOther(), criteriaBuilder, root)); return predicates; } if (userSearchDTO.getFirstName() != null) { predicates.add(createLikePredicate(userSearchDTO.getFirstName(), root.get("firstName"), criteriaBuilder)); } if (userSearchDTO.getLastName() != null) { predicates.add(createLikePredicate(userSearchDTO.getLastName(), root.get("lastName"), criteriaBuilder)); } if (userSearchDTO.getLogin() != null) { predicates.add(createLikePredicate(userSearchDTO.getLogin(), root.get("login"), criteriaBuilder)); } return predicates; } private Predicate createRoleByNamePredicate(final UserRole role, final CriteriaBuilder criteriaBuilder, final Root<User> root) { final Join<User, Role> roleJoin = root.join("role", JoinType.LEFT); return criteriaBuilder.equal(roleJoin.get("name"), role); } private Predicate createStatusByNamePredicate(final UserStatus status, final CriteriaBuilder criteriaBuilder, final Root<User> root) { final Join<User, Status> statusJoin = root.join("status", JoinType.LEFT); return criteriaBuilder.equal(statusJoin.get("name"), status); } private Predicate createTechnologyGroupByNamePredicate(final String technologyGroup, final CriteriaBuilder criteriaBuilder, final Root<User> root) { final Join<User, TechnologyGroup> technologyGroupsJoin = root.join("technologyGroups", JoinType.LEFT); return criteriaBuilder.like( criteriaBuilder.lower( technologyGroupsJoin.get("name") ), technologyGroup.toLowerCase() ); } private Predicate createOtherPredicate(final String other, final CriteriaBuilder criteriaBuilder, final Root<User> root) { final boolean hasSpace = other.contains(SPACE); return hasSpace ? createOtherPredicateComplexCase(other, criteriaBuilder, root) : createOtherPredicateOneWordCase(other, criteriaBuilder, root); } private Predicate createOtherPredicateComplexCase(final String other, final CriteriaBuilder criteriaBuilder, final Root<User> root) { return criteriaBuilder.or( createOtherPredicateOneWordCase(other, criteriaBuilder, root), createOtherPredicateWithSpaceCase(other, criteriaBuilder, root) ); } private Predicate createOtherPredicateOneWordCase(final String other, final CriteriaBuilder criteriaBuilder, final Root<User> root) { return criteriaBuilder.or( createLikePredicate(other, root.get("login"), criteriaBuilder), createLikePredicate(other, root.get("firstName"), criteriaBuilder), createLikePredicate(other, root.get("lastName"), criteriaBuilder) ); } private Predicate createOtherPredicateWithSpaceCase(final String other, final CriteriaBuilder criteriaBuilder, final Root<User> root) { return criteriaBuilder.or( createFirstAndLastNamePredicate(other, criteriaBuilder, root, false), createFirstAndLastNamePredicate(other, criteriaBuilder, root, true) ); } private Predicate createFirstAndLastNamePredicate(final String other, final CriteriaBuilder criteriaBuilder, final Root<User> root, final boolean isReversed) { final var firstField = isReversed ? "lastName" : "firstName"; final var secondField = isReversed ? "firstName" : "lastName"; final Expression<String> concatenatedFieldSpaceFieldExpression = createConcatenatedFieldSpaceFieldExpression(criteriaBuilder, root, firstField, secondField); return createLikePredicate(other, concatenatedFieldSpaceFieldExpression, criteriaBuilder); } private Expression<String> createConcatenatedFieldSpaceFieldExpression(final CriteriaBuilder criteriaBuilder, final Root<User> root, final String firstField, final String secondField) { return criteriaBuilder.concat( criteriaBuilder.concat( root.get(firstField), SPACE ), root.get(secondField) ); } private Predicate createLikePredicate(final String value, final Expression<String> expression, final CriteriaBuilder criteriaBuilder) { return criteriaBuilder.like( criteriaBuilder.lower( expression ), "%" + value.toLowerCase() + "%" ); } }
UTF-8
Java
7,957
java
UserSearchRepositoryImpl.java
Java
[]
null
[]
package com.intive.patronative.repository; import com.intive.patronative.dto.UserSearchDTO; import com.intive.patronative.dto.profile.UserRole; import com.intive.patronative.dto.profile.UserStatus; import com.intive.patronative.repository.model.Role; import com.intive.patronative.repository.model.Status; import com.intive.patronative.repository.model.TechnologyGroup; import com.intive.patronative.repository.model.User; import lombok.AllArgsConstructor; import org.springframework.stereotype.Repository; import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.Expression; import javax.persistence.criteria.Join; import javax.persistence.criteria.JoinType; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import java.util.ArrayList; import java.util.Collections; import java.util.List; import static org.apache.commons.lang3.StringUtils.SPACE; @AllArgsConstructor @Repository public class UserSearchRepositoryImpl implements UserSearchRepository { private final EntityManager entityManager; @Override public List<User> findAllUsers(final UserSearchDTO userSearchDTO) { if (userSearchDTO == null) { return Collections.emptyList(); } final var criteriaBuilder = entityManager.getCriteriaBuilder(); final var criteriaQuery = criteriaBuilder.createQuery(User.class); final var root = criteriaQuery.from(User.class); criteriaQuery.select(root); final List<Predicate> predicates = buildPredicates(userSearchDTO, criteriaBuilder, root); criteriaQuery.where(predicates.toArray(new Predicate[]{})); final var typedQuery = entityManager.createQuery(criteriaQuery); return typedQuery.getResultList(); } private List<Predicate> buildPredicates(final UserSearchDTO userSearchDTO, final CriteriaBuilder criteriaBuilder, final Root<User> root) { final List<Predicate> predicates = new ArrayList<>(); if (userSearchDTO.getRole() != null) { predicates.add(createRoleByNamePredicate(userSearchDTO.getRole(), criteriaBuilder, root)); } if (userSearchDTO.getStatus() != null) { predicates.add(createStatusByNamePredicate(userSearchDTO.getStatus(), criteriaBuilder, root)); } if (userSearchDTO.getTechnologyGroup() != null) { predicates.add(createTechnologyGroupByNamePredicate(userSearchDTO.getTechnologyGroup(), criteriaBuilder, root)); } if (userSearchDTO.getOther() != null) { predicates.add(createOtherPredicate(userSearchDTO.getOther(), criteriaBuilder, root)); return predicates; } if (userSearchDTO.getFirstName() != null) { predicates.add(createLikePredicate(userSearchDTO.getFirstName(), root.get("firstName"), criteriaBuilder)); } if (userSearchDTO.getLastName() != null) { predicates.add(createLikePredicate(userSearchDTO.getLastName(), root.get("lastName"), criteriaBuilder)); } if (userSearchDTO.getLogin() != null) { predicates.add(createLikePredicate(userSearchDTO.getLogin(), root.get("login"), criteriaBuilder)); } return predicates; } private Predicate createRoleByNamePredicate(final UserRole role, final CriteriaBuilder criteriaBuilder, final Root<User> root) { final Join<User, Role> roleJoin = root.join("role", JoinType.LEFT); return criteriaBuilder.equal(roleJoin.get("name"), role); } private Predicate createStatusByNamePredicate(final UserStatus status, final CriteriaBuilder criteriaBuilder, final Root<User> root) { final Join<User, Status> statusJoin = root.join("status", JoinType.LEFT); return criteriaBuilder.equal(statusJoin.get("name"), status); } private Predicate createTechnologyGroupByNamePredicate(final String technologyGroup, final CriteriaBuilder criteriaBuilder, final Root<User> root) { final Join<User, TechnologyGroup> technologyGroupsJoin = root.join("technologyGroups", JoinType.LEFT); return criteriaBuilder.like( criteriaBuilder.lower( technologyGroupsJoin.get("name") ), technologyGroup.toLowerCase() ); } private Predicate createOtherPredicate(final String other, final CriteriaBuilder criteriaBuilder, final Root<User> root) { final boolean hasSpace = other.contains(SPACE); return hasSpace ? createOtherPredicateComplexCase(other, criteriaBuilder, root) : createOtherPredicateOneWordCase(other, criteriaBuilder, root); } private Predicate createOtherPredicateComplexCase(final String other, final CriteriaBuilder criteriaBuilder, final Root<User> root) { return criteriaBuilder.or( createOtherPredicateOneWordCase(other, criteriaBuilder, root), createOtherPredicateWithSpaceCase(other, criteriaBuilder, root) ); } private Predicate createOtherPredicateOneWordCase(final String other, final CriteriaBuilder criteriaBuilder, final Root<User> root) { return criteriaBuilder.or( createLikePredicate(other, root.get("login"), criteriaBuilder), createLikePredicate(other, root.get("firstName"), criteriaBuilder), createLikePredicate(other, root.get("lastName"), criteriaBuilder) ); } private Predicate createOtherPredicateWithSpaceCase(final String other, final CriteriaBuilder criteriaBuilder, final Root<User> root) { return criteriaBuilder.or( createFirstAndLastNamePredicate(other, criteriaBuilder, root, false), createFirstAndLastNamePredicate(other, criteriaBuilder, root, true) ); } private Predicate createFirstAndLastNamePredicate(final String other, final CriteriaBuilder criteriaBuilder, final Root<User> root, final boolean isReversed) { final var firstField = isReversed ? "lastName" : "firstName"; final var secondField = isReversed ? "firstName" : "lastName"; final Expression<String> concatenatedFieldSpaceFieldExpression = createConcatenatedFieldSpaceFieldExpression(criteriaBuilder, root, firstField, secondField); return createLikePredicate(other, concatenatedFieldSpaceFieldExpression, criteriaBuilder); } private Expression<String> createConcatenatedFieldSpaceFieldExpression(final CriteriaBuilder criteriaBuilder, final Root<User> root, final String firstField, final String secondField) { return criteriaBuilder.concat( criteriaBuilder.concat( root.get(firstField), SPACE ), root.get(secondField) ); } private Predicate createLikePredicate(final String value, final Expression<String> expression, final CriteriaBuilder criteriaBuilder) { return criteriaBuilder.like( criteriaBuilder.lower( expression ), "%" + value.toLowerCase() + "%" ); } }
7,957
0.642327
0.642202
167
46.652695
36.982426
124
false
false
0
0
0
0
0
0
0.832335
false
false
4
dd2d55216bc3cb90f0263b6510880dc3a451195d
34,325,378,636,321
49d567e2d47e11f2a5475470df2827f14337a5a2
/src/main/java/info/krogulec/streams/UsingDoubleStreams.java
4b56cec7a1fb2948a9c5c7d29500a36d7e5b4f2c
[ "Apache-2.0" ]
permissive
Abraxus3003/ocp-exercises
https://github.com/Abraxus3003/ocp-exercises
e0b8e05c9bd322608a1744f154d1f767a2ed1974
35ff7804869ed25c5f603dc056c44d99d5c0b584
refs/heads/master
2020-06-11T23:03:49.488000
2019-06-23T11:21:10
2019-06-23T11:21:10
194,115,441
0
1
Apache-2.0
true
2019-06-27T14:58:20
2019-06-27T14:58:19
2019-06-27T14:58:11
2019-06-23T11:21:21
58
0
0
0
null
false
false
package info.krogulec.streams; import java.util.function.BinaryOperator; import java.util.function.DoubleBinaryOperator; import java.util.function.DoubleFunction; import java.util.stream.DoubleStream; import java.util.stream.Stream; public class UsingDoubleStreams { public static void main(String[] args) { System.out.println("mapToDouble() zwraca DoubleStream" + Stream.of(1,2,3,4).mapToDouble(a -> (double) a)); DoubleFunction<String> df = d -> "msg" + d; DoubleStream.of(1.1, 1.2, 2.1).mapToObj(df).forEach(System.out::print); System.out.println(); BinaryOperator<Double> doubleBinaryOperator = BinaryOperator.maxBy(Double::compare); System.out.println("BinaryOperator.maxBy: " + doubleBinaryOperator.apply(1.1, 1.2)); BinaryOperator<Double> doubleBinaryOperator2 = BinaryOperator.minBy(Double::compare); System.out.println("BinaryOperator.minBy: " + doubleBinaryOperator2.apply(1.1, 1.2)); } }
UTF-8
Java
980
java
UsingDoubleStreams.java
Java
[]
null
[]
package info.krogulec.streams; import java.util.function.BinaryOperator; import java.util.function.DoubleBinaryOperator; import java.util.function.DoubleFunction; import java.util.stream.DoubleStream; import java.util.stream.Stream; public class UsingDoubleStreams { public static void main(String[] args) { System.out.println("mapToDouble() zwraca DoubleStream" + Stream.of(1,2,3,4).mapToDouble(a -> (double) a)); DoubleFunction<String> df = d -> "msg" + d; DoubleStream.of(1.1, 1.2, 2.1).mapToObj(df).forEach(System.out::print); System.out.println(); BinaryOperator<Double> doubleBinaryOperator = BinaryOperator.maxBy(Double::compare); System.out.println("BinaryOperator.maxBy: " + doubleBinaryOperator.apply(1.1, 1.2)); BinaryOperator<Double> doubleBinaryOperator2 = BinaryOperator.minBy(Double::compare); System.out.println("BinaryOperator.minBy: " + doubleBinaryOperator2.apply(1.1, 1.2)); } }
980
0.715306
0.694898
27
35.296295
36.065594
114
false
false
0
0
0
0
0
0
0.777778
false
false
4
322ec1badade4abdc39f465548b1ea8649c82dbd
34,583,076,692,324
deb4a5b047c33bbee795dc7e7b75b680574fd329
/JavaCoreLesson7/src/ua/lviv/lgs/Distance.java
2376ce4a119e0f9fbc5d02e4c6ecd9ec40ed0d45
[]
no_license
ProkopaloA/JavaCoreLesson7
https://github.com/ProkopaloA/JavaCoreLesson7
b4feefb985af3256fbe8bbd876a7a225ad9abd68
250bcbacf08e9719a9b8a146aca64487f8f9dc4c
refs/heads/master
2023-05-05T02:45:55.254000
2021-05-25T13:19:30
2021-05-25T13:19:30
370,698,771
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ua.lviv.lgs; public class Distance { static int distance() { int distance = (int)(Math.random()*10000); return distance; } }
UTF-8
Java
141
java
Distance.java
Java
[]
null
[]
package ua.lviv.lgs; public class Distance { static int distance() { int distance = (int)(Math.random()*10000); return distance; } }
141
0.673759
0.638298
9
14.666667
14.275075
44
false
false
0
0
0
0
0
0
1
false
false
4
ed48a2e82dad9db643ad052ff709af3691fb16b1
34,591,666,605,959
b2e52383e3085845c49e9a7a6d28b7df73edb6f9
/src/main/java/com/microsoft/graph/termstore/requests/RelationRequestBuilder.java
cfb56548a7364bb7d23265158815ddb874cecd91
[ "MIT" ]
permissive
microsoftgraph/msgraph-sdk-java
https://github.com/microsoftgraph/msgraph-sdk-java
d6173043ba783c040e80a724970da19837e8aa1d
d7b25b23209613c78452d59eb327a30e4673bb44
refs/heads/dev
2023-08-16T02:55:39.472000
2023-08-10T23:18:19
2023-08-10T23:18:19
103,300,409
352
160
MIT
false
2023-09-14T06:21:25
2017-09-12T17:20:15
2023-09-08T10:53:45
2023-09-14T06:21:24
116,553
319
125
24
Java
false
false
// Template Source: BaseEntityRequestBuilder.java.tt // ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.termstore.requests; import com.microsoft.graph.http.IRequestBuilder; import com.microsoft.graph.core.ClientException; import com.microsoft.graph.termstore.models.Relation; import java.util.Arrays; import java.util.EnumSet; import javax.annotation.Nullable; import javax.annotation.Nonnull; import com.microsoft.graph.core.IBaseClient; import com.microsoft.graph.http.BaseRequestBuilder; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The class for the Relation Request Builder. */ public class RelationRequestBuilder extends BaseRequestBuilder<Relation> { /** * The request builder for the Relation * * @param requestUrl the request URL * @param client the service client * @param requestOptions the options for this request */ public RelationRequestBuilder(@Nonnull final String requestUrl, @Nonnull final IBaseClient<?> client, @Nullable final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) { super(requestUrl, client, requestOptions); } /** * Creates the request * * @param requestOptions the options for this request * @return the RelationRequest instance */ @Nonnull public RelationRequest buildRequest(@Nullable final com.microsoft.graph.options.Option... requestOptions) { return buildRequest(getOptions(requestOptions)); } /** * Creates the request with specific requestOptions instead of the existing requestOptions * * @param requestOptions the options for this request * @return the RelationRequest instance */ @Nonnull public RelationRequest buildRequest(@Nonnull final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) { return new com.microsoft.graph.termstore.requests.RelationRequest(getRequestUrl(), getClient(), requestOptions); } /** * Gets the request builder for Term * * @return the TermWithReferenceRequestBuilder instance */ @Nonnull public com.microsoft.graph.termstore.requests.TermWithReferenceRequestBuilder fromTerm() { return new com.microsoft.graph.termstore.requests.TermWithReferenceRequestBuilder(getRequestUrlWithAdditionalSegment("fromTerm"), getClient(), null); } /** * Gets the request builder for Set * * @return the SetWithReferenceRequestBuilder instance */ @Nonnull public com.microsoft.graph.termstore.requests.SetWithReferenceRequestBuilder set() { return new com.microsoft.graph.termstore.requests.SetWithReferenceRequestBuilder(getRequestUrlWithAdditionalSegment("set"), getClient(), null); } /** * Gets the request builder for Term * * @return the TermWithReferenceRequestBuilder instance */ @Nonnull public com.microsoft.graph.termstore.requests.TermWithReferenceRequestBuilder toTerm() { return new com.microsoft.graph.termstore.requests.TermWithReferenceRequestBuilder(getRequestUrlWithAdditionalSegment("toTerm"), getClient(), null); } }
UTF-8
Java
3,492
java
RelationRequestBuilder.java
Java
[]
null
[]
// Template Source: BaseEntityRequestBuilder.java.tt // ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.termstore.requests; import com.microsoft.graph.http.IRequestBuilder; import com.microsoft.graph.core.ClientException; import com.microsoft.graph.termstore.models.Relation; import java.util.Arrays; import java.util.EnumSet; import javax.annotation.Nullable; import javax.annotation.Nonnull; import com.microsoft.graph.core.IBaseClient; import com.microsoft.graph.http.BaseRequestBuilder; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The class for the Relation Request Builder. */ public class RelationRequestBuilder extends BaseRequestBuilder<Relation> { /** * The request builder for the Relation * * @param requestUrl the request URL * @param client the service client * @param requestOptions the options for this request */ public RelationRequestBuilder(@Nonnull final String requestUrl, @Nonnull final IBaseClient<?> client, @Nullable final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) { super(requestUrl, client, requestOptions); } /** * Creates the request * * @param requestOptions the options for this request * @return the RelationRequest instance */ @Nonnull public RelationRequest buildRequest(@Nullable final com.microsoft.graph.options.Option... requestOptions) { return buildRequest(getOptions(requestOptions)); } /** * Creates the request with specific requestOptions instead of the existing requestOptions * * @param requestOptions the options for this request * @return the RelationRequest instance */ @Nonnull public RelationRequest buildRequest(@Nonnull final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) { return new com.microsoft.graph.termstore.requests.RelationRequest(getRequestUrl(), getClient(), requestOptions); } /** * Gets the request builder for Term * * @return the TermWithReferenceRequestBuilder instance */ @Nonnull public com.microsoft.graph.termstore.requests.TermWithReferenceRequestBuilder fromTerm() { return new com.microsoft.graph.termstore.requests.TermWithReferenceRequestBuilder(getRequestUrlWithAdditionalSegment("fromTerm"), getClient(), null); } /** * Gets the request builder for Set * * @return the SetWithReferenceRequestBuilder instance */ @Nonnull public com.microsoft.graph.termstore.requests.SetWithReferenceRequestBuilder set() { return new com.microsoft.graph.termstore.requests.SetWithReferenceRequestBuilder(getRequestUrlWithAdditionalSegment("set"), getClient(), null); } /** * Gets the request builder for Term * * @return the TermWithReferenceRequestBuilder instance */ @Nonnull public com.microsoft.graph.termstore.requests.TermWithReferenceRequestBuilder toTerm() { return new com.microsoft.graph.termstore.requests.TermWithReferenceRequestBuilder(getRequestUrlWithAdditionalSegment("toTerm"), getClient(), null); } }
3,492
0.70189
0.70189
89
38.235954
44.071194
200
false
false
0
0
0
0
0
0
0.314607
false
false
4
274ff7d11a18dc8acca483c69fb1494d869b43c7
35,124,242,567,348
f31405a75f521fee1f5ad7f7b87167bf4dd9f346
/src/main/java/dto/role/PermissionRoleDto.java
c7c3dcbc460a21c424a0a52d2afd82865ebd8a91
[]
no_license
hua-1/tanke
https://github.com/hua-1/tanke
39ca9edfa94021b3e5595c38a51ba0a52f5e379e
a7443c2c36d1a06d6713abd66c18b8ab0664a3ea
refs/heads/master
2020-03-18T17:12:58.750000
2018-06-09T03:17:12
2018-06-09T03:17:12
135,013,937
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package dto.role; import java.util.List; public class PermissionRoleDto { private Long id; private String roleCode; private String roleName; private Long applicationId; private String remark; private String enabled; public String getEnabled() { return enabled; } public void setEnabled(String enabled) { this.enabled = enabled; } private List<PermissionSimpleDto> permissionList; public List<PermissionSimpleDto> getPermissionList() { return permissionList; } public void setPermissionList(List<PermissionSimpleDto> permissionList) { this.permissionList = permissionList; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public Long getApplicationId() { return applicationId; } public void setApplicationId(Long applicationId) { this.applicationId = applicationId; } public String getRoleCode() { return roleCode; } public void setRoleCode(String roleCode) { this.roleCode = roleCode; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } }
UTF-8
Java
1,421
java
PermissionRoleDto.java
Java
[]
null
[]
package dto.role; import java.util.List; public class PermissionRoleDto { private Long id; private String roleCode; private String roleName; private Long applicationId; private String remark; private String enabled; public String getEnabled() { return enabled; } public void setEnabled(String enabled) { this.enabled = enabled; } private List<PermissionSimpleDto> permissionList; public List<PermissionSimpleDto> getPermissionList() { return permissionList; } public void setPermissionList(List<PermissionSimpleDto> permissionList) { this.permissionList = permissionList; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public Long getApplicationId() { return applicationId; } public void setApplicationId(Long applicationId) { this.applicationId = applicationId; } public String getRoleCode() { return roleCode; } public void setRoleCode(String roleCode) { this.roleCode = roleCode; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } }
1,421
0.636172
0.636172
72
18.736111
18.177362
77
false
false
0
0
0
0
0
0
0.319444
false
false
4
7d3810f67d83a696bd72fc757059f8e2e47db6d5
9,869,834,883,391
f924f981f1468d8a9ccdff4bf2915b9f36c46191
/src/main/java/lars/ooad/Builder.java
62ae12a1d7cb3025f0087f62a127da82bde00f60
[ "Apache-2.0" ]
permissive
LarsEckart/java_playground
https://github.com/LarsEckart/java_playground
1d9908fd0b945ec95b92c5a6818db7436e55b554
3e3879959b4e2f2739f0de999a47774e8ac2c2f0
refs/heads/main
2023-09-03T17:16:28.146000
2023-08-21T02:45:57
2023-08-31T11:50:55
46,675,922
2
0
null
false
2023-09-11T02:31:52
2015-11-22T19:24:01
2023-01-18T13:29:45
2023-09-11T02:31:52
2,496
2
0
5
Java
false
false
package lars.ooad; public enum Builder { FENDER, MARTIN, GIBSON, COLLINGS, OLSON, RYAN, PRS, ANY; public String toString() { switch (this) { case FENDER: return "Fender"; case MARTIN: return "Martin"; case GIBSON: return "Gibson"; case COLLINGS: return "Collings"; case OLSON: return "Olson"; case RYAN: return "Ryan"; case PRS: return "PRS"; default: return "Unspecified"; } } }
UTF-8
Java
522
java
Builder.java
Java
[ { "context": "kage lars.ooad;\n\npublic enum Builder {\n FENDER,\n MARTIN,\n GIBSON,\n COLLINGS,\n OLSON,\n RYAN,\n PRS,\n ", "end": 60, "score": 0.9966878890991211, "start": 54, "tag": "NAME", "value": "MARTIN" }, { "context": "ooad;\n\npublic enum Builder {\n FENDER,\n MARTIN,\n GIBSON,\n COLLINGS,\n OLSON,\n RYAN,\n PRS,\n ANY;\n\n pu", "end": 70, "score": 0.9980230927467346, "start": 64, "tag": "NAME", "value": "GIBSON" }, { "context": "lic enum Builder {\n FENDER,\n MARTIN,\n GIBSON,\n COLLINGS,\n OLSON,\n RYAN,\n PRS,\n ANY;\n\n public String ", "end": 82, "score": 0.9969579577445984, "start": 74, "tag": "NAME", "value": "COLLINGS" }, { "context": "lder {\n FENDER,\n MARTIN,\n GIBSON,\n COLLINGS,\n OLSON,\n RYAN,\n PRS,\n ANY;\n\n public String toString(", "end": 91, "score": 0.9969248175621033, "start": 86, "tag": "NAME", "value": "OLSON" }, { "context": "FENDER,\n MARTIN,\n GIBSON,\n COLLINGS,\n OLSON,\n RYAN,\n PRS,\n ANY;\n\n public String toString() {\n ", "end": 99, "score": 0.9925215244293213, "start": 95, "tag": "NAME", "value": "RYAN" }, { "context": "witch (this) {\n case FENDER:\n return \"Fender\";\n case MARTIN:\n return \"Martin\";\n ", "end": 206, "score": 0.9968819618225098, "start": 200, "tag": "NAME", "value": "Fender" }, { "context": " case FENDER:\n return \"Fender\";\n case MARTIN:\n return \"Martin\";\n case GIBSON:\n ", "end": 226, "score": 0.9951141476631165, "start": 220, "tag": "NAME", "value": "MARTIN" }, { "context": "turn \"Fender\";\n case MARTIN:\n return \"Martin\";\n case GIBSON:\n return \"Gibson\";\n ", "end": 250, "score": 0.9985419511795044, "start": 244, "tag": "NAME", "value": "Martin" }, { "context": " case MARTIN:\n return \"Martin\";\n case GIBSON:\n return \"Gibson\";\n case COLLINGS:\n ", "end": 270, "score": 0.994960606098175, "start": 264, "tag": "NAME", "value": "GIBSON" }, { "context": "turn \"Martin\";\n case GIBSON:\n return \"Gibson\";\n case COLLINGS:\n return \"Collings\";", "end": 294, "score": 0.9984148144721985, "start": 288, "tag": "NAME", "value": "Gibson" }, { "context": " case GIBSON:\n return \"Gibson\";\n case COLLINGS:\n return \"Collings\";\n case OLSON:\n ", "end": 316, "score": 0.9928516745567322, "start": 308, "tag": "NAME", "value": "COLLINGS" }, { "context": "rn \"Gibson\";\n case COLLINGS:\n return \"Collings\";\n case OLSON:\n return \"Olson\";\n ", "end": 342, "score": 0.9922733306884766, "start": 334, "tag": "NAME", "value": "Collings" }, { "context": "se COLLINGS:\n return \"Collings\";\n case OLSON:\n return \"Olson\";\n case RYAN:\n ", "end": 361, "score": 0.99189692735672, "start": 356, "tag": "NAME", "value": "OLSON" }, { "context": "urn \"Collings\";\n case OLSON:\n return \"Olson\";\n case RYAN:\n return \"Ryan\";\n c", "end": 384, "score": 0.9983710050582886, "start": 379, "tag": "NAME", "value": "Olson" }, { "context": " case OLSON:\n return \"Olson\";\n case RYAN:\n return \"Ryan\";\n case PRS:\n r", "end": 402, "score": 0.9922806620597839, "start": 398, "tag": "NAME", "value": "RYAN" }, { "context": " return \"Olson\";\n case RYAN:\n return \"Ryan\";\n case PRS:\n return \"PRS\";\n def", "end": 424, "score": 0.9976868629455566, "start": 420, "tag": "NAME", "value": "Ryan" } ]
null
[]
package lars.ooad; public enum Builder { FENDER, MARTIN, GIBSON, COLLINGS, OLSON, RYAN, PRS, ANY; public String toString() { switch (this) { case FENDER: return "Fender"; case MARTIN: return "Martin"; case GIBSON: return "Gibson"; case COLLINGS: return "Collings"; case OLSON: return "Olson"; case RYAN: return "Ryan"; case PRS: return "PRS"; default: return "Unspecified"; } } }
522
0.522988
0.522988
33
14.818182
8.321037
29
false
false
0
0
0
0
0
0
0.515152
false
false
4
3adb28493b517f5e0bf64d12a04ab7380cfa41eb
16,681,653,011,366
4152b9f20932a13fa27535fbe0c8455cea269bd0
/jstarcraft-ai-jsat/src/test/java/com/jstarcraft/ai/jsat/clustering/DBSCANTest.java
37e0309b4b269e8e0043d54ac208b163d14dd94d
[ "Apache-2.0" ]
permissive
kingrom/jstarcraft-ai
https://github.com/kingrom/jstarcraft-ai
ab7843bd6c09503bf9156aabbf07386577ddff63
5029228e27efa3dd934d431cd8dd90e786b760a7
refs/heads/master
2020-08-01T21:28:42.582000
2019-09-23T09:58:54
2019-09-23T09:58:54
208,401,831
1
0
Apache-2.0
true
2019-09-14T06:54:48
2019-09-14T06:54:45
2019-09-14T04:31:01
2019-09-14T04:30:59
16,742
0
0
0
null
false
false
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.jstarcraft.ai.jsat.clustering; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import java.util.List; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import com.jstarcraft.ai.jsat.SimpleDataSet; import com.jstarcraft.ai.jsat.classifiers.DataPoint; import com.jstarcraft.ai.jsat.distributions.Uniform; import com.jstarcraft.ai.jsat.linear.distancemetrics.EuclideanDistance; import com.jstarcraft.ai.jsat.linear.vectorcollection.VectorArray; import com.jstarcraft.ai.jsat.utils.GridDataGenerator; import com.jstarcraft.ai.jsat.utils.SystemInfo; import it.unimi.dsi.fastutil.ints.IntOpenHashSet; /** * * @author Edward Raff */ public class DBSCANTest { static private DBSCAN dbscan; static private SimpleDataSet easyData10; static private ExecutorService ex; public DBSCANTest() { } @BeforeClass public static void setUpClass() throws Exception { dbscan = new DBSCAN(new EuclideanDistance(), new VectorArray<>()); GridDataGenerator gdg = new GridDataGenerator(new Uniform(-0.15, 0.15), new Random(12), 2, 5); easyData10 = gdg.generateData(40); ex = Executors.newFixedThreadPool(SystemInfo.LogicalCores); } @AfterClass public static void tearDownClass() throws Exception { ex.shutdown(); } @Before public void setUp() { } /** * Test of cluster method, of class DBSCAN. */ @Test public void testCluster_DataSet_int() { System.out.println("cluster(dataset, int)"); List<List<DataPoint>> clusters = dbscan.cluster(easyData10, 5); assertEquals(10, clusters.size()); IntOpenHashSet seenBefore = new IntOpenHashSet(); for (List<DataPoint> cluster : clusters) { int thisClass = cluster.get(0).getCategoricalValue(0); assertFalse(seenBefore.contains(thisClass)); for (DataPoint dp : cluster) assertEquals(thisClass, dp.getCategoricalValue(0)); } } /** * Test of cluster method, of class DBSCAN. */ @Test public void testCluster_DataSet() { System.out.println("cluster(dataset)"); List<List<DataPoint>> clusters = dbscan.cluster(easyData10); assertEquals(10, clusters.size()); IntOpenHashSet seenBefore = new IntOpenHashSet(); for (List<DataPoint> cluster : clusters) { int thisClass = cluster.get(0).getCategoricalValue(0); assertFalse(seenBefore.contains(thisClass)); for (DataPoint dp : cluster) assertEquals(thisClass, dp.getCategoricalValue(0)); } } /** * Test of cluster method, of class DBSCAN. */ @Test public void testCluster_DataSet_ExecutorService() { System.out.println("cluster(dataset, executorService)"); List<List<DataPoint>> clusters = dbscan.cluster(easyData10, true); assertEquals(10, clusters.size()); IntOpenHashSet seenBefore = new IntOpenHashSet(); for (List<DataPoint> cluster : clusters) { int thisClass = cluster.get(0).getCategoricalValue(0); assertFalse(seenBefore.contains(thisClass)); for (DataPoint dp : cluster) assertEquals(thisClass, dp.getCategoricalValue(0)); } } /** * Test of cluster method, of class DBSCAN. */ @Test public void testCluster_3args_1() { System.out.println("cluster(dataset, double, int)"); // We know the range is [-.15, .15] List<List<DataPoint>> clusters = dbscan.cluster(easyData10, 0.15, 5); assertEquals(10, clusters.size()); IntOpenHashSet seenBefore = new IntOpenHashSet(); for (List<DataPoint> cluster : clusters) { int thisClass = cluster.get(0).getCategoricalValue(0); assertFalse(seenBefore.contains(thisClass)); for (DataPoint dp : cluster) assertEquals(thisClass, dp.getCategoricalValue(0)); } } /** * Test of cluster method, of class DBSCAN. */ @Test public void testCluster_3args_2() { System.out.println("cluster(dataset, int, executorService)"); List<List<DataPoint>> clusters = dbscan.cluster(easyData10, 3, true); assertEquals(10, clusters.size()); IntOpenHashSet seenBefore = new IntOpenHashSet(); for (List<DataPoint> cluster : clusters) { int thisClass = cluster.get(0).getCategoricalValue(0); assertFalse(seenBefore.contains(thisClass)); for (DataPoint dp : cluster) assertEquals(thisClass, dp.getCategoricalValue(0)); } } /** * Test of cluster method, of class DBSCAN. */ @Test public void testCluster_4args() { System.out.println("cluster(dataset, double, int, executorService)"); // We know the range is [-.15, .15] List<List<DataPoint>> clusters = dbscan.cluster(easyData10, 0.15, 5, true); assertEquals(10, clusters.size()); IntOpenHashSet seenBefore = new IntOpenHashSet(); for (List<DataPoint> cluster : clusters) { int thisClass = cluster.get(0).getCategoricalValue(0); assertFalse(seenBefore.contains(thisClass)); for (DataPoint dp : cluster) assertEquals(thisClass, dp.getCategoricalValue(0)); } } }
UTF-8
Java
5,683
java
DBSCANTest.java
Java
[ { "context": "i.fastutil.ints.IntOpenHashSet;\n\n/**\n *\n * @author Edward Raff\n */\npublic class DBSCANTest {\n static private ", "end": 949, "score": 0.9997531771659851, "start": 938, "tag": "NAME", "value": "Edward Raff" } ]
null
[]
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.jstarcraft.ai.jsat.clustering; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import java.util.List; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import com.jstarcraft.ai.jsat.SimpleDataSet; import com.jstarcraft.ai.jsat.classifiers.DataPoint; import com.jstarcraft.ai.jsat.distributions.Uniform; import com.jstarcraft.ai.jsat.linear.distancemetrics.EuclideanDistance; import com.jstarcraft.ai.jsat.linear.vectorcollection.VectorArray; import com.jstarcraft.ai.jsat.utils.GridDataGenerator; import com.jstarcraft.ai.jsat.utils.SystemInfo; import it.unimi.dsi.fastutil.ints.IntOpenHashSet; /** * * @author <NAME> */ public class DBSCANTest { static private DBSCAN dbscan; static private SimpleDataSet easyData10; static private ExecutorService ex; public DBSCANTest() { } @BeforeClass public static void setUpClass() throws Exception { dbscan = new DBSCAN(new EuclideanDistance(), new VectorArray<>()); GridDataGenerator gdg = new GridDataGenerator(new Uniform(-0.15, 0.15), new Random(12), 2, 5); easyData10 = gdg.generateData(40); ex = Executors.newFixedThreadPool(SystemInfo.LogicalCores); } @AfterClass public static void tearDownClass() throws Exception { ex.shutdown(); } @Before public void setUp() { } /** * Test of cluster method, of class DBSCAN. */ @Test public void testCluster_DataSet_int() { System.out.println("cluster(dataset, int)"); List<List<DataPoint>> clusters = dbscan.cluster(easyData10, 5); assertEquals(10, clusters.size()); IntOpenHashSet seenBefore = new IntOpenHashSet(); for (List<DataPoint> cluster : clusters) { int thisClass = cluster.get(0).getCategoricalValue(0); assertFalse(seenBefore.contains(thisClass)); for (DataPoint dp : cluster) assertEquals(thisClass, dp.getCategoricalValue(0)); } } /** * Test of cluster method, of class DBSCAN. */ @Test public void testCluster_DataSet() { System.out.println("cluster(dataset)"); List<List<DataPoint>> clusters = dbscan.cluster(easyData10); assertEquals(10, clusters.size()); IntOpenHashSet seenBefore = new IntOpenHashSet(); for (List<DataPoint> cluster : clusters) { int thisClass = cluster.get(0).getCategoricalValue(0); assertFalse(seenBefore.contains(thisClass)); for (DataPoint dp : cluster) assertEquals(thisClass, dp.getCategoricalValue(0)); } } /** * Test of cluster method, of class DBSCAN. */ @Test public void testCluster_DataSet_ExecutorService() { System.out.println("cluster(dataset, executorService)"); List<List<DataPoint>> clusters = dbscan.cluster(easyData10, true); assertEquals(10, clusters.size()); IntOpenHashSet seenBefore = new IntOpenHashSet(); for (List<DataPoint> cluster : clusters) { int thisClass = cluster.get(0).getCategoricalValue(0); assertFalse(seenBefore.contains(thisClass)); for (DataPoint dp : cluster) assertEquals(thisClass, dp.getCategoricalValue(0)); } } /** * Test of cluster method, of class DBSCAN. */ @Test public void testCluster_3args_1() { System.out.println("cluster(dataset, double, int)"); // We know the range is [-.15, .15] List<List<DataPoint>> clusters = dbscan.cluster(easyData10, 0.15, 5); assertEquals(10, clusters.size()); IntOpenHashSet seenBefore = new IntOpenHashSet(); for (List<DataPoint> cluster : clusters) { int thisClass = cluster.get(0).getCategoricalValue(0); assertFalse(seenBefore.contains(thisClass)); for (DataPoint dp : cluster) assertEquals(thisClass, dp.getCategoricalValue(0)); } } /** * Test of cluster method, of class DBSCAN. */ @Test public void testCluster_3args_2() { System.out.println("cluster(dataset, int, executorService)"); List<List<DataPoint>> clusters = dbscan.cluster(easyData10, 3, true); assertEquals(10, clusters.size()); IntOpenHashSet seenBefore = new IntOpenHashSet(); for (List<DataPoint> cluster : clusters) { int thisClass = cluster.get(0).getCategoricalValue(0); assertFalse(seenBefore.contains(thisClass)); for (DataPoint dp : cluster) assertEquals(thisClass, dp.getCategoricalValue(0)); } } /** * Test of cluster method, of class DBSCAN. */ @Test public void testCluster_4args() { System.out.println("cluster(dataset, double, int, executorService)"); // We know the range is [-.15, .15] List<List<DataPoint>> clusters = dbscan.cluster(easyData10, 0.15, 5, true); assertEquals(10, clusters.size()); IntOpenHashSet seenBefore = new IntOpenHashSet(); for (List<DataPoint> cluster : clusters) { int thisClass = cluster.get(0).getCategoricalValue(0); assertFalse(seenBefore.contains(thisClass)); for (DataPoint dp : cluster) assertEquals(thisClass, dp.getCategoricalValue(0)); } } }
5,678
0.648777
0.634524
162
34.080246
25.163166
102
false
false
0
0
0
0
0
0
0.703704
false
false
4
bc9d8697324d91bfa6b26274e1d082371ec4a6de
32,839,319,988,604
3bf8a2ce20821159dff4df2ba4cb536d323fb36f
/src/main/java/ru/digitalsoft/document/dto/auth/FullUserDto.java
df56f1ddf0d43556ad9270050d9d1d12a3ad65b1
[]
no_license
Giperkot/DocumentRecognizer
https://github.com/Giperkot/DocumentRecognizer
d7f3b24e621dd65c7ec9621e0d8f0e03ae045018
740076664b5ee391759e4bb40d0f3f2e09b93e91
refs/heads/master
2023-08-03T12:38:05.007000
2021-09-05T06:57:53
2021-09-05T06:57:53
402,995,518
0
3
null
false
2021-09-04T22:31:14
2021-09-04T07:40:09
2021-09-04T21:42:00
2021-09-04T22:31:13
841
0
1
0
Java
false
false
package ru.digitalsoft.document.dto.auth; import ru.digitalsoft.document.dao.entity.auth.UserEntity; import ru.digitalsoft.document.dto.abilities.PermissionDto; import ru.digitalsoft.document.dto.abilities.RoleDto; import java.util.ArrayList; import java.util.List; public class FullUserDto extends ru.digitalsoft.document.dto.auth.UserDto { private List<RoleDto> roleDtoList = new ArrayList<>(); private List<Long> roleDtoIdList = new ArrayList<>(); private List<PermissionDto> permissionDtoList = new ArrayList<>(); private boolean changePassword; public FullUserDto() { } public FullUserDto(UserEntity entity) { super(entity); } public FullUserDto(UserEntity entity, List<PermissionDto> permissionDtoList) { super(entity); this.permissionDtoList = permissionDtoList; } public List<RoleDto> getRoleDtoList() { return roleDtoList; } public void setRoleDtoList(List<RoleDto> roleDtoList) { this.roleDtoList = roleDtoList; } public boolean isChangePassword() { return changePassword; } public void setChangePassword(boolean changePassword) { this.changePassword = changePassword; } public List<Long> getRoleDtoIdList() { return roleDtoIdList; } public void setRoleDtoIdList(List<Long> roleDtoIdList) { this.roleDtoIdList = roleDtoIdList; } public List<PermissionDto> getPermissionDtoList() { return permissionDtoList; } public void setPermissionDtoList(List<PermissionDto> permissionDtoList) { this.permissionDtoList = permissionDtoList; } }
UTF-8
Java
1,651
java
FullUserDto.java
Java
[]
null
[]
package ru.digitalsoft.document.dto.auth; import ru.digitalsoft.document.dao.entity.auth.UserEntity; import ru.digitalsoft.document.dto.abilities.PermissionDto; import ru.digitalsoft.document.dto.abilities.RoleDto; import java.util.ArrayList; import java.util.List; public class FullUserDto extends ru.digitalsoft.document.dto.auth.UserDto { private List<RoleDto> roleDtoList = new ArrayList<>(); private List<Long> roleDtoIdList = new ArrayList<>(); private List<PermissionDto> permissionDtoList = new ArrayList<>(); private boolean changePassword; public FullUserDto() { } public FullUserDto(UserEntity entity) { super(entity); } public FullUserDto(UserEntity entity, List<PermissionDto> permissionDtoList) { super(entity); this.permissionDtoList = permissionDtoList; } public List<RoleDto> getRoleDtoList() { return roleDtoList; } public void setRoleDtoList(List<RoleDto> roleDtoList) { this.roleDtoList = roleDtoList; } public boolean isChangePassword() { return changePassword; } public void setChangePassword(boolean changePassword) { this.changePassword = changePassword; } public List<Long> getRoleDtoIdList() { return roleDtoIdList; } public void setRoleDtoIdList(List<Long> roleDtoIdList) { this.roleDtoIdList = roleDtoIdList; } public List<PermissionDto> getPermissionDtoList() { return permissionDtoList; } public void setPermissionDtoList(List<PermissionDto> permissionDtoList) { this.permissionDtoList = permissionDtoList; } }
1,651
0.708661
0.708661
63
25.206348
25.254992
82
false
false
0
0
0
0
0
0
0.349206
false
false
4
12b673fcad9277125aaecd192ff1c926797db07c
35,854,386,991,945
92f3c63791fc3416c2688036153972cdff8cf928
/src/ganada/mc/action/MCLogAction.java
6b7dfbfea5a0b3b003204f399e0c1c1e40ef0b8a
[]
no_license
Crune/GaNaDa-Mart
https://github.com/Crune/GaNaDa-Mart
93852760ac5b026f6002aed930d3a5d978bbed09
d5954d787aa00840cfb5dc17582bd4b15021256e
refs/heads/master
2021-01-23T22:00:39.158000
2016-10-18T07:38:12
2016-10-18T07:38:12
67,416,810
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ganada.mc.action; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.json.simple.*; import ganada.action.common.SuperAction; import ganada.core.DB; import ganada.core.NULL; import ganada.obj.common.LogDB; import ganada.obj.common.LogDBDao; public class MCLogAction implements SuperAction { @SuppressWarnings("unchecked") @Override public String executeAction(HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); LogDBDao dao = LogDBDao.getInstance(); List<LogDB> logs; String ajaxStr=""; String reqTime1 = NULL.toDQ(request.getParameter("st")); String reqTime2 = NULL.toDQ(request.getParameter("en")); Timestamp time1 = null, time2 = null; if (!reqTime1.isEmpty()) { time1 = DB.string2Timestamp(reqTime1, "yyyy-MM-dd/hh:mm"); } if (!reqTime2.isEmpty()) { time2 = DB.string2Timestamp(reqTime2, "yyyy-MM-dd/hh:mm"); } System.out.println("mm:"+time1.toString()); //최종 완성될 JSONObject 선언(전체) JSONObject json = new JSONObject(); //person의 JSON정보를 담을 Array 선언 JSONArray logArray = new JSONArray(); logs = dao.getLogs(time1, time2); for (LogDB log : logs) { logArray.add(log.getJSONObject()); } //전체의 JSONObject에 사람이란 name으로 JSON의 정보로 구성된 Array의 value를 입력 json.put("logs", logArray); //JSONObject를 String 객체에 할당 ajaxStr = json.toJSONString(); session.setAttribute("ajaxStr", ajaxStr); return "/jsp/template/ajax.jsp"; } }
UTF-8
Java
2,056
java
MCLogAction.java
Java
[]
null
[]
package ganada.mc.action; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.json.simple.*; import ganada.action.common.SuperAction; import ganada.core.DB; import ganada.core.NULL; import ganada.obj.common.LogDB; import ganada.obj.common.LogDBDao; public class MCLogAction implements SuperAction { @SuppressWarnings("unchecked") @Override public String executeAction(HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); LogDBDao dao = LogDBDao.getInstance(); List<LogDB> logs; String ajaxStr=""; String reqTime1 = NULL.toDQ(request.getParameter("st")); String reqTime2 = NULL.toDQ(request.getParameter("en")); Timestamp time1 = null, time2 = null; if (!reqTime1.isEmpty()) { time1 = DB.string2Timestamp(reqTime1, "yyyy-MM-dd/hh:mm"); } if (!reqTime2.isEmpty()) { time2 = DB.string2Timestamp(reqTime2, "yyyy-MM-dd/hh:mm"); } System.out.println("mm:"+time1.toString()); //최종 완성될 JSONObject 선언(전체) JSONObject json = new JSONObject(); //person의 JSON정보를 담을 Array 선언 JSONArray logArray = new JSONArray(); logs = dao.getLogs(time1, time2); for (LogDB log : logs) { logArray.add(log.getJSONObject()); } //전체의 JSONObject에 사람이란 name으로 JSON의 정보로 구성된 Array의 value를 입력 json.put("logs", logArray); //JSONObject를 String 객체에 할당 ajaxStr = json.toJSONString(); session.setAttribute("ajaxStr", ajaxStr); return "/jsp/template/ajax.jsp"; } }
2,056
0.610772
0.60315
64
28.75
22.557566
108
false
false
0
0
0
0
0
0
0.59375
false
false
4
0a80084751040c68bf4feed1308268a9385ff346
38,551,626,449,365
93f2ca88d6ec804733d051ee4915ac30258e9388
/app/src/main/java/com/tekadept/coffeefinder/app/DetailsActivity.java
63fa605aad7453ae51467f4d1fed8926161a06d9
[]
no_license
Rockncoder/CoffeeFinder-2
https://github.com/Rockncoder/CoffeeFinder-2
c565734a3c60ae4dc606f7df5eb4f4f01239bd9e
9928e3a31626566a1bf170807ab33fbb184aca5e
refs/heads/master
2021-01-22T03:12:56.331000
2014-05-17T12:05:14
2014-05-17T12:05:14
19,867,916
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tekadept.coffeefinder.app; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import java.util.Map; import java.util.Objects; public class DetailsActivity extends ActionBarActivity { private Activity myActivity; private CoffeeFinderApplication myApp; private GoogleMap mMap; private int listingId; TextView businessName; TextView address; TextView city; TextView state; TextView zip; TextView telephone; Map<String, Object> shop; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.details); myActivity = this; myApp = (CoffeeFinderApplication) this.getApplication(); setWidgets(); setUpMapIfNeeded(); myActivity = this; myApp = (CoffeeFinderApplication) this.getApplication(); } private void setWidgets() { Bundle extras = getIntent().getExtras(); if(extras != null && extras.containsKey(Constants.LISTING_ID)){ listingId = extras.getInt(Constants.LISTING_ID); } else { listingId = 0; } shop = myApp.getListingItem(listingId); businessName = (TextView)findViewById(R.id.businessName); address = (TextView)findViewById(R.id.address); city = (TextView)findViewById(R.id.city); state = (TextView)findViewById(R.id.state); zip = (TextView)findViewById(R.id.zip); telephone = (TextView)findViewById(R.id.telephone); businessName.setText(shop.get("businessName").toString()); address.setText(shop.get("street").toString()); city.setText(shop.get("city").toString()); state.setText(shop.get("state").toString()); int zipCode = (int) Math.round(((Double)shop.get("zip"))); zip.setText(Integer.toString(zipCode)); telephone.setText(shop.get("phone").toString()); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.details, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { Intent intent; // Handle presses on the action bar items switch (item.getItemId()) { case R.id.action_map: intent = new Intent(this, MapActivity.class); startActivity(intent); return true; case R.id.action_listings: intent = new Intent(this, ListingsActivity.class); startActivity(intent); return true; default: return super.onOptionsItemSelected(item); } } private void setUpMapIfNeeded() { // Do a null check to confirm that we have not already instantiated the map. if (mMap == null) { // Try to obtain the map from the SupportMapFragment. mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap(); // Check if we were successful in obtaining the map. if (mMap != null) { setUpMap(); } } } private void setUpMap() { LatLng loc = new LatLng((Double)shop.get("latitude"), (Double)shop.get("longitude")); mMap.addMarker(new MarkerOptions() .position(loc) .title(shop.get("businessName").toString()) .snippet(shop.get("street").toString())); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(loc, 14)); } }
UTF-8
Java
4,247
java
DetailsActivity.java
Java
[]
null
[]
package com.tekadept.coffeefinder.app; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import java.util.Map; import java.util.Objects; public class DetailsActivity extends ActionBarActivity { private Activity myActivity; private CoffeeFinderApplication myApp; private GoogleMap mMap; private int listingId; TextView businessName; TextView address; TextView city; TextView state; TextView zip; TextView telephone; Map<String, Object> shop; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.details); myActivity = this; myApp = (CoffeeFinderApplication) this.getApplication(); setWidgets(); setUpMapIfNeeded(); myActivity = this; myApp = (CoffeeFinderApplication) this.getApplication(); } private void setWidgets() { Bundle extras = getIntent().getExtras(); if(extras != null && extras.containsKey(Constants.LISTING_ID)){ listingId = extras.getInt(Constants.LISTING_ID); } else { listingId = 0; } shop = myApp.getListingItem(listingId); businessName = (TextView)findViewById(R.id.businessName); address = (TextView)findViewById(R.id.address); city = (TextView)findViewById(R.id.city); state = (TextView)findViewById(R.id.state); zip = (TextView)findViewById(R.id.zip); telephone = (TextView)findViewById(R.id.telephone); businessName.setText(shop.get("businessName").toString()); address.setText(shop.get("street").toString()); city.setText(shop.get("city").toString()); state.setText(shop.get("state").toString()); int zipCode = (int) Math.round(((Double)shop.get("zip"))); zip.setText(Integer.toString(zipCode)); telephone.setText(shop.get("phone").toString()); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.details, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { Intent intent; // Handle presses on the action bar items switch (item.getItemId()) { case R.id.action_map: intent = new Intent(this, MapActivity.class); startActivity(intent); return true; case R.id.action_listings: intent = new Intent(this, ListingsActivity.class); startActivity(intent); return true; default: return super.onOptionsItemSelected(item); } } private void setUpMapIfNeeded() { // Do a null check to confirm that we have not already instantiated the map. if (mMap == null) { // Try to obtain the map from the SupportMapFragment. mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap(); // Check if we were successful in obtaining the map. if (mMap != null) { setUpMap(); } } } private void setUpMap() { LatLng loc = new LatLng((Double)shop.get("latitude"), (Double)shop.get("longitude")); mMap.addMarker(new MarkerOptions() .position(loc) .title(shop.get("businessName").toString()) .snippet(shop.get("street").toString())); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(loc, 14)); } }
4,247
0.645161
0.644219
126
32.706348
23.938105
106
false
false
0
0
0
0
0
0
0.603175
false
false
4
45cd7ec5f570fc7f9cd883dd68706b7eea015d5a
16,295,105,967,547
0429ec7192a11756b3f6b74cb49dc1ba7c548f60
/src/main/java/dao/resource/ImportUsersBBMSDAO.java
67f8314ec1fa2fea755b21270e10db2fb7d01204
[]
no_license
lichao20000/WEB
https://github.com/lichao20000/WEB
5c7730779280822619782825aae58506e8ba5237
5d2964387d66b9a00a54b90c09332e2792af6dae
refs/heads/master
2023-06-26T16:43:02.294000
2021-07-29T08:04:46
2021-07-29T08:04:46
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package dao.resource; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.sql.DataSource; import jxl.Sheet; import jxl.Workbook; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.jdbc.core.JdbcTemplate; import com.linkage.commons.db.PrepareSQL; import com.linkage.litms.common.database.DataSetBean; import com.linkage.litms.common.util.DateTimeUtil; public class ImportUsersBBMSDAO { private static Logger log = LoggerFactory.getLogger(ImportUsersBBMSDAO.class); // 用户信息的临时数据集 private Map<String, String> userMap = new HashMap<String, String>(); // jdbc模板 private JdbcTemplate jt; // 执行的sql列表 private String[] sqlList = null; private ArrayList<String> sqlArr = null; // 标题 private String[] title = null; // 导入文件的类型 0:excel文件 1:csv文件 @SuppressWarnings("unused") private String fileType = ""; // 导入文件的来源 0:BSS 1:IPOSS @SuppressWarnings("unused") private String resArea = "0"; /** * 输入excel文件解析入库,若数据已有值则更新,没有则新插入 * * @param file * 输入的excel文件 */ public String importFile(File file, String type) { fileType = type; sqlArr = new ArrayList<String>(); String resultCode = "0"; // 初始化列名 title = new String[11]; title[0] = "device_id"; title[1] = "city_id"; title[2] = "username"; title[3] = "serv_type_id"; title[4] = "linkaddress"; title[5] = "realname"; title[6] = "linkman"; title[7] = "linkphone"; title[8] = "cred_type_id"; title[9] = "sex"; title[10] = "address"; // 解析excel文件 ArrayList<Map> data = importFromExcel(file); // 查询当前所有的用户数据并放入map中 getAllUser(); // 取user_id long user_id = DataSetBean.getMaxId("tab_egwcustomer", "user_id"); // 遍历数据,解析入库 for (int i = 0; i < data.size(); i++) { Map dataMap = (Map) data.get(i); if ("1".equals(checkData(dataMap))) { log.debug("GSJ--------------A"); return "lackDataErr"; } else if ("2".equals(checkData(dataMap))) { log.debug("GSJ--------------B"); return "numErr"; } else { log.debug("GSJ--------------C"); if (dataMap != null) { String userName = (String) dataMap.get("username"); // 取得数据后比较数据中是否已有,若有则更新,若没有则新增 if (userMap.containsKey(userName)) { updUserInfo(dataMap, (String) userMap.get(userName)); } else { user_id++; insertUserInfo(dataMap, user_id); } } } } // 清空数据 data = null; // 初始化sql数组 int arrSize = sqlArr.size(); sqlList = new String[arrSize]; for (int j = 0; j < arrSize; j++) { sqlList[j] = sqlArr.get(j); } sqlArr = null; // 执行全部sql resultCode = "1"; //excuteSql(); return resultCode; } private String checkData(Map dataMap) { String result = "succ"; if (null == dataMap.get("device_id") || null == dataMap.get("city_id") || null == dataMap.get("username") || null == dataMap.get("serv_type_id") || null == dataMap.get("linkaddress") || null == dataMap.get("realname") || null == dataMap.get("linkman") || null == dataMap.get("linkphone") || "".equals(dataMap.get("device_id")) || "".equals(dataMap.get("city_id")) || "".equals(dataMap.get("username")) || "".equals(dataMap.get("serv_type_id")) || "".equals(dataMap.get("linkaddress")) || "".equals(dataMap.get("realname")) || "".equals(dataMap.get("linkman")) || "".equals(dataMap.get("linkphone"))) { result = "1"; } else if (!"0".equals(checkIsNumber(dataMap.get("serv_type_id").toString()))) { result = "2"; } else if (null != dataMap.get("cred_type_id") && !"0".equals(checkIsNumber(dataMap.get("cred_type_id").toString()))) { result = "2"; } log.debug("GSJ--------------E:" + result); return result; } private String checkIsNumber(String value) { String result = "0"; String s = value; if (s.length() > 5) { log.debug("您输入的数据太长!"); result = "1"; } for (int j = 0; j < s.length(); j++) { if (!(s.charAt(j) >= 48 && s.charAt(j) <= 57)) { log.debug("您输入的不是纯数字!"); result = "2"; break; } } log.debug("GSJ--------------F:" + result); return result; } /** * 输入excel文件,解析后返回ArrayList * * @param file * 输入的excel文件 * @return ArrayList<Map>,其中的map以第一行的内容为键值 */ private ArrayList<Map> importFromExcel(File file) { // 初始化返回值和字段名数组 ArrayList<Map> arr = new ArrayList<Map>(); Workbook wwb = null; Sheet ws = null; try { // 读取excel文件 wwb = Workbook.getWorkbook(file); // 总sheet数 int sheetNumber = wwb.getNumberOfSheets(); log.debug("sheetNumber:" + sheetNumber); for (int m = 0; m < sheetNumber; m++) { ws = wwb.getSheet(m); // 当前页总记录行数和列数 int rowCount = ws.getRows(); int columeCount = ws.getColumns(); log.debug("rowCount:" + rowCount); log.debug("columeCount:" + columeCount); // 第一行为字段名,所以行数大于1才执行 if (rowCount > 1 && columeCount > 0) { // 取当前页所有值放入list中 for (int i = 1; i < rowCount; i++) { Map<String, String> dataMap = new HashMap<String, String>(); for (int j = 0; j < columeCount; j++) { dataMap.put(title[j], ws.getCell(j, i) .getContents()); } arr.add(dataMap); } } } } catch (Exception e) { e.printStackTrace(); } finally { wwb.close(); } return arr; } /** * 查询当前所有的用户信息,并放入临时map中 * */ private void getAllUser() { // 查询用户名 List list = null; PrepareSQL psql = new PrepareSQL("select username,user_id from tab_egwcustomer"); psql.getSQL(); list = jt.queryForList("select username,user_id from tab_egwcustomer"); // 遍历数据 Iterator it = list.iterator(); while (it.hasNext()) { Map map = (Map) it.next(); // 若数据存在且不为空则放入map中 String username = (String) map.get("username"); String user_id = map.get("user_id").toString(); if (username != null && !"".equals(username)) { userMap.put(username, user_id); } } } /** * 更新已有的用户数据 * * @param dataMap * 解析出来的数据集 */ private void updUserInfo(Map dataMap, String user_id) { // 初始化sql语句 String sql = ""; sql += "update tab_egwcustomer "; String dateStr = (String) dataMap.get("dealdate"); log.debug("GSJ-------------B:" + dateStr); // 更新时间取当前时间 long updatetime = (new DateTimeUtil()).getLongTime(); sql += "set device_id='" + dataMap.get("device_id") + "',username='" + dataMap.get("username") + "',city_id='" + dataMap.get("city_id") + "',username='" + dataMap.get("username") + "',serv_type_id=" + dataMap.get("serv_type_id") + ",linkaddress='" + dataMap.get("linkaddress") + "',realname='" + dataMap.get("realname") + "',cred_type_id=" + dataMap.get("cred_type_id") + ",sex='" + dataMap.get("sex") + "',address='" + dataMap.get("address") + "',linkman='" + dataMap.get("linkman") + "',linkphone='" + dataMap.get("linkphone") + "',dealdate=" + dateStr + ",updatetime=" + updatetime + " where user_id=" + user_id; log.debug("updUserInfo: " + sql); PrepareSQL psql = new PrepareSQL(sql); psql.getSQL(); sqlArr.add(sql); } /** * 新增用户数据 * * @param dataMap * 解析出来的数据集 */ private void insertUserInfo(Map dataMap, long user_id) { // 初始化sql语句 String sql = ""; @SuppressWarnings("unused") int serv_type_id = 50; sql += "insert into tab_egwcustomer"; sql += "(user_id,username,device_id,city_id,serv_type_id,linkaddress,realname,cred_type_id,sex,address,linkman,linkphone) values(" + user_id + ",'" + dataMap.get("username") + "','" + dataMap.get("device_id") + "','" + dataMap.get("city_id") + "'," + dataMap.get("serv_type_id") + ",'" + dataMap.get("linkaddress") + "','" + dataMap.get("realname") + "'," + dataMap.get("cred_type_id") + ",'" + dataMap.get("sex") + "','" + dataMap.get("address") + "','" + dataMap.get("linkman") + "','" + dataMap.get("linkphone") + "')"; log.debug("insertUserInfo: " + sql); PrepareSQL psql = new PrepareSQL(sql); psql.getSQL(); sqlArr.add(sql); } /** * 执行sql数组 * */ @SuppressWarnings("unused") private String excuteSql() { String resultCode = "0"; if (sqlList != null && sqlList.length > 0 && sqlList[0] != null) { int[] code = jt.batchUpdate(sqlList); if (code[0] > 0) { resultCode = "1"; } } // 清空数组 sqlList = null; return resultCode; } /** * 初始化数据库连接 * * @param dao */ public void setDao(DataSource dao) { jt = new JdbcTemplate(dao); } public void setResArea(String resArea) { this.resArea = resArea; } }
UTF-8
Java
9,300
java
ImportUsersBBMSDAO.java
Java
[ { "context": "device_id\";\n\t\ttitle[1] = \"city_id\";\n\t\ttitle[2] = \"username\";\n\t\ttitle[3] = \"serv_type_id\";\n\t\ttitle[4] = \"link", "end": 1384, "score": 0.9790853261947632, "start": 1376, "tag": "USERNAME", "value": "username" }, { "context": "kaddress\";\n\t\ttitle[5] = \"realname\";\n\t\ttitle[6] = \"linkman\";\n\t\ttitle[7] = \"linkphone\";\n\t\ttitle[8] = \"cred_ty", "end": 1490, "score": 0.5998249053955078, "start": 1483, "tag": "NAME", "value": "linkman" }, { "context": "l) {\n\t\t\t\t\tString userName = (String) dataMap.get(\"username\");\n\t\t\t\t\t// 取得数据后比较数据中是否已有,若有则更新,若没有则新增\n\t\t\t\t\tif (u", "end": 2214, "score": 0.9992721080780029, "start": 2206, "tag": "USERNAME", "value": "username" }, { "context": "dataMap.get(\"city_id\")) || \"\".equals(dataMap.get(\"username\"))\n\t\t\t\t || \"\".equals(dataMap.get(\"serv_type_id\"))", "end": 3201, "score": 0.9964335560798645, "start": 3193, "tag": "USERNAME", "value": "username" }, { "context": "不为空则放入map中\n\t\t\tString username = (String) map.get(\"username\");\n\t\t\tString user_id = map.get(\"user_id\").toStrin", "end": 5764, "score": 0.9949251413345337, "start": 5756, "tag": "USERNAME", "value": "username" }, { "context": "(\"device_id\") + \"',username='\"\n\t\t\t\t+ dataMap.get(\"username\") + \"',city_id='\"\n\t\t\t\t+ dataMap.get(\"city_id\") + ", "end": 6388, "score": 0.9250155687332153, "start": 6380, "tag": "USERNAME", "value": "username" }, { "context": "insert into tab_egwcustomer\";\n\n\t\tsql += \"(user_id,username,device_id,city_id,serv_type_id,linkaddress,realna", "end": 7356, "score": 0.9938600659370422, "start": 7348, "tag": "USERNAME", "value": "username" }, { "context": "ues(\"\n\t\t\t\t+ user_id\n\t\t\t\t+ \",'\"\n\t\t\t\t+ dataMap.get(\"username\")\n\t\t\t\t+ \"','\"\n\t\t\t\t+ dataMap.get(\"device_id\")\n\t\t\t\t", "end": 7514, "score": 0.6844006180763245, "start": 7506, "tag": "USERNAME", "value": "username" } ]
null
[]
package dao.resource; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.sql.DataSource; import jxl.Sheet; import jxl.Workbook; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.jdbc.core.JdbcTemplate; import com.linkage.commons.db.PrepareSQL; import com.linkage.litms.common.database.DataSetBean; import com.linkage.litms.common.util.DateTimeUtil; public class ImportUsersBBMSDAO { private static Logger log = LoggerFactory.getLogger(ImportUsersBBMSDAO.class); // 用户信息的临时数据集 private Map<String, String> userMap = new HashMap<String, String>(); // jdbc模板 private JdbcTemplate jt; // 执行的sql列表 private String[] sqlList = null; private ArrayList<String> sqlArr = null; // 标题 private String[] title = null; // 导入文件的类型 0:excel文件 1:csv文件 @SuppressWarnings("unused") private String fileType = ""; // 导入文件的来源 0:BSS 1:IPOSS @SuppressWarnings("unused") private String resArea = "0"; /** * 输入excel文件解析入库,若数据已有值则更新,没有则新插入 * * @param file * 输入的excel文件 */ public String importFile(File file, String type) { fileType = type; sqlArr = new ArrayList<String>(); String resultCode = "0"; // 初始化列名 title = new String[11]; title[0] = "device_id"; title[1] = "city_id"; title[2] = "username"; title[3] = "serv_type_id"; title[4] = "linkaddress"; title[5] = "realname"; title[6] = "linkman"; title[7] = "linkphone"; title[8] = "cred_type_id"; title[9] = "sex"; title[10] = "address"; // 解析excel文件 ArrayList<Map> data = importFromExcel(file); // 查询当前所有的用户数据并放入map中 getAllUser(); // 取user_id long user_id = DataSetBean.getMaxId("tab_egwcustomer", "user_id"); // 遍历数据,解析入库 for (int i = 0; i < data.size(); i++) { Map dataMap = (Map) data.get(i); if ("1".equals(checkData(dataMap))) { log.debug("GSJ--------------A"); return "lackDataErr"; } else if ("2".equals(checkData(dataMap))) { log.debug("GSJ--------------B"); return "numErr"; } else { log.debug("GSJ--------------C"); if (dataMap != null) { String userName = (String) dataMap.get("username"); // 取得数据后比较数据中是否已有,若有则更新,若没有则新增 if (userMap.containsKey(userName)) { updUserInfo(dataMap, (String) userMap.get(userName)); } else { user_id++; insertUserInfo(dataMap, user_id); } } } } // 清空数据 data = null; // 初始化sql数组 int arrSize = sqlArr.size(); sqlList = new String[arrSize]; for (int j = 0; j < arrSize; j++) { sqlList[j] = sqlArr.get(j); } sqlArr = null; // 执行全部sql resultCode = "1"; //excuteSql(); return resultCode; } private String checkData(Map dataMap) { String result = "succ"; if (null == dataMap.get("device_id") || null == dataMap.get("city_id") || null == dataMap.get("username") || null == dataMap.get("serv_type_id") || null == dataMap.get("linkaddress") || null == dataMap.get("realname") || null == dataMap.get("linkman") || null == dataMap.get("linkphone") || "".equals(dataMap.get("device_id")) || "".equals(dataMap.get("city_id")) || "".equals(dataMap.get("username")) || "".equals(dataMap.get("serv_type_id")) || "".equals(dataMap.get("linkaddress")) || "".equals(dataMap.get("realname")) || "".equals(dataMap.get("linkman")) || "".equals(dataMap.get("linkphone"))) { result = "1"; } else if (!"0".equals(checkIsNumber(dataMap.get("serv_type_id").toString()))) { result = "2"; } else if (null != dataMap.get("cred_type_id") && !"0".equals(checkIsNumber(dataMap.get("cred_type_id").toString()))) { result = "2"; } log.debug("GSJ--------------E:" + result); return result; } private String checkIsNumber(String value) { String result = "0"; String s = value; if (s.length() > 5) { log.debug("您输入的数据太长!"); result = "1"; } for (int j = 0; j < s.length(); j++) { if (!(s.charAt(j) >= 48 && s.charAt(j) <= 57)) { log.debug("您输入的不是纯数字!"); result = "2"; break; } } log.debug("GSJ--------------F:" + result); return result; } /** * 输入excel文件,解析后返回ArrayList * * @param file * 输入的excel文件 * @return ArrayList<Map>,其中的map以第一行的内容为键值 */ private ArrayList<Map> importFromExcel(File file) { // 初始化返回值和字段名数组 ArrayList<Map> arr = new ArrayList<Map>(); Workbook wwb = null; Sheet ws = null; try { // 读取excel文件 wwb = Workbook.getWorkbook(file); // 总sheet数 int sheetNumber = wwb.getNumberOfSheets(); log.debug("sheetNumber:" + sheetNumber); for (int m = 0; m < sheetNumber; m++) { ws = wwb.getSheet(m); // 当前页总记录行数和列数 int rowCount = ws.getRows(); int columeCount = ws.getColumns(); log.debug("rowCount:" + rowCount); log.debug("columeCount:" + columeCount); // 第一行为字段名,所以行数大于1才执行 if (rowCount > 1 && columeCount > 0) { // 取当前页所有值放入list中 for (int i = 1; i < rowCount; i++) { Map<String, String> dataMap = new HashMap<String, String>(); for (int j = 0; j < columeCount; j++) { dataMap.put(title[j], ws.getCell(j, i) .getContents()); } arr.add(dataMap); } } } } catch (Exception e) { e.printStackTrace(); } finally { wwb.close(); } return arr; } /** * 查询当前所有的用户信息,并放入临时map中 * */ private void getAllUser() { // 查询用户名 List list = null; PrepareSQL psql = new PrepareSQL("select username,user_id from tab_egwcustomer"); psql.getSQL(); list = jt.queryForList("select username,user_id from tab_egwcustomer"); // 遍历数据 Iterator it = list.iterator(); while (it.hasNext()) { Map map = (Map) it.next(); // 若数据存在且不为空则放入map中 String username = (String) map.get("username"); String user_id = map.get("user_id").toString(); if (username != null && !"".equals(username)) { userMap.put(username, user_id); } } } /** * 更新已有的用户数据 * * @param dataMap * 解析出来的数据集 */ private void updUserInfo(Map dataMap, String user_id) { // 初始化sql语句 String sql = ""; sql += "update tab_egwcustomer "; String dateStr = (String) dataMap.get("dealdate"); log.debug("GSJ-------------B:" + dateStr); // 更新时间取当前时间 long updatetime = (new DateTimeUtil()).getLongTime(); sql += "set device_id='" + dataMap.get("device_id") + "',username='" + dataMap.get("username") + "',city_id='" + dataMap.get("city_id") + "',username='" + dataMap.get("username") + "',serv_type_id=" + dataMap.get("serv_type_id") + ",linkaddress='" + dataMap.get("linkaddress") + "',realname='" + dataMap.get("realname") + "',cred_type_id=" + dataMap.get("cred_type_id") + ",sex='" + dataMap.get("sex") + "',address='" + dataMap.get("address") + "',linkman='" + dataMap.get("linkman") + "',linkphone='" + dataMap.get("linkphone") + "',dealdate=" + dateStr + ",updatetime=" + updatetime + " where user_id=" + user_id; log.debug("updUserInfo: " + sql); PrepareSQL psql = new PrepareSQL(sql); psql.getSQL(); sqlArr.add(sql); } /** * 新增用户数据 * * @param dataMap * 解析出来的数据集 */ private void insertUserInfo(Map dataMap, long user_id) { // 初始化sql语句 String sql = ""; @SuppressWarnings("unused") int serv_type_id = 50; sql += "insert into tab_egwcustomer"; sql += "(user_id,username,device_id,city_id,serv_type_id,linkaddress,realname,cred_type_id,sex,address,linkman,linkphone) values(" + user_id + ",'" + dataMap.get("username") + "','" + dataMap.get("device_id") + "','" + dataMap.get("city_id") + "'," + dataMap.get("serv_type_id") + ",'" + dataMap.get("linkaddress") + "','" + dataMap.get("realname") + "'," + dataMap.get("cred_type_id") + ",'" + dataMap.get("sex") + "','" + dataMap.get("address") + "','" + dataMap.get("linkman") + "','" + dataMap.get("linkphone") + "')"; log.debug("insertUserInfo: " + sql); PrepareSQL psql = new PrepareSQL(sql); psql.getSQL(); sqlArr.add(sql); } /** * 执行sql数组 * */ @SuppressWarnings("unused") private String excuteSql() { String resultCode = "0"; if (sqlList != null && sqlList.length > 0 && sqlList[0] != null) { int[] code = jt.batchUpdate(sqlList); if (code[0] > 0) { resultCode = "1"; } } // 清空数组 sqlList = null; return resultCode; } /** * 初始化数据库连接 * * @param dao */ public void setDao(DataSource dao) { jt = new JdbcTemplate(dao); } public void setResArea(String resArea) { this.resArea = resArea; } }
9,300
0.593903
0.587503
361
22.806095
22.265362
154
false
false
0
0
0
0
0
0
2.570637
false
false
4
e7a85c01b8d0483c19d12fa2e7139a40ad2346a4
36,163,624,656,217
57f20a58fb73375efbd7df330b45b53d07c8546a
/app/src/main/java/edu/uchicago/kjhawryluk/whoWouldWin/data/remote/StarWarsRestService.java
8d2e2038c6961d77d77dafcdc4afac688e5129de
[]
no_license
kjhawryluk/whoWouldWin
https://github.com/kjhawryluk/whoWouldWin
eecde42ccb0eea0f7af517c2bee688434f62117e
8c13424800ceb02d8b3f0908b19019950d4149de
refs/heads/master
2020-09-02T09:56:30.302000
2019-11-02T18:32:50
2019-11-02T18:32:50
219,194,862
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.uchicago.kjhawryluk.whoWouldWin.data.remote; import edu.uchicago.kjhawryluk.whoWouldWin.data.remote.model.PeopleResponse; import edu.uchicago.kjhawryluk.whoWouldWin.data.remote.model.PlanetResponse; import io.reactivex.Single; import retrofit2.http.GET; import retrofit2.http.Query; /** * https://android.jlelse.eu/rest-api-on-android-made-simple-or-how-i-learned-to-stop-worrying-and-love-the-rxjava-b3c2c949cad4 */ public interface StarWarsRestService { @GET("people/") Single<PeopleResponse> loadPeople(@Query("page") int page_num); @GET("planets/") Single<PlanetResponse> loadPlanets(@Query("page") int page_num); }
UTF-8
Java
655
java
StarWarsRestService.java
Java
[]
null
[]
package edu.uchicago.kjhawryluk.whoWouldWin.data.remote; import edu.uchicago.kjhawryluk.whoWouldWin.data.remote.model.PeopleResponse; import edu.uchicago.kjhawryluk.whoWouldWin.data.remote.model.PlanetResponse; import io.reactivex.Single; import retrofit2.http.GET; import retrofit2.http.Query; /** * https://android.jlelse.eu/rest-api-on-android-made-simple-or-how-i-learned-to-stop-worrying-and-love-the-rxjava-b3c2c949cad4 */ public interface StarWarsRestService { @GET("people/") Single<PeopleResponse> loadPeople(@Query("page") int page_num); @GET("planets/") Single<PlanetResponse> loadPlanets(@Query("page") int page_num); }
655
0.770992
0.758779
20
31.75
34.771935
127
false
false
0
0
0
0
0
0
0.4
false
false
4
b5fcdb0b0a1342081fa91785dd198f945e884cf3
37,434,934,955,548
67d0f9a38efe8c1168789ac780975b2c29aa6447
/code/src/Calibragem.java
0b3d2fe168ef1c1455d8b3115204b985121b2b61
[]
no_license
viniciusilidio/ProjetoIC
https://github.com/viniciusilidio/ProjetoIC
9a92a23b470fd6533d0a496c5aa31b16671ed9d4
e95dfcb6eec456f94bf69093ae0be7b8e7348103
refs/heads/master
2021-01-01T03:38:53.207000
2018-10-17T15:06:49
2018-10-17T15:06:49
57,312,339
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.awt.Point; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.IOException; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import Catalano.Core.IntRange; import Catalano.Imaging.Color; import Catalano.Imaging.FastBitmap; public class Calibragem { private static Point[] pressed = new Point[2]; private static int count = 0; public static float pixelsPerCm; public static void calibragemCor (int intervalo, FastBitmap file) { FastBitmap fb = file; JFrame frame = new JFrame("Calibragem Cores"); frame.setBounds(0, 0, fb.getWidth(), fb.getHeight()); JPanel panel = new JPanel(); JLabel label = new JLabel(fb.toIcon()); panel.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { int[] posTemp = new int[2]; posTemp[0] = e.getY(); posTemp[1] = e.getX(); addColorToIndex(posTemp, intervalo, fb); } }); panel.add(label); frame.add(panel); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.setAlwaysOnTop(true); frame.setVisible(true); } private static void addColorToIndex(int[] pos, int intervalo, FastBitmap fb) { IntRange[] color = new IntRange[4]; int[] rgb = fb.getRGB(pos[0], pos[1]); if ((rgb[0] - intervalo) >= 0) { if (rgb[0] + intervalo <= 255) { color[0] = new IntRange(rgb[0] - intervalo, rgb[0] + intervalo); } else { color[0] = new IntRange(rgb[0] - 2 * intervalo, 255); } } else { color[0] = new IntRange(0, rgb[0] + 2 * intervalo); } if ((rgb[1] - intervalo) >= 0) { if (rgb[1] + intervalo <= 255) { color[1] = new IntRange(rgb[1] - intervalo, rgb[1] + intervalo); } else { color[1] = new IntRange(rgb[1] - 2 * intervalo, 255); } } else { color[1] = new IntRange(0, rgb[1] + 2 * intervalo); } if ((rgb[2] - intervalo) >= 0) { if (rgb[2] + intervalo <= 255) { color[2] = new IntRange(rgb[2] - intervalo, rgb[2] + intervalo); } else { color[2] = new IntRange(rgb[2] - 2 * intervalo, 255); } } else { color[2] = new IntRange(0, rgb[2] + 2 * intervalo); } color[3] = new IntRange(pos[0], pos[1]); Tela.logMessage((new Color(color[0].getMax(), color[1].getMax(), color[2].getMax())).toString()); Protocolo.add(color); } public static void calibDist (FastBitmap bmp) { FastBitmap fb = bmp; JFrame frame = new JFrame("Calibragem Distância"); frame.setBounds(0, 0, fb.getWidth(), fb.getHeight()); JPanel panel = new JPanel(); JLabel label = new JLabel(fb.toIcon()); panel.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { pressed[count] = e.getPoint(); count++; if (count == 2) { Tela.logMessage(pressed[0] + " " + pressed[1]); if (pressed[1].x > pressed[0].x) { float temp = Math.abs(pressed[1].x - pressed[0].x); pixelsPerCm = temp / Tela.distCalib; Tela.logMessage(String.valueOf(pixelsPerCm)); Tela.pixelsPerCm = pixelsPerCm; } else { float temp = Math.abs(pressed[1].y - pressed[0].y); pixelsPerCm = temp / Tela.distCalib; Tela.logMessage(String.valueOf(pixelsPerCm)); Tela.pixelsPerCm = pixelsPerCm; } } } }); panel.add(label); frame.add(panel); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.setAlwaysOnTop(true); frame.setVisible(true); } }
UTF-8
Java
3,596
java
Calibragem.java
Java
[]
null
[]
import java.awt.Point; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.IOException; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import Catalano.Core.IntRange; import Catalano.Imaging.Color; import Catalano.Imaging.FastBitmap; public class Calibragem { private static Point[] pressed = new Point[2]; private static int count = 0; public static float pixelsPerCm; public static void calibragemCor (int intervalo, FastBitmap file) { FastBitmap fb = file; JFrame frame = new JFrame("Calibragem Cores"); frame.setBounds(0, 0, fb.getWidth(), fb.getHeight()); JPanel panel = new JPanel(); JLabel label = new JLabel(fb.toIcon()); panel.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { int[] posTemp = new int[2]; posTemp[0] = e.getY(); posTemp[1] = e.getX(); addColorToIndex(posTemp, intervalo, fb); } }); panel.add(label); frame.add(panel); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.setAlwaysOnTop(true); frame.setVisible(true); } private static void addColorToIndex(int[] pos, int intervalo, FastBitmap fb) { IntRange[] color = new IntRange[4]; int[] rgb = fb.getRGB(pos[0], pos[1]); if ((rgb[0] - intervalo) >= 0) { if (rgb[0] + intervalo <= 255) { color[0] = new IntRange(rgb[0] - intervalo, rgb[0] + intervalo); } else { color[0] = new IntRange(rgb[0] - 2 * intervalo, 255); } } else { color[0] = new IntRange(0, rgb[0] + 2 * intervalo); } if ((rgb[1] - intervalo) >= 0) { if (rgb[1] + intervalo <= 255) { color[1] = new IntRange(rgb[1] - intervalo, rgb[1] + intervalo); } else { color[1] = new IntRange(rgb[1] - 2 * intervalo, 255); } } else { color[1] = new IntRange(0, rgb[1] + 2 * intervalo); } if ((rgb[2] - intervalo) >= 0) { if (rgb[2] + intervalo <= 255) { color[2] = new IntRange(rgb[2] - intervalo, rgb[2] + intervalo); } else { color[2] = new IntRange(rgb[2] - 2 * intervalo, 255); } } else { color[2] = new IntRange(0, rgb[2] + 2 * intervalo); } color[3] = new IntRange(pos[0], pos[1]); Tela.logMessage((new Color(color[0].getMax(), color[1].getMax(), color[2].getMax())).toString()); Protocolo.add(color); } public static void calibDist (FastBitmap bmp) { FastBitmap fb = bmp; JFrame frame = new JFrame("Calibragem Distância"); frame.setBounds(0, 0, fb.getWidth(), fb.getHeight()); JPanel panel = new JPanel(); JLabel label = new JLabel(fb.toIcon()); panel.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { pressed[count] = e.getPoint(); count++; if (count == 2) { Tela.logMessage(pressed[0] + " " + pressed[1]); if (pressed[1].x > pressed[0].x) { float temp = Math.abs(pressed[1].x - pressed[0].x); pixelsPerCm = temp / Tela.distCalib; Tela.logMessage(String.valueOf(pixelsPerCm)); Tela.pixelsPerCm = pixelsPerCm; } else { float temp = Math.abs(pressed[1].y - pressed[0].y); pixelsPerCm = temp / Tela.distCalib; Tela.logMessage(String.valueOf(pixelsPerCm)); Tela.pixelsPerCm = pixelsPerCm; } } } }); panel.add(label); frame.add(panel); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.setAlwaysOnTop(true); frame.setVisible(true); } }
3,596
0.618359
0.594993
135
25.622223
21.560549
99
false
false
0
0
0
0
0
0
2.955555
false
false
4
eb9e39019e1725e6794c0fffa3fe50d539bc7c1b
38,328,288,152,045
666d8536cf6b4ba5a86b047b01baf6298199e4ca
/WebKiosk/source/src/com/RMK/MonTool/Main.java
fdf14d193a248dcee7c6a789cd985e889798e76d
[]
no_license
zenonv4/FastScript
https://github.com/zenonv4/FastScript
a1ac1aa4e002ed3494b2f65ac1f77bd77a0c1c2d
0a8518f8e22eb7fe148cbe5a6b1bf9a990fd7ffb
refs/heads/master
2020-04-30T05:24:15.443000
2012-08-21T03:24:23
2012-08-21T03:24:23
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.RMK.MonTool; import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; import org.eclipse.swt.*; import org.eclipse.swt.layout.*; import org.eclipse.swt.widgets.*; import org.eclipse.swt.browser.*; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; public class Main { static Display display = new Display(); final static Shell shell = new Shell(display,SWT.ON_TOP | SWT.NO_TRIM | SWT.NO_SCROLL); final static Browser browser = new Browser(shell, SWT.NO_SCROLL); static Properties WebProps = new Properties(); public static void main(String[] args) throws IOException { // create and load default properties FileInputStream in = new FileInputStream("Web.properties"); WebProps.load(in); in.close(); FillLayout fillLayout = new FillLayout(); fillLayout.type = SWT.VERTICAL; shell.setLayout(fillLayout); shell.setMaximized(true); shell.setBounds(Display.getDefault().getPrimaryMonitor().getBounds()); shell.open(); browser.addKeyListener(new KeyAdapter() { private int keynum; public void keyPressed(KeyEvent e) { if (e.keyCode == SWT.END) { keynum += 1; if(keynum == 4) { Main.shell.close(); } } if (e.keyCode == SWT.DEL) { keynum += 0; } if (e.keyCode == SWT.HOME) { Main.this.browser.setUrl(WebProps.getProperty("url")); } } }); browser.setUrl(WebProps.getProperty("url")); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); } }
UTF-8
Java
1,589
java
Main.java
Java
[]
null
[]
package com.RMK.MonTool; import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; import org.eclipse.swt.*; import org.eclipse.swt.layout.*; import org.eclipse.swt.widgets.*; import org.eclipse.swt.browser.*; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; public class Main { static Display display = new Display(); final static Shell shell = new Shell(display,SWT.ON_TOP | SWT.NO_TRIM | SWT.NO_SCROLL); final static Browser browser = new Browser(shell, SWT.NO_SCROLL); static Properties WebProps = new Properties(); public static void main(String[] args) throws IOException { // create and load default properties FileInputStream in = new FileInputStream("Web.properties"); WebProps.load(in); in.close(); FillLayout fillLayout = new FillLayout(); fillLayout.type = SWT.VERTICAL; shell.setLayout(fillLayout); shell.setMaximized(true); shell.setBounds(Display.getDefault().getPrimaryMonitor().getBounds()); shell.open(); browser.addKeyListener(new KeyAdapter() { private int keynum; public void keyPressed(KeyEvent e) { if (e.keyCode == SWT.END) { keynum += 1; if(keynum == 4) { Main.shell.close(); } } if (e.keyCode == SWT.DEL) { keynum += 0; } if (e.keyCode == SWT.HOME) { Main.this.browser.setUrl(WebProps.getProperty("url")); } } }); browser.setUrl(WebProps.getProperty("url")); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); } }
1,589
0.681561
0.679673
64
23.84375
20.227007
88
false
false
0
0
0
0
0
0
2.5625
false
false
4
27031b6f656f384d45f6ee9cdb8bde0a28bd7b5b
29,875,792,552,803
f7a53679f91dd7095b4a1b925f092dc28987d06b
/src/test/java/test/PrimaryDefinitions.java
b8bfaa864972ab3f65aaf978aad704e1ae002a5f
[]
no_license
engNagi/test_cucmber_error
https://github.com/engNagi/test_cucmber_error
5fad22807659fb80b9ea04405687aa32e8b4e59f
a3a769fee4494a1e9d5cb978be2fa8219bb37b18
refs/heads/master
2020-04-23T02:40:44
2019-02-25T09:08:36
2019-02-25T09:08:36
170,853,925
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package test; import cucumber.api.Argument; import cucumber.api.CucumberOptions; import cucumber.api.Scenario; import io.cucumber.datatable.DataTable; import cucumber.api.java.After; import cucumber.api.java.AfterStep; import cucumber.api.java.Before; import cucumber.api.java.en.And; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import org.junit.Assert; import org.openqa.selenium.*; import org.openqa.selenium.WebDriver.Options; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.ui.FluentWait; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxOptions; import static org.junit.Assert.fail; import java.io.IOException; import java.io.File; import java.time.Duration; import java.util.Date; import java.util.List; import java.util.Map; import java.util.function.Function; import java.text.SimpleDateFormat; import org.apache.commons.io.FileUtils; public class PrimaryDefinitions { public static WebDriver driver; public String scenario_name; @Before public void before(Scenario scenario) { if ( System.getenv("MAVEN_CMD_LINE_ARGS").contains("DBROWSER=chrome") ) { if ( System.getenv("MAVEN_CMD_LINE_ARGS").contains("DHEADLESS=true") ){ ChromeOptions chromeOptions = new ChromeOptions(); chromeOptions.addArguments("--headless"); driver = new ChromeDriver(chromeOptions); driver.manage().window().setSize(new Dimension(1280, 800)); //driver.manage().deleteAllCookies();; } else { driver = new ChromeDriver(); driver.manage().window().setSize(new Dimension(1280, 800)); //driver.manage().deleteAllCookies(); } } else if ( System.getenv("MAVEN_CMD_LINE_ARGS").contains("DBROWSER=firefox") ){ if ( System.getenv("MAVEN_CMD_LINE_ARGS").contains("DHEADLESS=true") ){ FirefoxOptions firefoxOptions = new FirefoxOptions(); firefoxOptions.addArguments("--headless"); driver = new FirefoxDriver(firefoxOptions); driver.manage().window().setSize(new Dimension(1280, 800)); } else { driver = new FirefoxDriver(); driver.manage().window().setSize(new Dimension(1280, 800)); //driver.manage().deleteAllCookies(); } } else { driver = new ChromeDriver(); driver.manage().window().setSize(new Dimension(1280, 800)); driver.manage().deleteAllCookies(); } scenario_name = scenario.getName(); } @After ("@LoginAdmin") public void after(Scenario scenario) { if (!scenario.isFailed()) { Actions action = new Actions(driver); action.moveToElement(driver.findElement(By.id("wp-admin-bar-my-account"))).perform(); WebElement e_abmelden = new FluentWait<WebDriver>(driver).withTimeout(Duration.ofSeconds(5)).pollingEvery(Duration.ofSeconds(1)).ignoring(NoSuchElementException.class).until(new Function<WebDriver, WebElement>() { public WebElement apply(WebDriver driver) { return driver.findElement(By.linkText("Abmelden")); } }); e_abmelden.click(); WebElement e_message = new FluentWait<WebDriver>(driver).withTimeout(Duration.ofSeconds(5)).pollingEvery(Duration.ofSeconds(1)).ignoring(NoSuchElementException.class).until(new Function<WebDriver, WebElement>() { public WebElement apply(WebDriver driver) { return driver.findElement(By.className("message")); } }); Assert.assertEquals(e_message.getText().contains("Du hast dich erfolgreich abgemeldet."), true); //byte[] screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES); //scenario.embed(screenshot, "image/png"); } } @AfterStep public void afterStep (Scenario scenario) { if ( System.getenv("MAVEN_CMD_LINE_ARGS").contains("SCREENSHOT=true") ) { File src= ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); Date date = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("MMddyy_HHmmss"); String strDate = formatter.format(date); try { FileUtils.copyFile(src, new File("/home/testautomation/Documents/picture_"+scenario_name+"_"+strDate+".png")); } catch (IOException e){ } } } }
UTF-8
Java
4,835
java
PrimaryDefinitions.java
Java
[ { "context": "o_name = scenario.getName();\n\n }\n\n @After (\"@LoginAdmin\")\n public void after(Scenario scenario) {\n ", "end": 2895, "score": 0.9481961131095886, "start": 2884, "tag": "USERNAME", "value": "@LoginAdmin" } ]
null
[]
package test; import cucumber.api.Argument; import cucumber.api.CucumberOptions; import cucumber.api.Scenario; import io.cucumber.datatable.DataTable; import cucumber.api.java.After; import cucumber.api.java.AfterStep; import cucumber.api.java.Before; import cucumber.api.java.en.And; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import org.junit.Assert; import org.openqa.selenium.*; import org.openqa.selenium.WebDriver.Options; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.ui.FluentWait; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxOptions; import static org.junit.Assert.fail; import java.io.IOException; import java.io.File; import java.time.Duration; import java.util.Date; import java.util.List; import java.util.Map; import java.util.function.Function; import java.text.SimpleDateFormat; import org.apache.commons.io.FileUtils; public class PrimaryDefinitions { public static WebDriver driver; public String scenario_name; @Before public void before(Scenario scenario) { if ( System.getenv("MAVEN_CMD_LINE_ARGS").contains("DBROWSER=chrome") ) { if ( System.getenv("MAVEN_CMD_LINE_ARGS").contains("DHEADLESS=true") ){ ChromeOptions chromeOptions = new ChromeOptions(); chromeOptions.addArguments("--headless"); driver = new ChromeDriver(chromeOptions); driver.manage().window().setSize(new Dimension(1280, 800)); //driver.manage().deleteAllCookies();; } else { driver = new ChromeDriver(); driver.manage().window().setSize(new Dimension(1280, 800)); //driver.manage().deleteAllCookies(); } } else if ( System.getenv("MAVEN_CMD_LINE_ARGS").contains("DBROWSER=firefox") ){ if ( System.getenv("MAVEN_CMD_LINE_ARGS").contains("DHEADLESS=true") ){ FirefoxOptions firefoxOptions = new FirefoxOptions(); firefoxOptions.addArguments("--headless"); driver = new FirefoxDriver(firefoxOptions); driver.manage().window().setSize(new Dimension(1280, 800)); } else { driver = new FirefoxDriver(); driver.manage().window().setSize(new Dimension(1280, 800)); //driver.manage().deleteAllCookies(); } } else { driver = new ChromeDriver(); driver.manage().window().setSize(new Dimension(1280, 800)); driver.manage().deleteAllCookies(); } scenario_name = scenario.getName(); } @After ("@LoginAdmin") public void after(Scenario scenario) { if (!scenario.isFailed()) { Actions action = new Actions(driver); action.moveToElement(driver.findElement(By.id("wp-admin-bar-my-account"))).perform(); WebElement e_abmelden = new FluentWait<WebDriver>(driver).withTimeout(Duration.ofSeconds(5)).pollingEvery(Duration.ofSeconds(1)).ignoring(NoSuchElementException.class).until(new Function<WebDriver, WebElement>() { public WebElement apply(WebDriver driver) { return driver.findElement(By.linkText("Abmelden")); } }); e_abmelden.click(); WebElement e_message = new FluentWait<WebDriver>(driver).withTimeout(Duration.ofSeconds(5)).pollingEvery(Duration.ofSeconds(1)).ignoring(NoSuchElementException.class).until(new Function<WebDriver, WebElement>() { public WebElement apply(WebDriver driver) { return driver.findElement(By.className("message")); } }); Assert.assertEquals(e_message.getText().contains("Du hast dich erfolgreich abgemeldet."), true); //byte[] screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES); //scenario.embed(screenshot, "image/png"); } } @AfterStep public void afterStep (Scenario scenario) { if ( System.getenv("MAVEN_CMD_LINE_ARGS").contains("SCREENSHOT=true") ) { File src= ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); Date date = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("MMddyy_HHmmss"); String strDate = formatter.format(date); try { FileUtils.copyFile(src, new File("/home/testautomation/Documents/picture_"+scenario_name+"_"+strDate+".png")); } catch (IOException e){ } } } }
4,835
0.646536
0.63847
123
38.317074
36.642044
225
false
false
0
0
0
0
0
0
0.642276
false
false
4
75aed81aa2bd237fd04f9b5f4ab23a236905463e
34,608,846,498,233
0d0a8a7bd0e00bc05926d5d275c3cdc546507f3c
/app/src/main/java/com/gaidelfanclub/codenames/utils/KeywordsStore.java
6b283d169cabbe52408c285ef7ee802a00e17bf1
[]
no_license
GaidelFanClub/Codenames
https://github.com/GaidelFanClub/Codenames
13ec262aed9fb68335015724499ba00b086f8dd9
f57fd953aa567b876b6393cb05cd6d12c20bbeb2
refs/heads/master
2021-01-11T14:53:32.891000
2017-02-02T20:06:52
2017-02-02T20:06:52
80,243,234
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.gaidelfanclub.codenames.utils; import android.content.Context; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.zip.ZipInputStream; public class KeywordsStore { private static KeywordsStore instance = new KeywordsStore(); public static KeywordsStore getInstance() { return instance; } private String[] data; private CountDownLatch latch = new CountDownLatch(1); public void init(final Context context) { new Thread() { @Override public void run() { innerInit(context); latch.countDown(); } }.start(); } private void awaitInit() { try { latch.await(); } catch (InterruptedException ignored) { } } public int getSeedByPublicKey(String keyword) { awaitInit(); return Arrays.binarySearch(data, keyword); } public String getParticipantKeyword(String keyword) { awaitInit(); return data[new Random(keyword.hashCode()).nextInt(data.length)]; } public String getWord(int index) { awaitInit(); return data[index]; } public int findLowerPosition(String keyword) { awaitInit(); int left = 0; int right = data.length - 1; int result = data.length - 1; while (left <= right) { int mid = (left + right) >> 1; if (data[mid].compareTo(keyword) <= 0) { result = mid; left = mid + 1; } else { right = mid - 1; } } return result; } private void innerInit(Context context) { try { InputStream stream = context.getAssets().open("dic.zip"); ZipInputStream zipInputStream = new ZipInputStream(new BufferedInputStream(stream)); zipInputStream.getNextEntry(); BufferedReader reader = new BufferedReader(new InputStreamReader(zipInputStream)); List<String> list = new ArrayList<>(); while (true) { String line = reader.readLine(); if (line == null) break; list.add(line); } data = list.toArray(new String[list.size()]); } catch (Exception e) { throw new RuntimeException(); } } }
UTF-8
Java
2,607
java
KeywordsStore.java
Java
[]
null
[]
package com.gaidelfanclub.codenames.utils; import android.content.Context; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.zip.ZipInputStream; public class KeywordsStore { private static KeywordsStore instance = new KeywordsStore(); public static KeywordsStore getInstance() { return instance; } private String[] data; private CountDownLatch latch = new CountDownLatch(1); public void init(final Context context) { new Thread() { @Override public void run() { innerInit(context); latch.countDown(); } }.start(); } private void awaitInit() { try { latch.await(); } catch (InterruptedException ignored) { } } public int getSeedByPublicKey(String keyword) { awaitInit(); return Arrays.binarySearch(data, keyword); } public String getParticipantKeyword(String keyword) { awaitInit(); return data[new Random(keyword.hashCode()).nextInt(data.length)]; } public String getWord(int index) { awaitInit(); return data[index]; } public int findLowerPosition(String keyword) { awaitInit(); int left = 0; int right = data.length - 1; int result = data.length - 1; while (left <= right) { int mid = (left + right) >> 1; if (data[mid].compareTo(keyword) <= 0) { result = mid; left = mid + 1; } else { right = mid - 1; } } return result; } private void innerInit(Context context) { try { InputStream stream = context.getAssets().open("dic.zip"); ZipInputStream zipInputStream = new ZipInputStream(new BufferedInputStream(stream)); zipInputStream.getNextEntry(); BufferedReader reader = new BufferedReader(new InputStreamReader(zipInputStream)); List<String> list = new ArrayList<>(); while (true) { String line = reader.readLine(); if (line == null) break; list.add(line); } data = list.toArray(new String[list.size()]); } catch (Exception e) { throw new RuntimeException(); } } }
2,607
0.579593
0.576525
95
26.442104
20.991585
96
false
false
0
0
0
0
0
0
0.484211
false
false
4
f19093cf62da9466d36b50d26c31495ad923bf9c
35,682,588,326,790
f69a85b6509aa10d72961b8b8dd322622ec01914
/app/src/main/java/com/dyh/commonlib/ui/adapter/BannerListAdapter.java
4641a70d308051761d9cd107dc50076201e3521f
[]
no_license
zqlhh/CommonLib
https://github.com/zqlhh/CommonLib
012e9528d71866a0005f08229739bd5641ccef34
6b97f3a934fdd489cd89505f62fb42d41448b8d6
refs/heads/master
2022-03-29T18:42:04.620000
2020-01-15T08:52:25
2020-01-15T08:52:25
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.dyh.commonlib.ui.adapter; import android.support.annotation.NonNull; import android.widget.ImageView; import com.bumptech.glide.Glide; import com.dyh.commonlib.R; import com.dyh.commonlib.constants.ServerConstants; import com.dyh.commonlib.entity.response.BannerItemBean; import com.dyh.commonlib.entity.response.DeliveryAddressManageItemBean; import com.dyh.commonlib.util.CommonImagesUtil; import com.dyh.common.lib.dw.listview.BaseQuickRecyclerViewAdapter; import com.dyh.common.lib.recyclerview_helper.BaseViewHolder; import java.util.List; /** * 作者:DongYonghui * 邮箱:648731994@qq.com * 创建时间:2019/11/19/019 17:33 * 描述:Tpc列表 */ public class BannerListAdapter extends BaseQuickRecyclerViewAdapter<BannerItemBean> { public BannerListAdapter(int layoutResId) { super(layoutResId); } @Override protected void convert(@NonNull BaseViewHolder helper, BannerItemBean item) { StringBuilder deliveryAddressInfo = new StringBuilder(); List<DeliveryAddressManageItemBean> addressManageItemBeanList = item.getDeliveryAddress(); if (null != addressManageItemBeanList) { for (int i = 0; i < addressManageItemBeanList.size(); i++) { if (i > 5) { break; } deliveryAddressInfo.append(addressManageItemBeanList.get(i).getRemark()).append(";"); } } helper.setText(R.id.mClickedEffectTextView, item.getToUrl())// .setText(R.id.mStatusTextView, ServerConstants.BANNER_TYPE.IN_APP_PAGES.equals(item.getType()) ? R.string.inAppPages : R.string.webUrl)//跳转类型 .setText(R.id.mDeliverAddressTextView, deliveryAddressInfo.toString())//配送地址 .addOnClickListener(R.id.mEditTextView) .addOnClickListener(R.id.mDeleteTextView); //商品图片 Glide.with(mContext).load(CommonImagesUtil.getFullImageHttpUrl(item.getImageUrl())).into((ImageView) helper.getView(R.id.mImageView)); } }
UTF-8
Java
2,086
java
BannerListAdapter.java
Java
[ { "context": "aseViewHolder;\n\nimport java.util.List;\n\n/**\n * 作者:DongYonghui\n * 邮箱:648731994@qq.com\n * 创建时间:2019/11/19/019 17:", "end": 582, "score": 0.9968276619911194, "start": 571, "tag": "NAME", "value": "DongYonghui" }, { "context": "port java.util.List;\n\n/**\n * 作者:DongYonghui\n * 邮箱:648731994@qq.com\n * 创建时间:2019/11/19/019 17:33\n * 描述:Tpc列表\n */\npubl", "end": 605, "score": 0.9992462992668152, "start": 589, "tag": "EMAIL", "value": "648731994@qq.com" } ]
null
[]
package com.dyh.commonlib.ui.adapter; import android.support.annotation.NonNull; import android.widget.ImageView; import com.bumptech.glide.Glide; import com.dyh.commonlib.R; import com.dyh.commonlib.constants.ServerConstants; import com.dyh.commonlib.entity.response.BannerItemBean; import com.dyh.commonlib.entity.response.DeliveryAddressManageItemBean; import com.dyh.commonlib.util.CommonImagesUtil; import com.dyh.common.lib.dw.listview.BaseQuickRecyclerViewAdapter; import com.dyh.common.lib.recyclerview_helper.BaseViewHolder; import java.util.List; /** * 作者:DongYonghui * 邮箱:<EMAIL> * 创建时间:2019/11/19/019 17:33 * 描述:Tpc列表 */ public class BannerListAdapter extends BaseQuickRecyclerViewAdapter<BannerItemBean> { public BannerListAdapter(int layoutResId) { super(layoutResId); } @Override protected void convert(@NonNull BaseViewHolder helper, BannerItemBean item) { StringBuilder deliveryAddressInfo = new StringBuilder(); List<DeliveryAddressManageItemBean> addressManageItemBeanList = item.getDeliveryAddress(); if (null != addressManageItemBeanList) { for (int i = 0; i < addressManageItemBeanList.size(); i++) { if (i > 5) { break; } deliveryAddressInfo.append(addressManageItemBeanList.get(i).getRemark()).append(";"); } } helper.setText(R.id.mClickedEffectTextView, item.getToUrl())// .setText(R.id.mStatusTextView, ServerConstants.BANNER_TYPE.IN_APP_PAGES.equals(item.getType()) ? R.string.inAppPages : R.string.webUrl)//跳转类型 .setText(R.id.mDeliverAddressTextView, deliveryAddressInfo.toString())//配送地址 .addOnClickListener(R.id.mEditTextView) .addOnClickListener(R.id.mDeleteTextView); //商品图片 Glide.with(mContext).load(CommonImagesUtil.getFullImageHttpUrl(item.getImageUrl())).into((ImageView) helper.getView(R.id.mImageView)); } }
2,077
0.69803
0.685222
50
39.599998
34.15377
142
false
false
0
0
0
0
0
0
0.52
false
false
4
178293604f0b6b395eea3ed4bd789ce416a2b168
26,336,739,521,312
3ea918037c6de4f27c37d253f0a8c74689bf1c9f
/app/build/intermediates/classes/debug/com/e/legion/test/app/databinding/FragmentRepoBinding.java
90acce2a884a367c9332866748e4496dec2d3eaa
[]
no_license
Vittt2008/eLegionTestApp
https://github.com/Vittt2008/eLegionTestApp
35a2a160b0002509673d9676e475c91133a65fbc
47317ca1920bcfb82e27478a4f7355156453d54e
refs/heads/master
2020-04-15T14:42:11.249000
2015-10-03T12:18:41
2015-10-03T12:18:41
40,430,315
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.e.legion.test.app.databinding; import com.e.legion.test.app.R; import com.e.legion.test.app.BR; import android.view.View; public class FragmentRepoBinding extends android.databinding.ViewDataBinding { private static final android.databinding.ViewDataBinding.IncludedLayouts sIncludes; private static final android.util.SparseIntArray sViewsWithIds; static { sIncludes = null; sViewsWithIds = new android.util.SparseIntArray(); sViewsWithIds.put(R.id.rv_commits, 1); sViewsWithIds.put(R.id.pb_commits, 2); } // views private final android.widget.FrameLayout mboundView0; public final android.widget.ProgressBar pbCommits; public final android.support.v7.widget.RecyclerView rvCommits; // variables // values // listeners public FragmentRepoBinding(View root) { super(root, 0); final Object[] bindings = mapBindings(root, 3, sIncludes, sViewsWithIds); this.mboundView0 = (android.widget.FrameLayout) bindings[0]; this.mboundView0.setTag(null); this.pbCommits = (android.widget.ProgressBar) bindings[2]; this.rvCommits = (android.support.v7.widget.RecyclerView) bindings[1]; setRootTag(root); invalidateAll(); } @Override public void invalidateAll() { synchronized(this) { mDirtyFlags = 0b10L; } requestRebind(); } @Override public boolean hasPendingBindings() { synchronized(this) { if (mDirtyFlags != 0) { return true; } } return false; } private void log(String msg, long i) { android.util.Log.d("BINDER", msg + ":" + Long.toHexString(i)); } public boolean setVariable(int variableId, Object variable) { switch(variableId) { } return false; } public void setRepo(com.e.legion.test.app.entities.Repo repo) { // not used, ignore } public com.e.legion.test.app.entities.Repo getRepo() { return null; } @Override protected boolean onFieldChange(int localFieldId, Object object, int fieldId) { switch (localFieldId) { } return false; } @Override protected void executeBindings() { long dirtyFlags = 0; synchronized(this) { dirtyFlags = mDirtyFlags; mDirtyFlags = 0; } // batch finished } // Listener Stub Implementations // dirty flag private long mDirtyFlags = 0b1111111111111111111111111111111111111111111111111111111111111111L; public static FragmentRepoBinding inflate(android.view.LayoutInflater inflater, android.view.ViewGroup root, boolean attachToRoot) { return android.databinding.DataBindingUtil.<FragmentRepoBinding>inflate(inflater, com.e.legion.test.app.R.layout.fragment_repo, root, attachToRoot); } public static FragmentRepoBinding inflate(android.view.LayoutInflater inflater) { return bind(inflater.inflate(com.e.legion.test.app.R.layout.fragment_repo, null, false)); } public static FragmentRepoBinding bind(android.view.View view) { if (!"layout/fragment_repo_0".equals(view.getTag())) { throw new RuntimeException("view tag isn't correct on view:" + view.getTag()); } return new FragmentRepoBinding(view); } } /* flag mapping flag 0: repo~ flag 1: INVALIDATE ANY flag mapping end*/ //end
UTF-8
Java
3,539
java
FragmentRepoBinding.java
Java
[]
null
[]
package com.e.legion.test.app.databinding; import com.e.legion.test.app.R; import com.e.legion.test.app.BR; import android.view.View; public class FragmentRepoBinding extends android.databinding.ViewDataBinding { private static final android.databinding.ViewDataBinding.IncludedLayouts sIncludes; private static final android.util.SparseIntArray sViewsWithIds; static { sIncludes = null; sViewsWithIds = new android.util.SparseIntArray(); sViewsWithIds.put(R.id.rv_commits, 1); sViewsWithIds.put(R.id.pb_commits, 2); } // views private final android.widget.FrameLayout mboundView0; public final android.widget.ProgressBar pbCommits; public final android.support.v7.widget.RecyclerView rvCommits; // variables // values // listeners public FragmentRepoBinding(View root) { super(root, 0); final Object[] bindings = mapBindings(root, 3, sIncludes, sViewsWithIds); this.mboundView0 = (android.widget.FrameLayout) bindings[0]; this.mboundView0.setTag(null); this.pbCommits = (android.widget.ProgressBar) bindings[2]; this.rvCommits = (android.support.v7.widget.RecyclerView) bindings[1]; setRootTag(root); invalidateAll(); } @Override public void invalidateAll() { synchronized(this) { mDirtyFlags = 0b10L; } requestRebind(); } @Override public boolean hasPendingBindings() { synchronized(this) { if (mDirtyFlags != 0) { return true; } } return false; } private void log(String msg, long i) { android.util.Log.d("BINDER", msg + ":" + Long.toHexString(i)); } public boolean setVariable(int variableId, Object variable) { switch(variableId) { } return false; } public void setRepo(com.e.legion.test.app.entities.Repo repo) { // not used, ignore } public com.e.legion.test.app.entities.Repo getRepo() { return null; } @Override protected boolean onFieldChange(int localFieldId, Object object, int fieldId) { switch (localFieldId) { } return false; } @Override protected void executeBindings() { long dirtyFlags = 0; synchronized(this) { dirtyFlags = mDirtyFlags; mDirtyFlags = 0; } // batch finished } // Listener Stub Implementations // dirty flag private long mDirtyFlags = 0b1111111111111111111111111111111111111111111111111111111111111111L; public static FragmentRepoBinding inflate(android.view.LayoutInflater inflater, android.view.ViewGroup root, boolean attachToRoot) { return android.databinding.DataBindingUtil.<FragmentRepoBinding>inflate(inflater, com.e.legion.test.app.R.layout.fragment_repo, root, attachToRoot); } public static FragmentRepoBinding inflate(android.view.LayoutInflater inflater) { return bind(inflater.inflate(com.e.legion.test.app.R.layout.fragment_repo, null, false)); } public static FragmentRepoBinding bind(android.view.View view) { if (!"layout/fragment_repo_0".equals(view.getTag())) { throw new RuntimeException("view tag isn't correct on view:" + view.getTag()); } return new FragmentRepoBinding(view); } } /* flag mapping flag 0: repo~ flag 1: INVALIDATE ANY flag mapping end*/ //end
3,539
0.64538
0.621079
106
32.396225
29.924332
156
false
false
0
0
0
0
67
0.018932
0.528302
false
false
4
95bf6019fce74af7516b38f09f685c9afc48ddb4
35,527,969,499,045
8f748974ae4318cc9dbd9cf4f5c5da9621440e75
/bean/ResultJson.java
966a1218e27b003e408f9dbdbb40c823668d2474
[]
no_license
heyu1024/JavaUtil
https://github.com/heyu1024/JavaUtil
b3a339188bb5ee3eda3196b0727978bb7c743b2e
fc03b225e163dbb446ba10c1da0c4f4470a32a34
refs/heads/main
2023-08-22T08:13:18.061000
2021-10-22T12:13:43
2021-10-22T12:13:43
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.heyu.bean; /** * description TODO . * * @author chengxuewen * @createTime 2021年08月23日 19:14:00 */ public class ResultJson { private String theme; private String tagclass; private String tag; private String article; private String url; @Override public String toString() { return "ResultJson{" + "theme='" + theme + '\'' + ", tagclass='" + tagclass + '\'' + ", tag='" + tag + '\'' + ", article='" + article + '\'' + ", url='" + url + '\'' + '}'; } public ResultJson() { } public String getTheme() { return theme; } public void setTheme(String theme) { this.theme = theme; } public String getTagclass() { return tagclass; } public void setTagclass(String tagclass) { this.tagclass = tagclass; } public String getTag() { return tag; } public void setTag(String tag) { this.tag = tag; } public String getArticle() { return article; } public void setArticle(String article) { this.article = article; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public ResultJson(String theme, String tagclass, String tag, String article, String url) { this.theme = theme; this.tagclass = tagclass; this.tag = tag; this.article = article; this.url = url; } }
UTF-8
Java
1,573
java
ResultJson.java
Java
[ { "context": "eyu.bean;\n\n/**\n * description TODO .\n *\n * @author chengxuewen\n * @createTime 2021年08月23日 19:14:00\n */\npublic cl", "end": 75, "score": 0.9670537710189819, "start": 64, "tag": "USERNAME", "value": "chengxuewen" } ]
null
[]
package com.heyu.bean; /** * description TODO . * * @author chengxuewen * @createTime 2021年08月23日 19:14:00 */ public class ResultJson { private String theme; private String tagclass; private String tag; private String article; private String url; @Override public String toString() { return "ResultJson{" + "theme='" + theme + '\'' + ", tagclass='" + tagclass + '\'' + ", tag='" + tag + '\'' + ", article='" + article + '\'' + ", url='" + url + '\'' + '}'; } public ResultJson() { } public String getTheme() { return theme; } public void setTheme(String theme) { this.theme = theme; } public String getTagclass() { return tagclass; } public void setTagclass(String tagclass) { this.tagclass = tagclass; } public String getTag() { return tag; } public void setTag(String tag) { this.tag = tag; } public String getArticle() { return article; } public void setArticle(String article) { this.article = article; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public ResultJson(String theme, String tagclass, String tag, String article, String url) { this.theme = theme; this.tagclass = tagclass; this.tag = tag; this.article = article; this.url = url; } }
1,573
0.523931
0.514997
77
19.350649
17.031496
94
false
false
0
0
0
0
0
0
0.38961
false
false
4
172388f43248822370cb4912c8e7295675ba1633
36,043,365,574,029
331b0f329919166aa1be62a11850ba1090c5537e
/src/main/java/com/bindingdai/repository/DiagnosisRepository.java
8660b525f83d6eb2667ae2bd77187d9172f4ec60
[]
no_license
landesire/SpringDiagnosisEMR
https://github.com/landesire/SpringDiagnosisEMR
d50107c16cf46050f4e7bfb0df378d9f80b7ae19
33a57164c72442122441de57c5ec0ad11d6952e3
refs/heads/master
2020-04-06T07:08:45.268000
2016-08-26T14:17:07
2016-08-26T14:17:07
66,650,345
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bindingdai.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.bindingdai.model.DiagnosisEntity; /** * Created by daibinding on 16/4/19. */ @Repository public interface DiagnosisRepository extends JpaRepository<DiagnosisEntity,Integer>{ }
UTF-8
Java
339
java
DiagnosisRepository.java
Java
[ { "context": "indingdai.model.DiagnosisEntity;\n/**\n * Created by daibinding on 16/4/19.\n */\n@Repository\npublic interface Diag", "end": 221, "score": 0.9996885657310486, "start": 211, "tag": "USERNAME", "value": "daibinding" } ]
null
[]
package com.bindingdai.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.bindingdai.model.DiagnosisEntity; /** * Created by daibinding on 16/4/19. */ @Repository public interface DiagnosisRepository extends JpaRepository<DiagnosisEntity,Integer>{ }
339
0.823009
0.80826
12
27.166666
27.156441
84
false
false
0
0
0
0
0
0
0.416667
false
false
4
d57eb186861276ecf2715d2fc0910907b6fe75cc
7,267,084,668,763
7ed2e21225fdf3e91d84934c4bd88493e441a5e7
/app/src/main/java/com/xiongxh/baking_app/api/RecipeApiService.java
f4760ee1d2f5b5efb0a0bb01872c6348fceaaad3
[ "MIT" ]
permissive
xionger/Baking-App
https://github.com/xionger/Baking-App
93e66bfa871a8c54fbf45b7deac34c44e4f62c1e
2a8c1f44df6ae8c7bff50876a50c30685ba7a2f6
refs/heads/master
2021-01-20T06:51:40.610000
2018-03-26T23:14:12
2018-03-26T23:14:12
101,519,777
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.xiongxh.baking_app.api; import okhttp3.OkHttpClient; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; public class RecipeApiService { private static Retrofit retrofit; private static final String API_URL = "https://d17h27t6h515a5.cloudfront.net/topher/2017/May/59121517_baking/"; public static void initRetrofit(OkHttpClient client){ retrofit = new Retrofit.Builder() .baseUrl(API_URL) .client(client) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build(); } public static ApiService initService(){ ApiService apiService = retrofit.create(ApiService.class); return apiService; } }
UTF-8
Java
899
java
RecipeApiService.java
Java
[]
null
[]
package com.xiongxh.baking_app.api; import okhttp3.OkHttpClient; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; public class RecipeApiService { private static Retrofit retrofit; private static final String API_URL = "https://d17h27t6h515a5.cloudfront.net/topher/2017/May/59121517_baking/"; public static void initRetrofit(OkHttpClient client){ retrofit = new Retrofit.Builder() .baseUrl(API_URL) .client(client) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build(); } public static ApiService initService(){ ApiService apiService = retrofit.create(ApiService.class); return apiService; } }
899
0.690768
0.659622
30
28.966667
25.521864
85
false
false
0
0
0
0
0
0
0.333333
false
false
4
95ca033cb3ad97db365ede1c4f0cd79d7f334a30
20,349,555,098,846
eed7f52c7227c146c48f7d377fcbdcb3708e18f8
/carbonj.service/src/main/java/com/demandware/carbonj/service/engine/FileCheckPointMgr.java
b86e30199cf8167367c47797b0b6a618ed782761
[ "BSD-3-Clause" ]
permissive
salesforce/carbonj
https://github.com/salesforce/carbonj
1b7cd3ed231238d7989e1924669e201f84e1e21e
195c316a59a9c3ae83ff0214af2418e1e667e79a
refs/heads/master
2023-09-03T17:50:13.634000
2023-09-02T02:32:03
2023-09-02T02:32:03
237,186,234
26
19
BSD-3-Clause
false
2023-09-11T15:49:37
2020-01-30T10:08:18
2023-06-21T04:10:13
2023-09-11T15:49:36
1,875
19
16
4
Java
false
false
/** * Copyright (c) 2018, salesforce.com, inc. * All rights reserved. * SPDX-License-Identifier: BSD-3-Clause * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause */ package com.demandware.carbonj.service.engine; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.PrintWriter; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Date; import java.util.concurrent.TimeUnit; public class FileCheckPointMgr implements CheckPointMgr<Date> { private static final Logger log = LoggerFactory.getLogger(FileCheckPointMgr.class); private static final String VERSION = "1.0"; private final File checkPointFile; private final int defaultOffsetMins; public FileCheckPointMgr(Path checkPointDir, int defaultOffsetMins) throws Exception { this.defaultOffsetMins = defaultOffsetMins; if (Files.notExists(checkPointDir)) { Files.createDirectories(checkPointDir); } checkPointFile = Paths.get(checkPointDir.toString(), "checkpoint.txt").toFile(); } @Override public void checkPoint(Date checkPoint) throws Exception { try (PrintWriter pw = new PrintWriter(checkPointFile)) { pw.println(VERSION); pw.println(String.valueOf(checkPoint.getTime())); } } @Override public Date lastCheckPoint() throws Exception { if (!checkPointFile.exists()) { return getDefaultCheckPoint(); } try (BufferedReader br = new BufferedReader(new FileReader(checkPointFile))) { br.readLine(); // version -- ignore for now.. String ts = br.readLine(); if (ts != null) { return new Date(Long.parseLong(ts)); } else { return getDefaultCheckPoint(); } } } private Date getDefaultCheckPoint() { Date checkPoint = new Date(System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(defaultOffsetMins)); log.warn("Check point not found! new checkpoint using default offset: " + checkPoint); return checkPoint; } }
UTF-8
Java
2,287
java
FileCheckPointMgr.java
Java
[]
null
[]
/** * Copyright (c) 2018, salesforce.com, inc. * All rights reserved. * SPDX-License-Identifier: BSD-3-Clause * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause */ package com.demandware.carbonj.service.engine; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.PrintWriter; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Date; import java.util.concurrent.TimeUnit; public class FileCheckPointMgr implements CheckPointMgr<Date> { private static final Logger log = LoggerFactory.getLogger(FileCheckPointMgr.class); private static final String VERSION = "1.0"; private final File checkPointFile; private final int defaultOffsetMins; public FileCheckPointMgr(Path checkPointDir, int defaultOffsetMins) throws Exception { this.defaultOffsetMins = defaultOffsetMins; if (Files.notExists(checkPointDir)) { Files.createDirectories(checkPointDir); } checkPointFile = Paths.get(checkPointDir.toString(), "checkpoint.txt").toFile(); } @Override public void checkPoint(Date checkPoint) throws Exception { try (PrintWriter pw = new PrintWriter(checkPointFile)) { pw.println(VERSION); pw.println(String.valueOf(checkPoint.getTime())); } } @Override public Date lastCheckPoint() throws Exception { if (!checkPointFile.exists()) { return getDefaultCheckPoint(); } try (BufferedReader br = new BufferedReader(new FileReader(checkPointFile))) { br.readLine(); // version -- ignore for now.. String ts = br.readLine(); if (ts != null) { return new Date(Long.parseLong(ts)); } else { return getDefaultCheckPoint(); } } } private Date getDefaultCheckPoint() { Date checkPoint = new Date(System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(defaultOffsetMins)); log.warn("Check point not found! new checkpoint using default offset: " + checkPoint); return checkPoint; } }
2,287
0.672059
0.667687
71
31.197184
28.769907
111
false
false
0
0
0
0
0
0
0.478873
false
false
4
9226747c211be76b1da4d8caf01f59fb4366634f
38,869,454,057,147
01daa27eb12a78b67b6b56666fe6ba0ded6ce141
/Yelp Stats Map_Spark/Map Reduce/yelpData/Q1_Top10_Review_And_Business/ReviewMapper.java
5d180479187e32be576e6e510b80dfa730586349
[]
no_license
RAVALI13/Big-Data
https://github.com/RAVALI13/Big-Data
a9b12b0ca5c27387514dba1a8315d46131323afc
f2aa58b76aa329973a3c3236af48d6f6a5b5302b
refs/heads/master
2021-01-18T20:37:49.607000
2016-10-19T05:09:15
2016-10-19T05:09:15
68,351,361
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package hadoop.algorithms.joins.yelpData.Q1_Top10_Review_And_Business; import java.io.IOException; import org.apache.commons.lang.StringUtils; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; public class ReviewMapper extends Mapper<LongWritable, Text, Text, Text>{ @Override public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String delims = "^"; String[] reviewData = StringUtils.split(value.toString(),delims); if (reviewData.length == 4) { //Write BUSINESS_ID and RATING context.write(new Text(reviewData[2]), new Text(reviewData[3]+"\t"+"Review_1") ); //Output will be of the form BUSINESSID, RATING } } }
UTF-8
Java
767
java
ReviewMapper.java
Java
[]
null
[]
package hadoop.algorithms.joins.yelpData.Q1_Top10_Review_And_Business; import java.io.IOException; import org.apache.commons.lang.StringUtils; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; public class ReviewMapper extends Mapper<LongWritable, Text, Text, Text>{ @Override public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String delims = "^"; String[] reviewData = StringUtils.split(value.toString(),delims); if (reviewData.length == 4) { //Write BUSINESS_ID and RATING context.write(new Text(reviewData[2]), new Text(reviewData[3]+"\t"+"Review_1") ); //Output will be of the form BUSINESSID, RATING } } }
767
0.747066
0.73794
22
33.909092
30.233799
106
false
false
0
0
0
0
0
0
2.090909
false
false
4
f5a904f214ee0a87756863a8b7b2130f6409ef99
9,526,237,506,968
f58e149cb592f9af22e2e7c90d5633e8708fc409
/src/controllers/ControllerPromocionesDescuentos.java
534b8042db56f92e5de6c75776ba8c3d83b39ac2
[]
no_license
RicardoAntonio24/Punto_Venta_FerreteriaACME_ERKASoftware
https://github.com/RicardoAntonio24/Punto_Venta_FerreteriaACME_ERKASoftware
2ccd05edb345a654f370195a637ed33047993755
2301ea63a76c1db7ee14bd5eea9dfa00dbf0bec7
refs/heads/master
2020-04-01T15:07:58.090000
2018-12-07T08:50:28
2018-12-07T08:50:28
153,322,664
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package controllers; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.Date; import java.sql.SQLException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import models.ModelPromocionesDescuentos; import views.ViewPromocionesDescuentos; /** * * @author ERKA Software */ public class ControllerPromocionesDescuentos { ModelPromocionesDescuentos modelPromocionesDescuentos; ViewPromocionesDescuentos viewPromocionesDescuentos; ActionListener actionListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == viewPromocionesDescuentos.jb_nuevo3) { jb_nuevo3_actionPerformed(); } else if (e.getSource() == viewPromocionesDescuentos.jb_insertar1) { try { jb_insertar1_actionPerformed(); } catch (SQLException ex) { Logger.getLogger(ControllerPromocionesDescuentos.class.getName()).log(Level.SEVERE, null, ex); } } else if (e.getSource() == viewPromocionesDescuentos.jb_modificar1) { try { jb_modificar1_actionPerformed(); } catch (SQLException ex) { Logger.getLogger(ControllerPromocionesDescuentos.class.getName()).log(Level.SEVERE, null, ex); } } else if (e.getSource() == viewPromocionesDescuentos.jb_nuevo2) { jb_nuevo2_actionPerformed(); } else if (e.getSource() == viewPromocionesDescuentos.jb_insertar){ try { jb_insertar_actionPerformed(); } catch (SQLException ex) { Logger.getLogger(ControllerPromocionesDescuentos.class.getName()).log(Level.SEVERE, null, ex); } } } }; /** * Constructor para unir los componentes del sistema (MVC). * @param modelPromocionesDescuentos * @param viewPromocionesDescuentos */ public ControllerPromocionesDescuentos(ModelPromocionesDescuentos modelPromocionesDescuentos, ViewPromocionesDescuentos viewPromocionesDescuentos) throws SQLException { this.modelPromocionesDescuentos = modelPromocionesDescuentos; this.viewPromocionesDescuentos = viewPromocionesDescuentos; setActionListener(); initDB(); modelPromocionesDescuentos.llenarComboBox(); initComponents(); for (int pr = 0; pr < modelPromocionesDescuentos.getProductos().size(); pr++) { viewPromocionesDescuentos.jcb_producto.addItem((String) modelPromocionesDescuentos.getProductos().get(pr)); } for (int s = 0; s < modelPromocionesDescuentos.getSucursales().size(); s++) { viewPromocionesDescuentos.jcb_sucursal.addItem((String) modelPromocionesDescuentos.getSucursales().get(s)); } modelPromocionesDescuentos.llenarTabla(); viewPromocionesDescuentos.table_promo.setModel(modelPromocionesDescuentos.getTable_promo()); //descuentos initDB2(); modelPromocionesDescuentos.mostrar2(); viewPromocionesDescuentos.table_descuento.setModel(modelPromocionesDescuentos.getTable_descuento()); } private void initDB() { modelPromocionesDescuentos.conectarDB(); String id_prom = Integer.toString(modelPromocionesDescuentos.getId_promocion()); viewPromocionesDescuentos.jtf_idpromocion.setText(id_prom); viewPromocionesDescuentos.jcb_producto.setSelectedItem(modelPromocionesDescuentos.getNom_producto()); viewPromocionesDescuentos.jcb_tipo.setSelectedItem(modelPromocionesDescuentos.getTipo_promocion()); String desc_promo = Integer.toString(modelPromocionesDescuentos.getDescuento_promocion()); viewPromocionesDescuentos.jtf_descuento.setText(desc_promo); viewPromocionesDescuentos.jcb_sucursal.setSelectedItem(modelPromocionesDescuentos.getId_sucursal()); //fecha inicio DateFormat fecha = new SimpleDateFormat("yyyy-MM-dd"); Date fecha_in = modelPromocionesDescuentos.getFecha_inicio_promo(); String fecha_inicio= fecha.format(fecha_in); String [] afecha1 = fecha_inicio.split("-"); String anio_ini = afecha1[0]; String mes_ini = afecha1[1]; String dia_ini = afecha1[2]; viewPromocionesDescuentos.jcb_dia3.setSelectedItem(dia_ini); viewPromocionesDescuentos.jcb_mes3.setSelectedItem(mes_ini); viewPromocionesDescuentos.jtf_anio1.setText(anio_ini); //fecha limite Date fecha_lim = modelPromocionesDescuentos.getFecha_limite_promo(); String fecha_limite = fecha.format(fecha_lim); String [] afecha2 = fecha_limite.split("-"); String anio_li = afecha2[0]; String mes_li = afecha2[1]; String dia_li = afecha2[2]; viewPromocionesDescuentos.jcb_dia4.setSelectedItem(dia_li); viewPromocionesDescuentos.jcb_mes2.setSelectedItem(mes_li); viewPromocionesDescuentos.jtf_anio2.setText(anio_li); } private void initDB2() { modelPromocionesDescuentos.conectarDB2(); DateFormat fecha = new SimpleDateFormat("yyyy-MM-dd"); String id_desc = Integer.toString(modelPromocionesDescuentos.getId_descuento()); viewPromocionesDescuentos.jtf_iddescuento.setText(id_desc); String monto_mini = Float.toString(modelPromocionesDescuentos.getMonto_minimo()); viewPromocionesDescuentos.jtf_montominimo.setText(monto_mini); String monto_limi = Float.toString(modelPromocionesDescuentos.getMonto_limite()); viewPromocionesDescuentos.jtf_montolimite.setText(monto_limi); String porcentaje_desc = Integer.toString(modelPromocionesDescuentos.getPorcentaje_descuento()); viewPromocionesDescuentos.jtf_des.setText(porcentaje_desc); //fecha inicio Date fecha_ini2 = modelPromocionesDescuentos.getFecha_inicio2(); String fecha_inicio2= fecha.format(fecha_ini2); String [] fechaa2 = fecha_inicio2.split("-"); String anio_ini2 = fechaa2[0]; String mes_ini2 = fechaa2[1]; String dia_ini2 = fechaa2[2]; viewPromocionesDescuentos.jcb_dia1.setSelectedItem(dia_ini2); viewPromocionesDescuentos.jcb_mes1.setSelectedItem(mes_ini2); viewPromocionesDescuentos.jtf_anio3.setText(anio_ini2); //fecha limite Date fecha_limí2 = modelPromocionesDescuentos.getFecha_limite2(); String fecha_limite2 = fecha.format(fecha_limí2); String [] fechaa3 = fecha_limite2.split("-"); String anio_li2 = fechaa3[0]; String mes_li2 = fechaa3[1]; String dia_li2 = fechaa3[2]; viewPromocionesDescuentos.jcb_dia2.setSelectedItem(dia_li2); viewPromocionesDescuentos.jcb_mes.setSelectedItem(mes_li2); viewPromocionesDescuentos.jtf_anio4.setText(anio_li2); } public void initComponents() { viewPromocionesDescuentos.setLocationRelativeTo(null); viewPromocionesDescuentos.setTitle("Descuentos y Promociones ACME"); viewPromocionesDescuentos.setVisible(true); } private void setActionListener() { viewPromocionesDescuentos.jb_nuevo3.addActionListener(actionListener); viewPromocionesDescuentos.jb_insertar1.addActionListener(actionListener); viewPromocionesDescuentos.jb_modificar1.addActionListener(actionListener); viewPromocionesDescuentos.jb_nuevo2.addActionListener(actionListener); viewPromocionesDescuentos.jb_insertar.addActionListener(actionListener); viewPromocionesDescuentos.jb_modificar.addActionListener(actionListener); } private void setValues() { modelPromocionesDescuentos.conectarDB(); String id_prom = Integer.toString(modelPromocionesDescuentos.getId_promocion()); viewPromocionesDescuentos.jtf_idpromocion.setText(id_prom); viewPromocionesDescuentos.jcb_producto.setSelectedItem(modelPromocionesDescuentos.getNom_producto()); viewPromocionesDescuentos.jcb_tipo.setSelectedItem(modelPromocionesDescuentos.getTipo_promocion()); String desc_promo = Integer.toString(modelPromocionesDescuentos.getDescuento_promocion()); viewPromocionesDescuentos.jtf_descuento.setText(desc_promo); viewPromocionesDescuentos.jcb_sucursal.setSelectedItem(modelPromocionesDescuentos.getId_sucursal()); DateFormat fecha = new SimpleDateFormat("yyyy-MM-dd"); Date fecha_in = modelPromocionesDescuentos.getFecha_inicio_promo(); String fecha_inicio= fecha.format(fecha_in); String [] afecha1 = fecha_inicio.split("-"); String anio_ini = afecha1[0]; String mes_ini = afecha1[1]; String dia_ini = afecha1[2]; viewPromocionesDescuentos.jcb_dia3.setSelectedItem(dia_ini); viewPromocionesDescuentos.jcb_mes3.setSelectedItem(mes_ini); viewPromocionesDescuentos.jtf_anio1.setText(anio_ini); Date fecha_lim = modelPromocionesDescuentos.getFecha_limite_promo(); String fecha_limite = fecha.format(fecha_lim); String [] afecha2 = fecha_limite.split("-"); String anio_li = afecha2[0]; String mes_li = afecha2[1]; String dia_li = afecha2[2]; viewPromocionesDescuentos.jcb_dia4.setSelectedItem(dia_li); viewPromocionesDescuentos.jcb_mes2.setSelectedItem(mes_li); viewPromocionesDescuentos.jtf_anio2.setText(anio_li); } private void setValues2(){ // descuentos modelPromocionesDescuentos.conectarDB2(); String id_desc = Integer.toString(modelPromocionesDescuentos.getId_descuento()); viewPromocionesDescuentos.jtf_iddescuento.setText(id_desc); String monto_mini = Float.toString(modelPromocionesDescuentos.getMonto_minimo()); viewPromocionesDescuentos.jtf_montominimo.setText(monto_mini); String monto_limi = Float.toString(modelPromocionesDescuentos.getMonto_limite()); viewPromocionesDescuentos.jtf_montolimite.setText(monto_limi); String porcentaje_desc = Integer.toString(modelPromocionesDescuentos.getPorcentaje_descuento()); viewPromocionesDescuentos.jtf_des.setText(porcentaje_desc); viewPromocionesDescuentos.jcb_sucursal.setSelectedItem(modelPromocionesDescuentos.getId_sucursal()); //fecha inicio DateFormat fecha = new SimpleDateFormat("yyyy-MM-dd"); Date fecha_ini2 = modelPromocionesDescuentos.getFecha_inicio2(); String fecha_inicio2= fecha.format(fecha_ini2); String [] fechaa2 = fecha_inicio2.split("-"); String anio_ini2 = fechaa2[0]; String mes_ini2 = fechaa2[1]; String dia_ini2 = fechaa2[2]; viewPromocionesDescuentos.jcb_dia1.setSelectedItem(dia_ini2); viewPromocionesDescuentos.jcb_mes1.setSelectedItem(mes_ini2); viewPromocionesDescuentos.jtf_anio3.setText(anio_ini2); //fecha limite Date fecha_limí2 = modelPromocionesDescuentos.getFecha_limite2(); String fecha_limite2 = fecha.format(fecha_limí2); String [] fechaa3 = fecha_limite2.split("-"); String anio_li2 = fechaa3[0]; String mes_li2 = fechaa3[1]; String dia_li2 = fechaa3[2]; viewPromocionesDescuentos.jcb_dia2.setSelectedItem(dia_li2); viewPromocionesDescuentos.jcb_mes.setSelectedItem(mes_li2); viewPromocionesDescuentos.jtf_anio4.setText(anio_li2); } private void setValuesPromocion(){ viewPromocionesDescuentos.table_promo.setModel(modelPromocionesDescuentos.getTable_promo()); } private void setValuesDescuento(){ viewPromocionesDescuentos.table_descuento.setModel(modelPromocionesDescuentos.getTable_descuento()); } private void jb_nuevo3_actionPerformed() { viewPromocionesDescuentos.jtf_idpromocion.setText("0"); viewPromocionesDescuentos.jcb_producto.setSelectedIndex(0); viewPromocionesDescuentos.jcb_tipo.setSelectedIndex(0); viewPromocionesDescuentos.jtf_descuento.setText(""); viewPromocionesDescuentos.jcb_dia3.setSelectedIndex(0); viewPromocionesDescuentos.jcb_mes3.setSelectedIndex(0); viewPromocionesDescuentos.jtf_anio1.setText(""); viewPromocionesDescuentos.jcb_dia4.setSelectedIndex(0); viewPromocionesDescuentos.jcb_mes2.setSelectedIndex(0); viewPromocionesDescuentos.jtf_anio2.setText(""); viewPromocionesDescuentos.jcb_sucursal.setSelectedIndex(0); viewPromocionesDescuentos.table_promo.setModel(modelPromocionesDescuentos.getTable_promo()); } private void jb_insertar1_actionPerformed() throws SQLException { modelPromocionesDescuentos.setTemp_idpromo(viewPromocionesDescuentos.jtf_idpromocion.getText()); modelPromocionesDescuentos.setTemp_nomproducto((String)viewPromocionesDescuentos.jcb_producto.getSelectedItem()); modelPromocionesDescuentos.setTemp_tipopromo((String)viewPromocionesDescuentos.jcb_tipo.getSelectedItem()); modelPromocionesDescuentos.setTemp_descpromo(viewPromocionesDescuentos.jtf_descuento.getText()); //fecha inicio modelPromocionesDescuentos.setDia((String)viewPromocionesDescuentos.jcb_dia3.getSelectedItem()); modelPromocionesDescuentos.setMes((String)viewPromocionesDescuentos.jcb_mes3.getSelectedItem()); modelPromocionesDescuentos.setAnio(viewPromocionesDescuentos.jtf_anio1.getText()); //y fecha limite modelPromocionesDescuentos.setDia2((String)viewPromocionesDescuentos.jcb_dia4.getSelectedItem()); modelPromocionesDescuentos.setMes2((String)viewPromocionesDescuentos.jcb_mes2.getSelectedItem()); modelPromocionesDescuentos.setAnio2(viewPromocionesDescuentos.jtf_anio2.getText()); modelPromocionesDescuentos.setTem_idsucursal((String)viewPromocionesDescuentos.jcb_sucursal.getSelectedItem()); modelPromocionesDescuentos.agregarPromocion(); viewPromocionesDescuentos.table_promo.setModel(modelPromocionesDescuentos.getTable_promo()); } private void jb_modificar1_actionPerformed() throws SQLException{ modelPromocionesDescuentos.setTemp_idpromo(viewPromocionesDescuentos.jtf_idpromocion.getText()); modelPromocionesDescuentos.setTemp_nomproducto((String)viewPromocionesDescuentos.jcb_producto.getSelectedItem()); modelPromocionesDescuentos.setTemp_tipopromo((String)viewPromocionesDescuentos.jcb_tipo.getSelectedItem()); modelPromocionesDescuentos.setTemp_descpromo(viewPromocionesDescuentos.jtf_descuento.getText()); //fecha inicio modelPromocionesDescuentos.setDia((String)viewPromocionesDescuentos.jcb_dia3.getSelectedItem()); modelPromocionesDescuentos.setMes((String)viewPromocionesDescuentos.jcb_mes3.getSelectedItem()); modelPromocionesDescuentos.setAnio(viewPromocionesDescuentos.jtf_anio1.getText()); //y fecha limite modelPromocionesDescuentos.setDia2((String)viewPromocionesDescuentos.jcb_dia4.getSelectedItem()); modelPromocionesDescuentos.setMes2((String)viewPromocionesDescuentos.jcb_mes2.getSelectedItem()); modelPromocionesDescuentos.setAnio2(viewPromocionesDescuentos.jtf_anio2.getText()); modelPromocionesDescuentos.setTem_idsucursal((String)viewPromocionesDescuentos.jcb_sucursal.getSelectedItem()); modelPromocionesDescuentos.modificarPromocion(); viewPromocionesDescuentos.table_promo.setModel(modelPromocionesDescuentos.getTable_promo()); for (int i =0; i < viewPromocionesDescuentos.table_promo.getRowCount(); i++) { modelPromocionesDescuentos.getTable_promo().removeRow(i); i -= 1; } } //descuentos private void jb_nuevo2_actionPerformed(){ viewPromocionesDescuentos.jtf_iddescuento.setText(""); viewPromocionesDescuentos.jtf_montominimo.setText(""); viewPromocionesDescuentos.jtf_montolimite.setText(""); viewPromocionesDescuentos.jtf_des.setText(""); viewPromocionesDescuentos.jcb_dia1.setSelectedIndex(0); viewPromocionesDescuentos.jcb_mes1.setSelectedIndex(0); viewPromocionesDescuentos.jtf_anio3.setText(""); viewPromocionesDescuentos.jcb_dia2.setSelectedIndex(0); viewPromocionesDescuentos.jcb_mes.setSelectedIndex(0); viewPromocionesDescuentos.jtf_anio4.setText(""); } private void jb_insertar_actionPerformed() throws SQLException { modelPromocionesDescuentos.setTemp_iddescuento(viewPromocionesDescuentos.jtf_iddescuento.getText()); modelPromocionesDescuentos.setTemp_montomini(viewPromocionesDescuentos.jtf_montominimo.getText()); modelPromocionesDescuentos.setTemp_montolimi(viewPromocionesDescuentos.jtf_montolimite.getText()); modelPromocionesDescuentos.setTemp_porcentaje(viewPromocionesDescuentos.jtf_des.getText()); //fecha inicio modelPromocionesDescuentos.setDiaDesc1((String)viewPromocionesDescuentos.jcb_dia1.getSelectedItem()); modelPromocionesDescuentos.setMesDesc1((String)viewPromocionesDescuentos.jcb_mes1.getSelectedItem()); modelPromocionesDescuentos.setAnioDesc1(viewPromocionesDescuentos.jtf_anio3.getText()); //y fecha limite modelPromocionesDescuentos.setDiaDesc2((String)viewPromocionesDescuentos.jcb_dia2.getSelectedItem()); modelPromocionesDescuentos.setMesDesc2((String)viewPromocionesDescuentos.jcb_mes.getSelectedItem()); modelPromocionesDescuentos.setAnioDesc2(viewPromocionesDescuentos.jtf_anio4.getText()); modelPromocionesDescuentos.agregarDescuento(); viewPromocionesDescuentos.table_descuento.setModel(modelPromocionesDescuentos.getTable_descuento()); } }
UTF-8
Java
19,135
java
ControllerPromocionesDescuentos.java
Java
[ { "context": "iews.ViewPromocionesDescuentos;\n\n/**\n *\n * @author ERKA Software\n */\npublic class ControllerPromocionesDescuentos ", "end": 423, "score": 0.9245429039001465, "start": 410, "tag": "USERNAME", "value": "ERKA Software" } ]
null
[]
package controllers; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.Date; import java.sql.SQLException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import models.ModelPromocionesDescuentos; import views.ViewPromocionesDescuentos; /** * * @author ERKA Software */ public class ControllerPromocionesDescuentos { ModelPromocionesDescuentos modelPromocionesDescuentos; ViewPromocionesDescuentos viewPromocionesDescuentos; ActionListener actionListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == viewPromocionesDescuentos.jb_nuevo3) { jb_nuevo3_actionPerformed(); } else if (e.getSource() == viewPromocionesDescuentos.jb_insertar1) { try { jb_insertar1_actionPerformed(); } catch (SQLException ex) { Logger.getLogger(ControllerPromocionesDescuentos.class.getName()).log(Level.SEVERE, null, ex); } } else if (e.getSource() == viewPromocionesDescuentos.jb_modificar1) { try { jb_modificar1_actionPerformed(); } catch (SQLException ex) { Logger.getLogger(ControllerPromocionesDescuentos.class.getName()).log(Level.SEVERE, null, ex); } } else if (e.getSource() == viewPromocionesDescuentos.jb_nuevo2) { jb_nuevo2_actionPerformed(); } else if (e.getSource() == viewPromocionesDescuentos.jb_insertar){ try { jb_insertar_actionPerformed(); } catch (SQLException ex) { Logger.getLogger(ControllerPromocionesDescuentos.class.getName()).log(Level.SEVERE, null, ex); } } } }; /** * Constructor para unir los componentes del sistema (MVC). * @param modelPromocionesDescuentos * @param viewPromocionesDescuentos */ public ControllerPromocionesDescuentos(ModelPromocionesDescuentos modelPromocionesDescuentos, ViewPromocionesDescuentos viewPromocionesDescuentos) throws SQLException { this.modelPromocionesDescuentos = modelPromocionesDescuentos; this.viewPromocionesDescuentos = viewPromocionesDescuentos; setActionListener(); initDB(); modelPromocionesDescuentos.llenarComboBox(); initComponents(); for (int pr = 0; pr < modelPromocionesDescuentos.getProductos().size(); pr++) { viewPromocionesDescuentos.jcb_producto.addItem((String) modelPromocionesDescuentos.getProductos().get(pr)); } for (int s = 0; s < modelPromocionesDescuentos.getSucursales().size(); s++) { viewPromocionesDescuentos.jcb_sucursal.addItem((String) modelPromocionesDescuentos.getSucursales().get(s)); } modelPromocionesDescuentos.llenarTabla(); viewPromocionesDescuentos.table_promo.setModel(modelPromocionesDescuentos.getTable_promo()); //descuentos initDB2(); modelPromocionesDescuentos.mostrar2(); viewPromocionesDescuentos.table_descuento.setModel(modelPromocionesDescuentos.getTable_descuento()); } private void initDB() { modelPromocionesDescuentos.conectarDB(); String id_prom = Integer.toString(modelPromocionesDescuentos.getId_promocion()); viewPromocionesDescuentos.jtf_idpromocion.setText(id_prom); viewPromocionesDescuentos.jcb_producto.setSelectedItem(modelPromocionesDescuentos.getNom_producto()); viewPromocionesDescuentos.jcb_tipo.setSelectedItem(modelPromocionesDescuentos.getTipo_promocion()); String desc_promo = Integer.toString(modelPromocionesDescuentos.getDescuento_promocion()); viewPromocionesDescuentos.jtf_descuento.setText(desc_promo); viewPromocionesDescuentos.jcb_sucursal.setSelectedItem(modelPromocionesDescuentos.getId_sucursal()); //fecha inicio DateFormat fecha = new SimpleDateFormat("yyyy-MM-dd"); Date fecha_in = modelPromocionesDescuentos.getFecha_inicio_promo(); String fecha_inicio= fecha.format(fecha_in); String [] afecha1 = fecha_inicio.split("-"); String anio_ini = afecha1[0]; String mes_ini = afecha1[1]; String dia_ini = afecha1[2]; viewPromocionesDescuentos.jcb_dia3.setSelectedItem(dia_ini); viewPromocionesDescuentos.jcb_mes3.setSelectedItem(mes_ini); viewPromocionesDescuentos.jtf_anio1.setText(anio_ini); //fecha limite Date fecha_lim = modelPromocionesDescuentos.getFecha_limite_promo(); String fecha_limite = fecha.format(fecha_lim); String [] afecha2 = fecha_limite.split("-"); String anio_li = afecha2[0]; String mes_li = afecha2[1]; String dia_li = afecha2[2]; viewPromocionesDescuentos.jcb_dia4.setSelectedItem(dia_li); viewPromocionesDescuentos.jcb_mes2.setSelectedItem(mes_li); viewPromocionesDescuentos.jtf_anio2.setText(anio_li); } private void initDB2() { modelPromocionesDescuentos.conectarDB2(); DateFormat fecha = new SimpleDateFormat("yyyy-MM-dd"); String id_desc = Integer.toString(modelPromocionesDescuentos.getId_descuento()); viewPromocionesDescuentos.jtf_iddescuento.setText(id_desc); String monto_mini = Float.toString(modelPromocionesDescuentos.getMonto_minimo()); viewPromocionesDescuentos.jtf_montominimo.setText(monto_mini); String monto_limi = Float.toString(modelPromocionesDescuentos.getMonto_limite()); viewPromocionesDescuentos.jtf_montolimite.setText(monto_limi); String porcentaje_desc = Integer.toString(modelPromocionesDescuentos.getPorcentaje_descuento()); viewPromocionesDescuentos.jtf_des.setText(porcentaje_desc); //fecha inicio Date fecha_ini2 = modelPromocionesDescuentos.getFecha_inicio2(); String fecha_inicio2= fecha.format(fecha_ini2); String [] fechaa2 = fecha_inicio2.split("-"); String anio_ini2 = fechaa2[0]; String mes_ini2 = fechaa2[1]; String dia_ini2 = fechaa2[2]; viewPromocionesDescuentos.jcb_dia1.setSelectedItem(dia_ini2); viewPromocionesDescuentos.jcb_mes1.setSelectedItem(mes_ini2); viewPromocionesDescuentos.jtf_anio3.setText(anio_ini2); //fecha limite Date fecha_limí2 = modelPromocionesDescuentos.getFecha_limite2(); String fecha_limite2 = fecha.format(fecha_limí2); String [] fechaa3 = fecha_limite2.split("-"); String anio_li2 = fechaa3[0]; String mes_li2 = fechaa3[1]; String dia_li2 = fechaa3[2]; viewPromocionesDescuentos.jcb_dia2.setSelectedItem(dia_li2); viewPromocionesDescuentos.jcb_mes.setSelectedItem(mes_li2); viewPromocionesDescuentos.jtf_anio4.setText(anio_li2); } public void initComponents() { viewPromocionesDescuentos.setLocationRelativeTo(null); viewPromocionesDescuentos.setTitle("Descuentos y Promociones ACME"); viewPromocionesDescuentos.setVisible(true); } private void setActionListener() { viewPromocionesDescuentos.jb_nuevo3.addActionListener(actionListener); viewPromocionesDescuentos.jb_insertar1.addActionListener(actionListener); viewPromocionesDescuentos.jb_modificar1.addActionListener(actionListener); viewPromocionesDescuentos.jb_nuevo2.addActionListener(actionListener); viewPromocionesDescuentos.jb_insertar.addActionListener(actionListener); viewPromocionesDescuentos.jb_modificar.addActionListener(actionListener); } private void setValues() { modelPromocionesDescuentos.conectarDB(); String id_prom = Integer.toString(modelPromocionesDescuentos.getId_promocion()); viewPromocionesDescuentos.jtf_idpromocion.setText(id_prom); viewPromocionesDescuentos.jcb_producto.setSelectedItem(modelPromocionesDescuentos.getNom_producto()); viewPromocionesDescuentos.jcb_tipo.setSelectedItem(modelPromocionesDescuentos.getTipo_promocion()); String desc_promo = Integer.toString(modelPromocionesDescuentos.getDescuento_promocion()); viewPromocionesDescuentos.jtf_descuento.setText(desc_promo); viewPromocionesDescuentos.jcb_sucursal.setSelectedItem(modelPromocionesDescuentos.getId_sucursal()); DateFormat fecha = new SimpleDateFormat("yyyy-MM-dd"); Date fecha_in = modelPromocionesDescuentos.getFecha_inicio_promo(); String fecha_inicio= fecha.format(fecha_in); String [] afecha1 = fecha_inicio.split("-"); String anio_ini = afecha1[0]; String mes_ini = afecha1[1]; String dia_ini = afecha1[2]; viewPromocionesDescuentos.jcb_dia3.setSelectedItem(dia_ini); viewPromocionesDescuentos.jcb_mes3.setSelectedItem(mes_ini); viewPromocionesDescuentos.jtf_anio1.setText(anio_ini); Date fecha_lim = modelPromocionesDescuentos.getFecha_limite_promo(); String fecha_limite = fecha.format(fecha_lim); String [] afecha2 = fecha_limite.split("-"); String anio_li = afecha2[0]; String mes_li = afecha2[1]; String dia_li = afecha2[2]; viewPromocionesDescuentos.jcb_dia4.setSelectedItem(dia_li); viewPromocionesDescuentos.jcb_mes2.setSelectedItem(mes_li); viewPromocionesDescuentos.jtf_anio2.setText(anio_li); } private void setValues2(){ // descuentos modelPromocionesDescuentos.conectarDB2(); String id_desc = Integer.toString(modelPromocionesDescuentos.getId_descuento()); viewPromocionesDescuentos.jtf_iddescuento.setText(id_desc); String monto_mini = Float.toString(modelPromocionesDescuentos.getMonto_minimo()); viewPromocionesDescuentos.jtf_montominimo.setText(monto_mini); String monto_limi = Float.toString(modelPromocionesDescuentos.getMonto_limite()); viewPromocionesDescuentos.jtf_montolimite.setText(monto_limi); String porcentaje_desc = Integer.toString(modelPromocionesDescuentos.getPorcentaje_descuento()); viewPromocionesDescuentos.jtf_des.setText(porcentaje_desc); viewPromocionesDescuentos.jcb_sucursal.setSelectedItem(modelPromocionesDescuentos.getId_sucursal()); //fecha inicio DateFormat fecha = new SimpleDateFormat("yyyy-MM-dd"); Date fecha_ini2 = modelPromocionesDescuentos.getFecha_inicio2(); String fecha_inicio2= fecha.format(fecha_ini2); String [] fechaa2 = fecha_inicio2.split("-"); String anio_ini2 = fechaa2[0]; String mes_ini2 = fechaa2[1]; String dia_ini2 = fechaa2[2]; viewPromocionesDescuentos.jcb_dia1.setSelectedItem(dia_ini2); viewPromocionesDescuentos.jcb_mes1.setSelectedItem(mes_ini2); viewPromocionesDescuentos.jtf_anio3.setText(anio_ini2); //fecha limite Date fecha_limí2 = modelPromocionesDescuentos.getFecha_limite2(); String fecha_limite2 = fecha.format(fecha_limí2); String [] fechaa3 = fecha_limite2.split("-"); String anio_li2 = fechaa3[0]; String mes_li2 = fechaa3[1]; String dia_li2 = fechaa3[2]; viewPromocionesDescuentos.jcb_dia2.setSelectedItem(dia_li2); viewPromocionesDescuentos.jcb_mes.setSelectedItem(mes_li2); viewPromocionesDescuentos.jtf_anio4.setText(anio_li2); } private void setValuesPromocion(){ viewPromocionesDescuentos.table_promo.setModel(modelPromocionesDescuentos.getTable_promo()); } private void setValuesDescuento(){ viewPromocionesDescuentos.table_descuento.setModel(modelPromocionesDescuentos.getTable_descuento()); } private void jb_nuevo3_actionPerformed() { viewPromocionesDescuentos.jtf_idpromocion.setText("0"); viewPromocionesDescuentos.jcb_producto.setSelectedIndex(0); viewPromocionesDescuentos.jcb_tipo.setSelectedIndex(0); viewPromocionesDescuentos.jtf_descuento.setText(""); viewPromocionesDescuentos.jcb_dia3.setSelectedIndex(0); viewPromocionesDescuentos.jcb_mes3.setSelectedIndex(0); viewPromocionesDescuentos.jtf_anio1.setText(""); viewPromocionesDescuentos.jcb_dia4.setSelectedIndex(0); viewPromocionesDescuentos.jcb_mes2.setSelectedIndex(0); viewPromocionesDescuentos.jtf_anio2.setText(""); viewPromocionesDescuentos.jcb_sucursal.setSelectedIndex(0); viewPromocionesDescuentos.table_promo.setModel(modelPromocionesDescuentos.getTable_promo()); } private void jb_insertar1_actionPerformed() throws SQLException { modelPromocionesDescuentos.setTemp_idpromo(viewPromocionesDescuentos.jtf_idpromocion.getText()); modelPromocionesDescuentos.setTemp_nomproducto((String)viewPromocionesDescuentos.jcb_producto.getSelectedItem()); modelPromocionesDescuentos.setTemp_tipopromo((String)viewPromocionesDescuentos.jcb_tipo.getSelectedItem()); modelPromocionesDescuentos.setTemp_descpromo(viewPromocionesDescuentos.jtf_descuento.getText()); //fecha inicio modelPromocionesDescuentos.setDia((String)viewPromocionesDescuentos.jcb_dia3.getSelectedItem()); modelPromocionesDescuentos.setMes((String)viewPromocionesDescuentos.jcb_mes3.getSelectedItem()); modelPromocionesDescuentos.setAnio(viewPromocionesDescuentos.jtf_anio1.getText()); //y fecha limite modelPromocionesDescuentos.setDia2((String)viewPromocionesDescuentos.jcb_dia4.getSelectedItem()); modelPromocionesDescuentos.setMes2((String)viewPromocionesDescuentos.jcb_mes2.getSelectedItem()); modelPromocionesDescuentos.setAnio2(viewPromocionesDescuentos.jtf_anio2.getText()); modelPromocionesDescuentos.setTem_idsucursal((String)viewPromocionesDescuentos.jcb_sucursal.getSelectedItem()); modelPromocionesDescuentos.agregarPromocion(); viewPromocionesDescuentos.table_promo.setModel(modelPromocionesDescuentos.getTable_promo()); } private void jb_modificar1_actionPerformed() throws SQLException{ modelPromocionesDescuentos.setTemp_idpromo(viewPromocionesDescuentos.jtf_idpromocion.getText()); modelPromocionesDescuentos.setTemp_nomproducto((String)viewPromocionesDescuentos.jcb_producto.getSelectedItem()); modelPromocionesDescuentos.setTemp_tipopromo((String)viewPromocionesDescuentos.jcb_tipo.getSelectedItem()); modelPromocionesDescuentos.setTemp_descpromo(viewPromocionesDescuentos.jtf_descuento.getText()); //fecha inicio modelPromocionesDescuentos.setDia((String)viewPromocionesDescuentos.jcb_dia3.getSelectedItem()); modelPromocionesDescuentos.setMes((String)viewPromocionesDescuentos.jcb_mes3.getSelectedItem()); modelPromocionesDescuentos.setAnio(viewPromocionesDescuentos.jtf_anio1.getText()); //y fecha limite modelPromocionesDescuentos.setDia2((String)viewPromocionesDescuentos.jcb_dia4.getSelectedItem()); modelPromocionesDescuentos.setMes2((String)viewPromocionesDescuentos.jcb_mes2.getSelectedItem()); modelPromocionesDescuentos.setAnio2(viewPromocionesDescuentos.jtf_anio2.getText()); modelPromocionesDescuentos.setTem_idsucursal((String)viewPromocionesDescuentos.jcb_sucursal.getSelectedItem()); modelPromocionesDescuentos.modificarPromocion(); viewPromocionesDescuentos.table_promo.setModel(modelPromocionesDescuentos.getTable_promo()); for (int i =0; i < viewPromocionesDescuentos.table_promo.getRowCount(); i++) { modelPromocionesDescuentos.getTable_promo().removeRow(i); i -= 1; } } //descuentos private void jb_nuevo2_actionPerformed(){ viewPromocionesDescuentos.jtf_iddescuento.setText(""); viewPromocionesDescuentos.jtf_montominimo.setText(""); viewPromocionesDescuentos.jtf_montolimite.setText(""); viewPromocionesDescuentos.jtf_des.setText(""); viewPromocionesDescuentos.jcb_dia1.setSelectedIndex(0); viewPromocionesDescuentos.jcb_mes1.setSelectedIndex(0); viewPromocionesDescuentos.jtf_anio3.setText(""); viewPromocionesDescuentos.jcb_dia2.setSelectedIndex(0); viewPromocionesDescuentos.jcb_mes.setSelectedIndex(0); viewPromocionesDescuentos.jtf_anio4.setText(""); } private void jb_insertar_actionPerformed() throws SQLException { modelPromocionesDescuentos.setTemp_iddescuento(viewPromocionesDescuentos.jtf_iddescuento.getText()); modelPromocionesDescuentos.setTemp_montomini(viewPromocionesDescuentos.jtf_montominimo.getText()); modelPromocionesDescuentos.setTemp_montolimi(viewPromocionesDescuentos.jtf_montolimite.getText()); modelPromocionesDescuentos.setTemp_porcentaje(viewPromocionesDescuentos.jtf_des.getText()); //fecha inicio modelPromocionesDescuentos.setDiaDesc1((String)viewPromocionesDescuentos.jcb_dia1.getSelectedItem()); modelPromocionesDescuentos.setMesDesc1((String)viewPromocionesDescuentos.jcb_mes1.getSelectedItem()); modelPromocionesDescuentos.setAnioDesc1(viewPromocionesDescuentos.jtf_anio3.getText()); //y fecha limite modelPromocionesDescuentos.setDiaDesc2((String)viewPromocionesDescuentos.jcb_dia2.getSelectedItem()); modelPromocionesDescuentos.setMesDesc2((String)viewPromocionesDescuentos.jcb_mes.getSelectedItem()); modelPromocionesDescuentos.setAnioDesc2(viewPromocionesDescuentos.jtf_anio4.getText()); modelPromocionesDescuentos.agregarDescuento(); viewPromocionesDescuentos.table_descuento.setModel(modelPromocionesDescuentos.getTable_descuento()); } }
19,135
0.679212
0.668757
452
41.309734
35.983669
173
false
false
0
0
0
0
0
0
0.515487
false
false
4
52bdc512d55ca470c7b94d77b8b7c9390b242f63
36,438,502,569,502
b3029609fc81a3b773a9420bc40cba2f7b1a2d26
/src/service/AtaReuniaoService.java
fbbbb5670c544c3fca0e94d3466c3b9ef25a32cb
[]
no_license
iffsistemas/ProjetoRevisaoFormal
https://github.com/iffsistemas/ProjetoRevisaoFormal
182a2637d35bfaf959ddfa3cdfa287ef5bab4717
e8befbce39f8044e3a53c673e9006d7fcba939e5
refs/heads/master
2020-03-22T08:10:46.937000
2019-09-14T21:14:01
2019-09-14T21:14:01
139,750,186
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package service; import java.util.List; import javax.ejb.Stateless; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import modelo.Artefato; import modelo.AtaReuniao; import modelo.ReuniaoParticipante; @Stateless public class AtaReuniaoService extends GenericService<AtaReuniao> { public AtaReuniaoService(){ super(AtaReuniao.class); } public void gravarAtaReuniaoComParticipantes(AtaReuniao ata) { for(ReuniaoParticipante part: ata.getReuniaoParticipantes()) { getEntityManager().persist(part); } merge(ata); } public List<AtaReuniao> listAtasComParticipantes(){ final CriteriaBuilder cb = getEntityManager().getCriteriaBuilder(); final CriteriaQuery<AtaReuniao> cQuery = cb.createQuery(AtaReuniao.class); cQuery.select(cQuery.from(AtaReuniao.class)); List<AtaReuniao> list = getEntityManager().createQuery(cQuery).getResultList(); for(AtaReuniao ata: list) { ata.getReuniaoParticipantes().size(); } return list; } public List<AtaReuniao> obtemAtaPorArtefato(Artefato artefato) { CriteriaBuilder cb = getEntityManager().getCriteriaBuilder(); CriteriaQuery<AtaReuniao> cquery = cb.createQuery(AtaReuniao.class); Root<AtaReuniao> root = cquery.from(AtaReuniao.class); cquery.select(root).where(cb.equal(root.get("artefato"), artefato)); //cquery.orderBy(cb.desc(Artefato.<Long>get("id"))); //cquery.orderBy(cb.desc(cquery.get("id"))); List<AtaReuniao> atas = getEntityManager().createQuery(cquery).getResultList(); return atas; } }
UTF-8
Java
1,731
java
AtaReuniaoService.java
Java
[]
null
[]
package service; import java.util.List; import javax.ejb.Stateless; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import modelo.Artefato; import modelo.AtaReuniao; import modelo.ReuniaoParticipante; @Stateless public class AtaReuniaoService extends GenericService<AtaReuniao> { public AtaReuniaoService(){ super(AtaReuniao.class); } public void gravarAtaReuniaoComParticipantes(AtaReuniao ata) { for(ReuniaoParticipante part: ata.getReuniaoParticipantes()) { getEntityManager().persist(part); } merge(ata); } public List<AtaReuniao> listAtasComParticipantes(){ final CriteriaBuilder cb = getEntityManager().getCriteriaBuilder(); final CriteriaQuery<AtaReuniao> cQuery = cb.createQuery(AtaReuniao.class); cQuery.select(cQuery.from(AtaReuniao.class)); List<AtaReuniao> list = getEntityManager().createQuery(cQuery).getResultList(); for(AtaReuniao ata: list) { ata.getReuniaoParticipantes().size(); } return list; } public List<AtaReuniao> obtemAtaPorArtefato(Artefato artefato) { CriteriaBuilder cb = getEntityManager().getCriteriaBuilder(); CriteriaQuery<AtaReuniao> cquery = cb.createQuery(AtaReuniao.class); Root<AtaReuniao> root = cquery.from(AtaReuniao.class); cquery.select(root).where(cb.equal(root.get("artefato"), artefato)); //cquery.orderBy(cb.desc(Artefato.<Long>get("id"))); //cquery.orderBy(cb.desc(cquery.get("id"))); List<AtaReuniao> atas = getEntityManager().createQuery(cquery).getResultList(); return atas; } }
1,731
0.706528
0.706528
64
25.046875
26.719275
84
false
false
0
0
0
0
0
0
1.5625
false
false
4
a9b9eb71a909e56e7ff4118938dd031defe5d3a1
35,235,911,737,822
2e5ac8ea12db1f18babc30a59023f5acb3e7f9ad
/src/me/capit/mechanization/parser/FactoryRecipeParser.java
a86aad7075248c1a50311b45b0ab9f42825ea981
[ "MIT" ]
permissive
Wehttam664/Mechanization-old
https://github.com/Wehttam664/Mechanization-old
8c72c63961a28c85a480c75f62d75aa112e96c48
61395331b2f73db1a199153f816a4eee83dc2632
refs/heads/master
2016-09-10T00:22:00.448000
2015-01-19T19:41:48
2015-01-19T19:41:48
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package me.capit.mechanization.parser; import me.capit.eapi.data.Child; import me.capit.eapi.data.DataModel; import me.capit.mechanization.Mechanization; import me.capit.mechanization.exception.MechaException; import me.capit.mechanization.recipe.MechaFactoryRecipe; import me.capit.mechanization.recipe.RecipeMatrixKey; import me.capit.mechanization.recipe.RecipeMatrix; public class FactoryRecipeParser { private RecipeMatrixKey[] keys; private RecipeMatrix input, output; private int fuel_cost; public FactoryRecipeParser(MechaFactoryRecipe recipe) throws MechaException { Child shapechild = recipe.getModel().findFirstChild("shape"); if (shapechild==null || !(shapechild instanceof DataModel)) throw new MechaException(recipe, "Shape data missing or invalid."); DataModel matrixmodel = (DataModel) shapechild; try { fuel_cost = Integer.parseInt(matrixmodel.getAttribute("fuel_cost").getValueString()); } catch (IllegalArgumentException | NullPointerException e){ fuel_cost = 1; } try { input = new RecipeMatrix(matrixmodel.hasAttribute("input") ? matrixmodel.getAttribute("input").getValueString() : null); output = new RecipeMatrix(matrixmodel.hasAttribute("output") ? matrixmodel.getAttribute("output").getValueString() : null); } catch (IllegalArgumentException e){ throw new MechaException(recipe,e.getMessage()); } Child keychild = recipe.getModel().findFirstChild("keys"); if (keychild==null || !(keychild instanceof DataModel)) throw new MechaException(recipe, "Key data missing or invalid."); DataModel keymodel = (DataModel) keychild; keys = new RecipeMatrixKey[keymodel.getChildren().size()]; for (int i=0; i<keys.length; i++){ try { keys[i] = new RecipeMatrixKey(keymodel.getChildren().get(i)); } catch (IllegalArgumentException e){ Mechanization.warn(recipe.getName()+": "+e.getMessage()); } } } public RecipeMatrixKey[] getKeys(){ return keys; } public RecipeMatrixKey getKey(char keyChar){ for (RecipeMatrixKey key : getKeys()) if (key.getKeyChar()==keyChar) return key; return new RecipeMatrixKey(); } public RecipeMatrix getInput(){ return input; } public RecipeMatrix getOutput(){ return output; } public int getFuelCost(){ return fuel_cost; } }
UTF-8
Java
2,286
java
FactoryRecipeParser.java
Java
[]
null
[]
package me.capit.mechanization.parser; import me.capit.eapi.data.Child; import me.capit.eapi.data.DataModel; import me.capit.mechanization.Mechanization; import me.capit.mechanization.exception.MechaException; import me.capit.mechanization.recipe.MechaFactoryRecipe; import me.capit.mechanization.recipe.RecipeMatrixKey; import me.capit.mechanization.recipe.RecipeMatrix; public class FactoryRecipeParser { private RecipeMatrixKey[] keys; private RecipeMatrix input, output; private int fuel_cost; public FactoryRecipeParser(MechaFactoryRecipe recipe) throws MechaException { Child shapechild = recipe.getModel().findFirstChild("shape"); if (shapechild==null || !(shapechild instanceof DataModel)) throw new MechaException(recipe, "Shape data missing or invalid."); DataModel matrixmodel = (DataModel) shapechild; try { fuel_cost = Integer.parseInt(matrixmodel.getAttribute("fuel_cost").getValueString()); } catch (IllegalArgumentException | NullPointerException e){ fuel_cost = 1; } try { input = new RecipeMatrix(matrixmodel.hasAttribute("input") ? matrixmodel.getAttribute("input").getValueString() : null); output = new RecipeMatrix(matrixmodel.hasAttribute("output") ? matrixmodel.getAttribute("output").getValueString() : null); } catch (IllegalArgumentException e){ throw new MechaException(recipe,e.getMessage()); } Child keychild = recipe.getModel().findFirstChild("keys"); if (keychild==null || !(keychild instanceof DataModel)) throw new MechaException(recipe, "Key data missing or invalid."); DataModel keymodel = (DataModel) keychild; keys = new RecipeMatrixKey[keymodel.getChildren().size()]; for (int i=0; i<keys.length; i++){ try { keys[i] = new RecipeMatrixKey(keymodel.getChildren().get(i)); } catch (IllegalArgumentException e){ Mechanization.warn(recipe.getName()+": "+e.getMessage()); } } } public RecipeMatrixKey[] getKeys(){ return keys; } public RecipeMatrixKey getKey(char keyChar){ for (RecipeMatrixKey key : getKeys()) if (key.getKeyChar()==keyChar) return key; return new RecipeMatrixKey(); } public RecipeMatrix getInput(){ return input; } public RecipeMatrix getOutput(){ return output; } public int getFuelCost(){ return fuel_cost; } }
2,286
0.741032
0.740157
70
31.657143
33.234615
129
false
false
0
0
0
0
0
0
2.1
false
false
4
36a9c2c1f76fa2394cf6c2ea67ca02cdcc094378
33,775,622,865,104
dd31b3fe94c73fd26f89005061e5a05ed07766ec
/testwebapp/src/ru/deployka/testwebapp/TestWebController.java
5de3094cda05c5715d944fc53e35c36145262806
[ "MIT" ]
permissive
alexclear/de-ployka
https://github.com/alexclear/de-ployka
84d3c9ee4b032d05789180a1f210c43a0bf37235
8519736d18f170909351190544e17f96ff062552
refs/heads/master
2021-01-20T03:29:14.709000
2017-04-28T07:59:48
2017-04-28T07:59:48
89,544,311
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.deployka.testwebapp; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RequestMapping; @RestController public class TestWebController { @RequestMapping("/") public String index() { return "Nothing to see here, move along!"; } }
UTF-8
Java
323
java
TestWebController.java
Java
[]
null
[]
package ru.deployka.testwebapp; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RequestMapping; @RestController public class TestWebController { @RequestMapping("/") public String index() { return "Nothing to see here, move along!"; } }
323
0.74613
0.74613
14
22.071428
22.214745
62
false
false
0
0
0
0
0
0
0.357143
false
false
4
0b22269c4bba729d76eb9912c190ed3ed984bf73
35,570,919,177,018
c91d5d473ae126daf05dcc03153bf8bd2911e6ba
/src/main/java/pvapersonal/ru/other/AccessKeyStore.java
e07594ced48402845a8309c9852704921d07c577
[]
no_license
IAmProgrammist/OrdersServer
https://github.com/IAmProgrammist/OrdersServer
858045aeb97930142964fcb10219688f1bd5eb23
8b80f313ee21a74eccaececb252f655db7200ffc
refs/heads/main
2023-06-17T12:39:39.722000
2021-07-13T16:34:41
2021-07-13T16:34:41
385,667,469
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pvapersonal.ru.other; import pvapersonal.ru.utils.Utils; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; public class AccessKeyStore { public static void init() throws SQLException, ClassNotFoundException { Long now = TimeManager.now(); Connection conn = MySQLConnector.getMySQLConnection(); String query = "SELECT * FROM accesskeys"; ResultSet resultSet = conn.createStatement().executeQuery(query); while (resultSet.next()) { Long date = resultSet.getLong("lastAction"); if (date + Utils.KEY_WORK_TIME < now) { query = String.format("DELETE FROM accesskeys WHERE id='%d';", resultSet.getInt("id")); conn.createStatement().execute(query); } } conn.close(); } public static boolean isKeyValid(String key) throws SQLException, ClassNotFoundException { Long now = TimeManager.now(); Connection conn = MySQLConnector.getMySQLConnection(); String query = String.format("SELECT * FROM accesskeys WHERE accessKey='%s'", key); ResultSet set = conn.createStatement().executeQuery(query); boolean found = false; while (set.next()) { found = true; Long db = set.getLong("lastAction"); if (db + Utils.KEY_WORK_TIME < now) { found = false; query = String.format("DELETE FROM accesskeys WHERE accessKey='%s';", set.getString("accessKey")); conn.createStatement().execute(query); break; } } conn.close(); return found; } public static void updateTimeForKey(String key) throws SQLException, ClassNotFoundException { Connection conn = MySQLConnector.getMySQLConnection(); Long now = TimeManager.now(); String query = String.format("UPDATE accesskeys SET lastAction='%d' WHERE accessKey='%s'", now, key); int affected = conn.createStatement().executeUpdate(query); if(affected == 0){ throw new SQLException(); } query = String.format("UPDATE users SET lastAction=%d WHERE id=%d;", now, getUserIdByKey(key)); conn.createStatement().executeUpdate(query); conn.close(); } public static String generateAccessKey(int userId) throws SQLException, ClassNotFoundException { Connection conn = MySQLConnector.getMySQLConnection(); String query = String.format("SELECT users.id, accesskeys.accessKey, accesskeys.lastAction, accesskeys.id" + " FROM users INNER JOIN accesskeys ON accesskeys.userId = users.id WHERE users.id='%d';", userId); ResultSet set = conn.createStatement().executeQuery(query); String minDateKey = null; Integer accessKeyId = null; long minDate = TimeManager.now(); while (set.next()){ if(set.getLong("lastAction") + Utils.KEY_WORK_TIME > minDate){ minDateKey = set.getString("accessKey"); minDate = set.getLong("lastAction"); accessKeyId = set.getInt(4); } } if(minDateKey == null){ while (true) { try { String key = Utils.generateRandomString(10); query = String.format("INSERT INTO accesskeys (accessKey, lastAction, userId) VALUES ('%s', '%d', '%d')", key, TimeManager.now(), userId); conn.createStatement().execute(query); minDateKey = key; }catch (SQLException e){ continue; } break; } }else{ query = String.format("UPDATE accesskeys SET lastAction='%d' WHERE id='%d';", TimeManager.now(), accessKeyId); conn.createStatement().executeUpdate(query); } conn.close(); return minDateKey; } public static int getUserIdByKey(String key) throws SQLException, ClassNotFoundException { String query = String.format("SELECT userId FROM accesskeys WHERE accessKey='%s' LIMIT 1;", key); Connection conn = MySQLConnector.getMySQLConnection(); ResultSet set = conn.createStatement().executeQuery(query); if(set.next()){ return set.getInt("userId"); }else{ throw new SQLException(); } } public static boolean isAdmin(int userId) throws SQLException, ClassNotFoundException { try(Connection conn = MySQLConnector.getMySQLConnection()){ String query = String.format("SELECT isAdmin FROM users WHERE id=%d LIMIT 1;", userId); ResultSet set = conn.createStatement().executeQuery(query); if(set.next()){ return set.getInt("isAdmin") == 1; }else{ throw new SQLException("Haven't found user with id " + userId); } } } }
UTF-8
Java
5,048
java
AccessKeyStore.java
Java
[]
null
[]
package pvapersonal.ru.other; import pvapersonal.ru.utils.Utils; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; public class AccessKeyStore { public static void init() throws SQLException, ClassNotFoundException { Long now = TimeManager.now(); Connection conn = MySQLConnector.getMySQLConnection(); String query = "SELECT * FROM accesskeys"; ResultSet resultSet = conn.createStatement().executeQuery(query); while (resultSet.next()) { Long date = resultSet.getLong("lastAction"); if (date + Utils.KEY_WORK_TIME < now) { query = String.format("DELETE FROM accesskeys WHERE id='%d';", resultSet.getInt("id")); conn.createStatement().execute(query); } } conn.close(); } public static boolean isKeyValid(String key) throws SQLException, ClassNotFoundException { Long now = TimeManager.now(); Connection conn = MySQLConnector.getMySQLConnection(); String query = String.format("SELECT * FROM accesskeys WHERE accessKey='%s'", key); ResultSet set = conn.createStatement().executeQuery(query); boolean found = false; while (set.next()) { found = true; Long db = set.getLong("lastAction"); if (db + Utils.KEY_WORK_TIME < now) { found = false; query = String.format("DELETE FROM accesskeys WHERE accessKey='%s';", set.getString("accessKey")); conn.createStatement().execute(query); break; } } conn.close(); return found; } public static void updateTimeForKey(String key) throws SQLException, ClassNotFoundException { Connection conn = MySQLConnector.getMySQLConnection(); Long now = TimeManager.now(); String query = String.format("UPDATE accesskeys SET lastAction='%d' WHERE accessKey='%s'", now, key); int affected = conn.createStatement().executeUpdate(query); if(affected == 0){ throw new SQLException(); } query = String.format("UPDATE users SET lastAction=%d WHERE id=%d;", now, getUserIdByKey(key)); conn.createStatement().executeUpdate(query); conn.close(); } public static String generateAccessKey(int userId) throws SQLException, ClassNotFoundException { Connection conn = MySQLConnector.getMySQLConnection(); String query = String.format("SELECT users.id, accesskeys.accessKey, accesskeys.lastAction, accesskeys.id" + " FROM users INNER JOIN accesskeys ON accesskeys.userId = users.id WHERE users.id='%d';", userId); ResultSet set = conn.createStatement().executeQuery(query); String minDateKey = null; Integer accessKeyId = null; long minDate = TimeManager.now(); while (set.next()){ if(set.getLong("lastAction") + Utils.KEY_WORK_TIME > minDate){ minDateKey = set.getString("accessKey"); minDate = set.getLong("lastAction"); accessKeyId = set.getInt(4); } } if(minDateKey == null){ while (true) { try { String key = Utils.generateRandomString(10); query = String.format("INSERT INTO accesskeys (accessKey, lastAction, userId) VALUES ('%s', '%d', '%d')", key, TimeManager.now(), userId); conn.createStatement().execute(query); minDateKey = key; }catch (SQLException e){ continue; } break; } }else{ query = String.format("UPDATE accesskeys SET lastAction='%d' WHERE id='%d';", TimeManager.now(), accessKeyId); conn.createStatement().executeUpdate(query); } conn.close(); return minDateKey; } public static int getUserIdByKey(String key) throws SQLException, ClassNotFoundException { String query = String.format("SELECT userId FROM accesskeys WHERE accessKey='%s' LIMIT 1;", key); Connection conn = MySQLConnector.getMySQLConnection(); ResultSet set = conn.createStatement().executeQuery(query); if(set.next()){ return set.getInt("userId"); }else{ throw new SQLException(); } } public static boolean isAdmin(int userId) throws SQLException, ClassNotFoundException { try(Connection conn = MySQLConnector.getMySQLConnection()){ String query = String.format("SELECT isAdmin FROM users WHERE id=%d LIMIT 1;", userId); ResultSet set = conn.createStatement().executeQuery(query); if(set.next()){ return set.getInt("isAdmin") == 1; }else{ throw new SQLException("Haven't found user with id " + userId); } } } }
5,048
0.589342
0.587956
119
41.42017
31.801775
125
false
false
0
0
0
0
0
0
0.815126
false
false
4
699b58f4fa62a783983bb062d23064a6f0117b80
36,163,624,668,106
c50cc810d301e4d70f46df1d48a61b90a6ef852a
/task1/src/test/java/by/radchuk/task1/reader/impl/CubeReaderTest.java
f02b49e15b5f46b53fbfd61d638c4f6c5e3d5c14
[]
no_license
denighte/epam-web-training
https://github.com/denighte/epam-web-training
c67093418e41311ccb4752f83b5e737a6dd9eabb
ebdb591ae460724e869ebcbf0fb15f24dbb0a86e
refs/heads/master
2020-04-22T06:04:03.744000
2019-05-26T21:51:54
2019-05-26T21:51:54
170,177,896
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package by.radchuk.task1.reader.impl; import by.radchuk.task1.entity.Cube; import by.radchuk.task1.exception.GeometryException; import by.radchuk.task1.factory.impl.CubeFactory; import by.radchuk.task1.reader.FigureReader; import by.radchuk.task1.util.TestComparator; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import java.io.IOException; import java.nio.file.Paths; import java.util.List; public class CubeReaderTest { FigureReader<Cube> reader; List<Cube> result; int testNumber; @BeforeClass void setUp() { reader = new CubeReader(new CubeFactory()); } @DataProvider Object[][] resultProvider() { return new Object[][]{ { "cube1", 1, 1, 1, 5 }, { "a", 3, -2, 1.1, 3.3 }, { "cube3", -1.5, -1.6, 1, 8.8 }, { "cube4", 0.5, -1.5, 1, 4 }, { "cube5", 0.8, 2, -10, 4.5 }, { "cube6", 1.4, 1, -1, 15.5 }, { "cube7", 3582.99, -2857, 1.111111111, 3.6 }, { "cube8", -1.55, -186, 10.11, 345 }, { "cube9", 0.85, 1555, -84.57, 71.1 }, }; } @Test @Parameters({"readerTestFile"}) void readTest(String path) throws IOException, GeometryException { result = reader.read(Paths.get(path)); } @Test(dataProvider = "resultProvider") void readTestCheck(String name, double x, double y, double z, double edgeLength) { Assert.assertTrue( TestComparator.compareCube(result.get(testNumber++), name, x, y, z, edgeLength)); } }
UTF-8
Java
2,084
java
CubeReaderTest.java
Java
[]
null
[]
package by.radchuk.task1.reader.impl; import by.radchuk.task1.entity.Cube; import by.radchuk.task1.exception.GeometryException; import by.radchuk.task1.factory.impl.CubeFactory; import by.radchuk.task1.reader.FigureReader; import by.radchuk.task1.util.TestComparator; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import java.io.IOException; import java.nio.file.Paths; import java.util.List; public class CubeReaderTest { FigureReader<Cube> reader; List<Cube> result; int testNumber; @BeforeClass void setUp() { reader = new CubeReader(new CubeFactory()); } @DataProvider Object[][] resultProvider() { return new Object[][]{ { "cube1", 1, 1, 1, 5 }, { "a", 3, -2, 1.1, 3.3 }, { "cube3", -1.5, -1.6, 1, 8.8 }, { "cube4", 0.5, -1.5, 1, 4 }, { "cube5", 0.8, 2, -10, 4.5 }, { "cube6", 1.4, 1, -1, 15.5 }, { "cube7", 3582.99, -2857, 1.111111111, 3.6 }, { "cube8", -1.55, -186, 10.11, 345 }, { "cube9", 0.85, 1555, -84.57, 71.1 }, }; } @Test @Parameters({"readerTestFile"}) void readTest(String path) throws IOException, GeometryException { result = reader.read(Paths.get(path)); } @Test(dataProvider = "resultProvider") void readTestCheck(String name, double x, double y, double z, double edgeLength) { Assert.assertTrue( TestComparator.compareCube(result.get(testNumber++), name, x, y, z, edgeLength)); } }
2,084
0.496161
0.448177
76
26.421053
20.871325
97
false
false
0
0
0
0
0
0
1
false
false
4
6831d96a3b2bbc5c51a03c528cb4b75d9aa384b7
36,825,049,627,657
607e3f5672ef4d6720aad551644d312e99158641
/biz-entity/src/main/java/cn/com/biz/travel/entity/SfaTravelApplyEntity.java
4b1e2f687b692fddf8081cc592ce4673dc1d0618
[]
no_license
xixi2018/dms
https://github.com/xixi2018/dms
0e759aeb6bb6dd2b4ede1f9914d0b3c71f6c9324
f1c0fa75e497c921d3c128b2e05114ca8f8160b1
refs/heads/master
2020-03-12T18:56:59.300000
2018-04-24T01:18:38
2018-04-24T01:18:38
130,773,708
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.com.biz.travel.entity; import org.eispframework.poi.excel.annotation.Excel; import org.hibernate.annotations.GenericGenerator; import javax.persistence.*; /** * @Title: Entity * @Description: 差旅报备 * @author Biz_Generator * @date 2015-08-27 13:26:25 * @version V1.0 * */ @Entity @Table(name = "SFA_TRAVEL_APPLY", schema = "") @SuppressWarnings("serial") public class SfaTravelApplyEntity extends BaseBean implements java.io.Serializable { /**主键*/ private String id; /**大区*/ @Excel(exportName="大区") private String region; /**营业所*/ @Excel(exportName="营业所") private String departName; /**出差人名称*/ @Excel(exportName="人员姓名") private String userName; /**创建日期*/ @Excel(exportName="报备日期") private String createDate; /**差旅起始日期*/ @Excel(exportName="出差开始日期") private String travelStartDate; /**差旅结束日期*/ @Excel(exportName="出差结束日期") private String travelEndDate; /**出差地址*/ @Excel(exportName="出差地址") private String travelAddress; /**出差原因*/ @Excel(exportName="出差原因") private String travelReason; /**考勤照片*/ // @Excel(exportName="考勤照片1" , exportType = 2) private String photoOne; /**考勤照片*/ // @Excel(exportName="考勤照片2" , exportType = 2) private String photoTwo; /**考勤照片*/ // @Excel(exportName="考勤照片3" , exportType = 2) private String photoThree; /**出差人编号*/ private String userId; /**状态009表示该出差还没执行,003表示已定位执行*/ private String status; /**审批状态001表示未审批 003表示审批未通过 009表示审批通过 **/ private String applyStatus; /** *方法: 取得java.lang.String *@return: java.lang.String 主键 */ @Id @GeneratedValue(generator = "paymentableGenerator") @GenericGenerator(name = "paymentableGenerator", strategy = "uuid") @Column(name ="ID",nullable=false,length=36) public String getId(){ return this.id; } /** *方法: 设置java.lang.String *描述: 属性set方法 *@param: java.lang.String 主键 */ public void setId(String id){ this.id = id; } /** *方法: 取得java.lang.String *@return: java.lang.String 创建日期 */ @Column(name ="CREATE_DATE",nullable=true,length=50) public String getCreateDate(){ return this.createDate; } /** *方法: 设置java.lang.String *描述: 属性set方法 *@param: java.lang.String 创建日期 */ public void setCreateDate(String createDate){ this.createDate = createDate; } /** *方法: 取得java.lang.String *@return: java.lang.String 差旅起始日期 */ @Column(name ="TRAVEL_START_DATE",nullable=true,length=50) public String getTravelStartDate(){ return this.travelStartDate; } /** *方法: 设置java.lang.String *描述: 属性set方法 *@param: java.lang.String 差旅起始日期 */ public void setTravelStartDate(String travelStartDate){ this.travelStartDate = travelStartDate; } /** *方法: 取得java.lang.String *@return: java.lang.String 差旅结束日期 */ @Column(name ="TRAVEL_END_DATE",nullable=true,length=50) public String getTravelEndDate(){ return this.travelEndDate; } /** *方法: 设置java.lang.String *描述: 属性set方法 *@param: java.lang.String 差旅结束日期 */ public void setTravelEndDate(String travelEndDate){ this.travelEndDate = travelEndDate; } /** *方法: 取得java.lang.String *@return: java.lang.String 出差原因 */ @Column(name ="TRAVEL_REASON",nullable=true,length=2000) public String getTravelReason(){ return this.travelReason; } /** *方法: 设置java.lang.String *描述: 属性set方法 *@param: java.lang.String 出差原因 */ public void setTravelReason(String travelReason){ this.travelReason = travelReason; } /** *方法: 取得java.lang.String *@return: java.lang.String 出差人名称 */ @Column(name ="USER_NAME",nullable=true,length=200) public String getUserName(){ return this.userName; } /** *方法: 设置java.lang.String *描述: 属性set方法 *@param: java.lang.String 出差人名称 */ public void setUserName(String userName){ this.userName = userName; } /** *方法: 取得java.lang.String *@return: java.lang.String 出差人编号 */ @Column(name ="USER_ID",nullable=true,length=50) public String getUserId(){ return this.userId; } /** *方法: 设置java.lang.String *描述: 属性set方法 *@param: java.lang.String 出差人编号 */ public void setUserId(String userId){ this.userId = userId; } @Column(name ="TRAVEL_ADDRESS",nullable=true,length=200) public String getTravelAddress() { return travelAddress; } public void setTravelAddress(String travelAddress) { this.travelAddress = travelAddress; } @Column(name ="STATUS",nullable=true,length=20) public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getApplyStatus() { return applyStatus; } @Column(name ="APPLYSTATUS",nullable=true,length=20) public void setApplyStatus(String applyStatus) { this.applyStatus = applyStatus; } @Transient public String getRegion() { return region; } public void setRegion(String region) { this.region = region; } @Transient public String getDepartName() { return departName; } public void setDepartName(String departName) { this.departName = departName; } @Transient public String getPhotoOne() { return photoOne; } public void setPhotoOne(String photoOne) { this.photoOne = photoOne; } @Transient public String getPhotoTwo() { return photoTwo; } public void setPhotoTwo(String photoTwo) { this.photoTwo = photoTwo; } @Transient public String getPhotoThree() { return photoThree; } public void setPhotoThree(String photoThree) { this.photoThree = photoThree; } }
UTF-8
Java
6,061
java
SfaTravelApplyEntity.java
Java
[ { "context": " * @Title: Entity\n * @Description: 差旅报备\n * @author Biz_Generator\n * @date 2015-08-27 13:26:25\n * @version V1.0 \n", "end": 240, "score": 0.9995127320289612, "start": 227, "tag": "USERNAME", "value": "Biz_Generator" } ]
null
[]
package cn.com.biz.travel.entity; import org.eispframework.poi.excel.annotation.Excel; import org.hibernate.annotations.GenericGenerator; import javax.persistence.*; /** * @Title: Entity * @Description: 差旅报备 * @author Biz_Generator * @date 2015-08-27 13:26:25 * @version V1.0 * */ @Entity @Table(name = "SFA_TRAVEL_APPLY", schema = "") @SuppressWarnings("serial") public class SfaTravelApplyEntity extends BaseBean implements java.io.Serializable { /**主键*/ private String id; /**大区*/ @Excel(exportName="大区") private String region; /**营业所*/ @Excel(exportName="营业所") private String departName; /**出差人名称*/ @Excel(exportName="人员姓名") private String userName; /**创建日期*/ @Excel(exportName="报备日期") private String createDate; /**差旅起始日期*/ @Excel(exportName="出差开始日期") private String travelStartDate; /**差旅结束日期*/ @Excel(exportName="出差结束日期") private String travelEndDate; /**出差地址*/ @Excel(exportName="出差地址") private String travelAddress; /**出差原因*/ @Excel(exportName="出差原因") private String travelReason; /**考勤照片*/ // @Excel(exportName="考勤照片1" , exportType = 2) private String photoOne; /**考勤照片*/ // @Excel(exportName="考勤照片2" , exportType = 2) private String photoTwo; /**考勤照片*/ // @Excel(exportName="考勤照片3" , exportType = 2) private String photoThree; /**出差人编号*/ private String userId; /**状态009表示该出差还没执行,003表示已定位执行*/ private String status; /**审批状态001表示未审批 003表示审批未通过 009表示审批通过 **/ private String applyStatus; /** *方法: 取得java.lang.String *@return: java.lang.String 主键 */ @Id @GeneratedValue(generator = "paymentableGenerator") @GenericGenerator(name = "paymentableGenerator", strategy = "uuid") @Column(name ="ID",nullable=false,length=36) public String getId(){ return this.id; } /** *方法: 设置java.lang.String *描述: 属性set方法 *@param: java.lang.String 主键 */ public void setId(String id){ this.id = id; } /** *方法: 取得java.lang.String *@return: java.lang.String 创建日期 */ @Column(name ="CREATE_DATE",nullable=true,length=50) public String getCreateDate(){ return this.createDate; } /** *方法: 设置java.lang.String *描述: 属性set方法 *@param: java.lang.String 创建日期 */ public void setCreateDate(String createDate){ this.createDate = createDate; } /** *方法: 取得java.lang.String *@return: java.lang.String 差旅起始日期 */ @Column(name ="TRAVEL_START_DATE",nullable=true,length=50) public String getTravelStartDate(){ return this.travelStartDate; } /** *方法: 设置java.lang.String *描述: 属性set方法 *@param: java.lang.String 差旅起始日期 */ public void setTravelStartDate(String travelStartDate){ this.travelStartDate = travelStartDate; } /** *方法: 取得java.lang.String *@return: java.lang.String 差旅结束日期 */ @Column(name ="TRAVEL_END_DATE",nullable=true,length=50) public String getTravelEndDate(){ return this.travelEndDate; } /** *方法: 设置java.lang.String *描述: 属性set方法 *@param: java.lang.String 差旅结束日期 */ public void setTravelEndDate(String travelEndDate){ this.travelEndDate = travelEndDate; } /** *方法: 取得java.lang.String *@return: java.lang.String 出差原因 */ @Column(name ="TRAVEL_REASON",nullable=true,length=2000) public String getTravelReason(){ return this.travelReason; } /** *方法: 设置java.lang.String *描述: 属性set方法 *@param: java.lang.String 出差原因 */ public void setTravelReason(String travelReason){ this.travelReason = travelReason; } /** *方法: 取得java.lang.String *@return: java.lang.String 出差人名称 */ @Column(name ="USER_NAME",nullable=true,length=200) public String getUserName(){ return this.userName; } /** *方法: 设置java.lang.String *描述: 属性set方法 *@param: java.lang.String 出差人名称 */ public void setUserName(String userName){ this.userName = userName; } /** *方法: 取得java.lang.String *@return: java.lang.String 出差人编号 */ @Column(name ="USER_ID",nullable=true,length=50) public String getUserId(){ return this.userId; } /** *方法: 设置java.lang.String *描述: 属性set方法 *@param: java.lang.String 出差人编号 */ public void setUserId(String userId){ this.userId = userId; } @Column(name ="TRAVEL_ADDRESS",nullable=true,length=200) public String getTravelAddress() { return travelAddress; } public void setTravelAddress(String travelAddress) { this.travelAddress = travelAddress; } @Column(name ="STATUS",nullable=true,length=20) public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getApplyStatus() { return applyStatus; } @Column(name ="APPLYSTATUS",nullable=true,length=20) public void setApplyStatus(String applyStatus) { this.applyStatus = applyStatus; } @Transient public String getRegion() { return region; } public void setRegion(String region) { this.region = region; } @Transient public String getDepartName() { return departName; } public void setDepartName(String departName) { this.departName = departName; } @Transient public String getPhotoOne() { return photoOne; } public void setPhotoOne(String photoOne) { this.photoOne = photoOne; } @Transient public String getPhotoTwo() { return photoTwo; } public void setPhotoTwo(String photoTwo) { this.photoTwo = photoTwo; } @Transient public String getPhotoThree() { return photoThree; } public void setPhotoThree(String photoThree) { this.photoThree = photoThree; } }
6,061
0.686113
0.674922
253
20.545454
17.044086
84
false
false
0
0
0
0
0
0
1.118577
false
false
4
606865bc65c0dfc5bc3129b852324dd8d2831c2f
12,747,463,003,711
ab888362d96e98ce6ff7a3d7134fb7cfab0a4d8b
/src/kmeans/Classify.java
3857ebd62872d8e714b3fe37733774a02cca00f0
[]
no_license
wittfabian/kmeans-java
https://github.com/wittfabian/kmeans-java
bc499738aaccacbee100033495b334965703fda0
300f1ca8b01dc2389faea946b78e7faf4baded0c
refs/heads/master
2021-01-12T17:42:49.609000
2016-10-22T08:55:45
2016-10-22T08:55:45
71,627,653
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package kmeans; import mapping.Overlap; import java.util.ArrayList; import java.util.Iterator; /** * This class uses the training data to classify the test data with the Naive * Bayes classification. * @author Fabian Witt, Steven Brandt */ public class Classify { private final ArrayList<String[]> m_trainData; private final ArrayList<String[]> m_testData; private final ArrayList<String[]> m_result; private final int m_k; /** * Consturctor to get the data and automatically classify the test data. * @param trainData The training data. * @param testData The test data. * @param k The number of centers. */ public Classify(ArrayList<String[]> trainData, ArrayList<String[]> testData, int k) { this.m_trainData = trainData; this.m_testData = testData; this.m_k = k; this.m_result = makeClassification(); } /** * Getter, which returns the result of the classification. * @return Returns a list with the target and the classification values. */ public ArrayList<String[]> getResult() { return m_result; } /** * Method to classify the test data. * @return Returns a list of all target classes and the classifications. */ private ArrayList<String[]> makeClassification(){ ArrayList<String[]> result = new ArrayList<>(); int classpos = m_trainData.get(0).length-1; Overlap overlap = new Overlap(m_trainData,m_k); // iterate through testdata and classify each one Iterator iter_test = m_testData.iterator(); while(iter_test.hasNext()){ String[] tmp = (String[])iter_test.next(); String clclass = overlap.getClass(tmp); String[] resstring = new String[2]; resstring[0] = tmp[classpos]; resstring[1] = clclass; result.add(resstring); } return result; } }
UTF-8
Java
1,971
java
Classify.java
Java
[ { "context": "with the Naive\n * Bayes classification.\n * @author Fabian Witt, Steven Brandt\n */\npublic class Classify {\n \n ", "end": 226, "score": 0.9998468160629272, "start": 215, "tag": "NAME", "value": "Fabian Witt" }, { "context": "e\n * Bayes classification.\n * @author Fabian Witt, Steven Brandt\n */\npublic class Classify {\n \n private fina", "end": 241, "score": 0.999854326248169, "start": 228, "tag": "NAME", "value": "Steven Brandt" } ]
null
[]
package kmeans; import mapping.Overlap; import java.util.ArrayList; import java.util.Iterator; /** * This class uses the training data to classify the test data with the Naive * Bayes classification. * @author <NAME>, <NAME> */ public class Classify { private final ArrayList<String[]> m_trainData; private final ArrayList<String[]> m_testData; private final ArrayList<String[]> m_result; private final int m_k; /** * Consturctor to get the data and automatically classify the test data. * @param trainData The training data. * @param testData The test data. * @param k The number of centers. */ public Classify(ArrayList<String[]> trainData, ArrayList<String[]> testData, int k) { this.m_trainData = trainData; this.m_testData = testData; this.m_k = k; this.m_result = makeClassification(); } /** * Getter, which returns the result of the classification. * @return Returns a list with the target and the classification values. */ public ArrayList<String[]> getResult() { return m_result; } /** * Method to classify the test data. * @return Returns a list of all target classes and the classifications. */ private ArrayList<String[]> makeClassification(){ ArrayList<String[]> result = new ArrayList<>(); int classpos = m_trainData.get(0).length-1; Overlap overlap = new Overlap(m_trainData,m_k); // iterate through testdata and classify each one Iterator iter_test = m_testData.iterator(); while(iter_test.hasNext()){ String[] tmp = (String[])iter_test.next(); String clclass = overlap.getClass(tmp); String[] resstring = new String[2]; resstring[0] = tmp[classpos]; resstring[1] = clclass; result.add(resstring); } return result; } }
1,959
0.621005
0.618468
62
30.790323
23.397778
89
false
false
0
0
0
0
0
0
0.467742
false
false
4
b3b84c9c4b46be2a0ffb48afb703222cbd22a1a3
25,572,235,338,950
204dad31a76c313963ae88a955a5e0901ecc8154
/app/src/main/java/reclamation/dev/com/reclamation20/MyModels/Post.java
a886de74e501b82b5d1c8549f4ef9d69f0a0c1d4
[]
no_license
ahmedhamzaoui/Reclamation2.0
https://github.com/ahmedhamzaoui/Reclamation2.0
67be077842379502d02ba61937f08cbce84fd653
7ff2f674de39adb645976a36949194edcdb106ce
refs/heads/master
2020-04-17T01:02:24.673000
2019-01-18T05:40:58
2019-01-18T05:40:58
166,073,109
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package reclamation.dev.com.reclamation20.MyModels; import android.os.Parcel; import android.os.Parcelable; public class Post implements Parcelable { private int idpub; private int idphoto1; private int idphoto2; private int idphoto3; private int idphoto4; private String tag; private int userid; private double lat; private double lng; private String titre; private String description; private String created_at; public Post() { } public Post(int idphoto1, int idphoto2, int idphoto3, int idphoto4, String tag, int userid, double lat, double lng, String titre, String description) { this.idphoto1 = idphoto1; this.idphoto2 = idphoto2; this.idphoto3 = idphoto3; this.idphoto4 = idphoto4; this.tag = tag; this.userid = userid; this.lat = lat; this.lng = lng; this.titre = titre; this.description = description; } protected Post(Parcel in) { idpub = in.readInt(); idphoto1 = in.readInt(); idphoto2 = in.readInt(); idphoto3 = in.readInt(); idphoto4 = in.readInt(); tag = in.readString(); userid = in.readInt(); lat = in.readDouble(); lng = in.readDouble(); titre = in.readString(); description = in.readString(); } public static final Creator<Post> CREATOR = new Creator<Post>() { @Override public Post createFromParcel(Parcel in) { return new Post(in); } @Override public Post[] newArray(int size) { return new Post[size]; } }; public int getIdpub() { return idpub; } public void setIdpub(int idpub) { this.idpub = idpub; } public int getIdphoto1() { return idphoto1; } public void setIdphoto1(int idphoto1) { this.idphoto1 = idphoto1; } public int getIdphoto2() { return idphoto2; } public void setIdphoto2(int idphoto2) { this.idphoto2 = idphoto2; } public int getIdphoto3() { return idphoto3; } public void setIdphoto3(int idphoto3) { this.idphoto3 = idphoto3; } public int getIdphoto4() { return idphoto4; } public void setIdphoto4(int idphoto4) { this.idphoto4 = idphoto4; } public String getTag() { return tag; } public void setTag(String tag) { this.tag = tag; } public int getUserid() { return userid; } public void setUserid(int userid) { this.userid = userid; } public double getLat() { return lat; } public void setLat(double lat) { this.lat = lat; } public double getLng() { return lng; } public void setLng(double lng) { this.lng = lng; } public String getTitre() { return titre; } public void setTitre(String titre) { this.titre = titre; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getCreated_at() { return created_at; } public void setCreated_at(String created_at) { this.created_at = created_at; } @Override public String toString() { return "Post{" + "idpub=" + idpub + ", idphoto1=" + idphoto1 + ", idphoto2=" + idphoto2 + ", idphoto3=" + idphoto3 + ", idphoto4=" + idphoto4 + ", tag='" + tag + '\'' + ", userid=" + userid + ", lat=" + lat + ", lng=" + lng + ", titre='" + titre + '\'' + ", description='" + description + '\'' + '}'; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(idpub); dest.writeInt(idphoto1); dest.writeInt(idphoto2); dest.writeInt(idphoto3); dest.writeInt(idphoto4); dest.writeString(tag); dest.writeInt(userid); dest.writeDouble(lat); dest.writeDouble(lng); dest.writeString(titre); dest.writeString(description); } }
UTF-8
Java
4,427
java
Post.java
Java
[]
null
[]
package reclamation.dev.com.reclamation20.MyModels; import android.os.Parcel; import android.os.Parcelable; public class Post implements Parcelable { private int idpub; private int idphoto1; private int idphoto2; private int idphoto3; private int idphoto4; private String tag; private int userid; private double lat; private double lng; private String titre; private String description; private String created_at; public Post() { } public Post(int idphoto1, int idphoto2, int idphoto3, int idphoto4, String tag, int userid, double lat, double lng, String titre, String description) { this.idphoto1 = idphoto1; this.idphoto2 = idphoto2; this.idphoto3 = idphoto3; this.idphoto4 = idphoto4; this.tag = tag; this.userid = userid; this.lat = lat; this.lng = lng; this.titre = titre; this.description = description; } protected Post(Parcel in) { idpub = in.readInt(); idphoto1 = in.readInt(); idphoto2 = in.readInt(); idphoto3 = in.readInt(); idphoto4 = in.readInt(); tag = in.readString(); userid = in.readInt(); lat = in.readDouble(); lng = in.readDouble(); titre = in.readString(); description = in.readString(); } public static final Creator<Post> CREATOR = new Creator<Post>() { @Override public Post createFromParcel(Parcel in) { return new Post(in); } @Override public Post[] newArray(int size) { return new Post[size]; } }; public int getIdpub() { return idpub; } public void setIdpub(int idpub) { this.idpub = idpub; } public int getIdphoto1() { return idphoto1; } public void setIdphoto1(int idphoto1) { this.idphoto1 = idphoto1; } public int getIdphoto2() { return idphoto2; } public void setIdphoto2(int idphoto2) { this.idphoto2 = idphoto2; } public int getIdphoto3() { return idphoto3; } public void setIdphoto3(int idphoto3) { this.idphoto3 = idphoto3; } public int getIdphoto4() { return idphoto4; } public void setIdphoto4(int idphoto4) { this.idphoto4 = idphoto4; } public String getTag() { return tag; } public void setTag(String tag) { this.tag = tag; } public int getUserid() { return userid; } public void setUserid(int userid) { this.userid = userid; } public double getLat() { return lat; } public void setLat(double lat) { this.lat = lat; } public double getLng() { return lng; } public void setLng(double lng) { this.lng = lng; } public String getTitre() { return titre; } public void setTitre(String titre) { this.titre = titre; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getCreated_at() { return created_at; } public void setCreated_at(String created_at) { this.created_at = created_at; } @Override public String toString() { return "Post{" + "idpub=" + idpub + ", idphoto1=" + idphoto1 + ", idphoto2=" + idphoto2 + ", idphoto3=" + idphoto3 + ", idphoto4=" + idphoto4 + ", tag='" + tag + '\'' + ", userid=" + userid + ", lat=" + lat + ", lng=" + lng + ", titre='" + titre + '\'' + ", description='" + description + '\'' + '}'; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(idpub); dest.writeInt(idphoto1); dest.writeInt(idphoto2); dest.writeInt(idphoto3); dest.writeInt(idphoto4); dest.writeString(tag); dest.writeInt(userid); dest.writeDouble(lat); dest.writeDouble(lng); dest.writeString(titre); dest.writeString(description); } }
4,427
0.548001
0.534674
199
21.246231
18.346325
155
false
false
0
0
0
0
0
0
0.482412
false
false
4
9810a81c60c3faaa0dcaee8351127fccde4a715c
37,039,797,985,397
b036e0191b541f792d8a66cd3d2e7ed22063adaa
/native-build/project/java/com/game/plate/Level01AppState.java
9f0b9e409e21b816f5a073d445535cc92da1dd33
[]
no_license
thoced/Plateforme
https://github.com/thoced/Plateforme
b60756498a08dbc4823a5650aa4146095b1d166f
76acc4cb6db512055676dadd26b9386c2ea5f6a9
refs/heads/master
2021-04-30T03:44:22.455000
2018-02-15T20:45:59
2018-02-15T20:46:01
121,520,948
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.game.plate; import com.jme3.animation.AnimChannel; import com.jme3.animation.AnimControl; import com.jme3.app.Application; import com.jme3.app.SimpleApplication; import com.jme3.app.state.AbstractAppState; import com.jme3.app.state.AppStateManager; import com.jme3.bullet.control.CharacterControl; import com.jme3.math.Vector3f; import com.jme3.scene.SceneGraphVisitor; import com.jme3.scene.Spatial; import controlers.AvatarControl; public class Level01AppState extends AbstractAppState { private SimpleApplication simpleApplication; @Override public void initialize(AppStateManager stateManager, Application app) { super.initialize(stateManager, app); simpleApplication = (SimpleApplication) app; } @Override public void update(float tpf) { super.update(tpf); } }
UTF-8
Java
847
java
Level01AppState.java
Java
[]
null
[]
package com.game.plate; import com.jme3.animation.AnimChannel; import com.jme3.animation.AnimControl; import com.jme3.app.Application; import com.jme3.app.SimpleApplication; import com.jme3.app.state.AbstractAppState; import com.jme3.app.state.AppStateManager; import com.jme3.bullet.control.CharacterControl; import com.jme3.math.Vector3f; import com.jme3.scene.SceneGraphVisitor; import com.jme3.scene.Spatial; import controlers.AvatarControl; public class Level01AppState extends AbstractAppState { private SimpleApplication simpleApplication; @Override public void initialize(AppStateManager stateManager, Application app) { super.initialize(stateManager, app); simpleApplication = (SimpleApplication) app; } @Override public void update(float tpf) { super.update(tpf); } }
847
0.762692
0.747344
39
20.666666
21.154297
75
false
false
0
0
0
0
0
0
0.461538
false
false
4
dc2c6aa7a005ca696992380c736f2d76b14db39f
37,306,085,959,700
eb260c79cd81da809afc5eed0e830af7150e3719
/trunk/satellite-service/src/main/java/com/esunny/satellite/report/entity/.svn/text-base/ReportInfoPlus.java.svn-base
31b60064576f11360ddb1eea8f86142229d56ba3
[]
no_license
mengweidsg/java_trunk
https://github.com/mengweidsg/java_trunk
209336337d78e960256807f51a9612290b879f16
c700265b092279c0c469085356792669566e1228
refs/heads/master
2020-04-05T23:44:38.109000
2014-10-15T12:18:57
2014-10-15T12:18:57
25,253,143
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.esunny.satellite.report.entity; import java.io.Serializable; public class ReportInfoPlus implements Serializable { private static final long serialVersionUID = -5255557112649520440L; private Long id; private String tableName; private String needIndex; private String sortColumn; private String sortDeriction; private String sortColumnList; private String hideSort; private String selectSql; private Integer pageSize; /** * @return the id */ public Long getId() { return id; } /** * @param id the id to set */ public void setId(Long id) { this.id = id; } /** * @return the tableName */ public String getTableName() { return tableName; } /** * @param tableName the tableName to set */ public void setTableName(String tableName) { this.tableName = tableName; } /** * @return the needIndex */ public String getNeedIndex() { return needIndex; } /** * @param needIndex the needIndex to set */ public void setNeedIndex(String needIndex) { this.needIndex = needIndex; } /** * @return the sortColumn */ public String getSortColumn() { return sortColumn; } /** * @param sortColumn the sortColumn to set */ public void setSortColumn(String sortColumn) { this.sortColumn = sortColumn; } /** * @return the sortDeriction */ public String getSortDeriction() { return sortDeriction; } /** * @param sortDeriction the sortDeriction to set */ public void setSortDeriction(String sortDeriction) { this.sortDeriction = sortDeriction; } /** * @return the sortColumnList */ public String getSortColumnList() { return sortColumnList; } /** * @param sortColumnList the sortColumnList to set */ public void setSortColumnList(String sortColumnList) { this.sortColumnList = sortColumnList; } /** * @return the hideSort */ public String getHideSort() { return hideSort; } /** * @param hideSort the hideSort to set */ public void setHideSort(String hideSort) { this.hideSort = hideSort; } /** * @return the selectSql */ public String getSelectSql() { return selectSql; } /** * @param selectSql the selectSql to set */ public void setSelectSql(String selectSql) { this.selectSql = selectSql; } /** * @return the pageSize */ public Integer getPageSize() { return pageSize; } /** * @param pageSize the pageSize to set */ public void setPageSize(Integer pageSize) { this.pageSize = pageSize; } }
UTF-8
Java
3,138
ReportInfoPlus.java.svn-base
Java
[]
null
[]
package com.esunny.satellite.report.entity; import java.io.Serializable; public class ReportInfoPlus implements Serializable { private static final long serialVersionUID = -5255557112649520440L; private Long id; private String tableName; private String needIndex; private String sortColumn; private String sortDeriction; private String sortColumnList; private String hideSort; private String selectSql; private Integer pageSize; /** * @return the id */ public Long getId() { return id; } /** * @param id the id to set */ public void setId(Long id) { this.id = id; } /** * @return the tableName */ public String getTableName() { return tableName; } /** * @param tableName the tableName to set */ public void setTableName(String tableName) { this.tableName = tableName; } /** * @return the needIndex */ public String getNeedIndex() { return needIndex; } /** * @param needIndex the needIndex to set */ public void setNeedIndex(String needIndex) { this.needIndex = needIndex; } /** * @return the sortColumn */ public String getSortColumn() { return sortColumn; } /** * @param sortColumn the sortColumn to set */ public void setSortColumn(String sortColumn) { this.sortColumn = sortColumn; } /** * @return the sortDeriction */ public String getSortDeriction() { return sortDeriction; } /** * @param sortDeriction the sortDeriction to set */ public void setSortDeriction(String sortDeriction) { this.sortDeriction = sortDeriction; } /** * @return the sortColumnList */ public String getSortColumnList() { return sortColumnList; } /** * @param sortColumnList the sortColumnList to set */ public void setSortColumnList(String sortColumnList) { this.sortColumnList = sortColumnList; } /** * @return the hideSort */ public String getHideSort() { return hideSort; } /** * @param hideSort the hideSort to set */ public void setHideSort(String hideSort) { this.hideSort = hideSort; } /** * @return the selectSql */ public String getSelectSql() { return selectSql; } /** * @param selectSql the selectSql to set */ public void setSelectSql(String selectSql) { this.selectSql = selectSql; } /** * @return the pageSize */ public Integer getPageSize() { return pageSize; } /** * @param pageSize the pageSize to set */ public void setPageSize(Integer pageSize) { this.pageSize = pageSize; } }
3,138
0.539834
0.53378
153
18.509804
17.918158
71
false
false
0
0
0
0
0
0
0.196078
false
false
4
ea5bfc8e17da159603e6fa59fc94d220096e7ab1
36,180,804,540,536
4a299bab17a8d3efa475ee78160c58d864d5e209
/springbook/learningtest/factorybean/Message.java
4c2f8417289dea93baf73629363894aa632b1c94
[]
no_license
engineer135/springbook
https://github.com/engineer135/springbook
b0c2448c7c363df725972c9d9efaa65ad26c199e
45d545d7fd4ec312c865fb51b502269ed8d98e0b
refs/heads/master
2021-01-19T05:13:03.503000
2016-06-24T11:43:46
2016-06-24T11:43:46
60,471,028
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package springbook.learningtest.factorybean; /** * @author Engineer135 * * 생성자를 제공하지 않는 클래스 * 생성자를 private으로 만들었다는 것은 스태틱 메소드를 통해 오브젝트가 만들어져야 하는 중요한 이유가 있기 때문이므로, * 이를 무시하고 오브젝트를 강제로 생성하면 위험하다. * 그러므로 팩토리빈을 사용해서 오브젝트를 생성하자. */ public class Message { String text; private Message(String text){ this.text = text; } public String getText(){ return text; } public static Message newMessage(String text){ return new Message(text); } }
UHC
Java
690
java
Message.java
Java
[ { "context": "gbook.learningtest.factorybean;\r\n\r\n/**\r\n * @author Engineer135\r\n *\r\n * 생성자를 제공하지 않는 클래스\r\n * 생성자를 private으로 만들었다는", "end": 75, "score": 0.999374270439148, "start": 64, "tag": "USERNAME", "value": "Engineer135" } ]
null
[]
package springbook.learningtest.factorybean; /** * @author Engineer135 * * 생성자를 제공하지 않는 클래스 * 생성자를 private으로 만들었다는 것은 스태틱 메소드를 통해 오브젝트가 만들어져야 하는 중요한 이유가 있기 때문이므로, * 이를 무시하고 오브젝트를 강제로 생성하면 위험하다. * 그러므로 팩토리빈을 사용해서 오브젝트를 생성하자. */ public class Message { String text; private Message(String text){ this.text = text; } public String getText(){ return text; } public static Message newMessage(String text){ return new Message(text); } }
690
0.6639
0.657676
25
17.280001
17.809031
71
false
false
0
0
0
0
0
0
0.88
false
false
4
9d280ebd11f5ddf5ffbfaa0654f7bae28964c15b
35,244,501,680,902
446a6f4def5432c43570cb29a243586cfb5eaffa
/console/src/main/java/com/excilys/cdb/controller/CliController.java
59dc3a526c64ed12651179c33625beb5ae9e938f
[]
no_license
felixg03/CDB
https://github.com/felixg03/CDB
58efe72ce66f8fdd8c722b5bde929f70194d3c24
4c040f66d993f2ccd28418d887423fedcd3266fe
refs/heads/master
2023-04-10T04:50:06.359000
2021-03-31T16:33:38
2021-03-31T16:33:38
339,052,566
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.excilys.cdb.controller; import java.util.InputMismatchException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import com.excilys.cdb.customExceptions.InvalidComputerIdException; import com.excilys.cdb.models.Computer; import com.excilys.cdb.services.CompanyService; import com.excilys.cdb.services.ComputerService; import com.excilys.cdb.views.ViewCompany; import com.excilys.cdb.views.ViewComputer; @Component @Scope( value = ConfigurableBeanFactory.SCOPE_SINGLETON ) public class CliController { private ViewComputer viewComputer; private ViewCompany viewCompany; private CompanyService companyService; private ComputerService computerService; @Autowired public CliController(ViewComputer viewComputer, ViewCompany viewCompany, CompanyService companyService, ComputerService computerService) { super(); this.viewComputer = viewComputer; this.viewCompany = viewCompany; this.companyService = companyService; this.computerService = computerService; } public boolean action(int input) throws NumberFormatException, InvalidComputerIdException, InputMismatchException { int next, offset = 0; switch (input) { // DISPLAY LIST COMPUTERS case 1: do { next = viewComputer.displayListComputers(computerService.getListComputers(offset)); if (next == 1 && offset >= 10) { offset -= 10; } else if (next == 2) { offset += 10; } } while (next == 1 || next == 2); break; // DISPLAY LIST COMPANIES case 2: do { next = viewCompany.displayListCompanies(companyService.getListCompanies(offset)); if (next == 1 && offset >= 10) offset -= 10; else if (next == 2) offset += 10; } while (next == 1 || next == 2); break; // DISPLAY ONE COMPUTER DETAILS case 3: try { long computerIdToShowDetails = viewComputer.getComputerId(input); // throws NumberFormatException viewComputer // throws InvalidComputerIdException .displayOneComputerDetails(computerService.getOneComputer(computerIdToShowDetails)); } catch (Exception e) { if (e.getClass() == NumberFormatException.class) { throw (NumberFormatException) e; } else if (e.getClass() == InvalidComputerIdException.class) { throw (InvalidComputerIdException) e; } } break; // CREATE COMPUTER case 4: try { Computer computerToCreate = viewComputer.getComputerToCreate(); computerService.createComputer(computerToCreate); viewComputer.displayResultComputerCreation(); } catch (InputMismatchException inputMismatchEx) { throw inputMismatchEx; } break; // UPDATE COMPUTER /* * !!!!!!!!!!!!!!!! !!! BROKEN !!! !!!!!!!!!!!!!!!! */ /* * case 5: Computer computerToUpdate = viewComputer .getComputerInfoToUpdate(); * * * * // BROKEN HERE AT LINE BELOW: // Broken because Update function has been * commented // because it has to be refactored * * model.getComputerService() .getResultComputerUpdate(computerToUpdate); * * viewComputer.displayResultComputerUpdate(); * * break; */ // DELETE COMPUTER case 6: long computerIdToDelete = viewComputer.getComputerId(input); computerService.deleteComputer(computerIdToDelete); viewComputer.displayResultComputerDeletion(); break; // DELETE COMPANY case 7: companyService.callCompanyDeletion(viewCompany.getCompanyId()); break; // EXIT APPLICATION case 8: return false; } return true; // default } }
UTF-8
Java
3,683
java
CliController.java
Java
[]
null
[]
package com.excilys.cdb.controller; import java.util.InputMismatchException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import com.excilys.cdb.customExceptions.InvalidComputerIdException; import com.excilys.cdb.models.Computer; import com.excilys.cdb.services.CompanyService; import com.excilys.cdb.services.ComputerService; import com.excilys.cdb.views.ViewCompany; import com.excilys.cdb.views.ViewComputer; @Component @Scope( value = ConfigurableBeanFactory.SCOPE_SINGLETON ) public class CliController { private ViewComputer viewComputer; private ViewCompany viewCompany; private CompanyService companyService; private ComputerService computerService; @Autowired public CliController(ViewComputer viewComputer, ViewCompany viewCompany, CompanyService companyService, ComputerService computerService) { super(); this.viewComputer = viewComputer; this.viewCompany = viewCompany; this.companyService = companyService; this.computerService = computerService; } public boolean action(int input) throws NumberFormatException, InvalidComputerIdException, InputMismatchException { int next, offset = 0; switch (input) { // DISPLAY LIST COMPUTERS case 1: do { next = viewComputer.displayListComputers(computerService.getListComputers(offset)); if (next == 1 && offset >= 10) { offset -= 10; } else if (next == 2) { offset += 10; } } while (next == 1 || next == 2); break; // DISPLAY LIST COMPANIES case 2: do { next = viewCompany.displayListCompanies(companyService.getListCompanies(offset)); if (next == 1 && offset >= 10) offset -= 10; else if (next == 2) offset += 10; } while (next == 1 || next == 2); break; // DISPLAY ONE COMPUTER DETAILS case 3: try { long computerIdToShowDetails = viewComputer.getComputerId(input); // throws NumberFormatException viewComputer // throws InvalidComputerIdException .displayOneComputerDetails(computerService.getOneComputer(computerIdToShowDetails)); } catch (Exception e) { if (e.getClass() == NumberFormatException.class) { throw (NumberFormatException) e; } else if (e.getClass() == InvalidComputerIdException.class) { throw (InvalidComputerIdException) e; } } break; // CREATE COMPUTER case 4: try { Computer computerToCreate = viewComputer.getComputerToCreate(); computerService.createComputer(computerToCreate); viewComputer.displayResultComputerCreation(); } catch (InputMismatchException inputMismatchEx) { throw inputMismatchEx; } break; // UPDATE COMPUTER /* * !!!!!!!!!!!!!!!! !!! BROKEN !!! !!!!!!!!!!!!!!!! */ /* * case 5: Computer computerToUpdate = viewComputer .getComputerInfoToUpdate(); * * * * // BROKEN HERE AT LINE BELOW: // Broken because Update function has been * commented // because it has to be refactored * * model.getComputerService() .getResultComputerUpdate(computerToUpdate); * * viewComputer.displayResultComputerUpdate(); * * break; */ // DELETE COMPUTER case 6: long computerIdToDelete = viewComputer.getComputerId(input); computerService.deleteComputer(computerIdToDelete); viewComputer.displayResultComputerDeletion(); break; // DELETE COMPANY case 7: companyService.callCompanyDeletion(viewCompany.getCompanyId()); break; // EXIT APPLICATION case 8: return false; } return true; // default } }
3,683
0.71735
0.709476
148
23.885136
26.291126
116
false
false
0
0
0
0
0
0
2.20946
false
false
4
9894cfec2ffd699c01d050f0925c4598d75d1e3c
37,400,575,239,597
a6b6ede9e2b5007c0a272c2dc03491f5f7897d1d
/app/src/main/java/com/example/prason/wifiattendence/MainActivity.java
a6cd5237a5b35a4b68bec8187a545733089d096f
[]
no_license
prason-chriso/ChrisoWifiAttendance
https://github.com/prason-chriso/ChrisoWifiAttendance
36ec697b12be4141d65f6bed5762c68481ff63b4
a66dba4627cbe873acda0f7a40f58b6b70fa59f6
refs/heads/master
2020-03-11T10:14:58.108000
2018-04-17T17:00:33
2018-04-17T17:00:33
129,937,322
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.prason.wifiattendence; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.wifi.WifiManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; import android.widget.Toast; import java.util.Date; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.RunnableFuture; public class MainActivity extends AppCompatActivity { public static Button makeAttendance; Button show_list; public static ProgressDialog dialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override protected void onStart(){ super.onStart(); ShowAllAttendance.mydata.clear(); BackgroundTask bkt = new BackgroundTask(MainActivity.this); bkt.execute("presentDays", "" + LauncherClassFile.CURRENT_USER_ID); dialog = new ProgressDialog(MainActivity.this); dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); dialog.setMessage("Loading. Please wait..."); dialog.setIndeterminate(true); dialog.setCanceledOnTouchOutside(false); dialog.show(); TimerTask task = new TimerTask() { @Override public void run() { if(dialog.isShowing()){ dialog.dismiss(); } } }; Timer timer = new Timer(); timer.schedule(task,4000); makeAttendance = (Button) findViewById(R.id.makeAttendance); /* if (ShowAllAttendance.mydata.size() > 0) { if (ShowAllAttendance.mydata.get(0).equals("new_user") || ShowAllAttendance.mydata.get(0).equals("need_attendance")) { //do nothing } else if (ShowAllAttendance.mydata.get(0).contains("remaining for next attendance")) { MainActivity.makeAttendance.setEnabled(false); Toast.makeText(MainActivity.this, ShowAllAttendance.mydata.get(0), Toast.LENGTH_SHORT).show(); } } */ show_list = (Button) findViewById(R.id.show_list); show_list.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(MainActivity.this, ShowAllAttendance.class)); } }); makeAttendance.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { makeAttendance.setEnabled(false); registerEvent(); } }); } public void registerEvent(){ registerReceiver(new MyBroadcastReceiver(), new IntentFilter(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION)); BackgroundTask backgroundTask = new BackgroundTask(this); backgroundTask.execute("make_attendace",""+LauncherClassFile.CURRENT_USER_ID); } }
UTF-8
Java
3,204
java
MainActivity.java
Java
[ { "context": "package com.example.prason.wifiattendence;\n\nimport android.app.ProgressDialo", "end": 26, "score": 0.8854405879974365, "start": 20, "tag": "USERNAME", "value": "prason" } ]
null
[]
package com.example.prason.wifiattendence; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.wifi.WifiManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; import android.widget.Toast; import java.util.Date; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.RunnableFuture; public class MainActivity extends AppCompatActivity { public static Button makeAttendance; Button show_list; public static ProgressDialog dialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override protected void onStart(){ super.onStart(); ShowAllAttendance.mydata.clear(); BackgroundTask bkt = new BackgroundTask(MainActivity.this); bkt.execute("presentDays", "" + LauncherClassFile.CURRENT_USER_ID); dialog = new ProgressDialog(MainActivity.this); dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); dialog.setMessage("Loading. Please wait..."); dialog.setIndeterminate(true); dialog.setCanceledOnTouchOutside(false); dialog.show(); TimerTask task = new TimerTask() { @Override public void run() { if(dialog.isShowing()){ dialog.dismiss(); } } }; Timer timer = new Timer(); timer.schedule(task,4000); makeAttendance = (Button) findViewById(R.id.makeAttendance); /* if (ShowAllAttendance.mydata.size() > 0) { if (ShowAllAttendance.mydata.get(0).equals("new_user") || ShowAllAttendance.mydata.get(0).equals("need_attendance")) { //do nothing } else if (ShowAllAttendance.mydata.get(0).contains("remaining for next attendance")) { MainActivity.makeAttendance.setEnabled(false); Toast.makeText(MainActivity.this, ShowAllAttendance.mydata.get(0), Toast.LENGTH_SHORT).show(); } } */ show_list = (Button) findViewById(R.id.show_list); show_list.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(MainActivity.this, ShowAllAttendance.class)); } }); makeAttendance.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { makeAttendance.setEnabled(false); registerEvent(); } }); } public void registerEvent(){ registerReceiver(new MyBroadcastReceiver(), new IntentFilter(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION)); BackgroundTask backgroundTask = new BackgroundTask(this); backgroundTask.execute("make_attendace",""+LauncherClassFile.CURRENT_USER_ID); } }
3,204
0.641698
0.638577
99
31.353535
28.46274
130
false
false
0
0
0
0
0
0
0.565657
false
false
4
407acb47fa9a90f8c3f62d3e58a39e8a2b13bf51
36,344,013,298,399
f0d452a5b340b6ab8f1a04025b41a23256ece11b
/src/cap03/Login.java
49638400f4f1857c340ffae3a561ad5ec2fbe5cd
[]
no_license
DeveloperMobile/java8
https://github.com/DeveloperMobile/java8
3a9312f4cf32a71de6c2f556518978509a9dcc46
412435645413b16a899448e8a8f865f4b79476f3
refs/heads/master
2021-01-23T01:12:56.467000
2017-10-03T18:56:15
2017-10-03T18:56:15
85,888,911
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cap03; import javax.swing.JOptionPane; /** * * @author tiago */ public class Login { public static void main(String[] args) { int contador = 0; while (true) { String login = JOptionPane.showInputDialog("Informe o login"); String senha = JOptionPane.showInputDialog("Informe a senha"); if (login.equals("tiago") && senha.equals("123456")) { JOptionPane.showMessageDialog(null, "Login efetuado com sucesso!"); break; } else { contador++; if (contador == 3) { JOptionPane.showMessageDialog(null, "Número de tentativas esgotado.\nTente novamente mais tarde."); break; } else { JOptionPane.showMessageDialog(null, "Falha, verifique login e senha.\nVocê tem mais " + (3 - contador) + " tentativas"); } } } System.exit(0); } }
UTF-8
Java
1,247
java
Login.java
Java
[ { "context": "import javax.swing.JOptionPane;\n\n/**\n *\n * @author tiago\n */\npublic class Login {\n \n public static v", "end": 73, "score": 0.9990734457969666, "start": 68, "tag": "USERNAME", "value": "tiago" }, { "context": "nha\");\n \n if (login.equals(\"tiago\") && senha.equals(\"123456\")) {\n \n ", "end": 427, "score": 0.9997324347496033, "start": 422, "tag": "USERNAME", "value": "tiago" }, { "context": " if (login.equals(\"tiago\") && senha.equals(\"123456\")) {\n \n JOptionPane", "end": 453, "score": 0.9993276000022888, "start": 447, "tag": "PASSWORD", "value": "123456" } ]
null
[]
package cap03; import javax.swing.JOptionPane; /** * * @author tiago */ public class Login { public static void main(String[] args) { int contador = 0; while (true) { String login = JOptionPane.showInputDialog("Informe o login"); String senha = JOptionPane.showInputDialog("Informe a senha"); if (login.equals("tiago") && senha.equals("<PASSWORD>")) { JOptionPane.showMessageDialog(null, "Login efetuado com sucesso!"); break; } else { contador++; if (contador == 3) { JOptionPane.showMessageDialog(null, "Número de tentativas esgotado.\nTente novamente mais tarde."); break; } else { JOptionPane.showMessageDialog(null, "Falha, verifique login e senha.\nVocê tem mais " + (3 - contador) + " tentativas"); } } } System.exit(0); } }
1,251
0.421687
0.412048
48
24.916666
28.737921
139
false
false
0
0
0
0
0
0
0.333333
false
false
4
01d1909c9d09a5d4aabb7e8c216f2dfc59b7d061
39,444,979,659,540
1972b2c7e8cb060b80ffa1588f9482e8aaf46ca9
/src/main/java/com/codexsoft/zagursky/service/ProjectService.java
05bb1cd657f8eb5dcbb5d4c8ba6c2312ad7148f3
[]
no_license
DenisZagursky/TaskTreker
https://github.com/DenisZagursky/TaskTreker
235534b19a4f33c929d686e21787b3c7509f5484
323af72a9cc79c6dcf09c435832a93cb06f715fb
refs/heads/master
2021-05-05T02:25:06.776000
2018-02-01T10:35:52
2018-02-01T10:35:52
119,743,697
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.codexsoft.zagursky.service; import com.codexsoft.zagursky.entity.Project; import com.codexsoft.zagursky.exception.CustomException; import java.util.List; /** * Created by Dzenyaa on 26.01.2018. */ public interface ProjectService { void createProject(Project project); void addProjectToUser(Long id, String username) throws CustomException; List<Project> getProjectsByUser(Long id); Project geProjectById(Long id); List<Project> findProjectsByUser(); void saveProject(String name, String description); }
UTF-8
Java
550
java
ProjectService.java
Java
[ { "context": "eption;\n\nimport java.util.List;\n\n/**\n * Created by Dzenyaa on 26.01.2018.\n */\npublic interface ProjectServic", "end": 194, "score": 0.9995899200439453, "start": 187, "tag": "USERNAME", "value": "Dzenyaa" } ]
null
[]
package com.codexsoft.zagursky.service; import com.codexsoft.zagursky.entity.Project; import com.codexsoft.zagursky.exception.CustomException; import java.util.List; /** * Created by Dzenyaa on 26.01.2018. */ public interface ProjectService { void createProject(Project project); void addProjectToUser(Long id, String username) throws CustomException; List<Project> getProjectsByUser(Long id); Project geProjectById(Long id); List<Project> findProjectsByUser(); void saveProject(String name, String description); }
550
0.761818
0.747273
24
21.916666
23.23237
75
false
false
0
0
0
0
0
0
0.5
false
false
4
e8a0f1d69313f434cdc39eae401edfc563f8ce03
37,151,467,146,930
0f8d70bb4d29c160fffbd2639e388b28af550650
/src/test/java/test/blog/ImportTest.java
988ada2a47ca5be0ac8336a1d8381f7b13578366
[]
no_license
Rong1235/AR
https://github.com/Rong1235/AR
c2cc11ed9db964b4a08c7a2c478eff8b941403c1
595645a2cd0b66cba92111fa9e586265cb8cbe77
refs/heads/master
2021-08-30T16:27:05.764000
2017-12-18T16:47:01
2017-12-18T16:47:01
111,991,806
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package test.blog; import java.io.FileInputStream; import java.io.InputStream; import java.util.List; import org.easy.excel.ExcelContext; import org.easy.excel.parsing.ExcelError; import org.easy.excel.result.ExcelImportResult; import sw.entity.Asset; import test.model.BookModel; import test.model.StudentModel; public class ImportTest { public static void main(String[] args) throws Exception { //准备excel文件流 InputStream excelStream = new FileInputStream("../sw/src/main/resources/upload/资产列表.xlsx"); //创建excel上下文实例,它的构成需要配置文件的路径 ExcelContext context = new ExcelContext("../sw/src/main/resources/excelConfig/Asset.xml"); //按照xml配置中id为student的配置形式读取excel文件,并转换成StudentModel //这里的第二个参数是值,标题是第几行开始,之前也说了标题之前的数据并不是规则的数据 //ExcelImportResult result = context.readExcel("HardwareAssets", 0,excelStream); ExcelImportResult result = context.readExcel("HardwareAssets", 0, excelStream,true); //打印导入结果,查看标题之前不规则的数据 List<List<Object>> header = result.getHeader(); // System.out.println(header.get(0)); // System.out.println(header.get(1)); //查看学生集合导入结果 List<Asset> assets = result.getListBean(); for(Asset ass:assets){ System.out.println(ass); } if(result.hasErrors()){ System.out.println("导入包含错误,下面是错误信息:"); for (ExcelError err:result.getErrors()) { System.out.println(err.getErrorMsg()); } } } }
UTF-8
Java
1,644
java
ImportTest.java
Java
[]
null
[]
package test.blog; import java.io.FileInputStream; import java.io.InputStream; import java.util.List; import org.easy.excel.ExcelContext; import org.easy.excel.parsing.ExcelError; import org.easy.excel.result.ExcelImportResult; import sw.entity.Asset; import test.model.BookModel; import test.model.StudentModel; public class ImportTest { public static void main(String[] args) throws Exception { //准备excel文件流 InputStream excelStream = new FileInputStream("../sw/src/main/resources/upload/资产列表.xlsx"); //创建excel上下文实例,它的构成需要配置文件的路径 ExcelContext context = new ExcelContext("../sw/src/main/resources/excelConfig/Asset.xml"); //按照xml配置中id为student的配置形式读取excel文件,并转换成StudentModel //这里的第二个参数是值,标题是第几行开始,之前也说了标题之前的数据并不是规则的数据 //ExcelImportResult result = context.readExcel("HardwareAssets", 0,excelStream); ExcelImportResult result = context.readExcel("HardwareAssets", 0, excelStream,true); //打印导入结果,查看标题之前不规则的数据 List<List<Object>> header = result.getHeader(); // System.out.println(header.get(0)); // System.out.println(header.get(1)); //查看学生集合导入结果 List<Asset> assets = result.getListBean(); for(Asset ass:assets){ System.out.println(ass); } if(result.hasErrors()){ System.out.println("导入包含错误,下面是错误信息:"); for (ExcelError err:result.getErrors()) { System.out.println(err.getErrorMsg()); } } } }
1,644
0.73088
0.727994
41
31.804878
24.590519
93
false
false
0
0
0
0
0
0
2.121951
false
false
4
36318b78275a01b28aa74406e0f58a0840895b96
38,594,576,145,464
80b292ae76f92eaf20ee1c0456e947eef51744c6
/src/org/bcm/hgsc/utils/KRCGTK.java
2cd472a32fcd0b16f4322b4900871048e0a4f7a2
[]
no_license
covingto/KRCGTK
https://github.com/covingto/KRCGTK
85ba7e6d090a7cb6139cfd3162adb0a6ca0b8571
902ea64c978c1e16e0af7b22e127d2fee85d36a0
refs/heads/master
2021-08-31T19:39:55.458000
2016-10-06T18:21:24
2016-10-06T18:21:24
112,523,101
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.bcm.hgsc.utils; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.Options; import org.apache.commons.cli.Parser; public class KRCGTK { public static void main(String[] args) { // TODO Auto-generated method stub Options options = new Options(); Parser parser = new BasicParser(); options.addOption("a", true, "action to process"); } }
UTF-8
Java
383
java
KRCGTK.java
Java
[]
null
[]
package org.bcm.hgsc.utils; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.Options; import org.apache.commons.cli.Parser; public class KRCGTK { public static void main(String[] args) { // TODO Auto-generated method stub Options options = new Options(); Parser parser = new BasicParser(); options.addOption("a", true, "action to process"); } }
383
0.733681
0.733681
16
22.9375
18.484686
52
false
false
0
0
0
0
0
0
1.1875
false
false
4
87ccd9f6d9b8407e3e416938637c2bde8c83310f
36,155,034,744,026
848d1e3cc9e714d0bef7a3aee732956950a5ed32
/src/optimate/TestUnmappedOptimateObject.java
649367faf76abbc72955692e7cc63bfc9774c7e5
[]
no_license
aarong-CD-adapco/macros
https://github.com/aarong-CD-adapco/macros
3641e5c78ee525fe56d1239391550b992866354d
69122d03dd91ace5c44ea641714be91227bf5da9
refs/heads/master
2021-01-18T14:58:43.644000
2016-02-27T00:18:51
2016-02-27T00:18:51
24,915,401
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * 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 optimate; import core.apiFramework.OptimateObject; import core.apiFramework.properties.OptimateObjectKey; import core.apiFramework.properties.PropertyKey; import core.apiFramework.properties.StringArrayKey; import core.apiFramework.properties.StringKey; import java.util.Map; /** * * @author aarong */ public class TestUnmappedOptimateObject extends OptimateObject { StringKey unMappedKey = new StringKey("Unmapped object property key", true); public TestUnmappedOptimateObject() { super(); set(unMappedKey, "unmapped property"); } public void set(String s) { set(unMappedKey, s); } @Override public String toString() { String toReturn = "TestUnmappedOptimateObject"; toReturn += has(OptimateObject.NAME) ? " " + getName() + ":\n" : ":\n"; toReturn += "\tProperties:\n"; for (Map.Entry<PropertyKey, Object> entry : _propertyMap._properties.entrySet()) { if (entry.getKey() instanceof StringArrayKey) { toReturn += "\t\tString Array:\n"; for (String s : (String[]) entry.getValue()) { toReturn += "\t\t\t" + s + "\n"; } } else if (entry.getKey() instanceof OptimateObjectKey) { toReturn += ((OptimateObject) entry.getValue()).toString(); } else { toReturn += "\t\t" + entry.getKey() + ", " + entry.getValue() + "\n"; } } return toReturn; } }
UTF-8
Java
1,724
java
TestUnmappedOptimateObject.java
Java
[ { "context": "tringKey;\nimport java.util.Map;\n\n/**\n *\n * @author aarong\n */\npublic class TestUnmappedOptimateObject exten", "end": 495, "score": 0.9995538592338562, "start": 489, "tag": "USERNAME", "value": "aarong" } ]
null
[]
/* * 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 optimate; import core.apiFramework.OptimateObject; import core.apiFramework.properties.OptimateObjectKey; import core.apiFramework.properties.PropertyKey; import core.apiFramework.properties.StringArrayKey; import core.apiFramework.properties.StringKey; import java.util.Map; /** * * @author aarong */ public class TestUnmappedOptimateObject extends OptimateObject { StringKey unMappedKey = new StringKey("Unmapped object property key", true); public TestUnmappedOptimateObject() { super(); set(unMappedKey, "unmapped property"); } public void set(String s) { set(unMappedKey, s); } @Override public String toString() { String toReturn = "TestUnmappedOptimateObject"; toReturn += has(OptimateObject.NAME) ? " " + getName() + ":\n" : ":\n"; toReturn += "\tProperties:\n"; for (Map.Entry<PropertyKey, Object> entry : _propertyMap._properties.entrySet()) { if (entry.getKey() instanceof StringArrayKey) { toReturn += "\t\tString Array:\n"; for (String s : (String[]) entry.getValue()) { toReturn += "\t\t\t" + s + "\n"; } } else if (entry.getKey() instanceof OptimateObjectKey) { toReturn += ((OptimateObject) entry.getValue()).toString(); } else { toReturn += "\t\t" + entry.getKey() + ", " + entry.getValue() + "\n"; } } return toReturn; } }
1,724
0.606729
0.606729
52
32.153847
27.007395
90
false
false
0
0
0
0
0
0
0.519231
false
false
4
fa06b9e8f11f992c7011370a02fc20d1332789b6
36,455,682,455,183
4f0e33a5dab58c3b553c0189f03823f32068e13f
/modules/client/src/main/java/com/mindbox/pe/client/applet/template/guideline/NewTemplateCutOverDetail.java
ec034825979ddec3968bd29e3a207144f36b8f76
[]
no_license
josfernandez-clgx/PowerEditor
https://github.com/josfernandez-clgx/PowerEditor
6e2e1f098fa11c871e6a0b8da982cca2ab22e285
a4399706feb4dfb2d10c8209ead59d6639e98473
refs/heads/master
2023-06-08T01:48:26.053000
2020-06-02T22:15:00
2020-06-02T22:15:00
379,699,653
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mindbox.pe.client.applet.template.guideline; import java.util.List; import com.mindbox.pe.model.DateSynonym; import com.mindbox.pe.model.GuidelineReportData; public final class NewTemplateCutOverDetail { private final DateSynonym dateSynonym; private List<GuidelineReportData> guidelinesToCutOver; public NewTemplateCutOverDetail(DateSynonym dateSynonym, List<GuidelineReportData> guidelinesToCutOver) { super(); this.dateSynonym = dateSynonym; this.guidelinesToCutOver = guidelinesToCutOver; } public final DateSynonym getDateSynonym() { return dateSynonym; } public final List<GuidelineReportData> getGuidelinesToCutOver() { return guidelinesToCutOver; } }
UTF-8
Java
724
java
NewTemplateCutOverDetail.java
Java
[]
null
[]
package com.mindbox.pe.client.applet.template.guideline; import java.util.List; import com.mindbox.pe.model.DateSynonym; import com.mindbox.pe.model.GuidelineReportData; public final class NewTemplateCutOverDetail { private final DateSynonym dateSynonym; private List<GuidelineReportData> guidelinesToCutOver; public NewTemplateCutOverDetail(DateSynonym dateSynonym, List<GuidelineReportData> guidelinesToCutOver) { super(); this.dateSynonym = dateSynonym; this.guidelinesToCutOver = guidelinesToCutOver; } public final DateSynonym getDateSynonym() { return dateSynonym; } public final List<GuidelineReportData> getGuidelinesToCutOver() { return guidelinesToCutOver; } }
724
0.781768
0.781768
27
24.814816
27.136196
106
false
false
0
0
0
0
0
0
1.111111
false
false
4
93ff426190eca7fcd65cda8ebe3f2f3d5f8ef516
36,455,682,453,314
3791d18c0f5e9af4c09aa89aaf48d6d035e2a473
/Study_Java/src/QueueExample.java
1cd24381c35bcb686b0760eab8683b7a15cbcf4f
[]
no_license
ChoSuYeon84/Study_Java
https://github.com/ChoSuYeon84/Study_Java
c91bc05c1afd0daec903bd27c9ddefbdc401fa8c
c2030803a76829eb2717be6f6bdbabd65e4fe0be
refs/heads/master
2021-02-06T08:09:03.639000
2020-08-02T10:58:19
2020-08-02T10:58:19
243,896,316
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.LinkedList; import java.util.Queue; //Queue를 이용한 메시지 큐 //Queue 인터페이스 : FIFO(First In First Out: 먼저 넣은 객체가 먼저 빠져나가는 자료구조)에서 사용 public class QueueExample { public static void main(String[] args) { Queue<Message> messageQueue = new LinkedList<Message>(); //메세지 저장 messageQueue.offer(new Message("sendMail", "고길동")); messageQueue.offer(new Message("sendSMS", "홍길동")); messageQueue.offer(new Message("sendKakaotalk", "홍두깨")); while(!messageQueue.isEmpty()) { //메시지 큐가 비어있지 않다면 Message message = messageQueue.poll(); //메시지큐에서 1개의 메시지 꺼냄 switch (message.command) { case "sendMail": System.out.println(message.to + "님에게 메일을 보냅니다."); break; case "sendSMS": System.out.println(message.to + "님에게 메일을 보냅니다."); break; case "sendKakaotalk": System.out.println(message.to + "님에게 메일을 보냅니다."); break; } } } }
UTF-8
Java
1,089
java
QueueExample.java
Java
[]
null
[]
import java.util.LinkedList; import java.util.Queue; //Queue를 이용한 메시지 큐 //Queue 인터페이스 : FIFO(First In First Out: 먼저 넣은 객체가 먼저 빠져나가는 자료구조)에서 사용 public class QueueExample { public static void main(String[] args) { Queue<Message> messageQueue = new LinkedList<Message>(); //메세지 저장 messageQueue.offer(new Message("sendMail", "고길동")); messageQueue.offer(new Message("sendSMS", "홍길동")); messageQueue.offer(new Message("sendKakaotalk", "홍두깨")); while(!messageQueue.isEmpty()) { //메시지 큐가 비어있지 않다면 Message message = messageQueue.poll(); //메시지큐에서 1개의 메시지 꺼냄 switch (message.command) { case "sendMail": System.out.println(message.to + "님에게 메일을 보냅니다."); break; case "sendSMS": System.out.println(message.to + "님에게 메일을 보냅니다."); break; case "sendKakaotalk": System.out.println(message.to + "님에게 메일을 보냅니다."); break; } } } }
1,089
0.666288
0.665153
31
27.419355
22.440996
70
false
false
0
0
0
0
0
0
2.677419
false
false
4
2a652e4adad15ad7749c35301af266fb2a88d234
36,455,682,451,382
e783911eb574edcea81fade03f0c464523a5a4c0
/Management/src/main/java/com/neu/management/controller/FactoryController.java
4a26bce59101c8ce83665131d00ca0245d44b122
[]
no_license
hanhandidi/CloudPlatform
https://github.com/hanhandidi/CloudPlatform
d45e93979af2e1f7308ff80c64991985f6044cc7
a06013356ef9a324858c9276816f483729e13246
refs/heads/master
2022-06-29T06:15:20.279000
2019-08-19T11:56:38
2019-08-19T11:56:38
201,020,462
3
0
null
false
2022-06-17T02:23:15
2019-08-07T09:43:07
2019-10-21T02:15:50
2022-06-17T02:23:14
635
2
0
3
Java
false
false
package com.neu.management.controller; import com.neu.management.model.Message; import com.neu.management.model.TFactory; import com.neu.management.service.FactoryService; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.sql.Timestamp; import java.util.Date; @RestController @RequestMapping(value = "/factory") public class FactoryController { private final FactoryService factoryService; @Autowired public FactoryController(FactoryService factoryService) { this.factoryService = factoryService; } // 添加工厂信息 ok @PostMapping("add") @ApiOperation("添加工厂信息") @ApiImplicitParam(name="tFactory",value="工厂实体类",dataType="TFactory") public Message addFactory(@RequestBody TFactory tFactory) { Message addFactoryMessage = new Message(); tFactory.setUpdateUserid(tFactory.getCreateUserid()); tFactory.setCreateTime(new Timestamp(new Date().getTime())); tFactory.setUpdateTime(new Timestamp(new Date().getTime())); TFactory tFactory1 = factoryService.addFactory(tFactory); if (tFactory1 == null){ addFactoryMessage.setCode(202); addFactoryMessage.setMessage("添加工厂信息失败,请重试!"); }else { // 借助get方法添加缓存 // System.out.println(addFactoryMessage.getId()); factoryService.getFactory((int) tFactory1.getId()); addFactoryMessage.setCode(200); addFactoryMessage.setMessage("添加工厂信息成功!"); addFactoryMessage.setData(tFactory1); } return addFactoryMessage; } // 根据ID删除工厂信息 ok @ApiOperation("根据ID删除工厂信息") @ApiImplicitParam(name="id",value="id",dataType="Integer") @DeleteMapping("delete/{id}") public Message deleteFactory(@PathVariable Integer id){ factoryService.deleteFactory(id); Message deleteFactoryMessage = new Message(); deleteFactoryMessage.setCode(200); deleteFactoryMessage.setMessage("删除工厂信息成功!"); return deleteFactoryMessage; } // 根据ID获取工厂信息 ok @GetMapping("get/{id}") @ApiOperation("根据ID获取工厂信息") @ApiImplicitParam(name="id",value="id",dataType="Integer") public Message getFactory(@PathVariable Integer id){ Message getFactoryMessage = new Message(); if (factoryService.getFactory(id) != null){ getFactoryMessage.setCode(200); getFactoryMessage.setMessage("获取工厂信息成功!"); getFactoryMessage.setData(factoryService.getFactory(id)); }else { getFactoryMessage.setCode(202); getFactoryMessage.setMessage("获取工厂信息失败!"); } return getFactoryMessage; } // 更新工厂信息 ok @PutMapping("update") @ApiOperation("更新工厂信息") @ApiImplicitParam(name="tFactory",value="工厂实体类",dataType="TFactory") public Message updateFactory(@RequestBody TFactory tFactory){ Message updateFactoryMessage = new Message(); tFactory.setUpdateTime(new Timestamp(new Date().getTime())); if (factoryService.updateFactory(tFactory) == null){ // 序列号重复 updateFactoryMessage.setCode(202); updateFactoryMessage.setMessage("更新工厂信息失败,请重试!"); }else { updateFactoryMessage.setCode(200); updateFactoryMessage.setMessage("更新工厂信息成功!"); updateFactoryMessage.setData(tFactory); } return updateFactoryMessage; } // 更新工厂状态信息 ok @PutMapping("updateState") @ApiOperation("更新工厂状态信息") @ApiImplicitParam(name="tFactory",value="工厂实体类",dataType="TFactory") public Message updateFactoryState(@RequestBody TFactory tFactory){ Message updateFactoryMessage = new Message(); tFactory.setUpdateTime(new Timestamp(new Date().getTime())); TFactory tFactory1 = factoryService.updateFactoryState(tFactory); if ( tFactory1 == null){ updateFactoryMessage.setCode(202); updateFactoryMessage.setMessage("更新工厂状态失败"); }else { updateFactoryMessage.setCode(200); updateFactoryMessage.setMessage("更新工厂状态成功!"); updateFactoryMessage.setData(tFactory1); } return updateFactoryMessage; } // 获取所有工厂信息 ok @GetMapping("getAll") @ApiOperation("获取所有工厂信息") public Message getAllFactory(){ Message getAllFactoryMessage = new Message(); if (factoryService.getAllFactory() != null){ getAllFactoryMessage.setCode(200); getAllFactoryMessage.setMessage("获取所有工厂信息成功!"); getAllFactoryMessage.setData(factoryService.getAllFactory()); }else { getAllFactoryMessage.setCode(202); getAllFactoryMessage.setMessage("获取所有工厂信息失败!"); } return getAllFactoryMessage; } // 分页搜索 ok @ApiOperation("分页 获取所有工厂信息") @ApiImplicitParams({ @ApiImplicitParam(name="currPage",value="当前页",dataType="Integer"), @ApiImplicitParam(name="tFactory",value="工厂实体类",dataType="TFactory") }) @PostMapping("list/{currPage}") public Message listFactory(@PathVariable Integer currPage, @RequestBody TFactory tFactory){ Message listFactoryMessage = new Message(); if (factoryService.listFactory(currPage,tFactory) != null){ listFactoryMessage.setCode(200); listFactoryMessage.setMessage("分页查询工厂信息成功!"); listFactoryMessage.setData(factoryService.listFactory(currPage,tFactory)); }else { listFactoryMessage.setCode(202); listFactoryMessage.setMessage("分页查询工厂信息失败!"); } return listFactoryMessage; } }
UTF-8
Java
6,366
java
FactoryController.java
Java
[]
null
[]
package com.neu.management.controller; import com.neu.management.model.Message; import com.neu.management.model.TFactory; import com.neu.management.service.FactoryService; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.sql.Timestamp; import java.util.Date; @RestController @RequestMapping(value = "/factory") public class FactoryController { private final FactoryService factoryService; @Autowired public FactoryController(FactoryService factoryService) { this.factoryService = factoryService; } // 添加工厂信息 ok @PostMapping("add") @ApiOperation("添加工厂信息") @ApiImplicitParam(name="tFactory",value="工厂实体类",dataType="TFactory") public Message addFactory(@RequestBody TFactory tFactory) { Message addFactoryMessage = new Message(); tFactory.setUpdateUserid(tFactory.getCreateUserid()); tFactory.setCreateTime(new Timestamp(new Date().getTime())); tFactory.setUpdateTime(new Timestamp(new Date().getTime())); TFactory tFactory1 = factoryService.addFactory(tFactory); if (tFactory1 == null){ addFactoryMessage.setCode(202); addFactoryMessage.setMessage("添加工厂信息失败,请重试!"); }else { // 借助get方法添加缓存 // System.out.println(addFactoryMessage.getId()); factoryService.getFactory((int) tFactory1.getId()); addFactoryMessage.setCode(200); addFactoryMessage.setMessage("添加工厂信息成功!"); addFactoryMessage.setData(tFactory1); } return addFactoryMessage; } // 根据ID删除工厂信息 ok @ApiOperation("根据ID删除工厂信息") @ApiImplicitParam(name="id",value="id",dataType="Integer") @DeleteMapping("delete/{id}") public Message deleteFactory(@PathVariable Integer id){ factoryService.deleteFactory(id); Message deleteFactoryMessage = new Message(); deleteFactoryMessage.setCode(200); deleteFactoryMessage.setMessage("删除工厂信息成功!"); return deleteFactoryMessage; } // 根据ID获取工厂信息 ok @GetMapping("get/{id}") @ApiOperation("根据ID获取工厂信息") @ApiImplicitParam(name="id",value="id",dataType="Integer") public Message getFactory(@PathVariable Integer id){ Message getFactoryMessage = new Message(); if (factoryService.getFactory(id) != null){ getFactoryMessage.setCode(200); getFactoryMessage.setMessage("获取工厂信息成功!"); getFactoryMessage.setData(factoryService.getFactory(id)); }else { getFactoryMessage.setCode(202); getFactoryMessage.setMessage("获取工厂信息失败!"); } return getFactoryMessage; } // 更新工厂信息 ok @PutMapping("update") @ApiOperation("更新工厂信息") @ApiImplicitParam(name="tFactory",value="工厂实体类",dataType="TFactory") public Message updateFactory(@RequestBody TFactory tFactory){ Message updateFactoryMessage = new Message(); tFactory.setUpdateTime(new Timestamp(new Date().getTime())); if (factoryService.updateFactory(tFactory) == null){ // 序列号重复 updateFactoryMessage.setCode(202); updateFactoryMessage.setMessage("更新工厂信息失败,请重试!"); }else { updateFactoryMessage.setCode(200); updateFactoryMessage.setMessage("更新工厂信息成功!"); updateFactoryMessage.setData(tFactory); } return updateFactoryMessage; } // 更新工厂状态信息 ok @PutMapping("updateState") @ApiOperation("更新工厂状态信息") @ApiImplicitParam(name="tFactory",value="工厂实体类",dataType="TFactory") public Message updateFactoryState(@RequestBody TFactory tFactory){ Message updateFactoryMessage = new Message(); tFactory.setUpdateTime(new Timestamp(new Date().getTime())); TFactory tFactory1 = factoryService.updateFactoryState(tFactory); if ( tFactory1 == null){ updateFactoryMessage.setCode(202); updateFactoryMessage.setMessage("更新工厂状态失败"); }else { updateFactoryMessage.setCode(200); updateFactoryMessage.setMessage("更新工厂状态成功!"); updateFactoryMessage.setData(tFactory1); } return updateFactoryMessage; } // 获取所有工厂信息 ok @GetMapping("getAll") @ApiOperation("获取所有工厂信息") public Message getAllFactory(){ Message getAllFactoryMessage = new Message(); if (factoryService.getAllFactory() != null){ getAllFactoryMessage.setCode(200); getAllFactoryMessage.setMessage("获取所有工厂信息成功!"); getAllFactoryMessage.setData(factoryService.getAllFactory()); }else { getAllFactoryMessage.setCode(202); getAllFactoryMessage.setMessage("获取所有工厂信息失败!"); } return getAllFactoryMessage; } // 分页搜索 ok @ApiOperation("分页 获取所有工厂信息") @ApiImplicitParams({ @ApiImplicitParam(name="currPage",value="当前页",dataType="Integer"), @ApiImplicitParam(name="tFactory",value="工厂实体类",dataType="TFactory") }) @PostMapping("list/{currPage}") public Message listFactory(@PathVariable Integer currPage, @RequestBody TFactory tFactory){ Message listFactoryMessage = new Message(); if (factoryService.listFactory(currPage,tFactory) != null){ listFactoryMessage.setCode(200); listFactoryMessage.setMessage("分页查询工厂信息成功!"); listFactoryMessage.setData(factoryService.listFactory(currPage,tFactory)); }else { listFactoryMessage.setCode(202); listFactoryMessage.setMessage("分页查询工厂信息失败!"); } return listFactoryMessage; } }
6,366
0.669756
0.661861
152
37.328949
22.917694
95
false
false
0
0
0
0
0
0
0.572368
false
false
4
95a30555282c76a6073d80d42986274ae898a76f
36,498,632,125,621
4f1a4c0b036efbe924d27d156ec1010e39088e51
/Aula13 - Vetores/src/br/com/fiap/tds/view/Exemplo03.java
8bc463f1c28a176a429b506e0ca1fa59f3308063
[]
no_license
alisonguima/Domain_Driven_Design
https://github.com/alisonguima/Domain_Driven_Design
4ae1a255f37100e5ea29971c5dfc48f3d80e5be4
0498938c3808a3fee8ce3bbc6c15cf90c9264229
refs/heads/main
2023-03-29T08:13:51.569000
2020-09-19T00:27:21
2020-09-19T00:27:21
268,659,839
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.fiap.tds.view; import br.com.fiap.tds.bean.Boletim; import br.com.fiap.tds.bean.Disciplina; public class Exemplo03 { public static void main(String[] args) { Boletim boletim = new Boletim("Joaozinho", new Disciplina[9]); Disciplina[] vetor = boletim.getDisciplinas(); vetor[0] = new Disciplina("Web", 10); vetor[1] = new Disciplina("Banco de Dados", 9.5f); boletim.setDisciplinas(vetor); System.out.println(boletim.getNome() + " " + boletim.getDisciplinas()[0].getNome() + " " + boletim.getDisciplinas()[0].getNota()); for ( Disciplina item : boletim.getDisciplinas()) { if (item != null) { System.out.println(item.getNome() + " " + item.getNota()); } } } }
UTF-8
Java
720
java
Exemplo03.java
Java
[ { "context": "tring[] args) {\n\n\t\tBoletim boletim = new Boletim(\"Joaozinho\", new Disciplina[9]);\n\t\t\n\t\tDisciplina[] vetor = b", "end": 220, "score": 0.9987255930900574, "start": 211, "tag": "NAME", "value": "Joaozinho" } ]
null
[]
package br.com.fiap.tds.view; import br.com.fiap.tds.bean.Boletim; import br.com.fiap.tds.bean.Disciplina; public class Exemplo03 { public static void main(String[] args) { Boletim boletim = new Boletim("Joaozinho", new Disciplina[9]); Disciplina[] vetor = boletim.getDisciplinas(); vetor[0] = new Disciplina("Web", 10); vetor[1] = new Disciplina("Banco de Dados", 9.5f); boletim.setDisciplinas(vetor); System.out.println(boletim.getNome() + " " + boletim.getDisciplinas()[0].getNome() + " " + boletim.getDisciplinas()[0].getNota()); for ( Disciplina item : boletim.getDisciplinas()) { if (item != null) { System.out.println(item.getNome() + " " + item.getNota()); } } } }
720
0.659722
0.644444
27
25.666666
24.805914
84
false
false
0
0
0
0
0
0
1.925926
false
false
4
62446b8dda8ff27b5fdd68c693faa2da9cb5fd93
37,606,733,676,181
e63d312d447b479e7bfc971e5f9b412bb409dd8e
/VISIEGamePlayback/src/VISIE/scenemanager/SceneObjectManager.java
603bdbdfa7bab6ebed95e1a4c699dd74c8d86e56
[]
no_license
DiveshLala/VirtBask
https://github.com/DiveshLala/VirtBask
6be6ea0c610ef45128cbc3ed71aee8e46f3c8f58
7e8971ab48d4af5c560437d74e722fe449d50312
refs/heads/master
2020-12-24T14:53:37.650000
2015-08-03T06:30:50
2015-08-03T06:30:50
37,406,752
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package VISIE.scenemanager; import Basketball.Ball; import com.jme3.collision.CollisionResult; import com.jme3.collision.CollisionResults; import java.util.ArrayList; import com.jme3.scene.Node; /** * * @author DiveshLala */ public class SceneObjectManager { private static Ball ball; public SceneObjectManager(Ball b){ ball = b; } public static Ball getBall(){ return ball; } public void updateBallPhysics(){ // if(SceneCharacterManager.getCharacterInPossession() instanceof VISIE.characters.Player){ // ball // } // } }
UTF-8
Java
729
java
SceneObjectManager.java
Java
[ { "context": "t;\nimport com.jme3.scene.Node;\n\n/**\n *\n * @author DiveshLala\n */\npublic class SceneObjectManager {\n \n pr", "end": 325, "score": 0.9973524212837219, "start": 315, "tag": "NAME", "value": "DiveshLala" } ]
null
[]
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package VISIE.scenemanager; import Basketball.Ball; import com.jme3.collision.CollisionResult; import com.jme3.collision.CollisionResults; import java.util.ArrayList; import com.jme3.scene.Node; /** * * @author DiveshLala */ public class SceneObjectManager { private static Ball ball; public SceneObjectManager(Ball b){ ball = b; } public static Ball getBall(){ return ball; } public void updateBallPhysics(){ // if(SceneCharacterManager.getCharacterInPossession() instanceof VISIE.characters.Player){ // ball // } // } }
729
0.651578
0.647462
35
19.828571
20.054905
98
false
false
0
0
0
0
0
0
0.314286
false
false
4
738675663b3a89a433c2e5008d3421cf9b31bc30
38,096,359,940,345
b6799b8ad82d0085ad03214dfc0d99e42def26d2
/wealdtech-users-jersey/src/main/java/com/wealdtech/jersey/auth/WealdTokenAuthenticator.java
83fc233464e49c4bdc1b830dcf8e1dab35743c2e
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
wealdtech/wealdtech
https://github.com/wealdtech/wealdtech
2c3e756f49bf089d12308ecc3c89fda5a64916f7
d7cb061d0ef954b38b088dcdb85358c26ec1af01
refs/heads/develop
2020-04-05T14:04:36.010000
2015-06-04T09:21:51
2015-06-04T09:21:51
7,378,306
0
1
null
false
2015-06-04T09:21:11
2012-12-30T16:55:35
2015-05-07T15:23:52
2015-06-04T09:21:10
2,588
0
0
0
Java
null
null
/* * Copyright 2012 - 2015 Weald Technology Trading Limited * * 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.wealdtech.jersey.auth; import com.google.common.base.Objects; import com.google.common.base.Optional; import com.google.inject.Inject; import com.sun.jersey.spi.container.ContainerRequest; import com.wealdtech.*; import com.wealdtech.authentication.*; import com.wealdtech.authorisation.UserAuthorisation; import com.wealdtech.services.UserService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.core.MultivaluedMap; import static com.wealdtech.Preconditions.checkNotNull; /** * Authenticate user with token authentication. */ public final class WealdTokenAuthenticator extends WealdAuthenticator { private static final Logger LOG = LoggerFactory.getLogger(WealdTokenAuthenticator.class); @Inject private WealdTokenAuthenticator(final UserService userService) { super(userService); } @Override public boolean canAuthenticate(final ContainerRequest request) { boolean result = false; try { obtainRequestCredentials(request); result = true; } catch (final DataError de) { // This happens if the request is not authenticated using a token } return result; } /** * Authenticate the user. If the credentials include an identity ID then this identity is the user which will be passed back (if * anything) * * @return A two-tuple containing the authenticated user and credentials; can be <code>absent</code> * @throws ServerError if there is a problem authenticating the credentials */ @Override public Optional<TwoTuple<User, UserAuthorisation>> authenticate(final ContainerRequest request) { final Credentials credentials = obtainRequestCredentials(request); final WID<User> identityId = obtainRequestedIdentityId(request); final Optional<TwoTuple<User, UserAuthorisation>> result; try { final User unauthenticatedUser = obtainUnauthenticatedUser(credentials); if (unauthenticatedUser == null) { throw new DataError.Bad("Credentials do not relate to a user"); } final UserAuthorisation authorisation = authenticateUser(request, unauthenticatedUser, credentials); // At this stage the user has been authenticated User user = unauthenticatedUser; // The token used to access the user will have been removed by the underlying system // Refetch the user with the token removed user = userService.obtain(user.getId()); // Resolve the user to their identity and return them result = Optional.of(resolveIdentity(user, authorisation, identityId)); } catch (final DataError.Bad de) { LOG.debug("Failed to obtain user", de); throw de; } return result; } @Override public Credentials obtainRequestCredentials(final ContainerRequest request) { final MultivaluedMap<String, String> params = request.getQueryParameters(); final String secret = params.getFirst("token"); checkNotNull(secret, "Missing ott parameter"); return TokenCredentials.builder().token(secret).build(); } /** * Authenticate an unauthenticated user * * @param user the unauthenticated user * @param credentials the credentials used to obtain the user * * @return Authorisation for the user * @throws DataError If the authentication fails */ @Override public UserAuthorisation authenticateUser(final ContainerRequest request, final User user, final Credentials credentials) { final TokenCredentials tokenCredentials = (TokenCredentials)credentials; for (final AuthenticationMethod authenticationMethod : user.getAuthenticationMethods()) { if (Objects.equal(authenticationMethod.getType(), TokenCredentials.TOKEN_CREDENTIALS)) { final TokenAuthenticationMethod tokenAuthenticationMethod = WObject.recast(authenticationMethod, TokenAuthenticationMethod.class); if (Objects.equal(tokenAuthenticationMethod.getToken(), tokenCredentials.getToken()) && !authenticationMethod.hasExpired()) { return UserAuthorisation.builder().userId(user.getId()).scope(tokenAuthenticationMethod.getScope()).build(); } } } LOG.info("Failed to authenticate user {} with token authentication", user.getId().toString()); throw new DataError.Authentication("Failed to authenticate user"); } }
UTF-8
Java
4,969
java
WealdTokenAuthenticator.java
Java
[]
null
[]
/* * Copyright 2012 - 2015 Weald Technology Trading Limited * * 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.wealdtech.jersey.auth; import com.google.common.base.Objects; import com.google.common.base.Optional; import com.google.inject.Inject; import com.sun.jersey.spi.container.ContainerRequest; import com.wealdtech.*; import com.wealdtech.authentication.*; import com.wealdtech.authorisation.UserAuthorisation; import com.wealdtech.services.UserService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.core.MultivaluedMap; import static com.wealdtech.Preconditions.checkNotNull; /** * Authenticate user with token authentication. */ public final class WealdTokenAuthenticator extends WealdAuthenticator { private static final Logger LOG = LoggerFactory.getLogger(WealdTokenAuthenticator.class); @Inject private WealdTokenAuthenticator(final UserService userService) { super(userService); } @Override public boolean canAuthenticate(final ContainerRequest request) { boolean result = false; try { obtainRequestCredentials(request); result = true; } catch (final DataError de) { // This happens if the request is not authenticated using a token } return result; } /** * Authenticate the user. If the credentials include an identity ID then this identity is the user which will be passed back (if * anything) * * @return A two-tuple containing the authenticated user and credentials; can be <code>absent</code> * @throws ServerError if there is a problem authenticating the credentials */ @Override public Optional<TwoTuple<User, UserAuthorisation>> authenticate(final ContainerRequest request) { final Credentials credentials = obtainRequestCredentials(request); final WID<User> identityId = obtainRequestedIdentityId(request); final Optional<TwoTuple<User, UserAuthorisation>> result; try { final User unauthenticatedUser = obtainUnauthenticatedUser(credentials); if (unauthenticatedUser == null) { throw new DataError.Bad("Credentials do not relate to a user"); } final UserAuthorisation authorisation = authenticateUser(request, unauthenticatedUser, credentials); // At this stage the user has been authenticated User user = unauthenticatedUser; // The token used to access the user will have been removed by the underlying system // Refetch the user with the token removed user = userService.obtain(user.getId()); // Resolve the user to their identity and return them result = Optional.of(resolveIdentity(user, authorisation, identityId)); } catch (final DataError.Bad de) { LOG.debug("Failed to obtain user", de); throw de; } return result; } @Override public Credentials obtainRequestCredentials(final ContainerRequest request) { final MultivaluedMap<String, String> params = request.getQueryParameters(); final String secret = params.getFirst("token"); checkNotNull(secret, "Missing ott parameter"); return TokenCredentials.builder().token(secret).build(); } /** * Authenticate an unauthenticated user * * @param user the unauthenticated user * @param credentials the credentials used to obtain the user * * @return Authorisation for the user * @throws DataError If the authentication fails */ @Override public UserAuthorisation authenticateUser(final ContainerRequest request, final User user, final Credentials credentials) { final TokenCredentials tokenCredentials = (TokenCredentials)credentials; for (final AuthenticationMethod authenticationMethod : user.getAuthenticationMethods()) { if (Objects.equal(authenticationMethod.getType(), TokenCredentials.TOKEN_CREDENTIALS)) { final TokenAuthenticationMethod tokenAuthenticationMethod = WObject.recast(authenticationMethod, TokenAuthenticationMethod.class); if (Objects.equal(tokenAuthenticationMethod.getToken(), tokenCredentials.getToken()) && !authenticationMethod.hasExpired()) { return UserAuthorisation.builder().userId(user.getId()).scope(tokenAuthenticationMethod.getScope()).build(); } } } LOG.info("Failed to authenticate user {} with token authentication", user.getId().toString()); throw new DataError.Authentication("Failed to authenticate user"); } }
4,969
0.736164
0.733347
139
34.748203
42.800877
309
false
false
0
0
0
0
0
0
0.438849
false
false
4
b69b0596df5d17762386d3fe812096493c14d71c
23,038,204,645,638
cf4d8112560f2ab7833a3567967796e9adfe6e5e
/JavaDemo/src/data/object/operators/AutoIncDecOpsDemo.java
06bbb1009f2923c3e5bb8d2b37f7a823b807c885
[]
no_license
eterinfi/java
https://github.com/eterinfi/java
3f19963bf1d2d0ee844951cd2ca3123ef7dfb5f6
4acd1151fce5660b3c2d7b04368a3c99ed9339d9
refs/heads/master
2020-04-17T22:17:34.961000
2016-11-18T14:01:43
2016-11-18T14:01:43
67,972,971
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package data.object.operators; public class AutoIncDecOpsDemo { public static void main(String[] args) { int a = 3; // 定义一个变量 int b = ++a; // 自增运算 int c = 3; int d = --c; // 自减运算 System.out.println("进行自增运算后的值等于 " + b); System.out.println("进行自减运算后的值等于 " + d); int e = 5; // 定义一个变量 int f = 5; int x = 2 * ++e; int y = 2 * f++; System.out.println("自增运算符前缀运算后 e= " + e + ", x= " + x); System.out.println("自增运算符前缀运算后 f= " + f + ", y= " + y); } }
UTF-8
Java
594
java
AutoIncDecOpsDemo.java
Java
[]
null
[]
package data.object.operators; public class AutoIncDecOpsDemo { public static void main(String[] args) { int a = 3; // 定义一个变量 int b = ++a; // 自增运算 int c = 3; int d = --c; // 自减运算 System.out.println("进行自增运算后的值等于 " + b); System.out.println("进行自减运算后的值等于 " + d); int e = 5; // 定义一个变量 int f = 5; int x = 2 * ++e; int y = 2 * f++; System.out.println("自增运算符前缀运算后 e= " + e + ", x= " + x); System.out.println("自增运算符前缀运算后 f= " + f + ", y= " + y); } }
594
0.557447
0.544681
19
23.789474
17.15741
57
false
false
0
0
0
0
0
0
2.263158
false
false
4
dcf7c4c611ecab143cba00375b102a56c29af62f
35,691,178,281,354
ddb9b29586e2ac59930484e562c7e62e8fcf2b98
/app/src/main/java/com/example/pdam/views/propiedad/PropInfo.java
da2b010a34cfe1b736b703fa319be02f8f08df8a
[]
no_license
mojonovka/pDAM
https://github.com/mojonovka/pDAM
40493a456e24134fbb65c628e855b91139158508
24c225e49def713c8bb17c24a3628a1c134e3acd
refs/heads/master
2023-06-06T01:25:42.799000
2021-06-23T12:04:27
2021-06-23T12:04:27
307,977,870
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.pdam.views.propiedad; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.os.PersistableBundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.example.pdam.R; import com.example.pdam.models.Inmueble; import com.example.pdam.models.User; import com.example.pdam.providers.PropiedadProvider; import com.example.pdam.providers.UserProvider; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapView; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.ValueEventListener; import com.squareup.picasso.Picasso; public class PropInfo extends AppCompatActivity implements OnMapReadyCallback { private String usuarioID; private String inmbID; private TextView tvInfoNombreDescriptivo; private ImageView ivInfoFoto; private TextView tvInfoDescripcion; private TextView tvInfoDireccion; private Button btnInfoContactar; private MapView mMapView; private static final String MAPVIEW_BUNDLE_KEY = "MapViewBundleKey"; private PropiedadProvider mPropiedadProvider; private Inmueble inmbl; private User usuario; private UserProvider mUserProvider; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_prop_info); usuarioID = getIntent().getStringExtra("usuarioID"); inmbID = getIntent().getStringExtra("inmbID"); getSupportActionBar().setDisplayHomeAsUpEnabled(true); Bundle mapViewBundle = null; if (savedInstanceState != null) { mapViewBundle = savedInstanceState.getBundle(MAPVIEW_BUNDLE_KEY); } mMapView = findViewById(R.id.infoMapa); mMapView.onCreate(mapViewBundle); mMapView.getMapAsync(this); inicializarComponentes(); rellenarPropiedad(inmbID); setlisteners(); } private void setlisteners() { btnInfoContactar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //iniciar chat mUserProvider.getUsuarioById(inmbl.getInmbPropID()).addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull @org.jetbrains.annotations.NotNull DataSnapshot snapshot) { usuario = new User(snapshot.getValue(User.class)); Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:" + usuario.getuEmail())); startActivity(intent); } @Override public void onCancelled(@NonNull @org.jetbrains.annotations.NotNull DatabaseError error) { } }); } }); } private void inicializarComponentes() { mPropiedadProvider = new PropiedadProvider(); mUserProvider = new UserProvider(); tvInfoNombreDescriptivo = findViewById(R.id.infoNombreDescriptivo); ivInfoFoto = findViewById(R.id.infoFoto); tvInfoDescripcion = findViewById(R.id.infoDescripcion); tvInfoDireccion = findViewById(R.id.infoDireccion); btnInfoContactar = findViewById(R.id.infoBTNContactar); } private void rellenarPropiedad(String inmbID) { mPropiedadProvider.getInmbById(inmbID).addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { inmbl = new Inmueble(snapshot.getValue(Inmueble.class)); tvInfoNombreDescriptivo.setText(inmbl.getInmbNombreDesc()); Picasso.get().load(inmbl.getInmbFotoURI()).into(ivInfoFoto); tvInfoDescripcion.setText("Tipo: " + inmbl.getInmbTipo() + "\n" + "Precio: " + inmbl.getInmbPrecio() + "€ / " + inmbl.getInmbPeriodo() + " \n\nDescripción: \n" + inmbl.getInmbDescCompleta()); tvInfoDireccion.setText("Dirección: " + inmbl.getInmbProvincia() + "\n" + inmbl.getInmbMunicipio() + " : " + inmbl.getInmbCP() + "\n" + inmbl.getInmbDireccion()); mMapView.getMapAsync(new OnMapReadyCallback() { @Override public void onMapReady(GoogleMap googleMap) { LatLng pos = new LatLng(inmbl.getInmbGEOLat(),inmbl.getInmbGEOLng()); googleMap.addMarker(new MarkerOptions().position(pos).title("*")); googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(pos, 15.5f), 4000, null); } }); } @Override public void onCancelled(@NonNull DatabaseError error) { } }); } @Override public void onMapReady(GoogleMap googleMap) { //googleMap.addMarker(new MarkerOptions().position(new LatLng(0,0)).title("Marker")); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != 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. googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() { @Override public void onMapClick(LatLng latLng) { Uri gmmIntentUri = Uri.parse("geo:0,0?q=" + inmbl.getInmbGEOLat() + "," + inmbl.getInmbGEOLng()); Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri); startActivity(mapIntent); } }); return; } googleMap.setMyLocationEnabled(true); } @Override public void onSaveInstanceState(@NonNull Bundle outState, @NonNull PersistableBundle outPersistentState) { super.onSaveInstanceState(outState, outPersistentState); Bundle mapViewBundle = outState.getBundle(MAPVIEW_BUNDLE_KEY); if (mapViewBundle == null){ mapViewBundle = new Bundle(); outState.putBundle(MAPVIEW_BUNDLE_KEY, mapViewBundle); } mMapView.onSaveInstanceState(mapViewBundle); } @Override public void onResume() { super.onResume(); mMapView.onResume(); } @Override public void onStart() { super.onStart(); mMapView.onStart(); } @Override public void onStop() { super.onStop(); mMapView.onStop(); } @Override public void onPause() { super.onPause(); mMapView.onPause(); } @Override public void onDestroy() { super.onDestroy(); mMapView.onDestroy(); } @Override public void onLowMemory() { super.onLowMemory(); mMapView.onLowMemory(); } }
UTF-8
Java
7,986
java
PropInfo.java
Java
[ { "context": " static final String MAPVIEW_BUNDLE_KEY = \"MapViewBundleKey\";\n\n private PropiedadProvider mPropiedadPro", "end": 1616, "score": 0.6143695712089539, "start": 1610, "tag": "KEY", "value": "Bundle" } ]
null
[]
package com.example.pdam.views.propiedad; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.os.PersistableBundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.example.pdam.R; import com.example.pdam.models.Inmueble; import com.example.pdam.models.User; import com.example.pdam.providers.PropiedadProvider; import com.example.pdam.providers.UserProvider; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapView; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.ValueEventListener; import com.squareup.picasso.Picasso; public class PropInfo extends AppCompatActivity implements OnMapReadyCallback { private String usuarioID; private String inmbID; private TextView tvInfoNombreDescriptivo; private ImageView ivInfoFoto; private TextView tvInfoDescripcion; private TextView tvInfoDireccion; private Button btnInfoContactar; private MapView mMapView; private static final String MAPVIEW_BUNDLE_KEY = "MapViewBundleKey"; private PropiedadProvider mPropiedadProvider; private Inmueble inmbl; private User usuario; private UserProvider mUserProvider; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_prop_info); usuarioID = getIntent().getStringExtra("usuarioID"); inmbID = getIntent().getStringExtra("inmbID"); getSupportActionBar().setDisplayHomeAsUpEnabled(true); Bundle mapViewBundle = null; if (savedInstanceState != null) { mapViewBundle = savedInstanceState.getBundle(MAPVIEW_BUNDLE_KEY); } mMapView = findViewById(R.id.infoMapa); mMapView.onCreate(mapViewBundle); mMapView.getMapAsync(this); inicializarComponentes(); rellenarPropiedad(inmbID); setlisteners(); } private void setlisteners() { btnInfoContactar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //iniciar chat mUserProvider.getUsuarioById(inmbl.getInmbPropID()).addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull @org.jetbrains.annotations.NotNull DataSnapshot snapshot) { usuario = new User(snapshot.getValue(User.class)); Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:" + usuario.getuEmail())); startActivity(intent); } @Override public void onCancelled(@NonNull @org.jetbrains.annotations.NotNull DatabaseError error) { } }); } }); } private void inicializarComponentes() { mPropiedadProvider = new PropiedadProvider(); mUserProvider = new UserProvider(); tvInfoNombreDescriptivo = findViewById(R.id.infoNombreDescriptivo); ivInfoFoto = findViewById(R.id.infoFoto); tvInfoDescripcion = findViewById(R.id.infoDescripcion); tvInfoDireccion = findViewById(R.id.infoDireccion); btnInfoContactar = findViewById(R.id.infoBTNContactar); } private void rellenarPropiedad(String inmbID) { mPropiedadProvider.getInmbById(inmbID).addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { inmbl = new Inmueble(snapshot.getValue(Inmueble.class)); tvInfoNombreDescriptivo.setText(inmbl.getInmbNombreDesc()); Picasso.get().load(inmbl.getInmbFotoURI()).into(ivInfoFoto); tvInfoDescripcion.setText("Tipo: " + inmbl.getInmbTipo() + "\n" + "Precio: " + inmbl.getInmbPrecio() + "€ / " + inmbl.getInmbPeriodo() + " \n\nDescripción: \n" + inmbl.getInmbDescCompleta()); tvInfoDireccion.setText("Dirección: " + inmbl.getInmbProvincia() + "\n" + inmbl.getInmbMunicipio() + " : " + inmbl.getInmbCP() + "\n" + inmbl.getInmbDireccion()); mMapView.getMapAsync(new OnMapReadyCallback() { @Override public void onMapReady(GoogleMap googleMap) { LatLng pos = new LatLng(inmbl.getInmbGEOLat(),inmbl.getInmbGEOLng()); googleMap.addMarker(new MarkerOptions().position(pos).title("*")); googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(pos, 15.5f), 4000, null); } }); } @Override public void onCancelled(@NonNull DatabaseError error) { } }); } @Override public void onMapReady(GoogleMap googleMap) { //googleMap.addMarker(new MarkerOptions().position(new LatLng(0,0)).title("Marker")); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != 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. googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() { @Override public void onMapClick(LatLng latLng) { Uri gmmIntentUri = Uri.parse("geo:0,0?q=" + inmbl.getInmbGEOLat() + "," + inmbl.getInmbGEOLng()); Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri); startActivity(mapIntent); } }); return; } googleMap.setMyLocationEnabled(true); } @Override public void onSaveInstanceState(@NonNull Bundle outState, @NonNull PersistableBundle outPersistentState) { super.onSaveInstanceState(outState, outPersistentState); Bundle mapViewBundle = outState.getBundle(MAPVIEW_BUNDLE_KEY); if (mapViewBundle == null){ mapViewBundle = new Bundle(); outState.putBundle(MAPVIEW_BUNDLE_KEY, mapViewBundle); } mMapView.onSaveInstanceState(mapViewBundle); } @Override public void onResume() { super.onResume(); mMapView.onResume(); } @Override public void onStart() { super.onStart(); mMapView.onStart(); } @Override public void onStop() { super.onStop(); mMapView.onStop(); } @Override public void onPause() { super.onPause(); mMapView.onPause(); } @Override public void onDestroy() { super.onDestroy(); mMapView.onDestroy(); } @Override public void onLowMemory() { super.onLowMemory(); mMapView.onLowMemory(); } }
7,986
0.65109
0.649712
225
34.48
35.888233
259
false
false
0
0
0
0
0
0
0.524444
false
false
4
ed1657c5152284178018461db5754f31eafa55ac
39,719,857,563,099
098aff8e23c5c5a49e94b22163819480588ebd6d
/src/main/java/net/haesleinhuepf/clij2/plugins/EuclideanDistanceFromLabelCentroidMap.java
3ca55a049a5e9f3fbe63e769a9d2fedd22f954e4
[ "BSD-3-Clause" ]
permissive
clij/clij2
https://github.com/clij/clij2
d274f272656ba1c9182cf97a2b9296ebcd62b95c
154150e60596e76f2b0773ef84691bebf5809f24
refs/heads/master
2023-04-10T13:38:27.230000
2022-08-06T15:55:46
2022-08-06T15:55:46
190,929,227
39
11
NOASSERTION
false
2023-03-02T19:15:26
2019-06-08T19:54:46
2023-02-16T22:00:18
2022-08-06T15:59:34
51,594
37
14
12
Java
false
false
package net.haesleinhuepf.clij2.plugins; import ij.IJ; import ij.ImageJ; import ij.ImagePlus; import ij.measure.ResultsTable; import net.haesleinhuepf.clij.clearcl.ClearCL; import net.haesleinhuepf.clij.clearcl.ClearCLBuffer; import net.haesleinhuepf.clij.coremem.enums.NativeTypeEnum; import net.haesleinhuepf.clij.macro.CLIJMacroPlugin; import net.haesleinhuepf.clij.macro.CLIJOpenCLProcessor; import net.haesleinhuepf.clij.macro.documentation.OffersDocumentation; import net.haesleinhuepf.clij2.AbstractCLIJ2Plugin; import net.haesleinhuepf.clij2.CLIJ2; import net.haesleinhuepf.clij2.plugins.OnlyzeroOverwriteMaximumBox; import net.haesleinhuepf.clij2.plugins.StatisticsOfLabelledPixels; import net.haesleinhuepf.clij2.utilities.HasClassifiedInputOutput; import net.haesleinhuepf.clij2.utilities.IsCategorized; import org.scijava.plugin.Plugin; import java.util.HashMap; @Plugin(type = CLIJMacroPlugin.class, name = "CLIJ2_euclideanDistanceFromLabelCentroidMap") public class EuclideanDistanceFromLabelCentroidMap extends AbstractCLIJ2Plugin implements CLIJMacroPlugin, CLIJOpenCLProcessor, OffersDocumentation, IsCategorized, HasClassifiedInputOutput { @Override public String getInputType() { return "Label Image"; } @Override public String getOutputType() { return "Image"; } @Override public String getParameterHelpText() { return "Image labelmap_input, ByRef Image destination"; } @Override public boolean executeCL() { return euclideanDistanceFromLabelCentroidMap(getCLIJ2(), (ClearCLBuffer) args[0], (ClearCLBuffer) args[1]); } public static boolean euclideanDistanceFromLabelCentroidMap(CLIJ2 clij2, ClearCLBuffer pushed, ClearCLBuffer result) { int number_of_labels = (int)clij2.maximumOfAllPixels(pushed); ClearCLBuffer pointlist = clij2.create(number_of_labels + 1,pushed.getDimension(), 1); clij2.centroidsOfBackgroundAndLabels(pushed, pointlist); HashMap<String, Object> parameters = new HashMap(); parameters.put("src", pushed); parameters.put("pointlist", pointlist); parameters.put("dst", result); clij2.execute(EuclideanDistanceFromLabelCentroidMap.class, "euclidean_distance_from_label_centroid_map_x.cl", "euclidean_distance_from_label_centroid_map", result.getDimensions(), result.getDimensions(), parameters); pointlist.close(); return true; } @Override public ClearCLBuffer createOutputBufferFromSource(ClearCLBuffer input) { return getCLIJ2().create(input.getDimensions(), NativeTypeEnum.Float); } @Override public String getDescription() { return "Takes a label map, determines the centroids of all labels and writes the distance of all labelled pixels to their centroid in the result image.\nBackground pixels stay zero."; } @Override public String getAvailableForDimensions() { return "2D, 3D"; } @Override public String getCategories() { return "Label, Measurements"; } }
UTF-8
Java
3,072
java
EuclideanDistanceFromLabelCentroidMap.java
Java
[]
null
[]
package net.haesleinhuepf.clij2.plugins; import ij.IJ; import ij.ImageJ; import ij.ImagePlus; import ij.measure.ResultsTable; import net.haesleinhuepf.clij.clearcl.ClearCL; import net.haesleinhuepf.clij.clearcl.ClearCLBuffer; import net.haesleinhuepf.clij.coremem.enums.NativeTypeEnum; import net.haesleinhuepf.clij.macro.CLIJMacroPlugin; import net.haesleinhuepf.clij.macro.CLIJOpenCLProcessor; import net.haesleinhuepf.clij.macro.documentation.OffersDocumentation; import net.haesleinhuepf.clij2.AbstractCLIJ2Plugin; import net.haesleinhuepf.clij2.CLIJ2; import net.haesleinhuepf.clij2.plugins.OnlyzeroOverwriteMaximumBox; import net.haesleinhuepf.clij2.plugins.StatisticsOfLabelledPixels; import net.haesleinhuepf.clij2.utilities.HasClassifiedInputOutput; import net.haesleinhuepf.clij2.utilities.IsCategorized; import org.scijava.plugin.Plugin; import java.util.HashMap; @Plugin(type = CLIJMacroPlugin.class, name = "CLIJ2_euclideanDistanceFromLabelCentroidMap") public class EuclideanDistanceFromLabelCentroidMap extends AbstractCLIJ2Plugin implements CLIJMacroPlugin, CLIJOpenCLProcessor, OffersDocumentation, IsCategorized, HasClassifiedInputOutput { @Override public String getInputType() { return "Label Image"; } @Override public String getOutputType() { return "Image"; } @Override public String getParameterHelpText() { return "Image labelmap_input, ByRef Image destination"; } @Override public boolean executeCL() { return euclideanDistanceFromLabelCentroidMap(getCLIJ2(), (ClearCLBuffer) args[0], (ClearCLBuffer) args[1]); } public static boolean euclideanDistanceFromLabelCentroidMap(CLIJ2 clij2, ClearCLBuffer pushed, ClearCLBuffer result) { int number_of_labels = (int)clij2.maximumOfAllPixels(pushed); ClearCLBuffer pointlist = clij2.create(number_of_labels + 1,pushed.getDimension(), 1); clij2.centroidsOfBackgroundAndLabels(pushed, pointlist); HashMap<String, Object> parameters = new HashMap(); parameters.put("src", pushed); parameters.put("pointlist", pointlist); parameters.put("dst", result); clij2.execute(EuclideanDistanceFromLabelCentroidMap.class, "euclidean_distance_from_label_centroid_map_x.cl", "euclidean_distance_from_label_centroid_map", result.getDimensions(), result.getDimensions(), parameters); pointlist.close(); return true; } @Override public ClearCLBuffer createOutputBufferFromSource(ClearCLBuffer input) { return getCLIJ2().create(input.getDimensions(), NativeTypeEnum.Float); } @Override public String getDescription() { return "Takes a label map, determines the centroids of all labels and writes the distance of all labelled pixels to their centroid in the result image.\nBackground pixels stay zero."; } @Override public String getAvailableForDimensions() { return "2D, 3D"; } @Override public String getCategories() { return "Label, Measurements"; } }
3,072
0.752279
0.744141
84
35.57143
42.945503
224
false
false
0
0
0
0
0
0
0.75
false
false
4
5d5ed3ac11fe59fafd4d555e5ef9fc1ab155622d
38,199,439,162,180
e7eb4791804e52a7733690a99b85a144a8644f05
/app/src/main/java/com/yang/bill/presenter/contract/LandContract.java
2569e70c38460f91910a3eaa62654caca7e1c471
[]
no_license
yangaoo/BillApp
https://github.com/yangaoo/BillApp
2ccea74afa87c5afd176816b11a8144fc86ae459
2fb7199a4433595df7aa5a2b989fe7cf5d734c0a
refs/heads/master
2022-01-27T02:10:13.255000
2019-06-23T02:44:02
2019-06-23T02:44:09
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yang.bill.presenter.contract; import com.yang.bill.base.BaseContract; import com.yang.bill.model.bean.remote.User; /** * 登录Contract */ public interface LandContract extends BaseContract { interface ViewRendererRenderer extends BaseViewRenderer { void landSuccess(User user); void showErrorMsg(String msg); } interface Presenter extends BaseContract.BasePresenter<ViewRendererRenderer>{ /** * 用户登陆 */ void login(String username, String password); /** * 用户注册 */ void signup(String username, String password); } }
UTF-8
Java
653
java
LandContract.java
Java
[]
null
[]
package com.yang.bill.presenter.contract; import com.yang.bill.base.BaseContract; import com.yang.bill.model.bean.remote.User; /** * 登录Contract */ public interface LandContract extends BaseContract { interface ViewRendererRenderer extends BaseViewRenderer { void landSuccess(User user); void showErrorMsg(String msg); } interface Presenter extends BaseContract.BasePresenter<ViewRendererRenderer>{ /** * 用户登陆 */ void login(String username, String password); /** * 用户注册 */ void signup(String username, String password); } }
653
0.652449
0.652449
30
20.1
22.833237
81
false
false
0
0
0
0
0
0
0.3
false
false
4
bd6604a6fe738eb7042f209d4222133c309993d7
2,765,958,954,986
4dfe548629a557a2e0825cf9ec1e1b7e8ee0c42d
/src/main/java/com/cffex/auctionsystem/controller/JsonTest.java
c95f0dac375bc92b881c0e362a07133e4e8ec97e
[]
no_license
lisycn/auctionsystem
https://github.com/lisycn/auctionsystem
d7dfd144afdda27541e496e3c31eecb9189fa8e3
dbbced2f43e09d3b4dc47e8ff9e4a1f593e7f083
refs/heads/master
2020-04-03T00:59:15.275000
2018-07-26T09:54:57
2018-07-26T09:54:57
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cffex.auctionsystem.controller; import com.cffex.auctionsystem.bean.User; import com.google.gson.Gson; public class JsonTest { public static void main(String[] args) { User user = new User(); Gson gson = new Gson(); user.setAge(18); user.setId(1); user.setName("yhx"); user.setSex("男"); String userObject = gson.toJson(user); System.out.println(userObject); User user1 = gson.fromJson(userObject, User.class); System.out.println(user1); } }
UTF-8
Java
501
java
JsonTest.java
Java
[ { "context": "er.setAge(18);\r\n\t\tuser.setId(1);\r\n\t\tuser.setName(\"yhx\");\r\n\t\tuser.setSex(\"男\");\r\n\t\tString userObject = gs", "end": 304, "score": 0.9981456995010376, "start": 301, "tag": "USERNAME", "value": "yhx" } ]
null
[]
package com.cffex.auctionsystem.controller; import com.cffex.auctionsystem.bean.User; import com.google.gson.Gson; public class JsonTest { public static void main(String[] args) { User user = new User(); Gson gson = new Gson(); user.setAge(18); user.setId(1); user.setName("yhx"); user.setSex("男"); String userObject = gson.toJson(user); System.out.println(userObject); User user1 = gson.fromJson(userObject, User.class); System.out.println(user1); } }
501
0.679359
0.669339
20
22.950001
15.73682
53
false
false
0
0
0
0
0
0
1.85
false
false
4
157fd633c504ee8765e032c90fc2a2376fca1a6e
9,010,841,456,862
2791fd564a3af6596cdd3630379f0e02502bd29c
/app/src/main/java/com/example/ski/adapter/ContactViewHolder.java
36e3f4e848efd84970f502058f98a5e929cc2aa5
[]
no_license
vgholcom/skislopesnow
https://github.com/vgholcom/skislopesnow
7a8e61c6676e92dbf8d3be47243a239cdd7a3cb7
2bd4decd000bcf43b8b05d40924b55329b313257
refs/heads/master
2021-02-09T00:03:12.713000
2020-03-19T00:16:56
2020-03-19T00:16:56
244,214,062
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.ski.adapter; import androidx.recyclerview.widget.RecyclerView; import android.content.Context; import android.content.Intent; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.example.ski.R; import com.example.ski.ResortActivity; public class ContactViewHolder extends RecyclerView.ViewHolder { public TextView resort; public ContactViewHolder(View itemView) { super(itemView); resort = (TextView)itemView.findViewById(R.id.resortTextView); } }
UTF-8
Java
553
java
ContactViewHolder.java
Java
[]
null
[]
package com.example.ski.adapter; import androidx.recyclerview.widget.RecyclerView; import android.content.Context; import android.content.Intent; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.example.ski.R; import com.example.ski.ResortActivity; public class ContactViewHolder extends RecyclerView.ViewHolder { public TextView resort; public ContactViewHolder(View itemView) { super(itemView); resort = (TextView)itemView.findViewById(R.id.resortTextView); } }
553
0.775769
0.775769
24
22.041666
21.072254
70
false
false
0
0
0
0
0
0
0.5
false
false
4
c80faf32d68427d63177b16566f7c567edbfff3c
21,174,188,824,755
cfe1727e83c860fab17c47b989f8966cf918aea2
/TodoVezhba/src/main/java/com/codeacademy/todo5/vezhba/TodoVezhba/model/User.java
91deb3231368007b0c66b63018e29f9680299c30
[]
no_license
angjel-afk/hello-world
https://github.com/angjel-afk/hello-world
1a877be17d6edd6e8556a01e8ef41f7d21deb823
cf7d954dc67e931cba66b3c62887ad58b40385b7
refs/heads/main
2023-01-24T13:32:59.466000
2020-11-26T16:31:15
2020-11-26T16:31:15
313,373,260
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.codeacademy.todo5.vezhba.TodoVezhba.model; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name = "USER") public class User { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE) private Long id; private String firstName; private String lastName; private String email; private int age; private String address; private String username; private String password; private String confirmPassword; private String aboutMe; private String gender; @OneToMany(mappedBy = "user", cascade = CascadeType.ALL) private List<Projects> projects = new ArrayList<>(); public User(String firstName, String lastName, String email, int age, String address, String username, String password, String confirmPassword, String aboutMe, String gender) { super(); this.firstName = firstName; this.lastName = lastName; this.email = email; this.age = age; this.address = address; this.username = username; this.password = password; this.confirmPassword = confirmPassword; this.aboutMe = aboutMe; this.gender=gender; } public User() { } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getConfirmPassword() { return confirmPassword; } public void setConfirmPassword(String confirmPassword) { this.confirmPassword = confirmPassword; } public String getAboutMe() { return aboutMe; } public void setAboutMe(String aboutMe) { this.aboutMe = aboutMe; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } }
UTF-8
Java
2,766
java
User.java
Java
[ { "context": "<>();\r\n\t\r\n\t\r\n\tpublic User(String firstName, String lastName, String email, int age, String address, String us", "end": 945, "score": 0.6900822520256042, "start": 937, "tag": "NAME", "value": "lastName" }, { "context": ", String gender) {\r\n\t\tsuper();\r\n\t\tthis.firstName = firstName;\r\n\t\tthis.lastName = lastName;\r\n\t\tthis.email = ema", "end": 1122, "score": 0.6420314311981201, "start": 1113, "tag": "NAME", "value": "firstName" }, { "context": "\r\n\t\tthis.firstName = firstName;\r\n\t\tthis.lastName = lastName;\r\n\t\tthis.email = email;\r\n\t\tthis.age = age;\r\n\t\tthi", "end": 1151, "score": 0.8873505592346191, "start": 1143, "tag": "NAME", "value": "lastName" }, { "context": "age;\r\n\t\tthis.address = address;\r\n\t\tthis.username = username;\r\n\t\tthis.password = password;\r\n\t\tthis.confirmPass", "end": 1249, "score": 0.9975372552871704, "start": 1241, "tag": "USERNAME", "value": "username" }, { "context": "s;\r\n\t\tthis.username = username;\r\n\t\tthis.password = password;\r\n\t\tthis.confirmPassword = confirmPassword;\r\n\t\tth", "end": 1278, "score": 0.9991070628166199, "start": 1270, "tag": "PASSWORD", "value": "password" }, { "context": "his.password = password;\r\n\t\tthis.confirmPassword = confirmPassword;\r\n\t\tthis.aboutMe = aboutMe;\r\n\t\tthis.gender=gender", "end": 1321, "score": 0.9634077548980713, "start": 1306, "tag": "PASSWORD", "value": "confirmPassword" }, { "context": "s;\r\n\t}\r\n\r\n\tpublic String getUsername() {\r\n\t\treturn username;\r\n\t}\r\n\r\n\tpublic void setUsername(String username)", "end": 2094, "score": 0.9847946166992188, "start": 2086, "tag": "USERNAME", "value": "username" }, { "context": " setUsername(String username) {\r\n\t\tthis.username = username;\r\n\t}\r\n\r\n\tpublic String getPassword() {\r\n\t\treturn ", "end": 2174, "score": 0.9877378940582275, "start": 2166, "tag": "USERNAME", "value": "username" } ]
null
[]
package com.codeacademy.todo5.vezhba.TodoVezhba.model; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name = "USER") public class User { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE) private Long id; private String firstName; private String lastName; private String email; private int age; private String address; private String username; private String password; private String confirmPassword; private String aboutMe; private String gender; @OneToMany(mappedBy = "user", cascade = CascadeType.ALL) private List<Projects> projects = new ArrayList<>(); public User(String firstName, String lastName, String email, int age, String address, String username, String password, String confirmPassword, String aboutMe, String gender) { super(); this.firstName = firstName; this.lastName = lastName; this.email = email; this.age = age; this.address = address; this.username = username; this.password = <PASSWORD>; this.confirmPassword = <PASSWORD>; this.aboutMe = aboutMe; this.gender=gender; } public User() { } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getConfirmPassword() { return confirmPassword; } public void setConfirmPassword(String confirmPassword) { this.confirmPassword = confirmPassword; } public String getAboutMe() { return aboutMe; } public void setAboutMe(String aboutMe) { this.aboutMe = aboutMe; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } }
2,763
0.694143
0.693782
138
18.043478
18.022076
103
false
false
0
0
0
0
0
0
1.434783
false
false
4
dde21b79cf1cdde9596f5a2b8b4b9c46ea1b2af9
33,268,816,740,124
c08988829065fbf28abcb6ece219b108ee4356fd
/src/test/java/se/patrikbergman/java/annotations/TestResourcesRule.java
67b5108590838674ac82d4de25aec7e913ea32cc
[]
no_license
karlpatrikbergman/java-examples
https://github.com/karlpatrikbergman/java-examples
b74d0816e9241dd93dcaf4353819b158f3bd3b46
4ebc1e34a341e30d71a53e534c45220782ef7e79
refs/heads/master
2021-01-18T23:21:21.789000
2017-03-27T08:28:06
2017-03-27T08:28:06
24,090,687
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package se.patrikbergman.java.annotations; import com.google.common.base.Preconditions; import org.junit.rules.ExternalResource; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @SuppressWarnings({"NullArgumentToVariableArgMethod", "unchecked"}) public class TestResourcesRule extends ExternalResource { private final Class target; public TestResourcesRule(Class target) { Preconditions.checkNotNull(target, "Test class cannot be null"); this.target = target; } @Override public void before() throws IllegalAccessException, IOException, InstantiationException, NoSuchMethodException, InvocationTargetException { for (Field field : target.getFields()) { if (field.isAnnotationPresent(InjectTestResource.class)) { final InjectTestResource injectTestResource = field.getAnnotation(InjectTestResource.class); final Class factoryClass = injectTestResource.getFactory(); final Object factoryInstance = factoryClass.newInstance(); final String methodName = injectTestResource.getMethod(); final Method method = factoryClass.getMethod(methodName, null); method.setAccessible(true); final Object value = method.invoke(factoryInstance, null); field.set(target, value); } } } }
UTF-8
Java
1,320
java
TestResourcesRule.java
Java
[]
null
[]
package se.patrikbergman.java.annotations; import com.google.common.base.Preconditions; import org.junit.rules.ExternalResource; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @SuppressWarnings({"NullArgumentToVariableArgMethod", "unchecked"}) public class TestResourcesRule extends ExternalResource { private final Class target; public TestResourcesRule(Class target) { Preconditions.checkNotNull(target, "Test class cannot be null"); this.target = target; } @Override public void before() throws IllegalAccessException, IOException, InstantiationException, NoSuchMethodException, InvocationTargetException { for (Field field : target.getFields()) { if (field.isAnnotationPresent(InjectTestResource.class)) { final InjectTestResource injectTestResource = field.getAnnotation(InjectTestResource.class); final Class factoryClass = injectTestResource.getFactory(); final Object factoryInstance = factoryClass.newInstance(); final String methodName = injectTestResource.getMethod(); final Method method = factoryClass.getMethod(methodName, null); method.setAccessible(true); final Object value = method.invoke(factoryInstance, null); field.set(target, value); } } } }
1,320
0.789394
0.789394
35
36.714287
31.454794
140
false
false
0
0
0
0
0
0
2.257143
false
false
4
40bae082745c5651a6d49ea183b3efe3ae291430
31,250,182,094,154
b6792ea7043914931c563918f6d3659e3296ade0
/syswave-erp-ui/src/com/syswave/forms/databinding/PlanMantenimientosTableModel.java
9086dc90b06697ca44fe59ecc035814501078393
[]
no_license
vbuciov/syswave-erp
https://github.com/vbuciov/syswave-erp
53ad3d8ff26dcb403e1332c630f8b3b7e1e03cce
ef86b8a96cd0205ce2bdde0c6428329d1f1d4292
refs/heads/master
2023-01-18T21:56:01.201000
2020-11-17T00:59:43
2020-11-17T00:59:43
140,904,673
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.syswave.forms.databinding; import com.syswave.entidades.miempresa.PlanMantenimiento; import com.syswave.swing.models.POJOTableModel; import com.syswave.swing.table.events.TableModelCellFormatEvent; import com.syswave.swing.table.events.TableModelGetValueEvent; import com.syswave.swing.table.events.TableModelSetValueEvent; /** * * @author Victor Manuel Bucio Vargas */ public class PlanMantenimientosTableModel extends POJOTableModel<PlanMantenimiento> { //-------------------------------------------------------------------- public PlanMantenimientosTableModel(String[] columns) { super(columns); } //-------------------------------------------------------------------- @Override public void onSetValueAt(TableModelSetValueEvent<PlanMantenimiento> e) { if (e.getNewValue() != null) { PlanMantenimiento actual = e.getItem(); switch (e.getDataProperty()) { case "linea": actual.setLinea((int) e.getNewValue()); break; case "id_variante": actual.setIdVariante((int) e.getNewValue()); break; case "actividad": actual.setActividad((String) e.getNewValue()); break; case "es_activo": actual.setActivo((boolean) e.getNewValue()); break; } } } //-------------------------------------------------------------------- @Override public Object onGetValueAt(TableModelGetValueEvent<PlanMantenimiento> e) { PlanMantenimiento actual = e.getItem(); switch (e.getDataProperty()) { case "linea": return actual.getLinea(); case "id_variante": return actual.getIdVariante(); case "actividad": return actual.getActividad(); case "es_activo": return actual.esActivo(); } return null; } //-------------------------------------------------------------------- @Override public Class<?> onGetColumnClass(TableModelCellFormatEvent e) { switch (e.getDataProperty()) { case "linea": case "id_variante": return Integer.class; case "es_activo": return Boolean.class; } return getDefaultColumnClass(); } //-------------------------------------------------------------------- @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return true; } }
UTF-8
Java
2,841
java
PlanMantenimientosTableModel.java
Java
[ { "context": "ts.TableModelSetValueEvent;\r\n\r\n/**\r\n *\r\n * @author Victor Manuel Bucio Vargas\r\n */\r\npublic class PlanMantenimientosTableModel e", "end": 392, "score": 0.999787449836731, "start": 366, "tag": "NAME", "value": "Victor Manuel Bucio Vargas" } ]
null
[]
package com.syswave.forms.databinding; import com.syswave.entidades.miempresa.PlanMantenimiento; import com.syswave.swing.models.POJOTableModel; import com.syswave.swing.table.events.TableModelCellFormatEvent; import com.syswave.swing.table.events.TableModelGetValueEvent; import com.syswave.swing.table.events.TableModelSetValueEvent; /** * * @author <NAME> */ public class PlanMantenimientosTableModel extends POJOTableModel<PlanMantenimiento> { //-------------------------------------------------------------------- public PlanMantenimientosTableModel(String[] columns) { super(columns); } //-------------------------------------------------------------------- @Override public void onSetValueAt(TableModelSetValueEvent<PlanMantenimiento> e) { if (e.getNewValue() != null) { PlanMantenimiento actual = e.getItem(); switch (e.getDataProperty()) { case "linea": actual.setLinea((int) e.getNewValue()); break; case "id_variante": actual.setIdVariante((int) e.getNewValue()); break; case "actividad": actual.setActividad((String) e.getNewValue()); break; case "es_activo": actual.setActivo((boolean) e.getNewValue()); break; } } } //-------------------------------------------------------------------- @Override public Object onGetValueAt(TableModelGetValueEvent<PlanMantenimiento> e) { PlanMantenimiento actual = e.getItem(); switch (e.getDataProperty()) { case "linea": return actual.getLinea(); case "id_variante": return actual.getIdVariante(); case "actividad": return actual.getActividad(); case "es_activo": return actual.esActivo(); } return null; } //-------------------------------------------------------------------- @Override public Class<?> onGetColumnClass(TableModelCellFormatEvent e) { switch (e.getDataProperty()) { case "linea": case "id_variante": return Integer.class; case "es_activo": return Boolean.class; } return getDefaultColumnClass(); } //-------------------------------------------------------------------- @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return true; } }
2,821
0.466033
0.466033
95
27.905264
24.533575
83
false
false
0
0
0
0
0
0
0.284211
false
false
4
e461c61d2b2f8dfcdf29711c60509dc59e402103
31,250,182,097,168
434e2644076990b4a21eb282eaa47de795c48d2f
/ydg/코드/programmers/ProHeap_2.java
aa81d900c700d09ee9a1c77c465f3358f1965c32
[]
no_license
JeeNi/Algorithms_Study
https://github.com/JeeNi/Algorithms_Study
32f8d438bbb3f344f9f0e755a7f3b46fa153da26
422da9a1386e3cfeb4609b8e89c48d169b8619ae
refs/heads/master
2020-06-30T15:12:08.057000
2019-10-23T13:34:34
2019-10-23T13:34:34
200,867,753
2
1
null
false
2019-09-04T12:00:30
2019-08-06T14:27:45
2019-09-04T11:41:35
2019-09-04T12:00:29
1,464
1
1
7
Python
false
false
package programmers; import java.util.Comparator; import java.util.PriorityQueue; import java.util.Queue; public class ProHeap_2 { public static void main(String[] args) { int stock = 4; int[] dates = {4, 10 ,15}; int[] supplies = {20, 5 ,10}; int k =30; System.out.println(new Solution_ProHeap_2().solution(stock, dates, supplies, k)); } } class Solution_ProHeap_2{ public int solution(int stock, int[] dates, int[] supplies, int k) { int answer = 0; /* * 문제풀이방법 * - 밀가루를 리필하는 시점은 하루씩 지나면서 재고가 0이되면 리필해준다. --------------------> (1) * - 리필해주기 위해 우선수위 큐에 가장 큰 값부터 나오게 저장한다 --------------------------> (2) * - 또한 큐에 저장하는 시기는 하루씩 지나면서 해당 일이 dates 배열의 일과 같을 때 채워준다. -----> (3) */ Queue<Integer> q = new PriorityQueue<>(Comparator.reverseOrder()); //(2) int pos = 0; for (int i = 0; i < k; i++) { if(pos < dates.length && i == dates[pos]) //(3) q.add(supplies[pos++]); if(stock == 0) { //(1) stock += q.poll(); answer++; } stock -= 1; //하루가 흘러 -1 } return answer; } }
UTF-8
Java
1,452
java
ProHeap_2.java
Java
[]
null
[]
package programmers; import java.util.Comparator; import java.util.PriorityQueue; import java.util.Queue; public class ProHeap_2 { public static void main(String[] args) { int stock = 4; int[] dates = {4, 10 ,15}; int[] supplies = {20, 5 ,10}; int k =30; System.out.println(new Solution_ProHeap_2().solution(stock, dates, supplies, k)); } } class Solution_ProHeap_2{ public int solution(int stock, int[] dates, int[] supplies, int k) { int answer = 0; /* * 문제풀이방법 * - 밀가루를 리필하는 시점은 하루씩 지나면서 재고가 0이되면 리필해준다. --------------------> (1) * - 리필해주기 위해 우선수위 큐에 가장 큰 값부터 나오게 저장한다 --------------------------> (2) * - 또한 큐에 저장하는 시기는 하루씩 지나면서 해당 일이 dates 배열의 일과 같을 때 채워준다. -----> (3) */ Queue<Integer> q = new PriorityQueue<>(Comparator.reverseOrder()); //(2) int pos = 0; for (int i = 0; i < k; i++) { if(pos < dates.length && i == dates[pos]) //(3) q.add(supplies[pos++]); if(stock == 0) { //(1) stock += q.poll(); answer++; } stock -= 1; //하루가 흘러 -1 } return answer; } }
1,452
0.468051
0.444888
46
26.217392
24.336332
83
false
false
0
0
0
0
0
0
0.956522
false
false
4
e7c8c1c8db5a9d12138ce63fdbf6457fc025be65
18,476,949,321,632
f208e05e30c70ce4e8f12ea4e61a044ba1b79ea5
/src/com/example/alarmclock/HomeScreenActivity.java
b754e1730af2527a3ccf97d7932c04ba0205b6e0
[]
no_license
tanvir63/AlarmClock
https://github.com/tanvir63/AlarmClock
bbc8a6833a62f7ac3b06f77fa4ad4f8d75fecfd3
12203c7ec9559778336b52abd6bcfd6b4046ba64
refs/heads/master
2021-01-10T02:48:17.318000
2015-12-06T14:25:06
2015-12-06T14:25:06
47,466,089
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.alarmclock; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class HomeScreenActivity extends Activity { private Button settingsButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.home_screen); settingsButton = (Button) findViewById(R.id.button_setting); settingsButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent intent = new Intent(HomeScreenActivity.this, SettingsActivity.class); startActivity(intent); } }); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); } }
UTF-8
Java
853
java
HomeScreenActivity.java
Java
[]
null
[]
package com.example.alarmclock; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class HomeScreenActivity extends Activity { private Button settingsButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.home_screen); settingsButton = (Button) findViewById(R.id.button_setting); settingsButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent intent = new Intent(HomeScreenActivity.this, SettingsActivity.class); startActivity(intent); } }); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); } }
853
0.779601
0.779601
30
27.466667
22.276644
83
false
false
0
0
0
0
0
0
1.533333
false
false
4
e3a19b3ca4de354cb0d8ebd5ab5e5290ebaa958c
12,893,491,860,452
a79b0d23483121eb155ab16ac579b1bbb9015f7e
/app/src/main/java/ru/eadm/nobird/data/FontMgr.java
a8e89270a4ef7e9ab929255497286ec202384e0c
[]
no_license
eadm/Nobird
https://github.com/eadm/Nobird
d88a956467d60b6154723ab47df896ea390946fc
b3d597b4db77e566dd5291b3da942f7fc5b971fa
refs/heads/master
2021-01-23T22:30:50.414000
2017-09-09T07:56:42
2017-09-09T07:56:42
102,937,435
0
0
null
false
2017-12-15T19:22:23
2017-09-09T07:58:07
2017-12-04T14:37:42
2017-12-15T19:22:22
2,042
0
0
0
Java
false
null
package ru.eadm.nobird.data; import android.content.Context; import android.databinding.BindingAdapter; import android.graphics.Typeface; import android.widget.EditText; import android.widget.TextView; public final class FontMgr { private final Context context; private static FontMgr instance; public Typeface RobotoLight, RobotoMedium, RobotoSlabLight, RobotoSlabRegular; private FontMgr(final Context context) { this.context = context; initFonts(); } public synchronized static void init(final Context context) { if (instance == null) { instance = new FontMgr(context); } } private void initFonts() { RobotoLight = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Light.ttf"); RobotoMedium = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Medium.ttf"); RobotoSlabLight = Typeface.createFromAsset(context.getAssets(), "fonts/RobotoSlab-Light.ttf"); RobotoSlabRegular = Typeface.createFromAsset(context.getAssets(), "fonts/RobotoSlab-Regular.ttf"); } public synchronized static FontMgr getInstance() { return instance; } @BindingAdapter({"typeface"}) public static void setTypeface(final TextView view, final Typeface typeface) { view.setTypeface(typeface); } @BindingAdapter({"typeface"}) public static void setTypeface(final EditText view, final Typeface typeface) { view.setTypeface(typeface); } }
UTF-8
Java
1,504
java
FontMgr.java
Java
[]
null
[]
package ru.eadm.nobird.data; import android.content.Context; import android.databinding.BindingAdapter; import android.graphics.Typeface; import android.widget.EditText; import android.widget.TextView; public final class FontMgr { private final Context context; private static FontMgr instance; public Typeface RobotoLight, RobotoMedium, RobotoSlabLight, RobotoSlabRegular; private FontMgr(final Context context) { this.context = context; initFonts(); } public synchronized static void init(final Context context) { if (instance == null) { instance = new FontMgr(context); } } private void initFonts() { RobotoLight = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Light.ttf"); RobotoMedium = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Medium.ttf"); RobotoSlabLight = Typeface.createFromAsset(context.getAssets(), "fonts/RobotoSlab-Light.ttf"); RobotoSlabRegular = Typeface.createFromAsset(context.getAssets(), "fonts/RobotoSlab-Regular.ttf"); } public synchronized static FontMgr getInstance() { return instance; } @BindingAdapter({"typeface"}) public static void setTypeface(final TextView view, final Typeface typeface) { view.setTypeface(typeface); } @BindingAdapter({"typeface"}) public static void setTypeface(final EditText view, final Typeface typeface) { view.setTypeface(typeface); } }
1,504
0.705452
0.705452
47
31
30.639982
106
false
false
0
0
0
0
0
0
0.595745
false
false
4
d950f989633f6a32f66c5f89ed9b6d46c0ae822b
25,520,695,686,886
ceb2945b875260c8b826fbae6932fbf9b24191be
/sjzs/src/com/hnzskj/service/sjzs/impl/CheckLogServiceImpl.java
35fe0cf0c85a6d824dfbefccc1215297bb7e0f16
[]
no_license
zhanght86/ZhongShen
https://github.com/zhanght86/ZhongShen
6a006c30ad8137b95f42f456abb3f50bdb992df3
ca4161485c893a357618893904f40d954d8e22c5
refs/heads/master
2021-08-14T18:10:44.096000
2017-11-16T11:28:30
2017-11-16T11:28:30
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hnzskj.service.sjzs.impl; import java.util.LinkedHashMap; import com.hnzskj.common.Page; import com.hnzskj.persist.bean.sjzs.CheckLogDTO; import com.hnzskj.persist.dao.sjzs.CheckLogDao; import com.hnzskj.service.sjzs.CheckLogService; public class CheckLogServiceImpl implements CheckLogService { private CheckLogDao checkLogDao; @Override public boolean addCheckLog(CheckLogDTO checkLog) { return checkLogDao.addCheckLog(checkLog)>0; } @Override public boolean deleteCheckLog(String id) { // TODO Auto-generated method stub return false; } @Override public CheckLogDTO getCheckLogById(String id) { // TODO Auto-generated method stub return null; } @Override public Page<CheckLogDTO> searchByCondition(Page<CheckLogDTO> page, CheckLogDTO checkLog) { StringBuffer condition = new StringBuffer(" where 1 = 1 "); if(checkLog.getInfoId()!=null&&!"".equals(checkLog.getInfoId())){ condition.append(" and infoId = '").append(checkLog.getInfoId()).append("'"); } LinkedHashMap<String,String> orderby = new LinkedHashMap<String, String>(); orderby.put("updateDate", "desc"); return checkLogDao.searchByCondition(page, "*", condition.toString(), null, orderby); } public CheckLogDao getCheckLogDao() { return checkLogDao; } public void setCheckLogDao(CheckLogDao checkLogDao) { this.checkLogDao = checkLogDao; } }
UTF-8
Java
1,419
java
CheckLogServiceImpl.java
Java
[]
null
[]
package com.hnzskj.service.sjzs.impl; import java.util.LinkedHashMap; import com.hnzskj.common.Page; import com.hnzskj.persist.bean.sjzs.CheckLogDTO; import com.hnzskj.persist.dao.sjzs.CheckLogDao; import com.hnzskj.service.sjzs.CheckLogService; public class CheckLogServiceImpl implements CheckLogService { private CheckLogDao checkLogDao; @Override public boolean addCheckLog(CheckLogDTO checkLog) { return checkLogDao.addCheckLog(checkLog)>0; } @Override public boolean deleteCheckLog(String id) { // TODO Auto-generated method stub return false; } @Override public CheckLogDTO getCheckLogById(String id) { // TODO Auto-generated method stub return null; } @Override public Page<CheckLogDTO> searchByCondition(Page<CheckLogDTO> page, CheckLogDTO checkLog) { StringBuffer condition = new StringBuffer(" where 1 = 1 "); if(checkLog.getInfoId()!=null&&!"".equals(checkLog.getInfoId())){ condition.append(" and infoId = '").append(checkLog.getInfoId()).append("'"); } LinkedHashMap<String,String> orderby = new LinkedHashMap<String, String>(); orderby.put("updateDate", "desc"); return checkLogDao.searchByCondition(page, "*", condition.toString(), null, orderby); } public CheckLogDao getCheckLogDao() { return checkLogDao; } public void setCheckLogDao(CheckLogDao checkLogDao) { this.checkLogDao = checkLogDao; } }
1,419
0.732206
0.730092
48
27.5625
26.652788
91
false
false
0
0
0
0
0
0
1.479167
false
false
4
09a2d956b6f1c2e7701ec518ccdcf5b8b13ed2df
32,916,629,414,430
f4828f17c590f457b8ae447c5617e3824115fcd9
/Chapter 5/src/test/java/com/tad/arquillian/chp5/test/spring/XMLUserProviderTest.java
58bef654e51df76ff3a4fa4785a9f8caacde062c
[]
no_license
adamrduffy/arquillian-testing-guide-code
https://github.com/adamrduffy/arquillian-testing-guide-code
03df234b98db6461efaa43537a3363a4cd1009ce
511f639d5114c42600da3f4e56a0775dffa54a87
refs/heads/master
2021-07-05T03:37:22.020000
2017-09-27T16:39:18
2017-09-27T16:39:18
105,039,000
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tad.arquillian.chp5.test.spring; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.util.List; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.spring.integration.test.annotation.SpringConfiguration; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import com.tad.arquillian.chp5.spring.User; import com.tad.arquillian.chp5.spring.UserProvider; @RunWith(Arquillian.class) @SpringConfiguration({ "test-userProviderContext.xml" }) public class XMLUserProviderTest { @Deployment public static WebArchive createTestArchive() { return SpringTestUtils.createTestArchive().addAsResource( "test-userProviderContext.xml"); } @Autowired private UserProvider userProvider; @Test public void testInjection() { assertNotNull(userProvider); } @Test public void testUsersContent() { List<User> users = userProvider.findAllUsers(); assertEquals(2, users.size()); } }
UTF-8
Java
1,146
java
XMLUserProviderTest.java
Java
[]
null
[]
package com.tad.arquillian.chp5.test.spring; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.util.List; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.spring.integration.test.annotation.SpringConfiguration; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import com.tad.arquillian.chp5.spring.User; import com.tad.arquillian.chp5.spring.UserProvider; @RunWith(Arquillian.class) @SpringConfiguration({ "test-userProviderContext.xml" }) public class XMLUserProviderTest { @Deployment public static WebArchive createTestArchive() { return SpringTestUtils.createTestArchive().addAsResource( "test-userProviderContext.xml"); } @Autowired private UserProvider userProvider; @Test public void testInjection() { assertNotNull(userProvider); } @Test public void testUsersContent() { List<User> users = userProvider.findAllUsers(); assertEquals(2, users.size()); } }
1,146
0.802792
0.799302
38
29.157894
21.945538
83
false
false
0
0
0
0
0
0
1.105263
false
false
4
1da0fadb7abf0b897d715f9c86fdfa38ae1b4307
7,017,976,574,493
72dec52cfcb7b86d8970d8b645b506a413b3fdbf
/continuuity-test/src/main/java/com/continuuity/test/DataSetManager.java
e70d5bffae5b358218bd0c9c838f7fa685c48876
[]
no_license
bemre/cdap
https://github.com/bemre/cdap
55e5ca6251f9313df2c0ae2f969a5ca7fcce8802
c424ba412cc74f063db10f26c25b9b9a1a9495a3
refs/heads/master
2020-12-26T04:27:08.842000
2014-07-30T02:00:55
2014-07-30T02:00:55
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.continuuity.test; /** * Instance of this class is for managing {@link com.continuuity.api.data.DataSet}. * * NOTE: changes made with the instance of the dataset acquired via {@link #get()} are not visible to other components * unless {@link #flush()} is called. * * Typical usage for read: * {@code ApplicationManager appManager = deployApplication(AppWithTable.class); DataSetManager<Table> myTableManager = appManager.getDataSet("my_table"); myTableManager = appManager.getDataSet("my_table"); String value = myTableManager.get().get(new Get("key1", "column1")).getString("column1"); * } * * Typical usage for write: * {@code ApplicationManager appManager = deployApplication(AppWithTable.class); DataSetManager<Table> myTableManager = appManager.getDataSet("my_table"); myTableManager.get().put(new Put("key1", "column1", "value1")); myTableManager.flush(); * } * * @param <T> actual type of the dataset */ public interface DataSetManager<T> { /** * @return dataset instance. * NOTE: the returned instance of dataset will see only changes made before it was acquired. */ T get(); /** * Makes changes performed using dataset instance acquired via {@link #get()} visible to all other components. * Can be called multiple times on same instance of the dataset. */ void flush(); }
UTF-8
Java
1,389
java
DataSetManager.java
Java
[]
null
[]
package com.continuuity.test; /** * Instance of this class is for managing {@link com.continuuity.api.data.DataSet}. * * NOTE: changes made with the instance of the dataset acquired via {@link #get()} are not visible to other components * unless {@link #flush()} is called. * * Typical usage for read: * {@code ApplicationManager appManager = deployApplication(AppWithTable.class); DataSetManager<Table> myTableManager = appManager.getDataSet("my_table"); myTableManager = appManager.getDataSet("my_table"); String value = myTableManager.get().get(new Get("key1", "column1")).getString("column1"); * } * * Typical usage for write: * {@code ApplicationManager appManager = deployApplication(AppWithTable.class); DataSetManager<Table> myTableManager = appManager.getDataSet("my_table"); myTableManager.get().put(new Put("key1", "column1", "value1")); myTableManager.flush(); * } * * @param <T> actual type of the dataset */ public interface DataSetManager<T> { /** * @return dataset instance. * NOTE: the returned instance of dataset will see only changes made before it was acquired. */ T get(); /** * Makes changes performed using dataset instance acquired via {@link #get()} visible to all other components. * Can be called multiple times on same instance of the dataset. */ void flush(); }
1,389
0.691865
0.687545
39
34.615383
35.903442
118
false
false
0
0
0
0
0
0
0.358974
false
false
4
d9f9c09f54f47c63bc9947ebb92630004079d629
7,121,055,803,533
9694ccbc7f3e2100e6a9ae2770082b4d59519c4f
/src/main/java/edu/agh/lroza/actors/java/GetNotice.java
0482923e23768cb7eeed6e5ec0ad6c5bad57a029
[]
no_license
lroza/mgr
https://github.com/lroza/mgr
f893577458e6bb1a2b4d01bbf1768d715a74ca3a
31e3e4443d5cbd0050da9bb1dba1de38ff379aef
refs/heads/master
2016-09-06T14:38:27.619000
2012-12-11T21:02:43
2012-12-11T21:02:43
2,743,139
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.agh.lroza.actors.java; import java.util.UUID; import edu.agh.lroza.common.Id; public class GetNotice extends NoticeActorMessage { private final UUID token; public GetNotice(UUID token, Id id) { super(id); this.token = token; } @Override public void handleMessage(NoticeActor instance) { instance.getContext().reply(instance.getNotice()); } @Override public UUID getToken() { return token; } }
UTF-8
Java
480
java
GetNotice.java
Java
[]
null
[]
package edu.agh.lroza.actors.java; import java.util.UUID; import edu.agh.lroza.common.Id; public class GetNotice extends NoticeActorMessage { private final UUID token; public GetNotice(UUID token, Id id) { super(id); this.token = token; } @Override public void handleMessage(NoticeActor instance) { instance.getContext().reply(instance.getNotice()); } @Override public UUID getToken() { return token; } }
480
0.652083
0.652083
25
18.200001
18.229647
58
false
false
0
0
0
0
0
0
0.36
false
false
4
88dc570c025476d6ecf167431812d9d929c82c87
27,109,833,615,982
e4820b1dbf6d7ba633effffc9b5e6689d3b4f784
/src/main/java/com/github/jnidzwetzki/bitfinex/v2/command/BitfinexCommands.java
d59b6de6659c1619db19ad81277f18b5f49bdbe2
[ "Apache-2.0" ]
permissive
IAMDimchik/bitfinex-v2-wss-api-java
https://github.com/IAMDimchik/bitfinex-v2-wss-api-java
070d87e8809d51ae3298ad47255716a07d66f907
35ef9b44c1ec8cc9d275ed2d0cc3280086e7bc3a
refs/heads/master
2020-03-30T06:30:16.646000
2018-09-21T13:20:28
2018-09-21T13:20:28
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.github.jnidzwetzki.bitfinex.v2.command; import com.github.jnidzwetzki.bitfinex.v2.entity.BitfinexNewOrder; import com.github.jnidzwetzki.bitfinex.v2.symbol.BitfinexCandlestickSymbol; import com.github.jnidzwetzki.bitfinex.v2.symbol.BitfinexExecutedTradeSymbol; import com.github.jnidzwetzki.bitfinex.v2.symbol.BitfinexOrderBookSymbol; import com.github.jnidzwetzki.bitfinex.v2.symbol.BitfinexStreamSymbol; import com.github.jnidzwetzki.bitfinex.v2.symbol.BitfinexTickerSymbol; /** * bitfinex commands factorry */ public final class BitfinexCommands { private BitfinexCommands() { } public static OrderCommand newOrder(BitfinexNewOrder order) { return new OrderCommand(order); } public static CancelOrderCommand cancelOrder(long orderId) { return new CancelOrderCommand(orderId); } public static CancelOrderGroupCommand cancelOrderGroup(int orderGroupId) { return new CancelOrderGroupCommand(orderGroupId); } public static PingCommand ping() { return new PingCommand(); } public static SubscribeCandlesCommand subscribeCandlesChannel(BitfinexCandlestickSymbol symbol) { return new SubscribeCandlesCommand(symbol); } public static SubscribeOrderbookCommand subscribeOrderbookChannel(BitfinexOrderBookSymbol symbol) { return new SubscribeOrderbookCommand(symbol); } public static SubscribeTickerCommand subscribeTickerChannel(BitfinexTickerSymbol symbol) { return new SubscribeTickerCommand(symbol); } public static SubscribeTradesCommand subscribeTradesChannel(BitfinexExecutedTradeSymbol symbol) { return new SubscribeTradesCommand(symbol); } public static UnsubscribeChannelCommand unsubscribeChannel(BitfinexStreamSymbol symbol) { return new UnsubscribeChannelCommand(symbol); } }
UTF-8
Java
1,862
java
BitfinexCommands.java
Java
[ { "context": "package com.github.jnidzwetzki.bitfinex.v2.command;\n\nimport com.github.jnidzwetz", "end": 30, "score": 0.9994499087333679, "start": 19, "tag": "USERNAME", "value": "jnidzwetzki" }, { "context": "idzwetzki.bitfinex.v2.command;\n\nimport com.github.jnidzwetzki.bitfinex.v2.entity.BitfinexNewOrder;\nimport com.g", "end": 82, "score": 0.9993550777435303, "start": 71, "tag": "USERNAME", "value": "jnidzwetzki" }, { "context": "nex.v2.entity.BitfinexNewOrder;\nimport com.github.jnidzwetzki.bitfinex.v2.symbol.BitfinexCandlestickSymbol;\nimp", "end": 149, "score": 0.9991368651390076, "start": 138, "tag": "USERNAME", "value": "jnidzwetzki" }, { "context": "mbol.BitfinexCandlestickSymbol;\nimport com.github.jnidzwetzki.bitfinex.v2.symbol.BitfinexExecutedTradeSymbol;\ni", "end": 225, "score": 0.9990766644477844, "start": 214, "tag": "USERNAME", "value": "jnidzwetzki" }, { "context": "ol.BitfinexExecutedTradeSymbol;\nimport com.github.jnidzwetzki.bitfinex.v2.symbol.BitfinexOrderBookSymbol;\nimpor", "end": 303, "score": 0.9991514086723328, "start": 292, "tag": "USERNAME", "value": "jnidzwetzki" }, { "context": "symbol.BitfinexOrderBookSymbol;\nimport com.github.jnidzwetzki.bitfinex.v2.symbol.BitfinexStreamSymbol;\nimport c", "end": 377, "score": 0.998831570148468, "start": 366, "tag": "USERNAME", "value": "jnidzwetzki" }, { "context": "v2.symbol.BitfinexStreamSymbol;\nimport com.github.jnidzwetzki.bitfinex.v2.symbol.BitfinexTickerSymbol;\n\n/**\n * ", "end": 448, "score": 0.9990063309669495, "start": 437, "tag": "USERNAME", "value": "jnidzwetzki" } ]
null
[]
package com.github.jnidzwetzki.bitfinex.v2.command; import com.github.jnidzwetzki.bitfinex.v2.entity.BitfinexNewOrder; import com.github.jnidzwetzki.bitfinex.v2.symbol.BitfinexCandlestickSymbol; import com.github.jnidzwetzki.bitfinex.v2.symbol.BitfinexExecutedTradeSymbol; import com.github.jnidzwetzki.bitfinex.v2.symbol.BitfinexOrderBookSymbol; import com.github.jnidzwetzki.bitfinex.v2.symbol.BitfinexStreamSymbol; import com.github.jnidzwetzki.bitfinex.v2.symbol.BitfinexTickerSymbol; /** * bitfinex commands factorry */ public final class BitfinexCommands { private BitfinexCommands() { } public static OrderCommand newOrder(BitfinexNewOrder order) { return new OrderCommand(order); } public static CancelOrderCommand cancelOrder(long orderId) { return new CancelOrderCommand(orderId); } public static CancelOrderGroupCommand cancelOrderGroup(int orderGroupId) { return new CancelOrderGroupCommand(orderGroupId); } public static PingCommand ping() { return new PingCommand(); } public static SubscribeCandlesCommand subscribeCandlesChannel(BitfinexCandlestickSymbol symbol) { return new SubscribeCandlesCommand(symbol); } public static SubscribeOrderbookCommand subscribeOrderbookChannel(BitfinexOrderBookSymbol symbol) { return new SubscribeOrderbookCommand(symbol); } public static SubscribeTickerCommand subscribeTickerChannel(BitfinexTickerSymbol symbol) { return new SubscribeTickerCommand(symbol); } public static SubscribeTradesCommand subscribeTradesChannel(BitfinexExecutedTradeSymbol symbol) { return new SubscribeTradesCommand(symbol); } public static UnsubscribeChannelCommand unsubscribeChannel(BitfinexStreamSymbol symbol) { return new UnsubscribeChannelCommand(symbol); } }
1,862
0.779807
0.776047
55
32.854546
33.953667
103
false
false
0
0
0
0
0
0
0.290909
false
false
4
1fcee54248cdefc5fc4c498a0c1ba7e8b46a5c5f
14,113,262,553,185
eeea0ae3c59d39a2999b8b0d0958463c412f5ae7
/src/main/java/dao/EducationDao.java
79bebf52e2461296979ff8c1fb08ef2825a38314
[]
no_license
Sacr/SocialNetworkTestDataGenerator
https://github.com/Sacr/SocialNetworkTestDataGenerator
30c872d89e17a2922c794a508c1f63e180cd2968
b1f947ac4d0228513b9ada4e0f8a6dd1256c7b14
refs/heads/master
2016-09-13T08:15:50.159000
2016-06-06T18:24:50
2016-06-06T18:24:50
57,362,685
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package dao; import model.Education; import java.sql.SQLException; import java.util.List; public interface EducationDao { void createEducation(List<Education> educationList) throws SQLException; }
UTF-8
Java
204
java
EducationDao.java
Java
[]
null
[]
package dao; import model.Education; import java.sql.SQLException; import java.util.List; public interface EducationDao { void createEducation(List<Education> educationList) throws SQLException; }
204
0.79902
0.79902
10
19.4
22.29888
76
false
false
0
0
0
0
0
0
0.5
false
false
4
ea9779b92959c158819fd98a15ef48693ba9c81d
29,411,936,095,693
6df34c044d328c00f9e27d4f241ed78a46aaadb2
/src/com/burnevsky/firu/TranslationsFragmentModel.java
7f6a670d2024e2a382460bfcfb1176ef2cc3a07c
[ "MIT" ]
permissive
sergburn/firu
https://github.com/sergburn/firu
0985787d32d3551c8910d86500207b44b48682dc
ba86ac1ab6ec9c3d2d2a6de78d8e934fa244352d
refs/heads/master
2021-01-17T07:50:20.412000
2017-02-10T07:52:10
2017-02-10T07:52:10
22,769,278
5
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/******************************************************************************* * The MIT License (MIT) * * Copyright (c) 2014 Sergey Burnevsky * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *******************************************************************************/ package com.burnevsky.firu; import android.os.AsyncTask; import android.util.Log; import com.burnevsky.firu.model.DictionaryID; import com.burnevsky.firu.model.IDictionary; import com.burnevsky.firu.model.Mark; import com.burnevsky.firu.model.MarkedTranslation; import com.burnevsky.firu.model.Model; import com.burnevsky.firu.model.Text; import com.burnevsky.firu.model.Translation; import com.burnevsky.firu.model.Vocabulary; import com.burnevsky.firu.model.Word; import java.util.ArrayList; import java.util.List; public class TranslationsFragmentModel { interface IListener { void onVocabularyCheckCompleted(); void onWordUpdated(); void onTranslationsUpdated(); } Model mModel = null; private IListener mListener = null; private Word mWord = null; private List<Translation> mAllTranslations = new ArrayList<>(); private Word mLastRemovedWord = null; public TranslationsFragmentModel(Model model, IListener listener) { mModel = model; mListener = listener; } public Word getWord() { return mWord; } public List<? extends Translation> getTranslations() { return mAllTranslations.subList(0, mAllTranslations.size()); // copy of the list } class FindWord extends AsyncTask<Text, Void, Word> { DictionaryID mDictionaryID; public FindWord(DictionaryID dictionaryId) { mDictionaryID = dictionaryId; } @Override protected Word doInBackground(Text... param) { IDictionary dictionary = mModel.getDictionary(mDictionaryID); if (dictionary != null) { return dictionary.findWord(param[0]); } return null; } @Override protected void onPostExecute(Word word) { if (word != null) { if (word.isVocabularyItem()) { mWord = word; mListener.onWordUpdated(); } mergeTranslations(word.getTranslations()); mListener.onTranslationsUpdated(); } if (mDictionaryID == DictionaryID.VOCABULARY) { mListener.onVocabularyCheckCompleted(); } } } class LoadTranslations extends AsyncTask<Word, Void, Word> { @Override protected Word doInBackground(Word... param) { Word word = param[0]; IDictionary dictionary = mModel.getDictionary(word.getDictID()); if (dictionary != null) { dictionary.loadTranslations(word); } return word; } @Override protected void onPostExecute(Word result) { mergeTranslations(result.getTranslations()); mListener.onTranslationsUpdated(); } } class VocabularyAdd extends AsyncTask<Object, Void, Word> { void start(Text word, List<? extends Text> translations) { execute(word, translations); } @Override protected Word doInBackground(Object... param) { Vocabulary vocabulary = (Vocabulary) mModel.getDictionary(DictionaryID.VOCABULARY); if (vocabulary != null) { try { return vocabulary.addWord((Text) param[0], (List<? extends Text>) param[1]); } catch (Exception e) { e.printStackTrace(); } } return null; } @Override protected void onPostExecute(Word word) { if (word != null) { mWord = word; mAllTranslations = mWord.getTranslations(); mListener.onWordUpdated(); mListener.onTranslationsUpdated(); } } } class VocabularyRestore extends AsyncTask<Word, Void, Word> { @Override protected Word doInBackground(Word... param) { Vocabulary vocabulary = (Vocabulary) mModel.getDictionary(DictionaryID.VOCABULARY); if (vocabulary != null) { try { Word word = param[0]; return vocabulary.addWord(word, word.getTranslations()); } catch (Exception e) { e.printStackTrace(); } } return null; } @Override protected void onPostExecute(Word word) { if (word != null) { mWord = word; mAllTranslations = mWord.getTranslations(); mListener.onWordUpdated(); mListener.onTranslationsUpdated(); } } } class VocabularyAddTranslation extends AsyncTask<Object, Void, Word> { void start(Word word, Text translation) { execute(word, translation); } @Override protected Word doInBackground(Object... param) { Vocabulary vocabulary = (Vocabulary) mModel.getDictionary(DictionaryID.VOCABULARY); if (vocabulary != null) { try { List<Text> list = new ArrayList<>(); list.add((Text) param[1]); return vocabulary.addTranslations((Word) param[0], list); } catch (Exception e) { e.printStackTrace(); } } return null; } @Override protected void onPostExecute(Word word) { if (word != null) { mWord = word; mListener.onWordUpdated(); mAllTranslations = mWord.getTranslations(); mListener.onTranslationsUpdated(); } } } class VocabularyRemove extends AsyncTask<Word, Void, Boolean> { @Override protected Boolean doInBackground(Word... param) { Vocabulary vocabulary = (Vocabulary) mModel.getDictionary(DictionaryID.VOCABULARY); if (vocabulary != null) { try { return vocabulary.removeWord(param[0]); } catch (Exception e) { e.printStackTrace(); } } return false; } @Override protected void onPostExecute(Boolean removed) { if (removed) { mWord.unlink(); mAllTranslations = mWord.getTranslations(); mListener.onWordUpdated(); mListener.onTranslationsUpdated(); } } } class VocabularyUpdateMarks extends AsyncTask<MarkedTranslation, Void, Boolean> { @Override protected Boolean doInBackground(MarkedTranslation... param) { Vocabulary vocabulary = (Vocabulary) mModel.getDictionary(DictionaryID.VOCABULARY); if (vocabulary != null) { try { vocabulary.updateMarks(param[0]); return true; } catch (Exception e) { e.printStackTrace(); } } return false; } @Override protected void onPostExecute(Boolean updated) { if (updated) { mListener.onTranslationsUpdated(); } } } public void loadWord(Word word) { mWord = word; mAllTranslations.clear(); for (IDictionary dictionary : mModel.getDictionaries()) { if (mWord.getDictID() == dictionary.getDictID()) { new LoadTranslations().execute(mWord); } else { new FindWord(dictionary.getDictID()).execute(mWord); } } } public void addWordToVocabulary() { if (mWord != null) { if (!mWord.isVocabularyItem()) { new VocabularyAdd().start(mWord, mAllTranslations); } else { Log.d("firu", "Attempt to re-add vocabulary word"); } } } public void removeWordFromVocabulary() { if (mWord != null) { if (mWord.isVocabularyItem()) { mLastRemovedWord = mWord; new VocabularyRemove().execute(mWord); } else { Log.d("firu", "Attempt to remove non-vocabulary word"); } } } public void restoreLastRemovedWord() { if (mLastRemovedWord != null) { new VocabularyRestore().execute(mLastRemovedWord); } else { Log.d("firu", "No removed word to restore"); } } public void forgetLastRemovedWord() { mLastRemovedWord = null; } public void addTranslationToVocabulary(int position) { if (mWord != null && mWord.isVocabularyItem()) { new VocabularyAddTranslation().start(mWord, mAllTranslations.get(position)); } } private void mergeTranslations(List<Translation> translations) { for (Translation trans : translations) { int matchIndex = Translation.findMatch(trans, mAllTranslations); if (matchIndex >= 0) { if (trans.isVocabularyItem()) { mAllTranslations.set(matchIndex, trans); } } else { mAllTranslations.add(trans); } } } /** * Removes translation from training */ public void deselectTranslation(int position) { Translation trans = mAllTranslations.get(position); if (trans.isVocabularyItem()) { MarkedTranslation mt = (MarkedTranslation) trans; mt.ReverseMark = Mark.UNFAMILIAR; new VocabularyUpdateMarks().execute(mt); } } /** Adds translation to training */ public void selectTranslation(int position) { selectTranslation(position, Mark.YET_TO_LEARN); } /** * Restores translation for training */ public void selectTranslation(int position, Mark mark) { Translation trans = mAllTranslations.get(position); if (trans.isVocabularyItem()) { MarkedTranslation mt = (MarkedTranslation) trans; mt.ReverseMark = mark; new VocabularyUpdateMarks().execute(mt); } } }
UTF-8
Java
12,483
java
TranslationsFragmentModel.java
Java
[ { "context": "\n * The MIT License (MIT)\n *\n * Copyright (c) 2014 Sergey Burnevsky\n *\n * Permission is hereby granted, free of charg", "end": 147, "score": 0.9998644590377808, "start": 131, "tag": "NAME", "value": "Sergey Burnevsky" } ]
null
[]
/******************************************************************************* * The MIT License (MIT) * * Copyright (c) 2014 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *******************************************************************************/ package com.burnevsky.firu; import android.os.AsyncTask; import android.util.Log; import com.burnevsky.firu.model.DictionaryID; import com.burnevsky.firu.model.IDictionary; import com.burnevsky.firu.model.Mark; import com.burnevsky.firu.model.MarkedTranslation; import com.burnevsky.firu.model.Model; import com.burnevsky.firu.model.Text; import com.burnevsky.firu.model.Translation; import com.burnevsky.firu.model.Vocabulary; import com.burnevsky.firu.model.Word; import java.util.ArrayList; import java.util.List; public class TranslationsFragmentModel { interface IListener { void onVocabularyCheckCompleted(); void onWordUpdated(); void onTranslationsUpdated(); } Model mModel = null; private IListener mListener = null; private Word mWord = null; private List<Translation> mAllTranslations = new ArrayList<>(); private Word mLastRemovedWord = null; public TranslationsFragmentModel(Model model, IListener listener) { mModel = model; mListener = listener; } public Word getWord() { return mWord; } public List<? extends Translation> getTranslations() { return mAllTranslations.subList(0, mAllTranslations.size()); // copy of the list } class FindWord extends AsyncTask<Text, Void, Word> { DictionaryID mDictionaryID; public FindWord(DictionaryID dictionaryId) { mDictionaryID = dictionaryId; } @Override protected Word doInBackground(Text... param) { IDictionary dictionary = mModel.getDictionary(mDictionaryID); if (dictionary != null) { return dictionary.findWord(param[0]); } return null; } @Override protected void onPostExecute(Word word) { if (word != null) { if (word.isVocabularyItem()) { mWord = word; mListener.onWordUpdated(); } mergeTranslations(word.getTranslations()); mListener.onTranslationsUpdated(); } if (mDictionaryID == DictionaryID.VOCABULARY) { mListener.onVocabularyCheckCompleted(); } } } class LoadTranslations extends AsyncTask<Word, Void, Word> { @Override protected Word doInBackground(Word... param) { Word word = param[0]; IDictionary dictionary = mModel.getDictionary(word.getDictID()); if (dictionary != null) { dictionary.loadTranslations(word); } return word; } @Override protected void onPostExecute(Word result) { mergeTranslations(result.getTranslations()); mListener.onTranslationsUpdated(); } } class VocabularyAdd extends AsyncTask<Object, Void, Word> { void start(Text word, List<? extends Text> translations) { execute(word, translations); } @Override protected Word doInBackground(Object... param) { Vocabulary vocabulary = (Vocabulary) mModel.getDictionary(DictionaryID.VOCABULARY); if (vocabulary != null) { try { return vocabulary.addWord((Text) param[0], (List<? extends Text>) param[1]); } catch (Exception e) { e.printStackTrace(); } } return null; } @Override protected void onPostExecute(Word word) { if (word != null) { mWord = word; mAllTranslations = mWord.getTranslations(); mListener.onWordUpdated(); mListener.onTranslationsUpdated(); } } } class VocabularyRestore extends AsyncTask<Word, Void, Word> { @Override protected Word doInBackground(Word... param) { Vocabulary vocabulary = (Vocabulary) mModel.getDictionary(DictionaryID.VOCABULARY); if (vocabulary != null) { try { Word word = param[0]; return vocabulary.addWord(word, word.getTranslations()); } catch (Exception e) { e.printStackTrace(); } } return null; } @Override protected void onPostExecute(Word word) { if (word != null) { mWord = word; mAllTranslations = mWord.getTranslations(); mListener.onWordUpdated(); mListener.onTranslationsUpdated(); } } } class VocabularyAddTranslation extends AsyncTask<Object, Void, Word> { void start(Word word, Text translation) { execute(word, translation); } @Override protected Word doInBackground(Object... param) { Vocabulary vocabulary = (Vocabulary) mModel.getDictionary(DictionaryID.VOCABULARY); if (vocabulary != null) { try { List<Text> list = new ArrayList<>(); list.add((Text) param[1]); return vocabulary.addTranslations((Word) param[0], list); } catch (Exception e) { e.printStackTrace(); } } return null; } @Override protected void onPostExecute(Word word) { if (word != null) { mWord = word; mListener.onWordUpdated(); mAllTranslations = mWord.getTranslations(); mListener.onTranslationsUpdated(); } } } class VocabularyRemove extends AsyncTask<Word, Void, Boolean> { @Override protected Boolean doInBackground(Word... param) { Vocabulary vocabulary = (Vocabulary) mModel.getDictionary(DictionaryID.VOCABULARY); if (vocabulary != null) { try { return vocabulary.removeWord(param[0]); } catch (Exception e) { e.printStackTrace(); } } return false; } @Override protected void onPostExecute(Boolean removed) { if (removed) { mWord.unlink(); mAllTranslations = mWord.getTranslations(); mListener.onWordUpdated(); mListener.onTranslationsUpdated(); } } } class VocabularyUpdateMarks extends AsyncTask<MarkedTranslation, Void, Boolean> { @Override protected Boolean doInBackground(MarkedTranslation... param) { Vocabulary vocabulary = (Vocabulary) mModel.getDictionary(DictionaryID.VOCABULARY); if (vocabulary != null) { try { vocabulary.updateMarks(param[0]); return true; } catch (Exception e) { e.printStackTrace(); } } return false; } @Override protected void onPostExecute(Boolean updated) { if (updated) { mListener.onTranslationsUpdated(); } } } public void loadWord(Word word) { mWord = word; mAllTranslations.clear(); for (IDictionary dictionary : mModel.getDictionaries()) { if (mWord.getDictID() == dictionary.getDictID()) { new LoadTranslations().execute(mWord); } else { new FindWord(dictionary.getDictID()).execute(mWord); } } } public void addWordToVocabulary() { if (mWord != null) { if (!mWord.isVocabularyItem()) { new VocabularyAdd().start(mWord, mAllTranslations); } else { Log.d("firu", "Attempt to re-add vocabulary word"); } } } public void removeWordFromVocabulary() { if (mWord != null) { if (mWord.isVocabularyItem()) { mLastRemovedWord = mWord; new VocabularyRemove().execute(mWord); } else { Log.d("firu", "Attempt to remove non-vocabulary word"); } } } public void restoreLastRemovedWord() { if (mLastRemovedWord != null) { new VocabularyRestore().execute(mLastRemovedWord); } else { Log.d("firu", "No removed word to restore"); } } public void forgetLastRemovedWord() { mLastRemovedWord = null; } public void addTranslationToVocabulary(int position) { if (mWord != null && mWord.isVocabularyItem()) { new VocabularyAddTranslation().start(mWord, mAllTranslations.get(position)); } } private void mergeTranslations(List<Translation> translations) { for (Translation trans : translations) { int matchIndex = Translation.findMatch(trans, mAllTranslations); if (matchIndex >= 0) { if (trans.isVocabularyItem()) { mAllTranslations.set(matchIndex, trans); } } else { mAllTranslations.add(trans); } } } /** * Removes translation from training */ public void deselectTranslation(int position) { Translation trans = mAllTranslations.get(position); if (trans.isVocabularyItem()) { MarkedTranslation mt = (MarkedTranslation) trans; mt.ReverseMark = Mark.UNFAMILIAR; new VocabularyUpdateMarks().execute(mt); } } /** Adds translation to training */ public void selectTranslation(int position) { selectTranslation(position, Mark.YET_TO_LEARN); } /** * Restores translation for training */ public void selectTranslation(int position, Mark mark) { Translation trans = mAllTranslations.get(position); if (trans.isVocabularyItem()) { MarkedTranslation mt = (MarkedTranslation) trans; mt.ReverseMark = mark; new VocabularyUpdateMarks().execute(mt); } } }
12,473
0.525515
0.524313
441
27.306122
23.77434
96
false
false
0
0
0
0
0
0
0.371882
false
false
4
037f82a3c54da86f476f5ee0d7f45aec900f8212
21,148,418,983,664
8beea28cac7ce245bc03dab9792be40bbe7a906f
/src/main/java/com/imc/figures/Rock.java
ffc2550e1cb53fb02a2bd3b6f11cf4c83ffc7c5d
[]
no_license
Jekatim/rock_paper_scissors
https://github.com/Jekatim/rock_paper_scissors
c7a1940ee9bd1c21a775f37571d1553299af6b09
e59d78aa960d2e5df32a9a1a72247e15526975cd
refs/heads/master
2022-11-23T16:13:52.796000
2020-07-23T16:43:51
2020-07-23T16:43:51
280,466,617
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.imc.figures; public class Rock extends Figure { private static final Rock INSTANCE = new Rock(); private Rock() { super(FigureType.ROCK, FigureType.PAPER); } public static Rock getInstance() { return INSTANCE; } }
UTF-8
Java
266
java
Rock.java
Java
[]
null
[]
package com.imc.figures; public class Rock extends Figure { private static final Rock INSTANCE = new Rock(); private Rock() { super(FigureType.ROCK, FigureType.PAPER); } public static Rock getInstance() { return INSTANCE; } }
266
0.642857
0.642857
14
18
18.462317
52
false
false
0
0
0
0
0
0
0.357143
false
false
4
5324f29879c40d0c01964278e22cb6b1ec43071b
27,865,747,826,977
bc2398c5594e15bfa2ba4a9feacc1b450e03caa4
/manager/manager-boot/src/main/java/cn/vbill/middleware/porter/manager/controller/CRoleMenuController.java
e96f5799ce09c67e2516981c5ec14f3e59984a13
[ "Apache-2.0" ]
permissive
dailai/porter
https://github.com/dailai/porter
adb5a5691400c430c0ba367e7e0189f56ea67ab2
2b18b561ab3e5e5a88bd06d05dd5b4ea437c2b1b
refs/heads/master
2020-04-16T07:49:30.765000
2019-01-11T09:09:34
2019-01-11T09:09:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * All rights Reserved, Designed By Suixingpay. * * @author: hexin[he_xin@suixingpay.com] * @date: 2018年12月03日 17时54分 * @Copyright 2018 Suixingpay. All rights reserved. * 注意:本内容仅限于随行付支付有限公司内部传阅,禁止外泄以及用于其他的商业用途。 */ package cn.vbill.middleware.porter.manager.controller; import cn.vbill.middleware.porter.manager.core.dto.CRoleMenuVo; import cn.vbill.middleware.porter.manager.core.entity.CRoleMenu; import cn.vbill.middleware.porter.manager.service.CRoleMenuService; import cn.vbill.middleware.porter.manager.web.message.ResponseMessage; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; import static cn.vbill.middleware.porter.manager.web.message.ResponseMessage.ok; /** * 角色菜单管理 * * @author: he_xin * @date: 2018年12月03日 17:55 * @version: V1.0 * @review: he_xin/2018年12月03日 17:55 */ @Api(description = "角色菜单管理") @RestController @RequestMapping("/manager/crolemenu") public class CRoleMenuController { @Autowired private CRoleMenuService cRoleMenuService; /** * 添加某一权限能访问的菜单 * * @author he_xin * @param cRoleMenuVoList * @return */ @PostMapping("/insert") @ApiOperation(value = "添加", notes = "添加") public ResponseMessage insert(@RequestBody List<CRoleMenuVo> cRoleMenuVoList) { cRoleMenuService.insert(cRoleMenuVoList); return ok(); } /** * 回显权限和能访问的菜单 * * @author he_xin * @return */ @GetMapping("/getroleMenu") @ApiOperation(value = "回显权限和能访问的菜单", notes = "回显权限和能访问的菜单") public ResponseMessage getRoleMenu() { List<CRoleMenu> cRoleMenuList = cRoleMenuService.getRoleMenu(); return ok(cRoleMenuList); } }
UTF-8
Java
2,054
java
CRoleMenuController.java
Java
[ { "context": "s Reserved, Designed By Suixingpay.\n *\n * @author: hexin[he_xin@suixingpay.com]\n * @date: 2018年12月03日 17时5", "end": 72, "score": 0.9995729923248291, "start": 67, "tag": "USERNAME", "value": "hexin" }, { "context": "ved, Designed By Suixingpay.\n *\n * @author: hexin[he_xin@suixingpay.com]\n * @date: 2018年12月03日 17时54分\n * @Copyright 2018 ", "end": 94, "score": 0.9999135732650757, "start": 73, "tag": "EMAIL", "value": "he_xin@suixingpay.com" }, { "context": ".ResponseMessage.ok;\n\n/**\n * 角色菜单管理\n *\n * @author: he_xin\n * @date: 2018年12月03日 17:55\n * @version: V1.0\n * ", "end": 884, "score": 0.9996007084846497, "start": 878, "tag": "USERNAME", "value": "he_xin" }, { "context": "\n /**\n * 添加某一权限能访问的菜单\n *\n * @author he_xin\n * @param cRoleMenuVoList\n * @return\n ", "end": 1210, "score": 0.9996106624603271, "start": 1204, "tag": "USERNAME", "value": "he_xin" }, { "context": "\n\n /**\n * 回显权限和能访问的菜单\n *\n * @author he_xin\n * @return\n */\n @GetMapping(\"/getroleM", "end": 1555, "score": 0.9991756081581116, "start": 1549, "tag": "USERNAME", "value": "he_xin" } ]
null
[]
/** * All rights Reserved, Designed By Suixingpay. * * @author: hexin[<EMAIL>] * @date: 2018年12月03日 17时54分 * @Copyright 2018 Suixingpay. All rights reserved. * 注意:本内容仅限于随行付支付有限公司内部传阅,禁止外泄以及用于其他的商业用途。 */ package cn.vbill.middleware.porter.manager.controller; import cn.vbill.middleware.porter.manager.core.dto.CRoleMenuVo; import cn.vbill.middleware.porter.manager.core.entity.CRoleMenu; import cn.vbill.middleware.porter.manager.service.CRoleMenuService; import cn.vbill.middleware.porter.manager.web.message.ResponseMessage; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; import static cn.vbill.middleware.porter.manager.web.message.ResponseMessage.ok; /** * 角色菜单管理 * * @author: he_xin * @date: 2018年12月03日 17:55 * @version: V1.0 * @review: he_xin/2018年12月03日 17:55 */ @Api(description = "角色菜单管理") @RestController @RequestMapping("/manager/crolemenu") public class CRoleMenuController { @Autowired private CRoleMenuService cRoleMenuService; /** * 添加某一权限能访问的菜单 * * @author he_xin * @param cRoleMenuVoList * @return */ @PostMapping("/insert") @ApiOperation(value = "添加", notes = "添加") public ResponseMessage insert(@RequestBody List<CRoleMenuVo> cRoleMenuVoList) { cRoleMenuService.insert(cRoleMenuVoList); return ok(); } /** * 回显权限和能访问的菜单 * * @author he_xin * @return */ @GetMapping("/getroleMenu") @ApiOperation(value = "回显权限和能访问的菜单", notes = "回显权限和能访问的菜单") public ResponseMessage getRoleMenu() { List<CRoleMenu> cRoleMenuList = cRoleMenuService.getRoleMenu(); return ok(cRoleMenuList); } }
2,040
0.713428
0.690502
68
25.941177
23.230864
83
false
false
0
0
0
0
0
0
0.279412
false
false
4
2b38b5303d5d56c3c5818e69f35983e3f5f97a58
16,037,407,897,425
cb4cb56ab997634f374f48883c7c5deac94a297b
/JustePrix.java
1da0fb4d71bea9b3715e8b8d50bd42f9eecfb719
[]
no_license
sophie62330/Algo
https://github.com/sophie62330/Algo
7eb8a3f67e7a15b082329f80fcb4cadbd5517510
31cdf1a14a7c7b92871d84ca849a73171fecfae3
refs/heads/main
2023-08-18T10:00:03.473000
2021-10-12T10:13:54
2021-10-12T10:13:54
416,278,820
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package intro; import intro.Tools; public class JustePrix { /** * Lance une partie du juste prix */ public static void jouerAuJustePrix() { int nbVies=Tools.inputInt("Combien de tentatives voulez-vous ? "); int limite=Tools.inputInt("Quel est le nombre maximum à prendre en compte?"); int nbATrouver=Tools.randomint(limite); int nbPropose; while (nbVies>0){ nbPropose=Tools.inputInt("Saisissez un nombre : "); if (afficherResultatProposition(nbPropose, nbATrouver)) { break; }; nbVies=nbVies-1; } if (nbVies==0) { System.out.println("Game Over"); } } /** * permet de savoir si le nombre proposé est plus grnd que le nombre à trouver * @param nbPropose nombre proposé * @param nbAtrouver nombre à trouver * @return vrai si le nombre proposé est plus grand que le nombre à trouver, faux sinon */ public static boolean nbProposeEstPlusGrand(int nbPropose,int nbAtrouver) { return (nbPropose>nbAtrouver); } /** * permet de savoir si le nombre proposé est plus petit que le nombre à trouver * @param nbPropose nombre proposé * @param nbAtrouver nombre à trouver * @return vrai si le nombre proposé est plus petit que le nombre à trouver, faux sinon */ public static boolean nbProposeEstPlusPetit(int nbPropose,int nbAtrouver) { return (nbPropose<nbAtrouver); } /** * fonction d'affichage du résultat pour savoir si le nombre proposé est plus grand ou plus petit * @param nbPropose le nombre proposé * @param nbATrouver le nombre à trouver * @return true si le nombre a été trouvé */ public static boolean afficherResultatProposition(int nbPropose,int nbATrouver) { boolean res=false; if (nbProposeEstPlusGrand(nbPropose, nbATrouver)) { System.out.println("C'est moins !"); } else if (nbProposeEstPlusPetit(nbPropose, nbATrouver)) { System.out.println("C'est plus !"); } else { System.out.println("Bravo ! Vous avez trouvé le nombre "+nbATrouver); res=true; } return res; } }
UTF-8
Java
2,016
java
JustePrix.java
Java
[]
null
[]
package intro; import intro.Tools; public class JustePrix { /** * Lance une partie du juste prix */ public static void jouerAuJustePrix() { int nbVies=Tools.inputInt("Combien de tentatives voulez-vous ? "); int limite=Tools.inputInt("Quel est le nombre maximum à prendre en compte?"); int nbATrouver=Tools.randomint(limite); int nbPropose; while (nbVies>0){ nbPropose=Tools.inputInt("Saisissez un nombre : "); if (afficherResultatProposition(nbPropose, nbATrouver)) { break; }; nbVies=nbVies-1; } if (nbVies==0) { System.out.println("Game Over"); } } /** * permet de savoir si le nombre proposé est plus grnd que le nombre à trouver * @param nbPropose nombre proposé * @param nbAtrouver nombre à trouver * @return vrai si le nombre proposé est plus grand que le nombre à trouver, faux sinon */ public static boolean nbProposeEstPlusGrand(int nbPropose,int nbAtrouver) { return (nbPropose>nbAtrouver); } /** * permet de savoir si le nombre proposé est plus petit que le nombre à trouver * @param nbPropose nombre proposé * @param nbAtrouver nombre à trouver * @return vrai si le nombre proposé est plus petit que le nombre à trouver, faux sinon */ public static boolean nbProposeEstPlusPetit(int nbPropose,int nbAtrouver) { return (nbPropose<nbAtrouver); } /** * fonction d'affichage du résultat pour savoir si le nombre proposé est plus grand ou plus petit * @param nbPropose le nombre proposé * @param nbATrouver le nombre à trouver * @return true si le nombre a été trouvé */ public static boolean afficherResultatProposition(int nbPropose,int nbATrouver) { boolean res=false; if (nbProposeEstPlusGrand(nbPropose, nbATrouver)) { System.out.println("C'est moins !"); } else if (nbProposeEstPlusPetit(nbPropose, nbATrouver)) { System.out.println("C'est plus !"); } else { System.out.println("Bravo ! Vous avez trouvé le nombre "+nbATrouver); res=true; } return res; } }
2,016
0.713784
0.712281
67
28.776119
28.380054
98
false
false
0
0
0
0
0
0
1.895522
false
false
4
8702f17512306c31fa712bdb6e99bb051f008a7e
9,680,856,291,779
9d32980f5989cd4c55cea498af5d6a413e08b7a2
/A1_7_1_1/src/main/java/com/android/server/am/OppoAmsUtils.java
fc04d205e075cbe0dd355e7c759aed60f1e7e65a
[]
no_license
liuhaosource/OppoFramework
https://github.com/liuhaosource/OppoFramework
e7cc3bcd16958f809eec624b9921043cde30c831
ebe39acabf5eae49f5f991c5ce677d62b683f1b6
refs/heads/master
2023-06-03T23:06:17.572000
2020-11-30T08:40:07
2020-11-30T08:40:07
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.android.server.am; import android.content.ComponentName; import android.content.Intent; import android.os.SystemClock; import android.util.Slog; import com.android.server.NetworkManagementService; import java.util.ArrayList; /* JADX ERROR: NullPointerException in pass: ReSugarCode java.lang.NullPointerException at jadx.core.dex.visitors.ReSugarCode.initClsEnumMap(ReSugarCode.java:159) at jadx.core.dex.visitors.ReSugarCode.visit(ReSugarCode.java:44) at jadx.core.dex.visitors.DepthTraversal.visit(DepthTraversal.java:12) at jadx.core.ProcessClass.process(ProcessClass.java:32) at jadx.core.ProcessClass.lambda$processDependencies$0(ProcessClass.java:51) at java.lang.Iterable.forEach(Iterable.java:75) at jadx.core.ProcessClass.processDependencies(ProcessClass.java:51) at jadx.core.ProcessClass.process(ProcessClass.java:37) at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:292) at jadx.api.JavaClass.decompile(JavaClass.java:62) at jadx.api.JadxDecompiler.lambda$appendSourcesSave$0(JadxDecompiler.java:200) */ /* JADX ERROR: NullPointerException in pass: ExtractFieldInit java.lang.NullPointerException at jadx.core.dex.visitors.ExtractFieldInit.checkStaticFieldsInit(ExtractFieldInit.java:58) at jadx.core.dex.visitors.ExtractFieldInit.visit(ExtractFieldInit.java:44) at jadx.core.dex.visitors.DepthTraversal.visit(DepthTraversal.java:12) at jadx.core.ProcessClass.process(ProcessClass.java:32) at jadx.core.ProcessClass.lambda$processDependencies$0(ProcessClass.java:51) at java.lang.Iterable.forEach(Iterable.java:75) at jadx.core.ProcessClass.processDependencies(ProcessClass.java:51) at jadx.core.ProcessClass.process(ProcessClass.java:37) at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:292) at jadx.api.JavaClass.decompile(JavaClass.java:62) at jadx.api.JadxDecompiler.lambda$appendSourcesSave$0(JadxDecompiler.java:200) */ class OppoAmsUtils { private static final String FEATURE_ACT_FREQ_CONTROL = "oppo.ams.act.freqcontrol"; static final String TAG = null; private static OppoAmsUtils mInstance; private ActStartFreqControler mActStartFreqControler; private ActStartupAccelerator mActStartupAccelerator; final ActivityManagerService mAm; private boolean mIsSupportActFreqCon; private boolean mIsSystemReady; private KeyguardServiceRestartDelay mKeyguardServiceRestartDelay; private class ActStartFreqControler { private static final boolean DEBUG_EMULATE = false; private static final boolean DEBUG_FREQ_CONTROL = false; private static final long DECT_TIME_MAX_INTERVEL = 30000; private static final long DECT_TIME_MIN_INTERVEL = 4000; private static final int MIN_START_DECT_COUNT = 3; private ArrayList<ActStartFreqData> mFreqControlActList = new ArrayList(); public ActStartFreqControler() { initActList(); } private void initActList() { this.mFreqControlActList.add(new ActStartFreqData("com.lianlian", "com.lianlian.activity.RetryAnonymousLoginActivity")); this.mFreqControlActList.add(new ActStartFreqData("tv.danmaku.bili", "tv.danmaku.bili.ui.video.VideoDetailsActivity")); this.mFreqControlActList.add(new ActStartFreqData("com.example.startactfreq", "com.example.startactfreq.FreqActivity")); } private ActStartFreqData getActStartFreqData(String pkgName, String className) { int size = this.mFreqControlActList.size(); for (int index = 0; index < size; index++) { ActStartFreqData tmpData = (ActStartFreqData) this.mFreqControlActList.get(index); if (tmpData != null && tmpData.mPkgName.equals(pkgName) && tmpData.mClassName.equals(className)) { return tmpData; } } return null; } public boolean doControlActivityStartFreq(Intent intent) { if (intent == null) { return false; } ComponentName cmpName = intent.getComponent(); if (cmpName == null) { return false; } String pkgName = cmpName.getPackageName(); String className = cmpName.getClassName(); if (pkgName == null || className == null) { return false; } ActStartFreqData data = getActStartFreqData(pkgName, className); if (data == null) { return false; } long curTime = SystemClock.elapsedRealtime(); long timeElapsed = curTime - data.mLastDectTime; data.mCount++; if (1 == data.mCount) { data.mLastDectTime = curTime; return false; } else if (!data.mIsFrequent) { if (timeElapsed > 4000) { data.mLastDectTime = curTime; data.mCount = 0; } else if (data.mCount >= 3) { data.mIsFrequent = true; data.mLastDectTime = curTime; } return false; } else if (timeElapsed <= DECT_TIME_MAX_INTERVEL) { data.mLastDectTime = curTime; return true; } else { data.mIsFrequent = false; data.mCount = 0; data.mLastDectTime = curTime; return false; } } } private class ActStartFreqData { String mClassName = null; int mCount = 0; boolean mIsFrequent = false; long mLastDectTime = 0; String mPkgName = null; public ActStartFreqData(String pkgName, String className) { this.mPkgName = pkgName; this.mClassName = className; this.mLastDectTime = SystemClock.elapsedRealtime(); this.mCount = 0; } public String toShortString() { return "mPkgName:" + this.mPkgName + ", mClassName" + this.mClassName + ", c:" + this.mCount; } } private class ActStartupAccelerator { private static final int ACCE_DURATION_TIME = 1000; private boolean DEBUG_ACT_ACCE = true; private ArrayList<String> mAccelerateActList = new ArrayList(); private long mLastAcceTime = 0; private LocalPerformance mLocalPerformance = null; private int[] mPerformanceConfigList = new int[]{1077936128, 1, 1086324736, 1, 1090519040, 2, 1082130432, NetworkManagementService.DNS_RESOLVER_DEFAULT_SAMPLE_VALIDITY_SECONDS}; private boolean mSupportActAccelerate = true; public ActStartupAccelerator() { initAccelaerateActList(); initPerformaceConfig(); } private void initAccelaerateActList() { if (this.mSupportActAccelerate) { this.mAccelerateActList.add("{com.tencent.mm/com.tencent.mm.plugin.voip.ui.VideoActivity}"); } } private void initPerformaceConfig() { if (this.mSupportActAccelerate) { this.mLocalPerformance = new LocalPerformance(); } } private boolean isInAcceList(String shortCmpName) { int size = this.mAccelerateActList.size(); for (int index = 0; index < size; index++) { String tmpData = (String) this.mAccelerateActList.get(index); if (this.DEBUG_ACT_ACCE) { Slog.d(OppoAmsUtils.TAG, "isInAcceList, index:" + index + ", shortCmpName:" + shortCmpName + ", data:" + tmpData); } if (tmpData != null && tmpData.equals(shortCmpName)) { return true; } } return false; } public boolean doAccelerateActStartup(Intent intent) { ComponentName cmpName = null; if (!this.mSupportActAccelerate) { return false; } if (intent != null) { cmpName = intent.getComponent(); } if (cmpName == null) { if (this.DEBUG_ACT_ACCE) { Slog.d(OppoAmsUtils.TAG, "doAccelerateActStartup cmpName null, not control"); } return false; } String shortName = cmpName.toShortString(); if (shortName == null || shortName.length() <= 0) { if (this.DEBUG_ACT_ACCE) { Slog.d(OppoAmsUtils.TAG, "doAccelerateActStartup shortName empty, not control"); } return false; } else if (isInAcceList(shortName)) { long curTime = SystemClock.elapsedRealtime(); if (this.mLastAcceTime > 0 && curTime - this.mLastAcceTime <= 1000) { return false; } this.mLastAcceTime = curTime; this.mLocalPerformance.perfLockAcquire(1000, this.mPerformanceConfigList); return true; } else { if (this.DEBUG_ACT_ACCE) { Slog.d(OppoAmsUtils.TAG, "doAccelerateActStartup data not found in list."); } return false; } } } private class KeyguardServiceRestartDelay { private static final String KEYGUARD_SERVICE = "com.android.keyguard/.KeyguardService"; private static final int MAX_DELAY_COUNT = 4; private static final long RESTART_DETECT_TIME = 6; private int mDelayCount = 0; private long mDelayDetectTime = 0; public boolean shouldDelay(String shortName, boolean shouldDelay) { if (!shouldDelay) { return false; } if (!KEYGUARD_SERVICE.equals(shortName)) { return shouldDelay; } if (this.mDelayCount == 0) { this.mDelayDetectTime = SystemClock.elapsedRealtime(); this.mDelayCount++; return shouldDelay; } long curTime = SystemClock.elapsedRealtime(); if (curTime - this.mDelayDetectTime <= RESTART_DETECT_TIME) { this.mDelayCount++; if (this.mDelayCount >= 4) { this.mDelayDetectTime = curTime; this.mDelayCount = 0; return false; } } this.mDelayDetectTime = curTime; this.mDelayCount = 0; return shouldDelay; } } private class LocalPerformance { public int perfLockAcquire(int duration, int... list) { return 0; } } /* JADX ERROR: Method load error jadx.core.utils.exceptions.DecodeException: Load method exception: bogus opcode: 0073 in method: com.android.server.am.OppoAmsUtils.<clinit>():void, dex: at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:118) at jadx.core.dex.nodes.ClassNode.load(ClassNode.java:248) at jadx.core.ProcessClass.process(ProcessClass.java:29) at jadx.core.ProcessClass.lambda$processDependencies$0(ProcessClass.java:51) at java.lang.Iterable.forEach(Iterable.java:75) at jadx.core.ProcessClass.processDependencies(ProcessClass.java:51) at jadx.core.ProcessClass.process(ProcessClass.java:37) at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:292) at jadx.api.JavaClass.decompile(JavaClass.java:62) at jadx.api.JadxDecompiler.lambda$appendSourcesSave$0(JadxDecompiler.java:200) Caused by: java.lang.IllegalArgumentException: bogus opcode: 0073 at com.android.dx.io.OpcodeInfo.get(OpcodeInfo.java:1227) at com.android.dx.io.OpcodeInfo.getName(OpcodeInfo.java:1234) at jadx.core.dex.instructions.InsnDecoder.decode(InsnDecoder.java:581) at jadx.core.dex.instructions.InsnDecoder.process(InsnDecoder.java:74) at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:104) ... 9 more */ static { /* // Can't load method instructions: Load method exception: bogus opcode: 0073 in method: com.android.server.am.OppoAmsUtils.<clinit>():void, dex: */ throw new UnsupportedOperationException("Method not decompiled: com.android.server.am.OppoAmsUtils.<clinit>():void"); } public static OppoAmsUtils getInstance(ActivityManagerService service) { if (mInstance == null) { mInstance = new OppoAmsUtils(service); } return mInstance; } private OppoAmsUtils(ActivityManagerService service) { this.mIsSystemReady = false; this.mIsSupportActFreqCon = false; this.mActStartFreqControler = null; this.mActStartupAccelerator = null; this.mKeyguardServiceRestartDelay = null; this.mAm = service; } protected void systemReady() { initActStartFreqControl(); this.mActStartupAccelerator = new ActStartupAccelerator(); this.mKeyguardServiceRestartDelay = new KeyguardServiceRestartDelay(); this.mIsSystemReady = true; } private void initActStartFreqControl() { this.mIsSupportActFreqCon = this.mAm.mContext.getPackageManager().hasSystemFeature(FEATURE_ACT_FREQ_CONTROL); Slog.i(TAG, "mIsSupportActFreqCon:" + this.mIsSupportActFreqCon); if (this.mIsSupportActFreqCon) { this.mActStartFreqControler = new ActStartFreqControler(); } } /* JADX WARNING: Missing block: B:7:0x000e, code: return false; */ /* Code decompiled incorrectly, please refer to instructions dump. */ public boolean needToControlActivityStartFreq(Intent intent) { if (this.mIsSystemReady && this.mIsSupportActFreqCon && this.mActStartFreqControler != null) { return this.mActStartFreqControler.doControlActivityStartFreq(intent); } return false; } public boolean accelerateActStartup(Intent intent) { if (this.mIsSystemReady && this.mActStartupAccelerator != null) { return this.mActStartupAccelerator.doAccelerateActStartup(intent); } return false; } public boolean shouldDelayKeyguardServiceRestart(String shortName, boolean shouldDelay) { if (this.mIsSystemReady && this.mKeyguardServiceRestartDelay != null) { return this.mKeyguardServiceRestartDelay.shouldDelay(shortName, shouldDelay); } return false; } }
UTF-8
Java
14,697
java
OppoAmsUtils.java
Java
[]
null
[]
package com.android.server.am; import android.content.ComponentName; import android.content.Intent; import android.os.SystemClock; import android.util.Slog; import com.android.server.NetworkManagementService; import java.util.ArrayList; /* JADX ERROR: NullPointerException in pass: ReSugarCode java.lang.NullPointerException at jadx.core.dex.visitors.ReSugarCode.initClsEnumMap(ReSugarCode.java:159) at jadx.core.dex.visitors.ReSugarCode.visit(ReSugarCode.java:44) at jadx.core.dex.visitors.DepthTraversal.visit(DepthTraversal.java:12) at jadx.core.ProcessClass.process(ProcessClass.java:32) at jadx.core.ProcessClass.lambda$processDependencies$0(ProcessClass.java:51) at java.lang.Iterable.forEach(Iterable.java:75) at jadx.core.ProcessClass.processDependencies(ProcessClass.java:51) at jadx.core.ProcessClass.process(ProcessClass.java:37) at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:292) at jadx.api.JavaClass.decompile(JavaClass.java:62) at jadx.api.JadxDecompiler.lambda$appendSourcesSave$0(JadxDecompiler.java:200) */ /* JADX ERROR: NullPointerException in pass: ExtractFieldInit java.lang.NullPointerException at jadx.core.dex.visitors.ExtractFieldInit.checkStaticFieldsInit(ExtractFieldInit.java:58) at jadx.core.dex.visitors.ExtractFieldInit.visit(ExtractFieldInit.java:44) at jadx.core.dex.visitors.DepthTraversal.visit(DepthTraversal.java:12) at jadx.core.ProcessClass.process(ProcessClass.java:32) at jadx.core.ProcessClass.lambda$processDependencies$0(ProcessClass.java:51) at java.lang.Iterable.forEach(Iterable.java:75) at jadx.core.ProcessClass.processDependencies(ProcessClass.java:51) at jadx.core.ProcessClass.process(ProcessClass.java:37) at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:292) at jadx.api.JavaClass.decompile(JavaClass.java:62) at jadx.api.JadxDecompiler.lambda$appendSourcesSave$0(JadxDecompiler.java:200) */ class OppoAmsUtils { private static final String FEATURE_ACT_FREQ_CONTROL = "oppo.ams.act.freqcontrol"; static final String TAG = null; private static OppoAmsUtils mInstance; private ActStartFreqControler mActStartFreqControler; private ActStartupAccelerator mActStartupAccelerator; final ActivityManagerService mAm; private boolean mIsSupportActFreqCon; private boolean mIsSystemReady; private KeyguardServiceRestartDelay mKeyguardServiceRestartDelay; private class ActStartFreqControler { private static final boolean DEBUG_EMULATE = false; private static final boolean DEBUG_FREQ_CONTROL = false; private static final long DECT_TIME_MAX_INTERVEL = 30000; private static final long DECT_TIME_MIN_INTERVEL = 4000; private static final int MIN_START_DECT_COUNT = 3; private ArrayList<ActStartFreqData> mFreqControlActList = new ArrayList(); public ActStartFreqControler() { initActList(); } private void initActList() { this.mFreqControlActList.add(new ActStartFreqData("com.lianlian", "com.lianlian.activity.RetryAnonymousLoginActivity")); this.mFreqControlActList.add(new ActStartFreqData("tv.danmaku.bili", "tv.danmaku.bili.ui.video.VideoDetailsActivity")); this.mFreqControlActList.add(new ActStartFreqData("com.example.startactfreq", "com.example.startactfreq.FreqActivity")); } private ActStartFreqData getActStartFreqData(String pkgName, String className) { int size = this.mFreqControlActList.size(); for (int index = 0; index < size; index++) { ActStartFreqData tmpData = (ActStartFreqData) this.mFreqControlActList.get(index); if (tmpData != null && tmpData.mPkgName.equals(pkgName) && tmpData.mClassName.equals(className)) { return tmpData; } } return null; } public boolean doControlActivityStartFreq(Intent intent) { if (intent == null) { return false; } ComponentName cmpName = intent.getComponent(); if (cmpName == null) { return false; } String pkgName = cmpName.getPackageName(); String className = cmpName.getClassName(); if (pkgName == null || className == null) { return false; } ActStartFreqData data = getActStartFreqData(pkgName, className); if (data == null) { return false; } long curTime = SystemClock.elapsedRealtime(); long timeElapsed = curTime - data.mLastDectTime; data.mCount++; if (1 == data.mCount) { data.mLastDectTime = curTime; return false; } else if (!data.mIsFrequent) { if (timeElapsed > 4000) { data.mLastDectTime = curTime; data.mCount = 0; } else if (data.mCount >= 3) { data.mIsFrequent = true; data.mLastDectTime = curTime; } return false; } else if (timeElapsed <= DECT_TIME_MAX_INTERVEL) { data.mLastDectTime = curTime; return true; } else { data.mIsFrequent = false; data.mCount = 0; data.mLastDectTime = curTime; return false; } } } private class ActStartFreqData { String mClassName = null; int mCount = 0; boolean mIsFrequent = false; long mLastDectTime = 0; String mPkgName = null; public ActStartFreqData(String pkgName, String className) { this.mPkgName = pkgName; this.mClassName = className; this.mLastDectTime = SystemClock.elapsedRealtime(); this.mCount = 0; } public String toShortString() { return "mPkgName:" + this.mPkgName + ", mClassName" + this.mClassName + ", c:" + this.mCount; } } private class ActStartupAccelerator { private static final int ACCE_DURATION_TIME = 1000; private boolean DEBUG_ACT_ACCE = true; private ArrayList<String> mAccelerateActList = new ArrayList(); private long mLastAcceTime = 0; private LocalPerformance mLocalPerformance = null; private int[] mPerformanceConfigList = new int[]{1077936128, 1, 1086324736, 1, 1090519040, 2, 1082130432, NetworkManagementService.DNS_RESOLVER_DEFAULT_SAMPLE_VALIDITY_SECONDS}; private boolean mSupportActAccelerate = true; public ActStartupAccelerator() { initAccelaerateActList(); initPerformaceConfig(); } private void initAccelaerateActList() { if (this.mSupportActAccelerate) { this.mAccelerateActList.add("{com.tencent.mm/com.tencent.mm.plugin.voip.ui.VideoActivity}"); } } private void initPerformaceConfig() { if (this.mSupportActAccelerate) { this.mLocalPerformance = new LocalPerformance(); } } private boolean isInAcceList(String shortCmpName) { int size = this.mAccelerateActList.size(); for (int index = 0; index < size; index++) { String tmpData = (String) this.mAccelerateActList.get(index); if (this.DEBUG_ACT_ACCE) { Slog.d(OppoAmsUtils.TAG, "isInAcceList, index:" + index + ", shortCmpName:" + shortCmpName + ", data:" + tmpData); } if (tmpData != null && tmpData.equals(shortCmpName)) { return true; } } return false; } public boolean doAccelerateActStartup(Intent intent) { ComponentName cmpName = null; if (!this.mSupportActAccelerate) { return false; } if (intent != null) { cmpName = intent.getComponent(); } if (cmpName == null) { if (this.DEBUG_ACT_ACCE) { Slog.d(OppoAmsUtils.TAG, "doAccelerateActStartup cmpName null, not control"); } return false; } String shortName = cmpName.toShortString(); if (shortName == null || shortName.length() <= 0) { if (this.DEBUG_ACT_ACCE) { Slog.d(OppoAmsUtils.TAG, "doAccelerateActStartup shortName empty, not control"); } return false; } else if (isInAcceList(shortName)) { long curTime = SystemClock.elapsedRealtime(); if (this.mLastAcceTime > 0 && curTime - this.mLastAcceTime <= 1000) { return false; } this.mLastAcceTime = curTime; this.mLocalPerformance.perfLockAcquire(1000, this.mPerformanceConfigList); return true; } else { if (this.DEBUG_ACT_ACCE) { Slog.d(OppoAmsUtils.TAG, "doAccelerateActStartup data not found in list."); } return false; } } } private class KeyguardServiceRestartDelay { private static final String KEYGUARD_SERVICE = "com.android.keyguard/.KeyguardService"; private static final int MAX_DELAY_COUNT = 4; private static final long RESTART_DETECT_TIME = 6; private int mDelayCount = 0; private long mDelayDetectTime = 0; public boolean shouldDelay(String shortName, boolean shouldDelay) { if (!shouldDelay) { return false; } if (!KEYGUARD_SERVICE.equals(shortName)) { return shouldDelay; } if (this.mDelayCount == 0) { this.mDelayDetectTime = SystemClock.elapsedRealtime(); this.mDelayCount++; return shouldDelay; } long curTime = SystemClock.elapsedRealtime(); if (curTime - this.mDelayDetectTime <= RESTART_DETECT_TIME) { this.mDelayCount++; if (this.mDelayCount >= 4) { this.mDelayDetectTime = curTime; this.mDelayCount = 0; return false; } } this.mDelayDetectTime = curTime; this.mDelayCount = 0; return shouldDelay; } } private class LocalPerformance { public int perfLockAcquire(int duration, int... list) { return 0; } } /* JADX ERROR: Method load error jadx.core.utils.exceptions.DecodeException: Load method exception: bogus opcode: 0073 in method: com.android.server.am.OppoAmsUtils.<clinit>():void, dex: at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:118) at jadx.core.dex.nodes.ClassNode.load(ClassNode.java:248) at jadx.core.ProcessClass.process(ProcessClass.java:29) at jadx.core.ProcessClass.lambda$processDependencies$0(ProcessClass.java:51) at java.lang.Iterable.forEach(Iterable.java:75) at jadx.core.ProcessClass.processDependencies(ProcessClass.java:51) at jadx.core.ProcessClass.process(ProcessClass.java:37) at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:292) at jadx.api.JavaClass.decompile(JavaClass.java:62) at jadx.api.JadxDecompiler.lambda$appendSourcesSave$0(JadxDecompiler.java:200) Caused by: java.lang.IllegalArgumentException: bogus opcode: 0073 at com.android.dx.io.OpcodeInfo.get(OpcodeInfo.java:1227) at com.android.dx.io.OpcodeInfo.getName(OpcodeInfo.java:1234) at jadx.core.dex.instructions.InsnDecoder.decode(InsnDecoder.java:581) at jadx.core.dex.instructions.InsnDecoder.process(InsnDecoder.java:74) at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:104) ... 9 more */ static { /* // Can't load method instructions: Load method exception: bogus opcode: 0073 in method: com.android.server.am.OppoAmsUtils.<clinit>():void, dex: */ throw new UnsupportedOperationException("Method not decompiled: com.android.server.am.OppoAmsUtils.<clinit>():void"); } public static OppoAmsUtils getInstance(ActivityManagerService service) { if (mInstance == null) { mInstance = new OppoAmsUtils(service); } return mInstance; } private OppoAmsUtils(ActivityManagerService service) { this.mIsSystemReady = false; this.mIsSupportActFreqCon = false; this.mActStartFreqControler = null; this.mActStartupAccelerator = null; this.mKeyguardServiceRestartDelay = null; this.mAm = service; } protected void systemReady() { initActStartFreqControl(); this.mActStartupAccelerator = new ActStartupAccelerator(); this.mKeyguardServiceRestartDelay = new KeyguardServiceRestartDelay(); this.mIsSystemReady = true; } private void initActStartFreqControl() { this.mIsSupportActFreqCon = this.mAm.mContext.getPackageManager().hasSystemFeature(FEATURE_ACT_FREQ_CONTROL); Slog.i(TAG, "mIsSupportActFreqCon:" + this.mIsSupportActFreqCon); if (this.mIsSupportActFreqCon) { this.mActStartFreqControler = new ActStartFreqControler(); } } /* JADX WARNING: Missing block: B:7:0x000e, code: return false; */ /* Code decompiled incorrectly, please refer to instructions dump. */ public boolean needToControlActivityStartFreq(Intent intent) { if (this.mIsSystemReady && this.mIsSupportActFreqCon && this.mActStartFreqControler != null) { return this.mActStartFreqControler.doControlActivityStartFreq(intent); } return false; } public boolean accelerateActStartup(Intent intent) { if (this.mIsSystemReady && this.mActStartupAccelerator != null) { return this.mActStartupAccelerator.doAccelerateActStartup(intent); } return false; } public boolean shouldDelayKeyguardServiceRestart(String shortName, boolean shouldDelay) { if (this.mIsSystemReady && this.mKeyguardServiceRestartDelay != null) { return this.mKeyguardServiceRestartDelay.shouldDelay(shortName, shouldDelay); } return false; } }
14,697
0.626522
0.61271
340
42.226471
31.234953
185
false
false
0
0
0
0
0
0
0.638235
false
false
4
08cef1813017c472c693062983930c84caae7df9
21,595,095,569,531
79d31217a047001578220fd3dc860ec2b171034c
/captcha/src/test/java/io/nixer/nixerplugin/captcha/recaptcha/RecaptchaV2ServiceTest.java
9262df533fff1ce23ef0d00a0161fe7f47e982cc
[ "Apache-2.0" ]
permissive
nixer-io/nixer-spring-plugin
https://github.com/nixer-io/nixer-spring-plugin
aa53cadfa0fd1b71efdbed2dc1c74f323e65dc3f
5ef6afd938ed38b1a8f845d0c2a25cb012e5b988
refs/heads/master
2023-02-07T04:45:06.016000
2023-01-24T08:35:12
2023-01-24T08:35:12
216,840,838
12
2
Apache-2.0
false
2022-12-27T16:34:56
2019-10-22T14:58:10
2022-07-19T09:25:11
2022-12-27T16:34:56
1,568
6
2
4
Java
false
false
package io.nixer.nixerplugin.captcha.recaptcha; import com.google.common.collect.ImmutableList; import io.nixer.nixerplugin.captcha.error.CaptchaErrors; import io.nixer.nixerplugin.captcha.error.CaptchaClientException; import io.nixer.nixerplugin.captcha.error.CaptchaServiceException; import io.nixer.nixerplugin.captcha.metrics.CaptchaMetricsReporter; import io.nixer.nixerplugin.captcha.metrics.CaptchaMetricsReporter; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.web.client.RestClientException; import static io.nixer.nixerplugin.captcha.recaptcha.RecaptchaVerifyResponse.ErrorCode.InvalidResponse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.BDDMockito.given; @ExtendWith(MockitoExtension.class) class RecaptchaV2ServiceTest { private RecaptchaV2Service captchaService; @Mock private RecaptchaClient recaptchaClient; @Mock private CaptchaMetricsReporter captchaMetricsReporter; @BeforeEach void init() { captchaService = new RecaptchaV2Service(recaptchaClient, captchaMetricsReporter); } @Test void should_throw_exception_when_captcha_empty() { assertThrows(CaptchaClientException.class, () -> captchaService.verifyResponse("")); } @Test void should_throw_exception_when_captcha_misformatted() { assertThrows(CaptchaClientException.class, () -> captchaService.verifyResponse("!")); } @Test void should_throw_exception_when_got_timeout() { given(recaptchaClient.call("good")) .willThrow(CaptchaErrors.serviceFailure("timeout", new RestClientException("timeout"))); assertThrows(CaptchaServiceException.class, () -> captchaService.verifyResponse("good")); } @Test void should_throw_exception_when_error_received() { given(recaptchaClient.call("bad")) .willReturn(new RecaptchaVerifyResponse(false, "", "host", ImmutableList.of(RecaptchaVerifyResponse.ErrorCode.InvalidResponse))); assertThrows(CaptchaClientException.class, () -> captchaService.verifyResponse("bad")); } @Test void should_not_throw_exception_if_ok() { given(recaptchaClient.call("good")) .willReturn(new RecaptchaVerifyResponse(true, "", "host", ImmutableList.of())); captchaService.verifyResponse("good"); } }
UTF-8
Java
2,537
java
RecaptchaV2ServiceTest.java
Java
[]
null
[]
package io.nixer.nixerplugin.captcha.recaptcha; import com.google.common.collect.ImmutableList; import io.nixer.nixerplugin.captcha.error.CaptchaErrors; import io.nixer.nixerplugin.captcha.error.CaptchaClientException; import io.nixer.nixerplugin.captcha.error.CaptchaServiceException; import io.nixer.nixerplugin.captcha.metrics.CaptchaMetricsReporter; import io.nixer.nixerplugin.captcha.metrics.CaptchaMetricsReporter; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.web.client.RestClientException; import static io.nixer.nixerplugin.captcha.recaptcha.RecaptchaVerifyResponse.ErrorCode.InvalidResponse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.BDDMockito.given; @ExtendWith(MockitoExtension.class) class RecaptchaV2ServiceTest { private RecaptchaV2Service captchaService; @Mock private RecaptchaClient recaptchaClient; @Mock private CaptchaMetricsReporter captchaMetricsReporter; @BeforeEach void init() { captchaService = new RecaptchaV2Service(recaptchaClient, captchaMetricsReporter); } @Test void should_throw_exception_when_captcha_empty() { assertThrows(CaptchaClientException.class, () -> captchaService.verifyResponse("")); } @Test void should_throw_exception_when_captcha_misformatted() { assertThrows(CaptchaClientException.class, () -> captchaService.verifyResponse("!")); } @Test void should_throw_exception_when_got_timeout() { given(recaptchaClient.call("good")) .willThrow(CaptchaErrors.serviceFailure("timeout", new RestClientException("timeout"))); assertThrows(CaptchaServiceException.class, () -> captchaService.verifyResponse("good")); } @Test void should_throw_exception_when_error_received() { given(recaptchaClient.call("bad")) .willReturn(new RecaptchaVerifyResponse(false, "", "host", ImmutableList.of(RecaptchaVerifyResponse.ErrorCode.InvalidResponse))); assertThrows(CaptchaClientException.class, () -> captchaService.verifyResponse("bad")); } @Test void should_not_throw_exception_if_ok() { given(recaptchaClient.call("good")) .willReturn(new RecaptchaVerifyResponse(true, "", "host", ImmutableList.of())); captchaService.verifyResponse("good"); } }
2,537
0.748916
0.747734
70
35.242859
34.433968
145
false
false
0
0
0
0
0
0
0.571429
false
false
4
0d0b649eff1f1ba457c1b96970f1130ccdf870fb
721,554,517,812
e411638b54e787befdb813c7bc03f6c29797bd6b
/android/src/main/java/org/vovkasm/WebImage/MonoBorder.java
fc503b56cb68e59b5f42d6b9b16834e78cb451d7
[ "MIT", "Apache-2.0" ]
permissive
vovkasm/react-native-web-image
https://github.com/vovkasm/react-native-web-image
955e18df8687b82575ca1e83a728f7d0e97eb826
e269cc5f8aad06e6e7429ddc6de95bd20ff82407
refs/heads/develop
2023-01-06T23:18:04.703000
2019-08-03T07:11:53
2019-08-03T07:11:53
74,192,763
159
35
MIT
false
2023-01-03T15:13:59
2016-11-19T06:56:55
2022-12-19T15:10:58
2023-01-03T15:13:59
30,912
148
26
33
Java
false
false
package org.vovkasm.WebImage; import android.graphics.Canvas; import androidx.annotation.ColorInt; import androidx.annotation.NonNull; class MonoBorder extends BaseBorder { public void setColor(@ColorInt final int color) { mPaint.setColor(color); } @Override public void draw(@NonNull Canvas canvas) { canvas.drawPath(mBoxMetrics.getBorderPath(), mPaint); } }
UTF-8
Java
401
java
MonoBorder.java
Java
[]
null
[]
package org.vovkasm.WebImage; import android.graphics.Canvas; import androidx.annotation.ColorInt; import androidx.annotation.NonNull; class MonoBorder extends BaseBorder { public void setColor(@ColorInt final int color) { mPaint.setColor(color); } @Override public void draw(@NonNull Canvas canvas) { canvas.drawPath(mBoxMetrics.getBorderPath(), mPaint); } }
401
0.723192
0.723192
18
21.277779
20.2342
61
false
false
0
0
0
0
0
0
0.388889
false
false
4
3115629623df3cb76a6161038016e6dfbdb1aaf5
21,234,318,344,684
e693a3be6644b74b5cd4fc20d0f9a1db78671c55
/src/test/java/com/banana/utilities/FakeExpenseFetcher.java
b30c795083de3c829a5fe36e0400ea06ee62c504
[]
no_license
Cyphle/Banana
https://github.com/Cyphle/Banana
680519398b79917d42d07bce9ea7a3634f1a272c
9f29a375dbb609f2930eb88e82a6ff516eb4622b
refs/heads/master
2021-01-18T23:23:58.035000
2017-08-20T10:10:07
2017-08-20T10:10:07
53,219,712
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.banana.utilities; import com.banana.domain.adapters.IExpenseFetcher; import com.banana.domain.models.Account; import com.banana.domain.models.Budget; import com.banana.domain.models.Expense; import com.banana.utils.Moment; import java.util.ArrayList; import java.util.List; public class FakeExpenseFetcher implements IExpenseFetcher { public List<Expense> getExpensesOfAccount(Account account) { return this.getExpenses(); } public List<Expense> getExpensesOfBudget(Budget budget) { return this.getExpenses(); } public Expense createAccountExpense(long accountId, Expense expense) { return new Expense(1, "Courses", 24, (new Moment("2017-07-18")).getDate()); } public Expense createBudgetExpense(long budgetId, Expense expense) { return new Expense(1, "Courses", 24, (new Moment("2017-07-18")).getDate()); } public Expense updateBudgetExpense(long budgetId, Expense expense) { return expense; } public Expense updateAccountExpense(long accountId, Expense expense) { return expense; } private List<Expense> getExpenses() { Expense expenseOne = new Expense("Courses", 24, (new Moment("2017-07-10")).getDate()); Expense expenseTwo = new Expense("Bar", 40, (new Moment("2017-08-01")).getDate()); List<Expense> expenses = new ArrayList<>(); expenses.add(expenseOne); expenses.add(expenseTwo); return expenses; } public boolean deleteExpense(Expense expense) { return true; } }
UTF-8
Java
1,478
java
FakeExpenseFetcher.java
Java
[]
null
[]
package com.banana.utilities; import com.banana.domain.adapters.IExpenseFetcher; import com.banana.domain.models.Account; import com.banana.domain.models.Budget; import com.banana.domain.models.Expense; import com.banana.utils.Moment; import java.util.ArrayList; import java.util.List; public class FakeExpenseFetcher implements IExpenseFetcher { public List<Expense> getExpensesOfAccount(Account account) { return this.getExpenses(); } public List<Expense> getExpensesOfBudget(Budget budget) { return this.getExpenses(); } public Expense createAccountExpense(long accountId, Expense expense) { return new Expense(1, "Courses", 24, (new Moment("2017-07-18")).getDate()); } public Expense createBudgetExpense(long budgetId, Expense expense) { return new Expense(1, "Courses", 24, (new Moment("2017-07-18")).getDate()); } public Expense updateBudgetExpense(long budgetId, Expense expense) { return expense; } public Expense updateAccountExpense(long accountId, Expense expense) { return expense; } private List<Expense> getExpenses() { Expense expenseOne = new Expense("Courses", 24, (new Moment("2017-07-10")).getDate()); Expense expenseTwo = new Expense("Bar", 40, (new Moment("2017-08-01")).getDate()); List<Expense> expenses = new ArrayList<>(); expenses.add(expenseOne); expenses.add(expenseTwo); return expenses; } public boolean deleteExpense(Expense expense) { return true; } }
1,478
0.728011
0.699594
49
29.163265
28.102108
90
false
false
0
0
0
0
0
0
0.714286
false
false
4
e075c636363e13472f8d9d9cac23a5b285fa5e74
12,300,786,379,265
3806a370921471c68ea4c52f048def6c2371264f
/app/src/main/java/com/cesarpim/androidcourse/popularmovies/DetailsActivity.java
8d19ef7883b751b6e1cd3126c3bce2dd2465519a
[]
no_license
cesarpim/PopularMovies
https://github.com/cesarpim/PopularMovies
5f5c786fad1d3cf9febd7f571eff886f51ba0f79
2a9a16a13dfabd5f8eba237e81f957fca1b49e79
refs/heads/master
2020-12-30T23:46:26.606000
2017-03-21T23:09:24
2017-03-21T23:09:24
80,571,075
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cesarpim.androidcourse.popularmovies; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.support.v4.app.LoaderManager; import android.support.v4.content.AsyncTaskLoader; import android.support.v4.content.Loader; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import android.widget.ToggleButton; import com.cesarpim.androidcourse.popularmovies.data.FavoriteMoviesContract; import com.squareup.picasso.Picasso; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; public class DetailsActivity extends AppCompatActivity implements TrailersAdapter.TrailerClickListener, LoaderManager.LoaderCallbacks<String> { private static final int TRAILERS_LOADER_ID = 2001; private static final int REVIEWS_LOADER_ID = 2002; private static final int FAVORITE_CHECK_LOADER_ID = 2003; private static final int FAVORITE_TOGGLE_LOADER_ID = 2004; private ImageView posterImageView; private TextView titleTextView; private TextView dateTextView; private TextView ratingTextView; private TextView synopsisTextView; private ToggleButton favoriteToggleButton; private TextView trailersTitleText; private TextView reviewsTitleText; private RecyclerView trailersRecyclerView; private RecyclerView reviewsRecyclerView; private TrailersAdapter trailersAdapter = null; private ReviewsAdapter reviewsAdapter = null; private Movie movie = null; private Uri movieUri; /** * Loader that returns a boolean indicating whether the movie is or isn't in the favorites. */ private LoaderManager.LoaderCallbacks<Boolean> favoriteCheckLoaderListener = new LoaderManager.LoaderCallbacks<Boolean>() { @Override public Loader<Boolean> onCreateLoader(int id, Bundle args) { return new AsyncTaskLoader<Boolean>(DetailsActivity.this) { @Override protected void onStartLoading() { super.onStartLoading(); forceLoad(); } @Override public Boolean loadInBackground() { Boolean isFavorite = false; Cursor queryResult = null; try { queryResult = getContentResolver() .query(movieUri, null, null, null, null); } finally { if (queryResult != null) { isFavorite = queryResult.getCount() > 0; queryResult.close(); } } return isFavorite; } }; } @Override public void onLoadFinished(Loader<Boolean> loader, Boolean data) { favoriteToggleButton.setChecked(data); favoriteToggleButton.setEnabled(true); } @Override public void onLoaderReset(Loader<Boolean> loader) { } }; /** * Loader that inserts/deletes the movie to/from the favorites */ private LoaderManager.LoaderCallbacks<Void> favoriteToggleLoaderListener = new LoaderManager.LoaderCallbacks<Void>() { @Override public Loader<Void> onCreateLoader(int id, Bundle args) { return new AsyncTaskLoader<Void>(DetailsActivity.this) { @Override protected void onStartLoading() { super.onStartLoading(); forceLoad(); } @Override public Void loadInBackground() { if (favoriteToggleButton.isChecked()) { addFavorite(); } else { deleteFavorite(); } return null; } }; } @Override public void onLoadFinished(Loader<Void> loader, Void data) { } @Override public void onLoaderReset(Loader<Void> loader) { } }; @Override public void onTrailerClick(String clickedTrailerYoutubeKey) { String trailerAddress = String.format( getString(R.string.youtube_video_template_address), clickedTrailerYoutubeKey); Uri trailerUri = Uri.parse(trailerAddress); Intent launchTrailerIntent = new Intent(Intent.ACTION_VIEW, trailerUri); startActivity(launchTrailerIntent); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_details); posterImageView = (ImageView) findViewById(R.id.image_poster); titleTextView = (TextView) findViewById(R.id.text_original_title); dateTextView = (TextView) findViewById(R.id.text_release_date); ratingTextView = (TextView) findViewById(R.id.text_rating); synopsisTextView = (TextView) findViewById(R.id.text_synopsis); favoriteToggleButton = (ToggleButton) findViewById(R.id.toggle_favorite); trailersTitleText = (TextView) findViewById(R.id.text_trailers_title); reviewsTitleText = (TextView) findViewById(R.id.text_reviews_title); trailersRecyclerView = initRecyclerView(R.id.recycler_trailers); reviewsRecyclerView = initRecyclerView(R.id.recycler_reviews); trailersAdapter = new TrailersAdapter(new Trailer[0], DetailsActivity.this); trailersRecyclerView.setAdapter(trailersAdapter); reviewsAdapter = new ReviewsAdapter(new Review[0]); reviewsRecyclerView.setAdapter(reviewsAdapter); Intent launchIntent = getIntent(); if (launchIntent.hasExtra(getString(R.string.intent_extra_movie_key))) { movie = (Movie) launchIntent.getSerializableExtra(getString(R.string.intent_extra_movie_key)); } if (movie != null) { loadViews(); } } private RecyclerView initRecyclerView(int viewResId) { RecyclerView recyclerView = (RecyclerView) findViewById(viewResId); recyclerView.setLayoutManager(new LinearLayoutManager(this)); recyclerView.setHasFixedSize(true); recyclerView.setNestedScrollingEnabled(false); return recyclerView; } private void loadViews() { String posterStringURL = getString(R.string.themoviedb_image_base_url) + getString(R.string.themoviedb_image_size) + movie.getPosterPath(); Picasso.with(this).load(posterStringURL).into(posterImageView); titleTextView.setText(movie.getOriginalTitle()); DateFormat dateFormat = new SimpleDateFormat(getString(R.string.details_release_date_format)); dateTextView.setText(dateFormat.format(movie.getReleaseDate())); String ratingString = String.valueOf(movie.getRating()) + getString(R.string.details_rating_cap); ratingTextView.setText(ratingString); synopsisTextView.setText(movie.getSynopsis()); movieUri = FavoriteMoviesContract.MovieEntry.CONTENT_URI.buildUpon() .appendPath(Integer.toString(movie.getId())) .build(); LoaderManager manager = getSupportLoaderManager(); manager.initLoader(FAVORITE_CHECK_LOADER_ID, null, favoriteCheckLoaderListener); manager.initLoader(TRAILERS_LOADER_ID, null, this); manager.initLoader(REVIEWS_LOADER_ID, null, this); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); return true; default: return super.onOptionsItemSelected(item); } } public void onClickToggleFavorite(View view) { getSupportLoaderManager() .restartLoader(FAVORITE_TOGGLE_LOADER_ID, null, favoriteToggleLoaderListener); } private void addFavorite() { if (movie != null) { ContentValues contentValues = new ContentValues(); contentValues.put(FavoriteMoviesContract.MovieEntry.COLUMN_API_MOVIE_ID, movie.getId()); contentValues.put( FavoriteMoviesContract.MovieEntry.COLUMN_ORIGINAL_TITLE, movie.getOriginalTitle()); contentValues.put( FavoriteMoviesContract.MovieEntry.COLUMN_POSTER_PATH, movie.getPosterPath()); contentValues.put( FavoriteMoviesContract.MovieEntry.COLUMN_SYNOPSIS, movie.getSynopsis()); contentValues.put( FavoriteMoviesContract.MovieEntry.COLUMN_RATING, movie.getRating()); contentValues.put( FavoriteMoviesContract.MovieEntry.COLUMN_RELEASE_DATE, movie.getReleaseDate().getTime()); getContentResolver() .insert(FavoriteMoviesContract.MovieEntry.CONTENT_URI, contentValues); } } private void deleteFavorite() { if (movie != null) { getContentResolver().delete(movieUri, null, null); } } private Trailer[] getTrailersFromJSONString(String s) throws JSONException, ParseException { JSONObject jsonObject = new JSONObject(s); JSONArray jsonArray = jsonObject.getJSONArray( getString(R.string.themoviedb_json_trailer_results_tag)); int numTrailers = jsonArray.length(); Trailer[] trailersRead = new Trailer[numTrailers]; for (int i = 0; i < numTrailers; i++) { JSONObject jsonTrailer = jsonArray.getJSONObject(i); trailersRead[i] = new Trailer( jsonTrailer.getString( getString(R.string.themoviedb_json_trailer_title_tag)), jsonTrailer.getString( getString(R.string.themoviedb_json_trailer_youtube_key_tag))); } return trailersRead; } private Review[] getReviewsFromJSONString(String s) throws JSONException, ParseException { JSONObject jsonObject = new JSONObject(s); JSONArray jsonArray = jsonObject.getJSONArray( getString(R.string.themoviedb_json_review_results_tag)); int numReviews = jsonArray.length(); Review[] reviewsRead = new Review[numReviews]; for (int i = 0; i < numReviews; i++) { JSONObject jsonTrailer = jsonArray.getJSONObject(i); reviewsRead[i] = new Review( jsonTrailer.getString( getString(R.string.themoviedb_json_review_author_tag)), jsonTrailer.getString( getString(R.string.themoviedb_json_review_content_key_tag))); } return reviewsRead; } @Override public Loader<String> onCreateLoader(int id, Bundle args) { final int pathResId; switch (id) { case TRAILERS_LOADER_ID: pathResId = R.string.themoviedb_trailers_path; break; case REVIEWS_LOADER_ID: pathResId = R.string.themoviedb_reviews_path; break; default: throw new RuntimeException("Invalid loader id: " + id); } return new AsyncTaskLoader<String>(this) { @Override protected void onStartLoading() { super.onStartLoading(); forceLoad(); } @Override public String loadInBackground() { return MoviesApiUtils.getResponse( DetailsActivity.this, new String[] {"" + movie.getId(), getString(pathResId)}); } }; } @Override public void onLoadFinished(Loader<String> loader, String data) { int id = loader.getId(); switch (id) { case TRAILERS_LOADER_ID: if ((data != null) && (!data.equals(""))) { Trailer[] trailers; try { trailers = getTrailersFromJSONString(data); } catch (JSONException|ParseException e) { trailers = new Trailer[0]; e.printStackTrace(); } trailersTitleText.setText(getString(trailers.length == 0 ? R.string.no_trailers_title : R.string.trailers_title)); trailersAdapter.updateTrailers(trailers); } break; case REVIEWS_LOADER_ID: if ((data != null) && (!data.equals(""))) { Review[] reviews; try { reviews = getReviewsFromJSONString(data); } catch (JSONException|ParseException e) { reviews = new Review[0]; e.printStackTrace(); } reviewsTitleText.setText(getString(reviews.length == 0 ? R.string.no_reviews_title : R.string.reviews_title)); reviewsAdapter.updateReviews(reviews); } break; default: throw new RuntimeException("Invalid loader id: " + id); } } @Override public void onLoaderReset(Loader<String> loader) { int id = loader.getId(); switch (id) { case TRAILERS_LOADER_ID: if (trailersAdapter != null) { trailersAdapter.updateTrailers(null); } break; case REVIEWS_LOADER_ID: if (reviewsAdapter != null) { reviewsAdapter.updateReviews(null); } break; default: throw new RuntimeException("Invalid loader id: " + id); } } }
UTF-8
Java
15,124
java
DetailsActivity.java
Java
[]
null
[]
package com.cesarpim.androidcourse.popularmovies; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.support.v4.app.LoaderManager; import android.support.v4.content.AsyncTaskLoader; import android.support.v4.content.Loader; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import android.widget.ToggleButton; import com.cesarpim.androidcourse.popularmovies.data.FavoriteMoviesContract; import com.squareup.picasso.Picasso; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; public class DetailsActivity extends AppCompatActivity implements TrailersAdapter.TrailerClickListener, LoaderManager.LoaderCallbacks<String> { private static final int TRAILERS_LOADER_ID = 2001; private static final int REVIEWS_LOADER_ID = 2002; private static final int FAVORITE_CHECK_LOADER_ID = 2003; private static final int FAVORITE_TOGGLE_LOADER_ID = 2004; private ImageView posterImageView; private TextView titleTextView; private TextView dateTextView; private TextView ratingTextView; private TextView synopsisTextView; private ToggleButton favoriteToggleButton; private TextView trailersTitleText; private TextView reviewsTitleText; private RecyclerView trailersRecyclerView; private RecyclerView reviewsRecyclerView; private TrailersAdapter trailersAdapter = null; private ReviewsAdapter reviewsAdapter = null; private Movie movie = null; private Uri movieUri; /** * Loader that returns a boolean indicating whether the movie is or isn't in the favorites. */ private LoaderManager.LoaderCallbacks<Boolean> favoriteCheckLoaderListener = new LoaderManager.LoaderCallbacks<Boolean>() { @Override public Loader<Boolean> onCreateLoader(int id, Bundle args) { return new AsyncTaskLoader<Boolean>(DetailsActivity.this) { @Override protected void onStartLoading() { super.onStartLoading(); forceLoad(); } @Override public Boolean loadInBackground() { Boolean isFavorite = false; Cursor queryResult = null; try { queryResult = getContentResolver() .query(movieUri, null, null, null, null); } finally { if (queryResult != null) { isFavorite = queryResult.getCount() > 0; queryResult.close(); } } return isFavorite; } }; } @Override public void onLoadFinished(Loader<Boolean> loader, Boolean data) { favoriteToggleButton.setChecked(data); favoriteToggleButton.setEnabled(true); } @Override public void onLoaderReset(Loader<Boolean> loader) { } }; /** * Loader that inserts/deletes the movie to/from the favorites */ private LoaderManager.LoaderCallbacks<Void> favoriteToggleLoaderListener = new LoaderManager.LoaderCallbacks<Void>() { @Override public Loader<Void> onCreateLoader(int id, Bundle args) { return new AsyncTaskLoader<Void>(DetailsActivity.this) { @Override protected void onStartLoading() { super.onStartLoading(); forceLoad(); } @Override public Void loadInBackground() { if (favoriteToggleButton.isChecked()) { addFavorite(); } else { deleteFavorite(); } return null; } }; } @Override public void onLoadFinished(Loader<Void> loader, Void data) { } @Override public void onLoaderReset(Loader<Void> loader) { } }; @Override public void onTrailerClick(String clickedTrailerYoutubeKey) { String trailerAddress = String.format( getString(R.string.youtube_video_template_address), clickedTrailerYoutubeKey); Uri trailerUri = Uri.parse(trailerAddress); Intent launchTrailerIntent = new Intent(Intent.ACTION_VIEW, trailerUri); startActivity(launchTrailerIntent); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_details); posterImageView = (ImageView) findViewById(R.id.image_poster); titleTextView = (TextView) findViewById(R.id.text_original_title); dateTextView = (TextView) findViewById(R.id.text_release_date); ratingTextView = (TextView) findViewById(R.id.text_rating); synopsisTextView = (TextView) findViewById(R.id.text_synopsis); favoriteToggleButton = (ToggleButton) findViewById(R.id.toggle_favorite); trailersTitleText = (TextView) findViewById(R.id.text_trailers_title); reviewsTitleText = (TextView) findViewById(R.id.text_reviews_title); trailersRecyclerView = initRecyclerView(R.id.recycler_trailers); reviewsRecyclerView = initRecyclerView(R.id.recycler_reviews); trailersAdapter = new TrailersAdapter(new Trailer[0], DetailsActivity.this); trailersRecyclerView.setAdapter(trailersAdapter); reviewsAdapter = new ReviewsAdapter(new Review[0]); reviewsRecyclerView.setAdapter(reviewsAdapter); Intent launchIntent = getIntent(); if (launchIntent.hasExtra(getString(R.string.intent_extra_movie_key))) { movie = (Movie) launchIntent.getSerializableExtra(getString(R.string.intent_extra_movie_key)); } if (movie != null) { loadViews(); } } private RecyclerView initRecyclerView(int viewResId) { RecyclerView recyclerView = (RecyclerView) findViewById(viewResId); recyclerView.setLayoutManager(new LinearLayoutManager(this)); recyclerView.setHasFixedSize(true); recyclerView.setNestedScrollingEnabled(false); return recyclerView; } private void loadViews() { String posterStringURL = getString(R.string.themoviedb_image_base_url) + getString(R.string.themoviedb_image_size) + movie.getPosterPath(); Picasso.with(this).load(posterStringURL).into(posterImageView); titleTextView.setText(movie.getOriginalTitle()); DateFormat dateFormat = new SimpleDateFormat(getString(R.string.details_release_date_format)); dateTextView.setText(dateFormat.format(movie.getReleaseDate())); String ratingString = String.valueOf(movie.getRating()) + getString(R.string.details_rating_cap); ratingTextView.setText(ratingString); synopsisTextView.setText(movie.getSynopsis()); movieUri = FavoriteMoviesContract.MovieEntry.CONTENT_URI.buildUpon() .appendPath(Integer.toString(movie.getId())) .build(); LoaderManager manager = getSupportLoaderManager(); manager.initLoader(FAVORITE_CHECK_LOADER_ID, null, favoriteCheckLoaderListener); manager.initLoader(TRAILERS_LOADER_ID, null, this); manager.initLoader(REVIEWS_LOADER_ID, null, this); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); return true; default: return super.onOptionsItemSelected(item); } } public void onClickToggleFavorite(View view) { getSupportLoaderManager() .restartLoader(FAVORITE_TOGGLE_LOADER_ID, null, favoriteToggleLoaderListener); } private void addFavorite() { if (movie != null) { ContentValues contentValues = new ContentValues(); contentValues.put(FavoriteMoviesContract.MovieEntry.COLUMN_API_MOVIE_ID, movie.getId()); contentValues.put( FavoriteMoviesContract.MovieEntry.COLUMN_ORIGINAL_TITLE, movie.getOriginalTitle()); contentValues.put( FavoriteMoviesContract.MovieEntry.COLUMN_POSTER_PATH, movie.getPosterPath()); contentValues.put( FavoriteMoviesContract.MovieEntry.COLUMN_SYNOPSIS, movie.getSynopsis()); contentValues.put( FavoriteMoviesContract.MovieEntry.COLUMN_RATING, movie.getRating()); contentValues.put( FavoriteMoviesContract.MovieEntry.COLUMN_RELEASE_DATE, movie.getReleaseDate().getTime()); getContentResolver() .insert(FavoriteMoviesContract.MovieEntry.CONTENT_URI, contentValues); } } private void deleteFavorite() { if (movie != null) { getContentResolver().delete(movieUri, null, null); } } private Trailer[] getTrailersFromJSONString(String s) throws JSONException, ParseException { JSONObject jsonObject = new JSONObject(s); JSONArray jsonArray = jsonObject.getJSONArray( getString(R.string.themoviedb_json_trailer_results_tag)); int numTrailers = jsonArray.length(); Trailer[] trailersRead = new Trailer[numTrailers]; for (int i = 0; i < numTrailers; i++) { JSONObject jsonTrailer = jsonArray.getJSONObject(i); trailersRead[i] = new Trailer( jsonTrailer.getString( getString(R.string.themoviedb_json_trailer_title_tag)), jsonTrailer.getString( getString(R.string.themoviedb_json_trailer_youtube_key_tag))); } return trailersRead; } private Review[] getReviewsFromJSONString(String s) throws JSONException, ParseException { JSONObject jsonObject = new JSONObject(s); JSONArray jsonArray = jsonObject.getJSONArray( getString(R.string.themoviedb_json_review_results_tag)); int numReviews = jsonArray.length(); Review[] reviewsRead = new Review[numReviews]; for (int i = 0; i < numReviews; i++) { JSONObject jsonTrailer = jsonArray.getJSONObject(i); reviewsRead[i] = new Review( jsonTrailer.getString( getString(R.string.themoviedb_json_review_author_tag)), jsonTrailer.getString( getString(R.string.themoviedb_json_review_content_key_tag))); } return reviewsRead; } @Override public Loader<String> onCreateLoader(int id, Bundle args) { final int pathResId; switch (id) { case TRAILERS_LOADER_ID: pathResId = R.string.themoviedb_trailers_path; break; case REVIEWS_LOADER_ID: pathResId = R.string.themoviedb_reviews_path; break; default: throw new RuntimeException("Invalid loader id: " + id); } return new AsyncTaskLoader<String>(this) { @Override protected void onStartLoading() { super.onStartLoading(); forceLoad(); } @Override public String loadInBackground() { return MoviesApiUtils.getResponse( DetailsActivity.this, new String[] {"" + movie.getId(), getString(pathResId)}); } }; } @Override public void onLoadFinished(Loader<String> loader, String data) { int id = loader.getId(); switch (id) { case TRAILERS_LOADER_ID: if ((data != null) && (!data.equals(""))) { Trailer[] trailers; try { trailers = getTrailersFromJSONString(data); } catch (JSONException|ParseException e) { trailers = new Trailer[0]; e.printStackTrace(); } trailersTitleText.setText(getString(trailers.length == 0 ? R.string.no_trailers_title : R.string.trailers_title)); trailersAdapter.updateTrailers(trailers); } break; case REVIEWS_LOADER_ID: if ((data != null) && (!data.equals(""))) { Review[] reviews; try { reviews = getReviewsFromJSONString(data); } catch (JSONException|ParseException e) { reviews = new Review[0]; e.printStackTrace(); } reviewsTitleText.setText(getString(reviews.length == 0 ? R.string.no_reviews_title : R.string.reviews_title)); reviewsAdapter.updateReviews(reviews); } break; default: throw new RuntimeException("Invalid loader id: " + id); } } @Override public void onLoaderReset(Loader<String> loader) { int id = loader.getId(); switch (id) { case TRAILERS_LOADER_ID: if (trailersAdapter != null) { trailersAdapter.updateTrailers(null); } break; case REVIEWS_LOADER_ID: if (reviewsAdapter != null) { reviewsAdapter.updateReviews(null); } break; default: throw new RuntimeException("Invalid loader id: " + id); } } }
15,124
0.572071
0.570021
363
40.663914
24.720085
106
false
false
0
0
0
0
0
0
0.564738
false
false
4
107e024466c00f71292200820ddb1f1d3bb7beef
6,322,191,892,546
8d47cb8453eddc494598fd7b5a5911dc8e2ec367
/openfire.plugin.demeter_core/src/java/com/sercomm/openfire/plugin/AppManager.java
f080f331c786af5e3c52224411bf467b87738a05
[ "Apache-2.0" ]
permissive
leeshen64/lcmdemeter
https://github.com/leeshen64/lcmdemeter
7b31d4bb715f194f4182c7f400b1f5531e2c8940
822ed16ba69366db7f0d98ae4edec8157f0b12e9
refs/heads/main
2023-03-08T08:10:39.858000
2022-02-18T13:31:11
2022-02-24T10:00:01
311,529,125
0
1
Apache-2.0
false
2020-12-09T09:36:15
2020-11-10T03:00:47
2020-12-09T05:05:07
2020-12-09T09:36:15
2,341
0
1
0
Java
false
false
package com.sercomm.openfire.plugin; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.stream.Stream; import java.util.stream.Collectors; import javax.ws.rs.core.Response.Status; import org.apache.commons.io.FileUtils; import org.jivesoftware.database.DbConnectionManager; import com.sercomm.common.util.Algorithm; import com.sercomm.common.util.ManagerBase; import com.sercomm.commons.util.XStringUtil; import com.sercomm.openfire.plugin.data.frontend.App; import com.sercomm.openfire.plugin.data.frontend.AppIcon; import com.sercomm.openfire.plugin.data.frontend.AppSubscription; import com.sercomm.openfire.plugin.data.frontend.AppVersion; import com.sercomm.openfire.plugin.exception.DemeterException; import com.sercomm.openfire.plugin.util.DbConnectionUtil; import com.sercomm.openfire.plugin.util.IpkUtil; import com.sercomm.openfire.plugin.util.StorageUtil; import com.sercomm.openfire.plugin.define.StorageType; import io.minio.BucketExistsArgs; import io.minio.MakeBucketArgs; import io.minio.MinioClient; import io.minio.UploadObjectArgs; import io.minio.RemoveObjectArgs; import io.minio.StatObjectArgs; import io.minio.ListObjectsArgs; import io.minio.Result; import io.minio.messages.Item; import okhttp3.HttpUrl; import io.minio.errors.MinioException; import io.minio.StatObjectResponse; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AppManager extends ManagerBase { //private static final Logger log = LoggerFactory.getLogger(AppManager.class); private final static String TABLE_S_APP = "sApp"; private final static String TABLE_S_APP_ICON = "sAppIcon"; private final static String TABLE_S_APP_VERSION = "sAppVersion"; private final static String TABLE_S_APP_SUBSCRIPTION = "sAppSubscription"; private final static String SQL_UPDATE_APP = String.format("INSERT INTO `%s`" + "(`id`,`publisher`,`name`,`catalog`,`model`,`price`,`publish`,`description`,`creationTime`) " + "VALUES(?,?,?,?,?,?,?,?,?) " + "ON DUPLICATE KEY UPDATE `catalog`=?,`price`=?,`publish`=?,`description`=?", TABLE_S_APP); private final static String SQL_UPDATE_APP_ICON = String.format("INSERT INTO `%s`" + "(`appId`,`iconId`,`size`,`updatedTime`,`data`) " + "VALUES(?,?,?,?,?) " + "ON DUPLICATE KEY UPDATE `iconId`=?,`size`=?,`updatedTime`=?,`data`=?", TABLE_S_APP_ICON); private final static String SQL_INSERT_APP_VERSION = String.format("INSERT INTO `%s`" + "(`id`,`appId`,`version`,`status`,`filename`,`creationTime`,`ipkFilePath`,`ipkFileSize`,`releaseNote`,`realVersion`) " + "VALUES(?,?,?,?,?,?,?,?,?,?)", TABLE_S_APP_VERSION); private final static String SQL_UPDATE_APP_VERSION = String.format("UPDATE `%s` SET " + "`version`=?,`status`=?,`filename`=?,`ipkFileSize`=?,`releaseNote`=?,`realVersion`=? " + "WHERE `id`=?", TABLE_S_APP_VERSION); private final static String SQL_UPDATE_APP_VERSION_PATH = String.format("UPDATE `%s` SET " + "`ipkFilePath`=? " + "WHERE `id`=?", TABLE_S_APP_VERSION); private final static String SQL_QUERY_APP = String.format("SELECT * FROM `%s` WHERE `id`=?", TABLE_S_APP); private final static String SQL_QUERY_APPS = String.format("SELECT * FROM `%s` ORDER BY `name`", TABLE_S_APP); private final static String SQL_QUERY_APPS_BY_MODEL = String.format("SELECT SQL_CALC_FOUND_ROWS * FROM `%s` WHERE `model`=? ORDER BY ? ? LIMIT ?,?", TABLE_S_APP); private final static String SQL_DELETE_APP = String.format("DELETE FROM `%s` WHERE `id`=?", TABLE_S_APP); private final static String SQL_QUERY_APP_COUNT_BY_CATALOG = String.format("SELECT COUNT(*) AS `count` FROM `%s` WHERE `catalog`=?", TABLE_S_APP); private final static String SQL_QUERY_APP_VERSION = String.format("SELECT * FROM `%s` WHERE `appId`=? AND `version`=?", TABLE_S_APP_VERSION); private final static String SQL_QUERY_APP_VERSION_REAL_VERSION = String.format("SELECT * FROM `%s` WHERE `appId`=? AND `realVersion`=?", TABLE_S_APP_VERSION); private final static String SQL_QUERY_APP_VERSION_BY_ID = String.format("SELECT * FROM `%s` WHERE `id`=?", TABLE_S_APP_VERSION); private final static String SQL_QUERY_APP_VERSIONS = String.format("SELECT * FROM `%s` WHERE `appId`=?", TABLE_S_APP_VERSION); private final static String SQL_QUERY_APP_LATEST_VERSION = String.format("SELECT * FROM `%s` WHERE `appId`=? ORDER BY `creationTime` DESC LIMIT 1", TABLE_S_APP_VERSION); private final static String SQL_DELETE_APP_VERSION = String.format("DELETE FROM `%s` WHERE `appId`=? AND `id`=?", TABLE_S_APP_VERSION); private final static String SQL_QUERY_ALL_APP_VERSIONS = String.format("SELECT * FROM `%s`", TABLE_S_APP_VERSION); private final static String SQL_QUERY_APP_ICON = String.format("SELECT * FROM `%s` WHERE `iconId`=?", TABLE_S_APP_ICON); private final static String SQL_QUERY_APP_ICON_BY_APP_ID = String.format("SELECT * FROM `%s` WHERE `appId`=?", TABLE_S_APP_ICON); private final static String SQL_DELETE_APP_ICON_BY_APP_ID = String.format("DELETE FROM `%s` WHERE `appId`=?", TABLE_S_APP_ICON); private final static String SQL_QUERY_APP_INSTALLED_COUNT = String.format("SELECT SUM(`installedCount`) AS `count` FROM `%s` WHERE `appId`=?", TABLE_S_APP_VERSION); private final static String SQL_QUERY_APP_INSTALLED_COUNT_BY_VERSION = String.format("SELECT `installedCount` AS `count` FROM `%s` WHERE `appId`=? AND `version`=?", TABLE_S_APP_VERSION); private final static String SQL_QUERY_APP_SUBSCRIPTIONS = String.format("SELECT * FROM `%s` WHERE `userId`=?", TABLE_S_APP_SUBSCRIPTION); private final static String SQL_QUERY_APP_SUBSCRIPTION = String.format("SELECT * FROM `%s` WHERE `appId`=? AND `userId`=?", TABLE_S_APP_SUBSCRIPTION); private final static String SQL_INSERT_APP_SUBSCRIPTION = String.format("INSERT INTO `%s`(`appId`,`userId`,`creationTime`) VALUES(?,?,?)", TABLE_S_APP_SUBSCRIPTION); private final static String SQL_DELETE_APP_SUBSCRIPTION = String.format("DELETE FROM `%s` WHERE `appId`=? AND `userId`=?", TABLE_S_APP_SUBSCRIPTION); private final static String SQL_DELETE_APP_SUBSCRIPTIONS = String.format("DELETE FROM `%s` WHERE `appId`=?", TABLE_S_APP_SUBSCRIPTION); private static class AppManagerContainer { private final static AppManager instance = new AppManager(); private final static HttpUrl minio_getUrl(){ HttpUrl url = HttpUrl.parse(SystemProperties.getInstance().getStorage().getAwsUrl()); return new HttpUrl.Builder() .scheme(SystemProperties.getInstance().getStorage().getAwsScheme()) .host(url.host()) .port(url.port()) .build(); } private final static MinioClient minio_instance = MinioClient.builder() .endpoint(minio_getUrl()) .credentials( SystemProperties.getInstance().getStorage().getAwsKey(), SystemProperties.getInstance().getStorage().getAwsSecret()) .build(); } private AppManager() { } public static AppManager getInstance() { return AppManagerContainer.instance; } public static MinioClient getMinioInstance() { return AppManagerContainer.minio_instance; } @Override protected void onInitialize() { } @Override protected void onUninitialize() { } public static class CloudObj{ public CloudObj (String fname, String obj_name) { filename = fname; object_name = obj_name; } public String filename; public String object_name; } public void SaveFileToCloud( String filepath, String object_name) throws DemeterException { List<CloudObj> objects = new ArrayList<CloudObj>(); objects.add(new CloudObj(filepath, object_name)); SaveFilesToCloud(objects, false); } public void setManifest( String appId, String manifestFileName, byte[] manifestFileData) throws DemeterException, Throwable { if(manifestFileData != null) { String FSRootPathString = SystemProperties.getInstance().getStorage().getRootPath(); if(FSRootPathString.endsWith(File.separator) == false){ FSRootPathString = FSRootPathString.concat(File.separator); } final String manifestFilePathString = appId + File.separator + IpkUtil.PACKAGE_MANIFEST_FILENAME; final Path manifestFilePath = Paths.get(FSRootPathString + manifestFilePathString); final Path packageFolderPath = Paths.get(FSRootPathString + appId); final StorageType storage_type = SystemProperties.getInstance().getStorage().getStorageType(); // create temporary folder Path tempFolder = Files.createTempDirectory(UUID.randomUUID().toString()); try { Path tempFilePath = Paths.get( tempFolder.toAbsolutePath().toString() + File.separator + IpkUtil.PACKAGE_MANIFEST_FILENAME); // save bytes array as "data.ipk" file to temporary folder try(FileOutputStream fos = new FileOutputStream(tempFilePath.toFile())) { fos.write(manifestFileData); } boolean moved = false; try { if(storage_type == StorageType.LOCAL_FS){ try { // check if the package folder exists if(false == Files.exists(packageFolderPath)) { Files.createDirectories(packageFolderPath.toAbsolutePath()); } } catch(IOException e) { throw new IOException("FAILED TO CREATE DIRECTORY: " + e.getMessage()); } try { // move manifest file try { this.deleteManifest(appId); } catch(Throwable ignored) {} Files.move(tempFilePath, manifestFilePath); } catch(IOException e) { throw new IOException("FAILED TO Create Manifest FILE"); } } else if(storage_type == StorageType.AWS_S3) { this.RemoveObjectFromCloud(manifestFilePathString); List<CloudObj> objects = new ArrayList<CloudObj>(); objects.add(new CloudObj(tempFilePath.toString(), manifestFilePathString)); SaveFilesToCloud(objects, false); } else { throw new DemeterException("STORAGE TYPE IS NOT SUPPORTED"); } moved = true; } finally {} } finally { // clean temporary files FileUtils.forceDelete(tempFolder.toFile()); } } } public static void SaveFilesToCloud( Iterable<CloudObj> objects, boolean ignore_errors_flag) throws DemeterException { int saved_num = 0; boolean err = true; String err_string = ""; Status http_status = Status.BAD_GATEWAY; final String bucket_name = SystemProperties.getInstance().getStorage().getAwsBucket(); try { MinioClient minioClient = getMinioInstance(); boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucket_name).build()); if (!found) { minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucket_name).build()); } for(CloudObj obj : objects){ try{ minioClient.uploadObject( UploadObjectArgs.builder() .bucket(bucket_name) .object(obj.object_name) .filename(obj.filename) .build()); saved_num++; } catch(Throwable e){ if(ignore_errors_flag == false) throw e; } } err = false; } catch (MinioException e) { err_string = "Minio exception: " + e + " HTTP trace: " + e.httpTrace(); http_status = Status.SERVICE_UNAVAILABLE; } catch (InvalidKeyException e) { err_string = "Minio exception: " + e; } catch (NoSuchAlgorithmException e){ err_string = "Minio exception: " + e; } catch(IOException e){ err_string = "IOException: " + e; } if(err && !ignore_errors_flag){ List<String> obj_names = new ArrayList<String>(); int i = 0; for(CloudObj obj : objects){ if(i == saved_num) break; obj_names.add(obj.object_name); } try{ RemoveObjectsFromCloud(obj_names); } catch(DemeterException ignored){ } throw (new DemeterException(err_string)).SettHttpStatus(http_status); } } public static void RemoveObjectFromCloud( String object_name) throws DemeterException { List<String> list = new ArrayList<String>(); list.add(object_name); RemoveObjectsFromCloud(list); } public static void RemoveObjectsFromCloud( Iterable<String> objects) throws DemeterException { final String bucket_name = SystemProperties.getInstance().getStorage().getAwsBucket(); try { MinioClient minioClient = getMinioInstance(); for(String obj : objects){ minioClient.removeObject(RemoveObjectArgs.builder() .bucket(bucket_name) .object(obj).build()); } } catch (MinioException e) { throw (new DemeterException("Minio exception: " + e + " HTTP trace: " + e.httpTrace())) .SettHttpStatus(Status.SERVICE_UNAVAILABLE); } catch (InvalidKeyException e) { throw (new DemeterException("Minio exception: " + e)) .SettHttpStatus(Status.BAD_GATEWAY); } catch (NoSuchAlgorithmException e){ throw (new DemeterException("Minio exception: " + e)) .SettHttpStatus(Status.BAD_GATEWAY); } catch(IOException e){ throw (new DemeterException("IOException: " + e)) .SettHttpStatus(Status.BAD_GATEWAY); } } public static boolean ExistFileOnCloud( String object_name) throws DemeterException { final String bucket_name = SystemProperties.getInstance().getStorage().getAwsBucket(); try { MinioClient minioClient = getMinioInstance(); io.minio.StatObjectResponse stat = minioClient.statObject(StatObjectArgs.builder() .bucket(bucket_name) .object(object_name).build()); if(stat.size() != 0) { return true; } } catch (MinioException e) { return false; } catch (InvalidKeyException e) { return false; } catch (NoSuchAlgorithmException e){ return false; } catch(IOException e){ return false; } return false; } public static void RemoveFolderFromCloud( String folder_name) throws DemeterException { if(folder_name.length() == 0){ return; } if(false == folder_name.endsWith(File.separator)){ folder_name = folder_name.concat(File.separator); } try { final String bucket_name = SystemProperties.getInstance().getStorage().getAwsBucket(); MinioClient minioClient = getMinioInstance(); Iterable<Result<Item>> results = minioClient.listObjects( ListObjectsArgs.builder() .bucket(bucket_name) .prefix(folder_name) .build()); for (Result<Item> result : results) { minioClient.removeObject(RemoveObjectArgs.builder() .bucket(bucket_name) .object(result.get().objectName()) .build()); } } catch (MinioException e) { throw (new DemeterException("Minio exception: " + e + " HTTP trace: " + e.httpTrace())) .SettHttpStatus(Status.SERVICE_UNAVAILABLE); } catch (InvalidKeyException e) { throw (new DemeterException("Minio exception: " + e)) .SettHttpStatus(Status.BAD_GATEWAY); } catch (NoSuchAlgorithmException e){ throw (new DemeterException("Minio exception: " + e)) .SettHttpStatus(Status.BAD_GATEWAY); } catch(IOException e){ throw (new DemeterException("IOException: " + e)) .SettHttpStatus(Status.BAD_GATEWAY); } } public void addApp( String publisher, String name, String catalog, String modelName, String price, Integer publish, String description, String manifestFileName, byte[] manifestFileData, byte[] iconData) throws DemeterException, Throwable { App application = null; try { application = this.getApp(publisher, name, modelName); } catch(DemeterException ignored) {} if(null != application) { throw new DemeterException("APPLICATION ALREADY EXISTS"); } Connection conn = null; PreparedStatement stmt = null; boolean abort = false; try { final String id = Algorithm.md5(publisher + name + modelName); final long creationTime = System.currentTimeMillis(); conn = DbConnectionManager.getConnection(); conn = DbConnectionUtil.openTransaction(conn); do { int idx; // update first table stmt = conn.prepareStatement(SQL_UPDATE_APP); idx = 0; // `id`,`publisher`,`name`,`catalog`,`modelName`,`price`,`publish`,`description`,`creationTime` stmt.setString(++idx, id); stmt.setString(++idx, publisher); stmt.setString(++idx, name); stmt.setString(++idx, catalog); stmt.setString(++idx, modelName); stmt.setString(++idx, price); stmt.setInt(++idx, publish); stmt.setString(++idx, description); stmt.setLong(++idx, creationTime); // `catalog`,`price`,`publish`,`description` stmt.setString(++idx, catalog); stmt.setString(++idx, price); stmt.setInt(++idx, publish); stmt.setString(++idx, description); stmt.executeUpdate(); DbConnectionManager.fastcloseStmt(stmt); final String appId = id; setManifest(appId, manifestFileName, manifestFileData); if(null == iconData) { break; } // update 2nd table stmt = conn.prepareStatement(SQL_UPDATE_APP_ICON); final String iconId = Algorithm.md5(iconData); idx = 0; // `appId`,`iconId`,`size`,`updatedTime`,`data` stmt.setString(++idx, appId); stmt.setString(++idx, iconId); stmt.setLong(++idx, iconData.length); stmt.setLong(++idx, creationTime); stmt.setBytes(++idx, iconData); // `iconId`,`size`,`updatedTime`,`data` stmt.setString(++idx, iconId); stmt.setLong(++idx, iconData.length); stmt.setLong(++idx, creationTime); stmt.setBytes(++idx, iconData); stmt.executeUpdate(); } while(false); } catch(Throwable t) { abort = true; throw t; } finally { DbConnectionManager.closeStatement(stmt); DbConnectionUtil.closeTransaction(conn, abort); DbConnectionManager.closeConnection(conn); } } public void setApp( App object, String manifestFileName, byte[] manifestFileData, byte[] iconData) throws DemeterException, Throwable { final String id = object.getId(); if(null == this.getApp(id)) { throw new DemeterException("APP DOES NOT EXIST"); } Connection conn = null; PreparedStatement stmt = null; boolean abort = false; try { conn = DbConnectionManager.getConnection(); conn = DbConnectionUtil.openTransaction(conn); do { int idx; // update 1st table idx = 0; stmt = conn.prepareStatement(SQL_UPDATE_APP); // `id`,`publisher`,`name`,`catalog`,`model`,`price`,`publish`,`description`,`creationTime` stmt.setString(++idx, id); stmt.setString(++idx, object.getPublisher()); stmt.setString(++idx, object.getName()); stmt.setString(++idx, object.getCatalog()); stmt.setString(++idx, object.getModelName()); stmt.setString(++idx, object.getPrice()); stmt.setInt(++idx, object.getPublish()); stmt.setString(++idx, object.getDescription()); stmt.setLong(++idx, object.getCreationTime()); // `catalog`,`price`,`publish`,`description` stmt.setString(++idx, object.getCatalog()); stmt.setString(++idx, object.getPrice()); stmt.setInt(++idx, object.getPublish()); stmt.setString(++idx, object.getDescription()); stmt.executeUpdate(); DbConnectionManager.fastcloseStmt(stmt); final String appId = id; setManifest(appId, manifestFileName, manifestFileData); if(null == iconData) { break; } // update 2nd table final long updatedTime = System.currentTimeMillis(); // generate icon ID int length = iconData.length + Long.BYTES; ByteBuffer buffer = ByteBuffer.allocate(length); buffer.put(iconData); buffer.putLong(updatedTime); final String iconId = Algorithm.md5(buffer.array()); idx = 0; stmt = conn.prepareStatement(SQL_UPDATE_APP_ICON); // `appId`,`iconId`,`size`,`updatedTime`,`data` stmt.setString(++idx, appId); stmt.setString(++idx, iconId); stmt.setLong(++idx, iconData.length); stmt.setLong(++idx, updatedTime); stmt.setBytes(++idx, iconData); // `iconId`,`size`,`updatedTime`,`data` stmt.setString(++idx, iconId); stmt.setLong(++idx, iconData.length); stmt.setLong(++idx, updatedTime); stmt.setBytes(++idx, iconData); stmt.executeUpdate(); } while(false); } catch(Throwable t) { abort = true; throw t; } finally { DbConnectionManager.closeStatement(stmt); DbConnectionUtil.closeTransaction(conn, abort); DbConnectionManager.closeConnection(conn); } } public List<App> getApps() throws DemeterException, Throwable { List<App> apps = new ArrayList<App>(); Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = DbConnectionManager.getConnection(); stmt = conn.prepareStatement(SQL_QUERY_APPS); rs = stmt.executeQuery(); while(rs.next()) { App object = App.from(rs); apps.add(object); } } finally { DbConnectionManager.closeConnection(rs, stmt, conn); } return apps; } public List<App> getAppsByModel(String modelName) throws DemeterException, Throwable { List<App> apps = new ArrayList<App>(); this.getAppsByModel(modelName, 0, 9999, "name", "asc", apps); return apps; } public int getAppsByModel( String modelName, Integer from, Integer size, String sort, String order, List<App> apps) throws DemeterException, Throwable { int totalCount = 0; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = DbConnectionManager.getConnection(); stmt = conn.prepareStatement(SQL_QUERY_APPS_BY_MODEL); int idx = 0; stmt.setString(++idx, modelName); stmt.setString(++idx, sort); stmt.setString(++idx, order); stmt.setInt(++idx, from); stmt.setInt(++idx, size); rs = stmt.executeQuery(); while(rs.next()) { App object = App.from(rs); apps.add(object); } } finally { DbConnectionManager.closeStatement(rs, stmt); try { stmt = conn.prepareStatement("SELECT FOUND_ROWS()"); rs = stmt.executeQuery(); if(rs.next()) { totalCount = rs.getInt(1); } } finally { DbConnectionManager.closeConnection(rs, stmt, conn); } } return totalCount; } public App getApp( String publisher, String name, String modelName) throws DemeterException, Throwable { if(XStringUtil.isBlank(publisher) || XStringUtil.isBlank(name)) { throw new DemeterException("ARGUMENT(S) CANNOT BE BLANK"); } final String id = Algorithm.md5(publisher + name + modelName); return this.getApp(id); } public App getApp(String appId) throws DemeterException, Throwable { App object = null; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = DbConnectionManager.getConnection(); stmt = conn.prepareStatement(SQL_QUERY_APP); int idx = 0; stmt.setString(++idx, appId); rs = stmt.executeQuery(); do { if(!rs.next()) { throw new DemeterException("APP CANNOT BE FOUND"); } object = App.from(rs); } while(false); } finally { DbConnectionManager.closeConnection(rs, stmt, conn); } return object; } public void deleteApp( String appId) throws DemeterException, Throwable { // obtain the App object and check if the App ID is valid App app = this.getApp(appId); // backup the App's versions information at first List<AppVersion> appVersions = this.getAppVersions(app.getId()); boolean abort = false; Connection conn = null; PreparedStatement stmt = null; try { conn = DbConnectionManager.getConnection(); conn = DbConnectionUtil.openTransaction(conn); // delete App manifest try { this.deleteManifest(app.getId()); } catch(Throwable ignored) {} // delete versions of the application for(AppVersion appVersion: appVersions) { this.deleteAppVersion(app.getId(), appVersion.getId()); } // delete App subscriptions this.deleteAppSubscriptions(conn, app.getId()); // delete App icon this.deleteAppIcon(conn, app.getId()); // delete the App int idx; idx = 0; stmt = conn.prepareStatement(SQL_DELETE_APP); stmt.setString(++idx, app.getId()); stmt.executeUpdate(); try { String FSRootPathString = SystemProperties.getInstance().getStorage().getRootPath(); if(FSRootPathString.endsWith(File.separator) == false){ FSRootPathString = FSRootPathString.concat(File.separator); } final Path packageFolderPath = Paths.get(FSRootPathString + app.getId()); if(true == Files.exists(packageFolderPath)) { FileUtils.forceDelete(packageFolderPath.toFile()); } } catch(Throwable ignored) {} } catch(Throwable t) { abort = true; throw t; } finally { DbConnectionManager.closeStatement(stmt); DbConnectionUtil.closeTransaction(conn, abort); DbConnectionManager.closeConnection(conn); } // delete its physical files if(false == abort) { final StorageType storage_type = SystemProperties.getInstance().getStorage().getStorageType(); if(storage_type == StorageType.LOCAL_FS){ if(false == appVersions.isEmpty()) { StringBuilder sb = new StringBuilder(SystemProperties.getInstance().getStorage().getRootPath()); if(sb.toString().endsWith(File.separator) == false){ sb.append(File.separator); } sb.append(appId); try { FileUtils.forceDelete(new File(sb.toString())); } catch(Throwable ignored) {} } } } } public void deleteManifest( String appId) throws DemeterException, Throwable { String FSRootPathString = SystemProperties.getInstance().getStorage().getRootPath(); if(FSRootPathString.endsWith(File.separator) == false){ FSRootPathString = FSRootPathString.concat(File.separator); } final String manifestFilePathString = appId + File.separator + IpkUtil.PACKAGE_MANIFEST_FILENAME; final Path manifestFilePath = Paths.get(FSRootPathString + manifestFilePathString); final StorageType storage_type = SystemProperties.getInstance().getStorage().getStorageType(); if(storage_type == StorageType.LOCAL_FS) { if(true == Files.exists(manifestFilePath)) { FileUtils.forceDelete(manifestFilePath.toFile()); } } else if(storage_type == StorageType.AWS_S3) { this.RemoveObjectFromCloud(manifestFilePathString); } else { throw new DemeterException("STORAGE TYPE IS NOT SUPPORTED"); } } public String getManifestExist( String appId) throws DemeterException, Throwable { String ret = "no"; String FSRootPathString = SystemProperties.getInstance().getStorage().getRootPath(); if(FSRootPathString.endsWith(File.separator) == false){ FSRootPathString = FSRootPathString.concat(File.separator); } final String manifestFilePathString = appId + File.separator + IpkUtil.PACKAGE_MANIFEST_FILENAME; final Path manifestFilePath = Paths.get(FSRootPathString + manifestFilePathString); final StorageType storage_type = SystemProperties.getInstance().getStorage().getStorageType(); if(storage_type == StorageType.LOCAL_FS) { if(true == Files.exists(manifestFilePath)) { ret = "yes"; } else { ret = "no"; } } else if(storage_type == StorageType.AWS_S3) { if(this.ExistFileOnCloud(manifestFilePathString)) { ret = "yes"; } else { ret = "no"; } } else { throw new DemeterException("STORAGE TYPE IS NOT SUPPORTED"); } return ret; } public void deleteAppVersion( String appId, String versionId) throws DemeterException, Throwable { AppVersion appVersion = this.getAppVersion(versionId); boolean abortTransaction = true; Connection conn = null; PreparedStatement stmt = null; try { // delete the row from database conn = DbConnectionManager.getConnection(); DbConnectionUtil.openTransaction(conn); stmt = conn.prepareStatement(SQL_DELETE_APP_VERSION); int idx = 0; stmt.setString(++idx, appId); stmt.setString(++idx, versionId); stmt.executeUpdate(); final StorageType storage_type = SystemProperties.getInstance().getStorage().getStorageType(); if(storage_type == StorageType.LOCAL_FS){ // delete the package's folder from volume File ipkFile = new File( SystemProperties.getInstance().getStorage().getRootPath() + File.separator + appVersion.getIPKFilePath()); FileUtils.forceDelete(ipkFile.getParentFile()); } else if(storage_type == StorageType.AWS_S3){ File ipkFile = new File(appVersion.getIPKFilePath()); RemoveFolderFromCloud(ipkFile.getParentFile().toString()); } else { throw new DemeterException("STORAGE TYPE IS NOT SUPPORTED"); } abortTransaction = false; } catch(Throwable t) { throw t; } finally { DbConnectionManager.closeStatement(stmt); DbConnectionUtil.closeTransaction(conn, abortTransaction); DbConnectionManager.closeConnection(conn); } } private void deleteAppIcon( Connection conn, String appId) throws DemeterException, Throwable { PreparedStatement stmt = null; try { stmt = conn.prepareStatement(SQL_DELETE_APP_ICON_BY_APP_ID); int idx = 0; stmt.setString(++idx, appId); stmt.executeUpdate(); } finally { DbConnectionManager.closeStatement(stmt); } } private void deleteAppSubscriptions( Connection conn, String appId) throws DemeterException, Throwable { PreparedStatement stmt = null; try { stmt = conn.prepareStatement(SQL_DELETE_APP_SUBSCRIPTIONS); int idx = 0; stmt.setString(++idx, appId); stmt.executeUpdate(); } finally { DbConnectionManager.closeStatement(stmt); } } public Long getAppCount( String catalogName) throws DemeterException, Throwable { Long count = 0L; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = DbConnectionManager.getConnection(); stmt = conn.prepareStatement(SQL_QUERY_APP_COUNT_BY_CATALOG); int idx = 0; stmt.setString(++idx, catalogName); rs = stmt.executeQuery(); if(rs.next()) { count = rs.getLong("count"); } } finally { DbConnectionManager.closeConnection(rs, stmt, conn); } return count; } public void addAppVersion( String applicationId, String versionName, Integer status, // 1: enable, 0: disable String ipkFileName, byte[] ipkFileData) throws DemeterException, Throwable { App app = this.getApp(applicationId); if(null == app) { throw new DemeterException("APPLICATION DOES NOT EXIST"); } if(XStringUtil.isBlank(versionName)) { //throw new DemeterException("VERSION NAME CANNOT BE BLANK"); // !!! added temporary version name as there is no version here (due to a bug) versionName = "version_" + String.valueOf(System.currentTimeMillis()); } // create temporary folder Path tempFolder = Files.createTempDirectory(UUID.randomUUID().toString()); try { Path tempIPKFilePath = Paths.get( tempFolder.toAbsolutePath().toString() + File.separator + IpkUtil.PACKAGE_IPK_FILENAME); // save bytes array as "data.ipk" file to temporary folder try(FileOutputStream fos = new FileOutputStream(tempIPKFilePath.toFile())) { fos.write(ipkFileData); } // extract the IPK, and verify its package information // finally, a "Packages.gz" file will be left in the temporary folder com.sercomm.openfire.plugin.data.ipk.Meta meta = IpkUtil.validate(tempIPKFilePath); if(XStringUtil.isBlank(meta.Version)) { throw new DemeterException("BAD PACKAGE INFORMATION. NO REQUIRED FIELD WITHIN 'control' FILE OF THE PACKAGE: 'Version'"); } // a "Packages.gz" file will be generated after IpkUtil.validate() method being executed final Path tempPackageInfoFilePath = Paths.get(tempFolder.toAbsolutePath().toString() + File.separator + IpkUtil.PACKAGE_GZ_FILENAME); final long creationTime = System.currentTimeMillis(); // generate version ID final String versionId = generateVersionId( app.getId(), app.getModelName(), creationTime); // --> begin filename investigation // 1. if there is no specific IPK filename, use the filename within // package information by default if(XStringUtil.isBlank(ipkFileName)) { ipkFileName = meta.Filename; } // 2. if IPK filename is still blank, set the filename same as application's name if(XStringUtil.isBlank(ipkFileName)) { ipkFileName = app.getName(); } // --> end filename investigation final String description = XStringUtil.isBlank(meta.Description) ? XStringUtil.BLANK : meta.Description; final String realVersion = XStringUtil.isBlank(meta.Version) ? XStringUtil.BLANK : meta.Version; AppVersion appVersion = null; // check if duplicate version name exists try { appVersion = this.getAppVersion(applicationId, versionName); } catch(DemeterException ignored) {} finally { if(null != appVersion) { throw new DemeterException("APP VERSION ALREADY EXISTS"); } } // check if duplicate version ID exists try { appVersion = this.getAppVersion(versionId); } catch(DemeterException ignored) {} finally { if(null != appVersion) { throw new DemeterException("APP VERSION ALREADY EXISTS"); } } final StorageType storage_type = SystemProperties.getInstance().getStorage().getStorageType(); final String VersionPathString = app.getId() + File.separator + versionId; String FSRootPathString = SystemProperties.getInstance().getStorage().getRootPath(); if(FSRootPathString.endsWith(File.separator) == false){ FSRootPathString = FSRootPathString.concat(File.separator); } final String ipkFilePathString = VersionPathString + File.separator + IpkUtil.PACKAGE_IPK_FILENAME; final String packageInfoFilePathString = VersionPathString + File.separator + IpkUtil.PACKAGE_GZ_FILENAME; // 1. establish database records // 2. move files boolean abortTransaction = true; Connection conn = null; PreparedStatement stmt = null; try { conn = DbConnectionManager.getConnection(); DbConnectionUtil.openTransaction(conn); stmt = conn.prepareStatement(SQL_INSERT_APP_VERSION); int idx = 0; // `id`,`appId`,`version`,`status`,`creationTime`,`ipkFilePath`,`ipkFileSize`,`releaseNote` stmt.setString(++idx, versionId); stmt.setString(++idx, applicationId); stmt.setString(++idx, versionName); stmt.setInt(++idx, status); stmt.setString(++idx, ipkFileName); stmt.setLong(++idx, creationTime); stmt.setString(++idx, ipkFilePathString); stmt.setLong(++idx, ipkFileData.length); stmt.setString(++idx, description); stmt.setString(++idx, realVersion); stmt.executeUpdate(); // database record being inserted successfully // then moving the files boolean moved = false; try { if(storage_type == StorageType.LOCAL_FS){ final Path packageFolderPath = Paths.get(FSRootPathString + VersionPathString); final Path ipkFilePath = Paths.get(FSRootPathString + ipkFilePathString); final Path packageInfoFilePath = Paths.get(FSRootPathString + packageInfoFilePathString); try { // check if the package folder exists if(false == Files.exists(packageFolderPath)) { Files.createDirectories(packageFolderPath.toAbsolutePath()); } } catch(IOException e) { throw new IOException("FAILED TO CREATE DIRECTORY: " + e.getMessage()); } try { // move IPK file Files.move(tempIPKFilePath, ipkFilePath); // move package info. file Files.move(tempPackageInfoFilePath, packageInfoFilePath); } catch(IOException e) { throw new IOException("FAILED TO MOVE IPK FILE TO VOLUME: " + e.getMessage()); } } else if(storage_type == StorageType.AWS_S3){ List<CloudObj> objects = new ArrayList<CloudObj>(); objects.add(new CloudObj(tempIPKFilePath.toString(), ipkFilePathString)); objects.add(new CloudObj(tempPackageInfoFilePath.toString(), packageInfoFilePathString)); SaveFilesToCloud(objects, false); } else { throw new DemeterException("STORAGE TYPE IS NOT SUPPORTED"); } moved = true; } finally { // fallback if(false == moved) { if(storage_type == StorageType.LOCAL_FS){ // catch surrounded since the folder path might not be created yet try { final Path VPath = Paths.get(FSRootPathString + VersionPathString); FileUtils.forceDelete(VPath.toFile()); } catch(Throwable ignored) {} } } } abortTransaction = false; } finally { DbConnectionManager.closeStatement(stmt); DbConnectionUtil.closeTransaction(conn, abortTransaction); DbConnectionManager.closeConnection(conn); } } finally { // clean temporary files FileUtils.forceDelete(tempFolder.toFile()); } } public void updateAppVersion( String applicationId, String versionId, String versionName, Integer status, // 1: enable, 0: disable String ipkFileName, byte[] ipkFileData) throws DemeterException, Throwable { App app = this.getApp(applicationId); if(null == app) { throw new DemeterException("APPLICATION DOES NOT EXIST"); } if(XStringUtil.isBlank(versionName)) { throw new DemeterException("VERSION NAME CANNOT BE BLANK"); } if(0 != status && 1 != status) { throw new DemeterException("INVALID 'status' VALUE"); } AppVersion appVersion = this.getAppVersion(versionId); // update the IPK file if necessary if(null != ipkFileData) { // create temporary folder Path tempFolder = Files.createTempDirectory( UUID.randomUUID().toString()); try { Path tempIPKFilePath = Paths.get( tempFolder.toAbsolutePath().toString() + File.separator + IpkUtil.PACKAGE_IPK_FILENAME); // save bytes array as "data.ipk" file to temporary folder try(FileOutputStream fos = new FileOutputStream(tempIPKFilePath.toFile())) { fos.write(ipkFileData); } // extract the IPK, and verify its package information // finally, a "Packages.gz" file will be left in the temporary folder com.sercomm.openfire.plugin.data.ipk.Meta meta = IpkUtil.validate(tempIPKFilePath); // --> begin filename investigation // 1. if there is no specific IPK filename, use the filename within // package information by default if(XStringUtil.isBlank(ipkFileName)) { ipkFileName = meta.Filename; } // 2. if IPK filename is still blank, set the filename same as application's name if(XStringUtil.isBlank(ipkFileName)) { ipkFileName = app.getName(); } // --> end filename investigation // a "Packages.gz" file will be generated after IpkUtil.validate() method being executed final Path tempPackageInfoFilePath = Paths.get(tempFolder.toAbsolutePath().toString() + File.separator + IpkUtil.PACKAGE_GZ_FILENAME); String FSRootPathString = SystemProperties.getInstance().getStorage().getRootPath(); if(FSRootPathString.endsWith(File.separator) == false){ FSRootPathString = FSRootPathString.concat(File.separator); } final String VersionPathString = app.getId() + File.separator + versionId; final String ipkFilePathString = VersionPathString + File.separator + IpkUtil.PACKAGE_IPK_FILENAME; final String packageInfoFilePathString = VersionPathString + File.separator + IpkUtil.PACKAGE_GZ_FILENAME; final StorageType storage_type = SystemProperties.getInstance().getStorage().getStorageType(); final String description = XStringUtil.isBlank(meta.Description) ? XStringUtil.BLANK : meta.Description; final String realVersion = XStringUtil.isBlank(meta.Version) ? XStringUtil.BLANK : meta.Version; Connection conn = null; PreparedStatement stmt = null; try { conn = DbConnectionManager.getConnection(); stmt = conn.prepareStatement(SQL_UPDATE_APP_VERSION); // `version`=?,`status`=?,`filename`=?,`ipkFileSize`=?,`releaseNote`=?,`realVersion`=? int idx = 0; stmt.setString(++idx, versionName); stmt.setInt(++idx, status); stmt.setString(++idx, ipkFileName); stmt.setLong(++idx, null == ipkFileData ? appVersion.getIPKFileSize() : ipkFileData.length); stmt.setString(++idx, description); stmt.setString(++idx, realVersion); stmt.setString(++idx, appVersion.getId()); stmt.executeUpdate(); } finally { DbConnectionManager.closeConnection(stmt, conn); } if(storage_type == StorageType.LOCAL_FS){ final Path packageFolderPath = Paths.get(FSRootPathString + VersionPathString); final Path ipkFilePath = Paths.get(FSRootPathString + ipkFilePathString); final Path packageInfoFilePath = Paths.get(FSRootPathString + packageInfoFilePathString); try { // check if the package folder exists if(Files.exists(packageFolderPath)) { // force delete the original folder FileUtils.forceDelete(packageFolderPath.toFile()); } // re-create it Files.createDirectories(packageFolderPath); } catch(IOException e) { throw new IOException("FAILED TO CREATE DIRECTORY: " + e.getMessage()); } try { // move IPK file Files.move(tempIPKFilePath, ipkFilePath); // move package info. file Files.move(tempPackageInfoFilePath, packageInfoFilePath); } catch(IOException e) { throw new IOException("FAILED TO MOVE IPK FILE TO VOLUME: " + e.getMessage()); } } else if(storage_type == StorageType.AWS_S3){ RemoveFolderFromCloud(VersionPathString); List<CloudObj> objects = new ArrayList<CloudObj>(); objects.add(new CloudObj(tempIPKFilePath.toString(), ipkFilePathString)); objects.add(new CloudObj(tempPackageInfoFilePath.toString(), packageInfoFilePathString)); SaveFilesToCloud(objects, false); } else { throw new DemeterException("STORAGE TYPE IS NOT SUPPORTED"); } } finally { // clean temporary files FileUtils.forceDelete(tempFolder.toFile()); } } } public AppVersion getAppVersionByRealVersion( String appId, String version) throws DemeterException, Throwable { AppVersion object = null; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = DbConnectionManager.getConnection(); stmt = conn.prepareStatement(SQL_QUERY_APP_VERSION_REAL_VERSION); int idx = 0; stmt.setString(++idx, appId); stmt.setString(++idx, version); rs = stmt.executeQuery(); if(!rs.next()) { throw new DemeterException("APP VERSION WAS NOT FOUND"); } object = AppVersion.from(rs); } finally { DbConnectionManager.closeConnection(rs, stmt, conn); } return object; } public AppVersion getAppVersion( String appId, String version) throws DemeterException, Throwable { AppVersion object = null; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = DbConnectionManager.getConnection(); stmt = conn.prepareStatement(SQL_QUERY_APP_VERSION); int idx = 0; stmt.setString(++idx, appId); stmt.setString(++idx, version); rs = stmt.executeQuery(); if(!rs.next()) { throw new DemeterException("APP VERSION WAS NOT FOUND"); } object = AppVersion.from(rs); } finally { DbConnectionManager.closeConnection(rs, stmt, conn); } return object; } public AppVersion getAppVersion( String versionId) throws DemeterException, Throwable { AppVersion object = null; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = DbConnectionManager.getConnection(); stmt = conn.prepareStatement(SQL_QUERY_APP_VERSION_BY_ID); int idx = 0; stmt.setString(++idx, versionId); rs = stmt.executeQuery(); if(!rs.next()) { throw new DemeterException("APP VERSION WAS NOT FOUND"); } object = AppVersion.from(rs); } finally { DbConnectionManager.closeConnection(rs, stmt, conn); } return object; } public AppVersion getAppLatestVersion( String appId) throws DemeterException, Throwable { AppVersion object = null; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = DbConnectionManager.getConnection(); stmt = conn.prepareStatement(SQL_QUERY_APP_LATEST_VERSION); int idx = 0; stmt.setString(++idx, appId); rs = stmt.executeQuery(); if(!rs.next()) { throw new DemeterException("NO APP VERSION AVAILABLE"); } object = AppVersion.from(rs); } finally { DbConnectionManager.closeConnection(rs, stmt, conn); } return object; } public List<AppVersion> getAppVersions(String appId) throws DemeterException, Throwable { List<AppVersion> appVersions = null; Connection conn = null; try { conn = DbConnectionManager.getConnection(); appVersions = this.getAppVersions(conn, appId); } finally { DbConnectionManager.closeConnection(conn); } return appVersions; } private List<AppVersion> getAppVersions(Connection conn, String appId) throws DemeterException, Throwable { List<AppVersion> appVersions = new ArrayList<AppVersion>(); PreparedStatement stmt = null; ResultSet rs = null; try { stmt = conn.prepareStatement(SQL_QUERY_APP_VERSIONS); int idx = 0; stmt.setString(++idx, appId); rs = stmt.executeQuery(); while(rs.next()) { AppVersion object = AppVersion.from(rs); appVersions.add(object); } } finally { DbConnectionManager.closeStatement(rs, stmt); } return appVersions; } public AppIcon getAppIcon( String iconId) throws DemeterException, Throwable { AppIcon object = null; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = DbConnectionManager.getConnection(); stmt = conn.prepareStatement(SQL_QUERY_APP_ICON); int idx = 0; stmt.setString(++idx, iconId); rs = stmt.executeQuery(); /* if(!rs.next()) { throw new DemeterException("APP ICON WAS NOT FOUND"); } object = AppIcon.from(rs); */ } finally { DbConnectionManager.closeConnection(rs, stmt, conn); } return object; } public AppIcon getAppIconByAppId( String appId) throws DemeterException, Throwable { AppIcon object = null; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = DbConnectionManager.getConnection(); stmt = conn.prepareStatement(SQL_QUERY_APP_ICON_BY_APP_ID); int idx = 0; stmt.setString(++idx, appId); rs = stmt.executeQuery(); /* if(!rs.next()) { throw new DemeterException("APP ICON WAS NOT FOUND"); } object = AppIcon.from(rs); */ } finally { DbConnectionManager.closeConnection(rs, stmt, conn); } return object; } public long getAppInstalledCount( String appId) throws DemeterException, Throwable { long count = 0; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = DbConnectionManager.getConnection(); stmt = conn.prepareStatement(SQL_QUERY_APP_INSTALLED_COUNT); int idx = 0; stmt.setString(++idx, appId); rs = stmt.executeQuery(); if(rs.next()) { count = rs.getLong("count"); } } finally { DbConnectionManager.closeConnection(rs, stmt, conn); } return count; } public long getAppInstalledCount( String appId, String version) throws DemeterException, Throwable { long count = 0; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = DbConnectionManager.getConnection(); stmt = conn.prepareStatement(SQL_QUERY_APP_INSTALLED_COUNT_BY_VERSION); int idx = 0; stmt.setString(++idx, appId); stmt.setString(++idx, version); rs = stmt.executeQuery(); if(rs.next()) { count = rs.getLong("count"); } } finally { DbConnectionManager.closeConnection(rs, stmt, conn); } return count; } public List<AppSubscription> getSubscribedApps( String userId) throws DemeterException, Throwable { List<AppSubscription> collection = new ArrayList<AppSubscription>(); Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = DbConnectionManager.getConnection(); stmt = conn.prepareStatement(SQL_QUERY_APP_SUBSCRIPTIONS); int idx = 0; stmt.setString(++idx, userId); rs = stmt.executeQuery(); while(rs.next()) { AppSubscription object = AppSubscription.from(rs); collection.add(object); } } finally { DbConnectionManager.closeConnection(rs, stmt, conn); } return collection; } public AppSubscription getSubscribedApp( String appId, String userId) throws DemeterException, Throwable { AppSubscription object = null; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = DbConnectionManager.getConnection(); stmt = conn.prepareStatement(SQL_QUERY_APP_SUBSCRIPTION); int idx = 0; stmt.setString(++idx, appId); stmt.setString(++idx, userId); rs = stmt.executeQuery(); do { if(!rs.next()) { break; } object = AppSubscription.from(rs); } while(false); } finally { DbConnectionManager.closeConnection(rs, stmt, conn); } return object; } public void subscribeApp(String appId, String userId) throws DemeterException, Throwable { AppSubscription object = this.getSubscribedApp(appId, userId); if(null != object) { throw new DemeterException("APP HAS ALREADY BEEN SUBSCRIBED"); } Connection conn = null; PreparedStatement stmt = null; try { conn = DbConnectionManager.getConnection(); stmt = conn.prepareStatement(SQL_INSERT_APP_SUBSCRIPTION); int idx = 0; stmt.setString(++idx, appId); stmt.setString(++idx, userId); stmt.setLong(++idx, System.currentTimeMillis()); stmt.executeUpdate(); } finally { DbConnectionManager.closeConnection(stmt, conn); } } public void unsubscribeApp(String appId, String userId) throws DemeterException, Throwable { AppSubscription object = this.getSubscribedApp(appId, userId); if(null == object) { throw new DemeterException("APP HAS NOT BEEN SUBSCRIBED"); } Connection conn = null; PreparedStatement stmt = null; try { conn = DbConnectionManager.getConnection(); stmt = conn.prepareStatement(SQL_DELETE_APP_SUBSCRIPTION); int idx = 0; stmt.setString(++idx, appId); stmt.setString(++idx, userId); stmt.executeUpdate(); } finally { DbConnectionManager.closeConnection(stmt, conn); } } private String generateVersionId( String applicationId, String modelName, Long creationTime) { byte[] applicationIdData = applicationId.getBytes(StandardCharsets.UTF_8); byte[] modelNameData = modelName.getBytes(StandardCharsets.UTF_8); int length = applicationIdData.length + modelNameData.length + Long.BYTES; ByteBuffer buffer = ByteBuffer.allocate(length); buffer.put(applicationIdData); buffer.put(modelNameData); buffer.putLong(creationTime); return Algorithm.md5(buffer.array()); } public static void exportAppsToCloud() throws DemeterException, Throwable { Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; List<CloudObj> file_objs = new ArrayList<CloudObj>(); class update_item{ String id; String path; update_item(String _id, String _path){ id = _id; path = _path; } }; List<update_item> update_app_versions = new ArrayList<update_item>(); try { conn = DbConnectionManager.getConnection(); stmt = conn.prepareStatement(SQL_QUERY_ALL_APP_VERSIONS); rs = stmt.executeQuery(); while(rs.next()){ AppVersion object = AppVersion.from(rs); try{ appendFileObjs(object.getIPKFilePath(), file_objs); } catch(Throwable ignored){} String new_path = getRelativePath(object); if(new_path.equals(object.getIPKFilePath()) == false ){ update_app_versions.add(new update_item(object.getId(), new_path)); } } for(update_item version : update_app_versions){ stmt = conn.prepareStatement(SQL_UPDATE_APP_VERSION_PATH); stmt.setString(1, version.path); stmt.setString(2, version.id); stmt.executeUpdate(); } } catch(SQLException e){ throw (new DemeterException("SQL exception: " + e.getMessage())).SettHttpStatus(Status.INTERNAL_SERVER_ERROR); } finally { DbConnectionManager.closeConnection(rs, stmt, conn); } if(file_objs.size() > 0){ SaveFilesToCloud(file_objs, true); } } private static void appendFileObjs( String ipk_file_path, List<CloudObj> objs) throws Throwable { String root_path = ""; String file_path = ""; root_path = SystemProperties.getInstance().getStorage().getRootPath(); if(root_path.endsWith(File.separator) == false){ root_path = root_path.concat(File.separator); } if(ipk_file_path.startsWith(File.separator) == false){ file_path = root_path + ipk_file_path; } else { file_path = ipk_file_path; if(file_path.startsWith(root_path) == false){ // system setting for root path do not match root path in DB entry File path = new File(file_path); root_path = path.getParentFile().getParentFile().getParentFile().toString(); if(root_path.endsWith(File.separator) == false){ root_path = root_path.concat(File.separator); } } } //find parent (app version) folder File ipkFile = new File(file_path); //collect all file names in folder List<String> all_files = null; try (Stream<Path> walk = Files.walk(ipkFile.getParentFile().toPath())) { all_files = walk.filter(Files::isRegularFile) .filter(file -> !Files.isDirectory(file)) .map(x -> x.toString()) .collect(Collectors.toList()); } catch (IOException ignored) {} String version_path = ipkFile.getParentFile().toString(); if(version_path.endsWith(File.separator) == false){ version_path = version_path.concat(File.separator); } // add object for each found file if(all_files != null){ for(String file : all_files){ objs.add(new CloudObj(file, file.substring(root_path.length()))); } } } private static String getRelativePath( AppVersion version){ String app_str = version.getAppId(); String cur_path = version.getIPKFilePath(); if(cur_path.startsWith(File.separator) == false && cur_path.startsWith(app_str) == true){ return cur_path; } return cur_path.substring(cur_path.indexOf(app_str)); } }
UTF-8
Java
72,771
java
AppManager.java
Java
[]
null
[]
package com.sercomm.openfire.plugin; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.stream.Stream; import java.util.stream.Collectors; import javax.ws.rs.core.Response.Status; import org.apache.commons.io.FileUtils; import org.jivesoftware.database.DbConnectionManager; import com.sercomm.common.util.Algorithm; import com.sercomm.common.util.ManagerBase; import com.sercomm.commons.util.XStringUtil; import com.sercomm.openfire.plugin.data.frontend.App; import com.sercomm.openfire.plugin.data.frontend.AppIcon; import com.sercomm.openfire.plugin.data.frontend.AppSubscription; import com.sercomm.openfire.plugin.data.frontend.AppVersion; import com.sercomm.openfire.plugin.exception.DemeterException; import com.sercomm.openfire.plugin.util.DbConnectionUtil; import com.sercomm.openfire.plugin.util.IpkUtil; import com.sercomm.openfire.plugin.util.StorageUtil; import com.sercomm.openfire.plugin.define.StorageType; import io.minio.BucketExistsArgs; import io.minio.MakeBucketArgs; import io.minio.MinioClient; import io.minio.UploadObjectArgs; import io.minio.RemoveObjectArgs; import io.minio.StatObjectArgs; import io.minio.ListObjectsArgs; import io.minio.Result; import io.minio.messages.Item; import okhttp3.HttpUrl; import io.minio.errors.MinioException; import io.minio.StatObjectResponse; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AppManager extends ManagerBase { //private static final Logger log = LoggerFactory.getLogger(AppManager.class); private final static String TABLE_S_APP = "sApp"; private final static String TABLE_S_APP_ICON = "sAppIcon"; private final static String TABLE_S_APP_VERSION = "sAppVersion"; private final static String TABLE_S_APP_SUBSCRIPTION = "sAppSubscription"; private final static String SQL_UPDATE_APP = String.format("INSERT INTO `%s`" + "(`id`,`publisher`,`name`,`catalog`,`model`,`price`,`publish`,`description`,`creationTime`) " + "VALUES(?,?,?,?,?,?,?,?,?) " + "ON DUPLICATE KEY UPDATE `catalog`=?,`price`=?,`publish`=?,`description`=?", TABLE_S_APP); private final static String SQL_UPDATE_APP_ICON = String.format("INSERT INTO `%s`" + "(`appId`,`iconId`,`size`,`updatedTime`,`data`) " + "VALUES(?,?,?,?,?) " + "ON DUPLICATE KEY UPDATE `iconId`=?,`size`=?,`updatedTime`=?,`data`=?", TABLE_S_APP_ICON); private final static String SQL_INSERT_APP_VERSION = String.format("INSERT INTO `%s`" + "(`id`,`appId`,`version`,`status`,`filename`,`creationTime`,`ipkFilePath`,`ipkFileSize`,`releaseNote`,`realVersion`) " + "VALUES(?,?,?,?,?,?,?,?,?,?)", TABLE_S_APP_VERSION); private final static String SQL_UPDATE_APP_VERSION = String.format("UPDATE `%s` SET " + "`version`=?,`status`=?,`filename`=?,`ipkFileSize`=?,`releaseNote`=?,`realVersion`=? " + "WHERE `id`=?", TABLE_S_APP_VERSION); private final static String SQL_UPDATE_APP_VERSION_PATH = String.format("UPDATE `%s` SET " + "`ipkFilePath`=? " + "WHERE `id`=?", TABLE_S_APP_VERSION); private final static String SQL_QUERY_APP = String.format("SELECT * FROM `%s` WHERE `id`=?", TABLE_S_APP); private final static String SQL_QUERY_APPS = String.format("SELECT * FROM `%s` ORDER BY `name`", TABLE_S_APP); private final static String SQL_QUERY_APPS_BY_MODEL = String.format("SELECT SQL_CALC_FOUND_ROWS * FROM `%s` WHERE `model`=? ORDER BY ? ? LIMIT ?,?", TABLE_S_APP); private final static String SQL_DELETE_APP = String.format("DELETE FROM `%s` WHERE `id`=?", TABLE_S_APP); private final static String SQL_QUERY_APP_COUNT_BY_CATALOG = String.format("SELECT COUNT(*) AS `count` FROM `%s` WHERE `catalog`=?", TABLE_S_APP); private final static String SQL_QUERY_APP_VERSION = String.format("SELECT * FROM `%s` WHERE `appId`=? AND `version`=?", TABLE_S_APP_VERSION); private final static String SQL_QUERY_APP_VERSION_REAL_VERSION = String.format("SELECT * FROM `%s` WHERE `appId`=? AND `realVersion`=?", TABLE_S_APP_VERSION); private final static String SQL_QUERY_APP_VERSION_BY_ID = String.format("SELECT * FROM `%s` WHERE `id`=?", TABLE_S_APP_VERSION); private final static String SQL_QUERY_APP_VERSIONS = String.format("SELECT * FROM `%s` WHERE `appId`=?", TABLE_S_APP_VERSION); private final static String SQL_QUERY_APP_LATEST_VERSION = String.format("SELECT * FROM `%s` WHERE `appId`=? ORDER BY `creationTime` DESC LIMIT 1", TABLE_S_APP_VERSION); private final static String SQL_DELETE_APP_VERSION = String.format("DELETE FROM `%s` WHERE `appId`=? AND `id`=?", TABLE_S_APP_VERSION); private final static String SQL_QUERY_ALL_APP_VERSIONS = String.format("SELECT * FROM `%s`", TABLE_S_APP_VERSION); private final static String SQL_QUERY_APP_ICON = String.format("SELECT * FROM `%s` WHERE `iconId`=?", TABLE_S_APP_ICON); private final static String SQL_QUERY_APP_ICON_BY_APP_ID = String.format("SELECT * FROM `%s` WHERE `appId`=?", TABLE_S_APP_ICON); private final static String SQL_DELETE_APP_ICON_BY_APP_ID = String.format("DELETE FROM `%s` WHERE `appId`=?", TABLE_S_APP_ICON); private final static String SQL_QUERY_APP_INSTALLED_COUNT = String.format("SELECT SUM(`installedCount`) AS `count` FROM `%s` WHERE `appId`=?", TABLE_S_APP_VERSION); private final static String SQL_QUERY_APP_INSTALLED_COUNT_BY_VERSION = String.format("SELECT `installedCount` AS `count` FROM `%s` WHERE `appId`=? AND `version`=?", TABLE_S_APP_VERSION); private final static String SQL_QUERY_APP_SUBSCRIPTIONS = String.format("SELECT * FROM `%s` WHERE `userId`=?", TABLE_S_APP_SUBSCRIPTION); private final static String SQL_QUERY_APP_SUBSCRIPTION = String.format("SELECT * FROM `%s` WHERE `appId`=? AND `userId`=?", TABLE_S_APP_SUBSCRIPTION); private final static String SQL_INSERT_APP_SUBSCRIPTION = String.format("INSERT INTO `%s`(`appId`,`userId`,`creationTime`) VALUES(?,?,?)", TABLE_S_APP_SUBSCRIPTION); private final static String SQL_DELETE_APP_SUBSCRIPTION = String.format("DELETE FROM `%s` WHERE `appId`=? AND `userId`=?", TABLE_S_APP_SUBSCRIPTION); private final static String SQL_DELETE_APP_SUBSCRIPTIONS = String.format("DELETE FROM `%s` WHERE `appId`=?", TABLE_S_APP_SUBSCRIPTION); private static class AppManagerContainer { private final static AppManager instance = new AppManager(); private final static HttpUrl minio_getUrl(){ HttpUrl url = HttpUrl.parse(SystemProperties.getInstance().getStorage().getAwsUrl()); return new HttpUrl.Builder() .scheme(SystemProperties.getInstance().getStorage().getAwsScheme()) .host(url.host()) .port(url.port()) .build(); } private final static MinioClient minio_instance = MinioClient.builder() .endpoint(minio_getUrl()) .credentials( SystemProperties.getInstance().getStorage().getAwsKey(), SystemProperties.getInstance().getStorage().getAwsSecret()) .build(); } private AppManager() { } public static AppManager getInstance() { return AppManagerContainer.instance; } public static MinioClient getMinioInstance() { return AppManagerContainer.minio_instance; } @Override protected void onInitialize() { } @Override protected void onUninitialize() { } public static class CloudObj{ public CloudObj (String fname, String obj_name) { filename = fname; object_name = obj_name; } public String filename; public String object_name; } public void SaveFileToCloud( String filepath, String object_name) throws DemeterException { List<CloudObj> objects = new ArrayList<CloudObj>(); objects.add(new CloudObj(filepath, object_name)); SaveFilesToCloud(objects, false); } public void setManifest( String appId, String manifestFileName, byte[] manifestFileData) throws DemeterException, Throwable { if(manifestFileData != null) { String FSRootPathString = SystemProperties.getInstance().getStorage().getRootPath(); if(FSRootPathString.endsWith(File.separator) == false){ FSRootPathString = FSRootPathString.concat(File.separator); } final String manifestFilePathString = appId + File.separator + IpkUtil.PACKAGE_MANIFEST_FILENAME; final Path manifestFilePath = Paths.get(FSRootPathString + manifestFilePathString); final Path packageFolderPath = Paths.get(FSRootPathString + appId); final StorageType storage_type = SystemProperties.getInstance().getStorage().getStorageType(); // create temporary folder Path tempFolder = Files.createTempDirectory(UUID.randomUUID().toString()); try { Path tempFilePath = Paths.get( tempFolder.toAbsolutePath().toString() + File.separator + IpkUtil.PACKAGE_MANIFEST_FILENAME); // save bytes array as "data.ipk" file to temporary folder try(FileOutputStream fos = new FileOutputStream(tempFilePath.toFile())) { fos.write(manifestFileData); } boolean moved = false; try { if(storage_type == StorageType.LOCAL_FS){ try { // check if the package folder exists if(false == Files.exists(packageFolderPath)) { Files.createDirectories(packageFolderPath.toAbsolutePath()); } } catch(IOException e) { throw new IOException("FAILED TO CREATE DIRECTORY: " + e.getMessage()); } try { // move manifest file try { this.deleteManifest(appId); } catch(Throwable ignored) {} Files.move(tempFilePath, manifestFilePath); } catch(IOException e) { throw new IOException("FAILED TO Create Manifest FILE"); } } else if(storage_type == StorageType.AWS_S3) { this.RemoveObjectFromCloud(manifestFilePathString); List<CloudObj> objects = new ArrayList<CloudObj>(); objects.add(new CloudObj(tempFilePath.toString(), manifestFilePathString)); SaveFilesToCloud(objects, false); } else { throw new DemeterException("STORAGE TYPE IS NOT SUPPORTED"); } moved = true; } finally {} } finally { // clean temporary files FileUtils.forceDelete(tempFolder.toFile()); } } } public static void SaveFilesToCloud( Iterable<CloudObj> objects, boolean ignore_errors_flag) throws DemeterException { int saved_num = 0; boolean err = true; String err_string = ""; Status http_status = Status.BAD_GATEWAY; final String bucket_name = SystemProperties.getInstance().getStorage().getAwsBucket(); try { MinioClient minioClient = getMinioInstance(); boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucket_name).build()); if (!found) { minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucket_name).build()); } for(CloudObj obj : objects){ try{ minioClient.uploadObject( UploadObjectArgs.builder() .bucket(bucket_name) .object(obj.object_name) .filename(obj.filename) .build()); saved_num++; } catch(Throwable e){ if(ignore_errors_flag == false) throw e; } } err = false; } catch (MinioException e) { err_string = "Minio exception: " + e + " HTTP trace: " + e.httpTrace(); http_status = Status.SERVICE_UNAVAILABLE; } catch (InvalidKeyException e) { err_string = "Minio exception: " + e; } catch (NoSuchAlgorithmException e){ err_string = "Minio exception: " + e; } catch(IOException e){ err_string = "IOException: " + e; } if(err && !ignore_errors_flag){ List<String> obj_names = new ArrayList<String>(); int i = 0; for(CloudObj obj : objects){ if(i == saved_num) break; obj_names.add(obj.object_name); } try{ RemoveObjectsFromCloud(obj_names); } catch(DemeterException ignored){ } throw (new DemeterException(err_string)).SettHttpStatus(http_status); } } public static void RemoveObjectFromCloud( String object_name) throws DemeterException { List<String> list = new ArrayList<String>(); list.add(object_name); RemoveObjectsFromCloud(list); } public static void RemoveObjectsFromCloud( Iterable<String> objects) throws DemeterException { final String bucket_name = SystemProperties.getInstance().getStorage().getAwsBucket(); try { MinioClient minioClient = getMinioInstance(); for(String obj : objects){ minioClient.removeObject(RemoveObjectArgs.builder() .bucket(bucket_name) .object(obj).build()); } } catch (MinioException e) { throw (new DemeterException("Minio exception: " + e + " HTTP trace: " + e.httpTrace())) .SettHttpStatus(Status.SERVICE_UNAVAILABLE); } catch (InvalidKeyException e) { throw (new DemeterException("Minio exception: " + e)) .SettHttpStatus(Status.BAD_GATEWAY); } catch (NoSuchAlgorithmException e){ throw (new DemeterException("Minio exception: " + e)) .SettHttpStatus(Status.BAD_GATEWAY); } catch(IOException e){ throw (new DemeterException("IOException: " + e)) .SettHttpStatus(Status.BAD_GATEWAY); } } public static boolean ExistFileOnCloud( String object_name) throws DemeterException { final String bucket_name = SystemProperties.getInstance().getStorage().getAwsBucket(); try { MinioClient minioClient = getMinioInstance(); io.minio.StatObjectResponse stat = minioClient.statObject(StatObjectArgs.builder() .bucket(bucket_name) .object(object_name).build()); if(stat.size() != 0) { return true; } } catch (MinioException e) { return false; } catch (InvalidKeyException e) { return false; } catch (NoSuchAlgorithmException e){ return false; } catch(IOException e){ return false; } return false; } public static void RemoveFolderFromCloud( String folder_name) throws DemeterException { if(folder_name.length() == 0){ return; } if(false == folder_name.endsWith(File.separator)){ folder_name = folder_name.concat(File.separator); } try { final String bucket_name = SystemProperties.getInstance().getStorage().getAwsBucket(); MinioClient minioClient = getMinioInstance(); Iterable<Result<Item>> results = minioClient.listObjects( ListObjectsArgs.builder() .bucket(bucket_name) .prefix(folder_name) .build()); for (Result<Item> result : results) { minioClient.removeObject(RemoveObjectArgs.builder() .bucket(bucket_name) .object(result.get().objectName()) .build()); } } catch (MinioException e) { throw (new DemeterException("Minio exception: " + e + " HTTP trace: " + e.httpTrace())) .SettHttpStatus(Status.SERVICE_UNAVAILABLE); } catch (InvalidKeyException e) { throw (new DemeterException("Minio exception: " + e)) .SettHttpStatus(Status.BAD_GATEWAY); } catch (NoSuchAlgorithmException e){ throw (new DemeterException("Minio exception: " + e)) .SettHttpStatus(Status.BAD_GATEWAY); } catch(IOException e){ throw (new DemeterException("IOException: " + e)) .SettHttpStatus(Status.BAD_GATEWAY); } } public void addApp( String publisher, String name, String catalog, String modelName, String price, Integer publish, String description, String manifestFileName, byte[] manifestFileData, byte[] iconData) throws DemeterException, Throwable { App application = null; try { application = this.getApp(publisher, name, modelName); } catch(DemeterException ignored) {} if(null != application) { throw new DemeterException("APPLICATION ALREADY EXISTS"); } Connection conn = null; PreparedStatement stmt = null; boolean abort = false; try { final String id = Algorithm.md5(publisher + name + modelName); final long creationTime = System.currentTimeMillis(); conn = DbConnectionManager.getConnection(); conn = DbConnectionUtil.openTransaction(conn); do { int idx; // update first table stmt = conn.prepareStatement(SQL_UPDATE_APP); idx = 0; // `id`,`publisher`,`name`,`catalog`,`modelName`,`price`,`publish`,`description`,`creationTime` stmt.setString(++idx, id); stmt.setString(++idx, publisher); stmt.setString(++idx, name); stmt.setString(++idx, catalog); stmt.setString(++idx, modelName); stmt.setString(++idx, price); stmt.setInt(++idx, publish); stmt.setString(++idx, description); stmt.setLong(++idx, creationTime); // `catalog`,`price`,`publish`,`description` stmt.setString(++idx, catalog); stmt.setString(++idx, price); stmt.setInt(++idx, publish); stmt.setString(++idx, description); stmt.executeUpdate(); DbConnectionManager.fastcloseStmt(stmt); final String appId = id; setManifest(appId, manifestFileName, manifestFileData); if(null == iconData) { break; } // update 2nd table stmt = conn.prepareStatement(SQL_UPDATE_APP_ICON); final String iconId = Algorithm.md5(iconData); idx = 0; // `appId`,`iconId`,`size`,`updatedTime`,`data` stmt.setString(++idx, appId); stmt.setString(++idx, iconId); stmt.setLong(++idx, iconData.length); stmt.setLong(++idx, creationTime); stmt.setBytes(++idx, iconData); // `iconId`,`size`,`updatedTime`,`data` stmt.setString(++idx, iconId); stmt.setLong(++idx, iconData.length); stmt.setLong(++idx, creationTime); stmt.setBytes(++idx, iconData); stmt.executeUpdate(); } while(false); } catch(Throwable t) { abort = true; throw t; } finally { DbConnectionManager.closeStatement(stmt); DbConnectionUtil.closeTransaction(conn, abort); DbConnectionManager.closeConnection(conn); } } public void setApp( App object, String manifestFileName, byte[] manifestFileData, byte[] iconData) throws DemeterException, Throwable { final String id = object.getId(); if(null == this.getApp(id)) { throw new DemeterException("APP DOES NOT EXIST"); } Connection conn = null; PreparedStatement stmt = null; boolean abort = false; try { conn = DbConnectionManager.getConnection(); conn = DbConnectionUtil.openTransaction(conn); do { int idx; // update 1st table idx = 0; stmt = conn.prepareStatement(SQL_UPDATE_APP); // `id`,`publisher`,`name`,`catalog`,`model`,`price`,`publish`,`description`,`creationTime` stmt.setString(++idx, id); stmt.setString(++idx, object.getPublisher()); stmt.setString(++idx, object.getName()); stmt.setString(++idx, object.getCatalog()); stmt.setString(++idx, object.getModelName()); stmt.setString(++idx, object.getPrice()); stmt.setInt(++idx, object.getPublish()); stmt.setString(++idx, object.getDescription()); stmt.setLong(++idx, object.getCreationTime()); // `catalog`,`price`,`publish`,`description` stmt.setString(++idx, object.getCatalog()); stmt.setString(++idx, object.getPrice()); stmt.setInt(++idx, object.getPublish()); stmt.setString(++idx, object.getDescription()); stmt.executeUpdate(); DbConnectionManager.fastcloseStmt(stmt); final String appId = id; setManifest(appId, manifestFileName, manifestFileData); if(null == iconData) { break; } // update 2nd table final long updatedTime = System.currentTimeMillis(); // generate icon ID int length = iconData.length + Long.BYTES; ByteBuffer buffer = ByteBuffer.allocate(length); buffer.put(iconData); buffer.putLong(updatedTime); final String iconId = Algorithm.md5(buffer.array()); idx = 0; stmt = conn.prepareStatement(SQL_UPDATE_APP_ICON); // `appId`,`iconId`,`size`,`updatedTime`,`data` stmt.setString(++idx, appId); stmt.setString(++idx, iconId); stmt.setLong(++idx, iconData.length); stmt.setLong(++idx, updatedTime); stmt.setBytes(++idx, iconData); // `iconId`,`size`,`updatedTime`,`data` stmt.setString(++idx, iconId); stmt.setLong(++idx, iconData.length); stmt.setLong(++idx, updatedTime); stmt.setBytes(++idx, iconData); stmt.executeUpdate(); } while(false); } catch(Throwable t) { abort = true; throw t; } finally { DbConnectionManager.closeStatement(stmt); DbConnectionUtil.closeTransaction(conn, abort); DbConnectionManager.closeConnection(conn); } } public List<App> getApps() throws DemeterException, Throwable { List<App> apps = new ArrayList<App>(); Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = DbConnectionManager.getConnection(); stmt = conn.prepareStatement(SQL_QUERY_APPS); rs = stmt.executeQuery(); while(rs.next()) { App object = App.from(rs); apps.add(object); } } finally { DbConnectionManager.closeConnection(rs, stmt, conn); } return apps; } public List<App> getAppsByModel(String modelName) throws DemeterException, Throwable { List<App> apps = new ArrayList<App>(); this.getAppsByModel(modelName, 0, 9999, "name", "asc", apps); return apps; } public int getAppsByModel( String modelName, Integer from, Integer size, String sort, String order, List<App> apps) throws DemeterException, Throwable { int totalCount = 0; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = DbConnectionManager.getConnection(); stmt = conn.prepareStatement(SQL_QUERY_APPS_BY_MODEL); int idx = 0; stmt.setString(++idx, modelName); stmt.setString(++idx, sort); stmt.setString(++idx, order); stmt.setInt(++idx, from); stmt.setInt(++idx, size); rs = stmt.executeQuery(); while(rs.next()) { App object = App.from(rs); apps.add(object); } } finally { DbConnectionManager.closeStatement(rs, stmt); try { stmt = conn.prepareStatement("SELECT FOUND_ROWS()"); rs = stmt.executeQuery(); if(rs.next()) { totalCount = rs.getInt(1); } } finally { DbConnectionManager.closeConnection(rs, stmt, conn); } } return totalCount; } public App getApp( String publisher, String name, String modelName) throws DemeterException, Throwable { if(XStringUtil.isBlank(publisher) || XStringUtil.isBlank(name)) { throw new DemeterException("ARGUMENT(S) CANNOT BE BLANK"); } final String id = Algorithm.md5(publisher + name + modelName); return this.getApp(id); } public App getApp(String appId) throws DemeterException, Throwable { App object = null; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = DbConnectionManager.getConnection(); stmt = conn.prepareStatement(SQL_QUERY_APP); int idx = 0; stmt.setString(++idx, appId); rs = stmt.executeQuery(); do { if(!rs.next()) { throw new DemeterException("APP CANNOT BE FOUND"); } object = App.from(rs); } while(false); } finally { DbConnectionManager.closeConnection(rs, stmt, conn); } return object; } public void deleteApp( String appId) throws DemeterException, Throwable { // obtain the App object and check if the App ID is valid App app = this.getApp(appId); // backup the App's versions information at first List<AppVersion> appVersions = this.getAppVersions(app.getId()); boolean abort = false; Connection conn = null; PreparedStatement stmt = null; try { conn = DbConnectionManager.getConnection(); conn = DbConnectionUtil.openTransaction(conn); // delete App manifest try { this.deleteManifest(app.getId()); } catch(Throwable ignored) {} // delete versions of the application for(AppVersion appVersion: appVersions) { this.deleteAppVersion(app.getId(), appVersion.getId()); } // delete App subscriptions this.deleteAppSubscriptions(conn, app.getId()); // delete App icon this.deleteAppIcon(conn, app.getId()); // delete the App int idx; idx = 0; stmt = conn.prepareStatement(SQL_DELETE_APP); stmt.setString(++idx, app.getId()); stmt.executeUpdate(); try { String FSRootPathString = SystemProperties.getInstance().getStorage().getRootPath(); if(FSRootPathString.endsWith(File.separator) == false){ FSRootPathString = FSRootPathString.concat(File.separator); } final Path packageFolderPath = Paths.get(FSRootPathString + app.getId()); if(true == Files.exists(packageFolderPath)) { FileUtils.forceDelete(packageFolderPath.toFile()); } } catch(Throwable ignored) {} } catch(Throwable t) { abort = true; throw t; } finally { DbConnectionManager.closeStatement(stmt); DbConnectionUtil.closeTransaction(conn, abort); DbConnectionManager.closeConnection(conn); } // delete its physical files if(false == abort) { final StorageType storage_type = SystemProperties.getInstance().getStorage().getStorageType(); if(storage_type == StorageType.LOCAL_FS){ if(false == appVersions.isEmpty()) { StringBuilder sb = new StringBuilder(SystemProperties.getInstance().getStorage().getRootPath()); if(sb.toString().endsWith(File.separator) == false){ sb.append(File.separator); } sb.append(appId); try { FileUtils.forceDelete(new File(sb.toString())); } catch(Throwable ignored) {} } } } } public void deleteManifest( String appId) throws DemeterException, Throwable { String FSRootPathString = SystemProperties.getInstance().getStorage().getRootPath(); if(FSRootPathString.endsWith(File.separator) == false){ FSRootPathString = FSRootPathString.concat(File.separator); } final String manifestFilePathString = appId + File.separator + IpkUtil.PACKAGE_MANIFEST_FILENAME; final Path manifestFilePath = Paths.get(FSRootPathString + manifestFilePathString); final StorageType storage_type = SystemProperties.getInstance().getStorage().getStorageType(); if(storage_type == StorageType.LOCAL_FS) { if(true == Files.exists(manifestFilePath)) { FileUtils.forceDelete(manifestFilePath.toFile()); } } else if(storage_type == StorageType.AWS_S3) { this.RemoveObjectFromCloud(manifestFilePathString); } else { throw new DemeterException("STORAGE TYPE IS NOT SUPPORTED"); } } public String getManifestExist( String appId) throws DemeterException, Throwable { String ret = "no"; String FSRootPathString = SystemProperties.getInstance().getStorage().getRootPath(); if(FSRootPathString.endsWith(File.separator) == false){ FSRootPathString = FSRootPathString.concat(File.separator); } final String manifestFilePathString = appId + File.separator + IpkUtil.PACKAGE_MANIFEST_FILENAME; final Path manifestFilePath = Paths.get(FSRootPathString + manifestFilePathString); final StorageType storage_type = SystemProperties.getInstance().getStorage().getStorageType(); if(storage_type == StorageType.LOCAL_FS) { if(true == Files.exists(manifestFilePath)) { ret = "yes"; } else { ret = "no"; } } else if(storage_type == StorageType.AWS_S3) { if(this.ExistFileOnCloud(manifestFilePathString)) { ret = "yes"; } else { ret = "no"; } } else { throw new DemeterException("STORAGE TYPE IS NOT SUPPORTED"); } return ret; } public void deleteAppVersion( String appId, String versionId) throws DemeterException, Throwable { AppVersion appVersion = this.getAppVersion(versionId); boolean abortTransaction = true; Connection conn = null; PreparedStatement stmt = null; try { // delete the row from database conn = DbConnectionManager.getConnection(); DbConnectionUtil.openTransaction(conn); stmt = conn.prepareStatement(SQL_DELETE_APP_VERSION); int idx = 0; stmt.setString(++idx, appId); stmt.setString(++idx, versionId); stmt.executeUpdate(); final StorageType storage_type = SystemProperties.getInstance().getStorage().getStorageType(); if(storage_type == StorageType.LOCAL_FS){ // delete the package's folder from volume File ipkFile = new File( SystemProperties.getInstance().getStorage().getRootPath() + File.separator + appVersion.getIPKFilePath()); FileUtils.forceDelete(ipkFile.getParentFile()); } else if(storage_type == StorageType.AWS_S3){ File ipkFile = new File(appVersion.getIPKFilePath()); RemoveFolderFromCloud(ipkFile.getParentFile().toString()); } else { throw new DemeterException("STORAGE TYPE IS NOT SUPPORTED"); } abortTransaction = false; } catch(Throwable t) { throw t; } finally { DbConnectionManager.closeStatement(stmt); DbConnectionUtil.closeTransaction(conn, abortTransaction); DbConnectionManager.closeConnection(conn); } } private void deleteAppIcon( Connection conn, String appId) throws DemeterException, Throwable { PreparedStatement stmt = null; try { stmt = conn.prepareStatement(SQL_DELETE_APP_ICON_BY_APP_ID); int idx = 0; stmt.setString(++idx, appId); stmt.executeUpdate(); } finally { DbConnectionManager.closeStatement(stmt); } } private void deleteAppSubscriptions( Connection conn, String appId) throws DemeterException, Throwable { PreparedStatement stmt = null; try { stmt = conn.prepareStatement(SQL_DELETE_APP_SUBSCRIPTIONS); int idx = 0; stmt.setString(++idx, appId); stmt.executeUpdate(); } finally { DbConnectionManager.closeStatement(stmt); } } public Long getAppCount( String catalogName) throws DemeterException, Throwable { Long count = 0L; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = DbConnectionManager.getConnection(); stmt = conn.prepareStatement(SQL_QUERY_APP_COUNT_BY_CATALOG); int idx = 0; stmt.setString(++idx, catalogName); rs = stmt.executeQuery(); if(rs.next()) { count = rs.getLong("count"); } } finally { DbConnectionManager.closeConnection(rs, stmt, conn); } return count; } public void addAppVersion( String applicationId, String versionName, Integer status, // 1: enable, 0: disable String ipkFileName, byte[] ipkFileData) throws DemeterException, Throwable { App app = this.getApp(applicationId); if(null == app) { throw new DemeterException("APPLICATION DOES NOT EXIST"); } if(XStringUtil.isBlank(versionName)) { //throw new DemeterException("VERSION NAME CANNOT BE BLANK"); // !!! added temporary version name as there is no version here (due to a bug) versionName = "version_" + String.valueOf(System.currentTimeMillis()); } // create temporary folder Path tempFolder = Files.createTempDirectory(UUID.randomUUID().toString()); try { Path tempIPKFilePath = Paths.get( tempFolder.toAbsolutePath().toString() + File.separator + IpkUtil.PACKAGE_IPK_FILENAME); // save bytes array as "data.ipk" file to temporary folder try(FileOutputStream fos = new FileOutputStream(tempIPKFilePath.toFile())) { fos.write(ipkFileData); } // extract the IPK, and verify its package information // finally, a "Packages.gz" file will be left in the temporary folder com.sercomm.openfire.plugin.data.ipk.Meta meta = IpkUtil.validate(tempIPKFilePath); if(XStringUtil.isBlank(meta.Version)) { throw new DemeterException("BAD PACKAGE INFORMATION. NO REQUIRED FIELD WITHIN 'control' FILE OF THE PACKAGE: 'Version'"); } // a "Packages.gz" file will be generated after IpkUtil.validate() method being executed final Path tempPackageInfoFilePath = Paths.get(tempFolder.toAbsolutePath().toString() + File.separator + IpkUtil.PACKAGE_GZ_FILENAME); final long creationTime = System.currentTimeMillis(); // generate version ID final String versionId = generateVersionId( app.getId(), app.getModelName(), creationTime); // --> begin filename investigation // 1. if there is no specific IPK filename, use the filename within // package information by default if(XStringUtil.isBlank(ipkFileName)) { ipkFileName = meta.Filename; } // 2. if IPK filename is still blank, set the filename same as application's name if(XStringUtil.isBlank(ipkFileName)) { ipkFileName = app.getName(); } // --> end filename investigation final String description = XStringUtil.isBlank(meta.Description) ? XStringUtil.BLANK : meta.Description; final String realVersion = XStringUtil.isBlank(meta.Version) ? XStringUtil.BLANK : meta.Version; AppVersion appVersion = null; // check if duplicate version name exists try { appVersion = this.getAppVersion(applicationId, versionName); } catch(DemeterException ignored) {} finally { if(null != appVersion) { throw new DemeterException("APP VERSION ALREADY EXISTS"); } } // check if duplicate version ID exists try { appVersion = this.getAppVersion(versionId); } catch(DemeterException ignored) {} finally { if(null != appVersion) { throw new DemeterException("APP VERSION ALREADY EXISTS"); } } final StorageType storage_type = SystemProperties.getInstance().getStorage().getStorageType(); final String VersionPathString = app.getId() + File.separator + versionId; String FSRootPathString = SystemProperties.getInstance().getStorage().getRootPath(); if(FSRootPathString.endsWith(File.separator) == false){ FSRootPathString = FSRootPathString.concat(File.separator); } final String ipkFilePathString = VersionPathString + File.separator + IpkUtil.PACKAGE_IPK_FILENAME; final String packageInfoFilePathString = VersionPathString + File.separator + IpkUtil.PACKAGE_GZ_FILENAME; // 1. establish database records // 2. move files boolean abortTransaction = true; Connection conn = null; PreparedStatement stmt = null; try { conn = DbConnectionManager.getConnection(); DbConnectionUtil.openTransaction(conn); stmt = conn.prepareStatement(SQL_INSERT_APP_VERSION); int idx = 0; // `id`,`appId`,`version`,`status`,`creationTime`,`ipkFilePath`,`ipkFileSize`,`releaseNote` stmt.setString(++idx, versionId); stmt.setString(++idx, applicationId); stmt.setString(++idx, versionName); stmt.setInt(++idx, status); stmt.setString(++idx, ipkFileName); stmt.setLong(++idx, creationTime); stmt.setString(++idx, ipkFilePathString); stmt.setLong(++idx, ipkFileData.length); stmt.setString(++idx, description); stmt.setString(++idx, realVersion); stmt.executeUpdate(); // database record being inserted successfully // then moving the files boolean moved = false; try { if(storage_type == StorageType.LOCAL_FS){ final Path packageFolderPath = Paths.get(FSRootPathString + VersionPathString); final Path ipkFilePath = Paths.get(FSRootPathString + ipkFilePathString); final Path packageInfoFilePath = Paths.get(FSRootPathString + packageInfoFilePathString); try { // check if the package folder exists if(false == Files.exists(packageFolderPath)) { Files.createDirectories(packageFolderPath.toAbsolutePath()); } } catch(IOException e) { throw new IOException("FAILED TO CREATE DIRECTORY: " + e.getMessage()); } try { // move IPK file Files.move(tempIPKFilePath, ipkFilePath); // move package info. file Files.move(tempPackageInfoFilePath, packageInfoFilePath); } catch(IOException e) { throw new IOException("FAILED TO MOVE IPK FILE TO VOLUME: " + e.getMessage()); } } else if(storage_type == StorageType.AWS_S3){ List<CloudObj> objects = new ArrayList<CloudObj>(); objects.add(new CloudObj(tempIPKFilePath.toString(), ipkFilePathString)); objects.add(new CloudObj(tempPackageInfoFilePath.toString(), packageInfoFilePathString)); SaveFilesToCloud(objects, false); } else { throw new DemeterException("STORAGE TYPE IS NOT SUPPORTED"); } moved = true; } finally { // fallback if(false == moved) { if(storage_type == StorageType.LOCAL_FS){ // catch surrounded since the folder path might not be created yet try { final Path VPath = Paths.get(FSRootPathString + VersionPathString); FileUtils.forceDelete(VPath.toFile()); } catch(Throwable ignored) {} } } } abortTransaction = false; } finally { DbConnectionManager.closeStatement(stmt); DbConnectionUtil.closeTransaction(conn, abortTransaction); DbConnectionManager.closeConnection(conn); } } finally { // clean temporary files FileUtils.forceDelete(tempFolder.toFile()); } } public void updateAppVersion( String applicationId, String versionId, String versionName, Integer status, // 1: enable, 0: disable String ipkFileName, byte[] ipkFileData) throws DemeterException, Throwable { App app = this.getApp(applicationId); if(null == app) { throw new DemeterException("APPLICATION DOES NOT EXIST"); } if(XStringUtil.isBlank(versionName)) { throw new DemeterException("VERSION NAME CANNOT BE BLANK"); } if(0 != status && 1 != status) { throw new DemeterException("INVALID 'status' VALUE"); } AppVersion appVersion = this.getAppVersion(versionId); // update the IPK file if necessary if(null != ipkFileData) { // create temporary folder Path tempFolder = Files.createTempDirectory( UUID.randomUUID().toString()); try { Path tempIPKFilePath = Paths.get( tempFolder.toAbsolutePath().toString() + File.separator + IpkUtil.PACKAGE_IPK_FILENAME); // save bytes array as "data.ipk" file to temporary folder try(FileOutputStream fos = new FileOutputStream(tempIPKFilePath.toFile())) { fos.write(ipkFileData); } // extract the IPK, and verify its package information // finally, a "Packages.gz" file will be left in the temporary folder com.sercomm.openfire.plugin.data.ipk.Meta meta = IpkUtil.validate(tempIPKFilePath); // --> begin filename investigation // 1. if there is no specific IPK filename, use the filename within // package information by default if(XStringUtil.isBlank(ipkFileName)) { ipkFileName = meta.Filename; } // 2. if IPK filename is still blank, set the filename same as application's name if(XStringUtil.isBlank(ipkFileName)) { ipkFileName = app.getName(); } // --> end filename investigation // a "Packages.gz" file will be generated after IpkUtil.validate() method being executed final Path tempPackageInfoFilePath = Paths.get(tempFolder.toAbsolutePath().toString() + File.separator + IpkUtil.PACKAGE_GZ_FILENAME); String FSRootPathString = SystemProperties.getInstance().getStorage().getRootPath(); if(FSRootPathString.endsWith(File.separator) == false){ FSRootPathString = FSRootPathString.concat(File.separator); } final String VersionPathString = app.getId() + File.separator + versionId; final String ipkFilePathString = VersionPathString + File.separator + IpkUtil.PACKAGE_IPK_FILENAME; final String packageInfoFilePathString = VersionPathString + File.separator + IpkUtil.PACKAGE_GZ_FILENAME; final StorageType storage_type = SystemProperties.getInstance().getStorage().getStorageType(); final String description = XStringUtil.isBlank(meta.Description) ? XStringUtil.BLANK : meta.Description; final String realVersion = XStringUtil.isBlank(meta.Version) ? XStringUtil.BLANK : meta.Version; Connection conn = null; PreparedStatement stmt = null; try { conn = DbConnectionManager.getConnection(); stmt = conn.prepareStatement(SQL_UPDATE_APP_VERSION); // `version`=?,`status`=?,`filename`=?,`ipkFileSize`=?,`releaseNote`=?,`realVersion`=? int idx = 0; stmt.setString(++idx, versionName); stmt.setInt(++idx, status); stmt.setString(++idx, ipkFileName); stmt.setLong(++idx, null == ipkFileData ? appVersion.getIPKFileSize() : ipkFileData.length); stmt.setString(++idx, description); stmt.setString(++idx, realVersion); stmt.setString(++idx, appVersion.getId()); stmt.executeUpdate(); } finally { DbConnectionManager.closeConnection(stmt, conn); } if(storage_type == StorageType.LOCAL_FS){ final Path packageFolderPath = Paths.get(FSRootPathString + VersionPathString); final Path ipkFilePath = Paths.get(FSRootPathString + ipkFilePathString); final Path packageInfoFilePath = Paths.get(FSRootPathString + packageInfoFilePathString); try { // check if the package folder exists if(Files.exists(packageFolderPath)) { // force delete the original folder FileUtils.forceDelete(packageFolderPath.toFile()); } // re-create it Files.createDirectories(packageFolderPath); } catch(IOException e) { throw new IOException("FAILED TO CREATE DIRECTORY: " + e.getMessage()); } try { // move IPK file Files.move(tempIPKFilePath, ipkFilePath); // move package info. file Files.move(tempPackageInfoFilePath, packageInfoFilePath); } catch(IOException e) { throw new IOException("FAILED TO MOVE IPK FILE TO VOLUME: " + e.getMessage()); } } else if(storage_type == StorageType.AWS_S3){ RemoveFolderFromCloud(VersionPathString); List<CloudObj> objects = new ArrayList<CloudObj>(); objects.add(new CloudObj(tempIPKFilePath.toString(), ipkFilePathString)); objects.add(new CloudObj(tempPackageInfoFilePath.toString(), packageInfoFilePathString)); SaveFilesToCloud(objects, false); } else { throw new DemeterException("STORAGE TYPE IS NOT SUPPORTED"); } } finally { // clean temporary files FileUtils.forceDelete(tempFolder.toFile()); } } } public AppVersion getAppVersionByRealVersion( String appId, String version) throws DemeterException, Throwable { AppVersion object = null; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = DbConnectionManager.getConnection(); stmt = conn.prepareStatement(SQL_QUERY_APP_VERSION_REAL_VERSION); int idx = 0; stmt.setString(++idx, appId); stmt.setString(++idx, version); rs = stmt.executeQuery(); if(!rs.next()) { throw new DemeterException("APP VERSION WAS NOT FOUND"); } object = AppVersion.from(rs); } finally { DbConnectionManager.closeConnection(rs, stmt, conn); } return object; } public AppVersion getAppVersion( String appId, String version) throws DemeterException, Throwable { AppVersion object = null; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = DbConnectionManager.getConnection(); stmt = conn.prepareStatement(SQL_QUERY_APP_VERSION); int idx = 0; stmt.setString(++idx, appId); stmt.setString(++idx, version); rs = stmt.executeQuery(); if(!rs.next()) { throw new DemeterException("APP VERSION WAS NOT FOUND"); } object = AppVersion.from(rs); } finally { DbConnectionManager.closeConnection(rs, stmt, conn); } return object; } public AppVersion getAppVersion( String versionId) throws DemeterException, Throwable { AppVersion object = null; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = DbConnectionManager.getConnection(); stmt = conn.prepareStatement(SQL_QUERY_APP_VERSION_BY_ID); int idx = 0; stmt.setString(++idx, versionId); rs = stmt.executeQuery(); if(!rs.next()) { throw new DemeterException("APP VERSION WAS NOT FOUND"); } object = AppVersion.from(rs); } finally { DbConnectionManager.closeConnection(rs, stmt, conn); } return object; } public AppVersion getAppLatestVersion( String appId) throws DemeterException, Throwable { AppVersion object = null; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = DbConnectionManager.getConnection(); stmt = conn.prepareStatement(SQL_QUERY_APP_LATEST_VERSION); int idx = 0; stmt.setString(++idx, appId); rs = stmt.executeQuery(); if(!rs.next()) { throw new DemeterException("NO APP VERSION AVAILABLE"); } object = AppVersion.from(rs); } finally { DbConnectionManager.closeConnection(rs, stmt, conn); } return object; } public List<AppVersion> getAppVersions(String appId) throws DemeterException, Throwable { List<AppVersion> appVersions = null; Connection conn = null; try { conn = DbConnectionManager.getConnection(); appVersions = this.getAppVersions(conn, appId); } finally { DbConnectionManager.closeConnection(conn); } return appVersions; } private List<AppVersion> getAppVersions(Connection conn, String appId) throws DemeterException, Throwable { List<AppVersion> appVersions = new ArrayList<AppVersion>(); PreparedStatement stmt = null; ResultSet rs = null; try { stmt = conn.prepareStatement(SQL_QUERY_APP_VERSIONS); int idx = 0; stmt.setString(++idx, appId); rs = stmt.executeQuery(); while(rs.next()) { AppVersion object = AppVersion.from(rs); appVersions.add(object); } } finally { DbConnectionManager.closeStatement(rs, stmt); } return appVersions; } public AppIcon getAppIcon( String iconId) throws DemeterException, Throwable { AppIcon object = null; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = DbConnectionManager.getConnection(); stmt = conn.prepareStatement(SQL_QUERY_APP_ICON); int idx = 0; stmt.setString(++idx, iconId); rs = stmt.executeQuery(); /* if(!rs.next()) { throw new DemeterException("APP ICON WAS NOT FOUND"); } object = AppIcon.from(rs); */ } finally { DbConnectionManager.closeConnection(rs, stmt, conn); } return object; } public AppIcon getAppIconByAppId( String appId) throws DemeterException, Throwable { AppIcon object = null; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = DbConnectionManager.getConnection(); stmt = conn.prepareStatement(SQL_QUERY_APP_ICON_BY_APP_ID); int idx = 0; stmt.setString(++idx, appId); rs = stmt.executeQuery(); /* if(!rs.next()) { throw new DemeterException("APP ICON WAS NOT FOUND"); } object = AppIcon.from(rs); */ } finally { DbConnectionManager.closeConnection(rs, stmt, conn); } return object; } public long getAppInstalledCount( String appId) throws DemeterException, Throwable { long count = 0; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = DbConnectionManager.getConnection(); stmt = conn.prepareStatement(SQL_QUERY_APP_INSTALLED_COUNT); int idx = 0; stmt.setString(++idx, appId); rs = stmt.executeQuery(); if(rs.next()) { count = rs.getLong("count"); } } finally { DbConnectionManager.closeConnection(rs, stmt, conn); } return count; } public long getAppInstalledCount( String appId, String version) throws DemeterException, Throwable { long count = 0; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = DbConnectionManager.getConnection(); stmt = conn.prepareStatement(SQL_QUERY_APP_INSTALLED_COUNT_BY_VERSION); int idx = 0; stmt.setString(++idx, appId); stmt.setString(++idx, version); rs = stmt.executeQuery(); if(rs.next()) { count = rs.getLong("count"); } } finally { DbConnectionManager.closeConnection(rs, stmt, conn); } return count; } public List<AppSubscription> getSubscribedApps( String userId) throws DemeterException, Throwable { List<AppSubscription> collection = new ArrayList<AppSubscription>(); Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = DbConnectionManager.getConnection(); stmt = conn.prepareStatement(SQL_QUERY_APP_SUBSCRIPTIONS); int idx = 0; stmt.setString(++idx, userId); rs = stmt.executeQuery(); while(rs.next()) { AppSubscription object = AppSubscription.from(rs); collection.add(object); } } finally { DbConnectionManager.closeConnection(rs, stmt, conn); } return collection; } public AppSubscription getSubscribedApp( String appId, String userId) throws DemeterException, Throwable { AppSubscription object = null; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = DbConnectionManager.getConnection(); stmt = conn.prepareStatement(SQL_QUERY_APP_SUBSCRIPTION); int idx = 0; stmt.setString(++idx, appId); stmt.setString(++idx, userId); rs = stmt.executeQuery(); do { if(!rs.next()) { break; } object = AppSubscription.from(rs); } while(false); } finally { DbConnectionManager.closeConnection(rs, stmt, conn); } return object; } public void subscribeApp(String appId, String userId) throws DemeterException, Throwable { AppSubscription object = this.getSubscribedApp(appId, userId); if(null != object) { throw new DemeterException("APP HAS ALREADY BEEN SUBSCRIBED"); } Connection conn = null; PreparedStatement stmt = null; try { conn = DbConnectionManager.getConnection(); stmt = conn.prepareStatement(SQL_INSERT_APP_SUBSCRIPTION); int idx = 0; stmt.setString(++idx, appId); stmt.setString(++idx, userId); stmt.setLong(++idx, System.currentTimeMillis()); stmt.executeUpdate(); } finally { DbConnectionManager.closeConnection(stmt, conn); } } public void unsubscribeApp(String appId, String userId) throws DemeterException, Throwable { AppSubscription object = this.getSubscribedApp(appId, userId); if(null == object) { throw new DemeterException("APP HAS NOT BEEN SUBSCRIBED"); } Connection conn = null; PreparedStatement stmt = null; try { conn = DbConnectionManager.getConnection(); stmt = conn.prepareStatement(SQL_DELETE_APP_SUBSCRIPTION); int idx = 0; stmt.setString(++idx, appId); stmt.setString(++idx, userId); stmt.executeUpdate(); } finally { DbConnectionManager.closeConnection(stmt, conn); } } private String generateVersionId( String applicationId, String modelName, Long creationTime) { byte[] applicationIdData = applicationId.getBytes(StandardCharsets.UTF_8); byte[] modelNameData = modelName.getBytes(StandardCharsets.UTF_8); int length = applicationIdData.length + modelNameData.length + Long.BYTES; ByteBuffer buffer = ByteBuffer.allocate(length); buffer.put(applicationIdData); buffer.put(modelNameData); buffer.putLong(creationTime); return Algorithm.md5(buffer.array()); } public static void exportAppsToCloud() throws DemeterException, Throwable { Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; List<CloudObj> file_objs = new ArrayList<CloudObj>(); class update_item{ String id; String path; update_item(String _id, String _path){ id = _id; path = _path; } }; List<update_item> update_app_versions = new ArrayList<update_item>(); try { conn = DbConnectionManager.getConnection(); stmt = conn.prepareStatement(SQL_QUERY_ALL_APP_VERSIONS); rs = stmt.executeQuery(); while(rs.next()){ AppVersion object = AppVersion.from(rs); try{ appendFileObjs(object.getIPKFilePath(), file_objs); } catch(Throwable ignored){} String new_path = getRelativePath(object); if(new_path.equals(object.getIPKFilePath()) == false ){ update_app_versions.add(new update_item(object.getId(), new_path)); } } for(update_item version : update_app_versions){ stmt = conn.prepareStatement(SQL_UPDATE_APP_VERSION_PATH); stmt.setString(1, version.path); stmt.setString(2, version.id); stmt.executeUpdate(); } } catch(SQLException e){ throw (new DemeterException("SQL exception: " + e.getMessage())).SettHttpStatus(Status.INTERNAL_SERVER_ERROR); } finally { DbConnectionManager.closeConnection(rs, stmt, conn); } if(file_objs.size() > 0){ SaveFilesToCloud(file_objs, true); } } private static void appendFileObjs( String ipk_file_path, List<CloudObj> objs) throws Throwable { String root_path = ""; String file_path = ""; root_path = SystemProperties.getInstance().getStorage().getRootPath(); if(root_path.endsWith(File.separator) == false){ root_path = root_path.concat(File.separator); } if(ipk_file_path.startsWith(File.separator) == false){ file_path = root_path + ipk_file_path; } else { file_path = ipk_file_path; if(file_path.startsWith(root_path) == false){ // system setting for root path do not match root path in DB entry File path = new File(file_path); root_path = path.getParentFile().getParentFile().getParentFile().toString(); if(root_path.endsWith(File.separator) == false){ root_path = root_path.concat(File.separator); } } } //find parent (app version) folder File ipkFile = new File(file_path); //collect all file names in folder List<String> all_files = null; try (Stream<Path> walk = Files.walk(ipkFile.getParentFile().toPath())) { all_files = walk.filter(Files::isRegularFile) .filter(file -> !Files.isDirectory(file)) .map(x -> x.toString()) .collect(Collectors.toList()); } catch (IOException ignored) {} String version_path = ipkFile.getParentFile().toString(); if(version_path.endsWith(File.separator) == false){ version_path = version_path.concat(File.separator); } // add object for each found file if(all_files != null){ for(String file : all_files){ objs.add(new CloudObj(file, file.substring(root_path.length()))); } } } private static String getRelativePath( AppVersion version){ String app_str = version.getAppId(); String cur_path = version.getIPKFilePath(); if(cur_path.startsWith(File.separator) == false && cur_path.startsWith(app_str) == true){ return cur_path; } return cur_path.substring(cur_path.indexOf(app_str)); } }
72,771
0.51838
0.517349
2,157
32.737133
26.212408
137
false
false
0
0
0
0
0
0
0.536857
false
false
4
fd49f62a810053d0d0b26d6a4ed81a7af8570efd
32,993,938,782,812
7b7c96cffa5e8b5efc870a966bca852b1c5b4fc2
/demo-spring-boot02/src/main/java/com/demo/spring/boot02/MegaCorpService.java
c8adfb9f215ebd79a676c9c2bf25fa94f11cb8a0
[]
no_license
littlell/demo-spring-boot
https://github.com/littlell/demo-spring-boot
fd9c06be89f7cc5a7cb84c0c8e049708465f3603
14449eef5965978fed833dd28c2a9bd263661307
refs/heads/master
2023-08-08T19:43:30.382000
2023-08-02T14:41:39
2023-08-02T14:41:39
245,936,205
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.demo.spring.boot02; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; @Service public class MegaCorpService { @Autowired private MegaCorpRepository megaCorpRepository; @PostConstruct public void init() { megaCorpRepository.save(new MegaCorp("1", "John", "Smith", 25, "I love to go rock climbing", new ArrayList<>() {{ add("sports"); add("music"); }})); megaCorpRepository.save(new MegaCorp("2", "Jane", "Smith", 32, "I like to collect rock albums", new ArrayList<>() {{ add("music"); }})); megaCorpRepository.save(new MegaCorp("3", "Douglas", "Fir", 35, "I like to build cabinets", new ArrayList<>() {{ add("forestry"); }})); } @PreDestroy public void destroy() { megaCorpRepository.deleteAll(); } }
UTF-8
Java
950
java
MegaCorpService.java
Java
[ { "context": " {\n megaCorpRepository.save(new MegaCorp(\"1\", \"John\", \"Smith\", 25, \"I love to go rock climbing\", new ", "end": 444, "score": 0.9998687505722046, "start": 440, "tag": "NAME", "value": "John" }, { "context": "egaCorpRepository.save(new MegaCorp(\"1\", \"John\", \"Smith\", 25, \"I love to go rock climbing\", new ArrayList", "end": 453, "score": 0.9996027946472168, "start": 448, "tag": "NAME", "value": "Smith" }, { "context": ");\n megaCorpRepository.save(new MegaCorp(\"2\", \"Jane\", \"Smith\", 32, \"I like to collect rock albums\", n", "end": 613, "score": 0.9995740652084351, "start": 609, "tag": "NAME", "value": "Jane" }, { "context": "egaCorpRepository.save(new MegaCorp(\"2\", \"Jane\", \"Smith\", 32, \"I like to collect rock albums\", new ArrayL", "end": 622, "score": 0.9996005296707153, "start": 617, "tag": "NAME", "value": "Smith" }, { "context": ");\n megaCorpRepository.save(new MegaCorp(\"3\", \"Douglas\", \"Fir\", 35, \"I like to build cabinets\", new Arra", "end": 767, "score": 0.9995927214622498, "start": 760, "tag": "NAME", "value": "Douglas" }, { "context": "CorpRepository.save(new MegaCorp(\"3\", \"Douglas\", \"Fir\", 35, \"I like to build cabinets\", new ArrayList<>", "end": 774, "score": 0.9996100664138794, "start": 771, "tag": "NAME", "value": "Fir" } ]
null
[]
package com.demo.spring.boot02; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; @Service public class MegaCorpService { @Autowired private MegaCorpRepository megaCorpRepository; @PostConstruct public void init() { megaCorpRepository.save(new MegaCorp("1", "John", "Smith", 25, "I love to go rock climbing", new ArrayList<>() {{ add("sports"); add("music"); }})); megaCorpRepository.save(new MegaCorp("2", "Jane", "Smith", 32, "I like to collect rock albums", new ArrayList<>() {{ add("music"); }})); megaCorpRepository.save(new MegaCorp("3", "Douglas", "Fir", 35, "I like to build cabinets", new ArrayList<>() {{ add("forestry"); }})); } @PreDestroy public void destroy() { megaCorpRepository.deleteAll(); } }
950
0.683158
0.671579
35
26.142857
32.063457
120
false
false
0
0
0
0
0
0
0.857143
false
false
4
c08d117f0d886c08e3b941f7f86ec1e891f61a3a
2,035,814,547,709
ada58b08512f0390c1bf1a31f63defcac442d58b
/kj-repo-infra/src/main/java/com/kj/repo/infra/batch/QueueBatchBuffer.java
4189179580d9c843d8915949ce75843529e6240f
[]
no_license
Kuojian21/kj-repo
https://github.com/Kuojian21/kj-repo
a508e83325f6cab9a2acba550d07f4515f9d2ca9
5ae4ff95fd843d69317e471ac20345fdbe109cbe
refs/heads/master
2022-12-21T11:50:21.906000
2021-10-04T23:24:50
2021-10-04T23:24:50
149,978,220
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.kj.repo.infra.batch; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.function.Function; import java.util.stream.Collectors; import com.google.common.collect.Lists; /** * @author kj */ public class QueueBatchBuffer<E, T> implements BatchBuffer<E, T> { private final BlockingQueue<E> queue; private final Function<E, T> mapper; public QueueBatchBuffer(int capacity, Function<E, T> mapper) { this.queue = new LinkedBlockingQueue<>(capacity); this.mapper = mapper; } @Override public void add(E element) throws InterruptedException { queue.put(element); } @Override public List<T> drainTo(int batchsize) { List<E> data = Lists.newArrayList(); queue.drainTo(data, batchsize); return data.stream().map(mapper).collect(Collectors.toList()); } @Override public int size() { return 0; } }
UTF-8
Java
994
java
QueueBatchBuffer.java
Java
[ { "context": "t com.google.common.collect.Lists;\n\n/**\n * @author kj\n */\npublic class QueueBatchBuffer<E, T> implement", "end": 280, "score": 0.9995443820953369, "start": 278, "tag": "USERNAME", "value": "kj" } ]
null
[]
package com.kj.repo.infra.batch; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.function.Function; import java.util.stream.Collectors; import com.google.common.collect.Lists; /** * @author kj */ public class QueueBatchBuffer<E, T> implements BatchBuffer<E, T> { private final BlockingQueue<E> queue; private final Function<E, T> mapper; public QueueBatchBuffer(int capacity, Function<E, T> mapper) { this.queue = new LinkedBlockingQueue<>(capacity); this.mapper = mapper; } @Override public void add(E element) throws InterruptedException { queue.put(element); } @Override public List<T> drainTo(int batchsize) { List<E> data = Lists.newArrayList(); queue.drainTo(data, batchsize); return data.stream().map(mapper).collect(Collectors.toList()); } @Override public int size() { return 0; } }
994
0.679074
0.678068
40
23.85
21.808886
70
false
false
0
0
0
0
0
0
0.55
false
false
4
fbcb8c19c8653577f08b2ede8756a864c03c461e
15,728,170,294,991
fba08811e60ae736e25af859f22e475d86e6a3d0
/src/main/java/com/springboot2/learning/javabasic/cath/cathdemo.java
6ba642d500648846c8a4f2315c5084fbcd4671e2
[]
no_license
wangtongzhou520/learning
https://github.com/wangtongzhou520/learning
e8cbceadc4972aaa6ce6ee038063bdb202a15fdf
6579f09b9fe4f1d465fd2ef56113deda1c489f4e
refs/heads/master
2020-06-09T21:03:25.991000
2019-11-20T00:03:37
2019-11-20T00:03:37
193,505,612
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.springboot2.learning.javabasic.cath; /** * 异常 * * 异常分类 * 1.错误 * 常见的错误 * 内存溢出、线程终止 * 2.异常 * 异常分两类 * 受检查的异常(CheckedException) 发生在编译器 * * 不受检查的异常(UnCheckedException) 发生在运行区,主要因为逻辑引起的 * */ public class cathdemo { }
UTF-8
Java
365
java
cathdemo.java
Java
[]
null
[]
package com.springboot2.learning.javabasic.cath; /** * 异常 * * 异常分类 * 1.错误 * 常见的错误 * 内存溢出、线程终止 * 2.异常 * 异常分两类 * 受检查的异常(CheckedException) 发生在编译器 * * 不受检查的异常(UnCheckedException) 发生在运行区,主要因为逻辑引起的 * */ public class cathdemo { }
365
0.670886
0.658228
18
12.166667
14.92295
48
false
false
0
0
0
0
0
0
0.055556
false
false
4
cb3adde75754725a833b1af07d6caa65084614e3
549,755,847,534
6a18d8cb11065aa65131eeded409ad29960bb998
/03-lukema/learn/Quartz/src/main/java/com/learn/job/MyOtherJob.java
fc9139f34f6dbd830144e5b97a3b924574ecaf2c
[]
no_license
xlukema/RemoteLukeMaWorkGit
https://github.com/xlukema/RemoteLukeMaWorkGit
810b42263c768232b42cff51bb881ab8a53054c4
b8fc97e0eddc113c2d5293a78edc6600e6eef057
refs/heads/master
2017-05-04T04:04:37.487000
2017-05-03T01:32:43
2017-05-03T01:32:43
32,882,681
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.learn.job; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; public class MyOtherJob implements Job { private static final Logger LOG = LogManager.getLogger(); @Override public void execute(JobExecutionContext context) throws JobExecutionException { LOG.info("Hello MyOtherJob! --------"); } }
UTF-8
Java
510
java
MyOtherJob.java
Java
[]
null
[]
package com.learn.job; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; public class MyOtherJob implements Job { private static final Logger LOG = LogManager.getLogger(); @Override public void execute(JobExecutionContext context) throws JobExecutionException { LOG.info("Hello MyOtherJob! --------"); } }
510
0.698039
0.694118
23
20.173914
20.025314
61
false
false
0
0
0
0
0
0
0.347826
false
false
4
3b365d68416ad762ba44214d98dac208a5ed4ebb
28,638,841,973,727
95f0c767a566542d78c19765f23f6bbfe23bb2be
/81.search-in-rotated-sorted-array-ii.java
55c15a7549ddeab5a86f5784ba23603e8e9704af
[ "MIT" ]
permissive
GuozhiTang/LeetCode
https://github.com/GuozhiTang/LeetCode
7603e4881bf8f323eb1650b107d997daf5aa61a6
5575a2f22a8be8ea26a7905222e9960c8bc952b2
refs/heads/main
2022-04-28T12:23:12.502000
2022-04-05T00:16:25
2022-04-05T00:16:25
165,311,827
0
0
Apache-2.0
false
2019-07-27T21:31:14
2019-01-11T21:23:40
2019-07-27T21:04:06
2019-07-27T21:31:14
412
0
0
0
Java
false
false
/* * @lc app=leetcode id=81 lang=java * * [81] Search in Rotated Sorted Array II * * https://leetcode.com/problems/search-in-rotated-sorted-array-ii/description/ * * algorithms * Medium (33.02%) * Likes: 1519 * Dislikes: 493 * Total Accepted: 255.6K * Total Submissions: 773.9K * Testcase Example: '[2,5,6,0,0,1,2]\n0' * * Suppose an array sorted in ascending order is rotated at some pivot unknown * to you beforehand. * * (i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]). * * You are given a target value to search. If found in the array return true, * otherwise return false. * * Example 1: * * * Input: nums = [2,5,6,0,0,1,2], target = 0 * Output: true * * * Example 2: * * * Input: nums = [2,5,6,0,0,1,2], target = 3 * Output: false * * Follow up: * * * This is a follow up problem to Search in Rotated Sorted Array, where nums * may contain duplicates. * Would this affect the run-time complexity? How and why? * * */ // @lc code=start class Solution { // Time: O(logn) // Space: O(1) // Binary Search (find the ascending part) public boolean search(int[] nums, int target) { // Corner Cases if (nums == null || nums.length == 0) { return false; } int start = 0, end = nums.length - 1; while (start + 1 < end) { int mid = start + (end - start) / 2; if (nums[mid] == target) { return true; } else if (nums[start] < nums[mid]) { // left part is ascending if (target >= nums[start] && target <= nums[mid]) { end = mid; } else { start = mid; } } else if (nums[start] > nums[mid]) { // check the right part if (nums[mid] <= target && target <= nums[end]) { start = mid; } else { end = mid; } } else { // if nums[start] == nums[mid]/nums[end] start++; } } if (nums[start] == target || nums[end] == target) { return true; } else { return false; } } /***********************************/ // // Time: O(logn) // // Space: O(1) // // Binary Search // public boolean search(int[] nums, int target) { // // Corner cases // if (nums == null || nums.length == 0) { // return false; // } // int start = 0, end = nums.length - 1; // while (start + 1 < end) { // int mid = start + (end - start) / 2; // if (nums[mid] == target) { // return true; // } else if (nums[start] < nums[mid]) { // // the left part // if (target >= nums[start] && target <= nums[mid]) { // end = mid; // } else { // start = mid; // } // } else if (nums[start] > nums[mid]) { // two judge the nums[mid] and nums[start] // // the right part // if (target >= nums[mid] && target <= nums[end]) { // start = mid; // } else { // end = mid; // } // } else { // // if nums[start] == nums[end] // start++; // } // } // // Judge the adjacent ones // if (nums[start] == target || nums[end] == target) { // return true; // } // return false; // } } // @lc code=end
UTF-8
Java
3,665
java
81.search-in-rotated-sorted-array-ii.java
Java
[]
null
[]
/* * @lc app=leetcode id=81 lang=java * * [81] Search in Rotated Sorted Array II * * https://leetcode.com/problems/search-in-rotated-sorted-array-ii/description/ * * algorithms * Medium (33.02%) * Likes: 1519 * Dislikes: 493 * Total Accepted: 255.6K * Total Submissions: 773.9K * Testcase Example: '[2,5,6,0,0,1,2]\n0' * * Suppose an array sorted in ascending order is rotated at some pivot unknown * to you beforehand. * * (i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]). * * You are given a target value to search. If found in the array return true, * otherwise return false. * * Example 1: * * * Input: nums = [2,5,6,0,0,1,2], target = 0 * Output: true * * * Example 2: * * * Input: nums = [2,5,6,0,0,1,2], target = 3 * Output: false * * Follow up: * * * This is a follow up problem to Search in Rotated Sorted Array, where nums * may contain duplicates. * Would this affect the run-time complexity? How and why? * * */ // @lc code=start class Solution { // Time: O(logn) // Space: O(1) // Binary Search (find the ascending part) public boolean search(int[] nums, int target) { // Corner Cases if (nums == null || nums.length == 0) { return false; } int start = 0, end = nums.length - 1; while (start + 1 < end) { int mid = start + (end - start) / 2; if (nums[mid] == target) { return true; } else if (nums[start] < nums[mid]) { // left part is ascending if (target >= nums[start] && target <= nums[mid]) { end = mid; } else { start = mid; } } else if (nums[start] > nums[mid]) { // check the right part if (nums[mid] <= target && target <= nums[end]) { start = mid; } else { end = mid; } } else { // if nums[start] == nums[mid]/nums[end] start++; } } if (nums[start] == target || nums[end] == target) { return true; } else { return false; } } /***********************************/ // // Time: O(logn) // // Space: O(1) // // Binary Search // public boolean search(int[] nums, int target) { // // Corner cases // if (nums == null || nums.length == 0) { // return false; // } // int start = 0, end = nums.length - 1; // while (start + 1 < end) { // int mid = start + (end - start) / 2; // if (nums[mid] == target) { // return true; // } else if (nums[start] < nums[mid]) { // // the left part // if (target >= nums[start] && target <= nums[mid]) { // end = mid; // } else { // start = mid; // } // } else if (nums[start] > nums[mid]) { // two judge the nums[mid] and nums[start] // // the right part // if (target >= nums[mid] && target <= nums[end]) { // start = mid; // } else { // end = mid; // } // } else { // // if nums[start] == nums[end] // start++; // } // } // // Judge the adjacent ones // if (nums[start] == target || nums[end] == target) { // return true; // } // return false; // } } // @lc code=end
3,665
0.436408
0.415939
132
26.75
21.812346
95
false
false
0
0
0
0
0
0
0.522727
false
false
4
5503d5af5020106c47c78a8000147737c0f6bed6
10,763,188,087,921
5f74233ade68c110fddc074f5d64cf18ff287d45
/easyrec-core/src/main/java/org/easyrec/store/dao/BaseProfileDAO.java
c7c33376c2bb40e289be01746ab3f3d7b1c8528f
[ "Apache-2.0" ]
permissive
feesa/easyrec-parent
https://github.com/feesa/easyrec-parent
0f0c187884eb773b40794d7d0ac107c5c410e552
a3c6d8911c88abdb4df6662f2d4e0220eda4a16c
refs/heads/master
2022-12-27T12:37:00.204000
2016-12-26T10:47:55
2016-12-26T10:47:55
75,718,347
1
1
Apache-2.0
false
2022-12-15T23:43:53
2016-12-06T09:57:51
2017-05-23T15:56:07
2022-12-15T23:43:50
3,283
0
1
18
Java
false
false
/**Copyright 2010 Research Studios Austria Forschungsgesellschaft mBH * * This file is part of easyrec. * * easyrec is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * easyrec is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with easyrec. If not, see <http://www.gnu.org/licenses/>. */ package org.easyrec.store.dao; import org.easyrec.model.core.ItemVO; import org.easyrec.utils.spring.store.dao.TableCreatingDAO; import java.util.List; import java.util.Set; /** * This interface provides methods to store data into and read <code>Profile</code> entries from an easyrec database. * <p/> * <p><b>Company:&nbsp;</b> * SAT, Research Studios Austria</p> * <p/> * <p><b>Copyright:&nbsp;</b> * (c) 2007</p> * <p/> * <p><b>last modified:</b><br/> * $Author: fsalcher $<br/> * $Date: 2012-03-23 15:35:07 +0100 (Fr, 23 Mär 2012) $<br/> * $Revision: 18791 $</p> * * @author Stephan Zavrel */ public interface BaseProfileDAO<T, I, IT> extends TableCreatingDAO { /////////////////////////////////////////////////////////////////////////// // constants public final static String DEFAULT_TABLE_NAME = "item"; public final static String DEFAULT_TENANT_ID_COLUMN_NAME = "tenantId"; public final static String DEFAULT_ITEM_ID_COLUMN_NAME = "itemid"; public final static String DEFAULT_ITEM_TYPE_ID_COLUMN_NAME = "itemtype"; public final static String DEFAULT_PROFILE_DATA_COLUMN_NAME = "profileData"; public final static String DEFAULT_ACTIVE_COLUMN_NAME = "active"; // non abstract public int storeProfile(T tenant, I item, IT itemType, String profileXML); public String getProfile(T tenant, I item, IT itemType); public String getProfile(T tenantId, I itemId, IT itemTypeId, Boolean active); public Set<String> getMultiDimensionValue(T tenantId, I itemId, IT itemTypeId, String dimensionXPath); public String getSimpleDimensionValue(T tenantId, I itemId, IT itemTypeId, String dimensionXPath); /** * This method replaces some parts of the <code>Profile XML</code> * defined by a XPath with another string. * * @param tenantId the tenantId of the item with the profile * @param itemId the itemId of the item with the profile * @param itemTypeId the itemTypeId of the item with the profile * @param updateXPath an XPath which points to the part of the * <code>Profile</code> which will be replaced * @param newXML the string which will be placed at the given * XPath location * @return <code>true</code> if the operation succeeds and * <code>false</code> otherwise */ public boolean updateXML(T tenantId, I itemId, IT itemTypeId, String updateXPath, String newXML); public boolean deleteProfile(T tenantId, I itemId, IT itemTypeId); public List<ItemVO<Integer, Integer>> getItemsByDimensionValue(T tenantId, IT itemType, String dimensionXPath, String value); public List<ItemVO<Integer, Integer>> getItemsByItemType(T Tenant, IT itemType, int count); public void activateProfile(T tenant, I item, IT itemType); public void deactivateProfile(T tenant, I item, IT itemType); }
UTF-8
Java
3,757
java
BaseProfileDAO.java
Java
[ { "context": " <p/>\n * <p><b>last modified:</b><br/>\n * $Author: fsalcher $<br/>\n * $Date: 2012-03-23 15:35:07 +0100 (Fr, 2", "end": 1231, "score": 0.999626636505127, "start": 1223, "tag": "USERNAME", "value": "fsalcher" }, { "context": "12) $<br/>\n * $Revision: 18791 $</p>\n *\n * @author Stephan Zavrel\n */\npublic interface BaseProfileDAO<T, I, IT> ext", "end": 1354, "score": 0.9997929334640503, "start": 1340, "tag": "NAME", "value": "Stephan Zavrel" } ]
null
[]
/**Copyright 2010 Research Studios Austria Forschungsgesellschaft mBH * * This file is part of easyrec. * * easyrec is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * easyrec is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with easyrec. If not, see <http://www.gnu.org/licenses/>. */ package org.easyrec.store.dao; import org.easyrec.model.core.ItemVO; import org.easyrec.utils.spring.store.dao.TableCreatingDAO; import java.util.List; import java.util.Set; /** * This interface provides methods to store data into and read <code>Profile</code> entries from an easyrec database. * <p/> * <p><b>Company:&nbsp;</b> * SAT, Research Studios Austria</p> * <p/> * <p><b>Copyright:&nbsp;</b> * (c) 2007</p> * <p/> * <p><b>last modified:</b><br/> * $Author: fsalcher $<br/> * $Date: 2012-03-23 15:35:07 +0100 (Fr, 23 Mär 2012) $<br/> * $Revision: 18791 $</p> * * @author <NAME> */ public interface BaseProfileDAO<T, I, IT> extends TableCreatingDAO { /////////////////////////////////////////////////////////////////////////// // constants public final static String DEFAULT_TABLE_NAME = "item"; public final static String DEFAULT_TENANT_ID_COLUMN_NAME = "tenantId"; public final static String DEFAULT_ITEM_ID_COLUMN_NAME = "itemid"; public final static String DEFAULT_ITEM_TYPE_ID_COLUMN_NAME = "itemtype"; public final static String DEFAULT_PROFILE_DATA_COLUMN_NAME = "profileData"; public final static String DEFAULT_ACTIVE_COLUMN_NAME = "active"; // non abstract public int storeProfile(T tenant, I item, IT itemType, String profileXML); public String getProfile(T tenant, I item, IT itemType); public String getProfile(T tenantId, I itemId, IT itemTypeId, Boolean active); public Set<String> getMultiDimensionValue(T tenantId, I itemId, IT itemTypeId, String dimensionXPath); public String getSimpleDimensionValue(T tenantId, I itemId, IT itemTypeId, String dimensionXPath); /** * This method replaces some parts of the <code>Profile XML</code> * defined by a XPath with another string. * * @param tenantId the tenantId of the item with the profile * @param itemId the itemId of the item with the profile * @param itemTypeId the itemTypeId of the item with the profile * @param updateXPath an XPath which points to the part of the * <code>Profile</code> which will be replaced * @param newXML the string which will be placed at the given * XPath location * @return <code>true</code> if the operation succeeds and * <code>false</code> otherwise */ public boolean updateXML(T tenantId, I itemId, IT itemTypeId, String updateXPath, String newXML); public boolean deleteProfile(T tenantId, I itemId, IT itemTypeId); public List<ItemVO<Integer, Integer>> getItemsByDimensionValue(T tenantId, IT itemType, String dimensionXPath, String value); public List<ItemVO<Integer, Integer>> getItemsByItemType(T Tenant, IT itemType, int count); public void activateProfile(T tenant, I item, IT itemType); public void deactivateProfile(T tenant, I item, IT itemType); }
3,749
0.67279
0.662673
94
38.957447
33.286926
117
false
false
0
0
0
0
76
0.020234
0.680851
false
false
4
d243c80f39d95289f3662339dd51b8bb50526da2
15,152,644,667,467
1fcc577f1e6f8bed30e45c02aeedcd4975ab4ecd
/src/org/launchcode/studio7/BaseDisc.java
f8a890a131806f6b58412775ba7b5c8aaa831cee
[]
no_license
RenataSentsova/java-web-dev-studio7
https://github.com/RenataSentsova/java-web-dev-studio7
745bd6c12dccbd6ec1a8e39c8f6d828a22344783
de724f7c9955e5b7de59f09bc8a0332892c7e25b
refs/heads/master
2022-11-19T22:32:22.946000
2020-07-21T21:02:43
2020-07-21T21:02:43
281,307,105
0
0
null
true
2020-07-21T05:47:57
2020-07-21T05:47:56
2019-11-08T20:58:43
2019-11-08T22:13:52
10
0
0
0
null
false
false
package org.launchcode.studio7; public abstract class BaseDisc{ private String labelName; public BaseDisc (String name) { this.labelName = name; } public String getLabelName() { return labelName; } public void setLabelName(String name) { this.labelName = name; } public abstract void getInfo(); }
UTF-8
Java
359
java
BaseDisc.java
Java
[]
null
[]
package org.launchcode.studio7; public abstract class BaseDisc{ private String labelName; public BaseDisc (String name) { this.labelName = name; } public String getLabelName() { return labelName; } public void setLabelName(String name) { this.labelName = name; } public abstract void getInfo(); }
359
0.640669
0.637883
20
16.950001
15.76856
43
false
false
0
0
0
0
0
0
0.3
false
false
4
d47ed4da13bd6ccf183b14b3c940075b5dfbdda3
9,122,510,571,093
4a221fd4cb63a3518f3b83ed60cfa811782b4d22
/src/main/java/com/zbq/leetcode/LeetCode_4.java
8a0aace98a5cc1f592bdd0d4d81b6e69349fb722
[]
no_license
zhangboqing/algorithm-java-old
https://github.com/zhangboqing/algorithm-java-old
77a6afa0cd1f291f5b16e4d07b7ac762e3130a5b
eb55d000969cf1f7c8893edde0c147c16806aaf6
refs/heads/master
2022-12-27T14:12:03.228000
2019-06-22T10:00:09
2019-06-22T10:00:09
115,963,324
0
0
null
false
2020-10-13T04:15:32
2018-01-02T01:53:44
2019-12-02T03:34:50
2020-10-13T04:15:30
98
0
1
1
Java
false
false
package com.zbq.leetcode; /** * @author zhangboqing * @date 2019/2/20 */ public class LeetCode_4 { public static double findMedianSortedArrays(int[] nums1, int[] nums2) { if (nums1 == null || nums2 == null) { return -1; } int length1 = nums1.length; int length2 = nums2.length; //区分奇数、偶数 int length = length1 + length2; //是否是奇数 boolean isOddNumber = length % 2 == 1 ? true : false; int middleIndex = length / 2; int temp11 = -1; int temp12 = -1; int temp21 = -1; int temp22 = -1; int m1 = 0; int m2 = 0; for (int i = 0; i <= middleIndex;i ++) { if ((m1 < length1) && ( ( m2 >= length2) || (nums1[m1] <= nums2[m2]))) { if (i == (middleIndex -1) && !isOddNumber){ if (temp11 == -1) { temp11 = m1; } else { temp12 = m1; } } if (i == middleIndex) { if (temp11 == -1) { temp11 = m1; } else { temp12 = m1; } } m1++; } else { if (i == (middleIndex -1) && !isOddNumber){ if (temp21 == -1) { temp21 = m2; } else { temp22 = m2; } } if (i == middleIndex) { if (temp21 == -1) { temp21 = m2; } else { temp22 = m2; } } m2++; } } double result = 0; if (temp11 != -1) { result += nums1[temp11]; } if (temp12 != -1) { result += nums1[temp12]; } if (temp21 != -1) { result += nums2[temp21]; } if (temp22 != -1) { result += nums2[temp22]; } if (!isOddNumber) { result = result / 2; } return result; } public static void main(String[] args) { int[] nums1 = {1,2}; int[] nums2 = {3,4}; double medianSortedArrays = findMedianSortedArrays(nums1, nums2); System.out.println(medianSortedArrays); } }
UTF-8
Java
2,539
java
LeetCode_4.java
Java
[ { "context": "package com.zbq.leetcode;\n\n/**\n * @author zhangboqing\n * @date 2019/2/20\n */\npublic class LeetCode_4 {\n", "end": 53, "score": 0.9952888488769531, "start": 42, "tag": "NAME", "value": "zhangboqing" } ]
null
[]
package com.zbq.leetcode; /** * @author zhangboqing * @date 2019/2/20 */ public class LeetCode_4 { public static double findMedianSortedArrays(int[] nums1, int[] nums2) { if (nums1 == null || nums2 == null) { return -1; } int length1 = nums1.length; int length2 = nums2.length; //区分奇数、偶数 int length = length1 + length2; //是否是奇数 boolean isOddNumber = length % 2 == 1 ? true : false; int middleIndex = length / 2; int temp11 = -1; int temp12 = -1; int temp21 = -1; int temp22 = -1; int m1 = 0; int m2 = 0; for (int i = 0; i <= middleIndex;i ++) { if ((m1 < length1) && ( ( m2 >= length2) || (nums1[m1] <= nums2[m2]))) { if (i == (middleIndex -1) && !isOddNumber){ if (temp11 == -1) { temp11 = m1; } else { temp12 = m1; } } if (i == middleIndex) { if (temp11 == -1) { temp11 = m1; } else { temp12 = m1; } } m1++; } else { if (i == (middleIndex -1) && !isOddNumber){ if (temp21 == -1) { temp21 = m2; } else { temp22 = m2; } } if (i == middleIndex) { if (temp21 == -1) { temp21 = m2; } else { temp22 = m2; } } m2++; } } double result = 0; if (temp11 != -1) { result += nums1[temp11]; } if (temp12 != -1) { result += nums1[temp12]; } if (temp21 != -1) { result += nums2[temp21]; } if (temp22 != -1) { result += nums2[temp22]; } if (!isOddNumber) { result = result / 2; } return result; } public static void main(String[] args) { int[] nums1 = {1,2}; int[] nums2 = {3,4}; double medianSortedArrays = findMedianSortedArrays(nums1, nums2); System.out.println(medianSortedArrays); } }
2,539
0.353877
0.305765
102
23.656862
17.075665
75
false
false
0
0
0
0
0
0
0.431373
false
false
4
2746b542e8f3807637ab1b333f8b1a5960e61828
9,122,510,567,849
58bfdac9ac7d397ca37907173e567861202d2f67
/trunk/src/bigdata/bdzk/src/main/java/com/dt/frame/zookeeper/lock/ver2/IDistributedLockTask.java
9836dab49672a449d177cc3e696708e81f616acd
[]
no_license
datatiger/project
https://github.com/datatiger/project
690734aacca36221d56c94d8c56c446b58e02393
3faccbf8ddc3f076b8b41b586eb2c87cf8a6eec5
refs/heads/master
2020-03-30T18:15:26.286000
2019-01-01T21:55:24
2019-01-01T21:55:24
151,491,094
2
0
null
false
2019-11-13T08:13:05
2018-10-03T22:57:10
2019-03-07T12:02:32
2019-11-13T08:13:04
226,847
0
0
6
Java
false
false
package com.dt.frame.zookeeper.lock.ver2; public interface IDistributedLockTask { void run(); }
UTF-8
Java
98
java
IDistributedLockTask.java
Java
[]
null
[]
package com.dt.frame.zookeeper.lock.ver2; public interface IDistributedLockTask { void run(); }
98
0.77551
0.765306
5
18.6
17.984438
41
false
false
0
0
0
0
0
0
0.6
false
false
4
825b7ccd7c3a904460a64784ae6d7bf7efa3dee5
25,151,328,486,995
fc82d92ce574bfc5f603f5db7227feaa23983d2b
/src/main/java/com/examen/java/adea/app/models/entity/Usuario.java
1fa74d7389d64847d8c67124baae068f656e929f
[]
no_license
polokiju/ExamenAdeABack
https://github.com/polokiju/ExamenAdeABack
4bb8754099894c42bea840df6b4f844072ee7205
67bc5739231d94242dd108afa4a3d89d326118dd
refs/heads/main
2023-05-26T02:38:17.296000
2021-06-06T19:09:08
2021-06-06T19:09:08
374,440,709
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.examen.java.adea.app.models.entity; import java.math.BigDecimal; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.PrePersist; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; @Entity @Table(name="usuario") public class Usuario { @Id @Column(nullable = false,columnDefinition = "varchar(20)") private String login; @Column(nullable = false,columnDefinition = "varchar(30)") private String password; @Column(nullable = false,columnDefinition = "varchar(50)") private String nombre; @Column(nullable = false, columnDefinition = "decimal") private BigDecimal cliente; @Column(nullable = true,columnDefinition = "varchar(50)") private String email; @Column(nullable = false) @Temporal(TemporalType.TIMESTAMP) private Date fechaAlta; @Column(nullable = true) @Temporal(TemporalType.TIMESTAMP) private Date fechaBaja; @Column(nullable = false, columnDefinition = "char(1) default 'A'") private char status; @Column(nullable = false, columnDefinition = "float default 0") private BigDecimal intentos; @Column(nullable = true) @Temporal(TemporalType.TIMESTAMP) private Date fechaRevocado; @Column(nullable = true) @Temporal(TemporalType.TIMESTAMP) private Date fechaVigencia; @Column(nullable = true) private Integer noAcceso; @Column(nullable = true,columnDefinition = "varchar(50)") private String apellidoPaterno; @Column(nullable = true,columnDefinition = "varchar(50)") private String apellidoMaterno; @Column(nullable = true,columnDefinition = "int(4)") private Integer area; @Column(nullable = false) @Temporal(TemporalType.TIMESTAMP) private Date fechaModificacion; @Transient private String accessToken; @PrePersist public void prePersist() { this.fechaAlta = new Date(); this.fechaModificacion = new Date(); } public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public BigDecimal getCliente() { return cliente; } public void setCliente(BigDecimal cliente) { this.cliente = cliente; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Date getFechaAlta() { return fechaAlta; } public void setFechaAlta(Date fechaAlta) { this.fechaAlta = fechaAlta; } public Date getFechaBaja() { return fechaBaja; } public void setFechaBaja(Date fechaBaja) { this.fechaBaja = fechaBaja; } public char getStatus() { return status; } public void setStatus(char status) { this.status = status; } public BigDecimal getIntentos() { return intentos; } public void setIntentos(BigDecimal intentos) { this.intentos = intentos; } public Date getFechaRevocado() { return fechaRevocado; } public void setFechaRevocado(Date fechaRevocado) { this.fechaRevocado = fechaRevocado; } public Date getFechaVigencia() { return fechaVigencia; } public void setFechaVigencia(Date fechaVigencia) { this.fechaVigencia = fechaVigencia; } public Integer getNoAcceso() { return noAcceso; } public void setNoAcceso(Integer noAcceso) { this.noAcceso = noAcceso; } public String getApellidoPaterno() { return apellidoPaterno; } public void setApellidoPaterno(String apellidoPaterno) { this.apellidoPaterno = apellidoPaterno; } public String getApellidoMaterno() { return apellidoMaterno; } public void setApellidoMaterno(String apellidoMaterno) { this.apellidoMaterno = apellidoMaterno; } public Integer getArea() { return area; } public void setArea(Integer area) { this.area = area; } public Date getFechaModificacion() { return fechaModificacion; } public void setFechaModificacion(Date fechaModificacion) { this.fechaModificacion = fechaModificacion; } @Override public boolean equals(Object obj) { if(this == obj) { return true; } if( !(obj instanceof Usuario)) { return false; } Usuario u = (Usuario) obj; return this.login != null && this.login.equals(u.getLogin()); } public String getAccessToken() { return accessToken; } public void setAccessToken(String accessToken) { this.accessToken = accessToken; } }
UTF-8
Java
4,629
java
Usuario.java
Java
[]
null
[]
package com.examen.java.adea.app.models.entity; import java.math.BigDecimal; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.PrePersist; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; @Entity @Table(name="usuario") public class Usuario { @Id @Column(nullable = false,columnDefinition = "varchar(20)") private String login; @Column(nullable = false,columnDefinition = "varchar(30)") private String password; @Column(nullable = false,columnDefinition = "varchar(50)") private String nombre; @Column(nullable = false, columnDefinition = "decimal") private BigDecimal cliente; @Column(nullable = true,columnDefinition = "varchar(50)") private String email; @Column(nullable = false) @Temporal(TemporalType.TIMESTAMP) private Date fechaAlta; @Column(nullable = true) @Temporal(TemporalType.TIMESTAMP) private Date fechaBaja; @Column(nullable = false, columnDefinition = "char(1) default 'A'") private char status; @Column(nullable = false, columnDefinition = "float default 0") private BigDecimal intentos; @Column(nullable = true) @Temporal(TemporalType.TIMESTAMP) private Date fechaRevocado; @Column(nullable = true) @Temporal(TemporalType.TIMESTAMP) private Date fechaVigencia; @Column(nullable = true) private Integer noAcceso; @Column(nullable = true,columnDefinition = "varchar(50)") private String apellidoPaterno; @Column(nullable = true,columnDefinition = "varchar(50)") private String apellidoMaterno; @Column(nullable = true,columnDefinition = "int(4)") private Integer area; @Column(nullable = false) @Temporal(TemporalType.TIMESTAMP) private Date fechaModificacion; @Transient private String accessToken; @PrePersist public void prePersist() { this.fechaAlta = new Date(); this.fechaModificacion = new Date(); } public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public BigDecimal getCliente() { return cliente; } public void setCliente(BigDecimal cliente) { this.cliente = cliente; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Date getFechaAlta() { return fechaAlta; } public void setFechaAlta(Date fechaAlta) { this.fechaAlta = fechaAlta; } public Date getFechaBaja() { return fechaBaja; } public void setFechaBaja(Date fechaBaja) { this.fechaBaja = fechaBaja; } public char getStatus() { return status; } public void setStatus(char status) { this.status = status; } public BigDecimal getIntentos() { return intentos; } public void setIntentos(BigDecimal intentos) { this.intentos = intentos; } public Date getFechaRevocado() { return fechaRevocado; } public void setFechaRevocado(Date fechaRevocado) { this.fechaRevocado = fechaRevocado; } public Date getFechaVigencia() { return fechaVigencia; } public void setFechaVigencia(Date fechaVigencia) { this.fechaVigencia = fechaVigencia; } public Integer getNoAcceso() { return noAcceso; } public void setNoAcceso(Integer noAcceso) { this.noAcceso = noAcceso; } public String getApellidoPaterno() { return apellidoPaterno; } public void setApellidoPaterno(String apellidoPaterno) { this.apellidoPaterno = apellidoPaterno; } public String getApellidoMaterno() { return apellidoMaterno; } public void setApellidoMaterno(String apellidoMaterno) { this.apellidoMaterno = apellidoMaterno; } public Integer getArea() { return area; } public void setArea(Integer area) { this.area = area; } public Date getFechaModificacion() { return fechaModificacion; } public void setFechaModificacion(Date fechaModificacion) { this.fechaModificacion = fechaModificacion; } @Override public boolean equals(Object obj) { if(this == obj) { return true; } if( !(obj instanceof Usuario)) { return false; } Usuario u = (Usuario) obj; return this.login != null && this.login.equals(u.getLogin()); } public String getAccessToken() { return accessToken; } public void setAccessToken(String accessToken) { this.accessToken = accessToken; } }
4,629
0.726075
0.722834
269
16.208178
17.967995
68
false
false
0
0
0
0
0
0
1.137546
false
false
4
babed976aaa873c7353884b2b853b711a56d5a99
21,904,333,265,476
b5bb926b591718ff8eb3275df53c09369b242764
/springboot-dao/src/main/java/com/ncme/springboot/mapper/ModelGuidePropMapper.java
17d8e7ace3fdf4235ba175cece7a6498641c3572
[ "Apache-2.0" ]
permissive
jamescaoBJ/springcloud
https://github.com/jamescaoBJ/springcloud
c4339f2f508f669141ac4418f966a1e59513ded3
a012debbc90b195584bb3da0300cb14f7ed2f8a0
refs/heads/master
2020-03-11T06:16:44.264000
2018-04-17T01:36:48
2018-04-17T01:36:48
129,826,293
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ncme.springboot.mapper; import com.ncme.springboot.model.ModelGuideProp; public interface ModelGuidePropMapper { int insert(ModelGuideProp record); int insertSelective(ModelGuideProp record); }
UTF-8
Java
224
java
ModelGuidePropMapper.java
Java
[]
null
[]
package com.ncme.springboot.mapper; import com.ncme.springboot.model.ModelGuideProp; public interface ModelGuidePropMapper { int insert(ModelGuideProp record); int insertSelective(ModelGuideProp record); }
224
0.776786
0.776786
9
23.111111
20.808355
48
false
false
0
0
0
0
0
0
0.444444
false
false
4
46f490e8195e1fcdf13ee96236706587e7ee005a
5,574,867,569,919
d5e91bfe6a16b4b19d41d8d3f2d507c561eada90
/src/main/java/com/hxm/userservice/UserService.java
bf5a2ef82fdfbaf2f8293cfc2aa3e4876886ecf3
[]
no_license
251006339/spring-boot-dubbo
https://github.com/251006339/spring-boot-dubbo
531f6810a794c91ba532bd8b937d411388caf275
12cfabfcd3ba9ea55d57cb988e977553fab7dfe2
refs/heads/master
2020-08-01T17:39:54.536000
2019-09-26T10:33:29
2019-09-26T10:33:29
211,063,757
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hxm.userservice; import com.alibaba.dubbo.config.annotation.Reference; import com.hxm.service.TicketService; import org.springframework.stereotype.Service; /** * @author XAIOHU * @date 2019/9/26 --16:45 **/ @Service public class UserService{ @Reference TicketService ticketservice; public void test(){ String ticket = ticketservice.getTicket(); System.out.println("调用远程服务+"+ticket); } }
UTF-8
Java
442
java
UserService.java
Java
[ { "context": "ringframework.stereotype.Service;\n\n\n/**\n * @author XAIOHU\n * @date 2019/9/26 --16:45\n **/\n@Service\npublic c", "end": 193, "score": 0.9996683597564697, "start": 187, "tag": "USERNAME", "value": "XAIOHU" } ]
null
[]
package com.hxm.userservice; import com.alibaba.dubbo.config.annotation.Reference; import com.hxm.service.TicketService; import org.springframework.stereotype.Service; /** * @author XAIOHU * @date 2019/9/26 --16:45 **/ @Service public class UserService{ @Reference TicketService ticketservice; public void test(){ String ticket = ticketservice.getTicket(); System.out.println("调用远程服务+"+ticket); } }
442
0.72093
0.695349
27
14.925926
17.454546
53
false
false
0
0
0
0
0
0
0.259259
false
false
4
0669bec0b7dc788cfa5756109e5732fe024397a8
12,240,656,848,485
cfa3f9317eec349f194243a7fed7cc348f51121c
/src/main/java/com/insticator/spring/project/models/user/UserResource.java
c749b0eefa9426e4229cad256d8893e5a7f65963
[]
no_license
Tommmmmmy/insticator_project
https://github.com/Tommmmmmy/insticator_project
6e64d5631c0cf532e6f15ab970dd2f1aa865ee36
39e2f8416e817ce9645bf4b69a165687a707c1b8
refs/heads/master
2018-12-19T12:18:50.031000
2018-09-17T02:50:59
2018-09-17T02:50:59
148,945,886
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.insticator.spring.project.models.user; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.insticator.spring.project.models.questions.QuestionNotFoundException; import com.insticator.spring.project.models.questions.Checkbox.Checkans; import com.insticator.spring.project.models.questions.Checkbox.CheckansId; import com.insticator.spring.project.models.questions.Checkbox.Checkbox; import com.insticator.spring.project.models.questions.Poll.Poll; import com.insticator.spring.project.models.questions.Poll.Pollans; import com.insticator.spring.project.models.questions.Poll.PollansId; import com.insticator.spring.project.models.questions.Trivia.Trivia; import com.insticator.spring.project.models.questions.Trivia.Triviaans; import com.insticator.spring.project.models.questions.Trivia.TriviaansId; import com.insticator.spring.project.models.questions.matrix.Matrix; import com.insticator.spring.project.models.questions.matrix.Matrixans; import com.insticator.spring.project.models.questions.matrix.MatrixansId; import com.insticator.spring.project.repository.CheckansRepository; import com.insticator.spring.project.repository.CheckboxRepository; import com.insticator.spring.project.repository.MatrixRepository; import com.insticator.spring.project.repository.MatrixansRepository; import com.insticator.spring.project.repository.PollRepository; import com.insticator.spring.project.repository.PollansRepository; import com.insticator.spring.project.repository.TriviaRepository; import com.insticator.spring.project.repository.TriviaansRepository; import com.insticator.spring.project.repository.UserRepository; @RestController public class UserResource { @Autowired private UserRepository service; @Autowired private CheckboxRepository checkService; @Autowired private CheckansRepository checkansService; @Autowired private TriviaRepository triviaService; @Autowired private TriviaansRepository triviaansService; @Autowired private PollRepository pollService; @Autowired private PollansRepository pollansService; @Autowired private MatrixRepository matrixService; @Autowired private MatrixansRepository matrixansService; @GetMapping("/users") public List<User> retrieveAllUsers() { return service.findAll(); } @GetMapping("/users/{id}") public User retrieveUser(@PathVariable int id) { Optional<User> user = service.findById(id); if (!user.isPresent()) { throw new UserNotFoundException("id-"+id); } return user.get(); } @GetMapping("/users/{id}/questions") public Map<String, Set<String>> retrieveAllQuestions(@PathVariable int id) { Optional<User> user = service.findById(id); if (!user.isPresent()) { throw new UserNotFoundException("id-"+id); } Map<String, Set<String>> res = new HashMap<>(); Set<Trivia> tQuestions = user.get().gettQuestions(); Set<Poll> pQuestions = user.get().getpQuestions(); Set<Matrix> mQuestions = user.get().getmQuestions(); Set<Checkbox> cQuestions = user.get().getcQuestions(); if(tQuestions.size() > 0) { for(Trivia trivia : tQuestions) { TriviaansId qid = new TriviaansId(id, trivia.getId()); Optional<Triviaans> ans = triviaansService.findById(qid); if(!ans.isPresent()) { res.put("Trivia " + trivia.getId() + " " + trivia.getQuestion(), trivia.getOptions()); } } } if(pQuestions.size() > 0) { for(Poll poll : pQuestions) { PollansId qid = new PollansId(id, poll.getId()); Optional<Pollans> ans = pollansService.findById(qid); if(!ans.isPresent()) { res.put("Poll " + poll.getId() + " " + poll.getQuestion(), poll.getOptions()); } } } if(mQuestions.size() > 0) { for(Matrix matrix : mQuestions) { MatrixansId qid = new MatrixansId(id, matrix.getId()); Optional<Matrixans> ans = matrixansService.findById(qid); if(ans.isPresent()) { continue; } Set<String> list = new HashSet<>(); int count = 0; StringBuilder str = new StringBuilder(); for(String option : matrix.getOptions1()) { str.append(option); if(count != matrix.getOptions1().size() - 1) str.append(","); count++; } list.add(str.toString()); count = 0; str = new StringBuilder(); for(String option : matrix.getOptions2()) { str.append(option); if(count != matrix.getOptions2().size() - 1) str.append(","); count++; } list.add(str.toString()); res.put("matrix " + matrix.getId(), list); } } if(cQuestions.size() > 0) { for(Checkbox checkbox : cQuestions) { CheckansId qid = new CheckansId(id, checkbox.getId()); Optional<Checkans> ans = checkansService.findById(qid); if(!ans.isPresent()) { res.put("Checkbox " + checkbox.getId() + " " + checkbox.getQuestion(), checkbox.getOptions()); } } } return res; } @PostMapping("/users/{uId}/checkboxs/{qId}") public void saveCheckAnswers(@Valid @RequestBody Map<String, String[]> checkans, @PathVariable int uId, @PathVariable int qId) { Optional<User> userOptional = service.findById(uId); if (!userOptional.isPresent()) { throw new UserNotFoundException("id-"+uId); } List<Checkbox> checkboxs = checkService.findByUUserAndId(userOptional.get(), qId); if (checkboxs.size() == 0) { throw new QuestionNotFoundException("UserId: " + uId + "CheckId: " + qId); } Checkbox checkbox = checkboxs.iterator().next(); Set<String> checkSet= new HashSet<>(Arrays.asList(checkans.get("answers"))); CheckansId id = new CheckansId(uId, qId); Checkans answer = new Checkans(id, checkSet, checkbox, userOptional.get()); checkansService.save(answer); } @GetMapping("/users/{uId}/checkboxs/{qId}") public Set<String> saveCheckAnswers(@PathVariable int uId, @PathVariable int qId) { Optional<User> userOptional = service.findById(uId); if (!userOptional.isPresent()) { throw new UserNotFoundException("id-"+uId); } List<Checkbox> checkboxs = checkService.findByUUserAndId(userOptional.get(), qId); if (checkboxs.size() == 0) { throw new QuestionNotFoundException("UserId: " + uId + "CheckId: " + qId); } Checkbox checkbox = checkboxs.iterator().next(); CheckansId id = new CheckansId(uId, qId); Optional<Checkans> ans = checkansService.findById(id); if(!ans.isPresent()) { throw new QuestionNotFoundException("No answer found for UserId: " + uId + ", CheckId: " + qId); } return ans.get().getAnswers(); } @GetMapping("/users/{uId}/checkboxs") public List<String> checkChecks(@PathVariable int uId) { Optional<User> userOptional = service.findById(uId); if (!userOptional.isPresent()) { throw new UserNotFoundException("id-"+uId); } Set<Checkbox> checkboxs = userOptional.get().getcQuestions(); List<String> res = new ArrayList<>(); for(Checkbox checkbox : checkboxs) { CheckansId id = new CheckansId(uId, checkbox.getId()); Optional<Checkans> ans = checkansService.findById(id); if(!ans.isPresent()) { res.add(checkbox.getQuestion()); } } if(res.size() == 0) { throw new QuestionNotFoundException("No checkbox found for UserId: " + uId + " or all were answered"); } return res; } //mapping for trivias @PostMapping("/users/{uId}/trivias/{qId}") public String saveTriviaAnswers(@Valid @RequestBody Map<String, String> trivaans, @PathVariable int uId, @PathVariable int qId) { Optional<User> userOptional = service.findById(uId); if (!userOptional.isPresent()) { throw new UserNotFoundException("id-"+uId); } List<Trivia> trivias = triviaService.findByUUserAndId(userOptional.get(), qId); if (trivias.size() == 0) { throw new QuestionNotFoundException("UserId: " + uId + "TriviaId: " + qId); } Trivia trivia = trivias.iterator().next(); String userAnswer= trivaans.get("answers"); TriviaansId id = new TriviaansId(uId, qId); Triviaans answer = new Triviaans(id, trivia, userOptional.get(), userAnswer); triviaansService.save(answer); if(trivia.getCorrectAns().equals(userAnswer)) { return "Correct Answer!"; } else { return "Wrong Answer!"; } } @GetMapping("/users/{uId}/trivias/{qId}") public String saveTriviaAnswers(@PathVariable int uId, @PathVariable int qId) { Optional<User> userOptional = service.findById(uId); if (!userOptional.isPresent()) { throw new UserNotFoundException("id-"+uId); } List<Trivia> trivias = triviaService.findByUUserAndId(userOptional.get(), qId); if (trivias.size() == 0) { throw new QuestionNotFoundException("UserId: " + uId + "TriviaId: " + qId); } Trivia trivia = trivias.iterator().next(); TriviaansId id = new TriviaansId(uId, qId); Optional<Triviaans> ans = triviaansService.findById(id); if(!ans.isPresent()) { throw new QuestionNotFoundException("No answer found for UserId: " + uId + ", TriviaId: " + qId); } return ans.get().getAnswer(); } @GetMapping("/users/{uId}/trivias") public List<String> checkTrivias(@PathVariable int uId) { Optional<User> userOptional = service.findById(uId); if (!userOptional.isPresent()) { throw new UserNotFoundException("id-"+uId); } Set<Trivia> trivias = userOptional.get().gettQuestions(); List<String> res = new ArrayList<>(); for(Trivia trivia : trivias) { TriviaansId id = new TriviaansId(uId, trivia.getId()); Optional<Triviaans> ans = triviaansService.findById(id); if(!ans.isPresent()) { res.add(trivia.getQuestion()); } } if(res.size() == 0) { throw new QuestionNotFoundException("No trivia found for UserId: " + uId + " or all were answered"); } return res; } //mapping for polls @PostMapping("/users/{uId}/polls/{qId}") public void savePollAnswers(@Valid @RequestBody Map<String, String> pollans, @PathVariable int uId, @PathVariable int qId) { Optional<User> userOptional = service.findById(uId); if (!userOptional.isPresent()) { throw new UserNotFoundException("id-"+uId); } List<Poll> polls = pollService.findByUUserAndId(userOptional.get(), qId); if (polls.size() == 0) { throw new QuestionNotFoundException("UserId: " + uId + "PollId: " + qId); } Poll poll = polls.iterator().next(); String userAnswer= pollans.get("answers"); PollansId id = new PollansId(uId, qId); Pollans answer = new Pollans(id, poll, userOptional.get(), userAnswer); pollansService.save(answer); } @GetMapping("/users/{uId}/polls/{qId}") public String savePollAnswers(@PathVariable int uId, @PathVariable int qId) { Optional<User> userOptional = service.findById(uId); if (!userOptional.isPresent()) { throw new UserNotFoundException("id-"+uId); } List<Poll> polls = pollService.findByUUserAndId(userOptional.get(), qId); if (polls.size() == 0) { throw new QuestionNotFoundException("UserId: " + uId + "pollId: " + qId); } Poll poll = polls.iterator().next(); PollansId id = new PollansId(uId, qId); Optional<Pollans> ans = pollansService.findById(id); if(!ans.isPresent()) { throw new QuestionNotFoundException("No answer found for UserId: " + uId + ", PollId: " + qId); } return ans.get().getAnswer(); } @GetMapping("/users/{uId}/polls") public List<String> checkPolls(@PathVariable int uId) { Optional<User> userOptional = service.findById(uId); if (!userOptional.isPresent()) { throw new UserNotFoundException("id-"+uId); } Set<Poll> polls = userOptional.get().getpQuestions(); List<String> res = new ArrayList<>(); for(Poll poll : polls) { PollansId id = new PollansId(uId, poll.getId()); Optional<Pollans> ans = pollansService.findById(id); if(!ans.isPresent()) { res.add(poll.getQuestion()); } } if(res.size() == 0) { throw new QuestionNotFoundException("No poll found for UserId: " + uId + " or all were answered"); } return res; } //mapping for matrix @PostMapping("/users/{uId}/matrixs/{qId}") public void saveMatrixAnswers(@Valid @RequestBody List<String> matrixans, @PathVariable int uId, @PathVariable int qId) { Optional<User> userOptional = service.findById(uId); if (!userOptional.isPresent()) { throw new UserNotFoundException("id-"+uId); } List<Matrix> matrixs = matrixService.findByUUserAndId(userOptional.get(), qId); if (matrixs.size() == 0) { throw new QuestionNotFoundException("UserId: " + uId + "MatrixId: " + qId); } Matrix matrix = matrixs.iterator().next(); MatrixansId id = new MatrixansId(uId, qId); Matrixans answer = new Matrixans(id, matrix, userOptional.get(), matrixans.get(0), matrixans.get(1)); matrixansService.save(answer); } @GetMapping("/users/{uId}/matrixs/{qId}") public List<String> saveMatrixAnswers(@PathVariable int uId, @PathVariable int qId) { Optional<User> userOptional = service.findById(uId); if (!userOptional.isPresent()) { throw new UserNotFoundException("id-"+uId); } List<Matrix> matrixs = matrixService.findByUUserAndId(userOptional.get(), qId); if (matrixs.size() == 0) { throw new QuestionNotFoundException("UserId: " + uId + "MatrixId: " + qId); } Matrix matrix = matrixs.iterator().next(); MatrixansId id = new MatrixansId(uId, qId); Optional<Matrixans> ans = matrixansService.findById(id); if(!ans.isPresent()) { throw new QuestionNotFoundException("No answer found for UserId: " + uId + ", MatrixId: " + qId); } List<String> res = new ArrayList<>(); res.add(ans.get().getAnswer1()); res.add(ans.get().getAnswer2()); return res; } @GetMapping("/users/{uId}/matrixs") public List<Set<String>> checkMatrixs(@PathVariable int uId) { Optional<User> userOptional = service.findById(uId); if (!userOptional.isPresent()) { throw new UserNotFoundException("id-"+uId); } Set<Matrix> matrixs = userOptional.get().getmQuestions(); List<Set<String>> res = new ArrayList<>(); for(Matrix matrix : matrixs) { MatrixansId id = new MatrixansId(uId, matrix.getId()); Optional<Matrixans> ans = matrixansService.findById(id); if(!ans.isPresent()) { res.add(matrix.getOptions1()); res.add(matrix.getOptions2()); } } if(res.size() == 0) { throw new QuestionNotFoundException("No matrix found for UserId: " + uId + " or all were answered"); } return res; } }
UTF-8
Java
14,859
java
UserResource.java
Java
[]
null
[]
package com.insticator.spring.project.models.user; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.insticator.spring.project.models.questions.QuestionNotFoundException; import com.insticator.spring.project.models.questions.Checkbox.Checkans; import com.insticator.spring.project.models.questions.Checkbox.CheckansId; import com.insticator.spring.project.models.questions.Checkbox.Checkbox; import com.insticator.spring.project.models.questions.Poll.Poll; import com.insticator.spring.project.models.questions.Poll.Pollans; import com.insticator.spring.project.models.questions.Poll.PollansId; import com.insticator.spring.project.models.questions.Trivia.Trivia; import com.insticator.spring.project.models.questions.Trivia.Triviaans; import com.insticator.spring.project.models.questions.Trivia.TriviaansId; import com.insticator.spring.project.models.questions.matrix.Matrix; import com.insticator.spring.project.models.questions.matrix.Matrixans; import com.insticator.spring.project.models.questions.matrix.MatrixansId; import com.insticator.spring.project.repository.CheckansRepository; import com.insticator.spring.project.repository.CheckboxRepository; import com.insticator.spring.project.repository.MatrixRepository; import com.insticator.spring.project.repository.MatrixansRepository; import com.insticator.spring.project.repository.PollRepository; import com.insticator.spring.project.repository.PollansRepository; import com.insticator.spring.project.repository.TriviaRepository; import com.insticator.spring.project.repository.TriviaansRepository; import com.insticator.spring.project.repository.UserRepository; @RestController public class UserResource { @Autowired private UserRepository service; @Autowired private CheckboxRepository checkService; @Autowired private CheckansRepository checkansService; @Autowired private TriviaRepository triviaService; @Autowired private TriviaansRepository triviaansService; @Autowired private PollRepository pollService; @Autowired private PollansRepository pollansService; @Autowired private MatrixRepository matrixService; @Autowired private MatrixansRepository matrixansService; @GetMapping("/users") public List<User> retrieveAllUsers() { return service.findAll(); } @GetMapping("/users/{id}") public User retrieveUser(@PathVariable int id) { Optional<User> user = service.findById(id); if (!user.isPresent()) { throw new UserNotFoundException("id-"+id); } return user.get(); } @GetMapping("/users/{id}/questions") public Map<String, Set<String>> retrieveAllQuestions(@PathVariable int id) { Optional<User> user = service.findById(id); if (!user.isPresent()) { throw new UserNotFoundException("id-"+id); } Map<String, Set<String>> res = new HashMap<>(); Set<Trivia> tQuestions = user.get().gettQuestions(); Set<Poll> pQuestions = user.get().getpQuestions(); Set<Matrix> mQuestions = user.get().getmQuestions(); Set<Checkbox> cQuestions = user.get().getcQuestions(); if(tQuestions.size() > 0) { for(Trivia trivia : tQuestions) { TriviaansId qid = new TriviaansId(id, trivia.getId()); Optional<Triviaans> ans = triviaansService.findById(qid); if(!ans.isPresent()) { res.put("Trivia " + trivia.getId() + " " + trivia.getQuestion(), trivia.getOptions()); } } } if(pQuestions.size() > 0) { for(Poll poll : pQuestions) { PollansId qid = new PollansId(id, poll.getId()); Optional<Pollans> ans = pollansService.findById(qid); if(!ans.isPresent()) { res.put("Poll " + poll.getId() + " " + poll.getQuestion(), poll.getOptions()); } } } if(mQuestions.size() > 0) { for(Matrix matrix : mQuestions) { MatrixansId qid = new MatrixansId(id, matrix.getId()); Optional<Matrixans> ans = matrixansService.findById(qid); if(ans.isPresent()) { continue; } Set<String> list = new HashSet<>(); int count = 0; StringBuilder str = new StringBuilder(); for(String option : matrix.getOptions1()) { str.append(option); if(count != matrix.getOptions1().size() - 1) str.append(","); count++; } list.add(str.toString()); count = 0; str = new StringBuilder(); for(String option : matrix.getOptions2()) { str.append(option); if(count != matrix.getOptions2().size() - 1) str.append(","); count++; } list.add(str.toString()); res.put("matrix " + matrix.getId(), list); } } if(cQuestions.size() > 0) { for(Checkbox checkbox : cQuestions) { CheckansId qid = new CheckansId(id, checkbox.getId()); Optional<Checkans> ans = checkansService.findById(qid); if(!ans.isPresent()) { res.put("Checkbox " + checkbox.getId() + " " + checkbox.getQuestion(), checkbox.getOptions()); } } } return res; } @PostMapping("/users/{uId}/checkboxs/{qId}") public void saveCheckAnswers(@Valid @RequestBody Map<String, String[]> checkans, @PathVariable int uId, @PathVariable int qId) { Optional<User> userOptional = service.findById(uId); if (!userOptional.isPresent()) { throw new UserNotFoundException("id-"+uId); } List<Checkbox> checkboxs = checkService.findByUUserAndId(userOptional.get(), qId); if (checkboxs.size() == 0) { throw new QuestionNotFoundException("UserId: " + uId + "CheckId: " + qId); } Checkbox checkbox = checkboxs.iterator().next(); Set<String> checkSet= new HashSet<>(Arrays.asList(checkans.get("answers"))); CheckansId id = new CheckansId(uId, qId); Checkans answer = new Checkans(id, checkSet, checkbox, userOptional.get()); checkansService.save(answer); } @GetMapping("/users/{uId}/checkboxs/{qId}") public Set<String> saveCheckAnswers(@PathVariable int uId, @PathVariable int qId) { Optional<User> userOptional = service.findById(uId); if (!userOptional.isPresent()) { throw new UserNotFoundException("id-"+uId); } List<Checkbox> checkboxs = checkService.findByUUserAndId(userOptional.get(), qId); if (checkboxs.size() == 0) { throw new QuestionNotFoundException("UserId: " + uId + "CheckId: " + qId); } Checkbox checkbox = checkboxs.iterator().next(); CheckansId id = new CheckansId(uId, qId); Optional<Checkans> ans = checkansService.findById(id); if(!ans.isPresent()) { throw new QuestionNotFoundException("No answer found for UserId: " + uId + ", CheckId: " + qId); } return ans.get().getAnswers(); } @GetMapping("/users/{uId}/checkboxs") public List<String> checkChecks(@PathVariable int uId) { Optional<User> userOptional = service.findById(uId); if (!userOptional.isPresent()) { throw new UserNotFoundException("id-"+uId); } Set<Checkbox> checkboxs = userOptional.get().getcQuestions(); List<String> res = new ArrayList<>(); for(Checkbox checkbox : checkboxs) { CheckansId id = new CheckansId(uId, checkbox.getId()); Optional<Checkans> ans = checkansService.findById(id); if(!ans.isPresent()) { res.add(checkbox.getQuestion()); } } if(res.size() == 0) { throw new QuestionNotFoundException("No checkbox found for UserId: " + uId + " or all were answered"); } return res; } //mapping for trivias @PostMapping("/users/{uId}/trivias/{qId}") public String saveTriviaAnswers(@Valid @RequestBody Map<String, String> trivaans, @PathVariable int uId, @PathVariable int qId) { Optional<User> userOptional = service.findById(uId); if (!userOptional.isPresent()) { throw new UserNotFoundException("id-"+uId); } List<Trivia> trivias = triviaService.findByUUserAndId(userOptional.get(), qId); if (trivias.size() == 0) { throw new QuestionNotFoundException("UserId: " + uId + "TriviaId: " + qId); } Trivia trivia = trivias.iterator().next(); String userAnswer= trivaans.get("answers"); TriviaansId id = new TriviaansId(uId, qId); Triviaans answer = new Triviaans(id, trivia, userOptional.get(), userAnswer); triviaansService.save(answer); if(trivia.getCorrectAns().equals(userAnswer)) { return "Correct Answer!"; } else { return "Wrong Answer!"; } } @GetMapping("/users/{uId}/trivias/{qId}") public String saveTriviaAnswers(@PathVariable int uId, @PathVariable int qId) { Optional<User> userOptional = service.findById(uId); if (!userOptional.isPresent()) { throw new UserNotFoundException("id-"+uId); } List<Trivia> trivias = triviaService.findByUUserAndId(userOptional.get(), qId); if (trivias.size() == 0) { throw new QuestionNotFoundException("UserId: " + uId + "TriviaId: " + qId); } Trivia trivia = trivias.iterator().next(); TriviaansId id = new TriviaansId(uId, qId); Optional<Triviaans> ans = triviaansService.findById(id); if(!ans.isPresent()) { throw new QuestionNotFoundException("No answer found for UserId: " + uId + ", TriviaId: " + qId); } return ans.get().getAnswer(); } @GetMapping("/users/{uId}/trivias") public List<String> checkTrivias(@PathVariable int uId) { Optional<User> userOptional = service.findById(uId); if (!userOptional.isPresent()) { throw new UserNotFoundException("id-"+uId); } Set<Trivia> trivias = userOptional.get().gettQuestions(); List<String> res = new ArrayList<>(); for(Trivia trivia : trivias) { TriviaansId id = new TriviaansId(uId, trivia.getId()); Optional<Triviaans> ans = triviaansService.findById(id); if(!ans.isPresent()) { res.add(trivia.getQuestion()); } } if(res.size() == 0) { throw new QuestionNotFoundException("No trivia found for UserId: " + uId + " or all were answered"); } return res; } //mapping for polls @PostMapping("/users/{uId}/polls/{qId}") public void savePollAnswers(@Valid @RequestBody Map<String, String> pollans, @PathVariable int uId, @PathVariable int qId) { Optional<User> userOptional = service.findById(uId); if (!userOptional.isPresent()) { throw new UserNotFoundException("id-"+uId); } List<Poll> polls = pollService.findByUUserAndId(userOptional.get(), qId); if (polls.size() == 0) { throw new QuestionNotFoundException("UserId: " + uId + "PollId: " + qId); } Poll poll = polls.iterator().next(); String userAnswer= pollans.get("answers"); PollansId id = new PollansId(uId, qId); Pollans answer = new Pollans(id, poll, userOptional.get(), userAnswer); pollansService.save(answer); } @GetMapping("/users/{uId}/polls/{qId}") public String savePollAnswers(@PathVariable int uId, @PathVariable int qId) { Optional<User> userOptional = service.findById(uId); if (!userOptional.isPresent()) { throw new UserNotFoundException("id-"+uId); } List<Poll> polls = pollService.findByUUserAndId(userOptional.get(), qId); if (polls.size() == 0) { throw new QuestionNotFoundException("UserId: " + uId + "pollId: " + qId); } Poll poll = polls.iterator().next(); PollansId id = new PollansId(uId, qId); Optional<Pollans> ans = pollansService.findById(id); if(!ans.isPresent()) { throw new QuestionNotFoundException("No answer found for UserId: " + uId + ", PollId: " + qId); } return ans.get().getAnswer(); } @GetMapping("/users/{uId}/polls") public List<String> checkPolls(@PathVariable int uId) { Optional<User> userOptional = service.findById(uId); if (!userOptional.isPresent()) { throw new UserNotFoundException("id-"+uId); } Set<Poll> polls = userOptional.get().getpQuestions(); List<String> res = new ArrayList<>(); for(Poll poll : polls) { PollansId id = new PollansId(uId, poll.getId()); Optional<Pollans> ans = pollansService.findById(id); if(!ans.isPresent()) { res.add(poll.getQuestion()); } } if(res.size() == 0) { throw new QuestionNotFoundException("No poll found for UserId: " + uId + " or all were answered"); } return res; } //mapping for matrix @PostMapping("/users/{uId}/matrixs/{qId}") public void saveMatrixAnswers(@Valid @RequestBody List<String> matrixans, @PathVariable int uId, @PathVariable int qId) { Optional<User> userOptional = service.findById(uId); if (!userOptional.isPresent()) { throw new UserNotFoundException("id-"+uId); } List<Matrix> matrixs = matrixService.findByUUserAndId(userOptional.get(), qId); if (matrixs.size() == 0) { throw new QuestionNotFoundException("UserId: " + uId + "MatrixId: " + qId); } Matrix matrix = matrixs.iterator().next(); MatrixansId id = new MatrixansId(uId, qId); Matrixans answer = new Matrixans(id, matrix, userOptional.get(), matrixans.get(0), matrixans.get(1)); matrixansService.save(answer); } @GetMapping("/users/{uId}/matrixs/{qId}") public List<String> saveMatrixAnswers(@PathVariable int uId, @PathVariable int qId) { Optional<User> userOptional = service.findById(uId); if (!userOptional.isPresent()) { throw new UserNotFoundException("id-"+uId); } List<Matrix> matrixs = matrixService.findByUUserAndId(userOptional.get(), qId); if (matrixs.size() == 0) { throw new QuestionNotFoundException("UserId: " + uId + "MatrixId: " + qId); } Matrix matrix = matrixs.iterator().next(); MatrixansId id = new MatrixansId(uId, qId); Optional<Matrixans> ans = matrixansService.findById(id); if(!ans.isPresent()) { throw new QuestionNotFoundException("No answer found for UserId: " + uId + ", MatrixId: " + qId); } List<String> res = new ArrayList<>(); res.add(ans.get().getAnswer1()); res.add(ans.get().getAnswer2()); return res; } @GetMapping("/users/{uId}/matrixs") public List<Set<String>> checkMatrixs(@PathVariable int uId) { Optional<User> userOptional = service.findById(uId); if (!userOptional.isPresent()) { throw new UserNotFoundException("id-"+uId); } Set<Matrix> matrixs = userOptional.get().getmQuestions(); List<Set<String>> res = new ArrayList<>(); for(Matrix matrix : matrixs) { MatrixansId id = new MatrixansId(uId, matrix.getId()); Optional<Matrixans> ans = matrixansService.findById(id); if(!ans.isPresent()) { res.add(matrix.getOptions1()); res.add(matrix.getOptions2()); } } if(res.size() == 0) { throw new QuestionNotFoundException("No matrix found for UserId: " + uId + " or all were answered"); } return res; } }
14,859
0.698566
0.696548
479
30.020876
28.622654
130
false
false
0
0
0
0
0
0
2.421712
false
false
4
e48fa72e0369cb514ef9893bc97419efc31ab0f2
12,240,656,852,550
03b63f316e70189d964ecc504373e9ee6dff3d77
/ScannerSkip/ScannerSkipString.java
3196ed37abf246769f3497341665632e95707b55
[]
no_license
fudisfuel/JavaCodes
https://github.com/fudisfuel/JavaCodes
23f00185749efe0206981ac5bcaab215c3fb9f24
04548625192647d392d2d194d9ee598afd6ed080
refs/heads/main
2023-03-13T22:01:42.235000
2021-02-09T14:32:25
2021-02-09T14:32:25
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package food; import java.util.*; public class ScannerSkipString { public static void main(String []args){ Scanner sc=new Scanner(System.in); System.out.println("Enter message"); String message=sc.nextLine(); Scanner sc1=new Scanner(message); System.out.println("Enter Skip String"); String skip=sc.nextLine(); sc1.skip(skip); System.out.println(sc1.nextLine()); sc1.close(); sc.close(); } }
UTF-8
Java
492
java
ScannerSkipString.java
Java
[]
null
[]
package food; import java.util.*; public class ScannerSkipString { public static void main(String []args){ Scanner sc=new Scanner(System.in); System.out.println("Enter message"); String message=sc.nextLine(); Scanner sc1=new Scanner(message); System.out.println("Enter Skip String"); String skip=sc.nextLine(); sc1.skip(skip); System.out.println(sc1.nextLine()); sc1.close(); sc.close(); } }
492
0.593496
0.585366
16
29.8125
14.599738
49
false
false
0
0
0
0
0
0
0.75
false
false
4