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
list
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
list
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
be9ac124ca034da9eb0b4164dd72fe94c68fd979
1,013,612,351,483
e80f3ac5d53e9356000688550a27fa8c00594c61
/src/main/java/com/t31/app/service/backend/BackendUserService.java
61e1b6374cded248e9c5fb64d4c58ac0eccd1e37
[]
no_license
T31-The-first/app
https://github.com/T31-The-first/app
45148e0a3db2f5ad1ccd331e0a8b55c313ed6ac1
8af618da8b9cbd55d158aeb6bf0e904aac6d53eb
refs/heads/master
2022-12-23T13:31:10.912000
2019-12-27T15:24:41
2019-12-27T15:24:41
227,851,648
0
0
null
false
2022-12-16T08:00:58
2019-12-13T13:57:26
2019-12-27T15:24:49
2022-12-16T08:00:55
59,994
0
0
12
Java
false
false
package com.t31.app.service.backend; import com.t31.app.entity.BackendUserDTO; import com.t31.app.entity.backend.BackendUserDTOInfo; /** * description: BackendUserService * date: 2019/12/16 10:32 * author: 周吉涛 * version: 1.0 */ public interface BackendUserService { public BackendUserDTOInfo login(String code, String pwd); }
UTF-8
Java
344
java
BackendUserService.java
Java
[ { "context": "dUserService\n * date: 2019/12/16 10:32\n * author: 周吉涛\n * version: 1.0\n */\npublic interface BackendUserS", "end": 214, "score": 0.9997051954269409, "start": 211, "tag": "NAME", "value": "周吉涛" } ]
null
[]
package com.t31.app.service.backend; import com.t31.app.entity.BackendUserDTO; import com.t31.app.entity.backend.BackendUserDTOInfo; /** * description: BackendUserService * date: 2019/12/16 10:32 * author: 周吉涛 * version: 1.0 */ public interface BackendUserService { public BackendUserDTOInfo login(String code, String pwd); }
344
0.754438
0.695266
15
21.533333
20.234844
61
false
false
0
0
0
0
0
0
0.333333
false
false
14
dbccba754e7e855e066a4dcc28ed6cfc80bdf97f
10,084,583,220,920
c4879bcbc6ee3224b735ee6753c22184705b9d8b
/Proyecto_Bibioteca/src/main/java/com/DBSolutions/Controladores/Controlador.java
6076888a8507e670694f7766bc42db9821318974
[]
no_license
kevinmora47/Proyecto_Biblioteca
https://github.com/kevinmora47/Proyecto_Biblioteca
1c04d53eea6297ef809dfb9e80130fa3f5c8227d
f93aad91fec7b5f0368601d5b3ff348e54879fc3
refs/heads/master
2020-06-12T22:58:50.391000
2019-07-18T22:33:02
2019-07-18T22:33:02
194,451,108
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.DBSolutions.Controladores; //Modelo Controlador. public class Controlador { }
UTF-8
Java
100
java
Controlador.java
Java
[]
null
[]
package com.DBSolutions.Controladores; //Modelo Controlador. public class Controlador { }
100
0.73
0.73
5
18
13.841965
38
false
false
0
0
0
0
0
0
0.2
false
false
14
4d866a1955d7fef8e71aef23d01082d2c8e304c2
14,663,018,364,316
4ffb6265f24c868ee4b5f9ee269a76a315b4ef5b
/app/src/main/java/com/pinig/launcher/HttpHandler.java
c121e7c5e3fb3bad6c951e4aa4ab719fc30c679a
[]
no_license
pinigtech/PinigB2BLauncher
https://github.com/pinigtech/PinigB2BLauncher
44d3b59dabd0ef699cea378ed19a814746d653c0
1b0b1be7e47528ba5a72e85dae214e60505802aa
refs/heads/master
2020-03-07T22:31:49.196000
2018-04-02T12:58:37
2018-04-02T12:58:37
127,756,429
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.pinig.launcher; /** * Created by varun on 15/12/16. */ import android.support.annotation.NonNull; import android.util.Log; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.json.JSONObject; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class HttpHandler { private static final String TAG = HttpHandler.class.getSimpleName(); public HttpHandler() { } public String getCall(String reqUrl) { String response = null; Log.i(TAG,"GET call made"); try { URL url = new URL(reqUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); int HttpResult = conn.getResponseCode(); if (HttpResult==HttpURLConnection.HTTP_OK) { InputStream in = new BufferedInputStream(conn.getInputStream()); response = convertStreamToString(in); } else if (HttpResult==HttpURLConnection.HTTP_FORBIDDEN){ response=null; } } catch (Exception e){ Log.e(TAG, "Exception: " + e.getMessage()); } return response; } public String[] postCall(String reqUrl, JSONObject jsonObject) { HttpResponse response; String[] values = new String[2]; try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost postRequest = new HttpPost(reqUrl); StringEntity input = new StringEntity(jsonObject.toString()); input.setContentType("application/json"); postRequest.setEntity(input); response = httpClient.execute(postRequest); HttpEntity httpEntity = response.getEntity(); String apiOutput = EntityUtils.toString(httpEntity); JSONObject jsonObject2 = new JSONObject(apiOutput); values[0] = String.valueOf(response.getStatusLine().getStatusCode()); values[1] = jsonObject2.toString(); httpClient.getConnectionManager().shutdown(); return values; } catch (Exception e){ e.printStackTrace(); } return null; } private String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line; try { while ((line = reader.readLine()) != null) { sb.append(line).append('\n'); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } }
UTF-8
Java
3,184
java
HttpHandler.java
Java
[ { "context": "package com.pinig.launcher;\n\n/**\n * Created by varun on 15/12/16.\n */\nimport android.support.annotatio", "end": 52, "score": 0.9987382888793945, "start": 47, "tag": "USERNAME", "value": "varun" } ]
null
[]
package com.pinig.launcher; /** * Created by varun on 15/12/16. */ import android.support.annotation.NonNull; import android.util.Log; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.json.JSONObject; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class HttpHandler { private static final String TAG = HttpHandler.class.getSimpleName(); public HttpHandler() { } public String getCall(String reqUrl) { String response = null; Log.i(TAG,"GET call made"); try { URL url = new URL(reqUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); int HttpResult = conn.getResponseCode(); if (HttpResult==HttpURLConnection.HTTP_OK) { InputStream in = new BufferedInputStream(conn.getInputStream()); response = convertStreamToString(in); } else if (HttpResult==HttpURLConnection.HTTP_FORBIDDEN){ response=null; } } catch (Exception e){ Log.e(TAG, "Exception: " + e.getMessage()); } return response; } public String[] postCall(String reqUrl, JSONObject jsonObject) { HttpResponse response; String[] values = new String[2]; try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost postRequest = new HttpPost(reqUrl); StringEntity input = new StringEntity(jsonObject.toString()); input.setContentType("application/json"); postRequest.setEntity(input); response = httpClient.execute(postRequest); HttpEntity httpEntity = response.getEntity(); String apiOutput = EntityUtils.toString(httpEntity); JSONObject jsonObject2 = new JSONObject(apiOutput); values[0] = String.valueOf(response.getStatusLine().getStatusCode()); values[1] = jsonObject2.toString(); httpClient.getConnectionManager().shutdown(); return values; } catch (Exception e){ e.printStackTrace(); } return null; } private String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line; try { while ((line = reader.readLine()) != null) { sb.append(line).append('\n'); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } }
3,184
0.615892
0.612437
102
30.225491
22.739319
81
false
false
0
0
0
0
0
0
0.558824
false
false
14
66c99c5d36d3917dab2eb510664603d5e43f8917
24,129,126,274,299
578f097e61290e0fe80f42bc636b2227559b34d5
/suningEBuyGit/src/com/suning/mobile/ebuy/ui/myebuy/myyfb/YfbBalanceActivity.java
2557d0d2ea45279c59a88bc65cbc33125a62bc8c
[]
no_license
siwangqishiq/MyNewToy
https://github.com/siwangqishiq/MyNewToy
1d6443f5985749a8ebcef1de06265d493b2aeb3e
110652825c92ff9a819c07b7e7a288644505d454
refs/heads/master
2015-08-09T19:19:44.478000
2013-12-19T06:59:06
2013-12-19T06:59:06
15,280,638
6
30
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.suning.mobile.ebuy.ui.myebuy.myyfb; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import com.suning.mobile.ebuy.R; import com.suning.mobile.ebuy.SuningEBuyActivity; import com.suning.mobile.ebuy.SuningEBuyApplication; import com.suning.mobile.ebuy.SuningEbuyHandleMessage; import com.suning.mobile.ebuy.utils.SuningFunctionUtils; import com.suning.mobile.sdk.logger.LogX; /** * * @Title:易付宝绑定页面 * @Description: 易付宝绑定 * @Author:张兵 * @Since:2013-5-16 * @Version: */ public class YfbBalanceActivity extends SuningEBuyActivity { // 是否绑定手机号(0:未绑定,1:已绑定) private String isBindMobile; // 账号对应姓名 private String mName; // 证件类型 private String mCardType; // 证件号码 private String mIdCode; // 登录类型(邮箱、手机号等) private String mLogonIdType; // 激活按钮隐藏、显示 public static LinearLayout mLinearLayout; // 激活或绑定 private Button btnActivateOrBind; // 易付宝余额 private TextView yfbBalance; // 易付宝状态 public static TextView yfbState; // 易付宝激活提示 private TextView textRemind; /* * (non-Javadoc) * * @see * com.suning.mobile.ebuy.SuningEBuyActivity#onCreate(android.os.Bundle) */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_yfb_balance); setSubPageTitle(getString(R.string.my_easy_payment)); setPageTitle("会员-我的易购-我的易付宝"); yfbBalance = (TextView) findViewById(R.id.yfb_balance); yfbState = (TextView) findViewById(R.id.yfb_state); textRemind = (TextView) findViewById(R.id.text_remind_msg); btnActivateOrBind = (Button) findViewById(R.id.btn_activate_or_bind); mLinearLayout = (LinearLayout) findViewById(R.id.layout_activate); backToLastPage(this); initData(); onActivateBindClick(); } /** * @Description initialization control view and data * @Author dlobo * @Date 2013-9-23 */ private void initData() { Intent intent = getIntent(); mName = intent.getStringExtra("name"); mCardType = intent.getStringExtra("cardType"); mIdCode = intent.getStringExtra("idCode"); String syifubaoBalance = SuningFunctionUtils .formatePrice(SuningEBuyApplication.getInstance().yifubaoBalance); yfbBalance.setText(syifubaoBalance); boolean bool = SuningEBuyApplication.getInstance().globleLogonId .contains("@"); if (bool) { mLogonIdType = "0"; } else { mLogonIdType = "1"; } notifyPage(); } /** * * @Description:通知页面刷新 * @Author 张兵 * @Date 2013-5-16 */ private void notifyPage() { String eppStatus = SuningEBuyApplication.getInstance().eppStatus; isBindMobile = SuningEBuyApplication.getInstance().isBindMobile; if ("0".equals(eppStatus)) { yfbState.setText(R.string.no_activate); if ("1".equals(isBindMobile)) { textRemind.setText(R.string.not_activate_tips); btnActivateOrBind.setText(R.string.activate_easy_payment); } else if ("0".equals(isBindMobile)) { textRemind.setText(R.string.activate_tips); if ("0".endsWith(mLogonIdType)) // 邮箱账户 { btnActivateOrBind.setText(R.string.bind_activate); } else if ("1".endsWith(mLogonIdType)) { btnActivateOrBind.setText(R.string.bind_telephone); } } } else if ("1".equals(eppStatus)) { yfbState.setText(R.string.activated); mLinearLayout.setVisibility(View.GONE); } else { this.finish(); } } /** * @Description User activate account or bind phone numbers * @Author dlobo * @Date 2013-9-23 */ private void onActivateBindClick() { btnActivateOrBind.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String logonId = SuningEBuyApplication.getInstance().globleLogonId; // goto bind telephone number if (logonId.contains("@")) { displayToast(R.string.emailacount); } else if ("0".equals(isBindMobile)) { LogX.i(this, "zachary isBindMobile =============> 0"); Intent intent = new Intent(YfbBalanceActivity.this, YfbBindMobileActivity.class); intent.putExtra("logonIdType", mLogonIdType); intent.putExtra("logonId", SuningEBuyApplication.getInstance().globleLogonId); intent.putExtra("name", mName); intent.putExtra("cardType", mCardType); intent.putExtra("idCode", mIdCode); startActivityForResult( intent, SuningEbuyHandleMessage.EBUY_PAYMENT_REQUEST_CODE_NO_BIND); } // goto activate easy payment else if ("1".equals(isBindMobile)) { LogX.i(this, "zachary isBindMobile =============> 1"); startActivateActivity(); } } }); } /** * @Description goto easy payment activate activity * @Author dlobo * @Date 2013-9-23 */ private void startActivateActivity() { hideInnerLoadView(); String mobile = SuningEBuyApplication.getInstance().phoneNo; Intent intent = new Intent(YfbBalanceActivity.this, YfbActivateActivity.class); intent.putExtra("logonIdType", mLogonIdType); intent.putExtra("mobile", mobile); intent.putExtra("isBindMobile", isBindMobile); intent.putExtra("name", mName); intent.putExtra("cardType", mCardType); intent.putExtra("idCode", mIdCode); startActivityForResult(intent, SuningEbuyHandleMessage.EBUY_PAYMENT_REQUEST_CODE_BIND); } /* * (non-Javadoc) * * @see android.app.Activity#onActivityResult(int, int, * android.content.Intent) */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { LogX.i(this, "requestCode = " + requestCode + ", resultCode =" + resultCode); switch (requestCode) { // activate or bind easy payment case SuningEbuyHandleMessage.EBUY_PAYMENT_REQUEST_CODE_BIND: case SuningEbuyHandleMessage.EBUY_PAYMENT_REQUEST_CODE_NO_BIND: notifyPage(); break; default: break; } } }
GB18030
Java
7,684
java
YfbBalanceActivity.java
Java
[ { "context": "Title:易付宝绑定页面\r\n * @Description: 易付宝绑定\r\n * @Author:张兵\r\n * @Since:2013-5-16\r\n * @Version:\r\n */\r\npublic c", "end": 645, "score": 0.9957129955291748, "start": 643, "tag": "NAME", "value": "张兵" }, { "context": "itialization control view and data\r\n * @Author...
null
[]
package com.suning.mobile.ebuy.ui.myebuy.myyfb; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import com.suning.mobile.ebuy.R; import com.suning.mobile.ebuy.SuningEBuyActivity; import com.suning.mobile.ebuy.SuningEBuyApplication; import com.suning.mobile.ebuy.SuningEbuyHandleMessage; import com.suning.mobile.ebuy.utils.SuningFunctionUtils; import com.suning.mobile.sdk.logger.LogX; /** * * @Title:易付宝绑定页面 * @Description: 易付宝绑定 * @Author:张兵 * @Since:2013-5-16 * @Version: */ public class YfbBalanceActivity extends SuningEBuyActivity { // 是否绑定手机号(0:未绑定,1:已绑定) private String isBindMobile; // 账号对应姓名 private String mName; // 证件类型 private String mCardType; // 证件号码 private String mIdCode; // 登录类型(邮箱、手机号等) private String mLogonIdType; // 激活按钮隐藏、显示 public static LinearLayout mLinearLayout; // 激活或绑定 private Button btnActivateOrBind; // 易付宝余额 private TextView yfbBalance; // 易付宝状态 public static TextView yfbState; // 易付宝激活提示 private TextView textRemind; /* * (non-Javadoc) * * @see * com.suning.mobile.ebuy.SuningEBuyActivity#onCreate(android.os.Bundle) */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_yfb_balance); setSubPageTitle(getString(R.string.my_easy_payment)); setPageTitle("会员-我的易购-我的易付宝"); yfbBalance = (TextView) findViewById(R.id.yfb_balance); yfbState = (TextView) findViewById(R.id.yfb_state); textRemind = (TextView) findViewById(R.id.text_remind_msg); btnActivateOrBind = (Button) findViewById(R.id.btn_activate_or_bind); mLinearLayout = (LinearLayout) findViewById(R.id.layout_activate); backToLastPage(this); initData(); onActivateBindClick(); } /** * @Description initialization control view and data * @Author dlobo * @Date 2013-9-23 */ private void initData() { Intent intent = getIntent(); mName = intent.getStringExtra("name"); mCardType = intent.getStringExtra("cardType"); mIdCode = intent.getStringExtra("idCode"); String syifubaoBalance = SuningFunctionUtils .formatePrice(SuningEBuyApplication.getInstance().yifubaoBalance); yfbBalance.setText(syifubaoBalance); boolean bool = SuningEBuyApplication.getInstance().globleLogonId .contains("@"); if (bool) { mLogonIdType = "0"; } else { mLogonIdType = "1"; } notifyPage(); } /** * * @Description:通知页面刷新 * @Author 张兵 * @Date 2013-5-16 */ private void notifyPage() { String eppStatus = SuningEBuyApplication.getInstance().eppStatus; isBindMobile = SuningEBuyApplication.getInstance().isBindMobile; if ("0".equals(eppStatus)) { yfbState.setText(R.string.no_activate); if ("1".equals(isBindMobile)) { textRemind.setText(R.string.not_activate_tips); btnActivateOrBind.setText(R.string.activate_easy_payment); } else if ("0".equals(isBindMobile)) { textRemind.setText(R.string.activate_tips); if ("0".endsWith(mLogonIdType)) // 邮箱账户 { btnActivateOrBind.setText(R.string.bind_activate); } else if ("1".endsWith(mLogonIdType)) { btnActivateOrBind.setText(R.string.bind_telephone); } } } else if ("1".equals(eppStatus)) { yfbState.setText(R.string.activated); mLinearLayout.setVisibility(View.GONE); } else { this.finish(); } } /** * @Description User activate account or bind phone numbers * @Author dlobo * @Date 2013-9-23 */ private void onActivateBindClick() { btnActivateOrBind.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String logonId = SuningEBuyApplication.getInstance().globleLogonId; // goto bind telephone number if (logonId.contains("@")) { displayToast(R.string.emailacount); } else if ("0".equals(isBindMobile)) { LogX.i(this, "zachary isBindMobile =============> 0"); Intent intent = new Intent(YfbBalanceActivity.this, YfbBindMobileActivity.class); intent.putExtra("logonIdType", mLogonIdType); intent.putExtra("logonId", SuningEBuyApplication.getInstance().globleLogonId); intent.putExtra("name", mName); intent.putExtra("cardType", mCardType); intent.putExtra("idCode", mIdCode); startActivityForResult( intent, SuningEbuyHandleMessage.EBUY_PAYMENT_REQUEST_CODE_NO_BIND); } // goto activate easy payment else if ("1".equals(isBindMobile)) { LogX.i(this, "zachary isBindMobile =============> 1"); startActivateActivity(); } } }); } /** * @Description goto easy payment activate activity * @Author dlobo * @Date 2013-9-23 */ private void startActivateActivity() { hideInnerLoadView(); String mobile = SuningEBuyApplication.getInstance().phoneNo; Intent intent = new Intent(YfbBalanceActivity.this, YfbActivateActivity.class); intent.putExtra("logonIdType", mLogonIdType); intent.putExtra("mobile", mobile); intent.putExtra("isBindMobile", isBindMobile); intent.putExtra("name", mName); intent.putExtra("cardType", mCardType); intent.putExtra("idCode", mIdCode); startActivityForResult(intent, SuningEbuyHandleMessage.EBUY_PAYMENT_REQUEST_CODE_BIND); } /* * (non-Javadoc) * * @see android.app.Activity#onActivityResult(int, int, * android.content.Intent) */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { LogX.i(this, "requestCode = " + requestCode + ", resultCode =" + resultCode); switch (requestCode) { // activate or bind easy payment case SuningEbuyHandleMessage.EBUY_PAYMENT_REQUEST_CODE_BIND: case SuningEbuyHandleMessage.EBUY_PAYMENT_REQUEST_CODE_NO_BIND: notifyPage(); break; default: break; } } }
7,684
0.560675
0.554112
226
31.035398
22.659437
83
false
false
0
0
0
0
0
0
0.473451
false
false
14
0c753a046677a6db88fd81080b772cfd9d3f13c1
12,730,283,074,060
411ff88058dc1c44636f5036fea93f070a68f3c2
/rokid-skill-sample-java/rokid-skill-kit-java/src/main/java/com/rokid/skill/dispatcher/SpeechletDispatcher.java
f92080cffd11c5de2cb9e2c16c6498174803ad61
[]
no_license
sukihxq/rokid-skill-sample
https://github.com/sukihxq/rokid-skill-sample
6b4d4bf367082e83e10fab43e027637cef3b90de
46ea3b17b7020bd05585a6f6a559cecec8e31b0e
refs/heads/master
2021-05-05T09:06:16.232000
2018-01-26T23:23:58
2018-01-26T23:23:58
119,232,207
1
0
null
true
2018-01-28T05:54:08
2018-01-28T05:54:07
2018-01-11T20:33:16
2018-01-26T23:23:59
6,207
0
0
0
null
false
null
package com.rokid.skill.dispatcher; import java.util.HashMap; import javax.servlet.http.HttpServletRequest; import com.rokid.skill.protocol.request.ReqRequest; import com.rokid.skill.protocol.request.context.application.media.ReqApplicationMedia; import com.rokid.skill.protocol.request.context.application.voice.ReqApplicationVoice; import com.rokid.skill.protocol.request.request.content.extra.media.ReqExtraMedia; import com.rokid.skill.protocol.request.request.content.extra.voice.ReqExtraVoice; import com.rokid.skill.protocol.request.request.content.slot.Slot; import com.rokid.skill.protocol.response.ResResponse; import com.rokid.skill.protocol.utils.ReqBasicInfo; /** * 所有请求事件的统一入口 * * @author Bassam * */ public interface SpeechletDispatcher { /** * * @param request * HttpServletRequest * @param reqRequest * 原始请求协议解析结果 * @param basicInfo * 处理后的基本请求信息 * @param attributes * Intent 请求中的Session里面的属性信息 * @param slots * Intent请求的 Slots信息 * @param mediaState * Intent请求的当前Skill的媒体状态信息 * @param voiceState * Intent请求的当前Skill的媒体语音状态信息 * @param mediaExtra * Event请求的媒体拓展信息 * @param voiceExtra * Event请求的Voice状态信息 */ public ResResponse dispatchSpeechletCall(HttpServletRequest request, ReqRequest reqRequest, ReqBasicInfo basicInfo, HashMap<String, Object> attributes, HashMap<String, Slot> slots, ReqApplicationMedia mediaState, ReqApplicationVoice voiceState, ReqExtraMedia mediaExtra, ReqExtraVoice voiceExtra) throws Exception; }
UTF-8
Java
1,772
java
SpeechletDispatcher.java
Java
[ { "context": "s.ReqBasicInfo;\n\n/**\n * 所有请求事件的统一入口\n * \n * @author Bassam\n *\n */\npublic interface SpeechletDispatcher ", "end": 711, "score": 0.7759897112846375, "start": 710, "tag": "NAME", "value": "B" }, { "context": "ReqBasicInfo;\n\n/**\n * 所有请求事件的统一入口\n * \n * @author Bas...
null
[]
package com.rokid.skill.dispatcher; import java.util.HashMap; import javax.servlet.http.HttpServletRequest; import com.rokid.skill.protocol.request.ReqRequest; import com.rokid.skill.protocol.request.context.application.media.ReqApplicationMedia; import com.rokid.skill.protocol.request.context.application.voice.ReqApplicationVoice; import com.rokid.skill.protocol.request.request.content.extra.media.ReqExtraMedia; import com.rokid.skill.protocol.request.request.content.extra.voice.ReqExtraVoice; import com.rokid.skill.protocol.request.request.content.slot.Slot; import com.rokid.skill.protocol.response.ResResponse; import com.rokid.skill.protocol.utils.ReqBasicInfo; /** * 所有请求事件的统一入口 * * @author Bassam * */ public interface SpeechletDispatcher { /** * * @param request * HttpServletRequest * @param reqRequest * 原始请求协议解析结果 * @param basicInfo * 处理后的基本请求信息 * @param attributes * Intent 请求中的Session里面的属性信息 * @param slots * Intent请求的 Slots信息 * @param mediaState * Intent请求的当前Skill的媒体状态信息 * @param voiceState * Intent请求的当前Skill的媒体语音状态信息 * @param mediaExtra * Event请求的媒体拓展信息 * @param voiceExtra * Event请求的Voice状态信息 */ public ResResponse dispatchSpeechletCall(HttpServletRequest request, ReqRequest reqRequest, ReqBasicInfo basicInfo, HashMap<String, Object> attributes, HashMap<String, Slot> slots, ReqApplicationMedia mediaState, ReqApplicationVoice voiceState, ReqExtraMedia mediaExtra, ReqExtraVoice voiceExtra) throws Exception; }
1,772
0.745922
0.745922
46
33.652172
30.205252
116
false
false
0
0
0
0
0
0
1.086957
false
false
14
5db299b0b47a0a972ecd1f793dc714355c26b2c5
4,492,535,802,276
949cd4c756fdf471555f7a64b397fe2febba8507
/src/main/java/Main.java
2848995951cae4893ecc9df6d0e8cad59de38ee7
[]
no_license
dawidworobiec/Converter
https://github.com/dawidworobiec/Converter
590d32631ad656341e47ef65c2c384658d449699
10f9560f033c75e89611d9c77a26151c9996cf3c
refs/heads/master
2020-07-03T00:33:55.479000
2017-01-27T20:03:59
2017-01-27T20:03:59
74,207,935
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
import app.Converter; import java.io.IOException; import java.util.List; /** * Created by Razios on 19.11.2016. */ public class Main { public static void main (String[] args) { Converter converter = new Converter(); try{ List<String> list; list = converter.readPointsData(); converter.writePointsData(list); converter.createDataSourceFile(); } catch(IOException e) { System.out.println("Error reading file: " + e.getMessage()); } } }
UTF-8
Java
544
java
Main.java
Java
[ { "context": "ception;\nimport java.util.List;\n\n/**\n * Created by Razios on 19.11.2016.\n */\npublic class Main {\n\n publi", "end": 99, "score": 0.9997994303703308, "start": 93, "tag": "NAME", "value": "Razios" } ]
null
[]
import app.Converter; import java.io.IOException; import java.util.List; /** * Created by Razios on 19.11.2016. */ public class Main { public static void main (String[] args) { Converter converter = new Converter(); try{ List<String> list; list = converter.readPointsData(); converter.writePointsData(list); converter.createDataSourceFile(); } catch(IOException e) { System.out.println("Error reading file: " + e.getMessage()); } } }
544
0.588235
0.573529
24
21.666666
19.808809
72
false
false
0
0
0
0
0
0
0.375
false
false
14
b007ece08a3f032767dae22f0db9ff9305ce4a1b
32,813,550,144,778
2df7b219c4ed93ca112fd8e18be498274998d82e
/Baekjoon/Baek_1963_소수경로.java
6bf05ee03e85328dc4647e3d9405dd1def6cc95f
[]
no_license
godhpjh/ALGORITHM
https://github.com/godhpjh/ALGORITHM
95ae0226633befd870871092bd61a6ed3c0912be
4cac9490d02b73a57c23ab5197390cbae8bbd384
refs/heads/master
2021-07-16T14:32:18.365000
2020-09-07T08:09:34
2020-09-07T08:09:34
209,449,775
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.PriorityQueue; public class Baek_1963_소수경로 { static final int INF = 987654321; static int ans; static String[] AB; private static class Pos implements Comparable<Pos>{ String num; int count; public Pos(String num, int count) { super(); this.num = num; this.count = count; } @Override public int compareTo(Pos p) { return this.count - p.count; } } public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); int T = Integer.parseInt(in.readLine()); for(int t=1; t<=T; ++t) { // 1. 입력 및 초기화 ans = INF; AB = in.readLine().split(" "); // 2. 완탐 bfs(); // 3. 정답 출력 if(ans == INF) sb.append("Impossible").append('\n'); else sb.append(ans).append('\n'); } System.out.println(sb.toString().trim()); } public static void bfs() { PriorityQueue<Pos> que = new PriorityQueue<Pos>(); boolean[] visited = new boolean[10000]; que.offer(new Pos(AB[0], 0)); visited[Integer.parseInt(AB[0])] = true; while(!que.isEmpty()) { Pos p = que.poll(); String n = p.num; if(n.equals(AB[1])) { ans = p.count; break; } // 각 자릿수마다 비교 String prev="", next="", value=""; for(int i=0; i<4; i++) { // 4자리 if(i>0) prev = n.substring(0, i); String snum = n.substring(i, i+1); if(i<4) next = n.substring(i+1); // 0 ~ 9까지 대입 for(int j=0; j<=9; j++) { if(i==0 && j==0) continue; // 천의자리는 0을 채우지않는다. if(Integer.parseInt(snum) == j) continue; // 같은번호 패스 // 1) 바꾸기 value = prev + j + next; int val = Integer.parseInt(value); // 2) 소수확인 if(!visited[val] && isPrime(val)) { visited[val] = true; que.offer(new Pos(value, p.count+1)); } } } } // while } // bfs // 소수구하기 (에라토스테네스의 체) public static boolean isPrime(int num) { int end = (int) Math.sqrt(num); for(int i=2; i<=end; i++) { if(num % i == 0) return false; } return true; } }
UTF-8
Java
2,307
java
Baek_1963_소수경로.java
Java
[]
null
[]
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.PriorityQueue; public class Baek_1963_소수경로 { static final int INF = 987654321; static int ans; static String[] AB; private static class Pos implements Comparable<Pos>{ String num; int count; public Pos(String num, int count) { super(); this.num = num; this.count = count; } @Override public int compareTo(Pos p) { return this.count - p.count; } } public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); int T = Integer.parseInt(in.readLine()); for(int t=1; t<=T; ++t) { // 1. 입력 및 초기화 ans = INF; AB = in.readLine().split(" "); // 2. 완탐 bfs(); // 3. 정답 출력 if(ans == INF) sb.append("Impossible").append('\n'); else sb.append(ans).append('\n'); } System.out.println(sb.toString().trim()); } public static void bfs() { PriorityQueue<Pos> que = new PriorityQueue<Pos>(); boolean[] visited = new boolean[10000]; que.offer(new Pos(AB[0], 0)); visited[Integer.parseInt(AB[0])] = true; while(!que.isEmpty()) { Pos p = que.poll(); String n = p.num; if(n.equals(AB[1])) { ans = p.count; break; } // 각 자릿수마다 비교 String prev="", next="", value=""; for(int i=0; i<4; i++) { // 4자리 if(i>0) prev = n.substring(0, i); String snum = n.substring(i, i+1); if(i<4) next = n.substring(i+1); // 0 ~ 9까지 대입 for(int j=0; j<=9; j++) { if(i==0 && j==0) continue; // 천의자리는 0을 채우지않는다. if(Integer.parseInt(snum) == j) continue; // 같은번호 패스 // 1) 바꾸기 value = prev + j + next; int val = Integer.parseInt(value); // 2) 소수확인 if(!visited[val] && isPrime(val)) { visited[val] = true; que.offer(new Pos(value, p.count+1)); } } } } // while } // bfs // 소수구하기 (에라토스테네스의 체) public static boolean isPrime(int num) { int end = (int) Math.sqrt(num); for(int i=2; i<=end; i++) { if(num % i == 0) return false; } return true; } }
2,307
0.589673
0.568465
90
23.1
17.546795
83
false
false
0
0
0
0
0
0
3.133333
false
false
14
242d401edf6c3bde7e47653fce19e4c5b3ce49f0
19,112,604,482,395
65c41f96a13b9e300122e5a3d2bacfdca554c00d
/dependency-inijection/src/main/java/org/kevin/SecondBreakfastTobacco.java
86a2af2a76bced4f26993d9dc251ae7e369e9d7c
[]
no_license
lk96/patterns-java
https://github.com/lk96/patterns-java
f63d28387e75278d3b9650ddc353a46e669ed182
7bf055089b7ccf5a1e0ee11a3fd78f8305b93988
refs/heads/main
2023-05-03T02:09:18.887000
2021-05-17T17:11:36
2021-05-17T17:11:36
359,070,453
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.kevin; public class SecondBreakfastTobacco extends Tobacco{ }
UTF-8
Java
75
java
SecondBreakfastTobacco.java
Java
[]
null
[]
package org.kevin; public class SecondBreakfastTobacco extends Tobacco{ }
75
0.826667
0.826667
4
17.75
21.028255
52
false
false
0
0
0
0
0
0
0.25
false
false
14
2db58ea60306145e20473555a25a736f3121fec7
9,491,877,787,979
6d55d7b5aa203e2bec55db33f1d4f516bd852193
/Project/src-CVM/src/edu/citadel/cvm/assembler/ast/InstructionDEFINT.java
e4964017e55676814d901b6a17ca8121fb0d7d17
[ "Unlicense" ]
permissive
SoftMoore/CPRL
https://github.com/SoftMoore/CPRL
991f14b9d0f36941a9720277b186cbbf53de5989
1ef55ca116a540fa1a38996b58cf0120f1238ee8
refs/heads/master
2022-10-24T10:48:41.256000
2022-10-04T13:03:09
2022-10-04T13:03:09
212,973,330
5
6
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.citadel.cvm.assembler.ast; import edu.citadel.compiler.ConstraintException; import edu.citadel.cvm.Constants; import edu.citadel.cvm.assembler.Symbol; import edu.citadel.cvm.assembler.Token; import java.util.List; import java.io.IOException; /** * This class implements the abstract syntax tree for the assembly * language pseudo instruction DEFINT. */ public class InstructionDEFINT extends InstructionOneArg { public InstructionDEFINT(List<Token> labels, Token opCode, Token arg) { super(labels, opCode, arg); } public void assertOpCode() { assertOpCode(Symbol.DEFINT); } public void checkArgType() throws ConstraintException { defineIdAddress(getArg(), Constants.BYTES_PER_INTEGER); checkArgType(Symbol.identifier); } /** * Must be overridden for pseudo opcodes since the opcode * doesn't actually occupy space in memory */ @Override public int getSize() { return 0; } /** * Abstract method -- must be overridden even though * it plays no significant role for pseudo opcodes. */ @Override protected int getArgSize() { return Constants.BYTES_PER_INTEGER; } @Override public void emit() throws IOException { // nothing to emit for pseudo opcode } }
UTF-8
Java
1,386
java
InstructionDEFINT.java
Java
[]
null
[]
package edu.citadel.cvm.assembler.ast; import edu.citadel.compiler.ConstraintException; import edu.citadel.cvm.Constants; import edu.citadel.cvm.assembler.Symbol; import edu.citadel.cvm.assembler.Token; import java.util.List; import java.io.IOException; /** * This class implements the abstract syntax tree for the assembly * language pseudo instruction DEFINT. */ public class InstructionDEFINT extends InstructionOneArg { public InstructionDEFINT(List<Token> labels, Token opCode, Token arg) { super(labels, opCode, arg); } public void assertOpCode() { assertOpCode(Symbol.DEFINT); } public void checkArgType() throws ConstraintException { defineIdAddress(getArg(), Constants.BYTES_PER_INTEGER); checkArgType(Symbol.identifier); } /** * Must be overridden for pseudo opcodes since the opcode * doesn't actually occupy space in memory */ @Override public int getSize() { return 0; } /** * Abstract method -- must be overridden even though * it plays no significant role for pseudo opcodes. */ @Override protected int getArgSize() { return Constants.BYTES_PER_INTEGER; } @Override public void emit() throws IOException { // nothing to emit for pseudo opcode } }
1,386
0.655123
0.654401
65
20.323076
21.261816
73
false
false
0
0
0
0
0
0
0.276923
false
false
14
e0e0b3413b5011822c028a5ef50d8dfe04ecd20d
5,875,515,278,616
9ead895536d736a7a3558f85efcfb63500047847
/AcademyBoxIt/src/main/java/es/gonzalez/AcademyBoxIt/service/impl/UserSvcImpl.java
a6a60884c45ecc191dc1fec62e94539ad64e0d3e
[]
no_license
Roperbreak/PabloGonzalez
https://github.com/Roperbreak/PabloGonzalez
253ee4a28f6889b79c55ad4c99a4ae858d220821
05ae9474fe5ee2741041e93e9cba243c7f4d954b
refs/heads/master
2020-04-05T13:24:42.446000
2018-12-19T22:37:20
2018-12-19T22:37:20
156,872,821
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package es.gonzalez.AcademyBoxIt.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import es.gonzalez.AcademyBoxIt.model.User; import es.gonzalez.AcademyBoxIt.model.UserType; import es.gonzalez.AcademyBoxIt.model.dao.UserDao; import es.gonzalez.AcademyBoxIt.model.dao.exceptions.UserDaoException; import es.gonzalez.AcademyBoxIt.service.UserSvc; import es.gonzalez.AcademyBoxIt.service.exceptions.UserSvcException; @Service @Transactional public class UserSvcImpl implements UserSvc { @Autowired private UserDao userDao; // public static String fecha() { // Date now = new Date(); // SimpleDateFormat formateador = new SimpleDateFormat("dd-MM-yyyy"); // return formateador.format(now); // } @Override public Double calculateMark(Double mark, Double gauss) { // TODO Auto-generated method stub return null; } @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) @Override public User login(String dni, String password) throws UserSvcException { User res = null; try { res = userDao.userLogin(dni, password); } catch (Exception ex) { throw new UserSvcException(ex); } return res; } @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) @Override public List<User> listUsers(UserType type) throws UserSvcException { List<User> list = null; try { list = userDao.findbyName(); } catch (Exception ex) { throw new UserSvcException(ex); } return list; } @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) @Override public User findById(Integer id) throws UserSvcException { User res = null; try { res = userDao.findById(id); } catch (Exception ex) { throw new UserSvcException(ex); } return res; } @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) @Override public void deleteUser(User user) throws UserSvcException { try { userDao.deleteUser(user); } catch (UserDaoException e) { throw new UserSvcException(e); } } @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) @Override public void updateUser(User user) throws UserSvcException { try { userDao.updateUser(user); } catch (UserDaoException e) { throw new UserSvcException(e); } } @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) @Override public void saveUser(User user) throws UserSvcException { try { if (user.getUsertype()==null) { UserType usertype = new UserType(); usertype.setIdtype(1); usertype.setTypename("User"); user.setUsertype(usertype); } userDao.saveUser(user); } catch (UserDaoException e) { throw new UserSvcException(e); } } @Override public void changePwd(String password, User user) throws UserSvcException { // TODO Auto-generated method stub } }
UTF-8
Java
3,258
java
UserSvcImpl.java
Java
[]
null
[]
package es.gonzalez.AcademyBoxIt.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import es.gonzalez.AcademyBoxIt.model.User; import es.gonzalez.AcademyBoxIt.model.UserType; import es.gonzalez.AcademyBoxIt.model.dao.UserDao; import es.gonzalez.AcademyBoxIt.model.dao.exceptions.UserDaoException; import es.gonzalez.AcademyBoxIt.service.UserSvc; import es.gonzalez.AcademyBoxIt.service.exceptions.UserSvcException; @Service @Transactional public class UserSvcImpl implements UserSvc { @Autowired private UserDao userDao; // public static String fecha() { // Date now = new Date(); // SimpleDateFormat formateador = new SimpleDateFormat("dd-MM-yyyy"); // return formateador.format(now); // } @Override public Double calculateMark(Double mark, Double gauss) { // TODO Auto-generated method stub return null; } @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) @Override public User login(String dni, String password) throws UserSvcException { User res = null; try { res = userDao.userLogin(dni, password); } catch (Exception ex) { throw new UserSvcException(ex); } return res; } @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) @Override public List<User> listUsers(UserType type) throws UserSvcException { List<User> list = null; try { list = userDao.findbyName(); } catch (Exception ex) { throw new UserSvcException(ex); } return list; } @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) @Override public User findById(Integer id) throws UserSvcException { User res = null; try { res = userDao.findById(id); } catch (Exception ex) { throw new UserSvcException(ex); } return res; } @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) @Override public void deleteUser(User user) throws UserSvcException { try { userDao.deleteUser(user); } catch (UserDaoException e) { throw new UserSvcException(e); } } @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) @Override public void updateUser(User user) throws UserSvcException { try { userDao.updateUser(user); } catch (UserDaoException e) { throw new UserSvcException(e); } } @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) @Override public void saveUser(User user) throws UserSvcException { try { if (user.getUsertype()==null) { UserType usertype = new UserType(); usertype.setIdtype(1); usertype.setTypename("User"); user.setUsertype(usertype); } userDao.saveUser(user); } catch (UserDaoException e) { throw new UserSvcException(e); } } @Override public void changePwd(String password, User user) throws UserSvcException { // TODO Auto-generated method stub } }
3,258
0.710252
0.709945
134
22.313433
24.802629
82
false
false
0
0
0
0
0
0
1.462687
false
false
14
4f62a1cb2bbedd575a584c863c60384dc26d85a6
23,441,931,503,017
44f904a6d7d8b191c062cdcb0c0c5e165357053e
/src/com/dkn199/encryptdecrypt/algorithms/ShiftEncryptionAlgorithm.java
b543b8563beeb99f32de06beec9a5ce326fd3b82
[]
no_license
rp199/encryption-decryption
https://github.com/rp199/encryption-decryption
ee1fab22b7637ed3914f54d17ae85922fe001ed7
12f7e315db7beede3e968b5c6aa02c792c0de1d4
refs/heads/master
2020-06-19T13:55:03.236000
2019-07-13T18:03:08
2019-07-13T18:03:08
196,733,979
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.dkn199.encryptdecrypt.algorithms; public class ShiftEncryptionAlgorithm extends EncryptionAlgorithm{ public ShiftEncryptionAlgorithm(int shift){ super(shift); } @Override public String encrypt(String text) { String cypher =""; for(char c: text.toCharArray()){ char shiftedChar = c; if(c >= 'a' && c<='z'){ shiftedChar += this.getShift(); if(c + this.getShift() > 'z'){ shiftedChar = (char)(shiftedChar -'z' + 'a' - 1); } } cypher += shiftedChar; } return cypher; } @Override public String decrypt(String text) { String cypher =""; for(char c: text.toCharArray()){ char shiftedChar = c; if(c >= 'a' && c<='z'){ shiftedChar -= this.getShift(); if(shiftedChar < 'a'){ shiftedChar = (char)('z' - ('a' - shiftedChar) + 1); } } cypher += shiftedChar; } return cypher; } }
UTF-8
Java
1,113
java
ShiftEncryptionAlgorithm.java
Java
[]
null
[]
package com.dkn199.encryptdecrypt.algorithms; public class ShiftEncryptionAlgorithm extends EncryptionAlgorithm{ public ShiftEncryptionAlgorithm(int shift){ super(shift); } @Override public String encrypt(String text) { String cypher =""; for(char c: text.toCharArray()){ char shiftedChar = c; if(c >= 'a' && c<='z'){ shiftedChar += this.getShift(); if(c + this.getShift() > 'z'){ shiftedChar = (char)(shiftedChar -'z' + 'a' - 1); } } cypher += shiftedChar; } return cypher; } @Override public String decrypt(String text) { String cypher =""; for(char c: text.toCharArray()){ char shiftedChar = c; if(c >= 'a' && c<='z'){ shiftedChar -= this.getShift(); if(shiftedChar < 'a'){ shiftedChar = (char)('z' - ('a' - shiftedChar) + 1); } } cypher += shiftedChar; } return cypher; } }
1,113
0.475292
0.4708
40
26.825001
19.529322
72
false
false
0
0
0
0
0
0
0.35
false
false
14
33d946267167d034859a78502a99e16ecdc7aafc
11,605,001,691,033
03898c98b1605f13cb41c8bca916694cb1208fcd
/LongestSubOrder.java
e167f9bb18da5c9c0b36edfa3470270a6f3c83e4
[]
no_license
muyesou/liuqiang
https://github.com/muyesou/liuqiang
d822d24f399e8bffc28c4b6ce7d4d2847e1069bc
c97d95b9040dc23521fccaf8c8fc28f32a65a21e
refs/heads/master
2021-06-14T16:35:52.314000
2021-05-15T13:34:09
2021-05-15T13:34:09
189,752,918
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.demo.algorithm; public class LongestSubOrder { public static void main(String[] args) { int[] arr = {2, 1, 5, 3, 6, 4, 8, 9, 7}; int[] arr1 = {1, 2, 4, 8, 9, 11, 23, 77, 88}; // int index = getIndex(arr1, 0, arr.length - 1, 99); int max = getMax(arr); System.out.println(); } public static int getMax(int[] arr) { int[] ends = new int[arr.length]; int end = 0; int[] result = new int[arr.length]; result[0] = 1; ends[0] = arr[0]; for (int i = 1; i < arr.length; i++) { int cur = arr[i]; int min = getIndex(ends, 0, end, cur); if (min == end) {//没有比他大的 end++; ends[end] = cur; result[i] = end + 1; } else { ends[min + 1] = cur; result[i] = min + 1 + 1; } } return getMaxNum(result); } private static int getMaxNum(int []arr){ int result=0; for (int i = 0; i <arr.length ; i++) { result=arr[i]>result?arr[i]:result; } return result; } private static int[] getResult(int[] arr,int []dp) { int []result=new int[arr.length]; int res=0; int pre=arr[0]; result[0]=arr[0]; for (int i = 1; i <dp.length ; i++) { if(dp[i]==pre){ result[res]=arr[i]; }else{ if(dp[i]>pre) { result[++res] = arr[i]; } else{ result[i-dp[i]]=arr[i]; } } pre=dp[i]; } return result; } //找到刚好比他小的 private static int getIndex(int[] arr, int start, int end, int target) { if (start > end) { return -1; } if (start == end) { return arr[start] > target ? start - 1 : start; } if (end - start == 1) { return arr[start] > target ? start - 1 : arr[end] > target ? start : end; } int mid = start + (end - start) / 2; if (arr[mid] < target) { return getIndex(arr, mid + 1, end, target); } else if (arr[mid] > target) { return getIndex(arr, start, mid, target); } else { return mid - 1; } } }
UTF-8
Java
2,418
java
LongestSubOrder.java
Java
[]
null
[]
package com.example.demo.algorithm; public class LongestSubOrder { public static void main(String[] args) { int[] arr = {2, 1, 5, 3, 6, 4, 8, 9, 7}; int[] arr1 = {1, 2, 4, 8, 9, 11, 23, 77, 88}; // int index = getIndex(arr1, 0, arr.length - 1, 99); int max = getMax(arr); System.out.println(); } public static int getMax(int[] arr) { int[] ends = new int[arr.length]; int end = 0; int[] result = new int[arr.length]; result[0] = 1; ends[0] = arr[0]; for (int i = 1; i < arr.length; i++) { int cur = arr[i]; int min = getIndex(ends, 0, end, cur); if (min == end) {//没有比他大的 end++; ends[end] = cur; result[i] = end + 1; } else { ends[min + 1] = cur; result[i] = min + 1 + 1; } } return getMaxNum(result); } private static int getMaxNum(int []arr){ int result=0; for (int i = 0; i <arr.length ; i++) { result=arr[i]>result?arr[i]:result; } return result; } private static int[] getResult(int[] arr,int []dp) { int []result=new int[arr.length]; int res=0; int pre=arr[0]; result[0]=arr[0]; for (int i = 1; i <dp.length ; i++) { if(dp[i]==pre){ result[res]=arr[i]; }else{ if(dp[i]>pre) { result[++res] = arr[i]; } else{ result[i-dp[i]]=arr[i]; } } pre=dp[i]; } return result; } //找到刚好比他小的 private static int getIndex(int[] arr, int start, int end, int target) { if (start > end) { return -1; } if (start == end) { return arr[start] > target ? start - 1 : start; } if (end - start == 1) { return arr[start] > target ? start - 1 : arr[end] > target ? start : end; } int mid = start + (end - start) / 2; if (arr[mid] < target) { return getIndex(arr, mid + 1, end, target); } else if (arr[mid] > target) { return getIndex(arr, start, mid, target); } else { return mid - 1; } } }
2,418
0.423013
0.400837
85
27.117647
18.422756
85
false
false
0
0
0
0
0
0
0.894118
false
false
14
096d9b658ad42a282991fd0866f64b789f9c7669
11,605,001,690,282
21c03cfe96e05f56be7a62412fba894ffbdbdb8a
/seat-planner/src/test/java/lt/lukasnakas/seatplanner/service/jms/ProducerServiceTest.java
21b0c69d039f6fd3fcf18c923fed1f4c84e19ab0
[]
no_license
lukasnakas/biuro-vietu-planavimas
https://github.com/lukasnakas/biuro-vietu-planavimas
735e34a9b5419763243ec27a5828879489858af0
a0a069a2caa2c2f9a8e9aeea59082790f27e7572
refs/heads/master
2023-04-26T02:06:24.456000
2021-05-26T12:30:26
2021-05-26T12:30:26
367,854,409
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package lt.lukasnakas.seatplanner.service.jms; import lt.lukasnakas.seatplanner.helper.FindSeatRequestResponseDataHelper; import lt.lukasnakas.seatplanner.model.exception.SearchActiveException; import lt.lukasnakas.seatplanner.service.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.springframework.jms.core.JmsTemplate; import static lt.lukasnakas.seatplanner.helper.FindSeatRequestResponseDataHelper.getFindSeatRequest; import static lt.lukasnakas.seatplanner.helper.FindSeatRequestResponseDataHelper.getStringFindSeatResponseMap; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.BDDMockito.given; import static org.mockito.MockitoAnnotations.initMocks; class ProducerServiceTest { @Mock TeamService teamService; @Mock RoomService roomService; @Mock JmsTemplate jmsTemplate; @Mock FloorService floorService; @Mock ConsumerService consumerService; @Mock OfficeService officeService; @Mock TeamRestrictionService teamRestrictionService; @InjectMocks private ProducerService producerService; @BeforeEach public void init() { initMocks(this); } @Test void shouldReturnSearchActiveException() { // given String errorMessage = "Search is currently active"; given(consumerService.getFindSeatResponseMap()) .willReturn(getStringFindSeatResponseMap (FindSeatRequestResponseDataHelper.getNonCompletedFindSeatResponse())); // when Exception exception = assertThrows(SearchActiveException.class, () -> { producerService.submitToSolver(getFindSeatRequest()); }); // then assertTrue(errorMessage.contains(exception.getMessage())); } }
UTF-8
Java
1,946
java
ProducerServiceTest.java
Java
[]
null
[]
package lt.lukasnakas.seatplanner.service.jms; import lt.lukasnakas.seatplanner.helper.FindSeatRequestResponseDataHelper; import lt.lukasnakas.seatplanner.model.exception.SearchActiveException; import lt.lukasnakas.seatplanner.service.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.springframework.jms.core.JmsTemplate; import static lt.lukasnakas.seatplanner.helper.FindSeatRequestResponseDataHelper.getFindSeatRequest; import static lt.lukasnakas.seatplanner.helper.FindSeatRequestResponseDataHelper.getStringFindSeatResponseMap; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.BDDMockito.given; import static org.mockito.MockitoAnnotations.initMocks; class ProducerServiceTest { @Mock TeamService teamService; @Mock RoomService roomService; @Mock JmsTemplate jmsTemplate; @Mock FloorService floorService; @Mock ConsumerService consumerService; @Mock OfficeService officeService; @Mock TeamRestrictionService teamRestrictionService; @InjectMocks private ProducerService producerService; @BeforeEach public void init() { initMocks(this); } @Test void shouldReturnSearchActiveException() { // given String errorMessage = "Search is currently active"; given(consumerService.getFindSeatResponseMap()) .willReturn(getStringFindSeatResponseMap (FindSeatRequestResponseDataHelper.getNonCompletedFindSeatResponse())); // when Exception exception = assertThrows(SearchActiveException.class, () -> { producerService.submitToSolver(getFindSeatRequest()); }); // then assertTrue(errorMessage.contains(exception.getMessage())); } }
1,946
0.749743
0.749743
66
28.484848
27.788837
110
false
false
0
0
0
0
0
0
0.454545
false
false
14
ac4facdc0358122f9f9c59f785624f0c4cbf131e
19,112,604,489,787
60f98f8ac9be24a573a7e8591ad26b9ccae9a4b3
/querydsl-jpa/src/main/java/com/mysema/query/jpa/hibernate/HibernateQuery.java
af6e17aa411c25b009f9d3a4f10268f3e0291d59
[]
no_license
dyokomizo/querydsl
https://github.com/dyokomizo/querydsl
6c881f3e80b8006d6edcd267f29c8414e27f4acb
2e5f1f2bcf956130bc825a4dec95b9d13626c786
refs/heads/master
2019-04-20T04:52:54.068000
2011-08-19T14:34:17
2011-08-19T14:34:17
2,227,535
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright (c) 2010 Mysema Ltd. * All rights reserved. * */ package com.mysema.query.jpa.hibernate; import org.hibernate.Session; import org.hibernate.StatelessSession; import com.mysema.query.DefaultQueryMetadata; import com.mysema.query.QueryMetadata; import com.mysema.query.jpa.JPQLQuery; import com.mysema.query.jpa.HQLTemplates; import com.mysema.query.jpa.JPQLTemplates; /** * HibernateQuery is the default implementation of the JPQLQuery interface for Hibernate * * @author tiwe * */ public final class HibernateQuery extends AbstractHibernateQuery<HibernateQuery> implements JPQLQuery{ /** * Creates a detached query * The query can be attached via the clone method */ public HibernateQuery() { super(NoSessionHolder.DEFAULT, HQLTemplates.DEFAULT, new DefaultQueryMetadata()); } /** * Creates a new Session bound query * * @param session */ public HibernateQuery(Session session) { super(new DefaultSessionHolder(session), HQLTemplates.DEFAULT, new DefaultQueryMetadata()); } /** * Creates a new Session bound query * * @param session */ public HibernateQuery(Session session, QueryMetadata metadata) { super(new DefaultSessionHolder(session), HQLTemplates.DEFAULT, metadata); } /** * Creates a new Session bound query * * @param session * @param templates */ public HibernateQuery(Session session, JPQLTemplates templates) { super(new DefaultSessionHolder(session), templates, new DefaultQueryMetadata()); } /** * Creates a new Stateless session bound query * * @param session */ public HibernateQuery(StatelessSession session) { super(new StatelessSessionHolder(session), HQLTemplates.DEFAULT, new DefaultQueryMetadata()); } /** * Creates a new Session bound query * * @param session * @param templates */ public HibernateQuery(SessionHolder session, JPQLTemplates templates) { super(session, templates, new DefaultQueryMetadata()); } /** * Creates a new Session bound query * * @param session * @param templates * @param metadata */ protected HibernateQuery(SessionHolder session, JPQLTemplates templates, QueryMetadata metadata) { super(session, templates, metadata); } /** * Clone the state of this query to a new HibernateQuery instance with the given Session * * @param session * @return */ public HibernateQuery clone(Session session){ return new HibernateQuery(new DefaultSessionHolder(session), getTemplates(), getMetadata().clone()); } }
UTF-8
Java
2,729
java
HibernateQuery.java
Java
[ { "context": "he JPQLQuery interface for Hibernate\n *\n * @author tiwe\n *\n */\npublic final class HibernateQuery extends ", "end": 500, "score": 0.9996416568756104, "start": 496, "tag": "USERNAME", "value": "tiwe" } ]
null
[]
/* * Copyright (c) 2010 Mysema Ltd. * All rights reserved. * */ package com.mysema.query.jpa.hibernate; import org.hibernate.Session; import org.hibernate.StatelessSession; import com.mysema.query.DefaultQueryMetadata; import com.mysema.query.QueryMetadata; import com.mysema.query.jpa.JPQLQuery; import com.mysema.query.jpa.HQLTemplates; import com.mysema.query.jpa.JPQLTemplates; /** * HibernateQuery is the default implementation of the JPQLQuery interface for Hibernate * * @author tiwe * */ public final class HibernateQuery extends AbstractHibernateQuery<HibernateQuery> implements JPQLQuery{ /** * Creates a detached query * The query can be attached via the clone method */ public HibernateQuery() { super(NoSessionHolder.DEFAULT, HQLTemplates.DEFAULT, new DefaultQueryMetadata()); } /** * Creates a new Session bound query * * @param session */ public HibernateQuery(Session session) { super(new DefaultSessionHolder(session), HQLTemplates.DEFAULT, new DefaultQueryMetadata()); } /** * Creates a new Session bound query * * @param session */ public HibernateQuery(Session session, QueryMetadata metadata) { super(new DefaultSessionHolder(session), HQLTemplates.DEFAULT, metadata); } /** * Creates a new Session bound query * * @param session * @param templates */ public HibernateQuery(Session session, JPQLTemplates templates) { super(new DefaultSessionHolder(session), templates, new DefaultQueryMetadata()); } /** * Creates a new Stateless session bound query * * @param session */ public HibernateQuery(StatelessSession session) { super(new StatelessSessionHolder(session), HQLTemplates.DEFAULT, new DefaultQueryMetadata()); } /** * Creates a new Session bound query * * @param session * @param templates */ public HibernateQuery(SessionHolder session, JPQLTemplates templates) { super(session, templates, new DefaultQueryMetadata()); } /** * Creates a new Session bound query * * @param session * @param templates * @param metadata */ protected HibernateQuery(SessionHolder session, JPQLTemplates templates, QueryMetadata metadata) { super(session, templates, metadata); } /** * Clone the state of this query to a new HibernateQuery instance with the given Session * * @param session * @return */ public HibernateQuery clone(Session session){ return new HibernateQuery(new DefaultSessionHolder(session), getTemplates(), getMetadata().clone()); } }
2,729
0.67424
0.672774
101
26.019802
29.223949
108
false
false
0
0
0
0
0
0
0.366337
false
false
14
ba128d0cad2bde6a1eb7c0a6f18322f394ab8c3e
19,112,604,490,033
19a0b6c93eeb0a87025f34408ff8fafa8b479eb1
/crailway/db/com/webul/bean/Company.java
5467b6b8ef41ae4d94dd3a64fec307b5c0c7aab5
[]
no_license
z2374105607/02.rebimyyjk
https://github.com/z2374105607/02.rebimyyjk
8b496845102c6a662f2052746149b2ad34d8036c
99286b7ee1d286237b9f8ef3820ab210d6a2ae29
refs/heads/master
2020-09-30T15:09:59.069000
2019-12-11T08:46:59
2019-12-11T08:46:59
227,312,840
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.webul.bean; import java.io.Serializable; import java.math.BigDecimal; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "COMPANY") public class Company implements Serializable{ /** * */ private static final long serialVersionUID = 1L; @Id @GeneratedValue private BigDecimal ID; private String FCOMPANY; private String SCOMPANY; private String FCOMCODE; private String SCOMCODE; private String PARENTID; private String YEAR; private String NUM; public BigDecimal getID() { return ID; } public void setID(BigDecimal iD) { ID = iD; } public String getFCOMPANY() { return FCOMPANY; } public void setFCOMPANY(String fCOMPANY) { FCOMPANY = fCOMPANY; } public String getSCOMPANY() { return SCOMPANY; } public void setSCOMPANY(String sCOMPANY) { SCOMPANY = sCOMPANY; } public String getFCOMCODE() { return FCOMCODE; } public void setFCOMCODE(String fCOMCODE) { FCOMCODE = fCOMCODE; } public String getSCOMCODE() { return SCOMCODE; } public void setSCOMCODE(String sCOMCODE) { SCOMCODE = sCOMCODE; } public String getPARENTID() { return PARENTID; } public void setPARENTID(String pARENTID) { PARENTID = pARENTID; } public String getYEAR() { return YEAR; } public void setYEAR(String yEAR) { YEAR = yEAR; } public String getNUM() { return NUM; } public void setNUM(String nUM) { NUM = nUM; } }
UTF-8
Java
1,490
java
Company.java
Java
[]
null
[]
package com.webul.bean; import java.io.Serializable; import java.math.BigDecimal; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "COMPANY") public class Company implements Serializable{ /** * */ private static final long serialVersionUID = 1L; @Id @GeneratedValue private BigDecimal ID; private String FCOMPANY; private String SCOMPANY; private String FCOMCODE; private String SCOMCODE; private String PARENTID; private String YEAR; private String NUM; public BigDecimal getID() { return ID; } public void setID(BigDecimal iD) { ID = iD; } public String getFCOMPANY() { return FCOMPANY; } public void setFCOMPANY(String fCOMPANY) { FCOMPANY = fCOMPANY; } public String getSCOMPANY() { return SCOMPANY; } public void setSCOMPANY(String sCOMPANY) { SCOMPANY = sCOMPANY; } public String getFCOMCODE() { return FCOMCODE; } public void setFCOMCODE(String fCOMCODE) { FCOMCODE = fCOMCODE; } public String getSCOMCODE() { return SCOMCODE; } public void setSCOMCODE(String sCOMCODE) { SCOMCODE = sCOMCODE; } public String getPARENTID() { return PARENTID; } public void setPARENTID(String pARENTID) { PARENTID = pARENTID; } public String getYEAR() { return YEAR; } public void setYEAR(String yEAR) { YEAR = yEAR; } public String getNUM() { return NUM; } public void setNUM(String nUM) { NUM = nUM; } }
1,490
0.724161
0.72349
78
18.102564
13.957435
49
false
false
0
0
0
0
0
0
1.423077
false
false
14
07d53f0de63b73fe1bf0bee6ca1b53454250b4d8
9,216,999,883,047
a538f04214b8a502e13229bc7d82c045af6dcd84
/src/main/java/me/xenyor/effects/InventoryManager/EffectsOpenInv.java
39819703b7125bcf6d154a71907a2b3ae6f9749d
[ "MIT" ]
permissive
xenyor/Effects
https://github.com/xenyor/Effects
689ad8659cc104a16428809e0e8ecd2d0002cf4d
1b81f39aaa3ac336047c65d9d434d7fd59b805b7
refs/heads/master
2020-07-21T11:41:50.921000
2020-04-05T21:35:21
2020-04-05T21:35:21
206,853,571
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package me.xenyor.effects.InventoryManager; import me.xenyor.effects.Main.EffectsMain; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class EffectsOpenInv implements CommandExecutor { private static final String noperms = EffectsMain.getCustomConfig().getString("plugin-no-permission"); @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] strings) { if (cmd.getName().equalsIgnoreCase("effects")) { Player player = (Player) sender; if (player.hasPermission("effects.menu") || player.hasPermission("effects.*")) { EffectsInv.openInventory(player); } else { player.sendMessage(ChatColor.translateAlternateColorCodes('&', noperms)); } return true; } return true; } }
UTF-8
Java
981
java
EffectsOpenInv.java
Java
[]
null
[]
package me.xenyor.effects.InventoryManager; import me.xenyor.effects.Main.EffectsMain; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class EffectsOpenInv implements CommandExecutor { private static final String noperms = EffectsMain.getCustomConfig().getString("plugin-no-permission"); @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] strings) { if (cmd.getName().equalsIgnoreCase("effects")) { Player player = (Player) sender; if (player.hasPermission("effects.menu") || player.hasPermission("effects.*")) { EffectsInv.openInventory(player); } else { player.sendMessage(ChatColor.translateAlternateColorCodes('&', noperms)); } return true; } return true; } }
981
0.687054
0.687054
26
36.73077
30.586018
106
false
false
0
0
0
0
0
0
0.730769
false
false
14
58a08e6296ffd65b44c9400bb3de03140d74cc30
24,704,651,912,671
9d1167c51f7e9d723a4c100fef76fa3e4e213d51
/backend/src/main/java/com/opensource/todo/project/ProjectService.java
363f77a4b4100e88ab870a07e1e69a04350a4465
[]
no_license
sofiane-benmahiddine/To-Do
https://github.com/sofiane-benmahiddine/To-Do
d06507f28595d229db7eadd43eb95fc27b59beb3
96e30ac1708da1455c5b752a9bc85bd65ed00004
refs/heads/master
2023-07-14T18:51:59.989000
2021-08-28T22:08:31
2021-08-28T22:08:31
369,017,236
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.opensource.todo.project; import com.google.common.collect.ImmutableList; import com.opensource.todo.errors.exceptions.InvalidDateValueException; import com.opensource.todo.errors.exceptions.ProjectAlreadyExistsException; import com.opensource.todo.errors.exceptions.ProjectNotFoundException; import com.opensource.todo.user.models.User; import com.opensource.todo.user.services.UserService; import com.opensource.todo.user.utils.UserUtils; import lombok.RequiredArgsConstructor; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Service; import java.util.List; import java.util.Set; @Service @RequiredArgsConstructor public class ProjectService { private final ProjectRepository projectRepository; private final UserService userService; private final UserUtils userUtils; public List<Project> getAllProjects() { return ImmutableList.copyOf(projectRepository.findAll()); } public Project getProjectById(String id) { return projectRepository .findById(id) .orElseThrow(() -> new ProjectNotFoundException("Project with id " + id + " not found")); } @PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_MANAGER')") public Project addProject(Project project) { isProjectValid(project); return projectRepository.save(project); } @PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_MANAGER')") public Project editProject(String id, Project newProject) { Project project = getProjectById(id); Long projectManagerId = project.getCreatedBy(); userUtils.userAccessFilter(projectManagerId); isProjectValid(newProject, project); if (newProject.getProjectName() != null) project.setProjectName(newProject.getProjectName()); if (newProject.getStartDate() != null) project.setStartDate(newProject.getStartDate()); if (newProject.getTargetEndDate() != null) project.setTargetEndDate(newProject.getTargetEndDate()); if (newProject.getActualEndDate() != null) project.setActualEndDate(newProject.getActualEndDate()); return projectRepository.save(project); } @PreAuthorize("hasRole('ROLE_MANAGER') or hasRole('ROLE_ADMIN')") public void removeProject(String id) { Project project = getProjectById(id); Long projectManagerId = project.getCreatedBy(); userUtils.userAccessFilter(projectManagerId); projectRepository.deleteById(id); } @PreAuthorize("hasRole('ROLE_MANAGER') or hasRole('ROLE_ADMIN')") public void manageProjectUsers(Long userId, String projectId, Operation operation) { Project project = getProjectById(projectId); Long projectManagerId = project.getCreatedBy(); userUtils.userAccessFilter(projectManagerId); User user = userService.getUserById(userId); Set<User> projectUsers = project.getUsers(); if (operation == Operation.ADD) { projectUsers.add(user); } else { projectUsers.remove(user); } project.setUsers(projectUsers); projectRepository.save(project); } @PreAuthorize("hasRole('ROLE_MANAGER') or hasRole('ROLE_ADMIN')") public void removeUserFromProject(Long UserId, String ProjectId) { } public void isProjectValid(Project project) { if (projectRepository.existsByProjectName(project.getProjectName())) { throw new ProjectAlreadyExistsException("project with the same name exists already"); } if (project.getTargetEndDate() != null && project.getStartDate() != null) if (project.getTargetEndDate().isBefore(project.getStartDate())) { throw new InvalidDateValueException("'End date' must be more recent than 'Start date'"); } } public void isProjectValid(Project newProject, Project oldProject) { if (projectRepository.existsByProjectName(newProject.getProjectName()) && !oldProject.getProjectName().equals(newProject.getProjectName())) { throw new ProjectAlreadyExistsException("project with the same name exists already"); } if (newProject.getTargetEndDate() != null && newProject.getStartDate() != null) if (newProject.getTargetEndDate().isBefore(newProject.getStartDate())) { throw new InvalidDateValueException("'End date' must be more recent than 'Start date'"); } if (newProject.getActualEndDate() != null && newProject.getStartDate() != null) if (newProject.getActualEndDate().isBefore(newProject.getStartDate())) { throw new InvalidDateValueException("'Actual end date' must be more recent than 'Start date'"); } } }
UTF-8
Java
4,850
java
ProjectService.java
Java
[]
null
[]
package com.opensource.todo.project; import com.google.common.collect.ImmutableList; import com.opensource.todo.errors.exceptions.InvalidDateValueException; import com.opensource.todo.errors.exceptions.ProjectAlreadyExistsException; import com.opensource.todo.errors.exceptions.ProjectNotFoundException; import com.opensource.todo.user.models.User; import com.opensource.todo.user.services.UserService; import com.opensource.todo.user.utils.UserUtils; import lombok.RequiredArgsConstructor; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Service; import java.util.List; import java.util.Set; @Service @RequiredArgsConstructor public class ProjectService { private final ProjectRepository projectRepository; private final UserService userService; private final UserUtils userUtils; public List<Project> getAllProjects() { return ImmutableList.copyOf(projectRepository.findAll()); } public Project getProjectById(String id) { return projectRepository .findById(id) .orElseThrow(() -> new ProjectNotFoundException("Project with id " + id + " not found")); } @PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_MANAGER')") public Project addProject(Project project) { isProjectValid(project); return projectRepository.save(project); } @PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_MANAGER')") public Project editProject(String id, Project newProject) { Project project = getProjectById(id); Long projectManagerId = project.getCreatedBy(); userUtils.userAccessFilter(projectManagerId); isProjectValid(newProject, project); if (newProject.getProjectName() != null) project.setProjectName(newProject.getProjectName()); if (newProject.getStartDate() != null) project.setStartDate(newProject.getStartDate()); if (newProject.getTargetEndDate() != null) project.setTargetEndDate(newProject.getTargetEndDate()); if (newProject.getActualEndDate() != null) project.setActualEndDate(newProject.getActualEndDate()); return projectRepository.save(project); } @PreAuthorize("hasRole('ROLE_MANAGER') or hasRole('ROLE_ADMIN')") public void removeProject(String id) { Project project = getProjectById(id); Long projectManagerId = project.getCreatedBy(); userUtils.userAccessFilter(projectManagerId); projectRepository.deleteById(id); } @PreAuthorize("hasRole('ROLE_MANAGER') or hasRole('ROLE_ADMIN')") public void manageProjectUsers(Long userId, String projectId, Operation operation) { Project project = getProjectById(projectId); Long projectManagerId = project.getCreatedBy(); userUtils.userAccessFilter(projectManagerId); User user = userService.getUserById(userId); Set<User> projectUsers = project.getUsers(); if (operation == Operation.ADD) { projectUsers.add(user); } else { projectUsers.remove(user); } project.setUsers(projectUsers); projectRepository.save(project); } @PreAuthorize("hasRole('ROLE_MANAGER') or hasRole('ROLE_ADMIN')") public void removeUserFromProject(Long UserId, String ProjectId) { } public void isProjectValid(Project project) { if (projectRepository.existsByProjectName(project.getProjectName())) { throw new ProjectAlreadyExistsException("project with the same name exists already"); } if (project.getTargetEndDate() != null && project.getStartDate() != null) if (project.getTargetEndDate().isBefore(project.getStartDate())) { throw new InvalidDateValueException("'End date' must be more recent than 'Start date'"); } } public void isProjectValid(Project newProject, Project oldProject) { if (projectRepository.existsByProjectName(newProject.getProjectName()) && !oldProject.getProjectName().equals(newProject.getProjectName())) { throw new ProjectAlreadyExistsException("project with the same name exists already"); } if (newProject.getTargetEndDate() != null && newProject.getStartDate() != null) if (newProject.getTargetEndDate().isBefore(newProject.getStartDate())) { throw new InvalidDateValueException("'End date' must be more recent than 'Start date'"); } if (newProject.getActualEndDate() != null && newProject.getStartDate() != null) if (newProject.getActualEndDate().isBefore(newProject.getStartDate())) { throw new InvalidDateValueException("'Actual end date' must be more recent than 'Start date'"); } } }
4,850
0.694021
0.694021
111
42.693695
30.187342
111
false
false
0
0
0
0
0
0
0.477477
false
false
14
e71c6b0739a0cb71ef838a8515fa33b4a09ca3bf
22,041,772,200,428
aeada48fb548995312d2117f2a97b05242348abf
/bundles/com.zeligsoft.domain.omg.corba.api/api-gen/com/zeligsoft/domain/omg/corba/api/IDL/impl/CORBAAttributeImplementation.java
d8afa97a07d8084abe58e8449f470db67165f6b8
[ "Apache-2.0" ]
permissive
elder4p/CX4CBDDS
https://github.com/elder4p/CX4CBDDS
8f103d5375595f583ceb30b343ae4c7cc240f18b
11296d3076c6d667ad86bc83fa47f708e8b5bf01
refs/heads/master
2023-03-16T01:51:59.122000
2022-08-04T22:13:10
2022-08-04T22:13:10
198,875,329
0
0
Apache-2.0
true
2019-08-22T17:33:21
2019-07-25T17:33:51
2019-08-22T17:23:32
2019-08-22T17:33:20
617,939
0
0
0
Java
false
false
package com.zeligsoft.domain.omg.corba.api.IDL.impl; import com.zeligsoft.base.zdl.staticapi.util.ZDLFactoryRegistry; import com.zeligsoft.domain.omg.corba.api.IDL.CORBAAttribute; import com.zeligsoft.domain.omg.corba.api.IDL.impl.CORBANamedElementImplementation; import com.zeligsoft.domain.omg.corba.api.IDL.CORBAException; import com.zeligsoft.domain.omg.corba.api.IDL.CORBAModuleContained; import com.zeligsoft.domain.omg.corba.api.IDL.CORBAType; import com.zeligsoft.base.zdl.util.ZDLUtil; public class CORBAAttributeImplementation extends CORBANamedElementImplementation implements CORBAAttribute { protected CORBAModuleContained _owner; protected java.util.List<CORBAException> _setraises; protected java.util.List<CORBAException> _getraises; protected CORBAType _idlType; public CORBAAttributeImplementation(org.eclipse.emf.ecore.EObject element) { super(element); } @Override public CORBAModuleContained getOwner() { if (_owner == null) { final Object rawValue = com.zeligsoft.base.zdl.util.ZDLUtil .getValue(eObject(), "CORBADomain::IDL::CORBAAttribute", "owner"); if (rawValue instanceof org.eclipse.emf.ecore.EObject) { _owner = ZDLFactoryRegistry.INSTANCE.create( (org.eclipse.emf.ecore.EObject) rawValue, CORBAModuleContained.class); } } return _owner; } @Override public java.util.List<CORBAException> getSetraises() { if (_setraises == null) { final Object rawValue = com.zeligsoft.base.zdl.util.ZDLUtil .getValue(eObject(), "CORBADomain::IDL::CORBAAttribute", "setraises"); _setraises = new java.util.ArrayList<CORBAException>(); @SuppressWarnings("unchecked") final java.util.List<Object> rawList = (java.util.List<Object>) rawValue; for (Object next : rawList) { if (next instanceof org.eclipse.emf.ecore.EObject) { CORBAException nextWrapper = ZDLFactoryRegistry.INSTANCE .create((org.eclipse.emf.ecore.EObject) next, CORBAException.class); _setraises.add(nextWrapper); } } } return _setraises; } @Override public void addSetraises(CORBAException val) { // make sure the setraises list is created getSetraises(); final Object rawValue = ZDLUtil.getValue(element, "CORBADomain::IDL::CORBAAttribute", "setraises"); @SuppressWarnings("unchecked") final java.util.List<Object> rawList = (java.util.List<Object>) rawValue; rawList.add(val.eObject()); if (_setraises != null) { _setraises.add(val); } } @Override public Boolean getIsReadOnly() { final Object rawValue = com.zeligsoft.base.zdl.util.ZDLUtil.getValue( eObject(), "CORBADomain::IDL::CORBAAttribute", "isReadOnly"); return (Boolean) rawValue; } @Override public void setIsReadOnly(Boolean val) { ZDLUtil.setValue(element, "CORBADomain::IDL::CORBAAttribute", "isReadOnly", val); } @Override public String getUuid() { final Object rawValue = com.zeligsoft.base.zdl.util.ZDLUtil.getValue( eObject(), "ZMLMM::ZML_Component::WorkerFunctionIdentifiable", "uuid"); return (String) rawValue; } @Override public void setUuid(String val) { ZDLUtil.setValue(element, "ZMLMM::ZML_Component::WorkerFunctionIdentifiable", "uuid", val); } @Override public java.util.List<CORBAException> getGetraises() { if (_getraises == null) { final Object rawValue = com.zeligsoft.base.zdl.util.ZDLUtil .getValue(eObject(), "CORBADomain::IDL::CORBAAttribute", "getraises"); _getraises = new java.util.ArrayList<CORBAException>(); @SuppressWarnings("unchecked") final java.util.List<Object> rawList = (java.util.List<Object>) rawValue; for (Object next : rawList) { if (next instanceof org.eclipse.emf.ecore.EObject) { CORBAException nextWrapper = ZDLFactoryRegistry.INSTANCE .create((org.eclipse.emf.ecore.EObject) next, CORBAException.class); _getraises.add(nextWrapper); } } } return _getraises; } @Override public void addGetraises(CORBAException val) { // make sure the getraises list is created getGetraises(); final Object rawValue = ZDLUtil.getValue(element, "CORBADomain::IDL::CORBAAttribute", "getraises"); @SuppressWarnings("unchecked") final java.util.List<Object> rawList = (java.util.List<Object>) rawValue; rawList.add(val.eObject()); if (_getraises != null) { _getraises.add(val); } } @Override public CORBAType getIdlType() { if (_idlType == null) { final Object rawValue = com.zeligsoft.base.zdl.util.ZDLUtil .getValue(eObject(), "CORBADomain::IDL::CORBATyped", "idlType"); if (rawValue instanceof org.eclipse.emf.ecore.EObject) { _idlType = ZDLFactoryRegistry.INSTANCE.create( (org.eclipse.emf.ecore.EObject) rawValue, CORBAType.class); } } return _idlType; } @Override public void setIdlType(CORBAType val) { ZDLUtil.setValue(element, "CORBADomain::IDL::CORBATyped", "idlType", val.eObject()); } @Override public org.eclipse.uml2.uml.Property asProperty() { return (org.eclipse.uml2.uml.Property) eObject(); } }
UTF-8
Java
5,057
java
CORBAAttributeImplementation.java
Java
[]
null
[]
package com.zeligsoft.domain.omg.corba.api.IDL.impl; import com.zeligsoft.base.zdl.staticapi.util.ZDLFactoryRegistry; import com.zeligsoft.domain.omg.corba.api.IDL.CORBAAttribute; import com.zeligsoft.domain.omg.corba.api.IDL.impl.CORBANamedElementImplementation; import com.zeligsoft.domain.omg.corba.api.IDL.CORBAException; import com.zeligsoft.domain.omg.corba.api.IDL.CORBAModuleContained; import com.zeligsoft.domain.omg.corba.api.IDL.CORBAType; import com.zeligsoft.base.zdl.util.ZDLUtil; public class CORBAAttributeImplementation extends CORBANamedElementImplementation implements CORBAAttribute { protected CORBAModuleContained _owner; protected java.util.List<CORBAException> _setraises; protected java.util.List<CORBAException> _getraises; protected CORBAType _idlType; public CORBAAttributeImplementation(org.eclipse.emf.ecore.EObject element) { super(element); } @Override public CORBAModuleContained getOwner() { if (_owner == null) { final Object rawValue = com.zeligsoft.base.zdl.util.ZDLUtil .getValue(eObject(), "CORBADomain::IDL::CORBAAttribute", "owner"); if (rawValue instanceof org.eclipse.emf.ecore.EObject) { _owner = ZDLFactoryRegistry.INSTANCE.create( (org.eclipse.emf.ecore.EObject) rawValue, CORBAModuleContained.class); } } return _owner; } @Override public java.util.List<CORBAException> getSetraises() { if (_setraises == null) { final Object rawValue = com.zeligsoft.base.zdl.util.ZDLUtil .getValue(eObject(), "CORBADomain::IDL::CORBAAttribute", "setraises"); _setraises = new java.util.ArrayList<CORBAException>(); @SuppressWarnings("unchecked") final java.util.List<Object> rawList = (java.util.List<Object>) rawValue; for (Object next : rawList) { if (next instanceof org.eclipse.emf.ecore.EObject) { CORBAException nextWrapper = ZDLFactoryRegistry.INSTANCE .create((org.eclipse.emf.ecore.EObject) next, CORBAException.class); _setraises.add(nextWrapper); } } } return _setraises; } @Override public void addSetraises(CORBAException val) { // make sure the setraises list is created getSetraises(); final Object rawValue = ZDLUtil.getValue(element, "CORBADomain::IDL::CORBAAttribute", "setraises"); @SuppressWarnings("unchecked") final java.util.List<Object> rawList = (java.util.List<Object>) rawValue; rawList.add(val.eObject()); if (_setraises != null) { _setraises.add(val); } } @Override public Boolean getIsReadOnly() { final Object rawValue = com.zeligsoft.base.zdl.util.ZDLUtil.getValue( eObject(), "CORBADomain::IDL::CORBAAttribute", "isReadOnly"); return (Boolean) rawValue; } @Override public void setIsReadOnly(Boolean val) { ZDLUtil.setValue(element, "CORBADomain::IDL::CORBAAttribute", "isReadOnly", val); } @Override public String getUuid() { final Object rawValue = com.zeligsoft.base.zdl.util.ZDLUtil.getValue( eObject(), "ZMLMM::ZML_Component::WorkerFunctionIdentifiable", "uuid"); return (String) rawValue; } @Override public void setUuid(String val) { ZDLUtil.setValue(element, "ZMLMM::ZML_Component::WorkerFunctionIdentifiable", "uuid", val); } @Override public java.util.List<CORBAException> getGetraises() { if (_getraises == null) { final Object rawValue = com.zeligsoft.base.zdl.util.ZDLUtil .getValue(eObject(), "CORBADomain::IDL::CORBAAttribute", "getraises"); _getraises = new java.util.ArrayList<CORBAException>(); @SuppressWarnings("unchecked") final java.util.List<Object> rawList = (java.util.List<Object>) rawValue; for (Object next : rawList) { if (next instanceof org.eclipse.emf.ecore.EObject) { CORBAException nextWrapper = ZDLFactoryRegistry.INSTANCE .create((org.eclipse.emf.ecore.EObject) next, CORBAException.class); _getraises.add(nextWrapper); } } } return _getraises; } @Override public void addGetraises(CORBAException val) { // make sure the getraises list is created getGetraises(); final Object rawValue = ZDLUtil.getValue(element, "CORBADomain::IDL::CORBAAttribute", "getraises"); @SuppressWarnings("unchecked") final java.util.List<Object> rawList = (java.util.List<Object>) rawValue; rawList.add(val.eObject()); if (_getraises != null) { _getraises.add(val); } } @Override public CORBAType getIdlType() { if (_idlType == null) { final Object rawValue = com.zeligsoft.base.zdl.util.ZDLUtil .getValue(eObject(), "CORBADomain::IDL::CORBATyped", "idlType"); if (rawValue instanceof org.eclipse.emf.ecore.EObject) { _idlType = ZDLFactoryRegistry.INSTANCE.create( (org.eclipse.emf.ecore.EObject) rawValue, CORBAType.class); } } return _idlType; } @Override public void setIdlType(CORBAType val) { ZDLUtil.setValue(element, "CORBADomain::IDL::CORBATyped", "idlType", val.eObject()); } @Override public org.eclipse.uml2.uml.Property asProperty() { return (org.eclipse.uml2.uml.Property) eObject(); } }
5,057
0.719399
0.719003
164
29.835365
24.469065
83
false
false
0
0
0
0
0
0
2.658537
false
false
14
8f1cae4ee3bc856853647c4b0da2eb4b30500299
22,041,772,198,853
89d0a9d72e09f05e8a3c6cd0f1f7010335ba9a01
/works/works-measurementbook/src/main/java/org/egov/works/measurementbook/domain/service/MeasurementBookService.java
ca12938151f1b9826aa11c62da669f4e65e7735a
[]
no_license
satishegov/egov-services
https://github.com/satishegov/egov-services
1abe35608c7405278124897f4523815d5a03ddf0
0b0517845f9d5d98758af686f51062ec76058598
refs/heads/master
2021-05-10T09:21:38.690000
2018-01-25T11:36:10
2018-01-25T11:36:10
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.egov.works.measurementbook.domain.service; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Map; import java.util.UUID; import org.apache.commons.lang3.StringUtils; import org.egov.tracer.kafka.LogAwareKafkaTemplate; import org.egov.works.commons.utils.CommonConstants; import org.egov.works.measurementbook.config.Constants; import org.egov.works.measurementbook.config.PropertiesManager; import org.egov.works.measurementbook.domain.repository.EstimateRepository; import org.egov.works.measurementbook.domain.repository.LetterOfAcceptanceRepository; import org.egov.works.measurementbook.domain.repository.MeasurementBookRepository; import org.egov.works.measurementbook.domain.validator.MeasurementBookValidator; import org.egov.works.measurementbook.utils.MeasurementBookUtils; import org.egov.works.measurementbook.web.contract.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import net.minidev.json.JSONArray; /** * @author manoj * */ @Service @Transactional(readOnly = true) public class MeasurementBookService { @Autowired private LogAwareKafkaTemplate<String, Object> kafkaTemplate; @Autowired private PropertiesManager propertiesManager; // @Autowired // private CommonUtils commonUtils; @Autowired private MeasurementBookUtils measurementBookUtils; @Autowired private MeasurementBookRepository measurementBookRepository; @Autowired private EstimateRepository estimateRepository; @Autowired private LetterOfAcceptanceRepository letterOfAcceptanceRepository; @Autowired private MeasurementBookValidator measurementBookValidator; public MeasurementBookResponse create(MeasurementBookRequest measurementBookRequest) { measurementBookValidator.validateMB(measurementBookRequest, true); Boolean isWorkflowReq = isConfigRequired(CommonConstants.WORKFLOW_REQUIRED_APPCONFIG, measurementBookRequest.getRequestInfo(), measurementBookRequest.getMeasurementBooks().get(0).getTenantId()); for (MeasurementBook measurementBook : measurementBookRequest.getMeasurementBooks()) { measurementBook.setId(UUID.randomUUID().toString().replace("-", "")); for (MeasurementBookDetail measurementBookDetail : measurementBook.getMeasurementBookDetails()) { measurementBookDetail.setId(UUID.randomUUID().toString().replace("-", "")); if(measurementBookDetail.getMeasurementSheets() != null && !measurementBookDetail.getMeasurementSheets().isEmpty()) for (MBMeasurementSheet sheet : measurementBookDetail.getMeasurementSheets()) { sheet.setId(UUID.randomUUID().toString().replace("-", "")); sheet.setAuditDetails( measurementBookUtils.setAuditDetails(measurementBookRequest.getRequestInfo(), false)); } measurementBookDetail.setAuditDetails( measurementBookUtils.setAuditDetails(measurementBookRequest.getRequestInfo(), false)); } if(measurementBook.getDocumentDetails() != null && !measurementBook.getDocumentDetails().isEmpty()) for (DocumentDetail detail : measurementBook.getDocumentDetails()) { detail.setId(UUID.randomUUID().toString().replace("-", "")); detail.setObjectType("MeasurementBook"); detail.setAuditDetails( measurementBookUtils.setAuditDetails(measurementBookRequest.getRequestInfo(), false)); } measurementBook.setAuditDetails( measurementBookUtils.setAuditDetails(measurementBookRequest.getRequestInfo(), false)); if (measurementBook.getLumpSumMBDetails() != null && !measurementBook.getLumpSumMBDetails().isEmpty()) createUpdateRevisionEstimate(measurementBook, measurementBookRequest.getRequestInfo(), false); if (measurementBook.getIsLegacyMB()) measurementBook.setApprovedDate(measurementBook.getMbDate()); if (measurementBook.getIsLegacyMB() && isWorkflowReq) { updateStatus(measurementBook, measurementBookRequest.getRequestInfo()); } else { List<String> filterNamesList = new ArrayList<>(Arrays.asList(CommonConstants.CODE,CommonConstants.MODULE_TYPE)); List<String> filterValuesList = new ArrayList<>(Arrays.asList(Constants.STATUS_APPROVED, Constants.MEASUREMENTBOOK_OBJECT)); JSONArray dBStatusArray = measurementBookUtils.getMDMSData(CommonConstants.WORKS_STATUS_APPCONFIG, filterNamesList, filterValuesList, measurementBook.getTenantId(), measurementBookRequest.getRequestInfo(), CommonConstants.MODULENAME_WORKS); if(dBStatusArray != null && !dBStatusArray.isEmpty()) { WorksStatus status = new WorksStatus(); status.code(Constants.STATUS_APPROVED); measurementBook.setStatus(status); } } } kafkaTemplate.send(propertiesManager.getWorksMBCreateUpdateTopic(), measurementBookRequest); MeasurementBookResponse measurementBookResponse = new MeasurementBookResponse(); measurementBookResponse.setMeasurementBooks(measurementBookRequest.getMeasurementBooks()); return measurementBookResponse; } private void updateStatus(MeasurementBook measurementBook, RequestInfo requestInfo) { String action = measurementBook.getWorkFlowDetails().getAction(); List<String> filterNamesList = null; List<String> filterValuesList = null; WorksStatus status = null; if (!action.equalsIgnoreCase(Constants.SAVE)) { filterNamesList = new ArrayList<>(Arrays.asList(CommonConstants.CODE,CommonConstants.MODULE_TYPE)); filterValuesList = new ArrayList<>(Arrays.asList(Constants.STATUS_CREATED, Constants.MEASUREMENTBOOK_OBJECT)); JSONArray dBStatusArray = measurementBookUtils.getMDMSData(CommonConstants.WORKS_STATUS_APPCONFIG, filterNamesList, filterValuesList, measurementBook.getTenantId(), requestInfo, CommonConstants.MODULENAME_WORKS); if(dBStatusArray != null && !dBStatusArray.isEmpty()) { status = new WorksStatus(); status.setCode(Constants.STATUS_CREATED); } } else { filterNamesList = new ArrayList<>(Arrays.asList(CommonConstants.CODE,CommonConstants.MODULE_TYPE)); filterValuesList = new ArrayList<>(Arrays.asList(Constants.STATUS_SAVED, Constants.MEASUREMENTBOOK_OBJECT)); JSONArray dBStatusArray = measurementBookUtils.getMDMSData(CommonConstants.WORKS_STATUS_APPCONFIG, filterNamesList, filterValuesList, measurementBook.getTenantId(), requestInfo, CommonConstants.MODULENAME_WORKS); if(dBStatusArray != null && !dBStatusArray.isEmpty()) { status = new WorksStatus(); status.setCode(Constants.STATUS_SAVED); } } measurementBook.setStatus(status); } /*private void updateStatus(MeasurementBook measurementBook, boolean isNew, RequestInfo requestInfo) { String action = measurementBook.getWorkFlowDetails().getAction(); if (isNew) { if (!action.equalsIgnoreCase(Constants.SAVE)) measurementBook.setStatus(MeasurementBookStatus.CREATED); else measurementBook.setStatus(MeasurementBookStatus.SAVED); } else { if (action.equalsIgnoreCase(Constants.SUBMIT) && measurementBook.getStatus().equals(MeasurementBookStatus.CREATED)) measurementBook.setStatus(MeasurementBookStatus.CHECKED); else if (action.equalsIgnoreCase(Constants.APPROVE) && measurementBook.getStatus().equals(MeasurementBookStatus.CHECKED)) measurementBook.setStatus(MeasurementBookStatus.APPROVED); else if (action.equalsIgnoreCase(Constants.REJECT) && !(measurementBook.getStatus().equals(MeasurementBookStatus.APPROVED) || measurementBook.getStatus().equals(MeasurementBookStatus.CANCELLED))) measurementBook.setStatus(MeasurementBookStatus.REJECTED); else if (action.equalsIgnoreCase(Constants.CANCEL) && measurementBook.getStatus().equals(MeasurementBookStatus.REJECTED)) measurementBook.setStatus(MeasurementBookStatus.CANCELLED); else if (action.equalsIgnoreCase(Constants.FORWARD) && measurementBook.getStatus().equals(MeasurementBookStatus.REJECTED)) measurementBook.setStatus(MeasurementBookStatus.RESUBMITTED); } } */ /** * @param measurementBook * @param requestInfo * @param isUpdate * * Create Revision DE and LOA if lumpsum activities present */ private void createUpdateRevisionEstimate(MeasurementBook measurementBook, RequestInfo requestInfo, Boolean isUpdate) { DetailedEstimateRequest detailedEstimateRequest = new DetailedEstimateRequest(); LetterOfAcceptanceRequest letterOfAcceptanceRequest = new LetterOfAcceptanceRequest(); Boolean deleted = true; AuditDetails auditDetails = measurementBookUtils.setAuditDetails(requestInfo, false); List<DetailedEstimate> detailedEstimates = new ArrayList<>(); List<LetterOfAcceptance> letterOfAcceptances = new ArrayList<>(); DetailedEstimate detailedEstimate = new DetailedEstimate(); LetterOfAcceptance letterOfAcceptance = new LetterOfAcceptance(); if (isUpdate) detailedEstimate.setId(measurementBook.getLumpSumMBDetails().get(0).getLoaActivity().getEstimateActivity() .getDetailedEstimate()); detailedEstimate.setTenantId(measurementBook.getTenantId()); detailedEstimate.setParent(measurementBook.getLetterOfAcceptanceEstimate().getDetailedEstimate().getId()); for (MeasurementBookDetail detail : measurementBook.getLumpSumMBDetails()) detailedEstimate.addEstimateActivitiesItem(detail.getLoaActivity().getEstimateActivity()); detailedEstimate.setEstimateDate(new Date().getTime()); detailedEstimate .setDepartment(measurementBook.getLetterOfAcceptanceEstimate().getDetailedEstimate().getDepartment()); detailedEstimate.setEstimateValue( measurementBook.getLetterOfAcceptanceEstimate().getDetailedEstimate().getEstimateValue()); for (final EstimateActivity estimateActivity : detailedEstimate.getEstimateActivities()) { estimateActivity.setTenantId(measurementBook.getTenantId()); estimateActivity.setAuditDetails(auditDetails); if (isUpdate && deleted && !estimateActivity.getDeleted()) deleted = false; if (estimateActivity.getEstimateMeasurementSheets() != null) { for (final EstimateMeasurementSheet estimateMeasurementSheet : estimateActivity .getEstimateMeasurementSheets()) { estimateMeasurementSheet.setTenantId(measurementBook.getTenantId()); estimateMeasurementSheet.setAuditDetails(auditDetails); } } } if (isUpdate) detailedEstimate.setDeleted(deleted); detailedEstimates.add(detailedEstimate); detailedEstimateRequest.setDetailedEstimates(detailedEstimates); detailedEstimateRequest.setRequestInfo(requestInfo); DetailedEstimateResponse detailedEstimateResponse = estimateRepository .createUpdateDetailedEstimate(detailedEstimateRequest, isUpdate); letterOfAcceptance.setTenantId(measurementBook.getTenantId()); letterOfAcceptance.setParent(measurementBook.getLetterOfAcceptanceEstimate().getLetterOfAcceptance()); letterOfAcceptance.setLoaDate(new Date().getTime()); letterOfAcceptance.setLoaAmount(detailedEstimateResponse.getDetailedEstimates().get(0).getEstimateValue()); WorksStatus status = new WorksStatus(); status.setCode(Constants.STATUS_APPROVED); letterOfAcceptance.setStatus(status); List<LetterOfAcceptanceEstimate> letterOfAcceptanceEstimates = new ArrayList<>(); LetterOfAcceptanceEstimate letterOfAcceptanceEstimate = new LetterOfAcceptanceEstimate(); LetterOfAcceptanceResponse letterOfAcceptanceResponse = null; if (isUpdate && StringUtils.isNotBlank(measurementBook.getRevisionLOA())) { letterOfAcceptance.setId(measurementBook.getRevisionLOA()); letterOfAcceptanceResponse = letterOfAcceptanceRepository.searchLOAById( Arrays.asList(measurementBook.getRevisionLOA()), measurementBook.getTenantId(), requestInfo); letterOfAcceptanceEstimate.setId(letterOfAcceptanceResponse.getLetterOfAcceptances().get(0) .getLetterOfAcceptanceEstimates().get(0).getId()); } letterOfAcceptanceEstimate.setTenantId(measurementBook.getTenantId()); letterOfAcceptanceEstimate.setAuditDetails(auditDetails); letterOfAcceptanceEstimate.setDetailedEstimate(detailedEstimateResponse.getDetailedEstimates().get(0)); letterOfAcceptanceEstimate.setLetterOfAcceptance(letterOfAcceptance.getId()); populateLOAActivities(letterOfAcceptanceEstimate, detailedEstimateResponse.getDetailedEstimates().get(0), auditDetails); if (isUpdate) { letterOfAcceptance.setDeleted(deleted); letterOfAcceptanceEstimate.setDeleted(deleted); } letterOfAcceptanceEstimates.add(letterOfAcceptanceEstimate); letterOfAcceptance.setLetterOfAcceptanceEstimates(letterOfAcceptanceEstimates); letterOfAcceptances.add(letterOfAcceptance); letterOfAcceptanceRequest.setLetterOfAcceptances(letterOfAcceptances); letterOfAcceptanceRequest.setRequestInfo(requestInfo); letterOfAcceptanceResponse = letterOfAcceptanceRepository.createUpdateLOA(letterOfAcceptanceRequest, isUpdate); measurementBook.setRevisionLOA(letterOfAcceptanceResponse.getLetterOfAcceptances().get(0).getId()); updateLumpsumActivities(measurementBook, letterOfAcceptanceResponse.getLetterOfAcceptances().get(0), isUpdate, requestInfo); } /** * @param measurementBook * @param letterOfAcceptance * @param isUpdate * @param requestInfo * * populate mb details with references after creating revision DE and LOA */ private void updateLumpsumActivities(MeasurementBook measurementBook, LetterOfAcceptance letterOfAcceptance, Boolean isUpdate, RequestInfo requestInfo) { if (isUpdate) for (MeasurementBookDetail detail : measurementBook.getLumpSumMBDetails()) { detail.setAuditDetails(measurementBookUtils.setAuditDetails(requestInfo, true)); for (MBMeasurementSheet sheet : detail.getMeasurementSheets()) sheet.setAuditDetails(measurementBookUtils.setAuditDetails(requestInfo, true)); measurementBook.addMeasurementBookDetailsItem(detail); } else { for (LOAActivity loaActivity : letterOfAcceptance.getLetterOfAcceptanceEstimates().get(0) .getLoaActivities()) { final EstimateActivity activity = loaActivity.getEstimateActivity(); final MeasurementBookDetail measurementBookDetail = new MeasurementBookDetail(); measurementBookDetail.setId(UUID.randomUUID().toString().replace("-", "")); measurementBookDetail.setTenantId(activity.getTenantId()); measurementBookDetail.setAmount(activity.getEstimateRate()); measurementBookDetail.setLoaActivity(loaActivity); measurementBookDetail.setMeasurementBook(measurementBook.getId()); List<MBMeasurementSheet> measurementSheets = new ArrayList<>(); for (LOAMeasurementSheet loaMeasurementSheet : loaActivity.getLoaMeasurements()) { MBMeasurementSheet sheet = new MBMeasurementSheet(); sheet.setId(UUID.randomUUID().toString().replace("-", "")); sheet.setDepthOrHeight(loaMeasurementSheet.getDepthOrHeight()); sheet.setLength(loaMeasurementSheet.getLength()); sheet.setLoaMeasurementSheet(loaMeasurementSheet); sheet.setMeasurementBookDetail(measurementBookDetail.getId()); sheet.setNumber(loaMeasurementSheet.getNumber()); sheet.setQuantity(loaMeasurementSheet.getQuantity()); sheet.setWidth(loaMeasurementSheet.getWidth()); sheet.setAuditDetails(measurementBookUtils.setAuditDetails(requestInfo, false)); measurementSheets.add(sheet); } measurementBookDetail.setMeasurementSheets(measurementSheets); measurementBookDetail.setQuantity(loaActivity.getApprovedQuantity().doubleValue()); measurementBookDetail.setRemarks(loaActivity.getRemarks()); measurementBookDetail.setAuditDetails(measurementBookUtils.setAuditDetails(requestInfo, false)); } } } /** * @param letterOfAcceptanceEstimate * @param detailedEstimate * @param auditDetails * * populate LOA activities after creating revision DE */ private void populateLOAActivities(LetterOfAcceptanceEstimate letterOfAcceptanceEstimate, DetailedEstimate detailedEstimate, AuditDetails auditDetails) { List<LOAActivity> loaActivities = new ArrayList<>(); for (EstimateActivity activity : detailedEstimate.getEstimateActivities()) { LOAActivity loaActivity = new LOAActivity(); loaActivity.setTenantId(activity.getTenantId()); loaActivity.setAuditDetails(auditDetails); loaActivity.setEstimateActivity(activity); loaActivity.setLetterOfAcceptanceEstimate(letterOfAcceptanceEstimate.getId()); List<LOAMeasurementSheet> loaMeasurementSheets = new ArrayList<>(); for (EstimateMeasurementSheet sheet : activity.getEstimateMeasurementSheets()) { LOAMeasurementSheet loaMeasurementSheet = new LOAMeasurementSheet(); loaMeasurementSheet.setTenantId(sheet.getTenantId()); loaMeasurementSheet.setAuditDetails(auditDetails); loaMeasurementSheet.setDepthOrHeight(sheet.getDepthOrHeight()); loaMeasurementSheet.setEstimateMeasurementSheet(sheet.getId()); loaMeasurementSheet.setLength(sheet.getLength()); loaMeasurementSheet.setLoaActivity(loaActivity.getId()); loaMeasurementSheet.setNumber(sheet.getNumber()); loaMeasurementSheet.setQuantity(sheet.getQuantity()); loaMeasurementSheet.setWidth(sheet.getWidth()); loaMeasurementSheets.add(loaMeasurementSheet); } loaActivity.setLoaMeasurements(loaMeasurementSheets); loaActivities.add(loaActivity); } letterOfAcceptanceEstimate.setLoaActivities(loaActivities); } public MeasurementBookResponse update(MeasurementBookRequest measurementBookRequest) { measurementBookValidator.validateMB(measurementBookRequest, false); for (MeasurementBook measurementBook : measurementBookRequest.getMeasurementBooks()) { for (MeasurementBookDetail measurementBookDetail : measurementBook.getMeasurementBookDetails()) { if (measurementBookDetail.getId() == null) measurementBookDetail.setId(UUID.randomUUID().toString().replace("-", "")); for (MBMeasurementSheet sheet : measurementBookDetail.getMeasurementSheets()) { if (sheet.getId() == null) sheet.setId(UUID.randomUUID().toString().replace("-", "")); sheet.setAuditDetails( measurementBookUtils.setAuditDetails(measurementBookRequest.getRequestInfo(), true)); } measurementBookDetail.setAuditDetails( measurementBookUtils.setAuditDetails(measurementBookRequest.getRequestInfo(), true)); } for (DocumentDetail detail : measurementBook.getDocumentDetails()) { if (detail.getId() == null) detail.setId(UUID.randomUUID().toString().replace("-", "")); detail.setObjectType("MeasurementBook"); detail.setAuditDetails( measurementBookUtils.setAuditDetails(measurementBookRequest.getRequestInfo(), true)); } measurementBook.setAuditDetails( measurementBookUtils.setAuditDetails(measurementBookRequest.getRequestInfo(), true)); if (measurementBook.getLumpSumMBDetails() != null && !measurementBook.getLumpSumMBDetails().isEmpty()) createUpdateRevisionEstimate(measurementBook, measurementBookRequest.getRequestInfo(), true); //updateStatus(measurementBook, false); } kafkaTemplate.send(propertiesManager.getWorksMBCreateUpdateTopic(), measurementBookRequest); MeasurementBookResponse measurementBookResponse = new MeasurementBookResponse(); measurementBookResponse.setMeasurementBooks(measurementBookRequest.getMeasurementBooks()); return measurementBookResponse; } public MeasurementBookResponse search(MeasurementBookSearchContract measurementBookSearchContract, RequestInfo requestInfo) { MeasurementBookResponse measurementBookResponse = new MeasurementBookResponse(); measurementBookResponse.setMeasurementBooks( measurementBookRepository.searchMeasurementBooks(measurementBookSearchContract, requestInfo)); return measurementBookResponse; } private Boolean isConfigRequired(String keyName, RequestInfo requestInfo, final String tenantId) { Boolean isSpilloverWFReq = false; JSONArray responseJSONArray = measurementBookUtils.getMDMSData(CommonConstants.APPCONFIGURATION_OBJECT, CommonConstants.CODE, keyName, tenantId, requestInfo, CommonConstants.MODULENAME_WORKS); if (responseJSONArray != null && !responseJSONArray.isEmpty()) { Map<String, Object> jsonMap = (Map<String, Object>) responseJSONArray.get(0); if (jsonMap.get("value").equals("Yes")) isSpilloverWFReq = true; } return isSpilloverWFReq; } }
UTF-8
Java
20,650
java
MeasurementBookService.java
Java
[ { "context": "import net.minidev.json.JSONArray;\n\n/**\n * @author manoj\n *\n */\n@Service\n@Transactional(readOnly = true)\np", "end": 1149, "score": 0.7006987929344177, "start": 1144, "tag": "USERNAME", "value": "manoj" } ]
null
[]
package org.egov.works.measurementbook.domain.service; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Map; import java.util.UUID; import org.apache.commons.lang3.StringUtils; import org.egov.tracer.kafka.LogAwareKafkaTemplate; import org.egov.works.commons.utils.CommonConstants; import org.egov.works.measurementbook.config.Constants; import org.egov.works.measurementbook.config.PropertiesManager; import org.egov.works.measurementbook.domain.repository.EstimateRepository; import org.egov.works.measurementbook.domain.repository.LetterOfAcceptanceRepository; import org.egov.works.measurementbook.domain.repository.MeasurementBookRepository; import org.egov.works.measurementbook.domain.validator.MeasurementBookValidator; import org.egov.works.measurementbook.utils.MeasurementBookUtils; import org.egov.works.measurementbook.web.contract.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import net.minidev.json.JSONArray; /** * @author manoj * */ @Service @Transactional(readOnly = true) public class MeasurementBookService { @Autowired private LogAwareKafkaTemplate<String, Object> kafkaTemplate; @Autowired private PropertiesManager propertiesManager; // @Autowired // private CommonUtils commonUtils; @Autowired private MeasurementBookUtils measurementBookUtils; @Autowired private MeasurementBookRepository measurementBookRepository; @Autowired private EstimateRepository estimateRepository; @Autowired private LetterOfAcceptanceRepository letterOfAcceptanceRepository; @Autowired private MeasurementBookValidator measurementBookValidator; public MeasurementBookResponse create(MeasurementBookRequest measurementBookRequest) { measurementBookValidator.validateMB(measurementBookRequest, true); Boolean isWorkflowReq = isConfigRequired(CommonConstants.WORKFLOW_REQUIRED_APPCONFIG, measurementBookRequest.getRequestInfo(), measurementBookRequest.getMeasurementBooks().get(0).getTenantId()); for (MeasurementBook measurementBook : measurementBookRequest.getMeasurementBooks()) { measurementBook.setId(UUID.randomUUID().toString().replace("-", "")); for (MeasurementBookDetail measurementBookDetail : measurementBook.getMeasurementBookDetails()) { measurementBookDetail.setId(UUID.randomUUID().toString().replace("-", "")); if(measurementBookDetail.getMeasurementSheets() != null && !measurementBookDetail.getMeasurementSheets().isEmpty()) for (MBMeasurementSheet sheet : measurementBookDetail.getMeasurementSheets()) { sheet.setId(UUID.randomUUID().toString().replace("-", "")); sheet.setAuditDetails( measurementBookUtils.setAuditDetails(measurementBookRequest.getRequestInfo(), false)); } measurementBookDetail.setAuditDetails( measurementBookUtils.setAuditDetails(measurementBookRequest.getRequestInfo(), false)); } if(measurementBook.getDocumentDetails() != null && !measurementBook.getDocumentDetails().isEmpty()) for (DocumentDetail detail : measurementBook.getDocumentDetails()) { detail.setId(UUID.randomUUID().toString().replace("-", "")); detail.setObjectType("MeasurementBook"); detail.setAuditDetails( measurementBookUtils.setAuditDetails(measurementBookRequest.getRequestInfo(), false)); } measurementBook.setAuditDetails( measurementBookUtils.setAuditDetails(measurementBookRequest.getRequestInfo(), false)); if (measurementBook.getLumpSumMBDetails() != null && !measurementBook.getLumpSumMBDetails().isEmpty()) createUpdateRevisionEstimate(measurementBook, measurementBookRequest.getRequestInfo(), false); if (measurementBook.getIsLegacyMB()) measurementBook.setApprovedDate(measurementBook.getMbDate()); if (measurementBook.getIsLegacyMB() && isWorkflowReq) { updateStatus(measurementBook, measurementBookRequest.getRequestInfo()); } else { List<String> filterNamesList = new ArrayList<>(Arrays.asList(CommonConstants.CODE,CommonConstants.MODULE_TYPE)); List<String> filterValuesList = new ArrayList<>(Arrays.asList(Constants.STATUS_APPROVED, Constants.MEASUREMENTBOOK_OBJECT)); JSONArray dBStatusArray = measurementBookUtils.getMDMSData(CommonConstants.WORKS_STATUS_APPCONFIG, filterNamesList, filterValuesList, measurementBook.getTenantId(), measurementBookRequest.getRequestInfo(), CommonConstants.MODULENAME_WORKS); if(dBStatusArray != null && !dBStatusArray.isEmpty()) { WorksStatus status = new WorksStatus(); status.code(Constants.STATUS_APPROVED); measurementBook.setStatus(status); } } } kafkaTemplate.send(propertiesManager.getWorksMBCreateUpdateTopic(), measurementBookRequest); MeasurementBookResponse measurementBookResponse = new MeasurementBookResponse(); measurementBookResponse.setMeasurementBooks(measurementBookRequest.getMeasurementBooks()); return measurementBookResponse; } private void updateStatus(MeasurementBook measurementBook, RequestInfo requestInfo) { String action = measurementBook.getWorkFlowDetails().getAction(); List<String> filterNamesList = null; List<String> filterValuesList = null; WorksStatus status = null; if (!action.equalsIgnoreCase(Constants.SAVE)) { filterNamesList = new ArrayList<>(Arrays.asList(CommonConstants.CODE,CommonConstants.MODULE_TYPE)); filterValuesList = new ArrayList<>(Arrays.asList(Constants.STATUS_CREATED, Constants.MEASUREMENTBOOK_OBJECT)); JSONArray dBStatusArray = measurementBookUtils.getMDMSData(CommonConstants.WORKS_STATUS_APPCONFIG, filterNamesList, filterValuesList, measurementBook.getTenantId(), requestInfo, CommonConstants.MODULENAME_WORKS); if(dBStatusArray != null && !dBStatusArray.isEmpty()) { status = new WorksStatus(); status.setCode(Constants.STATUS_CREATED); } } else { filterNamesList = new ArrayList<>(Arrays.asList(CommonConstants.CODE,CommonConstants.MODULE_TYPE)); filterValuesList = new ArrayList<>(Arrays.asList(Constants.STATUS_SAVED, Constants.MEASUREMENTBOOK_OBJECT)); JSONArray dBStatusArray = measurementBookUtils.getMDMSData(CommonConstants.WORKS_STATUS_APPCONFIG, filterNamesList, filterValuesList, measurementBook.getTenantId(), requestInfo, CommonConstants.MODULENAME_WORKS); if(dBStatusArray != null && !dBStatusArray.isEmpty()) { status = new WorksStatus(); status.setCode(Constants.STATUS_SAVED); } } measurementBook.setStatus(status); } /*private void updateStatus(MeasurementBook measurementBook, boolean isNew, RequestInfo requestInfo) { String action = measurementBook.getWorkFlowDetails().getAction(); if (isNew) { if (!action.equalsIgnoreCase(Constants.SAVE)) measurementBook.setStatus(MeasurementBookStatus.CREATED); else measurementBook.setStatus(MeasurementBookStatus.SAVED); } else { if (action.equalsIgnoreCase(Constants.SUBMIT) && measurementBook.getStatus().equals(MeasurementBookStatus.CREATED)) measurementBook.setStatus(MeasurementBookStatus.CHECKED); else if (action.equalsIgnoreCase(Constants.APPROVE) && measurementBook.getStatus().equals(MeasurementBookStatus.CHECKED)) measurementBook.setStatus(MeasurementBookStatus.APPROVED); else if (action.equalsIgnoreCase(Constants.REJECT) && !(measurementBook.getStatus().equals(MeasurementBookStatus.APPROVED) || measurementBook.getStatus().equals(MeasurementBookStatus.CANCELLED))) measurementBook.setStatus(MeasurementBookStatus.REJECTED); else if (action.equalsIgnoreCase(Constants.CANCEL) && measurementBook.getStatus().equals(MeasurementBookStatus.REJECTED)) measurementBook.setStatus(MeasurementBookStatus.CANCELLED); else if (action.equalsIgnoreCase(Constants.FORWARD) && measurementBook.getStatus().equals(MeasurementBookStatus.REJECTED)) measurementBook.setStatus(MeasurementBookStatus.RESUBMITTED); } } */ /** * @param measurementBook * @param requestInfo * @param isUpdate * * Create Revision DE and LOA if lumpsum activities present */ private void createUpdateRevisionEstimate(MeasurementBook measurementBook, RequestInfo requestInfo, Boolean isUpdate) { DetailedEstimateRequest detailedEstimateRequest = new DetailedEstimateRequest(); LetterOfAcceptanceRequest letterOfAcceptanceRequest = new LetterOfAcceptanceRequest(); Boolean deleted = true; AuditDetails auditDetails = measurementBookUtils.setAuditDetails(requestInfo, false); List<DetailedEstimate> detailedEstimates = new ArrayList<>(); List<LetterOfAcceptance> letterOfAcceptances = new ArrayList<>(); DetailedEstimate detailedEstimate = new DetailedEstimate(); LetterOfAcceptance letterOfAcceptance = new LetterOfAcceptance(); if (isUpdate) detailedEstimate.setId(measurementBook.getLumpSumMBDetails().get(0).getLoaActivity().getEstimateActivity() .getDetailedEstimate()); detailedEstimate.setTenantId(measurementBook.getTenantId()); detailedEstimate.setParent(measurementBook.getLetterOfAcceptanceEstimate().getDetailedEstimate().getId()); for (MeasurementBookDetail detail : measurementBook.getLumpSumMBDetails()) detailedEstimate.addEstimateActivitiesItem(detail.getLoaActivity().getEstimateActivity()); detailedEstimate.setEstimateDate(new Date().getTime()); detailedEstimate .setDepartment(measurementBook.getLetterOfAcceptanceEstimate().getDetailedEstimate().getDepartment()); detailedEstimate.setEstimateValue( measurementBook.getLetterOfAcceptanceEstimate().getDetailedEstimate().getEstimateValue()); for (final EstimateActivity estimateActivity : detailedEstimate.getEstimateActivities()) { estimateActivity.setTenantId(measurementBook.getTenantId()); estimateActivity.setAuditDetails(auditDetails); if (isUpdate && deleted && !estimateActivity.getDeleted()) deleted = false; if (estimateActivity.getEstimateMeasurementSheets() != null) { for (final EstimateMeasurementSheet estimateMeasurementSheet : estimateActivity .getEstimateMeasurementSheets()) { estimateMeasurementSheet.setTenantId(measurementBook.getTenantId()); estimateMeasurementSheet.setAuditDetails(auditDetails); } } } if (isUpdate) detailedEstimate.setDeleted(deleted); detailedEstimates.add(detailedEstimate); detailedEstimateRequest.setDetailedEstimates(detailedEstimates); detailedEstimateRequest.setRequestInfo(requestInfo); DetailedEstimateResponse detailedEstimateResponse = estimateRepository .createUpdateDetailedEstimate(detailedEstimateRequest, isUpdate); letterOfAcceptance.setTenantId(measurementBook.getTenantId()); letterOfAcceptance.setParent(measurementBook.getLetterOfAcceptanceEstimate().getLetterOfAcceptance()); letterOfAcceptance.setLoaDate(new Date().getTime()); letterOfAcceptance.setLoaAmount(detailedEstimateResponse.getDetailedEstimates().get(0).getEstimateValue()); WorksStatus status = new WorksStatus(); status.setCode(Constants.STATUS_APPROVED); letterOfAcceptance.setStatus(status); List<LetterOfAcceptanceEstimate> letterOfAcceptanceEstimates = new ArrayList<>(); LetterOfAcceptanceEstimate letterOfAcceptanceEstimate = new LetterOfAcceptanceEstimate(); LetterOfAcceptanceResponse letterOfAcceptanceResponse = null; if (isUpdate && StringUtils.isNotBlank(measurementBook.getRevisionLOA())) { letterOfAcceptance.setId(measurementBook.getRevisionLOA()); letterOfAcceptanceResponse = letterOfAcceptanceRepository.searchLOAById( Arrays.asList(measurementBook.getRevisionLOA()), measurementBook.getTenantId(), requestInfo); letterOfAcceptanceEstimate.setId(letterOfAcceptanceResponse.getLetterOfAcceptances().get(0) .getLetterOfAcceptanceEstimates().get(0).getId()); } letterOfAcceptanceEstimate.setTenantId(measurementBook.getTenantId()); letterOfAcceptanceEstimate.setAuditDetails(auditDetails); letterOfAcceptanceEstimate.setDetailedEstimate(detailedEstimateResponse.getDetailedEstimates().get(0)); letterOfAcceptanceEstimate.setLetterOfAcceptance(letterOfAcceptance.getId()); populateLOAActivities(letterOfAcceptanceEstimate, detailedEstimateResponse.getDetailedEstimates().get(0), auditDetails); if (isUpdate) { letterOfAcceptance.setDeleted(deleted); letterOfAcceptanceEstimate.setDeleted(deleted); } letterOfAcceptanceEstimates.add(letterOfAcceptanceEstimate); letterOfAcceptance.setLetterOfAcceptanceEstimates(letterOfAcceptanceEstimates); letterOfAcceptances.add(letterOfAcceptance); letterOfAcceptanceRequest.setLetterOfAcceptances(letterOfAcceptances); letterOfAcceptanceRequest.setRequestInfo(requestInfo); letterOfAcceptanceResponse = letterOfAcceptanceRepository.createUpdateLOA(letterOfAcceptanceRequest, isUpdate); measurementBook.setRevisionLOA(letterOfAcceptanceResponse.getLetterOfAcceptances().get(0).getId()); updateLumpsumActivities(measurementBook, letterOfAcceptanceResponse.getLetterOfAcceptances().get(0), isUpdate, requestInfo); } /** * @param measurementBook * @param letterOfAcceptance * @param isUpdate * @param requestInfo * * populate mb details with references after creating revision DE and LOA */ private void updateLumpsumActivities(MeasurementBook measurementBook, LetterOfAcceptance letterOfAcceptance, Boolean isUpdate, RequestInfo requestInfo) { if (isUpdate) for (MeasurementBookDetail detail : measurementBook.getLumpSumMBDetails()) { detail.setAuditDetails(measurementBookUtils.setAuditDetails(requestInfo, true)); for (MBMeasurementSheet sheet : detail.getMeasurementSheets()) sheet.setAuditDetails(measurementBookUtils.setAuditDetails(requestInfo, true)); measurementBook.addMeasurementBookDetailsItem(detail); } else { for (LOAActivity loaActivity : letterOfAcceptance.getLetterOfAcceptanceEstimates().get(0) .getLoaActivities()) { final EstimateActivity activity = loaActivity.getEstimateActivity(); final MeasurementBookDetail measurementBookDetail = new MeasurementBookDetail(); measurementBookDetail.setId(UUID.randomUUID().toString().replace("-", "")); measurementBookDetail.setTenantId(activity.getTenantId()); measurementBookDetail.setAmount(activity.getEstimateRate()); measurementBookDetail.setLoaActivity(loaActivity); measurementBookDetail.setMeasurementBook(measurementBook.getId()); List<MBMeasurementSheet> measurementSheets = new ArrayList<>(); for (LOAMeasurementSheet loaMeasurementSheet : loaActivity.getLoaMeasurements()) { MBMeasurementSheet sheet = new MBMeasurementSheet(); sheet.setId(UUID.randomUUID().toString().replace("-", "")); sheet.setDepthOrHeight(loaMeasurementSheet.getDepthOrHeight()); sheet.setLength(loaMeasurementSheet.getLength()); sheet.setLoaMeasurementSheet(loaMeasurementSheet); sheet.setMeasurementBookDetail(measurementBookDetail.getId()); sheet.setNumber(loaMeasurementSheet.getNumber()); sheet.setQuantity(loaMeasurementSheet.getQuantity()); sheet.setWidth(loaMeasurementSheet.getWidth()); sheet.setAuditDetails(measurementBookUtils.setAuditDetails(requestInfo, false)); measurementSheets.add(sheet); } measurementBookDetail.setMeasurementSheets(measurementSheets); measurementBookDetail.setQuantity(loaActivity.getApprovedQuantity().doubleValue()); measurementBookDetail.setRemarks(loaActivity.getRemarks()); measurementBookDetail.setAuditDetails(measurementBookUtils.setAuditDetails(requestInfo, false)); } } } /** * @param letterOfAcceptanceEstimate * @param detailedEstimate * @param auditDetails * * populate LOA activities after creating revision DE */ private void populateLOAActivities(LetterOfAcceptanceEstimate letterOfAcceptanceEstimate, DetailedEstimate detailedEstimate, AuditDetails auditDetails) { List<LOAActivity> loaActivities = new ArrayList<>(); for (EstimateActivity activity : detailedEstimate.getEstimateActivities()) { LOAActivity loaActivity = new LOAActivity(); loaActivity.setTenantId(activity.getTenantId()); loaActivity.setAuditDetails(auditDetails); loaActivity.setEstimateActivity(activity); loaActivity.setLetterOfAcceptanceEstimate(letterOfAcceptanceEstimate.getId()); List<LOAMeasurementSheet> loaMeasurementSheets = new ArrayList<>(); for (EstimateMeasurementSheet sheet : activity.getEstimateMeasurementSheets()) { LOAMeasurementSheet loaMeasurementSheet = new LOAMeasurementSheet(); loaMeasurementSheet.setTenantId(sheet.getTenantId()); loaMeasurementSheet.setAuditDetails(auditDetails); loaMeasurementSheet.setDepthOrHeight(sheet.getDepthOrHeight()); loaMeasurementSheet.setEstimateMeasurementSheet(sheet.getId()); loaMeasurementSheet.setLength(sheet.getLength()); loaMeasurementSheet.setLoaActivity(loaActivity.getId()); loaMeasurementSheet.setNumber(sheet.getNumber()); loaMeasurementSheet.setQuantity(sheet.getQuantity()); loaMeasurementSheet.setWidth(sheet.getWidth()); loaMeasurementSheets.add(loaMeasurementSheet); } loaActivity.setLoaMeasurements(loaMeasurementSheets); loaActivities.add(loaActivity); } letterOfAcceptanceEstimate.setLoaActivities(loaActivities); } public MeasurementBookResponse update(MeasurementBookRequest measurementBookRequest) { measurementBookValidator.validateMB(measurementBookRequest, false); for (MeasurementBook measurementBook : measurementBookRequest.getMeasurementBooks()) { for (MeasurementBookDetail measurementBookDetail : measurementBook.getMeasurementBookDetails()) { if (measurementBookDetail.getId() == null) measurementBookDetail.setId(UUID.randomUUID().toString().replace("-", "")); for (MBMeasurementSheet sheet : measurementBookDetail.getMeasurementSheets()) { if (sheet.getId() == null) sheet.setId(UUID.randomUUID().toString().replace("-", "")); sheet.setAuditDetails( measurementBookUtils.setAuditDetails(measurementBookRequest.getRequestInfo(), true)); } measurementBookDetail.setAuditDetails( measurementBookUtils.setAuditDetails(measurementBookRequest.getRequestInfo(), true)); } for (DocumentDetail detail : measurementBook.getDocumentDetails()) { if (detail.getId() == null) detail.setId(UUID.randomUUID().toString().replace("-", "")); detail.setObjectType("MeasurementBook"); detail.setAuditDetails( measurementBookUtils.setAuditDetails(measurementBookRequest.getRequestInfo(), true)); } measurementBook.setAuditDetails( measurementBookUtils.setAuditDetails(measurementBookRequest.getRequestInfo(), true)); if (measurementBook.getLumpSumMBDetails() != null && !measurementBook.getLumpSumMBDetails().isEmpty()) createUpdateRevisionEstimate(measurementBook, measurementBookRequest.getRequestInfo(), true); //updateStatus(measurementBook, false); } kafkaTemplate.send(propertiesManager.getWorksMBCreateUpdateTopic(), measurementBookRequest); MeasurementBookResponse measurementBookResponse = new MeasurementBookResponse(); measurementBookResponse.setMeasurementBooks(measurementBookRequest.getMeasurementBooks()); return measurementBookResponse; } public MeasurementBookResponse search(MeasurementBookSearchContract measurementBookSearchContract, RequestInfo requestInfo) { MeasurementBookResponse measurementBookResponse = new MeasurementBookResponse(); measurementBookResponse.setMeasurementBooks( measurementBookRepository.searchMeasurementBooks(measurementBookSearchContract, requestInfo)); return measurementBookResponse; } private Boolean isConfigRequired(String keyName, RequestInfo requestInfo, final String tenantId) { Boolean isSpilloverWFReq = false; JSONArray responseJSONArray = measurementBookUtils.getMDMSData(CommonConstants.APPCONFIGURATION_OBJECT, CommonConstants.CODE, keyName, tenantId, requestInfo, CommonConstants.MODULENAME_WORKS); if (responseJSONArray != null && !responseJSONArray.isEmpty()) { Map<String, Object> jsonMap = (Map<String, Object>) responseJSONArray.get(0); if (jsonMap.get("value").equals("Yes")) isSpilloverWFReq = true; } return isSpilloverWFReq; } }
20,650
0.784019
0.783438
409
49.488998
34.474335
140
false
false
0
0
0
0
0
0
2.850856
false
false
14
929601d1bcaeeb4fd47e22f2a0d47bcc3845b326
9,337,258,922,586
94ae56278c82bcd68604ae9e3db5818d2cbcdb7b
/commons/src/main/java/br/org/crea/commons/models/siacol/dtos/relatorios/RelSiacol14Dto.java
c3e4b3ab10045708ef090971bfe08e6fe38b4fe1
[]
no_license
mncoutinho/crea-rest-api
https://github.com/mncoutinho/crea-rest-api
442edbf75c63b8f25dcb13f90fa45a55413c1bca
2f8ba4b91d85bb3f0df511ce5b09d2ae370732cd
refs/heads/master
2022-06-03T13:13:16.832000
2019-10-12T15:24:23
2019-10-12T15:24:23
214,670,554
0
0
null
false
2022-05-20T21:12:06
2019-10-12T15:31:16
2019-10-12T15:31:59
2022-05-20T21:12:05
3,858
0
0
11
Java
false
false
package br.org.crea.commons.models.siacol.dtos.relatorios; import java.util.List; public class RelSiacol14Dto { private String mes; private List<Rel14DepartamentosSiacolDto> departamentos; public String getMes() { return mes; } public void setMes(String mes) { this.mes = mes; } public List<Rel14DepartamentosSiacolDto> getDepartamentos() { return departamentos; } public void setDepartamentos(List<Rel14DepartamentosSiacolDto> departamentos) { this.departamentos = departamentos; } }
UTF-8
Java
515
java
RelSiacol14Dto.java
Java
[]
null
[]
package br.org.crea.commons.models.siacol.dtos.relatorios; import java.util.List; public class RelSiacol14Dto { private String mes; private List<Rel14DepartamentosSiacolDto> departamentos; public String getMes() { return mes; } public void setMes(String mes) { this.mes = mes; } public List<Rel14DepartamentosSiacolDto> getDepartamentos() { return departamentos; } public void setDepartamentos(List<Rel14DepartamentosSiacolDto> departamentos) { this.departamentos = departamentos; } }
515
0.763107
0.747573
27
18.074074
22.6502
80
false
false
0
0
0
0
0
0
1.074074
false
false
14
b6146aec7000678d3538cb08ab6077c4f1e99727
9,337,258,923,241
30a60f3d8266218c8f85940e4b6a7eb7431508e1
/src/main/java/com/woowacourse/pelotonbackend/race/domain/RaceCategory.java
1197c17f1f59fc4c64b426044ef15605f53e7272
[]
no_license
JinJuMoon/2020-14f-guys
https://github.com/JinJuMoon/2020-14f-guys
6e32514571b2ea9c1876581006d1ccb351c7d143
7dd8808cdddda6f10c5d59c440c5d1af1d68b7ba
refs/heads/master
2022-12-04T13:18:28.178000
2020-07-13T05:17:47
2020-07-13T05:17:47
279,267,816
0
0
null
true
2020-07-20T10:24:17
2020-07-13T10:12:12
2020-07-13T10:12:14
2020-07-20T10:24:16
252
0
0
0
null
false
false
package com.woowacourse.pelotonbackend.race.domain; public enum RaceCategory { TIME }
UTF-8
Java
91
java
RaceCategory.java
Java
[]
null
[]
package com.woowacourse.pelotonbackend.race.domain; public enum RaceCategory { TIME }
91
0.78022
0.78022
5
17.200001
19.301813
51
false
false
0
0
0
0
0
0
0.2
false
false
14
076f763bf7c1a01acb74b8d232639853ea24a110
22,617,297,794,876
9a43c7116d6cda1b2e96635700e8ee8655ce0e58
/src/main/java/com/ibm/airlock/common/data/Entitlement.java
2ea6caab586f4401a5cd546e12c43bee7ba07826
[ "MIT" ]
permissive
IBM/airlock-sdk-common
https://github.com/IBM/airlock-sdk-common
04d8ff593d9271a8b95bb69bebceac938c821a48
2b0a4d4228a757cfba3cd7d48d994c78ffe5d8ec
refs/heads/master
2022-02-19T19:50:57.760000
2021-06-02T21:31:37
2021-06-02T21:31:37
201,275,133
0
4
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ibm.airlock.common.data; import com.ibm.airlock.common.util.BaseRawFeaturesJsonParser; import com.ibm.airlock.common.util.Constants; import org.json.JSONArray; import org.json.JSONObject; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.concurrent.CopyOnWriteArrayList; import javax.annotation.Nullable; /** * Object represents a feature in the feature map. * * @author Eitan Schreiber */ public class Entitlement extends Feature implements Serializable { private final String TAG = "airlock.Entitlement"; private Collection<PurchaseOption> purchaseOptions; private Collection<String> includedEntitlements; @Nullable private Entitlement parent; public Entitlement() { super(); purchaseOptions = new CopyOnWriteArrayList<>(); includedEntitlements = new CopyOnWriteArrayList<>(); setSource(Source.MISSING); } public Entitlement(JSONObject json) { super(json); // set configuration if (json.has(Constants.JSON_FEATURES_ATTRS)) { String tmpConfig = json.optString(Constants.JSON_FEATURES_ATTRS); setConfiguration(tmpConfig == null ? new JSONObject() : new JSONObject(tmpConfig)); } purchaseOptions = new CopyOnWriteArrayList<>(); includedEntitlements = new CopyOnWriteArrayList<>(); // the very first time an Entitlement is parsed from the default the source is DEFAULT if (json.has(Constants.JSON_FEATURE_FIELD_DEFAULT)) { setSource(Source.DEFAULT); name = json.optString(Constants.JSON_FEATURE_FIELD_NAMESPACE) + "." + json.optString(Constants.JSON_FEATURE_FIELD_NAME); } JSONArray purchaseOptionsArray = json.optJSONArray(Constants.JSON_FIELD_PURCHASE_OPTIONS); if (purchaseOptionsArray != null) { for (int i = 0; i < purchaseOptionsArray.length(); i++) { JSONObject purchaseOption = purchaseOptionsArray.getJSONObject(i); // skip MX if (purchaseOption.optString(Constants.JSON_FEATURE_FIELD_TYPE) != null && Type.valueOf(purchaseOption.optString(Constants.JSON_FEATURE_FIELD_TYPE)) == Type.PURCHASE_OPTIONS_MUTUAL_EXCLUSION_GROUP) { if (purchaseOption.optString(Constants.JSON_FIELD_PURCHASE_OPTIONS) != null) { JSONArray mxChildrenPurchaseOptionsArray = purchaseOption.optJSONArray(Constants.JSON_FIELD_PURCHASE_OPTIONS); for (int j = 0; j < mxChildrenPurchaseOptionsArray.length(); j++) { JSONObject mxChild = mxChildrenPurchaseOptionsArray.getJSONObject(j); purchaseOptions.add(new PurchaseOption(mxChild)); } } } else { purchaseOptions.add(new PurchaseOption(purchaseOptionsArray.getJSONObject(i))); } } } JSONArray includedEntitlementsArray = json.optJSONArray(Constants.JSON_FIELD_INCLUDED_ENTITLEMENTS); if (includedEntitlementsArray != null) { for (int i = 0; i < includedEntitlementsArray.length(); i++) { includedEntitlements.add(includedEntitlementsArray.getString(i)); } } setEnabledForAnalytics(BaseRawFeaturesJsonParser.getIsSendToAnalytics(json)); setAttributesForAnalytics(BaseRawFeaturesJsonParser.getConfigAttributesToAnalytics(json)); setAnalyticsAppliedRules(BaseRawFeaturesJsonParser.getAnalyticsAppliedRules(json)); setAnalyticsOrderedFeatures(BaseRawFeaturesJsonParser.getReorderedChildren(json)); setAnalyticsAppliedOrderRules(BaseRawFeaturesJsonParser.getAppliedOrderRules(json)); JSONArray childrenEntitlementsArray = json.optJSONArray(Constants.JSON_FEATURE_FIELD_ENTITLEMENTS); if (childrenEntitlementsArray != null) { for (int i = 0; i < childrenEntitlementsArray.length(); i++) { JSONObject child = childrenEntitlementsArray.getJSONObject(i); // skip MX if (child.optString(Constants.JSON_FEATURE_FIELD_TYPE) != null && Type.valueOf(child.optString(Constants.JSON_FEATURE_FIELD_TYPE)) == Type.ENTITLEMENT_MUTUAL_EXCLUSION_GROUP) { if (child.optString(Constants.JSON_FEATURE_FIELD_ENTITLEMENTS) != null) { JSONArray mxChildrenEntitlementsArray = child.optJSONArray(Constants.JSON_FEATURE_FIELD_ENTITLEMENTS); for (int j = 0; j < mxChildrenEntitlementsArray.length(); j++) { JSONObject mxChild = mxChildrenEntitlementsArray.getJSONObject(j); Entitlement entitlement = new Entitlement(mxChild); entitlement.setParent(this); addUpdateChild(entitlement); } } } else { Entitlement entitlement = new Entitlement(childrenEntitlementsArray.getJSONObject(i)); entitlement.setParent(this); addUpdateChild(entitlement); } } } } public boolean hasProductId(@Nullable String productId) { if (productId == null) { return false; } for (PurchaseOption purchaseOption : getPurchaseOptions()) { if (purchaseOption.getProductId().equals(productId)) { return true; } } return false; } public boolean isOn() { return isOn; } /** * @return the list of Entitlement children */ public Collection<Entitlement> getEntitlementChildren() { return Arrays.asList(children.toArray(new Entitlement[0])); } /** * @return the list of the included Entitlements, meaning the Entitlement is a bundle */ public Collection<String> getIncludedEntitlements() { return includedEntitlements; } /** * @return the list of available purchase options */ public Collection<PurchaseOption> getPurchaseOptions() { return purchaseOptions; } public void setPurchaseOptions(Collection<PurchaseOption> purchaseOptions) { this.purchaseOptions = purchaseOptions; } @Override @Nullable public Entitlement getParent() { return parent; } public void setParent(@Nullable Entitlement parent) { this.parent = parent; } public Entitlement(String name, boolean on, Source source, Collection<PurchaseOption> purchaseOptions) { super(name, on, source); this.purchaseOptions = purchaseOptions; } public Entitlement(String name, boolean on, Source source) { super(name, on, source); } @Override protected Entitlement getNew() { return new Entitlement(getName(), isOn(), getSource(), new ArrayList<PurchaseOption>(purchaseOptions)); } }
UTF-8
Java
7,114
java
Entitlement.java
Java
[ { "context": "esents a feature in the feature map.\n *\n * @author Eitan Schreiber\n */\npublic class Entitlement extends Feature impl", "end": 485, "score": 0.9998605847358704, "start": 470, "tag": "NAME", "value": "Eitan Schreiber" } ]
null
[]
package com.ibm.airlock.common.data; import com.ibm.airlock.common.util.BaseRawFeaturesJsonParser; import com.ibm.airlock.common.util.Constants; import org.json.JSONArray; import org.json.JSONObject; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.concurrent.CopyOnWriteArrayList; import javax.annotation.Nullable; /** * Object represents a feature in the feature map. * * @author <NAME> */ public class Entitlement extends Feature implements Serializable { private final String TAG = "airlock.Entitlement"; private Collection<PurchaseOption> purchaseOptions; private Collection<String> includedEntitlements; @Nullable private Entitlement parent; public Entitlement() { super(); purchaseOptions = new CopyOnWriteArrayList<>(); includedEntitlements = new CopyOnWriteArrayList<>(); setSource(Source.MISSING); } public Entitlement(JSONObject json) { super(json); // set configuration if (json.has(Constants.JSON_FEATURES_ATTRS)) { String tmpConfig = json.optString(Constants.JSON_FEATURES_ATTRS); setConfiguration(tmpConfig == null ? new JSONObject() : new JSONObject(tmpConfig)); } purchaseOptions = new CopyOnWriteArrayList<>(); includedEntitlements = new CopyOnWriteArrayList<>(); // the very first time an Entitlement is parsed from the default the source is DEFAULT if (json.has(Constants.JSON_FEATURE_FIELD_DEFAULT)) { setSource(Source.DEFAULT); name = json.optString(Constants.JSON_FEATURE_FIELD_NAMESPACE) + "." + json.optString(Constants.JSON_FEATURE_FIELD_NAME); } JSONArray purchaseOptionsArray = json.optJSONArray(Constants.JSON_FIELD_PURCHASE_OPTIONS); if (purchaseOptionsArray != null) { for (int i = 0; i < purchaseOptionsArray.length(); i++) { JSONObject purchaseOption = purchaseOptionsArray.getJSONObject(i); // skip MX if (purchaseOption.optString(Constants.JSON_FEATURE_FIELD_TYPE) != null && Type.valueOf(purchaseOption.optString(Constants.JSON_FEATURE_FIELD_TYPE)) == Type.PURCHASE_OPTIONS_MUTUAL_EXCLUSION_GROUP) { if (purchaseOption.optString(Constants.JSON_FIELD_PURCHASE_OPTIONS) != null) { JSONArray mxChildrenPurchaseOptionsArray = purchaseOption.optJSONArray(Constants.JSON_FIELD_PURCHASE_OPTIONS); for (int j = 0; j < mxChildrenPurchaseOptionsArray.length(); j++) { JSONObject mxChild = mxChildrenPurchaseOptionsArray.getJSONObject(j); purchaseOptions.add(new PurchaseOption(mxChild)); } } } else { purchaseOptions.add(new PurchaseOption(purchaseOptionsArray.getJSONObject(i))); } } } JSONArray includedEntitlementsArray = json.optJSONArray(Constants.JSON_FIELD_INCLUDED_ENTITLEMENTS); if (includedEntitlementsArray != null) { for (int i = 0; i < includedEntitlementsArray.length(); i++) { includedEntitlements.add(includedEntitlementsArray.getString(i)); } } setEnabledForAnalytics(BaseRawFeaturesJsonParser.getIsSendToAnalytics(json)); setAttributesForAnalytics(BaseRawFeaturesJsonParser.getConfigAttributesToAnalytics(json)); setAnalyticsAppliedRules(BaseRawFeaturesJsonParser.getAnalyticsAppliedRules(json)); setAnalyticsOrderedFeatures(BaseRawFeaturesJsonParser.getReorderedChildren(json)); setAnalyticsAppliedOrderRules(BaseRawFeaturesJsonParser.getAppliedOrderRules(json)); JSONArray childrenEntitlementsArray = json.optJSONArray(Constants.JSON_FEATURE_FIELD_ENTITLEMENTS); if (childrenEntitlementsArray != null) { for (int i = 0; i < childrenEntitlementsArray.length(); i++) { JSONObject child = childrenEntitlementsArray.getJSONObject(i); // skip MX if (child.optString(Constants.JSON_FEATURE_FIELD_TYPE) != null && Type.valueOf(child.optString(Constants.JSON_FEATURE_FIELD_TYPE)) == Type.ENTITLEMENT_MUTUAL_EXCLUSION_GROUP) { if (child.optString(Constants.JSON_FEATURE_FIELD_ENTITLEMENTS) != null) { JSONArray mxChildrenEntitlementsArray = child.optJSONArray(Constants.JSON_FEATURE_FIELD_ENTITLEMENTS); for (int j = 0; j < mxChildrenEntitlementsArray.length(); j++) { JSONObject mxChild = mxChildrenEntitlementsArray.getJSONObject(j); Entitlement entitlement = new Entitlement(mxChild); entitlement.setParent(this); addUpdateChild(entitlement); } } } else { Entitlement entitlement = new Entitlement(childrenEntitlementsArray.getJSONObject(i)); entitlement.setParent(this); addUpdateChild(entitlement); } } } } public boolean hasProductId(@Nullable String productId) { if (productId == null) { return false; } for (PurchaseOption purchaseOption : getPurchaseOptions()) { if (purchaseOption.getProductId().equals(productId)) { return true; } } return false; } public boolean isOn() { return isOn; } /** * @return the list of Entitlement children */ public Collection<Entitlement> getEntitlementChildren() { return Arrays.asList(children.toArray(new Entitlement[0])); } /** * @return the list of the included Entitlements, meaning the Entitlement is a bundle */ public Collection<String> getIncludedEntitlements() { return includedEntitlements; } /** * @return the list of available purchase options */ public Collection<PurchaseOption> getPurchaseOptions() { return purchaseOptions; } public void setPurchaseOptions(Collection<PurchaseOption> purchaseOptions) { this.purchaseOptions = purchaseOptions; } @Override @Nullable public Entitlement getParent() { return parent; } public void setParent(@Nullable Entitlement parent) { this.parent = parent; } public Entitlement(String name, boolean on, Source source, Collection<PurchaseOption> purchaseOptions) { super(name, on, source); this.purchaseOptions = purchaseOptions; } public Entitlement(String name, boolean on, Source source) { super(name, on, source); } @Override protected Entitlement getNew() { return new Entitlement(getName(), isOn(), getSource(), new ArrayList<PurchaseOption>(purchaseOptions)); } }
7,105
0.639303
0.638459
183
37.874317
36.257435
148
false
false
0
0
0
0
0
0
0.469945
false
false
14
f1c3e2379f24314a5edd2f58bb52c46fabcc6708
24,446,953,908,725
6e62362ee11050530fdd986b5d8561db4fb7d49a
/six_feet/app/src/main/java/com/mindrops/sixfeet/ARActivity.java
94c4ac0b25c15b034daab5249071a9a3cb7d8ede
[]
no_license
Zeuskartik/AR-Line-Draw
https://github.com/Zeuskartik/AR-Line-Draw
ab6e7d4ffc45b8481fae72d10e0f8634980767f9
d0f5150fdacac8091d3c4fc97eb023e1ad11eb2e
refs/heads/master
2021-01-03T05:54:25.467000
2020-12-01T06:17:58
2020-12-01T06:17:58
239,950,857
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mindrops.sixfeet; import android.content.Context; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.VibrationEffect; import android.os.Vibrator; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import androidx.cardview.widget.CardView; import com.google.ar.core.Anchor; import com.google.ar.core.Config; import com.google.ar.core.Frame; import com.google.ar.core.HitResult; import com.google.ar.core.Plane; import com.google.ar.core.Trackable; import com.google.ar.core.TrackingState; import com.google.ar.sceneform.AnchorNode; import com.google.ar.sceneform.FrameTime; import com.google.ar.sceneform.Node; import com.google.ar.sceneform.Scene; import com.google.ar.sceneform.math.Quaternion; import com.google.ar.sceneform.math.Vector3; import com.google.ar.sceneform.rendering.Color; import com.google.ar.sceneform.rendering.Material; import com.google.ar.sceneform.rendering.MaterialFactory; import com.google.ar.sceneform.rendering.ModelRenderable; import com.google.ar.sceneform.rendering.Renderable; import com.google.ar.sceneform.ux.ArFragment; import com.google.ar.sceneform.ux.TransformableNode; import java.util.Collection; import java.util.List; public class ARActivity extends AppCompatActivity implements Scene.OnUpdateListener { private ArFragment arFragment; private Config config; private ImageView targetLayout; private TextView distanceTv, startButtonLayout, warningTv; private Anchor hitAnchor; private AnchorNode firstAnchorNode; private AnchorNode firstPointNode; private AnchorNode lastAnchorNode; private AnchorNode lineNode; private AnchorNode endPointNode; private boolean isTracking; private boolean isHitting; private boolean firstPointReceived = false; private Color yellowLineColor = new Color(238.00f / 255.00f, 189.00f / 255.00f, 15.00f / 255.00f); private Color greenLineColor = new Color(0.00f / 255.00f, 214.00f / 255.00f, 145.00f / 255.00f); private Color lineColor; double currentDistance = 0.0; boolean sixFeetCovered = false; TextView resetBtn, finishBtn, descrTv; String distanceFormatted; CardView distanceCv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_ar); targetLayout = findViewById(R.id.target_button); startButtonLayout = findViewById(R.id.start_button); warningTv = findViewById(R.id.warning_tv); distanceTv = findViewById(R.id.distance_tv); lineColor = yellowLineColor; distanceCv = findViewById(R.id.ditanceCv); arFragment = (ArFragment) getSupportFragmentManager().findFragmentById(R.id.arFragment); resetBtn = findViewById(R.id.reset_btn); finishBtn = findViewById(R.id.finish_btn); descrTv = findViewById(R.id.descrText_Tv); resetBtn.setOnClickListener(v -> { try { if (firstAnchorNode != null) { arFragment.getArSceneView().getScene().removeOnUpdateListener(this); firstAnchorNode.setRenderable(null); arFragment.getArSceneView().getScene().removeChild(firstAnchorNode); firstAnchorNode = null; firstPointReceived = false; } if (lineNode != null) { lineNode.setRenderable(null); lastAnchorNode.removeChild(lineNode); lineNode = null; } if (endPointNode != null) { endPointNode.setRenderable(null); lastAnchorNode.removeChild(endPointNode); endPointNode = null; } if (lastAnchorNode != null) { lastAnchorNode.setRenderable(null); arFragment.getArSceneView().getScene().removeChild(lastAnchorNode); lastAnchorNode = null; } } catch (Exception e) { e.printStackTrace(); Log.d("##### Exception --> ", "exception occurred"); } resetBtn.setVisibility(View.GONE); finishBtn.setVisibility(View.GONE); distanceCv.setVisibility(View.GONE); descrTv.setVisibility(View.GONE); sixFeetCovered = false; lineColor = yellowLineColor; new Handler().postDelayed(() -> showControls(true), 1500); }); } @Override protected void onPause() { super.onPause(); } @Override protected void onResume() { super.onResume(); initArFragment(); } private void initArFragment() { if (arFragment != null) { arFragment.getArSceneView().getPlaneRenderer().setVisible(true); hideControls(true); } } private void onFrameDetected(FrameTime frameTime) { boolean trackingChanged = updateTracking(); View contentView = findViewById(android.R.id.content); if (trackingChanged) { if (isTracking) { new Handler().postDelayed( () -> { showControls(false); }, 1500 ); } else { hideControls(true); } contentView.invalidate(); } if (isTracking) { boolean hitTestChanged = updateHitTest(); if (hitTestChanged) { contentView.invalidate(); } } } private boolean updateTracking() { Frame frame = arFragment.getArSceneView().getArFrame(); boolean wasTracking = isTracking; /*isTracking = frame != null && frame.getCamera().getTrackingState() == TrackingState.TRACKING;*/ assert frame != null; Collection<Plane> planes = frame.getUpdatedTrackables(Plane.class); for (Plane p : planes) { isTracking = p.getTrackingState() == TrackingState.TRACKING; } return isTracking != wasTracking; } private boolean updateHitTest() { Frame frame = arFragment.getArSceneView().getArFrame(); android.graphics.Point pt = getScreenCenter(); List<HitResult> hits; boolean wasHitting = isHitting; isHitting = false; if (frame != null) { hits = frame.hitTest(pt.x, pt.y); for (HitResult hit : hits) { Trackable trackable = hit.getTrackable(); if (trackable instanceof Plane && ((Plane) trackable).isPoseInPolygon(hit.getHitPose())) { isHitting = true; hitAnchor = hit.createAnchor(); if (firstPointReceived && isTracking) { placePointsOnScreen(hit.createAnchor()); } break; } } } return wasHitting != isHitting; } private android.graphics.Point getScreenCenter() { View vw = findViewById(android.R.id.content); return new android.graphics.Point(vw.getWidth() / 2, vw.getHeight() / 2); } private void placePointsOnScreen(Anchor anchor) { AnchorNode anchorNode = new AnchorNode(anchor); hideControls(false); if (firstPointReceived) { anchorNode.setParent(arFragment.getArSceneView().getScene()); Vector3 point1, point2; point1 = firstAnchorNode.getWorldPosition(); point2 = anchorNode.getWorldPosition(); calculateDistanceInMeters(point1, point2); final Vector3 difference = Vector3.subtract(point2, point1); final Vector3 directionFromTopToBottom = difference.normalized(); final Quaternion rotationFromAToB = Quaternion.lookRotation(directionFromTopToBottom, Vector3.up()); if (currentDistance < 2.02 && !sixFeetCovered) { MaterialFactory.makeOpaqueWithColor(this, lineColor) .thenAccept( material -> { if (lineNode == null) { lineNode = new AnchorNode(); firstPointNode = new AnchorNode(); endPointNode = new AnchorNode(); } else { lastAnchorNode.removeChild(firstPointNode); lastAnchorNode.removeChild(endPointNode); lastAnchorNode.removeChild(lineNode); } createPoint(firstPointNode, new Vector3(0F, 0F, -difference.length()/2F)); createPoint(endPointNode, new Vector3(0F, 0F, difference.length()/2F)); firstPointNode.setParent(lineNode); endPointNode.setParent(lineNode); lineNode.setRenderable(getModel(material, difference)); lineNode.setParent(anchorNode); Vector3 abc = Vector3.add(point1, point2).scaled(.5f); Log.e("Position","Line:"+abc.x+abc.y+abc.z); lineNode.setWorldPosition(Vector3.add(point1, point2).scaled(.5f)); lineNode.setWorldRotation(rotationFromAToB); if (lineColor.equals(greenLineColor)) { sixFeetCovered = true; warningTv.setVisibility(View.GONE); distanceTv.setText("2.0m"); showPopup(); } } ); lastAnchorNode = anchorNode; } } } private void showPopup() { Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); // Vibrate for 500 milliseconds if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { v.vibrate(VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE)); } else { //deprecated in API 26 v.vibrate(500); } distanceTv.setVisibility(View.GONE); warningTv.setVisibility(View.GONE); descrTv.setVisibility(View.VISIBLE); finishBtn.setVisibility(View.VISIBLE); } private void calculateDistanceInMeters(Vector3 point1, Vector3 point2) { float dx = point2.x - point1.x; float dy = point2.y - point1.y; float dz = point2.z - point1.z; float dist = (float) (Math.sqrt((dx * dx + dy * dy + dz * dz))); distanceFormatted = String.format("%.1f", dist); currentDistance = dist; if (currentDistance < 1.98) { lineColor = yellowLineColor; } else if (currentDistance > 1.98 && currentDistance < 2.02) { lineColor = greenLineColor; } if (currentDistance > 2.02 && !sixFeetCovered) { warningTv.setVisibility(View.VISIBLE); } else { warningTv.setVisibility(View.GONE); } if (!sixFeetCovered && currentDistance < 2.02) { distanceTv.setVisibility(View.VISIBLE); distanceTv.setText(String.format("%sm", distanceFormatted)); } } private Renderable getModel(Material material, Vector3 difference) { //Cubical line ModelRenderable model = CustomShapeFactory.createCustomLine( new Vector3(.013f, .01f, difference.length()), Vector3.zero(), material); model.setShadowCaster(false); model.setShadowReceiver(false); return model; } public void showControls(Boolean shouldInitListener) { distanceTv.setVisibility(View.VISIBLE); arFragment.getPlaneDiscoveryController().hide(); //disablePlaneDiscovery(); if (shouldInitListener) { arFragment.getArSceneView().getScene().addOnUpdateListener(this); } targetLayout.setVisibility(View.VISIBLE); startButtonLayout.setVisibility(View.VISIBLE); startButtonLayout.setOnClickListener(v -> { createFirstAnchor(hitAnchor); resetBtn.setVisibility(View.VISIBLE); distanceCv.setVisibility(View.VISIBLE); }); } private void createPoint(Node node, Vector3 center) { MaterialFactory.makeTransparentWithColor(getApplicationContext(), lineColor).thenAccept(material -> { ModelRenderable modelRenderable = CustomShapeFactory.createPoint(center, material); modelRenderable.setShadowCaster(false); modelRenderable.setShadowReceiver(false); node.setRenderable(modelRenderable); }); } private void createFirstAnchor(Anchor hitAnchor) { hideControls(false); firstAnchorNode = new AnchorNode(hitAnchor); arFragment.getArSceneView().getScene().addChild(firstAnchorNode); firstPointReceived = true; } public void hideControls(boolean showPlaneDiscovery) { if (showPlaneDiscovery) { arFragment.getPlaneDiscoveryController().show(); distanceTv.setVisibility(View.GONE); //enablePlaneDiscovery(); } arFragment.getArSceneView().getScene().addOnUpdateListener(this); targetLayout.setVisibility(View.GONE); startButtonLayout.setVisibility(View.GONE); } private void enablePlaneDiscovery() { if (arFragment.getArSceneView().getSession() != null) { config = arFragment.getArSceneView().getSession().getConfig(); config.setPlaneFindingMode(Config.PlaneFindingMode.HORIZONTAL); arFragment.getArSceneView().getSession().configure(config); } } private void disablePlaneDiscovery() { if (arFragment.getArSceneView().getSession() != null) { config = arFragment.getArSceneView().getSession().getConfig(); config.setPlaneFindingMode(Config.PlaneFindingMode.DISABLED); arFragment.getArSceneView().getSession().configure(config); } } @Override public void onUpdate(FrameTime frameTime) { onFrameDetected(frameTime); } }
UTF-8
Java
14,771
java
ARActivity.java
Java
[]
null
[]
package com.mindrops.sixfeet; import android.content.Context; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.VibrationEffect; import android.os.Vibrator; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import androidx.cardview.widget.CardView; import com.google.ar.core.Anchor; import com.google.ar.core.Config; import com.google.ar.core.Frame; import com.google.ar.core.HitResult; import com.google.ar.core.Plane; import com.google.ar.core.Trackable; import com.google.ar.core.TrackingState; import com.google.ar.sceneform.AnchorNode; import com.google.ar.sceneform.FrameTime; import com.google.ar.sceneform.Node; import com.google.ar.sceneform.Scene; import com.google.ar.sceneform.math.Quaternion; import com.google.ar.sceneform.math.Vector3; import com.google.ar.sceneform.rendering.Color; import com.google.ar.sceneform.rendering.Material; import com.google.ar.sceneform.rendering.MaterialFactory; import com.google.ar.sceneform.rendering.ModelRenderable; import com.google.ar.sceneform.rendering.Renderable; import com.google.ar.sceneform.ux.ArFragment; import com.google.ar.sceneform.ux.TransformableNode; import java.util.Collection; import java.util.List; public class ARActivity extends AppCompatActivity implements Scene.OnUpdateListener { private ArFragment arFragment; private Config config; private ImageView targetLayout; private TextView distanceTv, startButtonLayout, warningTv; private Anchor hitAnchor; private AnchorNode firstAnchorNode; private AnchorNode firstPointNode; private AnchorNode lastAnchorNode; private AnchorNode lineNode; private AnchorNode endPointNode; private boolean isTracking; private boolean isHitting; private boolean firstPointReceived = false; private Color yellowLineColor = new Color(238.00f / 255.00f, 189.00f / 255.00f, 15.00f / 255.00f); private Color greenLineColor = new Color(0.00f / 255.00f, 214.00f / 255.00f, 145.00f / 255.00f); private Color lineColor; double currentDistance = 0.0; boolean sixFeetCovered = false; TextView resetBtn, finishBtn, descrTv; String distanceFormatted; CardView distanceCv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_ar); targetLayout = findViewById(R.id.target_button); startButtonLayout = findViewById(R.id.start_button); warningTv = findViewById(R.id.warning_tv); distanceTv = findViewById(R.id.distance_tv); lineColor = yellowLineColor; distanceCv = findViewById(R.id.ditanceCv); arFragment = (ArFragment) getSupportFragmentManager().findFragmentById(R.id.arFragment); resetBtn = findViewById(R.id.reset_btn); finishBtn = findViewById(R.id.finish_btn); descrTv = findViewById(R.id.descrText_Tv); resetBtn.setOnClickListener(v -> { try { if (firstAnchorNode != null) { arFragment.getArSceneView().getScene().removeOnUpdateListener(this); firstAnchorNode.setRenderable(null); arFragment.getArSceneView().getScene().removeChild(firstAnchorNode); firstAnchorNode = null; firstPointReceived = false; } if (lineNode != null) { lineNode.setRenderable(null); lastAnchorNode.removeChild(lineNode); lineNode = null; } if (endPointNode != null) { endPointNode.setRenderable(null); lastAnchorNode.removeChild(endPointNode); endPointNode = null; } if (lastAnchorNode != null) { lastAnchorNode.setRenderable(null); arFragment.getArSceneView().getScene().removeChild(lastAnchorNode); lastAnchorNode = null; } } catch (Exception e) { e.printStackTrace(); Log.d("##### Exception --> ", "exception occurred"); } resetBtn.setVisibility(View.GONE); finishBtn.setVisibility(View.GONE); distanceCv.setVisibility(View.GONE); descrTv.setVisibility(View.GONE); sixFeetCovered = false; lineColor = yellowLineColor; new Handler().postDelayed(() -> showControls(true), 1500); }); } @Override protected void onPause() { super.onPause(); } @Override protected void onResume() { super.onResume(); initArFragment(); } private void initArFragment() { if (arFragment != null) { arFragment.getArSceneView().getPlaneRenderer().setVisible(true); hideControls(true); } } private void onFrameDetected(FrameTime frameTime) { boolean trackingChanged = updateTracking(); View contentView = findViewById(android.R.id.content); if (trackingChanged) { if (isTracking) { new Handler().postDelayed( () -> { showControls(false); }, 1500 ); } else { hideControls(true); } contentView.invalidate(); } if (isTracking) { boolean hitTestChanged = updateHitTest(); if (hitTestChanged) { contentView.invalidate(); } } } private boolean updateTracking() { Frame frame = arFragment.getArSceneView().getArFrame(); boolean wasTracking = isTracking; /*isTracking = frame != null && frame.getCamera().getTrackingState() == TrackingState.TRACKING;*/ assert frame != null; Collection<Plane> planes = frame.getUpdatedTrackables(Plane.class); for (Plane p : planes) { isTracking = p.getTrackingState() == TrackingState.TRACKING; } return isTracking != wasTracking; } private boolean updateHitTest() { Frame frame = arFragment.getArSceneView().getArFrame(); android.graphics.Point pt = getScreenCenter(); List<HitResult> hits; boolean wasHitting = isHitting; isHitting = false; if (frame != null) { hits = frame.hitTest(pt.x, pt.y); for (HitResult hit : hits) { Trackable trackable = hit.getTrackable(); if (trackable instanceof Plane && ((Plane) trackable).isPoseInPolygon(hit.getHitPose())) { isHitting = true; hitAnchor = hit.createAnchor(); if (firstPointReceived && isTracking) { placePointsOnScreen(hit.createAnchor()); } break; } } } return wasHitting != isHitting; } private android.graphics.Point getScreenCenter() { View vw = findViewById(android.R.id.content); return new android.graphics.Point(vw.getWidth() / 2, vw.getHeight() / 2); } private void placePointsOnScreen(Anchor anchor) { AnchorNode anchorNode = new AnchorNode(anchor); hideControls(false); if (firstPointReceived) { anchorNode.setParent(arFragment.getArSceneView().getScene()); Vector3 point1, point2; point1 = firstAnchorNode.getWorldPosition(); point2 = anchorNode.getWorldPosition(); calculateDistanceInMeters(point1, point2); final Vector3 difference = Vector3.subtract(point2, point1); final Vector3 directionFromTopToBottom = difference.normalized(); final Quaternion rotationFromAToB = Quaternion.lookRotation(directionFromTopToBottom, Vector3.up()); if (currentDistance < 2.02 && !sixFeetCovered) { MaterialFactory.makeOpaqueWithColor(this, lineColor) .thenAccept( material -> { if (lineNode == null) { lineNode = new AnchorNode(); firstPointNode = new AnchorNode(); endPointNode = new AnchorNode(); } else { lastAnchorNode.removeChild(firstPointNode); lastAnchorNode.removeChild(endPointNode); lastAnchorNode.removeChild(lineNode); } createPoint(firstPointNode, new Vector3(0F, 0F, -difference.length()/2F)); createPoint(endPointNode, new Vector3(0F, 0F, difference.length()/2F)); firstPointNode.setParent(lineNode); endPointNode.setParent(lineNode); lineNode.setRenderable(getModel(material, difference)); lineNode.setParent(anchorNode); Vector3 abc = Vector3.add(point1, point2).scaled(.5f); Log.e("Position","Line:"+abc.x+abc.y+abc.z); lineNode.setWorldPosition(Vector3.add(point1, point2).scaled(.5f)); lineNode.setWorldRotation(rotationFromAToB); if (lineColor.equals(greenLineColor)) { sixFeetCovered = true; warningTv.setVisibility(View.GONE); distanceTv.setText("2.0m"); showPopup(); } } ); lastAnchorNode = anchorNode; } } } private void showPopup() { Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); // Vibrate for 500 milliseconds if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { v.vibrate(VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE)); } else { //deprecated in API 26 v.vibrate(500); } distanceTv.setVisibility(View.GONE); warningTv.setVisibility(View.GONE); descrTv.setVisibility(View.VISIBLE); finishBtn.setVisibility(View.VISIBLE); } private void calculateDistanceInMeters(Vector3 point1, Vector3 point2) { float dx = point2.x - point1.x; float dy = point2.y - point1.y; float dz = point2.z - point1.z; float dist = (float) (Math.sqrt((dx * dx + dy * dy + dz * dz))); distanceFormatted = String.format("%.1f", dist); currentDistance = dist; if (currentDistance < 1.98) { lineColor = yellowLineColor; } else if (currentDistance > 1.98 && currentDistance < 2.02) { lineColor = greenLineColor; } if (currentDistance > 2.02 && !sixFeetCovered) { warningTv.setVisibility(View.VISIBLE); } else { warningTv.setVisibility(View.GONE); } if (!sixFeetCovered && currentDistance < 2.02) { distanceTv.setVisibility(View.VISIBLE); distanceTv.setText(String.format("%sm", distanceFormatted)); } } private Renderable getModel(Material material, Vector3 difference) { //Cubical line ModelRenderable model = CustomShapeFactory.createCustomLine( new Vector3(.013f, .01f, difference.length()), Vector3.zero(), material); model.setShadowCaster(false); model.setShadowReceiver(false); return model; } public void showControls(Boolean shouldInitListener) { distanceTv.setVisibility(View.VISIBLE); arFragment.getPlaneDiscoveryController().hide(); //disablePlaneDiscovery(); if (shouldInitListener) { arFragment.getArSceneView().getScene().addOnUpdateListener(this); } targetLayout.setVisibility(View.VISIBLE); startButtonLayout.setVisibility(View.VISIBLE); startButtonLayout.setOnClickListener(v -> { createFirstAnchor(hitAnchor); resetBtn.setVisibility(View.VISIBLE); distanceCv.setVisibility(View.VISIBLE); }); } private void createPoint(Node node, Vector3 center) { MaterialFactory.makeTransparentWithColor(getApplicationContext(), lineColor).thenAccept(material -> { ModelRenderable modelRenderable = CustomShapeFactory.createPoint(center, material); modelRenderable.setShadowCaster(false); modelRenderable.setShadowReceiver(false); node.setRenderable(modelRenderable); }); } private void createFirstAnchor(Anchor hitAnchor) { hideControls(false); firstAnchorNode = new AnchorNode(hitAnchor); arFragment.getArSceneView().getScene().addChild(firstAnchorNode); firstPointReceived = true; } public void hideControls(boolean showPlaneDiscovery) { if (showPlaneDiscovery) { arFragment.getPlaneDiscoveryController().show(); distanceTv.setVisibility(View.GONE); //enablePlaneDiscovery(); } arFragment.getArSceneView().getScene().addOnUpdateListener(this); targetLayout.setVisibility(View.GONE); startButtonLayout.setVisibility(View.GONE); } private void enablePlaneDiscovery() { if (arFragment.getArSceneView().getSession() != null) { config = arFragment.getArSceneView().getSession().getConfig(); config.setPlaneFindingMode(Config.PlaneFindingMode.HORIZONTAL); arFragment.getArSceneView().getSession().configure(config); } } private void disablePlaneDiscovery() { if (arFragment.getArSceneView().getSession() != null) { config = arFragment.getArSceneView().getSession().getConfig(); config.setPlaneFindingMode(Config.PlaneFindingMode.DISABLED); arFragment.getArSceneView().getSession().configure(config); } } @Override public void onUpdate(FrameTime frameTime) { onFrameDetected(frameTime); } }
14,771
0.592919
0.582696
378
38.076721
26.170624
112
false
false
0
0
0
0
0
0
0.669312
false
false
14
7532824104f055aa14df97ff8e6d242c3db0e734
15,032,385,590,849
e481900c931590ad30fdb0108982c2868376b697
/src/main/java/com/fun/business/sharon/biz/business/bean/news/EHtml.java
d3f1995a56b1f216ffc10c57a9835472707febc6
[]
no_license
liangxin7788/ivs-rfid
https://github.com/liangxin7788/ivs-rfid
18343b8e9aa2386dadbb1d6e9647a5a20584dc9d
f1c4b9f68d7a085189b9aeeeb46d441a04e063c7
refs/heads/master
2023-04-07T20:30:13.398000
2021-05-24T09:18:28
2021-05-24T09:18:28
225,319,101
0
0
null
false
2023-03-27T22:19:05
2019-12-02T08:06:01
2021-05-24T09:20:32
2023-03-27T22:19:04
218
0
0
3
Java
false
false
package com.fun.business.sharon.biz.business.bean.news; import com.fasterxml.jackson.annotation.JsonView; import lombok.Data; @Data public class EHtml { interface Hide{} public interface Show{} private String title;// 标题 // @JsonView(Hide.class) private String tit_url; // 详细 @JsonView(Hide.class) private String detail_url; private int clicks; // 热度值 // @JsonView(Hide.class) private String trend; // 热度趋势 }
UTF-8
Java
489
java
EHtml.java
Java
[]
null
[]
package com.fun.business.sharon.biz.business.bean.news; import com.fasterxml.jackson.annotation.JsonView; import lombok.Data; @Data public class EHtml { interface Hide{} public interface Show{} private String title;// 标题 // @JsonView(Hide.class) private String tit_url; // 详细 @JsonView(Hide.class) private String detail_url; private int clicks; // 热度值 // @JsonView(Hide.class) private String trend; // 热度趋势 }
489
0.668094
0.668094
26
16.961538
16.125662
55
false
false
0
0
0
0
0
0
0.384615
false
false
14
891c61c399e6deaf5c87e7bf9303dce2f81d59ca
17,875,653,892,859
82ab571aca88fbe455a8f42f0e2f0369f556180e
/app/src/main/java/com/colpencil/redwood/view/activity/mine/SpecialActivity.java
1daf02c44bd46e67c8b2ae9e08156df90b095180
[]
no_license
zsj6102/zz
https://github.com/zsj6102/zz
61d5c28dc0a0faf53000d4d5c802ba6ab9184d25
618bd83fd936870c2458ac5928f75be00add8cdb
refs/heads/master
2020-12-02T22:55:32.820000
2017-07-12T14:48:04
2017-07-12T14:48:04
96,203,483
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.colpencil.redwood.view.activity.mine; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.colpencil.redwood.R; import com.colpencil.redwood.view.fragments.SpecialPastFragment; import com.colpencil.redwood.view.fragments.mine.CardWallFragment; import com.colpencil.redwood.view.fragments.mine.DynamicFragment; import com.colpencil.redwood.view.fragments.mine.SpecialCollectionFragment; import com.colpencil.redwood.view.fragments.mine.SpecialIntroduceFragment; import com.property.colpencil.colpencilandroidlibrary.ControlerBase.MVP.ColpencilActivity; import com.property.colpencil.colpencilandroidlibrary.ControlerBase.MVP.ColpencilPresenter; import com.property.colpencil.colpencilandroidlibrary.Function.Annotation.ActivityFragmentInject; import java.util.ArrayList; import java.util.List; import butterknife.Bind; /**@author QFZ * @deprecated 专场 * @date 2017/3/3. */ @ActivityFragmentInject( contentViewId = R.layout.activity_special ) public class SpecialActivity extends ColpencilActivity { @Bind(R.id.iv_back) ImageView iv_back; @Bind(R.id.tv_main_title) TextView tv_main_title; @Bind(R.id.tab_layout) TabLayout tab_layout; @Bind(R.id.viewpager) ViewPager viewpage; @Bind(R.id.totop_iv) ImageView totop_iv; @Bind(R.id.iv_post) ImageView iv_post; private MyPageAdapter adapter; private int special_id; private String special_name; @Override protected void initViews(View view) { special_id=getIntent().getIntExtra("special_id",0); special_name=getIntent().getStringExtra("special_name"); totop_iv.setImageResource(R.mipmap.totop_icon); iv_post.setImageResource(R.mipmap.release_icon); tv_main_title.setText(special_name); adapter=new MyPageAdapter(getSupportFragmentManager()); adapter.addFragment(SpecialIntroduceFragment.newInstance(special_id) ,"专场介绍"); adapter.addFragment(SpecialCollectionFragment.newInstance(special_id) ,"该场藏品"); adapter.addFragment(CardWallFragment.newInstance(0) ,"驻场名人"); tab_layout.addTab(tab_layout.newTab().setText("专场介绍")); tab_layout.addTab(tab_layout.newTab().setText("该场藏品")); tab_layout.addTab(tab_layout.newTab().setText("驻场名人")); viewpage.setAdapter(adapter); tab_layout.setupWithViewPager(viewpage); } @Override public ColpencilPresenter getPresenter() { return null; } @Override public void bindView(Bundle savedInstanceState) { } class MyPageAdapter extends FragmentPagerAdapter{ private List<Fragment> mFragments=new ArrayList<>(); private List<String> titles=new ArrayList<>(); public MyPageAdapter(FragmentManager fm){ super(fm); } public void addFragment(Fragment fragment, String title){ mFragments.add(fragment); titles.add(title); } @Override public Fragment getItem(int position) { return mFragments.get(position); } @Override public int getCount() { return titles.size(); } @Override public CharSequence getPageTitle(int position) { return titles.get(position); } } }
UTF-8
Java
3,644
java
SpecialActivity.java
Java
[ { "context": ".util.List;\n\nimport butterknife.Bind;\n\n/**@author QFZ\n * @deprecated 专场\n * @date 2017/3/3.\n */\n@Activi", "end": 1154, "score": 0.9989171028137207, "start": 1151, "tag": "USERNAME", "value": "QFZ" } ]
null
[]
package com.colpencil.redwood.view.activity.mine; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.colpencil.redwood.R; import com.colpencil.redwood.view.fragments.SpecialPastFragment; import com.colpencil.redwood.view.fragments.mine.CardWallFragment; import com.colpencil.redwood.view.fragments.mine.DynamicFragment; import com.colpencil.redwood.view.fragments.mine.SpecialCollectionFragment; import com.colpencil.redwood.view.fragments.mine.SpecialIntroduceFragment; import com.property.colpencil.colpencilandroidlibrary.ControlerBase.MVP.ColpencilActivity; import com.property.colpencil.colpencilandroidlibrary.ControlerBase.MVP.ColpencilPresenter; import com.property.colpencil.colpencilandroidlibrary.Function.Annotation.ActivityFragmentInject; import java.util.ArrayList; import java.util.List; import butterknife.Bind; /**@author QFZ * @deprecated 专场 * @date 2017/3/3. */ @ActivityFragmentInject( contentViewId = R.layout.activity_special ) public class SpecialActivity extends ColpencilActivity { @Bind(R.id.iv_back) ImageView iv_back; @Bind(R.id.tv_main_title) TextView tv_main_title; @Bind(R.id.tab_layout) TabLayout tab_layout; @Bind(R.id.viewpager) ViewPager viewpage; @Bind(R.id.totop_iv) ImageView totop_iv; @Bind(R.id.iv_post) ImageView iv_post; private MyPageAdapter adapter; private int special_id; private String special_name; @Override protected void initViews(View view) { special_id=getIntent().getIntExtra("special_id",0); special_name=getIntent().getStringExtra("special_name"); totop_iv.setImageResource(R.mipmap.totop_icon); iv_post.setImageResource(R.mipmap.release_icon); tv_main_title.setText(special_name); adapter=new MyPageAdapter(getSupportFragmentManager()); adapter.addFragment(SpecialIntroduceFragment.newInstance(special_id) ,"专场介绍"); adapter.addFragment(SpecialCollectionFragment.newInstance(special_id) ,"该场藏品"); adapter.addFragment(CardWallFragment.newInstance(0) ,"驻场名人"); tab_layout.addTab(tab_layout.newTab().setText("专场介绍")); tab_layout.addTab(tab_layout.newTab().setText("该场藏品")); tab_layout.addTab(tab_layout.newTab().setText("驻场名人")); viewpage.setAdapter(adapter); tab_layout.setupWithViewPager(viewpage); } @Override public ColpencilPresenter getPresenter() { return null; } @Override public void bindView(Bundle savedInstanceState) { } class MyPageAdapter extends FragmentPagerAdapter{ private List<Fragment> mFragments=new ArrayList<>(); private List<String> titles=new ArrayList<>(); public MyPageAdapter(FragmentManager fm){ super(fm); } public void addFragment(Fragment fragment, String title){ mFragments.add(fragment); titles.add(title); } @Override public Fragment getItem(int position) { return mFragments.get(position); } @Override public int getCount() { return titles.size(); } @Override public CharSequence getPageTitle(int position) { return titles.get(position); } } }
3,644
0.710746
0.707405
116
29.965517
25.352661
97
false
false
0
0
0
0
0
0
0.508621
false
false
14
3ba048477e1ac88dbe311fa448efed281f21c717
21,749,714,401,539
39d6fa556c438cc6f7355a4fe84e7a91ef47e08e
/app/src/main/java/com/raveena/snug/UploadingActivity.java
1d17ab21037ee037d481d2c0a2c9d57bb424bc78
[]
no_license
raveenamnair/Snug
https://github.com/raveenamnair/Snug
2930f17112cec7e1f15a727efda696370b58c5b4
e9f46fd8d831adcb1ef7f3b9a228b8471658d2d2
refs/heads/master
2023-02-22T02:09:31.368000
2021-01-24T14:26:08
2021-01-24T14:26:08
332,122,075
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.raveena.snug; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.view.View; import android.webkit.MimeTypeMap; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.Spinner; import android.widget.Toast; import android.widget.VideoView; import com.google.android.gms.tasks.Continuation; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.StorageTask; import com.google.firebase.storage.UploadTask; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.UUID; public class UploadingActivity extends AppCompatActivity { Button uploadBtn; VideoView videoField; AutoCompleteTextView spinner; List<String> categoryNames; String videoType; private Uri videoUri; private static final int REQUEST_CODE = 1; private StorageReference videoRef; private DatabaseReference reference; private StorageTask uploadTask; private String videoId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_uploading); uploadBtn = findViewById(R.id.uploadBtn); videoField = findViewById(R.id.videoview); spinner = findViewById(R.id.categories); spinner.setDropDownBackgroundResource(R.color.linen); categoryNames = new ArrayList<>(); addCategoryNames(); ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(getApplication(), android.R.layout.simple_spinner_item, categoryNames); arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(arrayAdapter); // clicking this button will allow you to choose a video uploadBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setType("video/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(intent, REQUEST_CODE); videoRef = FirebaseStorage.getInstance().getReference("uploads"); System.out.println(videoRef.getPath()); } }); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { videoType = spinner.getOnItemSelectedListener().toString(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(resultCode == RESULT_OK){ videoUri = data.getData(); try{ if (uploadTask != null && uploadTask.isInProgress()) { Toast.makeText(UploadingActivity.this, "Upload in progress...", Toast.LENGTH_SHORT).show(); } else { UploadVideo(); } }catch(Exception e){ e.printStackTrace(); } } else { Toast.makeText(getApplicationContext(), "Doesn't work", Toast.LENGTH_SHORT).show(); } } private String getFileExtension(Uri uri) { ContentResolver contentResolver = UploadingActivity.this.getContentResolver(); MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton(); return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri)); } //upload video filepath to firebase storage private void UploadVideo() { if (videoUri != null) { videoId = UUID.randomUUID().toString(); final StorageReference fileReference = videoRef.child(videoId + "." + getFileExtension(videoUri)); uploadTask = fileReference.putFile(videoUri); uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() { @Override public Task<Uri> then(@NonNull Task task) throws Exception { if(!task.isSuccessful()) { throw task.getException(); } return fileReference.getDownloadUrl(); } }).addOnCompleteListener(new OnCompleteListener<Uri>() { @Override public void onComplete(@NonNull Task<Uri> task) { if(task.isSuccessful()) { Toast.makeText(UploadingActivity.this, "Please wait...", Toast.LENGTH_SHORT).show(); Uri downloadUri = task.getResult(); String videoUri2 = downloadUri.toString(); reference = FirebaseDatabase.getInstance().getReference("Videos").child(videoId); HashMap<String, Object> hashMap = new HashMap<>(); hashMap.put("videoId", videoId); hashMap.put("videoUri", videoUri2); hashMap.put("filePath", videoId + "." + getFileExtension(videoUri)); hashMap.put("category", videoType); reference.setValue(hashMap); videoField.setVideoURI(videoUri); videoField.seekTo(1); videoField.pause(); Toast.makeText(UploadingActivity.this, "Upload Successful", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(UploadingActivity.this, "Upload Failed", Toast.LENGTH_SHORT).show(); } } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Toast.makeText(UploadingActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); } }); } else { Toast.makeText(UploadingActivity.this, "No Video Selected", Toast.LENGTH_SHORT).show(); } } public void addCategoryNames() { //categoryNames.add("Pick a Situation"); categoryNames.add("Car"); categoryNames.add("Party"); categoryNames.add("Group"); categoryNames.add("Walking"); categoryNames.add("Alone"); categoryNames.add("Work"); categoryNames.add("School"); categoryNames.add("Store"); categoryNames.add("Home"); } }
UTF-8
Java
7,472
java
UploadingActivity.java
Java
[ { "context": "package com.raveena.snug;\n\nimport androidx.annotation.NonNull;\nimp", "end": 16, "score": 0.5374760627746582, "start": 13, "tag": "USERNAME", "value": "ave" } ]
null
[]
package com.raveena.snug; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.view.View; import android.webkit.MimeTypeMap; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.Spinner; import android.widget.Toast; import android.widget.VideoView; import com.google.android.gms.tasks.Continuation; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.StorageTask; import com.google.firebase.storage.UploadTask; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.UUID; public class UploadingActivity extends AppCompatActivity { Button uploadBtn; VideoView videoField; AutoCompleteTextView spinner; List<String> categoryNames; String videoType; private Uri videoUri; private static final int REQUEST_CODE = 1; private StorageReference videoRef; private DatabaseReference reference; private StorageTask uploadTask; private String videoId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_uploading); uploadBtn = findViewById(R.id.uploadBtn); videoField = findViewById(R.id.videoview); spinner = findViewById(R.id.categories); spinner.setDropDownBackgroundResource(R.color.linen); categoryNames = new ArrayList<>(); addCategoryNames(); ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(getApplication(), android.R.layout.simple_spinner_item, categoryNames); arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(arrayAdapter); // clicking this button will allow you to choose a video uploadBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setType("video/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(intent, REQUEST_CODE); videoRef = FirebaseStorage.getInstance().getReference("uploads"); System.out.println(videoRef.getPath()); } }); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { videoType = spinner.getOnItemSelectedListener().toString(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(resultCode == RESULT_OK){ videoUri = data.getData(); try{ if (uploadTask != null && uploadTask.isInProgress()) { Toast.makeText(UploadingActivity.this, "Upload in progress...", Toast.LENGTH_SHORT).show(); } else { UploadVideo(); } }catch(Exception e){ e.printStackTrace(); } } else { Toast.makeText(getApplicationContext(), "Doesn't work", Toast.LENGTH_SHORT).show(); } } private String getFileExtension(Uri uri) { ContentResolver contentResolver = UploadingActivity.this.getContentResolver(); MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton(); return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri)); } //upload video filepath to firebase storage private void UploadVideo() { if (videoUri != null) { videoId = UUID.randomUUID().toString(); final StorageReference fileReference = videoRef.child(videoId + "." + getFileExtension(videoUri)); uploadTask = fileReference.putFile(videoUri); uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() { @Override public Task<Uri> then(@NonNull Task task) throws Exception { if(!task.isSuccessful()) { throw task.getException(); } return fileReference.getDownloadUrl(); } }).addOnCompleteListener(new OnCompleteListener<Uri>() { @Override public void onComplete(@NonNull Task<Uri> task) { if(task.isSuccessful()) { Toast.makeText(UploadingActivity.this, "Please wait...", Toast.LENGTH_SHORT).show(); Uri downloadUri = task.getResult(); String videoUri2 = downloadUri.toString(); reference = FirebaseDatabase.getInstance().getReference("Videos").child(videoId); HashMap<String, Object> hashMap = new HashMap<>(); hashMap.put("videoId", videoId); hashMap.put("videoUri", videoUri2); hashMap.put("filePath", videoId + "." + getFileExtension(videoUri)); hashMap.put("category", videoType); reference.setValue(hashMap); videoField.setVideoURI(videoUri); videoField.seekTo(1); videoField.pause(); Toast.makeText(UploadingActivity.this, "Upload Successful", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(UploadingActivity.this, "Upload Failed", Toast.LENGTH_SHORT).show(); } } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Toast.makeText(UploadingActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); } }); } else { Toast.makeText(UploadingActivity.this, "No Video Selected", Toast.LENGTH_SHORT).show(); } } public void addCategoryNames() { //categoryNames.add("Pick a Situation"); categoryNames.add("Car"); categoryNames.add("Party"); categoryNames.add("Group"); categoryNames.add("Walking"); categoryNames.add("Alone"); categoryNames.add("Work"); categoryNames.add("School"); categoryNames.add("Store"); categoryNames.add("Home"); } }
7,472
0.627944
0.627409
182
40.054947
26.674004
111
false
false
0
0
0
0
0
0
0.758242
false
false
14
c15a98e3e6d44132000e0e28fa111674958a8acc
33,509,334,851,263
31867e26c309cc86e974bacf05d8f6797112db73
/src/main/java/com/jiyingda/leetcode50/Leet45.java
6a7dea6c4836bff161e5a9277012796923d5b55b
[]
no_license
jiyingda/leetcode
https://github.com/jiyingda/leetcode
2bc1d274f4b660b281a9684369b87667af3ca215
e4187699f10f577142e627e8ba589a7290087843
refs/heads/master
2023-06-09T02:18:17.831000
2023-06-06T07:11:33
2023-06-06T07:11:33
144,972,242
0
2
null
false
2022-06-17T02:46:45
2018-08-16T10:19:52
2021-10-18T15:14:33
2022-06-17T02:46:44
428
0
0
1
Java
false
false
package com.jiyingda.leetcode50; /** * @author jiyingda * @date 2019/9/7 * 给定一个非负整数数组,你最初位于数组的第一个位置。 * * 数组中的每个元素代表你在该位置可以跳跃的最大长度。 * * 你的目标是使用最少的跳跃次数到达数组的最后一个位置。 * * 示例: * * 输入: [2,3,1,1,4] * 输出: 2 * 解释: 跳到最后一个位置的最小跳跃数是 2。 *   从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。 * 说明: * * 假设你总是可以到达数组的最后一个位置。 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/jump-game-ii * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ public class Leet45 { public static void main(String[] args){ int[] nums = new int[]{7,0,9,6,9,6,1,7,9,0,1,2,9,0,3}; jump(nums); } public static int jump(int[] nums) { int[] pd = new int[nums.length]; int m = nums[0]; pd[0] = 0; int j = 1; for(int i = 1; i < nums.length; i++){ for(;j <= m && j < nums.length; j++){ pd[j] = pd[i-1] + 1; } if(m < nums[i] + i){ m = nums[i] + i; } } return pd[nums.length - 1]; } }
UTF-8
Java
1,422
java
Leet45.java
Java
[ { "context": "package com.jiyingda.leetcode50;\n\n/**\n * @author jiyingda\n * @date 2019/9/7\n * 给定一个非负整数数组,你最初位于数组的第一个位置。\n *", "end": 57, "score": 0.999109148979187, "start": 49, "tag": "USERNAME", "value": "jiyingda" } ]
null
[]
package com.jiyingda.leetcode50; /** * @author jiyingda * @date 2019/9/7 * 给定一个非负整数数组,你最初位于数组的第一个位置。 * * 数组中的每个元素代表你在该位置可以跳跃的最大长度。 * * 你的目标是使用最少的跳跃次数到达数组的最后一个位置。 * * 示例: * * 输入: [2,3,1,1,4] * 输出: 2 * 解释: 跳到最后一个位置的最小跳跃数是 2。 *   从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。 * 说明: * * 假设你总是可以到达数组的最后一个位置。 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/jump-game-ii * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ public class Leet45 { public static void main(String[] args){ int[] nums = new int[]{7,0,9,6,9,6,1,7,9,0,1,2,9,0,3}; jump(nums); } public static int jump(int[] nums) { int[] pd = new int[nums.length]; int m = nums[0]; pd[0] = 0; int j = 1; for(int i = 1; i < nums.length; i++){ for(;j <= m && j < nums.length; j++){ pd[j] = pd[i-1] + 1; } if(m < nums[i] + i){ m = nums[i] + i; } } return pd[nums.length - 1]; } }
1,422
0.504399
0.461388
49
19.87755
16.730312
62
false
false
0
0
0
0
0
0
0.653061
false
false
14
faa16a38a6d89ec538efe695187fd705b655d358
12,618,613,976,872
e7c536d30c8415de1164ab57099172a548c7ab59
/src/java/Entity/Manager.java
63a2eb9adab8f102fc828db2a71bf80612240b75
[]
no_license
manhpdhe151290/Childcare-copy-
https://github.com/manhpdhe151290/Childcare-copy-
a108623ab8ed8ae087d242d19324ee1a2122c6c8
c06dd59738e2999e8c64e8cf80a8cb0a1bc47349
refs/heads/master
2023-08-16T09:42:14.987000
2021-10-25T16:07:29
2021-10-25T16:07:29
null
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 Entity; /** * * @author Viet */ public class Manager { private int mID; private int aID; private String first_name; private String last_name; private int age; private int gender; private String username; private String password; private String image; private int role; private String address; public Manager(int mID, int aID, String first_name, String last_name, int age, int gender, String username, String password, String image, int role, String address) { this.mID = mID; this.aID = aID; this.first_name = first_name; this.last_name = last_name; this.age = age; this.gender = gender; this.username = username; this.password = password; this.image = image; this.role = role; this.address = address; } public Manager() { } public int getmID() { return mID; } public void setmID(int mID) { this.mID = mID; } public int getaID() { return aID; } public void setaID(int aID) { this.aID = aID; } public String getFirst_name() { return first_name; } public void setFirst_name(String first_name) { this.first_name = first_name; } public String getLast_name() { return last_name; } public void setLast_name(String last_name) { this.last_name = last_name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getGender() { return gender; } public void setGender(int gender) { this.gender = gender; } public 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 getImage() { return image; } public void setImage(String image) { this.image = image; } public int getRole() { return role; } public void setRole(int role) { this.role = role; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "Manager{" + "mID=" + mID + ", aID=" + aID + ", first_name=" + first_name + ", last_name=" + last_name + ", age=" + age + ", gender=" + gender + ", username=" + username + ", password=" + password + ", image=" + image + ", role=" + role + ", address=" + address + '}'; } }
UTF-8
Java
2,972
java
Manager.java
Java
[ { "context": "the editor.\n */\npackage Entity;\n\n/**\n *\n * @author Viet\n */\npublic class Manager {\n private int mID;\n ", "end": 224, "score": 0.9962965250015259, "start": 220, "tag": "NAME", "value": "Viet" }, { "context": " this.gender = gender;\n this.username...
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 Entity; /** * * @author Viet */ public class Manager { private int mID; private int aID; private String first_name; private String last_name; private int age; private int gender; private String username; private String password; private String image; private int role; private String address; public Manager(int mID, int aID, String first_name, String last_name, int age, int gender, String username, String password, String image, int role, String address) { this.mID = mID; this.aID = aID; this.first_name = first_name; this.last_name = last_name; this.age = age; this.gender = gender; this.username = username; this.password = <PASSWORD>; this.image = image; this.role = role; this.address = address; } public Manager() { } public int getmID() { return mID; } public void setmID(int mID) { this.mID = mID; } public int getaID() { return aID; } public void setaID(int aID) { this.aID = aID; } public String getFirst_name() { return first_name; } public void setFirst_name(String first_name) { this.first_name = first_name; } public String getLast_name() { return last_name; } public void setLast_name(String last_name) { this.last_name = last_name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getGender() { return gender; } public void setGender(int gender) { this.gender = gender; } public 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 getImage() { return image; } public void setImage(String image) { this.image = image; } public int getRole() { return role; } public void setRole(int role) { this.role = role; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "Manager{" + "mID=" + mID + ", aID=" + aID + ", first_name=" + first_name + ", last_name=" + last_name + ", age=" + age + ", gender=" + gender + ", username=" + username + ", password=" + <PASSWORD> + ", image=" + image + ", role=" + role + ", address=" + address + '}'; } }
2,976
0.568641
0.568641
142
19.929577
29.871002
283
false
false
0
0
0
0
0
0
0.485915
false
false
14
f76b84870d807aaf7abc0d12b0bcfdeabf231c7d
12,618,613,976,822
263426253a3c78c5c7d806ba7150d8e28760cc06
/src/Prob228A.java
f98d21a37e7896072087c46f9879d7603fcfa88f
[]
no_license
ashutosh-uchiha16/codeforces_solutions
https://github.com/ashutosh-uchiha16/codeforces_solutions
61796fafbd8d6426e8e41d34c88cf159be17a259
3ff72d4a058760014c95357020dc5c1ff602dda6
refs/heads/master
2023-03-09T09:20:03.861000
2021-02-19T07:23:05
2021-02-19T07:23:05
337,933,596
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Prob228A { //Is your horseshoe on the other hoof? public static void main(String[] args) { Scanner sc = new Scanner(System.in); int arr[] = new int[4]; Set<Integer> set = new HashSet<>(); for(int i = 0; i <4; i++) { arr[i] = sc.nextInt(); set.add(arr[i]); } System.out.println(4 - set.size()); } }
UTF-8
Java
471
java
Prob228A.java
Java
[]
null
[]
import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Prob228A { //Is your horseshoe on the other hoof? public static void main(String[] args) { Scanner sc = new Scanner(System.in); int arr[] = new int[4]; Set<Integer> set = new HashSet<>(); for(int i = 0; i <4; i++) { arr[i] = sc.nextInt(); set.add(arr[i]); } System.out.println(4 - set.size()); } }
471
0.547771
0.532909
18
25.166666
15.610716
44
false
false
0
0
0
0
0
0
0.611111
false
false
14
3d80e00aff4e784d88ad360a7568bfdb97c1cd64
21,938,692,997,065
696b3e2b5007db8010e6722a54bf0141aa35a6a1
/src/main/java/com/jfrog/ide/idea/ui/menus/filtermenu/IssueFilterMenu.java
b50d6575ede9638b38ae3e7faa2b6bb5ec95c019
[ "Apache-2.0" ]
permissive
jfrog/jfrog-idea-plugin
https://github.com/jfrog/jfrog-idea-plugin
1db285aa740511cef0cbe45621083031222789cf
64e9c3d292058d6262a0318f6816c9fb96866e4a
refs/heads/master
2023-08-31T03:09:39.807000
2023-08-27T13:30:26
2023-08-27T13:30:26
96,010,119
164
28
Apache-2.0
false
2023-09-14T08:43:57
2017-07-02T08:01:50
2023-09-14T04:18:59
2023-09-14T08:43:56
4,373
172
29
33
Java
false
false
package com.jfrog.ide.idea.ui.menus.filtermenu; import com.intellij.openapi.project.Project; import com.jfrog.ide.common.filter.FilterManager; import org.jetbrains.annotations.NotNull; import org.jfrog.build.extractor.scan.Severity; import java.util.Map; /** * Created by Yahav Itzhak on 22 Nov 2017. */ public abstract class IssueFilterMenu extends FilterMenu<Severity> { public static final String TOOLTIP = "Select severities to show"; public static final String NAME = "Severity"; public IssueFilterMenu(@NotNull Project project, FilterManager filterManager) { super(project, NAME, TOOLTIP); Map<Severity, Boolean> severitiesFilters = filterManager.getSelectedSeverities(); addComponents(severitiesFilters, false); } }
UTF-8
Java
768
java
IssueFilterMenu.java
Java
[ { "context": "everity;\n\nimport java.util.Map;\n\n/**\n * Created by Yahav Itzhak on 22 Nov 2017.\n */\npublic abstract class IssueFi", "end": 288, "score": 0.9997806549072266, "start": 276, "tag": "NAME", "value": "Yahav Itzhak" } ]
null
[]
package com.jfrog.ide.idea.ui.menus.filtermenu; import com.intellij.openapi.project.Project; import com.jfrog.ide.common.filter.FilterManager; import org.jetbrains.annotations.NotNull; import org.jfrog.build.extractor.scan.Severity; import java.util.Map; /** * Created by <NAME> on 22 Nov 2017. */ public abstract class IssueFilterMenu extends FilterMenu<Severity> { public static final String TOOLTIP = "Select severities to show"; public static final String NAME = "Severity"; public IssueFilterMenu(@NotNull Project project, FilterManager filterManager) { super(project, NAME, TOOLTIP); Map<Severity, Boolean> severitiesFilters = filterManager.getSelectedSeverities(); addComponents(severitiesFilters, false); } }
762
0.760417
0.752604
22
33.954544
28.336416
89
false
false
0
0
0
0
0
0
0.727273
false
false
14
8b752c6f2733301f92a98e2a9dfceac0397eeb82
17,248,588,663,989
1665a10664ed50db1c6c1cc955c67e85d6f86b47
/app/src/main/java/retail/yzx/com/kz/Goods_Common_Notes_Activity.java
ff9fd72d909fd3ddb6fe57613ca280e6c25d6e5b
[]
no_license
13616632061/Kz
https://github.com/13616632061/Kz
63f7799642d3c95324810b934ddf43e8610af068
99a3b11306bb354a163ec045415099973ba9fd6d
refs/heads/master
2020-05-09T23:32:24.204000
2019-04-17T08:47:40
2019-04-17T08:47:40
100,901,438
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package retail.yzx.com.kz; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.GridView; import android.widget.ImageView; import android.widget.TextView; import com.lzy.okgo.OkGo; import com.lzy.okgo.callback.StringCallback; import com.lzy.okgo.request.BaseRequest; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; import Entty.Goods_Common_Notes; import Utils.SharedUtil; import Utils.SysUtils; import adapters.Goods_Common_Notes_Adapter; import base.BaseActivity; import okhttp3.Call; import okhttp3.Response; import retail.yzx.com.restaurant_nomal.Entry.ResDialog; import retail.yzx.com.supper_self_service.Utils.StringUtils; /** * 常用备注的页面 */ public class Goods_Common_Notes_Activity extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener { private ImageView iv_back; private Button btn_add_notes; private TextView tv_notes; private GridView gridview_content; private ArrayList<Goods_Common_Notes> mCommonNotesList; private Goods_Common_Notes_Adapter mGoods_Common_Notes_Adapter; @Override protected int getContentId() { return R.layout.activity_goods__common__notes_; } @Override protected void init() { super.init(); StringUtils.setupUI(this, findViewById(R.id.activity_goods__common__notes_));//点击空白处隐藏软键盘 iv_back= (ImageView) findViewById(R.id.iv_back); tv_notes= (TextView) findViewById(R.id.tv_notes); btn_add_notes= (Button) findViewById(R.id.btn_add_notes); gridview_content= (GridView) findViewById(R.id.gridview_content); iv_back.setOnClickListener(this); btn_add_notes.setOnClickListener(this); gridview_content.setOnItemClickListener(this); } @Override protected void loadDatas() { super.loadDatas(); getCommonNotesInfo(); } // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // retail.yzx.com.supper_self_service.Utils.StringUtils.initOKgo(Goods_Common_Notes_Activity.this);//初始化网络请求 // setContentView(R.layout.activity_goods__common__notes_); // StringUtils.HideBottomBar(Goods_Common_Notes_Activity.this); // StringUtils.setupUI(this, findViewById(R.id.activity_goods__common__notes_));//点击空白处隐藏软键盘 // //// initView(); //// inttData(); // } // @Override // protected void onStart() { // super.onStart(); // StringUtils.HideBottomBar(Goods_Common_Notes_Activity.this); // } // private void initView() { // iv_back= (ImageView) findViewById(R.id.iv_back); // tv_notes= (TextView) findViewById(R.id.tv_notes); // btn_add_notes= (Button) findViewById(R.id.btn_add_notes); // gridview_content= (GridView) findViewById(R.id.gridview_content); // // iv_back.setOnClickListener(this); // btn_add_notes.setOnClickListener(this); // gridview_content.setOnItemClickListener(this); // } // private void inttData() { // // getCommonNotesInfo(); // } @Override public void onClick(View v) { switch (v.getId()){ case R.id.iv_back: finish(); break; case R.id.btn_add_notes: ResDialog.AddNotesDialog(Goods_Common_Notes_Activity.this,"新增常用备注","请输入内容",tv_notes); ResDialog r=new ResDialog(); r.setOnClickListener(new ResDialog.onClickSure() { @Override public void onClickSure() { AddCommonNotesInfo(tv_notes.getText().toString().trim()); } }); break; } } @Override public void onItemClick(AdapterView<?> parent, View view, final int position, long id) { ResDialog.RemoveAndEditDialog(Goods_Common_Notes_Activity.this,mCommonNotesList.get(position).getNotes()); ResDialog r=new ResDialog(); r.setOnClickListener(new ResDialog.onClickRemove() { @Override public void onClickRemove() { RemoveCommonNotesInfo(position); } }); r.setOnClickListener(new ResDialog.onClickEdit() { @Override public void onClickEdit() { tv_notes.setText(mCommonNotesList.get(position).getNotes()); ResDialog.AddNotesDialog(Goods_Common_Notes_Activity.this,"编辑常用备注","请输入内容",tv_notes); ResDialog r=new ResDialog(); r.setOnClickListener(new ResDialog.onClickSure() { @Override public void onClickSure() { EditCommonNotesInfo(position,tv_notes.getText().toString().trim()); } }); } }); } //获取常用备注信息 private void getCommonNotesInfo(){ OkGo.post(SysUtils.getSellerServiceUrl("remarks_list")) .tag(this) .params("seller_token", SharedUtil.getString("seller_token")) .execute(new StringCallback() { @Override public void onBefore(BaseRequest request) { super.onBefore(request); Log.e("barcode", "请求URL:" + request.getUrl()); } @Override public void onSuccess(String s, Call call, Response response) { try { JSONObject jsonObject = new JSONObject(s); Log.e("barcode", "返回数据:" + jsonObject); JSONObject jo1 = jsonObject.getJSONObject("response"); String status = jo1.getString("status"); if (status.equals("200")) { if(mCommonNotesList!=null){ mCommonNotesList.clear(); } JSONArray data=jo1.getJSONArray("data"); mCommonNotesList=new ArrayList<Goods_Common_Notes>(); if(data!=null){ for(int i=0;i<data.length();i++){ JSONObject dataobj=data.getJSONObject(i); String notes=dataobj.getString("notes"); String notes_id=dataobj.getString("id"); Goods_Common_Notes goods_common_notes=new Goods_Common_Notes(notes_id,notes); mCommonNotesList.add(goods_common_notes); } } mGoods_Common_Notes_Adapter=new Goods_Common_Notes_Adapter(Goods_Common_Notes_Activity.this,mCommonNotesList); gridview_content.setAdapter(mGoods_Common_Notes_Adapter); } } catch (Exception e) { e.printStackTrace(); StringUtils.showToast(Goods_Common_Notes_Activity.this,"服务器数据异常",20); Log.e("print", "服务器数据异常: "+e.toString() ); } } @Override public void onError(Call call, Response response, Exception e) { super.onError(call, response, e); StringUtils.showToast(Goods_Common_Notes_Activity.this,"网络不给力",20); } }); } //添加常用备注信息 private void AddCommonNotesInfo(String notes){ OkGo.post(SysUtils.getSellerServiceUrl("remarks_operation")) .tag(this) .params("notes",notes) .params("seller_token", SharedUtil.getString("seller_token")) .execute(new StringCallback() { @Override public void onBefore(BaseRequest request) { super.onBefore(request); Log.e("barcode", "请求URL:" + request.getUrl()); } @Override public void onSuccess(String s, Call call, Response response) { try { JSONObject jsonObject = new JSONObject(s); Log.e("barcode", "返回数据:" + jsonObject); JSONObject jo1 = jsonObject.getJSONObject("response"); String status = jo1.getString("status"); if (status.equals("200")) { getCommonNotesInfo(); StringUtils.showToast(Goods_Common_Notes_Activity.this,"新增成功",20); } } catch (Exception e) { e.printStackTrace(); StringUtils.showToast(Goods_Common_Notes_Activity.this,"服务器数据异常",20); } } @Override public void onError(Call call, Response response, Exception e) { super.onError(call, response, e); StringUtils.showToast(Goods_Common_Notes_Activity.this,"网络不给力",20); } }); } //删除常用备注信息 private void RemoveCommonNotesInfo(final int position){ OkGo.post(SysUtils.getSellerServiceUrl("remarks_operation")) .tag(this) .params("id",mCommonNotesList.get(position).getNotes_id()) .params("type","remove") .params("seller_token", SharedUtil.getString("seller_token")) .execute(new StringCallback() { @Override public void onBefore(BaseRequest request) { super.onBefore(request); Log.e("barcode", "请求URL:" + request.getUrl()); } @Override public void onSuccess(String s, Call call, Response response) { try { JSONObject jsonObject = new JSONObject(s); Log.e("barcode", "返回数据:" + jsonObject); JSONObject jo1 = jsonObject.getJSONObject("response"); String status = jo1.getString("status"); if (status.equals("200")) { getCommonNotesInfo(); StringUtils.showToast(Goods_Common_Notes_Activity.this,"删除成功",20); } } catch (Exception e) { e.printStackTrace(); StringUtils.showToast(Goods_Common_Notes_Activity.this,"服务器数据异常",20); } } @Override public void onError(Call call, Response response, Exception e) { super.onError(call, response, e); StringUtils.showToast(Goods_Common_Notes_Activity.this,"网络不给力",20); } }); } //编辑常用备注信息 private void EditCommonNotesInfo(final int position,String editnotes){ OkGo.post(SysUtils.getSellerServiceUrl("remarks_operation")) .tag(this) .params("id",mCommonNotesList.get(position).getNotes_id()) .params("notes",editnotes) .params("seller_token", SharedUtil.getString("seller_token")) .execute(new StringCallback() { @Override public void onBefore(BaseRequest request) { super.onBefore(request); Log.e("barcode", "请求URL:" + request.getUrl()); } @Override public void onSuccess(String s, Call call, Response response) { try { JSONObject jsonObject = new JSONObject(s); Log.e("barcode", "返回数据:" + jsonObject); JSONObject jo1 = jsonObject.getJSONObject("response"); String status = jo1.getString("status"); if (status.equals("200")) { getCommonNotesInfo(); StringUtils.showToast(Goods_Common_Notes_Activity.this,"编辑成功",20); } } catch (Exception e) { e.printStackTrace(); StringUtils.showToast(Goods_Common_Notes_Activity.this,"服务器数据异常",20); } } @Override public void onError(Call call, Response response, Exception e) { super.onError(call, response, e); StringUtils.showToast(Goods_Common_Notes_Activity.this,"网络不给力",20); } }); } }
UTF-8
Java
13,745
java
Goods_Common_Notes_Activity.java
Java
[]
null
[]
package retail.yzx.com.kz; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.GridView; import android.widget.ImageView; import android.widget.TextView; import com.lzy.okgo.OkGo; import com.lzy.okgo.callback.StringCallback; import com.lzy.okgo.request.BaseRequest; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; import Entty.Goods_Common_Notes; import Utils.SharedUtil; import Utils.SysUtils; import adapters.Goods_Common_Notes_Adapter; import base.BaseActivity; import okhttp3.Call; import okhttp3.Response; import retail.yzx.com.restaurant_nomal.Entry.ResDialog; import retail.yzx.com.supper_self_service.Utils.StringUtils; /** * 常用备注的页面 */ public class Goods_Common_Notes_Activity extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener { private ImageView iv_back; private Button btn_add_notes; private TextView tv_notes; private GridView gridview_content; private ArrayList<Goods_Common_Notes> mCommonNotesList; private Goods_Common_Notes_Adapter mGoods_Common_Notes_Adapter; @Override protected int getContentId() { return R.layout.activity_goods__common__notes_; } @Override protected void init() { super.init(); StringUtils.setupUI(this, findViewById(R.id.activity_goods__common__notes_));//点击空白处隐藏软键盘 iv_back= (ImageView) findViewById(R.id.iv_back); tv_notes= (TextView) findViewById(R.id.tv_notes); btn_add_notes= (Button) findViewById(R.id.btn_add_notes); gridview_content= (GridView) findViewById(R.id.gridview_content); iv_back.setOnClickListener(this); btn_add_notes.setOnClickListener(this); gridview_content.setOnItemClickListener(this); } @Override protected void loadDatas() { super.loadDatas(); getCommonNotesInfo(); } // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // retail.yzx.com.supper_self_service.Utils.StringUtils.initOKgo(Goods_Common_Notes_Activity.this);//初始化网络请求 // setContentView(R.layout.activity_goods__common__notes_); // StringUtils.HideBottomBar(Goods_Common_Notes_Activity.this); // StringUtils.setupUI(this, findViewById(R.id.activity_goods__common__notes_));//点击空白处隐藏软键盘 // //// initView(); //// inttData(); // } // @Override // protected void onStart() { // super.onStart(); // StringUtils.HideBottomBar(Goods_Common_Notes_Activity.this); // } // private void initView() { // iv_back= (ImageView) findViewById(R.id.iv_back); // tv_notes= (TextView) findViewById(R.id.tv_notes); // btn_add_notes= (Button) findViewById(R.id.btn_add_notes); // gridview_content= (GridView) findViewById(R.id.gridview_content); // // iv_back.setOnClickListener(this); // btn_add_notes.setOnClickListener(this); // gridview_content.setOnItemClickListener(this); // } // private void inttData() { // // getCommonNotesInfo(); // } @Override public void onClick(View v) { switch (v.getId()){ case R.id.iv_back: finish(); break; case R.id.btn_add_notes: ResDialog.AddNotesDialog(Goods_Common_Notes_Activity.this,"新增常用备注","请输入内容",tv_notes); ResDialog r=new ResDialog(); r.setOnClickListener(new ResDialog.onClickSure() { @Override public void onClickSure() { AddCommonNotesInfo(tv_notes.getText().toString().trim()); } }); break; } } @Override public void onItemClick(AdapterView<?> parent, View view, final int position, long id) { ResDialog.RemoveAndEditDialog(Goods_Common_Notes_Activity.this,mCommonNotesList.get(position).getNotes()); ResDialog r=new ResDialog(); r.setOnClickListener(new ResDialog.onClickRemove() { @Override public void onClickRemove() { RemoveCommonNotesInfo(position); } }); r.setOnClickListener(new ResDialog.onClickEdit() { @Override public void onClickEdit() { tv_notes.setText(mCommonNotesList.get(position).getNotes()); ResDialog.AddNotesDialog(Goods_Common_Notes_Activity.this,"编辑常用备注","请输入内容",tv_notes); ResDialog r=new ResDialog(); r.setOnClickListener(new ResDialog.onClickSure() { @Override public void onClickSure() { EditCommonNotesInfo(position,tv_notes.getText().toString().trim()); } }); } }); } //获取常用备注信息 private void getCommonNotesInfo(){ OkGo.post(SysUtils.getSellerServiceUrl("remarks_list")) .tag(this) .params("seller_token", SharedUtil.getString("seller_token")) .execute(new StringCallback() { @Override public void onBefore(BaseRequest request) { super.onBefore(request); Log.e("barcode", "请求URL:" + request.getUrl()); } @Override public void onSuccess(String s, Call call, Response response) { try { JSONObject jsonObject = new JSONObject(s); Log.e("barcode", "返回数据:" + jsonObject); JSONObject jo1 = jsonObject.getJSONObject("response"); String status = jo1.getString("status"); if (status.equals("200")) { if(mCommonNotesList!=null){ mCommonNotesList.clear(); } JSONArray data=jo1.getJSONArray("data"); mCommonNotesList=new ArrayList<Goods_Common_Notes>(); if(data!=null){ for(int i=0;i<data.length();i++){ JSONObject dataobj=data.getJSONObject(i); String notes=dataobj.getString("notes"); String notes_id=dataobj.getString("id"); Goods_Common_Notes goods_common_notes=new Goods_Common_Notes(notes_id,notes); mCommonNotesList.add(goods_common_notes); } } mGoods_Common_Notes_Adapter=new Goods_Common_Notes_Adapter(Goods_Common_Notes_Activity.this,mCommonNotesList); gridview_content.setAdapter(mGoods_Common_Notes_Adapter); } } catch (Exception e) { e.printStackTrace(); StringUtils.showToast(Goods_Common_Notes_Activity.this,"服务器数据异常",20); Log.e("print", "服务器数据异常: "+e.toString() ); } } @Override public void onError(Call call, Response response, Exception e) { super.onError(call, response, e); StringUtils.showToast(Goods_Common_Notes_Activity.this,"网络不给力",20); } }); } //添加常用备注信息 private void AddCommonNotesInfo(String notes){ OkGo.post(SysUtils.getSellerServiceUrl("remarks_operation")) .tag(this) .params("notes",notes) .params("seller_token", SharedUtil.getString("seller_token")) .execute(new StringCallback() { @Override public void onBefore(BaseRequest request) { super.onBefore(request); Log.e("barcode", "请求URL:" + request.getUrl()); } @Override public void onSuccess(String s, Call call, Response response) { try { JSONObject jsonObject = new JSONObject(s); Log.e("barcode", "返回数据:" + jsonObject); JSONObject jo1 = jsonObject.getJSONObject("response"); String status = jo1.getString("status"); if (status.equals("200")) { getCommonNotesInfo(); StringUtils.showToast(Goods_Common_Notes_Activity.this,"新增成功",20); } } catch (Exception e) { e.printStackTrace(); StringUtils.showToast(Goods_Common_Notes_Activity.this,"服务器数据异常",20); } } @Override public void onError(Call call, Response response, Exception e) { super.onError(call, response, e); StringUtils.showToast(Goods_Common_Notes_Activity.this,"网络不给力",20); } }); } //删除常用备注信息 private void RemoveCommonNotesInfo(final int position){ OkGo.post(SysUtils.getSellerServiceUrl("remarks_operation")) .tag(this) .params("id",mCommonNotesList.get(position).getNotes_id()) .params("type","remove") .params("seller_token", SharedUtil.getString("seller_token")) .execute(new StringCallback() { @Override public void onBefore(BaseRequest request) { super.onBefore(request); Log.e("barcode", "请求URL:" + request.getUrl()); } @Override public void onSuccess(String s, Call call, Response response) { try { JSONObject jsonObject = new JSONObject(s); Log.e("barcode", "返回数据:" + jsonObject); JSONObject jo1 = jsonObject.getJSONObject("response"); String status = jo1.getString("status"); if (status.equals("200")) { getCommonNotesInfo(); StringUtils.showToast(Goods_Common_Notes_Activity.this,"删除成功",20); } } catch (Exception e) { e.printStackTrace(); StringUtils.showToast(Goods_Common_Notes_Activity.this,"服务器数据异常",20); } } @Override public void onError(Call call, Response response, Exception e) { super.onError(call, response, e); StringUtils.showToast(Goods_Common_Notes_Activity.this,"网络不给力",20); } }); } //编辑常用备注信息 private void EditCommonNotesInfo(final int position,String editnotes){ OkGo.post(SysUtils.getSellerServiceUrl("remarks_operation")) .tag(this) .params("id",mCommonNotesList.get(position).getNotes_id()) .params("notes",editnotes) .params("seller_token", SharedUtil.getString("seller_token")) .execute(new StringCallback() { @Override public void onBefore(BaseRequest request) { super.onBefore(request); Log.e("barcode", "请求URL:" + request.getUrl()); } @Override public void onSuccess(String s, Call call, Response response) { try { JSONObject jsonObject = new JSONObject(s); Log.e("barcode", "返回数据:" + jsonObject); JSONObject jo1 = jsonObject.getJSONObject("response"); String status = jo1.getString("status"); if (status.equals("200")) { getCommonNotesInfo(); StringUtils.showToast(Goods_Common_Notes_Activity.this,"编辑成功",20); } } catch (Exception e) { e.printStackTrace(); StringUtils.showToast(Goods_Common_Notes_Activity.this,"服务器数据异常",20); } } @Override public void onError(Call call, Response response, Exception e) { super.onError(call, response, e); StringUtils.showToast(Goods_Common_Notes_Activity.this,"网络不给力",20); } }); } }
13,745
0.5132
0.50976
311
41.993568
29.446993
142
false
false
0
0
0
0
0
0
0.70418
false
false
14
784e9738a928b4cd4de3308cffa071397ed12b48
2,001,454,770,108
ac959d40035ba9d9ac49603706c079eb46014edc
/src/main/java/com/kayeconsulting/DateUtils.java
6f0b3f64b70c5fdf2fa3a37aeaa64d12af7f704b
[]
no_license
daveikaye2/coinbase
https://github.com/daveikaye2/coinbase
ea30e7cd7ced4abff1d50162d69adf1abec1f573
97f162e458ec78a54c425c6ea03bdbc1be4ffed3
refs/heads/master
2022-11-12T14:47:44.305000
2020-06-29T04:17:57
2020-06-29T04:17:57
275,070,845
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.kayeconsulting; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; public class DateUtils { private final static DateFormat DEFAULT_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public String toString(Date date) { return DEFAULT_DATE_FORMAT.format(date); } }
UTF-8
Java
346
java
DateUtils.java
Java
[]
null
[]
package com.kayeconsulting; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; public class DateUtils { private final static DateFormat DEFAULT_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public String toString(Date date) { return DEFAULT_DATE_FORMAT.format(date); } }
346
0.736994
0.736994
16
20.625
26.431219
102
false
false
0
0
0
0
0
0
0.375
false
false
14
b845af8a3f3dfb94ce92dfe93559ca1056b739bb
10,196,252,398,563
0828467082eb888c5865ade72f276295ef6dad1b
/Assign2/src/store/Inventory.java
e74204bcf0b16705ece2220b7f86730c600f09da
[]
no_license
Jessegz123/CS4354
https://github.com/Jessegz123/CS4354
8931e760c0c26ffd8e234a521e81e234290c885f
adb926044c79922e3d3904bc50df81bfe3b0ce8b
refs/heads/master
2021-01-17T18:23:16.020000
2016-07-20T01:39:18
2016-07-20T01:39:18
63,481,774
1
1
null
false
2016-07-17T19:10:36
2016-07-16T12:23:58
2016-07-17T02:32:23
2016-07-17T19:10:36
25
1
1
0
Java
null
null
package store; import java.io.*; import java.util.*; /** * Represents the inventory of the store * it provides methods to add a product to the inventory, remove * a product from theinventory (given the sku from the user), find and * display a movie (given a sku from the user), and display all the * products in the inventory. * @author Sarah Zsohar * @author Jesse Gonzalez */ public class Inventory implements Serializable { ArrayList<Product> items = new ArrayList<Product>(); // inventory /** * Default constructor, creates an empty inventory */ public Inventory() { try { FileInputStream fin = new FileInputStream("inventory.dat"); ObjectInputStream ois = new ObjectInputStream(fin); items = (ArrayList<Product>)ois.readObject(); fin.close(); } catch (FileNotFoundException e) { System.out.println("Cannot find datafile."); } catch (IOException e) { System.out.println("Problem with file input."); } catch (ClassNotFoundException e) { System.out.println("Class not found on input from file."); } } /** * Create a file output stream */ void writeToFile(){ try{ FileOutputStream fout = new FileOutputStream("inventory.dat"); ObjectOutputStream oout = new ObjectOutputStream(fout); oout.writeObject(items); oout.close(); } catch (IOException e){ System.out.println("Problem with file output"); } } /** * Validates the product * @param sku of the product being validated * @param quantity of the product trying to ordered * @param price price of the product * @return returns 0 if the items meets all the necessary criteria * -1 if the sku already exists in the inventory, or -2 if the * quantity or price are less then 0 * */ int validateProduct(int sku, int quantity, double price) { for (Product m : items){ //p declares a product object if (sku == m.getSku()) return -1; if (quantity < 0 || price < 0 ) return -2; } return 0; } /** * Removes a product from the Inventory * @param removeSku sku of the product to be removed */ void removeProduct(int removeSku) { for(Product p : items){ //p declares a product object if(p.getSku() == removeSku){ items.remove(p); System.out.println("Product removed."); return; } } System.out.print("No product found with this SKU \n"); } /** * Displays a product selected by SKU input by the user * @param displaySku the sku of the product to be displayed */ void displayProductInfo(int displaySku){ for(Product p : items){ //p declares a product object if(p.getSku() == displaySku){ String display = p.display(); //display is a holder for the string returned System.out.println(display); //from the display function return; } } System.out.print("No product found with this SKU\n"); System.out.print("\n"); } /** * Displays all the products in the Inventory */ void displayAllProducts(){ Collections.sort(items); for(Product p : items){ //p declares a product object String display=p.displayAll(); //display is a holder for the string returned System.out.println(display); //from the display function } System.out.print("\n"); } /** * Processes sale of a certain product. Constructs a string * @param sku of the product being processed * @param quantity of the products purchased * @param shipping shipping cost used my store * @return a string with all of the field values labeled */ String ProcessSale( int sku, int quantity, double shippingC) { for(Product p : items){ //p declares a product object if(p.getSku() == sku){ if (p.getQuantity() < quantity){ return "Quantity exceeds inventory"; } else{ int newQuantity = p.getQuantity() - quantity; p.setQuantity(newQuantity); String output = String.format("%1s %16s %1s %5s %1s %10s %1s %21s", "Total price: ", p.dfd.format(p.getPrice() * quantity), "\nTotal shipping credit: ", p.dfd.format(p.getShippingCredit() * quantity), "\nTotal commission: ", p.dfd.format(p.getCommission() * quantity), "\nProfit: ", p.dfd.format((p.getPrice() * quantity) + (p.getShippingCredit() * quantity) - ((p.getCommission() * quantity)+ shippingC ))); return output; } } }return null; } }
UTF-8
Java
4,591
java
Inventory.java
Java
[ { "context": " all the \n * products in the inventory.\n * @author Sarah Zsohar\n * @author Jesse Gonzalez\n*/\n\npublic class Invent", "end": 359, "score": 0.9998728036880493, "start": 347, "tag": "NAME", "value": "Sarah Zsohar" }, { "context": " the inventory.\n * @author Sarah Zso...
null
[]
package store; import java.io.*; import java.util.*; /** * Represents the inventory of the store * it provides methods to add a product to the inventory, remove * a product from theinventory (given the sku from the user), find and * display a movie (given a sku from the user), and display all the * products in the inventory. * @author <NAME> * @author <NAME> */ public class Inventory implements Serializable { ArrayList<Product> items = new ArrayList<Product>(); // inventory /** * Default constructor, creates an empty inventory */ public Inventory() { try { FileInputStream fin = new FileInputStream("inventory.dat"); ObjectInputStream ois = new ObjectInputStream(fin); items = (ArrayList<Product>)ois.readObject(); fin.close(); } catch (FileNotFoundException e) { System.out.println("Cannot find datafile."); } catch (IOException e) { System.out.println("Problem with file input."); } catch (ClassNotFoundException e) { System.out.println("Class not found on input from file."); } } /** * Create a file output stream */ void writeToFile(){ try{ FileOutputStream fout = new FileOutputStream("inventory.dat"); ObjectOutputStream oout = new ObjectOutputStream(fout); oout.writeObject(items); oout.close(); } catch (IOException e){ System.out.println("Problem with file output"); } } /** * Validates the product * @param sku of the product being validated * @param quantity of the product trying to ordered * @param price price of the product * @return returns 0 if the items meets all the necessary criteria * -1 if the sku already exists in the inventory, or -2 if the * quantity or price are less then 0 * */ int validateProduct(int sku, int quantity, double price) { for (Product m : items){ //p declares a product object if (sku == m.getSku()) return -1; if (quantity < 0 || price < 0 ) return -2; } return 0; } /** * Removes a product from the Inventory * @param removeSku sku of the product to be removed */ void removeProduct(int removeSku) { for(Product p : items){ //p declares a product object if(p.getSku() == removeSku){ items.remove(p); System.out.println("Product removed."); return; } } System.out.print("No product found with this SKU \n"); } /** * Displays a product selected by SKU input by the user * @param displaySku the sku of the product to be displayed */ void displayProductInfo(int displaySku){ for(Product p : items){ //p declares a product object if(p.getSku() == displaySku){ String display = p.display(); //display is a holder for the string returned System.out.println(display); //from the display function return; } } System.out.print("No product found with this SKU\n"); System.out.print("\n"); } /** * Displays all the products in the Inventory */ void displayAllProducts(){ Collections.sort(items); for(Product p : items){ //p declares a product object String display=p.displayAll(); //display is a holder for the string returned System.out.println(display); //from the display function } System.out.print("\n"); } /** * Processes sale of a certain product. Constructs a string * @param sku of the product being processed * @param quantity of the products purchased * @param shipping shipping cost used my store * @return a string with all of the field values labeled */ String ProcessSale( int sku, int quantity, double shippingC) { for(Product p : items){ //p declares a product object if(p.getSku() == sku){ if (p.getQuantity() < quantity){ return "Quantity exceeds inventory"; } else{ int newQuantity = p.getQuantity() - quantity; p.setQuantity(newQuantity); String output = String.format("%1s %16s %1s %5s %1s %10s %1s %21s", "Total price: ", p.dfd.format(p.getPrice() * quantity), "\nTotal shipping credit: ", p.dfd.format(p.getShippingCredit() * quantity), "\nTotal commission: ", p.dfd.format(p.getCommission() * quantity), "\nProfit: ", p.dfd.format((p.getPrice() * quantity) + (p.getShippingCredit() * quantity) - ((p.getCommission() * quantity)+ shippingC ))); return output; } } }return null; } }
4,577
0.627532
0.623176
146
30.397261
24.233025
86
false
false
0
0
0
0
0
0
0.780822
false
false
14
309024eb11144143df1d2630ac59693ac93d5974
21,363,167,341,626
fb7d1e5a8c3f255b775d1d3885647c48fb0dac36
/src/main/java/LearningWithGoogleCom/PlayingWithGoogleComProvider/Discountable.java
a3bb6a93b081d914fe5bad138625c3e0ec57e4ac
[]
no_license
captainnemo2005/matsim-playground-monash
https://github.com/captainnemo2005/matsim-playground-monash
c4418cc14e9c4294bf9f56b7d0c73b04a3427d08
85d338309b0e8d87282468ecc2a72f5dc422f338
refs/heads/master
2022-12-18T14:01:00.792000
2020-09-25T04:42:57
2020-09-25T04:42:57
296,000,319
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package LearningWithGoogleCom.PlayingWithGoogleComProvider; public interface Discountable { double getDiscount(); }
UTF-8
Java
122
java
Discountable.java
Java
[]
null
[]
package LearningWithGoogleCom.PlayingWithGoogleComProvider; public interface Discountable { double getDiscount(); }
122
0.819672
0.819672
6
19.333334
21.699974
59
false
false
0
0
0
0
0
0
0.333333
false
false
14
ee1141bd73de4eb678a53892d9696c059089a5d6
27,118,423,536,262
f2a18ef78e06a2845565b4781e821633aded239b
/core/src/com/mygdx/abilities/Ability.java
339677e83e7d468b1cad652092dad1945b68f679
[]
no_license
p-han-tom/projectw
https://github.com/p-han-tom/projectw
b1386d4d096f02dfe307f4a8893b2f40cb082cdb
c3ce2ee1651e5b64031887dd9078939242934f34
refs/heads/master
2020-12-10T20:42:28.140000
2020-06-24T18:06:37
2020-06-24T18:06:37
233,705,440
1
0
null
false
2020-04-27T21:06:41
2020-01-13T22:18:48
2020-03-10T16:18:39
2020-04-27T21:06:41
73,694
0
0
3
Java
false
false
package com.mygdx.abilities; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.mygdx.abilities.range.AbilityRange; import com.mygdx.managers.BattleManager; public abstract class Ability { protected static SpriteBatch batcher = new SpriteBatch(); // variables for moving objects protected float x, y, fx, fy, rise, run; protected boolean aboveInitialPos; protected boolean sameInitialRow; protected boolean onInitialLeft; public boolean finishedDrawing = false; protected Texture spritesheet = new Texture("placeholder/sheet.png"); protected int spritedim = 16; protected Sprite icon; public AbilityRange range; protected int abilityRange; public abstract void effect(int row, int col, BattleManager combat); public abstract void draw(); public Sprite getIcon() {return icon;} public int getAbilityRange() {return abilityRange;} // this function initializes the direction and speed of the casted ability // x,y refers to the position of the unit // fx,fy refers to the position of the mouse where the ability has been cast public void drawLocation(float x, float y, float fx, float fy) { this.x = x; this.y = y; this.fx = fx; this.fy = fy; aboveInitialPos = (fy > y) ? true : false; sameInitialRow = (fy == y) ? true : false; onInitialLeft = (fx < x) ? true : false; if (fx > x) { run = 1; rise = (fy-y)/(fx-x); } else if (fx < x) { run = -1; rise = -(fy-y)/(fx-x); } else if (fx == x){ run = 0; rise = (fy > y) ? 1 : -1; } } }
UTF-8
Java
1,606
java
Ability.java
Java
[]
null
[]
package com.mygdx.abilities; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.mygdx.abilities.range.AbilityRange; import com.mygdx.managers.BattleManager; public abstract class Ability { protected static SpriteBatch batcher = new SpriteBatch(); // variables for moving objects protected float x, y, fx, fy, rise, run; protected boolean aboveInitialPos; protected boolean sameInitialRow; protected boolean onInitialLeft; public boolean finishedDrawing = false; protected Texture spritesheet = new Texture("placeholder/sheet.png"); protected int spritedim = 16; protected Sprite icon; public AbilityRange range; protected int abilityRange; public abstract void effect(int row, int col, BattleManager combat); public abstract void draw(); public Sprite getIcon() {return icon;} public int getAbilityRange() {return abilityRange;} // this function initializes the direction and speed of the casted ability // x,y refers to the position of the unit // fx,fy refers to the position of the mouse where the ability has been cast public void drawLocation(float x, float y, float fx, float fy) { this.x = x; this.y = y; this.fx = fx; this.fy = fy; aboveInitialPos = (fy > y) ? true : false; sameInitialRow = (fy == y) ? true : false; onInitialLeft = (fx < x) ? true : false; if (fx > x) { run = 1; rise = (fy-y)/(fx-x); } else if (fx < x) { run = -1; rise = -(fy-y)/(fx-x); } else if (fx == x){ run = 0; rise = (fy > y) ? 1 : -1; } } }
1,606
0.69863
0.693026
57
27.175438
21.272768
77
false
false
0
0
0
0
0
0
2.035088
false
false
14
fa606884fb1f326ccdcd06d1dac1150340e7ea48
10,677,288,746,250
081fee0385cef58e420f68cfebfe7d28a8ffd16d
/src/main/java/edu/willamette/crossearch/dao/HitsArrayAdapter.java
b2bb19d979bef78f817481e2903019dff77ea75e
[]
no_license
hatfieldlibrary/cross-search
https://github.com/hatfieldlibrary/cross-search
3218cd4bec3538e960206efbba8381e771190c04
2c78e7baa0f63c3522632b30402837850f94e095
refs/heads/master
2020-03-14T20:21:27.330000
2018-05-03T22:38:19
2018-05-03T22:38:19
128,823,659
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.willamette.crossearch.dao; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; import edu.willamette.crossearch.model.existdb.Hits; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class HitsArrayAdapter<T> extends TypeAdapter<List<Hits>> { private Hits adapterclass; public HitsArrayAdapter(Hits adapterclass) { this.adapterclass = adapterclass; } @Override public void write(JsonWriter out, List<Hits> value) throws IOException { } public List<Hits> read(JsonReader reader) throws IOException { List<Hits> list = new ArrayList<>(); Gson gson = new Gson(); String path = reader.getPath(); if (reader.peek() == JsonToken.BEGIN_OBJECT) { Hits inning = gson.fromJson(reader, Hits.class); list.add(inning); } else if (reader.peek() == JsonToken.BEGIN_ARRAY) { reader.beginArray(); while (reader.hasNext()) { Hits inning = gson.fromJson(reader, Hits.class); list.add(inning); } reader.endArray(); } else { reader.skipValue(); } return list; } }
UTF-8
Java
1,379
java
HitsArrayAdapter.java
Java
[]
null
[]
package edu.willamette.crossearch.dao; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; import edu.willamette.crossearch.model.existdb.Hits; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class HitsArrayAdapter<T> extends TypeAdapter<List<Hits>> { private Hits adapterclass; public HitsArrayAdapter(Hits adapterclass) { this.adapterclass = adapterclass; } @Override public void write(JsonWriter out, List<Hits> value) throws IOException { } public List<Hits> read(JsonReader reader) throws IOException { List<Hits> list = new ArrayList<>(); Gson gson = new Gson(); String path = reader.getPath(); if (reader.peek() == JsonToken.BEGIN_OBJECT) { Hits inning = gson.fromJson(reader, Hits.class); list.add(inning); } else if (reader.peek() == JsonToken.BEGIN_ARRAY) { reader.beginArray(); while (reader.hasNext()) { Hits inning = gson.fromJson(reader, Hits.class); list.add(inning); } reader.endArray(); } else { reader.skipValue(); } return list; } }
1,379
0.627266
0.627266
56
23.607143
22.370802
76
false
false
0
0
0
0
0
0
0.464286
false
false
14
f5ef088584860df0e3ef599f87f27e74b60eec43
33,517,924,793,653
58bec87f2aee994d2f1a518faba033ec88213cfe
/src/main/java/com/thenetcircle/services/commons/rest/utils/AjaxResLoader.java
9405096adbb911d8b8cf247fc263f16c47af2690
[]
no_license
cfcodefans/MQueueDispatcher
https://github.com/cfcodefans/MQueueDispatcher
e0a60e22d058164bde12500d3b297faa54f5d0d2
bc36102d9eaed054158cce5e21a6c7a749f699fe
refs/heads/master
2021-01-17T10:35:25.893000
2015-01-15T11:29:35
2015-01-15T11:29:35
28,588,520
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.thenetcircle.services.commons.rest.utils; import java.lang.reflect.Field; import java.security.AccessController; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import javax.inject.Singleton; import javax.ws.rs.CookieParam; import javax.ws.rs.Encoded; import javax.ws.rs.FormParam; import javax.ws.rs.HeaderParam; import javax.ws.rs.HttpMethod; import javax.ws.rs.MatrixParam; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.glassfish.hk2.api.PerLookup; import org.glassfish.jersey.internal.inject.Providers; import org.glassfish.jersey.internal.util.ReflectionHelper; import org.glassfish.jersey.jackson.JacksonFeature; import org.glassfish.jersey.message.DeflateEncoder; import org.glassfish.jersey.message.GZipEncoder; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.server.filter.EncodingFilter; import org.glassfish.jersey.server.model.AnnotatedMethod; import org.glassfish.jersey.server.model.MethodList; import org.glassfish.jersey.server.model.Parameter; import org.glassfish.jersey.server.model.Resource; import org.glassfish.jersey.server.model.ResourceModel; import org.glassfish.jersey.server.monitoring.ApplicationEvent; import org.glassfish.jersey.server.monitoring.ApplicationEvent.Type; import org.glassfish.jersey.server.monitoring.ApplicationEventListener; import org.glassfish.jersey.server.monitoring.RequestEvent; import org.glassfish.jersey.server.monitoring.RequestEventListener; import org.glassfish.jersey.server.spi.Container; import org.glassfish.jersey.server.spi.ContainerLifecycleListener; import com.thenetcircle.services.commons.MiscUtils; import com.thenetcircle.services.commons.ProcTrace; import com.thenetcircle.services.commons.cdi.rest.WeldBinder; import com.thenetcircle.services.commons.rest.ajax.AjaxResMetaData; import com.thenetcircle.services.commons.rest.ajax.ParamMetaData; public class AjaxResLoader extends ResourceConfig { private static Log log = LogFactory.getLog(AjaxResLoader.class); public AjaxResLoader() { ProcTrace.start(MiscUtils.invocationInfo()); ProcTrace.ongoing("set packages scann"); register(JacksonFeature.class); register(EncodingFilter.class); register(GZipEncoder.class); register(DeflateEncoder.class); // this.packages("com.thenetcircle.services.rest"); register(new ResLoaderListener()); register(new WeldBinder()); ProcTrace.end(); log.info(ProcTrace.flush()); } public static class AjaxResContext { private static final ConcurrentMap<String, AjaxResContext> cache = new ConcurrentHashMap<String, AjaxResContext>(); private AjaxResContext() {} public static AjaxResContext getInstance(String name) { cache.putIfAbsent(name, new AjaxResContext()); return cache.get(name); } private ResourceModel resModel = null; private ResourceConfig appCfg = null; private List<AjaxResMetaData> proxyList = new ArrayList<AjaxResMetaData>(); public List<AjaxResMetaData> getProxyList() { return proxyList; } @SuppressWarnings("rawtypes") public void build(final ResourceModel _resModel, final ResourceConfig _app) { resModel = _resModel; appCfg = _app; Collection<Resource> resources = resModel.getResources(); if (CollectionUtils.isEmpty(resources)) { return; } Set<Class<?>> resClss = appCfg.getClasses(); log.info("\nfound resources classes: \n" + StringUtils.join(resClss, '\n')); log.info("\nfound singleton instances: \n" + StringUtils.join(appCfg.getSingletons(), '\n')); for (final Resource res : resources) { AjaxResMetaData resMd = AjaxResMetaData.build(res); Collection<Class<?>> _clss = CollectionUtils.intersection(resClss, res.getHandlerClasses()); for (Class _cls : _clss) { if (isSingleton(_cls)) { continue; } for (Parameter p : getClassSetters(true, _cls)) { resMd.injectedParams.add(ParamMetaData.build(p)); } for (Parameter p : getClassFields(true, _cls)) { resMd.injectedParams.add(ParamMetaData.build(p)); } } log.info("\n injected Params: \n\t" + StringUtils.join(resMd.injectedParams, "\n\t")); resMd.appendInjectedParams(resMd.injectedParams); proxyList.add(resMd); } } @SuppressWarnings("rawtypes") private static List<Parameter> getClassSetters(final boolean encodedFlag, final Class handlerClass) { final MethodList methodList = new MethodList(handlerClass, true); List<Parameter> params = new ArrayList<Parameter>(); for (AnnotatedMethod method : methodList.withoutMetaAnnotation(HttpMethod.class). withoutAnnotation(Path.class). withoutAnnotation(Context.class). hasNumParams(1). hasReturnType(void.class). nameStartsWith("set")) { Parameter p = Parameter.create( handlerClass, method.getMethod().getDeclaringClass(), encodedFlag || method.isAnnotationPresent(Encoded.class), method.getParameterTypes()[0], method.getGenericParameterTypes()[0], method.getAnnotations()); if (null != p) { // ResourceMethodValidator.validateParameter(p, method.getMethod(), method.getMethod().toGenericString(), "1", // isSingleton(handlerClass)); params.add(p); } } return params; } @SuppressWarnings("rawtypes") private static List<Parameter> getClassFields(final boolean encodedFlag, Class handlerClass) { List<Parameter> params = new ArrayList<Parameter>(); for (Field field : AccessController.doPrivileged(ReflectionHelper.getDeclaredFieldsPA(handlerClass))) { if (field.getDeclaredAnnotations().length > 0 && (field.isAnnotationPresent(QueryParam.class) || field.isAnnotationPresent(PathParam.class) || field.isAnnotationPresent(CookieParam.class) || field.isAnnotationPresent(MatrixParam.class) || field.isAnnotationPresent(FormParam.class) || field.isAnnotationPresent(HeaderParam.class))) { Parameter p = Parameter.create( handlerClass, field.getDeclaringClass(), encodedFlag || field.isAnnotationPresent(Encoded.class), field.getType(), field.getGenericType(), field.getAnnotations()); if (null != p) { // ResourceMethodValidator.validateParameter(p, field, field.toGenericString(), field.getName(), // isInSingleton); params.add(p); } } } return params; } /** * Check if the resource class is declared to be a singleton. * * @param resourceClass resource class. * @return {@code true} if the resource class is a singleton, {@code false} otherwise. */ private static boolean isSingleton(Class<?> resourceClass) { return resourceClass.isAnnotationPresent(Singleton.class) || (Providers.isProvider(resourceClass) && !resourceClass.isAnnotationPresent(PerLookup.class)); } } public static class ResLoaderListener implements ContainerLifecycleListener, ApplicationEventListener { @Override public void onStartup(Container c) { log.info(MiscUtils.invocationInfo() + "\n\n\t"); } @Override public void onReload(Container c) { log.info(MiscUtils.invocationInfo()); } @Override public void onShutdown(Container c) { log.info(MiscUtils.invocationInfo()); } @Override public void onEvent(ApplicationEvent ev) { log.info(MiscUtils.invocationInfo() + "\n\n\t"); if (Type.INITIALIZATION_APP_FINISHED == ev.getType()) { AjaxResContext.getInstance(ev.getResourceConfig().getApplicationName()).build(ev.getResourceModel(), ev.getResourceConfig()); //AjaxRes.build(ev.getResourceModel(), ev.getResourceConfig()); } log.info(MiscUtils.invocationInfo() + " finished loading restful apis....."); } @Override public RequestEventListener onRequest(RequestEvent reqEv) { return null; } } }
UTF-8
Java
8,776
java
AjaxResLoader.java
Java
[]
null
[]
package com.thenetcircle.services.commons.rest.utils; import java.lang.reflect.Field; import java.security.AccessController; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import javax.inject.Singleton; import javax.ws.rs.CookieParam; import javax.ws.rs.Encoded; import javax.ws.rs.FormParam; import javax.ws.rs.HeaderParam; import javax.ws.rs.HttpMethod; import javax.ws.rs.MatrixParam; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.glassfish.hk2.api.PerLookup; import org.glassfish.jersey.internal.inject.Providers; import org.glassfish.jersey.internal.util.ReflectionHelper; import org.glassfish.jersey.jackson.JacksonFeature; import org.glassfish.jersey.message.DeflateEncoder; import org.glassfish.jersey.message.GZipEncoder; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.server.filter.EncodingFilter; import org.glassfish.jersey.server.model.AnnotatedMethod; import org.glassfish.jersey.server.model.MethodList; import org.glassfish.jersey.server.model.Parameter; import org.glassfish.jersey.server.model.Resource; import org.glassfish.jersey.server.model.ResourceModel; import org.glassfish.jersey.server.monitoring.ApplicationEvent; import org.glassfish.jersey.server.monitoring.ApplicationEvent.Type; import org.glassfish.jersey.server.monitoring.ApplicationEventListener; import org.glassfish.jersey.server.monitoring.RequestEvent; import org.glassfish.jersey.server.monitoring.RequestEventListener; import org.glassfish.jersey.server.spi.Container; import org.glassfish.jersey.server.spi.ContainerLifecycleListener; import com.thenetcircle.services.commons.MiscUtils; import com.thenetcircle.services.commons.ProcTrace; import com.thenetcircle.services.commons.cdi.rest.WeldBinder; import com.thenetcircle.services.commons.rest.ajax.AjaxResMetaData; import com.thenetcircle.services.commons.rest.ajax.ParamMetaData; public class AjaxResLoader extends ResourceConfig { private static Log log = LogFactory.getLog(AjaxResLoader.class); public AjaxResLoader() { ProcTrace.start(MiscUtils.invocationInfo()); ProcTrace.ongoing("set packages scann"); register(JacksonFeature.class); register(EncodingFilter.class); register(GZipEncoder.class); register(DeflateEncoder.class); // this.packages("com.thenetcircle.services.rest"); register(new ResLoaderListener()); register(new WeldBinder()); ProcTrace.end(); log.info(ProcTrace.flush()); } public static class AjaxResContext { private static final ConcurrentMap<String, AjaxResContext> cache = new ConcurrentHashMap<String, AjaxResContext>(); private AjaxResContext() {} public static AjaxResContext getInstance(String name) { cache.putIfAbsent(name, new AjaxResContext()); return cache.get(name); } private ResourceModel resModel = null; private ResourceConfig appCfg = null; private List<AjaxResMetaData> proxyList = new ArrayList<AjaxResMetaData>(); public List<AjaxResMetaData> getProxyList() { return proxyList; } @SuppressWarnings("rawtypes") public void build(final ResourceModel _resModel, final ResourceConfig _app) { resModel = _resModel; appCfg = _app; Collection<Resource> resources = resModel.getResources(); if (CollectionUtils.isEmpty(resources)) { return; } Set<Class<?>> resClss = appCfg.getClasses(); log.info("\nfound resources classes: \n" + StringUtils.join(resClss, '\n')); log.info("\nfound singleton instances: \n" + StringUtils.join(appCfg.getSingletons(), '\n')); for (final Resource res : resources) { AjaxResMetaData resMd = AjaxResMetaData.build(res); Collection<Class<?>> _clss = CollectionUtils.intersection(resClss, res.getHandlerClasses()); for (Class _cls : _clss) { if (isSingleton(_cls)) { continue; } for (Parameter p : getClassSetters(true, _cls)) { resMd.injectedParams.add(ParamMetaData.build(p)); } for (Parameter p : getClassFields(true, _cls)) { resMd.injectedParams.add(ParamMetaData.build(p)); } } log.info("\n injected Params: \n\t" + StringUtils.join(resMd.injectedParams, "\n\t")); resMd.appendInjectedParams(resMd.injectedParams); proxyList.add(resMd); } } @SuppressWarnings("rawtypes") private static List<Parameter> getClassSetters(final boolean encodedFlag, final Class handlerClass) { final MethodList methodList = new MethodList(handlerClass, true); List<Parameter> params = new ArrayList<Parameter>(); for (AnnotatedMethod method : methodList.withoutMetaAnnotation(HttpMethod.class). withoutAnnotation(Path.class). withoutAnnotation(Context.class). hasNumParams(1). hasReturnType(void.class). nameStartsWith("set")) { Parameter p = Parameter.create( handlerClass, method.getMethod().getDeclaringClass(), encodedFlag || method.isAnnotationPresent(Encoded.class), method.getParameterTypes()[0], method.getGenericParameterTypes()[0], method.getAnnotations()); if (null != p) { // ResourceMethodValidator.validateParameter(p, method.getMethod(), method.getMethod().toGenericString(), "1", // isSingleton(handlerClass)); params.add(p); } } return params; } @SuppressWarnings("rawtypes") private static List<Parameter> getClassFields(final boolean encodedFlag, Class handlerClass) { List<Parameter> params = new ArrayList<Parameter>(); for (Field field : AccessController.doPrivileged(ReflectionHelper.getDeclaredFieldsPA(handlerClass))) { if (field.getDeclaredAnnotations().length > 0 && (field.isAnnotationPresent(QueryParam.class) || field.isAnnotationPresent(PathParam.class) || field.isAnnotationPresent(CookieParam.class) || field.isAnnotationPresent(MatrixParam.class) || field.isAnnotationPresent(FormParam.class) || field.isAnnotationPresent(HeaderParam.class))) { Parameter p = Parameter.create( handlerClass, field.getDeclaringClass(), encodedFlag || field.isAnnotationPresent(Encoded.class), field.getType(), field.getGenericType(), field.getAnnotations()); if (null != p) { // ResourceMethodValidator.validateParameter(p, field, field.toGenericString(), field.getName(), // isInSingleton); params.add(p); } } } return params; } /** * Check if the resource class is declared to be a singleton. * * @param resourceClass resource class. * @return {@code true} if the resource class is a singleton, {@code false} otherwise. */ private static boolean isSingleton(Class<?> resourceClass) { return resourceClass.isAnnotationPresent(Singleton.class) || (Providers.isProvider(resourceClass) && !resourceClass.isAnnotationPresent(PerLookup.class)); } } public static class ResLoaderListener implements ContainerLifecycleListener, ApplicationEventListener { @Override public void onStartup(Container c) { log.info(MiscUtils.invocationInfo() + "\n\n\t"); } @Override public void onReload(Container c) { log.info(MiscUtils.invocationInfo()); } @Override public void onShutdown(Container c) { log.info(MiscUtils.invocationInfo()); } @Override public void onEvent(ApplicationEvent ev) { log.info(MiscUtils.invocationInfo() + "\n\n\t"); if (Type.INITIALIZATION_APP_FINISHED == ev.getType()) { AjaxResContext.getInstance(ev.getResourceConfig().getApplicationName()).build(ev.getResourceModel(), ev.getResourceConfig()); //AjaxRes.build(ev.getResourceModel(), ev.getResourceConfig()); } log.info(MiscUtils.invocationInfo() + " finished loading restful apis....."); } @Override public RequestEventListener onRequest(RequestEvent reqEv) { return null; } } }
8,776
0.692685
0.691773
232
36.827587
28.849125
129
false
false
0
0
0
0
0
0
2.435345
false
false
14
419795dc54be69fef303a88bd12a8a5a0016bb66
24,842,090,894,095
8b2a993d2a156c2c2ab976886b178985b15c5678
/src/Chop.java
652656e376e95f19090b6537f62ac58078b123fe
[]
no_license
hereismhtm/Chop
https://github.com/hereismhtm/Chop
dd21248d62b71f69a55fb176d0944810b71b6a99
c0951a2972863953cf4855848d0055e598f32b11
refs/heads/master
2023-08-02T19:06:20.161000
2021-10-06T09:25:55
2021-10-06T09:25:55
288,496,954
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import compress.CompressMode; import compress.disk.DataManager; import compress.disk.HeaderBuilder; import compress.memory.Table; import helpers.StopWatch; import java.io.File; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.Arrays; public class Chop { static final HeaderBuilder headerBuilder = new HeaderBuilder(); static final long[] matrix = new long[0xff]; static int round = 0; static long bestCompressedSize; static DataManager dm; static Table table; public static void main(String[] args) { CompressMode mode; File input; File output; switch (args.length) { case 0: case 1: System.out.println("(ง'̀-'́)ง compress mode and input file are not mentioned."); break; case 2: case 3: try { mode = CompressMode.valueOf(args[0].toLowerCase()); } catch (IllegalArgumentException e) { mode = CompressMode.b3; System.out.println("┬─┬ノ( º _ ºノ) compress mode is set to default one."); } input = new File(args[1]); output = new File(args.length == 3 ? args[2] : args[1].concat(Constants.EXT)); if (!input.isFile()) System.out.println("¯\\_(ツ)_/¯ input file not found."); else { System.out.println("mode: " + mode.name()); System.out.println("input file: " + input.getAbsolutePath()); System.out.println("output file: " + output.getAbsolutePath()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); DataManager.compressMode = mode; boolean success = compress(input, output); stopWatch.stop(); if (success) { System.out.println("\n(ノ◕ヮ◕)ノ*:・゚✧ Complete \u2714 "); System.out.print("new smaller size: " + bestCompressedSize + " bytes \u2764 "); System.out.println(readableSize(bestCompressedSize)); System.out.println("compress efficiency: " + outputEffAgainst(headerBuilder.originalSize)); System.out.println("sha1 fingerprint: " + dm.outputSha160Sum.digest()); } else { System.out.println("\n(ಥ﹏ಥ) PROCESS FAILED!"); } System.out.println("total rounds: " + round); System.out.print("process time: "); long minutes = stopWatch.getTimeMinutes(); long seconds = stopWatch.getTimeSeconds(); seconds = seconds - (minutes * 60); System.out.print(minutes + " minute and "); System.out.println(seconds + " second"); } break; } } static String outputEffAgainst(long size) { double percent = bestCompressedSize / (double) size * 100; return roundHalfUp2(100 - percent) + "%"; } static String readableSize(long size) { double d = size; int i = 0; while (d >= 1024) { d /= 1024; i++; } d = roundHalfUp2(d); switch (i) { case 4: return String.valueOf(d).concat(" TB"); case 3: return String.valueOf(d).concat(" GB"); case 2: return String.valueOf(d).concat(" MB"); case 1: return String.valueOf(d).concat(" KB"); default: return ""; } } static double roundHalfUp2(double value) { BigDecimal bd = BigDecimal.valueOf(value); bd = bd.setScale(2, RoundingMode.HALF_UP); return bd.doubleValue(); } static boolean compress(File input, File output) { round++; File roundFile = new File(output.getAbsolutePath().concat("^.cR" + round)); dm = new DataManager(input.getAbsoluteFile(), roundFile); if (table == null) table = new Table(); else table.reset(); if (round == 1) { headerBuilder.originalSize = dm.getSourceSize(); bestCompressedSize = headerBuilder.originalSize; System.out.print("input size: " + headerBuilder.originalSize + " bytes "); System.out.println("/ " + readableSize(headerBuilder.originalSize)); } System.out.println("\nROUND #" + round); System.out.println("\u2699 preparing ..."); int matrixBlocks = buildMatrix(); long domination = calculateMatrixDomination(); System.out.println("\u27A5 |Done|"); System.out.println(table.getCount() + " blocks in memory"); System.out.println("matrix blocks [" + matrixBlocks + "]"); System.out.println("domination " + domination); System.out.print("--> starting "); dm.virtualWriterMode = true; fullPassIndexer(matrixBlocks); if (round == 1) { headerBuilder.fingerprint = dm.inputSha160Sum.digest(); } long nextCompressedSize = dm.getSourceSize() - domination + ((1 + dm.getSections()) * 3 - 2) + 1 + HeaderBuilder.HEADER_SIZE; if (nextCompressedSize < bestCompressedSize) { dm.rewind(); System.out.println("now"); } else { dm.close(true); System.out.println("\n--> round " + round + " canceled"); round--; return round != 0 && dm.sourceSaveAs(output, headerBuilder); } System.out.println("\u2699 compressing ..."); dm.virtualWriterMode = false; dm.initWriter( (byte) (round == 1 ? Constants.VERSION_NUMBER : -Constants.VERSION_NUMBER), getMatrixBytes(matrixBlocks) ); fullPassIndexer(matrixBlocks); dm.close(false); System.out.println("\u27A5 |Done|"); if (dm.getDestinationSize() + HeaderBuilder.HEADER_SIZE == nextCompressedSize) { if (round != 1 && !dm.deleteSource()) { return false; } else { bestCompressedSize = dm.getDestinationSize() + HeaderBuilder.HEADER_SIZE; System.out.println(dm.getSections() + " sections, max " + dm.getMaxSectionSize()); System.out.println("size down to " + bestCompressedSize + " bytes"); System.out.println("efficiency " + outputEffAgainst(dm.getSourceSize())); if (bestCompressedSize <= Constants.SINGULARITY_SIZE) { return dm.destinationSaveAs(output, headerBuilder); } return compress(roundFile, output); } } else { System.out.println("diff " + (dm.getDestinationSize() + HeaderBuilder.HEADER_SIZE - nextCompressedSize)); System.out.println("--> round " + round + " ignored"); round--; return dm.deleteDestination() && round != 0 && dm.sourceSaveAs(output, headerBuilder); } } static void fullPassIndexer(int matrixBlocks) { int index; int indexCorrector = matrix.length - matrixBlocks; while (dm.fetchBlock() == DataManager.compressMode.BLOCK_LEN) { index = Arrays.binarySearch(matrix, dm.getBlockId()); if (index < 0) { dm.writeBlock(); } else { index -= indexCorrector; dm.writeCompressedBlock(index); } } dm.flush(); } static int buildMatrix() { while (dm.fetchBlock() == DataManager.compressMode.BLOCK_LEN) { table.updateValuePlus(dm.getBlockId()); } dm.rewind(); int mbc = 1 + DataManager.compressMode.BLOCK_LEN; mbc /= DataManager.compressMode.BLOCK_LEN - 2; int i; Arrays.fill(matrix, Constants.NO_BLOCK_ID); for (i = 0; i < matrix.length; i++) { matrix[i] = table.selectIdOfMaxValue(mbc); if (matrix[i] == -404) { matrix[i] = Constants.NO_BLOCK_ID; break; } table.updateValueNegative(matrix[i]); // System.out.print("BLK(" + matrix[i] + ") "); // System.out.println("X" + table.selectValue(matrix[i])); } Arrays.sort(matrix); return i; } static long calculateMatrixDomination() { int bl = DataManager.compressMode.BLOCK_LEN; long domination = 0; for (long id : matrix) { if (id == Constants.NO_BLOCK_ID) continue; domination += table.selectValue(id) * (bl - 2) - bl; } return domination - 2; } static byte[] getMatrixBytes(int matrixBlocks) { byte[] m = new byte[2 + (matrixBlocks * DataManager.compressMode.BLOCK_LEN)]; m[0] = (byte) (matrixBlocks > Byte.MAX_VALUE ? matrixBlocks - 256 : matrixBlocks); m[1] = (byte) DataManager.compressMode.BLOCK_LEN; int i = 2; for (long id : matrix) { if (id == Constants.NO_BLOCK_ID) continue; // System.out.println("BLK(" + id + ")"); idExpander(id, m, i); // System.out.println("--------"); i += DataManager.compressMode.BLOCK_LEN; } return m; } static void idExpander(long id, byte[] intoArray, int startIndex) { int endIndex = startIndex + DataManager.compressMode.BLOCK_LEN; int b; while (id > 0) { b = (int) (id % 256); if (b > Byte.MAX_VALUE) b -= 256; intoArray[startIndex++] = (byte) b; // System.out.println("byte " + b); id /= 256; } while (startIndex < endIndex) { intoArray[startIndex++] = 0; // System.out.println("byte 0"); } } private static class Constants { static final String EXT = ".bhs"; static final int VERSION_NUMBER = 1; static final int NO_BLOCK_ID = -1; static final int SINGULARITY_SIZE = 0/*1048576*/; } }
UTF-8
Java
10,483
java
Chop.java
Java
[]
null
[]
import compress.CompressMode; import compress.disk.DataManager; import compress.disk.HeaderBuilder; import compress.memory.Table; import helpers.StopWatch; import java.io.File; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.Arrays; public class Chop { static final HeaderBuilder headerBuilder = new HeaderBuilder(); static final long[] matrix = new long[0xff]; static int round = 0; static long bestCompressedSize; static DataManager dm; static Table table; public static void main(String[] args) { CompressMode mode; File input; File output; switch (args.length) { case 0: case 1: System.out.println("(ง'̀-'́)ง compress mode and input file are not mentioned."); break; case 2: case 3: try { mode = CompressMode.valueOf(args[0].toLowerCase()); } catch (IllegalArgumentException e) { mode = CompressMode.b3; System.out.println("┬─┬ノ( º _ ºノ) compress mode is set to default one."); } input = new File(args[1]); output = new File(args.length == 3 ? args[2] : args[1].concat(Constants.EXT)); if (!input.isFile()) System.out.println("¯\\_(ツ)_/¯ input file not found."); else { System.out.println("mode: " + mode.name()); System.out.println("input file: " + input.getAbsolutePath()); System.out.println("output file: " + output.getAbsolutePath()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); DataManager.compressMode = mode; boolean success = compress(input, output); stopWatch.stop(); if (success) { System.out.println("\n(ノ◕ヮ◕)ノ*:・゚✧ Complete \u2714 "); System.out.print("new smaller size: " + bestCompressedSize + " bytes \u2764 "); System.out.println(readableSize(bestCompressedSize)); System.out.println("compress efficiency: " + outputEffAgainst(headerBuilder.originalSize)); System.out.println("sha1 fingerprint: " + dm.outputSha160Sum.digest()); } else { System.out.println("\n(ಥ﹏ಥ) PROCESS FAILED!"); } System.out.println("total rounds: " + round); System.out.print("process time: "); long minutes = stopWatch.getTimeMinutes(); long seconds = stopWatch.getTimeSeconds(); seconds = seconds - (minutes * 60); System.out.print(minutes + " minute and "); System.out.println(seconds + " second"); } break; } } static String outputEffAgainst(long size) { double percent = bestCompressedSize / (double) size * 100; return roundHalfUp2(100 - percent) + "%"; } static String readableSize(long size) { double d = size; int i = 0; while (d >= 1024) { d /= 1024; i++; } d = roundHalfUp2(d); switch (i) { case 4: return String.valueOf(d).concat(" TB"); case 3: return String.valueOf(d).concat(" GB"); case 2: return String.valueOf(d).concat(" MB"); case 1: return String.valueOf(d).concat(" KB"); default: return ""; } } static double roundHalfUp2(double value) { BigDecimal bd = BigDecimal.valueOf(value); bd = bd.setScale(2, RoundingMode.HALF_UP); return bd.doubleValue(); } static boolean compress(File input, File output) { round++; File roundFile = new File(output.getAbsolutePath().concat("^.cR" + round)); dm = new DataManager(input.getAbsoluteFile(), roundFile); if (table == null) table = new Table(); else table.reset(); if (round == 1) { headerBuilder.originalSize = dm.getSourceSize(); bestCompressedSize = headerBuilder.originalSize; System.out.print("input size: " + headerBuilder.originalSize + " bytes "); System.out.println("/ " + readableSize(headerBuilder.originalSize)); } System.out.println("\nROUND #" + round); System.out.println("\u2699 preparing ..."); int matrixBlocks = buildMatrix(); long domination = calculateMatrixDomination(); System.out.println("\u27A5 |Done|"); System.out.println(table.getCount() + " blocks in memory"); System.out.println("matrix blocks [" + matrixBlocks + "]"); System.out.println("domination " + domination); System.out.print("--> starting "); dm.virtualWriterMode = true; fullPassIndexer(matrixBlocks); if (round == 1) { headerBuilder.fingerprint = dm.inputSha160Sum.digest(); } long nextCompressedSize = dm.getSourceSize() - domination + ((1 + dm.getSections()) * 3 - 2) + 1 + HeaderBuilder.HEADER_SIZE; if (nextCompressedSize < bestCompressedSize) { dm.rewind(); System.out.println("now"); } else { dm.close(true); System.out.println("\n--> round " + round + " canceled"); round--; return round != 0 && dm.sourceSaveAs(output, headerBuilder); } System.out.println("\u2699 compressing ..."); dm.virtualWriterMode = false; dm.initWriter( (byte) (round == 1 ? Constants.VERSION_NUMBER : -Constants.VERSION_NUMBER), getMatrixBytes(matrixBlocks) ); fullPassIndexer(matrixBlocks); dm.close(false); System.out.println("\u27A5 |Done|"); if (dm.getDestinationSize() + HeaderBuilder.HEADER_SIZE == nextCompressedSize) { if (round != 1 && !dm.deleteSource()) { return false; } else { bestCompressedSize = dm.getDestinationSize() + HeaderBuilder.HEADER_SIZE; System.out.println(dm.getSections() + " sections, max " + dm.getMaxSectionSize()); System.out.println("size down to " + bestCompressedSize + " bytes"); System.out.println("efficiency " + outputEffAgainst(dm.getSourceSize())); if (bestCompressedSize <= Constants.SINGULARITY_SIZE) { return dm.destinationSaveAs(output, headerBuilder); } return compress(roundFile, output); } } else { System.out.println("diff " + (dm.getDestinationSize() + HeaderBuilder.HEADER_SIZE - nextCompressedSize)); System.out.println("--> round " + round + " ignored"); round--; return dm.deleteDestination() && round != 0 && dm.sourceSaveAs(output, headerBuilder); } } static void fullPassIndexer(int matrixBlocks) { int index; int indexCorrector = matrix.length - matrixBlocks; while (dm.fetchBlock() == DataManager.compressMode.BLOCK_LEN) { index = Arrays.binarySearch(matrix, dm.getBlockId()); if (index < 0) { dm.writeBlock(); } else { index -= indexCorrector; dm.writeCompressedBlock(index); } } dm.flush(); } static int buildMatrix() { while (dm.fetchBlock() == DataManager.compressMode.BLOCK_LEN) { table.updateValuePlus(dm.getBlockId()); } dm.rewind(); int mbc = 1 + DataManager.compressMode.BLOCK_LEN; mbc /= DataManager.compressMode.BLOCK_LEN - 2; int i; Arrays.fill(matrix, Constants.NO_BLOCK_ID); for (i = 0; i < matrix.length; i++) { matrix[i] = table.selectIdOfMaxValue(mbc); if (matrix[i] == -404) { matrix[i] = Constants.NO_BLOCK_ID; break; } table.updateValueNegative(matrix[i]); // System.out.print("BLK(" + matrix[i] + ") "); // System.out.println("X" + table.selectValue(matrix[i])); } Arrays.sort(matrix); return i; } static long calculateMatrixDomination() { int bl = DataManager.compressMode.BLOCK_LEN; long domination = 0; for (long id : matrix) { if (id == Constants.NO_BLOCK_ID) continue; domination += table.selectValue(id) * (bl - 2) - bl; } return domination - 2; } static byte[] getMatrixBytes(int matrixBlocks) { byte[] m = new byte[2 + (matrixBlocks * DataManager.compressMode.BLOCK_LEN)]; m[0] = (byte) (matrixBlocks > Byte.MAX_VALUE ? matrixBlocks - 256 : matrixBlocks); m[1] = (byte) DataManager.compressMode.BLOCK_LEN; int i = 2; for (long id : matrix) { if (id == Constants.NO_BLOCK_ID) continue; // System.out.println("BLK(" + id + ")"); idExpander(id, m, i); // System.out.println("--------"); i += DataManager.compressMode.BLOCK_LEN; } return m; } static void idExpander(long id, byte[] intoArray, int startIndex) { int endIndex = startIndex + DataManager.compressMode.BLOCK_LEN; int b; while (id > 0) { b = (int) (id % 256); if (b > Byte.MAX_VALUE) b -= 256; intoArray[startIndex++] = (byte) b; // System.out.println("byte " + b); id /= 256; } while (startIndex < endIndex) { intoArray[startIndex++] = 0; // System.out.println("byte 0"); } } private static class Constants { static final String EXT = ".bhs"; static final int VERSION_NUMBER = 1; static final int NO_BLOCK_ID = -1; static final int SINGULARITY_SIZE = 0/*1048576*/; } }
10,483
0.5262
0.515183
284
35.757042
26.185163
117
false
false
0
0
0
0
0
0
0.630282
false
false
14
b04450e149f3f357979fe920a0543f0e7cd7989c
35,167,192,237,779
d9b3b8bcc66806e9937c4e83ce67a06f729abf2f
/Event-Works/src/com/eventworks/events/task/BaseJsonTask.java
ee9384d7f7107047390ba9c2ff6aa3eea8cc5014
[]
no_license
dan41k/event-works
https://github.com/dan41k/event-works
773ea7419b368b919af51893e1ef734a92e83de0
0b27427ab5683713d010e0f954cdc63002ef0021
refs/heads/master
2015-08-12T10:20:44.378000
2014-12-19T16:11:21
2014-12-19T16:11:21
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.eventworks.events.task; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import com.eventworks.events.https.HttpClientFactory; import android.os.AsyncTask; import android.util.Log; public abstract class BaseJsonTask extends AsyncTask<String, Void, String> { protected String url; protected String key; public BaseJsonTask(String key) { this.key = key; } @Override protected String doInBackground(String... params) { Log.d("MyTag", "doInBackground, URL = " + url); HttpClient httpClient = new HttpClientFactory().getNewHttpClient(); HttpGet httpGet = new HttpGet(url); httpGet.setHeader("Content-type", "application/json"); InputStream inputStream = null; String result = null; try { HttpResponse response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity(); inputStream = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader( inputStream, "UTF-8"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } result = sb.toString(); } catch (Exception e) { Log.e("MyTag", e.getMessage()); } finally { try { if (inputStream != null) inputStream.close(); } catch (Exception squish) { Log.e("MyTag", squish.getMessage()); } } Log.d("MyTag", "Result:" + result); parse(result); return result; } public void executeTask() { this.execute(); } public abstract void parse(String result); }
UTF-8
Java
1,917
java
BaseJsonTask.java
Java
[]
null
[]
package com.eventworks.events.task; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import com.eventworks.events.https.HttpClientFactory; import android.os.AsyncTask; import android.util.Log; public abstract class BaseJsonTask extends AsyncTask<String, Void, String> { protected String url; protected String key; public BaseJsonTask(String key) { this.key = key; } @Override protected String doInBackground(String... params) { Log.d("MyTag", "doInBackground, URL = " + url); HttpClient httpClient = new HttpClientFactory().getNewHttpClient(); HttpGet httpGet = new HttpGet(url); httpGet.setHeader("Content-type", "application/json"); InputStream inputStream = null; String result = null; try { HttpResponse response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity(); inputStream = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader( inputStream, "UTF-8"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } result = sb.toString(); } catch (Exception e) { Log.e("MyTag", e.getMessage()); } finally { try { if (inputStream != null) inputStream.close(); } catch (Exception squish) { Log.e("MyTag", squish.getMessage()); } } Log.d("MyTag", "Result:" + result); parse(result); return result; } public void executeTask() { this.execute(); } public abstract void parse(String result); }
1,917
0.685968
0.684924
73
24.260275
20.022608
76
false
false
0
0
0
0
0
0
2.041096
false
false
14
a8f954599869db8e6af8394c1ce096257298a324
35,742,717,850,335
5713df5803cafde4362b233149bc3e6c7ed7638e
/src/com/ennew/usualinterface/MyDialogFragmentInterface.java
c6437cf9be07d31a3af27b7bb3fd8fbb6aa254bb
[]
no_license
GeekGodfather/EnNew
https://github.com/GeekGodfather/EnNew
baeb3aa011b75d6b07249c23f6ecf7afa89878b1
df140a0d914906a67458747b178c3c04f00be805
refs/heads/master
2016-08-12T22:27:05.861000
2016-01-15T03:19:11
2016-01-15T03:19:11
49,693,489
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ennew.usualinterface; /** * * @author lilong * */ public interface MyDialogFragmentInterface { public void onDialogDone(); public void onDialogUndone(); }
UTF-8
Java
181
java
MyDialogFragmentInterface.java
Java
[ { "context": "kage com.ennew.usualinterface;\n\n/**\n * \n * @author lilong\n *\n */\n\npublic interface MyDialogFragmentInterfac", "end": 60, "score": 0.9988453388214111, "start": 54, "tag": "USERNAME", "value": "lilong" } ]
null
[]
package com.ennew.usualinterface; /** * * @author lilong * */ public interface MyDialogFragmentInterface { public void onDialogDone(); public void onDialogUndone(); }
181
0.701657
0.701657
14
11.928572
15.016487
44
false
false
0
0
0
0
0
0
0.428571
false
false
14
690d0fb98d74c186819ed509371470a416fca2dd
35,742,717,849,114
7d7c178ea0b0bcb80f368446e58ae303f1b37e4d
/melody.api/src/main/java/com/wat/melody/api/ITaskContext.java
b794615002859c29ae6a7b55e4d5c27f9f7b19d2
[]
no_license
wat-org/melody
https://github.com/wat-org/melody
0818480ccc8a5a3a50069105a4b8fcd31bf07313
e313c433365494b580b97f2b525781a8aee2c484
refs/heads/master
2021-01-23T08:14:58.067000
2015-12-11T16:29:20
2015-12-11T16:29:20
16,883,338
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.wat.melody.api; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.util.Date; import java.util.Set; import org.w3c.dom.Element; import com.wat.melody.api.event.TaskCreatedEvent; import com.wat.melody.api.event.TaskFinishedEvent; import com.wat.melody.api.event.TaskStartedEvent; import com.wat.melody.api.exception.TaskException; import com.wat.melody.api.report.ITaskReport; import com.wat.melody.api.report.ITaskReportItem; import com.wat.melody.api.report.TaskReportItemType; import com.wat.melody.common.files.exception.IllegalFileException; import com.wat.melody.common.order.OrderNameSet; import com.wat.melody.common.properties.PropertySet; import com.wat.melody.common.xpath.exception.ExpressionSyntaxException; /** * <p> * Contains contextual method and datas an {@link ITask} will need during its * processing. * </p> * * @author Guillaume Cornet * */ public interface ITaskContext { /** * @return the {@link IProcessorManager} associated to this {@link ITask}. * */ public IProcessorManager getProcessorManager(); /** * @return the {@link PropertySet} associated to this {@link ITask}. * */ public PropertySet getProperties(); /** * @return the {@link Element} associated to this {@link ITask}. * */ public Element getRelatedElement(); /** * <p> * Handle {@link IProcessorManager}'s state updates. * </p> * * <p> * <ul> * <li>If the {@link IProcessorManager} is either running or stopped, this * call will return immediately ;</li> * <li>If the {@link IProcessorManager} is paused, this call will be blocked * until the processing is either resumed or stopped ;</li> * </ul> * </p> * * @throws InterruptedException * if the {@link IProcessorManager} is stopping. Means that the * current thread must cleanly stop processing as soon as * possible. */ public void handleProcessorStateUpdates() throws InterruptedException; /** * <p> * Should be call by any task to report what was done. * </p> * * @param report */ public void reportActivity(ITaskReport report); public ITaskReport createTaskReport(Set<ITaskReportItem> reportItems); public ITaskReportItem createTaskReportItem(Date date, TaskReportItemType taskReportType, String message); /** * <p> * Expand the given input String and return the expanded String. * </p> * * @param sToExpand * is the String to expand. * * @return a <code>String</code>, which represents the expanded String. * * @throws ExpressionSyntaxException * if an expression cannot be expanded because it is not a valid * expression (ex: circular ref, invalid character, ...). */ public String expand(String sToExpand) throws ExpressionSyntaxException; /** * <p> * Expand the content of the {@link File} points by the given {@link Path} * and return the expanded String. * </p> * * @param fileToExpand * is the {@link Path} of the {@link File} to expand. * * @return a <code>String</code>, which represents the expanded String. * * @throws ExpressionSyntaxException * if an expression cannot be expanded because it is not a valid * expression (ex: circular ref, invalid character, ...). * @throws IllegalFileException * if the given {@link Path} doesn't point to a valid * {@link File}. * @throws IOException * if an IO error occurred while reading the {@link File} which * is pointed by the given input {@link Path}. * @throws IllegalArgumentException * if fileToExpand is <code>null</code>. */ public String expand(Path fileToExpand) throws ExpressionSyntaxException, IllegalFileException, IOException; /** * <p> * Expand the content of the template file into the destination file. * </p> * * @param template * is the {@link Path} of the {@link File} to expand. * @param destination * is the {@link Path} of the {@link File} where the expansion * result will be stored. Can be <tt>null</tt>. If <tt>null</tt>, * {@link Path} of the resulting {@link File} will be * automatically computed by this method. * * @return the {@link Path} of the resulting expanded {@link File}. * * @throws ExpressionSyntaxException * if an expression cannot be expanded because it is not a valid * expression (ex: circular ref, invalid character, ...). * @throws IllegalFileException * if any of the given {@link Path} doesn't point to a valid * {@link File}. * @throws IOException * if an IO error occurred while reading/writing {@link File}s * which are pointed by the given {@link Path}s. * @throws IllegalArgumentException * if fileToExpand is <code>null</code>. */ public Path expand(Path template, Path destination) throws ExpressionSyntaxException, IllegalFileException, IOException; /** * <p> * Create an {@link ITask} object based on the given {@link Element} and * processes it. * </p> * <p> * <i> * Generate an event {@link TaskCreatedEvent} as soon as the task is * created ; <BR/> * * Generate a {@link TaskStartedEvent} just before the task's processing * starts ; <BR/> * * Generate a {@link TaskFinishedEvent} just after the task's processing * ends ; <BR/> * </i> * </p> * * @param n * is a Task (in its native {@link Element} format) to create and * process. * * @throws TaskException * if an error occurred while creating the {@link ITask} (e.g. * expansion failure, mandatory attribute not provided, * attribute value rejected, ..) while creating or processing * the {@link ITask}. * @throws InterruptedException * if the {@link ITask}'s processing have been interrupted. * Means the caller must cleanly stop processing as soon as * possible. */ public void processTask(Element n) throws TaskException, InterruptedException; /** * <p> * Create an {@link ITask} object based on the given {@link Element} and * processes it. * </p> * <p> * <i> * Generate an event {@link TaskCreatedEvent} as soon as the task is * created ; <BR/> * * Generate a {@link TaskStartedEvent} just before the task's processing * starts ; <BR/> * * Generate a {@link TaskFinishedEvent} just after the task's processing * ends ; <BR/> * </i> * </p> * * @param n * is a Task (in its native {@link Element} format) to create and * process. * @param ps * is a specific set of variables which will be used during * variable's expansion. * * @throws TaskException * if an error occurred while creating the {@link ITask} (e.g. * expansion failure, mandatory attribute not provided, * attribute value rejected, ..) while creating or processing * the {@link ITask}. * @throws InterruptedException * if the {@link ITask}'s processing have been interrupted. * Means the caller must cleanly stop processing as soon as * possible. */ public void processTask(Element n, PropertySet ps) throws TaskException, InterruptedException; /** * <p> * Duplicate the {@link IProcessorManager} associate to this object into a * new sub-{@link IProcessorManager}, which have the capacity to process * specific {@link OrderNameSet} in its own {@link ISequenceDescriptor}. * </p> * * @return the duplicated {@link IProcessorManager}. */ public IProcessorManager createSubProcessorManager(); }
UTF-8
Java
8,105
java
ITaskContext.java
Java
[ { "context": "ring its\r\n * processing.\r\n * </p>\r\n * \r\n * @author Guillaume Cornet\r\n * \r\n */\r\npublic interface ITaskContext {\r\n\r\n\t/*", "end": 944, "score": 0.9996672868728638, "start": 928, "tag": "NAME", "value": "Guillaume Cornet" } ]
null
[]
package com.wat.melody.api; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.util.Date; import java.util.Set; import org.w3c.dom.Element; import com.wat.melody.api.event.TaskCreatedEvent; import com.wat.melody.api.event.TaskFinishedEvent; import com.wat.melody.api.event.TaskStartedEvent; import com.wat.melody.api.exception.TaskException; import com.wat.melody.api.report.ITaskReport; import com.wat.melody.api.report.ITaskReportItem; import com.wat.melody.api.report.TaskReportItemType; import com.wat.melody.common.files.exception.IllegalFileException; import com.wat.melody.common.order.OrderNameSet; import com.wat.melody.common.properties.PropertySet; import com.wat.melody.common.xpath.exception.ExpressionSyntaxException; /** * <p> * Contains contextual method and datas an {@link ITask} will need during its * processing. * </p> * * @author <NAME> * */ public interface ITaskContext { /** * @return the {@link IProcessorManager} associated to this {@link ITask}. * */ public IProcessorManager getProcessorManager(); /** * @return the {@link PropertySet} associated to this {@link ITask}. * */ public PropertySet getProperties(); /** * @return the {@link Element} associated to this {@link ITask}. * */ public Element getRelatedElement(); /** * <p> * Handle {@link IProcessorManager}'s state updates. * </p> * * <p> * <ul> * <li>If the {@link IProcessorManager} is either running or stopped, this * call will return immediately ;</li> * <li>If the {@link IProcessorManager} is paused, this call will be blocked * until the processing is either resumed or stopped ;</li> * </ul> * </p> * * @throws InterruptedException * if the {@link IProcessorManager} is stopping. Means that the * current thread must cleanly stop processing as soon as * possible. */ public void handleProcessorStateUpdates() throws InterruptedException; /** * <p> * Should be call by any task to report what was done. * </p> * * @param report */ public void reportActivity(ITaskReport report); public ITaskReport createTaskReport(Set<ITaskReportItem> reportItems); public ITaskReportItem createTaskReportItem(Date date, TaskReportItemType taskReportType, String message); /** * <p> * Expand the given input String and return the expanded String. * </p> * * @param sToExpand * is the String to expand. * * @return a <code>String</code>, which represents the expanded String. * * @throws ExpressionSyntaxException * if an expression cannot be expanded because it is not a valid * expression (ex: circular ref, invalid character, ...). */ public String expand(String sToExpand) throws ExpressionSyntaxException; /** * <p> * Expand the content of the {@link File} points by the given {@link Path} * and return the expanded String. * </p> * * @param fileToExpand * is the {@link Path} of the {@link File} to expand. * * @return a <code>String</code>, which represents the expanded String. * * @throws ExpressionSyntaxException * if an expression cannot be expanded because it is not a valid * expression (ex: circular ref, invalid character, ...). * @throws IllegalFileException * if the given {@link Path} doesn't point to a valid * {@link File}. * @throws IOException * if an IO error occurred while reading the {@link File} which * is pointed by the given input {@link Path}. * @throws IllegalArgumentException * if fileToExpand is <code>null</code>. */ public String expand(Path fileToExpand) throws ExpressionSyntaxException, IllegalFileException, IOException; /** * <p> * Expand the content of the template file into the destination file. * </p> * * @param template * is the {@link Path} of the {@link File} to expand. * @param destination * is the {@link Path} of the {@link File} where the expansion * result will be stored. Can be <tt>null</tt>. If <tt>null</tt>, * {@link Path} of the resulting {@link File} will be * automatically computed by this method. * * @return the {@link Path} of the resulting expanded {@link File}. * * @throws ExpressionSyntaxException * if an expression cannot be expanded because it is not a valid * expression (ex: circular ref, invalid character, ...). * @throws IllegalFileException * if any of the given {@link Path} doesn't point to a valid * {@link File}. * @throws IOException * if an IO error occurred while reading/writing {@link File}s * which are pointed by the given {@link Path}s. * @throws IllegalArgumentException * if fileToExpand is <code>null</code>. */ public Path expand(Path template, Path destination) throws ExpressionSyntaxException, IllegalFileException, IOException; /** * <p> * Create an {@link ITask} object based on the given {@link Element} and * processes it. * </p> * <p> * <i> * Generate an event {@link TaskCreatedEvent} as soon as the task is * created ; <BR/> * * Generate a {@link TaskStartedEvent} just before the task's processing * starts ; <BR/> * * Generate a {@link TaskFinishedEvent} just after the task's processing * ends ; <BR/> * </i> * </p> * * @param n * is a Task (in its native {@link Element} format) to create and * process. * * @throws TaskException * if an error occurred while creating the {@link ITask} (e.g. * expansion failure, mandatory attribute not provided, * attribute value rejected, ..) while creating or processing * the {@link ITask}. * @throws InterruptedException * if the {@link ITask}'s processing have been interrupted. * Means the caller must cleanly stop processing as soon as * possible. */ public void processTask(Element n) throws TaskException, InterruptedException; /** * <p> * Create an {@link ITask} object based on the given {@link Element} and * processes it. * </p> * <p> * <i> * Generate an event {@link TaskCreatedEvent} as soon as the task is * created ; <BR/> * * Generate a {@link TaskStartedEvent} just before the task's processing * starts ; <BR/> * * Generate a {@link TaskFinishedEvent} just after the task's processing * ends ; <BR/> * </i> * </p> * * @param n * is a Task (in its native {@link Element} format) to create and * process. * @param ps * is a specific set of variables which will be used during * variable's expansion. * * @throws TaskException * if an error occurred while creating the {@link ITask} (e.g. * expansion failure, mandatory attribute not provided, * attribute value rejected, ..) while creating or processing * the {@link ITask}. * @throws InterruptedException * if the {@link ITask}'s processing have been interrupted. * Means the caller must cleanly stop processing as soon as * possible. */ public void processTask(Element n, PropertySet ps) throws TaskException, InterruptedException; /** * <p> * Duplicate the {@link IProcessorManager} associate to this object into a * new sub-{@link IProcessorManager}, which have the capacity to process * specific {@link OrderNameSet} in its own {@link ISequenceDescriptor}. * </p> * * @return the duplicated {@link IProcessorManager}. */ public IProcessorManager createSubProcessorManager(); }
8,095
0.630352
0.630228
237
32.206753
28.245821
77
false
false
0
0
0
0
0
0
1.126582
false
false
14
2a8d4545bbf6bf76aab6fe7463dbbb2f919f2498
26,268,020,046,574
246db7e4c4c90b80897ebc881307e5a11223739e
/java/codechallenge/src/main/java/codechallenge/impl/Engine.java
0e7b7e20f7117393e97fb56ac34b5aaf35aa2a01
[]
no_license
jonthom1/code-challenge
https://github.com/jonthom1/code-challenge
156eac34db2cac2af02a2f34a3e1ad32824f7d8c
36ac93ac6e82aba9230c44bda1d6d38a1f0bd5da
refs/heads/master
2021-05-27T02:29:09.724000
2020-04-18T00:38:03
2020-04-18T00:38:03
254,205,639
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package codechallenge.impl; import java.util.ArrayList; import java.util.List; import java.util.Map; import codechallenge.interfaces.CmdHndlInterface; public class Engine { private CmdParse cmdp; private Map<Integer, CmdHndlInterface> hndl_map; public Engine(CmdParse cmdp, Map<Integer, CmdHndlInterface> hndl_map) { super(); this.cmdp = cmdp; this.hndl_map = hndl_map; } public List<String> process(final String input) { //Transform input command to command ID Command command = cmdp.parse(input); List<String> ret = new ArrayList<>(); //Find command handle by ID and execute CmdHndlInterface hndl = hndl_map.getOrDefault(command.getCmd(), null); if(hndl != null) { ret = hndl.handle(command); } return ret; } }
UTF-8
Java
759
java
Engine.java
Java
[]
null
[]
package codechallenge.impl; import java.util.ArrayList; import java.util.List; import java.util.Map; import codechallenge.interfaces.CmdHndlInterface; public class Engine { private CmdParse cmdp; private Map<Integer, CmdHndlInterface> hndl_map; public Engine(CmdParse cmdp, Map<Integer, CmdHndlInterface> hndl_map) { super(); this.cmdp = cmdp; this.hndl_map = hndl_map; } public List<String> process(final String input) { //Transform input command to command ID Command command = cmdp.parse(input); List<String> ret = new ArrayList<>(); //Find command handle by ID and execute CmdHndlInterface hndl = hndl_map.getOrDefault(command.getCmd(), null); if(hndl != null) { ret = hndl.handle(command); } return ret; } }
759
0.71805
0.71805
33
22
21.50687
72
false
false
0
0
0
0
0
0
1.666667
false
false
14
f30d5120508cba8988a2f02921e598568dd597db
36,782,099,924,159
9a52fe3bcdd090a396e59c68c63130f32c54a7a8
/sources/com/google/android/gms/internal/ads/zzbew.java
6e7fcfc00fb2586e556e91bcf78e8aeffd901ec8
[]
no_license
mzkh/LudoKing
https://github.com/mzkh/LudoKing
19d7c76a298ee5bd1454736063bc392e103a8203
ee0d0e75ed9fa8894ed9877576d8e5589813b1ba
refs/heads/master
2022-04-25T06:08:41.916000
2020-04-14T17:00:45
2020-04-14T17:00:45
255,670,636
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.google.android.gms.internal.ads; import androidx.annotation.Nullable; /* compiled from: com.google.android.gms:play-services-ads@@18.2.0 */ public final class zzbew implements zzdwb<zzaph> { private static final zzbew zzejz = new zzbew(); @Nullable public final /* synthetic */ Object get() { return null; } public static zzbew zzabt() { return zzejz; } }
UTF-8
Java
412
java
zzbew.java
Java
[]
null
[]
package com.google.android.gms.internal.ads; import androidx.annotation.Nullable; /* compiled from: com.google.android.gms:play-services-ads@@18.2.0 */ public final class zzbew implements zzdwb<zzaph> { private static final zzbew zzejz = new zzbew(); @Nullable public final /* synthetic */ Object get() { return null; } public static zzbew zzabt() { return zzejz; } }
412
0.669903
0.660194
17
23.235294
22.062822
69
false
false
0
0
0
0
0
0
0.294118
false
false
14
4d6e9e134be7fd3e4210bf7c23eff03cf2f6a063
4,698,694,250,145
13eb26ce9fb149e0fc60ed41e6cd306659ad126f
/api/src/main/java/io/strimzi/api/kafka/model/template/DeploymentStrategy.java
2dd448b0c915e5709d229e44dbb278912983584e
[ "Apache-2.0" ]
permissive
strimzi/strimzi-kafka-operator
https://github.com/strimzi/strimzi-kafka-operator
0cbd68783c951acb5a7fccff9a6d0652839ba7fe
789cb87b0c57f090096510e132156e07ff25e93b
refs/heads/main
2023-08-29T03:51:53.894000
2023-08-28T15:30:59
2023-08-28T15:30:59
58,194,180
3,980
1,279
Apache-2.0
false
2023-09-14T20:18:32
2016-05-06T08:52:33
2023-09-14T16:42:09
2023-09-14T20:18:31
65,912
4,024
1,152
137
Java
false
false
/* * Copyright Strimzi authors. * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). */ package io.strimzi.api.kafka.model.template; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import java.util.Locale; public enum DeploymentStrategy { ROLLING_UPDATE, RECREATE; @JsonCreator public static DeploymentStrategy forValue(String value) { switch (value.toLowerCase(Locale.ENGLISH)) { case "rollingupdate": return ROLLING_UPDATE; case "recreate": return RECREATE; default: return null; } } @JsonValue public String toValue() { switch (this) { case RECREATE: return "Recreate"; case ROLLING_UPDATE: return "RollingUpdate"; default: return null; } } }
UTF-8
Java
990
java
DeploymentStrategy.java
Java
[]
null
[]
/* * Copyright Strimzi authors. * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). */ package io.strimzi.api.kafka.model.template; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import java.util.Locale; public enum DeploymentStrategy { ROLLING_UPDATE, RECREATE; @JsonCreator public static DeploymentStrategy forValue(String value) { switch (value.toLowerCase(Locale.ENGLISH)) { case "rollingupdate": return ROLLING_UPDATE; case "recreate": return RECREATE; default: return null; } } @JsonValue public String toValue() { switch (this) { case RECREATE: return "Recreate"; case ROLLING_UPDATE: return "RollingUpdate"; default: return null; } } }
990
0.590909
0.586869
39
24.384615
20.681486
101
false
false
0
0
0
0
0
0
0.307692
false
false
14
666e237e2edd3e3c236bd83dbc644fc2da3cf3ce
20,031,727,533,959
d9b2fa46337b2f274059d0141db5de25a6e1285d
/src/main/java/ru/simsonic/rscPermissions/API/RowPermission.java
72e6eb00a9a4eb1dc97ca04e8b42ce32b04a1693
[]
no_license
Evaryan-MMO/rscPermissions
https://github.com/Evaryan-MMO/rscPermissions
955cbee3283ae7780ddcf6a0a488b020c8eb98d6
0b71af1737c7788eabe3f77e16e5864e0fd8113c
refs/heads/master
2021-06-13T15:34:59.954000
2017-03-03T05:49:52
2017-03-03T05:49:52
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.simsonic.rscPermissions.API; public final class RowPermission extends ConditionalRow implements Cloneable, Comparable<RowPermission> { public String permission; public boolean value; public transient RowEntity entityObject; @Override public RowPermission clone() throws CloneNotSupportedException { return (RowPermission)super.clone(); } @Override public int compareTo(RowPermission other) { final int compareByPermission = permission.toLowerCase().compareTo(other.permission.toLowerCase()); if(compareByPermission != 0) return compareByPermission; if(splittedId != null && other.splittedId != null) { final int compareBySplittedId = splittedId.compareTo(other.splittedId); if(compareBySplittedId != 0) return compareBySplittedId; } return Long.compare(id, other.id); } }
UTF-8
Java
854
java
RowPermission.java
Java
[]
null
[]
package ru.simsonic.rscPermissions.API; public final class RowPermission extends ConditionalRow implements Cloneable, Comparable<RowPermission> { public String permission; public boolean value; public transient RowEntity entityObject; @Override public RowPermission clone() throws CloneNotSupportedException { return (RowPermission)super.clone(); } @Override public int compareTo(RowPermission other) { final int compareByPermission = permission.toLowerCase().compareTo(other.permission.toLowerCase()); if(compareByPermission != 0) return compareByPermission; if(splittedId != null && other.splittedId != null) { final int compareBySplittedId = splittedId.compareTo(other.splittedId); if(compareBySplittedId != 0) return compareBySplittedId; } return Long.compare(id, other.id); } }
854
0.747073
0.744731
27
30.629629
28.876682
103
false
false
0
0
0
0
0
0
1.851852
false
false
14
791ee5eaa442454ec0fae4767af4aa5e4aa2f7f8
17,222,818,896,275
7f12ef982449c40b0039dd6e44e15eae92ad96f6
/MultiDimensionalSearch/axg137230_InputOperations.java
030030c1d6e49634b7635e5b9f6d6a20bb38f529
[]
no_license
abhishek182/DataStructuresAndAlgo
https://github.com/abhishek182/DataStructuresAndAlgo
75e5753a5bb23097fd40f94008396aa87c69eb70
393a9dc355f133eb0a1cf05bfee2d4606ceae547
refs/heads/master
2020-05-03T02:53:20.086000
2014-12-21T00:16:44
2014-12-21T00:16:44
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * This class implement methods to process operations provided by the client. * * @author Abhishek Gupta (axg137230) and Manuj Singh (mxs135630) * */ public class axg137230_InputOperations { /** * This variable holds the data structure storing the item information. */ private axg137230_ParallelDataStructure pds = new axg137230_ParallelDataStructure(); /** * This variable holds the sum of output of the all the operations */ private double output = 0.0; /** * This method accepts the operation string and decides what to do with it. * * @param operation */ public void processOperation(String operation) { String[] parts = operation.split(" "); if (parts[0].equalsIgnoreCase("Insert")) { long id = Long.parseLong(parts[1]); double price = (double) Double.parseDouble(parts[2]); // Remove the command, price and last 0 from the operation. int namesLength = parts.length - 4; long[] names = new long[namesLength]; if (namesLength != 0) { for (int i = 3, j = 0; i < parts.length - 1; i++, j++) { names[j] = Long.parseLong(parts[i]); } } double temp = (double) pds.insert(id, names, price); // System.out.println("Insert: " + temp); output = (double) output + (double) temp; } else if (parts[0].equalsIgnoreCase("Find")) { long id = Long.parseLong(parts[1]); double temp = (double) pds.find(id); // System.out.println("Find: " + temp); output = (double) output + (double) temp; } else if (parts[0].equalsIgnoreCase("Delete")) { long id = Long.parseLong(parts[1]); double temp = (double) pds.delete(id); // System.out.println("Delete: " + temp); output = (double) output + (double) temp; } else if (parts[0].equalsIgnoreCase("PriceHike")) { long lowId = Long.parseLong(parts[1]); long highId = Long.parseLong(parts[2]); int rate = Integer.parseInt(parts[3]); double temp = (double) pds.priceHike(lowId, highId, rate); // System.out.println("PriceHike: " + temp); output = (double) output + (double) temp; } else if (parts[0].equalsIgnoreCase("FindMaxPrice")) { long name = Long.parseLong(parts[1]); double temp = (double) pds.findMaxPrice(name); // System.out.println("FindMaxPrice: " + temp); output = (double) output + (double) temp; } else if (parts[0].equalsIgnoreCase("FindMinPrice")) { long name = Long.parseLong(parts[1]); double temp = (double) pds.findMinPrice(name); // System.out.println("FindMinPrice: " + temp); output = (double) output + (double) temp; } else if (parts[0].equalsIgnoreCase("FindPriceRange")) { long name = Long.parseLong(parts[1]); double lowPrice = (double) Double.parseDouble(parts[2]); double highPrice = (double) Double.parseDouble(parts[3]); double temp = (double) pds .findPriceRange(name, lowPrice, highPrice); // System.out.println("FindPriceRange: " + temp); output = (double) output + (double) temp; } } /** * This method returns the output. * * @return double */ public double getOutput() { return (double) output; } }
UTF-8
Java
3,060
java
axg137230_InputOperations.java
Java
[ { "context": " operations provided by the client.\n * \n * @author Abhishek Gupta (axg137230) and Manuj Singh (mxs135630)\n *\n */\n\np", "end": 111, "score": 0.9998787045478821, "start": 97, "tag": "NAME", "value": "Abhishek Gupta" }, { "context": "ent.\n * \n * @author Abhishek Gup...
null
[]
/** * This class implement methods to process operations provided by the client. * * @author <NAME> (axg137230) and <NAME> (mxs135630) * */ public class axg137230_InputOperations { /** * This variable holds the data structure storing the item information. */ private axg137230_ParallelDataStructure pds = new axg137230_ParallelDataStructure(); /** * This variable holds the sum of output of the all the operations */ private double output = 0.0; /** * This method accepts the operation string and decides what to do with it. * * @param operation */ public void processOperation(String operation) { String[] parts = operation.split(" "); if (parts[0].equalsIgnoreCase("Insert")) { long id = Long.parseLong(parts[1]); double price = (double) Double.parseDouble(parts[2]); // Remove the command, price and last 0 from the operation. int namesLength = parts.length - 4; long[] names = new long[namesLength]; if (namesLength != 0) { for (int i = 3, j = 0; i < parts.length - 1; i++, j++) { names[j] = Long.parseLong(parts[i]); } } double temp = (double) pds.insert(id, names, price); // System.out.println("Insert: " + temp); output = (double) output + (double) temp; } else if (parts[0].equalsIgnoreCase("Find")) { long id = Long.parseLong(parts[1]); double temp = (double) pds.find(id); // System.out.println("Find: " + temp); output = (double) output + (double) temp; } else if (parts[0].equalsIgnoreCase("Delete")) { long id = Long.parseLong(parts[1]); double temp = (double) pds.delete(id); // System.out.println("Delete: " + temp); output = (double) output + (double) temp; } else if (parts[0].equalsIgnoreCase("PriceHike")) { long lowId = Long.parseLong(parts[1]); long highId = Long.parseLong(parts[2]); int rate = Integer.parseInt(parts[3]); double temp = (double) pds.priceHike(lowId, highId, rate); // System.out.println("PriceHike: " + temp); output = (double) output + (double) temp; } else if (parts[0].equalsIgnoreCase("FindMaxPrice")) { long name = Long.parseLong(parts[1]); double temp = (double) pds.findMaxPrice(name); // System.out.println("FindMaxPrice: " + temp); output = (double) output + (double) temp; } else if (parts[0].equalsIgnoreCase("FindMinPrice")) { long name = Long.parseLong(parts[1]); double temp = (double) pds.findMinPrice(name); // System.out.println("FindMinPrice: " + temp); output = (double) output + (double) temp; } else if (parts[0].equalsIgnoreCase("FindPriceRange")) { long name = Long.parseLong(parts[1]); double lowPrice = (double) Double.parseDouble(parts[2]); double highPrice = (double) Double.parseDouble(parts[3]); double temp = (double) pds .findPriceRange(name, lowPrice, highPrice); // System.out.println("FindPriceRange: " + temp); output = (double) output + (double) temp; } } /** * This method returns the output. * * @return double */ public double getOutput() { return (double) output; } }
3,047
0.656209
0.637582
87
34.172413
22.851952
85
false
false
0
0
0
0
0
0
2.586207
false
false
14
a25554be4bd7f2fd086cedfee14a035983a9bc2f
16,681,653,008,516
f0b19b551ab79df5cce70f775628862e2663e579
/app/src/main/java/com/aliagushutapea/convertion/dependencyinjection/module_mpv/MainActivityPresenterModule.java
74fdc9d799c0082417afb8b23151c57350add1f5
[]
no_license
aliagus12/Currency
https://github.com/aliagus12/Currency
b961a9d9e3cf691bd1510102e273c8ca6d524916
7bfac7247f26cf5f0a01ceb5ecaab63207b25f67
refs/heads/master
2021-05-05T00:17:28.216000
2018-02-10T13:40:20
2018-02-10T13:40:20
119,476,764
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.aliagushutapea.convertion.dependencyinjection.module_mpv; import com.aliagushutapea.convertion.MainActivityContract; import dagger.Module; import dagger.Provides; /** * Created by ali on 24/01/18. */ @Module public class MainActivityPresenterModule { private MainActivityContract.View view; public MainActivityPresenterModule(MainActivityContract.View view) { this.view = view; } @Provides MainActivityContract.View providesContractView(){ return view; } }
UTF-8
Java
517
java
MainActivityPresenterModule.java
Java
[]
null
[]
package com.aliagushutapea.convertion.dependencyinjection.module_mpv; import com.aliagushutapea.convertion.MainActivityContract; import dagger.Module; import dagger.Provides; /** * Created by ali on 24/01/18. */ @Module public class MainActivityPresenterModule { private MainActivityContract.View view; public MainActivityPresenterModule(MainActivityContract.View view) { this.view = view; } @Provides MainActivityContract.View providesContractView(){ return view; } }
517
0.748549
0.736944
24
20.541666
23.081341
72
false
false
0
0
0
0
0
0
0.291667
false
false
14
ce1f9f54efd18f0a58707ab0cd24435be05e2f74
33,380,485,888,570
79e2c4bbae6774b3b83769b792b0a13851f75b08
/eco-app/src/test/java/easycare/cuke/support/mapping/AliasedMapper.java
544a15597b48f1d738d7b0e35bce0a3beed49625
[]
no_license
mikessun/reports-repo
https://github.com/mikessun/reports-repo
782916378ec3753c7c42db8a85c2313e588d41e0
b2f44c22547ef777402716393debb58039b39b5c
refs/heads/master
2019-01-19T20:11:40.844000
2016-04-15T23:08:32
2016-04-15T23:08:32
56,277,427
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package easycare.cuke.support.mapping; import java.util.List; import java.util.Map; import com.google.common.collect.Lists; import com.google.common.collect.Maps; public abstract class AliasedMapper<T, Accessor> { private Map<String, Accessor> mappers = Maps.newLinkedHashMap(); private Class<? extends T> mappedClass; public AliasedMapper(Class<? extends T> mappedClass) { this.mappedClass = mappedClass; } public void mapValue(String alias, T target, Object value) { try { doMap(alias, target, value); } catch (Exception e) { throw new RuntimeException( "Error using alias '" + alias + "' to set value on " + target.getClass().getSimpleName() + " with value " + value.toString() + ". " + e.getMessage()); } } public abstract void doMap(String alias, T target, Object value) throws Exception; public Accessor get(String alias) { return mappers.get(alias); } public List<String> getAliases() { return Lists.newArrayList(mappers.keySet()); } public void addAliases() { } public void addAlias(Accessor f, String alias) { Accessor existing = mappers.get(alias); if (existing != null && !existing.equals(f)) { throw new RuntimeException("Duplicate alias: " + alias + "; beware of parenthetical terms in aliases!"); } mappers.put(alias, f); } public void addAlias(String key, String... aliases) { Accessor a = get(key); for (String alias : aliases) { mappers.put(alias, a); } } }
UTF-8
Java
1,658
java
AliasedMapper.java
Java
[]
null
[]
package easycare.cuke.support.mapping; import java.util.List; import java.util.Map; import com.google.common.collect.Lists; import com.google.common.collect.Maps; public abstract class AliasedMapper<T, Accessor> { private Map<String, Accessor> mappers = Maps.newLinkedHashMap(); private Class<? extends T> mappedClass; public AliasedMapper(Class<? extends T> mappedClass) { this.mappedClass = mappedClass; } public void mapValue(String alias, T target, Object value) { try { doMap(alias, target, value); } catch (Exception e) { throw new RuntimeException( "Error using alias '" + alias + "' to set value on " + target.getClass().getSimpleName() + " with value " + value.toString() + ". " + e.getMessage()); } } public abstract void doMap(String alias, T target, Object value) throws Exception; public Accessor get(String alias) { return mappers.get(alias); } public List<String> getAliases() { return Lists.newArrayList(mappers.keySet()); } public void addAliases() { } public void addAlias(Accessor f, String alias) { Accessor existing = mappers.get(alias); if (existing != null && !existing.equals(f)) { throw new RuntimeException("Duplicate alias: " + alias + "; beware of parenthetical terms in aliases!"); } mappers.put(alias, f); } public void addAlias(String key, String... aliases) { Accessor a = get(key); for (String alias : aliases) { mappers.put(alias, a); } } }
1,658
0.608565
0.608565
58
27.586206
28.605543
116
false
false
0
0
0
0
0
0
0.534483
false
false
14
a0f5a1c8be26be7df1ab5a14394cd2a6b898d448
33,380,485,887,689
eb04f64fe94529413848f438f2de155ee39b5349
/app/src/main/java/com/example/trending/ParentView.java
f934d041f723eb7d970807ac5f95cb98ca1c0c47
[]
no_license
leslie1992-dqp/Trending
https://github.com/leslie1992-dqp/Trending
d6fa70e628d85e0a919d8aa175b3509f9e98503d
fa806ad9e09909684726be67426a1358eb7a2222
refs/heads/main
2023-05-26T23:38:12.530000
2021-06-05T12:27:56
2021-06-05T12:27:56
374,102,820
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.trending; import java.util.List; public interface ParentView { void success(List<ListBean> listBeans); void error(String error); }
UTF-8
Java
164
java
ParentView.java
Java
[]
null
[]
package com.example.trending; import java.util.List; public interface ParentView { void success(List<ListBean> listBeans); void error(String error); }
164
0.731707
0.731707
11
13.909091
15.75064
43
false
false
0
0
0
0
0
0
0.363636
false
false
14
c060e6a2c7507d9714db21a9c46cf039fafb5097
27,565,100,150,646
2e63398e28a703e8ef08a2e8627f4fcb79fa96f0
/src/ABC049C/Main.java
af083e740af1c0ee1d225863636d3a564b7f45f5
[]
no_license
Yu-s/atcoder-practice-java
https://github.com/Yu-s/atcoder-practice-java
ace0f81138423c72439d62408bc4fd6a21877dd1
0842710addd7bf21aba9b2e136196070895e18c2
refs/heads/main
2023-01-09T22:32:33.994000
2020-11-07T00:48:43
2020-11-07T00:48:43
309,272,527
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ABC049C; import java.util.Scanner; /** * https://atcoder.jp/contests/abs/tasks/arc065_a */ public class Main { private String[] divide = new String[4]; public Main() { divide[0] = new StringBuffer("dream").reverse().toString(); divide[1] = new StringBuffer("dreamer").reverse().toString(); divide[2] = new StringBuffer("erase").reverse().toString(); divide[3] = new StringBuffer("eraser").reverse().toString(); } public boolean isMatchable(String str) { String S = new StringBuffer(str).reverse().toString(); for (int i = 0; i < S.length();) { boolean isDividable = false; for (int j = 0; j < 4; j++) { if (i + divide[j].length() > S.length()) { continue; } String str2 = S.substring(i, i + divide[j].length()); if (str2.equals(divide[j])) { isDividable = true; i += divide[j].length(); } } if (!isDividable) { return false; } } return true; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); Main main = new Main(); if (main.isMatchable(sc.next())) { System.out.println(("YES")); } else { System.out.println(("NO")); } } }
UTF-8
Java
1,442
java
Main.java
Java
[]
null
[]
package ABC049C; import java.util.Scanner; /** * https://atcoder.jp/contests/abs/tasks/arc065_a */ public class Main { private String[] divide = new String[4]; public Main() { divide[0] = new StringBuffer("dream").reverse().toString(); divide[1] = new StringBuffer("dreamer").reverse().toString(); divide[2] = new StringBuffer("erase").reverse().toString(); divide[3] = new StringBuffer("eraser").reverse().toString(); } public boolean isMatchable(String str) { String S = new StringBuffer(str).reverse().toString(); for (int i = 0; i < S.length();) { boolean isDividable = false; for (int j = 0; j < 4; j++) { if (i + divide[j].length() > S.length()) { continue; } String str2 = S.substring(i, i + divide[j].length()); if (str2.equals(divide[j])) { isDividable = true; i += divide[j].length(); } } if (!isDividable) { return false; } } return true; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); Main main = new Main(); if (main.isMatchable(sc.next())) { System.out.println(("YES")); } else { System.out.println(("NO")); } } }
1,442
0.488211
0.477115
50
27.84
21.986687
69
false
false
0
0
0
0
0
0
0.48
false
false
14
0f00e0f914668eb2d983081e09d00a625eb3e131
35,064,113,024,760
7535cc709f35c93ce6109b824f9562baa6da1c37
/springhiberweb/src/com/service/LoginService.java
e37015e128497937fc411bf17df7d89a0dde766a
[]
no_license
Sivaranjitha1402/billing
https://github.com/Sivaranjitha1402/billing
df4cd7df7c663a91bc1bb5e64ca343ab1d6a0394
f1352bbc533377519d4b540ce1d65b90e443aab5
refs/heads/master
2023-02-05T11:29:14.218000
2020-12-31T12:02:22
2020-12-31T12:02:22
325,788,363
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.service; public interface LoginService { public int adminlogin(String username,String password); public int userlogin(String username,String password); public int getUserid(String username,String password); public int checkFlag(String username,String password); public void changeFlag(int userid); }
UTF-8
Java
318
java
LoginService.java
Java
[]
null
[]
package com.service; public interface LoginService { public int adminlogin(String username,String password); public int userlogin(String username,String password); public int getUserid(String username,String password); public int checkFlag(String username,String password); public void changeFlag(int userid); }
318
0.811321
0.811321
9
34.333332
21.756226
56
false
false
0
0
0
0
0
0
1.666667
false
false
14
0f5427933e04e9d75eb4c625a0219195cdbb1d25
22,728,966,960,517
b63d49dd45087307958dbd875baef0b11b7c227c
/src/main/java/rdf_star/StreamRDFStarPG.java
5b1f7ff0ff4806724001310a4f83e4f6a6d01fad
[]
permissive
afs/jena-workspace
https://github.com/afs/jena-workspace
5fad7409852a8de64c2f92ce408eb74a56776b3d
21147336aa7694fa5d75d2ee0d733ddcb06773f2
refs/heads/main
2023-03-15T05:45:20.325000
2023-03-10T10:25:18
2023-03-10T10:25:18
38,121,320
0
0
Apache-2.0
false
2022-06-20T17:34:12
2015-06-26T16:25:27
2021-12-29T16:30:51
2022-06-20T17:33:29
1,284
0
0
0
Java
false
false
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package rdf_star; import org.apache.jena.atlas.lib.CacheFactory; import org.apache.jena.atlas.lib.CacheSet; import org.apache.jena.graph.Node; import org.apache.jena.graph.Triple; import org.apache.jena.riot.system.StreamRDFBase; import org.apache.jena.sparql.core.Quad; /** * Generate the target triple for each RDF-star triple term. */ public class StreamRDFStarPG extends StreamRDFBase { // TODO Remember recently generated to suppress duplicates. private final CacheSet<Triple> cacheTriples; private final CacheSet<Quad> cacheQuads; private static final Node dftGraph = Quad.defaultGraphNodeGenerated; public StreamRDFStarPG(int cacheSize) { this.cacheTriples = CacheFactory.createCacheSet(cacheSize); this.cacheQuads = CacheFactory.createCacheSet(cacheSize); } @Override public void start() { super.start(); } @Override public void finish() { cacheTriples.clear(); cacheQuads.clear(); super.finish(); } @Override public void triple(Triple triple) { if ( triple.getSubject().isNodeTriple() ) gen(null, triple.getSubject().getTriple()); if ( triple.getObject().isNodeTriple() ) gen(null, triple.getObject().getTriple()); super.triple(triple); } private void gen(Node graph, Triple starTriple) { if ( starTriple == null ) return ; //Node g = ( graph == null ) ? dftGraph : graph; // NB: XXX Recurse! if ( graph == null || Quad.isDefaultGraph(graph) ) { if ( ! cacheTriples.contains(starTriple) ) { triple(starTriple); cacheTriples.add(starTriple); } } else { Quad starQuad = Quad.create(graph, starTriple); if ( ! cacheQuads.contains(starQuad) ) { quad(starQuad); cacheQuads.add(starQuad); } } } @Override public void quad(Quad quad) { if ( quad.getSubject().isNodeTriple() ) gen(quad.getGraph(), quad.getSubject().getTriple()); if ( quad.getObject().isNodeTriple() ) gen(quad.getGraph(), quad.getObject().getTriple()); super.quad(quad); } }
UTF-8
Java
3,075
java
StreamRDFStarPG.java
Java
[]
null
[]
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package rdf_star; import org.apache.jena.atlas.lib.CacheFactory; import org.apache.jena.atlas.lib.CacheSet; import org.apache.jena.graph.Node; import org.apache.jena.graph.Triple; import org.apache.jena.riot.system.StreamRDFBase; import org.apache.jena.sparql.core.Quad; /** * Generate the target triple for each RDF-star triple term. */ public class StreamRDFStarPG extends StreamRDFBase { // TODO Remember recently generated to suppress duplicates. private final CacheSet<Triple> cacheTriples; private final CacheSet<Quad> cacheQuads; private static final Node dftGraph = Quad.defaultGraphNodeGenerated; public StreamRDFStarPG(int cacheSize) { this.cacheTriples = CacheFactory.createCacheSet(cacheSize); this.cacheQuads = CacheFactory.createCacheSet(cacheSize); } @Override public void start() { super.start(); } @Override public void finish() { cacheTriples.clear(); cacheQuads.clear(); super.finish(); } @Override public void triple(Triple triple) { if ( triple.getSubject().isNodeTriple() ) gen(null, triple.getSubject().getTriple()); if ( triple.getObject().isNodeTriple() ) gen(null, triple.getObject().getTriple()); super.triple(triple); } private void gen(Node graph, Triple starTriple) { if ( starTriple == null ) return ; //Node g = ( graph == null ) ? dftGraph : graph; // NB: XXX Recurse! if ( graph == null || Quad.isDefaultGraph(graph) ) { if ( ! cacheTriples.contains(starTriple) ) { triple(starTriple); cacheTriples.add(starTriple); } } else { Quad starQuad = Quad.create(graph, starTriple); if ( ! cacheQuads.contains(starQuad) ) { quad(starQuad); cacheQuads.add(starQuad); } } } @Override public void quad(Quad quad) { if ( quad.getSubject().isNodeTriple() ) gen(quad.getGraph(), quad.getSubject().getTriple()); if ( quad.getObject().isNodeTriple() ) gen(quad.getGraph(), quad.getObject().getTriple()); super.quad(quad); } }
3,075
0.64748
0.646179
94
31.712767
24.028185
75
false
false
0
0
0
0
0
0
0.446809
false
false
14
0e41ed86b741bf98c5bf37203825c8d505616e51
19,765,439,557,935
56142dc06b9604a15872e9058b85987cff2b7e3a
/src/java/yourhome.java
d81239a5d5bc8db4c57e421578323cfed03b00e2
[]
no_license
Hari0077/House-Rental-Application-using-java
https://github.com/Hari0077/House-Rental-Application-using-java
265a5b1dd41c2c2a5f705ad291ed3e99220cdb79
66018bfb89bf6f029c44728665ea5cfe2d08c8d1
refs/heads/master
2023-06-25T23:41:24.208000
2021-07-29T08:06:20
2021-07-29T08:06:20
390,648,581
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /* * 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. */ /** * * @author Hari */ @WebServlet("/yourhome") public class yourhome extends HttpServlet{ public void doGet(HttpServletRequest req,HttpServletResponse rsp)throws IOException,ServletException { rsp.setContentType("text/html"); PrintWriter out = rsp.getWriter(); HttpSession session=req.getSession(false); String user = (String)session.getAttribute("email"); out.println("<style>"); out.println(".Nav {"); out.println("top:0;"); out.println("left:0;"); out.println("width:230px;"); out.println("background-color: lightblue;"); out.println("position:fixed;"); out.println("height:100%;"); out.println("font-size:25px;"); out.println("padding:20px;"); out.println("margin-bottom:4px;"); out.println("}"); out.println(".tablebook th, .tablebook td{"); out.println("padding-top:12px"); out.println("padding-bottom:12px"); out.println("text-align:left;"); out.println("background-color:rgba(0, 128, 0, 0.3);"); out.println("color:black;"); out.println("border: 1px solid #ddd;"); out.println(" padding: 8px;"); out.println("}"); out.println(".tablebook {"); out.println("margin-top:30px;"); out.println("}"); out.println(".tablebook input[type=submit] {"); out.println("cursor:pointer;"); out.println("}"); out.println(".yourhome {"); out.println("margin-left:300px;"); out.println("}"); out.println("a{"); out.println("text-decoration:none;"); out.println("}"); out.println("a:hover{"); out.println("text-decoration:underline;"); out.println("}"); out.println(".yourhome table{"); out.println("margin-left:150px"); out.println("}"); out.println(".yourhome td{"); out.println("padding-top:12px"); out.println("padding-bottom:12px"); out.println("text-align:left;"); out.println("background-color:rgba(0, 128, 0, 0.3);"); out.println("color:black;"); out.println("border: 1px solid #ddd;"); out.println(" padding: 8px;"); out.println("}"); out.println("</style>"); out.println("<div class='Nav'>"); out.println("Welcome"); out.println("<br>"); out.println("<br>"); out.println("<br>"); out.println(user); out.println("<br>"); out.println("<br>"); out.println("<a href='home.jsp'>Home</a>"); out.println("<br>"); out.println("<br>"); out.println("<a href='yourhome'>your Home</a>"); out.println("<br>"); out.println("<br>"); out.println("<a href='Logout'>Logout</a>"); out.println("</div>"); try { Class.forName("com.mysql.jdbc.Driver"); Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/rentalapp","root",""); String sql = "SELECT * FROM bookedhomes where youremail=?"; PreparedStatement statement = connection.prepareStatement(sql); statement.setString(1, user); ResultSet result = statement.executeQuery(); while(result.next()) { out.println("<div class='yourhome'>"); out.println("<table border='2'>"); out.println("<tr>"); out.println("<td>your Name</td>"); out.println("<td>"+ result.getString("yourname")+"</td>"); out.println("</tr>"); out.println("<tr>"); out.println("<td>your Email</td>"); out.println("<td>"+ result.getString("youremail")+"</td>"); out.println("</tr>"); out.println("<tr>"); out.println("<td>Owner Name</td>"); out.println("<td>"+ result.getString("ownername")+"</td>"); out.println("</tr>"); out.println("<tr>"); out.println("<td>Owner phonenumber</td>"); out.println("<td>"+ result.getString("phoneno")+"</td>"); out.println("</tr>"); out.println("<tr>"); out.println("<td>Villaname</td>"); out.println("<td>"+ result.getString("villaname")+"</td>"); out.println("</tr>"); out.println("<tr>"); out.println("<td>Address</td>"); out.println("<td>"+ result.getString("Address")+"</td>"); out.println("</tr>"); out.println("<tr>"); out.println("<td>Homespecification</td>"); out.println("<td>"+ result.getString("homespec")+"</td>"); out.println("</tr>"); out.println("<tr>"); out.println("<td>Rent Per Month</td>"); out.println("<td>"+ result.getString("rpm")+"</td>"); out.println("</tr>"); out.println("<tr>"); out.println("<td>Total amount paid</td>"); out.println("<td>"+ result.getString("total")+"</td>"); out.println("</tr>"); out.println("</table>"); out.println("</div>"); } } catch (ClassNotFoundException ex) { Logger.getLogger(yourhome.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(yourhome.class.getName()).log(Level.SEVERE, null, ex); } } }
UTF-8
Java
7,020
java
yourhome.java
Java
[ { "context": "the template in the editor.\n */\n\n/**\n *\n * @author Hari\n */\n@WebServlet(\"/yourhome\")\npublic class yourhom", "end": 736, "score": 0.9995697140693665, "start": 732, "tag": "NAME", "value": "Hari" } ]
null
[]
import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /* * 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. */ /** * * @author Hari */ @WebServlet("/yourhome") public class yourhome extends HttpServlet{ public void doGet(HttpServletRequest req,HttpServletResponse rsp)throws IOException,ServletException { rsp.setContentType("text/html"); PrintWriter out = rsp.getWriter(); HttpSession session=req.getSession(false); String user = (String)session.getAttribute("email"); out.println("<style>"); out.println(".Nav {"); out.println("top:0;"); out.println("left:0;"); out.println("width:230px;"); out.println("background-color: lightblue;"); out.println("position:fixed;"); out.println("height:100%;"); out.println("font-size:25px;"); out.println("padding:20px;"); out.println("margin-bottom:4px;"); out.println("}"); out.println(".tablebook th, .tablebook td{"); out.println("padding-top:12px"); out.println("padding-bottom:12px"); out.println("text-align:left;"); out.println("background-color:rgba(0, 128, 0, 0.3);"); out.println("color:black;"); out.println("border: 1px solid #ddd;"); out.println(" padding: 8px;"); out.println("}"); out.println(".tablebook {"); out.println("margin-top:30px;"); out.println("}"); out.println(".tablebook input[type=submit] {"); out.println("cursor:pointer;"); out.println("}"); out.println(".yourhome {"); out.println("margin-left:300px;"); out.println("}"); out.println("a{"); out.println("text-decoration:none;"); out.println("}"); out.println("a:hover{"); out.println("text-decoration:underline;"); out.println("}"); out.println(".yourhome table{"); out.println("margin-left:150px"); out.println("}"); out.println(".yourhome td{"); out.println("padding-top:12px"); out.println("padding-bottom:12px"); out.println("text-align:left;"); out.println("background-color:rgba(0, 128, 0, 0.3);"); out.println("color:black;"); out.println("border: 1px solid #ddd;"); out.println(" padding: 8px;"); out.println("}"); out.println("</style>"); out.println("<div class='Nav'>"); out.println("Welcome"); out.println("<br>"); out.println("<br>"); out.println("<br>"); out.println(user); out.println("<br>"); out.println("<br>"); out.println("<a href='home.jsp'>Home</a>"); out.println("<br>"); out.println("<br>"); out.println("<a href='yourhome'>your Home</a>"); out.println("<br>"); out.println("<br>"); out.println("<a href='Logout'>Logout</a>"); out.println("</div>"); try { Class.forName("com.mysql.jdbc.Driver"); Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/rentalapp","root",""); String sql = "SELECT * FROM bookedhomes where youremail=?"; PreparedStatement statement = connection.prepareStatement(sql); statement.setString(1, user); ResultSet result = statement.executeQuery(); while(result.next()) { out.println("<div class='yourhome'>"); out.println("<table border='2'>"); out.println("<tr>"); out.println("<td>your Name</td>"); out.println("<td>"+ result.getString("yourname")+"</td>"); out.println("</tr>"); out.println("<tr>"); out.println("<td>your Email</td>"); out.println("<td>"+ result.getString("youremail")+"</td>"); out.println("</tr>"); out.println("<tr>"); out.println("<td>Owner Name</td>"); out.println("<td>"+ result.getString("ownername")+"</td>"); out.println("</tr>"); out.println("<tr>"); out.println("<td>Owner phonenumber</td>"); out.println("<td>"+ result.getString("phoneno")+"</td>"); out.println("</tr>"); out.println("<tr>"); out.println("<td>Villaname</td>"); out.println("<td>"+ result.getString("villaname")+"</td>"); out.println("</tr>"); out.println("<tr>"); out.println("<td>Address</td>"); out.println("<td>"+ result.getString("Address")+"</td>"); out.println("</tr>"); out.println("<tr>"); out.println("<td>Homespecification</td>"); out.println("<td>"+ result.getString("homespec")+"</td>"); out.println("</tr>"); out.println("<tr>"); out.println("<td>Rent Per Month</td>"); out.println("<td>"+ result.getString("rpm")+"</td>"); out.println("</tr>"); out.println("<tr>"); out.println("<td>Total amount paid</td>"); out.println("<td>"+ result.getString("total")+"</td>"); out.println("</tr>"); out.println("</table>"); out.println("</div>"); } } catch (ClassNotFoundException ex) { Logger.getLogger(yourhome.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(yourhome.class.getName()).log(Level.SEVERE, null, ex); } } }
7,020
0.487892
0.480342
166
41.283131
20.424957
115
false
false
0
0
0
0
0
0
1.054217
false
false
14
0f3fc6228e016e03c1f903d63496c95c957845fb
29,334,626,655,845
d0abb09301735c66255684527438ed1ae1384a44
/EmployeeWageComputation/EmployeeWageComputation.java
8b8444967273ed2c6c41097144c58cc8edc08335
[]
no_license
birajit95/EmployeeWageComputationProgram
https://github.com/birajit95/EmployeeWageComputationProgram
36316c1a5cdbd72a3229d7cf8c71b108acfc047e
a82e2dc4c8968b645ad115de77003e66c1b5d2cc
refs/heads/master
2023-01-02T15:06:35.932000
2020-11-02T06:13:26
2020-11-02T06:13:26
307,804,450
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.ArrayList; import java.util.HashMap; import java.util.Random; public class EmployeeWageComputation{ public static void welcomeMessage(){ System.out.println("Welcome to Employee Wage Computation Program"); } public static void main(String[] args){ EmployeeWageComputation.welcomeMessage(); EmployeeWageBuilder empBuilder = new EmployeeWageBuilder(); empBuilder.addCompany("TCS",100,20,160); empBuilder.addCompany("MindTree",150,24,192); empBuilder.addCompany("Bridgelab",200,20,160); empBuilder.calculateEmpWage(); empBuilder.getTotalWage("Bridgelab"); empBuilder.getDailyWage("Bridgelab"); empBuilder.getTotalWage("MindTree"); empBuilder.getDailyWage("MindTree"); } } class CompanyEmpWage{ private final String companyName; private final int wagePerHour; private final int maxNoOfworkingDays; private final int maxNoOfWorkingHours; private int totalWage; private ArrayList<Integer> dailyWage; public CompanyEmpWage(String companyName, int wagePerHour, int maxNoOfworkingDays, int maxNoOfWorkingHours){ this.companyName=companyName; this.wagePerHour=wagePerHour; this.maxNoOfworkingDays=maxNoOfworkingDays; this.maxNoOfWorkingHours=maxNoOfWorkingHours; dailyWage=new ArrayList<>(); } String getCompanyName(){return this.companyName;} int getWagePerHour(){return this.wagePerHour;} int getMaxWorkingHours(){return this.maxNoOfWorkingHours;} int getMaxWorkingDays(){return this.maxNoOfworkingDays;} void setTotalWage(int totalWage){ this.totalWage=totalWage;} void setDailyWage(Integer dailyWage){this.dailyWage.add(dailyWage); } int getTotalWage(){return this.totalWage;} ArrayList getDailyWage(){return this.dailyWage;} } interface IcomputeEmployeWage{ public void addCompany(String companyName, int wagePerHour, int maxNoOfworkingDays, int maxNoOfWorkingHours); public String getAttendance(); public void calculateEmpWage(); public int getWorkingHourPerDay(); public void getTotalWage(String companyName); public void getDailyWage(String companyName); } class EmployeeWageBuilder implements IcomputeEmployeWage{ private static final int FULL_TIME=8; private static final int PART_TIME=4; private static final int MAX_DAYS_IN_MONTH=30; private ArrayList<CompanyEmpWage> companyWageList; private HashMap<String, CompanyEmpWage> totalWageMap; public EmployeeWageBuilder(){ companyWageList = new ArrayList<CompanyEmpWage>(); totalWageMap = new HashMap<>(); } @Override public void addCompany(String companyName, int wagePerHour, int maxNoOfworkingDays, int maxNoOfWorkingHours){ companyWageList.add(new CompanyEmpWage(companyName, wagePerHour, maxNoOfworkingDays, maxNoOfWorkingHours)); } @Override public String getAttendance(){ if(Math.random()*10>=3){ return "present"; } else{ return "absent"; } } public int getWorkingHourPerDay(){ int workingHourPerDay; Random random = new Random(); int status = random.nextInt(2); switch(status){ case 0: workingHourPerDay=FULL_TIME; break; case 1: workingHourPerDay=PART_TIME; break; default: workingHourPerDay=0; break; } return workingHourPerDay; } public int getDailyWage(int perDayWorkHour, int wagePerHour){ int workingHourPerDay=perDayWorkHour; return workingHourPerDay*wagePerHour; } public void calculateEmpWage( ){ for(CompanyEmpWage company : companyWageList) { int totalWorkingHour=0; int totalWorkingDays=0; int totalDays=0; int totalWage=0; int perDayWorkHour=0; int dailyWage=0; while(totalWorkingHour<company.getMaxWorkingHours() && totalWorkingDays<company.getMaxWorkingDays() && totalDays<MAX_DAYS_IN_MONTH){ totalDays++; if(getAttendance().equals("present")){ totalWorkingDays++; perDayWorkHour=getWorkingHourPerDay(); totalWorkingHour=totalWorkingHour+perDayWorkHour; dailyWage=getDailyWage(perDayWorkHour, company.getWagePerHour()); totalWage=totalWage+dailyWage; company.setDailyWage(dailyWage); } } company.setTotalWage(totalWage); totalWageMap.put(company.getCompanyName(), company); } } @Override public void getTotalWage(String companyName){ System.out.println("Total Wage for "+companyName+" is "+totalWageMap.get(companyName).getTotalWage()); } @Override public void getDailyWage(String companyName){ System.out.println("Daily Wage for "+companyName+ ": "); System.out.println(totalWageMap.get(companyName).getDailyWage()); } }
UTF-8
Java
5,147
java
EmployeeWageComputation.java
Java
[]
null
[]
import java.util.ArrayList; import java.util.HashMap; import java.util.Random; public class EmployeeWageComputation{ public static void welcomeMessage(){ System.out.println("Welcome to Employee Wage Computation Program"); } public static void main(String[] args){ EmployeeWageComputation.welcomeMessage(); EmployeeWageBuilder empBuilder = new EmployeeWageBuilder(); empBuilder.addCompany("TCS",100,20,160); empBuilder.addCompany("MindTree",150,24,192); empBuilder.addCompany("Bridgelab",200,20,160); empBuilder.calculateEmpWage(); empBuilder.getTotalWage("Bridgelab"); empBuilder.getDailyWage("Bridgelab"); empBuilder.getTotalWage("MindTree"); empBuilder.getDailyWage("MindTree"); } } class CompanyEmpWage{ private final String companyName; private final int wagePerHour; private final int maxNoOfworkingDays; private final int maxNoOfWorkingHours; private int totalWage; private ArrayList<Integer> dailyWage; public CompanyEmpWage(String companyName, int wagePerHour, int maxNoOfworkingDays, int maxNoOfWorkingHours){ this.companyName=companyName; this.wagePerHour=wagePerHour; this.maxNoOfworkingDays=maxNoOfworkingDays; this.maxNoOfWorkingHours=maxNoOfWorkingHours; dailyWage=new ArrayList<>(); } String getCompanyName(){return this.companyName;} int getWagePerHour(){return this.wagePerHour;} int getMaxWorkingHours(){return this.maxNoOfWorkingHours;} int getMaxWorkingDays(){return this.maxNoOfworkingDays;} void setTotalWage(int totalWage){ this.totalWage=totalWage;} void setDailyWage(Integer dailyWage){this.dailyWage.add(dailyWage); } int getTotalWage(){return this.totalWage;} ArrayList getDailyWage(){return this.dailyWage;} } interface IcomputeEmployeWage{ public void addCompany(String companyName, int wagePerHour, int maxNoOfworkingDays, int maxNoOfWorkingHours); public String getAttendance(); public void calculateEmpWage(); public int getWorkingHourPerDay(); public void getTotalWage(String companyName); public void getDailyWage(String companyName); } class EmployeeWageBuilder implements IcomputeEmployeWage{ private static final int FULL_TIME=8; private static final int PART_TIME=4; private static final int MAX_DAYS_IN_MONTH=30; private ArrayList<CompanyEmpWage> companyWageList; private HashMap<String, CompanyEmpWage> totalWageMap; public EmployeeWageBuilder(){ companyWageList = new ArrayList<CompanyEmpWage>(); totalWageMap = new HashMap<>(); } @Override public void addCompany(String companyName, int wagePerHour, int maxNoOfworkingDays, int maxNoOfWorkingHours){ companyWageList.add(new CompanyEmpWage(companyName, wagePerHour, maxNoOfworkingDays, maxNoOfWorkingHours)); } @Override public String getAttendance(){ if(Math.random()*10>=3){ return "present"; } else{ return "absent"; } } public int getWorkingHourPerDay(){ int workingHourPerDay; Random random = new Random(); int status = random.nextInt(2); switch(status){ case 0: workingHourPerDay=FULL_TIME; break; case 1: workingHourPerDay=PART_TIME; break; default: workingHourPerDay=0; break; } return workingHourPerDay; } public int getDailyWage(int perDayWorkHour, int wagePerHour){ int workingHourPerDay=perDayWorkHour; return workingHourPerDay*wagePerHour; } public void calculateEmpWage( ){ for(CompanyEmpWage company : companyWageList) { int totalWorkingHour=0; int totalWorkingDays=0; int totalDays=0; int totalWage=0; int perDayWorkHour=0; int dailyWage=0; while(totalWorkingHour<company.getMaxWorkingHours() && totalWorkingDays<company.getMaxWorkingDays() && totalDays<MAX_DAYS_IN_MONTH){ totalDays++; if(getAttendance().equals("present")){ totalWorkingDays++; perDayWorkHour=getWorkingHourPerDay(); totalWorkingHour=totalWorkingHour+perDayWorkHour; dailyWage=getDailyWage(perDayWorkHour, company.getWagePerHour()); totalWage=totalWage+dailyWage; company.setDailyWage(dailyWage); } } company.setTotalWage(totalWage); totalWageMap.put(company.getCompanyName(), company); } } @Override public void getTotalWage(String companyName){ System.out.println("Total Wage for "+companyName+" is "+totalWageMap.get(companyName).getTotalWage()); } @Override public void getDailyWage(String companyName){ System.out.println("Daily Wage for "+companyName+ ": "); System.out.println(totalWageMap.get(companyName).getDailyWage()); } }
5,147
0.667185
0.659219
155
32.200001
27.173374
140
false
false
0
0
0
0
0
0
0.670968
false
false
14
546cd412f9d9ae0837fd3f7e77720879c7893042
25,005,299,627,576
7b6165c8ac19f7e1ff4909002e62ec2bfd4d452b
/src/main/java/br/com/escola/infra/indicacao/EnviarEmailIndicacaoIndicacaoJavaMail.java
b729aecc13d44de06051851e639c1fe1bdf0e603
[]
no_license
denis-schimidt/escola-ddd
https://github.com/denis-schimidt/escola-ddd
51b688d036a591897a9e4bd99a7cb1d25f580ead
cdadc7ef612c378883257373adf7243762e2f8f2
refs/heads/master
2023-06-26T12:47:31.711000
2021-08-01T02:46:37
2021-08-01T02:46:37
387,924,434
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.escola.infra.indicacao; import br.com.escola.aplicacao.indicacao.EnviarEmailIndicacao; import br.com.escola.dominio.aluno.Aluno; import org.springframework.stereotype.Service; @Service public class EnviarEmailIndicacaoIndicacaoJavaMail implements EnviarEmailIndicacao { @Override public void enviarPara(Aluno indicado) { System.out.printf("Email de indicação enviado para o aluno %s", indicado.getNome()); } }
UTF-8
Java
450
java
EnviarEmailIndicacaoIndicacaoJavaMail.java
Java
[]
null
[]
package br.com.escola.infra.indicacao; import br.com.escola.aplicacao.indicacao.EnviarEmailIndicacao; import br.com.escola.dominio.aluno.Aluno; import org.springframework.stereotype.Service; @Service public class EnviarEmailIndicacaoIndicacaoJavaMail implements EnviarEmailIndicacao { @Override public void enviarPara(Aluno indicado) { System.out.printf("Email de indicação enviado para o aluno %s", indicado.getNome()); } }
450
0.785714
0.785714
14
31
30.875326
92
false
false
0
0
0
0
0
0
0.428571
false
false
14
e2336ee9bb36f79793a7bacf6cd88274471ea862
214,748,372,164
3fd33510c4328a49596465962e86f7fc855ad144
/spring/HelpDesk/src/main/java/com/fyd/sistema/api/repository/BenchmarkRepository.java
429f5428d8d7be4e1f85d93d87e77a2845bc0046
[]
no_license
dexterorion/fyd
https://github.com/dexterorion/fyd
63d9a8e1335d70826f765e05e58a1d840a78c124
4c7561a09688aac8faa75f3008efa2eed634fcef
refs/heads/master
2020-03-11T05:27:54.600000
2018-06-13T18:17:32
2018-06-13T18:17:32
129,451,571
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.fyd.sistema.api.repository; import org.springframework.data.mongodb.repository.MongoRepository; import com.fyd.sistema.api.entity.Benchmark; public interface BenchmarkRepository extends MongoRepository<Benchmark, String>{ }
UTF-8
Java
240
java
BenchmarkRepository.java
Java
[]
null
[]
package com.fyd.sistema.api.repository; import org.springframework.data.mongodb.repository.MongoRepository; import com.fyd.sistema.api.entity.Benchmark; public interface BenchmarkRepository extends MongoRepository<Benchmark, String>{ }
240
0.8375
0.8375
9
25.666666
30.58322
80
false
false
0
0
0
0
0
0
0.444444
false
false
14
db0c6c931aacde01b3384a087411489416960323
11,398,843,250,149
96fc391ef3452dcdb5459fbb0d0e13d7bad2e345
/jSONwriteRead/src/ConvertXMLtoJSON.java
55ecaf71b2362bd482572b1dbb4f21880203c27b
[]
no_license
AlexeiYakushyn/Homework
https://github.com/AlexeiYakushyn/Homework
04dd3d70be5887ea9893f7ee88c4ce004828219f
3c9abdd9755208cad67fa7aa684830a5e8d57f21
refs/heads/master
2020-12-07T15:20:39.317000
2017-10-05T10:09:13
2017-10-05T10:09:13
95,467,923
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import org.json.JSONException; import org.json.JSONObject; import org.json.XML; import java.io.*; /** * Created by alexei.yakushyn on 03.09.2017. */ public class ConvertXMLtoJSON { public static final int PRETTY_PRINT_INDENT_FACTOR = 4; public static final String TEST_XML_STRING = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" + "<trucks>\n" + " <superWeightTruck weightClass=\"Really Huge\">\n" + " <truckName type=\"Cement Truck\">Kayaba Rocket</truckName>\n" + " <truckName type=\"Truck Tractor\">Peterbilt 386</truckName>\n" + " <truckName type=\"Dump Truck\">Belaz 75710</truckName>\n" + " <truckName type=\"Sleeper Cab\">New Cascadia</truckName>\n" + " </superWeightTruck>\n" + "</trucks>"; public void xmlToJSON() { try { JSONObject xmlJSONObject = XML.toJSONObject(TEST_XML_STRING); String jsonPrettyPrintString = xmlJSONObject.toString(PRETTY_PRINT_INDENT_FACTOR); File file = new File("E:\\ProgrammFiles\\hillel\\Homework\\jSONwriteRead\\src\\trucksJSON_test.json"); ObjectOutputStream stream = new ObjectOutputStream(new FileOutputStream(file)); stream.writeObject(jsonPrettyPrintString); } catch (JSONException je) { System.out.println(je.toString()); } catch (IOException e) { e.printStackTrace(); } } }
UTF-8
Java
1,510
java
ConvertXMLtoJSON.java
Java
[ { "context": "rg.json.XML;\n\nimport java.io.*;\n\n/**\n * Created by alexei.yakushyn on 03.09.2017.\n */\npublic class ConvertXMLtoJSON ", "end": 133, "score": 0.9524095058441162, "start": 118, "tag": "NAME", "value": "alexei.yakushyn" } ]
null
[]
import org.json.JSONException; import org.json.JSONObject; import org.json.XML; import java.io.*; /** * Created by alexei.yakushyn on 03.09.2017. */ public class ConvertXMLtoJSON { public static final int PRETTY_PRINT_INDENT_FACTOR = 4; public static final String TEST_XML_STRING = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" + "<trucks>\n" + " <superWeightTruck weightClass=\"Really Huge\">\n" + " <truckName type=\"Cement Truck\">Kayaba Rocket</truckName>\n" + " <truckName type=\"Truck Tractor\">Peterbilt 386</truckName>\n" + " <truckName type=\"Dump Truck\">Belaz 75710</truckName>\n" + " <truckName type=\"Sleeper Cab\">New Cascadia</truckName>\n" + " </superWeightTruck>\n" + "</trucks>"; public void xmlToJSON() { try { JSONObject xmlJSONObject = XML.toJSONObject(TEST_XML_STRING); String jsonPrettyPrintString = xmlJSONObject.toString(PRETTY_PRINT_INDENT_FACTOR); File file = new File("E:\\ProgrammFiles\\hillel\\Homework\\jSONwriteRead\\src\\trucksJSON_test.json"); ObjectOutputStream stream = new ObjectOutputStream(new FileOutputStream(file)); stream.writeObject(jsonPrettyPrintString); } catch (JSONException je) { System.out.println(je.toString()); } catch (IOException e) { e.printStackTrace(); } } }
1,510
0.600662
0.587417
41
35.829269
34.664879
115
false
false
0
0
0
0
0
0
0.317073
false
false
14
f2fd42214303cf7d41c33f3307737b0b583fd70b
10,385,230,972,956
b51d862b37541907765daff6e1d4de4654f472b5
/src/main/java/com/rcircle/service/account/controller/AccountController.java
9665bba4b311152aabc4df103f638b24f55bc7c8
[ "Apache-2.0" ]
permissive
ray0728/accountserver
https://github.com/ray0728/accountserver
a95496d8167a462a2b4a46dd6972a849efa65c95
b2072e91c284c03373ad3ae22e36a7c035927d6a
refs/heads/master
2022-06-28T01:22:07.443000
2019-09-15T13:42:13
2019-09-15T13:42:13
197,343,808
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.rcircle.service.account.controller; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.rcircle.service.account.model.Account; import com.rcircle.service.account.model.ResultData; import com.rcircle.service.account.model.Role; import com.rcircle.service.account.services.AccountService; import com.rcircle.service.account.util.ResultInfo; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.security.Principal; import java.util.List; @RestController @RequestMapping("/account") public class AccountController { @Resource private AccountService mAccountService; private boolean isAdminAccount(String name) { Account opAccount = mAccountService.getAccount(name, 0); if (opAccount == null) { return false; } List<Role> authorities = opAccount.getRoles(); for (Role role : authorities) { if (role.isAdminRole() || role.isSuperRole()) { return true; } } return false; } @PostMapping("avatar") public String uploadAvatar(Principal principal, @RequestParam(name="file") MultipartFile file, @RequestParam(name = "checksum") String checksum) { Account opAccount = mAccountService.getAccount(principal.getName(), 0); if (opAccount == null) { return ResultInfo.assembleJson(ResultInfo.ErrType.INVALID, ResultInfo.CODE_UPLOAD_AVATAR, "Invalid resources."); } return mAccountService.updateAvatar(opAccount.getUid(), checksum, file); } @PostMapping(value = "create") public String create(Principal principal, @RequestParam(name = "file", required = false) MultipartFile file, @RequestParam(name = "username") String username, @RequestParam(name = "email") String email, @RequestParam(name = "passwd") String password, @RequestParam(name = "roles", required = false, defaultValue = "") int[] roles, @RequestParam(name = "signature", required = false, defaultValue = "") String profile, @RequestParam(name = "resume", required = false, defaultValue = "") String resume, @RequestParam(name = "checksum", required = false, defaultValue = "") String checksum ) { if (username == null || username.length() == 0 || password == null || password.length() == 0) { return ResultInfo.assembleJson(ResultInfo.ErrType.PARAMS, ResultInfo.CODE_CREATE_ACCOUNT, "Invalid request parameters."); } boolean isAdminOp = false; if (principal != null) { isAdminOp = isAdminAccount(principal.getName()); } Account account = new Account(); account.setUsername(username); account.setPassword(password); account.setEmail(email); account.setSignature(profile); account.setResume(resume); if (mAccountService.createAccount(account) == 0) { return ResultInfo.assembleJson(ResultInfo.ErrType.PARAMS, ResultInfo.CODE_CREATE_ACCOUNT, "Invalid request parameters."); } if (isAdminOp) { if (roles.length == 0) { mAccountService.addRole(account, Role.ID_USER); } else { mAccountService.addRole(account, roles); } } else { mAccountService.addRole(account, Role.ID_GUEST); } if (!checksum.isEmpty() && file != null) { mAccountService.updateAvatar(account.getUid(), checksum, file); mAccountService.updateAccountInfo(account.getUid(), null, null, null); } account.hideSensitiveInfo(true); ResultData data = new ResultData(); data.setCode(ResultInfo.CODE_CREATE_ACCOUNT); data.setType(ResultInfo.translate(ResultInfo.ErrType.SUCCESS)); data.addToMap("account", account); data.addToMap("uid", account.getUid()); return JSONObject.toJSONString(data); } @DeleteMapping("delete") public String delete(Principal principal, @RequestParam(name = "uid", required = true) int uid) { if (uid == 0) { return ResultInfo.assembleJson(ResultInfo.ErrType.PARAMS, ResultInfo.CODE_DELETE_ACCOUNT, "Invalid request parameters."); } boolean isAdminOp = false; if (principal != null) { isAdminOp = isAdminAccount(principal.getName()); } if (isAdminOp) { Account account = mAccountService.getAccount(null, uid); if (account == null) { return ResultInfo.assembleJson(ResultInfo.ErrType.NULLOBJ, ResultInfo.CODE_DELETE_ACCOUNT, "Invalid resources."); } mAccountService.destroyAccount(account); } return ResultInfo.assembleSuccessJson(ResultInfo.CODE_DELETE_ACCOUNT, null, null, null); } @PutMapping("change") public String changeAccount(Principal principal, @RequestParam(name = "uid", required = true) int uid, @RequestParam(name = "status", required = false, defaultValue = "-1") int status, @RequestParam(name = "roles", required = false) int[] roles) { if (uid == 0 || principal == null) { return ResultInfo.assembleJson(ResultInfo.ErrType.NULLOBJ, ResultInfo.CODE_CHANGE_ACCOUNT, "Invalid request parameters."); } Account opAccount = mAccountService.getAccount(principal.getName(), 0); if (opAccount == null) { return ResultInfo.assembleJson(ResultInfo.ErrType.NULLOBJ, ResultInfo.CODE_CHANGE_ACCOUNT, "Invalid request parameters."); } int maxRoleLevel = opAccount.getMaxLevelRole(); if (maxRoleLevel >= Role.ID_ADMIN) { Account account = mAccountService.getAccount(null, uid); if (account == null) { return ResultInfo.assembleJson(ResultInfo.ErrType.INVALID, ResultInfo.CODE_CHANGE_ACCOUNT, "Invalid resources."); } if (account.getMaxLevelRole() > maxRoleLevel) { return ResultInfo.assembleJson(ResultInfo.ErrType.INVALID, ResultInfo.CODE_CHANGE_ACCOUNT, "have no enough permission."); } if (status != -1) { mAccountService.setAccountStatus(account, status); } if (roles != null && roles.length > 0) { mAccountService.addRole(account, roles); } account.hideSensitiveInfo(false); return ResultInfo.assembleSuccessJson(ResultInfo.CODE_CHANGE_ACCOUNT, "finished", "account", account); } else { return ResultInfo.assembleJson(ResultInfo.ErrType.INVALID, ResultInfo.CODE_CHANGE_ACCOUNT, "have no enough permission."); } } @PutMapping("edit") public String changeProifle(Principal principal, @RequestParam(name = "email", required = false, defaultValue = "") String email, @RequestParam(name = "signature", required = false, defaultValue = "") String profile, @RequestParam(name = "resume", required = false, defaultValue = "") String resume) { if (principal == null) { return ResultInfo.assembleJson(ResultInfo.ErrType.NULLOBJ, ResultInfo.CODE_EDIT_ACCOUNT, "Invalid request parameters."); } Account account = mAccountService.getAccount(principal.getName(), 0); if (account == null) { return ResultInfo.assembleJson(ResultInfo.ErrType.INVALID, ResultInfo.CODE_EDIT_ACCOUNT, "Invalid resources."); } mAccountService.updateAccountInfo(account.getUid(), email, profile, resume); account.hideSensitiveInfo(true); return ResultInfo.assembleSuccessJson(ResultInfo.CODE_EDIT_ACCOUNT, "finished", "account", account); } @PutMapping("password") public String changePassword(Principal principal, @RequestParam(name = "old") String oldPass, @RequestParam(name = "new") String newPass) { Account opAccount = mAccountService.getAccount(principal.getName(), 0); if (opAccount == null || oldPass.isEmpty() || newPass.isEmpty() || oldPass.equals(newPass)) { return ResultInfo.assembleJson(ResultInfo.ErrType.INVALID, ResultInfo.CODE_CHANGE_PASSWORD, "Invalid resources."); } if (!opAccount.isSamePassword(oldPass)) { return ResultInfo.assembleJson(ResultInfo.ErrType.INVALID, ResultInfo.CODE_CHANGE_PASSWORD, "Invalid resources."); } mAccountService.changePassword(opAccount.getUid(), newPass); opAccount.hideSensitiveInfo(true); return ResultInfo.assembleSuccessJson(ResultInfo.CODE_EDIT_ACCOUNT, "finished", "account", opAccount); } @GetMapping("info") public String getInfo(Principal principal, HttpServletRequest request, @RequestParam(name = "username", required = false, defaultValue = "") String username, @RequestParam(name = "uid", required = false, defaultValue = "0") int uid) { String ret = null; Account opAccount = null; if (principal != null) { opAccount = mAccountService.getAccount(principal.getName(), 0); } if (username.isEmpty() && uid == 0) { List<Account> accounts = mAccountService.getAllAccounts(); for (Account account : accounts) { account.hideSensitiveInfo(false); } ret = accounts == null ? null : JSONArray.toJSONString(accounts); } else { Account account = mAccountService.getAccount(username, uid); String securityFlag = request.getHeader("rc-account-security"); if (account != null && securityFlag == null) { account.hideSensitiveInfo(account.isSame(opAccount)); } ret = account == null ? null : JSONObject.toJSONString(account); } return ret; } @GetMapping("avatar/{uid}") public ResponseEntity getAvatar(Principal principal, @PathVariable("uid") int uid) { Account account = mAccountService.getAccount(null, uid); String errinfo = null; try { return account.getAvatar().isEmpty() ? null : createResponseEntity("image/jpg", account.getAvatar() + File.separatorChar + "avatar"); } catch (IOException e) { errinfo = e.getMessage(); } return ResponseEntity.status(404).body(errinfo); } private ResponseEntity createResponseEntity(String type, String filePath) throws IOException { MediaType mediaType = MediaType.parseMediaType(type); HttpHeaders headers = new HttpHeaders(); headers.setContentType(mediaType); File file = new File(filePath); FileInputStream inputStream = new FileInputStream(file); byte[] bytes = new byte[inputStream.available()]; inputStream.read(bytes, 0, inputStream.available()); inputStream.close(); return new ResponseEntity(bytes, headers, HttpStatus.OK); } @PutMapping("refresh") public String refreshTime(Principal principal) { if (principal == null) { return ResultInfo.assembleJson(ResultInfo.ErrType.NULLOBJ, ResultInfo.CODE_REFRESH_ACCOUNT, "Invalid request parameters."); } Account account = mAccountService.getAccount(principal.getName(), 0); if (account == null) { return ResultInfo.assembleJson(ResultInfo.ErrType.INVALID, ResultInfo.CODE_REFRESH_ACCOUNT, "Invalid resources."); } mAccountService.updateAccountTimeInfo(account); account.hideSensitiveInfo(false); return ResultInfo.assembleSuccessJson(ResultInfo.CODE_REFRESH_ACCOUNT, "finished", "account", account); } @GetMapping("me") public String showMe(Principal principal) { Account account = null; if (principal != null) { account = mAccountService.getAccount(principal.getName(), 0); account.hideSensitiveInfo(true); } return account == null ? "" : JSONObject.toJSONString(account); } }
UTF-8
Java
12,866
java
AccountController.java
Java
[ { "context": "e,\n @RequestParam(name = \"username\") String username,\n @Requ", "end": 2256, "score": 0.9970030784606934, "start": 2248, "tag": "USERNAME", "value": "username" }, { "context": "ount = new Account();\n account.set...
null
[]
package com.rcircle.service.account.controller; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.rcircle.service.account.model.Account; import com.rcircle.service.account.model.ResultData; import com.rcircle.service.account.model.Role; import com.rcircle.service.account.services.AccountService; import com.rcircle.service.account.util.ResultInfo; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.security.Principal; import java.util.List; @RestController @RequestMapping("/account") public class AccountController { @Resource private AccountService mAccountService; private boolean isAdminAccount(String name) { Account opAccount = mAccountService.getAccount(name, 0); if (opAccount == null) { return false; } List<Role> authorities = opAccount.getRoles(); for (Role role : authorities) { if (role.isAdminRole() || role.isSuperRole()) { return true; } } return false; } @PostMapping("avatar") public String uploadAvatar(Principal principal, @RequestParam(name="file") MultipartFile file, @RequestParam(name = "checksum") String checksum) { Account opAccount = mAccountService.getAccount(principal.getName(), 0); if (opAccount == null) { return ResultInfo.assembleJson(ResultInfo.ErrType.INVALID, ResultInfo.CODE_UPLOAD_AVATAR, "Invalid resources."); } return mAccountService.updateAvatar(opAccount.getUid(), checksum, file); } @PostMapping(value = "create") public String create(Principal principal, @RequestParam(name = "file", required = false) MultipartFile file, @RequestParam(name = "username") String username, @RequestParam(name = "email") String email, @RequestParam(name = "passwd") String password, @RequestParam(name = "roles", required = false, defaultValue = "") int[] roles, @RequestParam(name = "signature", required = false, defaultValue = "") String profile, @RequestParam(name = "resume", required = false, defaultValue = "") String resume, @RequestParam(name = "checksum", required = false, defaultValue = "") String checksum ) { if (username == null || username.length() == 0 || password == null || password.length() == 0) { return ResultInfo.assembleJson(ResultInfo.ErrType.PARAMS, ResultInfo.CODE_CREATE_ACCOUNT, "Invalid request parameters."); } boolean isAdminOp = false; if (principal != null) { isAdminOp = isAdminAccount(principal.getName()); } Account account = new Account(); account.setUsername(username); account.setPassword(<PASSWORD>); account.setEmail(email); account.setSignature(profile); account.setResume(resume); if (mAccountService.createAccount(account) == 0) { return ResultInfo.assembleJson(ResultInfo.ErrType.PARAMS, ResultInfo.CODE_CREATE_ACCOUNT, "Invalid request parameters."); } if (isAdminOp) { if (roles.length == 0) { mAccountService.addRole(account, Role.ID_USER); } else { mAccountService.addRole(account, roles); } } else { mAccountService.addRole(account, Role.ID_GUEST); } if (!checksum.isEmpty() && file != null) { mAccountService.updateAvatar(account.getUid(), checksum, file); mAccountService.updateAccountInfo(account.getUid(), null, null, null); } account.hideSensitiveInfo(true); ResultData data = new ResultData(); data.setCode(ResultInfo.CODE_CREATE_ACCOUNT); data.setType(ResultInfo.translate(ResultInfo.ErrType.SUCCESS)); data.addToMap("account", account); data.addToMap("uid", account.getUid()); return JSONObject.toJSONString(data); } @DeleteMapping("delete") public String delete(Principal principal, @RequestParam(name = "uid", required = true) int uid) { if (uid == 0) { return ResultInfo.assembleJson(ResultInfo.ErrType.PARAMS, ResultInfo.CODE_DELETE_ACCOUNT, "Invalid request parameters."); } boolean isAdminOp = false; if (principal != null) { isAdminOp = isAdminAccount(principal.getName()); } if (isAdminOp) { Account account = mAccountService.getAccount(null, uid); if (account == null) { return ResultInfo.assembleJson(ResultInfo.ErrType.NULLOBJ, ResultInfo.CODE_DELETE_ACCOUNT, "Invalid resources."); } mAccountService.destroyAccount(account); } return ResultInfo.assembleSuccessJson(ResultInfo.CODE_DELETE_ACCOUNT, null, null, null); } @PutMapping("change") public String changeAccount(Principal principal, @RequestParam(name = "uid", required = true) int uid, @RequestParam(name = "status", required = false, defaultValue = "-1") int status, @RequestParam(name = "roles", required = false) int[] roles) { if (uid == 0 || principal == null) { return ResultInfo.assembleJson(ResultInfo.ErrType.NULLOBJ, ResultInfo.CODE_CHANGE_ACCOUNT, "Invalid request parameters."); } Account opAccount = mAccountService.getAccount(principal.getName(), 0); if (opAccount == null) { return ResultInfo.assembleJson(ResultInfo.ErrType.NULLOBJ, ResultInfo.CODE_CHANGE_ACCOUNT, "Invalid request parameters."); } int maxRoleLevel = opAccount.getMaxLevelRole(); if (maxRoleLevel >= Role.ID_ADMIN) { Account account = mAccountService.getAccount(null, uid); if (account == null) { return ResultInfo.assembleJson(ResultInfo.ErrType.INVALID, ResultInfo.CODE_CHANGE_ACCOUNT, "Invalid resources."); } if (account.getMaxLevelRole() > maxRoleLevel) { return ResultInfo.assembleJson(ResultInfo.ErrType.INVALID, ResultInfo.CODE_CHANGE_ACCOUNT, "have no enough permission."); } if (status != -1) { mAccountService.setAccountStatus(account, status); } if (roles != null && roles.length > 0) { mAccountService.addRole(account, roles); } account.hideSensitiveInfo(false); return ResultInfo.assembleSuccessJson(ResultInfo.CODE_CHANGE_ACCOUNT, "finished", "account", account); } else { return ResultInfo.assembleJson(ResultInfo.ErrType.INVALID, ResultInfo.CODE_CHANGE_ACCOUNT, "have no enough permission."); } } @PutMapping("edit") public String changeProifle(Principal principal, @RequestParam(name = "email", required = false, defaultValue = "") String email, @RequestParam(name = "signature", required = false, defaultValue = "") String profile, @RequestParam(name = "resume", required = false, defaultValue = "") String resume) { if (principal == null) { return ResultInfo.assembleJson(ResultInfo.ErrType.NULLOBJ, ResultInfo.CODE_EDIT_ACCOUNT, "Invalid request parameters."); } Account account = mAccountService.getAccount(principal.getName(), 0); if (account == null) { return ResultInfo.assembleJson(ResultInfo.ErrType.INVALID, ResultInfo.CODE_EDIT_ACCOUNT, "Invalid resources."); } mAccountService.updateAccountInfo(account.getUid(), email, profile, resume); account.hideSensitiveInfo(true); return ResultInfo.assembleSuccessJson(ResultInfo.CODE_EDIT_ACCOUNT, "finished", "account", account); } @PutMapping("password") public String changePassword(Principal principal, @RequestParam(name = "old") String oldPass, @RequestParam(name = "new") String newPass) { Account opAccount = mAccountService.getAccount(principal.getName(), 0); if (opAccount == null || oldPass.isEmpty() || newPass.isEmpty() || oldPass.equals(newPass)) { return ResultInfo.assembleJson(ResultInfo.ErrType.INVALID, ResultInfo.CODE_CHANGE_PASSWORD, "Invalid resources."); } if (!opAccount.isSamePassword(oldPass)) { return ResultInfo.assembleJson(ResultInfo.ErrType.INVALID, ResultInfo.CODE_CHANGE_PASSWORD, "Invalid resources."); } mAccountService.changePassword(opAccount.getUid(), newPass); opAccount.hideSensitiveInfo(true); return ResultInfo.assembleSuccessJson(ResultInfo.CODE_EDIT_ACCOUNT, "finished", "account", opAccount); } @GetMapping("info") public String getInfo(Principal principal, HttpServletRequest request, @RequestParam(name = "username", required = false, defaultValue = "") String username, @RequestParam(name = "uid", required = false, defaultValue = "0") int uid) { String ret = null; Account opAccount = null; if (principal != null) { opAccount = mAccountService.getAccount(principal.getName(), 0); } if (username.isEmpty() && uid == 0) { List<Account> accounts = mAccountService.getAllAccounts(); for (Account account : accounts) { account.hideSensitiveInfo(false); } ret = accounts == null ? null : JSONArray.toJSONString(accounts); } else { Account account = mAccountService.getAccount(username, uid); String securityFlag = request.getHeader("rc-account-security"); if (account != null && securityFlag == null) { account.hideSensitiveInfo(account.isSame(opAccount)); } ret = account == null ? null : JSONObject.toJSONString(account); } return ret; } @GetMapping("avatar/{uid}") public ResponseEntity getAvatar(Principal principal, @PathVariable("uid") int uid) { Account account = mAccountService.getAccount(null, uid); String errinfo = null; try { return account.getAvatar().isEmpty() ? null : createResponseEntity("image/jpg", account.getAvatar() + File.separatorChar + "avatar"); } catch (IOException e) { errinfo = e.getMessage(); } return ResponseEntity.status(404).body(errinfo); } private ResponseEntity createResponseEntity(String type, String filePath) throws IOException { MediaType mediaType = MediaType.parseMediaType(type); HttpHeaders headers = new HttpHeaders(); headers.setContentType(mediaType); File file = new File(filePath); FileInputStream inputStream = new FileInputStream(file); byte[] bytes = new byte[inputStream.available()]; inputStream.read(bytes, 0, inputStream.available()); inputStream.close(); return new ResponseEntity(bytes, headers, HttpStatus.OK); } @PutMapping("refresh") public String refreshTime(Principal principal) { if (principal == null) { return ResultInfo.assembleJson(ResultInfo.ErrType.NULLOBJ, ResultInfo.CODE_REFRESH_ACCOUNT, "Invalid request parameters."); } Account account = mAccountService.getAccount(principal.getName(), 0); if (account == null) { return ResultInfo.assembleJson(ResultInfo.ErrType.INVALID, ResultInfo.CODE_REFRESH_ACCOUNT, "Invalid resources."); } mAccountService.updateAccountTimeInfo(account); account.hideSensitiveInfo(false); return ResultInfo.assembleSuccessJson(ResultInfo.CODE_REFRESH_ACCOUNT, "finished", "account", account); } @GetMapping("me") public String showMe(Principal principal) { Account account = null; if (principal != null) { account = mAccountService.getAccount(principal.getName(), 0); account.hideSensitiveInfo(true); } return account == null ? "" : JSONObject.toJSONString(account); } }
12,868
0.629877
0.62809
268
47.007462
36.674953
145
false
false
0
0
0
0
0
0
0.985075
false
false
14
330160ff209c6b0cd5250995b07e54c26ba3c237
11,828,339,995,900
4bbbe4fec69937c43e54c86ed3d6f610e78228e9
/server/src/test/java/org/cloudfoundry/autoscaler/metric/rest/DashboardRESTTest.java
ce4f2bc60a5b2f82402f3f76891a5450967d4efd
[ "Apache-2.0" ]
permissive
cfibmers/open-Autoscaler
https://github.com/cfibmers/open-Autoscaler
6ef0ca3cf4259a8ed51a8ad862b255955ef482a5
b135e7c47c852df45657b4cd9477c86634f1c471
refs/heads/master
2020-04-06T13:28:44.866000
2016-11-23T15:31:14
2016-11-23T15:31:14
52,853,557
20
8
null
false
2016-10-13T02:25:41
2016-03-01T06:24:27
2016-09-16T13:13:41
2016-10-13T02:25:14
1,230
17
11
2
Java
null
null
package org.cloudfoundry.autoscaler.metric.rest; import static org.cloudfoundry.autoscaler.test.constant.Constants.*; import static org.junit.Assert.*; import java.util.HashMap; import java.util.Map; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import org.cloudfoundry.autoscaler.bean.Metric; import org.cloudfoundry.autoscaler.rest.mock.couchdb.CouchDBDocumentManager; import org.junit.Test; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.core.util.MultivaluedMapImpl; import com.sun.jersey.test.framework.JerseyTest; public class DashboardRESTTest extends JerseyTest{ public DashboardRESTTest(){ super("org.cloudfoundry.autoscaler.metric.rest","org.cloudfoundry.autoscaler.rest.mock"); } @Override public void tearDown() throws Exception{ super.tearDown(); CouchDBDocumentManager.getInstance().initDocuments(); } @Test public void testGetAppMetricsLastestData(){ WebResource webResource = resource(); MultivaluedMap<String, String> map = new MultivaluedMapImpl(); map.add("appId", TESTAPPID); ClientResponse response = webResource.path("/metrics/"+TESTSERVICEID).queryParams(map).get(ClientResponse.class); assertEquals(response.getStatus(), STATUS200); } @Test public void testGetAppHistoryMetrics(){ WebResource webResource = resource(); MultivaluedMap<String, String> map = new MultivaluedMapImpl(); map.add("appId", TESTAPPID); ClientResponse response = webResource.path("/metrics/"+TESTSERVICEID+"/"+TESTAPPID).get(ClientResponse.class); assertEquals(response.getStatus(), STATUS200); } @Test public void testGetAppHistoryMetrics2(){ WebResource webResource = resource(); ClientResponse response = webResource.path("/metrics/default/nodejs").get(ClientResponse.class); assertEquals(response.getStatus(), STATUS200); } // @Test // public void testAddMetricTestMode() throws JsonProcessingException { // WebResource webResource = resource(); // Metric pollerMem = new Metric(); // pollerMem.setCategory("cf-stats"); // pollerMem.setGroup("Memory"); // pollerMem.setName("Memory"); // pollerMem.setValue(String.valueOf(512 * 0.9)); // Map<String, Metric> testMetric = new HashMap<String, Metric>(); // testMetric.put(pollerMem.getCompoundName(), pollerMem); // // // test mode for memory // String testMetricStr = (new ObjectMapper()).writeValueAsString(testMetric); // ClientResponse response = webResource.path("/test/metrics/" + TESTAPPID).type(MediaType.APPLICATION_JSON).put(ClientResponse.class,testMetricStr); // assertEquals(response.getStatus(), STATUS200); // } // @Test // public void testRemoveMetricTestMode(){ // WebResource webResource = resource(); // ClientResponse response = webResource.path("/test/metrics/" + TESTAPPID).delete(ClientResponse.class); // assertEquals(response.getStatus(), STATUS200); // } }
UTF-8
Java
3,013
java
DashboardRESTTest.java
Java
[]
null
[]
package org.cloudfoundry.autoscaler.metric.rest; import static org.cloudfoundry.autoscaler.test.constant.Constants.*; import static org.junit.Assert.*; import java.util.HashMap; import java.util.Map; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import org.cloudfoundry.autoscaler.bean.Metric; import org.cloudfoundry.autoscaler.rest.mock.couchdb.CouchDBDocumentManager; import org.junit.Test; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.core.util.MultivaluedMapImpl; import com.sun.jersey.test.framework.JerseyTest; public class DashboardRESTTest extends JerseyTest{ public DashboardRESTTest(){ super("org.cloudfoundry.autoscaler.metric.rest","org.cloudfoundry.autoscaler.rest.mock"); } @Override public void tearDown() throws Exception{ super.tearDown(); CouchDBDocumentManager.getInstance().initDocuments(); } @Test public void testGetAppMetricsLastestData(){ WebResource webResource = resource(); MultivaluedMap<String, String> map = new MultivaluedMapImpl(); map.add("appId", TESTAPPID); ClientResponse response = webResource.path("/metrics/"+TESTSERVICEID).queryParams(map).get(ClientResponse.class); assertEquals(response.getStatus(), STATUS200); } @Test public void testGetAppHistoryMetrics(){ WebResource webResource = resource(); MultivaluedMap<String, String> map = new MultivaluedMapImpl(); map.add("appId", TESTAPPID); ClientResponse response = webResource.path("/metrics/"+TESTSERVICEID+"/"+TESTAPPID).get(ClientResponse.class); assertEquals(response.getStatus(), STATUS200); } @Test public void testGetAppHistoryMetrics2(){ WebResource webResource = resource(); ClientResponse response = webResource.path("/metrics/default/nodejs").get(ClientResponse.class); assertEquals(response.getStatus(), STATUS200); } // @Test // public void testAddMetricTestMode() throws JsonProcessingException { // WebResource webResource = resource(); // Metric pollerMem = new Metric(); // pollerMem.setCategory("cf-stats"); // pollerMem.setGroup("Memory"); // pollerMem.setName("Memory"); // pollerMem.setValue(String.valueOf(512 * 0.9)); // Map<String, Metric> testMetric = new HashMap<String, Metric>(); // testMetric.put(pollerMem.getCompoundName(), pollerMem); // // // test mode for memory // String testMetricStr = (new ObjectMapper()).writeValueAsString(testMetric); // ClientResponse response = webResource.path("/test/metrics/" + TESTAPPID).type(MediaType.APPLICATION_JSON).put(ClientResponse.class,testMetricStr); // assertEquals(response.getStatus(), STATUS200); // } // @Test // public void testRemoveMetricTestMode(){ // WebResource webResource = resource(); // ClientResponse response = webResource.path("/test/metrics/" + TESTAPPID).delete(ClientResponse.class); // assertEquals(response.getStatus(), STATUS200); // } }
3,013
0.769997
0.763027
78
37.628204
31.064081
150
false
false
0
0
0
0
0
0
1.833333
false
false
14
5bb84f79515f9767615e4f1dfeb2f979859b1977
27,101,243,691,053
17e8438486cb3e3073966ca2c14956d3ba9209ea
/dso/branches/4.0.8-rc/common/src/main/java/com/tc/properties/ReconnectConfig.java
afd11ce92d0489a674e5d354e1afa3b98862f32f
[]
no_license
sirinath/Terracotta
https://github.com/sirinath/Terracotta
fedfc2c4f0f06c990f94b8b6c3b9c93293334345
00a7662b9cf530dfdb43f2dd821fa559e998c892
refs/heads/master
2021-01-23T05:41:52.414000
2015-07-02T15:21:54
2015-07-02T15:21:54
38,613,711
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. */ package com.tc.properties; public interface ReconnectConfig { public boolean getReconnectEnabled(); public int getReconnectTimeout(); public int getSendQueueCapacity(); public int getMaxDelayAcks(); public int getSendWindow(); }
UTF-8
Java
353
java
ReconnectConfig.java
Java
[]
null
[]
/* * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. */ package com.tc.properties; public interface ReconnectConfig { public boolean getReconnectEnabled(); public int getReconnectTimeout(); public int getSendQueueCapacity(); public int getMaxDelayAcks(); public int getSendWindow(); }
353
0.736544
0.736544
18
18.611111
23.276451
91
false
false
0
0
0
0
0
0
0.444444
false
false
14
0600dc70b810b402bc2a07657ea4c7f1cf7ef073
3,161,095,949,665
78887910fbea9507997ec80de45468ac419fda42
/ReferenceTest/src/array/ArrayTest3.java
574669877ee5885418f4315ad9e85c0023119393
[]
no_license
ghtmdaks/javasource
https://github.com/ghtmdaks/javasource
5f3417ed2fdecf4da23414d003e20d1dd9515346
040f4cf9ea2d2a8c6baf5bf4820669ea0b381b91
refs/heads/master
2023-08-24T08:30:34.295000
2021-10-07T09:02:47
2021-10-07T09:02:47
411,899,097
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package array; public class ArrayTest3 { public static void main(String[] args) { // int 타입의 배열 5개 생성 // 0 10 20 30 40 int arr[] = {0, 10, 20, 30, 40}; // for (int i = 0; i < arr.length; i++) { // System.out.print(arr[i]+"\t"); // } //String 타입의 배열 5개 생성 // 과일 이름 초기화 // String fruit[] = {"사과", "멜론", "키위"}; // for (int i = 0; i < fruit.length; i++) { // System.out.print(fruit[i]+ "\t"); // } //향상된 for 문 for(int idx:arr) { System.out.print(idx+"\t"); } } } // 복습//////////////////////////////
UHC
Java
628
java
ArrayTest3.java
Java
[]
null
[]
package array; public class ArrayTest3 { public static void main(String[] args) { // int 타입의 배열 5개 생성 // 0 10 20 30 40 int arr[] = {0, 10, 20, 30, 40}; // for (int i = 0; i < arr.length; i++) { // System.out.print(arr[i]+"\t"); // } //String 타입의 배열 5개 생성 // 과일 이름 초기화 // String fruit[] = {"사과", "멜론", "키위"}; // for (int i = 0; i < fruit.length; i++) { // System.out.print(fruit[i]+ "\t"); // } //향상된 for 문 for(int idx:arr) { System.out.print(idx+"\t"); } } } // 복습//////////////////////////////
628
0.460573
0.419355
30
17.633333
15.531652
45
false
false
0
0
0
0
0
0
2.366667
false
false
14
5b6649a4e136bf46157278e88aff862d96e82e31
30,399,778,540,913
30472cec0dbe044d52b029530051ab404701687f
/src/main/java/com/sforce/soap/tooling/metadata/SummaryLayout.java
14466db2670399789fa98cd13e5d9521ae47c6ec
[ "BSD-3-Clause" ]
permissive
madmax983/ApexLink
https://github.com/madmax983/ApexLink
f8e9dcf8f697ed4e34ddcac353c13bec707f3670
30c989ce2c0098097bfaf586b87b733853913155
refs/heads/master
2020-05-07T16:03:15.046000
2019-04-08T21:08:06
2019-04-08T21:08:06
180,655,963
1
0
null
true
2019-04-10T20:08:30
2019-04-10T20:08:30
2019-04-10T20:08:29
2019-04-08T21:08:10
19,032
0
0
0
null
false
false
package com.sforce.soap.tooling.metadata; /** * This is a generated class for the SObject Enterprise API. * Do not edit this file, as your changes will be lost. */ public class SummaryLayout implements com.sforce.ws.bind.XMLizable { /** * Constructor */ public SummaryLayout() {} /* Cache the typeInfo instead of declaring static fields throughout*/ private transient java.util.Map<String, com.sforce.ws.bind.TypeInfo> typeInfoCache = new java.util.HashMap<String, com.sforce.ws.bind.TypeInfo>(); private com.sforce.ws.bind.TypeInfo _lookupTypeInfo(String fieldName, String namespace, String name, String typeNS, String type, int minOcc, int maxOcc, boolean elementForm) { com.sforce.ws.bind.TypeInfo typeInfo = typeInfoCache.get(fieldName); if (typeInfo == null) { typeInfo = new com.sforce.ws.bind.TypeInfo(namespace, name, typeNS, type, minOcc, maxOcc, elementForm); typeInfoCache.put(fieldName, typeInfo); } return typeInfo; } /** * element : masterLabel of type {http://www.w3.org/2001/XMLSchema}string * java type: java.lang.String */ private boolean masterLabel__is_set = false; private java.lang.String masterLabel; public java.lang.String getMasterLabel() { return masterLabel; } public void setMasterLabel(java.lang.String masterLabel) { this.masterLabel = masterLabel; masterLabel__is_set = true; } protected void setMasterLabel(com.sforce.ws.parser.XmlInputStream __in, com.sforce.ws.bind.TypeMapper __typeMapper) throws java.io.IOException, com.sforce.ws.ConnectionException { __in.peekTag(); if (__typeMapper.verifyElement(__in, _lookupTypeInfo("masterLabel", "urn:metadata.tooling.soap.sforce.com","masterLabel","http://www.w3.org/2001/XMLSchema","string",1,1,true))) { setMasterLabel(__typeMapper.readString(__in, _lookupTypeInfo("masterLabel", "urn:metadata.tooling.soap.sforce.com","masterLabel","http://www.w3.org/2001/XMLSchema","string",1,1,true), java.lang.String.class)); } } private void writeFieldMasterLabel(com.sforce.ws.parser.XmlOutputStream __out, com.sforce.ws.bind.TypeMapper __typeMapper) throws java.io.IOException { __typeMapper.writeObject(__out, _lookupTypeInfo("masterLabel", "urn:metadata.tooling.soap.sforce.com","masterLabel","http://www.w3.org/2001/XMLSchema","string",1,1,true), masterLabel, masterLabel__is_set); } /** * element : sizeX of type {http://www.w3.org/2001/XMLSchema}int * java type: int */ private boolean sizeX__is_set = false; private int sizeX; public int getSizeX() { return sizeX; } public void setSizeX(int sizeX) { this.sizeX = sizeX; sizeX__is_set = true; } protected void setSizeX(com.sforce.ws.parser.XmlInputStream __in, com.sforce.ws.bind.TypeMapper __typeMapper) throws java.io.IOException, com.sforce.ws.ConnectionException { __in.peekTag(); if (__typeMapper.verifyElement(__in, _lookupTypeInfo("sizeX", "urn:metadata.tooling.soap.sforce.com","sizeX","http://www.w3.org/2001/XMLSchema","int",1,1,true))) { setSizeX((int)__typeMapper.readInt(__in, _lookupTypeInfo("sizeX", "urn:metadata.tooling.soap.sforce.com","sizeX","http://www.w3.org/2001/XMLSchema","int",1,1,true), int.class)); } } private void writeFieldSizeX(com.sforce.ws.parser.XmlOutputStream __out, com.sforce.ws.bind.TypeMapper __typeMapper) throws java.io.IOException { __typeMapper.writeObject(__out, _lookupTypeInfo("sizeX", "urn:metadata.tooling.soap.sforce.com","sizeX","http://www.w3.org/2001/XMLSchema","int",1,1,true), sizeX, sizeX__is_set); } /** * element : sizeY of type {http://www.w3.org/2001/XMLSchema}int * java type: int */ private boolean sizeY__is_set = false; private int sizeY; public int getSizeY() { return sizeY; } public void setSizeY(int sizeY) { this.sizeY = sizeY; sizeY__is_set = true; } protected void setSizeY(com.sforce.ws.parser.XmlInputStream __in, com.sforce.ws.bind.TypeMapper __typeMapper) throws java.io.IOException, com.sforce.ws.ConnectionException { __in.peekTag(); if (__typeMapper.isElement(__in, _lookupTypeInfo("sizeY", "urn:metadata.tooling.soap.sforce.com","sizeY","http://www.w3.org/2001/XMLSchema","int",0,1,true))) { setSizeY((int)__typeMapper.readInt(__in, _lookupTypeInfo("sizeY", "urn:metadata.tooling.soap.sforce.com","sizeY","http://www.w3.org/2001/XMLSchema","int",0,1,true), int.class)); } } private void writeFieldSizeY(com.sforce.ws.parser.XmlOutputStream __out, com.sforce.ws.bind.TypeMapper __typeMapper) throws java.io.IOException { __typeMapper.writeObject(__out, _lookupTypeInfo("sizeY", "urn:metadata.tooling.soap.sforce.com","sizeY","http://www.w3.org/2001/XMLSchema","int",0,1,true), sizeY, sizeY__is_set); } /** * element : sizeZ of type {http://www.w3.org/2001/XMLSchema}int * java type: int */ private boolean sizeZ__is_set = false; private int sizeZ; public int getSizeZ() { return sizeZ; } public void setSizeZ(int sizeZ) { this.sizeZ = sizeZ; sizeZ__is_set = true; } protected void setSizeZ(com.sforce.ws.parser.XmlInputStream __in, com.sforce.ws.bind.TypeMapper __typeMapper) throws java.io.IOException, com.sforce.ws.ConnectionException { __in.peekTag(); if (__typeMapper.isElement(__in, _lookupTypeInfo("sizeZ", "urn:metadata.tooling.soap.sforce.com","sizeZ","http://www.w3.org/2001/XMLSchema","int",0,1,true))) { setSizeZ((int)__typeMapper.readInt(__in, _lookupTypeInfo("sizeZ", "urn:metadata.tooling.soap.sforce.com","sizeZ","http://www.w3.org/2001/XMLSchema","int",0,1,true), int.class)); } } private void writeFieldSizeZ(com.sforce.ws.parser.XmlOutputStream __out, com.sforce.ws.bind.TypeMapper __typeMapper) throws java.io.IOException { __typeMapper.writeObject(__out, _lookupTypeInfo("sizeZ", "urn:metadata.tooling.soap.sforce.com","sizeZ","http://www.w3.org/2001/XMLSchema","int",0,1,true), sizeZ, sizeZ__is_set); } /** * element : summaryLayoutItems of type {urn:metadata.tooling.soap.sforce.com}SummaryLayoutItem * java type: com.sforce.soap.tooling.metadata.SummaryLayoutItem[] */ private boolean summaryLayoutItems__is_set = false; private com.sforce.soap.tooling.metadata.SummaryLayoutItem[] summaryLayoutItems = new com.sforce.soap.tooling.metadata.SummaryLayoutItem[0]; public com.sforce.soap.tooling.metadata.SummaryLayoutItem[] getSummaryLayoutItems() { return summaryLayoutItems; } public void setSummaryLayoutItems(com.sforce.soap.tooling.metadata.SummaryLayoutItem[] summaryLayoutItems) { this.summaryLayoutItems = summaryLayoutItems; summaryLayoutItems__is_set = true; } protected void setSummaryLayoutItems(com.sforce.ws.parser.XmlInputStream __in, com.sforce.ws.bind.TypeMapper __typeMapper) throws java.io.IOException, com.sforce.ws.ConnectionException { __in.peekTag(); if (__typeMapper.isElement(__in, _lookupTypeInfo("summaryLayoutItems", "urn:metadata.tooling.soap.sforce.com","summaryLayoutItems","urn:metadata.tooling.soap.sforce.com","SummaryLayoutItem",0,-1,true))) { setSummaryLayoutItems((com.sforce.soap.tooling.metadata.SummaryLayoutItem[])__typeMapper.readObject(__in, _lookupTypeInfo("summaryLayoutItems", "urn:metadata.tooling.soap.sforce.com","summaryLayoutItems","urn:metadata.tooling.soap.sforce.com","SummaryLayoutItem",0,-1,true), com.sforce.soap.tooling.metadata.SummaryLayoutItem[].class)); } } private void writeFieldSummaryLayoutItems(com.sforce.ws.parser.XmlOutputStream __out, com.sforce.ws.bind.TypeMapper __typeMapper) throws java.io.IOException { __typeMapper.writeObject(__out, _lookupTypeInfo("summaryLayoutItems", "urn:metadata.tooling.soap.sforce.com","summaryLayoutItems","urn:metadata.tooling.soap.sforce.com","SummaryLayoutItem",0,-1,true), summaryLayoutItems, summaryLayoutItems__is_set); } /** * element : summaryLayoutStyle of type {urn:tooling.soap.sforce.com}SummaryLayoutStyle * java type: com.sforce.soap.tooling.SummaryLayoutStyle */ private boolean summaryLayoutStyle__is_set = false; private com.sforce.soap.tooling.SummaryLayoutStyle summaryLayoutStyle; public com.sforce.soap.tooling.SummaryLayoutStyle getSummaryLayoutStyle() { return summaryLayoutStyle; } public void setSummaryLayoutStyle(com.sforce.soap.tooling.SummaryLayoutStyle summaryLayoutStyle) { this.summaryLayoutStyle = summaryLayoutStyle; summaryLayoutStyle__is_set = true; } protected void setSummaryLayoutStyle(com.sforce.ws.parser.XmlInputStream __in, com.sforce.ws.bind.TypeMapper __typeMapper) throws java.io.IOException, com.sforce.ws.ConnectionException { __in.peekTag(); if (__typeMapper.verifyElement(__in, _lookupTypeInfo("summaryLayoutStyle", "urn:metadata.tooling.soap.sforce.com","summaryLayoutStyle","urn:tooling.soap.sforce.com","SummaryLayoutStyle",1,1,true))) { setSummaryLayoutStyle((com.sforce.soap.tooling.SummaryLayoutStyle)__typeMapper.readObject(__in, _lookupTypeInfo("summaryLayoutStyle", "urn:metadata.tooling.soap.sforce.com","summaryLayoutStyle","urn:tooling.soap.sforce.com","SummaryLayoutStyle",1,1,true), com.sforce.soap.tooling.SummaryLayoutStyle.class)); } } private void writeFieldSummaryLayoutStyle(com.sforce.ws.parser.XmlOutputStream __out, com.sforce.ws.bind.TypeMapper __typeMapper) throws java.io.IOException { __typeMapper.writeObject(__out, _lookupTypeInfo("summaryLayoutStyle", "urn:metadata.tooling.soap.sforce.com","summaryLayoutStyle","urn:tooling.soap.sforce.com","SummaryLayoutStyle",1,1,true), summaryLayoutStyle, summaryLayoutStyle__is_set); } /** */ @Override public void write(javax.xml.namespace.QName __element, com.sforce.ws.parser.XmlOutputStream __out, com.sforce.ws.bind.TypeMapper __typeMapper) throws java.io.IOException { __out.writeStartTag(__element.getNamespaceURI(), __element.getLocalPart()); writeFields(__out, __typeMapper); __out.writeEndTag(__element.getNamespaceURI(), __element.getLocalPart()); } protected void writeFields(com.sforce.ws.parser.XmlOutputStream __out, com.sforce.ws.bind.TypeMapper __typeMapper) throws java.io.IOException { writeFields1(__out, __typeMapper); } @Override public void load(com.sforce.ws.parser.XmlInputStream __in, com.sforce.ws.bind.TypeMapper __typeMapper) throws java.io.IOException, com.sforce.ws.ConnectionException { __typeMapper.consumeStartTag(__in); loadFields(__in, __typeMapper); __typeMapper.consumeEndTag(__in); } protected void loadFields(com.sforce.ws.parser.XmlInputStream __in, com.sforce.ws.bind.TypeMapper __typeMapper) throws java.io.IOException, com.sforce.ws.ConnectionException { loadFields1(__in, __typeMapper); } @Override public String toString() { java.lang.StringBuilder sb = new java.lang.StringBuilder(); sb.append("[SummaryLayout "); toString1(sb); sb.append("]\n"); return sb.toString(); } private void toStringHelper(StringBuilder sb, String name, Object value) { sb.append(' ').append(name).append("='").append(com.sforce.ws.util.Verbose.toString(value)).append("'\n"); } private void writeFields1(com.sforce.ws.parser.XmlOutputStream __out, com.sforce.ws.bind.TypeMapper __typeMapper) throws java.io.IOException { writeFieldMasterLabel(__out, __typeMapper); writeFieldSizeX(__out, __typeMapper); writeFieldSizeY(__out, __typeMapper); writeFieldSizeZ(__out, __typeMapper); writeFieldSummaryLayoutItems(__out, __typeMapper); writeFieldSummaryLayoutStyle(__out, __typeMapper); } private void loadFields1(com.sforce.ws.parser.XmlInputStream __in, com.sforce.ws.bind.TypeMapper __typeMapper) throws java.io.IOException, com.sforce.ws.ConnectionException { setMasterLabel(__in, __typeMapper); setSizeX(__in, __typeMapper); setSizeY(__in, __typeMapper); setSizeZ(__in, __typeMapper); setSummaryLayoutItems(__in, __typeMapper); setSummaryLayoutStyle(__in, __typeMapper); } private void toString1(StringBuilder sb) { toStringHelper(sb, "masterLabel", masterLabel); toStringHelper(sb, "sizeX", sizeX); toStringHelper(sb, "sizeY", sizeY); toStringHelper(sb, "sizeZ", sizeZ); toStringHelper(sb, "summaryLayoutItems", summaryLayoutItems); toStringHelper(sb, "summaryLayoutStyle", summaryLayoutStyle); } }
UTF-8
Java
12,859
java
SummaryLayout.java
Java
[]
null
[]
package com.sforce.soap.tooling.metadata; /** * This is a generated class for the SObject Enterprise API. * Do not edit this file, as your changes will be lost. */ public class SummaryLayout implements com.sforce.ws.bind.XMLizable { /** * Constructor */ public SummaryLayout() {} /* Cache the typeInfo instead of declaring static fields throughout*/ private transient java.util.Map<String, com.sforce.ws.bind.TypeInfo> typeInfoCache = new java.util.HashMap<String, com.sforce.ws.bind.TypeInfo>(); private com.sforce.ws.bind.TypeInfo _lookupTypeInfo(String fieldName, String namespace, String name, String typeNS, String type, int minOcc, int maxOcc, boolean elementForm) { com.sforce.ws.bind.TypeInfo typeInfo = typeInfoCache.get(fieldName); if (typeInfo == null) { typeInfo = new com.sforce.ws.bind.TypeInfo(namespace, name, typeNS, type, minOcc, maxOcc, elementForm); typeInfoCache.put(fieldName, typeInfo); } return typeInfo; } /** * element : masterLabel of type {http://www.w3.org/2001/XMLSchema}string * java type: java.lang.String */ private boolean masterLabel__is_set = false; private java.lang.String masterLabel; public java.lang.String getMasterLabel() { return masterLabel; } public void setMasterLabel(java.lang.String masterLabel) { this.masterLabel = masterLabel; masterLabel__is_set = true; } protected void setMasterLabel(com.sforce.ws.parser.XmlInputStream __in, com.sforce.ws.bind.TypeMapper __typeMapper) throws java.io.IOException, com.sforce.ws.ConnectionException { __in.peekTag(); if (__typeMapper.verifyElement(__in, _lookupTypeInfo("masterLabel", "urn:metadata.tooling.soap.sforce.com","masterLabel","http://www.w3.org/2001/XMLSchema","string",1,1,true))) { setMasterLabel(__typeMapper.readString(__in, _lookupTypeInfo("masterLabel", "urn:metadata.tooling.soap.sforce.com","masterLabel","http://www.w3.org/2001/XMLSchema","string",1,1,true), java.lang.String.class)); } } private void writeFieldMasterLabel(com.sforce.ws.parser.XmlOutputStream __out, com.sforce.ws.bind.TypeMapper __typeMapper) throws java.io.IOException { __typeMapper.writeObject(__out, _lookupTypeInfo("masterLabel", "urn:metadata.tooling.soap.sforce.com","masterLabel","http://www.w3.org/2001/XMLSchema","string",1,1,true), masterLabel, masterLabel__is_set); } /** * element : sizeX of type {http://www.w3.org/2001/XMLSchema}int * java type: int */ private boolean sizeX__is_set = false; private int sizeX; public int getSizeX() { return sizeX; } public void setSizeX(int sizeX) { this.sizeX = sizeX; sizeX__is_set = true; } protected void setSizeX(com.sforce.ws.parser.XmlInputStream __in, com.sforce.ws.bind.TypeMapper __typeMapper) throws java.io.IOException, com.sforce.ws.ConnectionException { __in.peekTag(); if (__typeMapper.verifyElement(__in, _lookupTypeInfo("sizeX", "urn:metadata.tooling.soap.sforce.com","sizeX","http://www.w3.org/2001/XMLSchema","int",1,1,true))) { setSizeX((int)__typeMapper.readInt(__in, _lookupTypeInfo("sizeX", "urn:metadata.tooling.soap.sforce.com","sizeX","http://www.w3.org/2001/XMLSchema","int",1,1,true), int.class)); } } private void writeFieldSizeX(com.sforce.ws.parser.XmlOutputStream __out, com.sforce.ws.bind.TypeMapper __typeMapper) throws java.io.IOException { __typeMapper.writeObject(__out, _lookupTypeInfo("sizeX", "urn:metadata.tooling.soap.sforce.com","sizeX","http://www.w3.org/2001/XMLSchema","int",1,1,true), sizeX, sizeX__is_set); } /** * element : sizeY of type {http://www.w3.org/2001/XMLSchema}int * java type: int */ private boolean sizeY__is_set = false; private int sizeY; public int getSizeY() { return sizeY; } public void setSizeY(int sizeY) { this.sizeY = sizeY; sizeY__is_set = true; } protected void setSizeY(com.sforce.ws.parser.XmlInputStream __in, com.sforce.ws.bind.TypeMapper __typeMapper) throws java.io.IOException, com.sforce.ws.ConnectionException { __in.peekTag(); if (__typeMapper.isElement(__in, _lookupTypeInfo("sizeY", "urn:metadata.tooling.soap.sforce.com","sizeY","http://www.w3.org/2001/XMLSchema","int",0,1,true))) { setSizeY((int)__typeMapper.readInt(__in, _lookupTypeInfo("sizeY", "urn:metadata.tooling.soap.sforce.com","sizeY","http://www.w3.org/2001/XMLSchema","int",0,1,true), int.class)); } } private void writeFieldSizeY(com.sforce.ws.parser.XmlOutputStream __out, com.sforce.ws.bind.TypeMapper __typeMapper) throws java.io.IOException { __typeMapper.writeObject(__out, _lookupTypeInfo("sizeY", "urn:metadata.tooling.soap.sforce.com","sizeY","http://www.w3.org/2001/XMLSchema","int",0,1,true), sizeY, sizeY__is_set); } /** * element : sizeZ of type {http://www.w3.org/2001/XMLSchema}int * java type: int */ private boolean sizeZ__is_set = false; private int sizeZ; public int getSizeZ() { return sizeZ; } public void setSizeZ(int sizeZ) { this.sizeZ = sizeZ; sizeZ__is_set = true; } protected void setSizeZ(com.sforce.ws.parser.XmlInputStream __in, com.sforce.ws.bind.TypeMapper __typeMapper) throws java.io.IOException, com.sforce.ws.ConnectionException { __in.peekTag(); if (__typeMapper.isElement(__in, _lookupTypeInfo("sizeZ", "urn:metadata.tooling.soap.sforce.com","sizeZ","http://www.w3.org/2001/XMLSchema","int",0,1,true))) { setSizeZ((int)__typeMapper.readInt(__in, _lookupTypeInfo("sizeZ", "urn:metadata.tooling.soap.sforce.com","sizeZ","http://www.w3.org/2001/XMLSchema","int",0,1,true), int.class)); } } private void writeFieldSizeZ(com.sforce.ws.parser.XmlOutputStream __out, com.sforce.ws.bind.TypeMapper __typeMapper) throws java.io.IOException { __typeMapper.writeObject(__out, _lookupTypeInfo("sizeZ", "urn:metadata.tooling.soap.sforce.com","sizeZ","http://www.w3.org/2001/XMLSchema","int",0,1,true), sizeZ, sizeZ__is_set); } /** * element : summaryLayoutItems of type {urn:metadata.tooling.soap.sforce.com}SummaryLayoutItem * java type: com.sforce.soap.tooling.metadata.SummaryLayoutItem[] */ private boolean summaryLayoutItems__is_set = false; private com.sforce.soap.tooling.metadata.SummaryLayoutItem[] summaryLayoutItems = new com.sforce.soap.tooling.metadata.SummaryLayoutItem[0]; public com.sforce.soap.tooling.metadata.SummaryLayoutItem[] getSummaryLayoutItems() { return summaryLayoutItems; } public void setSummaryLayoutItems(com.sforce.soap.tooling.metadata.SummaryLayoutItem[] summaryLayoutItems) { this.summaryLayoutItems = summaryLayoutItems; summaryLayoutItems__is_set = true; } protected void setSummaryLayoutItems(com.sforce.ws.parser.XmlInputStream __in, com.sforce.ws.bind.TypeMapper __typeMapper) throws java.io.IOException, com.sforce.ws.ConnectionException { __in.peekTag(); if (__typeMapper.isElement(__in, _lookupTypeInfo("summaryLayoutItems", "urn:metadata.tooling.soap.sforce.com","summaryLayoutItems","urn:metadata.tooling.soap.sforce.com","SummaryLayoutItem",0,-1,true))) { setSummaryLayoutItems((com.sforce.soap.tooling.metadata.SummaryLayoutItem[])__typeMapper.readObject(__in, _lookupTypeInfo("summaryLayoutItems", "urn:metadata.tooling.soap.sforce.com","summaryLayoutItems","urn:metadata.tooling.soap.sforce.com","SummaryLayoutItem",0,-1,true), com.sforce.soap.tooling.metadata.SummaryLayoutItem[].class)); } } private void writeFieldSummaryLayoutItems(com.sforce.ws.parser.XmlOutputStream __out, com.sforce.ws.bind.TypeMapper __typeMapper) throws java.io.IOException { __typeMapper.writeObject(__out, _lookupTypeInfo("summaryLayoutItems", "urn:metadata.tooling.soap.sforce.com","summaryLayoutItems","urn:metadata.tooling.soap.sforce.com","SummaryLayoutItem",0,-1,true), summaryLayoutItems, summaryLayoutItems__is_set); } /** * element : summaryLayoutStyle of type {urn:tooling.soap.sforce.com}SummaryLayoutStyle * java type: com.sforce.soap.tooling.SummaryLayoutStyle */ private boolean summaryLayoutStyle__is_set = false; private com.sforce.soap.tooling.SummaryLayoutStyle summaryLayoutStyle; public com.sforce.soap.tooling.SummaryLayoutStyle getSummaryLayoutStyle() { return summaryLayoutStyle; } public void setSummaryLayoutStyle(com.sforce.soap.tooling.SummaryLayoutStyle summaryLayoutStyle) { this.summaryLayoutStyle = summaryLayoutStyle; summaryLayoutStyle__is_set = true; } protected void setSummaryLayoutStyle(com.sforce.ws.parser.XmlInputStream __in, com.sforce.ws.bind.TypeMapper __typeMapper) throws java.io.IOException, com.sforce.ws.ConnectionException { __in.peekTag(); if (__typeMapper.verifyElement(__in, _lookupTypeInfo("summaryLayoutStyle", "urn:metadata.tooling.soap.sforce.com","summaryLayoutStyle","urn:tooling.soap.sforce.com","SummaryLayoutStyle",1,1,true))) { setSummaryLayoutStyle((com.sforce.soap.tooling.SummaryLayoutStyle)__typeMapper.readObject(__in, _lookupTypeInfo("summaryLayoutStyle", "urn:metadata.tooling.soap.sforce.com","summaryLayoutStyle","urn:tooling.soap.sforce.com","SummaryLayoutStyle",1,1,true), com.sforce.soap.tooling.SummaryLayoutStyle.class)); } } private void writeFieldSummaryLayoutStyle(com.sforce.ws.parser.XmlOutputStream __out, com.sforce.ws.bind.TypeMapper __typeMapper) throws java.io.IOException { __typeMapper.writeObject(__out, _lookupTypeInfo("summaryLayoutStyle", "urn:metadata.tooling.soap.sforce.com","summaryLayoutStyle","urn:tooling.soap.sforce.com","SummaryLayoutStyle",1,1,true), summaryLayoutStyle, summaryLayoutStyle__is_set); } /** */ @Override public void write(javax.xml.namespace.QName __element, com.sforce.ws.parser.XmlOutputStream __out, com.sforce.ws.bind.TypeMapper __typeMapper) throws java.io.IOException { __out.writeStartTag(__element.getNamespaceURI(), __element.getLocalPart()); writeFields(__out, __typeMapper); __out.writeEndTag(__element.getNamespaceURI(), __element.getLocalPart()); } protected void writeFields(com.sforce.ws.parser.XmlOutputStream __out, com.sforce.ws.bind.TypeMapper __typeMapper) throws java.io.IOException { writeFields1(__out, __typeMapper); } @Override public void load(com.sforce.ws.parser.XmlInputStream __in, com.sforce.ws.bind.TypeMapper __typeMapper) throws java.io.IOException, com.sforce.ws.ConnectionException { __typeMapper.consumeStartTag(__in); loadFields(__in, __typeMapper); __typeMapper.consumeEndTag(__in); } protected void loadFields(com.sforce.ws.parser.XmlInputStream __in, com.sforce.ws.bind.TypeMapper __typeMapper) throws java.io.IOException, com.sforce.ws.ConnectionException { loadFields1(__in, __typeMapper); } @Override public String toString() { java.lang.StringBuilder sb = new java.lang.StringBuilder(); sb.append("[SummaryLayout "); toString1(sb); sb.append("]\n"); return sb.toString(); } private void toStringHelper(StringBuilder sb, String name, Object value) { sb.append(' ').append(name).append("='").append(com.sforce.ws.util.Verbose.toString(value)).append("'\n"); } private void writeFields1(com.sforce.ws.parser.XmlOutputStream __out, com.sforce.ws.bind.TypeMapper __typeMapper) throws java.io.IOException { writeFieldMasterLabel(__out, __typeMapper); writeFieldSizeX(__out, __typeMapper); writeFieldSizeY(__out, __typeMapper); writeFieldSizeZ(__out, __typeMapper); writeFieldSummaryLayoutItems(__out, __typeMapper); writeFieldSummaryLayoutStyle(__out, __typeMapper); } private void loadFields1(com.sforce.ws.parser.XmlInputStream __in, com.sforce.ws.bind.TypeMapper __typeMapper) throws java.io.IOException, com.sforce.ws.ConnectionException { setMasterLabel(__in, __typeMapper); setSizeX(__in, __typeMapper); setSizeY(__in, __typeMapper); setSizeZ(__in, __typeMapper); setSummaryLayoutItems(__in, __typeMapper); setSummaryLayoutStyle(__in, __typeMapper); } private void toString1(StringBuilder sb) { toStringHelper(sb, "masterLabel", masterLabel); toStringHelper(sb, "sizeX", sizeX); toStringHelper(sb, "sizeY", sizeY); toStringHelper(sb, "sizeZ", sizeZ); toStringHelper(sb, "summaryLayoutItems", summaryLayoutItems); toStringHelper(sb, "summaryLayoutStyle", summaryLayoutStyle); } }
12,859
0.698266
0.6887
273
46.102566
59.250111
344
false
false
0
0
0
0
0
0
1.190476
false
false
14
879b3c843da2446b00b2e56076153c0f8b2c79e3
26,353,919,369,044
a29bfc235940b347b08f4dc10aff687d3cc077d9
/app/src/androidTest/java/com/bingerdranch/android/series_guide/Database_test.java
328a39f08046dc4729f79a146e343fb87069b1bd
[]
no_license
mikyascoder/Series-guide
https://github.com/mikyascoder/Series-guide
1224914f4225f3d13729be478ab9b51c37dbe752
0d767c022635254a5a3c77b40937f091cc6e47be
refs/heads/master
2020-04-08T21:40:51.599000
2018-11-30T02:26:55
2018-11-30T02:26:55
159,753,939
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bingerdranch.android.series_guide; import android.arch.persistence.room.Room; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import android.util.Log; import com.bingerdranch.android.series_guide.Database.AppDatabase; import com.bingerdranch.android.series_guide.Database.SeriesDao; import com.bingerdranch.android.series_guide.util.MockFactory; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.assertEquals; @RunWith(AndroidJUnit4.class) public class Database_test { public static final String TAG="Junit"; private AppDatabase mDb; private SeriesDao mDao; @Before public void createDb(){ Context context = InstrumentationRegistry.getTargetContext(); mDb= Room.inMemoryDatabaseBuilder(context,AppDatabase.class).build(); mDao = mDb.seriesDao(); Log.i(TAG,"createDb"); } @After public void closeDb(){ mDb.close(); Log.i(TAG,"closeDb"); } @Test public void createAndRetrieveNotes(){ mDao.insertall((MockFactory.getMockedSerieListfordb())); int count= mDao.getcount(); Log.i(TAG,"CreateAndRetrieveNotes: count="+ count); assertEquals(MockFactory.getMockedSerieListfordb().size(), count); } }
UTF-8
Java
1,414
java
Database_test.java
Java
[]
null
[]
package com.bingerdranch.android.series_guide; import android.arch.persistence.room.Room; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import android.util.Log; import com.bingerdranch.android.series_guide.Database.AppDatabase; import com.bingerdranch.android.series_guide.Database.SeriesDao; import com.bingerdranch.android.series_guide.util.MockFactory; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.assertEquals; @RunWith(AndroidJUnit4.class) public class Database_test { public static final String TAG="Junit"; private AppDatabase mDb; private SeriesDao mDao; @Before public void createDb(){ Context context = InstrumentationRegistry.getTargetContext(); mDb= Room.inMemoryDatabaseBuilder(context,AppDatabase.class).build(); mDao = mDb.seriesDao(); Log.i(TAG,"createDb"); } @After public void closeDb(){ mDb.close(); Log.i(TAG,"closeDb"); } @Test public void createAndRetrieveNotes(){ mDao.insertall((MockFactory.getMockedSerieListfordb())); int count= mDao.getcount(); Log.i(TAG,"CreateAndRetrieveNotes: count="+ count); assertEquals(MockFactory.getMockedSerieListfordb().size(), count); } }
1,414
0.72843
0.727016
50
27.280001
23.098953
77
false
false
0
0
0
0
0
0
0.64
false
false
14
ba3c89efc94359a1e717cdec998f882d237ef0f8
6,313,601,942,195
4bdab2bffe301203f725a4619c24a16cf6675cdf
/src/com/example/HomeTest/RegexExample.java
26ef4493ff227a8b49986d32f04fcb5567c13c8f
[]
no_license
masaDigitalRealEstate/Algorithms
https://github.com/masaDigitalRealEstate/Algorithms
40d0c0d98395c47a5027b27fc86342cdabc77f1b
af40448af2fa7cecf95d8380d5edae99a8b7ec65
refs/heads/master
2020-12-13T04:32:13.015000
2017-06-26T06:04:29
2017-06-26T06:04:29
95,411,984
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.HomeTest; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.MatchResult; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExample { private static final String VAR_REGEX = "[a-zA-Z]\\w{0,100}"; private static final String BIN_OPERATOR = "\\+|-|\\*|/|%|^"; private static final String NUM_REGEX = "\\d*"; //private static final String UNARY_REGEX = "(\\w+(\\+{2}|-{2}))|((\\+{2}|-{2})\\w+)"; //private static final Pattern UNARY_PATTERN = Pattern.compile(UNARY_REGEX); //private static final String PLUS_MINUS_REGEX = "((?<!\\+{1})\\+{1}(?!\\+{1}))|(?<!-{1})(-{1}(?!-{1}))"; private static final String PLUS_SEPERATOR_REGEX = "(?<!\\+{1})\\+{1}(?!\\+{1}))"; private static final String MINUS_SEPERATOR_REGEX = "(?<!-{1})(-{1}(?!-{1})"; private static final String PLUS_MINUS_REGEX = "(" + PLUS_SEPERATOR_REGEX + "|" + MINUS_SEPERATOR_REGEX +")"; private static final String NUMBERS_REGEX = "\\d+"; private static final String UNARY_PREFIX_OPERATOR = "(^(-{1})" + "((" + VAR_REGEX + ")" + "|(" + NUMBERS_REGEX + "))$)"; private static final Pattern UNARY_PREFIX_PATTERN = Pattern.compile(UNARY_PREFIX_OPERATOR); private static final String UNARY_REGEX = "(" + VAR_REGEX + "(\\+{2}|-{2}))|((\\+{2}|-{2})" + VAR_REGEX +" )"; private static final Pattern UNARY_PATTERN = Pattern.compile(UNARY_REGEX); private static final String DELIMITERS_REGEX = "[()\\/*%^=]"; private static final String ASSIGNMENT_OPERATORS_REGEX = "(\\+{1}|-{1}|\\*{1}|\\/{1})(\\={1})"; private static final String ASSIGNMENT_SPLIT_OPERATORS_REGEX = "((?<=" + ASSIGNMENT_OPERATORS_REGEX +")|(?=" + ASSIGNMENT_OPERATORS_REGEX +"))"; private static final Pattern ASSIGNMENT_OPERATORS_PATTERN = Pattern.compile(ASSIGNMENT_OPERATORS_REGEX); private static final String FULL_SPLIT_REGEX = "(" + ASSIGNMENT_SPLIT_OPERATORS_REGEX + ")" + "|(" + DELIMITERS_REGEX + ")" +"|(" + UNARY_REGEX + ")" + "|(" + PLUS_MINUS_REGEX + ")"; private static final String ILLEGAL_UNARY_REGEX = "(^\\d+\\w*(\\+{2}|-{2}))|(^(\\+{2}|-{2})\\d+\\w*)"; private static final Pattern ILLEGAL_UNARY_PATTERN = Pattern.compile(ILLEGAL_UNARY_REGEX); private static final String ASSIGNMENT_REGEX = "(=)"; private static final String ASSIGNMENTS_REGEX = "(" + ASSIGNMENT_REGEX + ")|(" + ASSIGNMENT_OPERATORS_REGEX + ")" ; private static final String SPACES_REGEX= "\\s*"; private static final String ANYTHING_REGEX = ".*"; private static final Pattern ASSIGNMENT_PATTERN = Pattern.compile(ASSIGNMENT_REGEX); //(?<assignment>(" + ASSIGNMENT_REGEX + ")|(" + ASSIGNMENT_OPERATORS_REGEX + "))"; //(?<expression>(.)) private static final String EXPRESSION_REGEX = "(" + SPACES_REGEX + ")(?<var>" + VAR_REGEX + ")(" + SPACES_REGEX + ")(?<assign>" + ASSIGNMENTS_REGEX + ")(" + SPACES_REGEX + ")(?<expression>" + ANYTHING_REGEX + ")"; private static final Pattern VAR_PATTERN = Pattern.compile(VAR_REGEX); private static final String REGEX = "#\\w+"; private static final String EXP_TEST = "(?<="+ REGEX+ ")|(?=" + REGEX + ")"; /* public static void main(String[] args) { // Matcher matcher = ASSIGNMENT_OPERATORS_PATTERN.matches("y += 5 +2"); //Matcher matcher =r ILLEGAL_UNARY_PATTERN.matcher("67676--"); //Matcher matcher = ASSIGNMENT_PATTERN.matcher("="); //Matcher matcher = ASSIGNMENT_OPERATORS_PATTERN.matcher("+="); //System.out.println(matcher.matches()); //todo validate 2 foolowing operators or operands are not valid //todo if someone put illegal char it is not valid look for illegal chars in the string like \.. String a = "y += 5 +2"; String[] str = splitExpression(a); for (int i = 0; i < str.length; i++) { System.out.println(str[i]); } }*/ //check validation of +- public static String[] splitExpression(String str) { String[] s1 = str.split(" "); List<String> list = new ArrayList<>(); for (String s : s1) { String[] splitted = null; /*if(!ASSIGNMENT_OPERATORS_PATTERN.matcher(s).matches()) { splitted = s.split("(?<=" + FULL_SPLIT_REGEX + ")|(?=" + FULL_SPLIT_REGEX + ")"); list.addAll(Arrays.asList(splitted)); } else{ list.add(s); }*/ splitted = s.split("(?<="+ FULL_SPLIT_REGEX+ ")|(?=" + FULL_SPLIT_REGEX + ")"); list.addAll(Arrays.asList(splitted)); } //..String[] splitted = str.replaceAll("\\s+","").split("(?<=[()\\/*%^=+-])|(?=[()\\/*%^=+-])"); String[] retArray = new String[list.size()]; retArray = list.toArray(retArray); return retArray; } public static void main(String[] args) { // Matcher matcher = Pattern.compile(VAR_REGEX).matcher("a123&"); //MatchResult matchResult = matcher.toMatchResult(); //if(matcher.matches()) { // System.out.println("yes"); //} String s = "#Séjour Hôtel Sol Jandia Mar Appartements *** #Fuerteventura 19.avr.15 8j/7n(889€/p) ✈ #Paris #AllInClusive http://t.co/YfEkoRPy6B"; String[] splitted = s.split(EXP_TEST); List<String> ls = Arrays.asList(splitted); System.out.println(ls); System.exit(0); } //split by + if ++ exist attach it to either left or right // private static final String PLUSMINUS_REGEX = "([^+])(\\+{2})([^+])";//"(\\w+(\\+{2}|-{2}))|((\\+{2}|-{2})\\w+)"; // private static final Pattern PLUSMINUS_PATTERN = Pattern.compile(PLUSMINUS_REGEX); // private static String[] splitPlusMinus(String s){ //} }
UTF-8
Java
5,819
java
RegexExample.java
Java
[ { "context": "(\"yes\");\n //}\n\n String s = \"#Séjour Hôtel Sol Jandia Mar Appartements *** #Fuerteventura 19.avr", "end": 5191, "score": 0.999688982963562, "start": 5182, "tag": "NAME", "value": "Hôtel Sol" }, { "context": " //}\n\n String s = \"#Séjour...
null
[]
package com.example.HomeTest; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.MatchResult; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExample { private static final String VAR_REGEX = "[a-zA-Z]\\w{0,100}"; private static final String BIN_OPERATOR = "\\+|-|\\*|/|%|^"; private static final String NUM_REGEX = "\\d*"; //private static final String UNARY_REGEX = "(\\w+(\\+{2}|-{2}))|((\\+{2}|-{2})\\w+)"; //private static final Pattern UNARY_PATTERN = Pattern.compile(UNARY_REGEX); //private static final String PLUS_MINUS_REGEX = "((?<!\\+{1})\\+{1}(?!\\+{1}))|(?<!-{1})(-{1}(?!-{1}))"; private static final String PLUS_SEPERATOR_REGEX = "(?<!\\+{1})\\+{1}(?!\\+{1}))"; private static final String MINUS_SEPERATOR_REGEX = "(?<!-{1})(-{1}(?!-{1})"; private static final String PLUS_MINUS_REGEX = "(" + PLUS_SEPERATOR_REGEX + "|" + MINUS_SEPERATOR_REGEX +")"; private static final String NUMBERS_REGEX = "\\d+"; private static final String UNARY_PREFIX_OPERATOR = "(^(-{1})" + "((" + VAR_REGEX + ")" + "|(" + NUMBERS_REGEX + "))$)"; private static final Pattern UNARY_PREFIX_PATTERN = Pattern.compile(UNARY_PREFIX_OPERATOR); private static final String UNARY_REGEX = "(" + VAR_REGEX + "(\\+{2}|-{2}))|((\\+{2}|-{2})" + VAR_REGEX +" )"; private static final Pattern UNARY_PATTERN = Pattern.compile(UNARY_REGEX); private static final String DELIMITERS_REGEX = "[()\\/*%^=]"; private static final String ASSIGNMENT_OPERATORS_REGEX = "(\\+{1}|-{1}|\\*{1}|\\/{1})(\\={1})"; private static final String ASSIGNMENT_SPLIT_OPERATORS_REGEX = "((?<=" + ASSIGNMENT_OPERATORS_REGEX +")|(?=" + ASSIGNMENT_OPERATORS_REGEX +"))"; private static final Pattern ASSIGNMENT_OPERATORS_PATTERN = Pattern.compile(ASSIGNMENT_OPERATORS_REGEX); private static final String FULL_SPLIT_REGEX = "(" + ASSIGNMENT_SPLIT_OPERATORS_REGEX + ")" + "|(" + DELIMITERS_REGEX + ")" +"|(" + UNARY_REGEX + ")" + "|(" + PLUS_MINUS_REGEX + ")"; private static final String ILLEGAL_UNARY_REGEX = "(^\\d+\\w*(\\+{2}|-{2}))|(^(\\+{2}|-{2})\\d+\\w*)"; private static final Pattern ILLEGAL_UNARY_PATTERN = Pattern.compile(ILLEGAL_UNARY_REGEX); private static final String ASSIGNMENT_REGEX = "(=)"; private static final String ASSIGNMENTS_REGEX = "(" + ASSIGNMENT_REGEX + ")|(" + ASSIGNMENT_OPERATORS_REGEX + ")" ; private static final String SPACES_REGEX= "\\s*"; private static final String ANYTHING_REGEX = ".*"; private static final Pattern ASSIGNMENT_PATTERN = Pattern.compile(ASSIGNMENT_REGEX); //(?<assignment>(" + ASSIGNMENT_REGEX + ")|(" + ASSIGNMENT_OPERATORS_REGEX + "))"; //(?<expression>(.)) private static final String EXPRESSION_REGEX = "(" + SPACES_REGEX + ")(?<var>" + VAR_REGEX + ")(" + SPACES_REGEX + ")(?<assign>" + ASSIGNMENTS_REGEX + ")(" + SPACES_REGEX + ")(?<expression>" + ANYTHING_REGEX + ")"; private static final Pattern VAR_PATTERN = Pattern.compile(VAR_REGEX); private static final String REGEX = "#\\w+"; private static final String EXP_TEST = "(?<="+ REGEX+ ")|(?=" + REGEX + ")"; /* public static void main(String[] args) { // Matcher matcher = ASSIGNMENT_OPERATORS_PATTERN.matches("y += 5 +2"); //Matcher matcher =r ILLEGAL_UNARY_PATTERN.matcher("67676--"); //Matcher matcher = ASSIGNMENT_PATTERN.matcher("="); //Matcher matcher = ASSIGNMENT_OPERATORS_PATTERN.matcher("+="); //System.out.println(matcher.matches()); //todo validate 2 foolowing operators or operands are not valid //todo if someone put illegal char it is not valid look for illegal chars in the string like \.. String a = "y += 5 +2"; String[] str = splitExpression(a); for (int i = 0; i < str.length; i++) { System.out.println(str[i]); } }*/ //check validation of +- public static String[] splitExpression(String str) { String[] s1 = str.split(" "); List<String> list = new ArrayList<>(); for (String s : s1) { String[] splitted = null; /*if(!ASSIGNMENT_OPERATORS_PATTERN.matcher(s).matches()) { splitted = s.split("(?<=" + FULL_SPLIT_REGEX + ")|(?=" + FULL_SPLIT_REGEX + ")"); list.addAll(Arrays.asList(splitted)); } else{ list.add(s); }*/ splitted = s.split("(?<="+ FULL_SPLIT_REGEX+ ")|(?=" + FULL_SPLIT_REGEX + ")"); list.addAll(Arrays.asList(splitted)); } //..String[] splitted = str.replaceAll("\\s+","").split("(?<=[()\\/*%^=+-])|(?=[()\\/*%^=+-])"); String[] retArray = new String[list.size()]; retArray = list.toArray(retArray); return retArray; } public static void main(String[] args) { // Matcher matcher = Pattern.compile(VAR_REGEX).matcher("a123&"); //MatchResult matchResult = matcher.toMatchResult(); //if(matcher.matches()) { // System.out.println("yes"); //} String s = "#Séjour <NAME> <NAME> *** #Fuerteventura 19.avr.15 8j/7n(889€/p) ✈ #Paris #AllInClusive http://t.co/YfEkoRPy6B"; String[] splitted = s.split(EXP_TEST); List<String> ls = Arrays.asList(splitted); System.out.println(ls); System.exit(0); } //split by + if ++ exist attach it to either left or right // private static final String PLUSMINUS_REGEX = "([^+])(\\+{2})([^+])";//"(\\w+(\\+{2}|-{2}))|((\\+{2}|-{2})\\w+)"; // private static final Pattern PLUSMINUS_PATTERN = Pattern.compile(PLUSMINUS_REGEX); // private static String[] splitPlusMinus(String s){ //} }
5,798
0.586272
0.574918
146
38.815067
43.306648
218
false
false
0
0
0
0
0
0
0.726027
false
false
14
4da86f4993197895abdb1519b6d90fff101b2bd6
11,819,750,004,696
3b7c79c7670a66fcc589fb0f0fbe28d55412edf3
/src/test/java/com/SetUpAppium.java
4f80d4e34821d4746798b89267fea2b5170aa172
[]
no_license
Grosha/gotoshop
https://github.com/Grosha/gotoshop
f16c634ebb66ee75f0e690e6b516da780b2f6416
0775f9aca163211a2ff676826fc4ca2b1ee3a9d3
refs/heads/master
2020-07-26T08:04:17.243000
2017-04-20T10:50:14
2017-04-20T10:50:14
73,728,264
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com; import io.appium.java_client.android.AndroidDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.testng.annotations.*; import java.net.MalformedURLException; import java.net.URL; import java.util.concurrent.TimeUnit; /** * Created by groshkka on 02.12.2016. */ public class SetUpAppium implements Variable, Locators { protected AndroidDriver driver; @BeforeMethod public void setUp() throws MalformedURLException { DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setCapability("deviceName", "Android Emulator"); capabilities.setCapability("platformVersion", "6.0"); capabilities.setCapability("appPackage", packageGoToShop); capabilities.setCapability("appWaitPackage", packageGoToShop); capabilities.setCapability("appActivity", mainActivity); driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); } @AfterMethod public void setDown() { driver.quit(); } }
UTF-8
Java
1,119
java
SetUpAppium.java
Java
[ { "context": " java.util.concurrent.TimeUnit;\n\n/**\n * Created by groshkka on 02.12.2016.\n */\npublic class SetUpAppium imple", "end": 280, "score": 0.9996776580810547, "start": 272, "tag": "USERNAME", "value": "groshkka" }, { "context": " driver = new AndroidDriver(new URL(...
null
[]
package com; import io.appium.java_client.android.AndroidDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.testng.annotations.*; import java.net.MalformedURLException; import java.net.URL; import java.util.concurrent.TimeUnit; /** * Created by groshkka on 02.12.2016. */ public class SetUpAppium implements Variable, Locators { protected AndroidDriver driver; @BeforeMethod public void setUp() throws MalformedURLException { DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setCapability("deviceName", "Android Emulator"); capabilities.setCapability("platformVersion", "6.0"); capabilities.setCapability("appPackage", packageGoToShop); capabilities.setCapability("appWaitPackage", packageGoToShop); capabilities.setCapability("appActivity", mainActivity); driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); } @AfterMethod public void setDown() { driver.quit(); } }
1,119
0.724754
0.705988
34
31.911764
27.376856
90
false
false
0
0
0
0
0
0
0.735294
false
false
14
ad58f09cbb87d9e9d881018202ba09a45f8e275f
11,819,750,006,447
5309078ffd0bab52904a634ec1286cdf1844057f
/integridad-api/src/main/java/com/mrzolution/integridad/app/domain/Subsidiary.java
63c398e9fc543ebbf44e4f6747b24701fca3b55a
[]
no_license
mrZolutions/Integridad
https://github.com/mrZolutions/Integridad
275e02004faadc997d9490ab791ac13254c4c3a4
094eebb4293ad38ed914f35a0f64f5bdd358be8d
refs/heads/master
2023-03-07T13:35:38.510000
2023-02-25T01:08:23
2023-02-25T01:08:23
94,840,653
0
0
null
false
2023-02-25T01:09:48
2017-06-20T02:21:51
2022-04-27T00:50:30
2023-02-25T01:09:47
23,103
0
0
8
HTML
false
false
package com.mrzolution.integridad.app.domain; import java.util.ArrayList; import java.util.List; import java.util.UUID; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Transient; import com.mrzolution.integridad.app.interfaces.Child; import lombok.Data; import org.hibernate.annotations.Type; /** * Created by daniel. */ @Entity @Data public class Subsidiary implements Child{ @Id @GeneratedValue private UUID id; private String name; private String threeCode; private String celPhone; private String phone; private String city; private String address1; private String address2; private long billNumberSeq; private long dateCreated; private boolean active; private boolean online; private boolean offline; private boolean contab; private boolean cxc; private boolean cxp; private boolean kar; private boolean swimm; @ManyToOne @JoinColumn(name = "user_client_id") private UserClient userClient; @OneToMany(mappedBy = "subsidiary", cascade = CascadeType.ALL) private List<UserIntegridad> users; @OneToMany(mappedBy = "subsidiary", cascade = CascadeType.ALL) private List<Cashier> cashiers; @OneToMany(mappedBy = "subsidiary", cascade = CascadeType.ALL) private List<Warehouse> warehouses; public void setListsNull(){ users = null; cashiers = null; warehouses = null; } public void setFatherListToNull(){ userClient.setListsNull(); userClient.setFatherListToNull(); } @Transient public static Subsidiary newSubsidiaryTest(){ Subsidiary subsidiary = new Subsidiary(); subsidiary.setUserClient(UserClient.newUserClientTest()); subsidiary.setUsers(new ArrayList<>()); subsidiary.setCashiers(new ArrayList<>()); subsidiary.setWarehouses(new ArrayList<>()); return subsidiary; } }
UTF-8
Java
2,191
java
Subsidiary.java
Java
[ { "context": "org.hibernate.annotations.Type;\n\n/**\n * Created by daniel.\n */\n@Entity\n@Data\npublic class Subsidiary imp", "end": 546, "score": 0.9155746102333069, "start": 543, "tag": "NAME", "value": "dan" }, { "context": "hibernate.annotations.Type;\n\n/**\n * Created by dani...
null
[]
package com.mrzolution.integridad.app.domain; import java.util.ArrayList; import java.util.List; import java.util.UUID; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Transient; import com.mrzolution.integridad.app.interfaces.Child; import lombok.Data; import org.hibernate.annotations.Type; /** * Created by daniel. */ @Entity @Data public class Subsidiary implements Child{ @Id @GeneratedValue private UUID id; private String name; private String threeCode; private String celPhone; private String phone; private String city; private String address1; private String address2; private long billNumberSeq; private long dateCreated; private boolean active; private boolean online; private boolean offline; private boolean contab; private boolean cxc; private boolean cxp; private boolean kar; private boolean swimm; @ManyToOne @JoinColumn(name = "user_client_id") private UserClient userClient; @OneToMany(mappedBy = "subsidiary", cascade = CascadeType.ALL) private List<UserIntegridad> users; @OneToMany(mappedBy = "subsidiary", cascade = CascadeType.ALL) private List<Cashier> cashiers; @OneToMany(mappedBy = "subsidiary", cascade = CascadeType.ALL) private List<Warehouse> warehouses; public void setListsNull(){ users = null; cashiers = null; warehouses = null; } public void setFatherListToNull(){ userClient.setListsNull(); userClient.setFatherListToNull(); } @Transient public static Subsidiary newSubsidiaryTest(){ Subsidiary subsidiary = new Subsidiary(); subsidiary.setUserClient(UserClient.newUserClientTest()); subsidiary.setUsers(new ArrayList<>()); subsidiary.setCashiers(new ArrayList<>()); subsidiary.setWarehouses(new ArrayList<>()); return subsidiary; } }
2,191
0.701963
0.70105
89
23.629213
17.979002
66
false
false
0
0
0
0
0
0
0.595506
false
false
14
45dbbba909073aad1ce069c69dc82a7658c7dd56
17,188,459,124,538
92667408bd3439a48fbf78ca65df7813286e7a53
/src/unit5/FilterTest.java
0007a21ae2eaf532000bc2d8a584f6f492d59707
[]
no_license
yeahseol/JavaStudy
https://github.com/yeahseol/JavaStudy
288f4d2d3900a50c0a7e8aa83c6e29558d5f1e47
a0edbdf6f6d818680cf99f412f8a02af7c5473ff
refs/heads/master
2016-09-22T09:58:35.929000
2016-08-26T09:46:08
2016-08-26T09:46:08
64,109,933
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package unit5; import java.io.IOException; import java.util.logging.*; /** * Created by Seolmin on 2016-08-05. */ public class FilterTest implements Filter { @Override public boolean isLoggable(LogRecord record){ if(record.getMessage().contains("섹스")) return false; return true; } public static void main(String[] args) throws IOException { Filter ft = new FilterTest(); Formatter lt = new LogTest(); Logger logger = Logger.getLogger("LogTest"); logger.setLevel(Level.ALL); logger.setUseParentHandlers(false); FileHandler fileHandler = new FileHandler(); fileHandler.setLevel(Level.ALL); fileHandler.setFormatter(lt); fileHandler.setFilter(ft); logger.addHandler(fileHandler); logger.fine("마약 트럼피아 화이팅 C++"); } }
UTF-8
Java
871
java
FilterTest.java
Java
[ { "context": ";\nimport java.util.logging.*;\n\n\n\n/**\n * Created by Seolmin on 2016-08-05.\n */\npublic class FilterTest implem", "end": 100, "score": 0.9989861845970154, "start": 93, "tag": "NAME", "value": "Seolmin" } ]
null
[]
package unit5; import java.io.IOException; import java.util.logging.*; /** * Created by Seolmin on 2016-08-05. */ public class FilterTest implements Filter { @Override public boolean isLoggable(LogRecord record){ if(record.getMessage().contains("섹스")) return false; return true; } public static void main(String[] args) throws IOException { Filter ft = new FilterTest(); Formatter lt = new LogTest(); Logger logger = Logger.getLogger("LogTest"); logger.setLevel(Level.ALL); logger.setUseParentHandlers(false); FileHandler fileHandler = new FileHandler(); fileHandler.setLevel(Level.ALL); fileHandler.setFormatter(lt); fileHandler.setFilter(ft); logger.addHandler(fileHandler); logger.fine("마약 트럼피아 화이팅 C++"); } }
871
0.644287
0.633687
37
21.972973
20.686184
63
false
false
0
0
0
0
0
0
0.432432
false
false
14
38fb6365b6b453abfb4cfb5f33b9a37464294830
17,188,459,124,298
cd4c08da17625ace68a52c776102b7c41818b40e
/src/main/java/com/minotaur/match/IntegerArray.java
7287f1a197f36bc290d57ccb09c0a3cbaa21d5af
[]
no_license
minotaursu/cat
https://github.com/minotaursu/cat
a341d76444b363e2ae83e924fda5c0a221c0dd4d
da65c682f3c7e3ccefc9549d2c4ff63f161105bc
refs/heads/master
2021-01-18T23:14:01.349000
2019-03-06T07:36:59
2019-03-06T07:36:59
7,233,790
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.minotaur.match; /** * ******************************** * Created by minotaur on 2018/8/23. * * ******************************** */ public class IntegerArray { public static void main(String[] args) { int[] array = { 1, 0, 2, 1, 2, 1 }; int[] arrayB = { 2, 2, 2, 1, 1, 0, 0 }; for (int i = 0; i < array.length; i++) { System.out.print(array[i]); } System.out.println(); for (int i = 0; i < arrayB.length; i++) { System.out.print(arrayB[i]); } arrayB = array; System.out.println(); for (int i = 0; i < arrayB.length; i++) { System.out.print(arrayB[i]); } } }
UTF-8
Java
708
java
IntegerArray.java
Java
[ { "context": "\n * ********************************\n * Created by minotaur on 2018/8/23. *\n * ******************************", "end": 91, "score": 0.9995817542076111, "start": 83, "tag": "USERNAME", "value": "minotaur" } ]
null
[]
package com.minotaur.match; /** * ******************************** * Created by minotaur on 2018/8/23. * * ******************************** */ public class IntegerArray { public static void main(String[] args) { int[] array = { 1, 0, 2, 1, 2, 1 }; int[] arrayB = { 2, 2, 2, 1, 1, 0, 0 }; for (int i = 0; i < array.length; i++) { System.out.print(array[i]); } System.out.println(); for (int i = 0; i < arrayB.length; i++) { System.out.print(arrayB[i]); } arrayB = array; System.out.println(); for (int i = 0; i < arrayB.length; i++) { System.out.print(arrayB[i]); } } }
708
0.426554
0.394068
27
25.222221
17.737453
49
false
false
0
0
0
0
0
0
0.962963
false
false
14
c50ed413e912b1064a1dfc2c300f7bb631e4072a
18,597,208,399,979
1632a9e9c0f0775293878ce07a36802f2055959e
/src/task/line_task/task14/Circle.java
c03eb7e2a7fb64a77a6fe5e86a536070cc3e9316
[]
no_license
OsipchikMinsk/Java_EPAM_Intro_To_Java
https://github.com/OsipchikMinsk/Java_EPAM_Intro_To_Java
7947ec42c15238ad89f8707233fe74541de0f5c3
7ccb783164ad85a97ab73742b499f6995fa3a8ae
refs/heads/master
2020-07-31T13:08:26.658000
2019-10-02T04:31:10
2019-10-02T04:31:10
210,605,673
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package line_task.task14; import static java.lang.Math.pow; /* Вычислить длинну иплощадь круга одного и того же заданного радиуса R */ public class Circle { private static double lengthOfCircle (int r){ return 2*3.14*r; } private static double areaOfCircle (int r){ return 3.14*pow(r,2.0); } public static void main(String[] args) { int radius = 10; double lengthOfCircle = Circle.lengthOfCircle(radius); double areaOfCircle = Circle.areaOfCircle(radius); System.out.printf("Length of circle %f\n",lengthOfCircle); System.out.printf("Area of circle %f",areaOfCircle); } }
UTF-8
Java
712
java
Circle.java
Java
[]
null
[]
package line_task.task14; import static java.lang.Math.pow; /* Вычислить длинну иплощадь круга одного и того же заданного радиуса R */ public class Circle { private static double lengthOfCircle (int r){ return 2*3.14*r; } private static double areaOfCircle (int r){ return 3.14*pow(r,2.0); } public static void main(String[] args) { int radius = 10; double lengthOfCircle = Circle.lengthOfCircle(radius); double areaOfCircle = Circle.areaOfCircle(radius); System.out.printf("Length of circle %f\n",lengthOfCircle); System.out.printf("Area of circle %f",areaOfCircle); } }
712
0.664122
0.644275
23
27.47826
24.064894
68
false
false
0
0
0
0
0
0
0.521739
false
false
14
b9bd1d8ec693d3797488bdbb325d302bb284abe3
23,871,428,239,295
9d03f540d3f3da67260dc63b59a61e5a2fbd6cf2
/src/main/java/com/hospital/web/service/PatientService.java
31a0d353bd91653ffd3988284ed0aa3edb67c716
[]
no_license
rufruv/hospitalSpring
https://github.com/rufruv/hospitalSpring
c1c145bb6993b1536fe81aacc61479c9ab28fd60
4ce1bc4831de8239033bee54a5583a08a8570797
refs/heads/master
2021-01-22T23:53:55.692000
2017-03-28T02:37:09
2017-03-28T02:37:09
85,677,653
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hospital.web.service; import org.springframework.stereotype.Component; import com.hospital.web.domain.PatientDTO; @Component public interface PatientService { // DAO 값을 토스해 주는 로직 public int join(PatientDTO member) throws Exception; public PatientDTO findById(String id) throws Exception; public PatientDTO login(PatientDTO member) throws Exception; public boolean logout() throws Exception; public int change(PatientDTO member) throws Exception; public int remove(PatientDTO member) throws Exception; // 추가되는 로직 public String getBirth(String patJumin); public String getAge(String patJumin); public PatientDTO getSession(); public int count() throws Exception; }
UTF-8
Java
730
java
PatientService.java
Java
[]
null
[]
package com.hospital.web.service; import org.springframework.stereotype.Component; import com.hospital.web.domain.PatientDTO; @Component public interface PatientService { // DAO 값을 토스해 주는 로직 public int join(PatientDTO member) throws Exception; public PatientDTO findById(String id) throws Exception; public PatientDTO login(PatientDTO member) throws Exception; public boolean logout() throws Exception; public int change(PatientDTO member) throws Exception; public int remove(PatientDTO member) throws Exception; // 추가되는 로직 public String getBirth(String patJumin); public String getAge(String patJumin); public PatientDTO getSession(); public int count() throws Exception; }
730
0.79
0.79
20
34
19.745886
62
false
false
0
0
0
0
0
0
1.8
false
false
14
280367cfc3db952fce66cfa4dd13cb215005ee1d
523,986,020,297
c1876d7a77ac2da0c8feabd833202cf9fc637c93
/TippDesTagesClient.java
bb6ca6abe38ad9399ed471f46de29f2b8a75dc48
[]
no_license
infSloe/TippClient
https://github.com/infSloe/TippClient
073c209235cde1838347749c75426681896096b6
42eb699b8e99f6fc7cb91aef9aa14e49d7c104b3
refs/heads/master
2020-04-08T07:34:59.670000
2018-11-26T09:35:34
2018-11-26T09:35:34
159,143,928
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// aus Java von Kopf bis Fu8 import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.Socket; public class TippDesTagesClient { String serverAdresse; int portNummer; public TippDesTagesClient() { serverAdresse = "127.0.0.1"; //Localhost // Ersetze diese Adresse! portNummer = 4242; } public String neuerTipp() { String tipp = ""; try { Socket socket = new Socket(serverAdresse, portNummer); InputStreamReader streamReader = new InputStreamReader(socket.getInputStream()); BufferedReader reader = new BufferedReader(streamReader); tipp = reader.readLine(); reader.close(); } catch(IOException ex) { //ex.printStackTrace(); } if (tipp != "") { return tipp; } else { return "Heute leider kein neuer Tipp."; } } }
UTF-8
Java
987
java
TippDesTagesClient.java
Java
[ { "context": "ppDesTagesClient()\n {\n serverAdresse = \"127.0.0.1\"; //Localhost // Ersetze diese Adresse!\n p", "end": 300, "score": 0.9995166063308716, "start": 291, "tag": "IP_ADDRESS", "value": "127.0.0.1" } ]
null
[]
// aus Java von Kopf bis Fu8 import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.Socket; public class TippDesTagesClient { String serverAdresse; int portNummer; public TippDesTagesClient() { serverAdresse = "127.0.0.1"; //Localhost // Ersetze diese Adresse! portNummer = 4242; } public String neuerTipp() { String tipp = ""; try { Socket socket = new Socket(serverAdresse, portNummer); InputStreamReader streamReader = new InputStreamReader(socket.getInputStream()); BufferedReader reader = new BufferedReader(streamReader); tipp = reader.readLine(); reader.close(); } catch(IOException ex) { //ex.printStackTrace(); } if (tipp != "") { return tipp; } else { return "Heute leider kein neuer Tipp."; } } }
987
0.580547
0.569402
38
24.947369
21.550365
92
false
false
0
0
0
0
0
0
0.473684
false
false
14
cfc17e543b4797dd0d8b9835c1e98c5325dd9c26
523,986,023,368
1962569b24079aff69f7cdebdcae9aa230aea644
/src/array_problem/DuplicateInteger.java
985184241e4d459a7ca3af36692d42d7fecd1058
[]
no_license
sizturriaga/data-structures
https://github.com/sizturriaga/data-structures
0ee185b01d53175c70e8203b0b92ff4d2c15eea7
35880d65b4be816b4b654167f20bbaac043c8429
refs/heads/master
2020-05-04T10:31:06.029000
2019-04-30T23:37:38
2019-04-30T23:37:38
179,089,205
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package array_problem; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class DuplicateInteger { public static void main(String[] args) { Integer[] array = new Integer[] {4,3,1,2,3,2,2,4}; long i = System.currentTimeMillis(); findDuplicateInteger(array); long f = System.currentTimeMillis(); long time = f - i; System.out.println("time "+ time); } private static void findDuplicateInteger(Integer[] array) { Map<Integer, Integer> values = new HashMap<>(); Set<Integer> duplicated = new HashSet<>(array.length); for (int i = 0; i < array.length; i++) { if(values.get(array[i]) != null) { duplicated.add(array[i]); }else { values.put(array[i], i); } } duplicated.stream().forEach(f -> System.out.println("duplicated "+ f)); } /** * It only run if the mayor element is less than the array's length * and there is not more than two duplicate elements * @param array */ private static void findDuplicateInteger2(Integer[] array) { for (int i = 0; i < array.length; i++) { int item = array[Math.abs(array[i])]; if( item > 0) { array[Math.abs(array[i])] = -item; }else { System.out.println("duplicated "+ Math.abs(array[i])); } } } }
UTF-8
Java
1,289
java
DuplicateInteger.java
Java
[]
null
[]
package array_problem; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class DuplicateInteger { public static void main(String[] args) { Integer[] array = new Integer[] {4,3,1,2,3,2,2,4}; long i = System.currentTimeMillis(); findDuplicateInteger(array); long f = System.currentTimeMillis(); long time = f - i; System.out.println("time "+ time); } private static void findDuplicateInteger(Integer[] array) { Map<Integer, Integer> values = new HashMap<>(); Set<Integer> duplicated = new HashSet<>(array.length); for (int i = 0; i < array.length; i++) { if(values.get(array[i]) != null) { duplicated.add(array[i]); }else { values.put(array[i], i); } } duplicated.stream().forEach(f -> System.out.println("duplicated "+ f)); } /** * It only run if the mayor element is less than the array's length * and there is not more than two duplicate elements * @param array */ private static void findDuplicateInteger2(Integer[] array) { for (int i = 0; i < array.length; i++) { int item = array[Math.abs(array[i])]; if( item > 0) { array[Math.abs(array[i])] = -item; }else { System.out.println("duplicated "+ Math.abs(array[i])); } } } }
1,289
0.637704
0.628394
56
22.017857
21.448019
73
false
false
0
0
0
0
0
0
2.178571
false
false
14
af6cd58f06c21c8ffacdc4235301bee2de6b53eb
1,322,849,940,126
23400916d964398c8a1f33645a6ba4905dabf240
/app/src/main/java/com/tuyenmonkey/designpatterns/behavioral/ConfirmOrder.java
dd9ec3155ef7b00bfa580d287932e479dc6e7659
[]
no_license
nntuyen/design-patterns
https://github.com/nntuyen/design-patterns
acd51798d6bc2ce263852c134311946ea29024a2
0a6314f18d0945b31d4b35591871869de0fbaa2d
refs/heads/master
2016-08-09T16:04:08.009000
2016-04-02T04:54:15
2016-04-02T04:54:15
55,278,363
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tuyenmonkey.designpatterns.behavioral; /** * Created by Tuyen Nguyen on 4/2/16. */ public class ConfirmOrder implements CheckoutStep { public ConfirmOrder() { } @Override public void execute() { } }
UTF-8
Java
238
java
ConfirmOrder.java
Java
[ { "context": "nkey.designpatterns.behavioral;\n\n/**\n * Created by Tuyen Nguyen on 4/2/16.\n */\npublic class ConfirmOrder implemen", "end": 82, "score": 0.9998757243156433, "start": 70, "tag": "NAME", "value": "Tuyen Nguyen" } ]
null
[]
package com.tuyenmonkey.designpatterns.behavioral; /** * Created by <NAME> on 4/2/16. */ public class ConfirmOrder implements CheckoutStep { public ConfirmOrder() { } @Override public void execute() { } }
232
0.668067
0.65126
16
13.875
17.828611
51
false
false
0
0
0
0
0
0
0.0625
false
false
14
26b28265ffe7388cc23884643f8dac5e943a3814
31,842,887,554,097
9ed4995dac72ffa2f3f18049ff41c5691cdde45f
/extras/wrangler/plugins/org.erlide.wrangler.refactoring/src/org/erlide/wrangler/refactoring/core/internal/GeneraliseFunctionRefactoring.java
538dd627ee93202a3561df4e0fbaebb4c79ddf58
[]
no_license
erlide/erlide
https://github.com/erlide/erlide
392e1d70afc3498c3f36544130196b69816404af
f683d084253380c03915df20e1f63cfd45f068fa
refs/heads/master
2021-05-22T09:51:30.280000
2021-02-15T21:09:42
2021-02-15T21:09:53
349,355
73
21
null
null
null
null
null
null
null
null
null
null
null
null
null
/******************************************************************************* * Copyright (c) 2010 György Orosz. All rights reserved. This program and the accompanying * materials are made available under the terms of the Eclipse Public License v1.0 which * accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: György Orosz - initial API and implementation ******************************************************************************/ package org.erlide.wrangler.refactoring.core.internal; import java.util.HashMap; import java.util.Map; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.ltk.core.refactoring.RefactoringStatus; import org.eclipse.swt.widgets.Shell; import org.erlide.util.ErlLogger; import org.erlide.wrangler.refactoring.backend.IRefactoringRpcMessage; import org.erlide.wrangler.refactoring.backend.internal.GenFunRefactoringMessage; import org.erlide.wrangler.refactoring.backend.internal.GenFunRefactoringMessage.GenFunReturnParameterName; import org.erlide.wrangler.refactoring.backend.internal.WranglerBackendManager; import org.erlide.wrangler.refactoring.core.CostumWorkflowRefactoringWithPositionsSelection; import org.erlide.wrangler.refactoring.core.RefactoringWorkflowController; import org.erlide.wrangler.refactoring.selection.IErlMemberSelection; import org.erlide.wrangler.refactoring.selection.IErlSelection; import org.erlide.wrangler.refactoring.util.ErlRange; import org.erlide.wrangler.refactoring.util.GlobalParameters; import org.erlide.wrangler.refactoring.util.IErlRange; import org.erlide.wrangler.refactoring.util.Range; import com.ericsson.otp.erlang.OtpErlangBoolean; import com.ericsson.otp.erlang.OtpErlangException; import com.ericsson.otp.erlang.OtpErlangList; import com.ericsson.otp.erlang.OtpErlangObject; import com.ericsson.otp.erlang.OtpErlangTuple; /** * Integration class of the generalise function refactoring * * @author Gyorgy Orosz * @version %I%, %G% */ public class GeneraliseFunctionRefactoring extends CostumWorkflowRefactoringWithPositionsSelection { /** * The state of the generalise function refactoring, after calling the first RPC * * @author Gyorgy Orosz * @version %I%, %G% */ public enum State { ok, error, multi_instance, unknown_side_effect, more_than_one_clause } private final State state; private String errorMessage; private GenFunRefactoringMessage message; private boolean onlyInClause; private boolean sideEffect; /** * Constructor * * @param state * state of the refactoring * @param text * error message in case of wrong input */ public GeneraliseFunctionRefactoring(final State state, final String text) { this.state = state; errorMessage = text; } /** * Constructor * * @param state * state of the refactoring * @param message * RPC message from Wrangler */ public GeneraliseFunctionRefactoring(final State state, final GenFunRefactoringMessage message) { this.state = state; this.message = message; } /** * Constructor * * @param state * state of the refactoring * @param message * RPC message from Wrangler * @param onlyInClause * user input */ public GeneraliseFunctionRefactoring(final State state, final GenFunRefactoringMessage message, final boolean onlyInClause) { this(state, message); this.onlyInClause = onlyInClause; } /** * Constructor * * @param state * state of the refactoring * @param message * RPC message from Wrangler * @param onlyInClause * user input * @param sideEffect * user input */ public GeneraliseFunctionRefactoring(final State state, final GenFunRefactoringMessage message, final boolean onlyInClause, final boolean sideEffect) { this(state, message, onlyInClause); this.sideEffect = sideEffect; } /* * public GeneraliseFunctionRefactoring(State state) { } */ @Override public RefactoringStatus checkInitialConditions(final IProgressMonitor pm) throws CoreException, OperationCanceledException { if (state == State.error) { return RefactoringStatus.createFatalErrorStatus(errorMessage); } else if (state == State.multi_instance) { positions = createPositionList((OtpErlangList) message.getParameters() .get(GenFunReturnParameterName.dupsInFun)); } else if (state == State.more_than_one_clause || state == State.unknown_side_effect) { if (onlyInClause) { positions = createPositionList((OtpErlangList) message.getParameters() .get(GenFunReturnParameterName.dupsInClause)); } else { positions = createPositionList((OtpErlangList) message.getParameters() .get(GenFunReturnParameterName.dupsInFun)); } } return new RefactoringStatus(); } /** * Returns IErlRange, OtpErlangTuple pairs, which are represents the same position in * a module * * @param thePositions * @return */ protected HashMap<IErlRange, OtpErlangTuple> createPositionList( final OtpErlangList thePositions) { try { final HashMap<IErlRange, OtpErlangTuple> ret = new HashMap<>(); final IErlMemberSelection sel = (IErlMemberSelection) GlobalParameters .getWranglerSelection(); for (final OtpErlangObject o : thePositions) { // {{sl, sc}, {el,ec}} final OtpErlangTuple pos = (OtpErlangTuple) o; ret.put(new ErlRange(new Range(pos), sel.getDocument()), pos); } return ret; } catch (final OtpErlangException e) { ErlLogger.error(e); return null; } } @Override public String getName() { return "Generalise function definition"; } @Override public IRefactoringRpcMessage run(final IErlSelection sel) { if (state == State.ok) { return message; } else if (state == State.error) { } else { final Map<GenFunReturnParameterName, OtpErlangObject> p = message .getParameters(); OtpErlangObject sideEffectPar; OtpErlangObject parName; OtpErlangObject funName; OtpErlangObject arity; OtpErlangObject funDefPos; OtpErlangObject exp; OtpErlangObject logCmd; sideEffectPar = p.get(GenFunReturnParameterName.sideEffect); parName = p.get(GenFunReturnParameterName.parName); funName = p.get(GenFunReturnParameterName.funName); arity = p.get(GenFunReturnParameterName.arity); funDefPos = p.get(GenFunReturnParameterName.funDefPos); exp = p.get(GenFunReturnParameterName.exp); logCmd = p.get(GenFunReturnParameterName.logCmd); if (state == State.multi_instance) { return WranglerBackendManager.getRefactoringBackend().call( "gen_fun_1_eclipse", "xsxxxxxxxix", sideEffectPar, sel.getFilePath(), parName, funName, arity, funDefPos, exp, getSelectedPos(), sel.getSearchPath(), GlobalParameters.getTabWidth(), logCmd); } else if (state == State.unknown_side_effect) { if (onlyInClause) { return WranglerBackendManager.getRefactoringBackend().call( "gen_fun_clause_eclipse", "sxxxxxixxx", sel.getFilePath(), parName, funName, arity, funDefPos, exp, GlobalParameters.getTabWidth(), new OtpErlangBoolean(sideEffect), getSelectedPos(), logCmd); } return WranglerBackendManager.getRefactoringBackend().call( "gen_fun_1_eclipse", "xsxxxxxxxix", new OtpErlangBoolean(sideEffect), sel.getFilePath(), parName, funName, arity, funDefPos, exp, getSelectedPos(), sel.getSearchPath(), GlobalParameters.getTabWidth(), logCmd); } else if (state == State.more_than_one_clause) { if (onlyInClause) { return WranglerBackendManager.getRefactoringBackend().call( "gen_fun_clause_eclipse", "sxxxxxixxx", sel.getFilePath(), parName, funName, arity, funDefPos, exp, GlobalParameters.getTabWidth(), sideEffectPar, getSelectedPos(), logCmd); } return WranglerBackendManager.getRefactoringBackend().call( "gen_fun_1_eclipse", "xsxxxxxxxix", sideEffectPar, sel.getFilePath(), parName, funName, arity, funDefPos, exp, getSelectedPos(), sel.getSearchPath(), GlobalParameters.getTabWidth(), logCmd); } } return null; } @Override public RefactoringStatus checkFinalConditions(final IProgressMonitor pm) throws CoreException, OperationCanceledException { final IErlSelection sel = GlobalParameters.getWranglerSelection(); final IRefactoringRpcMessage theMessage = run(sel); if (theMessage.isSuccessful()) { changedFiles = theMessage.getRefactoringChangeset(); return new RefactoringStatus(); } return RefactoringStatus.createFatalErrorStatus(theMessage.getMessageString()); } @Override public RefactoringWorkflowController getWorkflowController(final Shell shell) { return new RefactoringWorkflowController(shell) { @Override public void doRefactoring() { } }; } @Override public IRefactoringRpcMessage runAlternative(final IErlSelection selection) { return null; } }
UTF-8
Java
10,596
java
GeneraliseFunctionRefactoring.java
Java
[ { "context": "****************************\n * Copyright (c) 2010 György Orosz. All rights reserved. This program and the accomp", "end": 115, "score": 0.9998850226402283, "start": 103, "tag": "NAME", "value": "György Orosz" }, { "context": "eclipse.org/legal/epl-v10.html\n *\n * Con...
null
[]
/******************************************************************************* * Copyright (c) 2010 <NAME>. All rights reserved. This program and the accompanying * materials are made available under the terms of the Eclipse Public License v1.0 which * accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: <NAME> - initial API and implementation ******************************************************************************/ package org.erlide.wrangler.refactoring.core.internal; import java.util.HashMap; import java.util.Map; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.ltk.core.refactoring.RefactoringStatus; import org.eclipse.swt.widgets.Shell; import org.erlide.util.ErlLogger; import org.erlide.wrangler.refactoring.backend.IRefactoringRpcMessage; import org.erlide.wrangler.refactoring.backend.internal.GenFunRefactoringMessage; import org.erlide.wrangler.refactoring.backend.internal.GenFunRefactoringMessage.GenFunReturnParameterName; import org.erlide.wrangler.refactoring.backend.internal.WranglerBackendManager; import org.erlide.wrangler.refactoring.core.CostumWorkflowRefactoringWithPositionsSelection; import org.erlide.wrangler.refactoring.core.RefactoringWorkflowController; import org.erlide.wrangler.refactoring.selection.IErlMemberSelection; import org.erlide.wrangler.refactoring.selection.IErlSelection; import org.erlide.wrangler.refactoring.util.ErlRange; import org.erlide.wrangler.refactoring.util.GlobalParameters; import org.erlide.wrangler.refactoring.util.IErlRange; import org.erlide.wrangler.refactoring.util.Range; import com.ericsson.otp.erlang.OtpErlangBoolean; import com.ericsson.otp.erlang.OtpErlangException; import com.ericsson.otp.erlang.OtpErlangList; import com.ericsson.otp.erlang.OtpErlangObject; import com.ericsson.otp.erlang.OtpErlangTuple; /** * Integration class of the generalise function refactoring * * @author <NAME> * @version %I%, %G% */ public class GeneraliseFunctionRefactoring extends CostumWorkflowRefactoringWithPositionsSelection { /** * The state of the generalise function refactoring, after calling the first RPC * * @author <NAME> * @version %I%, %G% */ public enum State { ok, error, multi_instance, unknown_side_effect, more_than_one_clause } private final State state; private String errorMessage; private GenFunRefactoringMessage message; private boolean onlyInClause; private boolean sideEffect; /** * Constructor * * @param state * state of the refactoring * @param text * error message in case of wrong input */ public GeneraliseFunctionRefactoring(final State state, final String text) { this.state = state; errorMessage = text; } /** * Constructor * * @param state * state of the refactoring * @param message * RPC message from Wrangler */ public GeneraliseFunctionRefactoring(final State state, final GenFunRefactoringMessage message) { this.state = state; this.message = message; } /** * Constructor * * @param state * state of the refactoring * @param message * RPC message from Wrangler * @param onlyInClause * user input */ public GeneraliseFunctionRefactoring(final State state, final GenFunRefactoringMessage message, final boolean onlyInClause) { this(state, message); this.onlyInClause = onlyInClause; } /** * Constructor * * @param state * state of the refactoring * @param message * RPC message from Wrangler * @param onlyInClause * user input * @param sideEffect * user input */ public GeneraliseFunctionRefactoring(final State state, final GenFunRefactoringMessage message, final boolean onlyInClause, final boolean sideEffect) { this(state, message, onlyInClause); this.sideEffect = sideEffect; } /* * public GeneraliseFunctionRefactoring(State state) { } */ @Override public RefactoringStatus checkInitialConditions(final IProgressMonitor pm) throws CoreException, OperationCanceledException { if (state == State.error) { return RefactoringStatus.createFatalErrorStatus(errorMessage); } else if (state == State.multi_instance) { positions = createPositionList((OtpErlangList) message.getParameters() .get(GenFunReturnParameterName.dupsInFun)); } else if (state == State.more_than_one_clause || state == State.unknown_side_effect) { if (onlyInClause) { positions = createPositionList((OtpErlangList) message.getParameters() .get(GenFunReturnParameterName.dupsInClause)); } else { positions = createPositionList((OtpErlangList) message.getParameters() .get(GenFunReturnParameterName.dupsInFun)); } } return new RefactoringStatus(); } /** * Returns IErlRange, OtpErlangTuple pairs, which are represents the same position in * a module * * @param thePositions * @return */ protected HashMap<IErlRange, OtpErlangTuple> createPositionList( final OtpErlangList thePositions) { try { final HashMap<IErlRange, OtpErlangTuple> ret = new HashMap<>(); final IErlMemberSelection sel = (IErlMemberSelection) GlobalParameters .getWranglerSelection(); for (final OtpErlangObject o : thePositions) { // {{sl, sc}, {el,ec}} final OtpErlangTuple pos = (OtpErlangTuple) o; ret.put(new ErlRange(new Range(pos), sel.getDocument()), pos); } return ret; } catch (final OtpErlangException e) { ErlLogger.error(e); return null; } } @Override public String getName() { return "Generalise function definition"; } @Override public IRefactoringRpcMessage run(final IErlSelection sel) { if (state == State.ok) { return message; } else if (state == State.error) { } else { final Map<GenFunReturnParameterName, OtpErlangObject> p = message .getParameters(); OtpErlangObject sideEffectPar; OtpErlangObject parName; OtpErlangObject funName; OtpErlangObject arity; OtpErlangObject funDefPos; OtpErlangObject exp; OtpErlangObject logCmd; sideEffectPar = p.get(GenFunReturnParameterName.sideEffect); parName = p.get(GenFunReturnParameterName.parName); funName = p.get(GenFunReturnParameterName.funName); arity = p.get(GenFunReturnParameterName.arity); funDefPos = p.get(GenFunReturnParameterName.funDefPos); exp = p.get(GenFunReturnParameterName.exp); logCmd = p.get(GenFunReturnParameterName.logCmd); if (state == State.multi_instance) { return WranglerBackendManager.getRefactoringBackend().call( "gen_fun_1_eclipse", "xsxxxxxxxix", sideEffectPar, sel.getFilePath(), parName, funName, arity, funDefPos, exp, getSelectedPos(), sel.getSearchPath(), GlobalParameters.getTabWidth(), logCmd); } else if (state == State.unknown_side_effect) { if (onlyInClause) { return WranglerBackendManager.getRefactoringBackend().call( "gen_fun_clause_eclipse", "sxxxxxixxx", sel.getFilePath(), parName, funName, arity, funDefPos, exp, GlobalParameters.getTabWidth(), new OtpErlangBoolean(sideEffect), getSelectedPos(), logCmd); } return WranglerBackendManager.getRefactoringBackend().call( "gen_fun_1_eclipse", "xsxxxxxxxix", new OtpErlangBoolean(sideEffect), sel.getFilePath(), parName, funName, arity, funDefPos, exp, getSelectedPos(), sel.getSearchPath(), GlobalParameters.getTabWidth(), logCmd); } else if (state == State.more_than_one_clause) { if (onlyInClause) { return WranglerBackendManager.getRefactoringBackend().call( "gen_fun_clause_eclipse", "sxxxxxixxx", sel.getFilePath(), parName, funName, arity, funDefPos, exp, GlobalParameters.getTabWidth(), sideEffectPar, getSelectedPos(), logCmd); } return WranglerBackendManager.getRefactoringBackend().call( "gen_fun_1_eclipse", "xsxxxxxxxix", sideEffectPar, sel.getFilePath(), parName, funName, arity, funDefPos, exp, getSelectedPos(), sel.getSearchPath(), GlobalParameters.getTabWidth(), logCmd); } } return null; } @Override public RefactoringStatus checkFinalConditions(final IProgressMonitor pm) throws CoreException, OperationCanceledException { final IErlSelection sel = GlobalParameters.getWranglerSelection(); final IRefactoringRpcMessage theMessage = run(sel); if (theMessage.isSuccessful()) { changedFiles = theMessage.getRefactoringChangeset(); return new RefactoringStatus(); } return RefactoringStatus.createFatalErrorStatus(theMessage.getMessageString()); } @Override public RefactoringWorkflowController getWorkflowController(final Shell shell) { return new RefactoringWorkflowController(shell) { @Override public void doRefactoring() { } }; } @Override public IRefactoringRpcMessage runAlternative(final IErlSelection selection) { return null; } }
10,570
0.622994
0.621956
273
37.805862
28.084431
107
false
false
0
0
0
0
0
0
0.626374
false
false
14
481e4ac55944b451ab1fa0a6b1648644fe79dc85
1,228,360,700,585
0d47372d99db5c3b09f4dd65149d18d15f739d20
/src/main/java/egovframework/injeinc/common/util/FTPClientOroinc.java
f606fc9253fb369e6e91e330be32a44ecc99302b
[]
no_license
siwon95/nia
https://github.com/siwon95/nia
52a059225756304308af2997bc7043dad8cfc970
1b6ccffd386f2a66ed300c4a9efb28053989b72b
refs/heads/master
2022-12-26T17:15:37.919000
2020-09-25T09:13:10
2020-09-25T09:13:10
297,583,436
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package egovframework.injeinc.common.util; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.SocketException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.oroinc.net.ftp.FTP; import com.oroinc.net.ftp.FTPClient; import com.oroinc.net.ftp.FTPFile; import com.oroinc.net.ftp.FTPReply; import egovframework.cmm.EgovResourceCloseHelper; import egovframework.cmm.service.EgovProperties; public class FTPClientOroinc { private static final Logger LOGGER = LoggerFactory.getLogger(FTPClientOroinc.class); FTPClient ftpClient = new FTPClient(); String server = EgovProperties.getProperty("WebServer.FTP_SERVER"); String id = EgovProperties.getProperty("WebServer.FTP_USER"); String password = EgovProperties.getProperty("WebServer.FTP_PASS"); int port = Integer.valueOf(EgovProperties.getProperty("WebServer.FTP_PORT")); String platform = EgovProperties.getProperty("Globals.PLATFORM"); // 계정과 패스워드로 로그인 public boolean login() { try { this.connect(); return ftpClient.login(id, password); }catch (IOException e) { LOGGER.debug("IGNORED: "+e.getMessage()); } return false; } // 서버로부터 로그아웃 public boolean logout() { try { return ftpClient.logout(); }catch (IOException e) { LOGGER.debug("IGNORED: "+e.getMessage()); } return false; } // 서버로 연결 public boolean connect() { boolean bReturn = true; try { ftpClient.connect(server, port); // 연결 시도후, 성공했는지 응답 코드 확인 int reply= ftpClient.getReplyCode(); if(!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); System.out.print("서버로부터 연결을 거부당했습니다"); } }catch (SocketException e) { bReturn = false; if(ftpClient.isConnected()) { try { ftpClient.disconnect(); } catch(IOException e2) { bReturn = false; LOGGER.debug("IGNORED: "+e.getMessage()); } catch(Exception e2) { bReturn = false; LOGGER.debug("IGNORED: "+e.getMessage()); } } }catch (Exception e) { bReturn = false; if(ftpClient.isConnected()) { try { ftpClient.disconnect(); } catch(IOException e2) { bReturn = false; LOGGER.debug("IGNORED: "+e.getMessage()); } catch(Exception e2) { bReturn = false; LOGGER.debug("IGNORED: "+e.getMessage()); } } } return bReturn; } // 서버로부터 연결을 닫는다 public void disconnect() { try { ftpClient.disconnect(); }catch (IOException e) { LOGGER.debug("IGNORED: "+e.getMessage()); } } // FTP의 ls 명령, 모든 파일 리스트를 가져온다 public FTPFile[] list() { try { return this.ftpClient.listFiles(); }catch (IOException e) { LOGGER.debug("IGNORED: "+e.getMessage()); } return null; } public boolean put(String strRemotePath, String strRemoteFile, String strLocalPath, String strLocalFile) { boolean bReturn = true; if(platform != null){ if(platform.equals("service")) { try { if(!connect()) return false; if(!login()) return false; BufferedInputStream bis = new BufferedInputStream(new FileInputStream(strLocalPath + strLocalFile)); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.changeWorkingDirectory(strRemotePath); ftpClient.storeFile(strRemoteFile, bis); }catch (IOException e) { LOGGER.debug("IGNORED: "+e.getMessage()); }finally { logout(); disconnect(); } } } return bReturn; } // 파일을 전송 받는다 public File get(String source, String target) { OutputStream output = null; if(source == null) { return null; } try { File local = new File(source); output = new FileOutputStream(local); }catch (FileNotFoundException e) { LOGGER.debug("IGNORED: "+e.getMessage()); EgovResourceCloseHelper.close(output); }finally{ EgovResourceCloseHelper.close(output); } File file = new File(source); try { ftpClient.setFileType(FTP.BINARY_FILE_TYPE); if(ftpClient.retrieveFile(source, output)) { return file; } }catch (IOException ioe) { throw new RuntimeException(); } return null; } public boolean getFile(String strRemotePath, String strSfile,String strLocalPath, String strTfile) { boolean bReturn = true; if(!connect()) { // disconnect(); return false; } if(!login()) { disconnect(); return false; } if(!cd(strRemotePath)){ return false; } byte b[] = null; BufferedInputStream fin = null; BufferedOutputStream outs = null; File downfile = get(strSfile, strLocalPath + strTfile); File savefile = new File(strLocalPath + strTfile); b = new byte[(int)downfile.length()]; try { try { fin = new BufferedInputStream(new FileInputStream(downfile)); outs = new BufferedOutputStream(new FileOutputStream(savefile)); int read = 0; while((read = fin.read(b)) != -1){ outs.write(b,0,read); } outs.close(); fin.close(); }catch (IOException e) { bReturn = false; }finally { if(outs!=null) outs.close(); if(fin!=null) fin.close(); } }catch (IOException ioe) { bReturn = false; }finally { logout(); disconnect(); } return bReturn; } //파일 삭제 처리 public boolean delfile(String strPath, String source) { boolean bReturn = true; if(platform != null){ if(platform.equals("service")) { connect(); if(!login()) { disconnect(); return false; } if(!cd(strPath)){ return false; } try { ftpClient.deleteFile(source); }catch (IOException e) { bReturn = false; }finally { logout(); disconnect(); } } } return bReturn; } public boolean renamefile(String strPath, String strSname, String strRname) { boolean bReturn = true; connect(); if(!login()) { disconnect(); return false; } if(!cd(strPath)){ return false; } try { ftpClient.rename(strSname, strRname); }catch (Exception e) { bReturn = false; }finally { logout(); disconnect(); } return bReturn; } // 서버 디렉토리 이동 public boolean cd(String strPath) { boolean bReturn = true; try { ftpClient.changeWorkingDirectory(strPath); }catch (IOException ioe) { bReturn = false; } return bReturn; } public boolean mkdir(String strPath, String strDir) { boolean bReturn = true; if(platform != null){ if(platform.equals("service")) { connect(); if(!login()) { disconnect(); return false; } if(!cd(strPath)){ return false; } try { ftpClient.makeDirectory(strDir); }catch (IOException ioe) { bReturn = false; }finally { logout(); disconnect(); } } } return bReturn; } public boolean rmdir(String strPath, String strDir) { boolean bReturn = true; connect(); if(!login()) { disconnect(); return false; } if(!cd(strPath)){ return false; } try { ftpClient.removeDirectory(strDir); }catch (IOException ioe) { bReturn = false; }finally { logout(); disconnect(); } return bReturn; } }
UTF-8
Java
7,490
java
FTPClientOroinc.java
Java
[ { "context": "rty(\"WebServer.FTP_USER\");\n\tString password\t= EgovProperties.getProperty(\"WebServer.FTP_PASS\");\n\tint port\t\t= I", "end": 956, "score": 0.5057267546653748, "start": 946, "tag": "PASSWORD", "value": "Properties" } ]
null
[]
package egovframework.injeinc.common.util; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.SocketException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.oroinc.net.ftp.FTP; import com.oroinc.net.ftp.FTPClient; import com.oroinc.net.ftp.FTPFile; import com.oroinc.net.ftp.FTPReply; import egovframework.cmm.EgovResourceCloseHelper; import egovframework.cmm.service.EgovProperties; public class FTPClientOroinc { private static final Logger LOGGER = LoggerFactory.getLogger(FTPClientOroinc.class); FTPClient ftpClient = new FTPClient(); String server = EgovProperties.getProperty("WebServer.FTP_SERVER"); String id = EgovProperties.getProperty("WebServer.FTP_USER"); String password = Egov<PASSWORD>.getProperty("WebServer.FTP_PASS"); int port = Integer.valueOf(EgovProperties.getProperty("WebServer.FTP_PORT")); String platform = EgovProperties.getProperty("Globals.PLATFORM"); // 계정과 패스워드로 로그인 public boolean login() { try { this.connect(); return ftpClient.login(id, password); }catch (IOException e) { LOGGER.debug("IGNORED: "+e.getMessage()); } return false; } // 서버로부터 로그아웃 public boolean logout() { try { return ftpClient.logout(); }catch (IOException e) { LOGGER.debug("IGNORED: "+e.getMessage()); } return false; } // 서버로 연결 public boolean connect() { boolean bReturn = true; try { ftpClient.connect(server, port); // 연결 시도후, 성공했는지 응답 코드 확인 int reply= ftpClient.getReplyCode(); if(!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); System.out.print("서버로부터 연결을 거부당했습니다"); } }catch (SocketException e) { bReturn = false; if(ftpClient.isConnected()) { try { ftpClient.disconnect(); } catch(IOException e2) { bReturn = false; LOGGER.debug("IGNORED: "+e.getMessage()); } catch(Exception e2) { bReturn = false; LOGGER.debug("IGNORED: "+e.getMessage()); } } }catch (Exception e) { bReturn = false; if(ftpClient.isConnected()) { try { ftpClient.disconnect(); } catch(IOException e2) { bReturn = false; LOGGER.debug("IGNORED: "+e.getMessage()); } catch(Exception e2) { bReturn = false; LOGGER.debug("IGNORED: "+e.getMessage()); } } } return bReturn; } // 서버로부터 연결을 닫는다 public void disconnect() { try { ftpClient.disconnect(); }catch (IOException e) { LOGGER.debug("IGNORED: "+e.getMessage()); } } // FTP의 ls 명령, 모든 파일 리스트를 가져온다 public FTPFile[] list() { try { return this.ftpClient.listFiles(); }catch (IOException e) { LOGGER.debug("IGNORED: "+e.getMessage()); } return null; } public boolean put(String strRemotePath, String strRemoteFile, String strLocalPath, String strLocalFile) { boolean bReturn = true; if(platform != null){ if(platform.equals("service")) { try { if(!connect()) return false; if(!login()) return false; BufferedInputStream bis = new BufferedInputStream(new FileInputStream(strLocalPath + strLocalFile)); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.changeWorkingDirectory(strRemotePath); ftpClient.storeFile(strRemoteFile, bis); }catch (IOException e) { LOGGER.debug("IGNORED: "+e.getMessage()); }finally { logout(); disconnect(); } } } return bReturn; } // 파일을 전송 받는다 public File get(String source, String target) { OutputStream output = null; if(source == null) { return null; } try { File local = new File(source); output = new FileOutputStream(local); }catch (FileNotFoundException e) { LOGGER.debug("IGNORED: "+e.getMessage()); EgovResourceCloseHelper.close(output); }finally{ EgovResourceCloseHelper.close(output); } File file = new File(source); try { ftpClient.setFileType(FTP.BINARY_FILE_TYPE); if(ftpClient.retrieveFile(source, output)) { return file; } }catch (IOException ioe) { throw new RuntimeException(); } return null; } public boolean getFile(String strRemotePath, String strSfile,String strLocalPath, String strTfile) { boolean bReturn = true; if(!connect()) { // disconnect(); return false; } if(!login()) { disconnect(); return false; } if(!cd(strRemotePath)){ return false; } byte b[] = null; BufferedInputStream fin = null; BufferedOutputStream outs = null; File downfile = get(strSfile, strLocalPath + strTfile); File savefile = new File(strLocalPath + strTfile); b = new byte[(int)downfile.length()]; try { try { fin = new BufferedInputStream(new FileInputStream(downfile)); outs = new BufferedOutputStream(new FileOutputStream(savefile)); int read = 0; while((read = fin.read(b)) != -1){ outs.write(b,0,read); } outs.close(); fin.close(); }catch (IOException e) { bReturn = false; }finally { if(outs!=null) outs.close(); if(fin!=null) fin.close(); } }catch (IOException ioe) { bReturn = false; }finally { logout(); disconnect(); } return bReturn; } //파일 삭제 처리 public boolean delfile(String strPath, String source) { boolean bReturn = true; if(platform != null){ if(platform.equals("service")) { connect(); if(!login()) { disconnect(); return false; } if(!cd(strPath)){ return false; } try { ftpClient.deleteFile(source); }catch (IOException e) { bReturn = false; }finally { logout(); disconnect(); } } } return bReturn; } public boolean renamefile(String strPath, String strSname, String strRname) { boolean bReturn = true; connect(); if(!login()) { disconnect(); return false; } if(!cd(strPath)){ return false; } try { ftpClient.rename(strSname, strRname); }catch (Exception e) { bReturn = false; }finally { logout(); disconnect(); } return bReturn; } // 서버 디렉토리 이동 public boolean cd(String strPath) { boolean bReturn = true; try { ftpClient.changeWorkingDirectory(strPath); }catch (IOException ioe) { bReturn = false; } return bReturn; } public boolean mkdir(String strPath, String strDir) { boolean bReturn = true; if(platform != null){ if(platform.equals("service")) { connect(); if(!login()) { disconnect(); return false; } if(!cd(strPath)){ return false; } try { ftpClient.makeDirectory(strDir); }catch (IOException ioe) { bReturn = false; }finally { logout(); disconnect(); } } } return bReturn; } public boolean rmdir(String strPath, String strDir) { boolean bReturn = true; connect(); if(!login()) { disconnect(); return false; } if(!cd(strPath)){ return false; } try { ftpClient.removeDirectory(strDir); }catch (IOException ioe) { bReturn = false; }finally { logout(); disconnect(); } return bReturn; } }
7,490
0.639247
0.638012
358
19.340782
18.327135
107
false
false
0
0
0
0
0
0
2.958101
false
false
14
e8b108d5962657a9d4fe99a814e5bea753d8c1c9
30,932,354,498,519
353e428985f7a46c335ad47cc08f1749dbf95387
/src/abstractAndInterface/Divisible.java
d34d9e03b898fc45402537ecfeafba169d888a6f
[]
no_license
zhhaojie/learnJava
https://github.com/zhhaojie/learnJava
0d610fb423cfd0dbb6378d46dece1519e69b41fa
3f6a906af383119c06803487e6eb4d780014e8d9
refs/heads/master
2016-03-06T11:39:02.937000
2015-05-16T08:26:56
2015-05-16T08:26:56
8,921,685
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package abstractAndInterface; public interface Divisible { void divisible(); }
UTF-8
Java
81
java
Divisible.java
Java
[]
null
[]
package abstractAndInterface; public interface Divisible { void divisible(); }
81
0.790123
0.790123
5
15.2
12.607934
29
false
false
0
0
0
0
0
0
0.6
false
false
14
ef49360a1abe88a8b76971b45a9d501e355b2aea
33,354,716,053,446
7de1348a0ddaff6e5559bf6ff47a69a60952cfeb
/src/main/java/net/maynard/examples/j2ee/web/controller/servlet/LoginServlet.java
e97482314d038d8036cbbb4e26d82c3e4ef5ef32
[ "Apache-2.0" ]
permissive
Stargator/testdrivenexamples
https://github.com/Stargator/testdrivenexamples
7f4c3943bfbbd2cdeb29e5c2f746410686d02dfc
0f4270a63bc472682fb076ebe272d3dbb34126e3
refs/heads/master
2021-01-21T00:53:20.746000
2016-09-10T15:44:01
2016-09-10T16:40:05
31,349,396
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.maynard.examples.j2ee.web.controller.servlet; import net.maynard.examples.j2ee.web.controller.authenticator.AuthenticationService; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class LoginServlet extends HttpServlet { private final String PARAMETER_USER = "j_username"; private final String PARAMETER_PASS = "j_password"; protected AuthenticationService getAuthenticationService() { return null; } @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String user = request.getParameter("j_username").toString(); String pass = request.getParameter("j_password").toString(); if (getAuthenticationService().isValidLogin(user, pass)) { response.sendRedirect("/frontpage"); request.getSession().setAttribute("username", user); } else { response.sendRedirect("/invalidlogin"); } } public String getPARAMETER_USER() { return PARAMETER_USER; } public String getPARAMETER_PASS() { return PARAMETER_PASS; } }
UTF-8
Java
1,308
java
LoginServlet.java
Java
[ { "context": "vlet {\n private final String PARAMETER_USER = \"j_username\";\n private final String PARAMETER_PASS = \"j_pa", "end": 446, "score": 0.9949888586997986, "start": 436, "tag": "USERNAME", "value": "j_username" }, { "context": "name\";\n private final String PARAM...
null
[]
package net.maynard.examples.j2ee.web.controller.servlet; import net.maynard.examples.j2ee.web.controller.authenticator.AuthenticationService; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class LoginServlet extends HttpServlet { private final String PARAMETER_USER = "j_username"; private final String PARAMETER_PASS = "<PASSWORD>"; protected AuthenticationService getAuthenticationService() { return null; } @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String user = request.getParameter("j_username").toString(); String pass = request.getParameter("j_password").toString(); if (getAuthenticationService().isValidLogin(user, pass)) { response.sendRedirect("/frontpage"); request.getSession().setAttribute("username", user); } else { response.sendRedirect("/invalidlogin"); } } public String getPARAMETER_USER() { return PARAMETER_USER; } public String getPARAMETER_PASS() { return PARAMETER_PASS; } }
1,308
0.711774
0.710245
40
31.700001
26.385792
84
false
false
0
0
0
0
0
0
0.525
false
false
14
62ade7b0a47b0cf0b16c01b278622dd3e6cb6347
32,469,952,787,916
40e43bbdbb5d4b88090674ac67d59700a14541dd
/zhengjy-demo-deploy/src/main/java/com/zhengjy/test/design/demo/组合模式/Quackable.java
6e8858e09da883178aab6f86eebc8fde1c37ac50
[]
no_license
zhengjy/zhengjy-demo
https://github.com/zhengjy/zhengjy-demo
8e854bdb23f38fbdcb5ccb213cf761613c659cf0
93b9b6298976400cf193d6979f673028ab903bc6
refs/heads/master
2022-10-26T22:52:46.829000
2019-12-23T05:17:42
2019-12-23T05:17:42
75,283,866
0
0
null
false
2022-10-05T19:11:22
2016-12-01T10:56:37
2019-12-23T05:20:18
2022-10-05T19:11:19
60,519
0
0
4
Java
false
false
package com.zhengjy.test.design.demo.组合模式; /** * Created by Administrator on 2016/11/20. */ public interface Quackable { void quack(); }
UTF-8
Java
152
java
Quackable.java
Java
[]
null
[]
package com.zhengjy.test.design.demo.组合模式; /** * Created by Administrator on 2016/11/20. */ public interface Quackable { void quack(); }
152
0.694444
0.638889
8
17
16.985289
42
false
false
0
0
0
0
0
0
0.25
false
false
14
e2e1f2ff32de213faba790a501dd5a45c0fcff87
28,278,064,709,477
877e94163f0b4bb4cb731341ded6732bc29a40ff
/src/main/java/com/oklink/util/HttpMethodEnum.java
30c33f8c19cd58829d285ba3a50b23ebbadd789f
[]
no_license
longdeng/oklink-ballance
https://github.com/longdeng/oklink-ballance
75fe50f57de5dbfe99c51d86ecc6751bbc6446c2
431d9346ab08c7839ef39708c2e268dea24b2a2c
refs/heads/master
2016-09-03T07:01:08.975000
2014-11-20T03:25:07
2014-11-20T03:25:07
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.oklink.util; /** * @author longdeng.zhang@gmail.com * @version 创建时间:2014-11-7 下午6:01:14 * 类说明 */ public enum HttpMethodEnum { GET, POST, HEAD, OPTIONS, PUT, DELETE, TRACE }
UTF-8
Java
219
java
HttpMethodEnum.java
Java
[ { "context": "package com.oklink.util;\r\n/**\r\n * @author longdeng.zhang@gmail.com\r\n * @version 创建时间:2014-11-7 下午6:01:14\r\n * 类说明\r\n *", "end": 66, "score": 0.9999222159385681, "start": 42, "tag": "EMAIL", "value": "longdeng.zhang@gmail.com" } ]
null
[]
package com.oklink.util; /** * @author <EMAIL> * @version 创建时间:2014-11-7 下午6:01:14 * 类说明 */ public enum HttpMethodEnum { GET, POST, HEAD, OPTIONS, PUT, DELETE, TRACE }
202
0.658291
0.59799
9
20.111111
16.058535
45
false
false
0
0
0
0
0
0
0.888889
false
false
14
9107a9db8989ccdba707adadd737172165a52efa
20,933,670,631,417
ea16de2020ab8fdefc8327a906f7aa79c65e4ad4
/src/main/java/com/hellogood/domain/PushMappingExample.java
e58ad190806481300e3dab0c81e139c554de0f15
[]
no_license
scaukejian/hellogood_admin
https://github.com/scaukejian/hellogood_admin
3cca6d4f8572e967c6d47b6afe097663201c80fd
f5754d1e55e1f322085805d9446077666f696485
refs/heads/master
2021-09-07T18:21:26.784000
2018-02-27T08:19:46
2018-02-27T08:19:46
104,710,472
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hellogood.domain; import java.util.ArrayList; import java.util.List; public class PushMappingExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public PushMappingExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andIdIsNull() { addCriterion("id is null"); return (Criteria) this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return (Criteria) this; } public Criteria andIdEqualTo(Integer value) { addCriterion("id =", value, "id"); return (Criteria) this; } public Criteria andIdNotEqualTo(Integer value) { addCriterion("id <>", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThan(Integer value) { addCriterion("id >", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThanOrEqualTo(Integer value) { addCriterion("id >=", value, "id"); return (Criteria) this; } public Criteria andIdLessThan(Integer value) { addCriterion("id <", value, "id"); return (Criteria) this; } public Criteria andIdLessThanOrEqualTo(Integer value) { addCriterion("id <=", value, "id"); return (Criteria) this; } public Criteria andIdIn(List<Integer> values) { addCriterion("id in", values, "id"); return (Criteria) this; } public Criteria andIdNotIn(List<Integer> values) { addCriterion("id not in", values, "id"); return (Criteria) this; } public Criteria andIdBetween(Integer value1, Integer value2) { addCriterion("id between", value1, value2, "id"); return (Criteria) this; } public Criteria andIdNotBetween(Integer value1, Integer value2) { addCriterion("id not between", value1, value2, "id"); return (Criteria) this; } public Criteria andUserIdIsNull() { addCriterion("user_id is null"); return (Criteria) this; } public Criteria andUserIdIsNotNull() { addCriterion("user_id is not null"); return (Criteria) this; } public Criteria andUserIdEqualTo(Integer value) { addCriterion("user_id =", value, "userId"); return (Criteria) this; } public Criteria andUserIdNotEqualTo(Integer value) { addCriterion("user_id <>", value, "userId"); return (Criteria) this; } public Criteria andUserIdGreaterThan(Integer value) { addCriterion("user_id >", value, "userId"); return (Criteria) this; } public Criteria andUserIdGreaterThanOrEqualTo(Integer value) { addCriterion("user_id >=", value, "userId"); return (Criteria) this; } public Criteria andUserIdLessThan(Integer value) { addCriterion("user_id <", value, "userId"); return (Criteria) this; } public Criteria andUserIdLessThanOrEqualTo(Integer value) { addCriterion("user_id <=", value, "userId"); return (Criteria) this; } public Criteria andUserIdIn(List<Integer> values) { addCriterion("user_id in", values, "userId"); return (Criteria) this; } public Criteria andUserIdNotIn(List<Integer> values) { addCriterion("user_id not in", values, "userId"); return (Criteria) this; } public Criteria andUserIdBetween(Integer value1, Integer value2) { addCriterion("user_id between", value1, value2, "userId"); return (Criteria) this; } public Criteria andUserIdNotBetween(Integer value1, Integer value2) { addCriterion("user_id not between", value1, value2, "userId"); return (Criteria) this; } public Criteria andDeviceNameIsNull() { addCriterion("device_name is null"); return (Criteria) this; } public Criteria andDeviceNameIsNotNull() { addCriterion("device_name is not null"); return (Criteria) this; } public Criteria andDeviceNameEqualTo(String value) { addCriterion("device_name =", value, "deviceName"); return (Criteria) this; } public Criteria andDeviceNameNotEqualTo(String value) { addCriterion("device_name <>", value, "deviceName"); return (Criteria) this; } public Criteria andDeviceNameGreaterThan(String value) { addCriterion("device_name >", value, "deviceName"); return (Criteria) this; } public Criteria andDeviceNameGreaterThanOrEqualTo(String value) { addCriterion("device_name >=", value, "deviceName"); return (Criteria) this; } public Criteria andDeviceNameLessThan(String value) { addCriterion("device_name <", value, "deviceName"); return (Criteria) this; } public Criteria andDeviceNameLessThanOrEqualTo(String value) { addCriterion("device_name <=", value, "deviceName"); return (Criteria) this; } public Criteria andDeviceNameLike(String value) { addCriterion("device_name like", value, "deviceName"); return (Criteria) this; } public Criteria andDeviceNameNotLike(String value) { addCriterion("device_name not like", value, "deviceName"); return (Criteria) this; } public Criteria andDeviceNameIn(List<String> values) { addCriterion("device_name in", values, "deviceName"); return (Criteria) this; } public Criteria andDeviceNameNotIn(List<String> values) { addCriterion("device_name not in", values, "deviceName"); return (Criteria) this; } public Criteria andDeviceNameBetween(String value1, String value2) { addCriterion("device_name between", value1, value2, "deviceName"); return (Criteria) this; } public Criteria andDeviceNameNotBetween(String value1, String value2) { addCriterion("device_name not between", value1, value2, "deviceName"); return (Criteria) this; } public Criteria andClientIdIsNull() { addCriterion("client_id is null"); return (Criteria) this; } public Criteria andClientIdIsNotNull() { addCriterion("client_id is not null"); return (Criteria) this; } public Criteria andClientIdEqualTo(String value) { addCriterion("client_id =", value, "clientId"); return (Criteria) this; } public Criteria andClientIdNotEqualTo(String value) { addCriterion("client_id <>", value, "clientId"); return (Criteria) this; } public Criteria andClientIdGreaterThan(String value) { addCriterion("client_id >", value, "clientId"); return (Criteria) this; } public Criteria andClientIdGreaterThanOrEqualTo(String value) { addCriterion("client_id >=", value, "clientId"); return (Criteria) this; } public Criteria andClientIdLessThan(String value) { addCriterion("client_id <", value, "clientId"); return (Criteria) this; } public Criteria andClientIdLessThanOrEqualTo(String value) { addCriterion("client_id <=", value, "clientId"); return (Criteria) this; } public Criteria andClientIdLike(String value) { addCriterion("client_id like", value, "clientId"); return (Criteria) this; } public Criteria andClientIdNotLike(String value) { addCriterion("client_id not like", value, "clientId"); return (Criteria) this; } public Criteria andClientIdIn(List<String> values) { addCriterion("client_id in", values, "clientId"); return (Criteria) this; } public Criteria andClientIdNotIn(List<String> values) { addCriterion("client_id not in", values, "clientId"); return (Criteria) this; } public Criteria andClientIdBetween(String value1, String value2) { addCriterion("client_id between", value1, value2, "clientId"); return (Criteria) this; } public Criteria andClientIdNotBetween(String value1, String value2) { addCriterion("client_id not between", value1, value2, "clientId"); return (Criteria) this; } public Criteria andDeviceTokenIsNull() { addCriterion("device_token is null"); return (Criteria) this; } public Criteria andDeviceTokenIsNotNull() { addCriterion("device_token is not null"); return (Criteria) this; } public Criteria andDeviceTokenEqualTo(String value) { addCriterion("device_token =", value, "deviceToken"); return (Criteria) this; } public Criteria andDeviceTokenNotEqualTo(String value) { addCriterion("device_token <>", value, "deviceToken"); return (Criteria) this; } public Criteria andDeviceTokenGreaterThan(String value) { addCriterion("device_token >", value, "deviceToken"); return (Criteria) this; } public Criteria andDeviceTokenGreaterThanOrEqualTo(String value) { addCriterion("device_token >=", value, "deviceToken"); return (Criteria) this; } public Criteria andDeviceTokenLessThan(String value) { addCriterion("device_token <", value, "deviceToken"); return (Criteria) this; } public Criteria andDeviceTokenLessThanOrEqualTo(String value) { addCriterion("device_token <=", value, "deviceToken"); return (Criteria) this; } public Criteria andDeviceTokenLike(String value) { addCriterion("device_token like", value, "deviceToken"); return (Criteria) this; } public Criteria andDeviceTokenNotLike(String value) { addCriterion("device_token not like", value, "deviceToken"); return (Criteria) this; } public Criteria andDeviceTokenIn(List<String> values) { addCriterion("device_token in", values, "deviceToken"); return (Criteria) this; } public Criteria andDeviceTokenNotIn(List<String> values) { addCriterion("device_token not in", values, "deviceToken"); return (Criteria) this; } public Criteria andDeviceTokenBetween(String value1, String value2) { addCriterion("device_token between", value1, value2, "deviceToken"); return (Criteria) this; } public Criteria andDeviceTokenNotBetween(String value1, String value2) { addCriterion("device_token not between", value1, value2, "deviceToken"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
UTF-8
Java
16,381
java
PushMappingExample.java
Java
[]
null
[]
package com.hellogood.domain; import java.util.ArrayList; import java.util.List; public class PushMappingExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public PushMappingExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andIdIsNull() { addCriterion("id is null"); return (Criteria) this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return (Criteria) this; } public Criteria andIdEqualTo(Integer value) { addCriterion("id =", value, "id"); return (Criteria) this; } public Criteria andIdNotEqualTo(Integer value) { addCriterion("id <>", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThan(Integer value) { addCriterion("id >", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThanOrEqualTo(Integer value) { addCriterion("id >=", value, "id"); return (Criteria) this; } public Criteria andIdLessThan(Integer value) { addCriterion("id <", value, "id"); return (Criteria) this; } public Criteria andIdLessThanOrEqualTo(Integer value) { addCriterion("id <=", value, "id"); return (Criteria) this; } public Criteria andIdIn(List<Integer> values) { addCriterion("id in", values, "id"); return (Criteria) this; } public Criteria andIdNotIn(List<Integer> values) { addCriterion("id not in", values, "id"); return (Criteria) this; } public Criteria andIdBetween(Integer value1, Integer value2) { addCriterion("id between", value1, value2, "id"); return (Criteria) this; } public Criteria andIdNotBetween(Integer value1, Integer value2) { addCriterion("id not between", value1, value2, "id"); return (Criteria) this; } public Criteria andUserIdIsNull() { addCriterion("user_id is null"); return (Criteria) this; } public Criteria andUserIdIsNotNull() { addCriterion("user_id is not null"); return (Criteria) this; } public Criteria andUserIdEqualTo(Integer value) { addCriterion("user_id =", value, "userId"); return (Criteria) this; } public Criteria andUserIdNotEqualTo(Integer value) { addCriterion("user_id <>", value, "userId"); return (Criteria) this; } public Criteria andUserIdGreaterThan(Integer value) { addCriterion("user_id >", value, "userId"); return (Criteria) this; } public Criteria andUserIdGreaterThanOrEqualTo(Integer value) { addCriterion("user_id >=", value, "userId"); return (Criteria) this; } public Criteria andUserIdLessThan(Integer value) { addCriterion("user_id <", value, "userId"); return (Criteria) this; } public Criteria andUserIdLessThanOrEqualTo(Integer value) { addCriterion("user_id <=", value, "userId"); return (Criteria) this; } public Criteria andUserIdIn(List<Integer> values) { addCriterion("user_id in", values, "userId"); return (Criteria) this; } public Criteria andUserIdNotIn(List<Integer> values) { addCriterion("user_id not in", values, "userId"); return (Criteria) this; } public Criteria andUserIdBetween(Integer value1, Integer value2) { addCriterion("user_id between", value1, value2, "userId"); return (Criteria) this; } public Criteria andUserIdNotBetween(Integer value1, Integer value2) { addCriterion("user_id not between", value1, value2, "userId"); return (Criteria) this; } public Criteria andDeviceNameIsNull() { addCriterion("device_name is null"); return (Criteria) this; } public Criteria andDeviceNameIsNotNull() { addCriterion("device_name is not null"); return (Criteria) this; } public Criteria andDeviceNameEqualTo(String value) { addCriterion("device_name =", value, "deviceName"); return (Criteria) this; } public Criteria andDeviceNameNotEqualTo(String value) { addCriterion("device_name <>", value, "deviceName"); return (Criteria) this; } public Criteria andDeviceNameGreaterThan(String value) { addCriterion("device_name >", value, "deviceName"); return (Criteria) this; } public Criteria andDeviceNameGreaterThanOrEqualTo(String value) { addCriterion("device_name >=", value, "deviceName"); return (Criteria) this; } public Criteria andDeviceNameLessThan(String value) { addCriterion("device_name <", value, "deviceName"); return (Criteria) this; } public Criteria andDeviceNameLessThanOrEqualTo(String value) { addCriterion("device_name <=", value, "deviceName"); return (Criteria) this; } public Criteria andDeviceNameLike(String value) { addCriterion("device_name like", value, "deviceName"); return (Criteria) this; } public Criteria andDeviceNameNotLike(String value) { addCriterion("device_name not like", value, "deviceName"); return (Criteria) this; } public Criteria andDeviceNameIn(List<String> values) { addCriterion("device_name in", values, "deviceName"); return (Criteria) this; } public Criteria andDeviceNameNotIn(List<String> values) { addCriterion("device_name not in", values, "deviceName"); return (Criteria) this; } public Criteria andDeviceNameBetween(String value1, String value2) { addCriterion("device_name between", value1, value2, "deviceName"); return (Criteria) this; } public Criteria andDeviceNameNotBetween(String value1, String value2) { addCriterion("device_name not between", value1, value2, "deviceName"); return (Criteria) this; } public Criteria andClientIdIsNull() { addCriterion("client_id is null"); return (Criteria) this; } public Criteria andClientIdIsNotNull() { addCriterion("client_id is not null"); return (Criteria) this; } public Criteria andClientIdEqualTo(String value) { addCriterion("client_id =", value, "clientId"); return (Criteria) this; } public Criteria andClientIdNotEqualTo(String value) { addCriterion("client_id <>", value, "clientId"); return (Criteria) this; } public Criteria andClientIdGreaterThan(String value) { addCriterion("client_id >", value, "clientId"); return (Criteria) this; } public Criteria andClientIdGreaterThanOrEqualTo(String value) { addCriterion("client_id >=", value, "clientId"); return (Criteria) this; } public Criteria andClientIdLessThan(String value) { addCriterion("client_id <", value, "clientId"); return (Criteria) this; } public Criteria andClientIdLessThanOrEqualTo(String value) { addCriterion("client_id <=", value, "clientId"); return (Criteria) this; } public Criteria andClientIdLike(String value) { addCriterion("client_id like", value, "clientId"); return (Criteria) this; } public Criteria andClientIdNotLike(String value) { addCriterion("client_id not like", value, "clientId"); return (Criteria) this; } public Criteria andClientIdIn(List<String> values) { addCriterion("client_id in", values, "clientId"); return (Criteria) this; } public Criteria andClientIdNotIn(List<String> values) { addCriterion("client_id not in", values, "clientId"); return (Criteria) this; } public Criteria andClientIdBetween(String value1, String value2) { addCriterion("client_id between", value1, value2, "clientId"); return (Criteria) this; } public Criteria andClientIdNotBetween(String value1, String value2) { addCriterion("client_id not between", value1, value2, "clientId"); return (Criteria) this; } public Criteria andDeviceTokenIsNull() { addCriterion("device_token is null"); return (Criteria) this; } public Criteria andDeviceTokenIsNotNull() { addCriterion("device_token is not null"); return (Criteria) this; } public Criteria andDeviceTokenEqualTo(String value) { addCriterion("device_token =", value, "deviceToken"); return (Criteria) this; } public Criteria andDeviceTokenNotEqualTo(String value) { addCriterion("device_token <>", value, "deviceToken"); return (Criteria) this; } public Criteria andDeviceTokenGreaterThan(String value) { addCriterion("device_token >", value, "deviceToken"); return (Criteria) this; } public Criteria andDeviceTokenGreaterThanOrEqualTo(String value) { addCriterion("device_token >=", value, "deviceToken"); return (Criteria) this; } public Criteria andDeviceTokenLessThan(String value) { addCriterion("device_token <", value, "deviceToken"); return (Criteria) this; } public Criteria andDeviceTokenLessThanOrEqualTo(String value) { addCriterion("device_token <=", value, "deviceToken"); return (Criteria) this; } public Criteria andDeviceTokenLike(String value) { addCriterion("device_token like", value, "deviceToken"); return (Criteria) this; } public Criteria andDeviceTokenNotLike(String value) { addCriterion("device_token not like", value, "deviceToken"); return (Criteria) this; } public Criteria andDeviceTokenIn(List<String> values) { addCriterion("device_token in", values, "deviceToken"); return (Criteria) this; } public Criteria andDeviceTokenNotIn(List<String> values) { addCriterion("device_token not in", values, "deviceToken"); return (Criteria) this; } public Criteria andDeviceTokenBetween(String value1, String value2) { addCriterion("device_token between", value1, value2, "deviceToken"); return (Criteria) this; } public Criteria andDeviceTokenNotBetween(String value1, String value2) { addCriterion("device_token not between", value1, value2, "deviceToken"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
16,381
0.576827
0.573897
530
29.909433
25.166527
102
false
false
0
0
0
0
0
0
0.675472
false
false
14
5e7c4ff33d9803083259a9234c4353304aad89ee
6,098,853,595,032
7eb13d669cdeb914642a64e747ec6ef1484a64a1
/engine/src/es/eucm/eadandroid/common/loader/parsers/DescriptorHandler.java
b3c7a7263f6c5482bfea42bb7a329b7307fcb3eb
[]
no_license
e-ucm/eadventure-legacy-android
https://github.com/e-ucm/eadventure-legacy-android
7efe68326dc272cee467b597b66153adf17bcd11
905a4f45e83f59e199645c086a9708cd9a82410b
refs/heads/master
2016-09-02T00:51:45.594000
2014-01-30T14:48:09
2014-01-30T14:48:09
14,957,009
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/******************************************************************************* * <e-Adventure> Mobile for Android(TM) is a port of the <e-Adventure> research project to the Android(TM) platform. * * Copyright 2009-2012 <e-UCM> research group. * * <e-UCM> is a research group of the Department of Software Engineering * and Artificial Intelligence at the Complutense University of Madrid * (School of Computer Science). * * C Profesor Jose Garcia Santesmases sn, * 28040 Madrid (Madrid), Spain. * * For more info please visit: <http://e-adventure.e-ucm.es/android> or * <http://www.e-ucm.es> * * *Android is a trademark of Google Inc. * * **************************************************************************** * This file is part of <e-Adventure> Mobile, version 1.0. * * Main contributors - Roberto Tornero * * Former contributors - Alvaro Villoria * Juan Manuel de las Cuevas * Guillermo Martin * * Directors - Baltasar Fernandez Manjon * Eugenio Marchiori * * You can access a list of all the contributors to <e-Adventure> Mobile at: * http://e-adventure.e-ucm.es/contributors * * **************************************************************************** * <e-Adventure> Mobile is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * <e-Adventure> Mobile 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 Lesser General Public License for more details. * * See <http://www.gnu.org/licenses/> ******************************************************************************/ package es.eucm.eadandroid.common.loader.parsers; import java.io.InputStream; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler; import es.eucm.eadandroid.common.data.adventure.ChapterSummary; import es.eucm.eadandroid.common.data.adventure.DescriptorData; import es.eucm.eadandroid.common.data.adventure.DescriptorData.Perspective; import es.eucm.eadandroid.common.loader.InputStreamCreator; /** * This class is the handler to parse the e-Adventure descriptor file. * * @author Javier Torrente */ public class DescriptorHandler extends DefaultHandler { /** * Constant for reading nothing */ private static final int READING_NONE = 0; /** * Constant for reading a chapter */ private static final int READING_CHAPTER = 1; /** * String to store the current string in the XML file */ private StringBuffer currentString; /** * Stores the game descriptor being read */ private DescriptorData gameDescriptor; /** * Stores the element which is being read */ private int reading = READING_NONE; /** * Chapter being currently read */ private ChapterSummary currentChapter; /** * InputStreamCreator used in resolveEntity to find dtds (only required in * Applet mode) */ private InputStreamCreator isCreator; /** * Constructor */ public DescriptorHandler( InputStreamCreator isCreator ) { currentString = new StringBuffer( ); gameDescriptor = new DescriptorData( ); this.isCreator = isCreator; } /** * Returns the game descriptor read * * @return Game descriptor */ public DescriptorData getGameDescriptor( ) { return gameDescriptor; } /* * (non-Javadoc) * @see org.xml.sax.ContentHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes) */ @Override public void startElement( String namespaceURI, String sName, String qName, Attributes attrs ) throws SAXException { if( sName.equals( "game-descriptor" ) ) { for( int i = 0; i < attrs.getLength( ); i++ ) if( attrs.getLocalName( i ).equals( "versionNumber" ) ) { gameDescriptor.setVersionNumber( attrs.getValue( i ) ); } } if( qName.equals( "configuration" ) ) { for( int i = 0; i < attrs.getLength( ); i++ ) { if( attrs.getLocalName( i ).equals( "keepShowing" ) ) gameDescriptor.setKeepShowing( attrs.getValue( i ).equals( "yes" ) ); if ( attrs.getLocalName( i ).equals( "perspective" )) { if (attrs.getValue( i ).equals( "regular" )) gameDescriptor.setPerspective( Perspective.REGULAR ); if (attrs.getValue( i ).equals( "isometric" )) gameDescriptor.setPerspective( Perspective.ISOMETRIC ); } } } // If the element is the GUI configuration, store the values if( sName.equals( "gui" ) ) { int guiType = DescriptorData.GUI_TRADITIONAL; boolean guiCustomized = false; int inventoryPosition = DescriptorData.INVENTORY_TOP_BOTTOM; for( int i = 0; i < attrs.getLength( ); i++ ) { // Type of the GUI if( attrs.getLocalName( i ).equals( "type" ) ) { if( attrs.getValue( i ).equals( "traditional" ) ) guiType = DescriptorData.GUI_TRADITIONAL; else if( attrs.getValue( i ).equals( "contextual" ) ) guiType = DescriptorData.GUI_CONTEXTUAL; } // Customized GUI else if( attrs.getLocalName( i ).equals( "customized" ) ) { guiCustomized = attrs.getValue( i ).equals( "yes" ); } if( attrs.getLocalName( i ).equals( "inventoryPosition" ) ) { if( attrs.getValue( i ).equals( "none" ) ) inventoryPosition = DescriptorData.INVENTORY_NONE; else if( attrs.getValue( i ).equals( "top_bottom" ) ) inventoryPosition = DescriptorData.INVENTORY_TOP_BOTTOM; else if( attrs.getValue( i ).equals( "top" ) ) inventoryPosition = DescriptorData.INVENTORY_TOP; else if( attrs.getValue( i ).equals( "bottom" ) ) inventoryPosition = DescriptorData.INVENTORY_BOTTOM; } } // Set the values gameDescriptor.setGUI( guiType, guiCustomized ); gameDescriptor.setInventoryPosition( inventoryPosition ); } //Cursor if( sName.equals( "cursor" ) ) { String type = ""; String uri = ""; for( int i = 0; i < attrs.getLength( ); i++ ) { if( attrs.getLocalName( i ).equals( "type" ) ) { type = attrs.getValue( i ); } else if( attrs.getLocalName( i ).equals( "uri" ) ) { uri = attrs.getValue( i ); } } gameDescriptor.addCursor( type, uri ); } //Button if( sName.equals( "button" ) ) { String type = ""; String uri = ""; String action = ""; for( int i = 0; i < attrs.getLength( ); i++ ) { if( attrs.getLocalName( i ).equals( "type" ) ) { type = attrs.getValue( i ); } else if( attrs.getLocalName( i ).equals( "uri" ) ) { uri = attrs.getValue( i ); } else if( attrs.getLocalName( i ).equals( "action" ) ) { action = attrs.getValue( i ); } } gameDescriptor.addButton( action, type, uri ); } if( sName.equals( "arrow" ) ) { String type = ""; String uri = ""; for( int i = 0; i < attrs.getLength( ); i++ ) { if( attrs.getLocalName( i ).equals( "type" ) ) { type = attrs.getValue( i ); } else if( attrs.getLocalName( i ).equals( "uri" ) ) { uri = attrs.getValue( i ); } } gameDescriptor.addArrow( type, uri ); } if( sName.endsWith( "automatic-commentaries" ) ) { gameDescriptor.setCommentaries( true ); } //If the element is the player mode, store value if( sName.equals( "mode" ) ) { for( int i = 0; i < attrs.getLength( ); i++ ) { if( attrs.getLocalName( i ).equals( "playerTransparent" ) ) { if( attrs.getValue( i ).equals( "yes" ) ) { gameDescriptor.setPlayerMode( DescriptorData.MODE_PLAYER_1STPERSON ); } else if( attrs.getValue( i ).equals( "no" ) ) { gameDescriptor.setPlayerMode( DescriptorData.MODE_PLAYER_3RDPERSON ); } } } } if( sName.equals( "graphics" ) ) { for( int i = 0; i < attrs.getLength( ); i++ ) { if( attrs.getLocalName( i ).equals( "mode" ) ) { if( attrs.getValue( i ).equals( "windowed" ) ) { gameDescriptor.setGraphicConfig( DescriptorData.GRAPHICS_WINDOWED ); } else if( attrs.getValue( i ).equals( "fullscreen" ) ) { gameDescriptor.setGraphicConfig( DescriptorData.GRAPHICS_FULLSCREEN ); } else if( attrs.getValue( i ).equals( "blackbkg" ) ) { gameDescriptor.setGraphicConfig( DescriptorData.GRAPHICS_BLACKBKG ); } } } } if( sName.equals( "type" ) ) { boolean gpsMode = false; boolean qrCodeMode = false; for( int i = 0; i < attrs.getLength( ); i++ ) { // Type of the GUI if( attrs.getLocalName( i ).equals( "barcode" ) ) { qrCodeMode = attrs.getValue( i ).equals( "yes" ); } // Customized GUI else if( attrs.getLocalName( i ).equals( "geolocated" ) ) { gpsMode = attrs.getValue( i ).equals( "yes" ); } } // Set the values gameDescriptor.setGpsMode(gpsMode); gameDescriptor.setQrCodeMode(qrCodeMode); } // If it is a chapter, create it and store the path else if( sName.equals( "chapter" ) ) { currentChapter = new ChapterSummary( ); // Store the path of the chapter for( int i = 0; i < attrs.getLength( ); i++ ) if( attrs.getLocalName( i ).equals( "path" ) ) currentChapter.setChapterPath( attrs.getValue( i ) ); // Change the state reading = READING_CHAPTER; } // If it is an adaptation file, store the path // With last profile modifications, only old games includes that information in its descriptor file. // For that reason, the next "path" info is the name of the profile, and it is necessary to eliminate the path's characteristic // such as / and .xml else if( sName.equals( "adaptation-configuration" ) ) { // Store the path of the adaptation file for( int i = 0; i < attrs.getLength( ); i++ ) if( attrs.getLocalName( i ).equals( "path" ) ) { String adaptationName = attrs.getValue( i ); // delete the path's characteristics // adaptationName = adaptationName.substring(adaptationName.indexOf("/")+1); // adaptationName = adaptationName.substring(0,adaptationName.indexOf(".")); currentChapter.setAdaptationName( adaptationName ); } } // If it is an assessment file, store the path // With last profile modifications, only old games includes that information in its descriptor file. // For that reason, the next "path" info is the name of the profile, and it is necessary to eliminate the path's characteristic // such as / and .xml else if( sName.equals( "assessment-configuration" ) ) { // Store the path of the assessment file for( int i = 0; i < attrs.getLength( ); i++ ) if( attrs.getLocalName( i ).equals( "path" ) ) { String assessmentName = attrs.getValue( i ); // delete the path's characteristics // assessmentName = assessmentName.substring(assessmentName.indexOf("/")+1); // assessmentName = assessmentName.substring(0,assessmentName.indexOf(".")); currentChapter.setAssessmentName( assessmentName ); } } } /* * (non-Javadoc) * @see org.xml.sax.ContentHandler#endElement(java.lang.String, java.lang.String, java.lang.String) */ @Override public void endElement( String namespaceURI, String sName, String qName ) throws SAXException { // Stores the title if( sName.equals( "title" ) ) { if( reading == READING_NONE ) gameDescriptor.setTitle( currentString.toString( ).trim( ) ); else if( reading == READING_CHAPTER ) currentChapter.setTitle( currentString.toString( ).trim( ) ); } // Stores the description else if( sName.equals( "description" ) ) { if( reading == READING_NONE ) gameDescriptor.setDescription( currentString.toString( ).trim( ) ); else if( reading == READING_CHAPTER ) currentChapter.setDescription( currentString.toString( ).trim( ) ); } // Change the state if ends reading a chapter else if( sName.equals( "chapter" ) ) { // Add the new chapter and change the state gameDescriptor.addChapterSummary( currentChapter ); reading = READING_NONE; } // Reset the current string currentString = new StringBuffer( ); } /* * (non-Javadoc) * @see org.xml.sax.ContentHandler#characters(char[], int, int) */ @Override public void characters( char[] buf, int offset, int len ) throws SAXException { // Append the new characters currentString.append( new String( buf, offset, len ) ); } /* * (non-Javadoc) * @see org.xml.sax.ErrorHandler#error(org.xml.sax.SAXParseException) */ @Override public void error( SAXParseException exception ) throws SAXParseException { // On validation, propagate exception exception.printStackTrace( ); throw exception; } /* * (non-Javadoc) * @see org.xml.sax.EntityResolver#resolveEntity(java.lang.String, java.lang.String) */ @Override public InputSource resolveEntity( String publicId, String systemId ) { int startFilename = systemId.lastIndexOf( "/" ) + 1; String filename = systemId.substring( startFilename, systemId.length( ) ); InputStream inputStream = isCreator.buildInputStream( filename ); return new InputSource( inputStream ); } }
UTF-8
Java
16,035
java
DescriptorHandler.java
Java
[ { "context": "puter Science).\n * \n * C Profesor Jose Garcia Santesmases sn,\n * 28040 Madrid (Madrid), Spain.\n * ", "end": 544, "score": 0.9993805289268494, "start": 518, "tag": "NAME", "value": "Jose Garcia Santesmases sn" }, { "context": ", version 1...
null
[]
/******************************************************************************* * <e-Adventure> Mobile for Android(TM) is a port of the <e-Adventure> research project to the Android(TM) platform. * * Copyright 2009-2012 <e-UCM> research group. * * <e-UCM> is a research group of the Department of Software Engineering * and Artificial Intelligence at the Complutense University of Madrid * (School of Computer Science). * * C Profesor <NAME>, * 28040 Madrid (Madrid), Spain. * * For more info please visit: <http://e-adventure.e-ucm.es/android> or * <http://www.e-ucm.es> * * *Android is a trademark of Google Inc. * * **************************************************************************** * This file is part of <e-Adventure> Mobile, version 1.0. * * Main contributors - <NAME> * * Former contributors - <NAME> * <NAME> * <NAME> * * Directors - <NAME> * <NAME> * * You can access a list of all the contributors to <e-Adventure> Mobile at: * http://e-adventure.e-ucm.es/contributors * * **************************************************************************** * <e-Adventure> Mobile is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * <e-Adventure> Mobile 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 Lesser General Public License for more details. * * See <http://www.gnu.org/licenses/> ******************************************************************************/ package es.eucm.eadandroid.common.loader.parsers; import java.io.InputStream; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler; import es.eucm.eadandroid.common.data.adventure.ChapterSummary; import es.eucm.eadandroid.common.data.adventure.DescriptorData; import es.eucm.eadandroid.common.data.adventure.DescriptorData.Perspective; import es.eucm.eadandroid.common.loader.InputStreamCreator; /** * This class is the handler to parse the e-Adventure descriptor file. * * @author <NAME> */ public class DescriptorHandler extends DefaultHandler { /** * Constant for reading nothing */ private static final int READING_NONE = 0; /** * Constant for reading a chapter */ private static final int READING_CHAPTER = 1; /** * String to store the current string in the XML file */ private StringBuffer currentString; /** * Stores the game descriptor being read */ private DescriptorData gameDescriptor; /** * Stores the element which is being read */ private int reading = READING_NONE; /** * Chapter being currently read */ private ChapterSummary currentChapter; /** * InputStreamCreator used in resolveEntity to find dtds (only required in * Applet mode) */ private InputStreamCreator isCreator; /** * Constructor */ public DescriptorHandler( InputStreamCreator isCreator ) { currentString = new StringBuffer( ); gameDescriptor = new DescriptorData( ); this.isCreator = isCreator; } /** * Returns the game descriptor read * * @return Game descriptor */ public DescriptorData getGameDescriptor( ) { return gameDescriptor; } /* * (non-Javadoc) * @see org.xml.sax.ContentHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes) */ @Override public void startElement( String namespaceURI, String sName, String qName, Attributes attrs ) throws SAXException { if( sName.equals( "game-descriptor" ) ) { for( int i = 0; i < attrs.getLength( ); i++ ) if( attrs.getLocalName( i ).equals( "versionNumber" ) ) { gameDescriptor.setVersionNumber( attrs.getValue( i ) ); } } if( qName.equals( "configuration" ) ) { for( int i = 0; i < attrs.getLength( ); i++ ) { if( attrs.getLocalName( i ).equals( "keepShowing" ) ) gameDescriptor.setKeepShowing( attrs.getValue( i ).equals( "yes" ) ); if ( attrs.getLocalName( i ).equals( "perspective" )) { if (attrs.getValue( i ).equals( "regular" )) gameDescriptor.setPerspective( Perspective.REGULAR ); if (attrs.getValue( i ).equals( "isometric" )) gameDescriptor.setPerspective( Perspective.ISOMETRIC ); } } } // If the element is the GUI configuration, store the values if( sName.equals( "gui" ) ) { int guiType = DescriptorData.GUI_TRADITIONAL; boolean guiCustomized = false; int inventoryPosition = DescriptorData.INVENTORY_TOP_BOTTOM; for( int i = 0; i < attrs.getLength( ); i++ ) { // Type of the GUI if( attrs.getLocalName( i ).equals( "type" ) ) { if( attrs.getValue( i ).equals( "traditional" ) ) guiType = DescriptorData.GUI_TRADITIONAL; else if( attrs.getValue( i ).equals( "contextual" ) ) guiType = DescriptorData.GUI_CONTEXTUAL; } // Customized GUI else if( attrs.getLocalName( i ).equals( "customized" ) ) { guiCustomized = attrs.getValue( i ).equals( "yes" ); } if( attrs.getLocalName( i ).equals( "inventoryPosition" ) ) { if( attrs.getValue( i ).equals( "none" ) ) inventoryPosition = DescriptorData.INVENTORY_NONE; else if( attrs.getValue( i ).equals( "top_bottom" ) ) inventoryPosition = DescriptorData.INVENTORY_TOP_BOTTOM; else if( attrs.getValue( i ).equals( "top" ) ) inventoryPosition = DescriptorData.INVENTORY_TOP; else if( attrs.getValue( i ).equals( "bottom" ) ) inventoryPosition = DescriptorData.INVENTORY_BOTTOM; } } // Set the values gameDescriptor.setGUI( guiType, guiCustomized ); gameDescriptor.setInventoryPosition( inventoryPosition ); } //Cursor if( sName.equals( "cursor" ) ) { String type = ""; String uri = ""; for( int i = 0; i < attrs.getLength( ); i++ ) { if( attrs.getLocalName( i ).equals( "type" ) ) { type = attrs.getValue( i ); } else if( attrs.getLocalName( i ).equals( "uri" ) ) { uri = attrs.getValue( i ); } } gameDescriptor.addCursor( type, uri ); } //Button if( sName.equals( "button" ) ) { String type = ""; String uri = ""; String action = ""; for( int i = 0; i < attrs.getLength( ); i++ ) { if( attrs.getLocalName( i ).equals( "type" ) ) { type = attrs.getValue( i ); } else if( attrs.getLocalName( i ).equals( "uri" ) ) { uri = attrs.getValue( i ); } else if( attrs.getLocalName( i ).equals( "action" ) ) { action = attrs.getValue( i ); } } gameDescriptor.addButton( action, type, uri ); } if( sName.equals( "arrow" ) ) { String type = ""; String uri = ""; for( int i = 0; i < attrs.getLength( ); i++ ) { if( attrs.getLocalName( i ).equals( "type" ) ) { type = attrs.getValue( i ); } else if( attrs.getLocalName( i ).equals( "uri" ) ) { uri = attrs.getValue( i ); } } gameDescriptor.addArrow( type, uri ); } if( sName.endsWith( "automatic-commentaries" ) ) { gameDescriptor.setCommentaries( true ); } //If the element is the player mode, store value if( sName.equals( "mode" ) ) { for( int i = 0; i < attrs.getLength( ); i++ ) { if( attrs.getLocalName( i ).equals( "playerTransparent" ) ) { if( attrs.getValue( i ).equals( "yes" ) ) { gameDescriptor.setPlayerMode( DescriptorData.MODE_PLAYER_1STPERSON ); } else if( attrs.getValue( i ).equals( "no" ) ) { gameDescriptor.setPlayerMode( DescriptorData.MODE_PLAYER_3RDPERSON ); } } } } if( sName.equals( "graphics" ) ) { for( int i = 0; i < attrs.getLength( ); i++ ) { if( attrs.getLocalName( i ).equals( "mode" ) ) { if( attrs.getValue( i ).equals( "windowed" ) ) { gameDescriptor.setGraphicConfig( DescriptorData.GRAPHICS_WINDOWED ); } else if( attrs.getValue( i ).equals( "fullscreen" ) ) { gameDescriptor.setGraphicConfig( DescriptorData.GRAPHICS_FULLSCREEN ); } else if( attrs.getValue( i ).equals( "blackbkg" ) ) { gameDescriptor.setGraphicConfig( DescriptorData.GRAPHICS_BLACKBKG ); } } } } if( sName.equals( "type" ) ) { boolean gpsMode = false; boolean qrCodeMode = false; for( int i = 0; i < attrs.getLength( ); i++ ) { // Type of the GUI if( attrs.getLocalName( i ).equals( "barcode" ) ) { qrCodeMode = attrs.getValue( i ).equals( "yes" ); } // Customized GUI else if( attrs.getLocalName( i ).equals( "geolocated" ) ) { gpsMode = attrs.getValue( i ).equals( "yes" ); } } // Set the values gameDescriptor.setGpsMode(gpsMode); gameDescriptor.setQrCodeMode(qrCodeMode); } // If it is a chapter, create it and store the path else if( sName.equals( "chapter" ) ) { currentChapter = new ChapterSummary( ); // Store the path of the chapter for( int i = 0; i < attrs.getLength( ); i++ ) if( attrs.getLocalName( i ).equals( "path" ) ) currentChapter.setChapterPath( attrs.getValue( i ) ); // Change the state reading = READING_CHAPTER; } // If it is an adaptation file, store the path // With last profile modifications, only old games includes that information in its descriptor file. // For that reason, the next "path" info is the name of the profile, and it is necessary to eliminate the path's characteristic // such as / and .xml else if( sName.equals( "adaptation-configuration" ) ) { // Store the path of the adaptation file for( int i = 0; i < attrs.getLength( ); i++ ) if( attrs.getLocalName( i ).equals( "path" ) ) { String adaptationName = attrs.getValue( i ); // delete the path's characteristics // adaptationName = adaptationName.substring(adaptationName.indexOf("/")+1); // adaptationName = adaptationName.substring(0,adaptationName.indexOf(".")); currentChapter.setAdaptationName( adaptationName ); } } // If it is an assessment file, store the path // With last profile modifications, only old games includes that information in its descriptor file. // For that reason, the next "path" info is the name of the profile, and it is necessary to eliminate the path's characteristic // such as / and .xml else if( sName.equals( "assessment-configuration" ) ) { // Store the path of the assessment file for( int i = 0; i < attrs.getLength( ); i++ ) if( attrs.getLocalName( i ).equals( "path" ) ) { String assessmentName = attrs.getValue( i ); // delete the path's characteristics // assessmentName = assessmentName.substring(assessmentName.indexOf("/")+1); // assessmentName = assessmentName.substring(0,assessmentName.indexOf(".")); currentChapter.setAssessmentName( assessmentName ); } } } /* * (non-Javadoc) * @see org.xml.sax.ContentHandler#endElement(java.lang.String, java.lang.String, java.lang.String) */ @Override public void endElement( String namespaceURI, String sName, String qName ) throws SAXException { // Stores the title if( sName.equals( "title" ) ) { if( reading == READING_NONE ) gameDescriptor.setTitle( currentString.toString( ).trim( ) ); else if( reading == READING_CHAPTER ) currentChapter.setTitle( currentString.toString( ).trim( ) ); } // Stores the description else if( sName.equals( "description" ) ) { if( reading == READING_NONE ) gameDescriptor.setDescription( currentString.toString( ).trim( ) ); else if( reading == READING_CHAPTER ) currentChapter.setDescription( currentString.toString( ).trim( ) ); } // Change the state if ends reading a chapter else if( sName.equals( "chapter" ) ) { // Add the new chapter and change the state gameDescriptor.addChapterSummary( currentChapter ); reading = READING_NONE; } // Reset the current string currentString = new StringBuffer( ); } /* * (non-Javadoc) * @see org.xml.sax.ContentHandler#characters(char[], int, int) */ @Override public void characters( char[] buf, int offset, int len ) throws SAXException { // Append the new characters currentString.append( new String( buf, offset, len ) ); } /* * (non-Javadoc) * @see org.xml.sax.ErrorHandler#error(org.xml.sax.SAXParseException) */ @Override public void error( SAXParseException exception ) throws SAXParseException { // On validation, propagate exception exception.printStackTrace( ); throw exception; } /* * (non-Javadoc) * @see org.xml.sax.EntityResolver#resolveEntity(java.lang.String, java.lang.String) */ @Override public InputSource resolveEntity( String publicId, String systemId ) { int startFilename = systemId.lastIndexOf( "/" ) + 1; String filename = systemId.substring( startFilename, systemId.length( ) ); InputStream inputStream = isCreator.buildInputStream( filename ); return new InputSource( inputStream ); } }
15,929
0.534269
0.531961
412
37.919903
30.362789
135
false
false
0
0
0
0
0
0
0.468447
false
false
14
2060c47ac885a6a598d8b4f49ef35aeafe1f0af8
15,135,464,780,017
3bd6cbeb140d843a0faa0eaf1d6e35e3f8af7fd5
/Programacion/Trabajos/Mayo/27deMayo-colecciones/Zoologico/Animal.java
1cdd81891b9f3ed632e68077d7623bdfbf6b2922
[]
no_license
ArKaGarCa/Trabajos-5to
https://github.com/ArKaGarCa/Trabajos-5to
2d7eb1a4e027554252f064312397f11a4c09963e
ff07ddaa361814e32fa6e6df968ab67e33526bba
refs/heads/master
2020-05-27T03:43:16.611000
2019-11-17T18:49:15
2019-11-17T18:49:15
188,469,033
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Zoologico; public class Animal{ private String nombre; private boolean esHerbivoro; public Animal(){ this.nombre = "Nico"; this.esHerbivoro = false; } public boolean isEsHerbivoro() { return esHerbivoro; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public void setEsHerbivoro(boolean esHerbivoro) { this.esHerbivoro = esHerbivoro; } }
UTF-8
Java
509
java
Animal.java
Java
[ { "context": "oro;\n\n public Animal(){\n this.nombre = \"Nico\";\n this.esHerbivoro = false;\n }\n\n pu", "end": 150, "score": 0.966256856918335, "start": 146, "tag": "NAME", "value": "Nico" } ]
null
[]
package Zoologico; public class Animal{ private String nombre; private boolean esHerbivoro; public Animal(){ this.nombre = "Nico"; this.esHerbivoro = false; } public boolean isEsHerbivoro() { return esHerbivoro; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public void setEsHerbivoro(boolean esHerbivoro) { this.esHerbivoro = esHerbivoro; } }
509
0.616896
0.616896
27
17.888889
15.687535
53
false
false
0
0
0
0
0
0
0.333333
false
false
14
1a48c023f2d8679e52b3e668b519ec0d3930ce03
11,295,764,017,400
f244713f35585e42d22321d5afd50f9bde2d891d
/src/bean/Mix.java
0ebad8782e3ed8827ff89cec29f5eee3587003de
[]
no_license
hoatruongdev09/QLLuuTru
https://github.com/hoatruongdev09/QLLuuTru
3fc46daf5b943c8ee8261962ac965d3895159e92
f8124a40759bb6873c561a17b85114616bed7860
refs/heads/master
2020-04-11T08:12:16.079000
2018-12-13T12:21:44
2018-12-13T12:21:44
161,635,148
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package bean; public class Mix { public CongDanBean congDan; public HoKhauBean hoKhau; public LichSuLuuTru lichSuLT; public LoaiLuuTruBean loaiLT; public Mix(CongDanBean congDan, HoKhauBean hoKhau, LichSuLuuTru lichSuLT, LoaiLuuTruBean loaiLT) { super(); this.congDan = congDan; this.hoKhau = hoKhau; this.lichSuLT = lichSuLT; this.loaiLT = loaiLT; } public CongDanBean getCongDan() { return congDan; } public void setCongDan(CongDanBean congDan) { this.congDan = congDan; } public HoKhauBean getHoKhau() { return hoKhau; } public void setHoKhau(HoKhauBean hoKhau) { this.hoKhau = hoKhau; } public LichSuLuuTru getLichSuLT() { return lichSuLT; } public void setLichSuLT(LichSuLuuTru lichSuLT) { this.lichSuLT = lichSuLT; } public LoaiLuuTruBean getLoaiLT() { return loaiLT; } public void setLoaiLT(LoaiLuuTruBean loaiLT) { this.loaiLT = loaiLT; } }
UTF-8
Java
902
java
Mix.java
Java
[]
null
[]
package bean; public class Mix { public CongDanBean congDan; public HoKhauBean hoKhau; public LichSuLuuTru lichSuLT; public LoaiLuuTruBean loaiLT; public Mix(CongDanBean congDan, HoKhauBean hoKhau, LichSuLuuTru lichSuLT, LoaiLuuTruBean loaiLT) { super(); this.congDan = congDan; this.hoKhau = hoKhau; this.lichSuLT = lichSuLT; this.loaiLT = loaiLT; } public CongDanBean getCongDan() { return congDan; } public void setCongDan(CongDanBean congDan) { this.congDan = congDan; } public HoKhauBean getHoKhau() { return hoKhau; } public void setHoKhau(HoKhauBean hoKhau) { this.hoKhau = hoKhau; } public LichSuLuuTru getLichSuLT() { return lichSuLT; } public void setLichSuLT(LichSuLuuTru lichSuLT) { this.lichSuLT = lichSuLT; } public LoaiLuuTruBean getLoaiLT() { return loaiLT; } public void setLoaiLT(LoaiLuuTruBean loaiLT) { this.loaiLT = loaiLT; } }
902
0.737251
0.737251
41
21
19.068554
99
false
false
0
0
0
0
0
0
1.731707
false
false
14
fed9aeb50c68b7477e4cae704d5726ef0f752d1b
16,303,695,888,436
3b3a98fba603ce3d2793a1bd0406311e92599444
/ListasDoblesEstudiantes/src/listas/Listas.java
26e1c99b3dc2d4fef17c118230ce7ca721a8fd34
[]
no_license
mariana458/Estructura_De_Datos
https://github.com/mariana458/Estructura_De_Datos
55b756c34ec5eb145e081e9d92a71508245ec049
7ccba6606bcaa5ffe6270f44ce7931c541f618fd
refs/heads/master
2021-01-06T23:31:09.293000
2020-05-27T17:13:43
2020-05-27T17:13:43
241,513,370
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/*000 * 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 listas; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author s208e19 */ public class Listas { /** * @param args the command line arguments */ public static void main(String[] args) throws Exception { // TODO code application logic here DoublyLinkedListEstudent<Estudiante> Students = new DoublyLinkedListEstudent<>(); DoublyLinkedListEstudent<Estudiante> Winner= new DoublyLinkedListEstudent<>(); DoublyLinkedListEstudent<Estudiante> Loser = new DoublyLinkedListEstudent<>(); InsertEstudent("1000439971", "Mariana", "Bombona", 2.7,Students,Winner,Loser); InsertEstudent("1020324181", "Laura", "Moravia", 3.2,Students,Winner,Loser); InsertEstudent("86041454", "Angeline", "Blanquizal", 5,Students,Winner,Loser); InsertEstudent("32106270", "Angie", "Caicedo", 2.9,Students,Winner,Loser); InsertEstudent("1201547889", "Ana", "Bombona", 1.5,Students,Winner,Loser); InsertEstudent("1234567892", "Edwin", "Enciso", 3.9,Students,Winner,Loser); InsertEstudent("2547893154", "Lourdes", "Enciso", 4.1,Students,Winner,Loser); //Permitir mostrar la lista de estudiantes con todos sus datos desde la cabeza a la cola. System.out.println("Mostrar"); System.out.println(Students.showData()); System.out.println(""); //Permitir buscar un estudiante por su código y mostrar todos sus datos, System.out.println("Buscar un estudiante por su codigo"); System.out.println(Students.searchEstudent("1000439971")); System.out.println(""); //Mostrar el nombre de todos los estudiantes que pertenecen a un mismo barrio System.out.println("Buscar estudiantes que pertenecen a un mismo barrio"); System.out.println(Students.searcneighborhood("Bombona")); System.out.println(""); } public static void InsertEstudent(String cedula, String nombre, String barrio, double nota,DoublyLinkedListEstudent<Estudiante> Estudents, DoublyLinkedListEstudent<Estudiante>Winner, DoublyLinkedListEstudent<Estudiante> Loser) throws Exception { Estudiante est = new Estudiante(cedula, nombre, barrio, nota); if (nota < 3.0) { Estudents.add(est); Loser.add(est); } else { Estudents.add(est); Winner.add(est); } } }
UTF-8
Java
2,703
java
Listas.java
Java
[ { "context": "mport java.util.logging.Logger;\n\n/**\n *\n * @author s208e19\n */\npublic class Listas {\n\n /**\n * @param ", "end": 296, "score": 0.9992860555648804, "start": 289, "tag": "USERNAME", "value": "s208e19" }, { "context": " \n \n InsertEstudent(\"1...
null
[]
/*000 * 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 listas; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author s208e19 */ public class Listas { /** * @param args the command line arguments */ public static void main(String[] args) throws Exception { // TODO code application logic here DoublyLinkedListEstudent<Estudiante> Students = new DoublyLinkedListEstudent<>(); DoublyLinkedListEstudent<Estudiante> Winner= new DoublyLinkedListEstudent<>(); DoublyLinkedListEstudent<Estudiante> Loser = new DoublyLinkedListEstudent<>(); InsertEstudent("1000439971", "Mariana", "Bombona", 2.7,Students,Winner,Loser); InsertEstudent("1020324181", "Laura", "Moravia", 3.2,Students,Winner,Loser); InsertEstudent("86041454", "Angeline", "Blanquizal", 5,Students,Winner,Loser); InsertEstudent("32106270", "Angie", "Caicedo", 2.9,Students,Winner,Loser); InsertEstudent("1201547889", "Ana", "Bombona", 1.5,Students,Winner,Loser); InsertEstudent("1234567892", "Edwin", "Enciso", 3.9,Students,Winner,Loser); InsertEstudent("2547893154", "Lourdes", "Enciso", 4.1,Students,Winner,Loser); //Permitir mostrar la lista de estudiantes con todos sus datos desde la cabeza a la cola. System.out.println("Mostrar"); System.out.println(Students.showData()); System.out.println(""); //Permitir buscar un estudiante por su código y mostrar todos sus datos, System.out.println("Buscar un estudiante por su codigo"); System.out.println(Students.searchEstudent("1000439971")); System.out.println(""); //Mostrar el nombre de todos los estudiantes que pertenecen a un mismo barrio System.out.println("Buscar estudiantes que pertenecen a un mismo barrio"); System.out.println(Students.searcneighborhood("Bombona")); System.out.println(""); } public static void InsertEstudent(String cedula, String nombre, String barrio, double nota,DoublyLinkedListEstudent<Estudiante> Estudents, DoublyLinkedListEstudent<Estudiante>Winner, DoublyLinkedListEstudent<Estudiante> Loser) throws Exception { Estudiante est = new Estudiante(cedula, nombre, barrio, nota); if (nota < 3.0) { Estudents.add(est); Loser.add(est); } else { Estudents.add(est); Winner.add(est); } } }
2,703
0.65322
0.61658
70
37.599998
33.746704
115
false
false
0
0
0
0
0
0
1.171429
false
false
14
a6cdc51327face52abad5498e42560a125abc1fb
7,559,142,477,126
8de92674c759c12ef6f990ca93ad681a45ff8ba6
/src/main/java/by/epam/receptionenrollee/command/ActionFactory.java
daa54187ed442f45649dc222e8c4845251d976cb
[]
no_license
maruvuina/ReceptionEnrolleeProject
https://github.com/maruvuina/ReceptionEnrolleeProject
e4dfa83cd615f44ef3a9eb9b01471871a0532b1e
2344c02bbffcbc612313ac307c43fe0268f4460e
refs/heads/master
2023-05-11T22:32:31.676000
2022-09-10T18:43:36
2022-09-10T18:43:36
225,902,931
0
2
null
false
2023-05-01T21:19:35
2019-12-04T15:50:44
2022-09-10T18:39:05
2023-05-01T21:19:34
16,980
0
0
1
JavaScript
false
false
package by.epam.receptionenrollee.command; import by.epam.receptionenrollee.manager.MessageManager; import javax.servlet.http.HttpServletRequest; import java.util.Arrays; import static by.epam.receptionenrollee.command.RequestParam.PARAM_NAME_LANGUAGE_SITE; public class ActionFactory { private static final ActionFactory INSTANCE = new ActionFactory(); private ActionFactory() {} public static ActionFactory getInstance() { return INSTANCE; } public ActionCommand defineCommand(HttpServletRequest request) { String commandName = request.getParameter("command"); return Arrays.stream(CommandType.values()) .filter(command -> command.name().equalsIgnoreCase(commandName)) .map(CommandType::getCommand) .findAny() .orElseGet(() -> { request.setAttribute("wrongAction", request.getParameter("command") + new MessageManager((String) request .getSession() .getAttribute(PARAM_NAME_LANGUAGE_SITE)).getProperty("message.wrongaction")); return CommandType.LOGIN.getCommand(); }); } }
UTF-8
Java
1,287
java
ActionFactory.java
Java
[]
null
[]
package by.epam.receptionenrollee.command; import by.epam.receptionenrollee.manager.MessageManager; import javax.servlet.http.HttpServletRequest; import java.util.Arrays; import static by.epam.receptionenrollee.command.RequestParam.PARAM_NAME_LANGUAGE_SITE; public class ActionFactory { private static final ActionFactory INSTANCE = new ActionFactory(); private ActionFactory() {} public static ActionFactory getInstance() { return INSTANCE; } public ActionCommand defineCommand(HttpServletRequest request) { String commandName = request.getParameter("command"); return Arrays.stream(CommandType.values()) .filter(command -> command.name().equalsIgnoreCase(commandName)) .map(CommandType::getCommand) .findAny() .orElseGet(() -> { request.setAttribute("wrongAction", request.getParameter("command") + new MessageManager((String) request .getSession() .getAttribute(PARAM_NAME_LANGUAGE_SITE)).getProperty("message.wrongaction")); return CommandType.LOGIN.getCommand(); }); } }
1,287
0.6115
0.6115
34
36.85294
29.690693
113
false
false
0
0
0
0
0
0
0.352941
false
false
14
51ff24368a0be11306fcc8e2a8e4cd4c4a69a833
12,790,412,642,176
82be85a3036eb162f9f9476a460f3eb323d07f71
/app/utils/DefaultTransactionIdGenerator.java
14058d37b054aaa1e4f94be5a7c656a7378a620b
[]
no_license
asifbshaikh/proposedsociety
https://github.com/asifbshaikh/proposedsociety
ae50b0bbe4d6338d33bd48835c285dc2a2842f5b
ef6304d339238bc9eca63afb3beb284864128fd7
refs/heads/master
2020-04-17T09:11:11.384000
2019-01-18T17:39:23
2019-01-18T17:39:23
166,448,142
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package utils; import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.atomic.AtomicInteger; public final class DefaultTransactionIdGenerator implements TransactionIdGenerator { private final AtomicInteger counter = new AtomicInteger(0); @Override public String generateTxnId() { StringBuilder txnId = new StringBuilder(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())); int tick = Math.abs(counter.getAndIncrement() % 100); if (tick < 10) { txnId.append("0"); } return txnId.append(tick).toString(); } }
UTF-8
Java
568
java
DefaultTransactionIdGenerator.java
Java
[]
null
[]
package utils; import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.atomic.AtomicInteger; public final class DefaultTransactionIdGenerator implements TransactionIdGenerator { private final AtomicInteger counter = new AtomicInteger(0); @Override public String generateTxnId() { StringBuilder txnId = new StringBuilder(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())); int tick = Math.abs(counter.getAndIncrement() % 100); if (tick < 10) { txnId.append("0"); } return txnId.append(tick).toString(); } }
568
0.757042
0.744718
22
24.818182
28.631889
101
false
false
0
0
0
0
0
0
1.227273
false
false
14
2b21067a890494646269505dfa06487eae25913d
20,779,051,807,427
dbbf117cb82923698bff83e2e022cf0ebae70d9b
/chapter_007/src/main/java/ru/job4j/stepik/ResetInterruption.java
9723e0bb3c3cafd3806cc6fc7fe31e1ddf34eeb9
[ "Apache-2.0" ]
permissive
andreiHi/hincuA
https://github.com/andreiHi/hincuA
a5eae5133ade19d203c69612f3b705fde7400f7f
506ada9b20200e030c2208a03ce99c13e314d6c3
refs/heads/master
2023-03-10T18:21:15.974000
2022-07-01T14:00:33
2022-07-01T14:00:33
101,287,137
2
0
Apache-2.0
false
2023-02-22T07:01:22
2017-08-24T11:21:08
2022-02-27T07:43:42
2023-02-22T07:01:21
15,507
0
0
5
Java
false
false
package ru.job4j.stepik; import java.util.concurrent.TimeUnit; /** * Java doesn't provide any safe mechanism to stop the running thread, instead it provides so called interruption, * which is a policy (or otherwise could be called the cooperation) between the running threads. * Although if the policy is unknown, or the running thread doesn't handle interruption exception, * it should not swallow it, but instead reset the interruption status back (as methods which could throw InterruptedException * clear the interruption status which has to be reset back). * So, in the code below how do you restore and check for the interruption status of the running thread? */ public class ResetInterruption implements Runnable { public static void main(final String[] args) throws Exception { final Thread thread = new Thread(new ResetInterruption()); thread.start(); thread.join(); System.out.printf("Interrupted %b%n", thread.isInterrupted()); } @Override public void run() { try { // The interrupted status of the current thread is cleared when InterruptedException is thrown by sleep() method. TimeUnit.SECONDS.sleep(10); } catch (final InterruptedException ex) { Thread.currentThread().interrupt(); } } }
UTF-8
Java
1,328
java
ResetInterruption.java
Java
[]
null
[]
package ru.job4j.stepik; import java.util.concurrent.TimeUnit; /** * Java doesn't provide any safe mechanism to stop the running thread, instead it provides so called interruption, * which is a policy (or otherwise could be called the cooperation) between the running threads. * Although if the policy is unknown, or the running thread doesn't handle interruption exception, * it should not swallow it, but instead reset the interruption status back (as methods which could throw InterruptedException * clear the interruption status which has to be reset back). * So, in the code below how do you restore and check for the interruption status of the running thread? */ public class ResetInterruption implements Runnable { public static void main(final String[] args) throws Exception { final Thread thread = new Thread(new ResetInterruption()); thread.start(); thread.join(); System.out.printf("Interrupted %b%n", thread.isInterrupted()); } @Override public void run() { try { // The interrupted status of the current thread is cleared when InterruptedException is thrown by sleep() method. TimeUnit.SECONDS.sleep(10); } catch (final InterruptedException ex) { Thread.currentThread().interrupt(); } } }
1,328
0.708145
0.705882
29
44.724136
40.194267
127
false
false
0
0
0
0
0
0
0.517241
false
false
14
a9104bd23e60e307e591238d53cba590ebc0de2c
240,518,204,677
bd191033b348537ea8a390023ae8665927013a71
/src/com/hwua/ManagementSystem/servlet/admin/T_sportstuServlet.java
da6998677391b1ca71f3748c5876ebfd6e38d4eb
[]
no_license
hebeiqing/ManagementSystem
https://github.com/hebeiqing/ManagementSystem
edba65e30fad71c0020e2b44306e7013e8ec3899
a8b0e36c4a7cbf714881189b15618ba8251dee46
refs/heads/master
2020-06-24T01:57:05.991000
2019-07-25T14:12:58
2019-07-25T14:12:58
198,814,803
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hwua.ManagementSystem.servlet.admin; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.hwua.ManagementSystem.entity.Student; import com.hwua.ManagementSystem.entity.StudentUnion; import com.hwua.ManagementSystem.entity.T_sportstu; import com.hwua.ManagementSystem.service.SportstuService; import com.hwua.ManagementSystem.service.StudentService; import com.hwua.ManagementSystem.service.StudentUnionservice; import com.hwua.ManagementSystem.service.impl.SportstuServiceImpl; import com.hwua.ManagementSystem.service.impl.StudentServiceImpl; import com.hwua.ManagementSystem.service.impl.StudentUnionServiceImpl; import com.hwua.ManagementSystem.util.CommonUtil; @WebServlet("/admin/Sportstu") public class T_sportstuServlet extends HttpServlet { private SportstuService sportstuService; private StudentService studentservice; private StudentUnionservice studentUnionservice; public T_sportstuServlet() { sportstuService=new SportstuServiceImpl(); studentservice=new StudentServiceImpl(); studentUnionservice=new StudentUnionServiceImpl(); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String act=request.getParameter("act"); T_sportstu sportstu=null; int row; switch (act) { case "list": List<T_sportstu> findAll = sportstuService.findAll(); request.setAttribute("sportstuall",findAll ); request.getRequestDispatcher("sportstu_list.jsp").forward(request, response); break; case "edit": String id=request.getParameter("id"); if(id!=null){ sportstu=sportstuService.findById(id); } else{ sportstu=new T_sportstu(); List<Student> student = studentservice.findAll(); List<StudentUnion> unin = studentUnionservice.findAll(); request.setAttribute("student", student); request.setAttribute("unin", unin); } List<StudentUnion> unin = studentUnionservice.findAll(); request.setAttribute("unin", unin); request.setAttribute("idstuun", sportstu); request.getRequestDispatcher("sportstu_eait.jsp").forward(request, response); break; case "save": String crid=request.getParameter("id"); String unid=request.getParameter("unid"); String Stuid=request.getParameter("stuid"); if(crid==null || crid.equals("")){ sportstu=new T_sportstu(); sportstu.setSportStu_ID(CommonUtil.getUUID()); sportstu.setStuId(Stuid); sportstu.setUn_ID(unid); row=sportstuService.create(sportstu); if(row>0){ response.sendRedirect("Sportstu?act=list"); //添加成功则刷新页面 }else{ request.setAttribute("error", "添加学生选修课失败"); request.getRequestDispatcher("Sportstu?act=edit").forward(request, response); } } else{ sportstu=new T_sportstu(); sportstu.setStuId(crid); sportstu.setUn_ID(unid); row=sportstuService.update(sportstu); if(row>0){ response.sendRedirect("Sportstu?act=list"); //添加成功则刷新页面 }else{ request.setAttribute("error", "修改失败"); request.getRequestDispatcher("Sportstu?act=edit").forward(request, response); } } break; case "delete": String deid=request.getParameter("id"); row=sportstuService.delete(deid); if(row>0){ response.sendRedirect("Sportstu?act=list"); //添加成功则刷新页面 }else{ request.setAttribute("error", "删除失败"); request.getRequestDispatcher("Sportstu?act=edit").forward(request, response); } break; } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } }
GB18030
Java
4,035
java
T_sportstuServlet.java
Java
[]
null
[]
package com.hwua.ManagementSystem.servlet.admin; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.hwua.ManagementSystem.entity.Student; import com.hwua.ManagementSystem.entity.StudentUnion; import com.hwua.ManagementSystem.entity.T_sportstu; import com.hwua.ManagementSystem.service.SportstuService; import com.hwua.ManagementSystem.service.StudentService; import com.hwua.ManagementSystem.service.StudentUnionservice; import com.hwua.ManagementSystem.service.impl.SportstuServiceImpl; import com.hwua.ManagementSystem.service.impl.StudentServiceImpl; import com.hwua.ManagementSystem.service.impl.StudentUnionServiceImpl; import com.hwua.ManagementSystem.util.CommonUtil; @WebServlet("/admin/Sportstu") public class T_sportstuServlet extends HttpServlet { private SportstuService sportstuService; private StudentService studentservice; private StudentUnionservice studentUnionservice; public T_sportstuServlet() { sportstuService=new SportstuServiceImpl(); studentservice=new StudentServiceImpl(); studentUnionservice=new StudentUnionServiceImpl(); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String act=request.getParameter("act"); T_sportstu sportstu=null; int row; switch (act) { case "list": List<T_sportstu> findAll = sportstuService.findAll(); request.setAttribute("sportstuall",findAll ); request.getRequestDispatcher("sportstu_list.jsp").forward(request, response); break; case "edit": String id=request.getParameter("id"); if(id!=null){ sportstu=sportstuService.findById(id); } else{ sportstu=new T_sportstu(); List<Student> student = studentservice.findAll(); List<StudentUnion> unin = studentUnionservice.findAll(); request.setAttribute("student", student); request.setAttribute("unin", unin); } List<StudentUnion> unin = studentUnionservice.findAll(); request.setAttribute("unin", unin); request.setAttribute("idstuun", sportstu); request.getRequestDispatcher("sportstu_eait.jsp").forward(request, response); break; case "save": String crid=request.getParameter("id"); String unid=request.getParameter("unid"); String Stuid=request.getParameter("stuid"); if(crid==null || crid.equals("")){ sportstu=new T_sportstu(); sportstu.setSportStu_ID(CommonUtil.getUUID()); sportstu.setStuId(Stuid); sportstu.setUn_ID(unid); row=sportstuService.create(sportstu); if(row>0){ response.sendRedirect("Sportstu?act=list"); //添加成功则刷新页面 }else{ request.setAttribute("error", "添加学生选修课失败"); request.getRequestDispatcher("Sportstu?act=edit").forward(request, response); } } else{ sportstu=new T_sportstu(); sportstu.setStuId(crid); sportstu.setUn_ID(unid); row=sportstuService.update(sportstu); if(row>0){ response.sendRedirect("Sportstu?act=list"); //添加成功则刷新页面 }else{ request.setAttribute("error", "修改失败"); request.getRequestDispatcher("Sportstu?act=edit").forward(request, response); } } break; case "delete": String deid=request.getParameter("id"); row=sportstuService.delete(deid); if(row>0){ response.sendRedirect("Sportstu?act=list"); //添加成功则刷新页面 }else{ request.setAttribute("error", "删除失败"); request.getRequestDispatcher("Sportstu?act=edit").forward(request, response); } break; } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } }
4,035
0.726881
0.726121
122
31.352459
25.607031
119
false
false
0
0
0
0
0
0
3.483607
false
false
14
fc179824e4016224a43008d8bbcb7b5478f69e5e
17,480,516,932,056
f07231459772caaa1a606bc94a2d551871d03919
/src/main/java/FeedbackManagement/GUI/RegisterPanel.java
dfdfefb1ad0477e98d89352e3cd9f3efc18e2b07
[]
no_license
forumber/FeedbackManagementGUI
https://github.com/forumber/FeedbackManagementGUI
726ede9054e4b476b6119e6b6789f340923b771a
46ff6d5ad0b3bbb823295bf0720f78cdadd483de
refs/heads/main
2023-06-10T06:13:01.218000
2021-07-05T07:32:42
2021-07-05T07:32:42
379,020,795
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 FeedbackManagement.GUI; import FeedbackManagement.GUI.RegisterAltPanels.CustomerRegisterPanel; import FeedbackManagement.GUI.RegisterAltPanels.EmployeeRegisterPanel; import FeedbackManagement.GUI.RegisterAltPanels.AdminRegisterPanel; import FeedbackManagement.Models.Admin; import FeedbackManagement.Models.Customer; import FeedbackManagement.Models.Employee; import FeedbackManagement.Models.User; import java.sql.SQLException; import javax.swing.JOptionPane; /** * @author Serhat Korkmaz */ public class RegisterPanel extends javax.swing.JPanel { private final MainFrame mainFrame; private javax.swing.JPanel extraPanel; public RegisterPanel(MainFrame mainFrame) { this.mainFrame = mainFrame; initComponents(); TypeCBActionPerformed(null); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the FormEditor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); UserNameTF = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); EmailTF = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); DateofBirthTF = new javax.swing.JTextField(); PasswordTF = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); RegisterButton = new javax.swing.JButton(); ExtraPanel = new javax.swing.JPanel(); TypeCB = new javax.swing.JComboBox(); BackButton = new javax.swing.JButton(); jLabel1.setText("User Name:"); jLabel2.setText("Email Address:"); jLabel3.setText("Date of Birth:"); DateofBirthTF.setText("DD/MM/YYYY"); DateofBirthTF.setToolTipText("DD/MM/YYYY"); jLabel4.setText("Password:"); jLabel5.setText("UserType:"); RegisterButton.setText("Register"); RegisterButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { RegisterButtonActionPerformed(evt); } }); TypeCB.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Admin", "Employee", "Customer" })); TypeCB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { TypeCBActionPerformed(evt); } }); BackButton.setText("Back"); BackButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BackButtonActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(ExtraPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(BackButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(RegisterButton)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(jLabel3) .addComponent(jLabel4) .addComponent(jLabel5) .addComponent(jLabel1)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(UserNameTF) .addComponent(EmailTF) .addComponent(DateofBirthTF) .addComponent(PasswordTF) .addComponent(TypeCB, 0, 119, Short.MAX_VALUE)))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(UserNameTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(EmailTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(DateofBirthTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(PasswordTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(TypeCB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(ExtraPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 71, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(RegisterButton) .addComponent(BackButton)) .addContainerGap()) ); UserNameTF.getAccessibleContext().setAccessibleName("RegisterName"); EmailTF.getAccessibleContext().setAccessibleName("RegisterMail"); DateofBirthTF.getAccessibleContext().setAccessibleName("RegisterDOB"); PasswordTF.getAccessibleContext().setAccessibleName("RegisterPassword"); RegisterButton.getAccessibleContext().setAccessibleName("RegisterButton"); ExtraPanel.getAccessibleContext().setAccessibleName("ExtraPanel"); }// </editor-fold>//GEN-END:initComponents private void RegisterButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RegisterButtonActionPerformed if (DateofBirthTF.getText().isEmpty() || EmailTF.getText().isEmpty() || PasswordTF.getText().isEmpty() || UserNameTF.getText().isEmpty()) JOptionPane.showMessageDialog(mainFrame, "You need to fill all the fields to register!!"); else { try { User newUser = null; java.text.SimpleDateFormat dateFormatter = new java.text.SimpleDateFormat("dd/MM/yyyy"); switch (TypeCB.getSelectedItem().toString()) { case "Admin": { newUser = new Admin(); ((Admin) newUser).setClearanceLevel(Integer.parseInt(((AdminRegisterPanel) extraPanel).AdminClearanceTF.getText())); newUser.setUserType(User.UserType.ADMIN); break; } case "Employee": { newUser = new Employee(); ((Employee) newUser).setDepCode(Integer.parseInt(((EmployeeRegisterPanel) extraPanel).EmpDepCodeTF.getText())); ((Employee) newUser).setStartDate(dateFormatter.parse(((EmployeeRegisterPanel) extraPanel).EmpStartDateTF.getText())); newUser.setUserType(User.UserType.EMPLOYEE); break; } case "Customer": { newUser = new Customer(); ((Customer) newUser).setPhoneNumber(((CustomerRegisterPanel) extraPanel).CustPhoneTF.getText()); newUser.setUserType(User.UserType.CUSTOMER); break; } default: break; } newUser.setDateOfBirth(dateFormatter.parse(DateofBirthTF.getText())); newUser.setEmail(EmailTF.getText()); newUser.setPassword(PasswordTF.getText()); newUser.setUserName(UserNameTF.getText()); mainFrame.application.repository.registerUser(newUser); JOptionPane.showMessageDialog(mainFrame, "Created successfully!"); mainFrame.changePanel("LoginRegisterSelection"); } catch (java.sql.SQLIntegrityConstraintViolationException e) { e.printStackTrace(); JOptionPane.showMessageDialog(mainFrame, "Email is already being used!"); } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(mainFrame, "Error on creation!"); } } }//GEN-LAST:event_RegisterButtonActionPerformed private void TypeCBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_TypeCBActionPerformed ExtraPanel.removeAll(); if(TypeCB.getSelectedItem() != null) switch (TypeCB.getSelectedItem().toString()) { case "Admin": extraPanel = new AdminRegisterPanel(); break; case "Employee": extraPanel = new EmployeeRegisterPanel(); break; case "Customer": extraPanel = new CustomerRegisterPanel(); break; default: break; } ExtraPanel.add(extraPanel); ExtraPanel.validate(); ExtraPanel.repaint(); }//GEN-LAST:event_TypeCBActionPerformed private void BackButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BackButtonActionPerformed mainFrame.changePanel("LoginRegisterSelection"); }//GEN-LAST:event_BackButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton BackButton; private javax.swing.JTextField DateofBirthTF; private javax.swing.JTextField EmailTF; private javax.swing.JPanel ExtraPanel; private javax.swing.JTextField PasswordTF; private javax.swing.JButton RegisterButton; private javax.swing.JComboBox TypeCB; private javax.swing.JTextField UserNameTF; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; // End of variables declaration//GEN-END:variables }
UTF-8
Java
12,528
java
RegisterPanel.java
Java
[ { "context": "\nimport javax.swing.JOptionPane;\n\n/**\n \n * @author Serhat Korkmaz\n */\npublic class RegisterPanel extends javax.swin", "end": 687, "score": 0.9998748898506165, "start": 673, "tag": "NAME", "value": "Serhat Korkmaz" } ]
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 FeedbackManagement.GUI; import FeedbackManagement.GUI.RegisterAltPanels.CustomerRegisterPanel; import FeedbackManagement.GUI.RegisterAltPanels.EmployeeRegisterPanel; import FeedbackManagement.GUI.RegisterAltPanels.AdminRegisterPanel; import FeedbackManagement.Models.Admin; import FeedbackManagement.Models.Customer; import FeedbackManagement.Models.Employee; import FeedbackManagement.Models.User; import java.sql.SQLException; import javax.swing.JOptionPane; /** * @author <NAME> */ public class RegisterPanel extends javax.swing.JPanel { private final MainFrame mainFrame; private javax.swing.JPanel extraPanel; public RegisterPanel(MainFrame mainFrame) { this.mainFrame = mainFrame; initComponents(); TypeCBActionPerformed(null); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the FormEditor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); UserNameTF = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); EmailTF = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); DateofBirthTF = new javax.swing.JTextField(); PasswordTF = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); RegisterButton = new javax.swing.JButton(); ExtraPanel = new javax.swing.JPanel(); TypeCB = new javax.swing.JComboBox(); BackButton = new javax.swing.JButton(); jLabel1.setText("User Name:"); jLabel2.setText("Email Address:"); jLabel3.setText("Date of Birth:"); DateofBirthTF.setText("DD/MM/YYYY"); DateofBirthTF.setToolTipText("DD/MM/YYYY"); jLabel4.setText("Password:"); jLabel5.setText("UserType:"); RegisterButton.setText("Register"); RegisterButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { RegisterButtonActionPerformed(evt); } }); TypeCB.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Admin", "Employee", "Customer" })); TypeCB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { TypeCBActionPerformed(evt); } }); BackButton.setText("Back"); BackButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BackButtonActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(ExtraPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(BackButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(RegisterButton)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(jLabel3) .addComponent(jLabel4) .addComponent(jLabel5) .addComponent(jLabel1)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(UserNameTF) .addComponent(EmailTF) .addComponent(DateofBirthTF) .addComponent(PasswordTF) .addComponent(TypeCB, 0, 119, Short.MAX_VALUE)))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(UserNameTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(EmailTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(DateofBirthTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(PasswordTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(TypeCB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(ExtraPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 71, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(RegisterButton) .addComponent(BackButton)) .addContainerGap()) ); UserNameTF.getAccessibleContext().setAccessibleName("RegisterName"); EmailTF.getAccessibleContext().setAccessibleName("RegisterMail"); DateofBirthTF.getAccessibleContext().setAccessibleName("RegisterDOB"); PasswordTF.getAccessibleContext().setAccessibleName("RegisterPassword"); RegisterButton.getAccessibleContext().setAccessibleName("RegisterButton"); ExtraPanel.getAccessibleContext().setAccessibleName("ExtraPanel"); }// </editor-fold>//GEN-END:initComponents private void RegisterButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RegisterButtonActionPerformed if (DateofBirthTF.getText().isEmpty() || EmailTF.getText().isEmpty() || PasswordTF.getText().isEmpty() || UserNameTF.getText().isEmpty()) JOptionPane.showMessageDialog(mainFrame, "You need to fill all the fields to register!!"); else { try { User newUser = null; java.text.SimpleDateFormat dateFormatter = new java.text.SimpleDateFormat("dd/MM/yyyy"); switch (TypeCB.getSelectedItem().toString()) { case "Admin": { newUser = new Admin(); ((Admin) newUser).setClearanceLevel(Integer.parseInt(((AdminRegisterPanel) extraPanel).AdminClearanceTF.getText())); newUser.setUserType(User.UserType.ADMIN); break; } case "Employee": { newUser = new Employee(); ((Employee) newUser).setDepCode(Integer.parseInt(((EmployeeRegisterPanel) extraPanel).EmpDepCodeTF.getText())); ((Employee) newUser).setStartDate(dateFormatter.parse(((EmployeeRegisterPanel) extraPanel).EmpStartDateTF.getText())); newUser.setUserType(User.UserType.EMPLOYEE); break; } case "Customer": { newUser = new Customer(); ((Customer) newUser).setPhoneNumber(((CustomerRegisterPanel) extraPanel).CustPhoneTF.getText()); newUser.setUserType(User.UserType.CUSTOMER); break; } default: break; } newUser.setDateOfBirth(dateFormatter.parse(DateofBirthTF.getText())); newUser.setEmail(EmailTF.getText()); newUser.setPassword(PasswordTF.getText()); newUser.setUserName(UserNameTF.getText()); mainFrame.application.repository.registerUser(newUser); JOptionPane.showMessageDialog(mainFrame, "Created successfully!"); mainFrame.changePanel("LoginRegisterSelection"); } catch (java.sql.SQLIntegrityConstraintViolationException e) { e.printStackTrace(); JOptionPane.showMessageDialog(mainFrame, "Email is already being used!"); } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(mainFrame, "Error on creation!"); } } }//GEN-LAST:event_RegisterButtonActionPerformed private void TypeCBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_TypeCBActionPerformed ExtraPanel.removeAll(); if(TypeCB.getSelectedItem() != null) switch (TypeCB.getSelectedItem().toString()) { case "Admin": extraPanel = new AdminRegisterPanel(); break; case "Employee": extraPanel = new EmployeeRegisterPanel(); break; case "Customer": extraPanel = new CustomerRegisterPanel(); break; default: break; } ExtraPanel.add(extraPanel); ExtraPanel.validate(); ExtraPanel.repaint(); }//GEN-LAST:event_TypeCBActionPerformed private void BackButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BackButtonActionPerformed mainFrame.changePanel("LoginRegisterSelection"); }//GEN-LAST:event_BackButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton BackButton; private javax.swing.JTextField DateofBirthTF; private javax.swing.JTextField EmailTF; private javax.swing.JPanel ExtraPanel; private javax.swing.JTextField PasswordTF; private javax.swing.JButton RegisterButton; private javax.swing.JComboBox TypeCB; private javax.swing.JTextField UserNameTF; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; // End of variables declaration//GEN-END:variables }
12,520
0.635696
0.632743
252
48.714287
36.32489
167
false
false
0
0
0
0
0
0
0.599206
false
false
14
88b4fbcab064f759152197d74a512901db1fde4f
17,480,516,929,890
018c2b256425a0682cbed3ffa91f682f1d428e7b
/kafka-wheather-producer/src/main/java/com/kafka/wheather/KafkaWheatherProducerApplication.java
1d93eafce1c45005146ee20d3af04c034c36dbeb
[]
no_license
mr-arora30/Data-Streaming-Kafka
https://github.com/mr-arora30/Data-Streaming-Kafka
61b49caf05d28682e550aebc518bfa8801a25f99
aaf4cdb66858c34e94a9379dc3143d9e9952a091
refs/heads/master
2023-05-02T07:32:00.613000
2021-05-19T11:06:30
2021-05-19T11:06:30
368,839,051
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.kafka.wheather; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class KafkaWheatherProducerApplication { public static void main(String[] args) { SpringApplication.run(KafkaWheatherProducerApplication.class, args); } }
UTF-8
Java
341
java
KafkaWheatherProducerApplication.java
Java
[]
null
[]
package com.kafka.wheather; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class KafkaWheatherProducerApplication { public static void main(String[] args) { SpringApplication.run(KafkaWheatherProducerApplication.class, args); } }
341
0.835777
0.835777
13
25.23077
26.100851
70
false
false
0
0
0
0
0
0
0.692308
false
false
14
3caba3f1b965731e55a5414a101a1e2861c6a308
16,449,724,782,920
ef62c12552c0e65d589f2214a57b3ac6a9f8964d
/src/BuyUnitPanel.java
fc01c9ea83884aff6b92a31d2234180f0821b955
[]
no_license
james-m-henderson/Mad-Scientist
https://github.com/james-m-henderson/Mad-Scientist
7c1a72f0e20547a4eb5dc595099b8bf5cccacad4
e41c76693ea11847b69b9089c9889d0942c019cd
refs/heads/master
2021-01-18T08:07:16.673000
2012-04-19T01:55:32
2012-04-19T01:55:32
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.Properties; import org.newdawn.slick.Color; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.SlickException; import org.newdawn.slick.Sound; import org.newdawn.slick.gui.MouseOverArea; import org.newdawn.slick.state.StateBasedGame; import org.newdawn.slick.util.Log; public class BuyUnitPanel { private MouseOverArea buyButton, detailButton; private int MoneyCost, PartsCost, TLCost; private int x,y; private boolean unitEnabled = false; private Image unitImage, detailButtonImage, buyButtonImage, buildButtonImage; private final String unitName; private final Sound buyFail, buySucceed; private String[] details = { "Gold Cost: ", "Parts Cost: ", "Tech Level Required: " }; // TODO: Move this into the config file private static final String themeDir = "./res/themes/"; private int padding = 4; public BuyUnitPanel(final String unitName, final GameCore mCore, int x, int y) throws SlickException { buyFail = new Sound(mCore.getConfiguration().getProperty("ClickFailSound")); buySucceed = new Sound(mCore.getConfiguration().getProperty("ClickSound")); this.unitName = unitName; this.x = x; this.y = y; String[] units = mCore.getConfiguration().getProperty("units").split(","); for ( int i = 0; i < units.length; i++ ) { if ( unitName.equalsIgnoreCase(units[i])) { unitEnabled = true; } } Properties mConfig = mCore.getConfiguration(); Properties mTheme = ConfigReader.readConfig(themeDir + mConfig.getProperty("theme")); buyButtonImage = new Image(themeDir + mTheme.getProperty("folder") + "/" + mTheme.getProperty("hire-button")); detailButtonImage = new Image(themeDir + mTheme.getProperty("folder") + "/" + mTheme.getProperty("detail-button")); buildButtonImage = new Image(themeDir + mTheme.getProperty("folder") + "/" + mTheme.getProperty("build-button")); final Properties unitConfig = ConfigReader.readConfig("./res/" + unitName + ".cfg"); unitImage = new Image(unitConfig.getProperty("icon")); MoneyCost = Integer.parseInt(unitConfig.getProperty("gold-cost")); PartsCost = Integer.parseInt(unitConfig.getProperty("parts-cost")); TLCost = Integer.parseInt(unitConfig.getProperty("tech-cost")); Image buttonImage = (PartsCost > 0) ? buildButtonImage : buyButtonImage; buyButton = new MouseOverArea(mCore.getGame().getContainer(), buttonImage, x + padding + unitImage.getWidth(), y + 18) { public void mouseClicked(int button, int x, int y, int clickCount) { if (x >= this.getX() && x < this.getX() + this.getWidth() && y >= this.getY() && y <= this.getY() + this.getHeight()) { if ( mCore.getValue("Money") >= MoneyCost && mCore.getValue("Parts") >= PartsCost && mCore.getValue("Tech") >= TLCost ) { Log.info("Attempting to buy unit " + unitName); // If the unit has a parts cost, it means it must be made in our lab if ( PartsCost > 0 ) { mCore.setValue("queue-build-minion-" + unitName, mCore.getValue("queue-build-minion-" + unitName)+1); OverlayGUI.LogMessage("Minions will now build a new " + unitName); buySucceed.play(); } // Otherwise it can just be hired and will arrive from town else { mCore.setValue("Money", mCore.getValue("Money")-MoneyCost); MinionFactory.hireMinion(unitName, mCore); OverlayGUI.LogMessage("A new " + unitName + " Has been hired"); buySucceed.play(); } } else { // Should play a bzzt sound or something here OverlayGUI.LogMessage("Could not afford minion!"); buyFail.play(); } } } }; detailButton = new MouseOverArea(mCore.getGame().getContainer(), detailButtonImage, x + padding + unitImage.getWidth(), y + padding + buyButtonImage.getHeight() + 20) { public void mouseClicked(int button, int x, int y, int clickCount) { if (x >= this.getX() && x < this.getX() + this.getWidth() && y >= this.getY() && y <= this.getY() + this.getHeight()) { OverlayGUI.LogMessage(unitConfig.getProperty("desc")); } } }; } public void render(GameContainer arg0, StateBasedGame arg1, Graphics arg2) throws SlickException { arg2.drawString(unitName, x, y); int h = arg2.getFont().getHeight(unitName); unitImage.draw(x, y + h); buyButton.render(arg0, arg2); detailButton.render(arg0, arg2); int w = 0; int lh = 20; // Gold Cost arg2.drawString(details[0], x, y + unitImage.getHeight() + lh + (padding*4)); w = arg2.getFont().getWidth(details[0]); arg2.drawString(String.valueOf(MoneyCost), x + w + 2, y + unitImage.getHeight() + lh + (padding*4)); // Parts Cost arg2.drawString(details[1], x, y + unitImage.getHeight() + (lh*2) + (padding*4)); w = arg2.getFont().getWidth(details[1]); arg2.drawString(String.valueOf(PartsCost), x + w + 2, y + unitImage.getHeight() + (lh*2) + (padding*4)); // Tech Level Required arg2.drawString(details[2], x, y + unitImage.getHeight() + (lh*3) + (padding*4)); w = arg2.getFont().getWidth(details[2]); arg2.drawString(String.valueOf(TLCost), x + w + 2, y + unitImage.getHeight() + (lh*3) + (padding*4)); if ( !unitEnabled ) { // If the unit is disabled, Draw a gray rectangle over the panel Color oldCol = arg2.getColor(); Color mCol = new Color(0.3f, 0.3f, 0.3f, 0.5f); arg2.setColor(mCol); arg2.drawRect(x, y, getWidth(), getHeight()); arg2.setColor(oldCol); } } public void setPosition(int x, int y) { this.x = x; this.y = y; resetButtons(); } private void resetButtons() { buyButton.setLocation(x + padding + unitImage.getWidth(), y); detailButton.setLocation(x + padding + unitImage.getWidth(), y + padding + buyButtonImage.getHeight()); } public int getWidth() { return unitImage.getWidth() + padding + detailButton.getWidth(); } public int getHeight() { int textLines = 3; return unitImage.getHeight() + padding + (textLines+4)*18; } }
UTF-8
Java
6,295
java
BuyUnitPanel.java
Java
[]
null
[]
import java.util.Properties; import org.newdawn.slick.Color; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.SlickException; import org.newdawn.slick.Sound; import org.newdawn.slick.gui.MouseOverArea; import org.newdawn.slick.state.StateBasedGame; import org.newdawn.slick.util.Log; public class BuyUnitPanel { private MouseOverArea buyButton, detailButton; private int MoneyCost, PartsCost, TLCost; private int x,y; private boolean unitEnabled = false; private Image unitImage, detailButtonImage, buyButtonImage, buildButtonImage; private final String unitName; private final Sound buyFail, buySucceed; private String[] details = { "Gold Cost: ", "Parts Cost: ", "Tech Level Required: " }; // TODO: Move this into the config file private static final String themeDir = "./res/themes/"; private int padding = 4; public BuyUnitPanel(final String unitName, final GameCore mCore, int x, int y) throws SlickException { buyFail = new Sound(mCore.getConfiguration().getProperty("ClickFailSound")); buySucceed = new Sound(mCore.getConfiguration().getProperty("ClickSound")); this.unitName = unitName; this.x = x; this.y = y; String[] units = mCore.getConfiguration().getProperty("units").split(","); for ( int i = 0; i < units.length; i++ ) { if ( unitName.equalsIgnoreCase(units[i])) { unitEnabled = true; } } Properties mConfig = mCore.getConfiguration(); Properties mTheme = ConfigReader.readConfig(themeDir + mConfig.getProperty("theme")); buyButtonImage = new Image(themeDir + mTheme.getProperty("folder") + "/" + mTheme.getProperty("hire-button")); detailButtonImage = new Image(themeDir + mTheme.getProperty("folder") + "/" + mTheme.getProperty("detail-button")); buildButtonImage = new Image(themeDir + mTheme.getProperty("folder") + "/" + mTheme.getProperty("build-button")); final Properties unitConfig = ConfigReader.readConfig("./res/" + unitName + ".cfg"); unitImage = new Image(unitConfig.getProperty("icon")); MoneyCost = Integer.parseInt(unitConfig.getProperty("gold-cost")); PartsCost = Integer.parseInt(unitConfig.getProperty("parts-cost")); TLCost = Integer.parseInt(unitConfig.getProperty("tech-cost")); Image buttonImage = (PartsCost > 0) ? buildButtonImage : buyButtonImage; buyButton = new MouseOverArea(mCore.getGame().getContainer(), buttonImage, x + padding + unitImage.getWidth(), y + 18) { public void mouseClicked(int button, int x, int y, int clickCount) { if (x >= this.getX() && x < this.getX() + this.getWidth() && y >= this.getY() && y <= this.getY() + this.getHeight()) { if ( mCore.getValue("Money") >= MoneyCost && mCore.getValue("Parts") >= PartsCost && mCore.getValue("Tech") >= TLCost ) { Log.info("Attempting to buy unit " + unitName); // If the unit has a parts cost, it means it must be made in our lab if ( PartsCost > 0 ) { mCore.setValue("queue-build-minion-" + unitName, mCore.getValue("queue-build-minion-" + unitName)+1); OverlayGUI.LogMessage("Minions will now build a new " + unitName); buySucceed.play(); } // Otherwise it can just be hired and will arrive from town else { mCore.setValue("Money", mCore.getValue("Money")-MoneyCost); MinionFactory.hireMinion(unitName, mCore); OverlayGUI.LogMessage("A new " + unitName + " Has been hired"); buySucceed.play(); } } else { // Should play a bzzt sound or something here OverlayGUI.LogMessage("Could not afford minion!"); buyFail.play(); } } } }; detailButton = new MouseOverArea(mCore.getGame().getContainer(), detailButtonImage, x + padding + unitImage.getWidth(), y + padding + buyButtonImage.getHeight() + 20) { public void mouseClicked(int button, int x, int y, int clickCount) { if (x >= this.getX() && x < this.getX() + this.getWidth() && y >= this.getY() && y <= this.getY() + this.getHeight()) { OverlayGUI.LogMessage(unitConfig.getProperty("desc")); } } }; } public void render(GameContainer arg0, StateBasedGame arg1, Graphics arg2) throws SlickException { arg2.drawString(unitName, x, y); int h = arg2.getFont().getHeight(unitName); unitImage.draw(x, y + h); buyButton.render(arg0, arg2); detailButton.render(arg0, arg2); int w = 0; int lh = 20; // Gold Cost arg2.drawString(details[0], x, y + unitImage.getHeight() + lh + (padding*4)); w = arg2.getFont().getWidth(details[0]); arg2.drawString(String.valueOf(MoneyCost), x + w + 2, y + unitImage.getHeight() + lh + (padding*4)); // Parts Cost arg2.drawString(details[1], x, y + unitImage.getHeight() + (lh*2) + (padding*4)); w = arg2.getFont().getWidth(details[1]); arg2.drawString(String.valueOf(PartsCost), x + w + 2, y + unitImage.getHeight() + (lh*2) + (padding*4)); // Tech Level Required arg2.drawString(details[2], x, y + unitImage.getHeight() + (lh*3) + (padding*4)); w = arg2.getFont().getWidth(details[2]); arg2.drawString(String.valueOf(TLCost), x + w + 2, y + unitImage.getHeight() + (lh*3) + (padding*4)); if ( !unitEnabled ) { // If the unit is disabled, Draw a gray rectangle over the panel Color oldCol = arg2.getColor(); Color mCol = new Color(0.3f, 0.3f, 0.3f, 0.5f); arg2.setColor(mCol); arg2.drawRect(x, y, getWidth(), getHeight()); arg2.setColor(oldCol); } } public void setPosition(int x, int y) { this.x = x; this.y = y; resetButtons(); } private void resetButtons() { buyButton.setLocation(x + padding + unitImage.getWidth(), y); detailButton.setLocation(x + padding + unitImage.getWidth(), y + padding + buyButtonImage.getHeight()); } public int getWidth() { return unitImage.getWidth() + padding + detailButton.getWidth(); } public int getHeight() { int textLines = 3; return unitImage.getHeight() + padding + (textLines+4)*18; } }
6,295
0.642097
0.631771
180
32.972221
33.193611
168
false
false
0
0
0
0
0
0
3.277778
false
false
14
fd79e5e075a9f5fc594f65c2f1fffedbabcc027f
16,449,724,786,462
326f1cb010fc21d6f9cfb51a2b561d150589b605
/app/src/main/java/com/example/epams/MainActivity.java
2896b30e71bc8626a724b38dcb49f7f1acf79426
[]
no_license
z-war/EPAMS
https://github.com/z-war/EPAMS
1d7514c25aa9cd7f8113f05c25913d8ecfb6018c
284cb69ddb1a746b5f274e4b39d0edcfaa203a80
refs/heads/master
2022-11-27T17:10:24.465000
2020-08-08T10:26:00
2020-08-08T10:26:00
268,159,757
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.epams; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; import android.content.Intent; import android.os.Bundle; import android.transition.TransitionManager; import android.view.MenuItem; import android.widget.Toast; import com.example.epams.Fragments.AdminLogin; import com.example.epams.Fragments.Guest; import com.example.epams.Fragments.UserLogin; import com.google.android.material.bottomnavigation.BottomNavigationView; public class MainActivity extends AppCompatActivity { BottomNavigationView bnv; Fragment admin_login , user_login , guest_user; Intent intent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); } void init() { try { bnv = findViewById(R.id.bottom_menu); admin_login = new AdminLogin(); user_login = new UserLogin(); guest_user = new Guest(); change_fragment(admin_login); // if(getIntent().getExtras()!=null) // { // // intent = getIntent(); // String status = intent.getStringExtra("status"); // if(status.equals("user_login")) // { // bnv.setSelectedItemId(R.id.user_login); // change_fragment(user_login); // } // // } bnv.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { if(item.getItemId()==R.id.admin_login) { Toast.makeText(MainActivity.this, "AdminLogin", Toast.LENGTH_SHORT).show(); change_fragment(admin_login); return true; } else if(item.getItemId()==R.id.user_login) { change_fragment(user_login); return true; } return false; } }); }catch (Exception e) { Toast.makeText(this, ""+e.getMessage(), Toast.LENGTH_SHORT).show(); } } void change_fragment(Fragment obj) { try { getSupportFragmentManager().beginTransaction().replace(R.id.fragment_holder_login,obj).commit(); }catch (Exception e) { Toast.makeText(this, "Error Changing Fragment", Toast.LENGTH_SHORT).show(); } } }
UTF-8
Java
2,746
java
MainActivity.java
Java
[]
null
[]
package com.example.epams; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; import android.content.Intent; import android.os.Bundle; import android.transition.TransitionManager; import android.view.MenuItem; import android.widget.Toast; import com.example.epams.Fragments.AdminLogin; import com.example.epams.Fragments.Guest; import com.example.epams.Fragments.UserLogin; import com.google.android.material.bottomnavigation.BottomNavigationView; public class MainActivity extends AppCompatActivity { BottomNavigationView bnv; Fragment admin_login , user_login , guest_user; Intent intent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); } void init() { try { bnv = findViewById(R.id.bottom_menu); admin_login = new AdminLogin(); user_login = new UserLogin(); guest_user = new Guest(); change_fragment(admin_login); // if(getIntent().getExtras()!=null) // { // // intent = getIntent(); // String status = intent.getStringExtra("status"); // if(status.equals("user_login")) // { // bnv.setSelectedItemId(R.id.user_login); // change_fragment(user_login); // } // // } bnv.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { if(item.getItemId()==R.id.admin_login) { Toast.makeText(MainActivity.this, "AdminLogin", Toast.LENGTH_SHORT).show(); change_fragment(admin_login); return true; } else if(item.getItemId()==R.id.user_login) { change_fragment(user_login); return true; } return false; } }); }catch (Exception e) { Toast.makeText(this, ""+e.getMessage(), Toast.LENGTH_SHORT).show(); } } void change_fragment(Fragment obj) { try { getSupportFragmentManager().beginTransaction().replace(R.id.fragment_holder_login,obj).commit(); }catch (Exception e) { Toast.makeText(this, "Error Changing Fragment", Toast.LENGTH_SHORT).show(); } } }
2,746
0.569192
0.569192
82
32.487804
25.75411
113
false
false
0
0
0
0
0
0
0.573171
false
false
14
7c480d451eec7e692239b369e22d1f0010912c63
8,529,805,082,182
d828546517c533b3310718258698e74c69b4b47f
/AMAPVox/Dependencies/Commons/commons-util/src/main/java/fr/amap/commons/util/io/file/FileManager.java
e33f41f5bbde0dda22a041df68d507c502e36be8
[]
no_license
floriandeboissieu/AMAPVox
https://github.com/floriandeboissieu/AMAPVox
11767690320dd9fe9a2f9e728f17bcf10f430003
f8af6ddf8fdf00aea17482e87873306ac106351c
refs/heads/master
2020-04-02T21:54:08.973000
2018-10-08T09:55:04
2018-10-08T09:55:04
null
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 fr.amap.commons.util.io.file; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class FileManager { public static void skipLines(BufferedReader reader, int number) throws IOException{ try { for(int i=0;i<number;i++){ reader.readLine(); } } catch (IOException ex) { throw ex; } } public static int getLineNumber(InputStreamReader stream) throws IOException{ int count = 0; try{ BufferedReader reader = new BufferedReader(stream); while ((reader.readLine()) != null) { count++; } //reader.close(); return count; } catch (IOException ex) { throw new IOException("Cannot read file", ex); } } public static int getLineNumber(File file) throws IOException{ return getLineNumber(file.getAbsolutePath()); } public static int getLineNumber(String path) throws IOException{ int count = 0; InputStream is; try { is = new BufferedInputStream(new FileInputStream(path)); byte[] c = new byte[1024]; int readChars = 0; boolean empty = true; while ((readChars = is.read(c)) != -1) { empty = false; for (int i = 0; i < readChars; ++i) { if (c[i] == '\n') { ++count; } } } return count; } catch (FileNotFoundException ex) { throw ex; } catch (IOException ex) { throw ex; } } public static String readHeader(String path){ try { BufferedReader reader = new BufferedReader(new FileReader(new File(path))); String line = reader.readLine(); reader.close(); return line; } catch (FileNotFoundException ex) { return null; } catch (IOException ex) { return null; } } public static String readSpecificLine(String path, int lineNumber) throws IOException{ try { BufferedReader reader = new BufferedReader(new FileReader(new File(path))); int count = 0; String line = null; do{ line = reader.readLine(); count++; }while(count != lineNumber); return line; } catch (FileNotFoundException ex) { throw ex; } catch (IOException ex) { throw ex; } } public static String getExtension(File file){ int dotIndex = file.getName().lastIndexOf("."); if(dotIndex == -1){ return ""; }else{ String extension = file.getName().substring(dotIndex, file.getName().length()); return extension; } } }
UTF-8
Java
3,825
java
FileManager.java
Java
[]
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 fr.amap.commons.util.io.file; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class FileManager { public static void skipLines(BufferedReader reader, int number) throws IOException{ try { for(int i=0;i<number;i++){ reader.readLine(); } } catch (IOException ex) { throw ex; } } public static int getLineNumber(InputStreamReader stream) throws IOException{ int count = 0; try{ BufferedReader reader = new BufferedReader(stream); while ((reader.readLine()) != null) { count++; } //reader.close(); return count; } catch (IOException ex) { throw new IOException("Cannot read file", ex); } } public static int getLineNumber(File file) throws IOException{ return getLineNumber(file.getAbsolutePath()); } public static int getLineNumber(String path) throws IOException{ int count = 0; InputStream is; try { is = new BufferedInputStream(new FileInputStream(path)); byte[] c = new byte[1024]; int readChars = 0; boolean empty = true; while ((readChars = is.read(c)) != -1) { empty = false; for (int i = 0; i < readChars; ++i) { if (c[i] == '\n') { ++count; } } } return count; } catch (FileNotFoundException ex) { throw ex; } catch (IOException ex) { throw ex; } } public static String readHeader(String path){ try { BufferedReader reader = new BufferedReader(new FileReader(new File(path))); String line = reader.readLine(); reader.close(); return line; } catch (FileNotFoundException ex) { return null; } catch (IOException ex) { return null; } } public static String readSpecificLine(String path, int lineNumber) throws IOException{ try { BufferedReader reader = new BufferedReader(new FileReader(new File(path))); int count = 0; String line = null; do{ line = reader.readLine(); count++; }while(count != lineNumber); return line; } catch (FileNotFoundException ex) { throw ex; } catch (IOException ex) { throw ex; } } public static String getExtension(File file){ int dotIndex = file.getName().lastIndexOf("."); if(dotIndex == -1){ return ""; }else{ String extension = file.getName().substring(dotIndex, file.getName().length()); return extension; } } }
3,825
0.476863
0.473725
142
24.936619
21.299082
91
false
false
0
0
0
0
0
0
0.422535
false
false
14
a1ed27ab1432d82d073eefd23e0ad9633764974f
28,862,180,271,513
d6c49f13501b2ef3690ddc29e31b772745f37718
/JavaTema1( Primeros programas.)/Explicaciones/JavaApplication11/src/javaapplication11/JavaApplication11.java
814d3034cf94b6a768f0c712fa0bf4d7983f2135
[]
no_license
pablovi97/PRO
https://github.com/pablovi97/PRO
8f568a3a7cd30720fcfddf85c3c371188018ddc1
1200641fbee772a84fa51581395838d63afc8fe9
refs/heads/master
2020-03-31T02:33:57.717000
2019-04-29T18:24:10
2019-04-29T18:24:10
151,829,779
3
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 javaapplication11; /** * * @author daw */ public class JavaApplication11 { /** * @param args the command line arguments */ public static void main(String[] args) { long milisegundos = 12345678901l; float resultadofactura = 1.5F ; long poblacion = 740000000000000000l; System.out.println(02E2);/* 20""octal" ----> 2x8^1 + 0x8^0 */ System.out.println("\t\t\tHorario"); System.out.println("hora \tL \tM \tX \tJ \tV"); System.out.println("14:15\tLND \tPRO \tLND \tLNT \tPRO"); System.out.println("15:10\tLND \tPRO \tLND \tBAE \tPRO"); System.out.println("16:05\tPRO \tSSF \tSSF \tBAE \tLNT"); System.out.println("17:15\tREC \tRE \tO \t!!! \t!!"); System.out.println("18:10\tSSF \tSSF \tSSF \tETS \tFOL"); System.out.println("19:05\tETS \tBAE \tFOL \tPRO \tBAE"); System.out.println("20:00\tETS \tBAE \tFOL \tPRO \tBAE"); double numero =2; System.out.println(numero); int num2 = (int)7.9; //Truncamiento System.out.println(num2); } }
UTF-8
Java
1,363
java
JavaApplication11.java
Java
[ { "context": "\n */\npackage javaapplication11;\n\n/**\n *\n * @author daw\n */\npublic class JavaApplication11 {\n\n /**\n ", "end": 234, "score": 0.9992791414260864, "start": 231, "tag": "USERNAME", "value": "daw" } ]
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 javaapplication11; /** * * @author daw */ public class JavaApplication11 { /** * @param args the command line arguments */ public static void main(String[] args) { long milisegundos = 12345678901l; float resultadofactura = 1.5F ; long poblacion = 740000000000000000l; System.out.println(02E2);/* 20""octal" ----> 2x8^1 + 0x8^0 */ System.out.println("\t\t\tHorario"); System.out.println("hora \tL \tM \tX \tJ \tV"); System.out.println("14:15\tLND \tPRO \tLND \tLNT \tPRO"); System.out.println("15:10\tLND \tPRO \tLND \tBAE \tPRO"); System.out.println("16:05\tPRO \tSSF \tSSF \tBAE \tLNT"); System.out.println("17:15\tREC \tRE \tO \t!!! \t!!"); System.out.println("18:10\tSSF \tSSF \tSSF \tETS \tFOL"); System.out.println("19:05\tETS \tBAE \tFOL \tPRO \tBAE"); System.out.println("20:00\tETS \tBAE \tFOL \tPRO \tBAE"); double numero =2; System.out.println(numero); int num2 = (int)7.9; //Truncamiento System.out.println(num2); } }
1,363
0.575935
0.517975
45
29.288889
23.912453
79
false
false
0
0
0
0
0
0
0.466667
false
false
14
917fa04a5545eaeb0cf690b7732cee0f20c94afb
4,535,485,476,874
99c7ffaf8ea657a799ea3b07dd41b1e9ef82634f
/app/app/src/main/java/de/codefest8/gamification8/listadapters/DrawerElementAdapter.java
28c7217b60d09dda218897fc690a6d2e40b9d55f
[]
no_license
tkohn/codefest8
https://github.com/tkohn/codefest8
2ea5c6d915d1216078adf98a3363f4d6f32212b5
db763d97f92d4097f81c0dd426112ad9514eb592
refs/heads/master
2021-03-19T14:19:48.165000
2015-03-22T20:07:04
2015-03-22T20:07:04
31,806,287
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package de.codefest8.gamification8.listadapters; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import de.codefest8.gamification8.DrawerElement; import de.codefest8.gamification8.R; /** * Created by koerfer on 07.03.2015. */ public class DrawerElementAdapter extends ArrayAdapter<DrawerElement> { private final Context Context; private final DrawerElement[] Values; public DrawerElementAdapter(Context context, DrawerElement[] values) { super(context, R.layout.drawer_list_item, values); this.Context = context; this.Values = values; } public View getView(int position, View convertView, ViewGroup parent) { DrawerElement currentElement = this.Values[position]; LayoutInflater inflater = (LayoutInflater) this.Context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.drawer_list_item, parent, false); ImageView imgView = (ImageView) view.findViewById(R.id.history_row_icon); imgView.setImageResource(currentElement.getImageResourceID()); TextView txtView = (TextView) view.findViewById(R.id.history_row_label); txtView.setText(currentElement.getLabel()); return view; } }
UTF-8
Java
1,420
java
DrawerElementAdapter.java
Java
[ { "context": "t de.codefest8.gamification8.R;\n\n/**\n * Created by koerfer on 07.03.2015.\n */\npublic class DrawerElementAdap", "end": 389, "score": 0.9995225071907043, "start": 382, "tag": "USERNAME", "value": "koerfer" } ]
null
[]
package de.codefest8.gamification8.listadapters; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import de.codefest8.gamification8.DrawerElement; import de.codefest8.gamification8.R; /** * Created by koerfer on 07.03.2015. */ public class DrawerElementAdapter extends ArrayAdapter<DrawerElement> { private final Context Context; private final DrawerElement[] Values; public DrawerElementAdapter(Context context, DrawerElement[] values) { super(context, R.layout.drawer_list_item, values); this.Context = context; this.Values = values; } public View getView(int position, View convertView, ViewGroup parent) { DrawerElement currentElement = this.Values[position]; LayoutInflater inflater = (LayoutInflater) this.Context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.drawer_list_item, parent, false); ImageView imgView = (ImageView) view.findViewById(R.id.history_row_icon); imgView.setImageResource(currentElement.getImageResourceID()); TextView txtView = (TextView) view.findViewById(R.id.history_row_label); txtView.setText(currentElement.getLabel()); return view; } }
1,420
0.740141
0.730282
41
33.634148
29.315571
114
false
false
0
0
0
0
0
0
0.731707
false
false
14
89adeadb4ebdf55ba25c3c331a17bc34353c1ce7
7,215,545,086,405
9b8243b54a7492634c808a175ea28063c3863594
/app/src/main/java/com/skyworth_hightong/view/CommonDialogView.java
cf38a0ad221c4e9244f6c0dafb40669caa570cb6
[]
no_license
fanlongbo/Android_phone_communal
https://github.com/fanlongbo/Android_phone_communal
50a9c6e8ccc2027009e6b3849c8d94d71d89181c
14daa2a6c75b84ff7731c00df046c38689b58511
refs/heads/master
2016-05-07T01:51:21.979000
2016-02-27T09:06:34
2016-02-27T09:06:34
52,650,543
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.skyworth_hightong.view; import android.app.AlertDialog; import android.content.Context; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.FrameLayout; import android.widget.TextView; import com.sh.pangea.zj.R; import com.skyworth_hightong.formwork.listener.OnCustomDialogListener; import com.skyworth_hightong.player.utils.ViewUtil; public class CommonDialogView extends FrameLayout implements OnClickListener { private TextView content_textview; private TextView confirmButton; private TextView cancelButton; private OnCustomDialogListener onCustomDialogListener; public void setOnCustomDialogListener( OnCustomDialogListener onCustomDialogListener) { this.onCustomDialogListener = onCustomDialogListener; } public CommonDialogView(Context context) { super(context); init(); } private void init() { ViewUtil.loadLayout(this, R.layout.common_dialog); content_textview = (TextView) findViewById(R.id.content_textview); confirmButton = (TextView) findViewById(R.id.cancelButton); confirmButton.setOnClickListener(this); title_textview = (TextView) findViewById(R.id.title_textview); cancelButton = (TextView) findViewById(R.id.confirmButton); cancelButton.setOnClickListener(this); } // public void creatDialog(String promtp, boolean isSingButton, // OnCustomDialogListener listener) { // creatDialog(promtp, "", "", isSingButton, listener); // } // // public void creatDialog(String promtp, String single, // OnCustomDialogListener listener) { // creatDialog(promtp, "", single, true, listener); // } public void creatDialog(String promtp, String title, String cacel, String confirm, boolean isSingleButton, OnCustomDialogListener listener) { if (!TextUtils.isEmpty(promtp)) { content_textview.setText(promtp); } else { } if (!TextUtils.isEmpty(title)) { title_textview.setText(title); } else { title_textview.setVisibility(View.GONE); } if (!TextUtils.isEmpty(cacel)) { cancelButton.setText(cacel); } if (!TextUtils.isEmpty(confirm)) { confirmButton.setText(confirm); } if (isSingleButton) { singButton(); } if (listener != null && onCustomDialogListener == null) { setOnCustomDialogListener(listener); } } private AlertDialog dialog; private TextView title_textview; public void setDialog(AlertDialog dialog) { this.dialog = dialog; } private void singButton() { cancelButton.setVisibility(View.GONE); // verticalView.setVisibility(View.GONE); } @Override public void onClick(View v) { if (dialog != null) { dialog.dismiss(); } if (onCustomDialogListener == null) return; switch (v.getId()) { case R.id.confirmButton: onCustomDialogListener.confirm(); break; case R.id.cancelButton: onCustomDialogListener.cancel(); break; default: break; } } }
UTF-8
Java
2,904
java
CommonDialogView.java
Java
[]
null
[]
package com.skyworth_hightong.view; import android.app.AlertDialog; import android.content.Context; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.FrameLayout; import android.widget.TextView; import com.sh.pangea.zj.R; import com.skyworth_hightong.formwork.listener.OnCustomDialogListener; import com.skyworth_hightong.player.utils.ViewUtil; public class CommonDialogView extends FrameLayout implements OnClickListener { private TextView content_textview; private TextView confirmButton; private TextView cancelButton; private OnCustomDialogListener onCustomDialogListener; public void setOnCustomDialogListener( OnCustomDialogListener onCustomDialogListener) { this.onCustomDialogListener = onCustomDialogListener; } public CommonDialogView(Context context) { super(context); init(); } private void init() { ViewUtil.loadLayout(this, R.layout.common_dialog); content_textview = (TextView) findViewById(R.id.content_textview); confirmButton = (TextView) findViewById(R.id.cancelButton); confirmButton.setOnClickListener(this); title_textview = (TextView) findViewById(R.id.title_textview); cancelButton = (TextView) findViewById(R.id.confirmButton); cancelButton.setOnClickListener(this); } // public void creatDialog(String promtp, boolean isSingButton, // OnCustomDialogListener listener) { // creatDialog(promtp, "", "", isSingButton, listener); // } // // public void creatDialog(String promtp, String single, // OnCustomDialogListener listener) { // creatDialog(promtp, "", single, true, listener); // } public void creatDialog(String promtp, String title, String cacel, String confirm, boolean isSingleButton, OnCustomDialogListener listener) { if (!TextUtils.isEmpty(promtp)) { content_textview.setText(promtp); } else { } if (!TextUtils.isEmpty(title)) { title_textview.setText(title); } else { title_textview.setVisibility(View.GONE); } if (!TextUtils.isEmpty(cacel)) { cancelButton.setText(cacel); } if (!TextUtils.isEmpty(confirm)) { confirmButton.setText(confirm); } if (isSingleButton) { singButton(); } if (listener != null && onCustomDialogListener == null) { setOnCustomDialogListener(listener); } } private AlertDialog dialog; private TextView title_textview; public void setDialog(AlertDialog dialog) { this.dialog = dialog; } private void singButton() { cancelButton.setVisibility(View.GONE); // verticalView.setVisibility(View.GONE); } @Override public void onClick(View v) { if (dialog != null) { dialog.dismiss(); } if (onCustomDialogListener == null) return; switch (v.getId()) { case R.id.confirmButton: onCustomDialogListener.confirm(); break; case R.id.cancelButton: onCustomDialogListener.cancel(); break; default: break; } } }
2,904
0.742769
0.742769
119
23.403362
21.189152
78
false
false
0
0
0
0
0
0
1.806723
false
false
14
f1215aab01e72c77e727d6e8d85f8a6ac99ef17f
7,017,976,582,988
ff1104fd8968b02fe7e1ebd12459c3908c27d280
/Basic_Programming/Input-output/Basics of Input-output/29:conjectIt/Solution.java
247534628f6ef3b17fe466d63882f439d4441624
[]
no_license
vaishali-bariwal/hackerearth
https://github.com/vaishali-bariwal/hackerearth
1466ad95cd2dfd262d8c656417c829e01fc3ba6d
d48c3cccfc8c06e524033d2bf4dc1d9cd62fd656
refs/heads/master
2021-07-15T16:34:40.217000
2020-07-26T18:27:43
2020-07-26T18:27:43
191,720,137
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.*; class TestClass { public static void main(String args[] ) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); sc.nextLine(); while(t > 0) { String n = sc.nextLine(); System.out.println("YES"); t --; } } }
UTF-8
Java
323
java
Solution.java
Java
[]
null
[]
import java.util.*; class TestClass { public static void main(String args[] ) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); sc.nextLine(); while(t > 0) { String n = sc.nextLine(); System.out.println("YES"); t --; } } }
323
0.470588
0.467492
13
23.923077
14.236797
45
false
false
0
0
0
0
0
0
0.538462
false
false
14
ab59d62fe7b76aa04d2454c82757ef5d5cc2046f
17,695,265,289,374
6baf1fe00541560788e78de5244ae17a7a2b375a
/hollywood/com.oculus.horizon-Horizon/sources/com/oculus/horizon/service/result/LaunchOtherAppResultBuilder.java
288ff1cb453cb1a7d50325baf357a9849cb62d03
[]
no_license
phwd/quest-tracker
https://github.com/phwd/quest-tracker
286e605644fc05f00f4904e51f73d77444a78003
3d46fbb467ba11bee5827f7cae7dfeabeb1fd2ba
refs/heads/main
2023-03-29T20:33:10.959000
2021-04-10T22:14:11
2021-04-10T22:14:11
357,185,040
4
2
null
true
2021-04-12T12:28:09
2021-04-12T12:28:08
2021-04-10T22:15:44
2021-04-10T22:15:39
116,441
0
0
0
null
false
false
package com.oculus.horizon.service.result; import X.AbstractC06640p5; import X.AnonymousClass0QC; import com.facebook.inject.Assisted; import com.facebook.ultralight.Dependencies; import com.facebook.ultralight.Inject; import com.oculus.horizon.service.OVRService; @Dependencies({"_UL__ULSEP_android_content_Context_ULSEP_com_facebook_inject_UnsafeContextInjection_ULSEP_BINDING_ID", "_UL__ULSEP_com_oculus_libraryapi_OVRLibrary_ULSEP_BINDING_ID", "_UL__ULSEP_com_oculus_horizon_platformsdk_DeeplinkIntentUtils_ULSEP_BINDING_ID"}) public class LaunchOtherAppResultBuilder extends ResultBuilder { public static final Class<?> TAG = LaunchOtherAppResultBuilder.class; public AnonymousClass0QC _UL_mInjectionContext; @Inject public LaunchOtherAppResultBuilder(AbstractC06640p5 r3, @Assisted OVRService oVRService) { super(oVRService); this._UL_mInjectionContext = new AnonymousClass0QC(3, r3); } }
UTF-8
Java
934
java
LaunchOtherAppResultBuilder.java
Java
[]
null
[]
package com.oculus.horizon.service.result; import X.AbstractC06640p5; import X.AnonymousClass0QC; import com.facebook.inject.Assisted; import com.facebook.ultralight.Dependencies; import com.facebook.ultralight.Inject; import com.oculus.horizon.service.OVRService; @Dependencies({"_UL__ULSEP_android_content_Context_ULSEP_com_facebook_inject_UnsafeContextInjection_ULSEP_BINDING_ID", "_UL__ULSEP_com_oculus_libraryapi_OVRLibrary_ULSEP_BINDING_ID", "_UL__ULSEP_com_oculus_horizon_platformsdk_DeeplinkIntentUtils_ULSEP_BINDING_ID"}) public class LaunchOtherAppResultBuilder extends ResultBuilder { public static final Class<?> TAG = LaunchOtherAppResultBuilder.class; public AnonymousClass0QC _UL_mInjectionContext; @Inject public LaunchOtherAppResultBuilder(AbstractC06640p5 r3, @Assisted OVRService oVRService) { super(oVRService); this._UL_mInjectionContext = new AnonymousClass0QC(3, r3); } }
934
0.795503
0.776231
20
45.700001
56.730152
265
false
false
0
0
0
0
0
0
0.75
false
false
14
7ba20df59f4fe6e277934cea0170d6f7300f8419
17,695,265,288,469
9da76f6ef25862e7a72b4cda969809869c20fe9d
/app/src/main/java/example/deronbrown/castvolumecontrolservicetest/NotificationsHelper.java
6fe61a2e185d90576bbe3069462297f9dc422b0b
[]
no_license
deRonbrown/CastVolumeControlServiceTest
https://github.com/deRonbrown/CastVolumeControlServiceTest
8a624e5ce911bfb5a6a80e82aad5d6d993bc7f38
0b2e037f96e4880e1063e2074b1ad8dd739def7a
refs/heads/master
2020-04-04T13:04:13.659000
2018-11-09T16:01:13
2018-11-09T16:01:13
155,947,566
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package example.deronbrown.castvolumecontrolservicetest; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Build; import android.support.annotation.NonNull; import android.support.v4.app.NotificationCompat; import android.support.v4.content.ContextCompat; import android.support.v4.media.MediaDescriptionCompat; import android.support.v4.media.session.MediaButtonReceiver; import android.support.v4.media.session.MediaSessionCompat; import android.support.v4.media.session.PlaybackStateCompat; import java.util.ArrayList; import java.util.List; public class NotificationsHelper { public static final int AUDIO_NOTIFICATION_ID = 1001; public static final String AUDIO_NOTIFICATION_CHANNEL_ID = "audio_playback"; private static boolean hasCreatedChannel = false; public static NotificationCompat.Builder getAudioNotificationBuilder(@NonNull Context context, @NonNull MediaSessionCompat.Token token, boolean isPlaying, @NonNull MediaDescriptionCompat description) { NotificationCompat.Builder builder = new NotificationCompat.Builder(context, AUDIO_NOTIFICATION_CHANNEL_ID); builder .setContentTitle(description.getTitle()) .setContentText(description.getSubtitle()) .setSubText(description.getDescription()) .setSmallIcon(R.mipmap.ic_launcher) .setColor(ContextCompat.getColor(context, android.R.color.holo_blue_dark)) .setColorized(false) .setDeleteIntent( MediaButtonReceiver.buildMediaButtonPendingIntent(context, PlaybackStateCompat.ACTION_STOP)) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC); Intent intent = new Intent(context, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); PendingIntent meditationPendingIntent = PendingIntent.getActivity(context, 1000, intent, PendingIntent.FLAG_CANCEL_CURRENT); builder.setContentIntent(meditationPendingIntent); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { builder.setLargeIcon(description.getIconBitmap()); } builder.setStyle(new android.support.v4.media.app.NotificationCompat.MediaStyle(builder) .setMediaSession(token) .setShowActionsInCompactView(0) // For backwards compatibility with Android L and earlier. .setShowCancelButton(true) .setCancelButtonIntent( MediaButtonReceiver.buildMediaButtonPendingIntent( context, PlaybackStateCompat.ACTION_STOP))); if (isPlaying) { builder.addAction(new NotificationCompat.Action( android.R.drawable.ic_media_pause, "Pause", MediaButtonReceiver.buildMediaButtonPendingIntent(context, PlaybackStateCompat.ACTION_PLAY_PAUSE))); } else { builder.addAction(new NotificationCompat.Action( android.R.drawable.ic_media_play, "Play", MediaButtonReceiver.buildMediaButtonPendingIntent(context, PlaybackStateCompat.ACTION_PLAY_PAUSE))); } builder.setSmallIcon(R.mipmap.ic_launcher); return builder; } public static void initChannels(@NonNull Context context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && !hasCreatedChannel) { List<NotificationChannel> channels = new ArrayList<>(); NotificationChannel audioChannel = new NotificationChannel( AUDIO_NOTIFICATION_CHANNEL_ID, "Audio", NotificationManager.IMPORTANCE_LOW); audioChannel.setShowBadge(false); audioChannel.enableLights(false); audioChannel.enableVibration(false); audioChannel.setSound(null, null); audioChannel.setLockscreenVisibility(NotificationCompat.VISIBILITY_PUBLIC); channels.add(audioChannel); NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); manager.createNotificationChannels(channels); hasCreatedChannel = true; } } }
UTF-8
Java
4,680
java
NotificationsHelper.java
Java
[ { "context": "package example.deronbrown.castvolumecontrolservicetest;\n\nimport android.app", "end": 26, "score": 0.961689293384552, "start": 16, "tag": "USERNAME", "value": "deronbrown" } ]
null
[]
package example.deronbrown.castvolumecontrolservicetest; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Build; import android.support.annotation.NonNull; import android.support.v4.app.NotificationCompat; import android.support.v4.content.ContextCompat; import android.support.v4.media.MediaDescriptionCompat; import android.support.v4.media.session.MediaButtonReceiver; import android.support.v4.media.session.MediaSessionCompat; import android.support.v4.media.session.PlaybackStateCompat; import java.util.ArrayList; import java.util.List; public class NotificationsHelper { public static final int AUDIO_NOTIFICATION_ID = 1001; public static final String AUDIO_NOTIFICATION_CHANNEL_ID = "audio_playback"; private static boolean hasCreatedChannel = false; public static NotificationCompat.Builder getAudioNotificationBuilder(@NonNull Context context, @NonNull MediaSessionCompat.Token token, boolean isPlaying, @NonNull MediaDescriptionCompat description) { NotificationCompat.Builder builder = new NotificationCompat.Builder(context, AUDIO_NOTIFICATION_CHANNEL_ID); builder .setContentTitle(description.getTitle()) .setContentText(description.getSubtitle()) .setSubText(description.getDescription()) .setSmallIcon(R.mipmap.ic_launcher) .setColor(ContextCompat.getColor(context, android.R.color.holo_blue_dark)) .setColorized(false) .setDeleteIntent( MediaButtonReceiver.buildMediaButtonPendingIntent(context, PlaybackStateCompat.ACTION_STOP)) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC); Intent intent = new Intent(context, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); PendingIntent meditationPendingIntent = PendingIntent.getActivity(context, 1000, intent, PendingIntent.FLAG_CANCEL_CURRENT); builder.setContentIntent(meditationPendingIntent); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { builder.setLargeIcon(description.getIconBitmap()); } builder.setStyle(new android.support.v4.media.app.NotificationCompat.MediaStyle(builder) .setMediaSession(token) .setShowActionsInCompactView(0) // For backwards compatibility with Android L and earlier. .setShowCancelButton(true) .setCancelButtonIntent( MediaButtonReceiver.buildMediaButtonPendingIntent( context, PlaybackStateCompat.ACTION_STOP))); if (isPlaying) { builder.addAction(new NotificationCompat.Action( android.R.drawable.ic_media_pause, "Pause", MediaButtonReceiver.buildMediaButtonPendingIntent(context, PlaybackStateCompat.ACTION_PLAY_PAUSE))); } else { builder.addAction(new NotificationCompat.Action( android.R.drawable.ic_media_play, "Play", MediaButtonReceiver.buildMediaButtonPendingIntent(context, PlaybackStateCompat.ACTION_PLAY_PAUSE))); } builder.setSmallIcon(R.mipmap.ic_launcher); return builder; } public static void initChannels(@NonNull Context context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && !hasCreatedChannel) { List<NotificationChannel> channels = new ArrayList<>(); NotificationChannel audioChannel = new NotificationChannel( AUDIO_NOTIFICATION_CHANNEL_ID, "Audio", NotificationManager.IMPORTANCE_LOW); audioChannel.setShowBadge(false); audioChannel.enableLights(false); audioChannel.enableVibration(false); audioChannel.setSound(null, null); audioChannel.setLockscreenVisibility(NotificationCompat.VISIBILITY_PUBLIC); channels.add(audioChannel); NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); manager.createNotificationChannels(channels); hasCreatedChannel = true; } } }
4,680
0.650855
0.647436
98
46.7551
33.428589
132
false
false
0
0
0
0
0
0
0.632653
false
false
14
eeee7d7facd339b0a84823bf99bda48f79e1b65d
21,569,325,770,233
038ea824890d6725b72f383a07e754eefa5763fb
/src/main/java/vn/codegym/springbootdatajpa/controllers/UserController.java
c26cf5dc52d45c3957d26d8d532603ddf79850c4
[]
no_license
trungquangphan/springboot-starter
https://github.com/trungquangphan/springboot-starter
e0abe63860c640781bbb642322872fb36159ec40
5b7bee9a2d41905a563752f2ce4f77ceddbe38f5
refs/heads/master
2020-05-27T18:56:37.053000
2019-06-05T02:58:22
2019-06-05T02:58:22
188,751,061
0
0
null
false
2019-06-14T02:40:25
2019-05-27T01:32:12
2019-06-05T02:58:35
2019-06-14T02:37:16
32
0
0
1
Java
false
false
package vn.codegym.springbootdatajpa.controllers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import vn.codegym.springbootdatajpa.dao.Dao; import vn.codegym.springbootdatajpa.entities.User; import vn.codegym.springbootdatajpa.repositories.UserRepository; import vn.codegym.springbootdatajpa.utils.JsonUtil; import javax.validation.Valid; import java.util.Locale; @Controller public class UserController { @Autowired MessageSource messageSource; private final UserRepository userRepository; @Autowired private Dao<User> userDao; @Autowired public UserController(UserRepository userRepository) { this.userRepository = userRepository; } @GetMapping("") public String getUsers(Model model) { // String text = messageSource.getMessage("greeting",new String[]{"Codegym"}, Locale.forLanguageTag("hghg")); model.addAttribute("users", userRepository.findAll()); model.addAttribute("name", "Trinh"); model.addAttribute("name2", "Nhut"); return "index"; } @GetMapping("/users") @ResponseBody public Iterable<User> getUsers() { Iterable<User> users = userRepository.findAll(); return users; } @PutMapping("/users") @ResponseBody public Iterable<User> editUser(@RequestBody @Valid User user) { userRepository.save(user); return userRepository.findAll(); } @GetMapping("/signup") public String showSignUpForm(User user) { return "add-user"; } @PostMapping("/adduser") public String addUser(@Valid User user, BindingResult result, Model model) { if (result.hasErrors()) { result.getFieldErrors(); return "add-user"; } userRepository.save(user); model.addAttribute("users", userRepository.findAll()); return "index"; } private boolean validateUser(@Valid User user, Model model) { String name = user.getName(); if (name.length() < 3 || name.length() > 10) { model.addAttribute("errMessage", "Error message here"); return false; } String email = user.getEmail(); return true; } @GetMapping("/edit/{id}") public String showUpdateForm(@PathVariable("id") long id, Model model) { User user = userRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("Invalid user Id:" + id)); model.addAttribute("user", user); return "update-user"; } @PostMapping("/update/{id}") public String updateUser(@PathVariable("id") long id, @Valid User user, BindingResult result, Model model) { if (result.hasErrors()) { user.setId(id); return "update-user"; } userRepository.save(user); model.addAttribute("users", userRepository.findAll()); return "index"; } @GetMapping("/delete/{id}") public String deleteUser(@PathVariable("id") long id, Model model) { User user = userRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("Invalid user Id:" + id)); userRepository.delete(user); model.addAttribute("users", userRepository.findAll()); return "index"; } }
UTF-8
Java
3,523
java
UserController.java
Java
[ { "context": "y.findAll());\n model.addAttribute(\"name\", \"Trinh\");\n model.addAttribute(\"name2\", \"Nhut\");\n ", "end": 1220, "score": 0.9993106722831726, "start": 1215, "tag": "NAME", "value": "Trinh" }, { "context": "\", \"Trinh\");\n model.addAttribute(\...
null
[]
package vn.codegym.springbootdatajpa.controllers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import vn.codegym.springbootdatajpa.dao.Dao; import vn.codegym.springbootdatajpa.entities.User; import vn.codegym.springbootdatajpa.repositories.UserRepository; import vn.codegym.springbootdatajpa.utils.JsonUtil; import javax.validation.Valid; import java.util.Locale; @Controller public class UserController { @Autowired MessageSource messageSource; private final UserRepository userRepository; @Autowired private Dao<User> userDao; @Autowired public UserController(UserRepository userRepository) { this.userRepository = userRepository; } @GetMapping("") public String getUsers(Model model) { // String text = messageSource.getMessage("greeting",new String[]{"Codegym"}, Locale.forLanguageTag("hghg")); model.addAttribute("users", userRepository.findAll()); model.addAttribute("name", "Trinh"); model.addAttribute("name2", "Nhut"); return "index"; } @GetMapping("/users") @ResponseBody public Iterable<User> getUsers() { Iterable<User> users = userRepository.findAll(); return users; } @PutMapping("/users") @ResponseBody public Iterable<User> editUser(@RequestBody @Valid User user) { userRepository.save(user); return userRepository.findAll(); } @GetMapping("/signup") public String showSignUpForm(User user) { return "add-user"; } @PostMapping("/adduser") public String addUser(@Valid User user, BindingResult result, Model model) { if (result.hasErrors()) { result.getFieldErrors(); return "add-user"; } userRepository.save(user); model.addAttribute("users", userRepository.findAll()); return "index"; } private boolean validateUser(@Valid User user, Model model) { String name = user.getName(); if (name.length() < 3 || name.length() > 10) { model.addAttribute("errMessage", "Error message here"); return false; } String email = user.getEmail(); return true; } @GetMapping("/edit/{id}") public String showUpdateForm(@PathVariable("id") long id, Model model) { User user = userRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("Invalid user Id:" + id)); model.addAttribute("user", user); return "update-user"; } @PostMapping("/update/{id}") public String updateUser(@PathVariable("id") long id, @Valid User user, BindingResult result, Model model) { if (result.hasErrors()) { user.setId(id); return "update-user"; } userRepository.save(user); model.addAttribute("users", userRepository.findAll()); return "index"; } @GetMapping("/delete/{id}") public String deleteUser(@PathVariable("id") long id, Model model) { User user = userRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("Invalid user Id:" + id)); userRepository.delete(user); model.addAttribute("users", userRepository.findAll()); return "index"; } }
3,523
0.659949
0.658814
108
31.620371
27.126493
121
false
false
0
0
0
0
0
0
0.638889
false
false
14